[antlr-interest] Heterogeneous AST nodes: In, but not out..

Bill Andersen bill.andersen at mac.com
Tue Jul 20 09:15:59 PDT 2010


Folks

So I got my problem fixed with *making* custom AST nodes.  I can make them and pass the right parameters to them.  Thanks to Jay for that.

Now, I'm trying to *use* them.

My AST consists of a mixture of ASNode (subclass of CommonTree) and CommonTree nodes.  Here's a production in a tree grammar I'm working on with template output:


options {

  ASTLabelType = CommonTree; 
  tokenVocab = AS;
  output = template;

}

<snip>

rule
	: ^(rNode=AS_RULE rName=ID alts+=alternative+)
	  { System.out.println($rNode); }
	  -> pRule( rName={$rName.text}, rType={????} )	
	;

Question is what to put in place of ???? to get an attribute value out of AS_RULE

Now, AS_RULE in input to this grammar is of type ASNode.  Relevant portions below:

public class ASNode extends CommonTree {
	
	public ASType rType = null;
	
	public ASNode() { }
	
	public ASNode(int ttype, ASType rType) {
		token = new CommonToken(ttype,"");
		this.rType = rType;
	}
	
	public ASNode(int ttype) {
		token = new CommonToken(ttype,"");
	}
	
	public ASType getRType() {
		return rType;
	}

}

If I put anything like $rNode.X, where X is a field or method access to an ASNode instance, I get a Java compile error.  ANTLR thinks $rNode is of type CommonTree.  So I figure I need to tell ANTLR what type to expect, so when I try

rule
	: ^(rNode=AS_RULE<ASNode> rName=ID alts+=alternative+)
	  { System.out.println($rNode); }
	  -> pRule( rName={$rName.text}, rType={$rNode.getRType()} )	
	;

I get the same compile error.  Maybe I can change the options of all my grammars to

	  ASTLabelType = ASNode; 

but that defeats the whole purpose of having hetergeneous nodes, not to mention I'm not sure what other side-effects this will cause.

So, what's the best way to get information out of these hetergeneous node objects?

	.bill





More information about the antlr-interest mailing list