13
Introduction of Bison/ Yacc

Introduction of Bison/Yacc

Embed Size (px)

DESCRIPTION

Introduction of Bison/Yacc. Yet another compiler-compiler. LALR(1) 分析生成器 安装 Bison 编写 .y 文件,描述文法 Bison *.y 生成 .c 文件 VC 编译 .c 文件生成 exe 文件 运行 exe 分析输入串. Yacc 说明文件 (.h) { 定义 } %% { 规则 } %% 辅助程序. Example. exp -> exp addop term | term addop -> + | - term -> term mulop factor | factor - PowerPoint PPT Presentation

Citation preview

Page 1: Introduction of Bison/Yacc

Introduction of Bison/Yacc

Page 2: Introduction of Bison/Yacc

Yet another compiler-compiler

LALR(1) 分析生成器 安装 Bison 编写 .y 文件,描述文法 Bison *.y 生成 .c 文件 VC 编译 .c 文件生成 exe 文件 运行 exe 分析输入串

Page 3: Introduction of Bison/Yacc

Yacc 说明文件 (.h) { 定义 } %% { 规则 } %% 辅助程序

Page 4: Introduction of Bison/Yacc

Example

exp -> exp addop term | term addop -> + | - term -> term mulop factor | factor mulop -> * factor -> (exp) | number

对应的 .y 文件

Page 5: Introduction of Bison/Yacc

解释

exp : exp ‘+’ term { $$ = $1 + $3; } yylval yylex yyerror yyparse

Page 6: Introduction of Bison/Yacc

分析表以及分析过程

Bison -v *.y 生成对应 .output 文件 .output 文件即生成的 LALR(1) 分析表 设置 yydebug 可直接输出分析过程

Page 7: Introduction of Bison/Yacc

处理二义性

E -> E+E | E-E | E*E | E/E | (E) | -E | E^E | number

归约 - 归约冲突:选择说明中最先出现的产生式

移进 - 归约冲突:移进优先 算符优先与结合性

Page 8: Introduction of Bison/Yacc

算符的优先级与结合性

优先级(越后出现优先级越高) %left ‘+’ ‘-’ %left ‘*’

结合性 %left ‘+’ ‘-’ 12+34-12 %right (右结合) %nonassoc (重复的算符不允许出现在相同的

层级)

Page 9: Introduction of Bison/Yacc

E -> E+E | E-E | E*E | E/E | (E) | -E | E^E | number

对应的 .y 文件

Page 10: Introduction of Bison/Yacc

Bison 与 Flex 的结合

Bison –d *.y 生成 .h 文件 .h 文件中存放需要的 token .l 文件定义所有的 token Flex *.l 替换 yylex 函数

Page 11: Introduction of Bison/Yacc

YYSTYPE

$$, $1, $2 的实际值,存放在 yylval 中 默认 yylval 为 int 类型 可通过 #define YYSTYPE double 设

置为其他类型 %union 设置复杂的类型 YYSTYPE 也可定义为特定的类型 ( 其

他头文件中定义 ), #define YYSTYPE treeNode *

Page 12: Introduction of Bison/Yacc

Example

%union{double val; char op} %token NUM %type <val> exp term factor NUM %type <op> addop mulop

exp : exp op term {switch($2) {

case ‘+’: $$ = S1 + S3; break; case ‘-’: $$ = S1 – S2; break;

} }

Tiny 程序(编译原理与实践 附录)

Page 13: Introduction of Bison/Yacc

Thanks