[antlr-interest] Nubie: How to approach multiple "required" subrules in any order

Jim Idle jimi at temporal-wave.com
Fri Nov 6 10:08:34 PST 2009


The trick is not to try and enforce the semantics by encoding them in the grammar, then you have to put the rules together carefully to ensure that recovery happens. I need to write a wiki article about recovery I think.

 

So, you allow any number of those rules in your parser and then when you walk the AST, count the occurrences and issue a good semantic based error about not being allowed to duplicate them. Without testing it, you would have:

 

big_rule : token_big rset -> ^(ROOT token_big rset) ;

rset  : ( r1 | r2 | r3)* ;

r1 : t1 EQ^ STRING;

r2...

 

While you are getting to know this stuff, do not use 'literals' in your parser, make lexer tokens and use their names:

 

EQ : '=';

// Other keywords/operators

STRING ...

ID ...

COMMENT ...

WS :

ANY : . {issue error - unknown character} ; // Always the last rule in the lexer

 

Jim

 

 

From: antlr-interest-bounces at antlr.org [mailto:antlr-interest-bounces at antlr.org] On Behalf Of gary mazzaferro
Sent: Friday, November 06, 2009 7:41 AM
To: antlr-interest at antlr.org
Subject: [antlr-interest] Nubie: How to approach multiple "required" subrules in any order

 

H,

I'm new to antlr and learning as I'm writing a parser to an ast tree. I'm not sure how to approach this problem ( I think its simple) and was hoping someone could help me out. 

I have a input stream with a token followed by 3 other rules. Each of the 3 "rules" occurs only once for the parse to be correct, but they can arrive in any order. If it fails, it should continue on the next characters after token_big. How do I write the "big_rule" ?
                            

big_rule : token_big  ( rule1 | rule2 | rule3 )  -> " also, what do I put here ?"
                not right >>>  ^      ^        ^

rule1: token1 '=' STRING -> ^('=' token1 STRING);
rule2: token2 '=' STRING -> ^('=' token2 STRING);
rule3: token3 '=' STRING -> ^('=' token3 STRING);

cheers,
gary



-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20091106/af7fda1f/attachment.html 


More information about the antlr-interest mailing list