private static void rename(
     PsiReference ref, String newName, PsiManager manager, PsiMember elementToResolve) {
   final PsiElement renamed = ref.handleElementRename(newName);
   PsiElement newly_resolved = ref.resolve();
   if (!manager.areElementsEquivalent(newly_resolved, elementToResolve)) {
     if (newly_resolved instanceof PsiMethod) {
       newly_resolved =
           GroovyPropertyUtils.findFieldForAccessor((PsiMethod) newly_resolved, false);
     }
     if (!manager.areElementsEquivalent(newly_resolved, elementToResolve)) {
       qualify(elementToResolve, renamed, newName);
     }
   }
 }
  private static boolean isGetterInvocation(@NotNull GrMethodCall call) {
    GrExpression expr = call.getInvokedExpression();
    if (!(expr instanceof GrReferenceExpression)) return false;

    PsiMethod method = call.resolveMethod();
    if (!GroovyPropertyUtils.isSimplePropertyGetter(method)) return false;
    LOG.assertTrue(method != null);
    if (!GroovyNamesUtil.isValidReference(
        GroovyPropertyUtils.getPropertyNameByGetterName(method.getName(), true),
        ((GrReferenceExpression) expr).getQualifier() != null,
        call.getProject())) {
      return false;
    }

    GrArgumentList args = call.getArgumentList();
    if (args == null || args.getAllArguments().length != 0) {
      return false;
    }

    GrExpression ref = genRefForGetter(call, ((GrReferenceExpression) expr).getReferenceName());
    if (ref instanceof GrReferenceExpression) {
      PsiElement resolved = ((GrReferenceExpression) ref).resolve();
      PsiManager manager = call.getManager();
      if (manager.areElementsEquivalent(resolved, method)
          || areEquivalentAccessors(method, resolved, manager)) {
        return true;
      }
    }

    return false;
  }
 @Nullable
 private static PsiClass getFieldOrMethodAccessedClass(
     PsiReferenceExpression ref, PsiClass fieldOrMethodClass) {
   PsiElement[] children = ref.getChildren();
   if (children.length > 1 && children[0] instanceof PsiExpression) {
     PsiExpression expr = (PsiExpression) children[0];
     PsiType type = expr.getType();
     if (type != null) {
       if (!(type instanceof PsiClassType)) return null;
       return PsiUtil.resolveClassInType(type);
     } else {
       if (expr instanceof PsiReferenceExpression) {
         PsiElement refElement = ((PsiReferenceExpression) expr).resolve();
         if (refElement instanceof PsiClass) return (PsiClass) refElement;
       }
       return null;
     }
   }
   PsiManager manager = ref.getManager();
   for (PsiElement parent = ref; parent != null; parent = parent.getParent()) {
     if (parent instanceof PsiClass
         && (manager.areElementsEquivalent(parent, fieldOrMethodClass)
             || ((PsiClass) parent).isInheritor(fieldOrMethodClass, true))) {
       return (PsiClass) parent;
     }
   }
   return null;
 }
  private boolean checkAccessibility(final PsiClass aClass) {
    // We don't care about accessibility in javadoc
    if (JavaResolveUtil.isInJavaDoc(myPlace)) {
      return true;
    }

    if (PsiImplUtil.isInServerPage(aClass.getContainingFile())) {
      PsiFile file = FileContextUtil.getContextFile(myPlace);
      if (PsiImplUtil.isInServerPage(file)) {
        return true;
      }
    }

    boolean accessible = true;
    if (aClass instanceof PsiTypeParameter) {
      accessible = !myStaticContext;
    }

    PsiManager manager = aClass.getManager();
    if (aClass.hasModifierProperty(PsiModifier.PRIVATE)) {
      PsiElement parent = aClass.getParent();
      while (true) {
        PsiElement parentScope = parent.getParent();
        if (parentScope instanceof PsiJavaFile) break;
        parent = parentScope;
        if (!(parentScope instanceof PsiClass)) break;
      }
      if (parent instanceof PsiDeclarationStatement) {
        parent = parent.getParent();
      }
      accessible = false;
      for (PsiElement placeParent = myPlace;
          placeParent != null;
          placeParent = placeParent.getContext()) {
        if (manager.areElementsEquivalent(placeParent, parent)) accessible = true;
      }
    }
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
    if (aClass.hasModifierProperty(PsiModifier.PROTECTED)) {
      accessible = false;
      if (myPlace != null && facade.arePackagesTheSame(aClass, myPlace)) {
        accessible = true;
      } else {
        if (aClass.getContainingClass() != null) {
          accessible =
              myAccessClass == null
                  || myPlace != null
                      && facade.getResolveHelper().isAccessible(aClass, myPlace, myAccessClass);
        }
      }
    }
    if (aClass.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
      if (myPlace == null || !facade.arePackagesTheSame(aClass, myPlace)) {
        accessible = false;
      }
    }
    return accessible;
  }
 private static List<MethodsChain> reduceChainsSize(
     final List<MethodsChain> chains, final PsiManager psiManager) {
   return ContainerUtil.map(
       chains,
       chain -> {
         final Iterator<PsiMethod[]> chainIterator = chain.iterator();
         if (!chainIterator.hasNext()) {
           LOG.error("empty chain");
           return chain;
         }
         final PsiMethod[] first = chainIterator.next();
         while (chainIterator.hasNext()) {
           final PsiMethod psiMethod = chainIterator.next()[0];
           if (psiMethod.hasModifierProperty(PsiModifier.STATIC)) {
             continue;
           }
           final PsiClass current = psiMethod.getContainingClass();
           if (current == null) {
             LOG.error("containing class must be not null");
             return chain;
           }
           final PsiMethod[] currentMethods =
               current.findMethodsByName(first[0].getName(), true);
           if (currentMethods.length != 0) {
             for (final PsiMethod f : first) {
               final PsiMethod[] fSupers = f.findDeepestSuperMethods();
               final PsiMethod fSuper = fSupers.length == 0 ? first[0] : fSupers[0];
               for (final PsiMethod currentMethod : currentMethods) {
                 if (psiManager.areElementsEquivalent(currentMethod, fSuper)) {
                   return createChainFromFirstElement(chain, currentMethod.getContainingClass());
                 }
                 for (final PsiMethod method : currentMethod.findDeepestSuperMethods()) {
                   if (psiManager.areElementsEquivalent(method, fSuper)) {
                     return createChainFromFirstElement(chain, method.getContainingClass());
                   }
                 }
               }
             }
           }
         }
         return chain;
       });
 }
 public void fix() throws IncorrectOperationException {
   if (myField == null) return;
   final PsiManager manager = myScope.getManager();
   for (GrReferenceExpression referenceExpression : myReferenceExpressions) {
     if (!referenceExpression.isValid()) continue;
     final PsiElement newlyResolved = referenceExpression.resolve();
     if (!manager.areElementsEquivalent(newlyResolved, myField)) {
       qualifyReference(referenceExpression, myField, myQualifyingClass);
     }
   }
 }
Exemplo n.º 7
0
 @Nullable
 private static DeclarationDescriptor findSuperFunction(
     @NotNull Collection<Pair<FunctionDescriptor, PsiMethod>> superFunctionCandidates,
     @NotNull PsiMethod superMethod) {
   PsiManager psiManager = PsiManager.getInstance(superMethod.getProject());
   for (Pair<FunctionDescriptor, PsiMethod> candidate : superFunctionCandidates) {
     if (psiManager.areElementsEquivalent(candidate.second, superMethod)) {
       return candidate.first;
     }
   }
   return null;
 }
  private static boolean areEquivalentAccessors(
      PsiMethod method, PsiElement resolved, PsiManager manager) {
    if (!(resolved instanceof GrAccessorMethod) || !(method instanceof GrAccessorMethod)) {
      return false;
    }

    if (((GrAccessorMethod) resolved).isSetter() != ((GrAccessorMethod) method).isSetter())
      return false;

    GrField p1 = ((GrAccessorMethod) resolved).getProperty();
    GrField p2 = ((GrAccessorMethod) method).getProperty();
    return manager.areElementsEquivalent(p1, p2);
  }
 private static void rename(
     PsiNamedElement element,
     UsageInfo info,
     String nameToUse,
     boolean shouldCheckForCorrectResolve,
     PsiManager manager) {
   final PsiReference ref = info.getReference();
   final PsiElement renamed = ((GrReferenceExpression) ref).handleElementRenameSimple(nameToUse);
   PsiElement newly_resolved = ref.resolve();
   if (shouldCheckForCorrectResolve) {
     if (element instanceof GrAccessorMethod && newly_resolved instanceof GrAccessorMethod) {
       final GrAccessorMethod oldAccessor = (GrAccessorMethod) element;
       final GrAccessorMethod newAccessor = (GrAccessorMethod) newly_resolved;
       if (!manager.areElementsEquivalent(oldAccessor.getProperty(), newAccessor.getProperty())
           && oldAccessor.isSetter() == newAccessor.isSetter()) {
         qualify(oldAccessor, renamed, nameToUse);
       }
     } else if (!manager.areElementsEquivalent(element, newly_resolved)) {
       qualify((PsiMember) element, renamed, nameToUse);
     }
   }
 }
  private void selectElementInLeftTree(PsiElement elt) {
    PsiManager manager = PsiManager.getInstance(myProject);

    PackageDependenciesNode root = (PackageDependenciesNode) myLeftTree.getModel().getRoot();
    Enumeration enumeration = root.breadthFirstEnumeration();
    while (enumeration.hasMoreElements()) {
      PackageDependenciesNode child = (PackageDependenciesNode) enumeration.nextElement();
      if (manager.areElementsEquivalent(child.getPsiElement(), elt)) {
        myLeftTree.setSelectionPath(
            new TreePath(((DefaultTreeModel) myLeftTree.getModel()).getPathToRoot(child)));
        break;
      }
    }
  }
 private static boolean isSafeToShortenReference(
     final String referenceText, final PsiElement psiReference, final PsiClass refClass) {
   final PsiManager manager = refClass.getManager();
   final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
   final PsiResolveHelper helper = facade.getResolveHelper();
   if (manager.areElementsEquivalent(
       refClass, helper.resolveReferencedClass(referenceText, psiReference))) {
     PsiElement parent = psiReference.getParent();
     if (parent instanceof PsiJavaCodeReferenceElement
         && parent.getParent() instanceof PsiNewExpression) return true;
     return helper.resolveReferencedVariable(referenceText, psiReference) == null;
   }
   return false;
 }
 private static void addFieldsUsages(
     final PsiClass aClass,
     final Processor<UsageInfo> results,
     final JavaClassFindUsagesOptions options) {
   if (options.isIncludeInherited) {
     final PsiManager manager = aClass.getManager();
     PsiField[] fields = aClass.getAllFields();
     FieldsLoop:
     for (int i = 0; i < fields.length; i++) {
       final PsiField field = fields[i];
       // filter hidden fields
       for (int j = 0; j < i; j++) {
         if (Comparing.strEqual(field.getName(), fields[j].getName())) continue FieldsLoop;
       }
       final PsiClass fieldClass = field.getContainingClass();
       if (manager.areElementsEquivalent(fieldClass, aClass)) {
         addElementUsages(fields[i], results, options);
       } else {
         ReferencesSearch.search(
                 new ReferencesSearch.SearchParameters(
                     field, options.searchScope, false, options.fastTrack))
             .forEach(
                 new ReadActionProcessor<PsiReference>() {
                   @Override
                   public boolean processInReadAction(final PsiReference reference) {
                     addResultFromReference(
                         reference, fieldClass, manager, aClass, results, options);
                     return true;
                   }
                 });
       }
     }
   } else {
     PsiField[] fields =
         ApplicationManager.getApplication()
             .runReadAction(
                 new Computable<PsiField[]>() {
                   @Override
                   public PsiField[] compute() {
                     return aClass.getFields();
                   }
                 });
     for (PsiField field : fields) {
       addElementUsages(field, results, options);
     }
   }
 }
  private static PsiSubstitutor getRawingSubstitutor(PsiElement context, PsiClass targetClass) {
    if (context == null || targetClass == null) return PsiSubstitutor.EMPTY;

    PsiTypeParameterListOwner currContext =
        PsiTreeUtil.getParentOfType(context, PsiTypeParameterListOwner.class);
    PsiManager manager = context.getManager();
    PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
    while (currContext != null && !manager.areElementsEquivalent(currContext, targetClass)) {
      PsiTypeParameter[] typeParameters = currContext.getTypeParameters();
      substitutor =
          JavaPsiFacade.getInstance(context.getProject())
              .getElementFactory()
              .createRawSubstitutor(substitutor, typeParameters);
      currContext = currContext.getContainingClass();
    }

    return substitutor;
  }
Exemplo n.º 14
0
    private boolean shouldFixSuper(PsiMethod method) {
      for (PsiMember element : myMembersAfterMove) {
        if (element instanceof PsiMethod) {
          PsiMethod member = (PsiMethod) element;
          // if there is such member among moved members, super qualifier
          // should not be removed
          final PsiManager manager = method.getManager();
          if (manager.areElementsEquivalent(
                  member.getContainingClass(), method.getContainingClass())
              && MethodSignatureUtil.areSignaturesEqual(member, method)) {
            return false;
          }
        }
      }

      final PsiMethod methodFromSuper = myTargetSuperClass.findMethodBySignature(method, false);
      return methodFromSuper == null;
    }
 private static boolean isInsideQualifierClass(PsiElement position) {
   if (position.getParent() instanceof PsiJavaCodeReferenceElement) {
     final PsiElement qualifier =
         ((PsiJavaCodeReferenceElement) position.getParent()).getQualifier();
     if (qualifier instanceof PsiJavaCodeReferenceElement) {
       final PsiElement qualifierClass = ((PsiJavaCodeReferenceElement) qualifier).resolve();
       if (qualifierClass instanceof PsiClass) {
         PsiElement parent = position;
         final PsiManager psiManager = position.getManager();
         while ((parent = PsiTreeUtil.getParentOfType(parent, PsiClass.class, true)) != null) {
           if (psiManager.areElementsEquivalent(parent, qualifierClass)) {
             return true;
           }
         }
       }
     }
   }
   return false;
 }
 private static void addResultFromReference(
     final PsiReference reference,
     final PsiClass methodClass,
     final PsiManager manager,
     final PsiClass aClass,
     final Processor<UsageInfo> results,
     final FindUsagesOptions options) {
   PsiElement refElement = reference.getElement();
   if (refElement instanceof PsiReferenceExpression) {
     PsiClass usedClass =
         getFieldOrMethodAccessedClass((PsiReferenceExpression) refElement, methodClass);
     if (usedClass != null) {
       if (manager.areElementsEquivalent(usedClass, aClass)
           || usedClass.isInheritor(aClass, true)) {
         addResult(results, refElement, options);
       }
     }
   }
 }
  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    if (!(file instanceof GroovyFile)) return false;

    VirtualFile vfile = file.getVirtualFile();
    if (vfile == null) return false;

    final VirtualFile sourceRoot =
        ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(vfile);
    if (sourceRoot == null) return false;

    final PsiManager manager = PsiManager.getInstance(project);
    PackageWrapper aPackage = new PackageWrapper(manager, myPackageName);
    final PsiDirectory targetDir =
        RefactoringUtil.findPackageDirectoryInSourceRoot(aPackage, sourceRoot);

    PsiDirectory currentDir = file.getContainingDirectory();
    return targetDir == null || !manager.areElementsEquivalent(targetDir, currentDir);
  }
 private static boolean same(PsiElement e1, PsiElement e2, @NotNull PsiManager manager) {
   if (e1 instanceof PsiLiteralExpression && e2 instanceof PsiLiteralExpression) {
     return Comparing.equal(
         ((PsiLiteralExpression) e1).getValue(), ((PsiLiteralExpression) e2).getValue());
   }
   if (e1 instanceof PsiPrefixExpression
       && e2 instanceof PsiPrefixExpression
       && ((PsiPrefixExpression) e1).getOperationTokenType()
           == ((PsiPrefixExpression) e2).getOperationTokenType()) {
     return same(
         ((PsiPrefixExpression) e1).getOperand(),
         ((PsiPrefixExpression) e2).getOperand(),
         manager);
   }
   if (e1 instanceof PsiReference && e2 instanceof PsiReference) {
     e1 = ((PsiReference) e1).resolve();
     e2 = ((PsiReference) e2).resolve();
   }
   return manager.areElementsEquivalent(e2, e1);
 }
 private static void addMethodsUsages(
     final PsiClass aClass,
     final Processor<UsageInfo> results,
     final JavaClassFindUsagesOptions options) {
   if (options.isIncludeInherited) {
     final PsiManager manager = aClass.getManager();
     PsiMethod[] methods = aClass.getAllMethods();
     MethodsLoop:
     for (int i = 0; i < methods.length; i++) {
       final PsiMethod method = methods[i];
       // filter overriden methods
       MethodSignature methodSignature = method.getSignature(PsiSubstitutor.EMPTY);
       for (int j = 0; j < i; j++) {
         if (methodSignature.equals(methods[j].getSignature(PsiSubstitutor.EMPTY)))
           continue MethodsLoop;
       }
       final PsiClass methodClass = method.getContainingClass();
       if (methodClass != null && manager.areElementsEquivalent(methodClass, aClass)) {
         addElementUsages(methods[i], results, options);
       } else {
         MethodReferencesSearch.search(
                 new MethodReferencesSearch.SearchParameters(
                     method, options.searchScope, true, options.fastTrack))
             .forEach(
                 new PsiReferenceProcessorAdapter(
                     new PsiReferenceProcessor() {
                       @Override
                       public boolean execute(PsiReference reference) {
                         addResultFromReference(
                             reference, methodClass, manager, aClass, results, options);
                         return true;
                       }
                     }));
       }
     }
   } else {
     for (PsiMethod method : aClass.getMethods()) {
       addElementUsages(method, results, options);
     }
   }
 }
  public void invoke(
      @NotNull final Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
    if (elements.length != 1) return;

    PsiElement element = elements[0];
    PsiClass aClass;
    PsiElement aMember = null;

    if (element instanceof PsiClass) {
      aClass = (PsiClass) element;
    } else if (element instanceof PsiMethod) {
      aClass = ((PsiMethod) element).getContainingClass();
      aMember = element;
    } else if (element instanceof PsiField) {
      aClass = ((PsiField) element).getContainingClass();
      aMember = element;
    } else return;

    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, aClass)) return;
    MemberInfoStorage memberInfoStorage =
        new MemberInfoStorage(
            aClass,
            new MemberInfo.Filter<PsiMember>() {
              public boolean includeMember(PsiMember element) {
                return !(element instanceof PsiEnumConstant);
              }
            });
    List<MemberInfo> members = memberInfoStorage.getClassMemberInfos(aClass);
    PsiManager manager = aClass.getManager();

    for (MemberInfoBase<PsiMember> member : members) {
      if (manager.areElementsEquivalent(member.getMember(), aMember)) {
        member.setChecked(true);
        break;
      }
    }
    PushDownDialog dialog =
        new PushDownDialog(project, members.toArray(new MemberInfo[members.size()]), aClass);
    dialog.show();
  }
  /**
   * @return true if both expressions resolve to the same variable/class or field in the same
   *     instance of the class
   */
  private static boolean sameInstanceReferences(
      @Nullable PsiJavaCodeReferenceElement lRef,
      @Nullable PsiJavaCodeReferenceElement rRef,
      PsiManager manager) {
    if (lRef == null && rRef == null) return true;
    if (lRef == null || rRef == null) return false;
    PsiElement lResolved = lRef.resolve();
    PsiElement rResolved = rRef.resolve();
    if (!manager.areElementsEquivalent(lResolved, rResolved)) return false;
    if (!(lResolved instanceof PsiVariable)) return false;
    final PsiVariable variable = (PsiVariable) lResolved;
    if (variable.hasModifierProperty(PsiModifier.STATIC)) return true;

    final PsiElement lQualifier = lRef.getQualifier();
    final PsiElement rQualifier = rRef.getQualifier();
    if (lQualifier instanceof PsiJavaCodeReferenceElement
        && rQualifier instanceof PsiJavaCodeReferenceElement) {
      return sameInstanceReferences(
          (PsiJavaCodeReferenceElement) lQualifier,
          (PsiJavaCodeReferenceElement) rQualifier,
          manager);
    }

    if (Comparing.equal(lQualifier, rQualifier)) return true;
    boolean lThis =
        lQualifier == null
            || lQualifier instanceof PsiThisExpression
            || lQualifier instanceof PsiSuperExpression;
    boolean rThis =
        rQualifier == null
            || rQualifier instanceof PsiThisExpression
            || rQualifier instanceof PsiSuperExpression;
    if (lThis && rThis) {
      final PsiJavaCodeReferenceElement llQualifier = getQualifier(lQualifier);
      final PsiJavaCodeReferenceElement rrQualifier = getQualifier(rQualifier);
      return sameInstanceReferences(llQualifier, rrQualifier, manager);
    }
    return false;
  }
  public static boolean isMethodEquivalentTo(@NotNull PsiMethod method1, PsiElement another) {
    if (method1 == another) return true;
    if (!(another instanceof PsiMethod)) return false;
    PsiMethod method2 = (PsiMethod) another;
    if (!another.isValid()) return false;
    if (!method1.getName().equals(method2.getName())) return false;
    PsiClass aClass1 = method1.getContainingClass();
    PsiClass aClass2 = method2.getContainingClass();
    PsiManager manager = method1.getManager();
    if (!(aClass1 != null && aClass2 != null && manager.areElementsEquivalent(aClass1, aClass2)))
      return false;

    PsiParameter[] parameters1 = method1.getParameterList().getParameters();
    PsiParameter[] parameters2 = method2.getParameterList().getParameters();
    if (parameters1.length != parameters2.length) return false;
    for (int i = 0; i < parameters1.length; i++) {
      PsiParameter parameter1 = parameters1[i];
      PsiParameter parameter2 = parameters2[i];
      PsiType type1 = parameter1.getType();
      PsiType type2 = parameter2.getType();
      if (!compareParamTypes(manager, type1, type2)) return false;
    }
    return true;
  }
  private static boolean compareParamTypes(
      @NotNull PsiManager manager, @NotNull PsiType type1, @NotNull PsiType type2) {
    if (type1 instanceof PsiArrayType) {
      return type2 instanceof PsiArrayType
          && compareParamTypes(
              manager,
              ((PsiArrayType) type1).getComponentType(),
              ((PsiArrayType) type2).getComponentType());
    }

    if (!(type1 instanceof PsiClassType) || !(type2 instanceof PsiClassType)) {
      return type1.equals(type2);
    }

    PsiClass class1 = ((PsiClassType) type1).resolve();
    PsiClass class2 = ((PsiClassType) type2).resolve();

    if (class1 instanceof PsiTypeParameter && class2 instanceof PsiTypeParameter) {
      return Comparing.equal(class1.getName(), class2.getName())
          && ((PsiTypeParameter) class1).getIndex() == ((PsiTypeParameter) class2).getIndex();
    }

    return manager.areElementsEquivalent(class1, class2);
  }
  @Override
  public void renameElement(
      final PsiElement psiElement,
      final String newName,
      final UsageInfo[] usages,
      final RefactoringElementListener listener)
      throws IncorrectOperationException {

    final GrField field = (GrField) psiElement;
    final PsiMethod getter = GroovyPropertyUtils.findGetterForField(field);
    final PsiMethod setter = GroovyPropertyUtils.findSetterForField(field);
    final String newGetterName =
        (getter != null && getter.getName().startsWith("is") ? "is" : "get")
            + StringUtil.capitalize(newName);
    final String newSetterName = "set" + StringUtil.capitalize(newName);

    final PsiManager manager = field.getManager();

    List<PsiReference> getterRefs = new ArrayList<PsiReference>();
    List<PsiReference> setterRefs = new ArrayList<PsiReference>();
    List<PsiReference> fieldRefs = new ArrayList<PsiReference>();

    for (UsageInfo usage : usages) {
      final PsiElement element = usage.getElement();
      if (element == null) continue;

      PsiReference ref = element.findReferenceAt(usage.startOffset);
      if (ref == null) continue;

      PsiElement resolved = ref.resolve();
      if (manager.areElementsEquivalent(resolved, getter)) {
        if (isPropertyAccess(element)) {
          fieldRefs.add(ref);
        } else {
          getterRefs.add(ref);
        }
      } else if (manager.areElementsEquivalent(resolved, setter)) {
        if (isPropertyAccess(element)) {
          fieldRefs.add(ref);
        } else {
          setterRefs.add(ref);
        }
      } else if (manager.areElementsEquivalent(resolved, field)) {
        fieldRefs.add(ref);
      } else {
        ref.handleElementRename(newName);
      }
    }

    field.setName(newName);

    final PsiMethod newGetter = GroovyPropertyUtils.findGetterForField(field);
    doRename(newGetterName, manager, getterRefs, newGetter);

    final PsiMethod newSetter = GroovyPropertyUtils.findSetterForField(field);
    doRename(newSetterName, manager, setterRefs, newSetter);

    doRename(newName, manager, fieldRefs, field);

    listener.elementRenamed(field);
  }
  private void correctMethodCall(
      final PsiMethodCallExpression expression, final boolean isInternalCall) {
    try {
      final PsiManager manager = myMethod.getManager();
      PsiReferenceExpression methodExpression = expression.getMethodExpression();
      if (!methodExpression.isReferenceTo(myMethod)) return;
      final PsiExpression oldQualifier = methodExpression.getQualifierExpression();
      PsiExpression newQualifier = null;
      final PsiClass classReferencedByThis =
          MoveInstanceMembersUtil.getClassReferencedByThis(methodExpression);
      if (myTargetVariable instanceof PsiParameter) {
        final int index =
            myMethod.getParameterList().getParameterIndex((PsiParameter) myTargetVariable);
        final PsiExpression[] arguments = expression.getArgumentList().getExpressions();
        if (index < arguments.length) {
          newQualifier = (PsiExpression) arguments[index].copy();
          arguments[index].delete();
        }
      } else {
        VisibilityUtil.escalateVisibility((PsiField) myTargetVariable, expression);
        String newQualifierName = myTargetVariable.getName();
        if (myTargetVariable instanceof PsiField && oldQualifier != null) {
          final PsiClass aClass = PsiUtil.resolveClassInClassTypeOnly(oldQualifier.getType());
          if (aClass == ((PsiField) myTargetVariable).getContainingClass()) {
            newQualifierName = oldQualifier.getText() + "." + newQualifierName;
          }
        }
        newQualifier =
            JavaPsiFacade.getInstance(manager.getProject())
                .getElementFactory()
                .createExpressionFromText(newQualifierName, null);
      }

      PsiExpression newArgument = null;

      if (classReferencedByThis != null) {
        @NonNls String thisArgumentText = null;
        if (manager.areElementsEquivalent(myMethod.getContainingClass(), classReferencedByThis)) {
          if (myOldClassParameterNames.containsKey(myMethod.getContainingClass())) {
            thisArgumentText = "this";
          }
        } else {
          thisArgumentText = classReferencedByThis.getName() + ".this";
        }

        if (thisArgumentText != null) {
          newArgument =
              JavaPsiFacade.getInstance(manager.getProject())
                  .getElementFactory()
                  .createExpressionFromText(thisArgumentText, null);
        }
      } else {
        if (!isInternalCall && oldQualifier != null) {
          final PsiType type = oldQualifier.getType();
          if (type instanceof PsiClassType) {
            final PsiClass resolved = ((PsiClassType) type).resolve();
            if (resolved != null && getParameterNameToCreate(resolved) != null) {
              newArgument =
                  replaceRefsToTargetVariable(
                      oldQualifier); // replace is needed in case old qualifier is e.g. the same as
                                     // field as target variable
            }
          }
        }
      }

      if (newArgument != null) {
        expression.getArgumentList().add(newArgument);
      }

      if (newQualifier != null) {
        if (newQualifier instanceof PsiThisExpression
            && ((PsiThisExpression) newQualifier).getQualifier() == null) {
          // Remove now redundant 'this' qualifier
          if (oldQualifier != null) oldQualifier.delete();
        } else {
          final PsiReferenceExpression refExpr =
              (PsiReferenceExpression)
                  JavaPsiFacade.getInstance(manager.getProject())
                      .getElementFactory()
                      .createExpressionFromText("q." + myMethod.getName(), null);
          refExpr.getQualifierExpression().replace(newQualifier);
          methodExpression.replace(refExpr);
        }
      }
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
  public static int insertClassReference(
      PsiClass psiClass, PsiFile file, int startOffset, int endOffset) {
    final Project project = file.getProject();
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    documentManager.commitAllDocuments();

    final PsiManager manager = file.getManager();

    final Document document =
        FileDocumentManager.getInstance().getDocument(file.getViewProvider().getVirtualFile());

    final PsiReference reference = file.findReferenceAt(startOffset);
    if (reference != null) {
      final PsiElement resolved = reference.resolve();
      if (resolved instanceof PsiClass) {
        if (((PsiClass) resolved).getQualifiedName() == null
            || manager.areElementsEquivalent(psiClass, resolved)) {
          return endOffset;
        }
      }
    }

    String name = psiClass.getName();
    if (name == null) {
      return endOffset;
    }

    assert document != null;
    document.replaceString(startOffset, endOffset, name);

    int newEndOffset = startOffset + name.length();
    final RangeMarker toDelete = insertTemporary(newEndOffset, document, " ");

    documentManager.commitAllDocuments();

    PsiElement element = file.findElementAt(startOffset);
    if (element instanceof PsiIdentifier) {
      PsiElement parent = element.getParent();
      if (parent instanceof PsiJavaCodeReferenceElement
          && !((PsiJavaCodeReferenceElement) parent).isQualified()
          && !(parent.getParent() instanceof PsiPackageStatement)) {
        PsiJavaCodeReferenceElement ref = (PsiJavaCodeReferenceElement) parent;

        if (psiClass.isValid()
            && !psiClass.getManager().areElementsEquivalent(psiClass, resolveReference(ref))) {
          final boolean staticImport = ref instanceof PsiImportStaticReferenceElement;
          PsiElement newElement;
          try {
            newElement =
                staticImport
                    ? ((PsiImportStaticReferenceElement) ref).bindToTargetClass(psiClass)
                    : ref.bindToElement(psiClass);
          } catch (IncorrectOperationException e) {
            return endOffset; // can happen if fqn contains reserved words, for example
          }

          final RangeMarker rangeMarker = document.createRangeMarker(newElement.getTextRange());
          documentManager.doPostponedOperationsAndUnblockDocument(document);
          documentManager.commitDocument(document);

          newElement =
              CodeInsightUtilCore.findElementInRange(
                  file,
                  rangeMarker.getStartOffset(),
                  rangeMarker.getEndOffset(),
                  PsiJavaCodeReferenceElement.class,
                  JavaLanguage.INSTANCE);
          rangeMarker.dispose();
          if (newElement != null) {
            newEndOffset = newElement.getTextRange().getEndOffset();
            if (!(newElement instanceof PsiReferenceExpression)) {
              PsiReferenceParameterList parameterList =
                  ((PsiJavaCodeReferenceElement) newElement).getParameterList();
              if (parameterList != null) {
                newEndOffset = parameterList.getTextRange().getStartOffset();
              }
            }

            if (!staticImport
                && !psiClass
                    .getManager()
                    .areElementsEquivalent(psiClass, resolveReference((PsiReference) newElement))
                && !PsiUtil.isInnerClass(psiClass)) {
              final String qName = psiClass.getQualifiedName();
              if (qName != null) {
                document.replaceString(
                    newElement.getTextRange().getStartOffset(), newEndOffset, qName);
                newEndOffset = newElement.getTextRange().getStartOffset() + qName.length();
              }
            }
          }
        }
      }
    }

    if (toDelete.isValid()) {
      document.deleteString(toDelete.getStartOffset(), toDelete.getEndOffset());
    }

    return newEndOffset;
  }