4

我正在使用 flex 2.5.35 和 bison 2.7(尽管我相信这是一个 flex 问题,所以我省略了 parser.y)

我的 Flex 语法很简单:

词法分析器

%{
#define YY_NO_INPUT
#include "parser.h"

#define YY_USER_ACTION yylloc->first_line = yylloc->last_line = yylineno; \
    yylloc->first_column = yycolumn; yylloc->last_column = yycolumn + (int)yyleng - 1; \
    yycolumn += (int)yyleng;

%}

%option yylineno
%option outfile="lexer.c" header-file="lexer.h"
%option warn
%option reentrant noyywrap never-interactive nounistd
%option nounput
%option bison-bridge
%option bison-locations

%%

[ \n\r\t]*               { /* Skip blanks. */ }
[A-Za-z0-9_\-@]+       { yylval->value = strdup(yytext); return TOKEN_VAR; }
"&&"                   { return TOKEN_AND; }
"||"                   { return TOKEN_OR; }
"!"                    { return TOKEN_NOT; }
"("                    { return TOKEN_LPAREN; }
")"                    { return TOKEN_RPAREN; }

%%

扫描字符串时,行号和列号的值是未初始化的垃圾。我跟踪代码并将以下行添加到生成的 lexer.c 中的 yy_scan_buffer 中:

b->yy_bs_lineno = 1;
b->yy_bs_column = 1;

现在这些值符合预期。

这是一个错误吗?yy_create_buffer正确初始化这些字段,但yy_scan_buffer没有。

%option yylineno解析字符串时不能使用吗?

有解决办法,还是我真的需要修改生成的 lexer.c?

4

2 回答 2

3

是的,我可以确认,这是野牛的问题。它发生在我身上,我已经通过在我的“编译器函数”中初始化它们来修复它

void myParseFunction(const char* code, ...){
    yyscan_t myscanner;
    yylex_init(&myscanner);
    struct yyguts_t * yyg = (struct yyguts_t*)myscanner;

    yy_delete_buffer(YY_CURRENT_BUFFER,myscanner);
    yy_scan_string(code, myscanner);

    // [HACK] Those are not properly initialized for non file parsers
    // and becuase of that we get garbage in yyerror...
    yylineno = 1;
    yycolumn = 0;

    bool nasi = yyparse(myscanner, <your_args>);
        yylex_destroy(myscanner);
        return nasi;
}

请注意,yyl​​ineno 和 yycolumn 与可重入解析器一起工作得很好,因为它们被定义为引用“yyg”的 marcos。

于 2016-04-30T20:15:32.740 回答
1

您从oreilly book的“Adding Locations to the Lexer”部分复制了您的 YY_USER_ACTION 代码

我相信您忘记int yycolumn = 1;在定义 YY_USER_ACTION 之前添加,因为它是在链接中的代码示例中完成的。

于 2013-02-10T14:15:25.117 回答