views:

148

answers:

1

For expressions like 3+4 I would like to use the value 7 in an intermediate representation tree.

I cannot work out how to get the returns value into a rewrite rule.

expression returns [int v]: etc.

How do I get expression.v into 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 an assembler.

A: 

I think you want to know how to use the rewrite syntax to construct a single numeric token with the value of $c, rather than another tree? If that's the case, you can do this with

^(WRITE c=expression) -> INT[$c.v] ;

assuming that INT is the token type for integers.

That assumes that your expression rule actually evaluates and returns an integer result. If it doesn't and you want to know how to do constant folding, that's a much bigger topic. Take a look at the polynomial example in the ANTLR examples collection; it shows how to do some basic simplification. You could probably do it with a tree rewriter using rules like

^('+' a=INT b=INT) -> INT[String.valueOf($a.int+$b.int)] ;
Maskull