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);
  }
 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 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
 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);
       }
     }
   }
 }
  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);
      }
    }
  }
  @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;
  }
  @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;
  }
  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;
  }
  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);
  }
예제 #12
0
  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;
  }
예제 #13
0
  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);
  }
  @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);
      }
    }
  }
예제 #15
0
  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
  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);
  }
 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;
 }
 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
 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;
 }
 @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;
 }
  @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 "&&"
    }
  }
예제 #24
0
  @Override
  public GrTypeElement getTypeElementGroovy() {
    final GrFieldStub stub = getStub();
    if (stub != null) {
      final String typeText = stub.getTypeText();
      if (typeText == null) {
        return null;
      }

      return GroovyPsiElementFactory.getInstance(getProject()).createTypeElement(typeText, this);
    }

    return super.getTypeElementGroovy();
  }
 private static PsiElement generateTryCatch(PsiElement element, PsiClassType[] exceptions) {
   if (exceptions.length == 0) return element;
   GrTryCatchStatement tryCatch =
       (GrTryCatchStatement)
           GroovyPsiElementFactory.getInstance(element.getProject())
               .createStatementFromText("try{} catch (Exception e){}");
   final GrStatement statement = PsiTreeUtil.getParentOfType(element, GrStatement.class);
   assert statement != null;
   tryCatch.getTryBlock().addStatementBefore(statement, null);
   tryCatch = (GrTryCatchStatement) statement.replace(tryCatch);
   tryCatch.getCatchClauses()[0].delete();
   fixCatchBlock(tryCatch, exceptions);
   return tryCatch;
 }
예제 #26
0
 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);
 }
  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;
  }
예제 #28
0
    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);
      }
    }
예제 #29
0
 public static <T extends GrCondition> T replaceBody(
     T newBody, GrStatement body, ASTNode node, Project project) {
   if (body == null || newBody == null) {
     throw new IncorrectOperationException();
   }
   ASTNode oldBodyNode = body.getNode();
   if (oldBodyNode.getTreePrev() != null
       && mNLS.equals(oldBodyNode.getTreePrev().getElementType())) {
     ASTNode whiteNode = GroovyPsiElementFactory.getInstance(project).createWhiteSpace().getNode();
     node.replaceChild(oldBodyNode.getTreePrev(), whiteNode);
   }
   node.replaceChild(oldBodyNode, newBody.getNode());
   return newBody;
 }
  public PsiElement handleElementRenameSimple(String newElementName)
      throws IncorrectOperationException {
    if (!PsiUtil.isValidReferenceName(newElementName)) {
      final PsiElement old = getReferenceNameElement();
      if (old == null) throw new IncorrectOperationException("ref has no name element");

      PsiElement element =
          GroovyPsiElementFactory.getInstance(getProject())
              .createStringLiteralForReference(newElementName);
      old.replace(element);
      return this;
    }

    return super.handleElementRenameSimple(newElementName);
  }