Making a Grammar LL(1)

自闭症网瘾萝莉.ら 提交于 2019-12-05 04:46:41
templatetypedef

In his original paper on LR parsing, Knuth gives the following grammar for this language, which he conjectures "is the briefest possible unambiguous grammar for this language:"

S → ε | aAbS | bBaS

A → ε | aAbA

B → ε | bBaB

Intuitively, this tries to break up any string of As and Bs into blocks that balance out completely. Some blocks start with a and end with b, while others start with b and end with a.

We can compute FIRST and FOLLOW sets as follows:

FIRST(S) = { ε, a, b }

FIRST(A) = { ε, a }

FIRST(B) = { ε, b }

FOLLOW(S) = { $ }

FOLLOW(A) = { b }

FOLLOW(B) = { a }

Based on this, we get the following LL(1) parse table:

   |   a   |   b   |   $   
 --+-------+-------+-------
 S | aAbS  | bBaS  |  e
 A | aAbA  |   e   |
 B |   e   | bBaB  |

And so this grammar is not only LR(1), but it's LL(1) as well.

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!