public MultiMap<PsiElement, String> findConflicts(Ref<UsageInfo[]> refUsages) {
      MultiMap<PsiElement, String> conflictDescriptions = new MultiMap<PsiElement, String>();
      addMethodConflicts(conflictDescriptions);
      Set<UsageInfo> usagesSet = new HashSet<UsageInfo>(Arrays.asList(refUsages.get()));
      RenameUtil.removeConflictUsages(usagesSet);
      if (myChangeInfo.isVisibilityChanged()) {
        try {
          addInaccessibilityDescriptions(usagesSet, conflictDescriptions);
        } catch (IncorrectOperationException e) {
          LOG.error(e);
        }
      }

      for (UsageInfo usageInfo : usagesSet) {
        if (usageInfo instanceof OverriderUsageInfo) {
          final PsiMethod method = (PsiMethod) usageInfo.getElement();
          final PsiMethod baseMethod = ((OverriderUsageInfo) usageInfo).getBaseMethod();
          final int delta =
              baseMethod.getParameterList().getParametersCount()
                  - method.getParameterList().getParametersCount();
          if (delta > 0) {
            final boolean[] toRemove = myChangeInfo.toRemoveParm();
            if (toRemove[
                toRemove.length - 1]) { // todo check if implicit parameter is not the last one
              conflictDescriptions.putValue(
                  baseMethod, "Implicit last parameter should not be deleted");
            }
          }
        }
      }

      return conflictDescriptions;
    }
 private boolean needToCatchExceptions(PsiMethod caller) {
   if (myChangeInfo instanceof JavaChangeInfo) {
     return myChangeInfo.isExceptionSetOrOrderChanged()
         && !((JavaChangeInfo) myChangeInfo).getMethodsToPropagateParameters().contains(caller);
   } else {
     return myChangeInfo.isExceptionSetOrOrderChanged();
   }
 }
 private static void generateDelegate(JavaChangeInfo changeInfo)
     throws IncorrectOperationException {
   final PsiMethod delegate = (PsiMethod) changeInfo.getMethod().copy();
   final PsiClass targetClass = changeInfo.getMethod().getContainingClass();
   LOG.assertTrue(!targetClass.isInterface());
   PsiElementFactory factory = JavaPsiFacade.getElementFactory(targetClass.getProject());
   ChangeSignatureProcessor.makeEmptyBody(factory, delegate);
   final PsiCallExpression callExpression =
       ChangeSignatureProcessor.addDelegatingCallTemplate(delegate, changeInfo.getNewName());
   addDelegateArguments(changeInfo, factory, callExpression);
   targetClass.addBefore(delegate, changeInfo.getMethod());
 }
 private static PsiClassType[] getPrimaryChangedExceptionInfo(JavaChangeInfo changeInfo)
     throws IncorrectOperationException {
   final ThrownExceptionInfo[] newExceptionInfos = changeInfo.getNewExceptions();
   PsiClassType[] newExceptions = new PsiClassType[newExceptionInfos.length];
   final PsiMethod method = changeInfo.getMethod();
   for (int i = 0; i < newExceptions.length; i++) {
     newExceptions[i] =
         (PsiClassType)
             newExceptionInfos[i].createType(
                 method, method.getManager()); // context really does not matter here
   }
   return newExceptions;
 }
  private static void processCallerMethod(
      JavaChangeInfo changeInfo,
      PsiMethod caller,
      PsiMethod baseMethod,
      boolean toInsertParams,
      boolean toInsertThrows)
      throws IncorrectOperationException {
    LOG.assertTrue(toInsertParams || toInsertThrows);
    if (toInsertParams) {
      List<PsiParameter> newParameters = new ArrayList<PsiParameter>();
      ContainerUtil.addAll(newParameters, caller.getParameterList().getParameters());
      final JavaParameterInfo[] primaryNewParms = changeInfo.getNewParameters();
      PsiSubstitutor substitutor =
          baseMethod == null
              ? PsiSubstitutor.EMPTY
              : ChangeSignatureProcessor.calculateSubstitutor(caller, baseMethod);
      for (JavaParameterInfo info : primaryNewParms) {
        if (info.getOldIndex() < 0)
          newParameters.add(createNewParameter(changeInfo, info, substitutor));
      }
      PsiParameter[] arrayed = newParameters.toArray(new PsiParameter[newParameters.size()]);
      boolean[] toRemoveParm = new boolean[arrayed.length];
      Arrays.fill(toRemoveParm, false);
      resolveParameterVsFieldsConflicts(arrayed, caller, caller.getParameterList(), toRemoveParm);
    }

    if (toInsertThrows) {
      List<PsiJavaCodeReferenceElement> newThrowns = new ArrayList<PsiJavaCodeReferenceElement>();
      final PsiReferenceList throwsList = caller.getThrowsList();
      ContainerUtil.addAll(newThrowns, throwsList.getReferenceElements());
      final ThrownExceptionInfo[] primaryNewExns = changeInfo.getNewExceptions();
      for (ThrownExceptionInfo thrownExceptionInfo : primaryNewExns) {
        if (thrownExceptionInfo.getOldIndex() < 0) {
          final PsiClassType type =
              (PsiClassType) thrownExceptionInfo.createType(caller, caller.getManager());
          final PsiJavaCodeReferenceElement ref =
              JavaPsiFacade.getInstance(caller.getProject())
                  .getElementFactory()
                  .createReferenceElementByType(type);
          newThrowns.add(ref);
        }
      }
      PsiJavaCodeReferenceElement[] arrayed =
          newThrowns.toArray(new PsiJavaCodeReferenceElement[newThrowns.size()]);
      boolean[] toRemoveParm = new boolean[arrayed.length];
      Arrays.fill(toRemoveParm, false);
      ChangeSignatureUtil.synchronizeList(
          throwsList, Arrays.asList(arrayed), ThrowsList.INSTANCE, toRemoveParm);
    }
  }
  private static void processMethodUsage(
      PsiElement ref,
      JavaChangeInfo changeInfo,
      boolean toChangeArguments,
      boolean toCatchExceptions,
      PsiMethod callee,
      PsiSubstitutor subsitutor,
      final UsageInfo[] usages)
      throws IncorrectOperationException {
    if (changeInfo.isNameChanged()) {
      if (ref instanceof PsiJavaCodeReferenceElement) {
        PsiElement last = ((PsiJavaCodeReferenceElement) ref).getReferenceNameElement();
        if (last instanceof PsiIdentifier && last.getText().equals(changeInfo.getOldName())) {
          last.replace(changeInfo.getNewNameIdentifier());
        }
      }
    }

    final PsiMethod caller = RefactoringUtil.getEnclosingMethod(ref);
    if (toChangeArguments) {
      final PsiExpressionList list = RefactoringUtil.getArgumentListByMethodReference(ref);
      LOG.assertTrue(list != null);
      boolean toInsertDefaultValue = needDefaultValue(changeInfo, caller);
      if (toInsertDefaultValue && ref instanceof PsiReferenceExpression) {
        final PsiExpression qualifierExpression =
            ((PsiReferenceExpression) ref).getQualifierExpression();
        if (qualifierExpression instanceof PsiSuperExpression
            && callerSignatureIsAboutToChangeToo(caller, usages)) {
          toInsertDefaultValue = false;
        }
      }

      fixActualArgumentsList(list, changeInfo, toInsertDefaultValue, subsitutor);
    }

    if (toCatchExceptions) {
      if (!(ref instanceof PsiReferenceExpression
          && ((PsiReferenceExpression) ref).getQualifierExpression()
              instanceof PsiSuperExpression)) {
        if (needToCatchExceptions(changeInfo, caller)) {
          PsiClassType[] newExceptions =
              callee != null
                  ? getCalleeChangedExceptionInfo(callee)
                  : getPrimaryChangedExceptionInfo(changeInfo);
          fixExceptions(ref, newExceptions);
        }
      }
    }
  }
 private static void addDefaultConstructor(
     JavaChangeInfo changeInfo, PsiClass aClass, final UsageInfo[] usages)
     throws IncorrectOperationException {
   if (!(aClass instanceof PsiAnonymousClass)) {
     PsiElementFactory factory = JavaPsiFacade.getElementFactory(aClass.getProject());
     PsiMethod defaultConstructor =
         factory.createMethodFromText(aClass.getName() + "(){}", aClass);
     defaultConstructor =
         (PsiMethod)
             CodeStyleManager.getInstance(aClass.getProject()).reformat(defaultConstructor);
     defaultConstructor = (PsiMethod) aClass.add(defaultConstructor);
     PsiUtil.setModifierProperty(
         defaultConstructor, VisibilityUtil.getVisibilityModifier(aClass.getModifierList()), true);
     addSuperCall(changeInfo, defaultConstructor, null, usages);
   } else {
     final PsiElement parent = aClass.getParent();
     if (parent instanceof PsiNewExpression) {
       final PsiExpressionList argumentList = ((PsiNewExpression) parent).getArgumentList();
       final PsiClass baseClass = changeInfo.getMethod().getContainingClass();
       final PsiSubstitutor substitutor =
           TypeConversionUtil.getSuperClassSubstitutor(baseClass, aClass, PsiSubstitutor.EMPTY);
       fixActualArgumentsList(argumentList, changeInfo, true, substitutor);
     }
   }
 }
  private void findUsagesInCallers(final ArrayList<UsageInfo> usages) {
    if (myChangeInfo instanceof JavaChangeInfo) {
      JavaChangeInfo changeInfo = (JavaChangeInfo) myChangeInfo;

      Set<PsiMethod> merged = new HashSet<PsiMethod>();
      merged.addAll(changeInfo.getMethodsToPropagateParameters());
      for (final PsiMethod method : merged) {
        findSimpleUsagesWithoutParameters(
            method,
            usages,
            changeInfo.getMethodsToPropagateParameters().contains(method),
            false,
            false);
      }
    }
  }
 private static void fixJavadocsForChangedMethod(
     PsiMethod method, JavaChangeInfo changeInfo, int newParamsLength)
     throws IncorrectOperationException {
   final PsiParameter[] parameters = method.getParameterList().getParameters();
   final JavaParameterInfo[] newParms = changeInfo.getNewParameters();
   LOG.assertTrue(parameters.length <= newParamsLength);
   final Set<PsiParameter> newParameters = new HashSet<PsiParameter>();
   final String[] oldParameterNames = changeInfo.getOldParameterNames();
   for (int i = 0; i < newParamsLength; i++) {
     JavaParameterInfo newParm = newParms[i];
     if (newParm.getOldIndex() < 0
         || !newParm.getName().equals(oldParameterNames[newParm.getOldIndex()])) {
       newParameters.add(parameters[i]);
     }
   }
   RefactoringUtil.fixJavadocsForParams(method, newParameters);
 }
 private static PsiParameter createNewParameter(
     JavaChangeInfo changeInfo, JavaParameterInfo newParm, PsiSubstitutor substitutor)
     throws IncorrectOperationException {
   final PsiParameterList list = changeInfo.getMethod().getParameterList();
   final PsiElementFactory factory =
       JavaPsiFacade.getInstance(list.getProject()).getElementFactory();
   final PsiType type = substitutor.substitute(newParm.createType(list, list.getManager()));
   return factory.createParameter(newParm.getName(), type);
 }
 private static void addDelegateArguments(
     JavaChangeInfo changeInfo, PsiElementFactory factory, final PsiCallExpression callExpression)
     throws IncorrectOperationException {
   final JavaParameterInfo[] newParms = changeInfo.getNewParameters();
   final String[] oldParameterNames = changeInfo.getOldParameterNames();
   for (int i = 0; i < newParms.length; i++) {
     JavaParameterInfo newParm = newParms[i];
     final PsiExpression actualArg;
     if (newParm.getOldIndex() >= 0) {
       actualArg =
           factory.createExpressionFromText(
               oldParameterNames[newParm.getOldIndex()], callExpression);
     } else {
       actualArg = changeInfo.getValue(i, callExpression);
     }
     JavaCodeStyleManager.getInstance(callExpression.getProject())
         .shortenClassReferences(callExpression.getArgumentList().add(actualArg));
   }
 }
  private static void processConstructor(GrMethod constructor, JavaChangeInfo changeInfo) {
    final PsiClass containingClass = constructor.getContainingClass();
    final PsiClass baseClass = changeInfo.getMethod().getContainingClass();
    final PsiSubstitutor substitutor =
        TypeConversionUtil.getSuperClassSubstitutor(
            baseClass, containingClass, PsiSubstitutor.EMPTY);

    GrOpenBlock block = constructor.getBlock();
    GrConstructorInvocation invocation =
        GroovyPsiElementFactory.getInstance(constructor.getProject())
            .createConstructorInvocation("super()");
    invocation =
        (GrConstructorInvocation) block.addStatementBefore(invocation, getFirstStatement(block));
    processMethodUsage(
        invocation.getInvokedExpression(),
        changeInfo,
        changeInfo.isParameterSetOrOrderChanged() || changeInfo.isParameterNamesChanged(),
        changeInfo.isExceptionSetChanged(),
        GrClosureSignatureUtil.ArgInfo.<PsiElement>empty_array(),
        substitutor);
  }
  public UsageInfo[] findUsages() {
    ArrayList<UsageInfo> result = new ArrayList<UsageInfo>();
    final PsiElement element = myChangeInfo.getMethod();
    if (element instanceof PsiMethod) {
      final PsiMethod method = (PsiMethod) element;

      findSimpleUsages(method, result);

      final UsageInfo[] usageInfos = result.toArray(new UsageInfo[result.size()]);
      return UsageViewUtil.removeDuplicatedUsages(usageInfos);
    }
    return UsageInfo.EMPTY_ARRAY;
  }
    private void addMethodConflicts(MultiMap<PsiElement, String> conflicts) {
      String newMethodName = myChangeInfo.getNewName();
      if (!(myChangeInfo instanceof JavaChangeInfo)) {
        return;
      }
      try {
        PsiMethod prototype;
        final PsiMethod method = myChangeInfo.getMethod();
        if (!StdLanguages.JAVA.equals(method.getLanguage())) return;
        PsiManager manager = method.getManager();
        PsiElementFactory factory =
            JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
        final CanonicalTypes.Type returnType = myChangeInfo.getNewReturnType();
        if (returnType != null) {
          prototype = factory.createMethod(newMethodName, returnType.getType(method, manager));
        } else {
          prototype = factory.createConstructor();
          prototype.setName(newMethodName);
        }
        JavaParameterInfo[] parameters = myChangeInfo.getNewParameters();

        for (JavaParameterInfo info : parameters) {
          PsiType parameterType = info.createType(method, manager);
          if (parameterType == null) {
            parameterType =
                JavaPsiFacade.getElementFactory(method.getProject())
                    .createTypeFromText(CommonClassNames.JAVA_LANG_OBJECT, method);
          }
          PsiParameter param = factory.createParameter(info.getName(), parameterType);
          prototype.getParameterList().add(param);
        }

        ConflictsUtil.checkMethodConflicts(
            method.getContainingClass(), method, prototype, conflicts);
      } catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }
  private void findParametersUsage(
      final PsiMethod method, ArrayList<UsageInfo> result, PsiMethod[] overriders) {
    if (JavaLanguage.INSTANCE.equals(myChangeInfo.getLanguage())) {
      PsiParameter[] parameters = method.getParameterList().getParameters();
      for (ParameterInfo info : myChangeInfo.getNewParameters()) {
        if (info.getOldIndex() >= 0) {
          PsiParameter parameter = parameters[info.getOldIndex()];
          if (!info.getName().equals(parameter.getName())) {
            addParameterUsages(parameter, result, info);

            for (PsiMethod overrider : overriders) {
              PsiParameter parameter1 =
                  overrider.getParameterList().getParameters()[info.getOldIndex()];
              if (parameter1 != null
                  && Comparing.strEqual(parameter.getName(), parameter1.getName())) {
                addParameterUsages(parameter1, result, info);
              }
            }
          }
        }
      }
    }
  }
    private void addInaccessibilityDescriptions(
        Set<UsageInfo> usages, MultiMap<PsiElement, String> conflictDescriptions)
        throws IncorrectOperationException {
      PsiMethod method = myChangeInfo.getMethod();
      PsiModifierList modifierList = (PsiModifierList) method.getModifierList().copy();
      VisibilityUtil.setVisibility(modifierList, myChangeInfo.getNewVisibility());

      for (Iterator<UsageInfo> iterator = usages.iterator(); iterator.hasNext(); ) {
        UsageInfo usageInfo = iterator.next();
        PsiElement element = usageInfo.getElement();
        if (element != null) {
          if (element instanceof PsiQualifiedReference) {
            PsiClass accessObjectClass = null;
            PsiElement qualifier = ((PsiQualifiedReference) element).getQualifier();
            if (qualifier instanceof PsiExpression) {
              accessObjectClass =
                  (PsiClass) PsiUtil.getAccessObjectClass((PsiExpression) qualifier).getElement();
            }

            if (!JavaPsiFacade.getInstance(element.getProject())
                .getResolveHelper()
                .isAccessible(method, modifierList, element, accessObjectClass, null)) {
              String message =
                  RefactoringBundle.message(
                      "0.with.1.visibility.is.not.accessible.from.2",
                      RefactoringUIUtil.getDescription(method, true),
                      myChangeInfo.getNewVisibility(),
                      RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(element), true));
              conflictDescriptions.putValue(method, message);
              if (!needToChangeCalls()) {
                iterator.remove();
              }
            }
          }
        }
      }
    }
 private static void addSuperCall(
     JavaChangeInfo changeInfo, PsiMethod constructor, PsiMethod callee, final UsageInfo[] usages)
     throws IncorrectOperationException {
   final PsiElementFactory factory = JavaPsiFacade.getElementFactory(constructor.getProject());
   PsiExpressionStatement superCall =
       (PsiExpressionStatement) factory.createStatementFromText("super();", constructor);
   PsiCodeBlock body = constructor.getBody();
   assert body != null;
   PsiStatement[] statements = body.getStatements();
   if (statements.length > 0) {
     superCall = (PsiExpressionStatement) body.addBefore(superCall, statements[0]);
   } else {
     superCall = (PsiExpressionStatement) body.add(superCall);
   }
   PsiMethodCallExpression callExpression = (PsiMethodCallExpression) superCall.getExpression();
   final PsiClass aClass = constructor.getContainingClass();
   final PsiClass baseClass = changeInfo.getMethod().getContainingClass();
   final PsiSubstitutor substitutor =
       TypeConversionUtil.getSuperClassSubstitutor(baseClass, aClass, PsiSubstitutor.EMPTY);
   processMethodUsage(
       callExpression.getMethodExpression(), changeInfo, true, false, callee, substitutor, usages);
 }
 private static boolean needToCatchExceptions(JavaChangeInfo changeInfo, PsiMethod caller) {
   return changeInfo.isExceptionSetOrOrderChanged()
       && !(changeInfo instanceof JavaChangeInfoImpl
           && ((JavaChangeInfoImpl) changeInfo).propagateExceptionsMethods.contains(caller));
 }
  private static boolean processPrimaryMethodInner(
      JavaChangeInfo changeInfo, GrMethod method, @Nullable PsiMethod baseMethod) {
    if (changeInfo.isNameChanged()) {
      String newName =
          baseMethod == null
              ? changeInfo.getNewName()
              : RefactoringUtil.suggestNewOverriderName(
                  method.getName(), baseMethod.getName(), changeInfo.getNewName());
      if (newName != null && !newName.equals(method.getName())) {
        method.setName(changeInfo.getNewName());
      }
    }

    final GrModifierList modifierList = method.getModifierList();
    if (changeInfo.isVisibilityChanged()) {
      modifierList.setModifierProperty(changeInfo.getNewVisibility(), true);
    }

    PsiSubstitutor substitutor =
        baseMethod != null ? calculateSubstitutor(method, baseMethod) : PsiSubstitutor.EMPTY;

    final PsiMethod context = changeInfo.getMethod();
    GrTypeElement oldReturnTypeElement = method.getReturnTypeElementGroovy();
    if (changeInfo.isReturnTypeChanged()) {
      CanonicalTypes.Type newReturnType = changeInfo.getNewReturnType();
      if (newReturnType == null) {
        if (oldReturnTypeElement != null) {
          oldReturnTypeElement.delete();
          if (modifierList.getModifiers().length == 0) {
            modifierList.setModifierProperty(GrModifier.DEF, true);
          }
        }
      } else {
        PsiType type = newReturnType.getType(context, method.getManager());
        GrReferenceAdjuster.shortenAllReferencesIn(
            method.setReturnType(substitutor.substitute(type)));
        if (oldReturnTypeElement == null) {
          modifierList.setModifierProperty(GrModifier.DEF, false);
        }
      }
    }

    JavaParameterInfo[] newParameters = changeInfo.getNewParameters();
    final GrParameterList parameterList = method.getParameterList();
    GrParameter[] oldParameters = parameterList.getParameters();
    final PsiParameter[] oldBaseParams =
        baseMethod != null ? baseMethod.getParameterList().getParameters() : null;

    Set<GrParameter> toRemove = new HashSet<GrParameter>(oldParameters.length);
    ContainerUtil.addAll(toRemove, oldParameters);

    GrParameter anchor = null;
    final GrDocComment docComment = method.getDocComment();
    final GrDocTag[] tags = docComment == null ? null : docComment.getTags();

    for (JavaParameterInfo newParameter : newParameters) {
      // if old parameter name differs from base method parameter name we don't change it
      final String newName;
      final int oldIndex = newParameter.getOldIndex();
      if (oldIndex >= 0 && oldBaseParams != null) {
        final String oldName = oldParameters[oldIndex].getName();
        if (oldName.equals(oldBaseParams[oldIndex].getName())) {
          newName = newParameter.getName();
        } else {
          newName = oldName;
        }
      } else {
        newName = newParameter.getName();
      }

      final GrParameter oldParameter = oldIndex >= 0 ? oldParameters[oldIndex] : null;

      if (docComment != null && oldParameter != null) {
        final String oldName = oldParameter.getName();
        for (GrDocTag tag : tags) {
          if ("@param".equals(tag.getName())) {
            final GrDocParameterReference parameterReference = tag.getDocParameterReference();
            if (parameterReference != null && oldName.equals(parameterReference.getText())) {
              parameterReference.handleElementRename(newName);
            }
          }
        }
      }

      GrParameter grParameter =
          createNewParameter(substitutor, context, parameterList, newParameter, newName);
      if (oldParameter != null) {
        grParameter.getModifierList().replace(oldParameter.getModifierList());
      }

      if ("def".equals(newParameter.getTypeText())) {
        grParameter.getModifierList().setModifierProperty(GrModifier.DEF, true);
      } else if (StringUtil.isEmpty(newParameter.getTypeText())) {
        grParameter.getModifierList().setModifierProperty(GrModifier.DEF, false);
      }

      anchor = (GrParameter) parameterList.addAfter(grParameter, anchor);
    }

    for (GrParameter oldParameter : toRemove) {
      oldParameter.delete();
    }
    JavaCodeStyleManager.getInstance(parameterList.getProject())
        .shortenClassReferences(parameterList);
    CodeStyleManager.getInstance(parameterList.getProject()).reformat(parameterList);

    if (changeInfo.isExceptionSetOrOrderChanged()) {
      final ThrownExceptionInfo[] infos = changeInfo.getNewExceptions();
      PsiClassType[] exceptionTypes = new PsiClassType[infos.length];
      for (int i = 0; i < infos.length; i++) {
        ThrownExceptionInfo info = infos[i];
        exceptionTypes[i] = (PsiClassType) info.createType(method, method.getManager());
      }

      PsiReferenceList thrownList =
          GroovyPsiElementFactory.getInstance(method.getProject()).createThrownList(exceptionTypes);
      thrownList = (PsiReferenceList) method.getThrowsList().replace(thrownList);
      JavaCodeStyleManager.getInstance(thrownList.getProject()).shortenClassReferences(thrownList);
      CodeStyleManager.getInstance(method.getProject()).reformat(method.getThrowsList());
    }
    return true;
  }
  @Nullable
  private static GrExpression createDefaultValue(
      GroovyPsiElementFactory factory,
      JavaChangeInfo changeInfo,
      JavaParameterInfo info,
      final GrArgumentList list) {
    if (info.isUseAnySingleVariable()) {
      final PsiResolveHelper resolveHelper =
          JavaPsiFacade.getInstance(list.getProject()).getResolveHelper();
      final PsiType type = info.getTypeWrapper().getType(changeInfo.getMethod(), list.getManager());
      final VariablesProcessor processor =
          new VariablesProcessor(false) {
            @Override
            protected boolean check(PsiVariable var, ResolveState state) {
              if (var instanceof PsiField
                  && !resolveHelper.isAccessible((PsiField) var, list, null)) return false;
              if (var instanceof GrVariable
                  && PsiUtil.isLocalVariable(var)
                  && list.getTextRange().getStartOffset() <= var.getTextRange().getStartOffset()) {
                return false;
              }
              if (PsiTreeUtil.isAncestor(var, list, false)) return false;
              final PsiType _type =
                  var instanceof GrVariable ? ((GrVariable) var).getTypeGroovy() : var.getType();
              final PsiType varType = state.get(PsiSubstitutor.KEY).substitute(_type);
              return type.isAssignableFrom(varType);
            }

            @Override
            public boolean execute(@NotNull PsiElement pe, @NotNull ResolveState state) {
              super.execute(pe, state);
              return size() < 2;
            }
          };
      ResolveUtil.treeWalkUp(list, processor, false);
      if (processor.size() == 1) {
        final PsiVariable result = processor.getResult(0);
        return factory.createExpressionFromText(result.getName(), list);
      }
      if (processor.size() == 0) {
        final PsiClass parentClass = PsiTreeUtil.getParentOfType(list, PsiClass.class);
        if (parentClass != null) {
          PsiClass containingClass = parentClass;
          final Set<PsiClass> containingClasses = new HashSet<PsiClass>();
          final PsiElementFactory jfactory = JavaPsiFacade.getElementFactory(list.getProject());
          while (containingClass != null) {
            if (type.isAssignableFrom(jfactory.createType(containingClass, PsiSubstitutor.EMPTY))) {
              containingClasses.add(containingClass);
            }
            containingClass = PsiTreeUtil.getParentOfType(containingClass, PsiClass.class);
          }
          if (containingClasses.size() == 1) {
            return factory.createThisExpression(
                containingClasses.contains(parentClass)
                    ? null
                    : containingClasses.iterator().next());
          }
        }
      }
    }

    final String value = info.getDefaultValue();
    return !StringUtil.isEmpty(value) ? factory.createExpressionFromText(value, list) : null;
  }
  private static void processMethodUsage(
      PsiElement element,
      JavaChangeInfo changeInfo,
      boolean toChangeArguments,
      boolean toCatchExceptions,
      GrClosureSignatureUtil.ArgInfo<PsiElement>[] map,
      PsiSubstitutor substitutor) {
    if (map == null) return;
    if (changeInfo.isNameChanged()) {
      if (element instanceof GrReferenceElement) {
        element = ((GrReferenceElement) element).handleElementRename(changeInfo.getNewName());
      }
    }
    if (toChangeArguments) {
      JavaParameterInfo[] parameters = changeInfo.getNewParameters();
      GrArgumentList argumentList = PsiUtil.getArgumentsList(element);
      GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(element.getProject());
      if (argumentList == null) {
        if (element instanceof GrEnumConstant) {
          argumentList = factory.createArgumentList();
          argumentList = (GrArgumentList) element.add(argumentList);
        } else {
          return;
        }
      }
      Set<PsiElement> argsToDelete = new HashSet<PsiElement>(map.length * 2);
      for (GrClosureSignatureUtil.ArgInfo<PsiElement> argInfo : map) {
        argsToDelete.addAll(argInfo.args);
      }

      for (JavaParameterInfo parameter : parameters) {
        int index = parameter.getOldIndex();
        if (index >= 0) {
          argsToDelete.removeAll(map[index].args);
        }
      }

      for (PsiElement arg : argsToDelete) {
        arg.delete();
      }

      boolean skipOptionals = false;
      PsiElement anchor = null; // PsiTreeUtil.getChildOfAnyType(argumentList, GrExpression.class,
      // GrNamedArgument.class);
      for (int i = 0; i < parameters.length; i++) {
        JavaParameterInfo parameter = parameters[i];
        int index = parameter.getOldIndex();
        if (index >= 0) {
          GrClosureSignatureUtil.ArgInfo<PsiElement> argInfo = map[index];
          List<PsiElement> arguments = argInfo.args;
          if (argInfo.isMultiArg) { // arguments for Map and varArg
            if ((i != 0
                    || !(!arguments.isEmpty()
                        && arguments.iterator().next() instanceof GrNamedArgument))
                && (i != parameters.length - 1 || !parameter.isVarargType())) {
              final PsiType type =
                  parameter.createType(
                      changeInfo.getMethod().getParameterList(), argumentList.getManager());
              final GrExpression arg =
                  GroovyRefactoringUtil.generateArgFromMultiArg(
                      substitutor, arguments, type, element.getProject());
              for (PsiElement argument : arguments) {
                argument.delete();
              }
              anchor = argumentList.addAfter(arg, anchor);
              JavaCodeStyleManager.getInstance(anchor.getProject()).shortenClassReferences(anchor);
            }
          } else { // arguments for simple parameters
            if (arguments.size() == 1) { // arg exists
              PsiElement arg = arguments.iterator().next();
              if (i == parameters.length - 1 && parameter.isVarargType()) {
                if (arg instanceof GrSafeCastExpression) {
                  PsiElement expr = ((GrSafeCastExpression) arg).getOperand();
                  if (expr instanceof GrListOrMap && !((GrListOrMap) expr).isMap()) {
                    final PsiElement copy = expr.copy();
                    PsiElement[] newVarargs = ((GrListOrMap) copy).getInitializers();
                    for (PsiElement vararg : newVarargs) {
                      anchor = argumentList.addAfter(vararg, anchor);
                    }
                    arg.delete();
                    continue;
                  }
                }
              }

              PsiElement curArg = getNextOfType(argumentList, anchor, GrExpression.class);
              if (curArg == arg) {
                anchor = arg;
              } else {
                final PsiElement copy = arg.copy();
                anchor = argumentList.addAfter(copy, anchor);
                arg.delete();
              }
            } else { // arg is skipped. Parameter is optional
              skipOptionals = true;
            }
          }
        } else {
          if (skipOptionals && isParameterOptional(parameter)) continue;

          if (forceOptional(parameter)) {
            skipOptionals = true;
            continue;
          }
          try {

            GrExpression value = createDefaultValue(factory, changeInfo, parameter, argumentList);
            if (i > 0 && (value == null || anchor == null)) {
              PsiElement comma =
                  Factory.createSingleLeafElement(
                          GroovyTokenTypes.mCOMMA,
                          ",",
                          0,
                          1,
                          SharedImplUtil.findCharTableByTree(argumentList.getNode()),
                          argumentList.getManager())
                      .getPsi();
              if (anchor == null) anchor = argumentList.getLeftParen();

              anchor = argumentList.addAfter(comma, anchor);
            }
            if (value != null) {
              anchor = argumentList.addAfter(value, anchor);
            }
          } catch (IncorrectOperationException e) {
            LOG.error(e.getMessage());
          }
        }
      }

      GrCall call = GroovyRefactoringUtil.getCallExpressionByMethodReference(element);
      if (argumentList.getText().trim().isEmpty()
          && (call == null || !PsiImplUtil.hasClosureArguments(call))) {
        argumentList = argumentList.replaceWithArgumentList(factory.createArgumentList());
      }
      CodeStyleManager.getInstance(argumentList.getProject()).reformat(argumentList);
    }

    if (toCatchExceptions) {
      final ThrownExceptionInfo[] exceptionInfos = changeInfo.getNewExceptions();
      PsiClassType[] exceptions = getExceptions(exceptionInfos, element, element.getManager());
      fixExceptions(element, exceptions);
    }
  }
  private void detectLocalsCollisionsInMethod(
      final PsiMethod method, final ArrayList<UsageInfo> result, boolean isOriginal) {
    if (!JavaLanguage.INSTANCE.equals(method.getLanguage())) return;

    final PsiParameter[] parameters = method.getParameterList().getParameters();
    final Set<PsiParameter> deletedOrRenamedParameters = new HashSet<PsiParameter>();
    if (isOriginal) {
      ContainerUtil.addAll(deletedOrRenamedParameters, parameters);
      for (ParameterInfo parameterInfo : myChangeInfo.getNewParameters()) {
        if (parameterInfo.getOldIndex() >= 0 && parameterInfo.getOldIndex() < parameters.length) {
          final PsiParameter parameter = parameters[parameterInfo.getOldIndex()];
          if (parameterInfo.getName().equals(parameter.getName())) {
            deletedOrRenamedParameters.remove(parameter);
          }
        }
      }
    }

    for (ParameterInfo parameterInfo : myChangeInfo.getNewParameters()) {
      final int oldParameterIndex = parameterInfo.getOldIndex();
      final String newName = parameterInfo.getName();
      if (oldParameterIndex >= 0) {
        if (isOriginal
            && oldParameterIndex < parameters.length
            && !newName.equals(myChangeInfo.getOldParameterNames()[oldParameterIndex])) {
          // Name changes take place only in primary method when name was actually changed
          final PsiParameter parameter = parameters[oldParameterIndex];
          if (!newName.equals(parameter.getName())) {
            JavaUnresolvableLocalCollisionDetector.visitLocalsCollisions(
                parameter,
                newName,
                method.getBody(),
                null,
                new JavaUnresolvableLocalCollisionDetector.CollidingVariableVisitor() {
                  public void visitCollidingElement(final PsiVariable collidingVariable) {
                    if (!deletedOrRenamedParameters.contains(collidingVariable)) {
                      result.add(
                          new RenamedParameterCollidesWithLocalUsageInfo(
                              parameter, collidingVariable, method));
                    }
                  }
                });
          }
        }
      } else {
        JavaUnresolvableLocalCollisionDetector.visitLocalsCollisions(
            method,
            newName,
            method.getBody(),
            null,
            new JavaUnresolvableLocalCollisionDetector.CollidingVariableVisitor() {
              public void visitCollidingElement(PsiVariable collidingVariable) {
                if (!deletedOrRenamedParameters.contains(collidingVariable)) {
                  result.add(
                      new NewParameterCollidesWithLocalUsageInfo(
                          collidingVariable, collidingVariable, method));
                }
              }
            });
      }
    }
  }
  private PsiMethod[] findSimpleUsagesWithoutParameters(
      final PsiMethod method,
      final ArrayList<UsageInfo> result,
      boolean isToModifyArgs,
      boolean isToThrowExceptions,
      boolean isOriginal) {

    GlobalSearchScope projectScope = GlobalSearchScope.projectScope(method.getProject());
    PsiMethod[] overridingMethods =
        OverridingMethodsSearch.search(method, true).toArray(PsiMethod.EMPTY_ARRAY);

    for (PsiMethod overridingMethod : overridingMethods) {
      result.add(
          new OverriderUsageInfo(
              overridingMethod, method, isOriginal, isToModifyArgs, isToThrowExceptions));
    }

    boolean needToChangeCalls =
        !myChangeInfo.isGenerateDelegate()
            && (myChangeInfo.isNameChanged()
                || myChangeInfo.isParameterSetOrOrderChanged()
                || myChangeInfo.isExceptionSetOrOrderChanged()
                || myChangeInfo.isVisibilityChanged() /*for checking inaccessible*/);
    if (needToChangeCalls) {
      int parameterCount = method.getParameterList().getParametersCount();

      PsiReference[] refs =
          MethodReferencesSearch.search(method, projectScope, true)
              .toArray(PsiReference.EMPTY_ARRAY);
      for (PsiReference ref : refs) {
        PsiElement element = ref.getElement();

        boolean isToCatchExceptions =
            isToThrowExceptions
                && needToCatchExceptions(RefactoringUtil.getEnclosingMethod(element));
        if (!isToCatchExceptions) {
          if (RefactoringUtil.isMethodUsage(element)) {
            PsiExpressionList list = RefactoringUtil.getArgumentListByMethodReference(element);
            if (list == null
                || !method.isVarArgs() && list.getExpressions().length != parameterCount) continue;
          }
        }
        if (RefactoringUtil.isMethodUsage(element)) {
          result.add(new MethodCallUsageInfo(element, isToModifyArgs, isToCatchExceptions));
        } else if (element instanceof PsiDocTagValue) {
          result.add(new UsageInfo(element));
        } else if (element instanceof PsiMethod && ((PsiMethod) element).isConstructor()) {
          if (JavaLanguage.INSTANCE.equals(element.getLanguage())) {
            DefaultConstructorImplicitUsageInfo implicitUsageInfo =
                new DefaultConstructorImplicitUsageInfo(
                    (PsiMethod) element, ((PsiMethod) element).getContainingClass(), method);
            result.add(implicitUsageInfo);
          }
        } else if (element instanceof PsiClass) {
          LOG.assertTrue(method.isConstructor());
          final PsiClass psiClass = (PsiClass) element;
          if (JavaLanguage.INSTANCE.equals(psiClass.getLanguage())) {
            if (myChangeInfo instanceof JavaChangeInfo) {
              if (shouldPropagateToNonPhysicalMethod(
                  method,
                  result,
                  psiClass,
                  ((JavaChangeInfo) myChangeInfo).getMethodsToPropagateParameters())) {
                continue;
              }
            }
            result.add(new NoConstructorClassUsageInfo(psiClass));
          }
        } else if (ref instanceof PsiCallReference) {
          result.add(new CallReferenceUsageInfo((PsiCallReference) ref));
        } else {
          result.add(new MoveRenameUsageInfo(element, ref, method));
        }
      }

      // if (method.isConstructor() && parameterCount == 0) {
      //    RefactoringUtil.visitImplicitConstructorUsages(method.getContainingClass(),
      //                                                   new
      // DefaultConstructorUsageCollector(result));
      // }
    } else if (myChangeInfo.isParameterTypesChanged()) {
      PsiReference[] refs =
          MethodReferencesSearch.search(method, projectScope, true)
              .toArray(PsiReference.EMPTY_ARRAY);
      for (PsiReference reference : refs) {
        final PsiElement element = reference.getElement();
        if (element instanceof PsiDocTagValue) {
          result.add(new UsageInfo(reference));
        } else if (element instanceof XmlElement) {
          result.add(new MoveRenameUsageInfo(reference, method));
        } else if (element instanceof PsiMethodReferenceExpression) {
          result.add(new UsageInfo(reference));
        }
      }
    }

    // Conflicts
    detectLocalsCollisionsInMethod(method, result, isOriginal);
    for (final PsiMethod overridingMethod : overridingMethods) {
      detectLocalsCollisionsInMethod(overridingMethod, result, isOriginal);
    }

    return overridingMethods;
  }
  private static void processPrimaryMethod(
      JavaChangeInfo changeInfo, PsiMethod method, PsiMethod baseMethod, boolean isOriginal)
      throws IncorrectOperationException {
    PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory();

    if (changeInfo.isVisibilityChanged()) {
      PsiModifierList modifierList = method.getModifierList();
      final String highestVisibility =
          isOriginal
              ? changeInfo.getNewVisibility()
              : VisibilityUtil.getHighestVisibility(
                  changeInfo.getNewVisibility(),
                  VisibilityUtil.getVisibilityModifier(modifierList));
      VisibilityUtil.setVisibility(modifierList, highestVisibility);
    }

    if (changeInfo.isNameChanged()) {
      String newName =
          baseMethod == null
              ? changeInfo.getNewName()
              : RefactoringUtil.suggestNewOverriderName(
                  method.getName(), baseMethod.getName(), changeInfo.getNewName());

      if (newName != null && !newName.equals(method.getName())) {
        final PsiIdentifier nameId = method.getNameIdentifier();
        assert nameId != null;
        nameId.replace(
            JavaPsiFacade.getInstance(method.getProject())
                .getElementFactory()
                .createIdentifier(newName));
      }
    }

    final PsiSubstitutor substitutor =
        baseMethod == null
            ? PsiSubstitutor.EMPTY
            : ChangeSignatureProcessor.calculateSubstitutor(method, baseMethod);

    if (changeInfo.isReturnTypeChanged()) {
      PsiType newTypeElement =
          changeInfo
              .getNewReturnType()
              .getType(changeInfo.getMethod().getParameterList(), method.getManager());
      final PsiType returnType = substitutor.substitute(newTypeElement);
      // don't modify return type for non-Java overriders (EJB)
      if (method.getName().equals(changeInfo.getNewName())) {
        final PsiTypeElement typeElement = method.getReturnTypeElement();
        if (typeElement != null) {
          typeElement.replace(factory.createTypeElement(returnType));
        }
      }
    }

    PsiParameterList list = method.getParameterList();
    PsiParameter[] parameters = list.getParameters();

    final JavaParameterInfo[] parameterInfos = changeInfo.getNewParameters();
    final int delta =
        baseMethod != null
            ? baseMethod.getParameterList().getParametersCount()
                - method.getParameterList().getParametersCount()
            : 0;
    PsiParameter[] newParms = new PsiParameter[Math.max(parameterInfos.length - delta, 0)];
    final String[] oldParameterNames = changeInfo.getOldParameterNames();
    final String[] oldParameterTypes = changeInfo.getOldParameterTypes();
    for (int i = 0; i < newParms.length; i++) {
      JavaParameterInfo info = parameterInfos[i];
      int index = info.getOldIndex();
      if (index >= 0) {
        PsiParameter parameter = parameters[index];
        newParms[i] = parameter;

        String oldName = oldParameterNames[index];
        if (!oldName.equals(info.getName()) && oldName.equals(parameter.getName())) {
          PsiIdentifier newIdentifier = factory.createIdentifier(info.getName());
          parameter.getNameIdentifier().replace(newIdentifier);
        }

        String oldType = oldParameterTypes[index];
        if (!oldType.equals(info.getTypeText())) {
          parameter.normalizeDeclaration();
          PsiType newType =
              substitutor.substitute(
                  info.createType(changeInfo.getMethod().getParameterList(), method.getManager()));

          parameter.getTypeElement().replace(factory.createTypeElement(newType));
        }
      } else {
        newParms[i] = createNewParameter(changeInfo, info, substitutor);
      }
    }

    resolveParameterVsFieldsConflicts(newParms, method, list, changeInfo.toRemoveParm());
    fixJavadocsForChangedMethod(method, changeInfo, newParms.length);
    if (changeInfo.isExceptionSetOrOrderChanged()) {
      final PsiClassType[] newExceptions = getPrimaryChangedExceptionInfo(changeInfo);
      fixPrimaryThrowsLists(method, newExceptions);
    }
  }
 private boolean needToChangeCalls() {
   return myChangeInfo.isNameChanged()
       || myChangeInfo.isParameterSetOrOrderChanged()
       || myChangeInfo.isExceptionSetOrOrderChanged();
 }
  // This methods works equally well for primary usages as well as for propagated callers' usages
  private static void fixActualArgumentsList(
      PsiExpressionList list,
      JavaChangeInfo changeInfo,
      boolean toInsertDefaultValue,
      PsiSubstitutor substitutor)
      throws IncorrectOperationException {
    final PsiElementFactory factory =
        JavaPsiFacade.getInstance(list.getProject()).getElementFactory();
    if (changeInfo.isParameterSetOrOrderChanged()) {
      if (changeInfo instanceof JavaChangeInfoImpl
          && ((JavaChangeInfoImpl) changeInfo).isPropagationEnabled) {
        final ParameterInfoImpl[] createdParmsInfo =
            ((JavaChangeInfoImpl) changeInfo).getCreatedParmsInfoWithoutVarargs();
        for (ParameterInfoImpl info : createdParmsInfo) {
          PsiExpression newArg;
          if (toInsertDefaultValue) {
            newArg = createDefaultValue(changeInfo, factory, info, list);
          } else {
            newArg = factory.createExpressionFromText(info.getName(), list);
          }
          JavaCodeStyleManager.getInstance(list.getProject())
              .shortenClassReferences(list.add(newArg));
        }
      } else {
        final PsiExpression[] args = list.getExpressions();
        final int nonVarargCount = getNonVarargCount(changeInfo, args);
        final int varargCount = args.length - nonVarargCount;
        if (varargCount < 0) return;
        PsiExpression[] newVarargInitializers = null;

        final int newArgsLength;
        final int newNonVarargCount;
        final JavaParameterInfo[] newParms = changeInfo.getNewParameters();
        if (changeInfo.isArrayToVarargs()) {
          newNonVarargCount = newParms.length - 1;
          final JavaParameterInfo lastNewParm = newParms[newParms.length - 1];
          final PsiExpression arrayToConvert = args[lastNewParm.getOldIndex()];
          if (arrayToConvert instanceof PsiNewExpression) {
            final PsiNewExpression expression = (PsiNewExpression) arrayToConvert;
            final PsiArrayInitializerExpression arrayInitializer = expression.getArrayInitializer();
            if (arrayInitializer != null) {
              newVarargInitializers = arrayInitializer.getInitializers();
            }
          }
          newArgsLength =
              newVarargInitializers == null
                  ? newParms.length
                  : newNonVarargCount + newVarargInitializers.length;
        } else if (changeInfo.isRetainsVarargs()) {
          newNonVarargCount = newParms.length - 1;
          newArgsLength = newNonVarargCount + varargCount;
        } else if (changeInfo.isObtainsVarags()) {
          newNonVarargCount = newParms.length - 1;
          newArgsLength = newNonVarargCount;
        } else {
          newNonVarargCount = newParms.length;
          newArgsLength = newParms.length;
        }

        String[] oldVarargs = null;
        if (changeInfo.wasVararg() && !changeInfo.isRetainsVarargs()) {
          oldVarargs = new String[varargCount];
          for (int i = nonVarargCount; i < args.length; i++) {
            oldVarargs[i - nonVarargCount] = args[i].getText();
          }
        }

        final PsiExpression[] newArgs = new PsiExpression[newArgsLength];
        for (int i = 0; i < newNonVarargCount; i++) {
          if (newParms[i].getOldIndex() == nonVarargCount && oldVarargs != null) {
            PsiType type = newParms[i].createType(changeInfo.getMethod(), list.getManager());
            if (type instanceof PsiArrayType) {
              type = substitutor.substitute(type);
              type = TypeConversionUtil.erasure(type);
              String typeText = type.getCanonicalText();
              if (type instanceof PsiEllipsisType) {
                typeText = typeText.replace("...", "[]");
              }
              String text = "new " + typeText + "{" + StringUtil.join(oldVarargs, ",") + "}";
              newArgs[i] = factory.createExpressionFromText(text, changeInfo.getMethod());
              continue;
            }
          }
          newArgs[i] =
              createActualArgument(changeInfo, list, newParms[i], toInsertDefaultValue, args);
        }
        if (changeInfo.isArrayToVarargs()) {
          if (newVarargInitializers == null) {
            newArgs[newNonVarargCount] =
                createActualArgument(
                    changeInfo, list, newParms[newNonVarargCount], toInsertDefaultValue, args);
          } else {
            System.arraycopy(
                newVarargInitializers, 0, newArgs, newNonVarargCount, newVarargInitializers.length);
          }
        } else {
          final int newVarargCount = newArgsLength - newNonVarargCount;
          LOG.assertTrue(newVarargCount == 0 || newVarargCount == varargCount);
          for (int i = newNonVarargCount; i < newArgsLength; i++) {
            final int oldIndex = newParms[newNonVarargCount].getOldIndex();
            if (oldIndex >= 0 && oldIndex != nonVarargCount) {
              newArgs[i] =
                  createActualArgument(
                      changeInfo, list, newParms[newNonVarargCount], toInsertDefaultValue, args);
            } else {
              System.arraycopy(args, nonVarargCount, newArgs, newNonVarargCount, newVarargCount);
              break;
            }
          }
        }
        ChangeSignatureUtil.synchronizeList(
            list, Arrays.asList(newArgs), ExpressionList.INSTANCE, changeInfo.toRemoveParm());
      }
    }
  }
  @Nullable
  private static PsiExpression createDefaultValue(
      JavaChangeInfo changeInfo,
      final PsiElementFactory factory,
      final JavaParameterInfo info,
      final PsiExpressionList list)
      throws IncorrectOperationException {
    if (info.isUseAnySingleVariable()) {
      final PsiResolveHelper resolveHelper =
          JavaPsiFacade.getInstance(list.getProject()).getResolveHelper();
      final PsiType type = info.getTypeWrapper().getType(changeInfo.getMethod(), list.getManager());
      final VariablesProcessor processor =
          new VariablesProcessor(false) {
            protected boolean check(PsiVariable var, ResolveState state) {
              if (var instanceof PsiField
                  && !resolveHelper.isAccessible((PsiField) var, list, null)) return false;
              if (var instanceof PsiLocalVariable
                  && list.getTextRange().getStartOffset() <= var.getTextRange().getStartOffset())
                return false;
              if (PsiTreeUtil.isAncestor(var, list, false)) return false;
              final PsiType varType = state.get(PsiSubstitutor.KEY).substitute(var.getType());
              return type.isAssignableFrom(varType);
            }

            public boolean execute(PsiElement pe, ResolveState state) {
              super.execute(pe, state);
              return size() < 2;
            }
          };
      PsiScopesUtil.treeWalkUp(processor, list, null);
      if (processor.size() == 1) {
        final PsiVariable result = processor.getResult(0);
        return factory.createExpressionFromText(result.getName(), list);
      }
      if (processor.size() == 0) {
        final PsiClass parentClass = PsiTreeUtil.getParentOfType(list, PsiClass.class);
        if (parentClass != null) {
          PsiClass containingClass = parentClass;
          final Set<PsiClass> containingClasses = new HashSet<PsiClass>();
          while (containingClass != null) {
            if (type.isAssignableFrom(factory.createType(containingClass, PsiSubstitutor.EMPTY))) {
              containingClasses.add(containingClass);
            }
            containingClass = PsiTreeUtil.getParentOfType(containingClass, PsiClass.class);
          }
          if (containingClasses.size() == 1) {
            return RefactoringUtil.createThisExpression(
                parentClass.getManager(),
                containingClasses.contains(parentClass)
                    ? null
                    : containingClasses.iterator().next());
          }
        }
      }
    }
    final PsiCallExpression callExpression =
        PsiTreeUtil.getParentOfType(list, PsiCallExpression.class);
    final String defaultValue = info.getDefaultValue();
    return callExpression != null
        ? info.getValue(callExpression)
        : defaultValue.length() > 0 ? factory.createExpressionFromText(defaultValue, list) : null;
  }
 private static int getNonVarargCount(JavaChangeInfo changeInfo, PsiExpression[] args) {
   if (!changeInfo.wasVararg()) return args.length;
   return changeInfo.getOldParameterTypes().length - 1;
 }