0

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: enter image description here

How can I resolve this? I think I am missing something, please help...

Brian
  • 3,850
  • 3
  • 21
  • 37
Salvo
  • 541
  • 6
  • 19

1 Answers1

3

The essential problem is that you are executing your code unconditionally as you parse it. So everything in the program executes exactly once, regardless of context. The general solution to your problem is to separate execution from parsing -- instead of executing as you parse, you parse into some kind of data structure that can be executed later. Then, when you want to execute some code, you execute just that code. This can deal with conditions, loops, functions, and anything else you might want to do in the future.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226