- Type
- Quiz
- Course
- CS606 Compiler Construction
- Size
- PDF 37 KB
- Updated
- 23 Oct 2026
You get 3 free files a day on the website. Add the Chrome extensionSign in with the extension for 30 a day.
Preview text
Text from pages 1, 2, 3 of 3. Download the file for all 3 pages.
Lecture 18
Computing FIRST Sets
Here is the algorithm for computing the FIRST sets.
- For all terminal symbols b,
FIRST(b) = {b}
- 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}
FIRST(A) ? Ø while ( FIRST sets are still changing)
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' | ε 4 T ? F T' 5 T' ? * F T' | ε 7 F ? ( E ) | 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:
- Add $ to FOLLOW(S) where S is the start non-terminal.
- If there is a production A ? α Bβ , then everything in FIRST(β ) – {ε} is in FOLLOW(B).
- If there is a production A ? α B, or A ? αBβ , where in ε ∈ FIRST(β ) (i.e., β ? ∗ ε), then everything in FOLLOW(A) is in FOLLOW(B)
The following procedure encodes this strategy.
FOLLOW(A) ? Ø FOLLOW(S) ? {$} while ( FOLLOW sets are still changing)
FOLLOW(β k) ? FOLLOW(βk) ∪ FOLLOW(A) T ? FOLLOW(A) for i ? k downto 2 if ( ε ∈ FIRST (β i) ) FOLLOW(β i-1) ? FOLLOW(β i-1) ∪ (FIRST(β i) – {ε}) ∪ T else FOLLOW(β i-1) ? FOLLOW(β i-1) ∪FIRST(β i) T ? Ø
Let’s apply the algorithm to the expression grammar.
Put $ in FOLLOW(E ). By rule (2) applied to production ? ( E ), ‘)’ is also in FOLLOW(E ). Thus, FOLLOW(E ) = { ), $}. By rule (3) applied to production E ? T E' , $ and ‘)’ are in FOLLOW(E' ). Thus, FOLLOW(E ) = FOLLOW (E' ) = { ), $ }. Similarly, FOLLOW(T ) = FOLLOW (T' ) = { +, ), $ } and FOLLOW(F ) = { +, ∗, ), $ }
Related CS606 files
All CS606 files →Get more out of VUBuddy, for free
- Unlimited downloads
- The explanation behind every MCQ answer
- Study offline on slow data
- 30 downloads a day instead of 3
- Sign in and buy Pro Semester here
One Pro Semester membership works in both the extension and the app.