【问题标题】:Bison syntax error unexpected $undefined expecting $end errorBison 语法错误意外 $undefined Expecting $end 错误
【发布时间】:2016-02-28 18:10:07
【问题描述】:

您好,我已经开始学习 Bison 解析器生成器。我尝试了以下程序。我使用MinGW on Window 7mintty 客户端编译并运行程序。 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

【问题讨论】:

  • 我推荐使用 flex 作为词法分析器。 Bison 和 flex 相得益彰。

标签: c parsing bison


【解决方案1】:

当您的词法分析器在您输入的数字之后读取\n(换行符)字符时,它会将其返回给您的解析器,解析器不会将其识别为任何内容,因此您会得到unexpected $undefined(换行符打印为$undefined 因为换行符永远不会出现在你的语法中),而它期待 $end(输入结束指示符)。

yylex 的最后一行更改为return 0;(0 是输入结束指示符)而不是return ch;,它应该可以工作。

【讨论】:

    猜你喜欢
    • 2014-12-18
    • 2012-05-16
    • 1970-01-01
    • 2012-08-15
    • 2011-02-09
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多