[antlr-interest] Custom AST node type - guidance needed
John B. Brodie
jbb at acm.org
Mon Jul 19 12:15:02 PDT 2010
On Mon, 2010-07-19 at 14:29 -0400, Bill Andersen wrote:
> Hi folks
Greetings!
>
> Having some trouble making ASTs using a custom node type. Before I ask any stupid questions, what is the best place to look on how to do this ( I'm using 3.2 )? I'm finding bits and pieces, some of them contradictory. For example I find this example
>
> static class V extends CommonTree {
> public int x,y,z;
> public V(int ttype, int x, int y, int z) {
> this.x=x; this.y=y; this.z=z; token=new CommonToken(ttype,"");
> }
> at http://www.antlr.org/wiki/display/ANTLR3/Tree+construction
>
> When I try to define a constructor like this I'm forced to put a cast between on CommonToken to Token, which causes a runtime can't cast error.
>
> What I want is really quite simple. Need to add one extra field to my AST nodes to carry DSL type information.
>
> Any help appreciated. Thanks.
Unable to reproduce.
Attached please find a complete example derived from the grammar on the
above wiki page that uses the class V. maybe I'm using a different
example than yours?
Need more info....
-jbb
-------------- next part --------------
grammar T;
options {output=AST; ASTLabelType=CommonTree;}
@members {
static class V extends CommonTree {
public int x,y,z;
public V(int ttype, int x, int y, int z) {
this.x=x; this.y=y; this.z=z; token=new CommonToken(ttype,"");
}
public V(int ttype, Token t, int x) { token=t; this.x=x; }
public String toString() {
return (token!=null?token.getText():"<null>")+"<V>:"+x+","+y+","+z;
}
}
private static final String [] x = new String[] {
"abcd"
};
public static void main(String [] args) {
for( int i = 0; i < x.length; ++i ) {
try {
System.out.println("about to parse:`"+x[i]+"`");
TLexer lexer = new TLexer(new ANTLRStringStream(x[i]));
CommonTokenStream tokens = new CommonTokenStream(lexer);
TParser parser = new TParser(tokens);
TParser.a_return p_result = parser.a();
CommonTree ast = p_result.tree;
if( ast == null ) {
System.out.println("resultant tree: is NULL");
} else {
System.out.println("resultant tree: " + ast.toStringTree());
}
System.out.println();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
a : ID -> ID<V>[42,19,30] ID<V>[$ID,99] ;
ID : 'a'..'z'+ ;
WS : (' '|'\\n') {$channel=HIDDEN;} ;
More information about the antlr-interest
mailing list