0

我想对Java源代码做一些静态代码分析。对于解析,我在 EclipseASTParser之外使用 Eclipse JDT (3.6),代码如下:

private static final Map<String, String> COMPILER_OPTIONS;

static {
    COMPILER_OPTIONS = new HashMap<String, String>(JavaCore.getOptions());
    COMPILER_OPTIONS.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_6);
    COMPILER_OPTIONS.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_6);
    COMPILER_OPTIONS.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6);
}

private CompilationUnit parseReadSourceFileIfPossible(String readSourceFile) {
    CompilationUnit result = null;
    if (isPossibleToParse(readSourceFile)) {
        final ASTParser parser = createAndConfigureParser();
        parser.setSource(readSourceFile.toCharArray());
        result = (CompilationUnit) parser.createAST(null);
    }
    return result;
}

private ASTParser createAndConfigureParser() {
    final ASTParser result = ASTParser.newParser(AST.JLS3);
    result.setKind(ASTParser.K_COMPILATION_UNIT);
    result.setCompilerOptions(COMPILER_OPTIONS); return result;
}

对于“普通”Java 类,这种方法非常有效。但是,如果我解析以下类 ( ValidUnrestrictedComponent),解析器就会遇到问题。

package valid;

import de.htwg_konstanz.joi.annotations.JoiComponten;

@JoiComponent
public final class ValidUnrestrictedComponent {

    private static final class Implementation implements TestInterface {

        @Override
        public int doSomething() {
            // TODO Auto-generated method stub
            return 0;
        }
    }

    private ValidUnrestrictedComponent() {
        throw new AssertionError();
    }

    public static Implementation getInstance() {
        return new Implementation();
    }

    private static void getNothing() {
      // Nothing to do here
    }

    private void doNothing() {
      // Nothing to do here
    }

}

我确实收到了一个 type 的对象CompilationUnit,但它只包含嵌套成员Implementation及其方法。班上的其他人——喜欢 getInstancedoNothing不见了。

得到的CompilationUnit包含一个字段problems,存在以下三个问题:

  • DefaultProblem (id=141): Pb(240) 语法错误,插入“}”完成ClassBody
  • DefaultProblem (id=143): Pb(240) Syntax error, insert "}" to complete ClassBody
  • DefaultProblem (id=164): Pb(240) Syntax error, insert "}" to complete MethodBody

I can not see any syntax errors in the above mentioned class ValidUnrestrictedComponent.

4

1 回答 1

0

Can you double check the contents of 'readSourceFile'? My guess is that there are no '\n' or new line characters in that. Missing new-line characters would result in all the lines after the first comment becoming part of the comment itself.

于 2012-06-13T08:33:03.900 回答