private void checkExpression(@NotNull PsiExpression expression) { if (expression.getParent() instanceof PsiParenthesizedExpression) { return; } final PsiType expressionType = expression.getType(); if (expressionType == null || expressionType.equals(PsiType.VOID) || !TypeConversionUtil.isPrimitiveAndNotNull(expressionType)) { return; } final PsiPrimitiveType primitiveType = (PsiPrimitiveType) expressionType; final PsiClassType boxedType = primitiveType.getBoxedType(expression); if (boxedType == null) { return; } final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false); if (expectedType == null || ClassUtils.isPrimitive(expectedType)) { return; } if (!expectedType.isAssignableFrom(boxedType)) { // JLS 5.2 Assignment Conversion // check if a narrowing primitive conversion is applicable if (!(expectedType instanceof PsiClassType) || !PsiUtil.isConstantExpression(expression)) { return; } final PsiClassType classType = (PsiClassType) expectedType; final String className = classType.getCanonicalText(); if (!convertableBoxedClassNames.contains(className)) { return; } if (!PsiType.BYTE.equals(expressionType) && !PsiType.CHAR.equals(expressionType) && !PsiType.SHORT.equals(expressionType) && !PsiType.INT.equals(expressionType)) { return; } } if (ignoreAddedToCollection && isAddedToCollection(expression)) { return; } registerError(expression); }
private boolean isAddedToCollection(PsiExpression expression) { final PsiElement parent = expression.getParent(); if (!(parent instanceof PsiExpressionList)) { return false; } final PsiExpressionList expressionList = (PsiExpressionList) parent; final PsiElement grandParent = expressionList.getParent(); if (!(grandParent instanceof PsiMethodCallExpression)) { return false; } final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) grandParent; final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); @NonNls final String methodName = methodExpression.getReferenceName(); if (!"put".equals(methodName) && !"set".equals(methodName) && !"add".equals(methodName)) { return false; } final PsiExpression qualifier = methodExpression.getQualifierExpression(); return TypeUtils.expressionHasTypeOrSubtype( qualifier, CommonClassNames.JAVA_UTIL_COLLECTION, CommonClassNames.JAVA_UTIL_MAP) != null; }