注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
previously:
第二个unit http://www.1point3acres.com/bbs/thread-37174-1-1.html
第一个unit http://www.1point3acres.com/bbs/thread-37089-1-1.html
经过前面状态机和词法分析的基础后,第三个unit开始进入语法分析的领域了。这部分中稍难点的有两个知识点:
1. 基于语句的一些常用运算。 比如给出一套语法规则,判断其是否是infinite的。
{
S -> Q
Q -> b
Q -> R a
R -> Q
}
这套语法规则是infinite的,因为从S开始,你可以得到无数种不同的终止状态。
2. 处理ambiguity的情况。在语言学中,ambiguity十分常见,比如在某语言中,有如下三条语法规则
{
S -> if E then S
S -> if E then S else S
E -> Number > Number
}
那么这三条语法规则会产生ambiguity的。比如 if 4>3 then if 3>2 return 2 else return 3 这条语句可以有两种语法分析方案。需要调整语法规则解决冲突。
编程作业题:
Expanding Expression
已定义了一套语法规则。输入一个语句,输出所有可能的语法分析结果。
例子:
语法规则 = {
Exp -> Exp + Exp Exp -> Exp - Exp
Exp -> 任意数字
}
输入语句 = EXP
输出结果 = {
Exp + Exp
Exp - Exp
任意数字
} (这是当迭代次数指定为1次时。同理,当迭代次数为更多时,应该继续扩展Exp)
Detecting Ambiguity (作业第五题)
A grammar is ambiguous if there exists a string in the language of that grammar that has two (or more) parse trees.
For example:
grammar1 = {
S -> P 规则 0
S -> a, Q 规则 1
P -> a, T 规则 2
P -> c 规则 3
Q -> b 规则 4
T -> b 规则 5
}
In this grammar, the tokens ["a", "b"] do demonstrate that the grammar is ambiguous because there are two difference sequences of rewrite rules to obtain them:
S --0-> P --2-> a T --5-> a b
S --1-> a Q --4-> a b
(I have written the 规则编号 inside the arrow for clarity.) The two sequences are [0,2,5] and [1,4].
|