How could I search references to a field on a AST

2019-08-10 12:27发布

问题:

Hi,

I'm developing an Eclipse plugin. I need to find all the references in the source using AST's or jdt.core.dom or something like that. I need this references like ASTNodes in order to get the parent node and check several things in the expression where references are involved. Thanks beforehand.


Edited:

I want to concrete a little more, My problem is that I try to catch some references to a constant but... I have not idea how I can do to catch in the matches this references. I need check the expressions which the references to a determined constant are involved. I only get the source of the method where they are used.

I think the problem is the scope or the pattern:

pattern = SearchPattern.createPattern(field, IJavaSearchConstants.REFERENCES);


scope = SearchEngine.createJavaSearchScope(declaringType.getMethods());

Thanks beforehand!

回答1:

I used something like:

  1. Search for the declaration of an method, returns an IMethod
  2. Search for references to the IMethod, record those IMethods
  3. For each IMethod returned, create an AST from its compilation unit

Searching for declarations or references looks like the following code.

SearchRequestor findMethod = ...; // do something with the search results
SearchEngine engine = new SearchEngine();
IJavaSearchScope workspaceScope = SearchEngine.createWorkspaceScope();
SearchPattern pattern = SearchPattern.createPattern(searchString,
            IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS,
            SearchPattern.R_EXACT_MATCH);
SearchParticipant[] participant = new SearchParticipant[] { SearchEngine
            .getDefaultSearchParticipant() };
engine.search(pattern, participant, workspaceScope, findMethod,
                monitor);

Once you have your IMethod references, you can get to the AST using:

ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setResolveBindings(true);
if (methodToSearch.isBinary()) {
    parser.setSource(methodToSearch.getClassFile());
} else {
    parser.setSource(methodToSearch.getCompilationUnit());
}
CompilationUnit cu = (CompilationUnit) parser.createAST(null);

See http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.jdt.doc.isv/guide/jdt_int_core.htm for more details on java search, the java model, and the AST.