在下面的代码中,虽然我添加了 \t
作为 token ,其优先级高于数字,但当我测试它时,它仍然接受 -2- 2
(在 -
之后有一个空格)和 -2 - 2
(在 -
周围有 2 个空格),但它不接受-2-2
(没有空格)。对于这种特殊情况有解决方案吗?
我的目标是,当我给它输入诸如 -2-2-2
或 2*3/6-1
时,它工作正常并且不输出“语法错误”。
词法.l
/* recognize tokens for the calculator and print them out */
/*"--"[0-9]+ { yytext++; yylval = atoi(yytext); return NUMBER; }*/
%{
#include"syntax.tab.h"
%}
%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"|" { return ABS; }
[ \t] { /* ignore whitespace */ }
(-|"")[0-9]+ { yylval = atoi(yytext); return NUMBER; }
\n { return EOL; }
. { printf("Mystery character %c\n", *yytext); }
%%
syntax.y
/* 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", $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);
}`
最佳答案
-2-2
被词法分析器解释为 -2
-2
,而不是 -2
-
2
。
Lexer 总是寻找最长的匹配,因此它总是更喜欢将减号和数字视为单个标记。
您的解析器没有接受两个连续数字的规则,因此会显示错误。 (您应该学习在词法分析器和解析器中打开调试输出。在这种情况下这非常有帮助。)
要解决此问题,您需要在词法分析器中删除作为数字一部分的 -
。
将其合并到数字中是非常常见的错误,它会导致您遇到的此类问题。
相反,您可以在解析器中定义一元 -
运算符。
(顺便说一句,(-|"")
可以写成 -?
。)
关于regex - 语法分析器如何忽略输入中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76030057/