ANTLR 3.x - How to format rewriting rules

I found that it’s hard for me to understand how to properly format rewrite rules when certain conditions arise in the original rule.

How can I rewrite this:

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

It seems to me that I don’t like Antlr, that there is something in the shortcut in brackets, and “op =” fails. In addition, I tried:

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

Antlr do not like or '|' and generates a grammatical error.

Replacing a character class with a token name solves this problem, however this creates a trick of other problems with my grammar.

--- edit ----

Added second issue. Please help me format this rule using tree grammar:

multExpression : unaryExpression (MULT_OP unaryExpression)* ;

: , () MULT, - :

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

UNARY_EXPR[$op], node / -1.

+2

Source: https://habr.com/ru/post/1734646/


All Articles