【问题标题】:yyerror in Bison- how to get more info?Bison 中的 yyerror-如何获取更多信息?
【发布时间】:2013-12-11 19:13:44
【问题描述】:

我有一个硬件任务,我需要使用 Bison 和 flex。

我需要在 Bison 文件中编写一个 yyerror 函数,它将出现问题的行号(来自输入文件)写入屏幕,并且它需要告诉 Bison 停止的令牌(来自堆栈它正在构建)

有简单的方法吗?

我尝试使用 lex 文件中的 yylineno 但出现错误。 解决方案的每个搜索选项都空手而归:(

【问题讨论】:

    标签: bison flex-lexer


    【解决方案1】:

    好的,找到了一个实用的答案。获得

    extern int yylineno;
    

    在 Bison 文件的第一部分

    编辑- 同样的方法可以帮助从 lex 文件中获取令牌,只需在 Bison 文件中写入: extern NODEPTR yylval;

    *yylval 在我的项目中被定义为 NODEPTR,如果你没有改变它,你应该使用 int(它的默认声明)

    【讨论】:

      【解决方案2】:

      您可以通过创建一个变量来跟踪行号来获取行号,然后在扫描仪(.l 文件)中增加该变量。

      要获取您需要的令牌信息,我只需在您的正则表达式中添加一个 %option debug 声明。

      两者的示例都可以在下面的示例 sudo 代码中看到。

      %{
      
          //Create variable to keep track of line number
          int linenum = 0;
      
      %}
      
      /*
       *  Definitions of regular expressions
       *  Note: You capture newlines here...
       */
      
      %%
       %option debug
      
       /*Token definitions*/
       NEWLINE      \n 
      
       ...
      
      %%
      {NEWLINE}   {   
                    linenum++;
                  }
      ...
      
      int main(void) {
         ...
         return 0;
      
      }
      

      【讨论】:

        【解决方案3】:

        除了使用 yylineno 的表格,如果你想在特定的生产中捕获错误,你可以在该生产中添加错误选项。例如。

        someproduction:
              option_one clause_1 
            | option_two clause_2
            | error { printf("Error in some production \n"); }
            ;
        

        您也可以在option_oneoption_two 中实现错误以捕获特定错误。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-06-29
          • 2023-03-26
          • 1970-01-01
          • 2020-04-24
          • 1970-01-01
          • 2023-03-07
          • 2020-06-30
          相关资源
          最近更新 更多