My question sounds a bit trivial; however, I was not able to find anything useful on google. So here it goes, Is there a way to get an element of a given AST if I know its start position?
I want to find the malformed elements that were flagged as errors in a compilation unit, I already know the source position by calling the function getSourceStart()
. Any idea, link, comment are greatly appreciated.
Code:
IResource res = delta.getResource();
if (res instanceof IFile && res.isAccessible()) {
IJavaElement element = JavaCore.create((IFile)res);
if (element instanceof ICompilationUnit) {
ICompilationUnit icu = (ICompilationUnit)element;
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(icu);
parser.setResolveBindings(true);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
IProblem[] problems = cu.getProblems();
for(IProblem problem : problems) {
String args[] = problem.getArguments();
int source = problem.getSourceStart();
//Get Element that is at that point...
//Should I traverse the AST?
//Also problem.getArguments() if not null will provide the type of that element, not the name.
}
}
}
I assume you are looking for the smallest AST node that spans the problem source location. Since you are specifically looking at problems, you might find that when there are certain kinds of syntax errors, the AST produced is extremely wacky.
Nonetheless, I am a little surprised that there is no pre-baked solution. You will have to create your own ASTVisitor. It will look something like this:
class MyFinder extends ASTVisitor {
public void postVisit(ASTNode node) {
if (spansProblemLocation(node)) {
throw new VisitComplete(node);
}
}
}
class VisitComplete extends Throwable {
ASTNode result;
...
}
Since we override the postVisit method, we are guaranteed to get the smallest ASTNode as the result. To use this visitor, wrap the call to accept
in a try-catch block that handles VisitComplete
.