I'm trying to build an AST for a simple programming language (homework). However I can't make it to work : it seems that intermediate values ($1, $2, ...) are invalid and doesn't correspond to what I return in "sub-expressions".
Here is the Bison code of my project (I think the problem is here and not in my AST functions) : I've put comments where I encounter invalid values. It's my first project using Bison so I'm not sure I'm doing things correctly.
I also use Flex but the flex code seems to work correctly.
Thanks.
%{
#include <stdio.h>
#include "node.h"
#include "print_node.h"
int yylex();
int yyerror(char * s);
CommandNode * root = NULL;
%}
%union
{
struct ExpressionNode * expression;
struct CommandNode * command;
int number;
char * var;
}
%type <expression> E T F
%type <command> C
%token <number> NUMBER
%token <var> VAR
%token AF SKIP SEQ IF THEN ELSE WHILE DO ADD SUB MUL EOL
%%
root: C EOL { root = $1; return 0; /************ $1 seems to be garbage ************/ }
;
E: E ADD T { $$ = newAddNode($1,$3); }
| E SUB T { $$ = newSubNode($1,$3); }
| T { $$ = $1; }
;
T: T MUL F { $$ = newMulNode($1,$3); }
| F { $$ = $1; }
;
F: '(' E ')' { $$ = $2; }
| NUMBER { $$ = newNumberNode($1); }
| VAR { $$ = newVarNode($1); }
;
C: SKIP { $$ = newSkipNode(); }
| VAR AF E { $$ = newAfNode($1,$3); }
| '(' C ')' { $$ = $2; }
| IF E THEN C ELSE C { $$ = newIfNode($2,$4,$6); }
| WHILE E DO C { $$ = newWhileNode($2,$4); }
| C SEQ C { $$ = newSeqNode($1,$3); /************ $1 and $3 seems to be garbage ************/ }
;
%%
int main()
{
yyparse();
}
int yyerror(char * s)
{
fprintf(stderr, "yyerror: %s\n", s);
}