 Contextfree grammar

In formal language theory, a contextfree grammar (CFG) is a formal grammar in which every production rule is of the form
 V → w
where V is a single nonterminal symbol, and w is a string of terminals and/or nonterminals (w can be empty).
The languages generated by contextfree grammars are known as the contextfree languages.
Contextfree grammars are important in linguistics for describing the structure of sentences and words in natural language, and in computer science for describing the structure of programming languages and other artificial languages.
In linguistics, some authors use the term phrase structure grammar to refer to contextfree grammars. In computer science, a popular notation for contextfree grammars is Backus–Naur Form, or BNF.
Contents
Background
Since the time of Pāṇini, at least, linguists have described the grammars of languages in terms of their block structure, and described how sentences are recursively built up from smaller phrases, and eventually individual words or word elements.
An essential property of these block structures is that logical units never overlap. For example, the sentence:

 John, whose blue car was in the garage, walked to the green store.
can be logically parenthesized as follows:

 (John, ((whose blue car) (was (in the garage)))), (walked (to (the green store))).
A contextfree grammar provides a simple and mathematically precise mechanism for describing the methods by which phrases in some natural language are built from smaller blocks, capturing the "block structure" of sentences in a natural way. Its simplicity makes the formalism amenable to rigorous mathematical study. Important features of natural language syntax such as agreement and reference are not part of the contextfree grammar, but the basic recursive structure of sentences, the way in which clauses nest inside other clauses, and the way in which lists of adjectives and adverbs are swallowed by nouns and verbs, is described exactly.
The formalism of contextfree grammars was developed in the mid1950s by Noam Chomsky, and also their classification as a special type of formal grammar (which he called phrasestructure grammars).^{[1]}
In Chomsky's generative grammar framework, the syntax of natural language was described by a contextfree rules combined with transformation rules. In later work (e.g. Chomsky 1981), the idea of formulating a grammar consisting of explicit rewrite rules was abandoned. In other generative frameworks, e.g. Generalized Phrase Structure Grammar (Gazdar et al. 1985), contextfree grammars were taken to be the mechanism for the entire syntax, eliminating transformations.
Block structure was introduced into computer programming languages by the Algol project (19571960), which, as a consequence, also featured a contextfree grammar to describe the resulting Algol syntax. This became a standard feature of computer languages, and the notation for grammars used in concrete descriptions of computer languages came to be known as BackusNaur Form, after two members of the Algol language design committee.
The "block structure" aspect that contextfree grammars capture is so fundamental to grammar that the terms syntax and grammar are often identified with contextfree grammar rules, especially in computer science. Formal constraints not captured by the grammar are then considered to be part of the "semantics" of the language.
Contextfree grammars are simple enough to allow the construction of efficient parsing algorithms which, for a given string, determine whether and how it can be generated from the grammar. An Earley parser is an example of such an algorithm, while the widely used LR and LL parsers are simpler algorithms that deal only with more restrictive subsets of contextfree grammars.
Formal definitions
A contextfree grammar G is defined by the 4tuple:
where
1. is a finite set; each element is called a nonterminal character or a variable. Each variable represents a different type of phrase or clause in the sentence. Variables are also sometimes called syntactic categories. Each variable defines a sublanguage of the language defined by .
2. is a finite set of terminals, disjoint from , which make up the actual content of the sentence. The set of terminals is the alphabet of the language defined by the grammar .
3. is a finite relation from to . The members of are called the (rewrite) rules or productions of the grammar. (also commonly symbolized by a )
4. is the start variable (or start symbol), used to represent the whole sentence (or program). It must be an element of .
The asterisk represents the Kleene star operation.
Rule application
For any strings , we say yields , written as , if and such that and . Thus, is the result of applying the rule to .
Repetitive rule application
For any (or in some textbooks), if such that
Contextfree language
The language of a grammar is the set
A language is said to be a contextfree language (CFL), if there exists a CFG , such that .
Proper CFGs
A contextfree grammar is said to be proper, if it has
 no inaccessible symbols:
 no unproductive symbols:
 no εproductions: ε
 no cycles:
The grammar G = ({S},{a,b},S,P), with productions
 S → aSa,
 S → bSb,
 S → ε,
is contextfree. A typical derivation in this grammar is S → aSa → aaSaa → aabSbaa → aabbaa. This makes it clear that . The language is contextfree, however it can be proved that it is not regular.
Examples
Wellformed parentheses
The canonical example of a context free grammar is parenthesis matching, which is representative of the general case. There are two terminal symbols "(" and ")" and one nonterminal symbol S. The production rules are
 S → SS
 S → (S)
 S → ()
The first rule allows Ss to multiply; the second rule allows Ss to become enclosed by matching parentheses; and the third rule terminates the recursion.
Starting with S, and applying the rules, one can construct:
 S → SS → SSS → (S)SS → ((S))SS → ((SS))S(S)
 → ((()S))S(S) → ((()()))S(S) → ((()()))()(S)
 → ((()()))()(())
Wellformed nested parentheses and square brackets
A second canonical example is two different kinds of matching nested parentheses, described by the productions:
 S → SS
 S → ()
 S → (S)
 S → []
 S → [S]
with terminal symbols [ ] ( ) and nonterminal S.
The following sequence can be derived in that grammar:
 ([ [ [ ()() [ ][ ] ] ]([ ]) ])
However, there is no contextfree grammar for generating all sequences of two different types of parentheses, each separately balanced disregarding the other, but where the two types need not nest inside one another, for example:
 [ [ [ [(((( ] ] ] ]))))(([ ))(([ ))([ )( ])( ])( ])
A regular grammar
 S → a
 S → aS
 S → bS
The terminals here are a and b, while the only nonterminal is S. The language described is all nonempty strings of as and bs that end in a.
This grammar is regular: no rule has more than one nonterminal in its righthand side, and each of these nonterminals is at the same end of the righthand side.
Every regular grammar corresponds directly to a nondeterministic finite automaton, so we know that this is a regular language.
It is common to list all righthand sides for the same lefthand side on the same line, using  (the pipe symbol) to separate them. Hence the grammar above can be described more tersely as follows:
 S → a  aS  bS
Matching pairs
In a contextfree grammar, we can pair up characters the way we do with brackets. The simplest example:
 S → aSb
 S → ab
This grammar generates the language , which is not regular (according to the Pumping Lemma for regular languages).
The special character ε stands for the empty string. By changing the above grammar to
 S → aSb  ε
we obtain a grammar generating the language instead. This differs only in that it contains the empty string while the original grammar did not.
Algebraic expressions
Here is a contextfree grammar for syntactically correct infix algebraic expressions in the variables x, y and z:
 S → x
 S → y
 S → z
 S → S + S
 S → S  S
 S → S * S
 S → S / S
 S → ( S )
This grammar can, for example, generate the string
 ( x + y ) * x  z * y / ( x + x )
as follows:
 S (the start symbol)
 → S  S (by rule 5)
 → S * S  S (by rule 6, applied to the leftmost S)
 → S * S  S / S (by rule 7, applied to the rightmost S)
 → ( S ) * S  S / S (by rule 8, applied to the leftmost S)
 → ( S ) * S  S / ( S ) (by rule 8, applied to the rightmost S)
 → ( S + S ) * S  S / ( S ) (etc.)
 → ( S + S ) * S  S * S / ( S )
 → ( S + S ) * S  S * S / ( S + S )
 → ( x + S ) * S  S * S / ( S + S )
 → ( x + y ) * S  S * S / ( S + S )
 → ( x + y ) * x  S * y / ( S + S )
 → ( x + y ) * x  S * y / ( x + S )
 → ( x + y ) * x  z * y / ( x + S )
 → ( x + y ) * x  z * y / ( x + x )
Note that many choices were made underway as to which rewrite was going to be performed next. These choices look quite arbitrary. As a matter of fact, they are, in the sense that the string finally generated is always the same. For example, the second and third rewrites
 → S * S  S (by rule 6, applied to the leftmost S)
 → S * S  S / S (by rule 7, applied to the rightmost S)
could be done in the opposite order:
 → S  S / S (by rule 7, applied to the rightmost S)
 → S * S  S / S (by rule 6, applied to the leftmost S)
Also, many choices were made on which rule to apply to each selected
S
. Changing the choices made and not only the order they were made in usually affects which terminal string comes out at the end.Let's look at this in more detail. Consider the parse tree of this derivation:
S  /\ S  S / \ /\ /\ S * S S / S /   \ /\ x /\ /\ ( S ) S * S ( S ) /   \ /\ z y /\ S + S S + S     x y x x
Starting at the top, step by step, an S in the tree is expanded, until no more unexpanded
S
es (nonterminals) remain. Picking a different order of expansion will produce a different derivation, but the same parse tree. The parse tree will only change if we pick a different rule to apply at some position in the tree.But can a different parse tree still produce the same terminal string, which is
( x + y ) * x  z * y / ( x + x )
in this case? Yes, for this particular grammar, this is possible. Grammars with this property are called ambiguous.For example,
x + y * z
can be produced with these two different parse trees:S S   /\ /\ S * S S + S / \ / \ /\ z x /\ x + y y * z
However, the language described by this grammar is not inherently ambiguous: an alternative, unambiguous grammar can be given for the language, for example:
 T → x
 T → y
 T → z
 S → S + T
 S → S  T
 S → S * T
 S → S / T
 T → ( S )
 S → T
(once again picking
S
as the start symbol).Further examples
Example 1
A contextfree grammar for the language consisting of all strings over {a,b} containing an unequal number of a's and b's:
 S → U  V
 U → TaU  TaT
 V → TbV  TbT
 T → aTbT  bTaT  ε
Here, the nonterminal T can generate all strings with the same number of a's as b's, the nonterminal U generates all strings with more a's than b's and the nonterminal V generates all strings with fewer a's than b's.
Example 2
Another example of a nonregular language is . It is contextfree as it can be generated by the following contextfree grammar:
 S → bSbb  A
 A → aA  ε
Other examples
The formation rules for the terms and formulas of formal logic fit the definition of contextfree grammar, except that the set of symbols may be infinite and there may be more than one start symbol.
Contextfree grammars are not limited in application to mathematical ("formal") languages. For example, it has been suggested that a class of Tamil poetry called Venpa is described by a contextfree grammar.^{[2]}
Derivations and syntax trees
A derivation of a string for a grammar is a sequence of grammar rule applications, that transforms the start symbol into the string. A derivation proves that the string belongs to the grammar's language.
A derivation is fully determined by giving, for each step:
 the rule applied in that step
 the occurrence of its right hand side to which it is applied
For clarity, the intermediate string is usually given as well.
For instance, with the grammar:
(1) S → S + S (2) S → 1 (3) S → a
the string
1 + 1 + a
can be derived with the derivation:
S → (rule 1 on first S) S+S → (rule 1 on second S) S+S+S → (rule 2 on second S) S+1+S → (rule 3 on third S) S+1+a → (rule 2 on first S) 1+1+a
Often, a strategy is followed that deterministically determines the next nonterminal to rewrite:
 in a leftmost derivation, it is always the leftmost nonterminal;
 in a rightmost derivation, it is always the rightmost nonterminal.
Given such a strategy, a derivation is completely determined by the sequence of rules applied. For instance, the leftmost derivation
S → (rule 1 on first S) S+S → (rule 2 on first S) 1+S → (rule 1 on first S) 1+S+S → (rule 2 on first S) 1+1+S → (rule 3 on first S) 1+1+a
can be summarized as
rule 1, rule 2, rule 1, rule 2, rule 3
The distinction between leftmost derivation and rightmost derivation is important because in most parsers the transformation of the input is defined by giving a piece of code for every grammar rule that is executed whenever the rule is applied. Therefore it is important to know whether the parser determines a leftmost or a rightmost derivation because this determines the order in which the pieces of code will be executed. See for an example LL parsers and LR parsers.
A derivation also imposes in some sense a hierarchical structure on the string that is derived. For example, if the string "1 + 1 + a" is derived according to the leftmost derivation:
 S → S + S (1)
 → 1 + S (2)
 → 1 + S + S (1)
 → 1 + 1 + S (2)
 → 1 + 1 + a (3)
the structure of the string would be:
 { { 1 }_{S} + { { 1 }_{S} + { a }_{S} }_{S} }_{S}
where { ... }_{S} indicates a substring recognized as belonging to S. This hierarchy can also be seen as a tree:
S /\ /  \ /  \ S '+' S  /\  /  \ '1' S '+' S   '1' 'a'
This tree is called a concrete syntax tree (see also abstract syntax tree) of the string. In this case the presented leftmost and the rightmost derivations define the same syntax tree; however, there is another (rightmost) derivation of the same string
 S → S + S (1)
 → S + a (3)
 → S + S + a (1)
 → S + 1 + a (2)
 → 1 + 1 + a (2)
and this defines the following syntax tree:
S /\ /  \ /  \ S '+' S /\  /  \  S '+' S 'a'   '1' '1'
If, for certain strings in the language of the grammar, there is more than one parsing tree, then the grammar is said to be an ambiguous grammar. Such grammars are usually hard to parse because the parser cannot always decide which grammar rule it has to apply. Usually, ambiguity is a feature of the grammar, not the language, and an unambiguous grammar can be found that generates the same contextfree language. However, there are certain languages that can only be generated by ambiguous grammars; such languages are called inherently ambiguous.
Normal forms
Every contextfree grammar that does not generate the empty string can be transformed into one in which no rule has the empty string as a product [a rule with ε as a product is called an εproduction]. If it does generate the empty string, it will be necessary to include the rule , but there need be no other εrule. Every contextfree grammar with no εproduction has an equivalent grammar in Chomsky normal form or Greibach normal form. "Equivalent" here means that the two grammars generate the same language.
Because of the especially simple form of production rules in Chomsky Normal Form grammars, this normal form has both theoretical and practical implications. For instance, given a contextfree grammar, one can use the Chomsky Normal Form to construct a polynomialtime algorithm that decides whether a given string is in the language represented by that grammar or not (the CYK algorithm).
Undecidable problems
Some questions that are undecidable for wider classes of grammars become decidable for contextfree grammars; e.g. the emptiness problem (whether the grammar generates any terminal strings at all), is undecidable for contextsensitive grammars, but decidable for contextfree grammars.
Still, many problems remain undecidable. Examples:
Universality
Given a CFG, does it generate the language of all strings over the alphabet of terminal symbols used in its rules?
A reduction can be demonstrated to this problem from the wellknown undecidable problem of determining whether a Turing machine accepts a particular input (the Halting problem). The reduction uses the concept of a computation history, a string describing an entire computation of a Turing machine. We can construct a CFG that generates all strings that are not accepting computation histories for a particular Turing machine on a particular input, and thus it will accept all strings only, if the machine doesn't accept that input.
Language equality
Given two CFGs, do they generate the same language?
The undecidability of this problem is a direct consequence of the previous: we cannot even decide whether a CFG is equivalent to the trivial CFG defining the language of all strings.
Language inclusion
Given two CFGs, can the first generate all strings that the second can generate?
If this problem is decidable, then we could use it to determine whether two CFGs G1 and G2 generate the same language by checking whether L(G1) is a subset of L(G2) and L(G2) is a subset of L(G1).
Being in a lower level of the Chomsky hierarchy
Given a contextsensitive grammar, does it describe a contextfree language? Given a contextfree grammar, does it describe a regular language?
Each of these problems is undecidable.
Extensions
An obvious way to extend the contextfree grammar formalism is to allow nonterminals to have arguments, the values of which are passed along within the rules. This allows natural language features such as agreement and reference, and programming language analogs such as the correct use and definition of identifiers, to be expressed in a natural way. E.g. we can now easily express that in English sentences, the subject and verb must agree in number.
In computer science, examples of this approach include affix grammars, attribute grammars, indexed grammars, and Van Wijngaarden twolevel grammars.
Similar extensions exist in linguistics.
Another extension is to allow additional terminal symbols to appear at the left hand side of rules, constraining their application. This produces the formalism of contextsensitive grammars.
Restrictions
There are a number of important subclasses of the contextfree grammars:
 LR(k) grammars (also known as deterministic contextfree grammars) allow parsing (string recognition) with deterministic pushdown automata, but they can only describe deterministic contextfree languages.
 Simple LR, LookAhead LR grammars are subclasses that allow further simplification of parsing.
 LL(k) and LL(*) grammars allow parsing by direct construction of a leftmost derivation as described above, and describe even fewer languages.
 Simple grammars are a subclass of the LL(1) grammars mostly interesting for its theoretical property that language equality of simple grammars is decidable, while language inclusion is not.
 Bracketed grammars have the property that the terminal symbols are divided into left and right bracket pairs that always match up in rules.
 Linear grammars have no rules with more than one nonterminal in the right hand side.
 Regular grammars are a subclass of the linear grammars and describe the regular languages, i.e. they correspond to finite automata and regular expressions.
LR parsing extends LL parsing to support a larger range of grammars; in turn, generalized LR parsing extends LR parsing to support arbitrary contextfree grammars. On LL grammars and LR grammars, it essentially performs LL parsing and LR parsing, respectively, while on nondeterministic grammars, it is as efficient as can be expected. Although GLR parsing was developed in the 1980s, many new language definitions and parser generators continue to be based on LL, LALR or LR parsing up to the present day.
Linguistic applications
Chomsky initially hoped to overcome the limitations of contextfree grammars by adding transformation rules.^{[1]}
Such rules are another standard device in traditional linguistics; e.g. passivization in English. Much of generative grammar has been devoted to finding ways of refining the descriptive mechanisms of phrasestructure grammar and transformation rules such that exactly the kinds of things can be expressed that natural language actually allows. Allowing arbitrary transformations doesn't meet that goal: they are much too powerful, being Turing complete unless significant restrictions are added (e.g. no transformations that introduce and then rewrite symbols in a contextfree fashion).
Chomsky's general position regarding the noncontextfreeness of natural language has held up since then,^{[3]} although his specific examples regarding the inadequacy of contextfree grammars (CFGs) in terms of their weak generative capacity were later disproved.^{[4]} Gerald Gazdar and Geoffrey Pullum have argued that despite a few noncontextfree constructions in natural language (such as crossserial dependencies in Swiss German^{[3]} and reduplication in Bambara^{[5]}), the vast majority of forms in natural language are indeed contextfree.^{[4]}
See also
 Contextsensitive grammar
 Formal grammar
 Parsing
 Parsing expression grammar
 Stochastic contextfree grammar
 Algorithms for contextfree grammar generation
Algorithms
 CYK algorithm
 GLR parser
 Earley algorithm
Notes
 ^ ^{a} ^{b} Chomsky, Noam (Sep 1956). "Three models for the description of language". Information Theory, IEEE Transactions 2 (3): 113–124. doi:10.1109/TIT.1956.1056813. http://ieeexplore.ieee.org/iel5/18/22738/01056813.pdf?isnumber=22738&prod=STD&arnumber=1056813&arnumber=1056813&arSt=+113&ared=+124&arAuthor=+Chomsky%2C+N.. Retrieved 20070618.
 ^ L, BalaSundaraRaman; Ishwar.S, Sanjeeth Kumar Ravindranath (20030822). "Context Free Grammar for Natural Language Constructs  An implementation for Venpa Class of Tamil Poetry". Proceedings of Tamil Internet, Chennai, 2003. International Forum for Information Technology in Tamil. pp. 128–136. http://citeseer.ist.psu.edu/balasundararaman03context.html. Retrieved 20060824.
 ^ ^{a} ^{b} Shieber, Stuart (1985). "Evidence against the contextfreeness of natural language". Linguistics and Philosophy 8 (3): 333–343. doi:10.1007/BF00630917. http://www.eecs.harvard.edu/~shieber/Biblio/Papers/shieber85.pdf.
 ^ ^{a} ^{b} Pullum, Geoffrey K.; Gerald Gazdar (1982). "Natural languages and contextfree languages". Linguistics and Philosophy 4 (4): 471–504. doi:10.1007/BF00360802.
 ^ Culy, Christopher (1985). "The Complexity of the Vocabulary of Bambara". Linguistics and Philosophy 8 (3): 345–351. doi:10.1007/BF00630918.
References
 Chomsky, Noam (Sept. 1956). "Three models for the description of language". Information Theory, IEEE Transactions 2 (3).
 Chomsky, Noam (1957), Syntactic Structures, Den Haag: Mouton.
 Chomsky, Noam (1965), Aspects of the Theory of Syntax, Cambridge (Mass.): MIT Press.
 Chomsky, Noam (1981), Lectures on Government and Binding, Dordrecht: Foris.
 Gazdar, Gerald; Klein, Ewan; Pullum, Geoffrey & Sag, Ivan (1985), Generalized Phrase Structure Grammar, Cambridge (Mass.): Harvard University Press.
Further reading
 Michael Sipser (1997). Introduction to the Theory of Computation. PWS Publishing. ISBN 053494728X. Section 2.1: ContextFree Grammars, pp. 91–101. Section 4.1.2: Decidable problems concerning contextfree languages, pp. 156–159. Section 5.1.1: Reductions via computation histories: pp. 176–183.
Automata theory: formal languages and formal grammars Chomsky hierarchy Type0—Type1———Type2——Type3—Grammars (no common name)Linear contextfree rewriting systems etc.Treeadjoining etc.Contextfree—Languages Minimal automaton Thread automataEach category of languages is a proper subset of the category directly above it.  Any automaton and any grammar in each category has an equivalent automaton or grammar in the category directly above it.Categories: 1956 in computer science
 Compiler construction
 Formal languages
 Programming language topics
 Wikipedia articles with ASCII art
Wikimedia Foundation. 2010.