0

I don't know if it is the right site to ask this. But we're studying about ambiguities of grammar. Including left most derivation and right most derivation. My practice problem is this:

E -> E * E | E + E | N
N -> 0N | 1N |
Output: 0110 + 110 * 01111

Is there a way to make it ambiguous? And any tips in making a grammar ambiguous?

Yodism
  • 227
  • 1
  • 5
  • 17

1 Answers1

1

Given your grammar, it is clearly ambiguous. Here, it doesn't define the preference between + and * operator.

As you said, if you have to parse this 0110 + 110 * 01111, it can be done using two ways :-

  1. 0110 + 110 * 01111 ----> (0110 + 110) * 01111

  2. 0110 + 110 * 01111 ----> 0110 + (110 * 01111)

So, this grammar is pretty ambiguous as it doesn't define operator precedence. Also, there is no provision of operator associativity.

It clearly depends on the production rules specified by the grammar to remove the ambiguity by specifying distinctions between conflicting cases. Some of the things while doing top-down parsing come to case are left factoring and left-recursion leading to ambiguous grammars.

You should see elimination of left recursion and other related tutorials as it'd be too broad to specify the rules.

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
  • Is using this grammar okay `E -> E * E | E + E | 0E | 1E` because i'm trying to make it in one line. Or it it possible to make it in one line? – Yodism Jan 18 '15 at 12:39
  • No, you need to disambiguate it using other non-terminal E' such that `E-> E';` and then try to resolve that. – Am_I_Helpful Jan 18 '15 at 12:42
  • So, it's not possible in one line grammar? – Yodism Jan 18 '15 at 12:43
  • Exactly, you need to disambiguate by adding new non-terminals. Just go through the links for ambiguous grammars. – Am_I_Helpful Jan 18 '15 at 12:44
  • Isn't it also true that `E -> E + E` is ambiguous all by itself since it doesn't define the associativity of `+`? That is, a + b + c could be parsed as either `(a + b) + c` or `a + (b + c)`. Even though in "normal" arithmetic the result is the same, there could be different results if we were adding floating point numbers, for example. – jacobq Dec 18 '15 at 13:15
  • Yes, that is why we do have associativity of operators in almost every language specification, say Java, etc. @iX3. I had already mentioned that point BTW in my answer too. – Am_I_Helpful Dec 18 '15 at 16:12