[antlr-interest] Getting started with Java target?

Shaoting Cai caishaoting at gmail.com
Mon Jun 9 14:12:52 PDT 2008


Hi Kevin,

To get the Tree from the parser:

1. set your parser grammar option:
options { output=AST; }

2. get the let the parser run and get the tree from it:
CharStream input = new ANTLRInputStream(System.in);
Lexer lex = new Lexer(input);
CommonTokenStream tokens = new CommonTokenStream(lex);
SLParser parser = new SLParser(tokens);
SLParser. compilationUnit_return r = parser.compilationUnit();
Tree t = (Tree)r.tree;     // or r.getTree();
(referenc: http://antlr.org/wiki/display/CS652/AST+Construction)
note: the compilationUnit is the name of your starting rule

3. if you have a tree grammar, feed the Tree t object to it and walk the AST.

Hope that helps :)
-Shaoting



On Mon, Jun 9, 2008 at 12:44 PM, Kevin Kelley <kkelley at adobe.com> wrote:
> Hello all,
>
> I can't help but feel like there's something really obvious that I'm missing
> here, but I'm driving myself ragged, so I figured I'd ask.
>
> I have used ANTLRworks (which is nice, by the way) to generate a Java lexer
> and parser, and have gotten that code and the ANTLR runtime JAR into a
> project of mine.  What I want to do now is to get the tree produced by the
> parser.  Unfortunately, the "how to use the Java runtime" section of the
> website is incomplete, and all the examples I can Google my way to seem to
> be for ANTLR 2 or to have other problems.
>
> I have a parser, and am giving it the token stream from the lexer and then
> invoking the method corresponding to the root rule on the parser, which
> presumably parses the token stream.  I think what I want to get out of the
> parser is an "org.antler.runtime.tree.CommonTree" or something similar—but I
> can't for the life of me figure out how to get the tree out of the parser.
>
> Any help would be much appreciated!
>
> Thanks,
>
> Kevin


More information about the antlr-interest mailing list