[antlr-interest] limit the number of characters in a string

Tim Halloran hallorant at gmail.com
Tue Sep 23 10:10:09 PDT 2008


Well, you could use "+" and then have the semantic analysis of the grammar
check the length of the input strings and output an error (raise
RecognitionException) if the string length is greater than 32.  Something
like this:

grammar Example;

string32
    : ID
    {
        final String id = $ID.text;
        if ((id.length() > 32))
            throw new RecognitionException();
    }
    ;

ID    : ('a'..'z'|'A'..'Z')+
    ;

This should work -- that said the error reporting probably could be improved
:-)  The example above just errors out because RecognitionException doesn't
allow a string message to be set (I'm not sure why).  You could create your
own runtime exception sub-class or throw something like
IllegalArgumentException that would allow you to pass a description (e.g.,
The identifier 'badbecauseitiswaywaywaywaywaywaywaywaywaywaytoolong' is too
long...all identifiers must be 32 characters or less.)

Good luck,
Tim

On Tue, Sep 23, 2008 at 12:50 PM, Waqas Javed <waqasjaved at gmail.com> wrote:

> Thanks, for the reply. Actually if I adopt this technique, antlr take a lot
> of time to make the parser tree. That is why I am looking for any built in
> command that can solve the problem in an efficient way.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20080923/ed8fbf0b/attachment.html 


More information about the antlr-interest mailing list