2

I want to prove that this grammar is ambiguous, but I'm not sure how I am supposed to do that. Do I have to use parse trees?

  S -> if E then S | if E then S else S | begin S L | print E
  L -> end | ; S L
  E -> i
name
  • 419
  • 3
  • 14
  • I'm voting to close this question as off-topic because it is not a programming question. – Raymond Chen Apr 05 '17 at 06:27
  • What exactly do you mean by _ambiguous_? That there exists a word for which more than one derivation is possible? – Codor Apr 05 '17 at 06:28
  • @Codor Yes, there has to be at least one string with more than one parse tree. – name Apr 05 '17 at 06:33
  • 2
    Will something like this `if E1 then if E2 then print S1 else S2` cause two different derivations? – name Apr 05 '17 at 06:49

2 Answers2

1

You can show it is ambiguous if you can find a string that parses more than one way:

if i then ( if i then print i   else print i ; )
if i then ( if i then print i ) else print i ;

This happens to be the classic "dangling else" ambiguity. Googling your tag(s), title & grammar gives other hits.

However, if you don't happen to guess at an ambiguous string then googling your tag(s) & title:

how can i prove that this grammar is ambiguous?

There is no easy method for proving a context-free grammar ambiguous -- in fact, the question is undecidable, by reduction to the Post correspondence problem.

philipxy
  • 14,867
  • 6
  • 39
  • 83
0

You can put the grammar into a parser generator which supports all context-free grammars, a context-free general parser generator. Generate the parser, then parse a string which you think is ambiguous and find out by looking at the output of the parser.

A context-free general parser generator generates parsers which produce all derivations in polynomial time. Examples of such parser generators include SDF2, Rascal, DMS, Elkhound, ART. There is also a backtracking version of yacc (btyacc) but I don't think it does it in polynomial time. Usually the output is encoded as a graph where alternative trees for sub-sentences are encoded with a nested set of alternative trees.

Jurgen Vinju
  • 6,393
  • 1
  • 15
  • 26