Context-Free Grammars & Derivations

a context-free grammar

Regular languages, recognised by finite automata, hit a wall: a machine with finite memory cannot count without bound, so it cannot guarantee that the number of left brackets equals the number of right brackets, nor describe arbitrarily deep nesting. Programming languages, arithmetic, and matched parentheses all NEED that nesting. A context-free grammar is the tool that climbs one rung up the ladder to capture exactly this recursive, nested structure.

Formally a context-free grammar is a 4-tuple (V, Σ, R, S). V is the finite set of variables (nonterminals), the placeholders. Σ (Sigma) is the alphabet of terminals, the actual letters of generated strings, and V and Σ are disjoint. R is the finite set of production rules, and S in V is the start symbol. The defining restriction — the reason it is called 'context-free' — is that every rule has the shape A → α where the left side is a SINGLE variable A and the right side α is any string of variables and terminals. Because the left side is just one variable, you may rewrite that variable no matter what surrounds it; its 'context' does not matter. This single-variable-on-the-left rule is the whole definition, and it is what distinguishes context-free from the more powerful context-sensitive grammars higher in the Chomsky hierarchy.

Context-free grammars are the workhorse of computer-language syntax: the structure of expressions, statements, and nested blocks in almost every programming language is specified by a CFG, usually written in BNF. They are equivalent in power to pushdown automata (finite-state control plus a single stack), and they generate exactly the context-free languages. A common misconception is that 'context-free' means meaning is ignored — it does not; it is a purely syntactic restriction on the FORM of the rules (one variable on the left), and a context-free grammar can still describe richly structured languages.

A CFG for balanced parentheses: V = {S}, Σ = {(, )}, S start, with rules S → S S | ( S ) | ε. Here ε (epsilon) is the empty string. From S we get S => (S) => (SS) => (()S) => (()()), generating a properly nested string.

(V, Σ, R, S): every rule rewrites a single variable, which is exactly what 'context-free' means.

'Context-free' is a restriction on rule FORM (one variable on the left), not a claim that semantics are ignored. CFGs are strictly more powerful than regular grammars but strictly less powerful than context-sensitive ones.

Also called
CFG前後文無關文法