Skip to content
GATEiit

GATE CSE · Compiler Design

Lexical analysis, parsing and syntax-directed translation

The compiler front end: tokens and lexemes, FIRST and FOLLOW sets, LL(1) parsing, shift-reduce and LR parsers (LR(0), SLR, LALR, CLR) with their conflicts, and evaluating syntax-directed translations with S- and L-attributed definitions.

Before you start

This topic comes before: Intermediate code generation

Concept notes

1. Lexical analysis: tokens, lexemes and patterns

The lexical analyser (scanner) reads characters and groups them into tokens.

  • A token is a category, such as id, num, relop or the keyword if.
  • A lexeme is the actual character sequence matched, such as count or >=.
  • A pattern is the rule (a regular expression) describing the lexemes of a token.

The scanner is a DFA built from the regular expressions of all tokens. It also removes white space and comments, tracks line numbers, and enters identifiers into the symbol table.

Two rules resolve clashes.

  1. Longest match (maximal munch): take the longest prefix that matches some pattern. So >= is one token, not > then =, and a+++b is read as a ++ + b.
  2. Priority: if two patterns match the same longest lexeme, the one listed first wins. Keywords are listed before id, so if is a keyword but iffy is an identifier.

Counting tokens (a frequent GATE question). Count every identifier, keyword, constant, operator and punctuation mark once. A whole string literal such as "x = %d" is one token. Comments and white space produce no tokens. Multi-character operators (<=, ==, ++, <<, ->) are single tokens.

Lexical errors are only those the scanner can see: an illegal character, an unterminated string or comment, a malformed number. A misspelt keyword like whlie (x) is just an identifier to the scanner; the parser reports the error.

source textlexical analyserparsersemantic actionstokens (DFA, longest match)parse tree (CFG)SDT: values, codesymbol table is shared by all phases
Front end of a compiler: the scanner feeds tokens to the parser, whose productions trigger semantic actions

2. FIRST, FOLLOW and LL(1) parsing

FIRST(α) is the set of terminals that can begin a string derived from α, plus ε if α⇒∗ε. For X1X2…Xk: take FIRST(X1) without ε; if X1 is nullable, add FIRST(X2), and so on; add ε only if all are nullable.

FOLLOW(A) is the set of terminals that can appear immediately after A in some sentential form. Rules: put $ in FOLLOW(S). For B→αAβ, add FIRST(β) −{ε}. If β is nullable (or empty), add FOLLOW(B). Repeat until nothing changes. FOLLOW never contains ε.

LL(1) table. For each production A→α: put it in M[A,a] for every a∈ FIRST(α); if α is nullable, also for every b∈ FOLLOW(A). The grammar is LL(1) iff no cell gets two entries. Equivalently, for every pair A→α∣β:

  • FIRST(α) and FIRST(β) are disjoint, and
  • if β⇒∗ε, then FIRST(α) and FOLLOW(A) are disjoint.

Preparing a grammar for top-down parsing.

  • Left recursion makes a top-down parser loop. A→Aα∣β becomes A→βA′, A′→αA′∣ε.
  • Left factoring removes a common prefix: A→αβ1∣αβ2 becomes A→αA′, A′→β1∣β2.

A left-recursive or ambiguous grammar is never LL(1). Removing left recursion and left factoring are necessary steps, but they do not guarantee LL(1).

Recursive descent is the hand-written version: one function per non-terminal, choosing a production by the next token.

3. Bottom-up parsing: shift-reduce and LR parsers

A bottom-up parser builds the rightmost derivation in reverse. A shift-reduce parser keeps a stack and does one of four actions: shift the next token, reduce a handle (the right side of a production at the top of the stack, whose reduction is a step of the reverse rightmost derivation), accept, or report error. Every reduction corresponds to one interior node of the parse tree.

LR(0) items are productions with a dot: A→α⋅β. The canonical LR(0) collection is built with closure and goto, starting from S′→⋅S for the augmented grammar.

Parser Items Reduce A→α⋅ on States
LR(0) LR(0) every terminal n0
SLR(1) LR(0) FOLLOW(A) n0
LALR(1) LR(1) cores merged the item's lookaheads n0
CLR(1) LR(1) the item's lookahead ≥n0

Conflicts.

  • Shift-reduce: a state has a complete item A→α⋅ and an item B→β⋅aγ with a in the reduce set.
  • Reduce-reduce: two complete items whose reduce sets overlap.

Merging CLR states into LALR (same core, union of lookaheads) can create reduce-reduce conflicts, but never a new shift-reduce conflict, because shift actions depend only on the core.

Power. LR(0) ⊂ SLR(1) ⊂ LALR(1) ⊂ CLR(1), each proper, for grammars. Every LL(1) grammar is LR(1), but an LL(1) grammar need not be LALR(1). No ambiguous grammar is LL(1) or LR(k). Parser generators such as YACC and Bison build LALR(1) parsers.

Operator precedence parsing works on operator grammars: no ε-productions and no two adjacent non-terminals on any right side.

LR(1) = CLR(1)LALR(1)SLR(1)LR(0)LL(1) grammarsall ambiguous grammars lie outside every box
Grammar classes accepted by deterministic parsers: each LR box properly contains the one inside it; LL(1) grammars all lie inside LR(1)

4. Syntax-directed translation

A syntax-directed definition (SDD) attaches attributes to grammar symbols and semantic rules to productions. An SDT scheme puts actions inside the right sides, which run when the parser reaches them.

  • A synthesized attribute of A is computed from attributes of its children (and A itself): E.val=E1.val+T.val.
  • An inherited attribute of a symbol is computed from its parent and siblings: L.type=T.type in D→T L.
Class Allowed rules Evaluated by
S-attributed synthesized attributes only a bottom-up (LR) parser, at each reduction
L-attributed synthesized, plus inherited attributes of Xi in A→X1…Xn that use only inherited attributes of A and attributes of X1…Xi−1 one left-to-right depth-first pass; fits top-down parsing

Every S-attributed SDD is L-attributed. A rule that uses an attribute of a right sibling, such as X1.i=X2.s, breaks the L-attributed condition.

Evaluating a translation (GATE pattern). The grammar fixes precedence and associativity, whatever the operator symbols look like:

  1. An operator generated deeper in the grammar (closer to the terminals) binds tighter.
  2. A left-recursive production (E→E#T) makes the operator left-associative; a right-recursive one makes it right-associative.
  3. Draw the parse tree, then apply the semantic rules bottom-up. Use the rule given, not the usual meaning of the symbol.

Actions that print. In a scheme such as E→E+T {print(’+’)}, actions at the end of productions run in postorder, so the output is the postfix form of the input. Actions placed before a symbol run when the parser reaches that point in a top-down parse. To read the output, walk the parse tree depth-first and print each action when you pass it.

Formulas to remember

Left recursion removal
A→Aα∣β  ⇒  A→βA′,  A′→αA′∣ε
Left factoring
A→αβ1∣αβ2  ⇒  A→αA′,  A′→β1∣β2
LL(1) condition for A → α | β
FIRST(α)∩FIRST(β)=∅;  β⇒∗ε⇒FIRST(α)∩FOLLOW(A)=∅
Parser power
LR(0)⊂SLR(1)⊂LALR(1)⊂CLR(1)
State counts
nLR(0)=nSLR=nLALR≤nCLR

Common mistakes

  • Counting a string literal as several tokens, or counting comments; a literal is one token and comments give none.
  • Splitting multi-character operators such as >=, ++ or << into two tokens instead of applying longest match.
  • Putting ε in a FOLLOW set, or forgetting to add $ to FOLLOW of the start symbol.
  • Using the usual meaning of + and * in a translation question instead of the semantic rule and the precedence fixed by the grammar.
  • Believing that LALR merging can create shift-reduce conflicts; it can create only reduce-reduce conflicts.
  • Assuming that removing left recursion and left factoring always makes a grammar LL(1).

Worked examples

Try each step yourself, then reveal the working.

Example 1: Counting tokens

numerical

How many tokens does the C statement int x = a+++b; contain?

  1. Step 1: Apply longest match to `a+++b`.

    Try it on paper first.

Example 2: FIRST, FOLLOW and the LL(1) table

numerical

Grammar: S→ABc, A→aA∣ε, B→b∣ε. Find FIRST and FOLLOW of each non-terminal and decide whether the grammar is LL(1).

  1. Step 1: Find FIRST of A and B.

    Try it on paper first.

Example 3: Counting LR(0) states

numerical

How many states does the LR(0) automaton have for S→AA, A→aA∣b (after adding S′→S)?

  1. Step 1: Build $I_0$.

    Try it on paper first.

Example 4: Evaluating a syntax-directed definition

numerical

SDD: E→E1#T {E.val=E1.val−T.val}, E→T {E.val=T.val}, T→T1 & F {T.val=T1.val×F.val}, T→F, F→num {F.val=num.value}. Find E.val for the input 8#2 & 3#1.

  1. Step 1: Read precedence from the grammar.

    Try it on paper first.

Previous year questions

43 official GATE CSE questions on this topic, newest first.

Practise these 43 PYQs →

Topic test

10 questions: up to 4 official PYQs and original practice questions, with GATE marking (MCQ wrong answers lose marks). Score 60% or more to pass. A new set is drawn each time.

Mark as mastered

Loading your progress…

My revision notes

Notes written by the GATEiit team against the official GATE CSE syllabus; being checked by a reviewer. Updated 2026-11-21. Spotted a mistake? Use Report an issue on any question, or contact us.