jitters: eval: add evaluator function

This commit is contained in:
Bruno BELANYI 2020-09-28 14:29:17 +02:00
parent ae8970bf30
commit 4b6c8abc75
4 changed files with 59 additions and 0 deletions

46
src/eval/evaluator.c Normal file
View file

@ -0,0 +1,46 @@
#include "evaluator.h"
static int evaluate_unop(const struct unop_node *un_op)
{
switch (un_op->op)
{
case IDENTITY:
return evaluate_ast(un_op->rhs);
case NEGATE:
return -evaluate_ast(un_op->rhs);
default:
return 0;
}
}
static int evaluate_binop(const struct binop_node *bin_op)
{
switch (bin_op->op)
{
case PLUS:
return evaluate_ast(bin_op->lhs) + evaluate_ast(bin_op->rhs);
case MINUS:
return evaluate_ast(bin_op->lhs) - evaluate_ast(bin_op->rhs);
case TIMES:
return evaluate_ast(bin_op->lhs) * evaluate_ast(bin_op->rhs);
case DIVIDE:
return evaluate_ast(bin_op->lhs) / evaluate_ast(bin_op->rhs);
default:
return 0;
}
}
int evaluate_ast(const struct ast_node *ast)
{
switch (ast->kind)
{
case NUM:
return ast->val.num;
case UNOP:
return evaluate_unop(&ast->val.un_op);
case BINOP:
return evaluate_binop(&ast->val.bin_op);
default:
return 0;
}
}

8
src/eval/evaluator.h Normal file
View file

@ -0,0 +1,8 @@
#ifndef EVALUATOR_H
#define EVALUATOR_H
#include "ast/ast.h"
int evaluate_ast(const struct ast_node *ast);
#endif /* !EVALUATOR_H */

4
src/eval/local.am Normal file
View file

@ -0,0 +1,4 @@
jitters_SOURCES += \
%D%/evaluator.c \
%D%/evaluator.h \
$(NULL)

View file

@ -15,5 +15,6 @@ AM_CPPFLAGS = -I$(top_builddir)/src -I$(top_srcdir)/src
jitters_LDADD =
include %D%/ast/local.am
include %D%/eval/local.am
include %D%/parse/local.am
include %D%/print/local.am