CS606 – Compiler Construction: Midterm Important Subjective (26 Solved Q&As)
Computer Science • Read every solved subjective question with its model answer directly on this page. Free, no login required.
All 664 Midterm Packs · CS606 Course Page · CS606 MCQ Pack (109 MCQs)
-
Write a regular expression for the language of all words that start and end with different letters. (Marks: 2)
Topic: Core Subjective Topics
Over the alphabet {a, b}, such a word has at least two letters: it either starts with a and ends with b, or starts with b and ends with a, with any string of a's and b's in between. Regular expression: a(a|b)*b | b(a|b)*a
-
Considering the following grammar, calculate the FIRST set of the non-terminals S, A and B. (Marks: 3) S → A B A → a | ε B → b | ε
Topic: Core Subjective Topics
FIRST(A) = {a, ε} and FIRST(B) = {b, ε}, read directly from their productions. For S → A B: FIRST(S) gets 'a' from FIRST(A). Since A is nullable (ε ∈ FIRST(A)), it also gets 'b' from FIRST(B). Since B is also nullable, ε is included as well. FIRST(S) = {a, b, ε}
-
Considering the string "ab", show that the following grammar is ambiguous using parse trees. The ε below is epsilon. (Marks: 5) S → A B A B A → a A | ε B → b B | ε
Topic: Core Subjective Topics
The string "ab" has two different parse trees. Parse tree 1: the first A derives 'a' (A → aA → a), the first B derives 'b' (B → bB → b), and the second A and second B both derive ε. Parse tree 2: the first A and first B both derive ε, the second A derives 'a' (A → aA → a) and the second B derives 'b' (B → bB → b). Since the same string has two distinct parse trees (two different leftmost derivations), the grammar is ambiguous.
-
Can we call shift-reduce parsing as bottom-up parsing? Justify your answer with reason. (Marks: 3)
Topic: Core Subjective Topics
Yes. Shift-reduce parsing is the standard implementation technique of bottom-up parsing. A bottom-up parser builds the parse tree starting from the leaves (the input tokens) and works up to the root (the start symbol), which is exactly what a shift-reduce parser does: it shifts input symbols onto a stack and, whenever the top of the stack forms the right-hand side of a production (a handle), it reduces it to the corresponding non-terminal. This process traces a rightmost derivation in reverse, ending when the stack contains only the start symbol and the input is exhausted.
-
How does the linker play an important role with respect to compiler construction? (Marks: 2)
Topic: Core Subjective Topics
A compiler translates each source module separately into relocatable object code, which contains unresolved references to functions and data defined in other modules or in libraries. The linker combines these object files and the required library routines, resolves all cross-references between modules, and relocates addresses so that the pieces form one consistent executable program. Without the linker, separately compiled modules and library functions (such as printf) could not be joined into a runnable program, and large programs could not be built from independently compiled parts.
-
Suppose you are going to construct a compiler for a regular language and currently you are constructing a suitable predictive parser from the grammar. If you have a production rule which is not clear to expand a non-terminal, then how will you handle this situation and what will you name this procedure? (Marks: 5)
Topic: Core Subjective Topics
When a non-terminal A has several productions and it is not clear which one to expand, the parser looks at the next input symbol (the lookahead symbol) and selects the production whose FIRST set contains that lookahead symbol. If the lookahead is in no FIRST set but A is nullable, the production is chosen using FOLLOW(A): if the lookahead belongs to FOLLOW(A), A is expanded to ε. This procedure of choosing the correct production by looking ahead at the input, without any backtracking, is called predictive parsing; it is implemented either as a recursive-descent parser or as a table-driven LL(1) parser using a predictive parsing table. If two productions of A have the lookahead in their FIRST sets, the grammar is not LL(1) and must first be rewritten (for example by left factoring).
-
Given the following grammar and the input string "bool id , id , id": (Marks: 20) Decl → Type IdList Type → bool | int | float IdList → IdList , id | id a) Show the leftmost derivation of the input string. b) Show the parse tree of the input string. c) Create a new equivalent grammar that has left recursion removed. d) Show the parse tree for the above input string on the new grammar.
Topic: Core Subjective Topics
a) Leftmost derivation: Decl ⇒ Type IdList ⇒ bool IdList ⇒ bool IdList , id ⇒ bool IdList , id , id ⇒ bool id , id , id b) Parse tree: Decl Type bool IdList IdList IdList id , id , id c) Removing the left recursion from IdList → IdList , id | id gives the equivalent grammar: IdList → id IdList' IdList' → , id IdList' | ε (Decl and Type remain unchanged.) d) Parse tree on the new grammar: Decl Type bool IdList id IdList' , id IdList' , id IdList' ε
-
Find the FIRST and FOLLOW sets for the following grammar: (Marks: 10) Exp → – Exp | ( Exp ) | Var ExpTail ExpTail → – Exp | ε Var → id VarTail VarTail → ( Exp ) | ε
Topic: Core Subjective Topics
FIRST sets: FIRST(Exp) = {–, (, id} (from its three productions) FIRST(ExpTail) = {–, ε} FIRST(Var) = {id} FIRST(VarTail) = {(, ε} FOLLOW sets: Exp is the start symbol, so $ ∈ FOLLOW(Exp); Exp also appears inside ( Exp ), giving ')'. FOLLOW(Exp) = {), $} FOLLOW(ExpTail) = FOLLOW(Exp) = {), $} (ExpTail ends the production Exp → Var ExpTail) FOLLOW(Var) = FIRST(ExpTail) without ε, plus FOLLOW(Exp) because ExpTail is nullable = {–, ), $} FOLLOW(VarTail) = FOLLOW(Var) = {–, ), $}
-
Consider the following grammar of lists. There are four different terminals: "(", ")", "a" and ",". (Marks: 15) S → ( ) | a | ( A ) A → S | A , S a) Show that the grammar is not LL(1). (Hint: compute some of the FIRST sets.) b) Rewrite the grammar so that it is suitable for recursive descent parsing. c) If you were going to build a table-driven top-down parser for the grammar from (b), how big would the table be (how many entries would it have)?
Topic: Core Subjective Topics
a) The three productions of S have FIRST sets: FIRST( ( ) ) = {(}, FIRST(a) = {a} and FIRST( ( A ) ) = {(}. The first and third productions both begin with '(', so their FIRST sets are not disjoint; with one lookahead symbol '(' the parser cannot decide which production to use. Hence the grammar is not LL(1). b) Factor out the common '(' prefix of S and remove the left recursion from A: S → a | ( S' S' → ) | A ) A → S A' A' → , S A' | ε c) The table has one row for each non-terminal and one column for each terminal plus the end marker $. Non-terminals are {S, S', A, A'} = 4 rows; terminals are {(, ), a, ,} plus $ = 5 columns. Table size = 4 × 5 = 20 entries.
-
Use the subset construction to create a DFA that is equivalent to the following NFA, which uses the alphabet {a, b}. The states with '*' are final states. (Marks: 10) State | a | b | ε 1 | – | – | 2 2 | 2 | 3, 4 | 5 3 | 5 | – | – 4 | – | 4 | 1, 5 5* | – | – | –
Topic: Core Subjective Topics
Start state of the DFA = ε-closure(1) = {1, 2, 5} = A. A is final because it contains state 5. From A = {1, 2, 5}: on 'a' the NFA can reach {2}, whose ε-closure is {2, 5} = B (final). On 'b' it can reach {3, 4}, whose ε-closure adds 1 (from 4), then 2 (from 1) and 5, giving {1, 2, 3, 4, 5} = C (final). From B = {2, 5}: on 'a' → {2, 5} = B; on 'b' → {3, 4} → ε-closure = C. From C = {1, 2, 3, 4, 5}: on 'a' → {2, 5} = B; on 'b' → {3, 4} → ε-closure = C. Resulting DFA (start state A; all states are accepting because every state contains 5): A: a → B, b → C B: a → B, b → C C: a → B, b → C
-
Compute the FIRST and FOLLOW sets for all the non-terminals of the following grammar: A → B C D B → h B | ε C → C g | g | C h | i D → A B | ε
Topic: Core Subjective Topics
FIRST sets: FIRST(B) = {h, ε} FIRST(C) = {g, i} (C derives g or i first; its left recursion adds nothing new) FIRST(A) = FIRST(B C D) = {h} ∪ FIRST(C) = {g, h, i} (B is nullable) FIRST(D) = FIRST(A) ∪ {ε} = {g, h, i, ε} FOLLOW sets ($ is the end marker; A is the start symbol): FOLLOW(A) = {h, $} ($, plus FIRST(B) − {ε} because A is followed by B in D → A B) FOLLOW(B) = FIRST(C) ∪ FOLLOW(A) ∪ FOLLOW(D) = {g, i} ∪ {h, $} = {g, h, i, $} FOLLOW(C) = (FIRST(D) − {ε}) ∪ FOLLOW(A) = {g, h, i} ∪ {h, $} = {g, h, i, $} FOLLOW(D) = FOLLOW(A) = {h, $} (D ends the production A → B C D)
-
Describe the structure of a two-pass compiler. What are its front end and back end, and what does each part take as input and produce as output?
Topic: Core Subjective Topics
A two-pass compiler is divided into a front end and a back end. The front end consists of the scanner (lexical analyzer) and the parser (syntax analyzer); it takes the source program as input, breaks it into tokens, checks its syntax and maps the legal source code into an intermediate representation (IR). The back end consists of instruction selection, register allocation and instruction scheduling; it takes the IR as input and maps it into target machine code, optimized for the hardware it will run on. The advantage of this structure is that it admits multiple front ends (for different languages) and multiple back ends (for different machines) sharing the same IR.
-
What is the difference between a parse tree and an abstract syntax tree (AST)? Give an example.
Topic: Core Subjective Topics
A parse tree (syntax tree) records the complete derivation of a sentence: every production application appears in it, including all the intermediate non-terminals and punctuation symbols. It therefore contains a lot of unneeded information. An abstract syntax tree summarizes the grammatical structure without the detail of the derivation: each internal node represents an operator and its children represent the operands, and redundant symbols such as parentheses and chain productions are dropped. For example, for the expression x + 2 – y, the parse tree shows every step of rewriting through the expression and term non-terminals, while the AST is simply a '–' node whose left child is a '+' node (with children <id, x> and <number, 2>) and whose right child is <id, y>.
-
Define token, lexeme and pattern, with an example.
Topic: Core Subjective Topics
A token is a syntactic category of the language — a class of similar character sequences; the scanner returns a token as a pair of its role (category) and its value. A lexeme is the actual sequence of characters in the source program that matches the pattern for a token. A pattern is the rule (usually written as a regular expression) that describes the set of lexemes belonging to a token. Example: for the input fragment "while count < 10", the word 'while' is a lexeme of the keyword token, 'count' is a lexeme of the identifier token (whose pattern is a letter followed by letters and digits), and '10' is a lexeme of the number token.
-
Why are regular languages used to describe (specify) tokens in lexical analysis?
Topic: Core Subjective Topics
Regular languages are the most popular choice for specifying tokens because: (1) they are based on a simple and useful theory (regular expressions and finite automata); (2) they are easy to understand and write, so token descriptions stay short and clear; and (3) efficient implementations exist — a scanner can be generated automatically from regular-expression specifications, as done by the flex tool.
-
What is Thompson's construction? Explain how it converts a regular expression into an NFA.
Topic: Core Subjective Topics
Thompson's construction is the algorithm that converts a regular expression into an NFA that accepts exactly the language of the expression. It works inductively on the structure of the expression. For a single symbol 'a' (or for ε), a small NFA with one start state, one final state and a single transition is built. For compound expressions, the NFAs of the parts are combined with new start and final states joined by ε-transitions: for a union r|s the new start state has ε-transitions to both sub-NFAs; for a concatenation r·s the final state of r's NFA is linked to the start state of s's NFA; for the Kleene star r* new ε-transitions allow the sub-NFA to be repeated or bypassed. Each step adds only a constant number of states, and the resulting NFA has exactly one final state.
-
Describe the subset construction algorithm for converting an NFA into a DFA. Why can a DFA simulate an NFA?
Topic: Core Subjective Topics
In the subset construction, every DFA state is a set of NFA states. The start state of the DFA is the ε-closure of the NFA's start state (the start state together with all states reachable from it by ε-transitions alone). Then, repeatedly, for each DFA state and each input symbol, collect all NFA states reachable by one transition on that symbol from any member state, and take the ε-closure of the result; this set becomes the target DFA state (and is added as a new state if not seen before). A DFA state is a final state if it contains at least one final NFA state. A DFA can simulate an NFA because, after reading any input string, the NFA can be in a whole set of possible states; the DFA simply tracks that entire set as its single current state, so no possibility is lost.
-
How does Hopcroft's algorithm minimize a DFA?
Topic: Core Subjective Topics
Hopcroft's algorithm starts by partitioning the DFA states into two groups: the final (accepting) states and the non-final states. It then repeatedly refines the partition: whenever the states of a group do not agree, for some input symbol, on which group they move to, the group is split into smaller groups whose states behave identically. When no group can be split any further, one DFA state is constructed for each group; transitions between these states follow the transitions of their member states. The result is the minimal DFA for the same language, and in DFA minimization we construct one state for each group of states of the initial DFA.
-
What is left recursion in a grammar? Why is it a problem for top-down parsers, and how is it eliminated? Give an example.
Topic: Core Subjective Topics
A production is left recursive if it has the form A → A α, i.e., the non-terminal appears as the first symbol of its own right-hand side. A top-down (recursive-descent) parser that tries to expand A will call itself on A again and again without consuming any input, so it loops forever; left recursion must therefore be removed before top-down parsing. The standard elimination rewrites A → A α | β (where β does not start with A) as: A → β A' A' → α A' | ε Example: E → E + T | T becomes E → T E' E' → + T E' | ε
-
What is left factoring? Why is it needed in predictive parsing? Give an example.
Topic: Core Subjective Topics
Left factoring is the transformation used when two or more productions of a non-terminal begin with the same prefix, e.g., A → α β1 | α β2. With only one lookahead symbol, a predictive parser cannot decide which production to use, because both start the same way; left factoring delays the decision by factoring out the common prefix: A → α A' A' → β1 | β2 Example: S → if E then S | if E then S else S is factored as S → if E then S S' S' → else S | ε Left factoring saves the parser from backtracking.
-
State the conditions that a grammar must satisfy to be an LL(1) grammar.
Topic: Core Subjective Topics
For every non-terminal A with two distinct productions A → α and A → β, the following conditions must hold: 1. FIRST(α) ∩ FIRST(β) = ∅ — the two alternatives must be selectable by disjoint lookahead sets. 2. If ε ∈ FIRST(β), then FIRST(α) ∩ FOLLOW(A) = ∅ — so that the lookahead also decides between taking α and deriving ε. In practice this means the grammar must be unambiguous, free of left recursion, and left factored. Such a grammar is called a predictive grammar and can be parsed by an LL(1) parser using a single lookahead symbol.
-
How is a predictive (LL(1)) parsing table constructed?
Topic: Core Subjective Topics
The parsing table M has one row for each non-terminal and one column for each terminal plus the end marker $. For each production A → α: 1. For every terminal 'a' in FIRST(α), add the production A → α to the entry M[A, a]. 2. If ε ∈ FIRST(α), then for every terminal 'b' in FOLLOW(A) (including $), add A → α to M[A, b]. A non-recursive predictive parser driven by this table is also called a table-driven parser. If any entry receives two different productions, the grammar is not LL(1).
-
Explain the shift and reduce actions of a bottom-up parser. What is a handle?
Topic: Core Subjective Topics
A bottom-up parser uses a stack and repeatedly applies two kinds of actions. In a shift action, the next input token is pushed onto the stack. In a reduce action, the symbols on top of the stack that match the right-hand side of a production are popped (a reduce action pops zero or more symbols) and replaced by the production's left-hand non-terminal. The substring on top of the stack that matches a right-hand side and is ready to be reduced is called a handle; finding handles is the key to efficient bottom-up parsing. The input is accepted when the stack contains only the start symbol and the input is fully consumed.
-
What tasks does the back end of a compiler perform, and what is the complexity of the algorithms used there? How does this compare with the front end?
Topic: Core Subjective Topics
The back end maps the intermediate representation into target machine code. Its main tasks are: instruction selection (choosing the machine instructions that implement each IR statement), register allocation (deciding which values stay in the limited set of fast CPU registers), and instruction scheduling (ordering the instructions so that all functional units are used productively and hardware stalls and interlocks are avoided). Optimal register allocation is an NP-complete problem, and optimal instruction scheduling is NP-complete in nearly all cases; in fact, the majority of the algorithms employed in the back end are NP-complete. In contrast, the algorithms employed in the front end (scanning and parsing) have polynomial time complexity. This difference is what makes compiler writing a challenging task.
-
How is a scanner (lexical analyzer) automatically generated by a tool such as flex? What are the sections of a flex specification file?
Topic: Core Subjective Topics
A flex specification file has three sections separated by %%. The first section contains definitions (named regular expressions) and declarations; the second section contains rules — a list of regular expressions (patterns) with the action to perform for each token; the third section contains user code (supporting routines). Flex processes the patterns by converting each regular expression into an NFA using Thompson's construction, combining them, converting the NFA into a DFA by subset construction, minimizing the DFA, and finally emitting a table-driven scanner program. At run time the scanner reads the input and returns the longest matching token (or an error if no pattern matches).
-
What is backtracking in top-down parsing? How does the use of a lookahead symbol avoid it?
Topic: Core Subjective Topics
In top-down parsing the parser expands the leftmost non-terminal by choosing one of its productions. If the choice turns out to be wrong (the derived string cannot match the input), the parser must undo the expansion and try another production; this retrying is called backtracking, and it is costly because input may be re-scanned many times. The alternative to backtracking is to use a lookahead symbol: before expanding a non-terminal, the parser peeks at the next input token and uses the FIRST (and, when needed, FOLLOW) sets to select the only production that can lead to a match. Parsing that works this way is called predictive parsing and never needs to backtrack.