我使用flex制作词法分析器。我想分析一些定义编译器语句,其形式为:#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);
}
}
<<EOF>> {
puts("EOF reached");
yypop_buffer_state();
if ( !YY_CURRENT_BUFFER )
{
yyterminate();
}
loop_detection = 0;
}
identifier_string的分析执行得很好。现在当达到EOF时,我想切换回初始缓冲区并恢复分析。但它完成了印刷EOF到达。
答案 0 :(得分:1)
虽然这种方法似乎是合乎逻辑的,但它不起作用,因为yy_scan_string
替换当前缓冲区,并且在调用yypush_buffer_state
之前发生。因此,原始缓冲区丢失,并且在调用yypop_buffer_state
时,恢复的缓冲区状态是(现已终止)字符串缓冲区。
所以你需要一点点hack:首先,将当前缓冲区状态复制到堆栈上,然后切换到新的字符串缓冲区:
/* Was: yypush_buffer_state(yy_scan_string(p)); */
yypush_buffer_state(YY_CURRENT_BUFFER);
yy_scan_string(p);