flex 和 bison 的常见代币

发布于 2024-12-19 11:05:19 字数 282 浏览 4 评论 0原文

我有一个包含令牌声明的文件。h:

#define ID 257
#define NUM 258
...

在我的 Flex 代码中,我返回此值或符号之一(例如“+”、“-”、“*”)。一切正常。

野牛文件中的问题。 如果我写这样的东西: exp: ID '+' ID 我会收到错误,因为 bison 不知道有关 ID 的任何信息。 添加行 %token ID 不会有帮助,因为在这种情况下我会遇到编译错误(预处理器将 ID 更改为 257,我将得到 257=257)

I have one file with declarations of my tokens declarations.h:

#define ID 257
#define NUM 258
...

In my flex code i return one of this values or symbol(for example '+', '-', '*'). And everything works.

The problem in bison file.
If i write something like that:
exp: ID '+' ID
i'll get error, because bison doesn't know anything about ID.
Adding the line %token ID will not help, because in that case i'll have compilation error(preprocessor will change ID by 257 and i'll get 257=257)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最好是你 2024-12-26 11:05:19

您让 Bison 创建代币列表;您的词法分析器使用 Bison 生成的列表。

bison -d grammar.y
# Generates grammar.tab.c and grammar.tab.h

然后,您的词法分析器使用 grammar.tab.h

$ cat grammar.y
%token ID
%%
program:    /* Nothing */
    |       program ID
    ;
%%
$ cat lexer.l
%{
#include "grammar.tab.h"
%}
%%
[a-zA-Z][A-Za-z_0-9]+   { return ID; }
[ \t\n]                 { /* Nothing */ }
.                       { return *yytext; }
%%
$ bison -d grammar.y
$ flex lexer.l
$ gcc -o testgrammar grammar.tab.c lex.yy.c -ly -lfl
$ ./testgrammar
id est
quod erat demonstrandum
$ 

MacOS X 10.7.2 上的 Bison 2.4.3 将令牌编号生成为 enum,而不是一系列 #define 值 - 将标记名称放入调试器的符号表中(一个非常好的主意!)。

You get Bison to create the list of tokens; your lexer uses the list generated by Bison.

bison -d grammar.y
# Generates grammar.tab.c and grammar.tab.h

Your lexer then uses grammar.tab.h:

$ cat grammar.y
%token ID
%%
program:    /* Nothing */
    |       program ID
    ;
%%
$ cat lexer.l
%{
#include "grammar.tab.h"
%}
%%
[a-zA-Z][A-Za-z_0-9]+   { return ID; }
[ \t\n]                 { /* Nothing */ }
.                       { return *yytext; }
%%
$ bison -d grammar.y
$ flex lexer.l
$ gcc -o testgrammar grammar.tab.c lex.yy.c -ly -lfl
$ ./testgrammar
id est
quod erat demonstrandum
$ 

Bison 2.4.3 on MacOS X 10.7.2 generates the token numbers as an enum, not as a series of #define values - to get the token names into the symbol table for debuggers (a very good idea!).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文