Reputation: 913
I'm trying to allow my grammar to support variable declarations where you don't have to repeat the variable type such as int i = 3, j = 4, k;
The problem I have is with my generated tree. This is my rule...
varDeclaration
: type ID (ASSIGN expression)? (COMMA ID (ASSIGN expression)?)* SEMICOLON -> ^(VAR_DECL type ID expression?)+;
It successfully splits apart the declaration into separate variable declarations, but it is repeating the expression tree for all of them.
So for int x = 4, y = 5
, they both have value 4
in the AST.
Any help with an operator or something I can use would be appreciated.
Upvotes: 1
Views: 1146
Reputation: 170158
ANTLR cannot make a distiction between the expression
s. AFAIK, you'll have to create a "helper" rule.
A quick demo:
options {
output=AST;
ASTLabelType=CommonTree; // <- important, otherwise `$t.tree` returns an Object instead of a CommonTree
}
tokens {
VAR_DECLS;
VAR_DECL;
}
// ...
varDeclaration
: t=type assign[$t.tree] (COMMA assign[$t.tree])* SEMICOLON -> ^(VAR_DECLS assign+)
;
assign[CommonTree type]
: ID (ASSIGN expression)? -> ^(VAR_DECL {type} ID expression?)
;
// ...
Now your input will produce the following AST:
Note that the type-node will be the same for all VAR_DECL
nodes. This might not be an issue (since this node is most probably not going to change), but if you want each VAR_DECL
node to have its own instance of a type node, do something like this:
assign[CommonTree type]
: ID (ASSIGN expression)? -> ^(VAR_DECL {new CommonTree(type)} ID expression?)
;
Or something similar. You can use plain target code inside the {
and }
in the rewrite rule.
Upvotes: 2