private static void addSuppressAnnotation(
     final Project project, final GrModifierList modifierList, final String id)
     throws IncorrectOperationException {
   PsiAnnotation annotation =
       modifierList.findAnnotation(BatchSuppressManager.SUPPRESS_INSPECTIONS_ANNOTATION_NAME);
   final GrExpression toAdd =
       GroovyPsiElementFactory.getInstance(project).createExpressionFromText("\"" + id + "\"");
   if (annotation != null) {
     final PsiAnnotationMemberValue value = annotation.findDeclaredAttributeValue(null);
     if (value instanceof GrAnnotationArrayInitializer) {
       value.add(toAdd);
     } else if (value != null) {
       GrAnnotation anno =
           GroovyPsiElementFactory.getInstance(project).createAnnotationFromText("@A([])");
       final GrAnnotationArrayInitializer list =
           (GrAnnotationArrayInitializer) anno.findDeclaredAttributeValue(null);
       list.add(value);
       list.add(toAdd);
       annotation.setDeclaredAttributeValue(null, list);
     }
   } else {
     modifierList
         .addAnnotation(BatchSuppressManager.SUPPRESS_INSPECTIONS_ANNOTATION_NAME)
         .setDeclaredAttributeValue(null, toAdd);
   }
 }
  private static GrMethodCallExpression createMethodCall(ExtractInfoHelper helper) {
    StringBuilder buffer = new StringBuilder();
    buffer.append(helper.getName()).append("(");
    int number = 0;
    for (ParameterInfo info : helper.getParameterInfos()) {
      if (info.passAsParameter()) number++;
    }
    int i = 0;
    String[] argumentNames = helper.getArgumentNames();
    for (String argName : argumentNames) {
      if (argName.length() > 0) {
        buffer.append(argName);
        if (i < number - 1) {
          buffer.append(",");
        }
        i++;
      }
    }

    buffer.append(")");
    String callText = buffer.toString();
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(helper.getProject());
    GrExpression expr = factory.createExpressionFromText(callText);
    LOG.assertTrue(expr instanceof GrMethodCallExpression, callText);
    return ((GrMethodCallExpression) expr);
  }
  private static PsiElement fixCatchBlock(GrTryCatchStatement tryCatch, PsiClassType[] exceptions) {
    if (exceptions.length == 0) return tryCatch;
    final GroovyPsiElementFactory factory =
        GroovyPsiElementFactory.getInstance(tryCatch.getProject());

    final GrCatchClause[] clauses = tryCatch.getCatchClauses();
    List<String> restricted =
        ContainerUtil.map(
            clauses,
            new Function<GrCatchClause, String>() {
              @Override
              @Nullable
              public String fun(GrCatchClause grCatchClause) {
                final GrParameter grParameter = grCatchClause.getParameter();
                return grParameter != null ? grParameter.getName() : null;
              }
            });

    restricted = ContainerUtil.skipNulls(restricted);
    final DefaultGroovyVariableNameValidator nameValidator =
        new DefaultGroovyVariableNameValidator(tryCatch, restricted);

    GrCatchClause anchor = clauses.length == 0 ? null : clauses[clauses.length - 1];
    for (PsiClassType type : exceptions) {
      final String[] names =
          GroovyNameSuggestionUtil.suggestVariableNameByType(type, nameValidator);
      final GrCatchClause catchClause = factory.createCatchClause(type, names[0]);
      final GrStatement printStackTrace =
          factory.createStatementFromText(names[0] + ".printStackTrace()");
      catchClause.getBody().addStatementBefore(printStackTrace, null);
      anchor = tryCatch.addCatchClause(catchClause, anchor);
      JavaCodeStyleManager.getInstance(anchor.getProject()).shortenClassReferences(anchor);
    }
    return tryCatch;
  }
  private static List<GrStatement> generateVarDeclarations(
      List<VariableInfo> varInfos, Project project, @Nullable GrExpression initializer) {
    List<GrStatement> result = new ArrayList<GrStatement>();
    if (varInfos.size() == 0) return result;

    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
    boolean distinctDeclaration = haveDifferentTypes(varInfos);

    if (distinctDeclaration) {
      for (VariableInfo info : varInfos) {
        result.add(
            factory.createVariableDeclaration(
                ArrayUtil.EMPTY_STRING_ARRAY, null, info.getType(), info.getName()));
      }
    } else {
      String[] names = new String[varInfos.size()];
      for (int i = 0, mustAddLength = varInfos.size(); i < mustAddLength; i++) {
        names[i] = varInfos.get(i).getName();
      }
      result.add(
          factory.createVariableDeclaration(
              ArrayUtil.EMPTY_STRING_ARRAY, initializer, varInfos.get(0).getType(), names));
    }
    return result;
  }
 @Override
 public void visitReferenceExpression(GrReferenceExpression expression) {
   super.visitReferenceExpression(expression);
   if (expression.getCopyableUserData(SUPER_REF) != null) {
     expression.putCopyableUserData(SUPER_REF, null);
     final GrExpression qualifier = expression.getQualifier();
     if (qualifier instanceof GrReferenceExpression
         && ((GrReferenceExpression) qualifier).isReferenceTo(mySourceClass)) {
       try {
         GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(myProject);
         GrExpression newExpr =
             factory.createExpressionFromText(myTargetSuperClass.getName() + ".this", null);
         expression.replace(newExpr);
       } catch (IncorrectOperationException e) {
         LOG.error(e);
       }
     }
   } else if (expression.getCopyableUserData(THIS_REF) != null) {
     expression.putCopyableUserData(THIS_REF, null);
     final GrExpression qualifier = expression.getQualifier();
     if (qualifier instanceof GrReferenceExpression
         && ((GrReferenceExpression) qualifier).isReferenceTo(mySourceClass)) {
       try {
         ((GrReferenceExpression) qualifier).bindToElement(myTargetSuperClass);
         GroovyChangeContextUtil.clearContextInfo(qualifier);
       } catch (IncorrectOperationException e) {
         LOG.error(e);
       }
     }
   }
 }
  public static void replaceMovedMemberTypeParameters(
      final PsiElement member,
      final Iterable<PsiTypeParameter> parametersIterable,
      final PsiSubstitutor substitutor,
      final GroovyPsiElementFactory factory) {
    final Map<PsiElement, PsiElement> replacement = new LinkedHashMap<PsiElement, PsiElement>();
    for (PsiTypeParameter parameter : parametersIterable) {
      PsiType substitutedType = substitutor.substitute(parameter);
      if (substitutedType == null) {
        substitutedType = TypeConversionUtil.erasure(factory.createType(parameter));
      }

      PsiElement scopeElement = member instanceof GrField ? member.getParent() : member;
      for (PsiReference reference :
          ReferencesSearch.search(parameter, new LocalSearchScope(scopeElement))) {
        final PsiElement element = reference.getElement();
        final PsiElement parent = element.getParent();
        if (parent instanceof PsiTypeElement) {
          replacement.put(parent, factory.createTypeElement(substitutedType));
        } else if (element instanceof GrCodeReferenceElement
            && substitutedType instanceof PsiClassType) {
          replacement.put(
              element, factory.createReferenceElementByType((PsiClassType) substitutedType));
        }
      }
    }

    for (PsiElement element : replacement.keySet()) {
      if (element.isValid()) {
        element.replace(replacement.get(element));
      }
    }
  }
  private void fixReferencesToStatic(GroovyPsiElement classMember, Set<PsiMember> movedMembers)
      throws IncorrectOperationException {
    final StaticReferencesCollector collector = new StaticReferencesCollector(movedMembers);
    classMember.accept(collector);
    ArrayList<GrReferenceElement> refs = collector.getReferences();
    ArrayList<PsiElement> members = collector.getReferees();
    ArrayList<PsiClass> classes = collector.getRefereeClasses();
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(myProject);

    for (int i = 0; i < refs.size(); i++) {
      GrReferenceElement ref = refs.get(i);
      PsiElement namedElement = members.get(i);
      PsiClass aClass = classes.get(i);

      if (namedElement instanceof PsiNamedElement) {
        GrReferenceExpression newRef =
            (GrReferenceExpression)
                factory.createExpressionFromText(
                    "a." + ((PsiNamedElement) namedElement).getName(), null);
        GrExpression qualifier = newRef.getQualifierExpression();
        assert qualifier != null;
        qualifier =
            (GrExpression)
                qualifier.replace(
                    factory.createReferenceExpressionFromText(aClass.getQualifiedName()));
        qualifier.putCopyableUserData(PRESERVE_QUALIFIER, ref.isQualified());
        PsiElement replaced = ref.replace(newRef);
        JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(replaced);
      }
    }
  }
  private static void qualify(PsiMember member, PsiElement renamed, String name) {
    if (!(renamed instanceof GrReferenceExpression)) return;

    final PsiClass clazz = member.getContainingClass();
    if (clazz == null) return;

    final GrReferenceExpression refExpr = (GrReferenceExpression) renamed;
    final PsiElement replaced;
    if (member.hasModifierProperty(GrModifier.STATIC)) {
      final GrReferenceExpression newRefExpr =
          GroovyPsiElementFactory.getInstance(member.getProject())
              .createReferenceExpressionFromText(clazz.getQualifiedName() + "." + name);
      replaced = refExpr.replace(newRefExpr);
    } else {
      final PsiClass containingClass = PsiTreeUtil.getParentOfType(renamed, PsiClass.class);
      if (member.getManager().areElementsEquivalent(containingClass, clazz)) {
        final GrReferenceExpression newRefExpr =
            GroovyPsiElementFactory.getInstance(member.getProject())
                .createReferenceExpressionFromText("this." + name);
        replaced = refExpr.replace(newRefExpr);
      } else {
        final GrReferenceExpression newRefExpr =
            GroovyPsiElementFactory.getInstance(member.getProject())
                .createReferenceExpressionFromText(clazz.getQualifiedName() + ".this." + name);
        replaced = refExpr.replace(newRefExpr);
      }
    }
    PsiUtil.shortenReferences((GroovyPsiElement) replaced);
  }
  @NotNull
  public GrAnnotation addAnnotation(@NotNull @NonNls String qualifiedName) {
    final PsiClass psiClass =
        JavaPsiFacade.getInstance(getProject()).findClass(qualifiedName, getResolveScope());
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(getProject());
    GrAnnotation annotation;
    if (psiClass != null && psiClass.isAnnotationType()) {
      annotation = (GrAnnotation) addAfter(factory.createModifierFromText("@xxx"), null);
      annotation.getClassReference().bindToElement(psiClass);
    } else {
      annotation =
          (GrAnnotation) addAfter(factory.createModifierFromText("@" + qualifiedName), null);
    }

    final PsiElement parent = getParent();
    if (!(parent instanceof GrParameter)) {
      final ASTNode node = annotation.getNode();
      final ASTNode treeNext = node.getTreeNext();
      if (treeNext != null) {
        getNode().addLeaf(TokenType.WHITE_SPACE, "\n", treeNext);
      } else {
        parent.getNode().addLeaf(TokenType.WHITE_SPACE, "\n", getNode().getTreeNext());
      }
    }

    return annotation;
  }
  public static GrMethod createMethod(ExtractMethodInfoHelper helper) {
    StringBuilder buffer = new StringBuilder();

    // Add signature
    PsiType type = helper.getOutputType();
    final PsiPrimitiveType outUnboxed = PsiPrimitiveType.getUnboxedType(type);
    if (outUnboxed != null) type = outUnboxed;
    String modifier = getModifierString(helper);
    String typeText = getTypeString(helper, false, modifier);
    buffer.append(modifier);
    buffer.append(typeText);
    buffer.append(helper.getName());
    buffer.append("(");
    for (String param : getParameterString(helper, true)) {
      buffer.append(param);
    }
    buffer.append(") { \n");

    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(helper.getProject());
    generateBody(helper, type == PsiType.VOID, buffer, helper.isForceReturn());

    buffer.append("\n}");

    String methodText = buffer.toString();
    GrMethod method = factory.createMethodFromText(methodText);
    LOG.assertTrue(method != null);
    return method;
  }
  @Override
  protected void processIntention(@NotNull PsiElement element, Project project, Editor editor)
      throws IncorrectOperationException {
    final GrMethodCallExpression expression = (GrMethodCallExpression) element;
    final GrClosableBlock block = expression.getClosureArguments()[0];
    final GrParameterList parameterList = block.getParameterList();
    final GrParameter[] parameters = parameterList.getParameters();

    String var;
    if (parameters.length == 1) {
      var = parameters[0].getText();
      var = StringUtil.replace(var, GrModifier.DEF, "");
    } else {
      var = "it";
    }

    final GrExpression invokedExpression = expression.getInvokedExpression();
    GrExpression qualifier = ((GrReferenceExpression) invokedExpression).getQualifierExpression();
    final GroovyPsiElementFactory elementFactory =
        GroovyPsiElementFactory.getInstance(element.getProject());
    if (qualifier == null) {
      qualifier = elementFactory.createExpressionFromText("this");
    }

    StringBuilder builder = new StringBuilder();
    builder.append("for (").append(var).append(" in ").append(qualifier.getText()).append(") {\n");
    String text = block.getText();
    final PsiElement blockArrow = block.getArrow();
    int index;
    if (blockArrow != null) {
      index = blockArrow.getStartOffsetInParent() + blockArrow.getTextLength();
    } else {
      index = 1;
    }
    while (index < text.length() && Character.isWhitespace(text.charAt(index))) index++;
    text = text.substring(index, text.length() - 1);
    builder.append(text);
    builder.append("}");

    final GrStatement statement = elementFactory.createStatementFromText(builder.toString());
    GrForStatement forStatement = (GrForStatement) expression.replaceWithStatement(statement);
    final GrForClause clause = forStatement.getClause();
    GrVariable variable = clause.getDeclaredVariable();

    forStatement = updateReturnStatements(forStatement);

    if (variable == null) return;

    if (ApplicationManager.getApplication().isUnitTestMode()) return;

    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    final Document doc = documentManager.getDocument(element.getContainingFile());
    if (doc == null) return;

    documentManager.doPostponedOperationsAndUnblockDocument(doc);
    editor.getCaretModel().moveToOffset(variable.getTextOffset());
    new VariableInplaceRenamer(variable, editor).performInplaceRename();
  }
  @Override
  protected void processIntention(@NotNull PsiElement element, Project project, Editor editor)
      throws IncorrectOperationException {
    PsiElement parent = element.getParent();

    if (!"if".equals(element.getText()) || !(parent instanceof GrIfStatement)) {
      throw new IncorrectOperationException("Not invoked on an if");
    }
    GrIfStatement parentIf = (GrIfStatement) parent;
    GroovyPsiElementFactory groovyPsiElementFactory = GroovyPsiElementFactory.getInstance(project);

    GrExpression condition = parentIf.getCondition();
    if (condition == null) {
      throw new IncorrectOperationException("Invoked on an if with empty condition");
    }

    GrExpression negatedCondition = null;
    if (condition instanceof GrUnaryExpression) {
      GrUnaryExpression unaryCondition = (GrUnaryExpression) condition;
      if ("!".equals(unaryCondition.getOperationToken().getText())) {
        negatedCondition = stripParenthesis(unaryCondition.getOperand());
      }
    }

    if (negatedCondition == null) {
      // Now check whether this is a simple expression
      condition = stripParenthesis(condition);
      String negatedExpressionText;
      if (condition instanceof GrCallExpression || condition instanceof GrReferenceExpression) {
        negatedExpressionText = "!" + condition.getText();
      } else {
        negatedExpressionText = "!(" + condition.getText() + ")";
      }
      negatedCondition =
          groovyPsiElementFactory.createExpressionFromText(negatedExpressionText, parentIf);
    }

    GrStatement thenBranch = parentIf.getThenBranch();
    final boolean thenIsNotEmpty = isNotEmpty(thenBranch);

    String newIfText = "if (" + negatedCondition.getText() + ") {}";
    if (thenIsNotEmpty) {
      newIfText += " else {}";
    }

    GrIfStatement newIf =
        (GrIfStatement)
            groovyPsiElementFactory.createStatementFromText(newIfText, parentIf.getContext());
    generateElseBranchTextAndRemoveTailStatements(parentIf, newIf);

    if (thenIsNotEmpty) {
      final GrStatement elseBranch = newIf.getElseBranch();
      assert elseBranch != null;
      elseBranch.replaceWithStatement(thenBranch);
    }

    parentIf.replace(newIf);
  }
  private static GrExpression genRefForGetter(GrMethodCall call, String accessorName) {
    String name = GroovyPropertyUtils.getPropertyNameByGetterName(accessorName, true);
    GrReferenceExpression refExpr = (GrReferenceExpression) call.getInvokedExpression();
    String oldNameStr = refExpr.getReferenceNameElement().getText();
    String newRefExpr = StringUtil.trimEnd(refExpr.getText(), oldNameStr) + name;

    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(call.getProject());
    return factory.createExpressionFromText(newRefExpr, call);
  }
  private void doMoveClass(PsiSubstitutor substitutor, GrMemberInfo info) {
    GroovyPsiElementFactory elementFactory = GroovyPsiElementFactory.getInstance(myProject);
    GrTypeDefinition aClass = (GrTypeDefinition) info.getMember();
    if (Boolean.FALSE.equals(info.getOverrides())) {
      final GrReferenceList sourceReferenceList = info.getSourceReferenceList();
      LOG.assertTrue(sourceReferenceList != null);
      GrCodeReferenceElement ref =
          mySourceClass.equals(sourceReferenceList.getParent())
              ? removeFromReferenceList(sourceReferenceList, aClass)
              : findReferenceToClass(sourceReferenceList, aClass);
      if (ref != null && !myTargetSuperClass.isInheritor(aClass, false)) {
        replaceMovedMemberTypeParameters(
            ref, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
        GrReferenceList referenceList;
        if (myTargetSuperClass.isInterface()) {
          referenceList = myTargetSuperClass.getExtendsClause();
          if (referenceList == null) {
            GrExtendsClause newClause =
                GroovyPsiElementFactory.getInstance(myProject).createExtendsClause();
            PsiElement anchor =
                myTargetSuperClass.getTypeParameterList() != null
                    ? myTargetSuperClass.getTypeParameterList()
                    : myTargetSuperClass.getNameIdentifierGroovy();
            referenceList = (GrReferenceList) myTargetSuperClass.addAfter(newClause, anchor);
            addSpacesAround(referenceList);
          }
        } else {
          referenceList = myTargetSuperClass.getImplementsClause();

          if (referenceList == null) {
            GrImplementsClause newClause =
                GroovyPsiElementFactory.getInstance(myProject).createImplementsClause();
            PsiElement anchor =
                myTargetSuperClass.getExtendsClause() != null
                    ? myTargetSuperClass.getExtendsClause()
                    : myTargetSuperClass.getTypeParameterList() != null
                        ? myTargetSuperClass.getTypeParameterList()
                        : myTargetSuperClass.getNameIdentifierGroovy();
            referenceList = (GrReferenceList) myTargetSuperClass.addAfter(newClause, anchor);
            addSpacesAround(referenceList);
          }
        }

        assert referenceList != null;
        referenceList.add(ref);
      }
    } else {
      replaceMovedMemberTypeParameters(
          aClass, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
      // fixReferencesToStatic(aClass, movedMembers);
      PsiMember movedElement = (PsiMember) myTargetSuperClass.addAfter(aClass, null);
      // movedElement = (PsiMember)CodeStyleManager.getInstance(myProject).reformat(movedElement);
      myMembersAfterMove.add(movedElement);
      deleteMemberWithDocComment(aClass);
    }
  }
  @Override
  protected void processIntention(@NotNull PsiElement element, Project project, Editor editor)
      throws IncorrectOperationException {
    if (!(element instanceof GrConditionalExpression)) {
      throw new IncorrectOperationException("Not invoked on a conditional");
    }
    GroovyPsiElementFactory groovyPsiElementFactory = GroovyPsiElementFactory.getInstance(project);
    GrConditionalExpression condExp = (GrConditionalExpression) element;
    GrExpression thenBranch = condExp.getThenBranch();
    GrExpression elseBranch = condExp.getElseBranch();

    Object thenVal = GroovyConstantExpressionEvaluator.evaluate(thenBranch);
    if (Boolean.TRUE.equals(thenVal) && elseBranch != null) {
      // aaa ? true : bbb -> aaa || bbb
      GrExpression conditionExp = condExp.getCondition();

      String conditionExpText = getStringToPutIntoOrExpression(conditionExp);
      String elseExpText = getStringToPutIntoOrExpression(elseBranch);
      String newExp = conditionExpText + "||" + elseExpText;
      int caretOffset = conditionExpText.length() + 2; // after "||"

      GrExpression expressionFromText =
          groovyPsiElementFactory.createExpressionFromText(newExp, condExp.getContext());

      expressionFromText = (GrExpression) condExp.replace(expressionFromText);

      editor
          .getCaretModel()
          .moveToOffset(expressionFromText.getTextOffset() + caretOffset); // just past "||"
      return;
    }

    Object elseVal = GroovyConstantExpressionEvaluator.evaluate(elseBranch);
    if (Boolean.FALSE.equals(elseVal) && thenBranch != null) {
      // aaa ? bbb : false -> aaa && bbb
      GrExpression conditionExp = condExp.getCondition();

      String conditionExpText = getStringToPutIntoAndExpression(conditionExp);
      String thenExpText = getStringToPutIntoAndExpression(thenBranch);

      String newExp = conditionExpText + "&&" + thenExpText;
      int caretOffset = conditionExpText.length() + 2; // after "&&"
      GrExpression expressionFromText =
          groovyPsiElementFactory.createExpressionFromText(newExp, condExp.getContext());

      expressionFromText = (GrExpression) condExp.replace(expressionFromText);

      editor
          .getCaretModel()
          .moveToOffset(expressionFromText.getTextOffset() + caretOffset); // just past "&&"
    }
  }
  public static GrMethod generateDelegate(
      PsiMethod prototype, IntroduceParameterData.ExpressionWrapper initializer, Project project) {
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);

    GrMethod result;
    if (prototype instanceof GrMethod) {
      result = (GrMethod) prototype.copy();
    } else {
      StringBuilder builder = new StringBuilder();
      builder.append(prototype.getModifierList().getText()).append(' ');

      if (prototype.getReturnTypeElement() != null) {
        builder.append(prototype.getReturnTypeElement().getText());
      }
      builder.append(' ').append(prototype.getName());
      builder.append(prototype.getParameterList().getText());
      builder.append("{}");
      result = factory.createMethodFromText(builder.toString());
    }

    StringBuilder call = new StringBuilder();
    call.append("def foo(){\n");
    final GrParameter[] parameters = result.getParameters();
    call.append(prototype.getName());
    if (initializer.getExpression() instanceof GrClosableBlock) {
      if (parameters.length > 0) {
        call.append('(');
        for (GrParameter parameter : parameters) {
          call.append(parameter.getName()).append(", ");
        }
        call.replace(call.length() - 2, call.length(), ")");
      }
      call.append(initializer.getText());
    } else {
      call.append('(');
      for (GrParameter parameter : parameters) {
        call.append(parameter.getName()).append(", ");
      }
      call.append(initializer.getText());
      call.append(")");
    }
    call.append("\n}");
    final GrOpenBlock block = factory.createMethodFromText(call.toString()).getBlock();

    result.getBlock().replace(block);
    final PsiElement parent = prototype.getParent();
    final GrMethod method = (GrMethod) parent.addBefore(result, prototype);
    GrReferenceAdjuster.shortenReferences(method);
    return method;
  }
    public void fixSupers() throws IncorrectOperationException {
      final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(myProject);
      GrReferenceExpression thisExpression =
          (GrReferenceExpression) factory.createExpressionFromText("this", null);
      for (GrExpression expression : mySupersToDelete) {
        if (expression.getParent() instanceof GrReferenceExpression) {
          ((GrReferenceExpression) expression.getParent()).setQualifier(null);
        }
      }

      for (GrReferenceExpression superExpression : mySupersToChangeToThis) {
        superExpression.replace(thisExpression);
      }
    }
  @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;
  }
  @Override
  protected void processIntention(@NotNull PsiElement element, Project project, Editor editor)
      throws IncorrectOperationException {
    if (!(element instanceof GrReferenceElement)) return;
    final GrReferenceElement ref = (GrReferenceElement) element;
    final PsiElement resolved = ref.resolve();
    if (!(resolved instanceof PsiClass)) return;

    final String qname = ((PsiClass) resolved).getQualifiedName();

    final GrImportStatement importStatement =
        GroovyPsiElementFactory.getInstance(project)
            .createImportStatementFromText(qname, true, true, null);

    final PsiFile containingFile = element.getContainingFile();
    if (!(containingFile instanceof GroovyFile)) return;
    ((GroovyFile) containingFile).addImport(importStatement);

    for (PsiReference reference :
        ReferencesSearch.search(resolved, new LocalSearchScope(containingFile))) {
      final PsiElement refElement = reference.getElement();
      if (refElement == null) continue;
      final PsiElement parent = refElement.getParent();
      if (parent instanceof GrQualifiedReference<?>) {
        org.jetbrains.plugins.groovy.codeStyle.GrReferenceAdjuster.shortenReference(
            (GrQualifiedReference<?>) parent);
      }
    }
  }
  public void setType(@Nullable PsiType type) {
    final GrTypeElement typeElement = getTypeElementGroovy();
    if (type == null) {
      if (typeElement == null) return;
      if (getModifierList().getModifiers().length == 0) {
        getModifierList().setModifierProperty(GrModifier.DEF, true);
      }
      typeElement.delete();
      return;
    }

    type = TypesUtil.unboxPrimitiveTypeWrapper(type);
    GrTypeElement newTypeElement;
    try {
      newTypeElement = GroovyPsiElementFactory.getInstance(getProject()).createTypeElement(type);
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return;
    }

    if (typeElement == null) {
      getModifierList().setModifierProperty(GrModifier.DEF, false);
      final GrVariable[] variables = getVariables();
      if (variables.length == 0) return;
      newTypeElement = (GrTypeElement) addBefore(newTypeElement, variables[0]);
    } else {
      newTypeElement = (GrTypeElement) typeElement.replace(newTypeElement);
    }

    JavaCodeStyleManager.getInstance(getProject()).shortenClassReferences(newTypeElement);
  }
  private static boolean generateDelegate(GrChangeInfoImpl grInfo) {
    final GrMethod method = grInfo.getMethod();
    final PsiClass psiClass = method.getContainingClass();
    GrMethod newMethod = (GrMethod) method.copy();
    newMethod = (GrMethod) psiClass.addAfter(newMethod, method);
    StringBuilder buffer = new StringBuilder();
    buffer.append("\n");
    if (method.isConstructor()) {
      buffer.append("this");
    } else {
      if (!PsiType.VOID.equals(method.getReturnType())) {
        buffer.append("return ");
      }
      buffer.append(
          GrChangeSignatureUtil.getNameWithQuotesIfNeeded(
              grInfo.getNewName(), method.getProject()));
    }

    generateParametersForDelegateCall(grInfo, method, buffer);

    final GrCodeBlock codeBlock =
        GroovyPsiElementFactory.getInstance(method.getProject())
            .createMethodBodyFromText(buffer.toString());
    newMethod.setBlock(codeBlock);
    newMethod.getModifierList().setModifierProperty(PsiModifier.ABSTRACT, false);

    CodeStyleManager.getInstance(method.getProject()).reformat(newMethod);
    return processPrimaryMethodInner(grInfo, method, null);
  }
  private void addNewClause(
      Collection<String> elements,
      Collection<String> additional,
      Project project,
      boolean isExtends)
      throws IncorrectOperationException {
    if (elements.isEmpty() && additional.isEmpty()) return;

    StringBuilder classText = new StringBuilder();
    classText.append("class A ");
    classText.append(isExtends ? "extends " : "implements ");

    for (String str : elements) {
      classText.append(str);
      classText.append(", ");
    }

    for (String str : additional) {
      classText.append(str);
      classText.append(", ");
    }

    classText.delete(classText.length() - 2, classText.length());

    classText.append(" {}");

    final GrTypeDefinition definition =
        GroovyPsiElementFactory.getInstance(project).createTypeDefinition(classText.toString());
    GroovyPsiElement clause =
        isExtends ? definition.getExtendsClause() : definition.getImplementsClause();
    assert clause != null;

    PsiElement addedClause = myClass.addBefore(clause, myClass.getBody());
    JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedClause);
  }
 public PsiElement setName(@NotNull String newName) throws IncorrectOperationException {
   if (!newName.equals(getName())) {
     GrParameter parameter =
         GroovyPsiElementFactory.getInstance(getProject())
             .createParameter(newName, (String) null, null);
     myClosure.addParameter(parameter);
   }
   return this;
 }
  @Nullable
  private static GrAssignmentExpression genRefForSetter(GrMethodCall call, String accessorName) {
    String name = GroovyPropertyUtils.getPropertyNameBySetterName(accessorName);
    if (name == null) return null;
    GrExpression value = call.getExpressionArguments()[0];
    GrReferenceExpression refExpr = (GrReferenceExpression) call.getInvokedExpression();

    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(call.getProject());
    final GrAssignmentExpression assignment =
        (GrAssignmentExpression) factory.createStatementFromText("yyy = xxx", call);

    GrReferenceExpression lvalueRef = (GrReferenceExpression) assignment.getLValue();
    lvalueRef.setQualifier(refExpr.getQualifier());
    lvalueRef.handleElementRenameSimple(name);
    assignment.getRValue().replaceWithExpression(value, true);

    return assignment;
  }
  private static boolean canBeSimplified(PsiElement element) {
    if (PsiTreeUtil.getParentOfType(element, PsiComment.class) != null) return false;

    if (element instanceof GrCodeReferenceElement) {
      if (PsiTreeUtil.getParentOfType(element, GrImportStatement.class, GrPackageDefinition.class)
          != null) return false;
    } else if (element instanceof GrReferenceExpression) {
      if (!PsiImplUtil.seemsToBeQualifiedClassName((GrReferenceExpression) element)) return false;
    } else {
      return false;
    }

    final GrReferenceElement ref = (GrReferenceElement) element;
    if (ref.getQualifier() == null) return false;
    if (!(ref.getContainingFile() instanceof GroovyFileBase)) return false;

    final PsiElement resolved = ref.resolve();
    if (!(resolved instanceof PsiClass)) return false;

    final String name = ((PsiClass) resolved).getName();
    if (name == null) return false;

    final GroovyPsiElementFactory factory =
        GroovyPsiElementFactory.getInstance(element.getProject());
    final GrReferenceExpression shortedRef =
        factory.createReferenceExpressionFromText(name, element);
    final GroovyResolveResult resolveResult = shortedRef.advancedResolve();

    if (element.getManager().areElementsEquivalent(resolved, resolveResult.getElement())) {
      return true;
    }

    final PsiClass containingClass = ((PsiClass) resolved).getContainingClass();
    if (containingClass != null
        && !GroovyCodeStyleSettingsFacade.getInstance(containingClass.getProject())
            .insertInnerClassImports()) {
      return false;
    }

    return resolveResult.getElement() == null
        || !resolveResult.isAccessible()
        || !resolveResult.isStaticsOK();
  }
 @Override
 protected GrReferenceExpression bindWithQualifiedRef(@NotNull String qName) {
   final GrTypeArgumentList list = getTypeArgumentList();
   final String typeArgs = (list != null) ? list.getText() : "";
   final String text = qName + typeArgs;
   GrReferenceExpression qualifiedRef =
       GroovyPsiElementFactory.getInstance(getProject()).createReferenceExpressionFromText(text);
   getNode().getTreeParent().replaceChild(getNode(), qualifiedRef.getNode());
   return qualifiedRef;
 }
 private boolean isGroovyMethodName(String name) {
   String methodText = "def " + name + "(){}";
   try {
     final GrMethod method =
         GroovyPsiElementFactory.getInstance(getProject()).createMethodFromText(methodText);
     return method != null;
   } catch (Throwable e) {
     return false;
   }
 }
  @Override
  public PsiElement setName(@NonNls @NotNull String name) throws IncorrectOperationException {
    PsiElement nameElement = getNameIdentifierGroovy();

    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(nameElement.getProject());
    PsiElement newNameElement;
    if (JavaPsiFacade.getInstance(getProject()).getNameHelper().isIdentifier(name)) {
      try {
        GrMethod method = factory.createMethod(name, null);
        newNameElement = method.getNameIdentifierGroovy();
      } catch (IncorrectOperationException e) {
        newNameElement = factory.createLiteralFromValue(name).getFirstChild();
      }
    } else {
      newNameElement = factory.createLiteralFromValue(name).getFirstChild();
    }
    nameElement.replace(newNameElement);
    return this;
  }
 @Override
 protected GrReferenceExpression bindWithQualifiedRef(@NotNull String qName) {
   GrReferenceExpression qualifiedRef =
       GroovyPsiElementFactory.getInstance(getProject()).createReferenceExpressionFromText(qName);
   final GrTypeArgumentList list = getTypeArgumentList();
   if (list != null) {
     qualifiedRef.getNode().addChild(list.copy().getNode());
   }
   getNode().getTreeParent().replaceChild(getNode(), qualifiedRef.getNode());
   return qualifiedRef;
 }
  /** @return replaced expression or null if expression is not replaced */
  @Nullable
  private static GrExpression addParenthesesIfNeeded(
      GrExpression newExpr, GrExpression oldExpr, GrExpression oldParent) {
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(oldExpr.getProject());

    int parentPriorityLevel = getExprPriorityLevel(oldParent);
    int newPriorityLevel = getExprPriorityLevel(newExpr);

    if (parentPriorityLevel > newPriorityLevel) {
      newExpr = factory.createParenthesizedExpr(newExpr);
    } else if (parentPriorityLevel == newPriorityLevel && parentPriorityLevel != 0) {
      if (oldParent instanceof GrBinaryExpression) {
        GrBinaryExpression binaryExpression = (GrBinaryExpression) oldParent;
        if (isNotAssociative(binaryExpression)
            && oldExpr.equals(binaryExpression.getRightOperand())) {
          newExpr = factory.createParenthesizedExpr(newExpr);
        }
      }
    }
    return newExpr;
  }