Sub topic 7
Context-free grammars
A context-free grammar (CFG) is the notation a compiler uses to describe the structure of a program. This chapter assumes you know regular expressions, basic set notation, and recursion. It also assumes you have seen the idea of a pushdown automaton. The goal is to read a grammar, say what language it generates, and avoid the usual mistakes in GATE questions.
Why regular expressions are not enough
Regular expressions describe tokens such as identifiers and numbers. They cannot describe nesting. The language of balanced parentheses, or { aⁿbⁿ : n ≥ 0 }, needs unbounded counting, and a finite automaton has only finitely many states. A CFG handles this by letting a rule refer to itself. Every regular language is context-free, but not the other way around.
The formal definition
A CFG is a 4-tuple G = (V, T, P, S).
| Part | Meaning | Example |
|---|---|---|
| V | Finite set of nonterminals (variables) | { S } |
| T | Finite set of terminals, the token alphabet; V and T are disjoint | { a, b } |
| P | Finite set of productions A → α, where A is in V and α is a string over V ∪ T | S → aSb, S → ε |
| S | Start symbol, an element of V | S |
The left side of a production is always a single nonterminal. That restriction is what "context-free" means. A nonterminal can be replaced no matter which symbols surround it. A production such as aSb → aab has a context on its left side and is not context-free.
By convention, uppercase letters are nonterminals and lowercase letters or quoted symbols are terminals. The first production's left side is the start symbol unless stated otherwise. Productions A → α and A → β can be written together as A → α | β.
Derivations and the language of a grammar
A derivation step, written ⇒, replaces one nonterminal in a string with the body of one of its productions. The relation ⇒* means "zero or more steps". For S → aSb | ε:
S ⇒ aSb ⇒ aaSbb ⇒ aabb
Two terms matter here:
- A sentential form is any string over V ∪ T reachable from S, such as aaSbb.
- A sentence is a sentential form made only of terminals, such as aabb.
The language of the grammar is L(G) = { w in T : S ⇒ w }. For this grammar, L(G) = { aⁿbⁿ : n ≥ 0 }.
Which nonterminal you replace at each step, and in what order, is the subject of the next chapter. Here you only need to know that a derivation is a sequence of replacements ending in a sentence.
A worked example: balanced parentheses
Consider the grammar S → ( S ) S | ε.
The body ( S ) S says that a balanced string is a pair of parentheses around a balanced string, followed by another balanced string. The ε production ends the recursion. Here is a derivation of ()():
S ⇒ ( S ) S ⇒ ( ) S ⇒ ( ) ( S ) S ⇒ ( ) ( ) S ⇒ ( ) ( )
The derivation can also be drawn as a tree. Each internal node is a nonterminal, and its children are the symbols of the production body.
Enumerating a language with code
You can generate short sentences by repeatedly expanding the leftmost nonterminal. The program below does this breadth-first and discards any form with more than max_len terminals. The bound makes it terminate for this grammar. It would not terminate for a grammar like S → SS | ε, because those forms never gain terminals.
from collections import deque
GRAMMAR = {"S": [["(", "S", ")", "S"], []]} # [] is the epsilon body
def generate(grammar, start, max_len):
results, seen = set(), set()
queue = deque([(start,)])
while queue:
form = queue.popleft()
if form in seen:
continue
seen.add(form)
idx = next((i for i, s in enumerate(form) if s in grammar), None)
if idx is None: # no nonterminals left: a sentence
results.add("".join(form))
continue
for body in grammar[form[idx]]:
new = form[:idx] + tuple(body) + form[idx + 1:]
if sum(1 for s in new if s not in grammar) <= max_len:
queue.append(new)
return sorted(results, key=lambda s: (len(s), s))
print(generate(GRAMMAR, "S", 4))
# ['', '()', '(())', '()()']Common errors
- Reading the language off the first few strings. Check that every sentence fits the pattern and that every string matching the pattern is derivable. For S → aSb | ε, the string
aabis not generated, even though it looks similar to strings that are. - Forgetting ε. The empty string is in L(G) whenever S ⇒* ε. In S → aSb | ε it is, because n = 0 is allowed.
- Treating a nonterminal as a terminal. A derivation is not finished until no nonterminal remains. Strings like aaSbb are sentential forms, not members of L(G).
- Assuming every grammar is usable by a parser as written. Some grammars are ambiguous. Others have left recursion or common prefixes. Both are fixed in later chapters.
- Mixing up "context-free" with "regular". A regular grammar is a CFG whose productions all have the form A → aB or A → a (right-linear). A CFG with productions like S → aSb is not regular.
What GATE asks about CFGs
Typical questions give a grammar and ask for one of these:
- The language it generates, for example "equal numbers of a and b, with all a's first".
- Whether a given string is derivable.
- The number of strings of a given length in L(G).
- A grammar for a described language, usually as a choice among options.
The reliable method for the first three is to enumerate the shortest sentences by hand. Compare them with each option, then test a string that should fail.
Exercise
For the grammar S → aSb | bSa | SS | ε, is the string "abba" in L(G)? Give a derivation or explain why not.
Show answer
Yes. S ⇒ aSb ⇒ abSab is wrong because the production aSb puts one a before S and one b after it, so S ⇒ aSb ⇒ a(bSa)b ⇒ abSab is also not what we want. A correct derivation uses SS: S ⇒ SS ⇒ aSb S ⇒ ab S ⇒ ab bSa ⇒ abba, where the inner S becomes ε in each of the two steps. The first S is replaced by aSb with the S inside becoming ε, giving "ab". The second S is replaced by bSa with the S inside becoming ε, giving "ba". Concatenated they give "abba", so the string is in L(G).
Exercise
Write a CFG for { aⁿb²ⁿ : n ≥ 0 }, and state how many sentences of length 6 it generates.
Show answer
S → a S b b | ε. Each use of the first production adds one a and two b's, so every sentence has the form aⁿb²ⁿ. Length 6 requires 3n = 6, so n = 2, giving exactly one sentence: aabbbb.