【问题标题】:Common tokens for flex and bisonflex 和 bison 的常用标记
【发布时间】:2012-01-12 14:35:02
【问题描述】:
我有一个包含我的令牌声明的文件 declarations.h:
#define ID 257
#define NUM 258
...
在我的弹性代码中,我返回其中一个值或符号(例如“+”、“-”、“*”)。一切正常。
bison 文件中的问题。
如果我写这样的东西:
exp: ID '+' ID
我会出错,因为野牛对 ID 一无所知。
添加行 %token ID 将无济于事,因为在这种情况下我会遇到编译错误(预处理器会将 ID 更改为 257,我会得到 257=257)
【问题讨论】:
标签:
c
compiler-construction
bison
flex-lexer
【解决方案1】:
您让 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 值 - 将令牌名称放入调试器的符号表中(一个非常好的主意! )。