我有一个包含我的 token declarations.h 声明的文件:
#define ID 257
#define NUM 258
...
在我的 flex 代码中,我返回此值或符号之一(例如“+”、“-”、“*”)。一切正常。
bison 文件中的问题。 如果我写这样的话: exp: ID '+' ID 我会出错,因为 Bison 对 ID 一无所知。 添加行 %token ID 将无济于事,因为在那种情况下我会出现编译错误(预处理器会将 ID 更改为 257,我将得到 257=257)
最佳答案
你让 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 将 token 编号生成为 enum
,而不是一系列 #define
值 - 将 token 名称放入调试器的符号表(一个非常好的主意!)。
关于flex 和 bison 的通用标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8375391/