I'm not really very clear on the concept of ambiguity in context free grammars. If anybody could help me out and explain the concept or provide a good resource I'd greatly appreciate it.
T * U;
Is that a pointer declaration or a multiplication? You can't tell until you know what T
and U
actually are.
So the syntax of the expression depends on the semantics (meaning) of the expression. That's not context-free -- in a context-free language, that could only be one thing, not two. (This is why they didn't let expressions like that be valid statements in D.)
Another example:
T<U> V;
Is that a template usage or is that a greater-than and less-than operation? (This is why they changed the syntax to T!(U) V
in D -- parentheses only have one use, whereas carets have another use.)
2 * 3;
would not be valid in the grammar. Not all ambiguities can be resolved like this, though. –
Conn How would you parse this:
if condition_1 then if condition_2 then action_1 else action_2
To which "if" does the "else" belong?
In Python, they are:
if condition_1:
if condition_2:
action_1
else:
action_2
and:
if condition_1:
if condition_2:
action_1
else:
action_2
if
that the else
matches doesn't have to do anything with the actual conditions or actions that are happening, it only has to do with the source code formatting, and/or brace matching. It's a little different from where the result would be different based on what condition_1
actually was. –
Conn Consider an input string recognized by context-free grammar. The string is derived ambiguously if it has two or more different leftmost derivations, or parse trees of you wish. A grammar is ambiguous if it generates strings ambiguously. For example, the grammar S -> E + E | E * E is an ambiguous grammar as it derives the string x + x * x ambiguously, in other words there are more than one parse tree to represent the expression (there are two actually). The grammar can be made non-ambiguous by changing the grammar to:
E -> E + T | T
T -> T * F | F
F -> (E) | x
The refactored grammar will always derive the string unambiguously, i.e. the derivation will always produce the same parse tree.
© 2022 - 2024 — McMap. All rights reserved.