Bison语法错误意外$ undefined期待$ end错误

时间:2016-02-28 18:10:07

标签: c parsing bison

您好我已经开始使用Bison解析器生成器。我尝试了以下程序。我使用MinGW on Window 7mintty客户端终端编译并运行程序。野牛版本是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编译了程序,当我尝试运行程序并在stdin中输入5时,我收到以下错误,因为它是从yyerror函数打印的。任何人都可以帮我找到我做错的事。

Error : syntax error, unexpected $undefined, expecting $end

1 个答案:

答案 0 :(得分:4)

当您的词法分析器在您输入的数字后面读取\n(换行符)字符时,会将其返回给您的解析器,该解析器无法识别它,因此您获得了unexpected $undefined (当换行符期望$undefined(输入指示符结束)时,换行符将打印为$end,因为换行符永远不会出现在语法中)。

yylex的最后一行更改为return 0;(0是输入指示符的结尾),而不是return ch;,它应该有效。

相关问题