[antlr-interest] Beginners Question
decoder
decoder-antlr at own-hero.net
Fri Oct 1 13:46:33 PDT 2010
Hello List,
I've recently started working with ANTLR because I need a JavaScript
parser (in Java). So I took the grammar at
http://www.antlr.org/grammar/1206736738015/JavaScript.g and used antlr3
to generate Java Classes from that. I figured out that I need Lexer and
Parser classes and have something like the code at the end of the mail.
The problem with this is that the returned "tree" is not a tree but a
flat list. It contains all tokens but flattened, I assumed that you
should get a real tree though, am I wrong there?
My goal for now would be to extract for example all things that are
"IfStatement" from the grammar, but I can't see how I can achieve that :(
I'd appreciate any help :)
Thanks and Regards,
Chris
public static CommonTree parseJava(String filename) throws
RecognitionException {
ANTLRFileStream fs = null;
try {
fs = new ANTLRFileStream(filename);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final TreeAdaptor adaptor = new CommonTreeAdaptor() {
public Object create(Token payload) {
CommonTree t = new CommonTree(payload);
return t;
}
};
JavaScriptLexer lex = new JavaScriptLexer(fs);
TokenRewriteStream tokens = new TokenRewriteStream(lex);
JavaScriptParser grammar = new JavaScriptParser(tokens);
JavaScriptParser.program_return ret = null;
grammar.setTreeAdaptor(adaptor);
StdErrReporter errorReporter = new StdErrReporter();
grammar.setErrorReporter(errorReporter);
lex.setErrorReporter(errorReporter);
ret = grammar.program();
if (errorReporter.error()) {
printTree((CommonTree) ret.getTree(), 0);
throw new RuntimeException("Parser/Lexer failure");
}
return (CommonTree)ret.getTree();
}
More information about the antlr-interest
mailing list