下面是使用Bison C++解析器生成减法表达式的代码示例:
subtraction.y
的Bison源文件,并输入以下内容:%{
#include
#include
#include
using namespace std;
void yyerror(const char* s) {
cout << "错误信息: " << s << endl;
}
int yywrap() {
return 1;
}
int yylex();
%}
%union {
int num;
}
%token NUMBER
%left '+' '-'
%type expr
%%
stmt: expr { cout << "结果: " << $1 << endl; }
;
expr: expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| NUMBER { $$ = $1; }
;
%%
int main() {
yyparse();
return 0;
}
int yylex() {
static int lookahead = -1;
if (lookahead == -1)
lookahead = cin.get();
while (isspace(lookahead))
lookahead = cin.get();
if (isdigit(lookahead)) {
int num = 0;
while (isdigit(lookahead)) {
num = num * 10 + lookahead - '0';
lookahead = cin.get();
}
yylval.num = num;
return NUMBER;
}
int token = lookahead;
lookahead = cin.get();
return token;
}
bison -d subtraction.y
这将生成名为subtraction.tab.h
和subtraction.tab.c
的文件。
subtraction.l
的Flex源文件,并输入以下内容:%{
#include "subtraction.tab.h"
%}
%%
[ \t] /* 忽略空格和制表符 */
[0-9]+ { yylval.num = atoi(yytext); return NUMBER; }
. { return yytext[0]; }
%%
int main() {
yyparse();
return 0;
}
flex subtraction.l
这将生成名为lex.yy.c
的文件。
g++ subtraction.tab.c lex.yy.c -o subtraction
./subtraction
现在,您可以输入一个减法表达式,例如5-2
,程序将输出结果3
。
上一篇:Bison 3.2编译问题