[antlr-interest] set max number of characters in a string literal

Gavin Lambert antlr at mirality.co.nz
Sat Sep 13 15:42:23 PDT 2008


At 10:24 14/09/2008, Olya Krachina wrote:
 >LONG_STRINGLITERAL
 >  :
 >    ('"') (~('"'|'\n'|'\r'))* ('"')
 >    {
 >        String wholeStr;
 >        int strLen, maxStrLen = 80;
 >        wholeStr = getText().toString();
 >        strLen = wholeStr.length();
 >         if ( strLen > maxStrLen )
 >         {
 >          {$setType(STRINGLITERAL))};
 >         }
 >    }
 >    ;
 >
 >It looks like this might work, only now i have to declare
 >STRINGLITERAL somehow, i would have to write ANOTHER RULE for
 >stringliteral, and i don't know what i could write where the
 >prefix does not match the LONGSTRINGLITERAL rule;

You can declare it as a protected rule.  That will define it as a 
possible token type without making it a top-level candidate; if 
you don't call it yourself elsewhere in the grammar then its 
precise contents are irrelevant.

But as I said before I wouldn't do it this way.  I'd just make a 
STRINGLITERAL rule that tolerates string literals of any length, 
and then do the length validation in the parser.  It's much easier 
to generate meaningful error messages in the parser than it is in 
the lexer.



More information about the antlr-interest mailing list