@Override
  protected PsiMethod findOrCreateSetUpMethod(PsiClass clazz) throws IncorrectOperationException {
    LOG.assertTrue(clazz.getLanguage() == GroovyFileType.GROOVY_LANGUAGE);
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(clazz.getProject());

    final PsiMethod patternMethod = createSetUpPatternMethod(factory);

    final PsiClass baseClass = clazz.getSuperClass();
    if (baseClass != null) {
      final PsiMethod baseMethod = baseClass.findMethodBySignature(patternMethod, false);
      if (baseMethod != null && baseMethod.hasModifierProperty(PsiModifier.PUBLIC)) {
        PsiUtil.setModifierProperty(patternMethod, PsiModifier.PROTECTED, false);
        PsiUtil.setModifierProperty(patternMethod, PsiModifier.PUBLIC, true);
      }
    }

    PsiMethod inClass = clazz.findMethodBySignature(patternMethod, false);
    if (inClass == null) {
      PsiMethod testMethod = JUnitUtil.findFirstTestMethod(clazz);
      if (testMethod != null) {
        return (PsiMethod) clazz.addBefore(patternMethod, testMethod);
      }
      return (PsiMethod) clazz.add(patternMethod);
    } else if (inClass.getBody() == null) {
      return (PsiMethod) inClass.replace(patternMethod);
    }
    return inClass;
  }
 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);
     }
   }
 }
  @NotNull
  @Override
  public PsiDeclarationStatement createVariableDeclarationStatement(
      @NotNull String name, @NotNull PsiType type, @Nullable PsiExpression initializer)
      throws IncorrectOperationException {
    if (!isIdentifier(name)) {
      throw new IncorrectOperationException("\"" + name + "\" is not an identifier.");
    }
    if (PsiType.NULL.equals(type)) {
      throw new IncorrectOperationException("Cannot create variable with type \"null\".");
    }

    String text = "X " + name + (initializer != null ? " = x" : "") + ";";
    PsiDeclarationStatement statement =
        (PsiDeclarationStatement) createStatementFromText(text, null);

    PsiVariable variable = (PsiVariable) statement.getDeclaredElements()[0];
    replace(variable.getTypeElement(), createTypeElement(type), text);

    boolean generateFinalLocals =
        JavaCodeStyleSettingsFacade.getInstance(myManager.getProject()).isGenerateFinalLocals();
    PsiUtil.setModifierProperty(variable, PsiModifier.FINAL, generateFinalLocals);

    if (initializer != null) {
      replace(variable.getInitializer(), initializer, text);
    }

    GeneratedMarkerVisitor.markGenerated(statement);
    return statement;
  }
 private void makeFinal() {
   for (PsiVariable var : getVariablesToFix()) {
     if (var.isValid()) {
       PsiUtil.setModifierProperty(var, PsiModifier.FINAL, true);
     }
   }
 }
 public static void setNewFieldVisibility(PsiField field, EncapsulateFieldsDescriptor descriptor) {
   try {
     if (descriptor.getFieldsVisibility() != null) {
       field.normalizeDeclaration();
       PsiUtil.setModifierProperty(field, descriptor.getFieldsVisibility(), true);
     }
   } catch (IncorrectOperationException e) {
     LOG.error(e);
   }
 }
  public void setCorrectVisibility(final HashSet<PsiMember> movedMembers, GrMemberInfo info) {
    PsiModifierListOwner modifierListOwner = info.getMember();
    if (myTargetSuperClass.isInterface()) {
      PsiUtil.setModifierProperty(modifierListOwner, PsiModifier.PUBLIC, true);
    } else if (modifierListOwner.hasModifierProperty(PsiModifier.PRIVATE)) {
      if (info.isToAbstract()
          || willBeUsedInSubclass(
              modifierListOwner, movedMembers, myTargetSuperClass, mySourceClass)) {
        PsiUtil.setModifierProperty(modifierListOwner, PsiModifier.PROTECTED, true);
      }

      if (modifierListOwner instanceof GrTypeDefinition) {
        ((GrTypeDefinition) modifierListOwner)
            .accept(
                new GroovyRecursiveElementVisitor() {
                  @Override
                  public void visitMethod(GrMethod method) {
                    check(method);
                  }

                  @Override
                  public void visitField(GrField field) {
                    check(field);
                  }

                  @Override
                  public void visitTypeDefinition(GrTypeDefinition typeDefinition) {
                    check(typeDefinition);
                    super.visitTypeDefinition(typeDefinition);
                  }

                  private void check(PsiMember member) {
                    if (member.hasModifierProperty(PsiModifier.PRIVATE)) {
                      if (willBeUsedInSubclass(
                          member, movedMembers, myTargetSuperClass, mySourceClass)) {
                        PsiUtil.setModifierProperty(member, PsiModifier.PROTECTED, true);
                      }
                    }
                  }
                });
      }
    }
  }
  private PsiMethod generateMethodFor(
      PsiField field, String methodName, String parameterName, PsiElementFactory elementFactory) {
    PsiMethod withMethod =
        elementFactory.createMethod(
            methodName, elementFactory.createType(field.getContainingClass()));
    PsiParameter parameter = elementFactory.createParameter(parameterName, field.getType());
    withMethod.getParameterList().add(parameter);
    PsiUtil.setModifierProperty(withMethod, PsiModifier.PUBLIC, true);

    return withMethod;
  }
  @Override
  public void invoke(@NotNull Project project, Editor editor, PsiFile file) {
    if (!CodeInsightUtilBase.prepareFileForWrite(myMethod.getContainingFile())) return;

    try {
      PsiUtil.setModifierProperty(myMethod, PsiModifier.ABSTRACT, false);
      CreateFromUsageUtils.setupMethodBody(myMethod);
      CreateFromUsageUtils.setupEditor(myMethod, editor);
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
  @Override
  public void setCorrectVisibility(MemberInfo info) {
    PsiModifierListOwner modifierListOwner = info.getMember();
    if (myIsTargetInterface) {
      PsiUtil.setModifierProperty(modifierListOwner, PsiModifier.PUBLIC, true);
    } else if (modifierListOwner.hasModifierProperty(PsiModifier.PRIVATE)) {
      if (info.isToAbstract()
          || willBeUsedInSubclass(modifierListOwner, myTargetSuperClass, mySourceClass)) {
        PsiUtil.setModifierProperty(modifierListOwner, PsiModifier.PROTECTED, true);
      }
      if (modifierListOwner instanceof PsiClass) {
        modifierListOwner.accept(
            new JavaRecursiveElementWalkingVisitor() {
              @Override
              public void visitMethod(PsiMethod method) {
                check(method);
              }

              @Override
              public void visitField(PsiField field) {
                check(field);
              }

              @Override
              public void visitClass(PsiClass aClass) {
                check(aClass);
                super.visitClass(aClass);
              }

              private void check(PsiMember member) {
                if (member.hasModifierProperty(PsiModifier.PRIVATE)) {
                  if (willBeUsedInSubclass(member, myTargetSuperClass, mySourceClass)) {
                    PsiUtil.setModifierProperty(member, PsiModifier.PROTECTED, true);
                  }
                }
              }
            });
      }
    }
  }
 private void addParameters(
     final PsiElementFactory factory, final PsiMethod methodCopy, final boolean isInterface)
     throws IncorrectOperationException {
   final Set<Map.Entry<PsiClass, String>> entries = myOldClassParameterNames.entrySet();
   for (final Map.Entry<PsiClass, String> entry : entries) {
     final PsiClassType type = factory.createType(entry.getKey());
     final PsiParameter parameter = factory.createParameter(entry.getValue(), type);
     if (isInterface) {
       PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, false);
     }
     methodCopy.getParameterList().add(parameter);
   }
 }
 private void doMoveField(PsiSubstitutor substitutor, GrMemberInfo info) {
   GroovyPsiElementFactory elementFactory = GroovyPsiElementFactory.getInstance(myProject);
   GrField field = (GrField) info.getMember();
   field.normalizeDeclaration();
   replaceMovedMemberTypeParameters(
       field, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
   // fixReferencesToStatic(field, movedMembers);
   if (myTargetSuperClass.isInterface()) {
     PsiUtil.setModifierProperty(field, PsiModifier.PUBLIC, true);
   }
   final PsiMember movedElement = (PsiMember) myTargetSuperClass.add(field);
   myMembersAfterMove.add(movedElement);
   deleteMemberWithDocComment(field);
 }
 private void copyToFinal() throws IncorrectOperationException {
   PsiManager psiManager = myClass.getManager();
   PsiElementFactory factory =
       JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
   PsiExpression initializer = factory.createExpressionFromText(myVariable.getName(), myClass);
   String newName = suggestNewName(psiManager.getProject(), myVariable);
   PsiType type = myVariable.getType();
   PsiDeclarationStatement copyDecl =
       factory.createVariableDeclarationStatement(newName, type, initializer);
   PsiVariable newVariable = (PsiVariable) copyDecl.getDeclaredElements()[0];
   PsiUtil.setModifierProperty(newVariable, PsiModifier.FINAL, true);
   PsiElement statement = getStatementToInsertBefore();
   if (statement == null) return;
   statement.getParent().addBefore(copyDecl, statement);
   PsiExpression newExpression = factory.createExpressionFromText(newName, myVariable);
   replaceReferences(myClass, myVariable, newExpression);
 }
 private PsiMethod addOrChangeAccessor(
     PsiMethod prototype, HashMap<String, PsiMethod> nameToAncestor) {
   PsiMethod existing = myClass.findMethodBySignature(prototype, false);
   PsiMethod result = existing;
   try {
     if (existing == null) {
       PsiUtil.setModifierProperty(prototype, myDescriptor.getAccessorsVisibility(), true);
       result = (PsiMethod) myClass.add(prototype);
     } else {
       // TODO : change visibility
     }
     nameToAncestor.put(prototype.getName(), result);
     return result;
   } catch (IncorrectOperationException e) {
     LOG.error(e);
   }
   return null;
 }
  protected void doFix(Project project, ProblemDescriptor descriptor, boolean external)
      throws IncorrectOperationException {
    PsiElement element = myPointer.getElement();
    if (!(element instanceof PsiClass)) return;
    PsiClass clazz = (PsiClass) element;

    PsiMethod ctor =
        JavaPsiFacade.getInstance(clazz.getProject()).getElementFactory().createConstructor();
    PsiUtil.setModifierProperty(ctor, PsiModifier.PUBLIC, true);

    PsiMethod[] constructors = clazz.getConstructors();
    if (constructors.length > 0) {
      ctor = (PsiMethod) clazz.addBefore(ctor, constructors[0]);
    } else {
      // shouldn't get here - it's legal if there's no ctor present at all
      ctor = (PsiMethod) clazz.add(ctor);
    }

    if (myOnTheFly) ctor.navigate(true);
  }
  private void doMoveField(PsiSubstitutor substitutor, MemberInfo info) {
    PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject);
    PsiField field = (PsiField) info.getMember();

    if (field instanceof HaxeVarDeclarationPart) {
      field = (HaxeVarDeclaration) field.getParent();
    }

    field.normalizeDeclaration();
    RefactoringUtil.replaceMovedMemberTypeParameters(
        field, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
    fixReferencesToStatic(field);
    if (myIsTargetInterface) {
      PsiUtil.setModifierProperty(field, PsiModifier.PUBLIC, true);
    }
    final PsiMember movedElement =
        (PsiMember)
            myTargetSuperClass.addBefore(
                convertFieldToLanguage(field, myTargetSuperClass.getLanguage()),
                myTargetSuperClass.getRBrace());
    myMembersAfterMove.add(movedElement);
    field.delete();
  }
  private PsiMethod getPatternMethod() throws IncorrectOperationException {
    final PsiMethod methodCopy = (PsiMethod) myMethod.copy();
    String name =
        myTargetClass.isInterface()
            ? PsiModifier.PUBLIC
            : !Comparing.strEqual(myNewVisibility, VisibilityUtil.ESCALATE_VISIBILITY)
                ? myNewVisibility
                : null;
    if (name != null) {
      PsiUtil.setModifierProperty(methodCopy, name, true);
    }
    if (myTargetVariable instanceof PsiParameter) {
      final int index =
          myMethod.getParameterList().getParameterIndex((PsiParameter) myTargetVariable);
      methodCopy.getParameterList().getParameters()[index].delete();
    }

    addParameters(
        JavaPsiFacade.getInstance(myProject).getElementFactory(),
        methodCopy,
        myTargetClass.isInterface());
    return methodCopy;
  }
  private void makeArray(PsiVariable variable) throws IncorrectOperationException {
    PsiType type = variable.getType();

    PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory();
    PsiType newType = type.createArrayType();

    PsiDeclarationStatement variableDeclarationStatement;
    PsiExpression initializer = variable.getInitializer();
    if (initializer == null) {
      String expression = "[1]";
      while (type instanceof PsiArrayType) {
        expression += "[1]";
        type = ((PsiArrayType) type).getComponentType();
      }
      PsiExpression init =
          factory.createExpressionFromText("new " + type.getCanonicalText() + expression, variable);
      variableDeclarationStatement =
          factory.createVariableDeclarationStatement(variable.getName(), newType, init);
    } else {
      PsiExpression init =
          factory.createExpressionFromText("{ " + initializer.getText() + " }", variable);
      variableDeclarationStatement =
          factory.createVariableDeclarationStatement(variable.getName(), newType, init);
    }
    PsiVariable newVariable = (PsiVariable) variableDeclarationStatement.getDeclaredElements()[0];
    PsiUtil.setModifierProperty(newVariable, PsiModifier.FINAL, true);
    PsiElement newExpression =
        factory.createExpressionFromText(variable.getName() + "[0]", variable);

    PsiElement outerCodeBlock = PsiUtil.getVariableCodeBlock(variable, null);
    if (outerCodeBlock == null) return;
    List<PsiReferenceExpression> outerReferences = new ArrayList<PsiReferenceExpression>();
    collectReferences(outerCodeBlock, variable, outerReferences);
    replaceReferences(outerReferences, newExpression);
    variable.replace(newVariable);
  }
  @NotNull
  @Override
  public PsiParameter createParameter(@NotNull final String name, @NotNull final PsiType type)
      throws IncorrectOperationException {
    PsiUtil.checkIsIdentifier(myManager, name);
    if (PsiType.NULL.equals(type)) {
      throw new IncorrectOperationException("Cannot create parameter with type \"null\".");
    }

    final String text = type.getCanonicalText() + " " + name;
    PsiParameter parameter = createParameterFromText(text, null);
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myManager.getProject());
    PsiUtil.setModifierProperty(
        parameter,
        PsiModifier.FINAL,
        JavaCodeStyleSettingsFacade.getInstance(myManager.getProject())
            .isGenerateFinalParameters());
    GeneratedMarkerVisitor.markGenerated(parameter);
    parameter =
        (PsiParameter)
            JavaCodeStyleManager.getInstance(myManager.getProject())
                .shortenClassReferences(parameter);
    return (PsiParameter) codeStyleManager.reformat(parameter);
  }
  public void invoke(@NotNull Project project, Editor editor, PsiFile file)
      throws IncorrectOperationException {
    LOG.assertTrue(myOutOfScopeVariable != null);
    PsiManager manager = file.getManager();
    myOutOfScopeVariable.normalizeDeclaration();
    PsiUtil.setModifierProperty(myOutOfScopeVariable, PsiModifier.FINAL, false);
    PsiElement commonParent =
        PsiTreeUtil.findCommonParent(myOutOfScopeVariable, myUnresolvedReference);
    LOG.assertTrue(commonParent != null);
    PsiElement child =
        myOutOfScopeVariable.getTextRange().getStartOffset()
                < myUnresolvedReference.getTextRange().getStartOffset()
            ? myOutOfScopeVariable
            : myUnresolvedReference;

    while (child.getParent() != commonParent) child = child.getParent();
    PsiDeclarationStatement newDeclaration =
        (PsiDeclarationStatement)
            JavaPsiFacade.getInstance(manager.getProject())
                .getElementFactory()
                .createStatementFromText("int i = 0", null);
    PsiVariable variable =
        (PsiVariable) newDeclaration.getDeclaredElements()[0].replace(myOutOfScopeVariable);
    if (variable.getInitializer() != null) {
      variable.getInitializer().delete();
    }

    while (!(child instanceof PsiStatement) || !(child.getParent() instanceof PsiCodeBlock)) {
      child = child.getParent();
      commonParent = commonParent.getParent();
    }
    LOG.assertTrue(commonParent != null);
    PsiDeclarationStatement added =
        (PsiDeclarationStatement) commonParent.addBefore(newDeclaration, child);
    PsiLocalVariable addedVar = (PsiLocalVariable) added.getDeclaredElements()[0];
    manager.getCodeStyleManager().reformat(commonParent);

    // Leave initializer assignment
    PsiExpression initializer = myOutOfScopeVariable.getInitializer();
    if (initializer != null) {
      PsiExpressionStatement assignment =
          (PsiExpressionStatement)
              JavaPsiFacade.getInstance(manager.getProject())
                  .getElementFactory()
                  .createStatementFromText(myOutOfScopeVariable.getName() + "= e;", null);
      ((PsiAssignmentExpression) assignment.getExpression()).getRExpression().replace(initializer);
      assignment = (PsiExpressionStatement) manager.getCodeStyleManager().reformat(assignment);
      PsiDeclarationStatement declStatement =
          PsiTreeUtil.getParentOfType(myOutOfScopeVariable, PsiDeclarationStatement.class);
      LOG.assertTrue(declStatement != null);
      PsiElement parent = declStatement.getParent();
      if (parent instanceof PsiForStatement) {
        declStatement.replace(assignment);
      } else {
        parent.addAfter(assignment, declStatement);
      }
    }

    if (myOutOfScopeVariable.isValid()) {
      myOutOfScopeVariable.delete();
    }

    if (HighlightControlFlowUtil.checkVariableInitializedBeforeUsage(
            myUnresolvedReference,
            addedVar,
            new THashMap<PsiElement, Collection<PsiReferenceExpression>>())
        != null) {
      initialize(addedVar);
    }

    DaemonCodeAnalyzer.getInstance(project).updateVisibleHighlighters(editor);
  }
  public static PsiMethod generateConstructorPrototype(
      PsiClass aClass, PsiMethod baseConstructor, boolean copyJavaDoc, PsiField[] fields)
      throws IncorrectOperationException {
    PsiManager manager = aClass.getManager();
    JVMElementFactory factory =
        JVMElementFactories.requireFactory(aClass.getLanguage(), aClass.getProject());
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());

    PsiMethod constructor = factory.createConstructor(aClass.getName(), aClass);
    String modifier = PsiUtil.getMaximumModifierForMember(aClass, false);

    if (modifier != null) {
      PsiUtil.setModifierProperty(constructor, modifier, true);
    }

    if (baseConstructor != null) {
      PsiJavaCodeReferenceElement[] throwRefs =
          baseConstructor.getThrowsList().getReferenceElements();
      for (PsiJavaCodeReferenceElement ref : throwRefs) {
        constructor.getThrowsList().add(ref);
      }

      if (copyJavaDoc) {
        final PsiDocComment docComment =
            ((PsiMethod) baseConstructor.getNavigationElement()).getDocComment();
        if (docComment != null) {
          constructor.addAfter(docComment, null);
        }
      }
    }

    boolean isNotEnum = false;
    if (baseConstructor != null) {
      PsiClass superClass = aClass.getSuperClass();
      LOG.assertTrue(superClass != null);
      if (!CommonClassNames.JAVA_LANG_ENUM.equals(superClass.getQualifiedName())) {
        isNotEnum = true;
        if (baseConstructor instanceof PsiCompiledElement) { // to get some parameter names
          PsiClass dummyClass =
              JVMElementFactories.requireFactory(
                      baseConstructor.getLanguage(), baseConstructor.getProject())
                  .createClass("Dummy");
          baseConstructor = (PsiMethod) dummyClass.add(baseConstructor);
        }
        PsiParameter[] params = baseConstructor.getParameterList().getParameters();
        for (PsiParameter param : params) {
          PsiParameter newParam = factory.createParameter(param.getName(), param.getType(), aClass);
          GenerateMembersUtil.copyOrReplaceModifierList(param, newParam);
          constructor.getParameterList().add(newParam);
        }
      }
    }

    JavaCodeStyleManager javaStyle = JavaCodeStyleManager.getInstance(aClass.getProject());

    final PsiMethod dummyConstructor = factory.createConstructor(aClass.getName());
    dummyConstructor.getParameterList().replace(constructor.getParameterList().copy());
    List<PsiParameter> fieldParams = new ArrayList<PsiParameter>();
    for (PsiField field : fields) {
      String fieldName = field.getName();
      String name = javaStyle.variableNameToPropertyName(fieldName, VariableKind.FIELD);
      String parmName = javaStyle.propertyNameToVariableName(name, VariableKind.PARAMETER);
      parmName = javaStyle.suggestUniqueVariableName(parmName, dummyConstructor, true);
      PsiParameter parm = factory.createParameter(parmName, field.getType(), aClass);

      final NullableNotNullManager nullableManager =
          NullableNotNullManager.getInstance(field.getProject());
      final String notNull = nullableManager.getNotNull(field);
      if (notNull != null) {
        parm.getModifierList()
            .addAfter(factory.createAnnotationFromText("@" + notNull, field), null);
      }

      constructor.getParameterList().add(parm);
      dummyConstructor.getParameterList().add(parm.copy());
      fieldParams.add(parm);
    }

    ConstructorBodyGenerator generator =
        ConstructorBodyGenerator.INSTANCE.forLanguage(aClass.getLanguage());
    if (generator != null) {
      @NonNls StringBuilder buffer = new StringBuilder();
      generator.start(buffer, constructor.getName(), PsiParameter.EMPTY_ARRAY);
      if (isNotEnum) {
        generator.generateSuperCallIfNeeded(
            buffer, baseConstructor.getParameterList().getParameters());
      }
      generator.generateFieldInitialization(
          buffer, fields, fieldParams.toArray(new PsiParameter[fieldParams.size()]));
      generator.finish(buffer);
      PsiMethod stub = factory.createMethodFromText(buffer.toString(), aClass);
      constructor.getBody().replace(stub.getBody());
    }

    constructor = (PsiMethod) codeStyleManager.reformat(constructor);
    return constructor;
  }
  private void tryToMoveInitializers(
      PsiMethod constructor,
      HashSet<PsiMethod> subConstructors,
      LinkedHashSet<PsiField> movedFields)
      throws IncorrectOperationException {
    final LinkedHashMap<PsiField, Initializer> fieldsToInitializers =
        new LinkedHashMap<PsiField, Initializer>();
    boolean anyFound = false;

    for (PsiField field : movedFields) {
      PsiStatement commonInitializer = null;
      final ArrayList<PsiElement> fieldInitializersToRemove = new ArrayList<PsiElement>();
      for (PsiMethod subConstructor : subConstructors) {
        commonInitializer =
            hasCommonInitializer(
                commonInitializer, subConstructor, field, fieldInitializersToRemove);
        if (commonInitializer == null) break;
      }
      if (commonInitializer != null) {
        final ParametersAndMovedFieldsUsedCollector visitor =
            new ParametersAndMovedFieldsUsedCollector(movedFields);
        commonInitializer.accept(visitor);
        fieldsToInitializers.put(
            field,
            new Initializer(
                commonInitializer,
                visitor.getUsedFields(),
                visitor.getUsedParameters(),
                fieldInitializersToRemove));
        anyFound = true;
      }
    }

    if (!anyFound) return;

    {
      final Set<PsiField> initializedFields = fieldsToInitializers.keySet();
      Set<PsiField> unmovable =
          RefactoringUtil.transitiveClosure(
              new RefactoringUtil.Graph<PsiField>() {
                public Set<PsiField> getVertices() {
                  return initializedFields;
                }

                public Set<PsiField> getTargets(PsiField source) {
                  return fieldsToInitializers.get(source).movedFieldsUsed;
                }
              },
              new Condition<PsiField>() {
                public boolean value(PsiField object) {
                  return !initializedFields.contains(object);
                }
              });

      for (PsiField psiField : unmovable) {
        fieldsToInitializers.remove(psiField);
      }
    }

    final PsiElementFactory factory = JavaPsiFacade.getElementFactory(myProject);

    if (constructor == null) {
      constructor = (PsiMethod) myTargetSuperClass.add(factory.createConstructor());
      final String visibilityModifier =
          VisibilityUtil.getVisibilityModifier(myTargetSuperClass.getModifierList());
      PsiUtil.setModifierProperty(constructor, visibilityModifier, true);
    }

    ArrayList<PsiField> initializedFields = new ArrayList<PsiField>(fieldsToInitializers.keySet());

    Collections.sort(
        initializedFields,
        new Comparator<PsiField>() {
          public int compare(PsiField field1, PsiField field2) {
            Initializer i1 = fieldsToInitializers.get(field1);
            Initializer i2 = fieldsToInitializers.get(field2);
            if (i1.movedFieldsUsed.contains(field2)) return 1;
            if (i2.movedFieldsUsed.contains(field1)) return -1;
            return 0;
          }
        });

    for (final PsiField initializedField : initializedFields) {
      Initializer initializer = fieldsToInitializers.get(initializedField);

      // correct constructor parameters and subConstructors super calls
      final PsiParameterList parameterList = constructor.getParameterList();
      for (final PsiParameter parameter : initializer.usedParameters) {
        parameterList.add(parameter);
      }

      for (final PsiMethod subConstructor : subConstructors) {
        modifySuperCall(subConstructor, initializer.usedParameters);
      }

      PsiStatement assignmentStatement =
          (PsiStatement) constructor.getBody().add(initializer.initializer);

      PsiManager manager = PsiManager.getInstance(myProject);
      ChangeContextUtil.decodeContextInfo(
          assignmentStatement,
          myTargetSuperClass,
          RefactoringChangeUtil.createThisExpression(manager, null));
      for (PsiElement psiElement : initializer.statementsToRemove) {
        psiElement.delete();
      }
    }
  }
  private void doMoveMethod(PsiSubstitutor substitutor, MemberInfo info) {
    PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject);
    PsiMethod method = (PsiMethod) info.getMember();
    PsiMethod sibling = method;
    PsiMethod anchor = null;
    while (sibling != null) {
      sibling = PsiTreeUtil.getNextSiblingOfType(sibling, PsiMethod.class);
      if (sibling != null) {
        anchor =
            MethodSignatureUtil.findMethodInSuperClassBySignatureInDerived(
                method.getContainingClass(),
                myTargetSuperClass,
                sibling.getSignature(PsiSubstitutor.EMPTY),
                false);
        if (anchor != null) {
          break;
        }
      }
    }
    PsiMethod methodCopy = (PsiMethod) method.copy();
    Language language = myTargetSuperClass.getLanguage();
    final PsiMethod superClassMethod = myTargetSuperClass.findMethodBySignature(methodCopy, false);
    if (superClassMethod != null && superClassMethod.findDeepestSuperMethods().length == 0
        || method.findSuperMethods(myTargetSuperClass).length == 0) {
      deleteOverrideAnnotationIfFound(methodCopy);
    }
    boolean isOriginalMethodAbstract =
        method.hasModifierProperty(PsiModifier.ABSTRACT)
            || method.hasModifierProperty(PsiModifier.DEFAULT);
    boolean isOriginalMethodPrototype =
        method instanceof HaxeFunctionPrototypeDeclarationWithAttributes;
    if (myIsTargetInterface || info.isToAbstract()) {
      ChangeContextUtil.clearContextInfo(method);

      if (!info.isToAbstract()
          && !method.hasModifierProperty(PsiModifier.ABSTRACT)
          && PsiUtil.isLanguageLevel8OrHigher(myTargetSuperClass)) {
        // pull as default
        RefactoringUtil.makeMethodDefault(methodCopy);
        isOriginalMethodAbstract = true;
      } else {
        RefactoringUtil.makeMethodAbstract(myTargetSuperClass, methodCopy);
      }

      RefactoringUtil.replaceMovedMemberTypeParameters(
          methodCopy, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);

      myJavaDocPolicy.processCopiedJavaDoc(
          methodCopy.getDocComment(), method.getDocComment(), isOriginalMethodAbstract);

      final PsiMember movedElement;
      if (superClassMethod != null && superClassMethod.hasModifierProperty(PsiModifier.ABSTRACT)) {
        movedElement =
            (PsiMember) superClassMethod.replace(convertMethodToLanguage(methodCopy, language));
      } else {
        methodCopy =
            HaxeElementGenerator.createFunctionPrototypeDeclarationWithAttributes(
                myProject, methodCopy.getText().trim() + ";");

        movedElement =
            anchor != null
                ? (PsiMember) myTargetSuperClass.addBefore(methodCopy, anchor)
                : (PsiMember)
                    myTargetSuperClass.addBefore(methodCopy, myTargetSuperClass.getRBrace());

        reformat(movedElement);
      }
      CodeStyleSettings styleSettings = CodeStyleSettingsManager.getSettings(method.getProject());
      if (styleSettings.INSERT_OVERRIDE_ANNOTATION) {
        if (PsiUtil.isLanguageLevel5OrHigher(mySourceClass) && !myIsTargetInterface
            || PsiUtil.isLanguageLevel6OrHigher(mySourceClass)) {
          new AddAnnotationFix(Override.class.getName(), method)
              .invoke(method.getProject(), null, mySourceClass.getContainingFile());
        }
      }
      if (!PsiUtil.isLanguageLevel6OrHigher(mySourceClass) && myIsTargetInterface) {
        if (isOriginalMethodAbstract) {
          for (PsiMethod oMethod : OverridingMethodsSearch.search(method)) {
            deleteOverrideAnnotationIfFound(oMethod);
          }
        }
        deleteOverrideAnnotationIfFound(method);
      }
      myMembersAfterMove.add(movedElement);
      // if (isOriginalMethodAbstract) {
      method.delete();
      // }
    } else {
      if (isOriginalMethodAbstract) {
        PsiUtil.setModifierProperty(myTargetSuperClass, PsiModifier.ABSTRACT, true);
      }
      RefactoringUtil.replaceMovedMemberTypeParameters(
          methodCopy, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
      fixReferencesToStatic(methodCopy);

      if (superClassMethod != null && superClassMethod.hasModifierProperty(PsiModifier.ABSTRACT)) {
        superClassMethod.replace(convertMethodToLanguage(methodCopy, language));
      } else {
        final PsiMember movedElement =
            anchor != null
                ? (PsiMember)
                    myTargetSuperClass.addBefore(
                        convertMethodToLanguage(methodCopy, language), anchor)
                : (PsiMember)
                    myTargetSuperClass.addBefore(
                        convertMethodToLanguage(methodCopy, language),
                        myTargetSuperClass.getRBrace());
        reformat(movedElement);
        myMembersAfterMove.add(movedElement);
      }
      method.delete();
    }
  }
  @Override
  protected void invokeImpl(final PsiClass targetClass) {
    if (CreateFromUsageUtils.isValidReference(myReferenceExpression, true)) {
      return;
    }

    final Project project = myReferenceExpression.getProject();
    PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();

    final PsiFile targetFile = targetClass.getContainingFile();

    PsiType[] expectedTypes = CreateFromUsageUtils.guessType(myReferenceExpression, false);
    PsiType type = expectedTypes[0];

    String varName = myReferenceExpression.getReferenceName();
    PsiExpression initializer = null;
    boolean isInline = false;
    PsiExpression[] expressions =
        CreateFromUsageUtils.collectExpressions(
            myReferenceExpression, PsiMember.class, PsiFile.class);
    PsiStatement anchor = getAnchor(expressions);
    if (anchor instanceof PsiExpressionStatement
        && ((PsiExpressionStatement) anchor).getExpression() instanceof PsiAssignmentExpression) {
      PsiAssignmentExpression assignment =
          (PsiAssignmentExpression) ((PsiExpressionStatement) anchor).getExpression();
      if (assignment.getLExpression().textMatches(myReferenceExpression)) {
        initializer = assignment.getRExpression();
        isInline = true;
      }
    }

    PsiDeclarationStatement decl =
        factory.createVariableDeclarationStatement(varName, type, initializer);

    TypeExpression expression = new TypeExpression(project, expectedTypes);

    if (isInline) {
      final PsiExpression expr = ((PsiExpressionStatement) anchor).getExpression();
      final PsiElement semicolon = expr.getNextSibling();
      if (semicolon != null) {
        final PsiElement nextSibling = semicolon.getNextSibling();
        if (nextSibling != null) {
          decl.addRange(nextSibling, anchor.getLastChild());
        }
      }
      decl = (PsiDeclarationStatement) anchor.replace(decl);
    } else {
      decl = (PsiDeclarationStatement) anchor.getParent().addBefore(decl, anchor);
    }

    PsiVariable var = (PsiVariable) decl.getDeclaredElements()[0];
    boolean isFinal =
        CodeStyleSettingsManager.getSettings(project).GENERATE_FINAL_LOCALS
            && !CreateFromUsageUtils.isAccessedForWriting(expressions);
    PsiUtil.setModifierProperty(var, PsiModifier.FINAL, isFinal);

    var = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(var);
    if (var == null) return;
    TemplateBuilderImpl builder = new TemplateBuilderImpl(var);
    builder.replaceElement(var.getTypeElement(), expression);
    builder.setEndVariableAfter(var.getNameIdentifier());
    Template template = builder.buildTemplate();

    final Editor newEditor = positionCursor(project, targetFile, var);
    TextRange range = var.getTextRange();
    newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());

    startTemplate(
        newEditor,
        template,
        project,
        new TemplateEditingAdapter() {
          @Override
          public void templateFinished(Template template, boolean brokenOff) {
            PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument());
            final int offset = newEditor.getCaretModel().getOffset();
            final PsiLocalVariable localVariable =
                PsiTreeUtil.findElementOfClassAtOffset(
                    targetFile, offset, PsiLocalVariable.class, false);
            if (localVariable != null) {
              ApplicationManager.getApplication()
                  .runWriteAction(
                      new Runnable() {
                        @Override
                        public void run() {
                          CodeStyleManager.getInstance(project).reformat(localVariable);
                        }
                      });
            }
          }
        });
  }
  private PsiClass buildClass() {
    if (existingClass != null) {
      return existingClass;
    }
    final ParameterObjectBuilder beanClassBuilder = new ParameterObjectBuilder();
    beanClassBuilder.setVisibility(myCreateInnerClass ? PsiModifier.PRIVATE : PsiModifier.PUBLIC);
    beanClassBuilder.setProject(myProject);
    beanClassBuilder.setTypeArguments(typeParams);
    beanClassBuilder.setClassName(className);
    beanClassBuilder.setPackageName(packageName);
    for (ParameterChunk parameterChunk : parameters) {
      final VariableData parameter = parameterChunk.parameter;
      final boolean setterRequired = paramsNeedingSetters.contains(parameter.variable);
      beanClassBuilder.addField(
          (PsiParameter) parameter.variable, parameter.name, parameter.type, setterRequired);
    }
    final String classString = beanClassBuilder.buildBeanClass();

    try {
      final PsiFileFactory factory = PsiFileFactory.getInstance(method.getProject());
      final PsiJavaFile newFile =
          (PsiJavaFile)
              factory.createFileFromText(className + ".java", JavaFileType.INSTANCE, classString);
      if (myCreateInnerClass) {
        final PsiClass containingClass = method.getContainingClass();
        final PsiClass[] classes = newFile.getClasses();
        assert classes.length > 0 : classString;
        final PsiClass innerClass = (PsiClass) containingClass.add(classes[0]);
        PsiUtil.setModifierProperty(innerClass, PsiModifier.STATIC, true);
        return (PsiClass)
            JavaCodeStyleManager.getInstance(newFile.getProject())
                .shortenClassReferences(innerClass);
      } else {
        final PsiFile containingFile = method.getContainingFile();
        final PsiDirectory containingDirectory = containingFile.getContainingDirectory();
        final PsiDirectory directory;
        if (myMoveDestination != null) {
          directory = myMoveDestination.getTargetDirectory(containingDirectory);
        } else {
          final Module module = ModuleUtil.findModuleForPsiElement(containingFile);
          directory =
              PackageUtil.findOrCreateDirectoryForPackage(
                  module, packageName, containingDirectory, true, true);
        }

        if (directory != null) {

          final CodeStyleManager codeStyleManager =
              CodeStyleManager.getInstance(method.getManager().getProject());
          final PsiElement shortenedFile =
              JavaCodeStyleManager.getInstance(newFile.getProject())
                  .shortenClassReferences(newFile);
          final PsiElement reformattedFile = codeStyleManager.reformat(shortenedFile);
          return ((PsiJavaFile) directory.add(reformattedFile)).getClasses()[0];
        }
      }
    } catch (IncorrectOperationException e) {
      logger.info(e);
    }
    return null;
  }
Example #25
0
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      if (!myField.isValid()) return; // weird. should not get here when field becomes invalid

      final Collection<PsiReference> refs = ReferencesSearch.search(myField).findAll();
      if (refs.isEmpty()) return;
      Set<PsiReference> refsSet = new HashSet<PsiReference>(refs);
      PsiCodeBlock anchorBlock = findAnchorBlock(refs);
      if (anchorBlock == null)
        return; // was assert, but need to fix the case when obsolete inspection highlighting is
                // left
      if (!CodeInsightUtil.preparePsiElementsForWrite(anchorBlock)) return;
      final PsiElementFactory elementFactory =
          JavaPsiFacade.getInstance(project).getElementFactory();
      final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
      final String propertyName =
          styleManager.variableNameToPropertyName(myField.getName(), VariableKind.FIELD);
      String localName =
          styleManager.propertyNameToVariableName(propertyName, VariableKind.LOCAL_VARIABLE);
      localName = RefactoringUtil.suggestUniqueVariableName(localName, anchorBlock, myField);
      PsiElement firstElement = getFirstElement(refs);
      boolean mayBeFinal = mayBeFinal(refsSet, firstElement);
      PsiElement newDeclaration = null;
      try {
        final PsiElement anchor = getAnchorElement(anchorBlock, firstElement);
        if (anchor instanceof PsiExpressionStatement
            && ((PsiExpressionStatement) anchor).getExpression()
                instanceof PsiAssignmentExpression) {
          final PsiAssignmentExpression expression =
              (PsiAssignmentExpression) ((PsiExpressionStatement) anchor).getExpression();
          if (expression.getOperationTokenType() == JavaTokenType.EQ
              && expression.getLExpression() instanceof PsiReferenceExpression
              && ((PsiReference) expression.getLExpression()).isReferenceTo(myField)) {
            final PsiExpression initializer = expression.getRExpression();
            final PsiDeclarationStatement decl =
                elementFactory.createVariableDeclarationStatement(
                    localName, myField.getType(), initializer);
            if (!mayBeFinal) {
              PsiUtil.setModifierProperty(
                  ((PsiModifierListOwner) decl.getDeclaredElements()[0]), PsiModifier.FINAL, false);
            }
            newDeclaration = anchor.replace(decl);
            refsSet.remove(expression.getLExpression());
            retargetReferences(elementFactory, localName, refsSet);
          } else {
            newDeclaration =
                addDeclarationWithFieldInitializerAndRetargetReferences(
                    elementFactory, localName, anchorBlock, anchor, refsSet);
          }
        } else {
          newDeclaration =
              addDeclarationWithFieldInitializerAndRetargetReferences(
                  elementFactory, localName, anchorBlock, anchor, refsSet);
        }
      } catch (IncorrectOperationException e) {
        LOG.error(e);
      }

      if (newDeclaration != null) {
        final PsiFile psiFile = myField.getContainingFile();
        final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (editor != null && IJSwingUtilities.hasFocus(editor.getComponent())) {
          final PsiFile file =
              PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
          if (file == psiFile) {
            editor.getCaretModel().moveToOffset(newDeclaration.getTextOffset());
            editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
          }
        }
      }

      try {
        myField.normalizeDeclaration();
        myField.delete();
      } catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }
  protected void changeSelf(PsiElementFactory factory, UsageInfo[] usages)
      throws IncorrectOperationException {
    final MethodJavaDocHelper javaDocHelper = new MethodJavaDocHelper(myMember);
    PsiParameterList paramList = myMember.getParameterList();
    PsiElement addParameterAfter = null;
    PsiDocTag anchor = null;
    List<PsiType> addedTypes = new ArrayList<PsiType>();

    final PsiClass containingClass = myMember.getContainingClass();
    LOG.assertTrue(containingClass != null);

    if (mySettings.isDelegate()) {
      List<ParameterInfoImpl> params = new ArrayList<ParameterInfoImpl>();
      PsiParameter[] parameters = myMember.getParameterList().getParameters();

      if (mySettings.isMakeClassParameter()) {
        params.add(
            new ParameterInfoImpl(
                -1,
                mySettings.getClassParameterName(),
                factory.createType(containingClass, PsiSubstitutor.EMPTY),
                "this"));
      }

      if (mySettings.isMakeFieldParameters()) {
        for (Settings.FieldParameter parameter : mySettings.getParameterOrderList()) {
          params.add(
              new ParameterInfoImpl(
                  -1,
                  mySettings.getClassParameterName(),
                  parameter.type,
                  parameter.field.getName()));
        }
      }

      for (int i = 0; i < parameters.length; i++) {
        params.add(new ParameterInfoImpl(i));
      }

      final PsiType returnType = myMember.getReturnType();
      LOG.assertTrue(returnType != null);
      JavaChangeSignatureUsageProcessor.generateDelegate(
          new JavaChangeInfoImpl(
              VisibilityUtil.getVisibilityModifier(myMember.getModifierList()),
              myMember,
              myMember.getName(),
              CanonicalTypes.createTypeWrapper(returnType),
              params.toArray(new ParameterInfoImpl[params.size()]),
              new ThrownExceptionInfo[0],
              false,
              Collections.<PsiMethod>emptySet(),
              Collections.<PsiMethod>emptySet()));
    }

    if (mySettings.isMakeClassParameter()) {
      // Add parameter for object
      PsiType parameterType = factory.createType(containingClass, PsiSubstitutor.EMPTY);
      addedTypes.add(parameterType);

      final String classParameterName = mySettings.getClassParameterName();
      PsiParameter parameter = factory.createParameter(classParameterName, parameterType);
      if (makeClassParameterFinal(usages)) {
        PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, true);
      }
      addParameterAfter = paramList.addAfter(parameter, null);
      anchor = javaDocHelper.addParameterAfter(classParameterName, anchor);
    }

    if (mySettings.isMakeFieldParameters()) {
      List<Settings.FieldParameter> parameters = mySettings.getParameterOrderList();

      for (Settings.FieldParameter fieldParameter : parameters) {
        final PsiType fieldParameterType = fieldParameter.field.getType();
        final PsiParameter parameter =
            factory.createParameter(fieldParameter.name, fieldParameterType);
        addedTypes.add(fieldParameterType);
        if (makeFieldParameterFinal(fieldParameter.field, usages)) {
          PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, true);
        }
        addParameterAfter = paramList.addAfter(parameter, addParameterAfter);
        anchor = javaDocHelper.addParameterAfter(fieldParameter.name, anchor);
      }
    }
    makeStatic(myMember);

    if (myAdditionalMethods != null) {
      for (PsiMethod method : myAdditionalMethods) {
        makeStatic(method);
      }
    }
  }
  public boolean processUsage(
      ChangeInfo changeInfo, UsageInfo usage, boolean beforeMethodChange, UsageInfo[] usages) {
    if (!isJavaUsage(usage)) return false;
    if (!(changeInfo instanceof JavaChangeInfo)) return false;

    if (beforeMethodChange) {
      if (usage instanceof CallerUsageInfo) {
        final CallerUsageInfo callerUsageInfo = (CallerUsageInfo) usage;
        processCallerMethod(
            (JavaChangeInfo) changeInfo,
            callerUsageInfo.getMethod(),
            null,
            callerUsageInfo.isToInsertParameter(),
            callerUsageInfo.isToInsertException());
        return true;
      } else if (usage instanceof OverriderUsageInfo) {
        OverriderUsageInfo info = (OverriderUsageInfo) usage;
        final PsiMethod method = info.getElement();
        final PsiMethod baseMethod = info.getBaseMethod();
        if (info.isOriginalOverrider()) {
          processPrimaryMethod((JavaChangeInfo) changeInfo, method, baseMethod, false);
        } else {
          processCallerMethod(
              (JavaChangeInfo) changeInfo,
              method,
              baseMethod,
              info.isToInsertArgs(),
              info.isToCatchExceptions());
        }
        return true;
      }

    } else {
      PsiElement element = usage.getElement();
      LOG.assertTrue(element != null);

      if (usage instanceof DefaultConstructorImplicitUsageInfo) {
        final DefaultConstructorImplicitUsageInfo defConstructorUsage =
            (DefaultConstructorImplicitUsageInfo) usage;
        PsiMethod constructor = defConstructorUsage.getConstructor();
        if (!constructor.isPhysical()) {
          final boolean toPropagate =
              changeInfo instanceof JavaChangeInfoImpl
                  && ((JavaChangeInfoImpl) changeInfo)
                      .propagateParametersMethods.remove(constructor);
          final PsiClass containingClass = defConstructorUsage.getContainingClass();
          constructor = (PsiMethod) containingClass.add(constructor);
          PsiUtil.setModifierProperty(
              constructor,
              VisibilityUtil.getVisibilityModifier(containingClass.getModifierList()),
              true);
          if (toPropagate) {
            ((JavaChangeInfoImpl) changeInfo).propagateParametersMethods.add(constructor);
          }
        }
        addSuperCall(
            (JavaChangeInfo) changeInfo,
            constructor,
            defConstructorUsage.getBaseConstructor(),
            usages);
        return true;
      } else if (usage instanceof NoConstructorClassUsageInfo) {
        addDefaultConstructor(
            ((JavaChangeInfo) changeInfo),
            ((NoConstructorClassUsageInfo) usage).getPsiClass(),
            usages);
        return true;
      } else if (usage instanceof MethodCallUsageInfo) {
        final MethodCallUsageInfo methodCallInfo = (MethodCallUsageInfo) usage;
        processMethodUsage(
            methodCallInfo.getElement(),
            (JavaChangeInfo) changeInfo,
            methodCallInfo.isToChangeArguments(),
            methodCallInfo.isToCatchExceptions(),
            methodCallInfo.getReferencedMethod(),
            methodCallInfo.getSubstitutor(),
            usages);
        return true;
      } else if (usage instanceof ChangeSignatureParameterUsageInfo) {
        String newName = ((ChangeSignatureParameterUsageInfo) usage).newParameterName;
        String oldName = ((ChangeSignatureParameterUsageInfo) usage).oldParameterName;
        processParameterUsage((PsiReferenceExpression) element, oldName, newName);
        return true;
      } else if (usage instanceof CallReferenceUsageInfo) {
        ((CallReferenceUsageInfo) usage).getReference().handleChangeSignature(changeInfo);
        return true;
      } else if (element instanceof PsiEnumConstant) {
        fixActualArgumentsList(
            ((PsiEnumConstant) element).getArgumentList(),
            (JavaChangeInfo) changeInfo,
            true,
            PsiSubstitutor.EMPTY);
        return true;
      } else if (!(usage instanceof OverriderUsageInfo)) {
        PsiReference reference =
            usage instanceof MoveRenameUsageInfo ? usage.getReference() : element.getReference();
        if (reference != null) {
          PsiElement target = changeInfo.getMethod();
          if (target != null) {
            reference.bindToElement(target);
          }
        }
      }
    }
    return false;
  }
  private void doMoveMethod(PsiSubstitutor substitutor, GrMemberInfo info) {
    GroovyPsiElementFactory elementFactory = GroovyPsiElementFactory.getInstance(myProject);
    GrMethod method = (GrMethod) info.getMember();
    PsiMethod sibling = method;
    PsiMethod anchor = null;
    while (sibling != null) {
      sibling = PsiTreeUtil.getNextSiblingOfType(sibling, PsiMethod.class);
      if (sibling != null) {
        anchor =
            MethodSignatureUtil.findMethodInSuperClassBySignatureInDerived(
                method.getContainingClass(),
                myTargetSuperClass,
                sibling.getSignature(PsiSubstitutor.EMPTY),
                false);
        if (anchor != null) {
          break;
        }
      }
    }

    GrMethod methodCopy = (GrMethod) method.copy();
    if (method.findSuperMethods(myTargetSuperClass).length == 0) {
      deleteOverrideAnnotationIfFound(methodCopy);
    }

    final boolean isOriginalMethodAbstract =
        method.hasModifierProperty(PsiModifier.ABSTRACT)
            || method.hasModifierProperty(PsiModifier.DEFAULT);
    if (myTargetSuperClass.isInterface() || info.isToAbstract()) {
      GroovyChangeContextUtil.clearContextInfo(method);
      RefactoringUtil.makeMethodAbstract(myTargetSuperClass, methodCopy);
      if (myTargetSuperClass.isInterface()) {
        PsiUtil.setModifierProperty(methodCopy, PsiModifier.ABSTRACT, false);
      }
      replaceMovedMemberTypeParameters(
          methodCopy, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);

      final GrMethod movedElement =
          anchor != null
              ? (GrMethod) myTargetSuperClass.addBefore(methodCopy, anchor)
              : (GrMethod) myTargetSuperClass.add(methodCopy);
      CodeStyleSettings styleSettings = CodeStyleSettingsManager.getSettings(method.getProject());
      if (styleSettings.INSERT_OVERRIDE_ANNOTATION) {
        if (PsiUtil.isLanguageLevel5OrHigher(mySourceClass) && !myTargetSuperClass.isInterface()
            || PsiUtil.isLanguageLevel6OrHigher(mySourceClass)) {
          new AddAnnotationFix(CommonClassNames.JAVA_LANG_OVERRIDE, method)
              .invoke(method.getProject(), null, mySourceClass.getContainingFile());
        }
      }

      GrDocComment oldDoc = method.getDocComment();
      if (oldDoc != null) {
        GrDocCommentUtil.setDocComment(movedElement, oldDoc);
      }

      myDocCommentPolicy.processCopiedJavaDoc(
          methodCopy.getDocComment(), oldDoc, isOriginalMethodAbstract);

      myMembersAfterMove.add(movedElement);
      if (isOriginalMethodAbstract) {
        deleteMemberWithDocComment(method);
      }
    } else {
      if (isOriginalMethodAbstract) {
        PsiUtil.setModifierProperty(myTargetSuperClass, PsiModifier.ABSTRACT, true);
      }

      // fixReferencesToStatic(methodCopy, movedMembers);
      replaceMovedMemberTypeParameters(
          methodCopy, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
      final PsiMethod superClassMethod =
          myTargetSuperClass.findMethodBySignature(methodCopy, false);
      final GrMethod movedElement;
      if (superClassMethod != null && superClassMethod.hasModifierProperty(PsiModifier.ABSTRACT)) {
        movedElement = (GrMethod) superClassMethod.replace(methodCopy);
      } else {
        movedElement =
            anchor != null
                ? (GrMethod) myTargetSuperClass.addBefore(methodCopy, anchor)
                : (GrMethod) myTargetSuperClass.add(methodCopy);
        myMembersAfterMove.add(movedElement);
      }

      GrDocCommentUtil.setDocComment(movedElement, method.getDocComment());

      deleteMemberWithDocComment(method);
    }
  }