antlr / antlr/antlr4

Explicitly resolving if/if/else ambiguity in a grammar

Open
#42 9 comments 0 reactions 0 assignees View on GitHub
atn-analysis comp:runtime grammars parsers status:pull-request type:feature
Dominant language
Java
Stars
19k
Forks
3.5k
PR merge metrics
No merged PRs in 30d

Description

I'm working with an ANTLR 4 grammar to correct any construct which results in a call to `reportAmbiguity`. In many cases this is done by refactoring or combining rules, but the case for an `if`/`if`/`else` construct is proving more challenging.

Starting with the following grammar:

```
grammar T;
stmt : ifStmt | ID;
ifStmt : 'if' ID stmt ('else' stmt)?;

ID : [a-zA-Z]+;
WS : ' '+ -> skip;
```

Given the input `if x if x a else b`, I'm looking for a way to modify the grammar such that no call to `reportAmbiguity` is needed, while following the standard `if`/`else` rule of binding to the closest unmatched `if` statement.

In ANTLR 3, a syntactic predicate allowed the user to explicitly handle this situation. In ANTLR 4, the correct decision is made through min-alt resolution, but it always wants to emit a "warning" regarding the situation.

Contributor guide

Open the contributing guide

Research direction

Start with the supplied grammar T and the input `if x if x a else b`, then inspect how ANTLR 4 reports ambiguity at the `ifStmt` decision and applies min-alt resolution. Done means the grammar follows closest-unmatched-if binding without requiring a `reportAmbiguity` warning.

Written by the indexing model from the issue text.

Assessment

Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.