Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fixing non-ll(1) grammars

Similar presentations


Presentation on theme: "Fixing non-ll(1) grammars"— Presentation transcript:

1 Fixing non-ll(1) grammars
COP4620 – Programming Language Translators Dr. Manuel E. Bermudez

2 Topics Problems with model grammar Fixing common prefices
Fixing left-recursion New grammar: LL(1)

3 Model grammar Problems: → id := E; {id} SL is left recursive.
S → begin SL end {begin} → id := E; {id} SL → SL S {begin,id} → S {begin,id} E → E+T {(, id} → T {(, id} T → P*T {(, id} → P {(, id} P → (E) {(} → id {id} Problems: SL is left recursive. E is left recursive. T → P * T have common → P prefices. Showing a grammar is not LL(1): easy. PL grammars: “mostly” LL(1). This is our “model” PL grammar. We’ll use it throughout Modules 07 and 08.

4 Fixing common prefices
Change: T → P * T { (, id } → P { (, id } to: T → P X { (, id } X → * T { * } → { +, ; , ) } Follow(X) ⊇ Follow(T) due to T → P X ⊇ Follow(E) due to E → E+T , E → T = { +, ;, ) } due to E → E+T, S → id := E ; and P → (E)

5 Fixing common prefices
In general, change A → 1 → 2 . . . → n to A →  X X → 1 → n Hopefully all the ’s begin with different symbols. If not, repeat !

6 Fixing left recursion of E
We have (…((( T + T) + T) + T)…) Instead, we want (T) (+T) (+T) … (+T) Change: E → E + T { (, id } → T { (, id } To: E → T Y { (, id } Y → + T Y { + } → { ; , ) } Follow(Y)  Follow(E) = { ; , ) } Yikes: destroyed the left associatvity of ‘+’ ! Will fix this later. No longer contains ‘+’: we eliminated E → E + T

7 Fixing left recursion In general, Change: A → A1 A →  1 . . . . . .
→ An →  m to: A → 1 X X → 1 X → m X → n X The ’s don’t begin with A.

8 Fixing left recursion of SL
We have (…(((S)S)S)…) Instead, we want (S)(S) …(S) Change: SL → SL S { begin, id } → S { begin, id } To: SL → S Z { begin, id } Z → S Z { begin, id } → { end } Destroyed the left associatvity of ‘ ’. Fixable, but won’t matter.

9 Modified grammar → id := E ; {id} SL → S Z {begin,id}
S → begin SL end {begin} → id := E ; {id} SL → S Z {begin,id} Z → S Z {begin,id} → {end} E → T Y {(,id} Y → + T Y {+} → {;,)} T → P X {(,id} X → * T {*} → {;,+,)} P → (E) {(} → id {id} Grammar is LL(1) !

10 summary Problems with model grammar Fixing common prefices
Fixing left-recursion New grammar is LL(1)


Download ppt "Fixing non-ll(1) grammars"

Similar presentations


Ads by Google