Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

theory - 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.

question from:https://stackoverflow.com/questions/65895540/is-this-context-free-grammar-unambiguous

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. 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.

This grammar could be written in the ABNF standard syntax like this:

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, i.e. 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:

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

Or with a one-liner with its automata under it:

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...