开发者

ANTLR expressions rewrite intermediate tree

开发者 https://www.devze.com 2022-12-26 04:14 出处:网络
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 rewri开发者_高级运维te rule.

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 rewri开发者_高级运维te 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.


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)] ;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号