gpt4 book ai didi

bison - flex 究竟是如何支持 Bison 定位的?

转载 作者:行者123 更新时间:2023-12-03 12:01:50 26 4
gpt4 key购买 nike

我正在尝试使用 flex 和 bison 创建过滤器,因为我想从复杂的语言中获取某些语法元素。我的计划是使用 flex + bison 来识别语法,并转储出感兴趣元素的位置。 (然后使用脚本根据转储的位置获取文本。)

我发现 flex 可以支持名为 bison-locations 的 Bison 功能,但它是如何工作的。我尝试了 flex 文档中的示例,似乎 yylloc 不是由 flex 自动设置的,我总是得到 (1,0)-(1,0) . flex 可以自动计算每个 token 的位置吗?如果没有,定义了哪些接口(interface)函数供我实现?有什么例子吗?

关于工具有更好的解决方案吗?

最好的祝福,
凯文

编辑:

现在yylex的界面变成了:

int yylex(YYSTYPE * yylval_param,YYLTYPE * yylloc_param );

Bison 手册未指定词法分析器应如何实现以正确设置 yylloc_param。对我来说,很难手动跟踪每个 token 的列号。

最佳答案

yylex 声明可能更改了,因为您使用了可重入或纯解析器。似乎网络上的许多文档都表明,如果您希望 Bison 位置工作,则需要这样做,但不是必需的。

我也需要行号,发现 Bison 文档在这方面令人困惑。
简单的解决方案(使用全局 var yylloc):
在您的 Bison 文件中,只需添加 %locations 指令:

%{
...
%}
%locations
...
%%
...

在你的词法分析器中:
%{
...
#include "yourprser.tab.h" /* This is where it gets the definition for yylloc from */
#define YY_USER_ACTION yylloc.first_line = yylloc.last_line = yylineno;
%}
%option yylineno
...
%%
...

YY_USER_ACTION 宏在您的每个 token 操作之前被“调用”并更新 yylloc。
现在您可以像这样使用@N/@$ 规则:
statement : error ';'   { fprintf(stderr, "Line %d: Bad statement.\n", @1.first_line); }

,或使用 yylloc 全局变量:
void yyerror(char *s)
{
fprintf(stderr, "ERROR line %d: %s\n", yylloc.first_line, s);
}

关于bison - flex 究竟是如何支持 Bison 定位的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/656703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com