如何使用纯(可重入)flex / bison解析器进行嵌套包含?

时间:2014-06-17 19:08:02

标签: bison flex-lexer

我一直在将我的解析器/词法分析器转换为可重入的实现,最后的障碍是能够执行嵌套的include script.txt类型指令。

这是我为include位实现的:但它是seg-faults ,否则令牌化器和解析器的其余部分工作正常:

^{include}{ws}+     { BEGIN INCL;             }
<INCL>[^ \t\n\r\f]+ { /* Swallow everything up to whitespace or an EOL character.
                       * When state returns to initial, the whitepsace
                       * and/or EOL will be taken care of. */
                      {
                        FILE * _yyin;
                        _yyin = fopen ( yytext, "r" );
                        if (! _yyin) {
                          char buf[256];
                          snprintf(buf, DIM(buf) - 1,"Script include file ""%s"" couldn't be opened: %s.",yytext,strerror(errno));
                          yyerror(yyscanner, "buf");
                        } else {
                          extern int yyparse( yyscan_t * scanner);
                          yyscan_t incl_scanner;
                          struct my_parser_data incl_data;

                          yylex_init(& incl_scanner);
                          yylex_init_extra(& incl_data, & incl_scanner);
                          yyset_in( _yyin, & incl_scanner);

                          /* This call causes a segmentation fault. */
                          yyparse(& incl_scanner);

                          yylex_destroy( & incl_scanner);
                        }
                      }
                      BEGIN 0;
                    }

如何实施嵌套包含?

1 个答案:

答案 0 :(得分:1)

您不能同时致电 yylex_inityylex_init_extra。你打电话给其中一个;如果您需要额外数据,请拨打yylex_init_extra 而不是 yylex_init

但是,这不是产生段错误的原因。对yylex_init的双重调用是内存泄漏,而不是段错误。

段错误来自将 incl_scanner地址传递给yyset_inyyparseyylex_destroy。这些函数需要 scanner_t参数(这是一个指针)。

以下是flex manual的相关示例:

         yylex_init_extra( buf, &scanner );
         yyset_in( in, scanner );
         yylex( scanner );
         yylex_destroy( scanner );

请注意哪些功能需要&scanner,哪些功能只需scanner