/**
   * @return 1 if second is more preferable 0 if methods are equal -1 if first is more preferable
   */
  private int compareMethods(
      @NotNull PsiMethod method1,
      @NotNull PsiSubstitutor substitutor1,
      @Nullable PsiElement resolveContext1,
      @NotNull PsiMethod method2,
      @NotNull PsiSubstitutor substitutor2,
      @Nullable PsiElement resolveContext2) {
    if (!method1.getName().equals(method2.getName())) return 0;

    if (secondMethodIsPreferable(
        method1, substitutor1, resolveContext1, method2, substitutor2, resolveContext2)) {
      if (secondMethodIsPreferable(
          method2, substitutor2, resolveContext2, method1, substitutor1, resolveContext1)) {
        if (method2 instanceof GrGdkMethod && !(method1 instanceof GrGdkMethod)) {
          return -1;
        }
      }
      return 1;
    }
    if (secondMethodIsPreferable(
        method2, substitutor2, resolveContext2, method1, substitutor1, resolveContext1)) {
      return -1;
    }

    return 0;
  }
Example #2
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 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;
  }
  @Nullable
  private static PsiMethod existingClassIsCompatible(PsiClass aClass, List<ParameterChunk> params) {
    if (params.size() == 1) {
      final ParameterChunk parameterChunk = params.get(0);
      final PsiType paramType = parameterChunk.parameter.type;
      if (TypeConversionUtil.isPrimitiveWrapper(aClass.getQualifiedName())) {
        parameterChunk.setField(aClass.findFieldByName("value", false));
        parameterChunk.setGetter(paramType.getCanonicalText() + "Value");
        for (PsiMethod constructor : aClass.getConstructors()) {
          if (constructorIsCompatible(constructor, params)) return constructor;
        }
      }
    }
    final PsiMethod[] constructors = aClass.getConstructors();
    PsiMethod compatibleConstructor = null;
    for (PsiMethod constructor : constructors) {
      if (constructorIsCompatible(constructor, params)) {
        compatibleConstructor = constructor;
        break;
      }
    }
    if (compatibleConstructor == null) {
      return null;
    }
    final PsiParameterList parameterList = compatibleConstructor.getParameterList();
    final PsiParameter[] constructorParams = parameterList.getParameters();
    for (int i = 0; i < constructorParams.length; i++) {
      final PsiParameter param = constructorParams[i];
      final ParameterChunk parameterChunk = params.get(i);

      final PsiField field = findFieldAssigned(param, compatibleConstructor);
      if (field == null) {
        return null;
      }

      parameterChunk.setField(field);

      final PsiMethod getterForField = PropertyUtil.findGetterForField(field);
      if (getterForField != null) {
        parameterChunk.setGetter(getterForField.getName());
      }

      final PsiMethod setterForField = PropertyUtil.findSetterForField(field);
      if (setterForField != null) {
        parameterChunk.setSetter(setterForField.getName());
      }
    }
    return compatibleConstructor;
  }
 public void bePatternConfiguration(List<PsiClass> classes, PsiMethod method) {
   data.TEST_OBJECT = TestType.PATTERN.getType();
   final String suffix;
   if (method != null) {
     data.METHOD_NAME = method.getName();
     suffix = "," + data.METHOD_NAME;
   } else {
     suffix = "";
   }
   LinkedHashSet<String> patterns = new LinkedHashSet<String>();
   for (PsiClass pattern : classes) {
     patterns.add(JavaExecutionUtil.getRuntimeQualifiedName(pattern) + suffix);
   }
   data.setPatterns(patterns);
   final Module module =
       RunConfigurationProducer.getInstance(TestNGPatternConfigurationProducer.class)
           .findModule(this, getConfigurationModule().getModule(), patterns);
   if (module == null) {
     data.setScope(TestSearchScope.WHOLE_PROJECT);
     setModule(null);
   } else {
     setModule(module);
   }
   setGeneratedName();
 }
 public void bePatternConfiguration(List<PsiClass> classes, PsiMethod method) {
   myData.TEST_OBJECT = TEST_PATTERN;
   final Set<String> patterns = new HashSet<String>();
   final String methodSufiix;
   if (method != null) {
     myData.METHOD_NAME = method.getName();
     methodSufiix = "," + myData.METHOD_NAME;
   } else {
     methodSufiix = "";
   }
   for (PsiClass pattern : classes) {
     patterns.add(JavaExecutionUtil.getRuntimeQualifiedName(pattern) + methodSufiix);
   }
   myData.setPatterns(patterns);
   final Module module =
       PatternConfigurationProducer.findModule(
           this, getConfigurationModule().getModule(), patterns);
   if (module == null) {
     myData.setScope(TestSearchScope.WHOLE_PROJECT);
     setModule(null);
   } else {
     setModule(module);
   }
   setGeneratedName();
 }
 @NotNull
 private static List<PsiMethod> findMethodsBySignature(
     @NotNull PsiClass aClass,
     @NotNull PsiMethod patternMethod,
     boolean checkBases,
     boolean stopOnFirst) {
   final PsiMethod[] methodsByName = aClass.findMethodsByName(patternMethod.getName(), checkBases);
   if (methodsByName.length == 0) return Collections.emptyList();
   final List<PsiMethod> methods = new SmartList<PsiMethod>();
   final MethodSignature patternSignature = patternMethod.getSignature(PsiSubstitutor.EMPTY);
   for (final PsiMethod method : methodsByName) {
     final PsiClass superClass = method.getContainingClass();
     final PsiSubstitutor substitutor;
     if (checkBases && !aClass.equals(superClass)) {
       substitutor =
           TypeConversionUtil.getSuperClassSubstitutor(superClass, aClass, PsiSubstitutor.EMPTY);
     } else {
       substitutor = PsiSubstitutor.EMPTY;
     }
     final MethodSignature signature = method.getSignature(substitutor);
     if (signature.equals(patternSignature)) {
       methods.add(method);
       if (stopOnFirst) {
         break;
       }
     }
   }
   return methods;
 }
 @Nullable
 private static PsiMethodCallExpression checkMethodResolvable(
     PsiMethodCallExpression methodCall,
     PsiMethod targetMethod,
     PsiReferenceExpression context,
     PsiClass aClass)
     throws IncorrectOperationException {
   PsiElementFactory factory =
       JavaPsiFacade.getInstance(targetMethod.getProject()).getElementFactory();
   final PsiElement resolved = methodCall.getMethodExpression().resolve();
   if (resolved != targetMethod) {
     PsiClass containingClass;
     if (resolved instanceof PsiMethod) {
       containingClass = ((PsiMethod) resolved).getContainingClass();
     } else if (resolved instanceof PsiClass) {
       containingClass = (PsiClass) resolved;
     } else {
       return null;
     }
     if (containingClass != null && containingClass.isInheritor(aClass, false)) {
       final PsiExpression newMethodExpression =
           factory.createExpressionFromText("super." + targetMethod.getName(), context);
       methodCall.getMethodExpression().replace(newMethodExpression);
     } else {
       methodCall = null;
     }
   }
   return methodCall;
 }
Example #9
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;
 }
Example #10
0
 @NotNull
 public static String getPropertyNameByGetter(PsiMethod getterMethod) {
   @NonNls String methodName = getterMethod.getName();
   return methodName.startsWith("get")
       ? StringUtil.decapitalize(methodName.substring(3))
       : StringUtil.decapitalize(methodName.substring(2));
 }
  @Override
  public void processQuery(
      @NotNull MethodReferencesSearch.SearchParameters p,
      @NotNull Processor<PsiReference> consumer) {
    final PsiMethod method = p.getMethod();
    final PsiClass aClass = method.getContainingClass();
    if (aClass == null) return;

    final String name = method.getName();
    if (StringUtil.isEmpty(name)) return;

    final boolean strictSignatureSearch = p.isStrictSignatureSearch();
    final PsiMethod[] methods =
        strictSignatureSearch ? new PsiMethod[] {method} : aClass.findMethodsByName(name, false);

    SearchScope accessScope = GroovyScopeUtil.getEffectiveScope(methods);
    final SearchScope restrictedByAccess =
        GroovyScopeUtil.restrictScopeToGroovyFiles(p.getScope(), accessScope);

    final String textToSearch = findLongestWord(name);

    p.getOptimizer()
        .searchWord(
            textToSearch,
            restrictedByAccess,
            UsageSearchContext.IN_STRINGS,
            true,
            new MethodTextOccurrenceProcessor(aClass, strictSignatureSearch, methods));
  }
  private void collectUncaughtExceptions(@NotNull PsiMethod method) {
    if (isExternalOverride()) return;
    if (getRefManager().isOfflineView()) return;
    @NonNls final String name = method.getName();
    if (getOwnerClass().isTestCase() && name.startsWith("test")) return;

    if (getSuperMethods().isEmpty()) {
      PsiClassType[] throwsList = method.getThrowsList().getReferencedTypes();
      if (throwsList.length > 0) {
        myUnThrownExceptions =
            throwsList.length == 1
                ? new SmartList<String>()
                : new ArrayList<String>(throwsList.length);
        for (final PsiClassType type : throwsList) {
          PsiClass aClass = type.resolve();
          String fqn = aClass == null ? null : aClass.getQualifiedName();
          if (fqn != null) {
            myUnThrownExceptions.add(fqn);
          }
        }
      }
    }

    final PsiCodeBlock body = method.getBody();
    if (body == null) return;

    final Collection<PsiClassType> exceptionTypes =
        ExceptionUtil.collectUnhandledExceptions(body, method, false);
    for (final PsiClassType exceptionType : exceptionTypes) {
      updateThrowsList(exceptionType);
    }
  }
 private void doTest(
     @PsiModifier.ModifierConstant @Nullable String newVisibility,
     @Nullable String newName,
     @Nullable String newReturnType,
     GenParams genParams,
     GenExceptions genExceptions,
     final boolean generateDelegate)
     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 PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory();
   PsiType newType =
       newReturnType != null
           ? factory.createTypeFromText(newReturnType, method)
           : method.getReturnType();
   new ChangeSignatureProcessor(
           getProject(),
           method,
           generateDelegate,
           newVisibility,
           newName != null ? newName : method.getName(),
           newType,
           genParams.genParams(method),
           genExceptions.genExceptions(method))
       .run();
   @NonNls String after = basePath + "_after.java";
   checkResultByFile(after);
 }
 private void processUsagesForMethod(
     final boolean deleteMethodHierarchy,
     PsiMethod method,
     int[] paramPermutation,
     String getterName,
     PsiMethod delegatedMethod,
     List<FixableUsageInfo> usages) {
   for (PsiReference reference : ReferencesSearch.search(method)) {
     final PsiElement referenceElement = reference.getElement();
     final PsiMethodCallExpression call = (PsiMethodCallExpression) referenceElement.getParent();
     final String access;
     if (call.getMethodExpression().getQualifierExpression() == null) {
       access = field.getName();
     } else {
       access = getterName + "()";
       if (getter == null) {
         getter = GenerateMembersUtil.generateGetterPrototype(field);
       }
     }
     usages.add(
         new InlineDelegatingCall(call, paramPermutation, access, delegatedMethod.getName()));
   }
   if (deleteMethodHierarchy) {
     usages.add(new DeleteMethod(method));
   }
 }
  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);
  }
 private void doTest(
     ParameterInfoImpl[] newParameters,
     final ThrownExceptionInfo[] newExceptions,
     Set<PsiMethod> methodsToPropagateParameterChanges,
     Set<PsiMethod> methodsToPropagateExceptionChanges,
     PsiMethod primaryMethod)
     throws Exception {
   final String filePath = getBasePath() + getTestName(false) + ".java";
   final PsiType returnType = primaryMethod.getReturnType();
   final CanonicalTypes.Type type =
       returnType == null ? null : CanonicalTypes.createTypeWrapper(returnType);
   new ChangeSignatureProcessor(
           getProject(),
           primaryMethod,
           false,
           null,
           primaryMethod.getName(),
           type,
           generateParameterInfos(primaryMethod, newParameters),
           generateExceptionInfos(primaryMethod, newExceptions),
           methodsToPropagateParameterChanges,
           methodsToPropagateExceptionChanges)
       .run();
   checkResultByFile(filePath + ".after");
 }
  private static boolean isGetterInvocation(@NotNull GrMethodCall call) {
    GrExpression expr = call.getInvokedExpression();
    if (!(expr instanceof GrReferenceExpression)) return false;

    PsiMethod method = call.resolveMethod();
    if (!GroovyPropertyUtils.isSimplePropertyGetter(method)) return false;
    LOG.assertTrue(method != null);
    if (!GroovyNamesUtil.isValidReference(
        GroovyPropertyUtils.getPropertyNameByGetterName(method.getName(), true),
        ((GrReferenceExpression) expr).getQualifier() != null,
        call.getProject())) {
      return false;
    }

    GrArgumentList args = call.getArgumentList();
    if (args == null || args.getAllArguments().length != 0) {
      return false;
    }

    GrExpression ref = genRefForGetter(call, ((GrReferenceExpression) expr).getReferenceName());
    if (ref instanceof GrReferenceExpression) {
      PsiElement resolved = ((GrReferenceExpression) ref).resolve();
      PsiManager manager = call.getManager();
      if (manager.areElementsEquivalent(resolved, method)
          || areEquivalentAccessors(method, resolved, manager)) {
        return true;
      }
    }

    return false;
  }
 @Override
 protected PsiMethod findTearDownMethod(@NotNull PsiClass clazz) {
   for (PsiMethod method : clazz.getMethods()) {
     if (method.getName().equals("tearDown")) return method;
   }
   return null;
 }
 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);
 }
  @Override
  public void visitMethod(PsiMethod method) {
    ArrangementSettingsToken type = method.isConstructor() ? CONSTRUCTOR : METHOD;
    JavaElementArrangementEntry entry =
        createNewEntry(method, method.getTextRange(), type, method.getName(), true);
    if (entry == null) {
      return;
    }

    processEntry(entry, method, method.getBody());
    parseProperties(method, entry);
    myInfo.onMethodEntryCreated(method, entry);
    MethodSignatureBackedByPsiMethod overridden =
        SuperMethodsSearch.search(method, null, true, false).findFirst();
    if (overridden != null) {
      myInfo.onOverriddenMethod(overridden.getMethod(), method);
    }
    boolean reset = myMethodBodyProcessor.setBaseMethod(method);
    try {
      method.accept(myMethodBodyProcessor);
    } finally {
      if (reset) {
        myMethodBodyProcessor.setBaseMethod(null);
      }
    }
  }
    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();
    }
 protected String getCommandName() {
   final PsiClass containingClass = method.getContainingClass();
   return RefactorJBundle.message(
       "introduced.parameter.class.command.name",
       className,
       containingClass.getName(),
       method.getName());
 }
 private static void searchMethod(
     ReferencesSearch.SearchParameters queryParameters, PsiMethod method) {
   if (method != null) {
     queryParameters
         .getOptimizer()
         .searchWord(method.getName(), queryParameters.getEffectiveSearchScope(), true, method);
   }
 }
  static void addExceptionsToThrowsList(
      @NotNull final Project project,
      @NotNull final PsiMethod targetMethod,
      @NotNull final Set<PsiClassType> unhandledExceptions) {
    final PsiMethod[] superMethods = getSuperMethods(targetMethod);

    boolean hasSuperMethodsWithoutExceptions =
        hasSuperMethodsWithoutExceptions(superMethods, unhandledExceptions);

    final boolean processSuperMethods;
    if (hasSuperMethodsWithoutExceptions && superMethods.length > 0) {
      int result =
          ApplicationManager.getApplication().isUnitTestMode()
              ? Messages.YES
              : Messages.showYesNoCancelDialog(
                  QuickFixBundle.message(
                      "add.exception.to.throws.inherited.method.warning.text",
                      targetMethod.getName()),
                  QuickFixBundle.message("method.is.inherited.warning.title"),
                  Messages.getQuestionIcon());

      if (result == Messages.YES) {
        processSuperMethods = true;
      } else if (result == Messages.NO) {
        processSuperMethods = false;
      } else {
        return;
      }
    } else {
      processSuperMethods = false;
    }

    ApplicationManager.getApplication()
        .runWriteAction(
            () -> {
              if (!FileModificationService.getInstance()
                  .prepareFileForWrite(targetMethod.getContainingFile())) return;
              if (processSuperMethods) {
                for (PsiMethod superMethod : superMethods) {
                  if (!FileModificationService.getInstance()
                      .prepareFileForWrite(superMethod.getContainingFile())) return;
                }
              }

              try {
                processMethod(project, targetMethod, unhandledExceptions);

                if (processSuperMethods) {
                  for (PsiMethod superMethod : superMethods) {
                    processMethod(project, superMethod, unhandledExceptions);
                  }
                }
              } catch (IncorrectOperationException e) {
                LOG.error(e);
              }
            });
  }
 public Module setTestMethod(final Location<PsiMethod> methodLocation) {
   final PsiMethod method = methodLocation.getPsiElement();
   METHOD_NAME = method.getName();
   TEST_OBJECT = TEST_METHOD;
   return setMainClass(
       methodLocation instanceof MethodLocation
           ? ((MethodLocation) methodLocation).getContainingClass()
           : method.getContainingClass());
 }
Example #26
0
 public MethodReturnTypeFix(
     @NotNull PsiMethod method, @NotNull PsiType returnType, boolean fixWholeHierarchy) {
   super(method);
   myReturnTypePointer =
       SmartTypePointerManager.getInstance(method.getProject()).createSmartTypePointer(returnType);
   myFixWholeHierarchy = fixWholeHierarchy;
   myName = method.getName();
   myCanonicalText = returnType.getCanonicalText();
 }
 public boolean isMethodSignatureExists() {
   PsiClass target = myTargetMethod.getContainingClass();
   LOG.assertTrue(target != null);
   PsiMethod[] methods = target.findMethodsByName(myTargetMethod.getName(), false);
   for (PsiMethod method : methods) {
     if (PsiUtil.isApplicable(method, PsiSubstitutor.EMPTY, myExpressions)) return true;
   }
   return false;
 }
 @Override
 public void visitMethod(@NotNull PsiMethod method) {
   super.visitMethod(method);
   final String name = method.getName();
   if (!PsiKeyword.ASSERT.equals(name)) {
     return;
   }
   registerMethodError(method);
 }
  @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"));
  }
 @Nullable
 private static PsiMethod findNearestMethod(String name, @Nullable PsiClass cls) {
   if (cls == null) return null;
   for (PsiMethod method : cls.getMethods()) {
     if (method.getParameterList().getParametersCount() == 0 && method.getName().equals(name)) {
       return method.getModifierList().hasModifierProperty(PsiModifier.ABSTRACT) ? null : method;
     }
   }
   return findNearestMethod(name, cls.getSuperClass());
 }