[英]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. 我正在尝试使用eclipse抽象语法树检查某些Java代码片段的语法和逻辑正确性。
I did some research on how this 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. 在此,应该将sdsds发出错误信号。
My question is how can I detect if the Java text is incorrect syntactically or lexically? 我的问题是如何检测Java文本在语法上还是词法上不正确? 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. 如果将解析器类型更改为K_COMPILATION_UNIT并调用解析器,则可以向返回的编译单元询问问题。
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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.