Введение
Тип формальной грамматики
In formal language theory, a context free grammar (CFG) is a formal grammar whose production rules
can be applied to a nonterminal symbol regardless of its context. In particular, in a context free grammar, each production rule is of the form
with a single nonterminal symbol, and a string of terminals and/or nonterminals ( can be empty). Regardless of which symbols surround it, the single nonterminal on the left hand side can always be replaced by on the right hand side. This distinguishes it from a context sensitive grammar, which can have production rules in the form with a nonterminal symbol and , , and strings of terminal and/or nonterminal symbols. 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 ("start symbol"). Nonterminal symbols are used during the derivation process, but do not appear in its final result string. Languages generated by context free grammars are known as context free languages (CFL). Different context free grammars can generate the same context free language. It is important to distinguish the properties of the language (intrinsic properties) from the properties of a particular grammar (extrinsic properties). The language equality question (do two given context free grammars generate the same language?) 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 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 (XML) 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.
В теории формальных языков, контекстно-свободная грамматика (CFG) — это формальная грамматика, правила которой могут применяться к нетерминальному символу независимо от его контекста. В частности, в контекстно-свободной грамматике каждое правило вывода имеет форму
In formal language theory, a context free grammar (CFG) is a formal grammar whose production rules
can be applied to a nonterminal symbol regardless of its context. In particular, in a context free grammar, each production rule is of the form
with a single nonterminal symbol, and a string of terminals and/or nonterminals ( can be empty). Regardless of which symbols surround it, the single nonterminal on the left hand side can always be replaced by on the right hand side. This distinguishes it from a context sensitive grammar, which can have production rules in the form with a nonterminal symbol and , , and strings of terminal and/or nonterminal symbols. 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 ("start symbol"). Nonterminal symbols are used during the derivation process, but do not appear in its final result string. Languages generated by context free grammars are known as context free languages (CFL). Different context free grammars can generate the same context free language. It is important to distinguish the properties of the language (intrinsic properties) from the properties of a particular grammar (extrinsic properties). The language equality question (do two given context free grammars generate the same language?) 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 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 (XML) 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.
с одним нетерминальным символом и строкой терминалов и/или нетерминалов (строка может быть пустой). Независимо от окружающих символов, единственный нетерминал в левой части всегда может быть заменен на строку в правой части. Это отличает её от контекстно-зависимой грамматики, которая может иметь правила вывода в форме
In formal language theory, a context free grammar (CFG) is a formal grammar whose production rules
can be applied to a nonterminal symbol regardless of its context. In particular, in a context free grammar, each production rule is of the form
with a single nonterminal symbol, and a string of terminals and/or nonterminals ( can be empty). Regardless of which symbols surround it, the single nonterminal on the left hand side can always be replaced by on the right hand side. This distinguishes it from a context sensitive grammar, which can have production rules in the form with a nonterminal symbol and , , and strings of terminal and/or nonterminal symbols. 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 ("start symbol"). Nonterminal symbols are used during the derivation process, but do not appear in its final result string. Languages generated by context free grammars are known as context free languages (CFL). Different context free grammars can generate the same context free language. It is important to distinguish the properties of the language (intrinsic properties) from the properties of a particular grammar (extrinsic properties). The language equality question (do two given context free grammars generate the same language?) 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 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 (XML) 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.
с нетерминальным символом и , , и строками терминальных и/или нетерминальных символов. Формальная грамматика по сути представляет собой набор правил вывода, описывающих все возможные строки в заданном формальном языке. Правила вывода — это простые замены. Например, первое правило на рисунке заменяет
In formal language theory, a context free grammar (CFG) is a formal grammar whose production rules
can be applied to a nonterminal symbol regardless of its context. In particular, in a context free grammar, each production rule is of the form
with a single nonterminal symbol, and a string of terminals and/or nonterminals ( can be empty). Regardless of which symbols surround it, the single nonterminal on the left hand side can always be replaced by on the right hand side. This distinguishes it from a context sensitive grammar, which can have production rules in the form with a nonterminal symbol and , , and strings of terminal and/or nonterminal symbols. 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 ("start symbol"). Nonterminal symbols are used during the derivation process, but do not appear in its final result string. Languages generated by context free grammars are known as context free languages (CFL). Different context free grammars can generate the same context free language. It is important to distinguish the properties of the language (intrinsic properties) from the properties of a particular grammar (extrinsic properties). The language equality question (do two given context free grammars generate the same language?) 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 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 (XML) 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.
на . Для данного нетерминального символа может существовать несколько правил замены. Язык, генерируемый грамматикой, — это множество всех строк терминальных символов, которые могут быть получены путем многократного применения правил из некоторого конкретного нетерминального символа ("начальный символ"). Нетерминальные символы используются в процессе вывода, но не появляются в конечной результирующей строке. Языки, генерируемые контекстно-свободными грамматиками, называются контекстно-свободными языками (CFL). Различные контекстно-свободные грамматики могут генерировать один и тот же контекстно-свободный язык. Важно различать свойства языка (внутренние свойства) и свойства конкретной грамматики (внешние свойства). Вопрос об эквивалентности языков (генерируют ли две данные контекстно-свободные грамматики один и тот же язык?) является неразрешимым. Контекстно-свободные грамматики используются в лингвистике для описания структуры предложений и слов в естественном языке и были изобретены лингвистом Ноамом Хомским для этой цели. В отличие от этого, в информатике, с увеличением использования рекурсивно определенных понятий, они стали применяться все чаще. В одном из ранних применений грамматики используются для описания структуры языков программирования. В более позднем применении они используются в важной части языка расширяемой разметки (XML), называемой определением типа документа. В лингвистике некоторые авторы используют термин "грамматика фразовой структуры" для обозначения контекстно-свободных грамматик, при этом грамматика фразовой структуры отличается от грамматики зависимостей. В информатике популярной нотацией для контекстно-свободных грамматик является форма Бэкуса — Наура, или BNF.
In formal language theory, a context free grammar (CFG) is a formal grammar whose production rules
can be applied to a nonterminal symbol regardless of its context. In particular, in a context free grammar, each production rule is of the form
with a single nonterminal symbol, and a string of terminals and/or nonterminals ( can be empty). Regardless of which symbols surround it, the single nonterminal on the left hand side can always be replaced by on the right hand side. This distinguishes it from a context sensitive grammar, which can have production rules in the form with a nonterminal symbol and , , and strings of terminal and/or nonterminal symbols. 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 ("start symbol"). Nonterminal symbols are used during the derivation process, but do not appear in its final result string. Languages generated by context free grammars are known as context free languages (CFL). Different context free grammars can generate the same context free language. It is important to distinguish the properties of the language (intrinsic properties) from the properties of a particular grammar (extrinsic properties). The language equality question (do two given context free grammars generate the same language?) 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 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 (XML) 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.
Применение нормы
Для любой строки u, мы говорим, что u напрямую порождает v, что записывается как u → v, если существуют строки w и x такие, что u = wx и v = x. Таким образом, v является результатом применения правила замены к u.
Повторное применение правила
Для любой строки мы говорим, что u порождает v или v выводится из u, если существует положительное целое число k и строки w₁, w₂, ..., wₖ такие, что u → w₁ → w₂ → ... → wₖ → v. Это отношение обозначается u ⇒ v, или u ⊢ v в некоторых учебниках. Если u ⇒ v, то отношение выводимости выполняется. Иными словами, u ⇒* v и u ⊢⁺ v являются рефлексивным транзитивным замыканием (допускающим, что строка порождает саму себя) и транзитивным замыканием (требующим как минимум одного шага) отношения u ⇒, соответственно.
Второй блок b's двойного размера
Еще один пример нерегулярного языка — это контекстно-свободный язык, поскольку он может быть сгенерирован следующей контекстно-свободной грамматикой:
Логические формулы первого порядка
Правила формирования терминов и формул формальной логики соответствуют определению контекстно-свободной грамматики, за исключением того, что множество символов может быть бесконечным и может существовать более одного начального символа.
Нормальные формы
Каждая контекстно-свободная грамматика, не содержащая ε-продукций, имеет эквивалентную грамматику в нормальной форме Чомского и грамматику в нормальной форме Грейбаха. Под "эквивалентностью" здесь понимается, что обе грамматики порождают один и тот же язык. Особенно простая форма правил вывода в грамматиках нормальной формы Чомского имеет как теоретическое, так и практическое значение. Например, для заданной контекстно-свободной грамматики можно использовать нормальную форму Чомского для построения алгоритма, работающего за полиномиальное время, который определяет, принадлежит ли заданная строка языку, определяемому этой грамматикой, или нет (алгоритм CYK).
Решаемые проблемы
Ниже приведены некоторые разрешимые задачи для контекстно-свободных грамматик.
Проверки регулярности и ПД
Можно определить, является ли заданная грамматика регулярной грамматикой, а также является ли она LL(k)-грамматикой для заданного k ≥ 0. Если k не задано, последняя задача неразрешима, равно как и вопрос о том, является ли язык LL(k)-языком для заданного k.
Нерешимые проблемы
Некоторые вопросы, неразрешимые для более широких классов грамматик, становятся разрешимыми для контекстно-свободных грамматик; например, проблема пустоты (порождает ли грамматика хотя бы одну терминальную цепочку), неразрешима для контекстно-зависимых грамматик, но разрешима для контекстно-свободных грамматик. Однако многие проблемы остаются неразрешимыми даже для контекстно-свободных грамматик; наиболее важные из них рассматриваются ниже.
Расширения
Очевидный способ расширить формализм контекстно-свободных грамматик — это разрешить нетерминалам иметь аргументы, значения которых передаются внутри правил. Это позволяет естественным образом выражать такие особенности естественного языка, как согласование и референция, а также аналогичные конструкции в языках программирования, например, правильное использование и определение идентификаторов. Например, теперь мы можем легко выразить, что в английских предложениях подлежащее и сказуемое должны согласовываться в числе. В информатике к этому подходу относятся аффиксные грамматики, атрибутные грамматики, индексированные грамматики и двухуровневые грамматики Ван Вийнгардена. Схожие расширения существуют и в лингвистике. Расширенная контекстно-свободная грамматика (или грамматика с регулярной правой частью) — это грамматика, в которой правая часть правил вывода может быть регулярным выражением над терминалами и нетерминалами данной грамматики. Расширенные контекстно-свободные грамматики точно описывают контекстно-свободные языки. Другое расширение заключается в разрешении дополнительных терминальных символов появляться в левой части правил, ограничивая тем самым область их применения. Это приводит к формализму контекстно-зависимых грамматик.
Языковые приложения
Чомский изначально надеялся преодолеть ограничения контекстно-свободных грамматик, добавив правила преобразований. Хотя его конкретные примеры, касающиеся недостаточности контекстно-свободных грамматик в отношении их слабой порождающей способности, были впоследствии опровергнуты. Джеральд Газдар и Джеффри Пуллум утверждают, что, несмотря на наличие нескольких неконтекстно-свободных конструкций в естественном языке (таких как перекрестные последовательные зависимости в швейцарском немецком), подавляющее большинство форм в естественном языке действительно контекстно-свободны.