A top-down parser that predicts which production rule to apply by looking ahead at the next input token.
It does not backtrack (unlike recursive descent parsers with backtracking)
Predictive Parsing
• Itis a special case of recursive descent parsing
where no backtracking is required.
• To determine the production to be applied
for a non-terminal in case of alternatives.
4.
Input Buffer:
• Itconsists of strings, followed by $
Stack:
• It contains a sequence of grammar symbols
preceded by $.
Parsing Table:
• It is a 2D array M[A, a], where ‘A’ is a NT and
‘a’ is a terminal.
Predictive Parsing Program:
• The parser is controlled by a program that considers
X(symbol on top of stack) and
a, the current input symbol. These two symbols
determine the parser action.
Predictive parsing tableconstruction
• The construction of a predictive parser is
depends on 2 functions.
1. FIRST
2. FOLLOW
7.
Rules for calculatingFIRST( ):
1. If a production rule X → ,
∈
First(X) = { }
∈
2. For any terminal symbol ‘a’,
First(a) = { a }
3. For a production rule X → Y1Y2Y3,
• If First(Y
∈ ∉ 1), then
First(X) = First(Y1)
8.
Construct the FIRST(A)of G, E TE’ ,
E’
+TE’
|, T FT’,
T’
*FT’
|, F (E)|id.
Ans:
9.
Rules for calculatingFollow( ):
1. If S is the start symbol then
Follow(S)={$}
2. if A B is a production rule then
Follow(B)=First() except .
3. If ( A B is a production rule ) or
( A B is a production
rule and is in FIRST() ) then
Follow(A) = Follow(B).
10.
Ex: Construct theFollow(A) of G, E TE’ ,
E’
+TE’
|, T FT’,
T’
*FT’
|, F (E)|id.
Sol: Non Terminals(A) are {E, E’, T, T’, F}
• Follow(E):
F(E)
Compare by AαBβ Where
A = F; α = (; B = E;β = )
By case 1 : Follow(E) = {$}
By Case 2 : Follow(B) = First(β)
∴Follow(E) = First())={)}
Finally Follow(E) = { ),$ }
Algorithm for P.Parser
•Input : Grammar G
• Output : Parsing table M
• Method :
1. For each production A → α of the grammar, do
steps 2 and 3.
2. For each terminal a in FIRST(α), add A → α to
M[A, a].
3. If ε is in First(α), add A → α to M[A, b]
Where b = Follow(A).
4. Make each undefined entry of M be error.
16.
Steps for P.Parser:
1.Elimination of left recursion, left factoring
and ambiguous grammar.
2. Construct FIRST() and FOLLOW() for all non-
terminals.
3. Construct predictive parsing table.
4. Parse the given input string using stack and
parsing table.
17.
Construct the predectiveparse table for the following
Grammar E E+T|T,
T T*F|F, F (E)|id.
Sol:
Step1:
The given grammar consists of Left Recursion. So we have
to eliminate the Left recursion, then the productions
becomes
E T E’
E’
+T E’
|
T F T’
T’
*F T’
|
F id | (E)
LL(1) Grammars
• Whoseparsing table has no multiple entries
L L (k) parsing.
Left to Right Scanning
Left-Most Derivation
k lookhead (k is omitted it is 1)
24.
Ex: Verify whetherthe given grammar
is LL(1) or Not.
S i C t S E | a
E e S |
C b
FIRST(iCtSE) = {i}
FIRST(a) = {a}
FIRST(eS) = {e}
FIRST() = {}
FIRST(b) = {b}
∴ The above grammar is not LL(1) because of two production rules
for M[E,e]