Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用EclipseAST检查Java代码片段_Java_Eclipse_Syntax_Abstract Syntax Tree - Fatal编程技术网

使用EclipseAST检查Java代码片段

使用EclipseAST检查Java代码片段,java,eclipse,syntax,abstract-syntax-tree,Java,Eclipse,Syntax,Abstract Syntax Tree,我试图使用eclipse抽象语法树检查一些Java代码片段的语法和逻辑正确性 我做了一些关于如何做到这一点的研究,我阅读了文档,但我还没有找到一个明确的例子 所以,我想检查一组语句的正确性,比如: System.out.println("I'm doing something"); callAMethod(7); System.out.println("I'm done");**sdsds** 差不多吧。你说得对。在这里,sdsds应显示为错误 我的问题是如何检测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
    }
}

希望有人能帮助我。非常感谢

如果将解析器种类更改为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());
    }

您提供的“不正确”示例在语法或逻辑上都不正确。只有在整个Java应用程序中没有包“Sy7stem”时,才是语义错误的。解析器不知道这一点;您必须超越解析到名称和类型解析(实际上,您只能在整个程序上进行解析)。尝试一个不同的解析,一个显然被破坏的解析,比如涉及文本[;],它在任何情况下都不是有效的Java语法。谢谢。您对我的示例完全正确。我编辑了问题,示例现在很好(我认为)。代码仍然不起作用。:(我不知道Eclipse解析器API的细节,所以我不知道如何帮助您检查“糟糕的语法”是否起作用。我只想说明,您对解析器的期望是“糟糕的语法”;您无法获得“逻辑正确性”(如果它与“语法有效性”不同,那么这意味着什么)。如果您需要执行比语法更复杂的检查,那么整个方法是不完整的或不起作用的。Eclipse API可能会提供更多帮助。谢谢。它以某种方式工作。问题是,无论我向解析器提供什么文本,第一个问题始终是:标记“++”上的语法错误,*应在该标记0之前。即使输入中的任何位置都没有“++”。这种行为的原因是什么?请再说一遍Thx:)