ANTLR expressions rewrite intermediate tree
For expressions like 3 + 4, I would like to use the value 7 in the intermediate representation tree.
I can't figure out how to get the return value into the rewrite rule.
expression returns [int v]: etc.
How to get expression.v in WR? At the moment I get (+ 3 4), I want (7)
| ^ (WRITE c = expression) → ^ (WRINT ^ (INTC ^ ($ c))
the next step is to emit 7 in assembler.
source to share
I think you want to know how to use the rewrite syntax to create a single numeric token with the value $ c and not a different tree? If this happens, you can do it with
^(WRITE c=expression) -> INT[$c.v] ;
assuming INT is the token type for integers.
This assumes that your expression rule actually evaluates and returns an integer result. If this is not the case, and you want to know how to do permanent folding, this is a much more important topic. Check out the polynomial example in the ANTLR examples collection; it shows you how to do basic simplification. Perhaps you could do it with a tree-rewriter using rules like
^('+' a=INT b=INT) -> INT[String.valueOf($a.int+$b.int)] ;
source to share