@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);
      }
    }
  }
예제 #2
0
 @NotNull
 public static PsiElement[] findSuperElements(@NotNull PsiElement element) {
   if (element instanceof PsiClass) {
     PsiClass aClass = (PsiClass) element;
     List<PsiClass> allSupers = new ArrayList<>(Arrays.asList(aClass.getSupers()));
     for (Iterator<PsiClass> iterator = allSupers.iterator(); iterator.hasNext(); ) {
       PsiClass superClass = iterator.next();
       if (CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName()))
         iterator.remove();
     }
     return allSupers.toArray(new PsiClass[allSupers.size()]);
   }
   if (element instanceof PsiMethod) {
     PsiMethod method = (PsiMethod) element;
     if (method.isConstructor()) {
       PsiMethod constructorInSuper = PsiSuperMethodUtil.findConstructorInSuper(method);
       if (constructorInSuper != null) {
         return new PsiMethod[] {constructorInSuper};
       }
     } else {
       PsiMethod[] superMethods = method.findSuperMethods(false);
       if (superMethods.length == 0) {
         PsiMethod superMethod = getSiblingInheritedViaSubClass(method);
         if (superMethod != null) {
           superMethods = new PsiMethod[] {superMethod};
         }
       }
       return superMethods;
     }
   }
   return PsiElement.EMPTY_ARRAY;
 }
 @Override
 public void visitMethod(@NotNull PsiMethod method) {
   // don't call super, to keep this from drilling in
   if (!method.isConstructor()) {
     return;
   }
   if (!method.hasModifierProperty(PsiModifier.PRIVATE)) {
     return;
   }
   final PsiClass aClass = method.getContainingClass();
   if (aClass == null) {
     return;
   }
   if (!aClass.isEnum()) {
     return;
   }
   final PsiModifierList modifiers = method.getModifierList();
   final PsiElement[] children = modifiers.getChildren();
   for (final PsiElement child : children) {
     final String text = child.getText();
     if (PsiModifier.PRIVATE.equals(text)) {
       registerError(child, child, method);
     }
   }
 }
 @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));
 }
  private static void collectMethods(
      PsiClass currentClass,
      PsiSubstitutor currentClassSubstitutor,
      boolean shouldProcessDeprecated,
      GrTypeDefinition classToDelegateTo,
      Collection<PsiMethod> collector,
      boolean keepParameterAnnotations) {
    final List<PsiMethod> methods;
    if (currentClass instanceof GrTypeDefinition) {
      methods = new ArrayList<PsiMethod>();
      GrClassImplUtil.collectMethodsFromBody((GrTypeDefinition) currentClass, methods);
    } else {
      methods = Arrays.asList(currentClass.getMethods());
    }

    for (PsiMethod method : methods) {
      if (method.isConstructor() || method.hasModifierProperty(PsiModifier.STATIC)) continue;
      if (overridesObjectOrGroovyObject(method)) continue;
      if (!shouldProcessDeprecated
          && PsiImplUtil.getAnnotation(method, CommonClassNames.JAVA_LANG_DEPRECATED) != null)
        continue;
      collector.add(
          generateDelegateMethod(
              method, classToDelegateTo, currentClassSubstitutor, keepParameterAnnotations));
    }
  }
  private static TailType getReturnTail(PsiElement position) {
    PsiElement scope = position;
    while (true) {
      if (scope instanceof PsiFile || scope instanceof PsiClassInitializer) {
        return TailType.NONE;
      }

      if (scope instanceof PsiMethod) {
        final PsiMethod method = (PsiMethod) scope;
        if (method.isConstructor() || PsiType.VOID.equals(method.getReturnType())) {
          return TailType.SEMICOLON;
        }

        return TailType.HUMBLE_SPACE_BEFORE_WORD;
      }
      if (scope instanceof PsiLambdaExpression) {
        final PsiType returnType =
            LambdaUtil.getFunctionalInterfaceReturnType(((PsiLambdaExpression) scope));
        if (PsiType.VOID.equals(returnType)) {
          return TailType.SEMICOLON;
        }
        return TailType.HUMBLE_SPACE_BEFORE_WORD;
      }
      scope = scope.getParent();
    }
  }
예제 #7
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;
 }
 private static boolean canHaveSuperMethod(
     PsiMethod method, boolean checkAccess, boolean allowStaticMethod) {
   if (method.isConstructor()) return false;
   if (!allowStaticMethod && method.hasModifierProperty(PsiModifier.STATIC)) return false;
   if (checkAccess && method.hasModifierProperty(PsiModifier.PRIVATE)) return false;
   PsiClass parentClass = method.getContainingClass();
   return parentClass != null
       && !CommonClassNames.JAVA_LANG_OBJECT.equals(parentClass.getQualifiedName());
 }
  /**
   * Check the element. If the element is a PsiMethod, than we want to know if it's a @Provides
   * method, or a Constructor annotated w/ @Inject.
   *
   * <p>If element is a field, than we only want to see if it is annotated with @Inject.
   *
   * @return a {@link com.intellij.codeInsight.daemon.GutterIconNavigationHandler} for the
   *     appropriate type, or null if we don't care about it.
   */
  @Nullable
  @Override
  public LineMarkerInfo getLineMarkerInfo(@NotNull final PsiElement element) {
    // Check methods first (includes constructors).
    if (element instanceof PsiMethod) {
      PsiMethod methodElement = (PsiMethod) element;

      // @Provides
      if (PsiConsultantImpl.hasAnnotation(element, CLASS_PROVIDES)) {
        PsiTypeElement returnTypeElement = methodElement.getReturnTypeElement();
        if (returnTypeElement != null) {
          return new LineMarkerInfo<PsiElement>(
              element,
              returnTypeElement.getTextRange(),
              ICON,
              UPDATE_ALL,
              null,
              new ProvidesToInjectHandler(),
              LEFT);
        }
      }

      // Constructor injection.
      if (methodElement.isConstructor() && PsiConsultantImpl.hasAnnotation(element, CLASS_INJECT)) {
        PsiIdentifier nameIdentifier = methodElement.getNameIdentifier();
        if (nameIdentifier != null) {
          return new LineMarkerInfo<PsiElement>(
              element,
              nameIdentifier.getTextRange(),
              ICON,
              UPDATE_ALL,
              null,
              new ConstructorInjectToProvidesHandler(),
              LEFT);
        }
      }

      // Not a method, is it a Field?
    } else if (element instanceof PsiField) {
      // Field injection.
      PsiField fieldElement = (PsiField) element;
      PsiTypeElement typeElement = fieldElement.getTypeElement();

      if (PsiConsultantImpl.hasAnnotation(element, CLASS_INJECT) && typeElement != null) {
        return new LineMarkerInfo<PsiElement>(
            element,
            typeElement.getTextRange(),
            ICON,
            UPDATE_ALL,
            null,
            new FieldInjectToProvidesHandler(),
            LEFT);
      }
    }

    return null;
  }
 private int calculateTotalMethodCount(PsiClass aClass) {
   final PsiMethod[] methods = aClass.getMethods();
   int totalCount = 0;
   for (final PsiMethod method : methods) {
     if (!method.isConstructor()) {
       totalCount++;
     }
   }
   return totalCount;
 }
예제 #11
0
 @NotNull
 public static PsiMethod[] getConstructors(@NotNull PsiClass aClass) {
   List<PsiMethod> result = null;
   for (PsiMethod method : aClass.getMethods()) {
     if (method.isConstructor()) {
       if (result == null) result = ContainerUtil.newSmartList();
       result.add(method);
     }
   }
   return result == null ? PsiMethod.EMPTY_ARRAY : result.toArray(new PsiMethod[result.size()]);
 }
  @Override
  protected void initialize() {
    final PsiMethod method = (PsiMethod) getElement();
    LOG.assertTrue(method != null);
    setConstructor(method.isConstructor());
    final PsiType returnType = method.getReturnType();
    setFlag(
        returnType == null
            || PsiType.VOID.equals(returnType)
            || returnType.equalsToText(CommonClassNames.JAVA_LANG_VOID),
        IS_RETURN_VALUE_USED_MASK);

    if (!isReturnValueUsed()) {
      myReturnValueTemplate = RETURN_VALUE_UNDEFINED;
    }

    if (isConstructor()) {
      addReference(getOwnerClass(), getOwnerClass().getElement(), method, false, true, null);
    }

    if (getOwnerClass().isInterface()) {
      setAbstract(false);
    } else {
      setAbstract(method.hasModifierProperty(PsiModifier.ABSTRACT));
    }

    setAppMain(isAppMain(method, this));
    setLibraryOverride(method.hasModifierProperty(PsiModifier.NATIVE));

    initializeSuperMethods(method);
    if (isExternalOverride()) {
      ((RefClassImpl) getOwnerClass()).addLibraryOverrideMethod(this);
    }

    @NonNls final String name = method.getName();
    if (getOwnerClass().isTestCase() && name.startsWith("test")) {
      setTestMethod(true);
    }

    PsiParameter[] paramList = method.getParameterList().getParameters();
    if (paramList.length > 0) {
      myParameters = new RefParameterImpl[paramList.length];
      for (int i = 0; i < paramList.length; i++) {
        PsiParameter parameter = paramList[i];
        myParameters[i] = getRefJavaManager().getParameterReference(parameter, i);
      }
    }

    if (method.hasModifierProperty(PsiModifier.NATIVE)) {
      updateReturnValueTemplate(null);
      updateThrowsList(null);
    }
    collectUncaughtExceptions(method);
  }
예제 #13
0
  @NotNull
  public static PsiMethod[] getConstructors(@NotNull PsiClass aClass) {
    final List<PsiMethod> constructorsList = new SmartList<PsiMethod>();

    final PsiMethod[] methods = aClass.getMethods();
    for (final PsiMethod method : methods) {
      if (method.isConstructor()) constructorsList.add(method);
    }

    return constructorsList.toArray(new PsiMethod[constructorsList.size()]);
  }
  @Nullable
  private static Condition<PsiElement> findMethodUsages(
      final PsiMethod psiMethod, final PsiElement[] allElementsToDelete, List<UsageInfo> usages) {
    final Collection<PsiReference> references = ReferencesSearch.search(psiMethod).findAll();

    if (psiMethod.isConstructor()) {
      return findConstructorUsages(psiMethod, references, usages, allElementsToDelete);
    }
    final PsiMethod[] overridingMethods =
        removeDeletedMethods(
            OverridingMethodsSearch.search(psiMethod).toArray(PsiMethod.EMPTY_ARRAY),
            allElementsToDelete);

    findFunctionalExpressions(usages, ArrayUtil.prepend(psiMethod, overridingMethods));

    final HashMap<PsiMethod, Collection<PsiReference>> methodToReferences = new HashMap<>();
    for (PsiMethod overridingMethod : overridingMethods) {
      final Collection<PsiReference> overridingReferences =
          ReferencesSearch.search(overridingMethod).findAll();
      methodToReferences.put(overridingMethod, overridingReferences);
    }
    final Set<PsiMethod> validOverriding =
        validateOverridingMethods(
            psiMethod,
            references,
            Arrays.asList(overridingMethods),
            methodToReferences,
            usages,
            allElementsToDelete);
    for (PsiReference reference : references) {
      final PsiElement element = reference.getElement();
      if (!isInside(element, allElementsToDelete) && !isInside(element, validOverriding)) {
        usages.add(
            new SafeDeleteReferenceJavaDeleteUsageInfo(
                element,
                psiMethod,
                PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class) != null));
      }
    }

    final List<PsiMethod> calleesSafeToDelete =
        SafeDeleteJavaCalleeChooser.computeCalleesSafeToDelete(psiMethod);
    if (calleesSafeToDelete != null) {
      for (PsiMethod method : calleesSafeToDelete) {
        usages.add(new SafeDeleteMethodCalleeUsageInfo(method, psiMethod));
      }
    }

    return usage -> {
      if (usage instanceof PsiFile) return false;
      return isInside(usage, allElementsToDelete) || isInside(usage, validOverriding);
    };
  }
    private static boolean resolvesToDefaultConstructor(GrCall call) {
      PsiMethod method = call.resolveMethod();
      if (method != null
          && method.isConstructor()
          && method.getParameterList().getParametersCount() == 0) return true;

      if (call instanceof GrConstructorCall) {
        PsiElement resolved =
            PsiImplUtil.extractUniqueResult(((GrConstructorCall) call).multiResolveClass())
                .getElement();
        if (resolved instanceof PsiClass) return true;
      }

      return false;
    }
 private static boolean classHasNoArgConstructor(PsiClass ancestor) {
   boolean hasConstructor = false;
   boolean hasNoArgConstructor = false;
   final PsiMethod[] methods = ancestor.getMethods();
   for (final PsiMethod method : methods) {
     if (method.isConstructor()) {
       hasConstructor = true;
       final PsiParameterList parameterList = method.getParameterList();
       if (parameterList.getParametersCount() == 0
           && (method.hasModifierProperty(PsiModifier.PUBLIC)
               || method.hasModifierProperty(PsiModifier.PROTECTED))) {
         hasNoArgConstructor = true;
       }
     }
   }
   return hasNoArgConstructor || !hasConstructor;
 }
예제 #17
0
  @NotNull
  private Function methodToFunction(@NotNull PsiMethod method, boolean notEmpty) {
    if (isOverrideObjectDirect(method)) {
      dispatcher.setExpressionVisitor(new ExpressionVisitorForDirectObjectInheritors(this));
    } else {
      dispatcher.setExpressionVisitor(new ExpressionVisitor(this));
    }

    methodReturnType = method.getReturnType();

    IdentifierImpl identifier = new IdentifierImpl(method.getName());
    Type returnType =
        typeToType(
            method.getReturnType(), ConverterUtil.isAnnotatedAsNotNull(method.getModifierList()));
    Block body =
        hasFlag(J2KConverterFlags.SKIP_BODIES)
            ? Block.EMPTY_BLOCK
            : blockToBlock(method.getBody(), notEmpty); // #TODO
    Element params = createFunctionParameters(method);
    List<Element> typeParameters = elementsToElementList(method.getTypeParameters());

    Set<String> modifiers = modifiersListToModifiersSet(method.getModifierList());
    if (isOverrideAnyMethodExceptMethodsFromObject(method)) {
      modifiers.add(Modifier.OVERRIDE);
    }
    if (method.getParent() instanceof PsiClass && ((PsiClass) method.getParent()).isInterface()) {
      modifiers.remove(Modifier.ABSTRACT);
    }
    if (isNotOpenMethod(method)) {
      modifiers.add(Modifier.NOT_OPEN);
    }

    if (method.isConstructor()) { // TODO: simplify
      boolean isPrimary = isConstructorPrimary(method);
      return new Constructor(
          identifier,
          modifiers,
          returnType,
          typeParameters,
          params,
          new Block(removeEmpty(body.getStatements()), false),
          isPrimary);
    }
    return new Function(identifier, modifiers, returnType, typeParameters, params, body);
  }
 @Override
 public void visitExpressionStatement(@NotNull PsiExpressionStatement statement) {
   super.visitExpressionStatement(statement);
   final PsiExpression expression = statement.getExpression();
   if (!(expression instanceof PsiMethodCallExpression)) {
     return;
   }
   final PsiMethodCallExpression call = (PsiMethodCallExpression) expression;
   final PsiMethod method = call.resolveMethod();
   if (method == null || method.isConstructor()) {
     return;
   }
   final PsiType returnType = method.getReturnType();
   if (PsiType.VOID.equals(returnType)) {
     return;
   }
   final PsiClass aClass = method.getContainingClass();
   if (aClass == null) {
     return;
   }
   if (PsiUtilCore.hasErrorElementChild(statement)) {
     return;
   }
   if (m_reportAllNonLibraryCalls && !LibraryUtil.classIsInLibrary(aClass)) {
     registerMethodCallError(call, aClass);
     return;
   }
   final PsiReferenceExpression methodExpression = call.getMethodExpression();
   final String methodName = methodExpression.getReferenceName();
   if (methodName == null) {
     return;
   }
   for (int i = 0; i < methodNamePatterns.size(); i++) {
     final String methodNamePattern = methodNamePatterns.get(i);
     if (!methodNamesMatch(methodName, methodNamePattern)) {
       continue;
     }
     final String className = classNames.get(i);
     if (!InheritanceUtil.isInheritor(aClass, className)) {
       continue;
     }
     registerMethodCallError(call, aClass);
     return;
   }
 }
  private void updateRefMethod(
      PsiElement psiResolved,
      RefElement refResolved,
      PsiElement refExpression,
      final PsiElement psiFrom,
      final RefElement refFrom) {
    PsiMethod psiMethod = (PsiMethod) psiResolved;
    RefMethodImpl refMethod = (RefMethodImpl) refResolved;

    PsiMethodCallExpression call =
        PsiTreeUtil.getParentOfType(refExpression, PsiMethodCallExpression.class);
    if (call != null) {
      PsiType returnType = psiMethod.getReturnType();
      if (!psiMethod.isConstructor() && returnType != PsiType.VOID) {
        if (!(call.getParent() instanceof PsiExpressionStatement)) {
          refMethod.setReturnValueUsed(true);
        }

        addTypeReference(psiFrom, returnType, refFrom.getRefManager());
      }

      PsiExpressionList argumentList = call.getArgumentList();
      if (argumentList.getExpressions().length > 0) {
        refMethod.updateParameterValues(argumentList.getExpressions());
      }

      final PsiExpression psiExpression = call.getMethodExpression().getQualifierExpression();
      if (psiExpression != null) {
        final PsiType usedType = psiExpression.getType();
        if (usedType != null) {
          final String fqName = psiMethod.getContainingClass().getQualifiedName();
          if (fqName != null) {
            final PsiClassType methodOwnerType =
                JavaPsiFacade.getInstance(call.getProject())
                    .getElementFactory()
                    .createTypeByFQClassName(
                        fqName, GlobalSearchScope.allScope(psiMethod.getProject()));
            if (!usedType.equals(methodOwnerType)) {
              refMethod.setCalledOnSubClass(true);
            }
          }
        }
      }
    }
  }
 private static void addSuperSignatureElements(
     final PsiClass parent,
     boolean implemented,
     CompletionResultSet result,
     Set<MethodSignature> addedSignatures) {
   for (CandidateInfo candidate :
       OverrideImplementExploreUtil.getMethodsToOverrideImplement(parent, implemented)) {
     PsiMethod baseMethod = (PsiMethod) candidate.getElement();
     PsiClass baseClass = baseMethod.getContainingClass();
     PsiSubstitutor substitutor = candidate.getSubstitutor();
     if (!baseMethod.isConstructor()
         && baseClass != null
         && addedSignatures.add(baseMethod.getSignature(substitutor))) {
       result.addElement(
           createOverridingLookupElement(implemented, baseMethod, baseClass, substitutor));
     }
   }
 }
  @Override
  protected boolean isAvailableImpl(int offset) {
    PsiReferenceExpression ref = myMethodCall.getMethodExpression();
    if (!ref.getText().equals(getSyntheticMethodName())) return false;

    PsiMethod method = PsiTreeUtil.getParentOfType(myMethodCall, PsiMethod.class);
    if (method == null || !method.isConstructor()) return false;
    if (CreateMethodFromUsageFix.hasErrorsInArgumentList(myMethodCall)) return false;
    List<PsiClass> targetClasses = getTargetClasses(myMethodCall);
    if (targetClasses.isEmpty()) return false;

    if (CreateFromUsageUtils.shouldShowTag(offset, ref.getReferenceNameElement(), myMethodCall)) {
      setText(QuickFixBundle.message("create.constructor.text", targetClasses.get(0).getName()));
      return true;
    }

    return false;
  }
예제 #22
0
  public static void addImportDirectiveOrChangeToFqName(
      @NotNull FqName importFqn,
      @NotNull JetFile file,
      int refOffset,
      @NotNull PsiElement targetElement) {
    PsiReference reference = file.findReferenceAt(refOffset);
    if (reference instanceof JetPsiReference) {
      PsiElement target = reference.resolve();
      if (target != null) {
        boolean same = file.getManager().areElementsEquivalent(target, targetElement);

        if (!same) {
          same =
              target instanceof PsiClass
                  && importFqn.getFqName().equals(((PsiClass) target).getQualifiedName());
        }

        if (!same) {
          if (target instanceof PsiMethod) {
            PsiMethod method = (PsiMethod) target;
            same =
                (method.isConstructor()
                    && file.getManager()
                        .areElementsEquivalent(method.getContainingClass(), targetElement));
          }
        }

        if (!same) {
          if (target instanceof JetObjectDeclarationName) {
            same = file.getManager().areElementsEquivalent(target.getParent(), targetElement);
          }
        }

        if (!same) {
          Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
          TextRange refRange = reference.getElement().getTextRange();
          document.replaceString(
              refRange.getStartOffset(), refRange.getEndOffset(), importFqn.getFqName());
        }
        return;
      }
    }
    addImportDirective(new ImportPath(importFqn, false), null, file);
  }
예제 #23
0
  public static boolean inferPurity(@NotNull final PsiMethod method) {
    if (!InferenceFromSourceUtil.shouldInferFromSource(method)
        || PsiType.VOID.equals(method.getReturnType())
        || method.isConstructor()) {
      return false;
    }

    return CachedValuesManager.getCachedValue(
        method,
        () -> {
          MethodData data = ContractInferenceIndexKt.getIndexedData(method);
          PurityInferenceResult result = data == null ? null : data.getPurity();
          Boolean pure =
              RecursionManager.doPreventingRecursion(
                  method,
                  true,
                  () -> result != null && result.isPure(method, data.methodBody(method)));
          return CachedValueProvider.Result.create(pure == Boolean.TRUE, method);
        });
  }
  @Override
  public InspectionGadgetsFix buildFix(Object... infos) {
    final PsiClass aClass = (PsiClass) infos[0];
    final String className = aClass.getName();
    if (infos.length == 1) {
      return new MakePackagePrivateFix(className, true);
    }
    final PsiMember member = (PsiMember) infos[1];
    @NonNls final String memberName;
    if (member instanceof PsiMethod) {
      final PsiMethod method = (PsiMethod) member;
      if (method.isConstructor()) {}

      memberName = member.getName() + "()";
    } else {
      memberName = member.getName();
    }
    @NonNls final String elementName = className + '.' + memberName;
    return new MakePackagePrivateFix(elementName, false);
  }
  @Override
  public void getNamedArguments(
      @NotNull GrCall call,
      @Nullable PsiElement resolve,
      @Nullable String argumentName,
      boolean forCompletion,
      Map<String, ArgumentDescriptor> result) {
    if (!(call instanceof GrNewExpression)) return;

    if (resolve != null) {
      if (!(resolve instanceof PsiMethod)) return;
      PsiMethod method = (PsiMethod) resolve;
      if (!method.isConstructor()) return;
    }

    GrNewExpression newCall = (GrNewExpression) call;

    GrArgumentList argumentList = newCall.getArgumentList();
    if (argumentList == null) return;

    GrExpression[] expressionArguments = argumentList.getExpressionArguments();
    if (expressionArguments.length > 1
        || (expressionArguments.length == 1
            && !(expressionArguments[0] instanceof GrReferenceExpression))) {
      return;
    }

    for (GroovyResolveResult resolveResult : newCall.multiResolveClass()) {
      PsiElement element = resolveResult.getElement();
      if (!(element instanceof PsiClass)) continue;

      PsiClass aClass = (PsiClass) element;

      if (!isClassHasConstructorWithMap(aClass)) continue;

      PsiClassType classType =
          JavaPsiFacade.getElementFactory(aClass.getProject()).createType(aClass);

      processClass(call, classType, argumentName, result);
    }
  }
  private static boolean isSuperMethod(
      PsiClass aClass,
      HierarchicalMethodSignature hierarchicalMethodSignature,
      HierarchicalMethodSignature superSignatureHierarchical) {
    PsiMethod superMethod = superSignatureHierarchical.getMethod();
    PsiClass superClass = superMethod.getContainingClass();
    PsiClass containingClass = hierarchicalMethodSignature.getMethod().getContainingClass();
    if (!superMethod.isConstructor()) {
      if (!aClass.equals(superClass)) {
        if (PsiUtil.isAccessible(aClass.getProject(), superMethod, aClass, aClass)) {
          if (MethodSignatureUtil.isSubsignature(
              superSignatureHierarchical, hierarchicalMethodSignature)) {
            if (superClass != null) {
              if (superClass.isInterface()
                  || CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName())) {
                if (superMethod.hasModifierProperty(PsiModifier.DEFAULT)
                    || hierarchicalMethodSignature
                        .getMethod()
                        .hasModifierProperty(PsiModifier.DEFAULT)) {
                  return !InheritanceUtil.isInheritorOrSelf(superClass, containingClass, true);
                }
                return true;
              }

              if (containingClass != null) {
                if (containingClass.isInterface()) {
                  return false;
                }

                if (!aClass.isInterface()
                    && !InheritanceUtil.isInheritorOrSelf(superClass, containingClass, true)) {
                  return true;
                }
              }
            }
          }
        }
      }
    }
    return false;
  }
  @Override
  public boolean execute(@NotNull PsiElement element, @NotNull ResolveState state) {
    if (myStopExecuting) {
      return false;
    }
    if (element instanceof PsiMethod) {
      PsiMethod method = (PsiMethod) element;

      if (method.isConstructor() != myIsConstructor) return true;

      PsiSubstitutor substitutor = inferSubstitutor(method, state);

      PsiElement resolveContext = state.get(RESOLVE_CONTEXT);
      final SpreadState spreadState = state.get(SpreadState.SPREAD_STATE);

      boolean isAccessible = isAccessible(method);
      boolean isStaticsOK = isStaticsOK(method, resolveContext, false);
      boolean isApplicable =
          PsiUtil.isApplicable(myArgumentTypes, method, substitutor, myPlace, myByShape);
      boolean isValidResult = isStaticsOK && isAccessible && isApplicable;

      GroovyResolveResultImpl candidate =
          new GroovyResolveResultImpl(
              method,
              resolveContext,
              spreadState,
              substitutor,
              isAccessible,
              isStaticsOK,
              false,
              isValidResult);

      if (!myAllVariants && isValidResult) {
        addCandidate(candidate);
      } else {
        addInapplicableCandidate(candidate);
      }
    }

    return true;
  }
  /**
   * Adds 'method' to 'signatures' if it doesn't yet contain any method with the same signature or
   * replaces abstract methods
   */
  private static void addMethodChecked(
      Map<MethodSignature, PsiMethod> signatures,
      PsiMethod method,
      PsiSubstitutor substitutor,
      @Nullable Set<PsiMethod> resultSet) {
    if (method.isConstructor()) return;
    if (method.hasModifierProperty(PsiModifier.STATIC)) return;

    final MethodSignature signature = method.getSignature(substitutor);
    final PsiMethod old = signatures.get(signature);

    if (old != null) {
      // if (method.hasModifierProperty(PsiModifier.ABSTRACT)) return;
      if (!old.hasModifierProperty(PsiModifier.ABSTRACT)) return;

      if (resultSet != null) resultSet.remove(old);
    }

    signatures.put(signature, method);
    if (resultSet != null) resultSet.add(method);
  }
 @Override
 public void visitMethod(@NotNull PsiMethod method) {
   super.visitMethod(method);
   if (method.isConstructor() || method.hasModifierProperty(PsiModifier.STATIC)) {
     return;
   }
   if (method.hasModifierProperty(PsiModifier.NATIVE)
       && isInspectionEnabled("NativeMethodNamingConvention", method)) {
     return;
   }
   final PsiIdentifier nameIdentifier = method.getNameIdentifier();
   if (nameIdentifier == null) {
     return;
   }
   if (TestUtils.isRunnable(method)) {
     if (TestUtils.isJUnit4TestMethod(method)
         && isInspectionEnabled("JUnit4MethodNamingConvention", method)) {
       return;
     }
     if (TestUtils.isJUnit3TestMethod(method)
         && isInspectionEnabled("JUnit3MethodNamingConvention", method)) {
       return;
     }
   }
   if (isTestNGTestMethod(method)
       && isInspectionEnabled("TestNGMethodNamingConvention", method)) {
     return;
   }
   final String name = method.getName();
   if (isValid(name)) {
     return;
   }
   if (!isOnTheFly() && MethodUtils.hasSuper(method)) {
     return;
   }
   if (LibraryUtil.isOverrideOfLibraryMethod(method)) {
     return;
   }
   registerMethodError(method, name);
 }
예제 #30
0
  @SuppressWarnings({"HardCodedStringLiteral"})
  public static boolean hasGetterName(final PsiMethod method) {
    if (method == null) return false;

    if (method.isConstructor()) return false;

    String methodName = method.getName();
    PsiType returnType = method.getReturnType();
    if (methodName.startsWith("get") && methodName.length() > "get".length()) {
      if (Character.isLowerCase(methodName.charAt("get".length()))
          && (methodName.length() == "get".length() + 1
              || Character.isLowerCase(methodName.charAt("get".length() + 1)))) {
        return false;
      }
      if (returnType != null && PsiType.VOID.equals(returnType)) return false;
    } else if (methodName.startsWith("is")) {
      return isBoolean(returnType);
    } else {
      return false;
    }
    return true;
  }