3
votes

I am kind of new to ANTLR and would like to do the following:

Given the grammar snippet below, I have a choice rule *comparison_op* that can match one of many tokens. What I would like to do is write conditional rewrite rules - such as, if token is DOESNOTENDWITH do something, if it is DOESNOTCONTAIN do something etc.

I just can't seem to get this right. Is it even possible to do this? Of course, I can write specific rules for each condition, but that does not seem to be the best way either.

Any suggestions?


{... snipped ...}

DOESNOTBEGINWITH        : 'does not begin with';
DOESNOTENDWITH          : 'does not end with';
DOESNOTCONTAIN          : 'does not contain';

comparison_op           : DOESNOTBEGINWITH | DOESNOTENDWITH | DOESNOTCONTAIN
condition_comparison    : (column_name comparison_op v1=valueExpression) 
                        ->  {$comparison_op.text == $DOESNOTBEGINWITH.text}?  
                                    ^(LIKE column_name $v1)
                        ->          ^(comparison_op column_name $v1);
1

1 Answers

2
votes

Try this:

condition_comparison
 : (column_name comparison_op v1=valueExpression) 
    -> {$comparison_op.start.getType() == DOESNOTBEGINWITH}? 
       ^(LIKE column_name $v1)
    -> ^(comparison_op column_name $v1)
 ;

However, I don't see any problem in writing it like this:

condition_comparison
 : column_name ( DOESNOTBEGINWITH valueExpression -> ^(LIKE column_name valueExpression)
               | DOESNOTENDWITH valueExpression   -> ^(DOESNOTENDWITH column_name valueExpression)
               | DOESNOTCONTAIN valueExpression   -> ^(DOESNOTCONTAIN column_name valueExpression)
               )
 ;