简体   繁体   中英

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.

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, 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:

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

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

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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