Compiler construction Flex&Bison简单BNF计算器常数输出为零

Compiler construction Flex&Bison简单BNF计算器常数输出为零,compiler-construction,bison,flex-lexer,bnf,Compiler Construction,Bison,Flex Lexer,Bnf,我正在阅读约翰·莱文的《O'Reilly Flex&Bison》一书,在为一个简单的BNF计算器编译和运行示例时遇到了以下问题 > ./fb1-5 2 + 3 * 4 = 0 2 * 3 + 4 = 0 c Mystery Character c error: syntax error 程序似乎能够识别非数字输入并相应地退出,但是任何带有mult/div/add/sub表达式的整数输入都会导致恒定输出为零 我已经搜索了关于堆栈溢出的类似问题,并且多次阅读了O'Reilly中的章节。我

我正在阅读约翰·莱文的《O'Reilly Flex&Bison》一书,在为一个简单的BNF计算器编译和运行示例时遇到了以下问题

> ./fb1-5 
2 + 3 * 4
= 0
2 * 3 + 4 
= 0
c
Mystery Character c
error: syntax error
程序似乎能够识别非数字输入并相应地退出,但是任何带有mult/div/add/sub表达式的整数输入都会导致恒定输出为零

我已经搜索了关于堆栈溢出的类似问题,并且多次阅读了O'Reilly中的章节。我也在挖掘过程中,通过尝试和发现我的错误。感谢你在一个看似基本的障碍面前忽略了我的困惑。我刚刚开始我的编译之旅。任何建议都将不胜感激

柔性fb1-5.L:

%{
#include "fb1-5.tab.h" /*forward declaration - not yet compiled*/
%}

%%
"+" {return ADD;}
"-" {return SUB;}
"*" {return MUL;}
"/" {return DIV;}
[0-9]+ { yylval = atoi(yytext); return NUMBER;}
\n { return EOL;}
[ \t] { } /*ignore whitespace*/
.  { printf("Mystery Character %c\n", *yytext);}
%%
野牛fb1-5.y:

%{
#include <stdio.h>
%}

/*declare tokens*/
%token NUMBER
%token ADD
%token SUB
%token MUL
%token DIV
%token ABS
%token EOL

/*BNF tree*/
%%
calclist: /*nothing - matches at beginning of input*/
  | calclist exp EOL { printf("= %d\n", $1);}
  ;

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

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

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

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

yyerror(char *s)
{
  fprintf(stderr, "error: %s\n", s);
}
应该是

printf("= %d\n", $2);
因为exp是该产品右侧的第二件事

printf("= %d\n", $1);
printf("= %d\n", $2);