Search in sources :

Example 1 with UBinaryExpressionWithType

use of org.jetbrains.uast.UBinaryExpressionWithType in project kotlin by JetBrains.

the class ServiceCastDetector method visitMethod.

@Override
public void visitMethod(@NonNull JavaContext context, @Nullable UastVisitor visitor, @NonNull UCallExpression call, @NonNull UMethod method) {
    UElement parent = LintUtils.skipParentheses(UastUtils.getQualifiedParentOrThis(call).getUastParent());
    if (UastExpressionUtils.isTypeCast(parent)) {
        UBinaryExpressionWithType cast = (UBinaryExpressionWithType) parent;
        List<UExpression> args = call.getValueArguments();
        if (args.size() == 1 && args.get(0) instanceof UReferenceExpression) {
            PsiElement resolvedServiceConst = ((UReferenceExpression) args.get(0)).resolve();
            if (!(resolvedServiceConst instanceof PsiField)) {
                return;
            }
            String name = ((PsiField) resolvedServiceConst).getName();
            String expectedClass = getExpectedType(name);
            if (expectedClass != null && cast != null) {
                String castType = cast.getType().getCanonicalText();
                if (castType.indexOf('.') == -1) {
                    expectedClass = stripPackage(expectedClass);
                }
                if (!castType.equals(expectedClass)) {
                    // android.content.ClipboardManager and android.text.ClipboardManager
                    if (isClipboard(castType) && isClipboard(expectedClass)) {
                        return;
                    }
                    String message = String.format("Suspicious cast to `%1$s` for a `%2$s`: expected `%3$s`", stripPackage(castType), name, stripPackage(expectedClass));
                    context.report(ISSUE, call, context.getUastLocation(cast), message);
                }
            }
        }
    }
}
Also used : UExpression(org.jetbrains.uast.UExpression) PsiField(com.intellij.psi.PsiField) UElement(org.jetbrains.uast.UElement) UReferenceExpression(org.jetbrains.uast.UReferenceExpression) UBinaryExpressionWithType(org.jetbrains.uast.UBinaryExpressionWithType) PsiElement(com.intellij.psi.PsiElement)

Aggregations

PsiElement (com.intellij.psi.PsiElement)1 PsiField (com.intellij.psi.PsiField)1 UBinaryExpressionWithType (org.jetbrains.uast.UBinaryExpressionWithType)1 UElement (org.jetbrains.uast.UElement)1 UExpression (org.jetbrains.uast.UExpression)1 UReferenceExpression (org.jetbrains.uast.UReferenceExpression)1