【发布时间】:2017-04-04 02:39:47
【问题描述】:
我正在阅读 John Levine 的 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 中的章节。我也在通过http://dinosaur.compilertools.net/bison/bison_5.html进行挖掘,试图找出我的错误。感谢您在面对看似简单的障碍时忽略了我的困惑。我刚刚开始通过编译器进行自我旅程。任何建议表示赞赏。
弹性(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);
}
生成文件:
fb1-5: fb1-5.l fb1-5.y
bison -d fb1-5.y
flex fb1-5.l
gcc -o $@ fb1-5.tab.c lex.yy.c -lfl
clean:
rm -f core fb1-5.tab.h fb1-5.tab.c lex.yy.c fb1-5
【问题讨论】:
标签: compiler-construction bison flex-lexer bnf