使用 eclipse AST 检查 Java 代码片段
我正在尝试使用 eclipse 抽象语法树检查一些 Java 代码片段的语法和逻辑正确性。
我对如何做到这一点做了一些研究,我阅读了文档,但我还没有找到明确的例子。
所以,我想检查一组陈述的正确性,例如:
System.out.println("I'm doing something");
callAMethod(7);
System.out.println("I'm done");**sdsds**
类似的东西。你明白了。此处,sdsds 应被标记为错误。
我的问题是如何检测 Java 文本在语法或词汇上是否不正确?我怎样才能得到描述错误的消息?
我的代码是:
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
}
}
希望有人能帮助我。多谢!
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 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.
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果将解析器类型更改为 K_COMPILATION_UNIT 并调用解析器,则可以向返回的编译单元询问问题。
If you change the parser kind to K_COMPILATION_UNIT and invoke the parser then you can ask the returned compilation unit for problems.