private static boolean isNullLiteralExpression(PsiElement expr) {
   if (expr instanceof PsiLiteralExpression) {
     final PsiLiteralExpression literalExpression = (PsiLiteralExpression) expr;
     return PsiType.NULL.equals(literalExpression.getType());
   }
   return false;
 }
 @Override
 public void visitLiteralExpression(@NotNull PsiLiteralExpression expression) {
   super.visitLiteralExpression(expression);
   final PsiType type = expression.getType();
   if (!ClassUtils.isPrimitiveNumericType(type)) {
     return;
   }
   if (PsiType.CHAR.equals(type)) {
     return;
   }
   if (isSpecialCaseLiteral(expression)) {
     return;
   }
   if (ExpressionUtils.isDeclaredConstant(expression)) {
     return;
   }
   if (ignoreInHashCode) {
     final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(expression, PsiMethod.class);
     if (MethodUtils.isHashCode(containingMethod)) {
       return;
     }
   }
   if (ignoreInTestCode && TestUtils.isInTestCode(expression)) {
     return;
   }
   final PsiElement parent = expression.getParent();
   if (parent instanceof PsiPrefixExpression) {
     registerError(parent);
   } else {
     registerError(expression);
   }
 }
  @Override
  public void computeUsages(List<PsiLiteralExpression> targets) {
    final Project project = myTarget.getProject();
    final PsiElement parent = myTarget.getParent().getParent();
    final LocalInspectionsPass pass =
        new LocalInspectionsPass(
            myFile,
            myFile.getViewProvider().getDocument(),
            parent.getTextRange().getStartOffset(),
            parent.getTextRange().getEndOffset(),
            LocalInspectionsPass.EMPTY_PRIORITY_RANGE,
            false,
            HighlightInfoProcessor.getEmpty());
    final InspectionProfile inspectionProfile =
        InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
    for (PsiLiteralExpression target : targets) {
      final Object value = target.getValue();
      if (!(value instanceof String)) {
        continue;
      }
      InspectionToolWrapper toolWrapperById =
          ((InspectionProfileImpl) inspectionProfile).getToolById((String) value, target);
      if (!(toolWrapperById instanceof LocalInspectionToolWrapper)) {
        continue;
      }
      final LocalInspectionToolWrapper toolWrapper =
          ((LocalInspectionToolWrapper) toolWrapperById).createCopy();
      final InspectionManagerEx managerEx =
          (InspectionManagerEx) InspectionManager.getInstance(project);
      final GlobalInspectionContextImpl context = managerEx.createNewGlobalContext(false);
      toolWrapper.initialize(context);
      ((RefManagerImpl) context.getRefManager()).inspectionReadActionStarted();
      ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
      Runnable inspect =
          new Runnable() {
            @Override
            public void run() {
              pass.doInspectInBatch(
                  context,
                  managerEx,
                  Collections.<LocalInspectionToolWrapper>singletonList(toolWrapper));
            }
          };
      if (indicator == null) {
        ProgressManager.getInstance()
            .executeProcessUnderProgress(inspect, new ProgressIndicatorBase());
      } else {
        inspect.run();
      }

      for (HighlightInfo info : pass.getInfos()) {
        final PsiElement element =
            CollectHighlightsUtil.findCommonParent(myFile, info.startOffset, info.endOffset);
        if (element != null) {
          addOccurrence(element);
        }
      }
    }
  }
 private static boolean literalExpressionsAreEquivalent(
     PsiLiteralExpression expression1, PsiLiteralExpression expression2) {
   final Object value1 = expression1.getValue();
   final Object value2 = expression2.getValue();
   if (value1 == null) {
     return value2 == null;
   } else if (value2 == null) {
     return false;
   }
   return value1.equals(value2);
 }
 @Nullable
 private static CompileTimeConstant<?> getCompileTimeConstFromLiteralExpression(
     PsiLiteralExpression value) {
   Object literalValue = value.getValue();
   if (literalValue instanceof String) {
     return new StringValue((String) literalValue);
   } else if (literalValue instanceof Byte) {
     return new ByteValue((Byte) literalValue);
   } else if (literalValue instanceof Short) {
     return new ShortValue((Short) literalValue);
   } else if (literalValue instanceof Character) {
     return new CharValue((Character) literalValue);
   } else if (literalValue instanceof Integer) {
     return new IntValue((Integer) literalValue);
   } else if (literalValue instanceof Long) {
     return new LongValue((Long) literalValue);
   } else if (literalValue instanceof Float) {
     return new FloatValue((Float) literalValue);
   } else if (literalValue instanceof Double) {
     return new DoubleValue((Double) literalValue);
   } else if (literalValue == null) {
     return NullValue.NULL;
   }
   return null;
 }
  public void updateReturnValueTemplate(PsiExpression expression) {
    if (myReturnValueTemplate == null) return;

    if (!getSuperMethods().isEmpty()) {
      for (final RefMethod refMethod : getSuperMethods()) {
        RefMethodImpl refSuper = (RefMethodImpl) refMethod;
        refSuper.updateReturnValueTemplate(expression);
      }
    } else {
      String newTemplate = null;
      final RefJavaUtil refUtil = RefJavaUtil.getInstance();
      if (expression instanceof PsiLiteralExpression) {
        PsiLiteralExpression psiLiteralExpression = (PsiLiteralExpression) expression;
        newTemplate = psiLiteralExpression.getText();
      } else if (expression instanceof PsiReferenceExpression) {
        PsiReferenceExpression referenceExpression = (PsiReferenceExpression) expression;
        PsiElement resolved = referenceExpression.resolve();
        if (resolved instanceof PsiField) {
          PsiField psiField = (PsiField) resolved;
          if (psiField.hasModifierProperty(PsiModifier.STATIC)
              && psiField.hasModifierProperty(PsiModifier.FINAL)
              && refUtil.compareAccess(refUtil.getAccessModifier(psiField), getAccessModifier())
                  >= 0) {
            newTemplate =
                PsiFormatUtil.formatVariable(
                    psiField,
                    PsiFormatUtilBase.SHOW_NAME
                        | PsiFormatUtilBase.SHOW_CONTAINING_CLASS
                        | PsiFormatUtilBase.SHOW_FQ_NAME,
                    PsiSubstitutor.EMPTY);
          }
        }
      } else if (refUtil.isCallToSuperMethod(expression, (PsiMethod) getElement())) return;

      //noinspection StringEquality
      if (myReturnValueTemplate == RETURN_VALUE_UNDEFINED) {
        myReturnValueTemplate = newTemplate;
      } else if (!Comparing.equal(myReturnValueTemplate, newTemplate)) {
        myReturnValueTemplate = null;
      }
    }
  }
  public boolean satisfiedBy(PsiElement element) {
    if (!(element instanceof PsiLiteralExpression)) {
      return false;
    }
    final PsiLiteralExpression expression = (PsiLiteralExpression) element;
    final PsiType type = expression.getType();
    if (!PsiType.CHAR.equals(type)) {
      return false;
    }
    final String charLiteral = element.getText();
    if (charLiteral.length() < 2)
      return false; // Incomplete char literal probably without closing amp

    final String charText = charLiteral.substring(1, charLiteral.length() - 1);
    if (StringUtil.unescapeStringCharacters(charText).length() != 1) {
      // not satisfied with character literals of more than one character
      return false;
    }
    return isInConcatenationContext(expression);
  }
 public static boolean isPropertyRef(
     final PsiLiteralExpression expression, final String key, final String resourceBundleName) {
   if (resourceBundleName == null) {
     return !PropertiesImplUtil.findPropertiesByKey(expression.getProject(), key).isEmpty();
   } else {
     final List<PropertiesFile> propertiesFiles =
         propertiesFilesByBundleName(resourceBundleName, expression);
     boolean containedInPropertiesFile = false;
     for (PropertiesFile propertiesFile : propertiesFiles) {
       containedInPropertiesFile |= propertiesFile.findPropertyByKey(key) != null;
     }
     return containedInPropertiesFile;
   }
 }
 @Override
 public void visitLiteralExpression(@NotNull PsiLiteralExpression value) {
   super.visitLiteralExpression(value);
   final String text = value.getText();
   if (!PsiKeyword.NULL.equals(text)) {
     return;
   }
   PsiElement parent = value.getParent();
   while (parent instanceof PsiParenthesizedExpression
       || parent instanceof PsiConditionalExpression
       || parent instanceof PsiTypeCastExpression) {
     parent = parent.getParent();
   }
   if (parent == null || !(parent instanceof PsiReturnStatement)) {
     return;
   }
   final PsiMethod method = PsiTreeUtil.getParentOfType(value, PsiMethod.class);
   if (method == null) {
     return;
   }
   final PsiType returnType = method.getReturnType();
   if (returnType == null) {
     return;
   }
   final boolean isArray = returnType.getArrayDimensions() > 0;
   if (AnnotationUtil.isAnnotated(method, AnnotationUtil.NULLABLE, false)) {
     return;
   }
   if (m_reportCollectionMethods && CollectionUtils.isCollectionClassOrInterface(returnType)) {
     registerError(value, value);
   } else if (m_reportArrayMethods && isArray) {
     registerError(value, value);
   } else if (m_reportObjectMethods && !isArray) {
     registerError(value, value);
   }
 }
 public static boolean mustBePropertyKey(
     @NotNull Project project,
     @NotNull PsiLiteralExpression expression,
     @NotNull Map<String, Object> annotationAttributeValues) {
   final PsiElement parent = expression.getParent();
   if (parent instanceof PsiVariable) {
     final PsiAnnotation annotation =
         AnnotationUtil.findAnnotation((PsiVariable) parent, AnnotationUtil.PROPERTY_KEY);
     if (annotation != null) {
       return processAnnotationAttributes(annotationAttributeValues, annotation);
     }
   }
   return isPassedToAnnotatedParam(
       project, expression, AnnotationUtil.PROPERTY_KEY, annotationAttributeValues, null);
 }
 /**
  * Returns number of different parameters in i18n message. For example, for string <i>Class {0}
  * info: Class {0} extends class {1} and implements interface {2}</i> number of parameters is 3.
  *
  * @param expression i18n literal
  * @return number of parameters
  */
 public static int getPropertyValueParamsMaxCount(final PsiLiteralExpression expression) {
   int maxCount = -1;
   for (PsiReference reference : expression.getReferences()) {
     if (reference instanceof PsiPolyVariantReference) {
       for (ResolveResult result : ((PsiPolyVariantReference) reference).multiResolve(false)) {
         if (result.isValidResult() && result.getElement() instanceof IProperty) {
           String value = ((IProperty) result.getElement()).getValue();
           MessageFormat format;
           try {
             format = new MessageFormat(value);
           } catch (Exception e) {
             continue; // ignore syntax error
           }
           try {
             int count = format.getFormatsByArgumentIndex().length;
             maxCount = Math.max(maxCount, count);
           } catch (IllegalArgumentException ignored) {
           }
         }
       }
     }
   }
   return maxCount;
 }
示例#12
0
  private NamesByExprInfo suggestVariableNameByExpressionOnly(
      PsiExpression expr,
      final VariableKind variableKind,
      boolean correctKeywords,
      boolean useAllMethodNames) {
    if (expr instanceof PsiMethodCallExpression) {
      PsiReferenceExpression methodExpr = ((PsiMethodCallExpression) expr).getMethodExpression();
      String methodName = methodExpr.getReferenceName();
      if (methodName != null) {
        if ("of".equals(methodName) || "ofNullable".equals(methodName)) {
          if (isJavaUtilMethodCall((PsiMethodCallExpression) expr)) {
            PsiExpression[] expressions =
                ((PsiMethodCallExpression) expr).getArgumentList().getExpressions();
            if (expressions.length > 0) {
              return suggestVariableNameByExpressionOnly(
                  expressions[0], variableKind, correctKeywords, useAllMethodNames);
            }
          }
        }
        if ("map".equals(methodName)
            || "flatMap".equals(methodName)
            || "filter".equals(methodName)) {
          if (isJavaUtilMethodCall((PsiMethodCallExpression) expr)) {
            return new NamesByExprInfo(null);
          }
        }

        String[] words = NameUtil.nameToWords(methodName);
        if (words.length > 0) {
          final String firstWord = words[0];
          if (GET_PREFIX.equals(firstWord)
              || IS_PREFIX.equals(firstWord)
              || FIND_PREFIX.equals(firstWord)
              || CREATE_PREFIX.equals(firstWord)) {
            if (words.length > 1) {
              final String propertyName = methodName.substring(firstWord.length());
              String[] names =
                  getSuggestionsByName(propertyName, variableKind, false, correctKeywords);
              final PsiExpression qualifierExpression = methodExpr.getQualifierExpression();
              if (qualifierExpression instanceof PsiReferenceExpression
                  && ((PsiReferenceExpression) qualifierExpression).resolve()
                      instanceof PsiVariable) {
                names =
                    ArrayUtil.append(
                        names,
                        StringUtil.sanitizeJavaIdentifier(
                            changeIfNotIdentifier(
                                qualifierExpression.getText()
                                    + StringUtil.capitalize(propertyName))));
              }
              return new NamesByExprInfo(propertyName, names);
            }
          } else if (words.length == 1 || useAllMethodNames) {
            return new NamesByExprInfo(
                methodName, getSuggestionsByName(methodName, variableKind, false, correctKeywords));
          }
        }
      }
    } else if (expr instanceof PsiReferenceExpression) {
      String propertyName = ((PsiReferenceExpression) expr).getReferenceName();
      PsiElement refElement = ((PsiReferenceExpression) expr).resolve();
      if (refElement instanceof PsiVariable) {
        VariableKind refVariableKind = getVariableKind((PsiVariable) refElement);
        propertyName = variableNameToPropertyName(propertyName, refVariableKind);
      }
      if (refElement != null && propertyName != null) {
        String[] names = getSuggestionsByName(propertyName, variableKind, false, correctKeywords);
        return new NamesByExprInfo(propertyName, names);
      }
    } else if (expr instanceof PsiArrayAccessExpression) {
      PsiExpression arrayExpr = ((PsiArrayAccessExpression) expr).getArrayExpression();
      if (arrayExpr instanceof PsiReferenceExpression) {
        String arrayName = ((PsiReferenceExpression) arrayExpr).getReferenceName();
        PsiElement refElement = ((PsiReferenceExpression) arrayExpr).resolve();
        if (refElement instanceof PsiVariable) {
          VariableKind refVariableKind = getVariableKind((PsiVariable) refElement);
          arrayName = variableNameToPropertyName(arrayName, refVariableKind);
        }

        if (arrayName != null) {
          String name = StringUtil.unpluralize(arrayName);
          if (name != null) {
            String[] names = getSuggestionsByName(name, variableKind, false, correctKeywords);
            return new NamesByExprInfo(name, names);
          }
        }
      }
    } else if (expr instanceof PsiLiteralExpression
        && variableKind == VariableKind.STATIC_FINAL_FIELD) {
      final PsiLiteralExpression literalExpression = (PsiLiteralExpression) expr;
      final Object value = literalExpression.getValue();
      if (value instanceof String) {
        final String stringValue = (String) value;
        String[] names = getSuggestionsByValue(stringValue);
        if (names.length > 0) {
          return new NamesByExprInfo(null, constantValueToConstantName(names));
        }
      }
    } else if (expr instanceof PsiParenthesizedExpression) {
      return suggestVariableNameByExpressionOnly(
          ((PsiParenthesizedExpression) expr).getExpression(),
          variableKind,
          correctKeywords,
          useAllMethodNames);
    } else if (expr instanceof PsiTypeCastExpression) {
      return suggestVariableNameByExpressionOnly(
          ((PsiTypeCastExpression) expr).getOperand(),
          variableKind,
          correctKeywords,
          useAllMethodNames);
    } else if (expr instanceof PsiLiteralExpression) {
      final String text = StringUtil.stripQuotesAroundValue(expr.getText());
      if (isIdentifier(text)) {
        return new NamesByExprInfo(
            text, getSuggestionsByName(text, variableKind, false, correctKeywords));
      }
    }

    return new NamesByExprInfo(null, ArrayUtil.EMPTY_STRING_ARRAY);
  }