A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Context-Free Grammars (CFGs)

College Depth 85 in the knowledge graph ☐ I know this ☆ Set as goal
334topics build on this
399prerequisites beneath it
See this on the map →
Formal Languages and StringsRecursion Basics+2 more→→Chomsky Normal Form (CNF)Context-Free Grammar Properties and Ambiguity+7 more
CFG context-free grammars productions derivation

Core Idea

A context-free grammar (CFG) is a 4-tuple (V, Σ, R, S) of variables, terminals, production rules, and a start variable. Each rule replaces a single variable with any string of variables and terminals. The language of a CFG is the set of terminal strings derivable from the start variable. CFGs are strictly more powerful than regular expressions — they can describe languages like {aⁿbⁿ} that no DFA can recognize. CFGs are the foundation of programming language syntax, used in parser generators and compilers.

How It's Best Learned

Begin by writing grammars for arithmetic expressions (which naturally requires recursion) and palindromes. Trace leftmost and rightmost derivations step-by-step. Then attempt to characterize which languages require CFGs versus which are regular.

Common Misconceptions

Explainer

You have already seen that regular languages — described by regular expressions and recognized by finite automata — have a fundamental limitation: they cannot count. A DFA has no memory beyond its current state, which means it cannot verify that a string has exactly as many a's as b's. Context-free grammars (CFGs) overcome this by introducing recursive structure, and recursion is the key insight.

A CFG is a 4-tuple (V, Σ, R, S): a set of variables (non-terminals), a terminal alphabet, a set of production rules, and a start variable. Each rule has the form A → α, where A is a single variable and α is any string of variables and terminals. A derivation begins at S, repeatedly replaces a variable using some rule, and terminates when no variables remain. The language of the grammar is the set of all terminal strings reachable this way. Notice that derivations can be arbitrarily long — this is where the expressive power comes from.

The name "context-free" refers to the rule form: the left side is always a single variable, with no surrounding context constraining when the rule can fire. This is in contrast to context-sensitive grammars, where a rule A → B might only apply when A appears between specific symbols. Context-free rules are simple but powerful enough to capture nested structure, which is exactly what programming languages require — parentheses must balance, if-else blocks must be properly nested, function calls must close with matching arguments.

A crucial concept is ambiguity. A string w is ambiguous in grammar G if G admits two or more distinct parse trees for w. This is not just a theoretical curiosity: an ambiguous grammar for a programming language means a statement like 1 + 2 * 3 could be parsed as (1 + 2) * 3 or 1 + (2 * 3), giving different results. Grammar designers go to considerable effort to eliminate ambiguity, often by introducing operator precedence rules directly into the grammar structure.

CFGs sit in the middle of the Chomsky hierarchy: strictly more powerful than regular languages (they can express { aⁿbⁿ }), but strictly less powerful than context-sensitive and Turing-complete grammars (they cannot express { aⁿbⁿcⁿ }). The decision problem for CFLs — membership testing — is solvable in polynomial time (CYK algorithm runs in O(n³)), which makes CFGs practical for real compilers. Every time a compiler parses your source code, it is essentially running a CFL recognition algorithm on a carefully designed CFG.

Practice Questions 3 questions

Prerequisite Chain

Understanding Zero → The Number Zero → Counting to Five → Counting to 10 → Counting to 20 → Counting a Set of Objects Up to 20 → Cardinality: The Last Number Counted → Matching Numerals to Quantities → Subitizing Small Quantities → Addition Within 10 → Number Bonds to 10 → Addition Within 20 → Doubles and Near Doubles → Doubles Facts Within 10 → Near Doubles Facts Within 20 → Mental Math Strategies for Addition → Mental Math: Adding and Subtracting Tens → Addition Within 100 → Repeated Addition as Multiplication → Multiplication as Equal Groups → Multiplication: Arrays → Basic Multiplication Facts (0s, 1s, 2s, 5s, 10s) → Multiplication Facts Within 100 → Division as Equal Sharing → Division as Grouping (Measurement Division) → Division: Grouping (Repeated Subtraction) Model → Division: Fair Sharing Model → Division as Equal Sharing → Division as Grouping → Basic Division Facts → Division Facts Within 100 → Multiplication and Division Fact Families → Relationship Between Multiplication and Division → Division Facts as Inverse of Multiplication → Remainders and Quotients in Division → Division Word Problems → Multi-Step Word Problems → Solving Multi-Step Word Problems → Multiplication Word Problems → Division Word Problems → Introduction to Long Division → Factors and Multiples → Prime and Composite Numbers → Equivalent Fractions → Relating Fractions and Decimals → Decimal Place Value → Integers and the Number Line → Comparing and Ordering Integers → Absolute Value → Adding Integers → Subtracting Integers → Multiplying Integers → Introduction to Exponents → Order of Operations → Integer Order of Operations → Variable Expressions → The Distributive Property → Variables and Expressions Review → Introduction to Polynomials → Adding and Subtracting Polynomials → Multiplying Polynomials → Factorial → Permutations → Combinations → Counting Principles: Addition and Multiplication Rules → Introduction to Graph Theory → Propositional Logic Foundations → Logical Equivalences → Boolean Algebra → Boolean Type and Truth Values → Comparison Operators and Boolean Tests → Logical Operators and Boolean Algebra → Boolean Algebra and Fundamental Laws → Logic Gates Fundamentals → Implementing Boolean Functions with Gates → Karnaugh Map Simplification → Combinational Circuit Design → Flip-Flops and Latches → Finite State Machines (FSMs) → Deterministic Finite Automata (DFA) → Nondeterministic Finite Automata (NFA) → Two-Way Finite Automata → NFA to DFA Conversion (Subset Construction) → DFA Properties and Minimization Algorithms → Regular Languages: Definition and Characterization → Context-Free Grammars (CFGs)

Longest path: 86 steps · 399 total prerequisite topics

Prerequisites (4)

Leads To (9)