I would like to do some static code analysis for Java source code. For parsing I use the Eclipse JDT (3.6) ASTParser outside of Eclipse with following code:
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;
}
For “normal” Java classes this approach works perfectly fine. However if I
parse the following class (ValidUnrestrictedComponent), the parser runs
into problems.
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
}
}
I do receive an object of type CompilationUnit, however it does only contain the
nested member Implementation and its method. The rest of the class – like
getInstance or doNothing is missing.
The obtained CompilationUnit contains a field problems with the following
three problems:
- DefaultProblem (id=141): Pb(240) Syntax error, insert “}” to complete 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.
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.