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

Bart Kiers bkiers at gmail.com
Wed Jan 12 09:26:09 PST 2011


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

> Hi Bart,
>
> Thank you for your response.
>
> Will the validating semantic predicate verify the amount of matches after
> the first number, or will it instruct the parser to stop consuming tokens
> after the Nth occurrence? The second option is what I need.
>
> I provided a bit more context in a previous email, in answer to Michael's
> proposal. The short version is:
>
> The protocol is more complex, and the sequence can be followed by more
> data.
>
> Using the same non-standard notation, as I dont know a proper way to
> express this:
>
> protocol: data+
>
> data: count number{count.value}
>
> Therefore, the following sequence needs to be valid:
>
> *3* 10 12 15 *2* 4 5
>
> I need to instruct the parser to only match 3 numeric values after matching
> the 3, and so on.
>
> From implementing your proposal, Bart, it seems it does not achieve what I
> am looking for (again, my bad for not giving enough context at the
> beginning)
>
> Cheers!


In that case, using a "gated semantic predicate" before the "validating
predicate" is more appropriate:

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


Tested with the following class:

*import org.antlr.runtime.*;*
*
*
*public class Main {*
*    public static void main(String[] args) throws Exception {*
*        ANTLRStringStream in = new ANTLRStringStream(*
*                "3 10 12 15    \n" +*
*                "2 6 9 3 1 1 111 \n"*
*        );*
*        TestLexer lexer = new TestLexer(in);*
*        CommonTokenStream tokens = new CommonTokenStream(lexer);*
*        TestParser parser = new TestParser(tokens);*
*        parser.parse();*
*    }*
*}*


Regards,

Bart.


More information about the antlr-interest mailing list