Resolve ambiguities in antlr v3

When there is ambiguities in writing antlr grammar, there are different ways to solve it.

1. Simply avoid them. This is the ideal way when it’s possible.

2. Turn on backtracking, which is most inefficient way.

3. Use left factoring.

4. Use syntax predicates.

For some samples, check it out at http://www.antlr.org/wiki/display/ANTLR3/How+to+remove+global+backtracking+from+your+grammar

The format of sytnax predicate is close to semantic predicates. There are 3 types of them:

1. Validating semantic predicate, to place constraints on rules. For example
data : ( b += BYTE )+ {$b.size() <= 4}? ;
2. Gated semantic predicate, to turn on some alternatives under runtime condition. For example:
stat: ifState | {allowAssert}?=> assertStat ;
3. Disambiguating semantic predicate, to choose alternatives based on semantic context. For example:
stat: keyIf ID stat | keyCall ID ‘;’ ;
keyIf: {input.LT(1).getText().equals(“if”)}? ID ;
keyCall: {input.LT(1).getText().equals(“call”)}? ID ;

This entry was posted in antlr. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.