下面列出了怎么用org.eclipse.jdt.core.dom.NodeFinder的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
super.addEdits(doc, root);
// build a full AST
CompilationUnit unit = CoreASTProvider.getInstance().getAST(getCompilationUnit(), CoreASTProvider.WAIT_YES, null);
ASTNode name= NodeFinder.perform(unit, fOffset, fLength);
if (name instanceof SimpleName) {
SimpleName[] names= LinkedNodeFinder.findByProblems(unit, (SimpleName) name);
if (names != null) {
for (int i= 0; i < names.length; i++) {
SimpleName curr= names[i];
root.addChild(new ReplaceEdit(curr.getStartPosition(), curr.getLength(), fNewName));
}
return;
}
}
root.addChild(new ReplaceEdit(fOffset, fLength, fNewName));
}
private boolean shouldIncludeDefinition(ITypeRoot typeRoot, IRegion region, IJavaElement elementToSearch, List<Location> implementations) {
boolean isUnimplemented = false;
try {
isUnimplemented = isUnimplementedMember(elementToSearch);
} catch (JavaModelException e) {
// do nothing.
}
if (isUnimplemented && implementations != null && !implementations.isEmpty()) {
return false;
}
CompilationUnit ast = CoreASTProvider.getInstance().getAST(typeRoot, CoreASTProvider.WAIT_YES, new NullProgressMonitor());
if (ast == null) {
return false;
}
ASTNode node = NodeFinder.perform(ast, region.getOffset(), region.getLength());
if (node instanceof SimpleName && !(node.getParent() instanceof MethodDeclaration || node.getParent() instanceof SuperMethodInvocation || node.getParent() instanceof AbstractTypeDeclaration)) {
return true;
}
return false;
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
try {
pm.beginTask(RefactoringCoreMessages.MoveMembersRefactoring_checking, 1);
RefactoringStatus result= new RefactoringStatus();
result.merge(checkDeclaringType());
pm.worked(1);
if (result.hasFatalError())
return result;
fSource= new CompilationUnitRewrite(fMembersToMove[0].getCompilationUnit());
fSourceBinding= (ITypeBinding)((SimpleName)NodeFinder.perform(fSource.getRoot(), fMembersToMove[0].getDeclaringType().getNameRange())).resolveBinding();
fMemberBindings= getMemberBindings();
if (fSourceBinding == null || hasUnresolvedMemberBinding()) {
result.addFatalError(Messages.format(
RefactoringCoreMessages.MoveMembersRefactoring_compile_errors,
BasicElementLabels.getFileName(fSource.getCu())));
}
fMemberDeclarations= getASTMembers(result);
return result;
} finally {
pm.done();
}
}
private BodyDeclaration[] getASTMembers(RefactoringStatus status) throws JavaModelException {
BodyDeclaration[] result= new BodyDeclaration[fMembersToMove.length];
for (int i= 0; i < fMembersToMove.length; i++) {
IMember member= fMembersToMove[i];
ASTNode node= NodeFinder.perform(fSource.getRoot(), member.getNameRange());
result[i]= (BodyDeclaration)ASTNodes.getParent(node, BodyDeclaration.class);
//Fix for bug 42383: exclude multiple VariableDeclarationFragments ("int a=1, b=2")
//ReferenceAnalyzer#visit(FieldDeclaration node) depends on fragments().size() != 1 !
if (result[i] instanceof FieldDeclaration
&& ((FieldDeclaration) result[i]).fragments().size() != 1) {
status.addFatalError(RefactoringCoreMessages.MoveMembersRefactoring_multi_var_fields);
return result;
}
}
//Sorting members is important for field declarations referring to previous fields.
Arrays.sort(result, new Comparator<BodyDeclaration>() {
public int compare(BodyDeclaration o1, BodyDeclaration o2) {
return o1.getStartPosition() - o2.getStartPosition();
}
});
return result;
}
private RefactoringStatus createExceptionInfoList() {
if (fExceptionInfos == null || fExceptionInfos.isEmpty()) {
fExceptionInfos= new ArrayList<ExceptionInfo>(0);
try {
ASTNode nameNode= NodeFinder.perform(fBaseCuRewrite.getRoot(), fMethod.getNameRange());
if (nameNode == null || !(nameNode instanceof Name) || !(nameNode.getParent() instanceof MethodDeclaration))
return null;
MethodDeclaration methodDeclaration= (MethodDeclaration) nameNode.getParent();
List<Type> exceptions= methodDeclaration.thrownExceptionTypes();
List<ExceptionInfo> result= new ArrayList<ExceptionInfo>(exceptions.size());
for (int i= 0; i < exceptions.size(); i++) {
Type type= exceptions.get(i);
ITypeBinding typeBinding= type.resolveBinding();
if (typeBinding == null)
return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_no_exception_binding);
IJavaElement element= typeBinding.getJavaElement();
result.add(ExceptionInfo.createInfoForOldException(element, typeBinding));
}
fExceptionInfos= result;
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return null;
}
private void initAST(IProgressMonitor pm) {
if (fCompilationUnitNode == null) {
fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, pm);
}
if (fAnonymousInnerClassNode == null) {
fAnonymousInnerClassNode= getAnonymousInnerClass(NodeFinder.perform(fCompilationUnitNode, fSelectionStart, fSelectionLength));
}
if (fAnonymousInnerClassNode != null) {
final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class);
if (declaration instanceof TypeDeclaration) {
final AbstractTypeDeclaration[] nested= ((TypeDeclaration) declaration).getTypes();
fClassNamesUsed= new HashSet<String>(nested.length);
for (int index= 0; index < nested.length; index++)
fClassNamesUsed.add(nested[index].getName().getIdentifier());
} else
fClassNamesUsed= Collections.emptySet();
}
}
private Name findConstantNameNode() {
ASTNode node= NodeFinder.perform(fSelectionCuRewrite.getRoot(), fSelectionStart, fSelectionLength);
if (node == null)
return null;
if (node instanceof FieldAccess)
node= ((FieldAccess) node).getName();
if (!(node instanceof Name))
return null;
Name name= (Name) node;
IBinding binding= name.resolveBinding();
if (!(binding instanceof IVariableBinding))
return null;
IVariableBinding variableBinding= (IVariableBinding) binding;
if (!variableBinding.isField() || variableBinding.isEnumConstant())
return null;
int modifiers= binding.getModifiers();
if (! (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)))
return null;
return name;
}
private void initDomAST() {
if (isReadOnly())
return;
ASTParser parser= ASTParser.newParser(AST.JLS8);
parser.setSource(getCompilationUnit());
parser.setResolveBindings(true);
org.eclipse.jdt.core.dom.ASTNode domAst = parser.createAST(new NullProgressMonitor());
// org.eclipse.jdt.core.dom.AST ast = domAst.getAST();
NodeFinder nf = new NodeFinder(domAst, getCompletionOffset(), 1);
org.eclipse.jdt.core.dom.ASTNode cv = nf.getCoveringNode();
bodyDeclaration = ASTResolving.findParentBodyDeclaration(cv);
parentDeclaration = ASTResolving.findParentType(cv);
domInitialized = true;
}
/**
* Finds and returns the <code>ASTNode</code> for the given source text
* selection, if it is an entire constructor call or the class name portion
* of a constructor call or constructor declaration, or null otherwise.
* @param unit The compilation unit in which the selection was made
* @param offset The textual offset of the start of the selection
* @param length The length of the selection in characters
* @return ClassInstanceCreation or MethodDeclaration
*/
private ASTNode getTargetNode(ICompilationUnit unit, int offset, int length) {
ASTNode node= ASTNodes.getNormalizedNode(NodeFinder.perform(fCU, offset, length));
if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
return node;
if (node.getNodeType() == ASTNode.METHOD_DECLARATION && ((MethodDeclaration)node).isConstructor())
return node;
// we have some sub node. Make sure its the right child of the parent
StructuralPropertyDescriptor location= node.getLocationInParent();
ASTNode parent= node.getParent();
if (location == ClassInstanceCreation.TYPE_PROPERTY) {
return parent;
} else if (location == MethodDeclaration.NAME_PROPERTY && ((MethodDeclaration)parent).isConstructor()) {
return parent;
}
return null;
}
/**
* Generates a new setter method for the specified field
*
* @param field the field
* @param astRewrite the AST rewrite to use
* @param rewrite the list rewrite to use
* @throws CoreException if an error occurs
* @throws OperationCanceledException if the operation has been cancelled
*/
private void generateSetterMethod(final IField field, ASTRewrite astRewrite, final ListRewrite rewrite) throws CoreException, OperationCanceledException {
final IType type= field.getDeclaringType();
final String name= GetterSetterUtil.getSetterName(field, null);
final IMethod existing= JavaModelUtil.findMethod(name, new String[] { field.getTypeSignature()}, false, type);
if (existing == null || !querySkipExistingMethods(existing)) {
IJavaElement sibling= null;
if (existing != null) {
sibling= StubUtility.findNextSibling(existing);
removeExistingAccessor(existing, rewrite);
} else
sibling= fInsert;
ASTNode insertion= StubUtility2.getNodeToInsertBefore(rewrite, sibling);
addNewAccessor(type, field, GetterSetterUtil.getSetterStub(field, name, fSettings.createComments, fVisibility | (field.getFlags() & Flags.AccStatic)), rewrite, insertion);
if (Flags.isFinal(field.getFlags())) {
ASTNode fieldDecl= ASTNodes.getParent(NodeFinder.perform(fASTRoot, field.getNameRange()), FieldDeclaration.class);
if (fieldDecl != null) {
ModifierRewrite.create(astRewrite, fieldDecl).setModifiers(0, Modifier.FINAL, null);
}
}
}
}
private int findInHierarchyWithAST(CompilationUnit astRoot, IMethod method) throws JavaModelException {
ASTNode node= NodeFinder.perform(astRoot, method.getNameRange());
if (node instanceof SimpleName && node.getParent() instanceof MethodDeclaration) {
IMethodBinding binding= ((MethodDeclaration) node.getParent()).resolveBinding();
if (binding != null) {
IMethodBinding defining= Bindings.findOverriddenMethod(binding, true);
if (defining != null) {
if (JdtFlags.isAbstract(defining)) {
return JavaElementImageDescriptor.IMPLEMENTS;
} else {
return JavaElementImageDescriptor.OVERRIDES;
}
}
return 0;
}
}
return -1;
}
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
super.addEdits(doc, root);
// build a full AST
CompilationUnit unit= SharedASTProvider.getAST(getCompilationUnit(), SharedASTProvider.WAIT_YES, null);
ASTNode name= NodeFinder.perform(unit, fOffset, fLength);
if (name instanceof SimpleName) {
SimpleName[] names= LinkedNodeFinder.findByProblems(unit, (SimpleName) name);
if (names != null) {
for (int i= 0; i < names.length; i++) {
SimpleName curr= names[i];
root.addChild(new ReplaceEdit(curr.getStartPosition(), curr.getLength(), fNewName));
}
return;
}
}
root.addChild(new ReplaceEdit(fOffset, fLength, fNewName));
}
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
if (!(getEditor() instanceof JavaEditor))
return null;
ITypeRoot je= getEditorInputJavaElement();
if (je == null)
return null;
// Never wait for an AST in UI thread.
CompilationUnit ast= SharedASTProvider.getAST(je, SharedASTProvider.WAIT_NO, null);
if (ast == null)
return null;
ASTNode node= NodeFinder.perform(ast, offset, 1);
if (node instanceof StringLiteral) {
StringLiteral stringLiteral= (StringLiteral)node;
return new Region(stringLiteral.getStartPosition(), stringLiteral.getLength());
} else if (node instanceof SimpleName) {
SimpleName simpleName= (SimpleName)node;
return new Region(simpleName.getStartPosition(), simpleName.getLength());
}
return null;
}
private static ASTNode getHoveredASTNode(ITypeRoot typeRoot, IRegion region) {
if (typeRoot == null || region == null) {
return null;
}
CompilationUnit unit = SharedASTProviderCore.getAST(typeRoot, SharedASTProviderCore.WAIT_ACTIVE_ONLY, null);
if (unit == null) {
return null;
}
return NodeFinder.perform(unit, region.getOffset(), region.getLength());
}
private static ASTNode findNode(ISourceRange range, CompilationUnit cuNode){
NodeFinder nodeFinder= new NodeFinder(cuNode, range.getOffset(), range.getLength());
ASTNode coveredNode= nodeFinder.getCoveredNode();
if (coveredNode != null) {
return coveredNode;
} else {
return nodeFinder.getCoveringNode();
}
}
public static ASTNode findNode(SearchMatch searchResult, CompilationUnit cuNode) {
ASTNode selectedNode= NodeFinder.perform(cuNode, searchResult.getOffset(), searchResult.getLength());
if (selectedNode == null) {
return null;
}
if (selectedNode.getParent() == null) {
return null;
}
return selectedNode;
}
private void initAST() {
if (!fIsComposite) {
fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, null);
}
ISourceRange sourceRange= fLocalVariable.getNameRange();
ASTNode name= NodeFinder.perform(fCompilationUnitNode, sourceRange);
if (name == null) {
return;
}
if (name.getParent() instanceof VariableDeclaration) {
fTempDeclarationNode= (VariableDeclaration) name.getParent();
}
}
/**
* This method analyzes a set of local variable renames inside one cu. It checks whether
* any new compile errors have been introduced by the rename(s) and whether the correct
* node(s) has/have been renamed.
*
* @param analyzePackages the LocalAnalyzePackages containing the information about the local renames
* @param cuChange the TextChange containing all local variable changes to be applied.
* @param oldCUNode the fully (incl. bindings) resolved AST node of the original compilation unit
* @param recovery whether statements and bindings recovery should be performed when parsing the changed CU
* @return a RefactoringStatus containing errors if compile errors or wrongly renamed nodes are found
* @throws CoreException thrown if there was an error greating the preview content of the change
*/
public static RefactoringStatus analyzeLocalRenames(LocalAnalyzePackage[] analyzePackages, TextChange cuChange, CompilationUnit oldCUNode, boolean recovery) throws CoreException {
RefactoringStatus result= new RefactoringStatus();
ICompilationUnit compilationUnit= (ICompilationUnit) oldCUNode.getJavaElement();
String newCuSource= cuChange.getPreviewContent(new NullProgressMonitor());
CompilationUnit newCUNode= new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(newCuSource, compilationUnit, true, recovery, null);
result.merge(analyzeCompileErrors(newCuSource, newCUNode, oldCUNode));
if (result.hasError()) {
return result;
}
for (int i= 0; i < analyzePackages.length; i++) {
ASTNode enclosing= getEnclosingBlockOrMethodOrLambda(analyzePackages[i].fDeclarationEdit, cuChange, newCUNode);
// get new declaration
IRegion newRegion= RefactoringAnalyzeUtil.getNewTextRange(analyzePackages[i].fDeclarationEdit, cuChange);
ASTNode newDeclaration= NodeFinder.perform(newCUNode, newRegion.getOffset(), newRegion.getLength());
Assert.isTrue(newDeclaration instanceof Name);
VariableDeclaration declaration= getVariableDeclaration((Name) newDeclaration);
Assert.isNotNull(declaration);
SimpleName[] problemNodes= ProblemNodeFinder.getProblemNodes(enclosing, declaration, analyzePackages[i].fOccurenceEdits, cuChange);
result.merge(RefactoringAnalyzeUtil.reportProblemNodes(newCuSource, problemNodes));
}
return result;
}
public static ASTNode getInlineableMethodNode(ITypeRoot typeRoot, CompilationUnit root, int offset, int length) {
ASTNode node = null;
try {
node = getInlineableMethodNode(NodeFinder.perform(root, offset, length, typeRoot), typeRoot);
} catch (JavaModelException e) {
// Do nothing
}
if (node != null) {
return node;
}
return getInlineableMethodNode(NodeFinder.perform(root, offset, length), typeRoot);
}
@Override
public boolean visit(Assignment node) {
boolean result = super.visit(node);
Selection selection = getSelection();
ASTNode selectedNode = NodeFinder.perform(node, selection.getOffset(), selection.getLength());
if ((selectedNode != null && SnippetFinder.isLeftHandSideOfAssignment(selectedNode)) || (selection.covers(node.getLeftHandSide()) && !selection.covers(node.getRightHandSide()))) {
invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_leftHandSideOfAssignment, JavaStatusContext.create(fCUnit, node));
return false;
}
return result;
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
if (fVisibility < 0) {
fVisibility = (fField.getFlags() & (Flags.AccPublic | Flags.AccProtected | Flags.AccPrivate));
}
RefactoringStatus result = new RefactoringStatus();
result.merge(Checks.checkAvailability(fField));
if (result.hasFatalError()) {
return result;
}
fRoot = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(fField.getCompilationUnit(), true, pm);
ISourceRange sourceRange = fField.getNameRange();
ASTNode node = NodeFinder.perform(fRoot, sourceRange.getOffset(), sourceRange.getLength());
if (node == null) {
return mappingErrorFound(result, node);
}
fFieldDeclaration = ASTNodes.getParent(node, VariableDeclarationFragment.class);
if (fFieldDeclaration == null) {
return mappingErrorFound(result, node);
}
if (fFieldDeclaration.resolveBinding() == null) {
if (!processCompilerError(result, node)) {
result.addFatalError(RefactoringCoreMessages.SelfEncapsulateField_type_not_resolveable);
}
return result;
}
computeUsedNames();
return result;
}
/**
* Finds the comment that contains the specified position
*
* @param comments
* @param offset
* @return
*/
public ASTNode containingComment(List<Comment> comments, int offset) {
for (Comment comment : comments) {
ASTNode result = NodeFinder.perform(comment, offset, 0);
if (result != null) {
return result;
}
}
return null;
}
private AbstractTypeDeclaration getDestinationNode() throws JavaModelException {
AbstractTypeDeclaration destination= (AbstractTypeDeclaration)
ASTNodes.getParent(
NodeFinder.perform(fTarget.getRoot(), fDestinationType.getNameRange()),
AbstractTypeDeclaration.class);
return destination;
}
private ITypeBinding getDestinationBinding() throws JavaModelException {
ASTNode node= NodeFinder.perform(fTarget.getRoot(), fDestinationType.getNameRange());
if (!(node instanceof SimpleName))
return null;
IBinding binding= ((SimpleName)node).resolveBinding();
if (!(binding instanceof ITypeBinding))
return null;
return (ITypeBinding)binding;
}
private IBinding[] getMemberBindings() throws JavaModelException {
IBinding[] result= new IBinding[fMembersToMove.length];
for (int i= 0; i < fMembersToMove.length; i++) {
IMember member= fMembersToMove[i];
SimpleName name= (SimpleName)NodeFinder.perform(fSource.getRoot(), member.getNameRange());
result[i]= name.resolveBinding();
}
return result;
}
private ASTNode findDeclaration(CompilationUnit root, ConstraintVariable cv) throws JavaModelException {
if (fFieldBinding != null){
IField f= (IField) fFieldBinding.getJavaElement();
return ASTNodeSearchUtil.getFieldDeclarationNode(f, root);
}
if (cv instanceof ExpressionVariable){
for (Iterator<ITypeConstraint> iter= fAllConstraints.iterator(); iter.hasNext();) {
ITypeConstraint constraint= iter.next();
if (constraint.isSimpleTypeConstraint()){
SimpleTypeConstraint stc= (SimpleTypeConstraint)constraint;
if (stc.isDefinesConstraint() && stc.getLeft().equals(cv)){
ConstraintVariable right= stc.getRight();
if (right instanceof TypeVariable){
TypeVariable typeVariable= (TypeVariable)right;
return NodeFinder.perform(root, typeVariable.getCompilationUnitRange().getSourceRange());
}
}
}
}
} else if (cv instanceof ReturnTypeVariable) {
ReturnTypeVariable rtv= (ReturnTypeVariable) cv;
IMethodBinding mb= rtv.getMethodBinding();
IMethod im= (IMethod) mb.getJavaElement();
return ASTNodeSearchUtil.getMethodDeclarationNode(im, root);
}
return null;
}
private static ASTNode findNode(ISourceRange range, CompilationUnit cuNode){
NodeFinder nodeFinder= new NodeFinder(cuNode, range.getOffset(), range.getLength());
ASTNode coveredNode= nodeFinder.getCoveredNode();
if (coveredNode != null)
return coveredNode;
else
return nodeFinder.getCoveringNode();
}
public static ASTNode findNode(SearchMatch searchResult, CompilationUnit cuNode) {
ASTNode selectedNode= NodeFinder.perform(cuNode, searchResult.getOffset(), searchResult.getLength());
if (selectedNode == null)
return null;
if (selectedNode.getParent() == null)
return null;
return selectedNode;
}
private void initAST() {
if (!fIsComposite)
fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, null);
ISourceRange sourceRange= fLocalVariable.getNameRange();
ASTNode name= NodeFinder.perform(fCompilationUnitNode, sourceRange);
if (name == null)
return;
if (name.getParent() instanceof VariableDeclaration)
fTempDeclarationNode= (VariableDeclaration) name.getParent();
}
/**
* This method analyzes a set of local variable renames inside one cu. It checks whether
* any new compile errors have been introduced by the rename(s) and whether the correct
* node(s) has/have been renamed.
*
* @param analyzePackages the LocalAnalyzePackages containing the information about the local renames
* @param cuChange the TextChange containing all local variable changes to be applied.
* @param oldCUNode the fully (incl. bindings) resolved AST node of the original compilation unit
* @param recovery whether statements and bindings recovery should be performed when parsing the changed CU
* @return a RefactoringStatus containing errors if compile errors or wrongly renamed nodes are found
* @throws CoreException thrown if there was an error greating the preview content of the change
*/
public static RefactoringStatus analyzeLocalRenames(LocalAnalyzePackage[] analyzePackages, TextChange cuChange, CompilationUnit oldCUNode, boolean recovery) throws CoreException {
RefactoringStatus result= new RefactoringStatus();
ICompilationUnit compilationUnit= (ICompilationUnit) oldCUNode.getJavaElement();
String newCuSource= cuChange.getPreviewContent(new NullProgressMonitor());
CompilationUnit newCUNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(newCuSource, compilationUnit, true, recovery, null);
result.merge(analyzeCompileErrors(newCuSource, newCUNode, oldCUNode));
if (result.hasError())
return result;
for (int i= 0; i < analyzePackages.length; i++) {
ASTNode enclosing= getEnclosingBlockOrMethodOrLambda(analyzePackages[i].fDeclarationEdit, cuChange, newCUNode);
// get new declaration
IRegion newRegion= RefactoringAnalyzeUtil.getNewTextRange(analyzePackages[i].fDeclarationEdit, cuChange);
ASTNode newDeclaration= NodeFinder.perform(newCUNode, newRegion.getOffset(), newRegion.getLength());
Assert.isTrue(newDeclaration instanceof Name);
VariableDeclaration declaration= getVariableDeclaration((Name) newDeclaration);
Assert.isNotNull(declaration);
SimpleName[] problemNodes= ProblemNodeFinder.getProblemNodes(enclosing, declaration, analyzePackages[i].fOccurenceEdits, cuChange);
result.merge(RefactoringAnalyzeUtil.reportProblemNodes(newCuSource, problemNodes));
}
return result;
}