弯曲和野牛的常见标记

kob*_*bra 4 c compiler-construction bison flex-lexer

我有一个文件,声明我的令牌声明.:

#define ID 257
#define NUM 258
...
Run Code Online (Sandbox Code Playgroud)

在我的flex代码中,我返回其中一个值或符号(例如'+',' - ','*').一切正常.

野牛文件中的问题.如果我写这样的东西:exp:ID'+'ID我会得到错误,因为野牛对ID没有任何了解.添加行%标记ID将无济于事,因为在这种情况下我将有编译错误(预处理器将更改ID 257,我将得到257 = 257)

Jon*_*ler 7

你让Bison创建令牌列表; 你的词法分析器使用Bison生成的列表.

bison -d grammar.y
# Generates grammar.tab.c and grammar.tab.h
Run Code Online (Sandbox Code Playgroud)

你的词法分析器然后使用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
$ 
Run Code Online (Sandbox Code Playgroud)

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