Checking Java code fragments using eclipse AST
I'm trying to check for syntactical and logical correctness some Java code fragments using the eclipse abstract syntax tree.
I did some research on how th开发者_C百科is could be done, I read the documentation, but I haven't found a clear example.
So, I want to check for correctness a set of statements, something like:
System.out.println("I'm doing something");
callAMethod(7);
System.out.println("I'm done");**sdsds**
Something like that. You got the point. Here, sdsds should be signaled as erroneous.
My question is how can I detect if the Java text is incorrect syntactically or lexically? And how can I get the messages describing the errors?
My code for that is:
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_STATEMENTS);
parser.setSource(textToParse.toCharArray());
parser.setResolveBindings(false);
ASTNode node = (ASTNode) parser.createAST(null);
// If MALFORMED bit is 1, then we have an error. The position of MALFORMED
being 1, then this should detect the error. **But it doesn't. What's the problem?**
if (node.getFlags() % 2 == 1) {
// error detected
}
if (node instanceof CompilationUnit) {
// there are severe parsing errors (unrecognized characters for example)
if (((CompilationUnit) node).getProblems().length != 0) {
// error detected
}
}
Hope somebody can help me. Thanks a lot!
If you change the parser kind to K_COMPILATION_UNIT and invoke the parser then you can ask the returned compilation unit for problems.
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
IProblem[] problems = cu.getProblems();
for(IProblem problem : problems) {
System.out.println("problem: " + problem.getMessage() + problem.getSourceStart());
}
精彩评论