flex 和 bison 的通用标记

标签 c compiler-construction bison flex-lexer

我有一个包含我的 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/

相关文章:

C-Qsort : Sort name in ascending order and grade in descending order

sqlite - SQLite源代码parse.y-nm

parsing - 我应该如何在 yacc/bison 和 lex 中制定递归规则?

c++ - Antlr 的优势(相对于 lex/yacc/bison)

c - 浮点模运算

c - 请求非结构或 union 中的成员 'something'

c - MPI:发送包含指针的结构数组

compiler-construction - 写入 REPL : where to start?

compiler-construction - 面向 JVM 而不是 x86 的缺点是什么?

c# - 静态变量和静态字段的实现区别是什么?