diff --git a/src/ast/ast.c b/src/ast/ast.c new file mode 100644 index 0000000..816d3a3 --- /dev/null +++ b/src/ast/ast.c @@ -0,0 +1,64 @@ +#include "ast.h" + +#include +#include + +static void *xmalloc(size_t size) +{ + void *ret = malloc(size); + + if (ret == NULL) + err(1, NULL); + + return ret; +} + +struct ast_node *make_num(int val) +{ + struct ast_node *ret = xmalloc(sizeof(*ret)); + + ret->kind = NUM; + ret->val.num = val; + + return ret; +} + +struct ast_node *make_unop(enum unop_kind op, struct ast_node *rhs) +{ + struct ast_node *ret = xmalloc(sizeof(*ret)); + + ret->kind = UNOP; + ret->val.un_op.op = op; + ret->val.un_op.rhs = rhs; + + return ret; +} + +struct ast_node *make_binop(enum binop_kind op, struct ast_node *lhs, + struct ast_node *rhs) +{ + struct ast_node *ret = xmalloc(sizeof(*ret)); + + ret->kind = BINOP; + ret->val.bin_op.op = op; + ret->val.bin_op.lhs = lhs; + ret->val.bin_op.rhs = rhs; + + return ret; +} + +void destroy_ast(struct ast_node *ast) +{ + if (!ast) + return; + + if (ast->kind == BINOP) + { + destroy_ast(ast->val.bin_op.lhs); + destroy_ast(ast->val.bin_op.rhs); + } + else if (ast->kind == UNOP) + destroy_ast(ast->val.un_op.rhs); + + free(ast); +} diff --git a/src/ast/ast.h b/src/ast/ast.h new file mode 100644 index 0000000..b04f7a9 --- /dev/null +++ b/src/ast/ast.h @@ -0,0 +1,59 @@ +#ifndef AST_H +#define AST_H + +// Forward declaration +struct ast_node; + +enum unop_kind +{ + IDENTITY, + NEGATE, +}; + +enum binop_kind +{ + PLUS, + MINUS, + TIMES, + DIVIDE, +}; + +struct unop_node +{ + enum unop_kind op; + struct ast_node *rhs; +}; + +struct binop_node +{ + enum binop_kind op; + struct ast_node *lhs; + struct ast_node *rhs; +}; + +struct ast_node +{ + enum node_kind + { + UNOP, + BINOP, + NUM, + } kind; + union ast_val + { + struct unop_node un_op; + struct binop_node bin_op; + int num; + } val; +}; + +struct ast_node *make_num(int val); + +struct ast_node *make_unop(enum unop_kind op, struct ast_node *rhs); + +struct ast_node *make_binop(enum binop_kind op, struct ast_node *lhs, + struct ast_node *rhs); + +void destroy_ast(struct ast_node *ast); + +#endif /* !AST_H */ diff --git a/src/ast/local.am b/src/ast/local.am new file mode 100644 index 0000000..fb8dc58 --- /dev/null +++ b/src/ast/local.am @@ -0,0 +1,4 @@ +jitters_SOURCES += \ + %D%/ast.c \ + %D%/ast.h \ + $(NULL) diff --git a/src/local.am b/src/local.am index cde0ef2..468d4e1 100644 --- a/src/local.am +++ b/src/local.am @@ -14,4 +14,5 @@ AM_CPPFLAGS = -I$(top_builddir)/src -I$(srcdir) # Initialise those variables for use in included files jitters_LDADD = +include %D%/ast/local.am include %D%/parse/local.am