您的位置:首页 > 其它

flex & bison学习(三)

2011-11-16 20:11 253 查看
GNU bison是一个自由软件,用于自动生成语法分析器程序,实际上可用于所有常见的操作系统。Bison把LALR形式的上下文无关文法描述转换为可做语法分析的CC++程序。在新近版本中,Bison增加了对GLR语法分析算法的支持。

GNU bison基本兼容Yacc,并做了一些改进。它一般与flex一起使用。

下面是一个简单的计算器的文法描述Bison程序

/* simplest version of calculator */

%{
# include <stdio.h>
%}

/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token OP CP
%token EOL

%%

calclist: /* nothing */
| calclist exp EOL { printf("= %d\n> ", $2); }
| calclist EOL { printf("> "); } /* blank line or a comment */
;

exp: factor
| exp ADD exp { $$ = $1 + $3; }
| exp SUB factor { $$ = $1 - $3; }
| exp ABS factor { $$ = $1 | $3; }
;

factor: term
| factor MUL term { $$ = $1 * $3; }
| factor DIV term { $$ = $1 / $3; }
;

term: NUMBER
| ABS term { $$ = $2 >= 0? $2 : - $2; }
| OP exp CP { $$ = $2; }
;
%%

int main()
{
yyparse();
return 0;
}

int yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
}

对应的flex词法分析器为

/* recognize tokens for the calculator and print them out */

%{
# include "fb1-5.tab.h"
%}
%option noyywrap

%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"|" { return ABS; }
"(" { return OP; }
")" { return CP; }
[0-9]+ { yylval = atoi(yytext); return NUMBER; }

\n { return EOL; }
"//".*
[ \t] { /* ignore white space */ }
. { yyerror("Mystery character %c\n", *yytext); }
%%

按照如下顺序编译出fb1-5即可
bison -d fb1-5.y
flex fb1-5.l
cc -o fb1-5 fb1-5.tab.c lex.yy.c -lfl
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: