2
votes

I'm working on multi function calculator from bison. I have found that if the following expression is passed into program, a wrong answer will be produced.

(1+2) * (2+1)

The above expression should produce 9. However it produces 6 in the following setup.

this is the bison code:

%token NUMBER

%%


statement_list:  statement '\n'
        |        statement_list statement '\n'
        ;
statement:  expression   { printf("= %d\n", $1); };

expression: expression '+' term   { $$ = $1 + $3; }
    |       expression '-' term   { $$ = $1 - $3; }
    |       term                  { $$ = $1; }
    ;

term:       term '*' factor       { $$ = $1 * $3; }
    |       term '/' factor        
                  {  if ($3 == 0)
                        yyerror("Division by zero");
                     else $$ = $1 / $3; }
    |       factor                { $$ = $1; }
    ;

factor:     '(' expression ')'    { $$ = $2; }
    |       '-' factor            { $$ = -$2; }
    |       NUMBER                { $$ = $1; }
    ;
%%

This is flex code

D     [0-9]
WS    [ \t\v\f]
%%

{D}+    { yylval = atof(yytext); return NUMBER; }

"+" { return yytext[0]; }
"-" { return yytext[0]; }
"*" { return yytext[0]; }
"/" { return yytext[0]; }

"(" { return yytext[0]; }
")" { return yytext[0]; }

"\n"    { return yytext[0]; }

{WS}    {}
.   {}
%%

Thanks, Ali

2
The problem is solved. I missed to put the "(" and ")" in flex code.Ali

2 Answers

1
votes

Unfortunately, I cannot remember the syntax for bison/flex, but my intuition is telling me that the precedence is not getting converted to C code correctly.

If so, is it the case that $2 means "for the output of this expression, substitute in the code generated for the second sub-expression at this point in the expansion, without any knowledge of C precedence rules"?

If so, your code is producing something like "printf(... 1+2*2+1)". Can you view the source produce and confirm? If so, you should presumably add some brackets round the $2 in the expansion of the '(' expression, or round the arguments $1 and $3 in the '*' expression?

0
votes

The Unix Programming Environment might be helpful http://cm.bell-labs.com/cm/cs/upe/