[antlr-interest] Equivalent of TOKEN{x,y}

Gavin Lambert antlr at mirality.co.nz
Wed Nov 11 11:44:00 PST 2009


At 08:35 12/11/2009, Kaleb Pederson wrote:
 >Is there an easy way to enforce in the grammar that a lexical 
token
 >must be present a certain number of times?
 >
 >For example, with TOKEN{x,y} as you might see in an extended
 >regular expression, it would require that TOKEN be present at
 >minimum x times and at most y times.

The best way to do it is to use validation code:

rule: (t+=TOKEN)+ { /* check $t and throw an error if the wrong 
number appears */ };

You can also do this purely syntactically, but there isn't a 
"nice" syntax for it and it won't produce as useful an error to 
the user:

// TOKEN{3,5}
rule: TOKEN TOKEN TOKEN (TOKEN TOKEN?)?;


This sort of requirement is fairly unusual for a language 
specification, though.



More information about the antlr-interest mailing list