From 7090a741bce631181e033d17f5fae2c686b5d7c1 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Mon, 28 Sep 2020 13:30:08 +0200 Subject: [PATCH] jitters: parse: build AST when parsing --- src/jitters.c | 5 +++-- src/parse/parse-jitters.y | 42 +++++++++++++++++++++++++++------------ src/parse/scan-jitters.l | 2 +- 3 files changed, 33 insertions(+), 16 deletions(-) diff --git a/src/jitters.c b/src/jitters.c index a3ed4bb..be817e9 100644 --- a/src/jitters.c +++ b/src/jitters.c @@ -1,14 +1,15 @@ #include #include +#include "ast/ast.h" #include "parse/parse-jitters.h" int main(void) { - int res; + struct ast_node *res; yydebug = getenv("PARSE") != NULL; if (yyparse(&res) == 0) { - printf("%d\n", res); + destroy_ast(res); } return 0; diff --git a/src/parse/parse-jitters.y b/src/parse/parse-jitters.y index 840a552..2127ae0 100644 --- a/src/parse/parse-jitters.y +++ b/src/parse/parse-jitters.y @@ -1,19 +1,30 @@ +%code requires +{ +#include "ast/ast.h" +} + %{ #include +#include "ast/ast.h" int yylex(void); -void yyerror(int *unused,char const *s); +void yyerror(struct ast_node **unused, char const *s); %} -%define api.value.type {int} +%union +{ + int num; + struct ast_node *node; +} + %define api.token.prefix {TOK_} %define parse.error verbose %define parse.trace true -%parse-param {int *result} +%parse-param {struct ast_node **ast} %locations %token EOF 0 "end-of-file" -%token NUM "number" +%token NUM "number" %token PLUS "+" MINUS "-" @@ -26,30 +37,35 @@ void yyerror(int *unused,char const *s); %left TIMES DIVIDE %precedence NEG +// Type of our built AST +%type exp +// Use destructor function when discarding tokens +%destructor { destroy_ast($$); } + %% input: exp EOF - { *result = $1; } + { *ast = $1; } ; exp: NUM - { $$ = $1; } + { $$ = make_num($1); } | exp PLUS exp - { $$ = $1 + $3; } + { $$ = make_binop(PLUS, $1, $3); } | exp MINUS exp - { $$ = $1 - $3; } + { $$ = make_binop(MINUS, $1, $3); } | exp TIMES exp - { $$ = $1 * $3; } + { $$ = make_binop(TIMES, $1, $3); } | exp DIVIDE exp - { $$ = $1 / $3; } + { $$ = make_binop(DIVIDE, $1, $3); } | PLUS exp %prec NEG - { $$ = $2; } + { $$ = make_unop(IDENTITY, $2); } | MINUS exp %prec NEG - { $$ = -$2; } + { $$ = make_unop(NEGATE, $2); } | LPAREN exp RPAREN { $$ = $2; } @@ -57,7 +73,7 @@ exp: %% -void yyerror(int *unused, char const *s) +void yyerror(struct ast_node **unused, char const *s) { unused = unused; // Unused fprintf(stderr, "%s\n", s); diff --git a/src/parse/scan-jitters.l b/src/parse/scan-jitters.l index 1312b50..5de5d3e 100644 --- a/src/parse/scan-jitters.l +++ b/src/parse/scan-jitters.l @@ -36,7 +36,7 @@ int [0-9]+ ")" return TOK_RPAREN; {int} { - yylval = atoi(yytext); + yylval.num = atoi(yytext); return TOK_NUM; }