Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANTLR 3.x - How to format rewrite rules

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
like image 236
Jesse Hallam Avatar asked Dec 21 '25 00:12

Jesse Hallam


1 Answers

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.

like image 101
Sam Harwell Avatar answered Dec 22 '25 23:12

Sam Harwell