I am trying to implement a simple if statement in Flex and Bison in the following form:
(expression)?(expression)
If the left expression is a non zero value, then the right expression will be executed.
Using Bison grammar rules, can anyone show me an example of how I can do it?
Here is a piec of my Bison code that shows what I have so far:
%union{
int d;
char *s;
}
%token <d>INTEGER
%token <s>VARIABLE
%nonassoc IF
%type <d>expr
%type <s> statement
%error-verbose
%left '+' '-'
%left '*' '/'
%left POWER
%right '!'
%%
program:
program statement {printf("Prefix notation of given expression: %s \n", stack[head]); /*Print final expression*/ }
|
;
statement:
expr '\n' { /* printf(" = %d \n", $1); */}
| VARIABLE '=' expr { sym[get_var_index($1)] = $3; printf(" = %d \n", $3); printf("Assigning var %s = %d index %d \n", $1, sym[get_var_index($1)],get_var_index($1)); }
| '(' expr ')' IF '('statement')' '\n' {printf("Bison found if statement: if(stmnt) then stmnt \n"); ($2)?$6: printf("False \n");}
|'\n'
;
expr:
INTEGER { $$ = $1; pushInt($1); printf("Got an Integer %d \n", $1);}
| VARIABLE { $$= sym[get_var_index($1)]; pushChars($1); printf("Printing %s = %d \n", $1, sym[get_var_index($1)]); }
| expr '+' expr { $$ = $1 + $3; popAndCalc("+"); }
| expr '-' expr { $$ = $1 - $3; popAndCalc("-"); }
| expr '*' expr { $$ = $1 * $3; popAndCalc("*"); }
| expr '/' expr { $$ = $1 / $3; popAndCalc("/"); }
| expr POWER expr { $$ = pow($1, $3); popAndCalc("**"); }
| '(' expr ')' { $$ = $2;}
| '!' expr { $$ = !$2; popAndCalc("!"); }
When I run it however, It runs the block even when it's false:
How can I resolve this? I think I am missing something, please help...