开发者

Problem with bison and flex calculator

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: express开发者_运维知识库ion '+' 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


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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜