简体   繁体   English

这种上下文无关的语法是明确的吗?

[英]Is this context-free grammar unambiguous?

I would like to know if the grammar I came up with is unambiguous.我想知道我想出的语法是否明确。

G(N, T, P, S)

N = {S, M}
T = {+, -, (, ), 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
P = {
S → 0, S → 1, … , S → 9
S → ( M )
M → S + S
M → S - S
M → S
}

S is the start variable, N is the set of nonterminal characters, T is the set of terminals and P is the set of productions. S 是起始变量,N 是非终结符集合,T 是终结符集合,P 是产生式集合。

This grammar is unambiguous, and it is also nondeterministic.这种语法是明确的,也是不确定的。 A grammar is ambiguous when there is more then one syntax tree, for at least one valid input string, and is deterministic, if for every valid input string, at any time during the parsing, there is at exactly one prediction to use.当对于至少一个有效的输入字符串存在多于一个语法树时,语法是不明确的,并且是确定性的,如果对于每个有效的输入字符串,在解析期间的任何时间,都只有一个要使用的预测。 For the invalid input strings, there will be a moment when there will be none predictions to use.对于无效的输入字符串,会有一段时间没有预测可以使用。

The predictions M → S + S , M → S - S and M → S make the grammar nondeterministic, because S is the first nonterminal symbol of each of them.预测M → S + SM → S - SM → S使文法具有不确定性,因为S是它们每个的第一个非终结符号。 However, this will not lead to more then one syntax tree for any input, after all of the input is parsed, because the terminal symbols after S are + , - (in M ) and ) after the nonterminal M in S → ( M ) will unanimously determine which prediction is valid.但是,在解析所有输入之后,这不会导致任何输入的多于一个语法树,因为S之后的终结符号是+- (在M中)和)S → ( M )中的非终结符M之后将一致确定哪个预测是有效的。

This grammar could be written in the ABNF standard syntax like this:该语法可以用 ABNF 标准语法编写,如下所示:

S = "0" / "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9" / "(" M ")"
M = S "+" S / S "-" S / S

After left refactoring, the grammar can become a deterministic one (that will not change the ambiguity, ie the grammar will still be unambiguous):左重构后,语法可以成为确定性语法(不会改变歧义,即语法仍然是明确的):

S = "0" / "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9" / "(" M ")"
M = S [("+" / "-") S]

And with the shorter ABNF range syntax:并且使用较短的 ABNF 范围语法:

S = %x30-39 / "(" M ")"
M = S [("+" / "-") S]

Or with a one-liner with its automata under it:或者使用带有自动机的单线:

S = %x30-39 / "(" S [("+" / "-") S] ")"

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM