2 Lexical Syntax And Semantic Analysis

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.

Lexical, Syntax and Semantic Analysis: notes

Lexical Analysis: Its role

Lexical analysis (also called scanning) is the first phase of a compiler. The lexical analyzer reads the source program left to right, one character at a time, and groups characters into lexemes, the actual substrings of the source text that match a pattern. For each lexeme it produces a token, of the form <token-name, attribute-value>, and hands the token stream to the parser one token at a time, typically through a getNextToken call issued by the parser whenever it needs the next symbol. Because it is the component that scans the raw text, the lexical analyzer is also the natural place to strip out whitespace and comments, since these carry no grammatical meaning, and to record line numbers for later error messages. It works closely with the symbol table: when it recognizes an identifier lexeme, it enters that lexeme into the symbol table (if not already present) and attaches a pointer to the table entry as the token's attribute value, so that later phases can retrieve everything known about that identifier from one place. Separating lexical analysis into its own phase, rather than having the parser read raw characters, simplifies the design of the parser, improves compiler efficiency (specialized buffering and matching techniques speed up scanning), and improves portability, since only the scanner needs to change for a different character set or input device.

Specification and Recognition of tokens

A token is a category of lexical unit, such as a keyword, identifier, operator or literal; a pattern is the rule, generally written as a regular expression, that describes the set of possible lexemes for a token; and a lexeme is the specific sequence of characters in the source program that matches a token's pattern. For the code fragment

int largest(int x, int y) {
    if (x > y)
        return x;
}

the analyzer recognizes lexemes and reports them as tokens roughly as follows.

LexemeToken
intkeyword
largestidentifier
(punctuation
xidentifier
,punctuation
)punctuation
{punctuation
ifkeyword
>relop
returnkeyword

Not every substring of the source becomes a token: comments (// this compares two numbers) and preprocessor directives (#include <stdio.h>) are recognized and discarded by the scanner (or, for directives, handed to the preprocessor) rather than passed on as tokens. Token patterns are specified with regular expressions over the source alphabet. A regular definition gives a name to a regular expression and allows later regular expressions to refer to that name, which is how the patterns for whole token classes are built up cleanly; for example, an identifier in a C-like language is defined by $$ \begin{aligned} \text{letter} &\to [A\text{-}Za\text{-}z_] \ \text{digit} &\to [0\text{-}9] \ \text{id} &\to \text{letter}(\text{letter} \mid \text{digit})^{*} \end{aligned} $$

so that any lexeme matching this pattern, x, largest, sum1, is recognized and returned as an id token, with the actual characters, and a pointer to its symbol table entry, carried as the token's attribute. Recognition of tokens is then the algorithmic problem of taking these regular expressions and building a program (in practice, a finite automaton) that decides, for the characters remaining in the input, which pattern the next lexeme matches and how long that lexeme is; this is developed fully once finite automata are introduced below.

Input Buffer

Because the lexical analyzer must look at the source program character by character, and sometimes needs to look one or more characters beyond the end of the current lexeme before it can decide the lexeme is complete, compilers use a specialized input buffering scheme rather than reading the source file character by character from disk. The buffer is commonly organized as two halves, each of a fixed size such as 4096 bytes, filled by a single system read call; two pointers move across this buffer:

  • the lexeme beginning pointer, which marks the start of the lexeme currently being scanned, and
  • the forward pointer, which scans ahead until the pattern for the current token is matched, sometimes having to look one or more characters past the actual end of the lexeme.

Whenever the forward pointer reaches the end of one half of the buffer, the other half is refilled with new input from the source, and if the forward pointer reaches the end of the second half, buffering wraps back to refill the first half, so long as the flow of tokens keeps up with the disk reads. To avoid checking, on every single character, whether the forward pointer has run off the end of a buffer half, each half is terminated with a special sentinel character (conventionally eof, distinct from any character that can appear in real source text). The forward pointer can then be advanced blindly and its character tested once; only if that character happens to be the sentinel does the scanner do the extra work of checking which buffer half just ended and reloading the other half, which cuts the number of tests per character from two down to effectively one in the common case. This buffering discipline matters most where a token's pattern requires lookahead beyond the lexeme itself, for instance distinguishing the single character operator < from the two character operator <=: the scanner must look at the character after < before it can commit to a token, and the buffer with its sentinel is what makes this efficient and safe to do repeatedly.

Finite Automata relevant to compiler construction syntactic specification of languages

A regular expression describes a language over an alphabet by combining single symbols with three operations: union ($r_1 \mid r_2$, either pattern), concatenation ($r_1 r_2$, one pattern followed by the other), and Kleene closure ($r^{*}$, zero or more repetitions of the pattern). Every regular expression can be recognized by a finite automaton, a formal machine used to decide, for an input string, whether it belongs to the language.

A nondeterministic finite automaton (NFA) is a 5-tuple $(Q, \Sigma, \delta, q_0, F)$ where $Q$ is a finite set of states, $\Sigma$ is the input alphabet, $q_0 \in Q$ is the start state, $F \subseteq Q$ is the set of accepting states, and $\delta$ is a transition function that may map a state and an input symbol (or the empty string $\varepsilon$) to a set of possible next states, so from a given state on a given symbol there can be zero, one, or many transitions, including silent $\varepsilon$-moves that consume no input. A deterministic finite automaton (DFA) is the special case where $\delta$ maps each state and input symbol to exactly one next state and no $\varepsilon$-moves are allowed, which is why a DFA can be run directly, character by character, with no backtracking or branching.

Thompson's construction builds an NFA for a regular expression compositionally, following the structure of the expression:

  • for a single symbol $a$, build two states joined by one edge labelled $a$;
  • for concatenation $r_1 r_2$, build the NFAs for $r_1$ and $r_2$ separately and join the accepting state of $r_1$'s NFA to the start state of $r_2$'s NFA with an $\varepsilon$-move;
  • for union $r_1 \mid r_2$, add a new start state with $\varepsilon$-moves to both sub-NFAs' start states, and a new accepting state reached by $\varepsilon$-moves from both sub-NFAs' accepting states;
  • for Kleene closure $r^{*}$, add a new start and accepting state, an $\varepsilon$-move from the new start directly to the new accepting state (to allow zero repetitions), an $\varepsilon$-move from the new start into the sub-NFA's start state, and an $\varepsilon$-move from the sub-NFA's accepting state both back into its own start state (to allow repetition) and forward to the new accepting state.

Applying these rules to the classic pattern $(a \mid b)^{*}abb$ (any mix of as and bs, followed by the fixed suffix abb, a pattern with exactly the shape used to recognize, say, a keyword that must be preceded only by letters and end in a specific suffix) gives an NFA with 14 states built from an a|b fragment concatenated with three literal fragments for a, b, b:

From stateOnTo state
0a1
2b3
4$\varepsilon$0, 2
1, 3$\varepsilon$5
5$\varepsilon$4, 7
6$\varepsilon$4, 7
7$\varepsilon$8
8a9
9$\varepsilon$10
10b11
11$\varepsilon$12
12b13

with start state 6 and accepting state 13. Converting this NFA into a DFA that can be run without branching is the subset construction: each DFA state is the set of NFA states reachable from the previous DFA state on the current input symbol, closed under $\varepsilon$-moves (the $\varepsilon$-closure). Starting from the $\varepsilon$-closure of the NFA start state and repeatedly computing the $\varepsilon$-closure of the move on each symbol of the alphabet until no new sets appear, this construction on the NFA above yields a 5 state DFA:

DFA stateNFA stateson aon baccepting
$D_0$0, 2, 4, 6, 7, 8$D_1$$D_2$no
$D_1$0, 1, 2, 4, 5, 7, 8, 9, 10$D_1$$D_3$no
$D_2$0, 2, 3, 4, 5, 7, 8$D_1$$D_2$no
$D_3$0, 2, 3, 4, 5, 7, 8, 11, 12$D_1$$D_4$no
$D_4$0, 2, 3, 4, 5, 7, 8, 13$D_1$$D_2$yes

with $D_0$ the start state and $D_4$, the only state whose NFA set contains the NFA's accepting state 13, the accepting state. Running this DFA on abb moves $D_0 \xrightarrow{a} D_1 \xrightarrow{b} D_3 \xrightarrow{b} D_4$, ending in the accepting state, so abb is accepted; similarly aabb and babb are accepted (they still end in $D_4$), while ab, a, and abab all end in a non-accepting state and are correctly rejected.

Optimization of DFA based pattern matchers

A DFA obtained directly by subset construction is not necessarily the smallest DFA for the same language: several of its states may behave identically for every possible remaining input, and merging such equivalent states shrinks the automaton (and the pattern-matching table a lexical analyzer generator would build from it) without changing the language it recognizes. Two states are equivalent if, for every input string, starting from either one leads to acceptance or to rejection together. DFA minimization finds this equivalence by partition refinement: start with two blocks, the accepting states and the non-accepting states, and repeatedly split any block whose states do not all go to the same current block on the same input symbol, continuing until no block can be split further.

Applied to the 5 state DFA above, states $D_0$ and $D_2$ turn out to be equivalent (both are non-accepting, and both go to $D_1$ on a and to their own block on b), so the minimization merges them, producing a 4 state minimal DFA:

Minimal stateMergeson aon baccepting
$M_1$ (start)$D_0, D_2$$M_2$$M_1$no
$M_2$$D_1$$M_2$$M_3$no
$M_3$$D_3$$M_2$$M_0$no
$M_0$$D_4$$M_2$$M_1$yes

Re-running the earlier test strings on this minimized automaton reaches exactly the same accept or reject verdict as the unminimized DFA for every one of them, confirming the minimization preserved the language while reducing the state count from 5 to 4. In a real lexical analyzer generator (such as Lex), this same idea is applied at scale: the patterns for every token class in the language are combined into one NFA (by unioning them behind a single new start state), converted to a DFA by subset construction, and minimized, with two extra conventions layered on top to resolve the fact that many different lexemes can now reach an accepting state: the longest match rule, where the analyzer always consumes the longest lexeme matching some pattern, and a priority rule, where if the longest match satisfies more than one token's pattern (for instance both a keyword and the general identifier pattern), the token listed first in the specification wins, which is exactly how a scanner is normally told to prefer the keyword if over treating it as a plain identifier.

Syntax Analysis: Its role

Syntax analysis (parsing) is the phase that takes the token stream produced by the lexical analyzer and determines whether it can be generated by the grammar of the source language, and if so, builds a tree, the parse tree, that exposes the grammatical structure of that derivation. The parser efficiently detects syntax errors, since a token stream that cannot be derived from the grammar signals a construct the language does not allow, and a well engineered parser reports such an error with enough context (typically the offending token and its line number) to be useful, and then attempts error recovery so that scanning for further errors in the same file can continue rather than stopping at the first fault. Structurally, the parser sits between the lexical analyzer, from which it requests tokens one at a time, and the rest of the front end (semantic analysis and intermediate code generation), to which it hands off the parse tree, or more commonly a compacted abstract syntax tree, or increasingly performs semantic checks and intermediate code generation directly as it recognizes each grammar rule, discussed in the sections on syntax directed translation below.

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 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$: $; from L -> L,E: ,; and E inherits from L -> E where L is followed by ) and ,)
  • $\text{FOLLOW}(L) = { ),\ ,\ }$ (from E -> (L): ); from L -> 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),$EL
0s2s31
1acc
2s2s354
3r2r2r2
4s6s7
5r4r4
6r1r1r1
7s2s38
8r3r3

Notes:

  • Reductions by production (2) E->a and (1) E->(L) appear on FOLLOW(E) = { ), , , $ }.
  • Reductions by production (4) L->E and (3) L->L,E appear on FOLLOW(L) = { ), , }.

The table has no multiply-defined entries, so the grammar is SLR(1).

Open this answer on its own page →

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 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

StateOn SOn AOn aOn 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.

Open this answer on its own page →

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]

Number the productions: - (0) $S' \to S$ - (1) $S \to AaAb$ - (2) $A \to BbBa$ - (3) $A \to \varepsilon$ - (4) $B \to \varepsilon$ Terminals: $$a, b, $ $$. Non-terminals: $S', S, A, B$. - $\text{FIRST}(B) = {\varepsilon}$ - $\text{FIRST}(A)$: from $A \to BbBa$, since $B \Rightarrow \varepsilon...

Open this answer on its own page →

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} $$

Grammar: - (1) $E \rightarrow T + E$ - (2) $E \rightarrow T$ - (3) $T \rightarrow int T$ - (4) $T \rightarrow int$ - (5) $T \rightarrow (E)$ Input string: int ( int + int ) $ Parsing table (as given): STATE int + ( ) $ E T --------------------------- 1 S5 S4 2 3 2 ACC 3 S6 R2 R2 4 S5 S4 7 3 5 S8...

Open this answer on its own page →

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]

S.N. LR(0) LR(1) -------------------- 1 Item has no look-ahead: form $[A \to \alpha.\beta]$ Item carries a look-ahead: form $[A \to \alpha.\beta, a]$ 2 Reductions applied on all input symbols (LR(0)/SLR use FOLLOW) Reduction applied only on the item's specific look-ahead 3 Less powerful; more shi...

Open this answer on its own page →

2076 · 6 marks

Construct SLR parsing table for the following grammar.S→aAa∣bAb∣baS \rightarrow aAa | bAb | baS→aAa∣bAb∣ba[6]

The grammar as given is: $$S \rightarrow aAa \mid bAb \mid ba$$ The nonterminal $A$ appears on the right-hand side but no productions for $A$ are given. A grammar with an undefined nonterminal is incomplete and cannot generate a language or produce a valid parsing table. This is a well-known stan...

Open this answer on its own page →

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]

Grammar: - $S \rightarrow E$ - $E \rightarrow E + T \mid T$ - $T \rightarrow T F \mid F$ - $F \rightarrow id$ Terminals: ${+, , id}$, plus endmarker $$$ $$ Non-terminals: ${S, E, T, F}$ $

Open this answer on its own page →

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 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

StateAction 0Action $Goto SGoto A
0s3 / r3r312
1acc
2s5r34
3s3 / r3r36
4r1
5s5r37
6r2r2
7r2

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).

Open this answer on its own page →

2081.1 · 5 marks

What is a symbol table? Discuss the general structure of an LR parser. [5]

Show solved 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

ComponentDescription
Input BufferContains the input string followed by $ (end marker)
StackStores states and grammar symbols (terminals or non-terminals)
Action TableA 2D table indexed by [state, terminal]; gives shift, reduce, accept, or error
Goto TableA 2D table indexed by [state, non-terminal]; gives the next state after a reduction
OutputA production rule representing a step in the derivation sequence

Working of LR Parser

  1. The parser starts with an initial state S0 on the stack.
  2. It reads the current input symbol a and the top state Sm.
  3. 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.
  4. 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.

Open this answer on its own page →

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]

Grammar: - $A \to BB$ - $B \to bB \mid a$ Start symbol: $A$. Terminals: ${a, b}$. Non-terminals: ${A, B}$. - $(0)\ A' \to A$ - $(1)\ A \to BB$ - $(2)\ B \to bB$ - $(3)\ B \to a$ $I0 = \text{Closure}({A' \to \cdot A})$ $A' \to \cdot A$ adds $A \to \cdot BB$; dot before $B$ adds

Open this answer on its own page →

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]

Grammar: $$S \rightarrow (L) \mid 1$$ $$L \rightarrow L,;,S \mid \varepsilon$$ - Non-terminals: $S$, $L$ - Terminals: $($, $)$, $1$, $;$ - Start symbol: $S$ --- FIRST(S): - $S \rightarrow (L)$ gives first symbol $($ - $S \rightarrow 1$ gives first symbol $1$ $$FIRST(S) = {\ (,\ 1\ }$$ FIRST(L...

Open this answer on its own page →

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]

Grammar productions: - $S \rightarrow SB \mid Ca$ - $B \rightarrow Bb \mid c$ - $C \rightarrow aB \mid a$ A grammar is left recursive if it contains a non-terminal $A$ such that there is a derivation $A \Rightarrow^{+} A\alpha$ for some string $\alpha$ of grammar symbols. In the simplest (immedia...

Open this answer on its own page →

Attribute Types

2081 · 5 marks

Describe the synthesized attribute and inherited attribute with an example. [5]

Definition: Attributes of a node that are derived from its children nodes are called synthesized attributes. - Information flows bottom-up in the parse tree (from children to parent). - A node's attribute value is computed from the attribute values of its children. Definition: Attributes which ar...

Open this answer on its own page →

2078 · 5 marks

Define attribute grammar with example of inherited and synthesized attributes. [5]

An attribute grammar (also called a Syntax-Directed Definition, SDD) is a context-free grammar together with attributes and semantic rules, where: - Attributes are associated with grammar symbols (terminals and non-terminals) - Semantic rules are associated with productions It is a generalization...

Open this answer on its own page →

2081.1 · 5 marks

Differentiate between synthesized and inherited attributes with example. [5]

Attributes of a node that are derived from its children nodes are called synthesized attributes. - Information flows bottom-up in the parse tree (from children to parent). - A node's attribute value is computed from the attribute values of its children. Attributes which are derived from the paren...

Open this answer on its own page →

Top-down parsing

2081 · 5 marks

What is a type expression? List the properties of LL(1) grammar. [5]

Show solved 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:

  1. Basic Types

    • Primitive types such as int, float, char, bool, etc.
    • A special basic type error is used to signal type errors.
  2. Arrays

    • If T is a type expression, then array(I, T) is a type expression denoting an array with elements of type T and index set I.
    • Example: array(0...99, int)
  3. Products

    • If T1 and T2 are type expressions, then their Cartesian product T1 x T2 is a type expression.
    • Example: int x int
  4. Pointers

    • If T is a type expression, then pointer(T) is a type expression denoting the type "pointer to an object of type T".
  5. Functions

    • A function maps a domain type to a range type, expressed as T1 -> T2.

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:

  1. 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.
  2. 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.
  3. Left Factoring

    • For any non-terminal A with 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(β) = ∅.
  4. FIRST and FOLLOW Condition

    • For each non-terminal A with productions A -> α | β:
      • FIRST(α) ∩ FIRST(β) = ∅
      • If α =>* ε, then FIRST(β) ∩ FOLLOW(A) = ∅
    • This ensures that the parsing table has at most one production per cell M[A, a].
  5. Deterministic Parsing Table

    • The LL(1) parsing table M[A, a] must have at most one entry for every non-terminal A and terminal a. Multiple entries indicate grammar conflicts and disqualify the grammar from being LL(1).
  6. 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.

Open this answer on its own page →

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]

Feature One-Pass Compiler Multi-Pass Compiler --------- Number of scans Scans source exactly once Scans source/intermediate form multiple times Speed Faster compilation Slower (multiple traversals) Memory usage Requires less memory Requires more memory (intermediate results stored) Optimization L...

Open this answer on its own page →

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]

Grammar productions: $$S \rightarrow aAbcD \mid \varepsilon$$ $$A \rightarrow SD \mid \varepsilon$$ $$C \rightarrow Sa$$ $$D \rightarrow aBD \mid \varepsilon$$ Non-terminals present in productions: $S, A, C, D$ (and $B$ appears on the RHS of $D \rightarrow aBD$). Missing data note: The non-termin...

Open this answer on its own page →

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]

Grammar: $$E \rightarrow TA$$ $$A \rightarrow +TA \mid \varepsilon$$ $$T \rightarrow FB$$ $$B \rightarrow FB \mid \varepsilon$$ $$F \rightarrow (E) \mid \text{id}$$ Non-terminals: $E, A, T, B, F$. Terminals: $+, , (, ), \text{id}$. --- Basis Recursive Descent Parser Non-Recursive Predictive Parse...

Open this answer on its own page →

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 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-terminalFIRST
$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-terminalFIRSTFOLLOW
$S$${0, 1}$$${$, 0, 1}$$
$A$${0, 1, \varepsilon}$${0, 1}$
$A'$${0, 1, \varepsilon}$${0, 1}$
$B$${0, 1}$$${$, 0, 1}$$
Open this answer on its own page →

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 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

ProductionFIRST(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

NT012$$$ $$
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).

Open this answer on its own page →

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]

--- A Lexical Analyzer (scanner) reads the source program character by character from left to right, groups sequences of characters into meaningful units called lexemes, and classifies each lexeme into a token by matching it against predefined patterns (specified using Regular Expressions). Term ...

Open this answer on its own page →

Syntax directed definitions

2080 · 5 marks

Describe about syntax directed translation with an example. [5]

Syntax Directed Translation (SDT) refers to a method of compiler implementation where the source language translation is completely driven by the parser. In SDT, a parse tree or syntax tree is constructed and the values of attributes at the nodes of the tree are computed by visiting them in a spe...

Open this answer on its own page →

Annotated Parse Tree

2080 · 5 marks

What is annotated parse tree? Define S-attributed grammar with an example. [5]

--- An annotated parse tree is a parse tree in which each node is labeled with its grammar symbol along with the values of its associated attributes. In Syntax-Directed Translation (SDT), semantic rules are used to compute attribute values at each node of the parse tree. When these computed attri...

Open this answer on its own page →

2076 · 6 marks

Syntax Directed Definition and Annotated Parse Tree

A Syntax-Directed Definition (SDD) is a context-free grammar in which each grammar symbol is associated with a set of attributes, and each production is associated with a set of semantic rules for computing the values of those attributes. - Attributes may be synthesized (computed from the attribu...

Open this answer on its own page →

2075 · 6 marks

Syntax Directed Definition and Annotated Parse Tree

A Syntax-Directed Definition (SDD) is a context-free grammar in which each grammar symbol is associated with a set of attributes, and each production is associated with a set of semantic rules for computing the values of those attributes. - Attributes may be synthesized (computed from children) o...

Open this answer on its own page →

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]

  • RE to convert (canonical/deduplicated form): $r = (a+b)^,a,(a+b)$ - Alphabet: $\Sigma = {a, b}$ - Marks: 10 Note: The question string repeats the pattern; the intended standard example is $(a+b)^a(a+b)$. --- 1. Scanning the source program character by character. 2. Tokenization - grouping c...
Open this answer on its own page →

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]

Append the end marker : $$(\varepsilon+0)^ \cdot 1 \cdot 0 \cdot (\varepsilon+0)^ \cdot 1 \cdot 0 \cdot $$ Assign position numbers to terminal leaves ($\varepsilon$ leaves get none): Symbol Position ------------------ $0$ (first star) 1 $1$ (first) 2 $0$ (first) 3 $0$ (second star) 4 $1$ (second...

Open this answer on its own page →

2075 · 6 marks

List out the major tasks carried out in Lexical Analysis Phase. Convert the following NFA to DFA.[6]

Part 1: Conceptual question - list major tasks of the lexical analysis phase. Part 2: "Convert the following NFA to DFA." - Missing data: The actual NFA (state transition diagram or table) is not present in the question text provided. No states, transitions, start state, or final states are suppl...

Open this answer on its own page →

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]

--- Type checking is the process performed during semantic analysis where the compiler verifies that each operator in an expression has operands of compatible (matching) types as defined by the language specification. - It ensures that operations are applied to operands of appropriate types. - If...

Open this answer on its own page →

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]

Type checking is a key part of semantic analysis. A Syntax-Directed Definition (SDD) associates attributes with grammar symbols and semantic rules with productions. For type checking, each expression E carries a synthesized attribute E.type that is computed bottom-up. --- Symbol Meaning ---------...

Open this answer on its own page →

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]

--- Type checking is the process of verifying that each operation in a program receives the correct number and type of operands. Feature Static Type Checking Dynamic Type Checking --------- When performed At compile time At run time Speed Faster execution (errors caught early) Slower (overhead at...

Open this answer on its own page →

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 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 1Operand 2OperationResult Type
intchar+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

FeatureExplicit ConversionImplicit Conversion
Initiated byProgrammerCompiler
Also known asType castingType coercion
RiskPossible data loss if misusedMay 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.

Open this answer on its own page →

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]

Grammar: $$E \rightarrow E - E \mid E / E \mid (E) \mid x$$ Input string: $w = (x-x).(x/x)$ Terminals visible in string: (, ), x, -, /, . Note on missing data: The grammar defines operators - and / only. The string contains a . (dot) operator between the two parenthesized expressions. There is no...

Open this answer on its own page →

2076 · 6 marks

What is shift reduce parsing techniques? Show shift reduce parsing action for the string (x+x)*a, given the grammar[6]

  • String to parse: (x+x)a - Grammar: Not explicitly printed in the question (the phrase "given the grammar" appears but no production rules follow). The standard expression grammar suitable for this string is assumed and stated explicitly below. This is the only missing item. Assumed grammar (sta...
Open this answer on its own page →