Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Parsing

Part II
Writing Grammars

When writing a grammar (or RE) for some language, the


following must be true:
1. All strings generated are in the language.
2. Your grammar produces all strings in the language.

Example:
SÆ (S) S | ε
Generates all strings of balanced parentheses

Using induction show that


Every sentence
E t derivable
d i bl ffrom S iis b balanced
l d
Every balanced string is derivable from S
• L={ anbn | n≥1}

• Show that L can be described by a grammar not by a


regular expression
• Construct a DFA D with k states to accept L
• For anbn (n>k) some state (si) of D must be entered
t i
twice
Path labeled aj-i

S0 … Si … f
Path labeled ai Path labeled ambn
m+j = n
m+i ≠ n
Elimination of Ambiguity

Ambiguous Grammar
• A Grammar is ambiguous
g if there are multiple
p p parse
trees for the same sentence
• For the most parsers, the grammar must be
unambiguous

Unambiguous
U bi grammar
unique selection of the parse tree for a sentence

Disambiguation
• Express Preference for one parse tree over others
– Add disambiguating rule into the grammar
Dangling-else grammar
Dangling-else grammar
Dangling-else grammar
Left Recursion
Immediate Left Recursion Elimination: example

• Grammar
EÆE+T|T
TÆT *F|F
F Æ ( E ) | id

• Left
L ft recursion
i Eliminated
Eli i t d
E Æ T E'
E' | ε
E' Æ + T E
E
T Æ F T'
T' Æ * F T' | ε
F Æ ( E ) | id
Left Recursion in More Than One Step
Left Recursion in More Than One Step
Left Recursion in More Than One Step
Left Recursion in More Than One Step
Left Recursion in More Than One Step
Left Recursion in More Than One Step
Left Recursion in More Than One Step
Left Recursion in More Than One Step

Next Form
Left Recursion in More Than One Step
Algorithm for Eliminating Left Recursion
Left Factoring
Left Factoring

You might also like