关于flex-bison工具的一点参考

这篇文章是上学期写的,有些地方还不完善,时间长了不想完善了,仅供参考。(2022.1.9)


概述

刚开始拿着一个flex-bison的程序来看一般都会有些迷茫,感觉我好像懂了,又好像没懂:为什么这个定义会重复出现?为什么开头的那段定义和之后的那些声明位置好像没有绝对的先后?%left%token%nonassoc%type都是些什么东西?那个%union还有yylval是干什么的?这些文件编译的指令是什么?头文件谁加谁呢?
总之,就是不怎么聪明的小脑袋里充满了大大的疑惑。不要着急,你疑惑的就是我已经疑惑过了的。

bison

  1. 特点:
    bison是有限的向前查看,大多数移进/冲突规约来自bison有限的向前查看。

名词

bison

  1. 记号:终结符,即词法分析器传递给语法分析器的符号。通过bison工具调用yylex()函数从输入中返回。输入结束时,yylex()返回0。
    记号的声明:
%token
%left
%right
%nonassoc

作用:词法分析器需要知道记号编号,以便于能够返回合适的数值给语法分析器。
对于文字记号,它使用对应的C字符常量,对于符号记号,可以通过-d命令行标志来让bison创建一个C的头文件,里面包含所有记号编号的定义,在词法分析器中#include这个头文件,就可以在C代码中直接使用符号记号。你可以通过--defines=filename命令行选项来更改生成的默认头文件名称。
2.

常用函数

bison

yyparse():bison生成的语法分析器的入口函数就是yyparse()。

二义性与冲突

flex处理二义性方法:(行之有效)

  1. 词法分析器匹配输入时匹配尽可能多的字符串
  2. 如果两个模式都可以匹配的话,匹配在程序中更早出现的模式
    eg:
"+" {return ADD;}
"+=" {return ASSIGNADD;}
"if" {return KEYWORDIF;}
[a-zA-Z_][a-zA-Z0-9_]* {return IDENTIFIER;}

对于前两个模式:若有+=先匹配+=,而不是+。对于后两个模式:只要关键词的模式在标识符的模式(.l文件里的顺序)前面,就会先匹配关键词。

[]为字符组:它把所有存在或关系的字符集中在[]里面。

推荐一个好的网站
它里面有一段话,告诉我们如何解决冲突:

Bison normally warns if there are any conflicts in the grammar (see section Shift/Reduce Conflicts), but most real grammars have harmless shift/reduce conflicts which are resolved in a predictable way and would be difficult to eliminate. It is desirable to suppress the warning about these conflicts unless the number of conflicts changes. You can do this with the %expect declaration.

The declaration looks like this:

%expect n
Here n is a decimal integer. The declaration says there should be no warning if there are n shift/reduce conflicts and no reduce/reduce conflicts. The usual warning is given if there are either more or fewer conflicts, or if there are any reduce/reduce conflicts.

In general, using %expect involves these steps:

Compile your grammar without %expect. Use the `-v' option to get a verbose list of where the conflicts occur. Bison will also print the number of conflicts.
Check each of the conflicts to make sure that Bison's default resolution is what you really want. If not, rewrite the grammar and go back to the beginning.
Add an %expect declaration, copying the number n from the number which Bison printed.
Now Bison will stop annoying you about the conflicts you have checked, but it will warn you again if changes in the grammar result in additional conflicts.

编译理论

代码体现

网站:

有关bison的command参看https://www.tutorialspoint.com/unix_commands/bison.htm
https://www.math.utah.edu/docs/info/bison_6.html#SEC54
有关flex的command参看https://www.cs.virginia.edu/~cr4bd/flex-manual/Index-of-Scanner-Options.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值