SlideShare a Scribd company logo
1 of 44
Download to read offline
i A l iSyntactic Analysis
(Top Down Parsing)p g
Dr. P K Singh
Dr. P K Singh TCS 502 Compiler Design slide1
Top-Down Parsing
The parse tree is created top to bottom• The parse tree is created top to bottom.
• Top-down parser
– Recursive-Descent Parsing
• Backtracking is needed (If a choice of a production rule does not work, we
backtrack to try other alternatives.)
• It is a general parsing technique, but not widely used.
• Not efficient
– Predictive Parsing
• no backtracking
• efficient
• needs a special form of grammars (LL(1) grammars).
• Recursive Predictive Parsing is a special form of Recursive Descent parsingg p p g
without backtracking.
• Non-Recursive (Table Driven) Predictive Parser is also known as LL(1)
parser.
TCS 502 Compiler Design 2Dr. P K Singh
Recursive-Descent Parsing (uses Backtracking)
B kt ki i d d• Backtracking is needed.
• It tries to find the left-most derivation.
S → aBc
B → bc | b
S S
fails backtrack
B Ba ac c
Input: abc
fails, backtrack
c bb
TCS 502 Compiler Design 3Dr. P K Singh
Predictive Parser
a grammar a grammar suitable for
eliminate left predictive parsing (a LL(1)
left recursion factor grammar) no %100 guarantee.
• When re-writing a non-terminal in a derivation step, a
predictive parser can uniquely choose a production rule by
just looking the current symbol in the input string.
A → α1 | ... | αn input: ... a .......
current token
Dr. P K Singh TCS 502 Compiler Design slide4
Left Recursion
A i l ft i if it h t i l A h th t• A grammar is left recursive if it has a non-terminal A such that
there is a derivation.
A A f t iA ⇒ Aα for some string α
• Top-down parsing techniques cannot handle left-recursive
+
• Top-down parsing techniques cannot handle left-recursive
grammars.
• So, we have to convert our left-recursive grammar into an equivalent
hi h i t l ft igrammar which is not left-recursive.
• The left-recursion may appear in a single step of the derivation
(immediate left-recursion), or may appear in more than one step of
the derivation.
Dr. P K Singh TCS 502 Compiler Design slide5
Immediate Left-Recursion
A → A α | β where β does not start with A
⇓ eliminate immediate left recursion
A → β A’A → β A
A’ → α A’ | ε an equivalent grammar
A → A α1 | ... | A αm | β1 | ... | βn where β1 ... βn do not start with A
⇓
In general,
⇓ eliminate immediate left recursion
A → β1 A’ | ... | βn A’
A’ → α1 A’ | ... | αm A’ | ε an equivalent grammar1 | | m | q g
Dr. P K Singh TCS 502 Compiler Design slide6
Immediate Left-Recursion -- Example
E → E+T | T
T → T*F | F
F id | (E)F → id | (E)
⇓ eliminate immediate left recursion
E → T E’
E’ → +T E’ | ε|
T → F T’
T’ → *F T’ | ε
F → id | (E)
Dr. P K Singh TCS 502 Compiler Design slide7
Left-Recursion -- Problem
• A grammar cannot be immediately left-recursive, but it still can
be left-recursive.
• By just eliminating the immediate left-recursion, we may notBy just eliminating the immediate left recursion, we may not
get a grammar which is not left-recursive.
S → Aa | b
A → Sc | d This grammar is not immediately left-recursive,
but it is still left-recursive.
S ⇒ Aa ⇒ Sca or
A ⇒ Sc ⇒ Aac causes to a left-recursion
• So, we have to eliminate all left-recursions from our grammar
Dr. P K Singh TCS 502 Compiler Design slide8
Eliminate Left-Recursion -- Algorithm
A t i l i d A A- Arrange non-terminals in some order: A1 ... An
- for i from 1 to n do {
for j from 1 to i 1 do {- for j from 1 to i-1 do {
replace each production
Ai → Aj γAi → Aj γ
by
Ai → α1 γ | ... | αk γi 1 γ | | k γ
where Aj → α1 | ... | αk
}
- eliminate immediate left-recursions among Ai productions
}
Dr. P K Singh TCS 502 Compiler Design slide9
Eliminate Left-Recursion -- Example
S → Aa | bS → Aa | b
A → Ac | Sd | f
- Order of non-terminals: S, A
for S:
- we do not enter the inner loop.
- there is no immediate left recursion in S.
for A:
- Replace A → Sd with A → Aad | bd
So, we will have A → Ac | Aad | bd | fSo, we will have A → Ac | Aad | bd | f
- Eliminate the immediate left-recursion in A
A → bdA’ | fA’
A’ → cA’ | adA’ | ε
So, the resulting equivalent grammar which is not left-recursive is:
S → Aa | b
A → bdA’ | fA’
Dr. P K Singh TCS 502 Compiler Design slide10
A’ → cA’ | adA’ | ε
Eliminate Left-Recursion – Example2
S → Aa | bS → Aa | b
A → Ac | Sd | f
- Order of non-terminals: A, S
for A:
- we do not enter the inner loop.
- Eliminate the immediate left-recursion in A
A → SdA’ | fA’|
A’ → cA’ | ε
for S:
- Replace S → Aa with S → SdA’a | fA’a
So, we will have S → SdA’a | fA’a | b
- Eliminate the immediate left-recursion in S
S → fA’aS’ | bS’
S’ → dA’aS’ | ε
So, the resulting equivalent grammar which is not left-recursive is:
S → fA’aS’ | bS’
S’ → dA’aS’ | ε
A → SdA’ | fA’
A’ cA’ |
Dr. P K Singh TCS 502 Compiler Design slide11
A → cA | ε
Left-Factoring
• A predictive parser (a top-down parser without backtracking) insists
that the grammar must be left-factored.
stmt → if expr then stmt else stmt |
i t tif expr then stmt
• when we see if we cannot now which production rule to choose to• when we see if, we cannot now which production rule to choose to
re-write stmt in the derivation.
Dr. P K Singh TCS 502 Compiler Design slide12
Left Factoring
R iti d ti t d l d i i• Rewriting productions to delay decisions
• Helpful for predictive parsing
• Not guaranteed to remove ambiguity
A αβ1 | αβ2
A αA’
A’ β | βA’ β1 | β2
Dr. P K Singh TCS 502 Compiler Design slide13
Algorithm: Left Factoring
Dr. P K Singh TCS 502 Compiler Design slide14
Left-Factoring – Example1
A bB | B | d | d B | dfBA → abB | aB | cdg | cdeB | cdfB
⇓
A → aA’ | cdg | cdeB | cdfB
A’ bB | BA → bB | B
⇓
A → aA’ | cdA’’
A’ → bB | BA → bB | B
A’’ → g | eB | fB
Dr. P K Singh TCS 502 Compiler Design slide15
Left-Factoring – Example2
A d | | b | b | bA → ad | a | ab | abc | b
⇓
A → aA’ | b
A’ d | | b | bA’ → d | ε | b | bc
⇓
A → aA’ | b
A’ → d | ε | bA’’A → d | ε | bA
A’’ → ε | c
Dr. P K Singh TCS 502 Compiler Design slide16
Top Down Parsing
C b i d t• Can be viewed two ways:
– Attempt to find leftmost derivation for input string
Att t t t t t ti f t t ti d– Attempt to create parse tree, starting from at root, creating nodes
in preorder
• General form is recursive descent parsingGeneral form is recursive descent parsing
– May require backtracking
– Backtracking parsers not used frequently because not neededg p q y
Dr. P K Singh TCS 502 Compiler Design slide17
Predictive Parsing
A i l f i d t i th t d• A special case of recursive-descent parsing that does
not require backtracking
• Must always know which production to use based on• Must always know which production to use based on
current input symbol
• Can often create appropriate grammar:• Can often create appropriate grammar:
– removing left-recursion
– left factoring the resulting grammarleft factoring the resulting grammar
Dr. P K Singh TCS 502 Compiler Design slide18
Predictive Parser (example)
t t if |stmt → if ...... |
while ...... |
begin |begin ...... |
for .....
• When we are trying to write the non-terminal stmt, if the current
token is if we have to choose first production rule.
• When we are trying to write the non-terminal stmt, we can uniquely
choose the production rule by just looking the current token.
• We eliminate the left recursion in the grammar and left factor it ButWe eliminate the left recursion in the grammar, and left factor it. But
it may not be suitable for predictive parsing (not LL(1) grammar).
TCS 502 Compiler Design 19Dr. P K Singh
Recursive Predictive Parsing
E h t i l d t d• Each non-terminal corresponds to a procedure.
Ex: A → aBb (This is only the production rule for A)
proc A {
- match the current token with a, and move to the next token;
- call ‘B’;
- match the current token with b, and move to the next token;
}
TCS 502 Compiler Design 20Dr. P K Singh
Recursive Predictive Parsing (cont.)
A → aBb | bABA → aBb | bAB
proc A {p {
case of the current token {
‘a’: - match the current token with a, and move to the next token;
ll ‘B’- call ‘B’;
- match the current token with b, and move to the next token;
‘b’: - match the current token with b, and move to the next token;
- call ‘A’;
- call ‘B’;
}}
}
TCS 502 Compiler Design 21Dr. P K Singh
Recursive Predictive Parsing (cont.)
Wh t l d ti• When to apply ε-productions.
A → aA | bB | εA → aA | bB | ε
• If all other productions fail, we should apply an ε-production. ForIf all other productions fail, we should apply an ε production. For
example, if the current token is not a or b, we may apply the
ε-production.
• Most correct choice: We should apply an ε production for a non• Most correct choice: We should apply an ε-production for a non-
terminal A when the current token is in the follow set of A (which
terminals can follow A in the sentential forms).
TCS 502 Compiler Design 22Dr. P K Singh
Transition Diagrams
F• For parser:
– One diagram for each nonterminal
– Edge labels can be tokens or nonterminal
• A transition on a token means we should take that transition
if token is next input symbol
• A transition on a nonterminal can be thought of as a call to a
procedure for that nonterminalp
• As opposed to lexical analyzers:
O ( ) di f h t k– One (or more) diagrams for each token
– Labels are symbols of input alphabet
Dr. P K Singh TCS 502 Compiler Design slide23
Creating Transition Diagrams
Fi li i l f i f• First eliminate left recursion from grammar
• Then left factor grammar
• For each nonterminal A:
Create an initial and final state– Create an initial and final state
– For every production A X1X2…Xn, create a path
from initial to final state with edges labeled X Xfrom initial to final state with edges labeled X1, X2, …,
Xn.
Dr. P K Singh TCS 502 Compiler Design slide24
Using Transition Diagrams
• Predictive parsers:• Predictive parsers:
– Start at start symbol of grammar
– From state s with edge to state t labeled with token a, if nextg ,
input token is a:
• State changes to t
• Input cursor moves one position rightp p g
– If edge labeled by nonterminal A:
• State changes to start state for A
• Input cursor is not moved• Input cursor is not moved
• If final state of A reached, then state changes to t
– If edge labeled by ε, state changes to t
• Can be recursive or non-recursive using stack
Dr. P K Singh TCS 502 Compiler Design slide25
Transition Diagram Example
E E + T | T
T T * F | F
E TE’
E’ +TE’ | ε
T FT’T T * F | F
F (E) | id
T FT
T’ *FT’ | ε
F (E) | id
0 1
T
2
E’
10 11
*
13
ε
12
F T’
E: T’:
3 4
+
6
ε
5
T E’
ε
E’:
ε
7 8
F
9
T’
14 15
(
17
id
16
E )
F:T:
Dr. P K Singh TCS 502 Compiler Design slide26
id
Simplifying Transition Diagrams
3 4
+
6
ε
5
T E’
E’:
0 1
T
2
E’
E:
3 4
+
ε
5
T
0 1
T
2
E’
0 3
T
4
+
6
0 3
T
4
+
ε
T
ε
+
6
3 4
+
ε
T
0 3
T
+
6
ε
Dr. P K Singh TCS 502 Compiler Design slide276
Simplified Transition Diagrams
Dr. P K Singh TCS 502 Compiler Design slide28
Recursive Predictive Parsing (Example)
A → aBe | cBd | CA → aBe | cBd | C
B → bB | ε
C → f proc C { match the current token with f,
proc A { and move to the next token; }
case of the current token {
a: - match the current token with a,
{and move to the next token; proc B {
- call B; case of the current token {
- match the current token with e, b:- match the current token with b,
and move to the next token; and move to the next token;and move to the next token; and move to the next token;
c: - match the current token with c, - call B
and move to the next token; e,d: do nothing
- call B; }
- match the current token with d, }
and move to the next token;
f: - call C follow set of B
Dr. P K Singh TCS 502 Compiler Design slide29
}
} first set of C
Nonrecursive Predictive Parsing (1)
a + b $Input
XStack
Predictive Parsing
Program
Output
X
Y
Z
$
Stac
$
Parsing Table
M
Dr. P K Singh TCS 502 Compiler Design slide30
Nonrecursive Predictive Parsing (2)
• The symbol at the top of the stack (say X) and the current symbol in the input string
(say a) determine the parser action.
• There are four possible parser actions.
1. If X and a are $ parser halts (successful completion)
2. If X and a are the same terminal symbol (different from $)
parser pops X from the stack and moves the next symbol in the input bufferparser pops X from the stack, and moves the next symbol in the input buffer.
3. If X is a non-terminal
parser looks at the parsing table entry M[X,a]. If M[X,a] holds a production rule
X→Y Y Y it pops X from the stack and pushes Y Y Y into the stack TheX→Y1Y2...Yk, it pops X from the stack and pushes Yk,Yk-1,...,Y1 into the stack. The
parser also outputs the production rule X→Y1Y2...Yk to represent a step of the
derivation.
4. none of the above error4. none of the above error
– all empty entries in the parsing table are errors.
– If X is a terminal symbol different from a, this is also an error case.
Dr. P K Singh TCS 502 Compiler Design slide31
Predictive Parsing Table
Nonter-
minal
Input Symbol
id + * ( ) $id + ( ) $
E E TE’ E TE’
E’ E’ +TE’ E’ ε E’ ε
T T FT’ T FT’
T’ T’ ε T’ *FT’ T’ ε T’ ε
F F id F (E)
Dr. P K Singh TCS 502 Compiler Design slide32
Using a Predictive Parsing Table
Stack Input Output
$E id+id*id$
Stack Input Output
… … …
$E’T id+id*id$ E TE’
$E’T’F id+id*id$ T FT’
$E’T’id id*id$ F id
$E’T’ *id$
$E’T’id id+id*id$ F id
$E’T’ +id*id$
$E’T’F* *id$ T’ *FT’
$E’T’F id$
$E’ +id*id$ T’ ε
$E’T+ +id*id$ E’ +TE’
$E’T’id id$ F id
$E’T’ $
$E’T id*id$
$E’T’F id*id$ T FT’
$E’ $ T’ ε
$ $ E’ ε
Dr. P K Singh TCS 502 Compiler Design slide33
FIRST
( ) i th t f ll t i l th t b i• FIRST(α) is the set of all terminals that begin any
string derived from α
• Computing FIRST:• Computing FIRST:
– If X is a terminal, FIRST(X) = {X}
If X ε is a production add ε to FIRST(X)– If X ε is a production, add ε to FIRST(X)
– If X is a nonterminal and X Y1Y2…Yn is a production:
• For all terminals a, add a to FIRST(X) if a is a member of any, ( ) y
FIRST(Yi) and ε is a member of FIRST(Y1), FIRST(Y2), …
FIRST(Yi-1)
• If ε is a member of FIRST(Y1), FIRST(Y2), … FIRST(Yn), add ε to( 1), ( 2), ( n),
FIRST(X)
Dr. P K Singh TCS 502 Compiler Design slide34
FOLLOW
• FOLLOW(A), for any nonterminal A, is the set of terminals a that can
appear immediately to the right if A in some sentential form
• More formally a is in FOLLOW(A) if and only if there exists aMore formally, a is in FOLLOW(A) if and only if there exists a
derivation of the form S *=>αAaβ
• $ is in FOLLOW(A) if and only if there exists a derivation of the form
S * > αAS => αA
Computing FOLLOW
Pl $ i• Place $ in FOLLOW(S)
• If there is a production A αBβ, then everything in FIRST(β)
(except for ε) is in FOLLOW(B)( p )
• If there is a production A αB, or a production A αBβ where
FIRST(β) contains ε,then everything in FOLLOW(A) is also in
FOLLOW(B)
Dr. P K Singh TCS 502 Compiler Design slide35
FOLLOW(B)
FIRST and FOLLOW Example
E TE’
E’ +TE’| ε
T FT’T FT’
T’ *FT’| ε
F (E) | id
FIRST(E) = FIRST(T) = FIRST(F) = {(, id}
FIRST(E’) {+ ε}FIRST(E’) = {+, ε}
FIRST(T’) = {*, ε}
FOLLOW(E) = FOLLOW(E’) = {), $}
FOLLOW(T) = FOLLOW(T’) = {+, ), $}
FOLLOW(F) = {+, *, $}
Dr. P K Singh TCS 502 Compiler Design slide36
Creating a Predictive Parsing Table
F h d ti• For each production A α :
– For each terminal a in FIRST(α) add A α to
M[A, a]
– If ε is in FIRST(α) add A α to M[A, b] for
every terminal b in FOLLOW(A)every terminal b in FOLLOW(A)
– If ε is in FIRST(α) and $ is in FOLLOW(A) add A
α to M[A $]α to M[A, $]
• Mark each undefined entry of M as an error
entry (use some recovery strategy)entry (use some recovery strategy)
Dr. P K Singh TCS 502 Compiler Design slide37
Example
E → TE’
E’ → +TE’ | ε|
T → FT’
T’ → *FT’ | ε
F (E) | idF → (E) | id
Dr. P K Singh TCS 502 Compiler Design slide38
Constructing LL(1) Parsing Table -- Example
’ ’ ’E → TE’ FIRST(TE’)={(,id} E → TE’ into M[E,(] and M[E,id]
E’ → +TE’ FIRST(+TE’ )={+} E’ → +TE’ into M[E’,+]
E’ → ε FIRST(ε)={ε} none
but since ε in FIRST(ε)
and FOLLOW(E’)={$,)} E’ → ε into M[E’,$] and M[E’,)]
T → FT’ FIRST(FT’)={(,id} T → FT’ into M[T,(] and M[T,id]
T’ → *FT’ FIRST(*FT’ )={*} T’ → *FT’ into M[T’,*]
T’ → ε FIRST(ε)={ε} none
but since ε in FIRST(ε)
and FOLLOW(T’)={$,),+} T’ → ε into M[T’,$], M[T’,)] and M[T’,+]
F → (E) FIRST((E) )={(} F → (E) into M[F,(]
F → id FIRST(id)={id} F → id into M[F,id]
TCS 502 Compiler Design 39Dr. P K Singh
LL(1) Grammars
A h i t bl h lti l d fi d• A grammar whose parsing table has no multiply-defined
entries is said to be LL(1) grammar.
one input symbol used as a look-head symbol do determine
parser action
LL(1) left most derivation
input scanned from left to rightp g
• The parsing table of a grammar may contain more than
one production rule. In this case, we say that it is not a
LL(1) grammar.
TCS 502 Compiler Design 40Dr. P K Singh
A Grammar which is not LL(1)
S i C t S E | FOLLOW(S) { $ }S → i C t S E | a FOLLOW(S) = { $,e }
E → e S | ε FOLLOW(E) = { $,e }
C b FOLLOW(C) { t }C → b FOLLOW(C) = { t }
FIRST(iCtSE) = {i}
FIRST(a) = {a}
a b e i t $
S S → a S →
iCtSE
FIRST(eS) = {e}
FIRST(ε) = {ε}
iCtSE
E E → e S
E → ε
E →
ε
FIRST(b) = {b}
C C → b
TCS 502 Compiler Design 41
two production rules for M[E,e]
Dr. P K Singh
A Grammar which is not LL(1) (cont.)
What do we have to do it if the resulting parsing table contains multiply defined• What do we have to do it if the resulting parsing table contains multiply defined
entries?
– If we didn’t eliminate left recursion, eliminate the left recursion in the grammar.
– If the grammar is not left factored we have to left factor the grammarIf the grammar is not left factored, we have to left factor the grammar.
– If its (new grammar’s) parsing table still contains multiply defined entries, that grammar is
ambiguous or it is inherently not a LL(1) grammar.
• A left recursive grammar cannot be a LL(1) grammar.
– A → Aα | β
any terminal that appears in FIRST(β) also appears FIRST(Aα) because Aα ⇒
βα.
i l h i FIRST( ) l i FIRST(A ) dIf β is ε, any terminal that appears in FIRST(α) also appears in FIRST(Aα) and
FOLLOW(A).
• A grammar is not left factored, it cannot be a LL(1) grammar
A β | β• A → αβ1 | αβ2
any terminal that appears in FIRST(αβ1) also appears in FIRST(αβ2).
• An ambiguous grammar cannot be a LL(1) grammar.
TCS 502 Compiler Design 42
g g ( ) g
Dr. P K Singh
Properties of LL(1) Grammars
A G i LL(1) if d l if th f ll i diti h ld f• A grammar G is LL(1) if and only if the following conditions hold for
two distinctive production rules A → α and A → β
1. Both α and β cannot derive strings starting with same terminals.
2. At most one of α and β can derive to ε.
3. If β can derive to ε, then α cannot derive to any string starting
ith t i l i FOLLOW(A)with a terminal in FOLLOW(A).
• A Grammar to be LL(1), following conditions must satisfied:
For every pair of productions A α І β
{
FIRST(α) ∩ FIRST(β) = Φ( ) (β)
and if FIRST(β) contains ε then
FIRST(α) ∩ FOLLOW(A) = Φ
}
TCS 502 Compiler Design 43
}
Dr. P K Singh
Example
T t th F ll i G i LL(1) t ?• Test the Following Grammar is LL(1) or not ?
S 1AB | ε
A 1AC | 0CA 1AC | 0C
B 0S
C 1C 1
For Production S 1AB | ε
FIRST(1AB) ∩ FIRST(ε) = {1} ∩ {ε} = Φ and( ) ( ) { } { }
FIRST(1AB) ∩ FOLLOW(S) = {1} ∩ {$} = Φ
Similarly A 1AC | 0C
FIRST(1AC) ∩ FIRST(0C) = {1} ∩ {0} = Φ
Hence The Grammar is LL(1)
Dr. P K Singh TCS 502 Compiler Design slide44

More Related Content

What's hot

Asymptotic Notations.pptx
Asymptotic Notations.pptxAsymptotic Notations.pptx
Asymptotic Notations.pptxSunilWork1
 
Error detection recovery
Error detection recoveryError detection recovery
Error detection recoveryTech_MX
 
Longest Common Subsequence (LCS) Algorithm
Longest Common Subsequence (LCS) AlgorithmLongest Common Subsequence (LCS) Algorithm
Longest Common Subsequence (LCS) AlgorithmDarshit Metaliya
 
Principle source of optimazation
Principle source of optimazationPrinciple source of optimazation
Principle source of optimazationSiva Sathya
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting classgiridaroori
 
Heuristic Search Techniques {Artificial Intelligence}
Heuristic Search Techniques {Artificial Intelligence}Heuristic Search Techniques {Artificial Intelligence}
Heuristic Search Techniques {Artificial Intelligence}FellowBuddy.com
 
Dynamic storage allocation techniques
Dynamic storage allocation techniquesDynamic storage allocation techniques
Dynamic storage allocation techniquesShashwat Shriparv
 
Error Detection & Recovery
Error Detection & RecoveryError Detection & Recovery
Error Detection & RecoveryAkhil Kaushik
 
Uninformed search /Blind search in AI
Uninformed search /Blind search in AIUninformed search /Blind search in AI
Uninformed search /Blind search in AIKirti Verma
 
Algorithms Design Patterns
Algorithms Design PatternsAlgorithms Design Patterns
Algorithms Design PatternsAshwin Shiv
 
Heuristic Search Techniques Unit -II.ppt
Heuristic Search Techniques Unit -II.pptHeuristic Search Techniques Unit -II.ppt
Heuristic Search Techniques Unit -II.pptkarthikaparthasarath
 
Artificial Intelligence Notes Unit 2
Artificial Intelligence Notes Unit 2Artificial Intelligence Notes Unit 2
Artificial Intelligence Notes Unit 2DigiGurukul
 
Three address code In Compiler Design
Three address code In Compiler DesignThree address code In Compiler Design
Three address code In Compiler DesignShine Raj
 
Intermediate code generation
Intermediate code generationIntermediate code generation
Intermediate code generationAkshaya Arunan
 
A presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmA presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmGaurav Kolekar
 

What's hot (20)

Asymptotic Notations.pptx
Asymptotic Notations.pptxAsymptotic Notations.pptx
Asymptotic Notations.pptx
 
Error detection recovery
Error detection recoveryError detection recovery
Error detection recovery
 
Longest Common Subsequence (LCS) Algorithm
Longest Common Subsequence (LCS) AlgorithmLongest Common Subsequence (LCS) Algorithm
Longest Common Subsequence (LCS) Algorithm
 
Principle source of optimazation
Principle source of optimazationPrinciple source of optimazation
Principle source of optimazation
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
 
Loops in flow
Loops in flowLoops in flow
Loops in flow
 
Heuristic Search Techniques {Artificial Intelligence}
Heuristic Search Techniques {Artificial Intelligence}Heuristic Search Techniques {Artificial Intelligence}
Heuristic Search Techniques {Artificial Intelligence}
 
Dynamic storage allocation techniques
Dynamic storage allocation techniquesDynamic storage allocation techniques
Dynamic storage allocation techniques
 
Debugging
DebuggingDebugging
Debugging
 
Error Detection & Recovery
Error Detection & RecoveryError Detection & Recovery
Error Detection & Recovery
 
Yacc
YaccYacc
Yacc
 
Intermediate code
Intermediate codeIntermediate code
Intermediate code
 
Uninformed search /Blind search in AI
Uninformed search /Blind search in AIUninformed search /Blind search in AI
Uninformed search /Blind search in AI
 
Algorithms Design Patterns
Algorithms Design PatternsAlgorithms Design Patterns
Algorithms Design Patterns
 
Heuristic Search Techniques Unit -II.ppt
Heuristic Search Techniques Unit -II.pptHeuristic Search Techniques Unit -II.ppt
Heuristic Search Techniques Unit -II.ppt
 
Artificial Intelligence Notes Unit 2
Artificial Intelligence Notes Unit 2Artificial Intelligence Notes Unit 2
Artificial Intelligence Notes Unit 2
 
Three address code In Compiler Design
Three address code In Compiler DesignThree address code In Compiler Design
Three address code In Compiler Design
 
Heap Management
Heap ManagementHeap Management
Heap Management
 
Intermediate code generation
Intermediate code generationIntermediate code generation
Intermediate code generation
 
A presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmA presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithm
 

Viewers also liked

Travelling and working abroad - Ielts topic -Jen
Travelling and working abroad - Ielts topic -JenTravelling and working abroad - Ielts topic -Jen
Travelling and working abroad - Ielts topic -JenJen Vuhuong
 
Țintirea inflației (aug 2012) - Raport trimestrial asupra inflației
Țintirea inflației (aug 2012) - Raport trimestrial asupra inflațieiȚintirea inflației (aug 2012) - Raport trimestrial asupra inflației
Țintirea inflației (aug 2012) - Raport trimestrial asupra inflațieiBanca Națională a României
 
Jason Tomas by Ryan
Jason Tomas by RyanJason Tomas by Ryan
Jason Tomas by RyanJolinspeeps
 
Producao sustentavelpecuarialeiteira
Producao sustentavelpecuarialeiteiraProducao sustentavelpecuarialeiteira
Producao sustentavelpecuarialeiteiraLiliane Almeida
 
Research, social media and getting published
Research, social media and getting publishedResearch, social media and getting published
Research, social media and getting publishedLeah Emary
 
Why do you want to study international management
Why do you want to study international managementWhy do you want to study international management
Why do you want to study international managementJen Vuhuong
 
ASSEMBLEA GENERALE ANDIL 2014
ASSEMBLEA GENERALE ANDIL 2014ASSEMBLEA GENERALE ANDIL 2014
ASSEMBLEA GENERALE ANDIL 2014ANDIL_laterizi
 
SQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload AnalysisSQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload AnalysisGianluca Sartori
 
Serendipity for SharePoint: The Power of Automated Metadata Tagging
Serendipity for SharePoint: The Power of Automated Metadata TaggingSerendipity for SharePoint: The Power of Automated Metadata Tagging
Serendipity for SharePoint: The Power of Automated Metadata TaggingFirestring
 
Wilson chemicals ltd
Wilson chemicals ltdWilson chemicals ltd
Wilson chemicals ltdCamilh
 

Viewers also liked (14)

Travelling and working abroad - Ielts topic -Jen
Travelling and working abroad - Ielts topic -JenTravelling and working abroad - Ielts topic -Jen
Travelling and working abroad - Ielts topic -Jen
 
Țintirea inflației (aug 2012) - Raport trimestrial asupra inflației
Țintirea inflației (aug 2012) - Raport trimestrial asupra inflațieiȚintirea inflației (aug 2012) - Raport trimestrial asupra inflației
Țintirea inflației (aug 2012) - Raport trimestrial asupra inflației
 
Doc1
Doc1Doc1
Doc1
 
sample
samplesample
sample
 
Jason Tomas by Ryan
Jason Tomas by RyanJason Tomas by Ryan
Jason Tomas by Ryan
 
Producao sustentavelpecuarialeiteira
Producao sustentavelpecuarialeiteiraProducao sustentavelpecuarialeiteira
Producao sustentavelpecuarialeiteira
 
The pencil 184
The pencil 184The pencil 184
The pencil 184
 
Research, social media and getting published
Research, social media and getting publishedResearch, social media and getting published
Research, social media and getting published
 
Why do you want to study international management
Why do you want to study international managementWhy do you want to study international management
Why do you want to study international management
 
Londres cris jas
Londres cris jasLondres cris jas
Londres cris jas
 
ASSEMBLEA GENERALE ANDIL 2014
ASSEMBLEA GENERALE ANDIL 2014ASSEMBLEA GENERALE ANDIL 2014
ASSEMBLEA GENERALE ANDIL 2014
 
SQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload AnalysisSQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload Analysis
 
Serendipity for SharePoint: The Power of Automated Metadata Tagging
Serendipity for SharePoint: The Power of Automated Metadata TaggingSerendipity for SharePoint: The Power of Automated Metadata Tagging
Serendipity for SharePoint: The Power of Automated Metadata Tagging
 
Wilson chemicals ltd
Wilson chemicals ltdWilson chemicals ltd
Wilson chemicals ltd
 

Similar to Topdown parsing

Similar to Topdown parsing (20)

Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2
 
Compiler unit 2&3
Compiler unit 2&3Compiler unit 2&3
Compiler unit 2&3
 
Syntactic analysis in NLP
Syntactic analysis in NLPSyntactic analysis in NLP
Syntactic analysis in NLP
 
PARSING.ppt
PARSING.pptPARSING.ppt
PARSING.ppt
 
Natural Language Processing - Writing Grammar
Natural Language Processing - Writing GrammarNatural Language Processing - Writing Grammar
Natural Language Processing - Writing Grammar
 
Lecture 3 RE NFA DFA
Lecture 3   RE NFA DFA Lecture 3   RE NFA DFA
Lecture 3 RE NFA DFA
 
Lecture9 syntax analysis_5
Lecture9 syntax analysis_5Lecture9 syntax analysis_5
Lecture9 syntax analysis_5
 
Lexical 2
Lexical 2Lexical 2
Lexical 2
 
Lecture 07 08 syntax analysis-4
Lecture 07 08 syntax analysis-4Lecture 07 08 syntax analysis-4
Lecture 07 08 syntax analysis-4
 
3. Syntax Analyzer.pptx
3. Syntax Analyzer.pptx3. Syntax Analyzer.pptx
3. Syntax Analyzer.pptx
 
Ch06
Ch06Ch06
Ch06
 
Theory of competition topic simplification of cfg, normal form of FG.pptx
Theory of competition topic simplification of cfg, normal form of FG.pptxTheory of competition topic simplification of cfg, normal form of FG.pptx
Theory of competition topic simplification of cfg, normal form of FG.pptx
 
CLaSH HIW 2014
CLaSH HIW 2014CLaSH HIW 2014
CLaSH HIW 2014
 
Ch5b.pdf
Ch5b.pdfCh5b.pdf
Ch5b.pdf
 
Cd2 [autosaved]
Cd2 [autosaved]Cd2 [autosaved]
Cd2 [autosaved]
 
Context free grammar
Context free grammarContext free grammar
Context free grammar
 
Chapter02b
Chapter02bChapter02b
Chapter02b
 
CS540-2-lecture11 - Copy.ppt
CS540-2-lecture11 - Copy.pptCS540-2-lecture11 - Copy.ppt
CS540-2-lecture11 - Copy.ppt
 
Code Optimization.ppt
Code Optimization.pptCode Optimization.ppt
Code Optimization.ppt
 
Optimization
OptimizationOptimization
Optimization
 

More from Royalzig Luxury Furniture

A Glimpse of Beautiful Hand-Carved Luxury Italian Furniture Photos from Royal...
A Glimpse of Beautiful Hand-Carved Luxury Italian Furniture Photos from Royal...A Glimpse of Beautiful Hand-Carved Luxury Italian Furniture Photos from Royal...
A Glimpse of Beautiful Hand-Carved Luxury Italian Furniture Photos from Royal...Royalzig Luxury Furniture
 
India's Luxury Furniture Brand Royalzig setting-Up a New Production Unit
India's Luxury Furniture Brand Royalzig setting-Up a New Production UnitIndia's Luxury Furniture Brand Royalzig setting-Up a New Production Unit
India's Luxury Furniture Brand Royalzig setting-Up a New Production UnitRoyalzig Luxury Furniture
 
Hand Carved Luxury & Designer Wooden arm chair
Hand Carved Luxury & Designer Wooden arm chairHand Carved Luxury & Designer Wooden arm chair
Hand Carved Luxury & Designer Wooden arm chairRoyalzig Luxury Furniture
 
Hand Carved Luxury & Designer Wooden Dining Table
Hand Carved Luxury & Designer Wooden Dining Table Hand Carved Luxury & Designer Wooden Dining Table
Hand Carved Luxury & Designer Wooden Dining Table Royalzig Luxury Furniture
 
Hand Carved Luxury & Designer Wooden sofa set
Hand Carved Luxury & Designer Wooden sofa setHand Carved Luxury & Designer Wooden sofa set
Hand Carved Luxury & Designer Wooden sofa setRoyalzig Luxury Furniture
 
Royalzig Hand Carved Luxury & Designer Wood Bed
Royalzig Hand Carved Luxury & Designer Wood BedRoyalzig Hand Carved Luxury & Designer Wood Bed
Royalzig Hand Carved Luxury & Designer Wood BedRoyalzig Luxury Furniture
 

More from Royalzig Luxury Furniture (20)

A Glimpse of Beautiful Hand-Carved Luxury Italian Furniture Photos from Royal...
A Glimpse of Beautiful Hand-Carved Luxury Italian Furniture Photos from Royal...A Glimpse of Beautiful Hand-Carved Luxury Italian Furniture Photos from Royal...
A Glimpse of Beautiful Hand-Carved Luxury Italian Furniture Photos from Royal...
 
French Style Slim Carving Bedroom Sets
French Style Slim Carving Bedroom SetsFrench Style Slim Carving Bedroom Sets
French Style Slim Carving Bedroom Sets
 
India's Luxury Furniture Brand Royalzig setting-Up a New Production Unit
India's Luxury Furniture Brand Royalzig setting-Up a New Production UnitIndia's Luxury Furniture Brand Royalzig setting-Up a New Production Unit
India's Luxury Furniture Brand Royalzig setting-Up a New Production Unit
 
Luxury furniture manufacturer in india
Luxury furniture manufacturer in indiaLuxury furniture manufacturer in india
Luxury furniture manufacturer in india
 
bone inlay hand carved luxury table
bone inlay hand carved luxury table bone inlay hand carved luxury table
bone inlay hand carved luxury table
 
Hand Carved Luxury & Designer Wooden arm chair
Hand Carved Luxury & Designer Wooden arm chairHand Carved Luxury & Designer Wooden arm chair
Hand Carved Luxury & Designer Wooden arm chair
 
beautiful hand carved dressing table
beautiful hand carved dressing table  beautiful hand carved dressing table
beautiful hand carved dressing table
 
Hand Carved Luxury & Designer Wooden Dining Table
Hand Carved Luxury & Designer Wooden Dining Table Hand Carved Luxury & Designer Wooden Dining Table
Hand Carved Luxury & Designer Wooden Dining Table
 
Hand Carved Luxury & Designer Wooden sofa set
Hand Carved Luxury & Designer Wooden sofa setHand Carved Luxury & Designer Wooden sofa set
Hand Carved Luxury & Designer Wooden sofa set
 
Royalzig Hand Carved Luxury & Designer Wood Bed
Royalzig Hand Carved Luxury & Designer Wood BedRoyalzig Hand Carved Luxury & Designer Wood Bed
Royalzig Hand Carved Luxury & Designer Wood Bed
 
hand carved luxury wedding throne
hand carved luxury wedding thronehand carved luxury wedding throne
hand carved luxury wedding throne
 
Hand carved Luxury wood divan
Hand carved Luxury wood divanHand carved Luxury wood divan
Hand carved Luxury wood divan
 
Royalzig luxury furniture
Royalzig luxury furnitureRoyalzig luxury furniture
Royalzig luxury furniture
 
Royalzigppt 004
Royalzigppt 004Royalzigppt 004
Royalzigppt 004
 
Royalzig high end furniture
Royalzig high end furnitureRoyalzig high end furniture
Royalzig high end furniture
 
Royalzigppt 002
Royalzigppt 002Royalzigppt 002
Royalzigppt 002
 
Transcript
TranscriptTranscript
Transcript
 
Syntaxdirected
SyntaxdirectedSyntaxdirected
Syntaxdirected
 
Run time
Run timeRun time
Run time
 
Perceptual rules
Perceptual rulesPerceptual rules
Perceptual rules
 

Recently uploaded

Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.EnglishCEIPdeSigeiro
 
General views of Histopathology and step
General views of Histopathology and stepGeneral views of Histopathology and step
General views of Histopathology and stepobaje godwin sunday
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxDr. Santhosh Kumar. N
 
Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxraviapr7
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxKatherine Villaluna
 
5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...CaraSkikne1
 
How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17Celine George
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17Celine George
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxMYDA ANGELICA SUAN
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17Celine George
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxheathfieldcps1
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesCeline George
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17Celine George
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxKatherine Villaluna
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice documentXsasf Sfdfasd
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxDr. Asif Anas
 
What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?TechSoup
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapitolTechU
 
The Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsThe Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsEugene Lysak
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...raviapr7
 

Recently uploaded (20)

Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.
 
General views of Histopathology and step
General views of Histopathology and stepGeneral views of Histopathology and step
General views of Histopathology and step
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptx
 
Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptx
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
 
5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...
 
How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptx
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 Sales
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptx
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice document
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptx
 
What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptx
 
The Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsThe Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George Wells
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...
 

Topdown parsing

  • 1. i A l iSyntactic Analysis (Top Down Parsing)p g Dr. P K Singh Dr. P K Singh TCS 502 Compiler Design slide1
  • 2. Top-Down Parsing The parse tree is created top to bottom• The parse tree is created top to bottom. • Top-down parser – Recursive-Descent Parsing • Backtracking is needed (If a choice of a production rule does not work, we backtrack to try other alternatives.) • It is a general parsing technique, but not widely used. • Not efficient – Predictive Parsing • no backtracking • efficient • needs a special form of grammars (LL(1) grammars). • Recursive Predictive Parsing is a special form of Recursive Descent parsingg p p g without backtracking. • Non-Recursive (Table Driven) Predictive Parser is also known as LL(1) parser. TCS 502 Compiler Design 2Dr. P K Singh
  • 3. Recursive-Descent Parsing (uses Backtracking) B kt ki i d d• Backtracking is needed. • It tries to find the left-most derivation. S → aBc B → bc | b S S fails backtrack B Ba ac c Input: abc fails, backtrack c bb TCS 502 Compiler Design 3Dr. P K Singh
  • 4. Predictive Parser a grammar a grammar suitable for eliminate left predictive parsing (a LL(1) left recursion factor grammar) no %100 guarantee. • When re-writing a non-terminal in a derivation step, a predictive parser can uniquely choose a production rule by just looking the current symbol in the input string. A → α1 | ... | αn input: ... a ....... current token Dr. P K Singh TCS 502 Compiler Design slide4
  • 5. Left Recursion A i l ft i if it h t i l A h th t• A grammar is left recursive if it has a non-terminal A such that there is a derivation. A A f t iA ⇒ Aα for some string α • Top-down parsing techniques cannot handle left-recursive + • Top-down parsing techniques cannot handle left-recursive grammars. • So, we have to convert our left-recursive grammar into an equivalent hi h i t l ft igrammar which is not left-recursive. • The left-recursion may appear in a single step of the derivation (immediate left-recursion), or may appear in more than one step of the derivation. Dr. P K Singh TCS 502 Compiler Design slide5
  • 6. Immediate Left-Recursion A → A α | β where β does not start with A ⇓ eliminate immediate left recursion A → β A’A → β A A’ → α A’ | ε an equivalent grammar A → A α1 | ... | A αm | β1 | ... | βn where β1 ... βn do not start with A ⇓ In general, ⇓ eliminate immediate left recursion A → β1 A’ | ... | βn A’ A’ → α1 A’ | ... | αm A’ | ε an equivalent grammar1 | | m | q g Dr. P K Singh TCS 502 Compiler Design slide6
  • 7. Immediate Left-Recursion -- Example E → E+T | T T → T*F | F F id | (E)F → id | (E) ⇓ eliminate immediate left recursion E → T E’ E’ → +T E’ | ε| T → F T’ T’ → *F T’ | ε F → id | (E) Dr. P K Singh TCS 502 Compiler Design slide7
  • 8. Left-Recursion -- Problem • A grammar cannot be immediately left-recursive, but it still can be left-recursive. • By just eliminating the immediate left-recursion, we may notBy just eliminating the immediate left recursion, we may not get a grammar which is not left-recursive. S → Aa | b A → Sc | d This grammar is not immediately left-recursive, but it is still left-recursive. S ⇒ Aa ⇒ Sca or A ⇒ Sc ⇒ Aac causes to a left-recursion • So, we have to eliminate all left-recursions from our grammar Dr. P K Singh TCS 502 Compiler Design slide8
  • 9. Eliminate Left-Recursion -- Algorithm A t i l i d A A- Arrange non-terminals in some order: A1 ... An - for i from 1 to n do { for j from 1 to i 1 do {- for j from 1 to i-1 do { replace each production Ai → Aj γAi → Aj γ by Ai → α1 γ | ... | αk γi 1 γ | | k γ where Aj → α1 | ... | αk } - eliminate immediate left-recursions among Ai productions } Dr. P K Singh TCS 502 Compiler Design slide9
  • 10. Eliminate Left-Recursion -- Example S → Aa | bS → Aa | b A → Ac | Sd | f - Order of non-terminals: S, A for S: - we do not enter the inner loop. - there is no immediate left recursion in S. for A: - Replace A → Sd with A → Aad | bd So, we will have A → Ac | Aad | bd | fSo, we will have A → Ac | Aad | bd | f - Eliminate the immediate left-recursion in A A → bdA’ | fA’ A’ → cA’ | adA’ | ε So, the resulting equivalent grammar which is not left-recursive is: S → Aa | b A → bdA’ | fA’ Dr. P K Singh TCS 502 Compiler Design slide10 A’ → cA’ | adA’ | ε
  • 11. Eliminate Left-Recursion – Example2 S → Aa | bS → Aa | b A → Ac | Sd | f - Order of non-terminals: A, S for A: - we do not enter the inner loop. - Eliminate the immediate left-recursion in A A → SdA’ | fA’| A’ → cA’ | ε for S: - Replace S → Aa with S → SdA’a | fA’a So, we will have S → SdA’a | fA’a | b - Eliminate the immediate left-recursion in S S → fA’aS’ | bS’ S’ → dA’aS’ | ε So, the resulting equivalent grammar which is not left-recursive is: S → fA’aS’ | bS’ S’ → dA’aS’ | ε A → SdA’ | fA’ A’ cA’ | Dr. P K Singh TCS 502 Compiler Design slide11 A → cA | ε
  • 12. Left-Factoring • A predictive parser (a top-down parser without backtracking) insists that the grammar must be left-factored. stmt → if expr then stmt else stmt | i t tif expr then stmt • when we see if we cannot now which production rule to choose to• when we see if, we cannot now which production rule to choose to re-write stmt in the derivation. Dr. P K Singh TCS 502 Compiler Design slide12
  • 13. Left Factoring R iti d ti t d l d i i• Rewriting productions to delay decisions • Helpful for predictive parsing • Not guaranteed to remove ambiguity A αβ1 | αβ2 A αA’ A’ β | βA’ β1 | β2 Dr. P K Singh TCS 502 Compiler Design slide13
  • 14. Algorithm: Left Factoring Dr. P K Singh TCS 502 Compiler Design slide14
  • 15. Left-Factoring – Example1 A bB | B | d | d B | dfBA → abB | aB | cdg | cdeB | cdfB ⇓ A → aA’ | cdg | cdeB | cdfB A’ bB | BA → bB | B ⇓ A → aA’ | cdA’’ A’ → bB | BA → bB | B A’’ → g | eB | fB Dr. P K Singh TCS 502 Compiler Design slide15
  • 16. Left-Factoring – Example2 A d | | b | b | bA → ad | a | ab | abc | b ⇓ A → aA’ | b A’ d | | b | bA’ → d | ε | b | bc ⇓ A → aA’ | b A’ → d | ε | bA’’A → d | ε | bA A’’ → ε | c Dr. P K Singh TCS 502 Compiler Design slide16
  • 17. Top Down Parsing C b i d t• Can be viewed two ways: – Attempt to find leftmost derivation for input string Att t t t t t ti f t t ti d– Attempt to create parse tree, starting from at root, creating nodes in preorder • General form is recursive descent parsingGeneral form is recursive descent parsing – May require backtracking – Backtracking parsers not used frequently because not neededg p q y Dr. P K Singh TCS 502 Compiler Design slide17
  • 18. Predictive Parsing A i l f i d t i th t d• A special case of recursive-descent parsing that does not require backtracking • Must always know which production to use based on• Must always know which production to use based on current input symbol • Can often create appropriate grammar:• Can often create appropriate grammar: – removing left-recursion – left factoring the resulting grammarleft factoring the resulting grammar Dr. P K Singh TCS 502 Compiler Design slide18
  • 19. Predictive Parser (example) t t if |stmt → if ...... | while ...... | begin |begin ...... | for ..... • When we are trying to write the non-terminal stmt, if the current token is if we have to choose first production rule. • When we are trying to write the non-terminal stmt, we can uniquely choose the production rule by just looking the current token. • We eliminate the left recursion in the grammar and left factor it ButWe eliminate the left recursion in the grammar, and left factor it. But it may not be suitable for predictive parsing (not LL(1) grammar). TCS 502 Compiler Design 19Dr. P K Singh
  • 20. Recursive Predictive Parsing E h t i l d t d• Each non-terminal corresponds to a procedure. Ex: A → aBb (This is only the production rule for A) proc A { - match the current token with a, and move to the next token; - call ‘B’; - match the current token with b, and move to the next token; } TCS 502 Compiler Design 20Dr. P K Singh
  • 21. Recursive Predictive Parsing (cont.) A → aBb | bABA → aBb | bAB proc A {p { case of the current token { ‘a’: - match the current token with a, and move to the next token; ll ‘B’- call ‘B’; - match the current token with b, and move to the next token; ‘b’: - match the current token with b, and move to the next token; - call ‘A’; - call ‘B’; }} } TCS 502 Compiler Design 21Dr. P K Singh
  • 22. Recursive Predictive Parsing (cont.) Wh t l d ti• When to apply ε-productions. A → aA | bB | εA → aA | bB | ε • If all other productions fail, we should apply an ε-production. ForIf all other productions fail, we should apply an ε production. For example, if the current token is not a or b, we may apply the ε-production. • Most correct choice: We should apply an ε production for a non• Most correct choice: We should apply an ε-production for a non- terminal A when the current token is in the follow set of A (which terminals can follow A in the sentential forms). TCS 502 Compiler Design 22Dr. P K Singh
  • 23. Transition Diagrams F• For parser: – One diagram for each nonterminal – Edge labels can be tokens or nonterminal • A transition on a token means we should take that transition if token is next input symbol • A transition on a nonterminal can be thought of as a call to a procedure for that nonterminalp • As opposed to lexical analyzers: O ( ) di f h t k– One (or more) diagrams for each token – Labels are symbols of input alphabet Dr. P K Singh TCS 502 Compiler Design slide23
  • 24. Creating Transition Diagrams Fi li i l f i f• First eliminate left recursion from grammar • Then left factor grammar • For each nonterminal A: Create an initial and final state– Create an initial and final state – For every production A X1X2…Xn, create a path from initial to final state with edges labeled X Xfrom initial to final state with edges labeled X1, X2, …, Xn. Dr. P K Singh TCS 502 Compiler Design slide24
  • 25. Using Transition Diagrams • Predictive parsers:• Predictive parsers: – Start at start symbol of grammar – From state s with edge to state t labeled with token a, if nextg , input token is a: • State changes to t • Input cursor moves one position rightp p g – If edge labeled by nonterminal A: • State changes to start state for A • Input cursor is not moved• Input cursor is not moved • If final state of A reached, then state changes to t – If edge labeled by ε, state changes to t • Can be recursive or non-recursive using stack Dr. P K Singh TCS 502 Compiler Design slide25
  • 26. Transition Diagram Example E E + T | T T T * F | F E TE’ E’ +TE’ | ε T FT’T T * F | F F (E) | id T FT T’ *FT’ | ε F (E) | id 0 1 T 2 E’ 10 11 * 13 ε 12 F T’ E: T’: 3 4 + 6 ε 5 T E’ ε E’: ε 7 8 F 9 T’ 14 15 ( 17 id 16 E ) F:T: Dr. P K Singh TCS 502 Compiler Design slide26 id
  • 27. Simplifying Transition Diagrams 3 4 + 6 ε 5 T E’ E’: 0 1 T 2 E’ E: 3 4 + ε 5 T 0 1 T 2 E’ 0 3 T 4 + 6 0 3 T 4 + ε T ε + 6 3 4 + ε T 0 3 T + 6 ε Dr. P K Singh TCS 502 Compiler Design slide276
  • 28. Simplified Transition Diagrams Dr. P K Singh TCS 502 Compiler Design slide28
  • 29. Recursive Predictive Parsing (Example) A → aBe | cBd | CA → aBe | cBd | C B → bB | ε C → f proc C { match the current token with f, proc A { and move to the next token; } case of the current token { a: - match the current token with a, {and move to the next token; proc B { - call B; case of the current token { - match the current token with e, b:- match the current token with b, and move to the next token; and move to the next token;and move to the next token; and move to the next token; c: - match the current token with c, - call B and move to the next token; e,d: do nothing - call B; } - match the current token with d, } and move to the next token; f: - call C follow set of B Dr. P K Singh TCS 502 Compiler Design slide29 } } first set of C
  • 30. Nonrecursive Predictive Parsing (1) a + b $Input XStack Predictive Parsing Program Output X Y Z $ Stac $ Parsing Table M Dr. P K Singh TCS 502 Compiler Design slide30
  • 31. Nonrecursive Predictive Parsing (2) • The symbol at the top of the stack (say X) and the current symbol in the input string (say a) determine the parser action. • There are four possible parser actions. 1. If X and a are $ parser halts (successful completion) 2. If X and a are the same terminal symbol (different from $) parser pops X from the stack and moves the next symbol in the input bufferparser pops X from the stack, and moves the next symbol in the input buffer. 3. If X is a non-terminal parser looks at the parsing table entry M[X,a]. If M[X,a] holds a production rule X→Y Y Y it pops X from the stack and pushes Y Y Y into the stack TheX→Y1Y2...Yk, it pops X from the stack and pushes Yk,Yk-1,...,Y1 into the stack. The parser also outputs the production rule X→Y1Y2...Yk to represent a step of the derivation. 4. none of the above error4. none of the above error – all empty entries in the parsing table are errors. – If X is a terminal symbol different from a, this is also an error case. Dr. P K Singh TCS 502 Compiler Design slide31
  • 32. Predictive Parsing Table Nonter- minal Input Symbol id + * ( ) $id + ( ) $ E E TE’ E TE’ E’ E’ +TE’ E’ ε E’ ε T T FT’ T FT’ T’ T’ ε T’ *FT’ T’ ε T’ ε F F id F (E) Dr. P K Singh TCS 502 Compiler Design slide32
  • 33. Using a Predictive Parsing Table Stack Input Output $E id+id*id$ Stack Input Output … … … $E’T id+id*id$ E TE’ $E’T’F id+id*id$ T FT’ $E’T’id id*id$ F id $E’T’ *id$ $E’T’id id+id*id$ F id $E’T’ +id*id$ $E’T’F* *id$ T’ *FT’ $E’T’F id$ $E’ +id*id$ T’ ε $E’T+ +id*id$ E’ +TE’ $E’T’id id$ F id $E’T’ $ $E’T id*id$ $E’T’F id*id$ T FT’ $E’ $ T’ ε $ $ E’ ε Dr. P K Singh TCS 502 Compiler Design slide33
  • 34. FIRST ( ) i th t f ll t i l th t b i• FIRST(α) is the set of all terminals that begin any string derived from α • Computing FIRST:• Computing FIRST: – If X is a terminal, FIRST(X) = {X} If X ε is a production add ε to FIRST(X)– If X ε is a production, add ε to FIRST(X) – If X is a nonterminal and X Y1Y2…Yn is a production: • For all terminals a, add a to FIRST(X) if a is a member of any, ( ) y FIRST(Yi) and ε is a member of FIRST(Y1), FIRST(Y2), … FIRST(Yi-1) • If ε is a member of FIRST(Y1), FIRST(Y2), … FIRST(Yn), add ε to( 1), ( 2), ( n), FIRST(X) Dr. P K Singh TCS 502 Compiler Design slide34
  • 35. FOLLOW • FOLLOW(A), for any nonterminal A, is the set of terminals a that can appear immediately to the right if A in some sentential form • More formally a is in FOLLOW(A) if and only if there exists aMore formally, a is in FOLLOW(A) if and only if there exists a derivation of the form S *=>αAaβ • $ is in FOLLOW(A) if and only if there exists a derivation of the form S * > αAS => αA Computing FOLLOW Pl $ i• Place $ in FOLLOW(S) • If there is a production A αBβ, then everything in FIRST(β) (except for ε) is in FOLLOW(B)( p ) • If there is a production A αB, or a production A αBβ where FIRST(β) contains ε,then everything in FOLLOW(A) is also in FOLLOW(B) Dr. P K Singh TCS 502 Compiler Design slide35 FOLLOW(B)
  • 36. FIRST and FOLLOW Example E TE’ E’ +TE’| ε T FT’T FT’ T’ *FT’| ε F (E) | id FIRST(E) = FIRST(T) = FIRST(F) = {(, id} FIRST(E’) {+ ε}FIRST(E’) = {+, ε} FIRST(T’) = {*, ε} FOLLOW(E) = FOLLOW(E’) = {), $} FOLLOW(T) = FOLLOW(T’) = {+, ), $} FOLLOW(F) = {+, *, $} Dr. P K Singh TCS 502 Compiler Design slide36
  • 37. Creating a Predictive Parsing Table F h d ti• For each production A α : – For each terminal a in FIRST(α) add A α to M[A, a] – If ε is in FIRST(α) add A α to M[A, b] for every terminal b in FOLLOW(A)every terminal b in FOLLOW(A) – If ε is in FIRST(α) and $ is in FOLLOW(A) add A α to M[A $]α to M[A, $] • Mark each undefined entry of M as an error entry (use some recovery strategy)entry (use some recovery strategy) Dr. P K Singh TCS 502 Compiler Design slide37
  • 38. Example E → TE’ E’ → +TE’ | ε| T → FT’ T’ → *FT’ | ε F (E) | idF → (E) | id Dr. P K Singh TCS 502 Compiler Design slide38
  • 39. Constructing LL(1) Parsing Table -- Example ’ ’ ’E → TE’ FIRST(TE’)={(,id} E → TE’ into M[E,(] and M[E,id] E’ → +TE’ FIRST(+TE’ )={+} E’ → +TE’ into M[E’,+] E’ → ε FIRST(ε)={ε} none but since ε in FIRST(ε) and FOLLOW(E’)={$,)} E’ → ε into M[E’,$] and M[E’,)] T → FT’ FIRST(FT’)={(,id} T → FT’ into M[T,(] and M[T,id] T’ → *FT’ FIRST(*FT’ )={*} T’ → *FT’ into M[T’,*] T’ → ε FIRST(ε)={ε} none but since ε in FIRST(ε) and FOLLOW(T’)={$,),+} T’ → ε into M[T’,$], M[T’,)] and M[T’,+] F → (E) FIRST((E) )={(} F → (E) into M[F,(] F → id FIRST(id)={id} F → id into M[F,id] TCS 502 Compiler Design 39Dr. P K Singh
  • 40. LL(1) Grammars A h i t bl h lti l d fi d• A grammar whose parsing table has no multiply-defined entries is said to be LL(1) grammar. one input symbol used as a look-head symbol do determine parser action LL(1) left most derivation input scanned from left to rightp g • The parsing table of a grammar may contain more than one production rule. In this case, we say that it is not a LL(1) grammar. TCS 502 Compiler Design 40Dr. P K Singh
  • 41. A Grammar which is not LL(1) S i C t S E | FOLLOW(S) { $ }S → i C t S E | a FOLLOW(S) = { $,e } E → e S | ε FOLLOW(E) = { $,e } C b FOLLOW(C) { t }C → b FOLLOW(C) = { t } FIRST(iCtSE) = {i} FIRST(a) = {a} a b e i t $ S S → a S → iCtSE FIRST(eS) = {e} FIRST(ε) = {ε} iCtSE E E → e S E → ε E → ε FIRST(b) = {b} C C → b TCS 502 Compiler Design 41 two production rules for M[E,e] Dr. P K Singh
  • 42. A Grammar which is not LL(1) (cont.) What do we have to do it if the resulting parsing table contains multiply defined• What do we have to do it if the resulting parsing table contains multiply defined entries? – If we didn’t eliminate left recursion, eliminate the left recursion in the grammar. – If the grammar is not left factored we have to left factor the grammarIf the grammar is not left factored, we have to left factor the grammar. – If its (new grammar’s) parsing table still contains multiply defined entries, that grammar is ambiguous or it is inherently not a LL(1) grammar. • A left recursive grammar cannot be a LL(1) grammar. – A → Aα | β any terminal that appears in FIRST(β) also appears FIRST(Aα) because Aα ⇒ βα. i l h i FIRST( ) l i FIRST(A ) dIf β is ε, any terminal that appears in FIRST(α) also appears in FIRST(Aα) and FOLLOW(A). • A grammar is not left factored, it cannot be a LL(1) grammar A β | β• A → αβ1 | αβ2 any terminal that appears in FIRST(αβ1) also appears in FIRST(αβ2). • An ambiguous grammar cannot be a LL(1) grammar. TCS 502 Compiler Design 42 g g ( ) g Dr. P K Singh
  • 43. Properties of LL(1) Grammars A G i LL(1) if d l if th f ll i diti h ld f• A grammar G is LL(1) if and only if the following conditions hold for two distinctive production rules A → α and A → β 1. Both α and β cannot derive strings starting with same terminals. 2. At most one of α and β can derive to ε. 3. If β can derive to ε, then α cannot derive to any string starting ith t i l i FOLLOW(A)with a terminal in FOLLOW(A). • A Grammar to be LL(1), following conditions must satisfied: For every pair of productions A α І β { FIRST(α) ∩ FIRST(β) = Φ( ) (β) and if FIRST(β) contains ε then FIRST(α) ∩ FOLLOW(A) = Φ } TCS 502 Compiler Design 43 } Dr. P K Singh
  • 44. Example T t th F ll i G i LL(1) t ?• Test the Following Grammar is LL(1) or not ? S 1AB | ε A 1AC | 0CA 1AC | 0C B 0S C 1C 1 For Production S 1AB | ε FIRST(1AB) ∩ FIRST(ε) = {1} ∩ {ε} = Φ and( ) ( ) { } { } FIRST(1AB) ∩ FOLLOW(S) = {1} ∩ {$} = Φ Similarly A 1AC | 0C FIRST(1AC) ∩ FIRST(0C) = {1} ∩ {0} = Φ Hence The Grammar is LL(1) Dr. P K Singh TCS 502 Compiler Design slide44