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

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

      return conflictDescriptions;
    }
 /** signature should be changed for methods with type parameters */
 private void prepareMethodsChangeSignature(
     final PsiClass currentClass,
     final PsiElement memberToChangeSignature,
     final PsiType memberType) {
   if (memberToChangeSignature instanceof PsiMethod) {
     final PsiMethod method =
         MethodSignatureUtil.findMethodBySuperMethod(
             currentClass, (PsiMethod) memberToChangeSignature, true);
     if (method != null && method.getContainingClass() == currentClass) {
       myLabeler.addRoot(new TypeMigrationUsageInfo(method), memberType, method, false);
     }
   } else if (memberToChangeSignature instanceof PsiParameter
       && ((PsiParameter) memberToChangeSignature).getDeclarationScope() instanceof PsiMethod) {
     final PsiMethod superMethod =
         (PsiMethod) ((PsiParameter) memberToChangeSignature).getDeclarationScope();
     final int parameterIndex =
         superMethod.getParameterList().getParameterIndex((PsiParameter) memberToChangeSignature);
     final PsiMethod method =
         MethodSignatureUtil.findMethodBySuperMethod(currentClass, superMethod, true);
     if (method != null && method.getContainingClass() == currentClass) {
       final PsiParameter parameter = method.getParameterList().getParameters()[parameterIndex];
       if (!parameter.getType().equals(memberType)) {
         myLabeler.addRoot(new TypeMigrationUsageInfo(parameter), memberType, parameter, false);
       }
     }
   }
 }
Ejemplo n.º 3
0
    private void processListenerProperties(@NotNull PsiMethod method) {
      if (!method.getName().startsWith("add")
          || method.getParameterList().getParametersCount() != 1) return;

      final PsiParameter parameter = method.getParameterList().getParameters()[0];
      final PsiType type = parameter.getType();
      if (!(type instanceof PsiClassType)) return;

      final PsiClassType classType = (PsiClassType) type;
      final PsiClass listenerClass = classType.resolve();
      if (listenerClass == null) return;

      final PsiMethod[] listenerMethods = listenerClass.getMethods();
      if (!InheritanceUtil.isInheritorOrSelf(listenerClass, myEventListener, true)) return;

      for (PsiMethod listenerMethod : listenerMethods) {
        final String name = listenerMethod.getName();
        if (myPropertyNames.add(name)) {
          LookupElementBuilder builder =
              LookupElementBuilder.create(
                      generatePropertyResolveResult(name, listenerMethod, null, null), name)
                  .withIcon(JetgroovyIcons.Groovy.Property);
          myConsumer.consume(builder);
        }
      }
    }
 public static boolean areParametersErasureEqual(
     @NotNull PsiMethod method1, @NotNull PsiMethod method2) {
   if (method1.getParameterList().getParametersCount()
       != method2.getParameterList().getParametersCount()) return false;
   return areSignaturesErasureEqual(
       method1.getSignature(PsiSubstitutor.EMPTY), method2.getSignature(PsiSubstitutor.EMPTY));
 }
  public void testImplicitConstructorUsage() throws Throwable {
    PsiMethod[] ctrs =
        myJavaFacade.findClass("Foo", GlobalSearchScope.allScope(myProject)).getConstructors();
    PsiMethod method = ctrs[0];
    assertEquals(0, method.getParameterList().getParametersCount());
    assertEquals(0, ReferencesSearch.search(method).findAll().size());

    PsiMethod usedMethod = ctrs[1];
    assertEquals(1, usedMethod.getParameterList().getParametersCount());
    assertEquals(1, ReferencesSearch.search(usedMethod).findAll().size());
  }
  private static void processCallerMethod(
      JavaChangeInfo changeInfo,
      PsiMethod caller,
      PsiMethod baseMethod,
      boolean toInsertParams,
      boolean toInsertThrows)
      throws IncorrectOperationException {
    LOG.assertTrue(toInsertParams || toInsertThrows);
    if (toInsertParams) {
      List<PsiParameter> newParameters = new ArrayList<PsiParameter>();
      ContainerUtil.addAll(newParameters, caller.getParameterList().getParameters());
      final JavaParameterInfo[] primaryNewParms = changeInfo.getNewParameters();
      PsiSubstitutor substitutor =
          baseMethod == null
              ? PsiSubstitutor.EMPTY
              : ChangeSignatureProcessor.calculateSubstitutor(caller, baseMethod);
      for (JavaParameterInfo info : primaryNewParms) {
        if (info.getOldIndex() < 0)
          newParameters.add(createNewParameter(changeInfo, info, substitutor));
      }
      PsiParameter[] arrayed = newParameters.toArray(new PsiParameter[newParameters.size()]);
      boolean[] toRemoveParm = new boolean[arrayed.length];
      Arrays.fill(toRemoveParm, false);
      resolveParameterVsFieldsConflicts(arrayed, caller, caller.getParameterList(), toRemoveParm);
    }

    if (toInsertThrows) {
      List<PsiJavaCodeReferenceElement> newThrowns = new ArrayList<PsiJavaCodeReferenceElement>();
      final PsiReferenceList throwsList = caller.getThrowsList();
      ContainerUtil.addAll(newThrowns, throwsList.getReferenceElements());
      final ThrownExceptionInfo[] primaryNewExns = changeInfo.getNewExceptions();
      for (ThrownExceptionInfo thrownExceptionInfo : primaryNewExns) {
        if (thrownExceptionInfo.getOldIndex() < 0) {
          final PsiClassType type =
              (PsiClassType) thrownExceptionInfo.createType(caller, caller.getManager());
          final PsiJavaCodeReferenceElement ref =
              JavaPsiFacade.getInstance(caller.getProject())
                  .getElementFactory()
                  .createReferenceElementByType(type);
          newThrowns.add(ref);
        }
      }
      PsiJavaCodeReferenceElement[] arrayed =
          newThrowns.toArray(new PsiJavaCodeReferenceElement[newThrowns.size()]);
      boolean[] toRemoveParm = new boolean[arrayed.length];
      Arrays.fill(toRemoveParm, false);
      ChangeSignatureUtil.synchronizeList(
          throwsList, Arrays.asList(arrayed), ThrowsList.INSTANCE, toRemoveParm);
    }
  }
 public void testPropagateParameter() throws Exception {
   String basePath = "/refactoring/changeSignature/" + getTestName(false);
   @NonNls final String filePath = basePath + ".java";
   configureByFile(filePath);
   final PsiElement targetElement =
       TargetElementUtilBase.findTargetElement(
           getEditor(), TargetElementUtilBase.ELEMENT_NAME_ACCEPTED);
   assertTrue("<caret> is not on method name", targetElement instanceof PsiMethod);
   PsiMethod method = (PsiMethod) targetElement;
   final PsiClass containingClass = method.getContainingClass();
   assertTrue(containingClass != null);
   final PsiMethod[] callers = containingClass.findMethodsByName("caller", false);
   assertTrue(callers.length > 0);
   final PsiMethod caller = callers[0];
   final HashSet<PsiMethod> propagateParametersMethods = new HashSet<PsiMethod>();
   propagateParametersMethods.add(caller);
   final PsiParameter[] parameters = method.getParameterList().getParameters();
   new ChangeSignatureProcessor(
           getProject(),
           method,
           false,
           null,
           method.getName(),
           CanonicalTypes.createTypeWrapper(PsiType.VOID),
           new ParameterInfoImpl[] {
             new ParameterInfoImpl(0, parameters[0].getName(), parameters[0].getType()),
             new ParameterInfoImpl(-1, "b", PsiType.BOOLEAN)
           },
           null,
           propagateParametersMethods,
           null)
       .run();
   @NonNls String after = basePath + "_after.java";
   checkResultByFile(after);
 }
  private PsiMethod generateDelegate(final PsiMethod methodToReplaceIn)
      throws IncorrectOperationException {
    final PsiMethod delegate = (PsiMethod) methodToReplaceIn.copy();
    final PsiElementFactory elementFactory =
        JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory();
    ChangeSignatureProcessor.makeEmptyBody(elementFactory, delegate);
    final PsiCallExpression callExpression =
        ChangeSignatureProcessor.addDelegatingCallTemplate(delegate, delegate.getName());
    final PsiExpressionList argumentList = callExpression.getArgumentList();
    assert argumentList != null;
    final PsiParameter[] psiParameters = methodToReplaceIn.getParameterList().getParameters();

    final PsiParameter anchorParameter = getAnchorParameter(methodToReplaceIn);
    if (psiParameters.length == 0) {
      argumentList.add(myParameterInitializer);
    } else {
      if (anchorParameter == null) {
        argumentList.add(myParameterInitializer);
      }
      for (int i = 0; i < psiParameters.length; i++) {
        PsiParameter psiParameter = psiParameters[i];
        if (!myParametersToRemove.contains(i)) {
          final PsiExpression expression =
              elementFactory.createExpressionFromText(psiParameter.getName(), delegate);
          argumentList.add(expression);
        }
        if (psiParameter == anchorParameter) {
          argumentList.add(myParameterInitializer);
        }
      }
    }

    return (PsiMethod)
        methodToReplaceIn.getContainingClass().addBefore(delegate, methodToReplaceIn);
  }
Ejemplo n.º 9
0
  public static Collection<AnnotationSearchResult> findAllAnnotatedElements(
      PsiElement element, String annotation) {
    final PsiClass bean = PsiUtil.getTopLevelClass(element);
    if (bean == null) {
      return Collections.emptyList();
    }

    final List<AnnotationSearchResult> elementList = new ArrayList<AnnotationSearchResult>();
    PsiAnnotation a;
    for (PsiField e : bean.getAllFields()) {
      a = getAnnotationFromElement(e, annotation);
      if (a != null) {
        elementList.add(new AnnotationSearchResult(a, e));
      }
    }

    for (PsiMethod e : bean.getAllMethods()) {
      a = getAnnotationFromElement(e, annotation);

      if (a != null) {
        elementList.add(new AnnotationSearchResult(a, e));
      }

      for (PsiParameter p : e.getParameterList().getParameters()) {
        a = getAnnotationFromElement(p, annotation);

        if (a != null) {
          elementList.add(new AnnotationSearchResult(a, p));
        }
      }
    }

    return elementList;
  }
Ejemplo n.º 10
0
 @Override
 public LightRef asLightUsage(@NotNull PsiElement element, @NotNull ByteArrayEnumerator names) {
   if (mayBeVisibleOutsideOwnerFile(element)) {
     if (element instanceof PsiField) {
       final PsiField field = (PsiField) element;
       final PsiClass aClass = field.getContainingClass();
       if (aClass == null || aClass instanceof PsiAnonymousClass) return null;
       final String jvmOwnerName = ClassUtil.getJVMClassName(aClass);
       final String name = field.getName();
       if (name == null || jvmOwnerName == null) return null;
       return new LightRef.JavaLightFieldRef(id(jvmOwnerName, names), id(name, names));
     } else if (element instanceof PsiMethod) {
       final PsiClass aClass = ((PsiMethod) element).getContainingClass();
       if (aClass == null || aClass instanceof PsiAnonymousClass) return null;
       final String jvmOwnerName = ClassUtil.getJVMClassName(aClass);
       if (jvmOwnerName == null) return null;
       final PsiMethod method = (PsiMethod) element;
       final String name = method.isConstructor() ? "<init>" : method.getName();
       final int parametersCount = method.getParameterList().getParametersCount();
       return new LightRef.JavaLightMethodRef(
           id(jvmOwnerName, names), id(name, names), parametersCount);
     } else if (element instanceof PsiClass) {
       final String jvmClassName = ClassUtil.getJVMClassName((PsiClass) element);
       if (jvmClassName != null) {
         return new LightRef.JavaLightClassRef(id(jvmClassName, names));
       }
     }
   }
   return null;
 }
Ejemplo n.º 11
0
  private static boolean isParameterUsedRecursively(
      @NotNull PsiElement element, @NotNull List<PsiReference> array) {
    if (!(element instanceof PsiParameter)) return false;
    PsiParameter parameter = (PsiParameter) element;
    PsiElement scope = parameter.getDeclarationScope();
    if (!(scope instanceof PsiMethod)) return false;
    PsiMethod method = (PsiMethod) scope;
    int paramIndex = ArrayUtilRt.find(method.getParameterList().getParameters(), parameter);

    for (PsiReference reference : array) {
      if (!(reference instanceof PsiElement)) return false;
      PsiElement argument = (PsiElement) reference;

      PsiMethodCallExpression methodCallExpression =
          (PsiMethodCallExpression)
              new PsiMatcherImpl(argument)
                  .dot(PsiMatchers.hasClass(PsiReferenceExpression.class))
                  .parent(PsiMatchers.hasClass(PsiExpressionList.class))
                  .parent(PsiMatchers.hasClass(PsiMethodCallExpression.class))
                  .getElement();
      if (methodCallExpression == null) return false;
      PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
      if (method != methodExpression.resolve()) return false;
      PsiExpressionList argumentList = methodCallExpression.getArgumentList();
      PsiExpression[] arguments = argumentList.getExpressions();
      int argumentIndex = ArrayUtilRt.find(arguments, argument);
      if (paramIndex != argumentIndex) return false;
    }

    return true;
  }
 @Override
 public void visitNewExpression(PsiNewExpression expression) {
   super.visitNewExpression(expression);
   final PsiJavaCodeReferenceElement classReference = expression.getClassReference();
   if (classReference == null) {
     return;
   }
   final String name = classReference.getReferenceName();
   if (!"BigDecimal".equals(name)) {
     return;
   }
   final PsiMethod constructor = expression.resolveConstructor();
   if (constructor == null) {
     return;
   }
   final PsiParameterList parameterList = constructor.getParameterList();
   final int length = parameterList.getParametersCount();
   if (length != 1 && length != 2) {
     return;
   }
   final PsiParameter[] parameters = parameterList.getParameters();
   final PsiParameter firstParameter = parameters[0];
   final PsiType type = firstParameter.getType();
   if (type != PsiType.DOUBLE) {
     return;
   }
   registerNewExpressionError(expression);
 }
  @Override
  public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element)
      throws IncorrectOperationException {
    final PsiNewExpression expression =
        PsiTreeUtil.getParentOfType(element, PsiNewExpression.class, false);
    if (expression == null) {
      return;
    }

    final PsiExpressionList arguments = expression.getArgumentList();
    if (arguments == null) {
      return;
    }

    final PsiMethod constructor = expression.resolveConstructor();
    if (constructor == null) {
      return;
    }

    final PsiExpressionList newArguments =
        createNewArguments(
            JavaPsiFacade.getElementFactory(project),
            constructor.getParameterList().getParameters(),
            arguments.getExpressions());

    if (newArguments == null) {
      return;
    }

    arguments.replace(newArguments);
  }
    public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor descriptor) {
      final PsiElement element = descriptor.getPsiElement();
      final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
      LOG.assertTrue(method != null);
      PsiParameter parameter = PsiTreeUtil.getParentOfType(element, PsiParameter.class, false);
      if (parameter == null) {
        final PsiParameter[] parameters = method.getParameterList().getParameters();
        for (PsiParameter psiParameter : parameters) {
          if (Comparing.strEqual(psiParameter.getName(), myParameterName)) {
            parameter = psiParameter;
            break;
          }
        }
      }
      if (parameter == null) return;
      if (!CommonRefactoringUtil.checkReadOnlyStatus(project, parameter)) return;

      final PsiExpression defToInline;
      try {
        defToInline =
            JavaPsiFacade.getInstance(project)
                .getElementFactory()
                .createExpressionFromText(myValue, parameter);
      } catch (IncorrectOperationException e) {
        return;
      }
      final PsiParameter parameterToInline = parameter;
      inlineSameParameterValue(method, parameterToInline, defToInline);
    }
 @Override
 public void visitMethod(@NotNull PsiMethod method) {
   // note: no call to super
   if (method.getNameIdentifier() == null) {
     return;
   }
   if (!method.isConstructor()) {
     return;
   }
   if (ignoreScope != Scope.NONE) {
     switch (ignoreScope.ordinal()) {
       case 3:
         if (method.hasModifierProperty(PsiModifier.PROTECTED)) return;
       case 2:
         if (method.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) return;
       case 1:
         if (method.hasModifierProperty(PsiModifier.PRIVATE)) return;
     }
   }
   final PsiParameterList parameterList = method.getParameterList();
   final int parametersCount = parameterList.getParametersCount();
   if (parametersCount <= getLimit()) {
     return;
   }
   registerMethodError(method, Integer.valueOf(parametersCount));
 }
Ejemplo n.º 16
0
  @NotNull
  public List<String> createConversions(@NotNull PsiCallExpression expression) {
    PsiExpressionList argumentList = expression.getArgumentList();
    PsiExpression[] arguments =
        argumentList != null ? argumentList.getExpressions() : new PsiExpression[] {};
    List<String> conversions = new LinkedList<String>();
    //noinspection UnusedDeclaration
    for (PsiExpression a : arguments) {
      conversions.add("");
    }

    PsiMethod resolve = expression.resolveMethod();
    if (resolve != null) {
      List<PsiType> expectedTypes = new LinkedList<PsiType>();
      List<PsiType> actualTypes = new LinkedList<PsiType>();

      for (PsiParameter p : resolve.getParameterList().getParameters())
        expectedTypes.add(p.getType());

      for (PsiExpression e : arguments) actualTypes.add(e.getType());

      if (conversions.size() == actualTypes.size() && actualTypes.size() == expectedTypes.size()) {
        for (int i = 0; i < actualTypes.size(); i++)
          conversions.set(i, createConversionForExpression(arguments[i], expectedTypes.get(i)));
      }
    }
    return conversions;
  }
Ejemplo n.º 17
0
  List<MethodContract> inferContracts() {
    PsiCodeBlock body = myMethod.getBody();
    PsiStatement[] statements = body == null ? PsiStatement.EMPTY_ARRAY : body.getStatements();
    if (statements.length == 0) return Collections.emptyList();

    if (statements.length == 1) {
      if (statements[0] instanceof PsiReturnStatement) {
        List<MethodContract> result =
            handleDelegation(((PsiReturnStatement) statements[0]).getReturnValue(), false);
        if (result != null) return result;
      } else if (statements[0] instanceof PsiExpressionStatement
          && ((PsiExpressionStatement) statements[0]).getExpression()
              instanceof PsiMethodCallExpression) {
        List<MethodContract> result =
            handleDelegation(((PsiExpressionStatement) statements[0]).getExpression(), false);
        if (result != null)
          return ContainerUtil.findAll(
              result,
              new Condition<MethodContract>() {
                @Override
                public boolean value(MethodContract contract) {
                  return contract.returnValue == THROW_EXCEPTION
                      || !textMatches(myMethod.getReturnTypeElement(), PsiKeyword.VOID);
                }
              });
      }
    }

    ValueConstraint[] emptyState =
        MethodContract.createConstraintArray(myMethod.getParameterList().getParametersCount());
    return visitStatements(Collections.singletonList(emptyState), statements);
  }
    @Override
    public boolean execute(PsiElement element, ResolveState state) {
      if (element instanceof PsiMethod || element instanceof PsiField) {
        String propertyName;
        PsiType type;

        if (element instanceof PsiMethod) {
          PsiMethod method = (PsiMethod) element;
          if (!GroovyPropertyUtils.isSimplePropertySetter(method)) return true;

          propertyName = GroovyPropertyUtils.getPropertyNameBySetter(method);
          if (propertyName == null) return true;

          type = method.getParameterList().getParameters()[0].getType();
        } else {
          type = ((PsiField) element).getType();
          propertyName = ((PsiField) element).getName();
        }

        if (((PsiModifierListOwner) element).hasModifierProperty(PsiModifier.STATIC)) return true;

        if (myResult.containsKey(propertyName) || propertyName.equals(METACLASS)) return true;

        PsiSubstitutor substitutor = state.get(PsiSubstitutor.KEY);
        if (substitutor != null) {
          type = substitutor.substitute(type);
        }

        myResult.put(propertyName, new TypeCondition(type, element));
      }

      return true;
    }
  public static boolean checkParametersNumber(
      @NotNull List<CandidateInfo> conflicts,
      final int argumentsCount,
      boolean ignoreIfStaticsProblem) {
    boolean atLeastOneMatch = false;
    TIntArrayList unmatchedIndices = null;
    for (int i = 0; i < conflicts.size(); i++) {
      ProgressManager.checkCanceled();
      CandidateInfo info = conflicts.get(i);
      if (ignoreIfStaticsProblem && !info.isStaticsScopeCorrect()) return true;
      if (!(info instanceof MethodCandidateInfo)) continue;
      PsiMethod method = ((MethodCandidateInfo) info).getElement();
      if (method.isVarArgs()) return true;
      if (method.getParameterList().getParametersCount() == argumentsCount) {
        // remove all unmatched before
        if (unmatchedIndices != null) {
          for (int u = unmatchedIndices.size() - 1; u >= 0; u--) {
            int index = unmatchedIndices.get(u);
            conflicts.remove(index);
            i--;
          }
          unmatchedIndices = null;
        }
        atLeastOneMatch = true;
      } else if (atLeastOneMatch) {
        conflicts.remove(i);
        i--;
      } else {
        if (unmatchedIndices == null) unmatchedIndices = new TIntArrayList(conflicts.size() - i);
        unmatchedIndices.add(i);
      }
    }

    return atLeastOneMatch;
  }
    private static void removeUnusedParameterViaChangeSignature(
        final PsiMethod psiMethod, final Collection<PsiElement> parametersToDelete) {
      ArrayList<ParameterInfoImpl> newParameters = new ArrayList<ParameterInfoImpl>();
      PsiParameter[] oldParameters = psiMethod.getParameterList().getParameters();
      for (int i = 0; i < oldParameters.length; i++) {
        PsiParameter oldParameter = oldParameters[i];
        if (!parametersToDelete.contains(oldParameter)) {
          newParameters.add(
              new ParameterInfoImpl(i, oldParameter.getName(), oldParameter.getType()));
        }
      }

      ParameterInfoImpl[] parameterInfos =
          newParameters.toArray(new ParameterInfoImpl[newParameters.size()]);

      ChangeSignatureProcessor csp =
          new ChangeSignatureProcessor(
              psiMethod.getProject(),
              psiMethod,
              false,
              null,
              psiMethod.getName(),
              psiMethod.getReturnType(),
              parameterInfos);

      csp.run();
    }
Ejemplo n.º 21
0
  @SuppressWarnings({"HardCodedStringLiteral"})
  private static JVMName getJVMSignature(
      @Nullable PsiMethod method, boolean constructor, @Nullable PsiClass declaringClass) {
    JVMNameBuffer signature = new JVMNameBuffer();
    signature.append("(");

    if (constructor) {
      if (declaringClass != null) {
        final PsiClass outerClass = declaringClass.getContainingClass();
        if (outerClass != null) {
          // declaring class is an inner class
          if (!declaringClass.hasModifierProperty(PsiModifier.STATIC)) {
            appendJvmClassQualifiedName(signature, getJVMQualifiedName(outerClass));
          }
        }
      }
    }
    if (method != null) {
      for (PsiParameter psiParameter : method.getParameterList().getParameters()) {
        appendJVMSignature(signature, psiParameter.getType());
      }
    }
    signature.append(")");
    if (!constructor && method != null) {
      appendJVMSignature(signature, method.getReturnType());
    } else {
      signature.append(new JVMRawText("V"));
    }
    return signature.toName();
  }
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      if (!CodeInsightUtilBase.preparePsiElementForWrite(descriptor.getPsiElement())) return;
      final PsiMethod psiMethod =
          PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethod.class);
      if (psiMethod != null) {
        final ArrayList<PsiElement> psiParameters = new ArrayList<PsiElement>();
        final RefElement refMethod = myManager != null ? myManager.getReference(psiMethod) : null;
        if (refMethod != null) {
          for (final RefParameter refParameter : getUnusedParameters((RefMethod) refMethod)) {
            psiParameters.add(refParameter.getElement());
          }
        } else {
          final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
          for (PsiParameter parameter : parameters) {
            if (Comparing.strEqual(parameter.getName(), myHint)) {
              psiParameters.add(parameter);
              break;
            }
          }
        }
        final PsiModificationTracker tracker = psiMethod.getManager().getModificationTracker();
        final long startModificationCount = tracker.getModificationCount();

        removeUnusedParameterViaChangeSignature(psiMethod, psiParameters);
        if (refMethod != null && startModificationCount != tracker.getModificationCount()) {
          myProcessor.ignoreElement(refMethod);
        }
      }
    }
 private static boolean doCreate(
     Project project,
     Editor editor,
     PsiParameter[] parameters,
     SmartPsiElementPointer constructorPointer,
     ParameterInfoImpl[] parameterInfos,
     HashMap<PsiField, String> fields) {
   PsiMethod constructor = (PsiMethod) constructorPointer.getElement();
   assert constructor != null;
   PsiParameter[] newParameters = constructor.getParameterList().getParameters();
   if (newParameters == parameters) return false; // user must have canceled dialog
   boolean created = false;
   // do not introduce assignment in chanined constructor
   if (JavaHighlightUtil.getChainedConstructors(constructor) == null) {
     for (PsiField field : fields.keySet()) {
       final String defaultParamName = fields.get(field);
       PsiParameter parameter =
           findParamByName(defaultParamName, field.getType(), newParameters, parameterInfos);
       if (parameter == null) {
         continue;
       }
       notNull(project, field, parameter);
       AssignFieldFromParameterAction.addFieldAssignmentStatement(
           project, field, parameter, editor);
       created = true;
     }
   }
   return created;
 }
  public IntroduceParameterObjectProcessor(
      String className,
      String packageName,
      MoveDestination moveDestination,
      PsiMethod method,
      VariableData[] parameters,
      boolean keepMethodAsDelegate,
      final boolean useExistingClass,
      final boolean createInnerClass,
      String newVisibility,
      boolean generateAccessors) {
    super(method.getProject());
    myMoveDestination = moveDestination;
    this.method = method;
    this.className = className;
    this.packageName = packageName;
    this.keepMethodAsDelegate = keepMethodAsDelegate;
    myUseExistingClass = useExistingClass;
    myCreateInnerClass = createInnerClass;
    myNewVisibility = newVisibility;
    myGenerateAccessors = generateAccessors;
    this.parameters = new ArrayList<ParameterChunk>();
    for (VariableData parameter : parameters) {
      this.parameters.add(new ParameterChunk(parameter));
    }
    final PsiParameterList parameterList = method.getParameterList();
    final PsiParameter[] methodParams = parameterList.getParameters();
    paramsToMerge = new int[parameters.length];
    for (int p = 0; p < parameters.length; p++) {
      VariableData parameter = parameters[p];
      for (int i = 0; i < methodParams.length; i++) {
        final PsiParameter methodParam = methodParams[i];
        if (parameter.variable.equals(methodParam)) {
          paramsToMerge[p] = i;
          break;
        }
      }
    }
    final Set<PsiTypeParameter> typeParamSet = new HashSet<PsiTypeParameter>();
    final PsiTypeVisitor<Object> typeParametersVisitor =
        new PsiTypeVisitor<Object>() {
          @Override
          public Object visitClassType(PsiClassType classType) {
            final PsiClass referent = classType.resolve();
            if (referent instanceof PsiTypeParameter) {
              typeParamSet.add((PsiTypeParameter) referent);
            }
            return super.visitClassType(classType);
          }
        };
    for (VariableData parameter : parameters) {
      parameter.type.accept(typeParametersVisitor);
    }
    typeParams = new ArrayList<PsiTypeParameter>(typeParamSet);

    final String qualifiedName = StringUtil.getQualifiedName(packageName, className);
    final GlobalSearchScope scope = GlobalSearchScope.allScope(myProject);
    existingClass = JavaPsiFacade.getInstance(myProject).findClass(qualifiedName, scope);
  }
 ParamUsageVisitor(PsiMethod method, int[] paramIndicesToMerge) {
   super();
   final PsiParameterList paramList = method.getParameterList();
   final PsiParameter[] parameters = paramList.getParameters();
   for (int i : paramIndicesToMerge) {
     paramsToMerge.add(parameters[i]);
   }
 }
Ejemplo n.º 26
0
 @Nullable
 private PsiParameter getParameter() {
   if (!myMethod.isValid()) return null;
   final PsiParameter[] parameters = myMethod.getParameterList().getParameters();
   return parameters.length > myParameterIndex && myParameterIndex >= 0
       ? parameters[myParameterIndex]
       : null;
 }
 private static boolean shouldRenameSetterParameter(
     JavaCodeStyleManager manager, String propertyName, PsiMethod setter) {
   boolean shouldRenameSetterParameter;
   String parameterName = manager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER);
   PsiParameter setterParameter = setter.getParameterList().getParameters()[0];
   shouldRenameSetterParameter = parameterName.equals(setterParameter.getName());
   return shouldRenameSetterParameter;
 }
 private static PsiElement[] getParameterElementsToSearch(final PsiParameter parameter) {
   final PsiMethod method = (PsiMethod) parameter.getDeclarationScope();
   PsiMethod[] overrides =
       OverridingMethodsSearch.search(method, true).toArray(PsiMethod.EMPTY_ARRAY);
   for (int i = 0; i < overrides.length; i++) {
     overrides[i] = (PsiMethod) overrides[i].getNavigationElement();
   }
   List<PsiElement> elementsToSearch = new ArrayList<PsiElement>(overrides.length + 1);
   elementsToSearch.add(parameter);
   int idx = method.getParameterList().getParameterIndex(parameter);
   for (PsiMethod override : overrides) {
     final PsiParameter[] parameters = override.getParameterList().getParameters();
     if (idx < parameters.length) {
       elementsToSearch.add(parameters[idx]);
     }
   }
   return elementsToSearch.toArray(new PsiElement[elementsToSearch.size()]);
 }
 @Override
 public PsiParameter createParameter(
     @NotNull @NonNls String name, PsiType type, PsiElement context)
     throws IncorrectOperationException {
   final PsiMethod psiMethod =
       createMethodFromText("void f(" + type.getCanonicalText() + " " + name + ") {}", context);
   final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
   return parameters[0];
 }
  @Nullable
  @Override
  protected List<ClosureParameterInfo> getParameterInfos(
      InsertionContext context,
      PsiMethod method,
      PsiSubstitutor substitutor,
      Document document,
      int offset,
      PsiElement parent) {
    final String name = method.getName();
    if (!"eachWithIndex".equals(name)) return null;

    if (method instanceof GrGdkMethod) method = ((GrGdkMethod) method).getStaticMethod();

    final PsiClass containingClass = method.getContainingClass();
    if (containingClass == null) return null;

    final String qname = containingClass.getQualifiedName();

    if (!GroovyCommonClassNames.DEFAULT_GROOVY_METHODS.equals(qname)) return null;

    final PsiParameter[] parameters = method.getParameterList().getParameters();
    if (parameters.length != 2) return null;

    final PsiType type = parameters[0].getType();
    final PsiType collection = substitutor.substitute(type);

    final PsiType iterable = getIteratedType(parent, collection);
    if (iterable != null) {
      return Arrays.asList(
          new ClosureParameterInfo(iterable.getCanonicalText(), "entry"),
          new ClosureParameterInfo("int", "i"));
    }

    if (InheritanceUtil.isInheritor(collection, CommonClassNames.JAVA_UTIL_MAP)) {
      final PsiType[] typeParams = ((PsiClassType) collection).getParameters();

      final Project project = context.getProject();

      final PsiClass entry =
          JavaPsiFacade.getInstance(project)
              .findClass("java.util.Map.Entry", parent.getResolveScope());
      if (entry == null) return null;

      final PsiClassType entryType =
          JavaPsiFacade.getElementFactory(project).createType(entry, typeParams);

      return Arrays.asList(
          new ClosureParameterInfo(entryType.getCanonicalText(), "entry"),
          new ClosureParameterInfo("int", "i"));
    }

    return Arrays.asList(
        new ClosureParameterInfo(collection.getCanonicalText(), "entry"),
        new ClosureParameterInfo("int", "i"));
  }