Top Down Parsing Example: The Problem Is Simple: Left Recursion!
Top Down Parsing Example: The Problem Is Simple: Left Recursion!
Example
S E
E T | E+T
T F | T*F
F unit | (E)
and the expression:
1+2*3
CC&P 2004
Slide 1
Example #2
Suppose we have a grammar:
S E
E T | E+T
T F | T*F
F unit | (E)
and the expression:
1+2*3
Slide 2
Solutions?
CC&P 2004
Slide 3
CC&P 2004
Slide 4
C c | Ac
2. Apply the following steps to the productions for N1, then N2, ...
3. For Ni :
a) For all productions Ni Nk , where k < i and if the productions
for Nk are Nk 1 | 2 | 3 | ... then expand the reference to Nk,
i.e. replace the production Ni Nk by Ni 1 | 2 | ...
b) If the productions for Ni are now
Ni 1 | 2 | ... | Ni 1 | Ni 2 | ...
(where the first few are not left recursive while the latter are)
then replace them with
Ni 1 Ni | 2 Ni | ...
Ni | 1 Ni | 2 Ni | ...
CC&P 2004
Slide 5
C | bacC
CC&P 2004
Slide 6
A Workable Solution
Definitions
Observation
The trouble which gives rise to nondeterminacy and
backtracking in top down parsers shows itself in only one
place that is when a parser has to choose between
several alternatives with the same left hand side.
The only information which we can use to make the
correct decision is the input stream itself.
CC&P 2004
Slide 7
CC&P 2004
Slide 8
Definition of LL(1)
Definition of First
To compute FIRST(X) for all grammar symbols X, apply
the following algorithm until no more terminals or can be
added to any FIRST set.
1. If X is a terminal, then FIRST(X) is {X}
2. If X is a production, then add to FIRST(X)
3. If X is a nonterminal and X Y1 Y2 ...Yn is a
production, then place a in FIRST(X) if for some i, a is in
FIRST(Yi), and is in all of FIRST(Y1 ), ..., FIRST (Yi-1 );
that is Y1 Y2 ...Yi-1 * .
If is in FIRST(Yj ) for all j = 1, 2, ... n, then add to
FIRST(X). For example, everything in FIRST(Y1) is surely
in FIRST(X). If Y1 does not derive , then we add nothing
more to FIRST(X), but if Y1 then we add FIRST(Y2)
and so on.
CC&P 2004
Slide 9
CC&P 2004
Definition of Follow
Slide 10
CC&P 2004
Slide 11
director(i) director(k) = i k
where:
director(i) = first(i) follow(A)
= first(i)
CC&P 2004
if j
otherwise
Slide 12
ST
T L B | L C array
L long |
CB |
B real | integer
2
Slide 13
CC&P 2004
Factorisation of B in X gives:
ST
TLX
X B Y | array
Y array |
L long |
B real | integer
Slide 14