コード例 #1
0
  private static boolean isCollectCall(PsiStatement body, final PsiParameter parameter) {
    PsiIfStatement ifStatement = extractIfStatement(body);
    final PsiMethodCallExpression methodCallExpression = extractAddCall(body, ifStatement);
    if (methodCallExpression != null) {
      final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
      final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
      PsiClass qualifierClass = null;
      if (qualifierExpression instanceof PsiReferenceExpression) {
        if (ReferencesSearch.search(parameter, new LocalSearchScope(qualifierExpression))
                .findFirst()
            != null) {
          return false;
        }
        final PsiElement resolve = ((PsiReferenceExpression) qualifierExpression).resolve();
        if (resolve instanceof PsiVariable) {
          if (ReferencesSearch.search(
                      resolve, new LocalSearchScope(methodCallExpression.getArgumentList()))
                  .findFirst()
              != null) {
            return false;
          }
        }
        qualifierClass = PsiUtil.resolveClassInType(qualifierExpression.getType());
      } else if (qualifierExpression == null) {
        final PsiClass enclosingClass = PsiTreeUtil.getParentOfType(body, PsiClass.class);
        if (PsiUtil.getEnclosingStaticElement(body, enclosingClass) == null) {
          qualifierClass = enclosingClass;
        }
      }

      if (qualifierClass != null
          && InheritanceUtil.isInheritor(
              qualifierClass, false, CommonClassNames.JAVA_UTIL_COLLECTION)) {

        while (ifStatement != null && PsiTreeUtil.isAncestor(body, ifStatement, false)) {
          final PsiExpression condition = ifStatement.getCondition();
          if (condition != null
              && isConditionDependsOnUpdatedCollections(condition, qualifierExpression))
            return false;
          ifStatement = PsiTreeUtil.getParentOfType(ifStatement, PsiIfStatement.class);
        }

        final PsiElement resolve = methodExpression.resolve();
        if (resolve instanceof PsiMethod
            && "add".equals(((PsiMethod) resolve).getName())
            && ((PsiMethod) resolve).getParameterList().getParametersCount() == 1) {
          final PsiExpression[] args = methodCallExpression.getArgumentList().getExpressions();
          if (args.length == 1) {
            if (args[0] instanceof PsiCallExpression) {
              final PsiMethod method = ((PsiCallExpression) args[0]).resolveMethod();
              return method != null && !method.hasTypeParameters() && !isThrowsCompatible(method);
            }
            return true;
          }
        }
      }
    }
    return false;
  }
コード例 #2
0
  @Override
  public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element)
      throws IncorrectOperationException {
    try {
      if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return;

      final PsiJavaToken token = (PsiJavaToken) element;
      final PsiPolyadicExpression expression =
          SplitConditionUtil.findCondition(element, true, false);

      final PsiLambdaExpression lambdaExpression =
          PsiTreeUtil.getParentOfType(expression, PsiLambdaExpression.class);
      LOG.assertTrue(lambdaExpression != null);
      final String lambdaParameterName =
          lambdaExpression.getParameterList().getParameters()[0].getName();

      final PsiMethodCallExpression methodCallExpression =
          PsiTreeUtil.getParentOfType(expression, PsiMethodCallExpression.class);
      LOG.assertTrue(methodCallExpression != null, expression);

      PsiExpression lOperand = getLOperands(expression, token);
      PsiExpression rOperand = getROperands(expression, token);

      final Collection<PsiComment> comments =
          PsiTreeUtil.findChildrenOfType(expression, PsiComment.class);

      final PsiMethodCallExpression chainedCall =
          (PsiMethodCallExpression)
              JavaPsiFacade.getElementFactory(project)
                  .createExpressionFromText(
                      "a.filter(" + lambdaParameterName + " -> x)", expression);
      final PsiExpression argExpression = chainedCall.getArgumentList().getExpressions()[0];
      final PsiElement rReplaced =
          ((PsiLambdaExpression) argExpression).getBody().replace(rOperand);

      final PsiExpression compoundArg = methodCallExpression.getArgumentList().getExpressions()[0];

      final int separatorOffset = token.getTextOffset();
      for (PsiComment comment : comments) {
        if (comment.getTextOffset() < separatorOffset) {
          compoundArg.getParent().add(comment);
        } else {
          rReplaced.getParent().add(comment);
        }
      }

      ((PsiLambdaExpression) compoundArg).getBody().replace(lOperand);

      chainedCall.getMethodExpression().getQualifierExpression().replace(methodCallExpression);
      methodCallExpression.replace(chainedCall);
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
コード例 #3
0
 private static boolean methodCallExpressionsAreEquivalent(
     @NotNull PsiMethodCallExpression methodExp1, @NotNull PsiMethodCallExpression methodExp2) {
   final PsiReferenceExpression methodExpression1 = methodExp1.getMethodExpression();
   final PsiReferenceExpression methodExpression2 = methodExp2.getMethodExpression();
   if (!expressionsAreEquivalent(methodExpression1, methodExpression2)) {
     return false;
   }
   final PsiExpressionList argumentList1 = methodExp1.getArgumentList();
   final PsiExpression[] args1 = argumentList1.getExpressions();
   final PsiExpressionList argumentList2 = methodExp2.getArgumentList();
   final PsiExpression[] args2 = argumentList2.getExpressions();
   return expressionListsAreEquivalent(args1, args2);
 }
コード例 #4
0
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      try {
        PsiBinaryExpression binaryExpression = (PsiBinaryExpression) descriptor.getPsiElement();
        IElementType opSign = binaryExpression.getOperationSign().getTokenType();
        PsiExpression lExpr = binaryExpression.getLOperand();
        PsiExpression rExpr = binaryExpression.getROperand();
        if (rExpr == null) return;

        PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
        PsiMethodCallExpression equalsCall =
            (PsiMethodCallExpression) factory.createExpressionFromText("a.equals(b)", null);

        equalsCall.getMethodExpression().getQualifierExpression().replace(lExpr);
        equalsCall.getArgumentList().getExpressions()[0].replace(rExpr);

        PsiExpression result = (PsiExpression) binaryExpression.replace(equalsCall);

        if (opSign == JavaTokenType.NE) {
          PsiPrefixExpression negation =
              (PsiPrefixExpression) factory.createExpressionFromText("!a", null);
          negation.getOperand().replace(result);
          result.replace(negation);
        }
      } catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }
 static String createContainsExpressionText(
     @NotNull PsiMethodCallExpression call, @NotNull PsiJavaToken sign, boolean flipped) {
   final IElementType tokenType = sign.getTokenType();
   final PsiReferenceExpression methodExpression = call.getMethodExpression();
   final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
   final String qualifierText;
   if (qualifierExpression == null) {
     qualifierText = "";
   } else {
     qualifierText = qualifierExpression.getText();
   }
   final PsiExpressionList argumentList = call.getArgumentList();
   final PsiExpression expression = argumentList.getExpressions()[0];
   @NonNls
   final String newExpressionText = qualifierText + ".contains(" + expression.getText() + ')';
   if (tokenType.equals(JavaTokenType.EQEQ)) {
     return '!' + newExpressionText;
   } else if (!flipped
       && (tokenType.equals(JavaTokenType.LT) || tokenType.equals(JavaTokenType.LE))) {
     return '!' + newExpressionText;
   } else if (flipped
       && (tokenType.equals(JavaTokenType.GT) || tokenType.equals(JavaTokenType.GE))) {
     return '!' + newExpressionText;
   }
   return newExpressionText;
 }
コード例 #6
0
 @Override
 public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) {
   super.visitMethodCallExpression(expression);
   final PsiExpressionList argumentList = expression.getArgumentList();
   final PsiExpression[] arguments = argumentList.getExpressions();
   if (arguments.length == 0) {
     return;
   }
   final PsiExpression xpathArgument = arguments[0];
   if (!ExpressionUtils.hasStringType(xpathArgument)) {
     return;
   }
   if (!PsiUtil.isConstantExpression(xpathArgument)) {
     return;
   }
   final PsiType type = xpathArgument.getType();
   if (type == null) {
     return;
   }
   final String value = (String) ConstantExpressionUtil.computeCastTo(xpathArgument, type);
   if (value == null) {
     return;
   }
   if (!callTakesXPathExpression(expression)) {
     return;
   }
   final XPathFactory xpathFactory = XPathFactory.newInstance();
   final XPath xpath = xpathFactory.newXPath();
   //noinspection UnusedCatchParameter,ProhibitedExceptionCaught
   try {
     xpath.compile(value);
   } catch (XPathExpressionException ignore) {
     registerError(xpathArgument);
   }
 }
 private static boolean isIndexOfCall(@NotNull PsiMethodCallExpression expression) {
   final PsiReferenceExpression methodExpression = expression.getMethodExpression();
   final String methodName = methodExpression.getReferenceName();
   if (!HardcodedMethodConstants.INDEX_OF.equals(methodName)) {
     return false;
   }
   final PsiExpressionList argumentList = expression.getArgumentList();
   final PsiExpression[] arguments = argumentList.getExpressions();
   if (arguments.length != 1) {
     return false;
   }
   final PsiExpression qualifier = methodExpression.getQualifierExpression();
   if (qualifier == null) {
     return false;
   }
   final PsiType qualifierType = qualifier.getType();
   if (qualifierType == null) {
     return false;
   }
   final Project project = expression.getProject();
   final GlobalSearchScope projectScope = GlobalSearchScope.allScope(project);
   final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
   final PsiClass javaUtilListClass =
       psiFacade.findClass(CommonClassNames.JAVA_UTIL_LIST, projectScope);
   if (javaUtilListClass == null) {
     return false;
   }
   final PsiElementFactory factory = psiFacade.getElementFactory();
   final PsiClassType javaUtilListType = factory.createType(javaUtilListClass);
   return javaUtilListType.isAssignableFrom(qualifierType);
 }
コード例 #8
0
 @Nullable
 private static PsiType guessElementTypeFromReference(
     MethodPatternMap methodPatternMap, PsiElement ref, TextRange rangeToIgnore) {
   PsiElement refParent = ref.getParent();
   if (refParent instanceof PsiReferenceExpression) {
     PsiReferenceExpression parentExpr = (PsiReferenceExpression) refParent;
     if (ref.equals(parentExpr.getQualifierExpression())
         && parentExpr.getParent() instanceof PsiMethodCallExpression) {
       String methodName = parentExpr.getReferenceName();
       PsiMethodCallExpression methodCall = (PsiMethodCallExpression) parentExpr.getParent();
       PsiExpression[] args = methodCall.getArgumentList().getExpressions();
       MethodPattern pattern = methodPatternMap.findPattern(methodName, args.length);
       if (pattern != null) {
         if (pattern.parameterIndex < 0) { // return value
           if (methodCall.getParent() instanceof PsiTypeCastExpression
               && (rangeToIgnore == null || !rangeToIgnore.contains(methodCall.getTextRange()))) {
             return ((PsiTypeCastExpression) methodCall.getParent()).getType();
           }
         } else {
           return args[pattern.parameterIndex].getType();
         }
       }
     }
   }
   return null;
 }
コード例 #9
0
 @Override
 public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) {
   super.visitMethodCallExpression(expression);
   final PsiReferenceExpression methodExpression = expression.getMethodExpression();
   @NonNls final String methodName = methodExpression.getReferenceName();
   if (methodName == null) {
     return;
   }
   if (!methodName.startsWith("get") && !methodName.startsWith("update")) {
     return;
   }
   final PsiExpressionList argumentList = expression.getArgumentList();
   final PsiExpression[] arguments = argumentList.getExpressions();
   if (arguments.length == 0) {
     return;
   }
   final PsiExpression argument = arguments[0];
   if (!TypeUtils.expressionHasType(argument, PsiKeyword.INT)) {
     return;
   }
   if (!PsiUtil.isConstantExpression(argument)) {
     return;
   }
   final Integer val = (Integer) ConstantExpressionUtil.computeCastTo(argument, PsiType.INT);
   if (val == null || val.intValue() != 0) {
     return;
   }
   final PsiExpression qualifier = methodExpression.getQualifierExpression();
   if (!TypeUtils.expressionHasTypeOrSubtype(qualifier, "java.sql.ResultSet")) {
     return;
   }
   registerError(argument);
 }
コード例 #10
0
ファイル: RefCountHolder.java プロジェクト: novokrest/JBIDEA
  private static boolean isParameterUsedRecursively(
      @NotNull PsiElement element, @NotNull List<PsiReference> array) {
    if (!(element instanceof PsiParameter)) return false;
    PsiParameter parameter = (PsiParameter) element;
    PsiElement scope = parameter.getDeclarationScope();
    if (!(scope instanceof PsiMethod)) return false;
    PsiMethod method = (PsiMethod) scope;
    int paramIndex = ArrayUtilRt.find(method.getParameterList().getParameters(), parameter);

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

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

    return true;
  }
コード例 #11
0
 @Override
 public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) {
   super.visitMethodCallExpression(expression);
   final PsiReferenceExpression methodExpression = expression.getMethodExpression();
   final String methodName = methodExpression.getReferenceName();
   @NonNls final String signal = "signal";
   if (!signal.equals(methodName)) {
     return;
   }
   final PsiExpressionList argumentList = expression.getArgumentList();
   if (argumentList.getExpressions().length != 0) {
     return;
   }
   final PsiMethod method = expression.resolveMethod();
   if (method == null) {
     return;
   }
   final PsiClass containingClass = method.getContainingClass();
   if (containingClass == null) {
     return;
   }
   if (!ClassUtils.isSubclass(containingClass, "java.util.concurrent.locks.Condition")) {
     return;
   }
   registerMethodCallError(expression);
 }
コード例 #12
0
  protected void changeSelfUsage(SelfUsageInfo usageInfo) throws IncorrectOperationException {
    PsiElement parent = usageInfo.getElement().getParent();
    LOG.assertTrue(parent instanceof PsiMethodCallExpression);
    PsiMethodCallExpression methodCall = (PsiMethodCallExpression) parent;
    final PsiExpression qualifier = methodCall.getMethodExpression().getQualifierExpression();
    if (qualifier != null) qualifier.delete();

    PsiElementFactory factory =
        JavaPsiFacade.getInstance(methodCall.getProject()).getElementFactory();
    PsiExpressionList args = methodCall.getArgumentList();
    PsiElement addParameterAfter = null;

    if (mySettings.isMakeClassParameter()) {
      PsiElement arg = factory.createExpressionFromText(mySettings.getClassParameterName(), null);
      addParameterAfter = args.addAfter(arg, null);
    }

    if (mySettings.isMakeFieldParameters()) {
      List<Settings.FieldParameter> parameters = mySettings.getParameterOrderList();
      for (Settings.FieldParameter fieldParameter : parameters) {
        PsiElement arg = factory.createExpressionFromText(fieldParameter.name, null);
        if (addParameterAfter == null) {
          addParameterAfter = args.addAfter(arg, null);
        } else {
          addParameterAfter = args.addAfter(arg, addParameterAfter);
        }
      }
    }
  }
コード例 #13
0
 @Override
 public void visitMethodCallExpression(PsiMethodCallExpression expression) {
   super.visitMethodCallExpression(expression);
   final PsiReferenceExpression methodExpression = expression.getMethodExpression();
   @NonNls final String referenceName = methodExpression.getReferenceName();
   if (!"toString".equals(referenceName)
       || ExpressionUtils.isConversionToStringNecessary(expression)) {
     return;
   }
   final PsiExpressionList argumentList = expression.getArgumentList();
   final PsiExpression[] arguments = argumentList.getExpressions();
   if (arguments.length != 0) {
     return;
   }
   final PsiExpression qualifier = methodExpression.getQualifierExpression();
   if (qualifier != null) {
     if (qualifier.getType() instanceof PsiArrayType) {
       // do not warn on nonsensical code
       return;
     } else if (qualifier instanceof PsiSuperExpression) {
       return;
     }
   }
   registerMethodCallError(expression, calculateReplacementText(qualifier));
 }
コード例 #14
0
 @Override
 public void doFix(Project project, ProblemDescriptor descriptor)
     throws IncorrectOperationException {
   final PsiIdentifier name = (PsiIdentifier) descriptor.getPsiElement();
   final PsiReferenceExpression expression = (PsiReferenceExpression) name.getParent();
   if (expression == null) {
     return;
   }
   final PsiMethodCallExpression call = (PsiMethodCallExpression) expression.getParent();
   final String methodName = expression.getReferenceName();
   if (call == null) {
     return;
   }
   final PsiMethod method = call.resolveMethod();
   if (method == null) {
     return;
   }
   final PsiClass containingClass = method.getContainingClass();
   final PsiExpressionList argumentList = call.getArgumentList();
   if (containingClass == null) {
     return;
   }
   final String containingClassName = containingClass.getQualifiedName();
   final String argText = argumentList.getText();
   PsiReplacementUtil.replaceExpressionAndShorten(
       call, containingClassName + '.' + methodName + argText);
 }
コード例 #15
0
 @Override
 public void visitMethodCallExpression(PsiMethodCallExpression expression) {
   super.visitMethodCallExpression(expression);
   final PsiReferenceExpression methodExpression = expression.getMethodExpression();
   @NonNls final String name = methodExpression.getReferenceName();
   if (HardcodedMethodConstants.TO_STRING.equals(name)) {
     final PsiExpressionList argumentList = expression.getArgumentList();
     final PsiExpression[] arguments = argumentList.getExpressions();
     if (arguments.length != 0) {
       return;
     }
     final PsiExpression qualifier = methodExpression.getQualifierExpression();
     checkExpression(qualifier);
   } else if ("append".equals(name)) {
     final PsiExpression qualifier = methodExpression.getQualifierExpression();
     if (!TypeUtils.expressionHasTypeOrSubtype(
         qualifier, CommonClassNames.JAVA_LANG_ABSTRACT_STRING_BUILDER)) {
       return;
     }
     final PsiExpressionList argumentList = expression.getArgumentList();
     final PsiExpression[] arguments = argumentList.getExpressions();
     if (arguments.length != 1) {
       return;
     }
     final PsiExpression argument = arguments[0];
     checkExpression(argument);
   } else if ("valueOf".equals(name)) {
     final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
     if (!(qualifierExpression instanceof PsiReferenceExpression)) {
       return;
     }
     final PsiReferenceExpression referenceExpression =
         (PsiReferenceExpression) qualifierExpression;
     final String canonicalText = referenceExpression.getCanonicalText();
     if (!CommonClassNames.JAVA_LANG_STRING.equals(canonicalText)) {
       return;
     }
     final PsiExpressionList argumentList = expression.getArgumentList();
     final PsiExpression[] arguments = argumentList.getExpressions();
     if (arguments.length != 1) {
       return;
     }
     final PsiExpression argument = arguments[0];
     checkExpression(argument);
   }
 }
コード例 #16
0
 private static boolean isValueOfCall(PsiMethodCallExpression methodCallExpression) {
   final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
   final PsiExpression[] arguments = argumentList.getExpressions();
   if (arguments.length != 1) {
     return false;
   }
   final PsiExpression argument = arguments[0];
   final PsiType type = argument.getType();
   return (MethodCallUtils.isCallToMethod(
               methodCallExpression,
               CommonClassNames.JAVA_LANG_INTEGER,
               null,
               "valueOf",
               PsiType.INT)
           && PsiType.INT.equals(type))
       || (MethodCallUtils.isCallToMethod(
               methodCallExpression,
               CommonClassNames.JAVA_LANG_SHORT,
               null,
               "valueOf",
               PsiType.SHORT)
           && PsiType.SHORT.equals(type))
       || (MethodCallUtils.isCallToMethod(
               methodCallExpression,
               CommonClassNames.JAVA_LANG_BYTE,
               null,
               "valueOf",
               PsiType.BYTE)
           && PsiType.BYTE.equals(type))
       || (MethodCallUtils.isCallToMethod(
               methodCallExpression,
               CommonClassNames.JAVA_LANG_LONG,
               null,
               "valueOf",
               PsiType.LONG)
           && PsiType.LONG.equals(type))
       || (MethodCallUtils.isCallToMethod(
               methodCallExpression,
               CommonClassNames.JAVA_LANG_CHARACTER,
               null,
               "valueOf",
               PsiType.CHAR)
           && PsiType.CHAR.equals(type))
       || (MethodCallUtils.isCallToMethod(
               methodCallExpression,
               CommonClassNames.JAVA_LANG_DOUBLE,
               null,
               "valueOf",
               PsiType.DOUBLE)
           && PsiType.DOUBLE.equals(type))
       || (MethodCallUtils.isCallToMethod(
               methodCallExpression,
               CommonClassNames.JAVA_LANG_FLOAT,
               null,
               "valueOf",
               PsiType.FLOAT)
           && PsiType.FLOAT.equals(type));
 }
 @Override
 protected boolean isValidElement(PsiElement element) {
   PsiMethodCallExpression methodCall = (PsiMethodCallExpression) element;
   PsiMethod method = (PsiMethod) methodCall.getMethodExpression().resolve();
   PsiExpressionList argumentList = methodCall.getArgumentList();
   List<PsiClass> classes = getTargetClasses(element);
   return !classes.isEmpty()
       && !CreateFromUsageUtils.shouldCreateConstructor(classes.get(0), argumentList, method);
 }
コード例 #18
0
 private static void removeParensFromMethodCallExpression(
     @NotNull PsiMethodCallExpression methodCallExpression, boolean ignoreClarifyingParentheses) {
   final PsiReferenceExpression target = methodCallExpression.getMethodExpression();
   final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
   final PsiExpression[] arguments = argumentList.getExpressions();
   removeParentheses(target, ignoreClarifyingParentheses);
   for (final PsiExpression argument : arguments) {
     removeParentheses(argument, ignoreClarifyingParentheses);
   }
 }
コード例 #19
0
 private static boolean isAddAllCall(PsiForeachStatement statement, PsiStatement body) {
   final PsiIfStatement ifStatement = extractIfStatement(body);
   if (ifStatement == null) {
     final PsiParameter parameter = statement.getIterationParameter();
     final PsiMethodCallExpression methodCallExpression = extractAddCall(body, null);
     LOG.assertTrue(methodCallExpression != null);
     return isIdentityMapping(
         parameter, methodCallExpression.getArgumentList().getExpressions()[0]);
   }
   return false;
 }
 @Override
 public void visitReferenceExpression(PsiReferenceExpression expression) {
   if (argumentsContainCatchParameter || !visited.add(expression)) {
     return;
   }
   super.visitReferenceExpression(expression);
   final PsiElement target = expression.resolve();
   if (!parameter.equals(target)) {
     if (target instanceof PsiLocalVariable) {
       final PsiLocalVariable variable = (PsiLocalVariable) target;
       final Query<PsiReference> query =
           ReferencesSearch.search(variable, variable.getUseScope(), false);
       query.forEach(
           reference -> {
             final PsiElement element = reference.getElement();
             final PsiElement parent =
                 PsiTreeUtil.skipParentsOfType(element, PsiParenthesizedExpression.class);
             if (!(parent instanceof PsiReferenceExpression)) {
               return true;
             }
             final PsiElement grandParent = parent.getParent();
             if (!(grandParent instanceof PsiMethodCallExpression)) {
               return true;
             }
             final PsiMethodCallExpression methodCallExpression =
                 (PsiMethodCallExpression) grandParent;
             final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
             final PsiExpression[] arguments = argumentList.getExpressions();
             for (PsiExpression argument : arguments) {
               argument.accept(ReferenceFinder.this);
             }
             return true;
           });
       final PsiExpression initializer = variable.getInitializer();
       if (initializer != null) {
         initializer.accept(this);
       }
     }
     return;
   }
   if (ignoreGetMessage) {
     argumentsContainCatchParameter = true;
   } else {
     final PsiElement parent = expression.getParent();
     if (parent instanceof PsiReferenceExpression) {
       final PsiElement grandParent = parent.getParent();
       if (grandParent instanceof PsiMethodCallExpression) {
         return;
       }
     }
     argumentsContainCatchParameter = true;
   }
 }
コード例 #21
0
 private void processCallArgument(
     PsiMethodCallExpression expression,
     Map<String, Computable<String>> argumentMap,
     List<String> result,
     final int index) {
   final PsiExpression[] arguments = expression.getArgumentList().getExpressions();
   if (arguments.length > index) {
     String testDataFile = evaluate(arguments[index], argumentMap);
     if (testDataFile != null) {
       result.add(myTestDataPath + testDataFile);
     }
   }
 }
コード例 #22
0
  public static PsiType captureReturnType(
      PsiMethodCallExpression call,
      PsiMethod method,
      PsiType ret,
      JavaResolveResult result,
      LanguageLevel languageLevel) {
    PsiSubstitutor substitutor = result.getSubstitutor();
    PsiType substitutedReturnType = substitutor.substitute(ret);
    if (substitutedReturnType == null) {
      return TypeConversionUtil.erasure(ret);
    }

    if (InferenceSession.wasUncheckedConversionPerformed(call)) {
      // 18.5.2
      // if unchecked conversion was necessary, then this substitution provides the parameter types
      // of the invocation type,
      // while the return type and thrown types are given by the erasure of m's type (without
      // applying θ').
      // due to https://bugs.openjdk.java.net/browse/JDK-8135087 erasure is called on
      // substitutedReturnType and not on ret type itself as by spec
      return TypeConversionUtil.erasure(substitutedReturnType);
    }

    // 15.12.2.6. Method Invocation Type
    // If unchecked conversion was necessary for the method to be applicable,
    // the parameter types of the invocation type are the parameter types of the method's type,
    // and the return type and thrown types are given by the erasures of the return type and thrown
    // types of the method's type.
    if (!languageLevel.isAtLeast(LanguageLevel.JDK_1_8)
        && (method.hasTypeParameters()
            || JavaVersionService.getInstance().isAtLeast(call, JavaSdkVersion.JDK_1_8))
        && result instanceof MethodCandidateInfo
        && ((MethodCandidateInfo) result).isApplicable()) {
      final PsiType[] args = call.getArgumentList().getExpressionTypes();
      final boolean allowUncheckedConversion = false;
      final int applicabilityLevel =
          PsiUtil.getApplicabilityLevel(
              method, substitutor, args, languageLevel, allowUncheckedConversion, true);
      if (applicabilityLevel == MethodCandidateInfo.ApplicabilityLevel.NOT_APPLICABLE) {
        return TypeConversionUtil.erasure(substitutedReturnType);
      }
    }

    if (PsiUtil.isRawSubstitutor(method, substitutor)) {
      final PsiType returnTypeErasure = TypeConversionUtil.erasure(ret);
      if (Comparing.equal(TypeConversionUtil.erasure(substitutedReturnType), returnTypeErasure)) {
        return returnTypeErasure;
      }
    }
    return PsiUtil.captureToplevelWildcards(substitutedReturnType, call);
  }
コード例 #23
0
  protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
    final UsageInfo[] usages = refUsages.get();
    MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
    final Set<PsiMember> members = new HashSet<PsiMember>();
    members.add(myMethod);
    if (myTargetVariable instanceof PsiField) members.add((PsiMember) myTargetVariable);
    if (!myTargetClass.isInterface()) {
      RefactoringConflictsUtil.analyzeAccessibilityConflicts(
          members, myTargetClass, conflicts, myNewVisibility);
    } else {
      for (final UsageInfo usage : usages) {
        if (usage instanceof InheritorUsageInfo) {
          RefactoringConflictsUtil.analyzeAccessibilityConflicts(
              members, ((InheritorUsageInfo) usage).getInheritor(), conflicts, myNewVisibility);
        }
      }
    }

    if (myTargetVariable instanceof PsiParameter) {
      PsiParameter parameter = (PsiParameter) myTargetVariable;
      for (final UsageInfo usageInfo : usages) {
        if (usageInfo instanceof MethodCallUsageInfo) {
          final PsiMethodCallExpression methodCall =
              ((MethodCallUsageInfo) usageInfo).getMethodCallExpression();
          final PsiExpression[] expressions = methodCall.getArgumentList().getExpressions();
          final int index = myMethod.getParameterList().getParameterIndex(parameter);
          if (index < expressions.length) {
            PsiExpression instanceValue = expressions[index];
            instanceValue = RefactoringUtil.unparenthesizeExpression(instanceValue);
            if (instanceValue instanceof PsiLiteralExpression
                && ((PsiLiteralExpression) instanceValue).getValue() == null) {
              String message =
                  RefactoringBundle.message(
                      "0.contains.call.with.null.argument.for.parameter.1",
                      RefactoringUIUtil.getDescription(
                          ConflictsUtil.getContainer(methodCall), true),
                      CommonRefactoringUtil.htmlEmphasize(parameter.getName()));
              conflicts.putValue(instanceValue, message);
            }
          }
        }
      }
    }

    try {
      ConflictsUtil.checkMethodConflicts(myTargetClass, myMethod, getPatternMethod(), conflicts);
    } catch (IncorrectOperationException e) {
    }

    return showConflicts(conflicts, usages);
  }
 @Override
 protected final void doFix(Project project, ProblemDescriptor descriptor)
     throws IncorrectOperationException {
   final PsiElement element = descriptor.getPsiElement();
   final PsiTypeElement castTypeElement;
   final PsiReferenceExpression reference;
   if (element instanceof PsiTypeCastExpression) {
     final PsiTypeCastExpression typeCastExpression = (PsiTypeCastExpression) element;
     castTypeElement = typeCastExpression.getCastType();
     final PsiExpression operand = typeCastExpression.getOperand();
     if (!(operand instanceof PsiReferenceExpression)) {
       return;
     }
     reference = (PsiReferenceExpression) operand;
   } else if (element instanceof PsiMethodCallExpression) {
     final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) element;
     final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
     final PsiExpression qualifier = methodExpression.getQualifierExpression();
     if (!(qualifier instanceof PsiClassObjectAccessExpression)) {
       return;
     }
     final PsiClassObjectAccessExpression classObjectAccessExpression =
         (PsiClassObjectAccessExpression) qualifier;
     castTypeElement = classObjectAccessExpression.getOperand();
     final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
     final PsiExpression[] arguments = argumentList.getExpressions();
     if (arguments.length != 1) {
       return;
     }
     final PsiExpression argument = arguments[0];
     if (!(argument instanceof PsiReferenceExpression)) {
       return;
     }
     reference = (PsiReferenceExpression) argument;
   } else {
     return;
   }
   if (castTypeElement == null) {
     return;
   }
   final PsiInstanceOfExpression conflictingInstanceof =
       InstanceOfUtils.getConflictingInstanceof(castTypeElement.getType(), reference, element);
   final PsiTypeElement instanceofTypeElement = conflictingInstanceof.getCheckType();
   if (instanceofTypeElement == null) {
     return;
   }
   final PsiElement newElement = replace(castTypeElement, instanceofTypeElement);
   final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
   codeStyleManager.shortenClassReferences(newElement);
 }
コード例 #25
0
  private List<MethodContract> handleCallDelegation(
      PsiMethodCallExpression expression, final boolean negated) {
    final PsiMethod targetMethod = expression.resolveMethod();
    if (targetMethod == null) return Collections.emptyList();

    final PsiExpression[] arguments = expression.getArgumentList().getExpressions();
    return RecursionManager.doPreventingRecursion(
        myMethod,
        true,
        new Computable<List<MethodContract>>() {
          @Override
          public List<MethodContract> compute() {
            List<MethodContract> delegateContracts =
                ControlFlowAnalyzer.getMethodContracts(targetMethod);
            return ContainerUtil.mapNotNull(
                delegateContracts,
                new NullableFunction<MethodContract, MethodContract>() {
                  @Nullable
                  @Override
                  public MethodContract fun(MethodContract delegateContract) {
                    ValueConstraint[] answer =
                        MethodContract.createConstraintArray(
                            myMethod.getParameterList().getParametersCount());
                    for (int i = 0; i < delegateContract.arguments.length; i++) {
                      if (i >= arguments.length) return null;

                      ValueConstraint argConstraint = delegateContract.arguments[i];
                      if (argConstraint != ANY_VALUE) {
                        int paramIndex = resolveParameter(arguments[i]);
                        if (paramIndex < 0) {
                          if (argConstraint != getLiteralConstraint(arguments[i])) {
                            return null;
                          }
                        } else {
                          answer = withConstraint(answer, paramIndex, argConstraint);
                        }
                      }
                    }
                    return answer == null
                        ? null
                        : new MethodContract(
                            answer,
                            negated
                                ? negateConstraint(delegateContract.returnValue)
                                : delegateContract.returnValue);
                  }
                });
          }
        });
  }
 @Override
 public void visitMethodCallExpression(PsiMethodCallExpression expression) {
   super.visitMethodCallExpression(expression);
   final PsiReferenceExpression methodExpression = expression.getMethodExpression();
   final String methodName = methodExpression.getReferenceName();
   if (!"cast".equals(methodName)) {
     return;
   }
   final PsiMethod method = expression.resolveMethod();
   if (method == null) {
     return;
   }
   final PsiClass containingClass = method.getContainingClass();
   if (containingClass == null) {
     return;
   }
   final String qualifiedName = containingClass.getQualifiedName();
   if (!"java.lang.Class".equals(qualifiedName)) {
     return;
   }
   final PsiExpression qualifier = methodExpression.getQualifierExpression();
   if (!(qualifier instanceof PsiClassObjectAccessExpression)) {
     return;
   }
   final PsiClassObjectAccessExpression classObjectAccessExpression =
       (PsiClassObjectAccessExpression) qualifier;
   final PsiTypeElement operand = classObjectAccessExpression.getOperand();
   final PsiType castType = operand.getType();
   if (!(castType instanceof PsiClassType)) {
     return;
   }
   final PsiExpressionList argumentList = expression.getArgumentList();
   final PsiExpression[] arguments = argumentList.getExpressions();
   if (arguments.length != 1) {
     return;
   }
   final PsiExpression argument = arguments[0];
   if (!(argument instanceof PsiReferenceExpression)) {
     return;
   }
   final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) argument;
   final PsiInstanceOfExpression conflictingInstanceof =
       InstanceOfUtils.getConflictingInstanceof(castType, referenceExpression, expression);
   if (conflictingInstanceof == null) {
     return;
   }
   final PsiTypeElement instanceofTypeElement = conflictingInstanceof.getCheckType();
   registerError(expression, referenceExpression, operand, instanceofTypeElement);
 }
コード例 #27
0
 @Nullable
 private String evaluate(PsiExpression expression, Map<String, Computable<String>> arguments) {
   if (expression instanceof PsiPolyadicExpression) {
     PsiPolyadicExpression binaryExpression = (PsiPolyadicExpression) expression;
     if (binaryExpression.getOperationTokenType() == JavaTokenType.PLUS) {
       String r = "";
       for (PsiExpression op : binaryExpression.getOperands()) {
         String lhs = evaluate(op, arguments);
         if (lhs == null) return null;
         r += lhs;
       }
       return r;
     }
   } else if (expression instanceof PsiLiteralExpression) {
     final Object value = ((PsiLiteralExpression) expression).getValue();
     if (value instanceof String) {
       return (String) value;
     }
   } else if (expression instanceof PsiReferenceExpression) {
     final PsiElement result = ((PsiReferenceExpression) expression).resolve();
     if (result instanceof PsiParameter) {
       final String name = ((PsiParameter) result).getName();
       final Computable<String> arg = arguments.get(name);
       return arg == null ? null : arg.compute();
     }
     if (result instanceof PsiVariable) {
       final PsiExpression initializer = ((PsiVariable) result).getInitializer();
       if (initializer != null) {
         return evaluate(initializer, arguments);
       }
     }
   } else if (expression instanceof PsiMethodCallExpression) {
     final PsiMethodCallExpression methodCall = (PsiMethodCallExpression) expression;
     final String callText = methodCall.getMethodExpression().getText();
     if (callText.equals("getTestName")) {
       final PsiExpression[] psiExpressions = methodCall.getArgumentList().getExpressions();
       if (psiExpressions.length == 1) {
         if ("true".equals(psiExpressions[0].getText()) && !StringUtil.isEmpty(myTestName)) {
           return UsefulTestCase.lowercaseFirstLetter(myTestName, true);
         }
         return myTestName;
       }
     }
   }
   if (expression != null) {
     myLogMessages.add("Failed to evaluate " + expression.getText());
   }
   return null;
 }
コード例 #28
0
    private boolean isListGetLookup(PsiElement element,
                                    String indexName,
                                    PsiVariable listVariable) {
      if (!(element instanceof PsiExpression)) {
        return false;
      }
      final PsiExpression expression = (PsiExpression)element;
      if (!expressionIsListGetLookup(expression)) {
        return false;
      }
      final PsiMethodCallExpression methodCallExpression =
        (PsiMethodCallExpression)
          ParenthesesUtils.stripParentheses(expression);
      if (methodCallExpression == null) {
        return false;
      }
      final PsiReferenceExpression methodExpression =
        methodCallExpression.getMethodExpression();
      final PsiExpression qualifierExpression =
        methodExpression.getQualifierExpression();

      final PsiExpressionList argumentList =
        methodCallExpression.getArgumentList();
      final PsiExpression[] expressions = argumentList.getExpressions();
      if (expressions.length != 1) {
        return false;
      }
      if (!indexName.equals(expressions[0].getText())) {
        return false;
      }
      if (qualifierExpression == null ||
          qualifierExpression instanceof PsiThisExpression ||
          qualifierExpression instanceof PsiSuperExpression) {
        return listVariable == null;
      }
      if (!(qualifierExpression instanceof PsiReferenceExpression)) {
        return false;
      }
      final PsiReferenceExpression referenceExpression =
        (PsiReferenceExpression)qualifierExpression;
      final PsiExpression qualifier =
        referenceExpression.getQualifierExpression();
      if (qualifier != null && !(qualifier instanceof PsiThisExpression) &&
          !(qualifier instanceof PsiSuperExpression)) {
        return false;
      }
      final PsiElement target = referenceExpression.resolve();
      return listVariable.equals(target);
    }
コード例 #29
0
    @Override
    public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) {
      super.visitMethodCallExpression(expression);
      final PsiReferenceExpression methodExpression = expression.getMethodExpression();
      final String methodName = methodExpression.getReferenceName();

      if (!HardcodedMethodConstants.NOTIFY.equals(methodName)) {
        return;
      }
      final PsiExpressionList argumentList = expression.getArgumentList();
      if (argumentList.getExpressions().length != 0) {
        return;
      }
      registerMethodCallError(expression);
    }
 private static boolean expressionIsArrayToCollectionCopy(
     PsiExpression expression, PsiVariable variable, boolean shouldBeOffsetArrayAccess) {
   expression = ParenthesesUtils.stripParentheses(expression);
   if (expression == null) {
     return false;
   }
   if (!(expression instanceof PsiMethodCallExpression)) {
     return false;
   }
   final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression;
   final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
   final PsiExpression[] arguments = argumentList.getExpressions();
   if (arguments.length != 1) {
     return false;
   }
   final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
   final PsiExpression qualifier = methodExpression.getQualifierExpression();
   if (!(qualifier instanceof PsiReferenceExpression)
       && !(qualifier instanceof PsiThisExpression)
       && !(qualifier instanceof PsiSuperExpression)) {
     return false;
   }
   final PsiExpression argument = arguments[0];
   final PsiType argumentType = argument.getType();
   if (argumentType instanceof PsiPrimitiveType) {
     return false;
   }
   if (SideEffectChecker.mayHaveSideEffects(argument)) {
     return false;
   }
   if (shouldBeOffsetArrayAccess) {
     if (!ExpressionUtils.isOffsetArrayAccess(argument, variable)) {
       return false;
     }
   } else if (!VariableAccessUtils.evaluatesToVariable(argument, variable)) {
     return false;
   }
   final PsiMethod method = methodCallExpression.resolveMethod();
   if (method == null) {
     return false;
   }
   @NonNls final String name = method.getName();
   if (!name.equals("add")) {
     return false;
   }
   final PsiClass containingClass = method.getContainingClass();
   return InheritanceUtil.isInheritor(containingClass, CommonClassNames.JAVA_UTIL_COLLECTION);
 }