0
votes

I am coding a simple calculator parser program using flex and bison. flex code is given as:

calc.l
%{
#include "fb1-5.tab.h"
%}
%%
"+"      { return ADD; }
"-"      { return SUB; }
"*"      { return MUL; }
"/"      { return DIV; }
"|"      { return ABS; }
[0-9]+   { yylval = atoi(yytext); return NUMBER; }
\n       { return EOL; }
[ \t]    { /* do nothing */ }
.        { return *yytext; }
%%

and the bison code is given as:

calc.y
%{
#include <stdio.h>
#include <stdlib.h>
%}

%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL

%%

calclist:
    | calclist exp EOL { printf("= %d\n", $1); }
    ;

exp: factor
    | exp ADD factor { $$ = $1 + $3; }
    | exp SUB factor { $$ = $1 - $3; }
    ;

factor: term
    | factor MUL term { $$ = $1 * $3; }
    | factor DIV term { $$ = $1 / $3; }
    ;

term: NUMBER
    | ABS term { $$ = $2 >= 0 ? $2 : -$2; }
;
%%

main(int argc, char **argv)
{
    yyparse();
}

yyerror(char* s)
{
    fprintf(stderr, "Error: %s\n", s);
}

For every input the answer is always 62.Even if I am giving spaces between the numbers or not the answer is always same. Even if the answer should be completely different. Like for 1+2+3 and also for 100+200+300 the answer given is always 62.

1

1 Answers

2
votes

In the reduction of calclist exp EOL to calclist, you want to print the value of the exp. That's the second symbol in the right-hand side ($2), not the first one.

The first symbol (calclist) has never been given a value, so it is undefined and could be anything. 62 is not implausible. Once the calclist: %empty rule is reduced, whatever garbage resulted as the semantic value of the rule is then passed through the calclist: calclist exp EOL rule by the default pre-action which initializes $$ to $1. So if it started as 62, it will keep being 62.