GATE CSE has asked 81 questions on Parsing & Syntax Analysis (Compiler Design) from 1991 to 2026, in 41 of the 46 papers; the most recent is in GATE CSE 2026 Set 2. In the last five years it carried 2.2 marks per 100-mark paper on average, against 2.2 since 2003. Since 2014 the questions have been 19 MCQ, 7 NAT and 4 MSQ. 8 groups of questions here are solved the same way; “One per method” keeps the newest of each.
Assess four claims: A LL(1) parsers backtrack; B an LL(1) grammar must be left-recursive; C an LL(1) grammar must be left-factored; D LL(1) parsers are more powerful than SLR parsers. The official choice is C, with a retained qualification about literal syntactic left factoring.
Select all that apply
Answer & solution
Official answer: C
Our answer: Official scoring answer C; literal necessity claim is overbroad (see discrepancy).
Givens and goal
Assess four claims: A LL(1) parsers backtrack; B an LL(1) grammar must be left-recursive; C an LL(1) grammar must be left-factored; D LL(1) parsers are more powerful than SLR parsers. The official choice is C, with a retained qualification about literal syntactic left factoring.
Approach
Apply predictive-table conditions rather than treating grammar-transformation advice as an unrestricted necessity theorem.
Step-by-step solution
1. LL(1) selects a production from the next input token using a predictive parsing table. It does not use trial-and-error backtracking, so A is false. 2. Left recursion prevents ordinary predictive top-down parsing; it is something to remove, not a requirement for LL(1). Hence B is false. 3. Left factoring is a standard transformation for removing shared prefixes that obstruct predictive selection. This explains the intended textbook answer C, but syntactic left factoring is not literally necessary for every LL(1) grammar. Left factoring is also not sufficient: FIRST/FIRST or FIRST/FOLLOW conflicts can remain. 4. LL(1) does not have greater grammar-recognition power than SLR parsing. Thus D is false.
Discrepancy / interpretation issue: A reduced, productive counterexample is S → A a | A b, A → ε. The two S alternatives share the syntactic prefix A, so the grammar is not literally left-factored. Nevertheless FIRST(Aa)={a} and FIRST(Ab)={b}; the predictive table selects the two S productions in different columns. For A, its sole epsilon production is selected on FOLLOW(A)={a,b}. There are no conflicts, so the grammar is LL(1). Thus the exact general necessity claim in C is false under the standard syntactic definition of left-factored form. C remains the official scoring answer, but its literal necessity claim requires the qualification above. The issue is not restricted to unreachable or unproductive grammar alternatives.
Review: This counterexample was supplied during independent peer review and checked against FIRST/FOLLOW construction.
Predictive-table check for the counterexample
Nonterminal lookahead a lookahead b
S S→Aa S→Ab
A A→ε A→ε
Each table cell contains at most one production, despite the common written prefix A. For the “more powerful” claim, note also that SLR parsing can handle standard left-recursive grammars such as E→E+a | a, which this predictive LL(1) form cannot parse without transformation. Do not replace the LL(1) table condition with either “left-recursive” or “left-factored” as a complete characterization.
Use canonical LR(0) parsing for S→ACB, A→aA|ε, C→cC|ε, B→bB|b, with start S. Count shift-reduce conflicts in the ACTION table: A 2; B 3; C 4; D 5.
Your answer
Answer & solution
Official answer: D
Step through it (21 steps)
Givens and goal
Use canonical LR(0) parsing for S→ACB, A→aA|ε, C→cC|ε, B→bB|b, with start S. Count shift-reduce conflicts in the ACTION table: A 2; B 3; C 4; D 5.
Approach
Construct the relevant item closures and identify states containing both a shift and a completed item.
Step-by-step solution
1. Augment with S′→S. A completed LR(0) item X→α· requests a reduction on every terminal, without restricting it to FOLLOW(X). It conflicts with any terminal shift present in the same state. 2. The initial state contains S′→·S, S→·ACB, A→·aA, A→·. It shifts a and reduces A→ε, giving one conflicting ACTION cell on a. After shifting a, the state contains A→a·A and the same two A closure items, giving a second conflict on a. 3. After recognizing A, the state contains S→A·CB, C→·cC, C→·. It shifts c and reduces C→ε, giving one conflict on c. After shifting c, the state contains C→c·C with the same C closure items, giving another conflict on c. 4. After recognizing AC, the B closure has B→·bB and B→·b. Shifting b reaches {B→b·B, B→b·, B→·bB, B→·b}. This state shifts b and reduces B→b, giving the fifth conflict. 5. The remaining completed states contain only S′→S·, A→aA·, C→cC·, S→ACB·, or B→bB·; they have no terminal shift. The state before reading B also has no completed item. These account for all 11 canonical states. 6. Therefore there are exactly five conflicting cells, D. Using SLR FOLLOW restrictions instead would be a different parsing method and could change which conflicts remain.
While computing FIRST and FOLLOW for top-down parsing, select true statements: A A→ε adds ε to FIRST(A); B the input end marker is added to FIRST(S), where S is the start symbol; C A→ε adds ε to FOLLOW(A); D the end marker is added to FOLLOW(S).
Select all that apply
Answer & solution
Official answer: A, D
Approach: Keep separate what a nonterminal can begin with and what can appear immediately after it. FIRST(A) contains terminals that can start a string derived from A, and includes ε when A can derive the empty string. Therefore the production A→ε makes A true. FOLLOW(A) contains terminals, or the designated end marker, that may occur immediately after A in a sentential form or completed parse. ε is not an input symbol and never belongs in FOLLOW merely because A is nullable, so C is false. Nullability instead causes FOLLOW information to propagate through nullable suffixes. The start symbol represents an entire accepted input, so the end marker follows it: D is true. That marker is not automatically the first symbol of any derivation from S, making B false. Thus select A,D. For an ε-production, a predictive parser uses FOLLOW(A) to decide when to take it; it does not put ε into FOLLOW(A).
For grammar S→Aa | bAc | dc | bda and A→d, choose the parsing classification. Options: A. neither LALR(1) nor SLR(1); B. CLR(1) but not LALR(1); C. LALR(1) but not SLR(1); D. both LALR(1) and SLR(1).
Your answer
Answer & solution
Official answer: C
Step through it (3 parts)
First compute FOLLOW(A). In S→Aa, a follows A; in S→bAc, c follows A. Thus FOLLOW(A)={a,c}.
The LR(0) state reached by reading d directly from the start contains A→d· and S→d·c. SLR puts the reduction A→d on every symbol in FOLLOW(A), including c, but S→d·c requires shifting c. This is a shift/reduce conflict. Likewise, after reading bd the state contains A→d· and S→bd·a, producing a conflict on a. So the grammar is not SLR(1).
Canonical LR(1) retains the particular context. After the initial d, the completed item is [A→d·,a]; it reduces only on a, while S→d·c shifts c. After bd, the completed item is [A→d·,c]; it reduces only on c, while S→bd·a shifts a. These actions do not conflict.
LALR merges states only when their complete LR(0) cores are identical. The two potentially troublesome states have different S items, S→d·c versus S→bd·a, so they are not merged merely because both contain A→d·. All other reductions arise in completed S productions or similarly nonconflicting states. Hence the precise lookahead separation survives LALR construction. Answer: C.
The terminals are if,then,else,a,b,c. Two grammars are: G1: S→if E then S | if E then S else S | a; E→b. G2: S→if E then S | M; M→if E then M else S | c; E→b. Select true statements: A. G1 not LL(1), G2 LL(1); B. G1 LL(1), G2 not LL(1); C. neither LL(1); D. both ambiguous.
Select all that apply
Answer & solution
Official answer: C, D
Write i for the complete terminal phrase “if b then” and e for “else.” In G1, the string i i a e a has two parses: i [i a e a] attaches the else to the inner if, while [i [i a] e a] attaches it to the outer if. This is the dangling-else ambiguity.
G2 may resemble a matched/unmatched-if grammar, but its M production ends in S, not in an entirely matched nonterminal. Consequently an unmatched if can occur in that else branch. A concrete ambiguous string is i i c e i c e c. Its first parse is i [i c e (i c e c)]: the initial S uses S→iS, and its inner S→M derives i c e (i c e c). Its second parse is i [i c e (i c)] e c: the outer S→M uses M→i M e S, with its then-branch M deriving i c e (i c) and its final S deriving c. The else tokens attach to different if occurrences, yet the terminal string is identical. Thus G2 is ambiguous too.
An LL(1) grammar is unambiguous, so neither grammar can be LL(1). Directly, G1's two if-alternatives have the same FIRST token, and G2's S alternatives both admit strings beginning with if. These create predictive parsing conflicts. Select C,D.
Which are bottom-up parsers? A Shift-reduce; B Predictive; C LL(1); D LR.
Select all that apply
Answer & solution
Official answer: A, D
Approach: Ask whether parsing starts with the input's terminal symbols and reduces upward, or starts with the grammar's start symbol and expands downward. 1. A shift-reduce parser shifts input symbols onto a stack, then reduces recognized handles to nonterminals. Repeated reductions construct the parse from leaves toward the root. Hence A is bottom-up. 2. An LR parser is a systematic shift-reduce parser. It reads input from left to right and reconstructs a rightmost derivation in reverse, so D is bottom-up as well. 3. Predictive parsing chooses productions while expanding from the start symbol toward the input. It is top-down, making B false. 4. LL(1) is a predictive, top-down method using one lookahead symbol. Its second L refers to a leftmost derivation, not to upward reduction. C is false. Answer: A and D. LR and LL both scan left to right, so scan direction alone does not distinguish bottom-up from top-down.
A grammar has S→daT | (1), T→aS | bT | (2), R→(3) | ε. FIRST(S)={c,d,f}, FIRST(T)={a,b,ε}, FIRST(R)={c,ε}; FOLLOW(S)=FOLLOW(T)={c,f,$}, FOLLOW(R)={f}. Complete (1),(2),(3). A Rf, ε, cTR; B fR, ε, cTR; C fR, cT, cR; D Rf, cT, cR.
Your answer
Answer & solution
Official answer: A
Approach: Use FIRST to eliminate incompatible productions, then verify the surviving option with FOLLOW rather than stopping after a partial match. 1. T must derive ε, and its FIRST set excludes c. Since aS and bT cannot produce ε, the missing alternative is T→ε, not T→cT. This eliminates C and D. 2. FIRST(S) contains c. The existing production daT starts with d. An alternative fR would start only with f, whereas Rf starts with c when R→cTR and with f when R→ε. Thus only A has the required FIRST(S). 3. In A, S→Rf places f immediately after R, giving FOLLOW(R)={f}. R→cTR places a nullable R after T, contributing c and FOLLOW(R)'s f to FOLLOW(T). 4. The trailing T in S→daT inherits FOLLOW(S), while the trailing S in T→aS inherits FOLLOW(T). Because S is the start symbol, $ propagates to both sets. The result is exactly {c,f,$} for each. Answer: A. FIRST describes how derived strings begin; FOLLOW describes terminals that can occur immediately after a nonterminal in a sentential form.
Grammar: S→AaAb | BbBa, A→cS | ε, B→dS | ε. Missing table cells are (1) M[S,c], (2) M[S,d], (3) M[A,b], (4) M[B,a]. Options: A AaAb,BbBa,ε,ε; B BbBa,AaAb,ε,ε; C AaAb,BbBa,blank,blank; D BbBa,AaAb,blank,blank (right sides for the relevant row nonterminal).
Your answer
Answer & solution
Official answer: A
Step through it (2 parts)
Approach: Use FIRST for nonempty alternatives and FOLLOW for epsilon alternatives.
1. Derivation. FIRST(AaAb)={c, a}, while FIRST(BbBa)={d, b}. Thus the S-row c cell chooses S→AaAb and the d cell S→BbBa. A occurs before a and b in the first production, so FOLLOW(A)={a, b}; its epsilon production is entered for both lookaheads. Similarly FOLLOW(B)={b, a}, so B→epsilon goes in both a, b cells. Hence cells(1)–(4) are S→AaAb, S→BbBa, A→epsilon, B→epsilon, option A.
2. Explanation and checks. A can disappear, so AaAb can start with a; if A does not disappear it begins with c. The same reasoning yields b or d for BbBa. Each occurrence of A in the S production is followed immediately by a terminal, once a and once b, so both terminals enter FOLLOW(A). The two B occurrences similarly supply b and a. There is no need to put an epsilon production under every lookahead: only FOLLOW lookaheads receive it.
Augmented grammar: S′→S; S→SS | Aa | bAc | Bc | bBa; A→d#; B→@. Terminals are a,b,c,d,#,@. I0=CLOSURE({S′→·S}). For an SLR parser, how many items are in GOTO(I0,S)?
Answer & solution
Official answer: 9
Step through it (3 steps)
Approach: Move dots over S only where S immediately follows the dot, then close the resulting item set.
1. Derivation. The initial closure contains S′→·S and S→·SS, plus the other four S-start items and A→·d#, B→·@. GOTO on S shifts the first two into S′→S· and S→S·S. The latter requires closure under S, adding all five S-start items: ·SS, ·Aa, ·bAc, ·Bc, ·bBa. Closure of their leading A/B adds A→·d# and B→·@. The total is 2+5+2=9 distinct LR(0) items; SLR FOLLOW sets do not change this item-set construction.
2. Explanation and checks. The full resulting set is S′→S·; S→S·S; S→·SS; S→·Aa; S→·bAc; S→·Bc; S→·bBa; A→·d#; B→·@. The item S→·SS does not generate endlessly many items: closure is a set and revisiting the same production adds no duplicate. Terminals b,d,@ do not cause further closure expansion. Both # and @ are explicitly terminals here, so neither denotes epsilon or the end marker. FOLLOW sets govern SLR reduction entries, not this GOTO construction.
Choose the true statement: A LALR(1) cannot introduce reduce/reduce conflicts absent from LR(1); B symbol tables are accessed only during lexical analysis; C data-flow analysis is necessary for run-time memory management; D LR(1) parsing suffices for deterministic context-free languages.
Your answer
Answer & solution
Official answer: D
Every deterministic context-free language has an LR(1) grammar, so LR(1) parsing is sufficient for these languages, D. LALR merging can introduce reduce-reduce conflicts even when canonical LR has none. Symbol-table information is used beyond lexical analysis, and data-flow analysis is not a necessary runtime step in program execution. The claim is about existence of a suitable LR(1) grammar, not that every grammar of the language is LR(1).
LALR merges canonical states with identical LR(0) cores but potentially different lookahead sets; combining these lookaheads can create a reduce/reduce choice. Symbol tables also serve declaration/type checking, code generation, and optimization. LR(1) sufficiency concerns a grammar for the language, not every arbitrary presentation of it.
Grammar: S′→S; S→S+R|R; R→R*P|P; P→(S)|id. Let I0={S′→S·, S→S·+R}. Count items in goto(closure(I0),+).
Answer & solution
Official answer: 5
Step through it (3 steps)
Taking goto on + advances S→S·+R to S→S+·R. Closure then adds R→·R*P, R→·P, P→·(S), and P→·id. No dot precedes S in these items, so no further closure is needed. Total 5 items.
Closure only expands a nonterminal immediately after a dot. Initially the dots precede end-of-rule or terminal +, so closure(I0)=I0. After shifting +, R is exposed; recursively expanding R and P yields the five items listed. The left-recursive R production is added once, so closure terminates.
S1: Every SLR(1) grammar is unambiguous, but some unambiguous grammars are not SLR(1). S2: For every context-free grammar there is a parser taking at most O(n³) time for an input of length n. Which is correct? A S1 true/S2 false; B S1 false/S2 true; C both true; D both false.
Your answer
Answer & solution
Official answer: C
A conflict-free SLR(1) table yields a unique parse, so every SLR(1) grammar is unambiguous. The converse fails: the standard grammar S→L=R|R, L→*R|id, R→L is unambiguous but has an SLR shift-reduce conflict. General CFG recognition and construction of a parse can be done in O(n³) for a fixed grammar, for example by Earley parsing or CYK after normalization. Thus both statements hold, C; this does not claim that exponentially many parse trees can all be listed in cubic time.
In the counterexample grammar, the LR(0) state after recognizing L contains S→L·=R and R→L·. Since '=' belongs to FOLLOW(R), SLR would both shift '=' and reduce R→L there. Thus unambiguity alone does not remove SLR conflicts. For cubic parsing, CYK stores whether each nonterminal derives each substring and considers O(n) split points for O(n²) substrings; the fixed grammar contributes only a constant factor. A parse witness can be recovered by stored backpointers.
For terminals {a,b,c,d,f}, grammar S→daT|Rf, T→aS|baT|ε, R→caTR|ε has a partially filled LL(1) table. Numbered cells are 1=(S,c), 2=(S,f), 3=(T,c), 4=(T,$). Known cells are (S,d)=S→daT; (T,a)=T→aS; (T,b)=T→baT; (T,f)=T→ε; (R,c)=R→caTR; (R,f)=R→ε; other unnumbered cells blank. Choose entries (1,2,3,4): A (S→Rf,S→Rf,T→ε,T→ε); B (blank,S→Rf,T→ε,T→ε); C (S→Rf,blank,blank,T→ε); D (blank,S→Rf,blank,blank).
Your answer
Answer & solution
Official answer: A
Step through it (2 parts)
FIRST(R)={c,ε}, so FIRST(Rf)={c, f}; both numbered S-row cells contain S→Rf. From R→caTR, c belongs to FOLLOW(T), and nullable R carries FOLLOW(R)={f} into FOLLOW(T). From S→daT and T→aS, the start marker $ also reaches FOLLOW(T). Thus FOLLOW(T)={c, f,$}, and the numbered T-row cells at c and $ contain T→ε. Therefore A.
The FIRST rule puts A→α in every terminal column of FIRST(α) except ε. When α is nullable, put it in all FOLLOW(A) columns. For S→Rf, R can start with c or disappear, exposing f. For T→ε, the c column comes from T followed by R in R→caTR; the f column comes from the following nullable R and S→Rf; the end marker flows from start S through S→daT. No guessed table entry is needed once these sets are computed.
Augmented grammar S′→S; S→S#cS | SS | S@ | <S> | a | b | c. I0=CLOSURE({S′→·S}). Count LR(0) items in GOTO(GOTO(I0,<),<).
Answer & solution
Official answer: 8
Step through it (4 steps)
On reading < from the initial closure the kernel is S→<·S>. Its closure adds all seven S productions with the dot at the beginning: S→·S#cS, ·SS, ·S@, ·<S>, ·a, ·b, ·c. Reading a second < reproduces exactly the same kernel and closure. Thus GOTO(GOTO(I0,<),<) has 1+7=8 items; the augmented S-prime item is not added because closure expands only S.
The resulting item set is {S→<·S>, S→·S#cS, S→·SS, S→·S@, S→·<S>, S→·a, S→·b, S→·c}. Recursive closure does not create infinitely many copies: items are set members. In particular, productions beginning with S are added once and their expansion adds no new productions beyond the seven already present.
Grammar: S→aSB | d; B→b. How many reductions does a bottom-up parser perform to accept aaadbbb?
Answer & solution
Official answer: 7
Step through it (16 steps)
Worked explanation
An explicit reduction sequence is aaadbbb ⇒ aaaSbbb ⇒ aaaSBbb ⇒ aaSbb ⇒ aaSBb ⇒ aSb ⇒ aSB ⇒ S. The first step uses d→S; each pair thereafter uses b→B followed by aSB→S. Thus there are 1+3+3=7 reductions. The corresponding derivation tree has four S-production nodes and three B-production nodes. A bottom-up parser may also shift seven terminals and eventually perform an accept action; neither shifts nor accept are additional grammar reductions.
Derivation and answer
The derivation uses S→aSB three times, S→d once, and B→b three times. A bottom-up parse reverses these seven production applications, so it performs 7 reductions, excluding the separate parser accept action.
An LR parser corresponds to which derivation order? Choices: A leftmost; B leftmost in reverse; C rightmost; D rightmost in reverse.
Your answer
Answer & solution
Official answer: D
Method: distinguish the left-to-right scan of the input from the order of grammar productions reconstructed by reductions.
1. LR parsing is bottom-up. A reduction replaces a handle, a right-hand side of a production, by its left-hand-side nonterminal. 2. This operation undoes a production application rather than applying it from the start symbol outward. Therefore the derivation is reconstructed in reverse. 3. The handles reduced by an LR parser are exactly those obtained by reversing a rightmost derivation. For example, with S → AB, A → a, B → b, a rightmost derivation is S ⇒ AB ⇒ Ab ⇒ ab. Reversing it gives ab ⇒ Ab ⇒ AB ⇒ S, the bottom-up reduction sequence. 4. In the name LR, L denotes scanning input left-to-right and R denotes reconstructing a rightmost derivation. The L does not mean leftmost derivation.
The grammar is S→Aa, A→BD, B→b|ε, D→d|ε. Symbols a,b,d,$ have indices 3,2,1,0 respectively. Find FOLLOW(B), then concatenate its symbol indices in descending order.
Answer & solution
Official answer: 31
Step through it (13 steps)
Method: use the rule for a nonterminal followed by a possibly nullable suffix.
1. FOLLOW(B) contains terminals that can appear immediately after B in a sentential form, not the terminals that B itself derives. In A→BD, the suffix following B is D. 2. FIRST(D)={d,ε}. Add its non-epsilon terminal d to FOLLOW(B), because D may produce d immediately after B. 3. D can also disappear via D→ε. In that case whatever follows A also follows B. From S→Aa, the terminal a follows A, so FOLLOW(A)={a}; add a to FOLLOW(B). 4. There are no other occurrences contributing more symbols. In particular, $ follows the start symbol S, but the required terminal a after A prevents $ from propagating to A or B. The symbol b is in FIRST(B), not FOLLOW(B), and ε is never a FOLLOW-set member. 5. Thus FOLLOW(B)={a,d}. Their indices are 3 and 1, already in descending order, so concatenate them as 31.
Result: 31. The language generated from S is {a,ba,da,bda}, which also illustrates that a B occurrence is followed by d or a.
Given augmented grammar S′→S; S→(L)|id; L→L,S|S, let I0=CLOSURE({S′→·S}). How many distinct LR(0) items are in GOTO(I0, '(')? The comma in L→L,S is a terminal.
Answer & solution
Official answer: 5
Step through it (3 steps)
1. An LR(0) item is a production with a dot marking how much has been recognized. Closure adds productions of any nonterminal immediately after a dot, with their dots at the start. 2. I0 contains S′→·S, S→·(L), and S→·id. Only S→·(L) has an opening parenthesis immediately after its dot. 3. GOTO on '(' advances that dot, yielding the kernel item S→(·L). Its dot precedes L, so add L→·L,S and L→·S. 4. The first of these new items again has L after its dot, but adding L's productions repeats existing items. The second has S after its dot, so add S→·(L) and S→·id. 5. The last two dots precede terminals, so closure stops. The complete set is {S→(·L), L→·L,S, L→·S, S→·(L), S→·id}: exactly 5 items. 6. Do not carry S′→·S into this destination merely because it was in I0. GOTO keeps shifted matching items and then their closure, not the entire starting state.
For a#b$c$d#e#f, the supplied tree represents a#(((b$c)$d)#(e#f)). Choose A $ higher and left-associative, # right-associative; B # higher and left-associative, $ right-associative; C $ higher and left-associative, # left-associative; D # higher and right-associative, $ left-associative.
Your answer
Answer & solution
Official answer: A
Method
Read each internal node as an operation on its two child subtrees. The $ subtree first combines b,c and then combines that result with d, demonstrating left association. Treating this whole subtree as one operand gives a#(X#(e#f)), which nests # to the right. Because the dollar chain is grouped into an operand before surrounding hash operations, $ has higher precedence in the intended grammar. Do not infer precedence from the visual height of leaf letters.
Solution
The tree groups the expression as a#(((b$c)$d)#(e#f)). The two dollar operations group left, and their subtree is below the hash operations, showing higher precedence. The hash chain groups to the right. Thus A.
Grammar: P→xQRS; Q→yz | z; R→w | ε; S→y. Find FOLLOW(Q). A {R}; B {w}; C {w,y}; D {w,$}.
Your answer
Answer & solution
Official answer: C
Step through it (13 steps)
1. FOLLOW(Q) contains terminal symbols that can occur immediately after a derivation of Q, not the next nonterminal’s name. Its only occurrence is in P→xQRS.
2. R can produce w, placing w immediately after Q. It can also disappear through ε, exposing S, which produces y.
3. S is not nullable, so Q never reaches the end of this production and no end marker is inherited. FOLLOW(Q)={w,y}, C.
Which parser-power statements are correct? I:Canonical LR is more powerful than SLR. II:SLR is more powerful than LALR. III:SLR is more powerful than canonical LR. A:I only. B:II only. C:III only. D:II and III.
Your answer
Answer & solution
Official answer: A
1. Power here refers to the class of grammars handled without parsing conflicts, with the usual one-symbol lookahead versions. The inclusion chain is SLR(1) ⊂ LALR(1) ⊂ canonical LR(1).
2. SLR uses coarse FOLLOW sets for reductions. Canonical LR uses item-specific lookahead information; LALR merges compatible LR state cores and retains more discrimination than SLR but can lose some canonical LR power.
3. Thus canonical LR can handle every SLR grammar and some additional grammars, making I true. II and III reverse the inclusion direction and are false. Choose A. This comparison is about grammar recognition capability, not parser speed or table size.
Grammar G is E→E−T|T, T→T+F|F, F→(E)|id. Choose an equivalent grammar without left recursion. A:the same grammar. B:E→TE′, E′→−TE′|ε, T→T+F|F, F→(E)|id. C:E→TX, X→−TX|ε, T→FY, Y→+FY|ε, F→(E)|id. D:E→TX|(TX), X→−TX|+TX|ε, T→id.
Your answer
Answer & solution
Official answer: C
1. Apply the standard direct-left-recursion transformation A→Aα|β becomes A→βA′, A′→αA′|ε. For E, α is −T and β is T, giving E→TX and X→−TX|ε.
2. Apply it separately to T: α is +F and β is F, giving T→FY and Y→+FY|ε. Keep F→(E)|id so arbitrarily nested factors remain possible. These are exactly option C.
3. A leaves both original recursions intact. B fixes E but leaves T→T+F directly left-recursive. D restricts T to id and cannot generate nested expressions such as ((id)) or parentheses as arbitrary factors. The transformation preserves the generated strings, although semantic associativity must be handled when constructing evaluation actions.
Three binary operators have these language-specific rules: + has highest precedence and is left-associative; − has medium precedence and is right-associative; * has lowest precedence and is left-associative. Evaluate 2−5+1−7*3.
Answer & solution
Official answer: 9.0 : 9.0
Our answer: 9
Addition has highest precedence, giving 5+1=6. The remaining subtraction is right-associative, so 2−6−7 groups as 2−(6−7)=3. Multiplication has lowest precedence, producing 3*3=9.
Insert parentheses in precedence order before calculating: the expression becomes (2−(5+1)−7)*3, then right associativity changes the subtraction part to 2−((5+1)−7). The inner result 6−7 is−1, so the outer result is 3 and multiplying by 3 gives 9. Ordinary arithmetic precedence would put multiplication first and produce a different result; this question intentionally defines a different expression grammar.
Which grammar has no left recursion? A S→AB,A→Aa|b,B→c; B S→Ab|Bb|c,A→Bd|ε,B→e; C S→Aa|B,A→Bb|Sc|ε,B→d; D S→Aa|Bb|c,A→Bd|ε,B→Ae|ε.
Your answer
Answer & solution
Official answer: B
Grammar B has an acyclic nonterminal dependency chain S→A/B, A→B, with B deriving only terminal e; it cannot derive a sentential form beginning again with the same nonterminal. A has direct A→Aa. C has S⇒Aa⇒Sca. D has A⇒Bd⇒Aed. Thus B alone is free of left recursion.
Left recursion means a derivation A⇒+Aα, possibly passing through other nonterminals and nullable productions. It is not the same as any recursion anywhere on a right side. In B every chain beginning in a nonterminal descends from S to A to B, and B immediately produces terminal e, so no cycle can return to its starting nonterminal.
Two grammars describe C-like declarations with at least one array dimension, e.g. int a[10][3];. Terminals: int, ;, id, [, ], num. G1: D→int L;, L→id [E, E→num] | num][E. G2: D→int L;, L→id E, E→E[num] | [num]. Which correctly generate the declarations? A both; B G1 only; C G2 only; D neither.
Your answer
Answer & solution
Official answer: A
G1 emits the opening bracket with id, then its recursive E→num][E adds each completed dimension and the next opening bracket, ending with E→num]. G2 emits one or more bracketed num groups through left recursion E→E[num] with base[num]. Both generate int id[num]...[num]; with at least one dimension, including the example. Thus A.
For two dimensions, G1 derives L⇒id [E⇒id [num][E⇒id [num][num]. G2 derives L⇒id E⇒id E[num]⇒id [num][num]. Substituting id=a and the two num tokens by 10 and 3 yields the example in each. Left recursion may inconvenience a parser, but it does not make the generated language incorrect.
At any valid shift-reduce parsing state, which is true? A viable prefixes appear only at the stack bottom, not inside; B only at its top, not inside; C the stack contains only a set of viable prefixes; D it never contains viable prefixes.
Your answer
Answer & solution
Official answer: C
A handle is the portion reduced in a reverse rightmost derivation. A viable prefix stops at or before the right end of such a handle. The parser stack's grammar symbols form one viable prefix, and each initial segment of those symbols is also viable. Read the paper's “set” wording in this prefix sense, not as a claim that arbitrary internal substrings or LR state numbers are grammar prefixes.
Solution: The grammar-symbol portion of a shift-reduce stack is a viable prefix: a prefix of a right-sentential form that does not pass the handle’s right end. Taking a shorter prefix cannot cross that end, so every prefix is viable too. Thus C.
Among simple LR (SLR), canonical LR and look-ahead LR (LALR), identify, in order, the easiest method to implement and the most powerful method. Options: (A) SLR, LALR; (B) canonical LR, LALR; (C) SLR, canonical LR; (D) LALR, canonical LR.
Your answer
Answer & solution
Official answer: C
1. SLR uses one FOLLOW set for all reductions of a nonterminal, whereas canonical LR keeps the lookahead specific to each item/context. LALR merges compatible LR states for smaller tables but may introduce conflicts that canonical LR avoids.
2. SLR uses LR(0) states plus FOLLOW sets and is the simplest of the three. Canonical LR(1) retains item-specific lookaheads and recognizes the broadest grammar class. Thus SLR, canonical LR, C.
Grammar G has productions S→F|H, F→p|c, H→d|c. S,F,H are nonterminals; p,d,c are terminals. Assess S1: LL(1) can parse all strings generated using grammar G; S2: LR(1) can parse all strings generated using grammar G. Options: (A) S1 only; (B) S2 only; (C) both; (D) neither. The question concerns this grammar, not whether its language has a different LL(1) or LR(1) grammar.
Your answer
Answer & solution
Official answer: D
Step through it (3 parts)
1. The string c has two parse trees: S→F→c and S→H→c.
2. Thus the displayed grammar is ambiguous and is neither LL(1) nor LR(1). Concretely FIRST(F) and FIRST(H) both contain c, causing an LL conflict; after shifting c, completed F→c and H→c items both reduce on end-of-input, causing an LR reduce/reduce conflict. Therefore D for parsing with this grammar. Its finite language can of course be represented by a different unambiguous grammar S→p|d|c.
An LR item set contains S→L·>R and Q→R·. On lookahead/input symbol <, does it contain a conflict? A: both shift-reduce and reduce-reduce. B: shift-reduce only. C: reduce-reduce only. D: neither. The symbol after the first dot is >, while the queried input is <.
Your answer
Answer & solution
Official answer: D
1. Method and setup. A shift is possible only for a terminal immediately after a dot, and a reduction only for a completed item, subject to the parser’s lookahead rules. Do not confuse the literal terminals < and >. There is only one completed item, so no pair of competing reductions is present.
2. Work through the result and its assumptions. The first item has its dot before >, not before <. Thus no shift is enabled on <. Only Q→R. is completed, so at most one reduction is possible on that symbol. There is neither a shift-reduce nor reduce-reduce conflict, D.
Grammar: S→T*P; T→U or T*U; P→Q+P or Q; Q→Id; U→Id. Which associativity statement is true? A + left, * right; B + right, * left; C both right; D both left.
Your answer
Answer & solution
Official answer: B
1. Set up the reasoning. Inspect the recursive side of each operator production. T recurs on the left of *, while P recurs on the right of +.
2. Derive the result. The rule T→T*U is left-recursive and groups multiplication to the left. P→Q+P is right-recursive and groups addition to the right. Thus + is right associative and * left associative, B.
3. Check the interpretation. Expanding T twice gives (Id*Id)*Id, whereas expanding P twice gives Id+(Id+Id). Associativity concerns grouping of repeated operators, not which operator has greater precedence.
A bottom-up parser processes n tokens using a grammar with no epsilon or “unit” productions, expressly described in the source as A→ε and A→a. What is the maximum number of reductions? A n/2; B n−1; C2n−1; D2^n.
Your answer
Answer & solution
Official answer: B
Our answer: B under the displayed no-single-symbol-production interpretation
A reduction with a right-hand side of length at least 2 decreases the stack/sentential length by at least 1. Starting with n terminals and ending with one start symbol thus allows at most n−1 such reductions, attained by binary reductions, giving B. However the source calls A→a a unit-production, whereas standard CFG terminology reserves unit-production for A→B with B a nonterminal. If only standard unit rules and epsilon rules are forbidden, terminal rules A→a remain, and a Chomsky-normal-form derivation can require n terminal reductions plus n−1 binary reductions=2n−1. The key therefore relies on the source’s intended ban on length-one reductions, not the usual terminology alone.
Each reduction replaces a right-hand side by one nonterminal. If every permitted right-hand side has at least two symbols, each reduction shrinks the total length by at least one. Reducing n tokens to one start symbol then permits at most n−1 reductions; a binary parse tree attains that many internal combinations. The caveat is not optional: a normal terminal production A→a has length 1 and would add reductions without shortening the string. The printed parenthetical explicitly rules those out, even though it uses nonstandard “unit” terminology.
Two LR(1) states have items X→c·X, X→·cX, X→·d; first has lookaheads c/d on all, second $. About merging them into LALR, which claims are false?1 cannot merge because lookaheads differ;2 merging creates shift/reduce conflict;3 merging creates reduce/reduce conflict;4 cannot merge because goto on c leads to different states. A1 only, B2 only, C1and4, Dallfour.
Your answer
Answer & solution
Official answer: D
The two LR(1) states have the same LR(0) core, so LALR construction merges them and unions the lookahead sets for each core item. Every displayed item still has symbols to the right of the dot. Consequently this merged state has no reduction action and can create neither a shift/reduce nor a reduce/reduce conflict there. Its equal-core goto states are likewise merged in the LALR construction. Each of the four asserted objections is false, so D.
LALR equivalence compares items after removing lookaheads, and the two displayed sets then match exactly. Unioning lookaheads gives{c, d,$} for each item. Shift actions depend on the symbol after the dot; none of these items has its dot at the end, so there is no reduce action to conflict with a shift or another reduction. Goto targets with equal cores are treated by the same merging rule. Different lookaheads and different original state numbers are not reasons to reject the merge.
FIRST and FOLLOW with nullable indirect productions
Parsing & Syntax Analysis
Tap to enlarge
Grammar: S→aAbB | bAaB | ε; A→S; B→S. S is the start symbol. The partial predictive table has columns a,b,$: S row=[E1,E2,S→ε]; A row=[A→S,A→S,error]; B row=[B→S,B→S,E3]. ε is empty and $ is the input-end marker. Find FIRST and FOLLOW of A and B. (A) FIRST(A)=FIRST(B)={a,b,ε}; FOLLOW(A)={a,b}; FOLLOW(B)={a,b,$}. (B) FIRST(A)={a,b,$}; FIRST(B)={a,b,ε}; FOLLOW(A)={a,b}; FOLLOW(B)={$}. (C) FIRST(A)=FIRST(B)={a,b,ε}; FOLLOW(A)={a,b}; FOLLOW(B)=∅. (D) FIRST(A)=FIRST(B)={a,b}; FOLLOW(A)=FOLLOW(B)={a,b}.
Your answer
Answer & solution
Official answer: A
Step through it (14 steps)
S can start with a or b or derive ε; A→S and B→S therefore give FIRST(A)=FIRST(B)={a, b,ε}. In S→aAbB and S→bAaB, A is immediately followed by b and a respectively, so FOLLOW(A)={a, b}. Since S is the start symbol, $ belongs to FOLLOW(S). A→S passes FOLLOW(A) into FOLLOW(S), giving FOLLOW(S)={a, b,$}. B occurs at the end of each nonempty S production, so it inherits FOLLOW(S), and FOLLOW(B)={a, b,$}. B→S adds no new symbols. These are option A.
Check: Nullable propagation is essential: A and B derive ε through S even though neither has an explicit ε production. FOLLOW sets require a fixed point because A→S and B→S propagate symbols back to S, which then propagates them to trailing B.
Grammar: S→aAbB | bAaB | ε; A→S; B→S. S is the start symbol. The partial predictive table has columns a,b,$: S row=[E1,E2,S→ε]; A row=[A→S,A→S,error]; B row=[B→S,B→S,E3]. ε is empty and $ is the input-end marker. Fill E1,E2,E3. (A) E1={S→aAbB,A→S}; E2={S→bAaB,B→S}; E3={B→S}. (B) E1={S→aAbB,S→ε}; E2={S→bAaB,S→ε}; E3={S→ε}. (C) E1={S→aAbB,S→ε}; E2={S→bAaB,S→ε}; E3={B→S}. (D) E1={A→S,S→ε}; E2={B→S,S→ε}; E3={B→S}.
Your answer
Answer & solution
Official answer: C
For M[S, a], FIRST(aAbB) supplies S→aAbB; because a belongs to FOLLOW(S), the nullable alternative also supplies S→ε. Similarly M[S, b] contains both S→bAaB and S→ε. At M[B,$], B→S is inserted because S is nullable and $ belongs to FOLLOW(B). Thus E1={S→aAbB, S→ε}, E2={S→bAaB, S→ε}, E3={B→S}, exactly C. The two multiple-production cells are FIRST/FOLLOW conflicts, proving this grammar is not LL(1). The source’s phrase “LL(1) parsing table” should be understood as the table-construction procedure, not as certification that the grammar admits deterministic LL(1) parsing.
Check: Each parsing-table row can contain only productions whose left-hand side is that row’s nonterminal. This immediately eliminates options inserting A→S or B→S into S’s row, and eliminates S→ε as the B-row entry E3.
For binary operators ↑ and ↓, ↑ has higher precedence and is right-associative, whereas ↓ is left-associative. Which parse tree represents 7↓3↑4↑3↓2? Trees are encoded below as fully parenthesized expressions.
Higher-precedence ↑ groups the middle chain, and its right associativity gives 3↑(4↑3). Lower-precedence ↓ then associates left, yielding(7↓(3↑(4↑3)))↓2. The displayed tree with that structure is B.
Associativity is applied only after precedence identifies which operators compete at the same level. First make the ↑ subtree with root ↑, left leaf 3 and right subtree (4↑3). The remaining expression has the form 7↓T↓2; left associativity makes its root the final ↓, with right child 2 and left child (7↓T). A gives ↓2 too high a binding priority; C and D left-group the ↑ chain or combine the initial ↓ too early.
Classify the grammar S→aSa | bS | c. Options: (A) LL(1) but not LR(1); (B) LR(1) but not LL(1); (C) Both LL(1) and LR(1); (D) Neither LL(1) nor LR(1).
Your answer
Answer & solution
Answer: C (no official key was published)
Step through it (3 parts)
The productions S→aSa, S→bS and S→c begin with distinct terminals a,b,c and none derives epsilon. Their FIRST sets are disjoint, so one lookahead symbol uniquely selects the production and the grammar is LL(1). Every LL(1) grammar is LR(1), so it is both, C. The trailing a in aSa does not cause a predictive conflict because the initial a already selects that alternative.
The predictive parsing table contains exactly S→aSa under lookahead a, S→bS under b and S→c under c. There are no epsilon productions, so no FIRST/FOLLOW conflict arises. Recursion does not by itself prevent LL(1); left recursion would, but here each recursive call is preceded by a terminal consumed from the input.
(A) A position in a sentential form for the next shift or reduce operation (B) A nonterminal whose production is used for the next reduction (C) A production possibly used for a future reduction and the position of the next shift or reduce operation (D) The production used in the next reduction and the position of its right-hand side in the sentential form
Your answer
Answer & solution
Answer: D (no official key was published)
1. Bottom-up LR parsing reverses a rightmost derivation: it replaces a production’s right-hand side by its left-hand-side nonterminal. 2. A handle must specify both which production to reduce and which occurrence of its right-hand side is the correct next one. Merely naming a position or a nonterminal is insufficient. 3. D gives exactly this production-and-position pair. A possible future reduction, as in C, is not necessarily the next handle.
An LALR(1) parser for G has shift-reduce conflicts if and only if:
(A) Its SLR(1) parser has shift-reduce conflicts (B) Its LR(1) parser has shift-reduce conflicts (C) Its LR(0) parser has shift-reduce conflicts (D) Its LALR(1) parser has reduce-reduce conflicts
Your answer
Answer & solution
Answer: B (no official key was published)
1. The equivalence is with canonical LR(1), option B. An LALR state merges LR(1) states having the same LR(0) core and unions lookaheads. Suppose a merged state has a reduction A→α on lookahead a and a shift on a. 2. The reduction/lookahead pair came from some original LR(1) state. The shift item is in the shared LR(0) core, so it also occurred in that very original state. Thus the shift-reduce conflict already existed before merging. 3. Conversely a conflict in an original LR(1) state survives the merge. Merging can introduce reduce-reduce conflicts, but cannot create a new shift-reduce conflict. SLR/LR(0) may report conflicts avoided by finer LR(1) lookaheads.
Which is a top-down parser? Options: (A) Recursive descent (B) Operator precedence (C) LR(k) (D) LALR(k)
Your answer
Answer & solution
Answer: A (no official key was published)
1. Approach. Top-down parsing constructs a derivation beginning with the start symbol. Bottom-up parsing starts with input symbols and reduces them toward the start symbol.
2. Derivation and interpretation. Recursive descent starts from the grammar’s start symbol and expands productions while matching input, so it is top-down. Operator-precedence, LR and LALR parsers reduce handles bottom-up. Therefore A.
A grammar has nonterminals S,C,S1, terminals a,b,i,t,e, start S, and productions S→iCtSS1 | a; S1→eS | ε; C→b. Why is this grammar not LL(1)? Options: (A) It is left recursive (B) It is right recursive (C) It is ambiguous (D) It is not context-free
Your answer
Answer & solution
Answer: C (no official key was published)
1. Approach. Read i,t,e as if, then, else. In nested conditionals, an else can attach to either the inner or the outer if. Exhibit two parses of the same string to prove ambiguity.
2. Derivation and interpretation. The grammar is S→iCtSS₁ | a, S₁→eS | ε, C→b. It is the dangling-else grammar. The string i b t i b t a e a has two parse trees: the e a can belong to the inner conditional (inner S₁→eS, outer S₁→ε) or the outer conditional (inner S₁→ε, outer S₁→eS). Therefore it is ambiguous and cannot be LL(1), giving C. Equivalently e belongs both to FIRST(eS) and FOLLOW(S₁), causing a prediction-table conflict with S₁→ε. Right recursion by itself is not an obstruction to LL(1), and these productions are context-free and not left recursive.
Regular grammars versus existence of LR(1) grammars
Parsing & Syntax Analysis
Tap to enlarge
Consider P: Every regular grammar is LL(1). Q: Every regular language has an LR(1) grammar. Which is true? Options: (A) Both P and Q true (B) P true,Q false (C) P false,Q true (D) Both false
Your answer
Answer & solution
Answer: C (no official key was published)
1. Approach. P concerns every presentation of a language, whereas Q asks whether a suitable presentation exists. A language can have a poorly factored grammar even though another grammar parses deterministically.
2. Derivation and interpretation. P is false: the right-linear regular grammar S→aA | aB, A→b, B→c has two alternatives whose FIRST sets both contain a, so this particular grammar is not LL(1). Q is true: construct a grammar from a DFA by using one nonterminal per state, production Q→aR for each transition on a, and Q→ε for each accepting state. Determinism gives at most one alternative per terminal; epsilon is selected at end of input. This yields an LL(1), hence LR(1), grammar for the regular language (or use the standard inclusion of regular languages in deterministic context-free languages). Thus P false and Q true, option C.
Grammar: S→S*E | E; E→F+E | F; F→id. Consider LR(0) items 1: S→S*·E; 2: E→F·+E; 3: E→F+·E. Which pair appears together in a canonical item set? Options: (A) 1 and 2 (B) 2 and 3 (C) 1 and 3 (D) None of these pairs
Your answer
Answer & solution
Answer: D (no official key was published)
Step through it (12 steps)
1. The state after recognizing S* contains S→S*·E plus closure items E→·F+E,E→·F,F→·id. The item E→F·+E occurs after a transition on F, together with E→F·.
2. The item E→F+·E occurs after a further transition on +, again with the initial E/F closure. These three kernels are different states; closure does not introduce either of the other listed advanced items.
3. Thus none of the listed pairs coexist, D.
4. Teaching check: LR closure inserts productions with the dot at their beginning when a nonterminal follows the dot. It never advances an existing dot. Thus an item beginning E→·F can coexist with item 1, but the advanced E→F·+E requires a GOTO on F, producing another state.
For grammar S→FR, R→*S|ε, F→id, what are predictive-table entries M[S,id] and M[R,$], respectively? Options: (A) {S→FR}, {R→ε} (B) {S→FR}, empty (C) {S→FR}, {R→*S} (D) {F→id}, {R→ε}
Your answer
Answer & solution
Answer: A (no official key was published)
Step through it (2 parts)
1. For S→FR, R→*S|ε, F→id, FIRST(FR)={id}; hence M[S,id]={S→FR}. Since S is the start symbol and R occurs at the end of S→FR, $ belongs to FOLLOW(R).
2. Therefore M[R,$]={R→ε}. Option A.
3. Teaching check: An LL(1) table uses FIRST of a nonempty production; ε productions use FOLLOW of their left-hand side. Since id begins FR, the S/id cell receives S→FR. Since R can end the start-symbol derivation, end marker $ belongs to FOLLOW(R).
Grammar A→AA|(A)|ε is unsuitable for predictive parsing because it is: A ambiguous; B left-recursive; C right-recursive; D an operator grammar. Assess the nonunique objections rather than forcing one choice.
Your answer
Answer & solution
Answer: Both A and B are valid objections (no official key was published)
The production A→AA is directly left-recursive, so a naive predictive recursive-descent parser can recur indefinitely before consuming input; this is B. The same grammar is also ambiguous: ε has the distinct derivations A→ε and A→AA→εA→ε, giving different parse trees. An ambiguous grammar cannot be LL(1), so A is also a valid reason. Therefore the single-choice wording does not uniquely distinguish these two objections. Right recursion alone is not a barrier to predictive parsing.
The production A→AA begins with the same nonterminal, so direct predictive expansion can recurse without consuming input. Independently, ε has distinct parse trees A⇒ε and A⇒AA⇒εε, demonstrating ambiguity. A grammar with these properties cannot be LL(1), making both A and B valid reasons in the literal single-choice wording. Right recursion alone is not an objection to predictive parsing, and adjacent nonterminals also prevent the standard operator-grammar restriction.
Grammar E→E+n | E×n | n generates n+n×n. List the handles in bottom-up reduction order. A n, E+n, E+n×n; B n, E+n, E+E×n; C n, n+n, n+n×n; D n, E+n, E×n.
Your answer
Answer & solution
Answer: D (no official key was published)
Step through it (10 steps)
The rightmost derivation is E ⇒ E×n ⇒ E+n×n ⇒ n+n×n. Reversing it reduces the leftmost n first, then E+n, then E×n. These handles are n, E+n, E×n, option D. The fixed terminal n on the right of each operator means this is not the usual ambiguous E→E+E|E×E grammar.
A handle is the RHS whose reduction undoes one step of a rightmost derivation, not an arbitrary matching substring. Reverse the displayed derivation: n+n×n→E+n×n→E×n→E. The successive reduced RHS strings are n, E+n and E×n. Reducing the rightmost terminal n first would not reverse this rightmost derivation. The grammar’s fixed terminal right operands force the association, unlike E→E+E.
For S→(S)|a, let n1, n2, n3 count SLR(1), canonical LR(1), LALR(1) states. In GFG: A n1<n2<n3; B n1=n3<n2; C n1=n2=n3; D n1=n3=n2 (duplicated equality as reproduced). Determine the actual counts independently; alternate distractor ordering differs.
Your answer
Answer & solution
Answer: B (no official key was published)
For augmented S′→S and S→(S)|a, LR(0) has six states with kernels S′→·S, S′→S·, S→(·S), S→a·, S→(S·), and S→(S)· (including closures). Canonical LR(1) separates the inner/non-inner versions with lookaheads ) and $, yielding ten states. Merging identical LR(0) cores gives six LALR states again. Therefore n1=n3<n2, B.
SLR states are LR(0) item-set states, so its FOLLOW-based action construction does not add states. The six cores are listed in the baseline derivation. Canonical LR(1) retains context: an expression enclosed by parentheses must expect a closing parenthesis, whereas the outer expression expects end-of-input, creating extra versions of cores and ten states. LALR merges versions sharing the same LR(0) core, restoring six. Therefore 6=6<10 in the order n1, n3, n2.
Expression grammar E→number | E+E | E×E has the usual synthesized arithmetic values and is given to yacc without precedence/associativity declarations. Printed 83(a): yacc A detects/eliminates recursion; B resolves reduce/reduce conflict; C resolves shift/reduce in favor of shift; D resolves shift/reduce in favor of reduce.
Your answer
Answer & solution
Answer: C (no official key was published)
The grammar E→number | E+E | E×E is ambiguous. After recognizing E+E or E×E, a following operator permits either reduction of the completed expression or shifting to build the right operand further. This is a shift/reduce conflict. With no precedence/associativity declarations, yacc defaults to shifting, option C; left recursion itself is valid for LR parsing.
After E+E has been recognized and a further operator is seen, the parser can either reduce the completed expression now or shift the operator to extend its right operand. The grammar does not specify which grouping is intended, hence a shift/reduce conflict. yacc’s default selects shift. Left recursion is supported naturally by LR parsing and is not removed automatically; no two distinct completed production reductions cause this particular ambiguity.
Expression grammar E→number | E+E | E×E has the usual synthesized arithmetic values and is given to yacc without precedence/associativity declarations. Printed 83(b): under its default resolution, how is 3×2+1 interpreted? A equal precedence, left associative, result 7; B equal precedence, right associative, result 9; C ×higher, left associative, result 7; D +higher, left associative, result 9.
Your answer
Answer & solution
Answer: B (no official key was published)
Using the default shift resolution from part(a), neither operator receives a special precedence declaration and pending operators are reduced from the right. Thus 3×2+1 is parsed as 3×(2+1)=9. This behaves as equal precedence and right associativity, option B. This conclusion is conditional on the default shift resolution, not on adding conventional arithmetic precedence declarations.
At the + following 3×2, shifting postpones reducing 3×2. The parser first combines 2+1, then multiplies that result by 3, giving 9. Applying the same shift default to repeated operators creates right association. This is not evidence of a declared higher precedence for+: the behavior is the equal-precedence default arising from unresolved conflicts. A user-supplied precedence declaration could intentionally change the result.
P,Q,R are nonterminals and r,s,t are terminals. Which rules violate the requirements for an operator grammar? (i) P→QR; (ii) P→QsR; (iii) P→ε; (iv) P→QtRr. Options: (A) i only (B) i and iii only (C) ii and iii only (D) iii and iv only
Your answer
Answer & solution
Answer: B (no official key was published)
1. An operator grammar forbids adjacent nonterminals on a right-hand side and, in the standard definition used here, empty productions. P→QR violates the first rule and P→ε the second.
2. P→QsR and P→QtRr separate nonterminals by terminals. Thus i and iii, B.
3. Teaching check: A right-hand side can contain several nonterminals provided terminals separate adjacent ones. Thus QsR and QtRr are permitted. The empty-production restriction belongs to the conventional operator-grammar definition used here; do not confuse this syntactic test with conflict-free operator-precedence parsing.
Which transformation suffices to turn an arbitrary context-free grammar into an LL(1) grammar? A. Removing left recursion alone; B. Left factoring alone; C. Both removing left recursion and left factoring; D. None of these.
Your answer
Answer & solution
Answer: D (no official key was published)
1. LL(1) requires a deterministic choice of production from one lookahead symbol. Factoring resolves shared prefixes and removing left recursion removes an immediate predictive-parsing obstacle; neither establishes the required disjoint prediction sets in all grammars. In particular LL(1) cannot describe every context-free language.
2. Removing left recursion and left factoring remove common obstacles but do not make every CFG LL(1). Inherently ambiguous CFLs have no unambiguous grammar, whereas every LL(1) grammar is unambiguous; some unambiguous CFLs also are not LL(1). Thus none of the proposed transformations suffices for an arbitrary CFG, D.
The SLR parser for grammar G has n₁ states and its LALR parser has n₂ states. Which relationship is necessary in the standard constructions? A. n₁<n₂; B. n₁=n₂; C. n₁>n₂; D. None of these.
Your answer
Answer & solution
Answer: B (no official key was published)
1. SLR states are sets of LR(0) items. Start with canonical LR(1) states for LALR and discard lookaheads to identify equal cores; merging those states leaves the reachable LR(0) cores. Different reduction entries in the tables do not create extra automaton cores.
2. SLR uses the canonical LR(0) item-state cores. LALR merges canonical LR(1) states that share an LR(0) core, leaving one state per such core. Thus their automata have the same number of states, n 1=n 2, B, under the conventional constructions, even though their reduction lookaheads and conflict behavior differ.
Predictive-table conflict for a dangling-else grammar
Parsing & Syntax Analysis
Tap to enlarge
For the grammar S→iEtSS′ | a; S′→eS | ε; E→b, consider the usual predictive parsing table M with end marker $. What are M[S′,e] and M[S′,$], respectively? A. {S′→eS}, {S′→ε} B. {S′→eS}, ∅ C. {S′→ε}, {S′→ε} D. {S′→eS,S′→ε}, {S′→ε}
Your answer
Answer & solution
Answer: D (no official key was published)
Step through it (2 parts)
1. FIRST(eS)={e}, so insert S′→eS in the e column. 2. S is the start symbol, so $∈FOLLOW(S). In S→iEtSS′, the first S is followed by nullable S′ whose nonempty FIRST is {e}; hence e∈FOLLOW(S) as well. 3. The final S′ inherits FOLLOW(S), giving FOLLOW(S′)={e,$}. For the ε production, put S′→ε in every FOLLOW column, therefore both e and $. 4. The resulting cells are {eS,ε} and {ε}, option D. The two entries in the e cell are the dangling-else conflict, so the grammar itself is not LL(1).
Solution: FIRST(eS)={e}, so the rule S′→eS enters M[S′,e]. Because S′ can be empty and follows S in S→iEtSS′, e belongs to FOLLOW(S), while $ belongs to FOLLOW(S) because S is the start symbol. The trailing S′ inherits FOLLOW(S), giving FOLLOW(S′)={e,$}. Thus S′→ε also enters both cells. The e cell contains both alternatives and the $ cell contains only ε, option D; the conflict means this grammar is not LL(1).
Consider S→CC and C→cC | d. This grammar is: A. LL(1) B. SLR(1) but not LL(1) C. LALR(1) but not SLR(1) D. LR(1) but not LALR(1)
Your answer
Answer & solution
Answer: A (no official key was published)
Step through it (2 parts)
1. C generates zero or more c symbols followed by d. Its alternatives begin with distinct terminal symbols: FIRST(cC)={c} and FIRST(d)={d}. 2. Neither C alternative is nullable, so no FIRST/FOLLOW overlap can create a second entry in its parsing-table cells. Put C→cC under c and C→d under d. 3. S has only one production; under either c or d use S→CC. No table cell has two choices. Thus one lookahead symbol always selects a production and the grammar is LL(1), A.
Solution: For C→cC|d the alternatives have disjoint FIRST sets {c} and {d}, and neither can derive ε. S has only its single production S→CC. Therefore every predictive-table cell has at most one production and the grammar is LL(1), option A. No stronger bottom-up distinction is needed.
Grammar E→E+E | E*E | id. Original22(a): Construct all parse trees for i+j*k, where i,j,k are identifiers.
Answer & solution
Answer: Two parse trees: +(i,*(j,k)) and *(+(i,j),k), with E→id at every identifier leaf. (no official key was published)
With productions E→E+E, E→E*E, E→id, the two full parse trees are:
Tree 1, root addition:
E
├── E
│ └── id(i)
├── +
└── E
├── E
│ └── id(j)
├── *
└── E
└── id(k)
Tree 2, root multiplication
E
├── E
│ ├── E
│ │ └── id(i)
│ ├── +
│ └── E
│ └── id(j)
├── *
└── E
└── id(k)
Here id(i), id(j), and id(k) denote the id tokens with those lexemes. Both yields are i + j * k. There are exactly two trees because the root split must be at one of the two operators, and each remaining two-identifier subtree has a unique possible split. Their grouping is i+(j*k) versus (i+j)*k.
Operator precedence in the ambiguous expression grammar
Parsing & Syntax Analysis
Tap to enlarge
Grammar E→E+E | E*E | id. Original22(b): What precedence, if any, does this grammar impose on * and +?
Answer & solution
Answer: No relative precedence is specified or enforced by this grammar. (no official key was published)
Both + and * are produced by the same nonterminal E, and the grammar allows both i+(j*k) and (i+j)*k for the same token string. It therefore does not enforce multiplication-before-addition or addition-before-multiplication. Saying merely that the operators have equal precedence is also incomplete: the grammar does not enforce associativity, so it does not define a unique parse even under that description. External parser precedence declarations could resolve conflicts, but they are not part of the supplied grammar.
Grammar E→E+E | E*E | id. Original22(c): Modify the grammar to obtain exactly one parse tree per string in the same language and a nonambiguous LALR(1) grammar.
Answer & solution
Answer: E→E+T | T; T→T*F | F; F→id. (no official key was published)
One replacement grammar is
E → E + T | T T → T * F | F F → id It accepts exactly the original token language id ((+|*) id)*, without introducing parentheses or changing which token strings are allowed. The E/T levels make * bind more tightly than +, and the left-recursive productions make repeated uses of either operator associate left. Thus i+j*k has only the i+(j*k) parse. This standard expression grammar is SLR(1), and hence LALR(1); separating the levels resolves the shift/reduce ambiguity. The original grammar specified no precedence, so multiplication-before-addition and left associativity are a legitimate choice of an unambiguous interpretation, not properties already forced by that grammar.
Which claim is false? An unambiguous grammar has identical leftmost and rightmost derivations; LL(1) parsing is top-down; LALR is more powerful than SLR; an ambiguous grammar cannot be LR(k) for any k.
Your answer
Answer & solution
Answer: A (no official key was published)
Step 1: Unambiguity means each generated string has one parse tree, hence one leftmost derivation and one rightmost derivation. It does not mean those two sequences of intermediate sentential forms are identical.
Step 2: For S→AB,A→a,B→b, the leftmost derivation is S⇒AB⇒aB⇒ab, while the rightmost one is S⇒AB⇒Ab⇒ab. The grammar is unambiguous, yet the derivations differ.
Thus A is false. LL(1) is top-down, LALR recognizes a strictly larger grammar class than SLR, and every LR(k) grammar is unambiguous.
Answer: FIRST(E)={a,(}; FIRST(A)={+,*,ε}; FOLLOW(E)=FOLLOW(A)={),$}. (no official key was published)
E→aA begins with a; E→(E) begins with (, so FIRST(E)={a,(}. A’s alternatives begin with + and *, or are empty, giving FIRST(A)={+,*,ε}. Put end marker $ into FOLLOW(E) because E is the start symbol. E→(E) adds ) to FOLLOW(E). E→aA puts A at the end, so FOLLOW(E) is included in FOLLOW(A). A→+E and A→*E put E at the end, so FOLLOW(A) is included in FOLLOW(E). Iterating these inclusions reaches the fixed point FOLLOW(E)=FOLLOW(A)={),$}. Neither + nor * follows E in this grammar; those operators start A.
Every occupied cell has exactly one production, so this grammar is LL(1). For example, on a+a the parser selects E→aA, matches a, uses A→+E, matches +, selects E→aA, matches a, then uses A→ε at end of input. The end marker is a parser marker, not a terminal in the original alphabet.
Answer: S→aR | bR; R→aR | bR | ε. (no official key was published)
In the standard transformation S→Sα1 | Sα2 | β1 | β2, choose α1=a, α2=b and β1=a, β2=b. Introduce a new nonterminal R and write S→aR | bR, R→aR | bR | ε. The initial S production contributes one mandatory letter; R generates any remaining sequence of a’s and b’s, including the empty suffix. Thus both grammars generate exactly all nonempty strings over {a,b}. No production now begins with its own left-hand nonterminal, directly or indirectly. The empty string remains excluded from S, as it was in the original grammar.
Grammar S→aSbS | bSaS | ε; construct all parse trees of abab and determine ambiguity.
Answer & solution
Answer: Exactly two parse trees; grammar is ambiguous. (no official key was published)
Step through it (2 derivations)
The root must use S→aSbS because the yield begins with a. Its explicit b can be the b at position 2 or position 4. These exhaust the possibilities. Use S[children] for an ordered parse-tree node; S[ε] is an empty production.
Tree 1: S[a, S[ε], b, S[a, S[ε], b, S[ε]]] Tree 2: S[a, S[b, S[ε], a, S[ε]], b, S[ε]]
Accessible tree description: in tree 1 the root’s first S is empty and its final S generates ab. In tree 2 its first S generates ba and its final S is empty. Their leftmost derivations are: S⇒aSbS⇒abS⇒abaSbS⇒ababS⇒abab. S⇒aSbS⇒abSaSbS⇒abaSbS⇒ababS⇒abab. The inner two-letter strings ab and ba each have only their direct production with both S children empty. Consequently there are precisely two trees, not merely at least two. Distinct trees with the same terminal yield prove ambiguity.
For input scanned left to right, does top-down parsing construct a leftmost derivation, its reverse, a rightmost derivation, or a reversed rightmost derivation?
Your answer
Answer & solution
Answer: A (no official key was published)
Step 1: A top-down parser starts from the start symbol and expands grammar symbols to match the input prefix. It expands the leftmost unprocessed nonterminal to produce the next input symbols.
Step 2: These expansions run in the forward direction from start symbol to terminal string, giving a leftmost derivation, A.
A reversed rightmost derivation characterizes standard bottom-up shift-reduce parsing instead.
Given E→E*F|F+E|F and F→F−F|id, which operator-precedence claim is true: * above +; − above *; + and − equal; + above *?
Your answer
Answer & solution
Answer: B (no official key was published)
Step 1: The only grammar productions introducing minus are inside F. Any operand F used by multiplication or addition is therefore formed before the surrounding E-level operation.
Step 2: For example id*id−id must have the minus within the right F, giving id*(id−id), rather than treating minus as an outer E-level operation. Thus minus binds more tightly than multiplication, B.
The E rules do not give a clean unambiguous ordering between + and *; some mixed expressions have multiple parses. F→F−F is itself associative-ambiguous. These ambiguities do not invalidate the separation placing minus at the tighter grammar level.
Grammar/SDTS: E→E1*T {E.val=E1.val*T.val}; E→T {E.val=T.val}; T→F−T1 {T.val=F.val−T1.val}; T→F {T.val=F.val}; F→2 {F.val=2}; F→4 {F.val=4}. Attributes are evaluated immediately after bottom-up reductions. Construct the parse tree for 4−2−4*2 and evaluate it.
Answer & solution
Answer: (4−(2−4))*2 = 12 (no official key was published)
Step through it (19 steps)
The grammar makes subtraction part of T and multiplication part of E. Thus subtraction binds more tightly than multiplication. Moreover T→F−T is right-recursive, so the subtraction chain groups to the right, not to the left. The annotated parse tree is:
Its left-to-right terminal yield is exactly 4−2−4*2. Bottom-up, the innermost T has value 4; its parent computes 2−4=−2; the next T computes 4−(−2)=6. E→T copies 6. The final right T has value 2, so the root computes 6*2=12. Ordinary arithmetic precedence would give a different result; here the supplied grammar, not familiar operator conventions, defines the grouping.
Which parser recognizes the broadest grammar class: LL(1), canonical LR, SLR, or LALR?
Your answer
Answer & solution
Answer: B (no official key was published)
Canonical LR(1) retains a full lookahead context in its states. SLR instead uses FOLLOW sets for reductions, and LALR merges states sharing LR(0) cores; both simplifications can create conflicts absent from the canonical construction. LL(1) is also a more restrictive deterministic grammar class. Consequently canonical LR is the most powerful among the choices, B. Power here concerns which grammars can be handled without conflicts, not implementation speed or table size.
A grammar is both left and right recursive for a nonterminal. Must it be ambiguous,unambiguous,or is more information required?
Select all that apply
Answer & solution
Answer: C literally; usefulness assumptions matter (no official key was published)
Both recursion directions can certainly occur in an ambiguous grammar: S→Sa|aS|a derives aa using either recursive rule. But the premise alone does not say that the recursive nonterminal is reachable and productive. For example S→c together with A→Aa|aA|b has both recursion directions at A, while the start language has just one parse tree for c. Thus the literal premise does not force ambiguity, giving C. The example deliberately exposes the omitted usefulness condition; it does not assert that an arbitrary useful doubly recursive nonterminal is harmless. The usual ambiguity claim needs a more precise grammar hypothesis.
Which is true about SLR, LALR, canonical LR power? C says canonical LR is more powerful than LALR.
Your answer
Answer & solution
Answer: C (no official key was published)
Canonical LR(1) retains separate lookahead contexts. LALR merges LR states with identical LR(0) cores; this can introduce reduce/reduce conflicts that did not exist before merging. SLR uses the still coarser FOLLOW-set reduction rule. Therefore the recognizable grammar classes satisfy SLR⊆LALR⊆canonical LR, with proper inclusions in general, giving C. This compares conflict-free grammar handling, not table compactness or parsing speed.
For S→Aa|b and A→Ac|Sd|ε, construct an equivalent grammar with no left recursion and the minimum number of productions. Count each alternative as a production.
Answer & solution
Answer: A valid six-alternative grammar is S→Ta|bdTa|b; T→cT|adT|ε. Global minimum among arbitrary CFGs is not certified. (no official key was published)
Substitute S→Aa|b into the occurrence S in A→Sd. Then A→Ac|Aad|bd|ε. Each recursive use appends either c or ad on the right; the base is either bd or ε. Thus L(A)=(ε∪{bd}){c,ad}*, and
L(S)={b} ∪ (ε∪{bd}){c,ad}*{a}.
Introduce T generating {c,ad}*. The following equivalent grammar has six individual alternatives:
S → Ta | bdTa | b T → cT | adT | ε
Every recursive T production starts with a terminal, so it cannot be left recursive. S is not reachable from T, and although S→Ta starts with a nonterminal, its nullable prefix cannot lead back to S. This also rules out indirect left recursion. The first two S alternatives select the two possible prefixes before a word from {c,ad}* and its final a; the third supplies the isolated word b. Conversely, each original derivation has exactly one of these forms, proving language equivalence.
For comparison, the usual mechanical elimination gives S→Aa|b, A→bdT|T, T→cT|adT|ε, with seven alternatives. Inlining A into S removes its two rules and replaces one S alternative by two, saving one production. The six-rule grammar is therefore smaller than that routine result.
The printed requirement “minimum number” needs care. This construction establishes an upper bound of six. It is not a proof that no differently structured, arbitrary CFG can use fewer alternatives. Counting a line with several bars as one “rule” would also give a different metric. The requested global minimum is left uncertified rather than asserted without a lower-bound proof; the equivalent non-left-recursive grammar itself is fully established.
Construct the LL(1) table for Program→begin d semi X end; X→d semi X | sY; Y→semi sY | ε. Treat begin,d,semi,s,end as terminals.
Answer & solution
Answer: Nonempty table entries: Program/begin; X/d,X/s; Y/semi,Y/end. (no official key was published)
Step through it (2 parts)
FIRST(Program)={begin}; FIRST(X)={d,s}; FIRST(Y)={semi,ε}. Program is the start symbol, so FOLLOW(Program)={$}. In Program's production, X is followed by end, hence FOLLOW(X)={end}. The occurrence Y at the end of X→sY gives FOLLOW(Y)={end}; its recursive production adds no new follower.
Fill a production in columns belonging to the FIRST set of its right side. For the ε production, use FOLLOW(Y). The complete non-error entries are:
Nonterminal | lookahead | production
Program | begin | Program→begin d semi X end
X | d | X→d semi X
X | s | X→sY
Y | semi | Y→semi sY
Y | end | Y→ε
Every other cell, including all cells under $, is an error for these nonterminals. The parsing stack accepts only when both its end marker and the input end marker match after Program is fully processed. There is no conflict: X's alternatives start with different terminals, and FIRST(semi sY)={semi} is disjoint from FOLLOW(Y)={end}. That establishes LL(1), rather than merely presenting a table without explaining why it works.
Answer: A: ⊕ left, ⊙ right (no official key was published)
In X→X⊕Y, additional⊕ operators are introduced inside the left X. Thus id⊕id⊕id groups as (id⊕id)⊕id. In Y→Z⊙Y, additional⊙ operators occur in the right Y, grouping id⊙id⊙id as id⊙(id⊙id). Therefore⊕ is left associative and⊙ right associative, A. The lower nonterminal level also makes⊙ bind more tightly, but precedence and associativity are distinct properties.
A language L is a subset of Pascal with expressions using only + and <, assignment statements, while statements, and compound statements begin ... end. Give an unambiguous grammar. The source does not specify lexical details, empty statements, or a trailing-semicolon convention.
Answer & solution
Answer: Use separate addition/comparison levels, one comparison per expression, and explicit statement/block productions. (no official key was published)
Here is one unambiguous grammar under the conventional choices that + binds more tightly than <, + associates to the left, and < is nonassociative. The lexer supplies tokens id and num; reserved words are distinct tokens, and := is assignment. Start symbol S denotes one statement.
S → id := E | while E do S | begin L end L → S R R → ; S R | ε E → A | A < A A → A + P | P P → id | num | ( E )
The grammar deliberately uses nonempty compound statements with semicolons between statements, not after the last one. If empty blocks are required, add the separate production S→begin end. If an optional trailing semicolon is required, replace R by R→ε | ; T and T→ε | S R. These are explicit syntax extensions, not facts supplied by the question.
The expression hierarchy enforces a unique outer operator structure. An unparenthesized < must be the single comparison at the E level, so a+b<c+d parses as (a+b)<(c+d), and a<b<c is rejected unless parentheses explicitly group a comparison. Left recursion at A gives (a+b)+c, not a+(b+c). Parentheses delimit a complete nested expression. At statement level, id, while and begin select disjoint alternatives. The keyword do separates a while condition from its body; matching begin/end delimit a compound body, and semicolons separate its statements. There is no if/else construct and hence no dangling-else ambiguity.
For example, while x<y+1 do begin x:=x+1; y:=y+2 end has a unique parse: its loop body is the entire block, containing two assignments. Static type rules, such as requiring a Boolean while condition and compatible assignment types, belong to semantic analysis rather than this context-free grammar. The source does not uniquely determine every optional Pascal syntax feature; the stated conventions make this proposed grammar precise.
For stmt→if id then stmt | if id then stmt else stmt | id:=id, which listed nested-if statement is ambiguous?
Your answer
Answer & solution
Answer: D: the nested-if statement with one dangling else (no official key was published)
An else following two unfinished nested if statements can attach either to the inner if or to the outer if. These choices produce different parse trees under the given grammar: if p then (if q then s else t), versus if p then (if q then s) else t. Both yield the same token sequence. The nested statement in D has precisely this form. A language implementation may impose “else matches the nearest if,” but that extra convention does not remove ambiguity from the grammar as printed.
Pascal executes X:=−10; Y:=20; if X>Y then if X<0 then X:=abs(X) else X:=2*X. What is X?
Your answer
Answer & solution
Answer: C: −10 (no official key was published)
The outer condition X>Y evaluates as −10>20, which is false. Its entire then statement, including the nested if and its else, is skipped. Therefore neither abs(X) nor doubling executes, and X stays −10. Pascal associates the else with the nearest unmatched if, namely the inner X<0 test. Treating that else as belonging to the outer test would incorrectly execute the doubling branch and obtain −20.
Construct the LL(1) table for productions: 1 E→−E; 2 E→(E); 3 E→V T; 4 T→−E; 5 T→ε; 6 V→id U; 7 U→(E); 8 U→ε; 9 G→E$. Here E=Expr,T=ExprTail,V=Var,U=VarTail,G=Goal; $ is the end marker.
Answer & solution
Answer: Non-error entries: E: −→1, (→2, id→3; T: −→4, )/$→5; V: id→6; U: (→7, −/)/$→8; G: −/(/id→9. (no official key was published)
FIRST(E)={−,(,id}, FIRST(T)={−,ε}, FIRST(V)={id}, FIRST(U)={(,ε}, and FIRST(G)={−,(,id}. E can be followed by a closing parenthesis in productions 2 and 7, or by $ in production 9. Its appearances at the ends of productions 1 and 4 add no new terminals. Hence FOLLOW(E)=FOLLOW(T)={),$}. From E→VT, FOLLOW(V)={−,),$}; U is at the end of V→idU, so FOLLOW(U)={−,),$}.
Place each nonnullable production under the terminals in its right-hand FIRST set. Place each ε-production under FOLLOW of its left-hand side. The complete table, listing columns in the order −, (, id, ), $, is: E: [1,2,3,error,error] T: [4,error,error,5,5] V: [error,error,6,error,error] U: [8,7,error,8,8] G: [9,9,9,error,error].
No cell has two productions, establishing the LL(1) property. Parentheses and the minus token are literal terminals; λ in the source denotes ε, not an input token. If $ is treated as an explicit grammar terminal, a separate meta-end marker follows it, without changing these table choices.
Construct an ordinary CFG for assignment id:=expression, for id:=expression to expression do statement, and begin statement;…;statement end. expression is already defined. Do not use EBNF optional brackets or star.
Answer & solution
Answer: S→id := E | for id := E to E do S | begin L end; L→S | S ; L. (no official key was published)
Let S denote a statement, L a nonempty statement list, E the given expression nonterminal, and id an identifier token. Use: S → id := E S → for id := E to E do S S → begin L end L → S L → S ; L
The first production recognizes assignments. The second has a statement as its body, permitting either a single assignment, another loop, or a block. The third encloses a list in begin/end. The two L productions generate exactly one or more statements separated by semicolons, without a trailing semicolon. They replace the informal ellipsis with ordinary CFG recursion; no repetition operator or optional metasyntax is used.
For any finite list length k≥1, apply L→S;L exactly k−1 times and finish with L→S. Conversely each derivation has precisely that separator structure. An empty block is not explicitly requested; if the language separately permits begin end, add an epsilon-list production as an explicit extension rather than silently changing the language. Expression syntax is delegated to the provided E grammar.
Using S→id:=E | for id:=E to E do S | begin L end and L→S | S;L, draw the parse tree for: for j:=2 to 10 do begin x:=expr1; y:=expr2 end.
Answer & solution
Answer: Root loop S, body block S, two assignment statements linked by L→S;L. (no official key was published)
The outermost construct is the for production, not a sequencing block. Its body is one statement S expanded as begin L end. Inside that block the list has two assignments, so its first L uses S;L and its final L uses S.
Reading leaves left to right gives exactly the requested token sequence. The E subtrees are abbreviated because the expression grammar was stipulated as already defined; 2 and 10 are constant expressions and expr1/expr2 stand for their expression subtrees. The semicolon separates the two assignments, while begin/end make both assignments part of a single loop body.
FOLLOW(A) uses arbitrary sentential forms; LFOLLOW/RFOLLOW restrict to leftmost/rightmost forms. Both sources lose the L/R prefixes in choices A/B. Determine valid semantic relationships.
Select all that apply
Answer & solution
Answer: Option letters unresolved; LFOLLOW may differ, and RFOLLOW=FOLLOW under a productive-grammar convention (no official key was published)
Restricted derivations yield subsets of the ordinary FOLLOW set. For S→AB, A→a, B→b, ordinary and rightmost derivations expose Ab, so b belongs to FOLLOW(A) and RFOLLOW(A). Leftmost derivations must expand A before B, so LFOLLOW(A) is empty. This refutes the choices asserting all three always identical or all three always different. For productive grammars, rightmost derivations can realize the needed right context, giving RFOLLOW=FOLLOW. Without that convention, S→XB, X→Ab, B→B gives FOLLOW(A) containing b but no rightmost occurrence of A. Since A/B repeat the unqualified name FOLLOW in both copies, their intended exact comparisons and letters are not reconstructed silently.
For one CFG, compare SLR(1) and LALR(1) tables: goto parts may differ; shifts identical; reductions may differ; errors may differ.
Select all that apply
Answer & solution
Answer: B, C, D under aligned LR(0)-core state numbering (no official key was published)
Both constructions use the same LR(0) cores for transitions, so terminal shifts and nonterminal gotos coincide when corresponding states are identified. SLR places a completed A production on every token in FOLLOW(A). LALR instead uses the lookaheads propagated to that completed item, often a smaller set. Thus a cell that is a reduction or conflict in SLR may be an error or a different action set in LALR. Therefore shifts are identical but reduction/error entries may differ. Renaming state numbers does not count as a structural goto difference; conflict-resolution policies are separate from raw table construction.
For arithmetic expressions using binary, mathematically nonassociative operators minus and division, the start symbol is E and the grammar is E→E−T | T; T→T/F | F; F→(E) | id. Is it unambiguous? If so state relative precedence; otherwise provide an unambiguous grammar giving division higher precedence.
Answer & solution
Answer: Unambiguous; / has higher precedence than −, and each operator is parsed left-associatively. (no official key was published)
The grammar separates expression levels: E combines terms with minus, while T combines factors with division. Thus id−id/id parses as id−(id/id), never as (id−id)/id. Division has higher precedence than subtraction.
Both recursive productions are left-recursive, so unparenthesized chains group to the left. For example id−id−id has structure (id−id)−id, and id/id/id has structure (id/id)/id. This is a syntactic associativity convention; it does not claim the arithmetic operators obey an associative law.
For uniqueness, consider an expression outside its matched parentheses. If it has a top-level minus, the root must be E→E−T, split at its last such minus because T cannot contain an unparenthesized minus. If there is no such minus, use E→T. Similarly a top-level slash in a term forces T→T/F split at its last top-level slash, since F cannot contain an unparenthesized slash. At the factor level, either the token is id or the uniquely matched outer parentheses contain an expression, to which the same argument applies. Induction on expression length gives a unique parse. Redundant parentheses are allowed by the grammar, but do not create two parses for the same token string.
For arithmetic expressions using binary, mathematically nonassociative operators minus and division, the start symbol is E and the grammar is E→E−T | T; T→T/F | F; F→(E) | id. Does it permit redundant parentheses such as (id/id) and id−(id/id)? Modify it to eliminate redundant parentheses, making minimal changes and adding at most one production rule.
Answer & solution
Answer: Yes. E→T|S; S→E−T|E−(S); T→id|T/F|(S)/F; F→id|(S)|(T/F)|((S)/F). Only the production group S is added. (no official key was published)
The original grammar allows both examples through F→(E). Deleting parentheses must be judged by preservation of the parse tree under / precedence and left associativity, not accidental numerical identities for particular values. Parentheses are needed around a subtraction in either operand of division, around a division in the right operand of division, and around a subtraction in the right operand of subtraction. They are not needed around a whole expression, a single id, a left operand at equal precedence, or a division used as a subtraction operand.
Use the following four-nonterminal grammar: E→T | S S→E−T | E−(S) T→id | T/F | (S)/F F→id | (S) | (T/F) | ((S)/F)
S is exactly subtraction-rooted, while T/F and (S)/F together are exactly division-rooted. This grammar generates every binary expression tree with no removable parenthesis pair. F appears only after /, preventing redundant outer parentheses. Examples: it generates id−(id−(id−id)) and id/((id−id)/id), but rejects (id/id), id−(id/id), (id), and ((id−id))/id. The source’s “one more production rule” is interpreted in the common sense of one more nonterminal production group: only S is added to E,T,F. All three original groups must change to prevent the old whole-expression wrapping while preserving needed contexts. A global minimum in number of RHS alternatives is not claimed because the source does not define its edit metric.
For arithmetic expressions using binary, mathematically nonassociative operators minus and division, the start symbol is E and the grammar is E→E−T | T; T→T/F | F; F→(E) | id. Part (b) requires necessary-parentheses-only expressions. For the grammar E→T|S; S→E−T|E−(S); T→id|T/F|(S)/F; F→id|(S)|(T/F)|((S)/F), remove left recursion.
Answer & solution
Answer: E→TR; R→−TR|−(S)R|ε; S→T−TR|T−(S)R; T→idU|(S)/FU; U→/FU|ε; F→id|(S)|(T/F)|((S)/F). (no official key was published)
First notice the indirect cycle E→S→E−T or E−(S). Removing only the obvious T→T/F recursion is insufficient. Substitute S’s alternatives into E to obtain E→T | E−T | E−(S). Its recursive suffixes are −T and −(S); its base is T. Introduce a tail R: E→T R R→−T R | −(S) R | ε.
S must still mean a subtraction-rooted expression, not an arbitrary E. Substituting E=T R into S initially gives S→T R−T | T R−(S). This is valid, but an equivalent clearer form selects the first subtraction and then any remaining subtraction tail: S→T−T R | T−(S) R. Both describe a T followed by a nonempty sequence of subtraction suffixes. Their ordering is preserved; the rewrite is about syntax, not commuting arithmetic operations.
Remove T’s immediate recursion T→T/F | id | (S)/F using a new tail U: T→id U | (S)/F U U→/F U | ε. Keep F→id | (S) | (T/F) | ((S)/F).
The complete grammar is the six displayed groups E,R,S,T,U,F. Every nonempty derivation of T begins with id or “(”. E and S begin through T; F directly begins with id or “(”; R begins with “−” or ε, and U with “/” or ε. No nonterminal can derive itself as the leftmost symbol, so neither direct nor indirect left recursion remains. The language is unchanged by the standard tail transformation. When constructing semantic actions, fold each R or U sequence leftward to retain the original left-associative parse: right-recursive grammar tails must not accidentally change subtraction or division evaluation order. The at-most-one-extra-production restriction belongs to part (b); part (c) requires the additional tail nonterminals.