I want to convert this grammar to an unambiguous grammar:
S -> if E then S
| if E then S else S
| a
E -> b
I found a solution which is more complicated than my solution but I'm not sure if my solution is correct:
S -> if E then T else S
| if E then S
| a
T -> if E then T else T
| a
E -> b
So is my solution correct?
It looks OK to me. It's really not much different from the standard solution:
stmt : matched | unmatched
matched : "if" expr "then" matched "else" matched
| other_stmt
unmatched : "if" expr "then" unmatched
| "if" expr "then" matched "else" unmatched
The advantage of the standard solution is that other_stmt
(a
in your grammar) is not duplicated, and the grammar is easier to extend with other compound statements. For example, if we add the while
statement:
stmt : matched | unmatched
matched : "if" expr "then" matched "else" matched
| "while" matched
| other_stmt
unmatched : "if" expr "then" unmatched
| "if" expr "then" matched "else" unmatched
| "while" unmatched