Computing the First and Follow Functions

advertisement
CIS 324: Language, Design and Implementation
Building Predictive Parsing Tables
1. Computing the Function FIRST
To compute FIRST( X ) for all grammar symbols X apply the following rules
until no more terminals or  can be added to any FIRST set:
 if X is terminal, then FIRST( X ) is { X }.
 if X   is a production, then add  to FIRST( X ).
 if X is nonterminal and X  Y1, Y2, ..., Yk is a production, then
place a in FIRST( X ) if a is in FIRST(Yi ) for some i, and  is in all of
FIRST(Y1 ), FIRST(Y2 ), ...,FIRST(Yi-1 ); that is Y1, Y2, ..., Yi-1 * .
If  is in FIRST(Yj ), all j = 1,2, ..., k then add  to FIRST( X ).
2. Computing the Function FOLLOW
To compute FOLLOW( A ) for all nonterminals A apply the following rules
until nothing can be added to any FOLLOW set:
 place $ in FOLLOW( S ) where S is the start symbol and
$ is the input right marker;
 if there is a production A  B , then everything in FIRST(  )
except the symbol  is placed in FOLLOW( B );
 if there is a production A  B , or a rpoduction A  B
where FIRST(  ) contains , then everything in FOLLOW( A )
is also in FOLLOW( B ).
3. Construction of Predicting Parsing Tables
Algorithm for Construction of Predictive Parsing Tables
Repeat: for each production A   of the grammar do
for each terminal a in FIRST(  )
add A   to M[ A, a ]
if FIRST(  ) contains 
add A   to M[ A, b ] for each b in FOLLOW( A )
if  is in FIRST(  ) and $ is in FOLLOW( A )
add A   to M[ A, $ ]
make each undefined entry of M be error
Example: Construct a predictive parsing table for the following grammar:
P  bSe
S  AR
R  AR | 
A  id = E ;
E  FT
T  +FT | 
F  (E) | id | INT
The construction of the predictive parsing table begins with the
computation of the functions FIRST and FOLLOW:
FIRST( P ) = { b }
FIRST( S ) = { id }
FIRST( R ) = { id,  }
FIRST( A ) = { id }
FIRST( E ) = { (, id, INT }
FIRST( T ) = { +,  }
FIRST( F ) = { (, id, INT }
FOLLOW( P ) = { $ }
/ according to rule 1 /
FOLLOW( S ) = { e }
/ according to rule 2 /
FOLLOW( R ) = { e }
/ according to rule 3 /
FOLLOW( A ) = { id,  } / according to rule 3 /
FOLLOW( E ) = { ; , ) } / according to rule 2 /
FOLLOW( T ) = { ; , ) } / according to rule 3 /
FOLLOW( F ) = { +, ; , ) } / according to rule 3 /
The parsing table for this grammar then becomes:
id
P
S
R
A
E
T
F
INT
=
+
;
S  AR
R  AR
A  id = E ;
E  FT
E  FT
F  INT
)
b
P  bSe
e
R
E  FT
T  +FT
F  id
(
T
T
F  (E)
$
Using the above parsing table a simple string will be parsed as follows:
Stack
$P
$ eSb
$eS
$eRA
$eR;E=id
$eR;E=
$eR;E
$eR;TF
$eR;Tid
$eR;T
$eR;TF+
$eR;TF
$eR;TINT
$eR;T
$eR;
$eR
$e
$
Input
b id = id + 1 ; e $
b id = id + 1 ; e $
id = id + 1 ; e $
id = id + 1 ; e $
id = id + 1 ; e $
= id + 1 ; e $
id + 1 ; e $
id + 1 ; e $
id + 1 ; e $
+1;e$
+1;e$
1;e$
1;e$
;e$
;e$
e$
e$
$
Output
P  bSe
S  AR
A  id = E ;
E  FT
F  id
T  +FT
F  INT
T
R
Download