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] ")"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…