【问题标题】:lexical analysis stops after yy_scan_string() is finishedyy_scan_string() 完成后词法分析停止
【发布时间】:2015-05-08 05:06:02
【问题描述】:

我使用 flex 来做一个词法分析器。我想分析一些定义编译器语句,格式为:#define identifier identifier_string。我保留了 (identifier identifier_string) 对的列表。因此,当我在文件中找到#define list 的标识符时,我需要从主文件切换词法分析以分析相应的标识符字符串。 (我没有放完整的 flex 代码,因为太大了) 这是部分:

{IDENTIFIER}                    {   // search if the identifier is in list
                                    if( p = get_identifier_string(yytext) )
                                    {
                                        puts("DEFINE MATCHED");
                                        yypush_buffer_state(yy_scan_string(p));
                                    }
                                    else//if not in list just print the identifier
                                    {
                                        printf("IDENTIFIER %s\n",yytext);
                                    }
                                }
<<EOF>>                         {
                                    puts("EOF reached");
                                    yypop_buffer_state();
                                    if ( !YY_CURRENT_BUFFER )
                                    {
                                        yyterminate();
                                    }
                                    loop_detection = 0;
                                }

identifier_string 的分析执行得很好。现在,当达到 EOF 时,我想切换回初始缓冲区并恢复分析。但它只完成了打印 EOF 到达。

【问题讨论】:

    标签: c lex


    【解决方案1】:

    虽然这种方法看起来合乎逻辑,但它不起作用,因为yy_scan_string 替换当前缓冲区,并且发生在调用yypush_buffer_state 之前。因此,原始缓冲区丢失,当调用yypop_buffer_state 时,恢复的缓冲区状态是(现在终止的)字符串缓冲区。

    所以你需要一点技巧:首先,将当前缓冲区状态复制到堆栈上,然后切换到新的字符串缓冲区:

    /* Was: yypush_buffer_state(yy_scan_string(p)); */
    yypush_buffer_state(YY_CURRENT_BUFFER);
    yy_scan_string(p);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-01
      • 2017-02-27
      • 2011-07-16
      • 2018-12-23
      • 2020-10-18
      • 1970-01-01
      相关资源
      最近更新 更多