Context-Free Grammars

Languages with nested structure — context-free grammars, derivations and parse trees, ambiguity, pushdown automata, the Chomsky hierarchy, closure properties and limits (the CFL pumping lemma), Chomsky normal form and CYK parsing, and how grammars drive parsers, JSON and programming languages.

Intermediate 5 min readLesson 7 of 9

Finite automata can't handle nesting: balanced parentheses, nested HTML tags, if inside while inside a function (Automata). Context-free grammars (CFGs) can — they're how virtually every programming language, data format and query language defines its syntax, and the basis of parsers (Parsing).

Grammars

A CFG has four parts:

PartMeaningExample
TerminalsThe alphabet — actual tokens(, ), +, num
Nonterminals (variables)Syntactic categoriesExpr, Term
ProductionsRules: nonterminal → string of terminals and nonterminalsExpr → Expr + Term
Start symbolWhere derivations beginExpr

Balanced parentheses — impossible for a DFA, two rules for a CFG:

S → ( S ) S
S → ε

The language {anbn}\{a^nb^n\}:

S → a S b | ε

Arithmetic expressions with precedence (written in BNF):

Expr   → Expr + Term   | Expr - Term   | Term
Term   → Term * Factor | Term / Factor | Factor
Factor → ( Expr ) | num | id

The language of a grammar is the set of terminal strings derivable from the start symbol. A language is context-free if some CFG generates it. "Context-free" means a rule applies to a nonterminal regardless of what surrounds it.

Derivations and parse trees

A derivation repeatedly replaces a nonterminal using a rule. For num + num * num:

Expr ⇒ Expr + Term
     ⇒ Term + Term
     ⇒ Factor + Term
     ⇒ num + Term
     ⇒ num + Term * Factor
     ⇒ num + Factor * Factor
     ⇒ num + num * Factor
     ⇒ num + num * num

The parse tree records the structure — which is what gives the string its meaning:

2FTE+3FT*4FTE
Parse tree for 2 + 3 * 4: multiplication sits deeper, so it's evaluated first

Ambiguity

A grammar is ambiguous if some string has two different parse trees:

E → E + E | E * E | num

2 + 3 * 4 can parse as (2 + 3) * 4 = 20 or 2 + (3 * 4) = 14. Ambiguity in a programming language means ambiguous meaning. Fixes:

  • Stratify the grammar by precedence (Expr/Term/Factor above) and use left recursion for left associativity.
  • Add disambiguation rules in the parser generator (precedence and associativity declarations).
  • The dangling else (if a then if b then s1 else s2) is resolved by convention: else binds to the nearest if.

Some context-free languages are inherently ambiguous — every grammar for them is ambiguous — and deciding whether an arbitrary CFG is ambiguous is undecidable.

Pushdown automata

A pushdown automaton (PDA) is a finite automaton plus a stack — unbounded memory, but only accessible at the top. To recognise anbna^nb^n: push a symbol for each a, pop one for each b, accept if the stack is empty at the end.

Theorem: context-free grammars and (nondeterministic) pushdown automata recognise exactly the same languages.

This explains a familiar programming fact: checking balanced brackets needs a stack (Stacks), and so does any parser — recursive-descent parsers use the call stack; LR parsers use an explicit stack of states.

Python
def balanced(s: str) -> bool:
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in s:
        if ch in "([{":
            stack.append(ch)                       # push
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False                       # pop must match
    return not stack                               # accept on empty stack

Deterministic PDAs are strictly weaker than nondeterministic ones (palindromes need guessing the middle). Deterministic context-free languages are exactly those parseable by efficient LR(k) parsers — which is why language designers keep grammars deterministic.

The Chomsky hierarchy

Type 0 — recursively enumerableunrestricted grammars · Turing machinesType 1 — context-sensitivelinear-bounded automata · e.g. aⁿbⁿcⁿType 2 — context-freepushdown automata · programming-language syntax, JSONType 3 — regularfinite automata · regexes, tokens

Each class strictly contains the one below it: regular ⊂ context-free ⊂ context-sensitive ⊂ recursively enumerable. More powerful machines recognise more languages — but answering questions about them gets harder (for Turing machines, many questions are undecidable — Turing machines).

Limits of context-free languages

Context-free languages can match one nested count, but not two interleaved ones. Non-context-free examples:

  • {anbncn}\{a^nb^nc^n\} — a stack can match a's to b's, but then the count is gone for the c's.
  • {ww}\{ww\} — a string repeated (a stack reverses, so it handles wwRww^R palindromes, not copies).

A pumping lemma for CFLs (pump two substrings simultaneously) proves these. CFLs are closed under union, concatenation and star, but not under intersection or complement.

Real programming languages aren't purely context-free: "variables must be declared before use" and "a function call must match the number of parameters" are context-sensitive constraints. Compilers handle them in semantic analysis after parsing (Semantic analysis), keeping the grammar context-free.

Parsing algorithms

AlgorithmHandlesTime
CYKAny CFG in Chomsky normal formO(n³) — dynamic programming over substrings
EarleyAny CFG (including ambiguous)O(n³) worst, O(n²) unambiguous, O(n) for most practical grammars
GLRAny CFG; forks on conflictsWorst O(n³)
LL(k) — recursive descentA subset (no left recursion, predictable with k lookahead)O(n)
LR(k), LALR(1)Deterministic CFLsO(n)
PEG / packratOrdered-choice grammars (not exactly CFGs)O(n) with memoisation

Chomsky normal form restricts rules to A → BC or A → a. Any CFG can be converted, and CYK then fills a table where cell [i, j] holds the nonterminals that derive the substring from i to j — a classic interval DP (Dynamic programming).

Grammars in practice

  • Language specifications: the Python grammar (PEG), the ECMAScript spec, the Java Language Specification and SQL standards all define syntax with grammar notation.
  • Data formats: JSON's entire syntax fits on one page of grammar rules; XML, YAML, TOML, protobuf text, GraphQL.
  • Tools: ANTLR, Bison/yacc, tree-sitter (incremental parsing for editors), Lark, parser combinators.
  • Fuzzing: grammar-based fuzzers generate random valid programs to test compilers and parsers.
  • Natural language: CFGs were introduced by Chomsky to model human language syntax; modern NLP uses neural models, but parse trees remain a useful concept.
Key takeaways
  • CFGs use recursive production rules to describe nested structure; context-free languages strictly include the regular languages.
  • Derivations produce parse trees, which carry meaning; ambiguous grammars give a string several trees.
  • Remove ambiguity with precedence layers, associativity rules and conventions like the dangling else.
  • Pushdown automata (finite control + stack) recognise exactly the CFLs — which is why parsers need stacks.
  • Chomsky hierarchy: regular ⊂ context-free ⊂ context-sensitive ⊂ recursively enumerable.
  • CFLs can't express aⁿbⁿcⁿ or declare-before-use; compilers check such rules in semantic analysis.
  • General parsing (CYK, Earley) is O(n³); practical languages use deterministic LL/LR grammars parsed in O(n).