Chapter 4: Syntax Analysis

Resolving dangling else problem

  • General rule: match each else with the closest previous then. The grammar can be rewritten as

stmt matched-stmt

| unmatched-stmt

| others

matched-stmt if expr then matched-stmt

else matched-stmt

| others

So, we need to have some way to decide to which if an ambiguous else should be associated. It can be solved either at the implementation level, by telling the parser what the right way to solve the ambiguity, or at the grammar level by using a Parsing expression grammar or equivalent. Basically, the idea is that a statement appearing between a then and an else must be matched i.e., it must not end with an unmatched then followed by any statement, for the else would then be forced to match this unmatched then . So, the general rule is " Match each else with the closest previous unmatched then".

Thus, we can rewrite the grammar as the following unambiguous grammar to eliminate the dangling else problem:

stmt matched-stmt | unmatched-stmt | others

matched-stmt if expr then matched-stmt else matched-stmt | others

unmatched-stmt if expr then stmt

| if expr then matched-stmt else unmatched-stmt

A matched statement is either an if-then-else statement containing no unmatched statements or it is any other kind of unconditional statement.