Context-Free Grammars (CFG)

Context: FIT2014_MOC · a generative device — build strings from a start symbol via rules · strictly more powerful than Regular Expressions, reaching the languages the pumping lemma ruled out

Quick Revision

  • 🎯 Objective: a finite set of production rules rewrites nonterminals into strings of terminals/nonterminals ➔ the language generated is every terminal string derivable from the start symbol .
  • ⚡ Key Constraint: rules replace one nonterminal at a time regardless of context (hence “context-free”); a rule’s left side is always a single nonterminal.

📝 The three ingredients

A context-free grammar consists of:

  1. An alphabet ➔ its letters are the terminals (the symbols of the final strings).
  2. A set of nonterminals ➔ often upper-case letters; one is the start symbol (usually ).
  3. A finite set of production rules of the form
  • Language generated ➔ the set of strings producible from the start symbol using the rules.
  • Context-Free Language (CFL) ➔ any language generated by some CFG.

✍️ Backus–Naur Form (BNF)

  • Shorthand ➔ collapse rules with the same left side using for “or”:
  • OriginBackus & Naur used it to define ALGOL 60; it is still how programming-language syntax is specified.
  • From an inductive definition ➔ “all integers are arithmetic expressions; if are, so are , , …” maps directly onto production rules — the standard way to invent a grammar.

🧩 Worked grammar — EQUAL (equal s and s)

Terminals ; nonterminals :

  • Design idea ➔ classify strings by their running imbalance (, one-more-, one-more-) and give each class a nonterminal — the general trick for building grammars.
  • Note ➔ EQUAL is non-regular (Proving a Language Non-Regular) yet context-free — the first concrete language separating the two classes.

🕰️ History

  • Pāṇini (~5th c. BC) ➔ rule-based grammar of Sanskrit — the ancient ancestor.
  • Chomsky ➔ formalised grammars for natural languages.
  • Backus ➔ applied them to programming languages (ALGOL).

⚠️ Common Mistakes

  • 💡 Left side is a single nonterminal ➔ that restriction is what makes a grammar context-free; a rule like (context on the left) is a different, more powerful class.
  • 💡 -rules are allowed is a legitimate production and is how the empty word enters a language.
  • 💡 Terminals vs nonterminals ➔ terminals appear in the final string; nonterminals are scaffolding that must all be rewritten away. A “derivation” isn’t finished while a nonterminal remains.
  • 💡 A grammar generates, an automaton recognises ➔ CFGs build strings top-down; the matching machine is the PDA, which reads strings.

🧠 Active Recall