Compiler Design and Construction · Unit 2 · 22 hrs
Lexical, Syntax and Semantic Analysis
Exam-focused notes for Lexical, Syntax and Semantic Analysis (Compiler Design and Construction, CSC376): what the TU syllabus asks and how it has actually been tested, with 35 solved past questions from this unit.
Lexical, Syntax and Semantic Analysis in short
This chapter covers the front end of a compiler in depth: how raw characters become tokens, how tokens become a parse tree under top-down and bottom-up parsing, how the parse tree is checked and annotated by semantic analysis, and how syntax directed definitions carry meaning through the tree.
What this unit covers
- Lexical Analysis: Its role
- Specification and Recognition of tokens
- Input Buffer
- Finite Automata relevant to compiler construction syntactic specification of languages
- Optimization of DFA based pattern matchers
- Syntax Analysis: Its role
- Basic parsing techniques: Problem of Left Recursion
- Left Factoring
- Ambiguous Grammar
- Top-down parsing
- Bottom-up parsing
- LR parsing
- Semantic Analysis: Static & Dynamic Checks
- Typical Semantic errors
- Scoping
- Type Checking
- Syntax directed definitions (SDD) & Translation (SDT)
- Attribute Types: Synthesized & Inherited
- Annotated Parse Tree
- S-attributed and L-attributed grammar
- Applications of syntax directed translation
- Type Systems
- Type Checking and Conversion
LR parsing
2081 · 10 marks
Give an example of reduce-reduce conflict. Construct the SLR parsing table for the following grammar.E→(L)∣aE \rightarrow (L) \mid aE→(L)∣aL→L,E∣EL \rightarrow L, E \mid EL→L,E∣E[10]
Show solved answerHide answer
Reduce-Reduce Conflict and SLR Parsing Table
Part 1: Reduce-Reduce Conflict Example
A reduce-reduce conflict occurs when, in a single LR state, two or more complete items (items with the dot at the far right) call for reduction by different productions, and a lookahead symbol is in the FOLLOW set of more than one of the corresponding left-hand nonterminals. The parser cannot decide which production to reduce by.
Example Grammar:
S -> A
S -> B
A -> c
B -> c
After reading c, the state contains both complete items:
A -> c .
B -> c .
Since both $A$ and $B$ can appear in the same context (via S -> A and S -> B), the FOLLOW sets of $A$ and $B$ overlap (both contain $). On lookahead $, the parser cannot decide whether to reduce A -> c or B -> c. This is a reduce-reduce conflict.
Part 2: SLR Parsing Table
Given Grammar (augmented and numbered):
$$ \begin{aligned} (0)\ & E' \rightarrow E \ (1)\ & E \rightarrow (L) \ (2)\ & E \rightarrow a \ (3)\ & L \rightarrow L, E \ (4)\ & L \rightarrow E \end{aligned} $$
FIRST and FOLLOW Sets
$$\text{FIRST}(E) = \text{FIRST}(L) = {\ (\ ,\ a\ }$$
- $$\text{FOLLOW}(E') = { $ }$$
- $$\text{FOLLOW}(E) = { $,\ ),\ ,\ }$$ (from $E'\to E$:
$; fromL -> L,E:,; andEinherits fromL -> EwhereLis followed by)and,) - $\text{FOLLOW}(L) = { ),\ ,\ }$ (from
E -> (L):); fromL -> L,E:,)
Canonical LR(0) Item Sets
I0: E'->.E, E->.(L), E->.a → on E→I1, on ( →I2, on a→I3
I1: E'->E.
I2: E->(.L), L->.L,E, L->.E, E->.(L), E->.a → on L→I4, on E→I5, on ( →I2, on a→I3
I3: E->a.
I4: E->(L.), L->L.,E → on ) →I6, on , →I7
I5: L->E.
I6: E->(L).
I7: L->L,.E, E->.(L), E->.a → on E→I8, on ( →I2, on a→I3
I8: L->L,E.
SLR Parsing Table
| State | ( | a | ) | , | $ | E | L |
|---|---|---|---|---|---|---|---|
| 0 | s2 | s3 | 1 | ||||
| 1 | acc | ||||||
| 2 | s2 | s3 | 5 | 4 | |||
| 3 | r2 | r2 | r2 | ||||
| 4 | s6 | s7 | |||||
| 5 | r4 | r4 | |||||
| 6 | r1 | r1 | r1 | ||||
| 7 | s2 | s3 | 8 | ||||
| 8 | r3 | r3 |
Notes:
- Reductions by production (2)
E->aand (1)E->(L)appear on FOLLOW(E) ={ ), , , $ }. - Reductions by production (4)
L->Eand (3)L->L,Eappear on FOLLOW(L) ={ ), , }.
The table has no multiply-defined entries, so the grammar is SLR(1).
2081 · 5 marks
Define core item. Compute the LR(1) item sets for the following grammar. S→AAS \rightarrow AAS→AAA→aA∣bA \rightarrow aA \mid bA→aA∣b[5]
Show solved answerHide answer
LR(1) Item Sets for S → AA, A → aA | b
Given Data
Grammar:
- $S \rightarrow AA$
- $A \rightarrow aA \mid b$
Definition of Core Item
The core of an LR(1) item $[A \rightarrow \alpha.\beta, a]$ is its first component $A \rightarrow \alpha.\beta$, i.e., the underlying LR(0) item with the look-ahead removed. Two LR(1) item sets have the same core if their sets of LR(0) items (ignoring look-aheads) are identical.
Step 1: Augmented Grammar
$$S' \rightarrow S,\quad S \rightarrow AA,\quad A \rightarrow aA,\quad A \rightarrow b$$
Step 2: FIRST Sets
$$\text{FIRST}(S) = {a,b},\qquad \text{FIRST}(A) = {a,b}$$
Step 3: Canonical Collection
I₀ = Closure([S' → .S, $]):
[S' → .S, $]
[S → .AA, $]
[A → .aA, a/b]
[A → .b, a/b]
I₁ = GOTO(I₀, S):
[S' → S., $] (accept)
I₂ = GOTO(I₀, A):
[S → A.A, $]
[A → .aA, $]
[A → .b, $]
I₃ = GOTO(I₀, a):
[A → a.A, a/b]
[A → .aA, a/b]
[A → .b, a/b]
I₄ = GOTO(I₀, b):
[A → b., a/b] (reduce A → b)
I₅ = GOTO(I₂, A):
[S → AA., $] (reduce S → AA)
I₆ = GOTO(I₂, a):
[A → a.A, $]
[A → .aA, $]
[A → .b, $]
I₇ = GOTO(I₂, b):
[A → b., $] (reduce A → b)
I₈ = GOTO(I₃, A):
[A → aA., a/b] (reduce A → aA)
- GOTO(I₃, a) = I₃ (same items, self-loop)
- GOTO(I₃, b) = I₄
I₉ = GOTO(I₆, A):
[A → aA., $] (reduce A → aA)
- GOTO(I₆, a) = I₆ (self-loop)
- GOTO(I₆, b) = I₇
Summary of Transitions
| State | On S | On A | On a | On b |
|---|---|---|---|---|
| I₀ | I₁ | I₂ | I₃ | I₄ |
| I₂ | I₅ | I₆ | I₇ | |
| I₃ | I₈ | I₃ | I₄ | |
| I₆ | I₉ | I₆ | I₇ |
Total: 10 canonical LR(1) item sets (I₀ through I₉).
Note: Unlike LALR, states I₄/I₇ and I₈/I₉ have the same core but different look-aheads, so they remain distinct in the canonical LR(1) collection.
2080 · 10 marks
Construct the LR(1) parsing table for the following grammar.S→AaAbS \rightarrow AaAbS→AaAbA→BbBaA \rightarrow BbBaA→BbBaA→εA \rightarrow \varepsilonA→εB→εB \rightarrow \varepsilonB→ε[10]
2080 · 5 marks
Given the following grammar with SLR parsing table, test whether the string "int * (int + int)" will be accepted or rejected.
$$ \begin{aligned} E &\to T + E \quad \ldots (1) \ E &\to T \quad \ldots (2) \ T &\to int * T \quad \ldots (3) \ T &\to int \quad \ldots (4) \ T &\to (E) \quad \ldots (5) \end{aligned} $$
$$\begin{array}{|c|c|c|c|c|c|c||c|c|}\hline & \text{ACTION} & & & & & & \text{GOTO} & \ \hline \text{STATE} & \text{int} & * & + & ( & ) & $ & E & T \ \hline 1 & S5 & & & S4 & & & 2 & 3 \ \hline 2 & & & & & & \text{ACC} & & \ \hline 3 & & S6 & & & R2 & R2 & & \ \hline 4 & S5 & & & S4 & & & 7 & 3 \ \hline 5 & & S8 & R4 & & R4 & R4 & & \ \hline 6 & S5 & & & S4 & & & 9 & 3 \ \hline 7 & & & & & S10 & & & \ \hline 8 & S5 & & & S4 & & & & 11 \ \hline 9 & & & & & R1 & R1 & & \ \hline 10 & & & R5 & & R5 & R5 & & \ \hline 11 & & & R3 & & R3 & R3 & & \ \hline \end{array} $$
2078 · 10 marks
Differentiate between LR(0) and LR(1) algorithm. Construct LR(1) parse table of the following grammar.S→AAS \rightarrow AAS→AAA→aA∣bA \rightarrow aA | bA→aA∣b[10]
2076 · 6 marks
Construct SLR parsing table for the following grammar.S→aAa∣bAb∣baS \rightarrow aAa | bAb | baS→aAa∣bAb∣ba[6]
2075 · 6 marks
Construct SLR parse table for the following grammarS→ES \rightarrow ES→EE→E+T∣TE \rightarrow E+T|TE→E+T∣TT→T∗F∣FT \rightarrow T*F|FT→T∗F∣FF→idF \rightarrow idF→id[6]
2081.1 · 10 marks
Create the LR(1) parsing table for following grammar.S→AAS \rightarrow AAS→AAA→0AA \rightarrow 0AA→0AA→εA \rightarrow \varepsilonA→ε[10]
Show solved answerHide answer
LR(1) Parsing Table for the Grammar
Given
Grammar: $$S \to AA$$ $$A \to 0A$$ $$A \to \varepsilon$$
- Terminals: $${0, $}$$
- Non-terminals: ${S, A}$
- Marks: 10
Solution
Augmented Grammar
$$ \begin{aligned} (0)\ & S' \to S\ (1)\ & S \to AA\ (2)\ & A \to 0A\ (3)\ & A \to \varepsilon \end{aligned} $$
Canonical LR(1) Item Sets
Closure rule: For $[B \to \alpha \bullet C\beta, a]$, add $[C \to \bullet \gamma, b]$ for each $b \in \text{FIRST}(\beta a)$.
$$I_0 = \text{Closure}([S' \to \bullet S, $])$$
- $$[S' \to \bullet S, $]$$
- $$[S \to \bullet AA, $]$$ (dot before $S$, FIRST($$$ $$) = $$$ $$)
- Dot before first $A$; lookahead $=$ FIRST$$(A$) = {0, $}$$ (since $A \Rightarrow \varepsilon$):
- $$[A \to \bullet 0A, 0/$]$$
- $$[A \to \bullet, 0/$]$$
Transitions: $S \to I_1$, $A \to I_2$, $0 \to I_3$
$I_1 = \text{goto}(I_0, S)$
- $$[S' \to S \bullet, $]$$ (Accept)
$I_2 = \text{goto}(I_0, A)$
- $$[S \to A \bullet A, $]$$
- Dot before second $A$; lookahead $=$ FIRST($$$ $$) $$= {$}$$:
- $$[A \to \bullet 0A, $]$$
- $$[A \to \bullet, $]$$
Transitions: $A \to I_4$, $0 \to I_5$
$I_3 = \text{goto}(I_0, 0)$
- $$[A \to 0 \bullet A, 0/$]$$
- Dot before $A$; lookahead $$= {0, $}$$:
- $$[A \to \bullet 0A, 0/$]$$
- $$[A \to \bullet, 0/$]$$
Transitions: $A \to I_6$, $0 \to I_3$ (self-loop, same item set)
$I_4 = \text{goto}(I_2, A)$
- $$[S \to AA \bullet, $]$$ (reduce by rule 1)
$I_5 = \text{goto}(I_2, 0)$
- $$[A \to 0 \bullet A, $]$$
- $$[A \to \bullet 0A, $]$$
- $$[A \to \bullet, $]$$
Transitions: $A \to I_7$, $0 \to I_5$ (self-loop)
$I_6 = \text{goto}(I_3, A)$
- $$[A \to 0A \bullet, 0/$]$$ (reduce by rule 2)
$I_7 = \text{goto}(I_5, A)$
- $$[A \to 0A \bullet, $]$$ (reduce by rule 2)
Reduce actions
- $I_0$: $$[A \to \bullet, 0/$]$$ → reduce by rule 3 on $0$ and $$$ $$
- $I_2$: $$[A \to \bullet, $]$$ → reduce by rule 3 on $$$ $$
- $I_3$: $$[A \to \bullet, 0/$]$$ → reduce by rule 3 on $0$ and $$$ $$
- $I_4$: reduce by rule 1 on $$$ $$
- $I_5$: $$[A \to \bullet, $]$$ → reduce by rule 3 on $$$ $$
- $I_6$: reduce by rule 2 on $0$ and $$$ $$
- $I_7$: reduce by rule 2 on $$$ $$
Notation: $sn$ = shift and go to state $n$; $rn$ = reduce by production $n$; $acc$ = accept; blank = error.
LR(1) Parsing Table
| State | Action 0 | Action $ | Goto S | Goto A |
|---|---|---|---|---|
| 0 | s3 / r3 | r3 | 1 | 2 |
| 1 | acc | |||
| 2 | s5 | r3 | 4 | |
| 3 | s3 / r3 | r3 | 6 | |
| 4 | r1 | |||
| 5 | s5 | r3 | 7 | |
| 6 | r2 | r2 | ||
| 7 | r2 |
Note on conflicts (States 0 and 3)
In states $I_0$ and $I_3$ the item $[A \to \bullet, 0]$ calls for reduce by rule 3 on input $0$, while the items $[A \to \bullet 0A, \dots]$ call for shift on $0$. This is a shift/reduce conflict on 0.
Resolving in favor of shift (standard convention, and required for this grammar to accept strings like $00$), the entries $s3$ / $s5$ are used on input $0$. With this resolution the parser works correctly. Strictly, the grammar is not LR(1) because of this genuine shift/reduce conflict in states 0 and 3, so I have shown both actions in those cells.
Final Result
The canonical collection has 8 states ($I_0$ through $I_7$), and the completed LR(1) table is as shown above, with shift/reduce conflicts on input 0 in states 0 and 3 (resolved by shift).
2081.1 · 5 marks
What is a symbol table? Discuss the general structure of an LR parser. [5]
Show solved answerHide answer
Symbol Table and General Structure of LR Parser
Part 1: Symbol Table
A symbol table is a data structure used by a compiler to store information about the identifiers (variables, functions, objects, etc.) encountered in the source program.
The lexical analyzer helps to identify tokens and enters them into the symbol table. It stores attributes such as:
- Name of the identifier
- Type (integer, float, etc.)
- Scope (local, global)
- Memory location / address
- Size
The symbol table is accessed and updated by almost all phases of the compiler (lexical analysis, syntax analysis, semantic analysis, code generation, etc.). It allows the compiler to quickly look up and verify identifier information during compilation.
Part 2: General Structure of an LR Parser
An LR parser is a bottom-up parser that uses right-most derivation in reverse. It is more powerful than top-down parsers and can handle a larger class of grammars.
Block Diagram of LR Parser
Input: a1 a2 ... an $
|
+------+------+
| LR Parser |
+------+------+
|
+---------+---------+
| |
Action Table Goto Table
(Terminals + $) (Non-terminals)
| |
S(shift), R(reduce),
Accept, Error
|
Stack
[State | Symbol]
Sm | Xm
Sm-1 | Xm-1
...
S0
Components of LR Parser
| Component | Description |
|---|---|
| Input Buffer | Contains the input string followed by $ (end marker) |
| Stack | Stores states and grammar symbols (terminals or non-terminals) |
| Action Table | A 2D table indexed by [state, terminal]; gives shift, reduce, accept, or error |
| Goto Table | A 2D table indexed by [state, non-terminal]; gives the next state after a reduction |
| Output | A production rule representing a step in the derivation sequence |
Working of LR Parser
- The parser starts with an initial state
S0on the stack. - It reads the current input symbol
aand the top stateSm. - It consults the Action Table with
[Sm, a]:- Shift (S): Push the next state onto the stack and advance input.
- Reduce (R): Pop symbols from the stack according to the production rule and push the goto state.
- Accept: Parsing is successful.
- Error: Syntax error is reported.
- The Goto Table is used after a reduction to determine the new state.
Augmented Grammar
Before constructing the LR parsing table, the grammar is augmented. If G is a grammar with start symbol S, the augmented grammar G' adds a new start symbol S' with production:
S' -> S
This ensures the parser has a definite accept state.
Types of LR Parsers
- SLR (Simple LR): Uses LR(0) items with FOLLOW sets
- CLR / LR(1): Uses LR(1) items with look-ahead symbols; more powerful
- LALR: Merges states of LR(1) to reduce table size
LR parsers are high power, use right-most derivation, and have a larger parsing table compared to top-down parsers.
2081.1 · 5 marks
Generate the LR(0) item sets for the following grammar. A→BBA \rightarrow BBA→BBB→bB∣aB \rightarrow bB \mid aB→bB∣a[5]
Basic parsing techniques
2081 · 5 marks
Compute the FIRST and FOLLOW of the non-terminals in the following grammar. S→(L)∣1S \rightarrow (L) \mid 1S→(L)∣1L→L;S∣εL \rightarrow L;S \mid \varepsilonL→L;S∣ε[5]
2078 · 5 marks
Define Left recursive grammar. Remove left recursion from the following grammar. S→SB∣CaS \rightarrow SB | CaS→SB∣CaB→Bb∣cB \rightarrow Bb | cB→Bb∣cC→aB∣aC \rightarrow aB | aC→aB∣a[5]
Attribute Types
2081 · 5 marks
Describe the synthesized attribute and inherited attribute with an example. [5]
2078 · 5 marks
Define attribute grammar with example of inherited and synthesized attributes. [5]
2081.1 · 5 marks
Differentiate between synthesized and inherited attributes with example. [5]
Top-down parsing
2081 · 5 marks
What is a type expression? List the properties of LL(1) grammar. [5]
Show solved answerHide answer
Type Expression and Properties of LL(1) Grammar
Part 1: Type Expression (2 marks)
Definition
The type of a language construct is denoted by a type expression. A type expression is either a basic type or is formed by applying an operator called a type constructor to other type expressions. The sets of basic types and constructors depend on the language being type-checked.
Type Constructors Include:
-
Basic Types
- Primitive types such as
int,float,char,bool, etc. - A special basic type
erroris used to signal type errors.
- Primitive types such as
-
Arrays
- If
Tis a type expression, thenarray(I, T)is a type expression denoting an array with elements of typeTand index setI. - Example:
array(0...99, int)
- If
-
Products
- If
T1andT2are type expressions, then their Cartesian productT1 x T2is a type expression. - Example:
int x int
- If
-
Pointers
- If
Tis a type expression, thenpointer(T)is a type expression denoting the type "pointer to an object of type T".
- If
-
Functions
- A function maps a domain type to a range type, expressed as
T1 -> T2.
- A function maps a domain type to a range type, expressed as
Part 2: Properties of LL(1) Grammar (3 marks)
Definition of LL(1) Grammar
LL(1) grammar is a class of context-free grammar that can be parsed by a non-recursive predictive (top-down) parser using a single lookahead symbol without backtracking. The name LL(1) stands for:
- L - Left to right scanning of input
- L - Leftmost derivation
- 1 - One lookahead symbol
Properties of LL(1) Grammar
A grammar G is said to be LL(1) if and only if the following conditions hold:
-
No Left Recursion
- The grammar must not contain any left-recursive productions.
- Example: A production of the form
A -> Aαis not allowed in LL(1) grammar.
-
No Ambiguity
- The grammar must be unambiguous. An ambiguous grammar cannot be LL(1) because it would lead to multiple entries in the parsing table for the same (non-terminal, terminal) pair.
-
Left Factoring
- For any non-terminal
Awith two or more productions, the productions must not have a common prefix. If they do, left factoring must be applied. - That is, for any two productions
A -> α | β,FIRST(α) ∩ FIRST(β) = ∅.
- For any non-terminal
-
FIRST and FOLLOW Condition
- For each non-terminal
Awith productionsA -> α | β:FIRST(α) ∩ FIRST(β) = ∅- If
α =>* ε, thenFIRST(β) ∩ FOLLOW(A) = ∅
- This ensures that the parsing table has at most one production per cell M[A, a].
- For each non-terminal
-
Deterministic Parsing Table
- The LL(1) parsing table M[A, a] must have at most one entry for every non-terminal
Aand terminala. Multiple entries indicate grammar conflicts and disqualify the grammar from being LL(1).
- The LL(1) parsing table M[A, a] must have at most one entry for every non-terminal
-
Single Lookahead is Sufficient
- Only one input symbol of lookahead is needed at each step to determine the correct production to apply, making parsing efficient and backtrack-free.
Summary: A type expression represents the type of a language construct using basic types and constructors like arrays, products, and functions. LL(1) grammar must be non-left-recursive, unambiguous, left-factored, and must produce a conflict-free parsing table using only one lookahead symbol.
2080 · 10 marks
Differentiate between one-pass and multi-pass compiler. Construct the LL(1) parsing table for the following grammar.S→ABCDS \rightarrow ABCDS→ABCDA→a∣εA \rightarrow a | \varepsilonA→a∣εB→bB \rightarrow bB→bC→0∣εC \rightarrow 0 | \varepsilonC→0∣εD→d∣εD \rightarrow d | \varepsilonD→d∣ε[10]
2080 · 5 marks
Find the FIRST and FOLLOW of all the non terminals in following grammar. S→aAbcD∣εS \rightarrow aAbcD | \varepsilonS→aAbcD∣εA→SD∣εA \rightarrow SD | \varepsilonA→SD∣εC→SaC \rightarrow SaC→SaD→aBD∣εD \rightarrow aBD | \varepsilonD→aBD∣ε[5]
2075 · 6 marks
Differentiate between recursive descent and non-recursive predictive parsing method. Find first and follow of all the non-terminals in the following grammar.E→TA;A→+TA∣ε;T→FB;B→∗FB∣ε;F→(E)∣idE \rightarrow TA; A \rightarrow +TA|\varepsilon; T \rightarrow FB; B \rightarrow *FB|\varepsilon; F \rightarrow (E)|idE→TA;A→+TA∣ε;T→FB;B→∗FB∣ε;F→(E)∣id[6]
2081.1 · 5 marks
Compute the FIRST and FOLLOW of all the non-terminals in following grammar. S→ABS \rightarrow ABS→ABA→0A′∣1A′∣εA \rightarrow 0A' \mid 1A' \mid \varepsilonA→0A′∣1A′∣εA′→SSA′∣εA' \rightarrow SSA' \mid \varepsilonA′→SSA′∣εB→AS∣1B \rightarrow AS \mid 1B→AS∣1[5]
Show solved answerHide answer
FIRST and FOLLOW Computation
Given data (Grammar)
$$S \rightarrow AB$$ $$A \rightarrow 0A' \mid 1A' \mid \varepsilon$$ $$A' \rightarrow SSA' \mid \varepsilon$$ $$B \rightarrow AS \mid 1$$
Non-terminals: $S, A, A', B$
Terminals: $0, 1$
Start symbol: $S$
Step 1: FIRST Sets
FIRST(A)
From $A \rightarrow 0A' \mid 1A' \mid \varepsilon$: $$FIRST(A) = {0, 1, \varepsilon}$$
FIRST(B)
From $B \rightarrow AS \mid 1$:
- $B \rightarrow 1$ gives $1$
- $B \rightarrow AS$: add $FIRST(A)\setminus{\varepsilon} = {0,1}$; since $\varepsilon \in FIRST(A)$, also add $FIRST(S)$.
Since $S$ cannot derive $\varepsilon$ (needs both $A$ and $B$ to vanish, but $B$ cannot), $FIRST(S)$ adds only ${0,1}$: $$FIRST(B) = {0, 1}$$
FIRST(S)
From $S \rightarrow AB$:
- Add $FIRST(A)\setminus{\varepsilon} = {0,1}$
- Since $\varepsilon \in FIRST(A)$, add $FIRST(B) = {0,1}$
- $\varepsilon$ not added (B cannot derive $\varepsilon$) $$FIRST(S) = {0, 1}$$
FIRST(A')
From $A' \rightarrow SSA' \mid \varepsilon$:
- $A' \rightarrow \varepsilon$ gives $\varepsilon$
- $A' \rightarrow SSA'$: add $FIRST(S) = {0,1}$ $$FIRST(A') = {0, 1, \varepsilon}$$
Summary
| Non-terminal | FIRST |
|---|---|
| $S$ | ${0, 1}$ |
| $A$ | ${0, 1, \varepsilon}$ |
| $A'$ | ${0, 1, \varepsilon}$ |
| $B$ | ${0, 1}$ |
Step 2: FOLLOW Sets
Rules: Start gets $$$ $$; for $X\to \alpha Y\beta$ add $FIRST(\beta)\setminus{\varepsilon}$ to $FOLLOW(Y)$; if $\varepsilon\in FIRST(\beta)$ or $\beta$ empty, add $FOLLOW(X)$ to $FOLLOW(Y)$.
FOLLOW(S)
- Start symbol: add $$$ $$
- $A' \rightarrow SSA'$:
- First $S$ followed by $SA'$: add $FIRST(S)\setminus{\varepsilon}={0,1}$
- Second $S$ followed by $A'$: add $FIRST(A')\setminus{\varepsilon}={0,1}$; since $\varepsilon\in FIRST(A')$, add $FOLLOW(A')$
- $B \rightarrow AS$: $S$ at end, add $FOLLOW(B)$
$$FOLLOW(S) = {$, 0, 1} \cup FOLLOW(A') \cup FOLLOW(B)$$
FOLLOW(A)
- $S \rightarrow AB$: $A$ followed by $B$, add $FIRST(B)\setminus{\varepsilon}={0,1}$; $\varepsilon\notin FIRST(B)$, no more.
- $B \rightarrow AS$: $A$ followed by $S$, add $FIRST(S)\setminus{\varepsilon}={0,1}$; $\varepsilon\notin FIRST(S)$, no more. $$FOLLOW(A) = {0, 1}$$
FOLLOW(A')
- $A \rightarrow 0A' \mid 1A'$: $A'$ at end, add $FOLLOW(A)={0,1}$
- $A' \rightarrow SSA'$: $A'$ at end, add $FOLLOW(A')$ (itself, no new info) $$FOLLOW(A') = {0, 1}$$
FOLLOW(B)
- $S \rightarrow AB$: $B$ at end, add $FOLLOW(S)$ $$FOLLOW(B) = FOLLOW(S)$$
Resolve FOLLOW(S) and FOLLOW(B)
$$FOLLOW(S) = {$, 0, 1} \cup FOLLOW(A') \cup FOLLOW(B)$$ $$= {$, 0, 1} \cup {0,1} \cup FOLLOW(B)$$
Since $FOLLOW(B) = FOLLOW(S)$, this is self-referential and adds nothing new: $$FOLLOW(S) = {$, 0, 1}$$ $$FOLLOW(B) = {$, 0, 1}$$
Final Answer
| Non-terminal | FIRST | FOLLOW |
|---|---|---|
| $S$ | ${0, 1}$ | $${$, 0, 1}$$ |
| $A$ | ${0, 1, \varepsilon}$ | ${0, 1}$ |
| $A'$ | ${0, 1, \varepsilon}$ | ${0, 1}$ |
| $B$ | ${0, 1}$ | $${$, 0, 1}$$ |
2081.1 · 5 marks
Construct the LL(1) parsing table for the following grammar. S→AS1∣CS \rightarrow AS1 \mid CS→AS1∣CA→0A \rightarrow 0A→0C→2C∣εC \rightarrow 2C \mid \varepsilonC→2C∣ε[5]
Show solved answerHide answer
LL(1) Parsing Table Construction
Given Data
Grammar: $$S \rightarrow AS1 \mid C$$ $$A \rightarrow 0$$ $$C \rightarrow 2C \mid \varepsilon$$
Non-terminals: $S, A, C$; Terminals: $0, 1, 2$; End marker: $$$ $$.
Note: In $AS1$, the symbol $1$ is treated as a terminal.
Step 1: FIRST Sets
FIRST(A): $A \to 0 \Rightarrow$ FIRST(A) = ${0}$
FIRST(C): $C \to 2C$ gives $2$; $C \to \varepsilon$ gives $\varepsilon$ $$FIRST(C) = {2, \varepsilon}$$
FIRST(S):
- $S \to AS1$: FIRST(A) = ${0}$ (A is non-nullable), so add $0$
- $S \to C$: FIRST(C) = ${2, \varepsilon}$, add $2$ and $\varepsilon$ $$FIRST(S) = {0, 2, \varepsilon}$$
Step 2: FOLLOW Sets
Start: $$FOLLOW(S) \supseteq {$}$$
Production $S \to AS1$:
- After $A$ is $S$: $FOLLOW(A) \supseteq FIRST(S)\setminus{\varepsilon} = {0,2}$. Since $\varepsilon \in FIRST(S)$, continue to next symbol $1$: add ${1}$. So $FOLLOW(A) \supseteq {0,2,1}$.
- After inner $S$ is $1$: $FOLLOW(S) \supseteq {1}$
Production $S \to C$: $FOLLOW(C) \supseteq FOLLOW(S)$
Production $C \to 2C$: After $C$ is nothing: $FOLLOW(C) \supseteq FOLLOW(C)$ (no change)
Final: $$FOLLOW(S) = {1, $}$$ $$FOLLOW(A) = {0, 1, 2}$$ $$FOLLOW(C) = {1, $}$$
Step 3: PREDICT (SELECT) Sets
| Production | FIRST(RHS) | ε in FIRST? | FOLLOW(LHS) | Predict Set |
|---|---|---|---|---|
| $S \to AS1$ | ${0}$ | No | - | ${0}$ |
| $S \to C$ | ${2,\varepsilon}$ | Yes | $${1,$}$$ | $${2, 1, $}$$ |
| $A \to 0$ | ${0}$ | No | - | ${0}$ |
| $C \to 2C$ | ${2}$ | No | - | ${2}$ |
| $C \to \varepsilon$ | ${\varepsilon}$ | Yes | $${1,$}$$ | $${1, $}$$ |
Step 4: LL(1) Parsing Table
| NT | 0 | 1 | 2 | $$$ $$ |
|---|---|---|---|---|
| S | $S \to AS1$ | $S \to C$ | $S \to C$ | $S \to C$ |
| A | $A \to 0$ | |||
| C | $C \to \varepsilon$ | $C \to 2C$ | $C \to \varepsilon$ |
Verification
Each cell holds at most one production, so no conflict exists. The grammar is LL(1).
Specification and Recognition of tokens
2080 · 10 marks
How does a Lexical Analyzer recognize a token? Give an example to make it clear. Convert the regular expression $a(a+b)(b+c)⭒a# to DFA.[10]
Syntax directed definitions
2080 · 5 marks
Describe about syntax directed translation with an example. [5]
Annotated Parse Tree
2080 · 5 marks
What is annotated parse tree? Define S-attributed grammar with an example. [5]
Finite Automata relevant to compiler construction syntactic specification of languages
2078 · 10 marks
List out the tasks performed by Lexical Analyser. Define DFA. Convert the Regular Expression (a+b)∗a(a+b)(a+b)^*a(a+b)(a+b)∗a(a+b) to DFA directly.[10]
2076 · 6 marks
Given a regular expression (ε+0)∗10(\varepsilon + 0)^* 10(ε+0)∗10. Construct the DFA recognizing the pattern described by this regular expression using syntax tree based reduction.[6]
2075 · 6 marks
List out the major tasks carried out in Lexical Analysis Phase. Convert the following NFA to DFA.[6]
Type Checking and Conversion
2078 · 10 marks
Define type checking. Differentiate between type casting and coercion? Write SDT to carry out type checking for the following expression. $E \rightarrow n \mid E * E \mid E == E \mid E[E] \mid E \uparrow$ [10]
2076 · 6 marks
Write Syntax Directed Definition to carry out type checking for the following expression.E→id∣E1 op E2∣E1 relop E2∣E1[E2]∣E1↑E \rightarrow id | E1 \text{ op } E2 | E1 \text{ relop } E2 | E1[E2] | E1↑E→id∣E1 op E2∣E1 relop E2∣E1[E2]∣E1↑[6]
2075 · 6 marks
Differentiate between static and dynamic type checking. How can we carry out type checking for the following expression using syntax-directed definition?
$S \rightarrow id = E$
$S \rightarrow \text{if } E \text{ then } S1$
$S \rightarrow \text{while } E \text{ do } S1$
$S \rightarrow S1; S2$
[6]
2081.1 · 5 marks
Define explicit and implicit type conversion. Why do we need to check type of the system? Justify with an example. [5]
Show solved answerHide answer
Type Conversion and Type Checking
Explicit Type Conversion
Explicit type conversion (also called type casting) is a conversion that is manually performed by the programmer by writing a specific instruction in the source code. The programmer explicitly specifies the target type to which a value should be converted.
Example:
int a = 10;
float b = (float) a; // programmer explicitly casts int to float
Implicit Type Conversion
Implicit type conversion (also called type coercion) is a conversion that is automatically performed by the compiler without any explicit instruction from the programmer. The compiler applies conversion rules defined by the type system when operands of different types are used together.
Example:
int a = 5;
float b = 3.2;
float c = a + b; // compiler automatically converts 'a' to float
Here, the integer a is automatically promoted to float before the addition is performed.
Why Do We Need to Check the Type of a System?
The collection of different data types and their associated rules to assign types to programming language constructs is known as type systems. A type checker implements a type system.
Type checking is necessary for the following reasons:
1. Ensures Type Correctness
Type checking verifies that operations are applied to compatible types. Without it, meaningless operations (such as adding a string to an integer) could go undetected.
2. Prevents Runtime Errors
Catching type mismatches at compile time avoids unexpected crashes or incorrect results at runtime.
3. Enforces Language Rules
Type systems define informal rules such as:
"If both operands of addition are of type integer, then the result is of type integer."
The type checker enforces these rules consistently across the program.
4. Supports Semantic Correctness
Even if a program is syntactically correct, it may be semantically wrong due to type mismatches. Type checking adds a layer of semantic validation.
Justification with an Example
Consider the following expression:
int x = 5;
char ch = 'A';
int result = x + ch;
Without type checking:
The compiler would not know whether adding an int and a char is valid, and the result type would be undefined or erroneous.
With type checking: The type checker applies the rule:
| Operand 1 | Operand 2 | Operation | Result Type |
|---|---|---|---|
int | char | + | int (char is coerced to its ASCII integer value) |
The type checker detects that char can be implicitly converted to int (ASCII value of 'A' = 65), so:
result = 5 + 65 = 70
This is a valid, well-typed expression. If instead we wrote:
int x = 5;
char *str = "hello";
int result = x + str; // TYPE ERROR
The type checker would flag this as a type error because adding an integer and a string pointer violates the type rules, preventing a potential runtime crash.
Summary
| Feature | Explicit Conversion | Implicit Conversion |
|---|---|---|
| Initiated by | Programmer | Compiler |
| Also known as | Type casting | Type coercion |
| Risk | Possible data loss if misused | May cause unintended behavior |
Type checking is essential to ensure that every operation in a program is applied to operands of appropriate and compatible types, making programs safe, correct, and predictable.
Bottom-up parsing
2078 · 5 marks
What are the disadvantages of shift reduce parsing. Perform shift reduce parsing of string w = (x-x). (x/x) for given grammar. E→E−E∣E/E∣(E)∣xE \rightarrow E-E | E/E | (E) | xE→E−E∣E/E∣(E)∣x[5]
2076 · 6 marks
What is shift reduce parsing techniques? Show shift reduce parsing action for the string (x+x)*a, given the grammar[6]
Make Unit 2 stick
Practice CSC376 with flashcards & quizzes