How can I add "imaginary" nodes (nodes without corresponding input token) to my AST?
Created May 4, 2012
class LangParser extends Parser; options { buildAST=true; } tokens { EXPR; // imaginary token } block : LCURLY! ( statement )* RCURLY! // add imaginary BLOCK node on top of statement list {#block = #([BLOCK, "BLOCK"], #block);} ;This operation should be done as the last operation in a rule where you have auto tree generation on lest you interfere with the tree construction. If you use '!' to turn off auto construction for the alternative or rule, then it is ok to add children and so on to various nodes during the rule's execution.
As for adding imaginary children nodes to existing trees, you can
label the node (not a rule reference unless you know the rule only
returns a node) and then use the #(...) tree operator to add children:
rule : A b:B C
{#rule = #(#b, [IMAG, "IMAG"]);}
;
If you want the operation to occur during the recognition, turn of auto construction:
rule :! A b:B {#rule = #(#b, [IMAG, "IMAG"]);} C
;
You don't want to interfere with ANTLR's construction code. Note that
this "add imaginary child" operation will be rare. "Add imaginary
parent" will be more common. Further, the above rule really should be written as:
rule :! A b:B C
{#rule = #(null, A, #(#b, [IMAG, "IMAG"]), C);}
;