An arithmetic expression like 2 * (3 + 4) has parentheses that open and close in a nested way, and to recognize it you must remember how many you have opened. In article 01 we saw that a finite-state automaton cannot do this, because remembering an unbounded number requires unbounded memory. Context-free grammars add this memory in the form of recursion: a rule can call itself. In short: a grammar generates a language with rewriting rules, every string has a derivation tree, a tree may not be unique (ambiguity), and trees do not solve everything, because there are languages, such as anbncn, that no grammar of this kind generates.
This is the third article in the Formal Languages and Compilers series. All the listings were run with Python 3.14.4, twice with identical output. The definitions of grammar, ambiguity and Chomsky normal form follow chapter 5 of Jeff Erickson, "Context-Free Languages and Grammars", which I downloaded and read on 2026-11-13.
What a context-free grammar is
A context-free grammar (CFG) is a structure with four components, which in Erickson's chapter are called symbols, non-terminals, rules and start symbol.
- the terminals
T: the symbols that appear in the final strings (herea,b,(,),+); - the non-terminals
V: names of categories, like "expression", not to be confused with terminals; - the production rules
P, of the formA → w, with a single non-terminal on the left and any sequence of terminals and non-terminals on the right; - the start symbol
S, a non-terminal from which every derivation starts.
The "context-free" lies in the form of the left-hand side: the rule A → w can be applied to A wherever it appears, without looking at what surrounds it. To derive means to start from S and replace one non-terminal at a time with the right-hand side of one of its rules, until only terminals remain; the language of the grammar is the set of strings of terminals that can be obtained. The minimal example is S → aSb | ε: from S you get aSb, then aaSbb, and when you choose ε the derivation stops. The language is {anbn : n ≥ 0}, the one that article 01 proved not regular.
The first listing treats the grammar as data, a dictionary from non-terminal to a list of productions, and the function genera enumerates all the strings up to length n by always expanding the leftmost non-terminal. To be sure that the enumeration tells the truth I compare it with a check written differently: a counter for anbn, and for balanced parentheses a depth counter, that is, a stack with a single kind of symbol. The second grammar, S → (S)S | ε, generates well-balanced parentheses.
# cfg.py - a context-free grammar as data, and its language by enumeration
from itertools import product
def genera(g, inizio, n):
"""All the strings of terminals of length at most n that derive from `inizio`
(leftmost derivations: the first non-terminal on the left is always expanded)."""
risultato, visti, pila = set(), set(), [(inizio,)]
while pila:
forma = pila.pop()
if forma in visti:
continue
visti.add(forma)
terminali = sum(1 for s in forma if s not in g)
if terminali > n or len(forma) > 2 * n + 1:
continue
i = next((k for k, s in enumerate(forma) if s in g), None)
if i is None:
risultato.add(''.join(forma))
continue
for produzione in g[forma[i]]:
pila.append(forma[:i] + produzione + forma[i + 1:])
return risultato
def an_bn(w): # independent check: a counter
n = w.count('a')
return w == 'a' * n + 'b' * n
def bilanciata(w): # independent check: a stack with a single symbol
profondita = 0
for c in w:
profondita += 1 if c == '(' else -1
if profondita < 0:
return False
return profondita == 0
if __name__ == '__main__':
N = 12
grammatiche = {
'S -> aSb | eps': ({'S': [('a', 'S', 'b'), ()]}, 'ab', an_bn),
'S -> (S)S | eps': ({'S': [('(', 'S', ')', 'S'), ()]}, '()', bilanciata),
}
for nome, (g, alfabeto, predicato) in grammatiche.items():
generate = genera(g, 'S', N)
attese = {''.join(t) for k in range(N + 1) for t in product(alfabeto, repeat=k)
if predicato(''.join(t))}
print(f'{nome:17} strings up to {N}: {len(generate):3} equal to the check: {generate == attese}')
print('examples of S -> aSb | eps:', sorted(genera(grammatiche['S -> aSb | eps'][0], 'S', 6), key=lambda w: (len(w), w)))
# Output:
# S -> aSb | eps strings up to 12: 7 equal to the check: True
# S -> (S)S | eps strings up to 12: 197 equal to the check: True
# examples of S -> aSb | eps: ['', 'ab', 'aabb', 'aaabbb']
On all strings up to length 12, the two languages coincide with the independent checks. The 197 balanced parenthesis strings up to length 12 are the sum of the Catalan numbers for k from 0 to 6 (1+1+2+5+14+42+132): it is a third count, and it matches. This does not prove that the grammars generate exactly those languages for every length: it shows that there is no defect up to 12, and it is the same guarantee as a test suite.
Derivations and derivation trees
The same string can be derived in several orders. In aabb from S → aSb | ε there is only one non-terminal at a time and the order changes nothing; with more non-terminals you can choose which one to expand. A leftmost derivation always expands the leftmost non-terminal, a rightmost one the rightmost. A derivation tree records the rules used but not the order: the root is S, every internal node is a non-terminal whose children are the symbols of the right-hand side of the rule applied, and the leaves, read from left to right, give the string.
Erickson observes that a tree with at least one node that has more than one non-terminal child corresponds to several derivations, those that differ in the order of expansion. Fixing the leftmost order removes this freedom: to each tree corresponds a single leftmost derivation, and vice versa. It is the fact I use in the next program, where counting trees and counting leftmost derivations are the same thing.
Ambiguity: when two trees say two different things
A string is ambiguous with respect to a grammar if it has more than one derivation tree, and the grammar is ambiguous if some string is (Erickson's definition). It is not an academic ambiguity: the meaning of a string is computed from the tree. The grammar E → E+E | E*E | (E) | d, with d standing for a number, generates arithmetic expressions but gives the string d+d*d two trees: one that groups (d+d)*d and one that groups d+(d*d). With the numbers 2, 3, 4 the two trees are worth 20 and 14.
The program ambiguita.py counts the trees in two independent ways. The first, conta_dp, is a dynamic programming over slices of the string: the trees of E on w[i:j] are the sum, over every rule and every cut point, of the products of the counts of the children. The second, conta_leftmost, really enumerates all the leftmost derivations that produce the string. Then it builds the trees (alberi), evaluates them with valore and compares the ambiguous grammar with a second one, SENZA, which encodes precedence with three levels (E sums of T, T products of F, F numbers or parenthesized expressions).
# ambiguita.py - counting derivation trees, in two independent ways
from functools import lru_cache
from math import comb
from cfg import genera
AMBIGUA = {'E': [('E', '+', 'E'), ('E', '*', 'E'), ('(', 'E', ')'), ('d',)]}
SENZA = {'E': [('E', '+', 'T'), ('T',)], 'T': [('T', '*', 'F'), ('F',)],
'F': [('(', 'E', ')'), ('d',)]}
def alberi(g, w, simbolo, i, j):
"""All the trees of `simbolo` on the slice w[i:j]. A grammar without epsilon."""
if simbolo not in g:
return [simbolo] if j - i == 1 and w[i] == simbolo else []
risultato = []
for produzione in g[simbolo]:
for figli in sequenze(g, w, produzione, i, j):
risultato.append((simbolo,) + figli)
return risultato
def sequenze(g, w, simboli, i, j):
if len(simboli) == 1:
return [(a,) for a in alberi(g, w, simboli[0], i, j)]
risultato = []
for k in range(i + 1, j - len(simboli) + 2): # every symbol derives at least 1 character
for a in alberi(g, w, simboli[0], i, k):
for resto in sequenze(g, w, simboli[1:], k, j):
risultato.append((a,) + resto)
return risultato
def conta_dp(g, w):
@lru_cache(maxsize=None)
def conta(simbolo, i, j):
if simbolo not in g:
return 1 if j - i == 1 and w[i] == simbolo else 0
return sum(conta_seq(p, i, j) for p in g[simbolo])
@lru_cache(maxsize=None)
def conta_seq(simboli, i, j):
if len(simboli) == 1:
return conta(simboli[0], i, j)
return sum(conta(simboli[0], i, k) * conta_seq(simboli[1:], k, j)
for k in range(i + 1, j - len(simboli) + 2))
return conta('E', 0, len(w))
def conta_leftmost(g, w):
"""Every tree corresponds to a single leftmost derivation: I count them all."""
contate, pila = 0, [('E',)]
while pila:
forma = pila.pop()
i = next((k for k, s in enumerate(forma) if s in g), None)
if i is None:
contate += ''.join(forma) == w
continue
if len(forma) > len(w) or not w.startswith(''.join(forma[:i])):
continue
pila.extend(forma[:i] + p + forma[i + 1:] for p in g[forma[i]])
return contate
def valore(albero, numeri):
if isinstance(albero, str):
return next(numeri) if albero == 'd' else None
v = [valore(f, numeri) for f in albero[1:]]
if len(v) == 1:
return v[0]
if albero[2] == '+': return v[0] + v[2]
if albero[2] == '*': return v[0] * v[2]
return v[1] # ( E )
w = 'd+d*d'
for nome, g in (('ambiguous', AMBIGUA), ('unambiguous', SENZA)):
valori = sorted(valore(t, iter([2, 3, 4])) for t in alberi(g, w, 'E', 0, len(w)))
print(f'{nome:16} trees for {w}: {conta_dp(g, w)} (leftmost: {conta_leftmost(g, w)}); 2+3*4 is worth {valori}')
print('k operators + : trees (DP, leftmost) and Catalan number comb(2k,k)/(k+1)')
for k in range(1, 8):
s = 'd' + '+d' * k
ptr = conta_leftmost(AMBIGUA, s) if k <= 4 else '-'
print(f' k={k}: {conta_dp(AMBIGUA, s):4} {ptr!s:>4} {comb(2 * k, k) // (k + 1)}')
N = 9
print('same language up to length', N, ':', genera(AMBIGUA, 'E', N) == genera(SENZA, 'E', N),
f'({len(genera(SENZA, "E", N))} strings)')
# Output:
# ambiguous trees for d+d*d: 2 (leftmost: 2); 2+3*4 is worth [14, 20]
# unambiguous trees for d+d*d: 1 (leftmost: 1); 2+3*4 is worth [14]
# k operators + : trees (DP, leftmost) and Catalan number comb(2k,k)/(k+1)
# k=1: 1 1 1
# k=2: 2 2 2
# k=3: 5 5 5
# k=4: 14 14 14
# k=5: 42 - 42
# k=6: 132 - 132
# k=7: 429 - 429
# same language up to length 9 : True (257 strings)
The two counts coincide where I compared them, for k from 1 to 4 (going derivation by derivation costs too much beyond that). The values are the Catalan numbers 1, 2, 5, 14, 42, 132, 429, and the case k = 3, five trees for d+d+d+d, is the same one that Erickson shows for S → 1 | S+S on the string 1+1+1+1. The unambiguous grammar has a single tree for d+d*d and its only value is 14, the one you expect from the precedence of multiplication, and the check by enumeration says that the two grammars generate the same 257 strings up to length 9.
You draw two practical rules from this. Ambiguity is a property of the grammar, not of the language: the same language has here an ambiguous grammar and an unambiguous one, and what Erickson calls "inherently ambiguous" is something else, a language for which every grammar is ambiguous. Moreover, I have no general ambiguity check here: in practice one looks, as I did, for strings with more than one tree. For a compiler, ambiguity must be removed or resolved with external rules (precedence and associativity). In article 04 the grammar becomes the basis of a parser, and there it matters to have a single tree per string.
Chomsky normal form and the CYK algorithm
A grammar in Chomsky normal form (CNF), in Erickson's definition, has the start symbol never appearing on the right, and every other rule is A → BC (two non-terminals) or A → a (one terminal); in addition, the start symbol may have the rule S → ε. The theorem that holds everything up says that every context-free grammar has an equivalent one in CNF; you find it with the conversion algorithm described in the chapter, which I do not reproduce here. The advantage is that the trees become binary: for a string of length n there are exactly 2n − 1 non-terminal nodes.
Converting S → aSb | ab by hand is instructive. aSb has three symbols: I split it into A X with X → S B, and A and B become the non-terminals of the two terminals. Since S must not appear on the right and X calls it, I introduce T with the same rules as S and use T inside X. With a grammar in this form you decide membership with the CYK algorithm, which fills a table.
- for each character of the string, write the non-terminals that produce it with a rule
A → a; - for increasing lengths from 2 to
n, consider every slice of that length; - for each cut point of the slice, if there is a rule
A → BCwithBin the cell of the left part andCin that of the right, addAto the cell of the slice; - accept if the start symbol is in the cell of the whole string.
Order matters here: the length grows because each cell depends on cells of shorter slices. The three nested loops over length, position and cut, plus the scan of the rules, make the time cubic in the length of the string (this is a reading of the loops of the listing, not a time measurement). The algorithm is called CYK; among the authors to whom it is due I verified on Crossref only "Recognition and parsing of context-free languages in time n³" by Younger (Information and Control 10, February 1967), cited but not read. The program runs CYK on two CNF grammars written as above, for anbn with n ≥ 1 and for the non-empty palindromes (P → aPa | bPb | aa | bb | a | b), and compares them with a direct predicate on 8191 strings.
# cyk.py - recognition with a grammar in Chomsky normal form (CYK algorithm)
from itertools import product
def cyk(g, inizio, w):
n = len(w)
if n == 0:
return False # these grammars do not produce epsilon
t = [[set() for _ in range(n + 1)] for _ in range(n)] # t[i][l]: non-terminals for w[i:i+l]
for i, c in enumerate(w):
t[i][1] = {A for A, ps in g.items() if (c,) in ps}
for lung in range(2, n + 1):
for i in range(n - lung + 1):
for taglio in range(1, lung):
for A, ps in g.items():
for p in ps:
if len(p) == 2 and p[0] in t[i][taglio] and p[1] in t[i + taglio][lung - taglio]:
t[i][lung].add(A)
return inizio in t[0][n]
# a^n b^n with n >= 1. S -> aSb | ab is not in normal form: aSb becomes A X with X -> S B.
# To keep the start symbol out of the right-hand sides, S and T have the same rules and X uses T.
G_ANBN = {'S': [('A', 'X'), ('A', 'B')], 'T': [('A', 'X'), ('A', 'B')],
'X': [('T', 'B')], 'A': [('a',)], 'B': [('b',)]}
# non-empty palindromes over {a, b}: P -> aPa | bPb | aa | bb | a | b, same technique.
REGOLE_P = [('A', 'Y'), ('B', 'Z'), ('A', 'A'), ('B', 'B'), ('a',), ('b',)]
G_PAL = {'S': REGOLE_P, 'P': REGOLE_P, 'Y': [('P', 'A')], 'Z': [('P', 'B')],
'A': [('a',)], 'B': [('b',)]}
def an_bn(w):
n = w.count('a')
return len(w) > 0 and w == 'a' * n + 'b' * n
tutte = [''.join(t) for k in range(13) for t in product('ab', repeat=k)]
for nome, g, predicato in (('a^n b^n', G_ANBN, an_bn),
('palindromes', G_PAL, lambda w: len(w) > 0 and w == w[::-1])):
errori = sum(cyk(g, 'S', w) != predicato(w) for w in tutte)
accettate = sum(cyk(g, 'S', w) for w in tutte)
print(f'{nome:11} strings={len(tutte)} accepted={accettate:3} errors={errori}')
# Output:
# a^n b^n strings=8191 accepted= 6 errors=0
# palindromes strings=8191 accepted=252 errors=0
Zero errors on 8191 strings for both: the 6 strings accepted for anbn are ab, aabb, …, a6b6, and the 252 of the palindromes are the sum of the 2⌈k/2⌉ non-empty palindromes of length k, for k from 1 to 12 (a third arithmetic check). Palindromes recall the case of anbn: recognizing them requires comparing the left half with the right half, that is, remembering an unbounded number of symbols, and for that reason a finite-state automaton is not enough (the proof follows that of article 01 and I do not redo it).
The pumping lemma for context-free languages
Context-free languages contain all the regular ones but are not everything: anbncn is not generated by any grammar. The lemma, in its classical form, says: if L is context-free there is p ≥ 1 such that every w ∈ L with |w| ≥ p can be written w = uvxyz with |vxy| ≤ p, |vy| ≥ 1 and uvixyiz ∈ L for every i ≥ 0. The outline of the proof, which I do not retrace in every detail, is the same pigeonhole as in article 01 applied to the tree: with a CNF grammar of m non-terminals, a sufficiently long word has a tree tall enough to have, along one path, a repeated non-terminal; the two subtrees with the same root can be swapped or duplicated, and this gives v and y to "pump" together.
How the lemma is used, to show that L = {anbncn} is not context-free, follows the same steps as in the regular case.
- suppose for contradiction that
Lis context-free, with pumping lengthp; - you choose a word,
w = apbpcp; - consider every decomposition
uvxyzwith|vxy| ≤ pand|vy| ≥ 1: the blockvxyis at mostplong, so it cannot touch both theas and thecs, which are separated byplettersb; - pumping
vandychanges the number of at most two of the three letters, never all three, so withi = 0ori = 2the word leavesL: contradiction.
The steps are ordered because each depends on the previous one, and the delicate point is the third: the decomposition is chosen by the adversary, so the proof must hold for all of them. The program cfl_pumping.py does the numerical check: for p from 1 to 6 it lists all the decompositions of apbpcp and counts how many hold for i from 0 to 3. For comparison it does the same for apbp, which is context-free, and where there must be at least one decomposition that holds (v = a, y = b).
# cfl_pumping.py - the pumping lemma for context-free languages, decomposition by decomposition
def in_anbn(w):
n = w.count('a')
return n > 0 and w == 'a' * n + 'b' * n
def in_anbncn(w):
n = w.count('a')
return n > 0 and w == 'a' * n + 'b' * n + 'c' * n
def sopravvivono(w, p, appartiene):
"""Decompositions w = u v x y z with |vxy| <= p and |vy| >= 1 that stay in the language
for i = 0, 1, 2, 3 (that is, u v^i x y^i z)."""
totale = buone = 0
for i in range(len(w) + 1):
for l in range(i, min(len(w), i + p) + 1):
for j in range(i, l + 1):
for k in range(j, l + 1):
u, v, x, y, z = w[:i], w[i:j], w[j:k], w[k:l], w[l:]
if len(v) + len(y) == 0:
continue
totale += 1
if all(appartiene(u + v * m + x + y * m + z) for m in range(4)):
buone += 1
return totale, buone
print(' p a^p b^p: decompositions / that hold a^p b^p c^p: decompositions / that hold')
for p in range(1, 7):
t1, b1 = sopravvivono('a' * p + 'b' * p, p, in_anbn)
t2, b2 = sopravvivono('a' * p + 'b' * p + 'c' * p, p, in_anbncn)
print(f'{p:3} {t1:6} / {b1:<6} {t2:7} / {b2}')
# Output:
# p a^p b^p: decompositions / that hold a^p b^p c^p: decompositions / that hold
# 1 4 / 0 6 / 0
# 2 23 / 1 37 / 0
# 3 73 / 3 121 / 0
# 4 175 / 7 295 / 0
# 5 355 / 13 605 / 0
# 6 644 / 22 1106 / 0
On apbpcp none of the decompositions holds for any p tried (from 6 decompositions for p = 1 to 1106 for p = 6, all rejected), while on apbp 1, 3, 7, 13, 22 hold from p = 2 onwards: for p = 1 the block vxy is too short to contain both a and b, and indeed none holds. The check covers six values of p, not all: the proof is the argument in words above, and the program shows its idea with numbers.
Here is what you can do now. You can write a context-free grammar and check by enumeration that it generates what you intended; you can distinguish derivation and derivation tree and count the trees of a string in two ways; you can recognize an ambiguity from the different values the trees compute; you can put a grammar in Chomsky normal form and run it with CYK; and you can use the pumping lemma to show that anbncn lies outside the field. In article 04 you use the grammar to build a top-down parser.
Frequently asked questions
What is the difference between a derivation and a derivation tree?
The derivation is the sequence of rewritings, in a certain order; the tree records which rules were used but not the order. A tree corresponds to a single leftmost derivation, and a single rightmost one, but may correspond to many others that differ in the order of expansion.
Does an ambiguous grammar make the language ambiguous?
No: ambiguity is a property of the grammar. Arithmetic expressions with parentheses have an ambiguous grammar and an unambiguous one that generates the same strings, as verified here up to length 9. A language is inherently ambiguous only if every one of its grammars is.
Why is a^n b^n context-free but not regular?
Because the grammar S → aSb | ε generates it with a recursive rule, while a finite-state automaton cannot count an unbounded number of a's: article 01 proves it with the regular pumping lemma and with the Myhill-Nerode classes.
The same series also includes article 05, bottom-up parsers and article 06, semantic analysis and optimization.
Sources
- Jeff Erickson, "Context-Free Languages and Grammars" (Models of Computation, ch. 5) - PDF downloaded and read on 2026-11-13 (text extracted): components of a grammar, derivation tree, ambiguity and the example of
S → 1 | S+Swith five trees, inherently ambiguous language, definition of Chomsky normal form and equivalence theorem. - D. H. Younger, "Recognition and parsing of context-free languages in time n³", Information and Control 10 (1967) - cited, not read: title, journal, volume and date verified on Crossref on 2026-11-13.
Previous article: 02 - DFA, NFA, ε-NFA: Equivalences and Thompson Construction. Next article: 04 - Top-Down Parsers: LL(1), Recursive Descent. The series index is on the series page.
Commenti
Caricamento commenti...
Sign in to comment