[antlr-interest] Doing things to rewritten AST nodes
Jarek Rzeszótko
sztywny at gmail.com
Sun Nov 16 23:19:47 PST 2008
Hello!
I want to do a tree-to-tree rewrite in the semantic analysis of my toy
compiler, replacing ^('+' (* 5 10) 'foobar') with ^(STRING_PLUS (* 5
10) 'foobar') when one of the arguments to '+' is a string. I'm
running into trouble with this, through - I have my custom ASTNode
class for AST nodes (extending CommonTree), which among other things
keeps track of the type of the expression the node represents (string,
int etc.) How can I do something to the resulting tree after the
rewrite was done? I have rules likes this (I want to flatten the tree
for string concatenation too):
addition
: ^('+' a=addition_flatten b=addition_flatten) {
TypeChecker.infer($start, $a.start, $b.start);
}
-> {$start.isOf(Types.String)}? ^(STRING_PLUS addition_flatten+)
-> ^('+' addition_flatten+)
;
addition_flatten
: ^('+' (operands+=addition_flatten)+) {
TypeChecker.infer($start, $operands);
}
-> {$start.isOf(Types.String)}? addition_flatten+
-> ^('+' addition_flatten+)
| binary_expression -> binary_expression
;
TypeChecker.infer deduces the type of his first argument based on the
type of his second two arguments, and as a result calls something like
$start.setNodeType(Types.String). It works correctly, but as you may
expect, what gets the attribute set is the tree ^('+' (* 5 10)
'foobar') and not the rewritten tree ^(STRING_PLUS (* 5 10) 'foobar').
This ends up with a null pointer exception at some point.
Do you have any idea how to fix that? You can see the complete code
here: http://github.com/sztywny/xpl/tree/master
Cheers,
Jarosław Rzeszótko
More information about the antlr-interest
mailing list