Compiler Design

105601
Back to Compiler Design

Module 2: Syntax Analysis (Parser)

  1. Q1a. Which of the following is the most powerful parser? (i) SLR (ii) LALR (iii) Canonical LR (iv) Operator precedence20232m

    Module 2: Syntax Analysis (Parser)

    Which of the following is the most powerful parser?
    (i) SLR
    (ii) LALR
    (iii) Canonical LR
    (iv) Operator precedence

    View this question on its own page →
    Worked Solution

    Answer: (iii) Canonical LR

    Explanation

    Parsers can be ordered by the size of the grammar class they can handle (their power):

    • Operator-precedence parsing: only works on operator grammars (no ϵ\epsilon, no two adjacent nonterminals) — the least general.
    • SLR(1): uses the LR(0) items but decides reduce actions using the broad FOLLOW\mathrm{FOLLOW} set of the left-hand nonterminal, ignoring the specific context of each item → weaker.
    • LALR(1): merges LR(1) items that share the same core (same item, different lookahead). More powerful than SLR(1).
    • Canonical LR / LR(1): keeps every lookahead separate, producing the most states and therefore accepting the largest set of grammars among the given options.

    Hence the most powerful parser is:

    (iii) Canonical LR (LR(1))\boxed{\text{(iii) Canonical LR (LR(1))}}

    Order of power (weakest → strongest):
    Operator-precedence < SLR(1) < LALR(1) < Canonical LR(1)

  2. Q1b. A top down parser generates (i) Rightmost derivation (ii) Rightmost derivation in reverse (iii) Leftmost derivation (iv) Left most derivation in reverse20232m

    Module 2: Syntax Analysis (Parser)

    A top down parser generates
    (i) Rightmost derivation
    (ii) Rightmost derivation in reverse
    (iii) Leftmost derivation
    (iv) Left most derivation in reverse

    View this question on its own page →
    Worked Solution

    Answer: (iii) Leftmost derivation

    Explanation

    A top-down parser starts from the start symbol (root) and tries to derive the input string by expanding nonterminals in leftmost order — i.e. it always expands the leftmost nonterminal first.

    • Leftmost derivation: each step replaces the leftmost nonterminal — this is exactly what a top-down (recursive-descent / predictive / LL) parser constructs.
    • Rightmost derivation: each step replaces the rightmost nonterminal — not what a top-down parser does.
    • Rightmost derivation in reverse / handle pruning: that is the basis of bottom-up parsing (LR parsers), not top-down.

    Therefore a top-down parser generates a

    (iii) Leftmost derivation\boxed{\text{(iii) Leftmost derivation}}

  3. Q1c. Which of the following is a problem for a top-down parser? (i) Left recursion (ii) Right recursion (iii) Ambiguity only (iv) Bottom-up derivation20262m

    Module 2: Syntax Analysis (Parser)

    Which of the following is a problem for a top-down parser?
    (i) Left recursion
    (ii) Right recursion
    (iii) Ambiguity only
    (iv) Bottom-up derivation

    View this question on its own page →
    Worked Solution

    Answer: (i) Left recursion

    Explanation

    A grammar is left recursive if it has a rule of the form A→Aα∣βA \to A\alpha \mid \beta.

    A top-down (recursive-descent / LL) parser expands the leftmost non-terminal first. For A→AαA \to A\alpha it would call A() which immediately calls A() again without consuming any input, so it falls into an infinite loop.

    Fix: eliminate left recursion

    A→Aα∣β    ⟹    A→βA′,A′→αA′∣εA \to A\alpha \mid \beta \;\;\Longrightarrow\;\; A \to \beta A',\quad A' \to \alpha A' \mid \varepsilon

    • Right recursion (A→αAA \to \alpha A) is harmless for top-down parsers.
    • Ambiguity affects all parsers, but it is not the characteristic problem of top-down parsing, and option (iii) says "only".

    (i) Left recursion\boxed{\text{(i) Left recursion}}

  4. Q1d. In bottom-up parsing, the parser constructs: (i) Leftmost derivation (ii) Rightmost derivation (iii) Reverse of a rightmost derivation (iv) Leftmost derivation in reverse20262m

    Module 2: Syntax Analysis (Parser)

    In bottom-up parsing, the parser constructs:
    (i) Leftmost derivation
    (ii) Rightmost derivation
    (iii) Reverse of a rightmost derivation
    (iv) Leftmost derivation in reverse

    View this question on its own page →
    Worked Solution

    Answer: (iii) Reverse of a rightmost derivation

    Explanation

    A bottom-up (shift-reduce) parser starts from the input string and repeatedly reduces a handle to a non-terminal until the start symbol is reached.

    Each reduction undoes one step of a rightmost derivation, so the sequence of reductions is a rightmost derivation traced backwards.

    Example for E→E+E∣idE \to E+E \mid id on id+idid + id:

    • Rightmost derivation: E⇒E+E⇒E+id⇒id+idE \Rightarrow E+E \Rightarrow E+id \Rightarrow id+id
    • Reductions performed by the parser: id+id→E+id→E+E→Eid+id \to E+id \to E+E \to E (exactly the reverse).

    (Top-down parsers build a leftmost derivation; options (i), (ii), (iv) are wrong.)

    (iii) Reverse of a rightmost derivation\boxed{\text{(iii) Reverse of a rightmost derivation}}

  5. Q1e. Handle pruning forms the basis of........ (i) Bottom up parsing (ii) Top down parsing (iii) Predictive parsing (iv) Recursive descent parsing20232m

    Module 2: Syntax Analysis (Parser)

    Handle pruning forms the basis of........
    (i) Bottom up parsing
    (ii) Top down parsing
    (iii) Predictive parsing
    (iv) Recursive descent parsing

    View this question on its own page →
    Worked Solution

    Answer: (i) Bottom-up parsing

    Explanation

    • A handle is a substring of a (right) sentential form that matches the right-hand side of a production, and whose reduction brings us one step closer to the start symbol when reduced.
    • Handle pruning is the process of repeatedly finding the handles (finding the rightmost such substring during a rightmost reduction) and reducing them — from the input string up to the start symbol.
    • This is precisely how a bottom-up parser (shift-reduce / LR parser) works: it repeatedly reduces handles until the entire input has been reduced to the start symbol.

    Top-down parsing, predictive parsing, and recursive-descent parsing all work top-down (expanding the root) and do not prune handles.

    (i) Bottom up parsing\boxed{\text{(i) Bottom up parsing}}

  6. Q1f. Left factoring guarantees (i) Not occurring of backtracking (ii) Cycle free parse tree (iii) Error free target code (iv) Correct LL(1) parsing table20232m

    Module 2: Syntax Analysis (Parser)

    Left factoring guarantees
    (i) Not occurring of backtracking
    (ii) Cycle free parse tree
    (iii) Error free target code
    (iv) Correct LL(1) parsing table

    View this question on its own page →
    Worked Solution

    Answer: (i) Not occurring of backtracking

    Explanation

    • Left factoring is a grammar transformation that factors out the common prefix of two or more production alternatives.
    • It is used to remove uncertainty about which alternative to choose when a common prefix could lead to two different nonterminal, which otherwise forces the parser to backtrack while building a predictive (LL) parser.

    How it works:
    A→αβ1∣αβ2  ⇒  A→αA′,A′→β1∣β2A \to \alpha\beta_1 \mid \alpha\beta_2 \;\Rightarrow\; A \to \alpha A', \quad A' \to \beta_1 \mid \beta_2

    In an LL(1) (predictive top-down) parser the decision is made by looking at the first token; factoring out a common prefix ensures the choice is deterministic, so backtracking never occurs.

    Hence left factoring guarantees:
    (i) Not occurring of backtracking\boxed{\text{(i) Not occurring of backtracking}}

  7. Q1g. Consider a grammar A \to a S_1 | a S_2. The left factored grammar produced from the grammar is (i) A \to a A', A' \to S_1 | S_2 (ii) A' \to a A, A \to a S_1 | a S_2 (iii) A \to a A', A' \to S_1 | S_2, S_1 \to S_1, S_2 (iv) None of these20232m

    Module 2: Syntax Analysis (Parser)

    Consider a grammar A→aS1∣aS2A \to a S_1 | a S_2. The left factored grammar produced from the grammar is
    (i) A→aA′,A′→S1∣S2A \to a A', A' \to S_1 | S_2
    (ii) A′→aA,A→aS1∣aS2A' \to a A, A \to a S_1 | a S_2
    (iii) A→aA′,A′→S1∣S2,S1→S1,S2A \to a A', A' \to S_1 | S_2, S_1 \to S_1, S_2
    (iv) None of these

    View this question on its own page →
    Worked Solution

    Answer: (i) A→aA′, A′→S1∣S2A \to aA',\ A' \to S_1 \mid S_2

    Step 1 — left factoring

    Given grammar:
    A→aS1∣aS2A \to aS_1 \mid aS_2

    The two alternatives share the common prefix a. We factor it out into a new nonterminal A′A':

    A→aA′A \to aA'

    A′→S1∣S2A' \to S_1 \mid S_2

    This is the standard left-factored (CFG) form that removes backtracking uncertainty, because after reading a the parser chooses between S1S_1 and S2S_2 by looking at the next input, not by backtracking.

    Hence the correct answer is:

    (i) A→aA′, A′→S1∣S2\boxed{\text{(i)}\ A \to aA',\ A' \to S_1 \mid S_2}

  8. Q1j. For a grammar G, shift reduce (S-R) conflicts are present in LALR(1) parser, if and only if (i) The LAR (1) parser for G has S.R conflicts (ii) The LR(0) parser for G has S.R conflicts (iii) The SLR(1) parser for G has S.R conflicts (iv) The SLR(0) parser for G has S.R conflicts20232m

    Module 2: Syntax Analysis (Parser)

    For a grammar G, shift reduce (S-R) conflicts are present in LALR(1) parser, if and only if
    (i) The LAR (1) parser for G has S.R conflicts
    (ii) The LR(0) parser for G has S.R conflicts
    (iii) The SLR(1) parser for G has S.R conflicts
    (iv) The SLR(0) parser for G has S.R conflicts

    View this question on its own page →
    Worked Solution

    Answer: (i) The LR(1) parser for G has S–R conflicts

    Explanation — LALR vs LR relationship

    • LALR(1) parsers are built by merging the states of a canonical LR(1) parser that share the same core (same items, different lookaheads).
    • Merging states can create a reduce–reduce (R–R) conflict (two different reduce actions that were separated by lookahead now share a cell).
    • However, state-merging cannot create a new shift–reduce (S–R) conflict. Intuitively, a shift action exists on a terminal tt in a state only if tt is in that state's core in the LR(1) automaton too. So if the LALR(1) table has an S–R conflict, the same conflict must have already been present in the LR(1) table.

    Therefore the correct statement is the one in option (i) — the LR(1) parser for GG has S–R conflicts (with LAR(1) in the paper being a typo for LR(1)).

    (i) The LR(1) parser for G has S.R conflicts\boxed{\text{(i) The LR(1) parser for G has S.R conflicts}}

  9. Q3a. What are the advantages of LALR parsing over SLR and CLR methods?20235m

    Module 2: Syntax Analysis (Parser)

    What are the advantages of LALR parsing over SLR and CLR methods?

    View this question on its own page →
    Worked Solution

    Advantages of LALR(1) parsing over SLR(1) and canonical LR (CLR)

    Method Number of states Power Slots management
    SLR(1) fewest weakest (uses FOLLOW) smallest
    LALR(1) same as SLR between SLR and CLR larger
    Canonical LR (CLR/CLR(1)) the most strongest largest

    Advantages of LALR over SLR:

    1. LALR(1) accepts a larger grammar class than SLR(1): SLR reduces using FOLLOW\mathrm{FOLLOW}, which may cause spurious reduce–reduce and shift–reduce conflicts, because it ignores which attribute context produced the follow. LALR uses the precise lookahead symbols from the LR(1) items (merged by core), so fewer conflicts arise. Many grammars that are not SLR are LALR.
    2. It is still simple: LALR(1) lookaheads are "compatible" — no shift–reduce conflict is introduced by merging states.

    Advantages of LALR over canonical LR (CLR):

    1. Fewer states — In practice LALR(1) has roughly the same number of states as SLR(1), whereas a canonical LR(1) parser can have a very large state space (up to exponential in the grammar size). This makes LALR tables much more compact and memory-efficient.
    2. Faster table construction — merging reduces the number of states to process.
    3. It is the method of choice in practice: LALR(1) is used in tools like YACC / Bison because it is strong enough for almost all practical grammars yet keeps the table small — the "sweet spot" between SLR (too weak) and CLR (too many states).

    Trade-off: CLR may parse a slightly larger class, but its cost (huge state) is not justified in most cases. So LALR(1) is the best power/size ratio.

    LALR(1) : smaller (SLR-like) state count, near-CLR power → most practical; wins for memory and speed.\boxed{\text{LALR(1) : smaller (SLR-like) state count, near-CLR power → most practical; wins for memory and speed.}}

  10. Q3b. Write the algorithm to compute FIRST and FOLLOW for a given grammar.20235m

    Module 2: Syntax Analysis (Parser)

    Write the algorithm to compute FIRST and FOLLOW for a given grammar.

    View this question on its own page →
    Worked Solution

    Algorithm to compute FIRST and FOLLOW

    Notation: XX = nonterminal/terminal; α,β\alpha,\beta = strings of grammar symbols; ϵ\epsilon = empty string; $ = end marker.

    FIRST

    Compute FIRST(X1…Xn))FIRST(X_1\dots X_n)) = set of terminals that can start any string derivable from X1X2…XnX_1X_2\dots X_n (plus ϵ\epsilon if the whole can derive ϵ\epsilon).

    Rules (for individual symbol):

    1. If XX is a terminal, then FIRST(X)={X}\mathrm{FIRST}(X) = \{X\}.
    2. If XX is ϵ\epsilon production i.e. X→ϵX\to\epsilon, add ϵ\epsilon to FIRST(X)\mathrm{FIRST}(X).
    3. If XX is a nonterminal and X→Y1Y2…YkX\to Y_1Y_2\dots Y_k, then:
      • Put FIRST(Y1)\mathrm{FIRST}(Y_1) \textbackslash}{\epsilon} into FIRST(X)\mathrm{FIRST}(X).
      • If Y1Y_1 derives ϵ\epsilon, also put FIRST(Y2)∖{ϵ}\mathrm{FIRST}(Y_2)\setminus\{\epsilon\}, and so on.
      • If Y1..YkY_1..Y_k all can derive ϵ\epsilon, then put ϵ\epsilon into FIRST(X)\mathrm{FIRST}(X).
      • Order: For each production, apply until no more additions; repeat the whole loop until no change.

    For a string α=X1X2…Xn\alpha = X_1X_2\dots X_n :
    FIRST(α)=FIRST(X1)∖{ϵ}\mathrm{FIRST}(\alpha) = \mathrm{FIRST}(X_1) \setminus \{\epsilon\}; if ϵ∈FIRST(X1)\epsilon\in \mathrm{FIRST}(X_1), add FIRST(X2)∖{ϵ}\mathrm{FIRST}(X_2)\setminus\{\epsilon\}, etc.; if all XiX_i derive ϵ\epsilon, add ϵ\epsilon to FIRST(α)\mathrm{FIRST}(\alpha).

    2. Compute FOLLOW(X) for every nonterminal X

    Rule to find the set of terminals that can appear immediately to the right of XX in some sentential form.

    1. If XX is the start symbol, place `‘in` in \mathrm{FOLLOW}(X)$.
    2. For a production A→αBβA\to\alpha B\beta: everything in FIRST(β)\mathrm{FIRST}(\beta) except ϵ\epsilon goes into FOLLOW(B)\mathrm{FOLLOW}(B).
    3. If there is a production A→αBA\to\alpha B or A→αBβA\to\alpha B\beta where β⇝ϵ\beta \rightsquigarrow \epsilon (i.e. β\beta is nullable), then everything in FOLLOW(A)\mathrm{FOLLOW}(A) gets added to FOLLOW(B)\mathrm{FOLLOW}(B).
    4. Repeat these steps until no further additions occur.

    (Terminals/symbol ) that are not nonterminals have no FOLLOW.)

    These First/Follow results are then used to build the predictive (LL(1)) parsing table: for A→αA\to\alpha, put the production into M[A][a] for each a in FIRST(α)\mathrm{FIRST}(\alpha); if α\alpha nullable, put it into M[A][b] for each b in FOLLOW(A)\mathrm{FOLLOW}(A).

  11. Budget App•POCKETLY

    Pocketly on Android

    Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.

    Install Pocketly
  12. Q3b. Consider the grammar: S \to ABC A \to aA \mid \varepsilon B \to bB \mid \varepsilon C \to cC \mid d Compute the \text{FIRST} and \text{FOLLOW} sets for all non-terminals. Using these, construct the \text{LL}(1) parsing table. Use the parsing table to show the parsing steps for the input string "aabd".20267m

    Module 2: Syntax Analysis (Parser)

    Consider the grammar:
    S→ABCS \to ABC
    A→aA∣εA \to aA \mid \varepsilon
    B→bB∣εB \to bB \mid \varepsilon
    C→cC∣dC \to cC \mid d
    Compute the FIRST\text{FIRST} and FOLLOW\text{FOLLOW} sets for all non-terminals. Using these, construct the LL(1)\text{LL}(1) parsing table. Use the parsing table to show the parsing steps for the input string "aabd".

    View this question on its own page →
    Worked Solution

    Grammar

    S→ABCS \to ABC, A→aA∣εA \to aA \mid \varepsilon, B→bB∣εB \to bB \mid \varepsilon, C→cC∣dC \to cC \mid d

    FIRST sets

    • FIRST(A)={a,ε}\mathrm{FIRST}(A) = \{a, \varepsilon\}
    • FIRST(B)={b,ε}\mathrm{FIRST}(B) = \{b, \varepsilon\}
    • FIRST(C)={c,d}\mathrm{FIRST}(C) = \{c, d\}
    • FIRST(S)=(FIRST(A)∖ε)∪(FIRST(B)∖ε)∪FIRST(C)={a,b,c,d}\mathrm{FIRST}(S) = (\mathrm{FIRST}(A)\setminus\varepsilon) \cup (\mathrm{FIRST}(B)\setminus\varepsilon) \cup \mathrm{FIRST}(C) = \{a, b, c, d\} (since AA and BB can both vanish, CC is reached)

    FOLLOW sets

    • $\mathrm{FOLLOW}(S) = {$}$
    • FOLLOW(A)=(FIRST(B)∖ε)∪FIRST(C)={b,c,d}\mathrm{FOLLOW}(A) = (\mathrm{FIRST}(B)\setminus\varepsilon) \cup \mathrm{FIRST}(C) = \{b, c, d\} (from S→ABCS \to ABC, as BB is nullable)
    • FOLLOW(B)=FIRST(C)={c,d}\mathrm{FOLLOW}(B) = \mathrm{FIRST}(C) = \{c, d\}
    • $\mathrm{FOLLOW}(C) = \mathrm{FOLLOW}(S) = {$}$
    Non-terminal FIRST FOLLOW
    SS {a,b,c,d}\{a,b,c,d\} ${$}$
    AA {a,ε}\{a,\varepsilon\} {b,c,d}\{b,c,d\}
    BB {b,ε}\{b,\varepsilon\} {c,d}\{c,d\}
    CC {c,d}\{c,d\} ${$}$

    LL(1) parsing table

    • S→ABCS \to ABC: FIRST(ABC)={a,b,c,d}\mathrm{FIRST}(ABC) = \{a,b,c,d\}, so fill a,b,c,da,b,c,d.
    • A→aAA \to aA on aa; A→εA \to \varepsilon on FOLLOW(A)=b,c,d\mathrm{FOLLOW}(A) = b,c,d.
    • B→bBB \to bB on bb; B→εB \to \varepsilon on FOLLOW(B)=c,d\mathrm{FOLLOW}(B) = c,d.
    • C→cCC \to cC on cc; C→dC \to d on dd.

    | | aa | bb | cc | dd | \0 | `aabd | S→ABCS \to ABC | | 2 | ABC\1 | `aabd | match a |
    | 4 | ABC\2 | `abd| matcha | | 6 | ABC\3 | `bd | B→bBB \to bB |
    | 8 | bBC\4 | `d | B→εB \to \varepsilon | | 10 | C\5 | `d | match d |
    | 12 | $$∣‘ | `` | accept |

    The string aabd is accepted.

  13. Q3c. What is shift-reduce conflict?20234m

    Module 2: Syntax Analysis (Parser)

    What is shift-reduce conflict?

    View this question on its own page →
    Worked Solution

    What is a shift–reduce conflict?

    A shift–reduce conflict (S–R conflict) is a parsing-table conflict in an LR-family bottom-up parser: in one state (looking at one input symbol), the parser has both a valid shift action and a valid reduce action.

    Why it happens: When constructing the parsing table, a single cell M[state,terminal]M[\text{state}, \text{terminal}] ends up with two entries: one saying "shift a (push onto the stack / go to next state)" and the other saying "reduce using production A→αA\to\alpha". Since the parser cannot decide deterministically, the grammar is not LR with the given method (and the table entry is ambiguous).

    Example grammar with S–R conflict: classic ambiguous grammar
    E→E+E∣E∗E∣(E)∣idE\to E+E \mid E*E \mid (E) \mid \text{id}
    produces S–R conflict in LR(0)/SLR(1)/LALR(1) because, e.g. after parsing E + E . with input + or *, the parser doesn't know whether to shift the operator (deferring) or reduce E+E.

    Remedies:

    • Add precedence/associativity (%left, %right, %prec in YACC) — e.g. make * bind tighter than +.
    • Refactor the grammar to an unambiguous form (e.g. with separate term/factor levels).
    • Use a more powerful parsing method (canonical LR can resolve conflicts that SLR can't) — but a true ambiguity cannot be removed by switching methods.

    Reduction internal form: in LR table notation, a cell with both s and r actions is marked as a conflict, and the grammar is rejected by the parser generator (unless a rule like "shift wins on S–R conflict" is chosen YACC's default: prefer shift).

    S–R conflict = a parsing table state where shift and reduce are both valid → grammar not LR for that method.\boxed{\text{S–R conflict = a parsing table state where shift and reduce are both valid → grammar not LR for that method.}}

  14. Q4a. Explain ambiguity in context-free grammars. Illustrate how ambiguity can lead to shift-reduce or reduce-reduce conflicts during LR parsing.20267m

    Module 2: Syntax Analysis (Parser)

    Explain ambiguity in context-free grammars. Illustrate how ambiguity can lead to shift-reduce or reduce-reduce conflicts during LR parsing.

    View this question on its own page →
    Worked Solution

    Ambiguity in a context-free grammar

    A CFG is ambiguous if some string in its language has more than one parse tree (equivalently, more than one leftmost derivation or more than one rightmost derivation).

    Example: E→E+E∣E∗E∣idE \to E + E \mid E * E \mid id on the string id+id∗idid + id * id has two parse trees.

    MermaidDiagram
    Rendering diagram…

    The two trees give different meanings (different evaluation order), so the compiler cannot decide which one is intended.

    How ambiguity causes conflicts in LR parsing

    An LR parser must decide in every state whether to shift or reduce. An ambiguous grammar can never be LR(k) for any kk, so its LR table always has at least one multiply-defined entry.

    1. Shift-reduce conflict. For the grammar above, after reading E + E the parser reaches a state containing both items

    E→E+E⋅andE→E⋅∗EE \to E + E \cdot \qquad\text{and}\qquad E \to E \cdot * E

    On the next input symbol * it could reduce by E→E+EE \to E+E (giving tree 2) or shift * (giving tree 1). The table entry for (state, *) holds both s and r.

    2. Reduce-reduce conflict. Take S→A∣BS \to A \mid B, A→aA \to a, B→aB \to a. The string a has two parse trees. After shifting a the state contains

    A→a⋅andB→a⋅A \to a \cdot \qquad\text{and}\qquad B \to a \cdot

    On lookahead `‘theparsercanreduceby` the parser can reduce by A \to a∗∗or∗∗by **or** by B \to a$: two reduce actions in one cell.

    Removing the conflicts

    • Rewrite the grammar to enforce precedence and associativity: E→E+T∣TE \to E+T \mid T, T→T∗F∣FT \to T*F \mid F, F→idF \to id.
    • Or keep the grammar and resolve conflicts with rules (precedence: * binds tighter than +; left associativity), as Yacc/Bison do.
    • Shift is the default choice in a shift-reduce conflict; the earlier rule is chosen in a reduce-reduce conflict.
  15. Q4b. Find the FIRST an FOLLOW form the following production: S \to aBDh B \to cC C \to bC | \epsilon D \to EF E \to g | \epsilon F \to f | \epsilon20237m

    Module 2: Syntax Analysis (Parser)

    Find the FIRST an FOLLOW form the following production:
    S→aBDhS \to aBDh
    B→cCB \to cC
    C→bC∣ϵC \to bC | \epsilon
    D→EFD \to EF
    E→g∣ϵE \to g | \epsilon
    F→f∣ϵF \to f | \epsilon

    View this question on its own page →
    Worked Solution

    First and Follow for the given grammar

    Grammar:
    S→aBDhB→cCC→bC∣ϵD→EFE→g∣ϵF→f∣ϵ \begin{array}{rcl} S &\to& aBDh\\ B &\to& cC\\ C &\to& bC \mid \epsilon\\ D &\to& EF\\ E &\to& g \mid \epsilon\\ F &\to& f \mid \epsilon \end{array}

    Step 1 — FIRST sets

    Compute allowed terminals that begin derivations (plus ϵ\epsilon if nullable).

    • FIRST(a)={a}, FIRST(b)={b}, FIRST(c)={c}, FIRST(g)={g}, FIRST(f)={f}, FIRST(h)={h}\mathrm{FIRST}(a) = \{a\},\ \mathrm{FIRST}(b)=\{b\},\ \mathrm{FIRST}(c)=\{c\},\ \mathrm{FIRST}(g)=\{g\},\ \mathrm{FIRST}(f)=\{f\},\ \mathrm{FIRST}(h)=\{h\}
    • FIRST(C)={b,ϵ}\mathrm{FIRST}(C) = \{b, \epsilon\} (from C→bCC\to bC and C→ϵC\to\epsilon)
    • FIRST(E)={g,ϵ}\mathrm{FIRST}(E) = \{g, \epsilon\}
    • FIRST(F)={f,ϵ}\mathrm{FIRST}(F) = \{f, \epsilon\}
    • FIRST(D)\mathrm{FIRST}(D): D→EFD\to EF. FIRST(E)={g,ϵ}\{g,\epsilon\} → take gg; since E nullable, take FIRST(F)={f,ϵ}\{f,\epsilon\} → ff; since both nullable, include ϵ\epsilon.
      FIRST(D)={g,f,ϵ}\mathrm{FIRST}(D) = \{g, f, \epsilon\}
    • FIRST(B)={c}\mathrm{FIRST}(B) = \{c\} (from B→cCB\to cC). (B is not nullable since cc is a terminal.)
    • FIRST(S)\mathrm{FIRST}(S): S→aBDhS\to aBDh → starts with terminal a.
      FIRST(S)={a}\mathrm{FIRST}(S) = \{a\}

    Step 2 — FOLLOW sets

    The follow of a nonterminal XX is the set of terminals that can appear immediately to the right of XX in some sentential form.

    • FOLLOW(S)FOLLOW(S): S is the start symbol → ${$}$.
      FOLLOW(S)={$}\mathrm{FOLLOW}(S) = \{\$\}

    • FOLLOW(B)FOLLOW(B): from S→a B D hS\to a\,B\,D\,h, after BB comes DD, so we add FIRST(D)∖{ϵ}={g,f}\mathrm{FIRST}(D)\setminus\{\epsilon\} = \{g,f\}. Also DD is nullable, so we add $\mathrm{FOLLOW}(S) = {$}$.
      FOLLOW(B)={g, f, $}\mathrm{FOLLOW}(B) = \{g,\ f,\ \$\}

    • FOLLOW(C)FOLLOW(C): from B→c CB\to c\,C (C at the end), so FOLLOW(C)=FOLLOW(B)\mathrm{FOLLOW}(C) = \mathrm{FOLLOW}(B).
      FOLLOW(C)={g, f, $}\mathrm{FOLLOW}(C) = \{g,\ f,\ \$\}

    • FOLLOW(D)FOLLOW(D): from S→aBD hS\to aBD\,h, after DD comes terminal h.
      FOLLOW(D)={h}\mathrm{FOLLOW}(D) = \{h\}

    • FOLLOW(E)FOLLOW(E): from D→E FD\to E\,F, after EE comes FF, so add FIRST(F)∖{ϵ}={f}\mathrm{FIRST}(F)\setminus\{\epsilon\} = \{f\}. Since FF is nullable, also add FOLLOW(D)={h}\mathrm{FOLLOW}(D)=\{h\}.
      FOLLOW(E)={f, h}\mathrm{FOLLOW}(E) = \{f,\ h\}

    • FOLLOW(F)FOLLOW(F): from D→EFD\to EF (F at the end), so FOLLOW(F)=FOLLOW(D)\mathrm{FOLLOW}(F) = \mathrm{FOLLOW}(D).
      FOLLOW(F)={h}\mathrm{FOLLOW}(F) = \{h\}

    Final answer:
    FIRST(S)={a},FIRST(B)={c},FIRST(C)={b,ϵ},FIRST(D)={g,f,ϵ},FIRST(E)={g,ϵ},FIRST(F)={f,ϵ}{\small \mathrm{FIRST}(S)=\{a\},\quad \mathrm{FIRST}(B)=\{c\},\quad \mathrm{FIRST}(C)=\{b,\epsilon\},\quad \mathrm{FIRST}(D)=\{g,f,\epsilon\},\quad \mathrm{FIRST}(E)=\{g,\epsilon\},\quad \mathrm{FIRST}(F)=\{f,\epsilon\}}
    FOLLOW(S)={$},FOLLOW(B)={g,f,$},FOLLOW(C)={g,f,$},FOLLOW(D)={h},FOLLOW(E)={f,h},FOLLOW(F)={h}{\small \mathrm{FOLLOW}(S)=\{\$\},\quad\mathrm{FOLLOW}(B)=\{g,f,\$\},\quad\mathrm{FOLLOW}(C)=\{g,f,\$\},\quad\mathrm{FOLLOW}(D)=\{h\},\quad\mathrm{FOLLOW}(E)=\{f,h\},\quad\mathrm{FOLLOW}(F)=\{h\}}

  16. Q4b. Construct a transition diagram for the Pushdown Automaton for the language: L = \{ wcw^R \mid w \in \{a, b\}^* \}20267m

    Module 2: Syntax Analysis (Parser)

    Construct a transition diagram for the Pushdown Automaton for the language:
    L={wcwR∣w∈{a,b}∗}L = \{ wcw^R \mid w \in \{a, b\}^* \}

    View this question on its own page →
    Worked Solution

    PDA for L={wcwR∣w∈{a,b}∗}L = \{ w c w^R \mid w \in \{a,b\}^* \}

    Idea

    1. In state q0q_0, push every symbol of ww on the stack.
    2. On reading the middle marker c, move to q1q_1 without touching the stack.
    3. In q1q_1, each input symbol must match the stack top; pop it. This checks the second half is wRw^R (the stack reverses ww).
    4. When the input is finished and only Z0Z_0 remains, move to the accepting state q2q_2.

    Formal definition: M=({q0,q1,q2},{a,b,c},{a,b,Z0},δ,q0,Z0,{q2})M = (\{q_0,q_1,q_2\}, \{a,b,c\}, \{a,b,Z_0\}, \delta, q_0, Z_0, \{q_2\}) (acceptance by final state).

    Transition function δ\delta (notation: input, stack top / new stack top)

    # Move
    1 δ(q0,a,Z0)=(q0,aZ0)\delta(q_0, a, Z_0) = (q_0, aZ_0)
    2 δ(q0,b,Z0)=(q0,bZ0)\delta(q_0, b, Z_0) = (q_0, bZ_0)
    3 δ(q0,a,a)=(q0,aa)\delta(q_0, a, a) = (q_0, aa)
    4 δ(q0,a,b)=(q0,ab)\delta(q_0, a, b) = (q_0, ab)
    5 δ(q0,b,a)=(q0,ba)\delta(q_0, b, a) = (q_0, ba)
    6 δ(q0,b,b)=(q0,bb)\delta(q_0, b, b) = (q_0, bb)
    7 δ(q0,c,X)=(q1,X)\delta(q_0, c, X) = (q_1, X) for X∈{Z0,a,b}X \in \{Z_0, a, b\}
    8 δ(q1,a,a)=(q1,ε)\delta(q_1, a, a) = (q_1, \varepsilon)
    9 δ(q1,b,b)=(q1,ε)\delta(q_1, b, b) = (q_1, \varepsilon)
    10 δ(q1,ε,Z0)=(q2,Z0)\delta(q_1, \varepsilon, Z_0) = (q_2, Z_0)

    Transition diagram

    MermaidDiagram
    Rendering diagram…

    Trace for abcba

    State Remaining input Stack (top left) Move
    q0q_0 abcba Z0Z_0 push a
    q0q_0 bcba aZ0aZ_0 push b
    q0q_0 cba baZ0baZ_0 read c, go to q1q_1
    q1q_1 ba baZ0baZ_0 b matches, pop
    q1q_1 a aZ0aZ_0 a matches, pop
    q1q_1 ε\varepsilon Z0Z_0 ε\varepsilon-move to q2q_2
    q2q_2 ε\varepsilon Z0Z_0 accept

    A string such as abcab is rejected: after c the stack top is b but the input is a, so no move exists. The PDA is deterministic because c marks the middle.

  17. Q5a. Construct the predictive parsing table for the following grammars: S \to AaAb | BbBa A \to \epsilon B \to \epsilon20237m

    Module 2: Syntax Analysis (Parser)

    Construct the predictive parsing table for the following grammars:
    S→AaAb∣BbBaS \to AaAb | BbBa
    A→ϵA \to \epsilon
    B→ϵB \to \epsilon

    View this question on its own page →
    Worked Solution

    Predictive (LL(1)) parsing table

    Grammar:
    S→AaAb∣BbBaA→ϵB→ϵ S \to AaAb \mid BbBa\\ A \to \epsilon\\ B \to \epsilon

    Step 1 — FIRST and FOLLOW

    FIRST(A)={ϵ}\mathrm{FIRST}(A) = \{\epsilon\}, FIRST(B)={ϵ}\mathrm{FIRST}(B) = \{\epsilon\}.

    For S→AAAbS\to AAAb : because A→ϵA\to\epsilon, the first of the right-hand string is a. For S→BbBaS\to BbBa: the first is b. Hence:
    FIRST(S)={a,b}\mathrm{FIRST}(S) = \{a, b\}

    FOLLOW:

    • SS is start → $\mathrm{FOLLOW}(S) = {$ }$.
    • From S→AaAbS\to AaAb: the first AA is followed by a, the second AA by b.
      FOLLOW(A)={a,b}\mathrm{FOLLOW}(A) = \{a, b\}
    • From S→BbBaS\to BbBa: first BB followed by b, second BB by a.
      FOLLOW(B)={a,b}\mathrm{FOLLOW}(B) = \{a, b\}

    Step 2 — build table M[X][terminal]M[X][\text{terminal}]

    For each production X→αX\to\alpha, put X→αX\to\alpha into M[X][t]M[X][t] for every t∈FIRST(α)t\in \mathrm{FIRST}(\alpha); if α⇒ϵ\alpha \Rightarrow \epsilon, also put it into M[X][t]M[X][t] for every t∈FOLLOW(X)t\in\mathrm{FOLLOW}(X).

    • For S→AaAbS \to AaAb: FIRST(AaAb)={a}\mathrm{FIRST}(AaAb)=\{a\} → entry M[S][a]=S→AaAbM[S][a] = S\to AaAb.
    • For S→BbBaS \to BbBa: FIRST={b}\mathrm{FIRST}=\{b\} → M[S][b]=S→BbBaM[S][b] = S\to BbBa.
    • For A→ϵA\to\epsilon: place under FOLLOW(A)={a,b}\mathrm{FOLLOW}(A)=\{a,b\} → M[A][a]=A→ϵM[A][a]=A\to\epsilon, M[A][b]=A→ϵM[A][b]=A\to\epsilon.
    • For B→ϵB\to\epsilon: FOLLOW(B)={a,b}\mathrm{FOLLOW}(B)=\{a,b\} → M[B][a]=B→ϵM[B][a]=B\to\epsilon, M[B][b]=B→ϵM[B][b]=B\to\epsilon.

    Predictive parsing table (blank cells = error, no production):

    Nonterminal a b $
    SS S→AaAbS\to AaAb S→BbBaS\to BbBa —
    AA A→ϵA\to\epsilon A→ϵA\to\epsilon —
    BB B→ϵB\to\epsilon B→ϵB\to\epsilon —

    Verification: Every cell has at most one entry, so the grammar is LL(1) — no conflicts. This is the classic example of an LL(1) grammar with A→ϵ, B→ϵA\to\epsilon,\ B\to\epsilon that resolves the choice using lookahead.

  18. Q6a. What is handle? Consider the grammar: E \to E + E | E * E | id Find the handles of the right sentential forms of the reduction for the string id + id * id.20235m

    Module 2: Syntax Analysis (Parser)

    What is handle? Consider the grammar:
    E→E+E∣E∗E∣idE \to E + E | E * E | id
    Find the handles of the right sentential forms of the reduction for the string id+id∗idid + id * id.

    View this question on its own page →
    Worked Solution

    Handle; reduction of id + id * id with grammar E→E+E∣E∗E∣idE\to E+E \mid E*E \mid \text{id}

    What is a handle?

    A handle of a (right) sentential form is a substring that matches the right-hand side of some production, and whose reduction to the left-hand-side nonterminal is a step in a rightmost (reverse) derivation — that is, the rightmost handle that, when reduced, produces a valid step toward the start symbol.

    In shift–reduce parsing we repeatedly prune handles: shift symbols onto the stack until the top stack symbols match a production RHS, then reduce (replace the handle by its nonterminal).

    Find the handles for id + id * id

    Grammar: E→E+E∣E∗E∣idE\to E+E \mid E*E \mid id. The (unique, rightmost) reduction sequence:

    Stack (top shown last) Input Action Handle reduced
    id + id * id shift id —
    E + id * id reduce id → E handle id
    E + id * id shift + —
    E + id * id shift id —
    E + E * id reduce handle id (2nd)
    E + E * id shift * —
    E + E * id (empty) shift —
    E + E * E reduce handle id (3rd)
    E + E reduce E*E → E handle E*E
    E reduce E+E → E handle E+E

    Handles (in reduction order), with the actual substrings:

    • id (first id on the left)
    • id (the middle id)
    • id (the id after *)
    • E * E (the redex E*E → E)
    • E + E (the redex E+E → E)

    Written against the original string, the reduction is a reverse of the rightmost derivation:
    id+id∗id  →reduce idE+id∗id→reduce idE+E∗id→E+E∗E→E+E→Eid + id * id \;\xrightarrow{\text{reduce id}} E + id*id \xrightarrow{\text{reduce id}} E+E*id \xrightarrow{} E+E*E \xrightarrow{E+E} \xrightarrow{E}
    The seeds/handles reduced, going left-to-right on the string: the *ids**, then EE, then E + E`.

  19. Q6b. When a grammar is called ambiguous? Is there any technique to remove ambiguity? Justify whether the grammar is ambiguous or not? A \to AA | (A) | a20234m

    Module 2: Syntax Analysis (Parser)

    When a grammar is called ambiguous? Is there any technique to remove ambiguity? Justify whether the grammar is ambiguous or not?
    A→AA∣(A)∣aA \to AA | (A) | a

    View this question on its own page →
    Worked Solution

    Ambiguous grammar; ambiguity removal; is A→AA∣(A)∣aA \to AA \mid (A) \mid a ambiguous?

    1. When is a grammar called ambiguous?

    A grammar is called ambiguous when there exists at least one string in its language that has two or more distinct parse trees (equivalently, two different leftmost or two different rightmost derivations).

    2. Techniques to remove ambiguity

    • Grammar rewriting (precedence/associativity): restructure the grammar with separate levels, e.g. expr → expr + term | term, term → term * factor | factor, so that operators bind with the intended precedence and associativity.
    • Parser-tool directives: in YACC/Bison, use precedence declarations %left / %right / %nonassoc to resolve conflicts (e.g. %left '+', %left '*').
    • Explicit structure: for left-associative operators use left recursion; for the dangling-else problem use separate matched/unmatched statement nonterminals.
    • Caveat: removing ambiguity from an arbitrary grammar is undecidable in general, but for practical expression grammars these techniques work.

    3. Justify whether A→AA∣(A)∣aA \to AA \mid (A) \mid a is ambiguous

    Yes — this grammar is ambiguous.

    The string aaa has two distinct parse trees:

    • Tree 1 (grouping as a (a a)): root A → A A, left A → a, right A → A A with children a a:
           A
          / \
         a   A
            / \
           a   a
    
    • Tree 2 (grouping as (a a) a): root A → A A, left A → A A with children a a, right A → a:
           A
          / \
         A   a
       / \
      a   a
    

    Both trees derive the same string aaa with different structure ⇒ the grammar is ambiguous. The root cause is the production A→AAA \to AA — two adjacent occurrences of the same nonterminal admit two groupings of any consecutive run of a's.

    A fix for this grammar: make the concatenation left- or right-associative explicitly, e.g. A→A starA \to A\,\mathbf{star}, or add a priority marker — but more importantly, grammar A→AA∣a∣(A)A\to AA\mid a\mid (A) is inherently ambiguous, so a parser generator such as YACC would report a conflict for it. In practice prepend associativity info (%left) or rewrite to an unambiguous grammar such as A→A cat∣(A)∣aA \to A\,\text{cat} \mid (A) \mid a with cat a real operator.

    A→AA∣(A)∣a IS ambiguous — the string aaa has two parse trees.\boxed{\text{A} \to A A \mid (A) \mid a\ \text{IS ambiguous — the string } aaa \text{ has two parse trees.}}

  20. Q6c. Discuss about operator precedence parser.20235m

    Module 2: Syntax Analysis (Parser)

    Discuss about operator precedence parser.

    View this question on its own page →
    Worked Solution

    Operator-Precedence Parser

    1. What it is

    An operator-precedence (OP) parser is a bottom-up shift–reduce parser whose shift/reduce decision is based only on a precedence relation table between terminal symbols (operators) — not on a full LR state machine.

    2. Operator grammar preconditions

    The grammar must be an operator grammar:

    • no ϵ\epsilon-production,
    • no two adjacent nonterminals on any right-hand side.

    3. Precedence relations

    Between terminals a and b:

    • a⋖ba \lessdot b — a has lower precedence than b (→ shift b)
    • a≐ba \doteq b — equal precedence (→ shift)
    • a⋗ba \gtrdot b — a has higher precedence than b (→ reduce)

    Computed from the grammar using the FIRST/LAST terminal sets:

    • if α a B β\alpha\, a\, B\, \beta and b∈FIRST(B)b\in \mathrm{FIRST}(B) then a⋖ba \lessdot b;
    • if A→α ab βA\to \alpha\, a b\, \beta then a≐ba \doteq b;
    • if A→α B b βA\to \alpha\, B\, b\,\beta and a∈LAST(B)a\in \mathrm{LAST}(B) then a⋗ba \gtrdot b.

    This yields the operator-precedence matrix M[t1][t2]M[t_1][t_2] for all terminal pairs.

    4. Algorithm (stack with ‘atbottom;inputendswith‘` at bottom; input ends with `):

    1. Compare precedence of the input symbol with the relevant top-of-stack terminal.
    2. If top ⋖\lessdot next, or top ≐\doteq next → shift the next token.
    3. If top ⋗\gtrdot next → a handle boundary has been found: scan back until the first preceding ⋖\lessdot relation; the substring between them is the handle → reduce it to its nonterminal. No state/lookahead table needed.
    4. Accept when the stack holds exactly the start symbol with no input left.

    5. Example — id + id * id with precedence * > +

    stack: $ id + id * id
    shift id, shift +, shift id
    when `*` (input) and top `id` reduce id→E... 
    then top `*` vs input `+`: since `*` ⋗ `+`, reduce E*E before E+ 
    → matches the expected "multiply before add" behaviour.
    

    6. Advantages & disadvantages

    Advantages:

    • very fast (simple matrix lookup), small table,
    • easy to implement (no GOTO states).

    Disadvantages:

    • works only for operator grammars (no adjacent nonterminals, no ϵ\epsilon),
    • handle detection is purely local — it ignores surrounding context, so many real languages need LR/LALR instead,
    • usually used in small/expression-oriented compilers or inside calculator-style evaluators.

    Example precedence table (* binds tighter than +):

    op + *
    + ≐,⋗\doteq, \gtrdot ⋖\lessdot
    * ⋗\gtrdot ⋗\gtrdot

    Rule: shift on ⋖\lessdot / ≐\doteq, reduce on ⋗\gtrdot — which reproduces standard arithmetic precedence.

  21. Q7b. Consider the following grammar: E \to E + T | T T \to T * F | F F \to td Draw a SLR state transition diagram for the above grammar. Also draw the SLR parse table.20237m

    Module 2: Syntax Analysis (Parser)

    Consider the following grammar:
    E→E+T∣TE \to E + T | T
    T→T∗F∣FT \to T * F | F
    F→tdF \to td
    Draw a SLR state transition diagram for the above grammar. Also draw the SLR parse table.

    View this question on its own page →
    Worked Solution

    SLR parse for the grammar E→E+T∣TE\to E+T\mid T, T→T∗F∣FT\to T*F\mid F, F→idF\to \mathbf{id}

    (The paper spells the token td; we treat it as the identifier token id.)

    Augment with E′→EE'\to E.

    Productions numbering:

    1. E→E+TE\to E+T
    2. E→TE\to T
    3. T→T∗FT\to T*F
    4. T→FT\to F
    5. F→idF\to\mathbf{id}

    LR(0) canonical collection (states I0I_0–I8I_8):

    • I0I_0: E′→⋅E, E→⋅E+T, E→⋅T, T→⋅T∗F, T→⋅F, F→⋅idE'\to\cdot E,\ E\to\cdot E+T,\ E\to\cdot T,\ T\to\cdot T*F,\ T\to\cdot F,\ F\to\cdot\mathbf{id}
    • I1=goto(I0,E)I_1 = goto(I_0,E): E′→E⋅E'\to E\cdot, E→E⋅+TE\to E\cdot+T
    • I2=goto(I0,T)I_2 = goto(I_0,T): E→T⋅E\to T\cdot, T→T⋅∗FT\to T\cdot*F
    • I3=goto(I0,F)I_3 = goto(I_0,F): T→F⋅T\to F\cdot
    • I4=goto(I0,id)I_4 = goto(I_0,id): F→id⋅F\to \mathbf{id}\cdot
    • I5=goto(I1,+)I_5 = goto(I_1,+): E→E+⋅TE\to E+\cdot T, T→⋅T∗FT\to\cdot T*F, T→⋅FT\to\cdot F, F→⋅idF\to\cdot\mathbf{id}
    • I6=goto(I2,∗)I_6 = goto(I_2,*): T→T∗⋅FT\to T*\cdot F, F→⋅idF\to\cdot\mathbf{id}
    • I7=goto(I5,T)I_7 = goto(I_5,T): E→E+T⋅E\to E+T\cdot, T→T⋅∗FT\to T\cdot*F
    • I8=goto(I6,F)I_8 = goto(I_6,F): T→T∗F⋅T\to T*F\cdot

    GOTO transitions: 0→E1, 0→T2, 0→F3, 0→id40\xrightarrow{E}1,\ 0\xrightarrow{T}2,\ 0\xrightarrow{F}3,\ 0\xrightarrow{id}4;
    1→+51\xrightarrow{+}5; 2→∗62\xrightarrow{*}6; 5→T7, 5→F3, 5→id45\xrightarrow{T}7,\ 5\xrightarrow{F}3,\ 5\xrightarrow{id}4; 6→F8, 6→id46\xrightarrow{F}8,\ 6\xrightarrow{id}4; 7→∗67\xrightarrow{*}6.

    (This is the state-transition diagram; every state is a node and every label above is an edge.)

    FOLLOW sets:

    • $\mathrm{FOLLOW}(E)={+, $}(start)∪‘+‘from (start) ∪ `+` from E\to E+T$.
    • $\mathrm{FOLLOW}(T)={+,,$}$ (E→E+T ⇒ FOLLOW(E), T→TF ⇒ *).
    • $\mathrm{FOLLOW}(F)={+,*,$}$.

    SLR parsing table (ACTION + GOTO):

    State id + * $ E T F
    0 s4 1 2 3
    1 s5 acc
    2 r2 s6 r2
    3 r4 r4 r4
    4 r5 r5 r5
    5 s4 7 3
    6 s4 8
    7 r1 s6 r1
    8 r3 r3 r3
    • s n = shift and go to state n; r k = reduce by production kk (list above); acc = accept.
    • Uses FOLLOW: r4/r5 in states 3/4 for +, *, $ (in FOLLOW(T)/FOLLOW(F)) etc.

    No cell has two actions → the grammar is SLR(1) (a conflict-free table), and id + id * id is accepted.

  22. Budget App•POCKETLY

    Pocketly on Android

    Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.

    Install Pocketly
  23. Q8a. Consider the following grammar: S \to CC C \to cC | d Find the LR(1) set of items.20235m

    Module 2: Syntax Analysis (Parser)

    Consider the following grammar:
    S→CCS \to CC
    C→cC∣dC \to cC | d
    Find the LR(1) set of items.

    View this question on its own page →
    Worked Solution

    LR(1) sets of items for S→CCS\to CC, C→cC∣dC\to cC\mid d

    Augmented grammar: S′→SS'\to S.

    Items are written [A→α⋅β, a][A\to\alpha\cdot\beta,\ a] where a is the lookahead terminal.

    Closure hint: from $[S\to \cdot CC,\ $],thesymbolafterthedotis, the symbol after the dot is Candthelookaheadcontextof and the lookahead context of C\to\cdotsis is \mathrm{FIRST}(C$)={c,d},soinner, so inner C−itemsreceivelookaheads-items receive lookaheads {c,d}$.

    Canonical LR(1) collection:

    • I0I_0: $[S'\to\cdot S,$],\ [S\to\cdot CC,$],\ [C\to\cdot cC,\ c/d],\ [C\to\cdot d,\ c/d]$
    • I1I_1 = goto(I0,S)(I_0,S): $[S'\to S\cdot,$]$
    • I2I_2 = goto(I0,C)(I_0,C): $[S\to C\cdot C,$],\ [C\to\cdot cC,$],\ [C\to\cdot d,$]$
    • I3I_3 = goto(I0,c)(I_0,c): [C→c⋅C, c/d], [C→⋅cC, c/d], [C→⋅d, c/d][C\to c\cdot C,\ c/d],\ [C\to\cdot cC,\ c/d],\ [C\to\cdot d,\ c/d]
    • I4I_4 = goto(I0,d)(I_0,d): [C→d⋅, c/d][C\to d\cdot,\ c/d]
    • I5I_5 = goto(I2,C)(I_2,C): $[S\to CC\cdot,$]$
    • I6I_6 = goto(I2,c)(I_2,c): $[C\to c\cdot C,$],\ [C\to\cdot cC,$],\ [C\to\cdot d,$]$
    • I7I_7 = goto(I2,d)(I_2,d): $[C\to d\cdot,$]$
    • I8I_8 = goto(I3,C)(I_3,C): [C→cC⋅, c/d][C\to cC\cdot,\ c/d]
    • I9I_9 = goto(I6,C)(I_6,C): $[C\to cC\cdot,$]$

    GOTO function:

    • goto(I0,S)(I_0,S)= I1I_1; goto(I0,C)(I_0,C)=I2I_2; goto(I0,c)(I_0,c)=I3I_3; goto(I0,d)(I_0,d)=I4I_4
    • goto(I2,C)(I_2,C)=I5I_5; goto(I2,c)(I_2,c)=I6I_6; goto(I2,d)(I_2,d)=I7I_7
    • goto(I3,C)(I_3,C)=I8I_8; goto(I3,c)(I_3,c)=I3I_3; goto(I3,d)(I_3,d)=I4I_4
    • goto(I6,C)(I_6,C)=I9I_9; goto(I6,c)(I_6,c)=I6I_6; goto(I6,d)(I_6,d)=I7I_7

    So the canonical LR(1) machine has 10 states (I0I_0–I9I_9).

    Reduce actions: I4I_4: C→dC\to d on {c,d}\{c,d\}; I7I_7: C→dC\to d on $$;; I_8:: C\to cCon on {c,d};; I_9:: C\to cCon‘ on `; I5I_5: S→CCS\to CC on ‘;`; I_1:accepton‘: accept on ``.

    Bonus — LALR(1): merging states with equal cores (I4∪I7I_4\cup I_7, I3∪I6I_3\cup I_6, I8∪I9I_8\cup I_9) gives the 7-state LALR(1) automaton, free of conflicts for this grammar.

  24. Q9. Write a short note on any two of the following: (a) \text{SLR}(1) parser (b) Syntax Directed Definition (c) Peephole optimization (d) Attribute grammar202614m

    Module 2: Syntax Analysis (Parser)

    Write a short note on any two of the following:
    (a) SLR(1)\text{SLR}(1) parser
    (b) Syntax Directed Definition
    (c) Peephole optimization
    (d) Attribute grammar

    View this question on its own page →
    Worked Solution

    Only two notes are required; all four are given here (7 marks each).


    (a) SLR(1) parser

    SLR(1) (Simple LR with 1 lookahead symbol) is a bottom-up LR parser whose states are the sets of LR(0) items, and which uses the FOLLOW sets to decide when to reduce.

    Construction steps

    1. Augment the grammar with S′→SS' \to S.
    2. Build the canonical collection of LR(0) item sets using closure and goto.
    3. Fill the ACTION/GOTO table:
      • A→α⋅aβA \to \alpha \cdot a\beta in IiI_i and goto(Ii,a)=Ij\mathrm{goto}(I_i, a) = I_j gives shift jj on terminal aa.
      • A→α⋅A \to \alpha \cdot in IiI_i gives reduce A→αA \to \alpha for every terminal in FOLLOW(A)\mathrm{FOLLOW}(A) (this is the SLR rule).
      • S′→S⋅S' \to S \cdot gives accept on $.
      • goto(Ii,A)=Ij\mathrm{goto}(I_i, A) = I_j gives GOTO entry jj for non-terminal AA.

    The grammar is SLR(1) if the table has no conflicts.

    Power: SLR(1) is stronger than LR(0) but weaker than LALR(1) and canonical LR(1), because FOLLOW(A) is a coarse lookahead that ignores the context of the item and can cause spurious shift-reduce conflicts. It has the same small number of states as LR(0) and LALR(1).


    (b) Syntax Directed Definition (SDD)

    An SDD is a context-free grammar in which each grammar symbol has attributes and each production has semantic rules that compute the attributes. It specifies the translation (evaluation of expressions, type checking, code generation) tied to the syntax.

    Production Semantic rule
    E→E1+TE \to E_1 + T E.val=E1.val+T.valE.val = E_1.val + T.val
    T→FT \to F T.val=F.valT.val = F.val
    F→digitF \to \text{digit} F.val=digit.lexvalF.val = \text{digit}.lexval
    • Synthesized attribute: computed from the attributes of the node's children (bottom-up).
    • Inherited attribute: computed from the parent and/or siblings (top-down or sideways).
    • S-attributed SDD: uses only synthesized attributes (suits bottom-up parsing). L-attributed SDD: each inherited attribute depends only on the parent and the siblings to its left (suits one left-to-right pass).
    • The rules are evaluated on the annotated parse tree; the order must respect the dependency graph. An SDD may contain rules with side effects (for example printing or updating the symbol table); an SDD whose rules have no side effects is an attribute grammar. Unlike a syntax-directed translation scheme, an SDD does not fix where actions run; it only states the rules.

    (c) Peephole optimization

    A peephole optimizer examines a small sliding window of target (or intermediate) instructions, the peephole (typically 2-5 instructions), and replaces patterns by shorter or faster equivalents. It may be applied repeatedly because one change can create new opportunities.

    Technique Before After
    Redundant load/store elimination ST a, R1<br>LD R1, a ST a, R1
    Constant folding x = 3 + 4 x = 7
    Algebraic simplification x = x + 0, x = x * 1 removed
    Strength reduction x = x * 2 x = x << 1
    Use of machine idioms ADD R1, R1, #1 INC R1
    Unreachable code removal goto L2 followed by instructions with no label instructions removed
    Control-flow optimization goto L1 ... L1: goto L2 goto L2

    Advantages: simple, local, machine-specific gains; limitation: it cannot see beyond the window, so it complements global optimization.


    (d) Attribute grammar

    An attribute grammar is a context-free grammar extended with attributes attached to grammar symbols and semantic (attribute evaluation) rules attached to productions. Formally, it is a CFG together with a set of attributes (partitioned into synthesized and inherited) and rules that define each attribute purely as a function of other attributes, with no side effects. An attribute grammar is thus an SDD without side effects, used to define the static semantics of a language.

    Example (type declaration, uses an inherited attribute):

    Production Semantic rule
    D→T LD \to T\,L L.in=T.typeL.in = T.type
    T→intT \to \text{int} T.type=integerT.type = integer
    T→floatT \to \text{float} T.type=floatT.type = float
    L→L1,idL \to L_1 , \text{id} L1.in=L.in;  addtype(id.entry,L.in)L_1.in = L.in;\; \text{addtype}(\text{id}.entry, L.in)
    L→idL \to \text{id} addtype(id.entry,L.in)\text{addtype}(\text{id}.entry, L.in)

    Here T.typeT.type is synthesized and L.inL.in is inherited: the type flows from TT to every identifier in the list.

    Evaluation: build the dependency graph of attribute instances on the parse tree; if it has no cycle, evaluate the attributes in a topological order. Attribute grammars are used for type checking, symbol-table construction and intermediate code generation.