Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Programming language grammars

Programming language grammars: definitions (CFG, terminals, nonterminals, productions), FIRST/FOLLOW, ambiguity, normal forms (CNF/GNF), left recursion removal and left factoring, LL(1) condition, and worked examples for exam preparation.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Compilers, interpreters, assemblers and many system tools read and understand source code by using a grammar. An engineer uses grammars when designing the parser phase of a compiler, when writing syntax checkers, and when converting language specifications (for example to make an LL(1) parser or to prove a grammar is unambiguous).

Key ideas

Start with clear definitions. Bold each defined term when first used.

  • Grammar: a formal description that generates strings of a language. A grammar specifies which sequences of symbols are valid and how valid sequences can be constructed.
  • Terminal: a symbol that appears in the final strings (tokens, e.g. keywords, identifiers, operators). Terminals cannot be expanded by productions. Denote set of terminals by T.
  • Nonterminal: a symbol that can be expanded using productions; it represents a syntactic category (e.g. <expr>, <stmt>). Denote set of nonterminals by V.
  • Production (or rule): an ordered pair showing how a nonterminal can be replaced. Written A -> α where A is a nonterminal and α is a string of terminals and/or nonterminals.
  • Start symbol: a distinguished nonterminal from which generation begins; denote by S.
  • Context-Free Grammar (CFG): a grammar G = (V, T, P, S) where every production in P has exactly one nonterminal on the left: A -> α with A ∈ V and α ∈ (V ∪ T)*.
  • Derivation: repeatedly replacing a nonterminal using a production to produce a string. If from S we can obtain w (a string of terminals) by such steps, we say the grammar generates w. A leftmost derivation always expands the leftmost nonterminal; a rightmost derivation always expands the rightmost nonterminal.
  • Sentential form: any intermediate string during a derivation containing terminals and/or nonterminals.
  • Parse tree: a tree with root S where interior nodes are nonterminals and leaves are terminals; it shows the structure of a derivation. (To draw: root labeled S; if you use production A -> X Y z then A has three children labeled X, Y, z; draw leaves left-to-right to produce the final string.)
  • Language of a grammar: the set of terminal strings derivable from S.
  • Ambiguity: a grammar is ambiguous if there exists at least one string that has two distinct parse trees (or two different leftmost or rightmost derivations). A grammar is unambiguous if no such string exists.

Exact theorem students are commonly asked to state (LL(1) condition):

  • LL(1) condition (precise statement): Let G be a CFG with no left recursion and productions for a nonterminal A of the form A -> α1 | α2 | ... | αn. Then G is LL(1) (i.e. an LL(1) parser can decide the correct production by looking at one input token) iff for all i ≠ j the following hold:

    1. FIRST(αi) ∩ FIRST(αj) = ∅.
    2. If ε ∈ FIRST(αi) then FIRST(αj) ∩ FOLLOW(A) = ∅. Here ε denotes the empty string. Assumption: FIRST and FOLLOW sets are computed for the grammar where ε means the right side can derive empty.
  • Chomsky Normal Form (CNF): every production is either A -> BC (two nonterminals) or A -> a (single terminal) or S -> ε if the language includes empty string. CNF is useful for algorithms (e.g. CYK) that need a restricted form. Common convention: the start symbol S does not appear on any right-hand side.

Key conversions and assumptions students must know step-by-step (universities ask to derive these):

  1. Removing ε-productions (except possibly for S): find nullable nonterminals (those that derive ε), and for each production include versions with nullable symbols omitted. If S ⇒* ε, introduce a new start symbol S' with S' -> S | ε and ensure S' does not appear on any right-hand side (useful for CNF).
  2. Removing unit productions A -> B: replace by A -> α for every B -> α (repeat until none left).
  3. Removing useless symbols: remove nonterminals that can't reach terminals or are not reachable from S.
  4. Converting to CNF: ensure right sides are either a terminal or two nonterminals, by factoring terminals into new nonterminals and breaking long right sides.
  • Left recursion: A grammar has left recursion if there is a nonterminal A and a derivation A ⇒+ Aα (immediate left recursion if A -> Aα | β). Left recursion must be removed for many top-down parsers.

Left recursion elimination (immediate case) algorithm (exact steps universities expect): Given A -> Aα1 | Aα2 | ... | β1 | β2 | ... where each β does not begin with A:

  1. Replace with: A -> β1 A' | β2 A' | ... A' -> α1 A' | α2 A' | ... | ε This removes immediate left recursion and preserves the language. For grammars with indirect left recursion across multiple nonterminals A1, A2, ..., An, use the standard algorithm: for i = 1 to n, for j = 1 to i - 1, for each production Ai -> Aj γ replace it by Ai -> δ γ for every production Aj -> δ; then eliminate immediate left recursion on Ai as above.
  • Left factoring: used when two productions share a common prefix and top-down parser cannot choose. For A -> αβ1 | αβ2, replace by A -> αA' and A' -> β1 | β2.

  • FIRST(X): the set of terminals that can appear as the first symbol in some string derived from X; includes ε if X can derive ε.

  • FOLLOW(A): the set of terminals that can appear immediately to the right of A in some sentential form; include $ (end marker) if A can appear at the end of the start symbol's sentential form.

Algorithms for FIRST and FOLLOW are standard fixed-point computations: initialize, then iterate rules until no change.

Formulas

G = (V, T, P, S)

  • V: set of nonterminals. T: set of terminals. P: set of productions. S: start symbol.

A -> α (production syntax)

  • A ∈ V. α ∈ (V ∪ T)*.

FIRST(X)

  • For a terminal a: FIRST(a) = { a }.
  • For ε: FIRST(ε) = { ε }.
  • For nonterminal A: FIRST(A) = { a ∈ T | A ⇒* aβ } ∪ { ε if A ⇒* ε }.

FIRST(αβ) = (FIRST(α) - {ε}) ∪ (if ε ∈ FIRST(α) then FIRST(β) else ∅); for a longer string α1 α2 ... αk, apply this iteratively left-to-right and include ε only if every αi can derive ε.

  • α, β are strings of grammar symbols.

FOLLOW(A)

  • Start with $ ∈ FOLLOW(S) (end marker).
  • If A -> αBβ then add (FIRST(β) - {ε}) to FOLLOW(B).
  • If A -> αB or A -> αBβ and ε ∈ FIRST(β) then add FOLLOW(A) to FOLLOW(B).

LL(1) condition (restate): For all productions A -> α | β: FIRST(α) ∩ FIRST(β) = ∅, and if ε ∈ FIRST(α) then FIRST(β) ∩ FOLLOW(A) = ∅.

BNF/EBNF syntax to remember (examples):

  • BNF production: <nonterminal> ::= <expr> | <term>
  • Optional in EBNF: [ ... ] (means 0 or 1 occurrence)
  • Repetition in EBNF: { ... } (means 0 or more occurrences)
  • Grouping: ( ... ).

Worked examples

Example 1 — FIRST and FOLLOW (step-by-step): Grammar G:

  1. S -> A b
  2. A -> c A | ε

Compute FIRST and FOLLOW. Steps:

  1. Terminals: b, c. Nonterminals: S, A. Start S.
  2. FIRST(c) = { c }, FIRST(b) = { b }, FIRST(ε) = { ε }.
  3. For A: productions A -> c A and A -> ε so FIRST(A) contains c and ε. So FIRST(A) = { c, ε }.
  4. For S: S -> A b. FIRST(S) contains FIRST(A) - {ε} = { c }. Because ε ∈ FIRST(A) but b follows A in S's production, add b to FIRST(S) only if considering FIRST(A b) calculation: FIRST(A b) = (FIRST(A) - {ε}) ∪ (if ε ∈ FIRST(A) then FIRST(b)) = {c} ∪ {b} = {b, c}. So FIRST(S) = { b, c }.
  5. FOLLOW: start with $ ∈ FOLLOW(S).
  6. From S -> A b: b follows A, so add b to FOLLOW(A).
  7. From A -> c A: A occurs at right; after that nothing, so add FOLLOW(A) (left side) to FOLLOW(A) — no new info.
  8. Also if A can appear at end of S's derivations: since S -> A b, A is not at end.
  9. Therefore FOLLOW(S) = { $ }, FOLLOW(A) = { b }. Final: FIRST(S) = { b, c }, FIRST(A) = { c, ε }, FOLLOW(S) = { $ }, FOLLOW(A) = { b }.

Example 2 — Remove immediate left recursion and build LL(1) choice (trace): Grammar:

  1. E -> E + T | T
  2. T -> T * F | F
  3. F -> ( E ) | id

Remove immediate left recursion for E and T. Steps:

  1. For E -> E + T | T, identify α = + T, β = T. Replace by: E -> T E' E' -> + T E' | ε.
  2. For T -> T * F | F, similarly: T -> F T' T' -> * F T' | ε.
  3. F unchanged.

Now compute FIRST sets quickly:

  • FIRST(id) = { id }, FIRST('(') = { '(' }.
  • FIRST(F) = { '(', id }.
  • FIRST(T) = FIRST(F) = { '(', id }.
  • FIRST(E) = FIRST(T) = { '(', id }.

Check LL(1) conflicts: after left recursion removal no FIRST sets of alternatives for the same nonterminal overlap (E has single production T E'). Also verify the ε-cases using FOLLOW: for E', FIRST(+ T E') ∩ FOLLOW(E') = ∅ and for T', FIRST(* F T') ∩ FOLLOW(T') = ∅; with FOLLOW(E') = { ')', '$' } and FOLLOW(T') = { '+', ')', '$' }, so the grammar is LL(1). If asked to build parsing table, fill table rows E, E', T, T', F with terminal columns id, (, +, *, ), $ using FIRST/FOLLOW rules.

Example 3 — Ambiguity: if-then-else classic (model answer style) Grammar (ambiguous):

  1. S -> if E then S | if E then S else S | other

Show ambiguity for input: if E1 then if E2 then S1 else S2. Steps:

  1. Two possible parse trees: (a) the else associates with inner if (common intended default), or (b) the else associates with outer if (different grouping).
  2. Draw two parse trees: describe how to draw each — root S with left child if E then S where S is again if E then S else S versus root S with if E then S else S where the then-part is if E then S.
  3. Conclude grammar is ambiguous because same input yields two distinct parse trees. To disambiguate, present a grammar that forces else to attach to nearest unmatched if (common solution):
  • S -> matched | unmatched
  • matched -> if E then matched else matched | other
  • unmatched -> if E then S | if E then matched else unmatched This grammar is unambiguous for the usual if-then-else preference.

Common mistakes

  • When computing FIRST for a sequence, forgetting to include FIRST of the next symbol when ε is in the FIRST of the previous symbol.
  • Improper left recursion removal: forgetting to allow ε in the new helper nonterminal.
  • Assuming that removing left recursion or left-factoring always preserves parse tree shape (they preserve language but may change parse trees — mention if asked).
  • Confusing ambiguity of a grammar with ambiguity of a language (a language can have both ambiguous and unambiguous grammars).

For your exam

Types of questions you will get:

  • Definition questions (define CFG, FIRST, FOLLOW, ambiguity).
  • Short notes (CNF, left recursion removal, LL(1) parsing table construction).
  • Derivation questions (show leftmost/rightmost derivation and draw parse tree).
  • Algorithmic/numerical style (compute FIRST and FOLLOW sets; convert to CNF).
  • Design/program style (transform grammar to be suitable for top-down parser; eliminate ambiguity for a particular case).

What a full-marks answer includes:

  • Clear definitions using the grammar notation and bolded terms (start symbol, productions).
  • Stepwise application of algorithms with intermediate results shown (e.g., show nullable set when removing ε-productions).
  • When asked to draw: include a parse tree with root S and label every node; for derivations show each sentential form step.
  • State assumptions (for LL(1) say you removed left recursion and performed left factoring first).

Quick check

  1. What is the start symbol in a grammar? 2. Give the FIRST set of A for A -> ε | a B. 3. Why is if-then-else grammar ambiguous?

Answers: 1. The distinguished nonterminal from which derivation begins (denoted S). 2. FIRST(A) = { a, ε }. 3. Because the same input can produce two different parse trees — the else can attach to either the nearest if or an outer if.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?