Context-free grammar
In formal language theory, a context-free grammar is a formal grammar in which every production rule is of the form
where is a single nonterminal symbol, and is a string of terminals and/or nonterminals. A formal grammar is considered "context free" when its production rules can be applied regardless of the context of a nonterminal. No matter which symbols surround it, the single nonterminal on the left hand side can always be replaced by the right hand side. This is what distinguishes it from a context-sensitive grammar.
A formal grammar is essentially a set of production rules that describe all possible strings in a given formal language. Production rules are simple replacements. For example, the first rule in the picture,
replaces with. There can be multiple replacement rules for a given nonterminal symbol. The language generated by a grammar is the set of all strings of terminal symbols that can be derived, by repeated rule applications, from some particular nonterminal symbol.
Nonterminal symbols are used during the derivation process, but may not appear in its final result string.
Languages generated by context-free grammars are known as context-free languages. Different context-free grammars can generate the same context-free language. It is important to distinguish the properties of the language from the properties of a particular grammar. The [|language equality] question is undecidable.
Context-free grammars arise in linguistics where they are used to describe the structure of sentences and words in a natural language, and they were in fact invented by the linguist Noam Chomsky for this purpose. By contrast, in computer science, as the use of recursively-defined concepts increased, they were used more and more. In an early application, grammars are used to describe the structure of programming languages. In a newer application, they are used in an essential part of the Extensible Markup Language called the Document Type Definition.
In linguistics, some authors use the term phrase structure grammar to refer to context-free grammars, whereby phrase-structure grammars are distinct from dependency grammars. In computer science, a popular notation for context-free grammars is Backus–Naur form, or BNF.
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:can be logically parenthesized as follows:
A context-free 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 context-free 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.
Context-free grammars are a special form of Semi-Thue systems that in their general form date back to the work of Axel Thue.
The formalism of context-free grammars was developed in the mid-1950s by Noam Chomsky, and also their classification as a special type of formal grammar. What Chomsky called a phrase structure grammar is also known now as a constituency grammar, whereby constituency grammars stand in contrast to dependency grammars. In Chomsky's generative grammar framework, the syntax of natural language was described by context-free rules combined with transformation rules.
Block structure was introduced into computer programming languages by the Algol project, which, as a consequence, also featured a context-free 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 Backus–Naur form, after two members of the Algol language design committee. The "block structure" aspect that context-free grammars capture is so fundamental to grammar that the terms syntax and grammar are often identified with context-free 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.
Context-free grammars are simple enough to allow the construction of efficient parsing algorithms that, 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 context-free grammars.
Formal definitions
A context-free grammar is defined by the 4-tuple,where
- 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 sub-language of the language defined by.
- 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.
- is a finite relation from to, where the asterisk represents the Kleene star operation. The members of are called the rules or productions of the grammar.
- is the start variable, used to represent the whole sentence. It must be an element of.
Production rule notation
It is allowed for to be the empty string, and in this case it is customary to denote it by ε. The form is called an -production.
It is common to list all right-hand sides for the same left-hand side on the same line, using | to separate them. Rules and can hence be written as. In this case, and is called the first and second alternative, respectively.
Rule application
For any strings, we say directly yields, written as, if with and such that and. Thus, is a result of applying the rule to.Repetitive rule application
For any strings we say yields or is derived from if there is a positive integer and strings such that. This relation is denoted, or in some textbooks. If, the relation holds. In other words, and are the reflexive transitive closure and the transitive closure of, respectively.Context-free language
The language of a grammar is the setof all terminal-symbol strings derivable from the start symbol.
A language is said to be a context-free language, if there exists a CFG, such that.
Non-deterministic pushdown automata recognize exactly the context-free languages.
Examples
Words concatenated with their reverse
The grammar, with productionsis context-free. It is not proper since it includes an ε-production. A typical derivation in this grammar is
This makes it clear that
.
The language is context-free, however, it can be proved that it is not regular.
If the productions
are added, a context-free grammar for the set of all palindromes over the alphabet is obtained.
Well-formed 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 one nonterminal symbol S. The production rules areThe first rule allows the S symbol to multiply; the second rule allows the S symbol to become enclosed by matching parentheses; and the third rule terminates the recursion.
Well-formed nested parentheses and square brackets
A second canonical example is two different kinds of matching nested parentheses, described by the productions:with terminal symbols and nonterminal S.
The following sequence can be derived in that grammar:
Matching pairs
In a context-free grammar, we can pair up characters the way we do with brackets. The simplest example:This grammar generates the language, which is not regular.
The special character ε stands for the empty string. By changing the above grammar to
we obtain a grammar generating the language instead. This differs only in that it contains the empty string while the original grammar did not.
Distinct number of a's and b's
A context-free grammar for the language consisting of all strings over containing an unequal number of a's and b's: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. Omitting the third alternative in the rule for U and V doesn't restrict the grammar's language.
Second block of b's of double size
Another example of a non-regular language is. It is context-free as it can be generated by the following context-free grammar:First-order logic formulas
The formation rules for the terms and formulas of formal logic fit the definition of context-free grammar, except that the set of symbols may be infinite and there may be more than one start symbol.Examples of languages that are not context free
In contrast to well-formed nested parentheses and square brackets in the previous section, there is no context-free grammar for generating all sequences of two different types of parentheses, each separately balanced disregarding the other, where the two types need not nest inside one another, for example:or
The fact that this language is not context free can be proven using Pumping lemma for context-free languages and a proof by contradiction, observing that all words of the form
should belong to the language. This language belongs instead to a more general class and can be described by a conjunctive grammar, which in turn also includes other non-context-free languages, such as the language of all words of the form
Regular grammars
Every regular grammar is context-free, but not all context-free grammars are regular. The following context-free grammar, however, is also regular.The terminals here are and, while the only nonterminal is.
The language described is all nonempty strings of s and s that end in.
This grammar is regular: no rule has more than one nonterminal in its right-hand side, and each of these nonterminals is at the same end of the right-hand side.
Every regular grammar corresponds directly to a nondeterministic finite automaton, so we know that this is a regular language.
Using pipe symbols, the grammar above can be described more tersely as follows:
Derivations and syntax trees
A derivation of a string for a grammar is a sequence of grammar rule applications that transform 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 left-hand side to which it is applied
For instance, with the grammar:
can be derived from the start symbol with the following derivation:
Often, a strategy is followed that deterministically chooses 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.
which can be summarized as
One rightmost derivation is:
which can be summarized as
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 outlined above, the structure of the string would be:
Example: Algebraic expressions
Here is a context-free grammar for syntactically correct infix algebraic expressions in the variables x, y and z:This grammar can, for example, generate the string
as follows:
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
could be done in the opposite order:
Also, many choices were made on which rule to apply to each selected.
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:
Starting at the top, step by step, an S in the tree is expanded, until no more unexpanded es 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 in this case?
Yes, for this particular grammar, this is possible.
Grammars with this property are called ambiguous.
For example, can be produced with these two different parse trees:
However, the language described by this grammar is not inherently ambiguous:
an alternative, unambiguous grammar can be given for the language, for example:
once again picking as the start symbol. This alternative grammar will produce with a parse tree similar to the left one above, i.e. implicitly assuming the association, which is does not follow standard order of operations. More elaborate, unambiguous and context-free grammars can be constructed that produce parse trees that obey all desired operator precedence and associativity rules.
Normal forms
Every context-free grammar with no ε-production has an equivalent grammar in Chomsky normal form, and a grammar in Greibach normal form. "Equivalent" here means that the two grammars generate the same language.The especially simple form of production rules in Chomsky normal form grammars has both theoretical and practical implications. For instance, given a context-free grammar, one can use the Chomsky normal form to construct a polynomial-time algorithm that decides whether a given string is in the language represented by that grammar or not.
Closure properties
Context-free languages are closed under the various operations, that is, if the languages K and L arecontext-free, so is the result of the following operations:
- union K ∪ L; concatenation K ∘ L; Kleene star L*
- substitution
- inverse homomorphism
- intersection with a regular language
Decidable problems
The following are some decidable problems about context-free grammars.Parsing
The parsing problem, checking whether a given word belongs to the language given by a context-free grammar, is decidable, using one of the general-purpose parsing algorithms:- CYK algorithm
- Earley parser
- GLR parser
- LL parser
Reachability, productiveness, nullability
A nonterminal symbol is called productive, or generating, if there is a derivation for some string of terminal symbols. is called reachable if there is a derivation for some strings of non-terminal and terminal symbols from the start symbol. is called useless if it is unreachable or unproductive. is called nullable if there is a derivation. A rule is called an ε-production. A derivation is called a cycle.Algorithms are known to eliminate from a given grammar, without changing its generated language,
- unproductive symbols,
- unreachable symbols,
- ε-productions, with one possible exception, and
- cycles.
Such rules and alternatives are called useless.
In the depicted example grammar, the nonterminal D is unreachable, and E is unproductive, while C → C causes a cycle.
Hence, omitting the last three rules doesn't change the language generated by the grammar, nor does omitting the alternatives "| Cc | Ee" from the right-hand side of the rule for S.
A context-free grammar is said to be proper if it has neither useless symbols nor ε-productions nor cycles.
Combining the above algorithms, every context-free grammar not generating ε can be transformed into a weakly equivalent proper one.
Regularity and LL(''k'') checks
It is decidable whether a given grammar is a regular grammar, as well as whether it is an LL grammar for a given k≥0. If k is not given, the latter problem is undecidable.Given a context-free language, it is neither decidable whether it is regular, nor whether it is an LL language for a given k.
Emptiness and finiteness
There are algorithms to decide whether a language of a given context-free language is empty, as well as whether it is finite.Undecidable problems
Some questions that are undecidable for wider classes of grammars become decidable for context-free grammars; e.g. the emptiness problem, is undecidable for context-sensitive grammars, but decidable for context-free grammars.However, many problems are undecidable even for context-free grammars. Examples are:
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 well-known undecidable problem of determining whether a Turing machine accepts a particular input. The reduction uses the concept of a computation history, a string describing an entire computation of a Turing machine. A CFG can be constructed 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: it is impossible to 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 one generate all strings that the second one can generate?If this problem was decidable, then language equality could be decided too: two CFGs G1 and G2 generate the same language if L is a subset of L and L is a subset of L.
Being in a lower or higher level of the Chomsky hierarchy
Using Greibach's theorem, it can be shown that the two following problems are undecidable:- Given a context-sensitive grammar, does it describe a context-free language?
- Given a context-free grammar, does it describe a regular language?
Grammar ambiguity
The undecidability of this problem follows from the fact that if an algorithm to determine ambiguity existed, the Post correspondence problem could be decided, which is known to be undecidable.
Language disjointness
Given two CFGs, is there any string derivable from both grammars?If this problem was decidable, the undecidable Post correspondence problem could be decided, too: given strings over some alphabet, let the grammar consist of the rule
where denotes the reversed string and doesn't occur among the ; and let grammar consist of the rule
Then the Post problem given by has a solution if and only if and share a derivable string.
Extensions
An obvious way to extend the context-free 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 two-level grammars. Similar extensions exist in linguistics.An extended context-free grammar is one in which the right-hand side of the production rules is allowed to be a regular expression over the grammar's terminals and nonterminals. Extended context-free grammars describe exactly the context-free languages.
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 context-sensitive grammars.
Subclasses
There are a number of important subclasses of the context-free grammars:- LR grammars allow parsing with deterministic pushdown automata, but they can only describe deterministic context-free languages.
- Simple LR, Look-Ahead LR grammars are subclasses that allow further simplification of parsing. SLR and LALR are recognized using the same PDA as LR, but with simpler tables, in most cases.
- LL 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 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 on 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.
Linguistic applications
initially hoped to overcome the limitations of context-free grammars by adding transformation rules.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 phrase-structure grammar and transformation rules such that exactly the kinds of things can be expressed that natural language actually allows. Allowing arbitrary transformations does not meet that goal: they are much too powerful, being Turing complete unless significant restrictions are added.
Chomsky's general position regarding the non-context-freeness of natural language has held up since then, although his specific examples regarding the inadequacy of context-free grammars in terms of their weak generative capacity were later disproved.
Gerald Gazdar and Geoffrey Pullum have argued that despite a few non-context-free constructions in natural language, the vast majority of forms in natural language are indeed context-free.