help-bison
[Top][All Lists]

## Parsing a simple mathematical statement

 From: Abdelmalek Halawani Subject: Parsing a simple mathematical statement Date: Sun, 04 Mar 2007 20:34:06 +0000

```Hi,

I would like to create a parser that reads the following input:

a = 1; b = 2; c = 3; d = 0;
y = a + b * c + d;

And outputs:

temp1 = b * c;
temp1 = 6;
temp2 = temp1 + d;
y = a + temp2;
y = 7;

I reviewed the bison manual and played with example three "mfcalc" from chapter
two. I copy the relevant part here, line numbers are added for convenience.

Obviously i need to define a counter that count the number of basic operations
( '+', '*' ) and use the number to identify the correct temp variable (temp1,
temp2, ...)

I need an action for the non-terminal expression (exp '+' exp), this action
should print (temp# = exp + exp;). Also, i need to find the result (\$\$ = \$1 +
\$3;). First, i added line 8 and received  (error: invalid type argument of
`->') as a compilation error.
Next i added line 3 and line 11. The result was as "expected" postorder

1:     exp:      NUM                { \$\$ = \$1;                         }
2:             | VAR                    { \$\$ = \$1->value.var;
3:                                              printf("%s",\$1->name);
4:                                           }
5:             | VAR '=' exp        { \$\$ = \$3; \$1->value.var = \$3;     }
6:             | FNCT '(' exp ')'   { \$\$ = (*(\$1->value.fnctptr))(\$3); }
7:             | exp '+' exp          {
8:                                             printf("temp%d = %s + %s",
temp_no, \$1->name, \$3->name);
9:                                             \$\$ = \$1 + \$3;
10:                                           printf("+");
11:                                           temp_no ++;
12:                                        }

Regards,
Abed

```