[antlr-interest] Fixed width field

Thomas Brandon tbrandonau at gmail.com
Wed Aug 1 02:08:43 PDT 2007


On 8/1/07, Gavin Lambert <antlr at mirality.co.nz> wrote:
> At 20:10 1/08/2007, Joel Shellman wrote:
>  >Is there a way to specify a number of matches of something?
> [...]
>  >rule4: CHAR CHAR CHAR;
>  >
>  >I know this would do 3 times, but it's rather unwieldy
> especially
>  >if I had 36 or 150 or something like that. Is there some syntax
>  >to specify to match n times?
>
> Nope.  But you can composite them if you really need to:
>
> char5: CHAR CHAR CHAR CHAR CHAR;
> char10: char5 char5;
> char50: char10 char10 char10 char10 char10;
> char150: char50 char50 char50;
>
Or use a semantic predicate. Off the top of my head, something like:
fixedChars[int count]
@init {
    int c = 0;
}
    : ( {c++ < $count}? CHAR )+ {c == $count}?
    ;

Or move count to the init section of you don't need to vary it.
Or it might be better to replace the second predicate with an action
to report the error to avoid having to handle the resulting predicate
failure exception.
Depending on how it's being used you may also want to remove the count
check in the first predicate and let the rule match any number of
CHARs and just report any mismatch. This will ease error recovery but
is not applicable if you need to partition a sequence of CHARs into
groups of n.

Tom.

> Although for really fixed-width input you'd probably want to do it
> in the lexer.  Or not use ANTLR at all, since fixed-width is easy
> :)
>
>


More information about the antlr-interest mailing list