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 void reportNullableReturns(
      DataFlowInstructionVisitor visitor,
      ProblemsHolder holder,
      Set<PsiElement> reportedAnchors,
      @NotNull PsiElement block) {
    final PsiMethod method = getScopeMethod(block);
    if (method == null || NullableStuffInspectionBase.isNullableNotInferred(method, true)) return;

    boolean notNullRequired = NullableNotNullManager.isNotNull(method);
    if (!notNullRequired && !SUGGEST_NULLABLE_ANNOTATIONS) return;

    PsiType returnType = method.getReturnType();
    // no warnings in void lambdas, where the expression is not returned anyway
    if (block instanceof PsiExpression
        && block.getParent() instanceof PsiLambdaExpression
        && returnType == PsiType.VOID) return;

    // no warnings for Void methods, where only null can be possibly returned
    if (returnType == null || returnType.equalsToText(CommonClassNames.JAVA_LANG_VOID)) return;

    for (PsiElement statement : visitor.getProblems(NullabilityProblem.nullableReturn)) {
      assert statement instanceof PsiExpression;
      final PsiExpression expr = (PsiExpression) statement;
      if (!reportedAnchors.add(expr)) continue;

      if (notNullRequired) {
        final String text =
            isNullLiteralExpression(expr)
                ? InspectionsBundle.message("dataflow.message.return.null.from.notnull")
                : InspectionsBundle.message("dataflow.message.return.nullable.from.notnull");
        holder.registerProblem(expr, text);
      } else if (AnnotationUtil.isAnnotatingApplicable(statement)) {
        final NullableNotNullManager manager =
            NullableNotNullManager.getInstance(expr.getProject());
        final String defaultNullable = manager.getDefaultNullable();
        final String presentableNullable = StringUtil.getShortName(defaultNullable);
        final String text =
            isNullLiteralExpression(expr)
                ? InspectionsBundle.message(
                    "dataflow.message.return.null.from.notnullable", presentableNullable)
                : InspectionsBundle.message(
                    "dataflow.message.return.nullable.from.notnullable", presentableNullable);
        final LocalQuickFix[] fixes =
            PsiTreeUtil.getParentOfType(expr, PsiMethod.class, PsiLambdaExpression.class)
                    instanceof PsiLambdaExpression
                ? LocalQuickFix.EMPTY_ARRAY
                : new LocalQuickFix[] {
                  new AnnotateMethodFix(
                      defaultNullable, ArrayUtil.toStringArray(manager.getNotNulls())) {
                    @Override
                    public int shouldAnnotateBaseMethod(
                        PsiMethod method, PsiMethod superMethod, Project project) {
                      return 1;
                    }
                  }
                };
        holder.registerProblem(expr, text, fixes);
      }
    }
  }
    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();
    }
Пример #4
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();
  }
 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 static void checkMethodCall(RefElement refWhat, final PsiElement element) {
    if (!(refWhat instanceof RefMethod)) return;
    final RefMethod refMethod = (RefMethod) refWhat;
    final PsiElement psiElement = refMethod.getElement();
    if (!(psiElement instanceof PsiMethod)) return;
    final PsiMethod psiMethod = (PsiMethod) psiElement;
    if (!PsiType.BOOLEAN.equals(psiMethod.getReturnType())) return;
    element.accept(
        new JavaRecursiveElementWalkingVisitor() {
          @Override
          public void visitMethodCallExpression(PsiMethodCallExpression call) {
            super.visitMethodCallExpression(call);
            final PsiReferenceExpression methodExpression = call.getMethodExpression();
            if (methodExpression.isReferenceTo(psiMethod)) {
              if (isInvertedMethodCall(methodExpression)) return;
              refMethod.putUserData(ALWAYS_INVERTED, Boolean.FALSE);
            }
          }

          @Override
          public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) {
            super.visitMethodReferenceExpression(expression);
            if (expression.isReferenceTo(psiElement)) {
              refMethod.putUserData(ALWAYS_INVERTED, Boolean.FALSE);
            }
          }
        });
  }
  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();
    }
  }
Пример #8
0
  @Override
  public boolean isAvailable(
      @NotNull Project project,
      @NotNull PsiFile file,
      @NotNull PsiElement startElement,
      @NotNull PsiElement endElement) {
    final PsiMethod myMethod = (PsiMethod) startElement;

    PsiType myReturnType = myReturnTypePointer.getType();
    return myMethod.isValid()
        && myMethod.getManager().isInProject(myMethod)
        && myReturnType != null
        && myReturnType.isValid()
        && !TypeConversionUtil.isNullType(myReturnType)
        && myMethod.getReturnType() != null
        && !Comparing.equal(myReturnType, myMethod.getReturnType());
  }
Пример #9
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);
  }
Пример #10
0
 /**
  * get initView method
  *
  * @return
  */
 private PsiMethod getInitView() {
   PsiMethod[] methods = mClass.findMethodsByName("initView", true);
   for (PsiMethod method : methods) {
     if (method.getReturnType().equals(PsiType.VOID)) {
       return method;
     }
   }
   return null;
 }
Пример #11
0
 /** "xxx", "void setMyProperty(String pp)" -> "setXxx" */
 @Nullable
 public static String suggestPropertyAccessor(String name, PsiMethod accessorTemplate) {
   if (isSimplePropertyGetter(accessorTemplate)) {
     PsiType type = accessorTemplate.getReturnType();
     return suggestGetterName(name, type, accessorTemplate.getName());
   }
   if (isSimplePropertySetter(accessorTemplate)) {
     return suggestSetterName(name);
   }
   return null;
 }
  @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);
  }
    private static boolean containsError(PsiAnnotation annotation) {
      final PsiJavaCodeReferenceElement nameRef = annotation.getNameReferenceElement();
      if (nameRef == null) {
        return true;
      }
      final PsiClass aClass = (PsiClass) nameRef.resolve();
      if (aClass == null || !aClass.isAnnotationType()) {
        return true;
      }
      final Set<String> names = new HashSet<String>();
      final PsiAnnotationParameterList annotationParameterList = annotation.getParameterList();
      if (PsiUtilCore.hasErrorElementChild(annotationParameterList)) {
        return true;
      }
      final PsiNameValuePair[] attributes = annotationParameterList.getAttributes();
      for (PsiNameValuePair attribute : attributes) {
        final PsiReference reference = attribute.getReference();
        if (reference == null) {
          return true;
        }
        final PsiMethod method = (PsiMethod) reference.resolve();
        if (method == null) {
          return true;
        }
        final PsiAnnotationMemberValue value = attribute.getValue();
        if (value == null || PsiUtilCore.hasErrorElementChild(value)) {
          return true;
        }
        if (value instanceof PsiAnnotation && containsError((PsiAnnotation) value)) {
          return true;
        }
        if (!hasCorrectType(value, method.getReturnType())) {
          return true;
        }
        final String name = attribute.getName();
        if (!names.add(name != null ? name : PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)) {
          return true;
        }
      }

      for (PsiMethod method : aClass.getMethods()) {
        if (!(method instanceof PsiAnnotationMethod)) {
          continue;
        }
        final PsiAnnotationMethod annotationMethod = (PsiAnnotationMethod) method;
        if (annotationMethod.getDefaultValue() == null
            && !names.contains(annotationMethod.getName())) {
          return true; // missing a required argument
        }
      }
      return false;
    }
Пример #14
0
  @Override
  public void invoke(
      @NotNull Project project,
      @NotNull PsiFile file,
      Editor editor,
      @NotNull PsiElement startElement,
      @NotNull PsiElement endElement) {
    final PsiMethod myMethod = (PsiMethod) startElement;

    if (!FileModificationService.getInstance().prepareFileForWrite(myMethod.getContainingFile()))
      return;
    final PsiType myReturnType = myReturnTypePointer.getType();
    if (myReturnType == null) return;
    if (myFixWholeHierarchy) {
      final PsiMethod superMethod = myMethod.findDeepestSuperMethod();
      final PsiType superReturnType = superMethod == null ? null : superMethod.getReturnType();
      if (superReturnType != null
          && !Comparing.equal(myReturnType, superReturnType)
          && !changeClassTypeArgument(
              myMethod,
              project,
              superReturnType,
              superMethod.getContainingClass(),
              editor,
              myReturnType)) {
        return;
      }
    }

    final List<PsiMethod> affectedMethods = changeReturnType(myMethod, myReturnType);

    PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
    PsiReturnStatement statementToSelect = null;
    if (!PsiType.VOID.equals(myReturnType)) {
      final ReturnStatementAdder adder = new ReturnStatementAdder(factory, myReturnType);

      for (PsiMethod affectedMethod : affectedMethods) {
        PsiReturnStatement statement = adder.addReturnForMethod(file, affectedMethod);
        if (statement != null && affectedMethod == myMethod) {
          statementToSelect = statement;
        }
      }
    }

    if (statementToSelect != null) {
      Editor editorForMethod =
          getEditorForMethod(myMethod, project, editor, statementToSelect.getContainingFile());
      if (editorForMethod != null) {
        selectReturnValueInEditor(statementToSelect, editorForMethod);
      }
    }
  }
Пример #15
0
 public static @Nullable PsiType resolveMethod(
     @Nullable PsiType type, String methodName, @NotNull PsiType... argTypes) {
   if (!(type instanceof PsiClassType) || methodName == null) return null;
   for (PsiType a : argTypes) if (a == null) return null;
   PsiClassType clas = (PsiClassType) type;
   PsiSubstitutor subst = clas.resolveGenerics().getSubstitutor();
   PsiClass psiClass = clas.resolve();
   if (psiClass == null) return null;
   LightMethodBuilder method =
       new LightMethodBuilder(psiClass.getManager(), JavaLanguage.INSTANCE, methodName);
   for (PsiType a : argTypes) method.addParameter("_", a);
   PsiMethod m = psiClass.findMethodBySignature(method, true);
   return m == null ? null : subst.substitute(m.getReturnType());
 }
Пример #16
0
 @Nullable
 public static PsiMethod findPropertyGetterWithType(
     String propertyName, boolean isStatic, PsiType type, Iterator<PsiMethod> methods) {
   while (methods.hasNext()) {
     PsiMethod method = methods.next();
     if (method.hasModifierProperty(PsiModifier.STATIC) != isStatic) continue;
     if (isSimplePropertyGetter(method)) {
       if (getPropertyNameByGetter(method).equals(propertyName)) {
         if (type.equals(method.getReturnType())) return method;
       }
     }
   }
   return null;
 }
Пример #17
0
 @Nullable
 public static PsiType getPropertyType(final PsiMember member) {
   if (member instanceof PsiField) {
     return ((PsiField) member).getType();
   } else if (member instanceof PsiMethod) {
     final PsiMethod psiMethod = (PsiMethod) member;
     if (isSimplePropertyGetter(psiMethod)) {
       return psiMethod.getReturnType();
     } else if (isSimplePropertySetter(psiMethod)) {
       return psiMethod.getParameterList().getParameters()[0].getType();
     }
   }
   return null;
 }
  /**
   * Creates a new {@link MethodElement} object.
   *
   * @param method the PSI method object.
   * @return a new {@link MethodElement} object.
   * @since 2.15
   */
  public static MethodElement newMethodElement(PsiMethod method) {
    MethodElement me = new MethodElement();
    PsiType type = method.getReturnType();
    PsiModifierList modifiers = method.getModifierList();

    // if something is wrong:
    // http://www.intellij.net/forums/thread.jsp?nav=false&forum=18&thread=88676&start=0&msRange=15
    if (type == null) {
      log.warn(
          "This method does not have a valid return type: "
              + method.getName()
              + ", returnType="
              + type);
      return me;
    }
    PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory();
    setElementInfo(me, factory, type, modifiers);

    // names
    String fieldName = PsiAdapter.getGetterFieldName(method);
    me.setName(fieldName == null ? method.getName() : fieldName);
    me.setFieldName(fieldName);
    me.setMethodName(method.getName());

    // getter
    me.setGetter(PsiAdapter.isGetterMethod(method));

    // misc
    me.setDeprecated(method.isDeprecated());
    me.setReturnTypeVoid(PsiAdapter.isTypeOfVoid(method.getReturnType()));

    // modifiers
    if (modifiers.hasModifierProperty(PsiModifier.ABSTRACT)) me.setModifierAbstract(true);
    if (modifiers.hasModifierProperty(PsiModifier.SYNCHRONIZED)) me.setModifierSynchronized(true);

    return me;
  }
 private static boolean cyclicDependencies(
     PsiClass aClass, PsiType type, @NotNull Set<PsiClass> checked, @NotNull PsiManager manager) {
   final PsiClass resolvedClass = PsiUtil.resolveClassInType(type);
   if (resolvedClass != null && resolvedClass.isAnnotationType()) {
     if (aClass == resolvedClass) {
       return true;
     }
     if (!checked.add(resolvedClass) || !manager.isInProject(resolvedClass)) return false;
     final PsiMethod[] methods = resolvedClass.getMethods();
     for (PsiMethod method : methods) {
       if (cyclicDependencies(aClass, method.getReturnType(), checked, manager)) return true;
     }
   }
   return false;
 }
  private static boolean isAppMain(PsiMethod psiMethod, RefMethod refMethod) {
    if (!refMethod.isStatic()) return false;
    if (!PsiType.VOID.equals(psiMethod.getReturnType())) return false;

    PsiMethod appMainPattern = ((RefMethodImpl) refMethod).getRefJavaManager().getAppMainPattern();
    if (MethodSignatureUtil.areSignaturesEqual(psiMethod, appMainPattern)) return true;

    PsiMethod appPremainPattern =
        ((RefMethodImpl) refMethod).getRefJavaManager().getAppPremainPattern();
    if (MethodSignatureUtil.areSignaturesEqual(psiMethod, appPremainPattern)) return true;

    PsiMethod appAgentmainPattern =
        ((RefMethodImpl) refMethod).getRefJavaManager().getAppAgentmainPattern();
    return MethodSignatureUtil.areSignaturesEqual(psiMethod, appAgentmainPattern);
  }
Пример #21
0
  @Nullable
  private PsiMethod[] getChangeRoots(final PsiMethod method, @NotNull PsiType returnType) {
    if (!myFixWholeHierarchy) return new PsiMethod[] {method};

    final PsiMethod[] methods = method.findDeepestSuperMethods();

    if (methods.length > 0) {
      for (PsiMethod psiMethod : methods) {
        if (returnType.equals(psiMethod.getReturnType())) {
          return new PsiMethod[] {method};
        }
      }
      return methods;
    }
    // no - only base
    return new PsiMethod[] {method};
  }
  // returns contained element
  private static PsiClass contained(PsiClass annotationType) {
    if (!annotationType.isAnnotationType()) return null;
    PsiMethod[] values = annotationType.findMethodsByName("value", false);
    if (values.length != 1) return null;
    PsiMethod value = values[0];
    PsiType returnType = value.getReturnType();
    if (!(returnType instanceof PsiArrayType)) return null;
    PsiType type = ((PsiArrayType) returnType).getComponentType();
    if (!(type instanceof PsiClassType)) return null;
    PsiClass contained = ((PsiClassType) type).resolve();
    if (contained == null || !contained.isAnnotationType()) return null;
    if (PsiImplUtil.findAnnotation(
            contained.getModifierList(), CommonClassNames.JAVA_LANG_ANNOTATION_REPEATABLE)
        == null) return null;

    return contained;
  }
  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);
            }
          }
        }
      }
    }
  }
 @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;
   }
 }
Пример #25
0
 public static boolean isJUnitTestMethod(PsiMethod method) {
   //noinspection HardCodedStringLiteral
   if (AnnotationUtil.isAnnotated(method, "org.junit.Test", true)) {
     return true;
   }
   final PsiType returnType = method.getReturnType();
   if (!PsiType.VOID.equals(returnType)) {
     return false;
   }
   if (!method.hasModifierProperty(PsiModifier.PUBLIC)) {
     return false;
   }
   @NonNls final String methodName = method.getName();
   if (!methodName.startsWith("test")) {
     return false;
   }
   final PsiClass containingClass = method.getContainingClass();
   return containingClass != null && isJUnitTestCase(containingClass);
 }
  public static boolean isMainOrPremainMethod(@NotNull PsiMethod method) {
    if (!PsiType.VOID.equals(method.getReturnType())) return false;
    String name = method.getName();
    if (!("main".equals(name) || "premain".equals(name))) return false;

    PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory();
    MethodSignature signature = method.getSignature(PsiSubstitutor.EMPTY);
    try {
      MethodSignature main = createSignatureFromText(factory, "void main(String[] args);");
      if (MethodSignatureUtil.areSignaturesEqual(signature, main)) return true;
      MethodSignature premain =
          createSignatureFromText(
              factory, "void premain(String args, java.lang.instrument.Instrumentation i);");
      if (MethodSignatureUtil.areSignaturesEqual(signature, premain)) return true;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }

    return false;
  }
Пример #27
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);
        });
  }
Пример #28
0
 @Nullable
 public static PsiField findPropertyFieldByMember(final PsiMember psiMember) {
   if (psiMember instanceof PsiField) {
     return (PsiField) psiMember;
   } else if (psiMember instanceof PsiMethod) {
     final PsiMethod psiMethod = (PsiMethod) psiMember;
     final PsiType returnType = psiMethod.getReturnType();
     if (returnType == null) return null;
     final PsiCodeBlock body = psiMethod.getBody();
     final PsiStatement[] statements = body == null ? null : body.getStatements();
     final PsiStatement statement =
         statements == null || statements.length != 1 ? null : statements[0];
     final PsiElement target;
     if (PsiType.VOID.equals(returnType)) {
       final PsiExpression expression =
           statement instanceof PsiExpressionStatement
               ? ((PsiExpressionStatement) statement).getExpression()
               : null;
       target =
           expression instanceof PsiAssignmentExpression
               ? ((PsiAssignmentExpression) expression).getLExpression()
               : null;
     } else {
       target =
           statement instanceof PsiReturnStatement
               ? ((PsiReturnStatement) statement).getReturnValue()
               : null;
     }
     final PsiElement resolved =
         target instanceof PsiReferenceExpression
             ? ((PsiReferenceExpression) target).resolve()
             : null;
     if (resolved instanceof PsiField) {
       final PsiField field = (PsiField) resolved;
       if (psiMember.getContainingClass() == field.getContainingClass()
           || psiMember.getContainingClass().isInheritor(field.getContainingClass(), true))
         return field;
     }
   }
   return null;
 }
 private boolean hasOnlyMain(PsiClass aClass) {
   final PsiMethod[] methods = aClass.getMethods();
   if (methods.length == 0) {
     return false;
   }
   for (PsiMethod method : methods) {
     if (method.isConstructor()) {
       continue;
     }
     if (!method.hasModifierProperty(PsiModifier.STATIC)) {
       return false;
     }
     if (method.hasModifierProperty(PsiModifier.PRIVATE)) {
       continue;
     }
     if (!method.hasModifierProperty(PsiModifier.PUBLIC)) {
       return false;
     }
     final String name = method.getName();
     if (!name.equals(HardcodedMethodConstants.MAIN)) {
       return false;
     }
     final PsiType returnType = method.getReturnType();
     if (!PsiType.VOID.equals(returnType)) {
       return false;
     }
     final PsiParameterList parameterList = method.getParameterList();
     if (parameterList.getParametersCount() != 1) {
       return false;
     }
     final PsiParameter[] parameters = parameterList.getParameters();
     final PsiParameter parameter = parameters[0];
     final PsiType type = parameter.getType();
     if (!type.equalsToText("java.lang.String[]")) {
       return false;
     }
   }
   return true;
 }
Пример #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;
  }