Why is the result of the bison is not displayed?

96 views Asked by At

I tested this example of teamwork Flex and Bison, but the result of the calculation is not displayed in the console. test.l:

%{
#include "parser.tab.h"
%}
%option yylineno
%option noyywrap
%%
[/][/].*\n      ; // comment
[0-9]+          { yylval = atoi(yytext);
                  return NUM;
                }
[ \t\r\n]      ; // whitespace
.              { return *yytext; }

%%

parser.y:

%{
#include <stdio.h>
void yyerror(char *s) {
  fprintf (stderr, "%s\n", s);
}
%}
%token NUM
%start EVALUATE
%%
EVALUATE: EXPR          {printf("=%d\n", $$);} ;

EXPR: EXPR '+' TERM { $$ = $1 + $3; }
    | EXPR '-' TERM { $$ = $1 - $3; }
    | TERM
;

TERM: TERM '*' NUM  { $$ = $1 * $3; }
    | TERM '/' NUM  { $$ = $1 / $3; }
    | NUM
;

%%
int main()
{
  return yyparse();
}

But if you add getchar(), then after you enter this additional character all the same calculation result is displayed. Why is not this change(EVALUATE: EXPR{printf("=%d\n", $$); getchar();} ;) , I do not see the result? Sorry for the my English.

1

There are 1 answers

1
mastov On BEST ANSWER

You are parsing the input coming from stdin, which is a "stream". Before that stream is terminated, the parser cannot know the complete parse tree. For example, if you enter the expression 1+1, the complete input could as well be 1+11, 1+1-1 or 1+11*4 - different expressions that would lead to completely different parse trees as result.

You can create a properly terminated input by doing one of the following:

  • pressing CTRL+D after typing in the input (on Unix shells)
  • piping the input: echo "1+1" | ./parser
  • reading the input from a file inputfile.txt containing the input 1+1:
    ./parser < inputfile.txt