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 -> αwithA ∈ Vandα ∈ (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 zthen 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:FIRST(αi) ∩ FIRST(αj) = ∅.- If
ε ∈ FIRST(αi)thenFIRST(α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) orA -> a(single terminal) orS -> ε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):
- 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). - Removing unit productions
A -> B: replace byA -> αfor everyB -> α(repeat until none left). - Removing useless symbols: remove nonterminals that can't reach terminals or are not reachable from S.
- 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:
- 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 byA -> αA'andA' -> β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(β) - {ε})toFOLLOW(B). - If
A -> αBorA -> αBβandε ∈ FIRST(β)then addFOLLOW(A)toFOLLOW(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:
S -> A bA -> c A | ε
Compute FIRST and FOLLOW. Steps:
- Terminals:
b, c. Nonterminals:S, A. StartS. - FIRST(c) = { c }, FIRST(b) = { b }, FIRST(ε) = { ε }.
- For A: productions
A -> c AandA -> εsoFIRST(A)containscandε. SoFIRST(A) = { c, ε }. - For S:
S -> A b.FIRST(S)containsFIRST(A)- {ε} = { c }. Because ε ∈ FIRST(A) but b follows A in S's production, addbto FIRST(S) only if considering FIRST(A b) calculation:FIRST(A b) = (FIRST(A) - {ε}) ∪ (if ε ∈ FIRST(A) then FIRST(b))={c} ∪ {b}={b, c}. SoFIRST(S) = { b, c }. - FOLLOW: start with
$ ∈ FOLLOW(S). - From
S -> A b:bfollowsA, so addbtoFOLLOW(A). - From
A -> c A: A occurs at right; after that nothing, so addFOLLOW(A)(left side) toFOLLOW(A)— no new info. - Also if A can appear at end of S's derivations: since S -> A b, A is not at end.
- 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:
E -> E + T | TT -> T * F | FF -> ( E ) | id
Remove immediate left recursion for E and T. Steps:
- For
E -> E + T | T, identify α =+ T, β =T. Replace by:E -> T E'E' -> + T E' | ε. - For
T -> T * F | F, similarly:T -> F T'T' -> * F T' | ε. Funchanged.
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):
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:
- Two possible parse trees: (a) the
elseassociates with innerif(common intended default), or (b) theelseassociates with outerif(different grouping). - Draw two parse trees: describe how to draw each — root S with left child
if E then Swhere S is againif E then S else Sversus root S withif E then S else Swhere the then-part isif E then S. - Conclude grammar is ambiguous because same input yields two distinct parse trees.
To disambiguate, present a grammar that forces
elseto attach to nearest unmatchedif(common solution):
S -> matched | unmatchedmatched -> if E then matched else matched | otherunmatched -> if E then S | if E then matched else unmatchedThis 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
- What is the start symbol in a grammar? 2. Give the FIRST set of
AforA -> ε | a B. 3. Why isif-then-elsegrammar 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?