简单的数学解析器 Flex&Bison
Simple Mathematical Parser Flex&Bison
所以我正在制作一个非常简单的 Flex 和 Bison 程序来求解数学表达式,但由于某种原因输出始终为 0。
我一直在关注 O'Reilly 的书 'Flex and Bison',我的代码与书中的代码几乎相同,但仍然无法正常工作。
已经有一段时间了,将不胜感激。
这是 .l 文件:
%{
#include "simple.tab.h"
/* enum yytokentype {
NUMBER = 258,
ADD,
SUB,
MUL,
DIV,
ABS,
EOL
};
int yylval; */
%}
%%
"+" { 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); }
%%
和 .y 文件:
%{
#include<cstdio>
int yylex();
int yyerror(const char *s);
%}
/* token declaration */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist:
| 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 ? : -; }
;
%%
int main(int argc, char **argv)
{
yyparse();
}
int yyerror(const char *s)
{
fprintf(stderr,"error: %s\n",s);
}
输出:
$ bison -d simple.y
$ flex stuff.l
$ g++ simple.tab.c lex.yy.c -lfl -o simple
$ ./simple
1+2
= 0
1*2
= 0
1/1
= 0
4/2
= 0
25/5
= 0
|1
= 0
此外,如果有人能推荐一本更好更简单的书,我们将不胜感激。
在这个语句中,</code>是<code>calclist
的值:
| calclist exp EOL { printf("= %d\n",); }
你要的是exp
的值:
| calclist exp EOL { printf("= %d\n",); }
所以我正在制作一个非常简单的 Flex 和 Bison 程序来求解数学表达式,但由于某种原因输出始终为 0。 我一直在关注 O'Reilly 的书 'Flex and Bison',我的代码与书中的代码几乎相同,但仍然无法正常工作。 已经有一段时间了,将不胜感激。
这是 .l 文件:
%{
#include "simple.tab.h"
/* enum yytokentype {
NUMBER = 258,
ADD,
SUB,
MUL,
DIV,
ABS,
EOL
};
int yylval; */
%}
%%
"+" { 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); }
%%
和 .y 文件:
%{
#include<cstdio>
int yylex();
int yyerror(const char *s);
%}
/* token declaration */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist:
| 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 ? : -; }
;
%%
int main(int argc, char **argv)
{
yyparse();
}
int yyerror(const char *s)
{
fprintf(stderr,"error: %s\n",s);
}
输出:
$ bison -d simple.y
$ flex stuff.l
$ g++ simple.tab.c lex.yy.c -lfl -o simple
$ ./simple
1+2
= 0
1*2
= 0
1/1
= 0
4/2
= 0
25/5
= 0
|1
= 0
此外,如果有人能推荐一本更好更简单的书,我们将不胜感激。
在这个语句中,</code>是<code>calclist
的值:
| calclist exp EOL { printf("= %d\n",); }
你要的是exp
的值:
| calclist exp EOL { printf("= %d\n",); }