孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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


posted on 2011-11-16 20:11  孤独的猫  阅读(1715)  评论(0编辑  收藏  举报