Theory of ComputationUnit 47 min read
Context-Free Languages & Pushdown Automata: Grammars, Parsing, and PDA
Unit 4 of Theory of Computation explores context-free grammars (CFGs), their Chomsky Normal Form, parsing trees, and Pushdown Automata (PDAs), including how they model nested structures like parentheses or balanced tags, with real-world ties to compilers, syntax validation, and stack-based algorithms.
TAKEAWAYS:
- Context-free grammars (CFGs) define languages where production rules apply to non-terminals without context, enabling syntax for programming languages and natural language parsing.
- Chomsky Normal Form (CNF) simplifies CFGs into binary productions (A→BC or A→a), crucial for parsing algorithms like CYK and Earley.
- Pushdown Automata (PDAs) extend finite automata with a stack, accepting context-free languages by tracking nested structures (e.g., balanced parentheses).
- The Pumping Lemma for CFLs proves languages like {aⁿbⁿcⁿ} are not context-free by showing no finite "pumpable" substring can generate all strings.
- Real-world applications include compilers (validating code syntax), HTML/XML parsers (checking tag balance), and stack-based algorithms (e.g., evaluating arithmetic expressions).
- Key difference: CFGs handle recursion/nesting (e.g., loops in code), while regular grammars only handle linear patterns (e.g., fixed-length IDs).
1. Context-Free Grammars (CFGs): Definitions and Examples
A context-free grammar (CFG) is a 4-tuple , where:
- : finite set of non-terminals (e.g.,
S,A,B). - : finite set of terminals (e.g.,
a,b,+). - : set of production rules (e.g., ).
- : start symbol (a non-terminal).
Key Property: Productions apply to single non-terminals without context (hence "context-free"). Example: Grammar for balanced parentheses:
S → SS | (S) | ε
Visualization:
graph TD S["S"] --> S1["S → S S"] S --> P[(S)] S --> E["ε"] P --> L[( L --> S2["S"] S2 --> R[")"]
Derivation Trace for (()):
2. Chomsky Normal Form (CNF)
CNF restricts productions to:
- (two non-terminals), or
- (single terminal), or
- (only for start symbol).
Why CNF?
- Simplifies parsing algorithms (e.g., CYK dynamic programming).
- Proves equivalence between CFGs and PDAs.
Example: Convert to CNF.
- Introduce new non-terminals:
- Eliminate -productions (if needed) by adding .
3. Pushdown Automata (PDAs): Stack-Based Recognition
A PDA extends NFAs with a stack to handle nested structures. Formal Definition: , where:
- : stack alphabet.
- : transition function (may push/pop stack).
- : start stack symbol.
Example: PDA for .
Trace for aabb:
- Push
Afor eacha: stack =[A, A]. - Pop
Afor eachb: stack empties → accept.
4. The Pumping Lemma for Context-Free Languages (CFLs)
Statement: If is CFL, there exists a pump length such that any with can be divided into , where:
- ,
- ,
- for all .
Proof Sketch:
- Assume is CFL; derive a PDA.
- Show the PDA’s stack cannot "remember" unbounded context (e.g., requires 3 stacks).
Example: Prove is not CFL.
- Assume is CFL; pick .
- Pump : (unbalanced s).
- Contradiction: cannot be CFL.
5. Applications in Real-World Systems
In the Real World
Compilers (e.g., GCC, Java Compiler)
- Idea Used: CFGs define syntax rules (e.g.,
if (condition) { statements }). - How: Parsers (e.g., recursive descent) use CFGs to validate code structure before execution.
- Idea Used: CFGs define syntax rules (e.g.,
HTML/XML Parsers (e.g., Chrome’s Blink Engine)
- Idea Used: PDA-like stack to track nested tags (e.g.,
<div><p></p></div>). - How: Push opening tags, pop on closing tags; mismatch → error.
- Idea Used: PDA-like stack to track nested tags (e.g.,
Arithmetic Expression Evaluators (e.g., Python’s
eval())- Idea Used: PDA stack to handle operator precedence (e.g.,
3 + 4 * 2). - How: Push operands, apply operations when higher-precedence operators are encountered.
- Idea Used: PDA stack to handle operator precedence (e.g.,
Nepali Apps: eSewa/Khalti Transaction Validation
- Idea Used: CFGs validate transaction formats (e.g.,
PAY <amount> <to> <ref>). - How: Reject malformed inputs (e.g.,
PAY 500without recipient).
- Idea Used: CFGs validate transaction formats (e.g.,
Bank Loan Amortization (Nepal’s NMB/Global IME)
- Idea Used: Recursive CFG to model loan repayment schedules.
- How: Each payment reduces principal + interest, mirrored in PDA stack states.
6. Worked Example: PDA for Balanced Parentheses
Language: . PDA Design:
stateDiagram-v2
[*] --> q0: start
q0 --> q0: read '(', push '('
q0 --> q1: read ')', pop '('
q1 --> q1: read ')', pop '('
q1 --> q0: read '(', push '('
q0 --> accept: stack empty, read εTrace for (()):
- Push
(,(: stack =[(, (]. - Pop
(,(: stack empty → accept.
7. Comparison: Regular vs. Context-Free Languages
| Feature | Regular Languages (RL) | Context-Free Languages (CFL) |
|---|---|---|
| Grammar Type | Regular Grammar | Context-Free Grammar (CFG) |
| Automaton | Finite Automaton (FA) | Pushdown Automaton (PDA) |
| Stack Needed? | No | Yes (for nesting) |
| Example | a*b* (linear patterns) |
aⁿbⁿ (nested balance) |
| Closure Properties | +, *, intersection, etc. | +, *, union, but not complement |
| Pumping Lemma | Exists | Exists (harder to apply) |
8. Exam Tip: How to Score Full Marks
For CFG → CNF Conversion:
- Show every intermediate step (e.g., introducing ).
- Label new non-terminals clearly (e.g., ).
For PDA Construction:
- Draw the state diagram with stack operations.
- Trace one example string (e.g.,
aabbfor ).
Pumping Lemma Proofs:
- Assume the language is CFL → derive contradiction.
- Pick a string with (e.g., ).
- Pump and show the result violates the language definition.
Real-World Links:
- Tie CFGs to compiler syntax or HTML parsing.
- For PDAs, mention stack-based algorithms (e.g., Dijkstra’s shortest path).
Avoid Common Mistakes:
- ❌ Forgetting to handle -productions in CNF.
- ❌ PDA transitions without stack updates.
- ❌ Pumping Lemma: not all substrings can be pumped (e.g., must be derivable from ).
Derivation tree for (Image: MartinThoma, CC BY 3.0, via Wikimedia Commons)
Based on the TU BSc CSIT syllabus for Theory of Computation (CSC262), unit 4.
Discussion
Loading…