【发布时间】:2019-08-15 22:12:03
【问题描述】:
我想在 Flex 和 Bison 中实现 abs 运算符;到目前为止,我制作的程序如下:
野牛文件
%{
#include <stdio.h>
%}
/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist: /* nothing */
| calclist exp EOL {
printf("= %d\n", $2);
}
;
exp: factor
| exp ADD factor { $$ = $1 + $3; }
| exp SUB factor { $$ = $1 - $3; }
;
factor: term
| factor MUL term { $$ = $1 * $3; }
| factor DIV term { $$ = $1 / $3; }
;
term: NUMBER
| ABS term {if ($2>=0) $$=$2;
else $$= - $2;}
;
%%
main(int argc, char **argv)
{
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
}
弹性文件
%{
# include "f5.tab.h"
%}
/* recognize tokens for the calculator and print them out */
%%
"+" { 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);
}
%%
yywrap()
{
}
我编译它:
bison -d bisonfile.y
flex flexfile.l
gcc bisonfile.tab.c lex.yy.c -o test.exe
然后当我输入如下表达式时:
34+|3
它输出 37
但是当我输入类似的内容时:
34+|-3
它打印“语法错误”
这是为什么呢?任何帮助都会很有价值。
谢谢
【问题讨论】:
-
您将其定义为
NUMBER, ADD, ABS, SUB, NUMBER,您的解析规则无法处理。您可能还想将+和-视为可能的一元运算 -
@jenesaisquoi 你能给我一些解决方案吗?我已经尝试了所有方法,但似乎没有任何效果
-
为什么不为一元表达式添加另一个规则,例如。
unary_expr: SUB ... | ...
标签: bison flex-lexer