org.jetbrains.uast.UExpression Java Examples

The following examples show how to use org.jetbrains.uast.UExpression. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WrongRetentionDetector.java    From dagger-reflect with Apache License 2.0 6 votes vote down vote up
private static void reportWrongRetentionType(
    @NotNull JavaContext context,
    boolean isKotlin,
    @NotNull UAnnotation retentionAnnotation,
    @NotNull String actualRetention) {
  final UExpression annotationValue = UastLintUtils.getAnnotationValue(retentionAnnotation);
  context.report(
      ISSUE_WRONG_RETENTION,
      retentionAnnotation,
      context.getLocation(retentionAnnotation),
      String.format(
          "Annotation used by Dagger Reflect must be annotated with `@Retention(RUNTIME)` but is `@Retention(%s)`.",
          actualRetention),
      LintFix.create()
          .name("Replace with: `@Retention(RUNTIME)`")
          .replace()
          .range(context.getLocation(annotationValue))
          .with(isKotlin ? FIX_RETENTION_TYPE_KOTLIN : FIX_RETENTION_TYPE_JAVA)
          .reformat(true)
          .shortenNames()
          .build());
}
 
Example #2
Source File: NoDelegateOnResumeDetector.java    From PermissionsDispatcher with Apache License 2.0 6 votes vote down vote up
private boolean isWithPermissionCheckCalled(@NotNull UCallExpression node, @NotNull UIdentifier methodIdentifier) {
    if (!(needPermissionMethodName + "WithPermissionCheck").equalsIgnoreCase(methodIdentifier.getName())) {
        return false;
    }

    UExpression receiver = node.getReceiver();
    if (isKotlin) {
        return receiver == null;
    } else {
        String qualifiedName = uClass.getQualifiedName();
        if (node.getValueArgumentCount() < 1) return false;
        PsiType expressionType = node.getValueArguments().get(0).getExpressionType();
        return receiver != null
                && qualifiedName != null
                && expressionType != null
                && qualifiedName.equalsIgnoreCase(expressionType.getCanonicalText())
                && (uClass.getName() + "PermissionsDispatcher").equalsIgnoreCase(receiver.asSourceString());
    }
}
 
Example #3
Source File: InvalidR2UsageDetector.java    From butterknife with Apache License 2.0 5 votes vote down vote up
private static boolean isR2Expression(UElement node) {
  UElement parentNode = node.getUastParent();
  if (parentNode == null) {
    return false;
  }
  String text = node.asSourceString();
  UElement parent = LintUtils.skipParentheses(parentNode);
  return (text.equals(R2) || text.contains(".R2"))
      && parent instanceof UExpression
      && endsWithAny(parent.asSourceString(), SUPPORTED_TYPES);
}
 
Example #4
Source File: SignalLogDetector.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private LintFix quickFixIssueLog(@NotNull UCallExpression logCall) {
  List<UExpression> arguments  = logCall.getValueArguments();
  String            methodName = logCall.getMethodName();
  UExpression       tag        = arguments.get(0);

  String fixSource = "org.thoughtcrime.securesms.logging.Log.";

  switch (arguments.size()) {
    case 2:
      UExpression msgOrThrowable = arguments.get(1);
      fixSource += String.format("%s(%s, %s)", methodName, tag, msgOrThrowable.asSourceString());
      break;

    case 3:
      UExpression msg = arguments.get(1);
      UExpression throwable = arguments.get(2);
      fixSource += String.format("%s(%s, %s, %s)", methodName, tag, msg.asSourceString(), throwable.asSourceString());
      break;

    default:
      throw new IllegalStateException("Log overloads should have 2 or 3 arguments");
  }

  String logCallSource = logCall.asSourceString();
  LintFix.GroupBuilder fixGrouper = fix().group();
  fixGrouper.add(fix().replace().text(logCallSource).shortenNames().reformat(true).with(fixSource).build());
  return fixGrouper.build();
}
 
Example #5
Source File: DebugLintIssue.java    From Debug with Apache License 2.0 5 votes vote down vote up
private static boolean isSubclassOf(
        @NonNull JavaContext context,
        @NonNull UExpression expression,
        @NonNull Class<?> cls) {

    final PsiType expressionType = expression.getExpressionType();
    if (!(expressionType instanceof PsiClassType)) {
        return false;
    }

    final PsiClassType classType = (PsiClassType) expressionType;
    final PsiClass resolvedClass = classType.resolve();
    return context.getEvaluator().extendsClass(resolvedClass, cls.getName(), false);
}
 
Example #6
Source File: WrongRetentionDetector.java    From dagger-reflect with Apache License 2.0 5 votes vote down vote up
@NotNull
private static String getQualifiedNameForValueJava(
    @NotNull JavaContext context, @Nullable UExpression annotationValue) {
  final Object evaluatedAnnotationValue = ConstantEvaluator.evaluate(context, annotationValue);
  if (evaluatedAnnotationValue instanceof PsiEnumConstant) {
    return UastLintUtils.getQualifiedName((PsiEnumConstant) evaluatedAnnotationValue);
  }
  throw new IllegalStateException("RetentionPolicy must not be null if @Retention is present");
}
 
Example #7
Source File: WrongRetentionDetector.java    From dagger-reflect with Apache License 2.0 5 votes vote down vote up
@NotNull
private static String getQualifiedNameForValueKotlin(
    @NotNull JavaContext context, @Nullable UExpression annotationValue) {
  final Object evaluatedAnnotationValue = ConstantEvaluator.evaluate(context, annotationValue);
  if (evaluatedAnnotationValue instanceof kotlin.Pair) {
    final kotlin.Pair<?, ?> value = (kotlin.Pair<?, ?>) evaluatedAnnotationValue;
    final String qualifiedName = (value.getFirst() + "." + value.getSecond());
    return qualifiedName.replace("/", ".");
  }
  throw new IllegalStateException("RetentionPolicy must not be null if @Retention is present");
}
 
Example #8
Source File: WrongRetentionDetector.java    From dagger-reflect with Apache License 2.0 5 votes vote down vote up
@NotNull
private static String getRetentionPolicy(
    @NotNull JavaContext context, boolean isKotlin, @NotNull UAnnotation retentationAnnotation) {
  final UExpression annotationValue = UastLintUtils.getAnnotationValue(retentationAnnotation);
  final String retentionPolicyQualifiedName =
      isKotlin
          ? getQualifiedNameForValueKotlin(context, annotationValue)
          : getQualifiedNameForValueJava(context, annotationValue);
  final String retentionPolicy = getRetentionPolicyForQualifiedName(retentionPolicyQualifiedName);
  if (retentionPolicy != null) {
    return retentionPolicy;
  }
  throw new IllegalStateException("RetentionPolicy must not be null if @Retention is present");
}
 
Example #9
Source File: ConfigElementsUtils.java    From aircon with MIT License 4 votes vote down vote up
private static PsiField getReferencedConfigField(final UAnnotation annotation, String attribute) {
	final UExpression value = annotation.findAttributeValue(attribute);
	return (PsiField) ((JavaUSimpleNameReferenceExpression) value).resolve();
}
 
Example #10
Source File: ElementUtils.java    From aircon with MIT License 4 votes vote down vote up
public static boolean hasConstInitializer(final @NotNull UField node) {
	final UExpression initializer = node.getUastInitializer();
	return initializer != null && initializer.evaluate() != null;
}
 
Example #11
Source File: ElementUtils.java    From aircon with MIT License 4 votes vote down vote up
public static boolean isFieldReference(UExpression expression) {
	return expression instanceof JavaUSimpleNameReferenceExpression;
}
 
Example #12
Source File: ElementUtils.java    From aircon with MIT License 4 votes vote down vote up
public static List<UExpression> getExpressions(UMethod method) {
	return ((JavaUCodeBlockExpression) method.getUastBody()).getExpressions();
}
 
Example #13
Source File: CallOnRequestPermissionsResultDetector.java    From PermissionsDispatcher with Apache License 2.0 4 votes vote down vote up
private static boolean isGeneratedMethodCalled(UMethod method, String className, boolean isKotlin) {
    UExpression methodBody = method.getUastBody();
    if (methodBody == null) {
        return false;
    }
    if (methodBody instanceof UBlockExpression) {
        UBlockExpression methodBodyExpression = (UBlockExpression) methodBody;
        List<UExpression> expressions = methodBodyExpression.getExpressions();
        for (UExpression expression : expressions) {
            if (isKotlin && expression instanceof KotlinUFunctionCallExpression) {
                KotlinUFunctionCallExpression functionalExpression = (KotlinUFunctionCallExpression) expression;
                if ("onRequestPermissionsResult".equals(functionalExpression.getMethodName())) {
                    return true;
                }
            }

            if (!(expression instanceof UQualifiedReferenceExpression)) {
                continue;
            }

            UQualifiedReferenceExpression referenceExpression = (UQualifiedReferenceExpression) expression;
            UExpression receiverExpression = referenceExpression.getReceiver();
            PsiElement receiverPsi = receiverExpression.getPsi();
            if (receiverPsi == null) {
                continue; // can this case be happened?
            }
            String receiverName = receiverPsi.getText();
            if ("super".equals(receiverName)) {
                // skip super method call
                continue;
            }

            if (isKotlin && referenceExpression instanceof KotlinUQualifiedReferenceExpression) {
                if ("onRequestPermissionsResult".equals(referenceExpression.getResolvedName())) {
                    return true;
                }
            } else {
                String targetClassName = className + "PermissionsDispatcher";
                if (targetClassName.equals(receiverName) && "onRequestPermissionsResult".equals(referenceExpression.getResolvedName())) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example #14
Source File: DebugLintIssue.java    From Debug with Apache License 2.0 4 votes vote down vote up
private static void process(@NonNull JavaContext context, @NonNull UCallExpression expression) {

        // to be able to mutate (we remove first Throwable if present)
        final List<UExpression> arguments = new ArrayList<>(expression.getValueArguments());
        if (arguments.isEmpty()) {
            // if there are no arguments -> no check
            return;
        }

        // remove throwable (comes first0
        if (isSubclassOf(context, arguments.get(0), Throwable.class)) {
            arguments.remove(0);
        }

        // still check for empty arguments (method can be called with just a throwable)
        // if first argument is not a string, then also nothing to do here
        if (arguments.isEmpty()
                || !isSubclassOf(context, arguments.get(0), String.class)) {
            return;
        }

        // now, first arg is string, check if it matches the pattern
        final String pattern = (String) arguments.get(0).evaluate();
        if (pattern == null
                || pattern.length() == 0) {
            // if no pattern is available -> return
            return;
        }

        final Matcher matcher = STRING_FORMAT_PATTERN.matcher(pattern);

        // we must _find_, not _matches_
        if (matcher.find()) {
            // okay, first argument is string
            // evaluate other arguments (actually create them)

            // remove pattern
            arguments.remove(0);

            // what else can we do -> count actual placeholders and arguments
            // (if mismatch... no, we can have positioned)
            final Object[] mock = mockArguments(arguments);

            try {
                //noinspection ResultOfMethodCallIgnored
                String.format(pattern, mock);
            } catch (Throwable t) {
                context.report(
                        ISSUE,
                        expression,
                        context.getLocation(expression),
                        t.getMessage());
            }
        }
    }
 
Example #15
Source File: DebugLintIssue.java    From Debug with Apache License 2.0 4 votes vote down vote up
@Nullable
private static Object[] mockArguments(@NonNull List<UExpression> list) {

    if (list.isEmpty()) {
        return null;
    }

    final List<Object> objects = new ArrayList<>(list.size());

    for (UExpression expression : list) {
        final Object eval = expression.evaluate();
        if (eval != null) {
            objects.add(eval);
        } else {

            // we must really _mock_ it
            // check for primitives -> and create them, else just `new Object()`

            final Object o;

            final PsiType psiType = expression.getExpressionType();
            if (PsiType.BOOLEAN.equals(psiType)) {
                o = false;
            } else if (PsiType.BYTE.equals(psiType)) {
                o = (byte) 0;
            } else if (PsiType.CHAR.equals(psiType)) {
                o = 'a';
            } else if (PsiType.DOUBLE.equals(psiType)) {
                o = 0.0D;
            } else if (PsiType.FLOAT.equals(psiType)) {
                o = 0.0F;
            } else if (PsiType.INT.equals(psiType)) {
                o = 0;
            } else if (PsiType.LONG.equals(psiType)) {
                o = 0L;
            } else if (PsiType.SHORT.equals(psiType)) {
                o = (short) 0;
            } else if (PsiType.NULL.equals(psiType)) {
                o = null;
            } else {
                o = new Object();
            }

            objects.add(o);
        }
    }

    return objects.toArray();
}
 
Example #16
Source File: DialogMethodCallLintDetector.java    From SimpleDialogFragments with Apache License 2.0 3 votes vote down vote up
@Override
public void visitMethod(JavaContext context, UCallExpression node, PsiMethod method) {

    if (context.getEvaluator().isMemberInSubClassOf(method,
            "eltos.simpledialogfragment.SimpleDialog", false)) {

        PsiClass definingClass = method.getContainingClass();
        UExpression callingExpression = node.getReceiver();

        if (definingClass != null && callingExpression != null) {

            PsiType type = TypeEvaluator.evaluate(callingExpression);
            if (type instanceof PsiClassType) {
                // when called on instance of a class
                PsiClass callingClass = ((PsiClassType) type).resolve();

                if (callingClass != null && !Objects.equals(callingClass, definingClass)) {

                    context.report(BUILD_CALL, context.getLocation(node), String.format(
                            BUILD_CALL_MESSAGE, callingClass.getName(), definingClass.getName()));
                }

            } else {
                // when called as static reference
                if (!Objects.equals(definingClass.getName(), callingExpression.toString())) {
                    context.report(BUILD_CALL, context.getLocation(node), String.format(
                            BUILD_CALL_MESSAGE, callingExpression, definingClass.getName()));
                }
            }

        }



    }

}
 
Example #17
Source File: DialogMethodCallLintDetector.java    From SimpleDialogFragments with Apache License 2.0 3 votes vote down vote up
@Override
public void visitMethod(JavaContext context, UCallExpression node, PsiMethod method) {

    if (context.getEvaluator().isMemberInSubClassOf(method,
            "eltos.simpledialogfragment.SimpleDialog", false)) {

        PsiClass definingClass = method.getContainingClass();
        UExpression callingExpression = node.getReceiver();

        if (definingClass != null && callingExpression != null) {

            PsiType type = TypeEvaluator.evaluate(callingExpression);
            if (type instanceof PsiClassType) {
                // when called on instance of a class
                PsiClass callingClass = ((PsiClassType) type).resolve();

                if (callingClass != null && !Objects.equals(callingClass, definingClass)) {

                    context.report(BUILD_CALL, context.getLocation(node), String.format(
                            BUILD_CALL_MESSAGE, callingClass.getName(), definingClass.getName()));
                }

            } else {
                // when called as static reference
                if (!Objects.equals(definingClass.getName(), callingExpression.toString())) {
                    context.report(BUILD_CALL, context.getLocation(node), String.format(
                            BUILD_CALL_MESSAGE, callingExpression, definingClass.getName()));
                }
            }

        }



    }

}