嗨,我已经开始学习 Bison 解析器生成器了。我尝试了以下程序。我使用 MinGW on Window 7
和 mintty
客户端编译并运行该程序。 Bison版本是2.4.2
%verbose
%error-verbose
%{
#include <cstdio>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
int yylex(void);
int yyerror(const char *msg);
%}
%token INT
%%
rule :
INT { $$ = $1; printf("value : %d %d %d %d\n", $1,
@1.first_line, @1.first_column, @1.last_column); }
;
%%
int main()
{
yyparse();
return 0;
}
int yylex()
{
char ch = getchar();
if(isdigit(ch))
{
ungetc(ch, stdin);
scanf("%d", &yylval);
return INT;
}
return ch;
}
int yyerror(const char *msg)
{
printf("Error : %s\n", msg);
}
我用 bison filename.y
编译了程序,然后用 gcc filename.tab.c
编译了程序,当我尝试运行该程序并在标准输入中输入 5 时,我得到了从 yyerror 函数打印以下错误。谁能帮我找出我做错了什么。
Error : syntax error, unexpected $undefined, expecting $end
最佳答案
当您的词法分析器读取您输入的数字后的 \n
(换行符)字符时,它会将其返回给您的解析器,解析器不会将其识别为任何内容,因此您会得到 当预期
(换行符打印为 $end
(输入指示符结束)时,意外 $undefined$undefined
因为换行符永远不会出现在语法中) .
将 yylex
的最后一行更改为 return 0;
(0 是输入指示符的结尾)而不是 return ch;
并且它应该可以工作。
关于c - Bison 语法错误 意外 $undefined 期待 $end 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35686293/