CSC 392 · Automata Theory, Computability and Formal Languages
Our notes
2 min readGrammars
A context-free grammar (CFG) G = (V, T, P, S):
- V: variables (non-terminals),
- T: terminals (the alphabet),
- P: productions A → α (one variable on the left),
- S: start variable.
It is context-free because A can be replaced whatever surrounds it.
Example: {aⁿbⁿ}
S → aSb | ε
Derivation of aabb: S ⇒ aSb ⇒ aaSbb ⇒ aabb. (A regular expression cannot do this; a grammar can.)
Example: arithmetic expressions
E → E + T | T
T → T * F | F
F → ( E ) | id
Leftmost derivation of id + id * id:
E ⇒ E + T ⇒ T + T ⇒ F + T ⇒ id + T ⇒ id + T * F ⇒ id + F * F ⇒ id + id * F ⇒ id + id * id.
In the parse tree, * sits lower than +, so the multiplication is grouped first: the grammar builds precedence in.
Derivations and parse trees
- Leftmost derivation: always replace the leftmost variable; rightmost: the rightmost.
- A parse tree shows the structure: the root is S, leaves read left to right give the string. Each parse tree has exactly one leftmost derivation.
Ambiguity
A grammar is ambiguous if some string has two different parse trees.
E → E + E | E * E | id is ambiguous: id + id * id can group as id + (id * id) or (id + id) * id. With values 2 + 3 × 4 these give 14 and 20. Compilers must not be ambiguous about this.
Remedies:
- Rewrite the grammar with levels for precedence (E, T, F above) and left recursion for left associativity.
- The classic dangling else: if a then if b then s1 else s2: which if owns the else? Languages settle it by a rule (the nearest if) or by syntax (end if).
Grammar transformations (for parsing)
- Eliminate left recursion: E → E + T | T becomes E → T E′, E′ → + T E′ | ε.
- Left factoring: A → ab | ac becomes A → aA′, A′ → b | c.
- Chomsky normal form: every rule A → BC or A → a (used by the CYK parsing algorithm).
Exams usually ask
- Write grammars for given languages.
- Give leftmost and rightmost derivations and draw parse trees.
- Show a grammar is ambiguous and remove the ambiguity.
Common mistake
Thinking ambiguity belongs to the language. It belongs to the grammar: the same language usually has an unambiguous grammar too (some rare languages have none).
Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.
No reading links here yet
Our team adds free books, videos and practice for each topic, and opens every link before it goes up.