Appetizer #1 Before Parsing: CFG Simplification
0. OverviewPermalink
为什么需要化简?为提高编译器的执行效率。比如提高 “判定
Types of Redundancy:
-productions,i.e. 形如 的产生式- 会得到语言
- 会得到语言
- unit productions (单元产生式),i.e. 形如
的产生式 - useless productions (无用产生式),i.e. 对文法定义语言没有贡献的产生式,分两类:
- non-reachable productions
- 比如
,这个 不可能被 触及,属于 non-reachable
- 比如
- non-generating productions
- 比如
,这个 不可能终结,属于 non-generating
- 比如
- non-reachable productions
工程中做 simplification 的可靠顺序是:
- Eliminate
-productions - Eliminate unit productions
- Eliminate non-generating productions
- Eliminate non-reachable productions
1. Eliminate -productionsPermalink
如果有一个 CFG
你也可以选择在
Dummy Start Symbol: 工程中还有一个 preprocessing practice 是给
Procedure:
- Eliminate all
production from (可以允许 ,也可以要求 ,看你需求) - 如果你消除了一个具体的
,然后有 :- 你可能原来是
,你消除了 但仍然有 ,所以你不能直接把 中的 直接删掉 - 如果原来就只有
,你是可以直接把 中的 直接删掉,但记住我们后面还有 ”消除 non-generating symbols“ 的步骤,所以你保留 中的 也是 ok 的 - 以上两种情况,有一个统一的解决方案就是:把
改写成 - 归纳一下就是:
occurrence of on the body of a production rule, add a new rule to with that occurrence of deleted. - 一个更复杂的例子是:
,它要改写成
- 你可能原来是
- 如果你消除了一个具体的
,然后有 ,可以改写成- 是的,这里你有引入了一个新的
,但我们可以 repeatedly 继续 eliminate
- 是的,这里你有引入了一个新的
- Repeat step 1~3 直到所有的
-production 都被消除
2. Eliminate unit productionsPermalink
Procedure:
- Eliminate all
production from - 如果你消除了一个具体的
,然后有 :可以直接添加一条 到 - Repeat step 1~2 直到所有的 unit-production 都被消除
Bonus: cycle-free grammar
A cycle in a grammar means a derivation
- If we have
, following the above procedure, we drop but keep in - If we have
, we drop and then augment into . Problem is reduced to Case 1.
Therefore, eliminating unit productions (with
3. Eliminate useless productionsPermalink
Procedure: Remove non-generating productions
- 初始化
- Repeat until no more variables are added:
with where , add to becomes the set of generating variables
- Define
is the set of generating productions
The grammar
Definition: VDG (Variable Dependency Graph) of a given Grammar
- For each variable
, draw a vertex - For each production
, draw an edge
Procedure: Remove non-reachable productions (by VDG):
- Construct a VDG
for the generating grammar - Find all variable
that has no path- DFS or BFS
- 注意是这里要求的是 directed path
- Remove such
from , get - Remove production from
whose LHS is such an , get
The grammar
此时
留下评论