[antlr-interest] greedy vs nongreedy lexer rules

Terence Parr parrt at cs.usfca.edu
Mon Apr 19 12:32:45 PDT 2010


On Apr 19, 2010, at 10:59 AM, Daniels, Troy (US SSA) wrote:
> That fails when there are predicates in the rule that use the variables.  Consider this rule, based on something that was discusses on the list a while ago.
> 
> Fragment LETTER: 'a'..'z';
> 
> OneToFiveLetters:
> @init {
> int i = 0;
> }
> 
> ( {i<5}? LETTER {++i;} )+ ;

Predicates are difficult to implement because you can't really have the action executed to you are sure that the entire rule matches.  That means backtracking if there are other rules that can match that input string. The solution is to use the always executing {{++i;}} version of the action. because i it's a local  variable, the side effects are relevant.

Ter


More information about the antlr-interest mailing list