yy_scan_string() 完成后词法分析停止

lexical analysis stops after yy_scan_string() is finished

我用flex做了一个词法分析器。我想分析一些 define 编译器语句,其形式为:#define identifier identifier_string。我保留了一个 (identifier identifier_string) 对的列表。因此,当我在文件中到达一个标识符,即#define 列表时,我需要将词法分析从主文件切换到分析相应的 identifier_string。 (我没有放完整的 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 reached。

虽然这种方法看起来合乎逻辑,但它不会起作用,因为 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);