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

我用flex来制作一个词法分析器。 我想分析一些定义编译器语句,其forms为:#define identifier identifier_string。 我保留了(标识符identifier_string)对的列表。 因此,当我在文件中到达#define list的标识符时,我需要从主文件切换词法分析以分析相应的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); } } <> { puts("EOF reached"); yypop_buffer_state(); if ( !YY_CURRENT_BUFFER ) { yyterminate(); } loop_detection = 0; } 

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

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