计算器中的错误

Bug in calculator

我尝试学习 flex 和 bison,但我的 flex/bison 计算器打印出错误的结果。例子

$ ./fb1-5 
1 + 2 + 3
= 32728

生成文件

fb1-5:  fb1-5.l fb1-5.y
    bison -d fb1-5.y
    flex fb1-5.l
    cc -o $@ fb1-5.tab.c lex.yy.c -lfl

词法分析器

%{
# 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]  { /* ignore whitespace */ }
.      { printf("Mystery character %c\n", *yytext); }
%%

解析器

/* simplest version of calculator */
%{
#include <stdio.h>
%}
/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist: /* nothing */                       
 | calclist exp EOL { printf("= %d\n", ); } 
 ;
exp: factor       

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

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

 | ABS term   { $$ =  >= 0?  : - ; }
;
%%
main(int argc, char **argv)
{
  yyparse();
}
yyerror(char *s)
{
  fprintf(stderr, "error: %s\n", s);
}

可能是什么问题?

在与 calclist 关联的操作中,您引用了 $1 的值,它指的是递归产生式规则的 calclist 部分。但是,您实际上从未在任何地方为 calclist 非终结符赋值。你是说 2 美元吗?