[antlr-interest] Change node content in AST tree generated with ANTLRWorks
Bart Kiers
bkiers at gmail.com
Thu May 5 12:14:24 PDT 2011
Note that it doesn't matter if you use ANTLRWorks or the org.antlr.Tool on
the command line to generate the lexer/parser: they do the same thing.
1. Did you define your custom tree in the options section of your
grammar?
2. Did you "attach" a custom TreeAdaptor to your parser?
Here's a little demo that demonstrates the 2 points I mentioned above:
grammar T;
options {
output=AST;
ASTLabelType=MyTree;
}
@parser::members {
static class MyTree extends CommonTree {
public MyTree(Token t) {
super(t);
}
@Override
public String toString() {
return "MyTree=" + super.toString();
}
}
public static void main(String[] args) throws Exception {
String source = "abc";
TLexer lexer = new TLexer(new ANTLRStringStream(source));
TParser parser = new TParser(new CommonTokenStream(lexer));
parser.setTreeAdaptor(new CommonTreeAdaptor(){
@Override
public Object create(Token t) {
return new MyTree(t);
}
});
parser.parse();
}
}
parse
: (ANY {System.out.println($ANY.tree);})+ EOF
;
ANY
: .
;
which, after generating the lexer/parser, compiling all .java files and
running the class with the main method:
$ java -cp antlr-3.2.jar org.antlr.Tool T.g
$ javac -cp antlr-3.2.jar *.java
$ java -cp .:antlr-3.2.jar TParser
produces:
MyTree=a
MyTree=b
MyTree=c
Regards,
Bart.
On Sun, May 1, 2011 at 2:47 AM, Fernando Sanchez <fernando at rti.com> wrote:
> Hi,
>
> Is there a way to customize the text associated with the nodes of the AST
> tree generated with ANTLRWorks?. I tried to overwrite the toString method in
> my Tree node (inherit from CommonTree) without success.
>
> Regards,
> Fernando
>
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe:
> http://www.antlr.org/mailman/options/antlr-interest/your-email-address
>
More information about the antlr-interest
mailing list