野牛语法错误意外 $undefined 期待 $end 错误
Bison syntax error unexpected $undefined expecting $end error
您好,我已经开始学习 Bison 解析器生成器。我尝试了以下程序。我使用 MinGW on Window 7
和 mintty
客户端编译并 运行ning 程序。 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 { $$ = ; printf("value : %d %d %d %d\n", ,
@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
(换行符)字符时,它 returns 将它发送给您的解析器,解析器不会将其识别为任何东西,因此您得到 unexpected $undefined
(换行符打印为 $undefined
,因为换行符永远不会出现在您的语法中),当它期望 $end
(输入指示符结束)时。
将 yylex
的最后一行更改为 return 0;
(0 是输入指示符的结尾)而不是 return ch;
,它应该可以工作。
您好,我已经开始学习 Bison 解析器生成器。我尝试了以下程序。我使用 MinGW on Window 7
和 mintty
客户端编译并 运行ning 程序。 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 { $$ = ; printf("value : %d %d %d %d\n", ,
@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
(换行符)字符时,它 returns 将它发送给您的解析器,解析器不会将其识别为任何东西,因此您得到 unexpected $undefined
(换行符打印为 $undefined
,因为换行符永远不会出现在您的语法中),当它期望 $end
(输入指示符结束)时。
将 yylex
的最后一行更改为 return 0;
(0 是输入指示符的结尾)而不是 return ch;
,它应该可以工作。