flex & bison学习(三)

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

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


相关文章
|
9月前
|
Ubuntu
ubuntu源码安装flex和bison
ubuntu源码安装flex和bison
364 0
|
Ubuntu
Ubuntu12.04(32bit)下安装bison和flex
Ubuntu12.04(32bit)下安装bison和flex
566 0
|
内存技术 开发工具 数据可视化
|
XML JavaScript 数据格式
|
XML JavaScript Java
|
自然语言处理 Unix SQL
OpenCASCADE Expression Interpreter by Flex & Bison
OpenCASCADE Expression Interpreter by Flex & Bison eryar@163.com Abstract. OpenCASCADE provide data structure of any expression, relation or function used in mathematics.
1313 0
|
Web App开发 JavaScript Java
flex学习
早就想弄个flex的东西了...总是没有心情弄..有的时候项目让人心力憔悴...   最近,,想着是破罐子破摔..弄点别的东西...换个心情..然后在去弄下项目...(已经快接近尾声了)   总是在开发的第一线..技术上面什么都弄..公司里面还要应付其他同事的问题...   能帮助别人就帮助吧..本人也没有别的什么有点..就代码上面略有研究.(投入的时间多了自然就有所领悟了)   1,先弄个s
1285 0
|
编译器
FlexPaper源码编译
FlexPaper是一个Flex中直接浏览PDF文件的控件,例如百度文库这种形式,我们可以对FlexPaper的源码进行修改,完成我们的需求。 首先下载FlexPaper的源码   下载点击我 一、导入Flex库项目文件 将flexswcnew.fxp 文件导入flex中。
817 0
Flex学习笔记(Day 2)
LineChart ViewStack控件 //一种方法 var url:String; url = "http://www.
692 0