views:

341

answers:

1

I'm finding myself challenged on how to properly format rewrite rules when certain conditions occur in the original rule.

What is the appropriate way to rewrite this:

unaryExpression: op=('!' | '-') t=term
  -> ^(UNARY_EXPR $op $t)

Antlr doesn't seem to like me branding anything in parenthesis with a label and "op=" fails. Also, I've tried:

unaryExpression: ('!' | '-') t=term
  -> ^(UNARY_EXPR ('!' | '-') $t)

Antlr doesn't like the or '|' and throws a grammar error.

Replacing the character class with a token name does solve this problem, however it creates a quagmire of other issues with my grammar.

--- edit ----

A second problem has been added. Please help me format this rule with tree grammar:

multExpression : unaryExpression (MULT_OP unaryExpression)* ;

Pretty simple: My expectation is to enclose every matched token in a parent (imaginary) token MULT so that I end up with something like:

 MULT
  o
  |
  o---o---o---o---o
  |   |   |   |   |
 '3' '*' '6' '%'  2
+1  A: 
unaryExpression
    :    (op='!' | op='-') term
         -> ^(UNARY_EXPR[$op] $op term)
    ;

I used the UNARY_EXPR[$op] so the root node gets some useful line/column information instead of defaulting to -1.

280Z28
Thanks a lot. I've never heard of using the TOKEN[$op] before, but I'm hardly a wide expert. Using it in this context did not produce the results I was looking for. The UNARY_EXPR token is imaginary and used in this context for describing the two tokens that follow it. However, the op=x|op=y was precisely what I wasn't doing correctly.
Kivin