Parse Tree
Innernodesofaparsetreearenon-terminalsymbols.
Theleavesofaparsetreeareterminalsymbols.
Aparsetreecanbeseenasagraphicalrepresentationofa
derivation.
E -E
E
E-
-(E)
E
E
E-
( )
-(E+E)
E
E
EE
E
+
-
( )
-(id+E)
E
E
E
EE+
-
( )
id
-(id+id)
E
E
id
E
E
E+
-
( )
id
Ambiguity
Agrammarproducesmorethanoneparsetreefora
sentenceiscalledasanambiguousgrammar.
EE+Eid+Eid+E*E
id+id*Eid+id*id
EE*EE+E*Eid+E*E
id+id*Eid+id*id
E
E+
id
E
E
*
E
id id
E
id
E+
id
id
E
E
*
E
Immediate Left-Recursion
AA| wheredoesnotstartwithA
eliminateimmediateleftrecursion
AA
’
A
’
A
’
| anequivalentgrammar
Ingeneral,
AA
1|...|A
m|
1|...|
n where
1...
ndonot
startwithA
eliminateimmediateleftrecursion
A
1A
’
|...|
nA
’
A
’
1A
’
|...|
mA
’
| an equivalent
grammar
Immediate Left-Recursion --Example
EE+T|T
TT*F|F
Fid|(E)
ETE
’
E
’
+TE
’
|
TFT
’
T
’
*FT
’
|
Fid|(E)
eliminateimmediate left recursion
Left-Recursion --Problem
Agrammarcannotbeimmediatelyleft-recursive,butitstill
canbeleft-recursive.
Byjusteliminatingtheimmediateleft-recursion,wemay
notgetagrammarwhichisnotleft-recursive.
SAa|b
A Sc| dThis grammar is not immediately left-
recursive, but it is still left-recursive.
SAaScaor
AScAac causestoaleft-recursion
So,wehavetoeliminateallleft-recursionsfromour
grammar
Left-Factoring (cont.)
Ingeneral,
A
1|
2 where is non-empty and the first
symbols of
1and
2(if they have one)are different.
whenprocessingwecannotknowwhetherexpand
Ato
1or
Ato
2
But,ifwere-writethegrammarasfollows
AA
’
A’
1|
2 so,wecanimmediatelyexpandA
toA
’
Left-Factoring --Algorithm
Foreachnon-terminalAwithtwoormorealternatives
(productionrules)withacommonnon-emptyprefix,letsay
A
1|...|
n|
1|...|
m
convertitinto
AA
’
|
1|...|
m
A
’
1|...|
n
Left-Factoring –Example1
AabB|aB|cdg|cdeB|cdfB
AaA
’
|cdg|cdeB|cdfB
A
’
bB|B
AaA
’
|cdA
’’
A
’
bB|B
A
’’
g|eB|fB