在研究语法分析器时,大部分语法分析器都期望文法是无二义性的,否则,我们就不能为一个句子唯一地选定语法分析树。但是在某种情况下,使用经过精心选择的二义性文法可以带来方便。此时需要使用消二义性规则来“抛弃”不想要的语法分析树,只为每个句子留下一棵语法分析树。假如我们要将if then else语句加入某一文法G中,我们可以给出无二义性文法如下:
stmt -> matched_stmt
| open_stmt
matched_stmt -> if expr then matched_stmtelse macthed_stmt
| other
open_stmt -> if expr then stmt
| if expr then matched_stmt else open_stmt
其中加粗的为终结符。
这段代码让我看了好久好久,才终于领悟。
if-then-else 存在二义性如下:
版本一:
if E1 then
if E2 then
S1
else
S2
版本二:
if E1 then
if E2 then
S1
else
S2
同样是if-then-else却会产生不同的语法分析树,主要原因在于悬空的else
而上面那段代码是直接定性给出stmt的各种情况分为matched_stmt 和 open_stmt
首先是
matched_stmt
主要是给出了类型 if - then - else 当然其中其后可以再多次穿插if - then -else可能再嵌套各种类型
open_stmt
主要是给出类型 if - then 或者是 if ( if then else) then
主要通过这几个组合实现if - then - else 的定性构造。
[编译原理]从if-then-else看二义性
最新推荐文章于 2023-06-09 16:00:08 发布