I am writing a plugin that reads a java project and in a case that there is any compiler error in the program, it uses Eclipse JDT Quick fix to extract possible solutions to fix the compiler errors. The code that is used to find error and eclipse solution for an input compilation unit is as below:
private void collectCorrections(final ICompilationUnit cu, final CompilationUnit astRoot) {
ArrayList<IProblem> problems = new ArrayList<IProblem>();
for (IProblem iProblem : astRoot.getProblems())
if (iProblem.isError()) problems.add(iProblem);
Map<IProblem, ArrayList<IJavaCompletionProposal>> ErrorproposalsMap = new HashMap<IProblem, ArrayList<IJavaCompletionProposal>>();
for (IProblem iProblem : problems) {
int offset = iProblem.getSourceStart();
int length = iProblem.getSourceEnd() + 1 - offset;
context = new AssistContext(cu, offset, length);
}
ProblemLocation problem = new ProblemLocation(iProblem);
ArrayList<IJavaCompletionProposal> proposals = new ArrayList<IJavaCompletionProposal>();
JavaCorrectionProcessor.collectCorrections(context, new IProblemLocation[] { problem }, proposals);
ErrorproposalsMap.put(iProblem, proposals);
}
I use both iProblem and proposals to get more detailed information about the error and solution. As an example I use iProblem.getOriginatingFileName() to extract the file where the error happens. However, the problem I am facing is that I do not know how to extract comilationUnit of class that need to be change to fix the error.
As a simple example, when we have a reference to a private filed (defined in class1) from another class (class2), we have a compiler error. In this case I need to extract compilationUnit for class1. Note that getOriginatingFileName return class2.
Please let me know how can I extract directly comilationUnit of class1 using org.eclipse.jdt.core.compiler.IProblem, and IJavaCompletionProposal.
You can use getCompilationUnit() defined in CUCorrectionProposal to extract CompilationUnit of class1. Note that LinkedCorrectionProposal extends CUCorrectionProposal. However, I am not sure all eclipse CorrectionProposal extend LinkedCorrectionProposal. Check it.
The solution can be like this.
CUCorrectionProposal cUCorrectionProposal = (CUCorrectionProposal) eclipseProposal;
ICompilationUnit iCompilationUnit = cUCorrectionProposal.getCompilationUnit();
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(iCompilationUnit );
CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);