grammar - CFG : Why is this grammar ambiguous?

标签 grammar context-free-grammar context-free-language ambiguous-grammar

语法如下。

S -> SS' | a | b
S' -> a | b

按照我的理解,该语法的派生将类似于 SS'S'S'S'...(0 个或多个 S'),其中每个 S S' 将生成 ab

有人可以提供一个例子来证明这个语法是不明确的吗? (解决方案说是这样。)

最佳答案

这并不含糊。你的分析是正确的。

这是对语法的机械检查(针对我们的工具进行了重新调整):

S = S Sprime ;
S = a ;
S = b ;
Sprime = a ;
Sprime = b ;

工具的执行:

C:\DMS\Domains\DMSStringGrammar\Tools\ParserGenerator>run ParserGenerator.P0B -interactive C:\
DMS GLR Parser Generator 2.4.1
Copyright (C) 1997-2018 Semantic Designs, Inc.
Opening C:\temp\Example.bnf
*** EOF seen
<<<Rule Collection Completed>>>
NTokens = 5 NRules = 5
LR(1) Parser Generator -- Find Follow and SLR Lookahead sets
Computing MemberSets for Nonterminal Tokens...

What next? ambiguities 100
Print results where (<CR> defaults to console)?
Default paper width: 80
How wide should the printout be (<CR> selects default)?
*** Search for ambiguities to depth 100

Nonterminal < Sprime > is not ambiguous
*** Search for ambiguities to depth 1; trying 2 rule pairs...
*** Search for ambiguities to depth 2; trying 2 rule pairs...
*** Search for ambiguities to depth 3; trying 2 rule pairs...
*** Search for ambiguities to depth 4; trying 2 rule pairs...
Nonterminal < S > is not ambiguous [modulo rule derivation loops]

*** 0 ambiguities found ***
*** All ambiguities in grammar detected ***

这个工具对于带有两个非终结符的语法来说有点过分了。但是,当有人给出一组 200 个非终结符时,手动完成就困难得多。

(对于理论家来说:这个工具显然无法决定所有语法。 它在非终结扩展空间中使用递归迭代加深搜索来查找重复/不明确的扩展。这在实践中效果很好)。

关于grammar - CFG : Why is this grammar ambiguous?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58647971/

相关文章:

java - ANTLR v4 的 mysql 语法文件中的语法错误

java - ANTLR:如何解释这种识别 Java 代码后缀的语法的行为?

parsing - 语法左因式分解

parsing - LALR解析器生成器实现问题

parsing - LL(1) S → a | 的解析表巴| C

parsing - 扩展的巴科斯诺尔形式 (EBNF) 能否描述一组无序的值?

parsing - 字符串常量导致 xtext 中出现意外的类型冲突

objective-c - Objective-C 中的保留关键字?

grammar - 确定是否可以在 CFG 中模糊地派生字符串

regular-language - Chomsky type 3 和 Chomsky type 2 语法的区别