句法分析器如何忽略输入中的空格

问题描述 投票:0回答:1

在下面的代码中,虽然我添加了

\t
作为标记,优先级高于数字,但当我测试它时,它仍然接受
-2- 2
(在
-
之后有一个空格)和
-2 - 2 
-
周围有 2 个空格)但它不接受
-2-2
(没有空格)。有针对这种特殊情况的解决方案吗?

我的目标是,当我给它一个输入,例如

-2-2-2
2*3/6-1
它工作正常并且不输出“语法错误”。

lexical.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);
}`
regex flex-lexer lexical-analysis
1个回答
0
投票

-2-2
被解释为
-2
-2
,而不是
-2
-
2
.

您的解析器没有接受两个连续数字的规则,因此它显示错误。 (你应该学会在词法分析器和解析器中打开调试输出。这在这种情况下非常有帮助。)

要解决此问题,您需要删除

-
作为词法分析器中数字的一部分。 把它变成一个数字是很常见的错误,它会导致你遇到的问题。 相反,您可以在解析器中定义一元
-
运算符。

(顺便说一句,

(-|"")
可以写成
-?
。)

© www.soinside.com 2019 - 2024. All rights reserved.