[antlr-interest] Protocol message recognition - an amateur grammar question

Bart Kiers bkiers at gmail.com
Wed Jan 12 08:29:20 PST 2011


On Wed, Jan 12, 2011 at 5:02 PM, Alex Lujan <alex at apption.com> wrote:

> I am trying Antlr v3 for message recognition, which must comply to a custom
> define protocol.
>
> I find myself unable to express the following rule (written in a
> non-standard notation):
>
> data: count number{count.value}
>
> What I am expecting to find in the input is a numerical value (which Ive
> labeled count), followed by as many numerical values as the value of count.
>
> Examples of valid input:
>
> 3 10 12 15
> 2 6 9
>
> Examples of invalid input:
>
> 3 10 12
> 2 4 5 6
>
>
You could use a 'validating semantic predicate'. A small demo:

*grammar Test;*
*
*
*parse*
*  :  line+ EOF*
*  ;*
*
*
*line*
*  :  n=number {int c = $n.value;} (number {--c;})* {c==0}? LineBreak*
*  ;*
*
*
*number returns [int value]*
*  :  Int {$value = Integer.parseInt($Int.text);}*
*  ;*
*    *
*Int*
*  :  '0'..'9'+ *
*  ;*
*
*
*LineBreak*
*  :  '\r'? '\n'*
*  |  '\r'*
*  ;*
*        *
*Space*
*  :  (' ' | '\t') {skip();}*
*  ;*



Regards,

Bart.


More information about the antlr-interest mailing list