嗨,我已经开始倾斜Bison解析器生成器。我尝试了以下程序。我使用MinGW on Window 7,在mintty客户端上使用编译并运行了程序。野牛版本是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);
}
Run Code Online (Sandbox Code Playgroud)
我用编译程序,bison filename.y然后gcc filename.tab.c尝试运行程序并在stdin中输入5时,由于从yyerror函数打印出来,因此出现以下错误。谁能帮我找到我做错了什么。
Error : syntax error, unexpected $undefined, expecting $end
Run Code Online (Sandbox Code Playgroud)
当您的词法分析器在\n输入数字后读取(换行符)字符时,会将其返回到解析器,后者无法将其识别为任何内容,因此您得到了unexpected $undefined(换行符被打印为$undefined因为换行符从未出现在语法中),预期的时间$end(输入指示器的结尾)。
将您的最后一行更改yylex为return 0;(0是输入指示器的末尾),而不是return ch;应该起作用。