[antlr-interest] Checking for missing optional token in rule

John B. Brodie jbb at acm.org
Mon Jul 23 15:11:13 PDT 2012


On 07/23/2012 05:55 PM, Burton Samograd wrote:
> See the comment below for an explanation:
> paren_delimited_numeric_unit_list
>      : LPAREN number unit1=unit (COMMA number unit2=unit? {
>              // I would like to check if unit2 was present in the input tokens
>              // and do something if it was not.
>          })* RPAREN
>          -> (number unit)+
>          ;
> In the tree walker we can say ($unit2 == NULL) to check for presence, but that technique does not work in the parser.  Is there a way to do what I would like to do?

off the top of my head (and untested)

   : LPAREN number unit1=unit (COMMA number ( ( /*empty*/ { handle missing $unit2 here } )
                                            | ( unit2=unit { handle existing $unit2 here } )
   )* RPAREN
   -> (number unit)+ <<==== probably improper rewrite, wrong cardinality, root of tree is not a TOKEN

so basically we realize that the "?" meta operator is equivalent to a 
choice between the empty phrase and the phrase we desire (e.g. foo ? == 
( | foo )

and i use the comment /*empty*/ to explicitly indicate that the empty 
phrase is a valid possibility.

and now we may simply add appropriate action code to handle each 
alternative as required.

Hope this helps...

More information about the antlr-interest mailing list