Predictive Parser Unit 2
Predictive Parser Unit 2
INPUT :- Grammar G
OUTPUT:- Parsing table M
For each production A -> α , do the following :
1. For each terminal ‘a’ in FIRST(A), add
A-> α to M[A,α].
2. If ε is in FIRST(α) then for each terminal b
in FOLLOW(A). A -> α to M[A,b]. If b is $
then also add A -> α to M[A,$].
3. If there is no production in M[A,a] , then
set M[A,a] to error.
Example of LL(1) grammar
E -> TE’
E -> +TE’|ε
T -> FT’
T’ -> *FT’|ε
F -> (E)|id
Generated Parser Table
For String id + id * id
Non INPUT
Terminal SYMBOLS
id + * ( ) $
Table
Parser
Input Buffer
Stack
Procedure of predictive parser
• The current symbol of the input string is
maintained by a pointer say ‘ip’.
• In every step consider the set {a,α} where ‘a’ is
(1) E->TE’
(2) E’->+TE’ id + * ( ) $
(3) E’->e E (1) (1)
(4) T->FT’ E’ (2) (3) (3)
(5) T’->*FT’
(6) T’->e
T (4) (4)
(7) F->(E) T’ (6) (5) (6) (6)
(8) F->id F (8) (7)
• Using the parsing table, the
predictive parsing program works
like this:
– A stack of grammar symbols ($ on the bottom)
– A string of input tokens ($ at the end)
– A parsing table, M[NT, T] of productions
– Algorithm:
– put ‘$ Start’ on the stack ($ is the end of input
string).
1) if top == input == $ then accept
2) if top == input then
pop top of the stack; advance to next input
symbol; goto 1;
3) If top is nonterminal
if M[top, input] is a production then
replace top with the production; goto 1
else error
4) else error
– Example:
id + * ( ) $
(1) E->TE’ E (1) (1)
(2) E’->+TE’
(3) E’->e
E’ (2) (3) (3)
(4) T->FT’ T (4) (4)
(5) T’->*FT’ T’ (6) (5) (6) (6)
(6) T’->e F (8) (7)
(7) F->(E)
(8) F->id
Stack input production
$E id+id*id$
$E’T id+id*id$ E->TE’
$E’T’F id+id*id$ T->FT’
$E’T’id id+id*id$ F->id
$E’T’ +id*id$
…...
if i , then
(a) no, j e, when i j
(b) First( j ) Follow(A) {}, when i j.
• Example, build LL(1) parsing table for the
following grammar:
S-> i E t S e S | i E t S | a
E -> b