Docsity

Computing FIRST Sets, FOLLOW Sets - Compiler Construction - Lecture Notes, Study notes of Compiler Construction

Toggle sidebar
bg1
L
Le
ec
ct
tu
ur
re
e
1
18
8
Computing FIRST Sets
Here is the algorithm for computing the FIRST sets.
1. For all terminal symbols b,
FIRST(b) = {b}
2. For all productions: X ? A1... An
Add FIRST(A1) − {ε} to FIRST(X), stop if ε ∉FIRST(A1)
Add FIRST(A2) − {ε} to FIRST(X), stop if ε ∉FIRST(A2)
.....
Add FIRST(An) − {ε} to FIRST(X), stop if ε ∉FIRST(A n)
Add ε to FIRST(X)
This strategy is encoded in the following procedure
for each a ∈ ( T ∪ ε )
FIRST(a) ? {a}
for each A ∈ NT
FIRST(A) ? Ø
while ( FIRST sets are still changing)
for each A ? β1 β2... βk ∈ P
FIRST(A) ?FIRST(A) ∪ (FIRST(β1) – {ε})
i ?1
while ( ε ∈ FIRST(βi) and i = k-1 )
FIRST(A) ?FIRST(A) ∪ (FIRST(βi+1) – {ε})
i ? i+1
if (i == k and ε ∈ FIRST(βk)
FIRST(A) ?FIRST(A) ∪ {ε}
Example: consider the expression grammar again
1 E ? T E'
2 E' ? + T E'
3 | ε
4 T ? F T'
5 T' ? * F T'
6 | ε
7 F ? ( E )
8 | Id
pf3

Partial preview of the text

Download Computing FIRST Sets, FOLLOW Sets - Compiler Construction - Lecture Notes and more Study notes Compiler Construction in PDF only on Docsity!

LeLeccttuurree 1 188

Computing FIRST Sets

Here is the algorithm for computing the FIRST sets.

  1. For all terminal symbols b,

FIRST(b) = {b}

  1. For all productions: X? A 1 ... An

Add FIRST(A 1 ) − {ε} to FIRST(X), stop if ε ∉ FIRST(A 1 ) Add FIRST(A 2 ) − {ε} to FIRST(X), stop if ε ∉ FIRST(A 2 ) ..... Add FIRST(A (^) n) − {ε} to FIRST(X), stop if ε ∉ FIRST(A (^) n) Add ε to FIRST(X)

This strategy is encoded in the following procedure

for each a ∈ ( T ∪ ε ) FIRST( a )? { a } for each A ∈ NT FIRST( A )? Ø while ( FIRST sets are still changing) for each A? β 1 β 2 ... βk ∈ P FIRST( A )? FIRST( A ) ∪ (FIRST( β 1 ) – {ε}) i? 1 while ( ε ∈ FIRST( βi ) and i = k-1 ) FIRST( A )? FIRST( A ) ∪ (FIRST( βi+1 ) – {ε}) i? i+ if (i == k and ε ∈ FIRST( βk ) FIRST( A )? FIRST( A ) ∪ {ε}

Example : consider the expression grammar again

1 E? T E' 2 E'? + T E' 3 | ε 4 T? F T' 5 T'? * F T' 6 | ε 7 F? ( E ) 8 | Id

FIRST(id) = { id } FIRST('(' ) = { ( } FIRST(‘+' ) = { + }

FIRST( E ) = {FIRST( T ) − { ε } } FIRST( T ) = {FIRST( F ) − { ε } } FIRST( F ) = {FIRST( '(') − { ε } } = { ( }

FIRST( F ) = { '(' } + {FIRST( id ) − { ε } } = { ( , id}

FIRST( E' ) = { +, ε } FIRST( T' ) = { ∗ , ε }

Thus, FIRST( E ) = FIRST( T ) = FIRST( F ) = { (, id } FIRST( E' ) = { +, ε } FIRST( T' ) = { ∗ , ε }

FOLLOW Sets

Definition:

FOLLOW(X) = { b | S? ∗^ β Xb ω }

Computing FOLLOW Sets:

  1. Add $ to FOLLOW(S) where S is the start non-terminal.
  2. If there is a production A? α B β , then everything in FIRST(β) – {ε} is in FOLLOW(B).
  3. If there is a production A? α B, or A? α B β , where in ε ∈ FIRST(β) (i.e., β? ∗^ ε), then everything in FOLLOW(A) is in FOLLOW(B)