lombok.ast.AstVisitor Java Examples

The following examples show how to use lombok.ast.AstVisitor. 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: AppCompatCallDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {
    if (mDependsOnAppCompat && isAppBarActivityCall(context, node)) {
        String name = node.astName().astValue();
        String replace = null;
        if (GET_ACTION_BAR.equals(name)) {
            replace = "getSupportActionBar";
        } else if (START_ACTION_MODE.equals(name)) {
            replace = "startSupportActionMode";
        } else if (SET_PROGRESS_BAR_VIS.equals(name)) {
            replace = "setSupportProgressBarVisibility";
        } else if (SET_PROGRESS_BAR_IN_VIS.equals(name)) {
            replace = "setSupportProgressBarIndeterminateVisibility";
        } else if (SET_PROGRESS_BAR_INDETERMINATE.equals(name)) {
            replace = "setSupportProgressBarIndeterminate";
        } else if (REQUEST_WINDOW_FEATURE.equals(name)) {
            replace = "supportRequestWindowFeature";
        }

        if (replace != null) {
            String message = String.format(ERROR_MESSAGE_FORMAT, replace, name);
            context.report(ISSUE, node, context.getLocation(node), message);
        }
    }
}
 
Example #2
Source File: TodoDetector.java    From linette with Apache License 2.0 6 votes vote down vote up
@Override
public AstVisitor createJavaVisitor(@NonNull JavaContext context) {
    String source = context.getContents();

    // Check validity of source
    if (source == null) {
        return null;
    }

    // Check for uses of to-dos
    int index = source.indexOf(TODO_MATCHER_STRING);
    for (int i = index; i >= 0; i = source.indexOf(TODO_MATCHER_STRING, i + 1)) {
        Location location = Location.create(context.file, source, i, i + TODO_MATCHER_STRING.length());
        context.report(ISSUE, location, ISSUE.getBriefDescription(TextFormat.TEXT));
    }
    return null;
}
 
Example #3
Source File: TodoDetector.java    From Android-Lint-Checks with Apache License 2.0 6 votes vote down vote up
@Override
public AstVisitor createJavaVisitor(@NonNull JavaContext context) {
    String source = context.getContents();

    // Check validity of source
    if (source == null) {
        return null;
    }

    // Check for uses of to-dos
    int index = source.indexOf(TODO_MATCHER_STRING);
    for (int i = index; i >= 0; i = source.indexOf(TODO_MATCHER_STRING, i + 1)) {
        Location location = Location.create(context.file, source, i, i + TODO_MATCHER_STRING.length());
        context.report(ISSUE, location, ISSUE.getBriefDescription(TextFormat.TEXT));
    }
    return null;
}
 
Example #4
Source File: MergeRootFrameLayoutDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visitMethod(
        @NonNull JavaContext context,
        @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {
    StrictListAccessor<Expression, MethodInvocation> argumentList = node.astArguments();
    if (argumentList != null && argumentList.size() == 1) {
        Expression argument = argumentList.first();
        if (argument instanceof Select) {
            String expression = argument.toString();
            if (expression.startsWith(R_LAYOUT_RESOURCE_PREFIX)) {
                whiteListLayout(expression.substring(R_LAYOUT_RESOURCE_PREFIX.length()));
            }
        }
    }
}
 
Example #5
Source File: LogDetector.java    From MeituanLintDemo with Apache License 2.0 6 votes vote down vote up
@Override
public AstVisitor createJavaVisitor(final JavaContext context) {
    return new ForwardingAstVisitor() {
        @Override
        public boolean visitMethodInvocation(MethodInvocation node) {
            JavaParser.ResolvedNode resolve = context.resolve(node);
            if (resolve instanceof JavaParser.ResolvedMethod) {
                JavaParser.ResolvedMethod method = (JavaParser.ResolvedMethod) resolve;
                // 方法所在的类校验
                JavaParser.ResolvedClass containingClass = method.getContainingClass();
                if (containingClass.matches("android.util.Log")) {
                    context.report(ISSUE, node, context.getLocation(node),
                                   "请使用Ln,避免使用Log");
                    return true;
                }
                if (node.toString().startsWith("System.out.println")) {
                    context.report(ISSUE, node, context.getLocation(node),
                                   "请使用Ln,避免使用System.out.println");
                    return true;
                }
            }
            return super.visitMethodInvocation(node);
        }
    };
}
 
Example #6
Source File: GetSignaturesDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {
    ResolvedNode resolved = context.resolve(node);

    if (!(resolved instanceof ResolvedMethod) ||
            !((ResolvedMethod) resolved).getContainingClass()
                    .isSubclassOf(PACKAGE_MANAGER_CLASS, false)) {
        return;
    }
    StrictListAccessor<Expression, MethodInvocation> argumentList = node.astArguments();

    // Ignore if the method doesn't fit our description.
    if (argumentList != null && argumentList.size() == 2) {
        TypeDescriptor firstParameterType = context.getType(argumentList.first());
        if (firstParameterType != null
            && firstParameterType.matchesSignature(JavaParser.TYPE_STRING)) {
            maybeReportIssue(calculateValue(context, argumentList.last()), context, node);
        }
    }
}
 
Example #7
Source File: PrivateResourceDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visitResourceReference(
        @NonNull JavaContext context,
        @Nullable AstVisitor visitor,
        @NonNull Node node,
        @NonNull String type,
        @NonNull String name,
        boolean isFramework) {
    if (context.getProject().isGradleProject() && !isFramework) {
        Project project = context.getProject();
        if (project.getGradleProjectModel() != null && project.getCurrentVariant() != null) {
            ResourceType resourceType = ResourceType.getEnum(type);
            if (resourceType != null && isPrivate(context, resourceType, name)) {
                String message = createUsageErrorMessage(context, resourceType, name);
                context.report(ISSUE, node, context.getLocation(node), message);
            }
        }
    }
}
 
Example #8
Source File: NonInternationalizedSmsDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {
    assert node.astName().astValue().equals("sendTextMessage") ||  //$NON-NLS-1$
        node.astName().astValue().equals("sendMultipartTextMessage");  //$NON-NLS-1$
    if (node.astOperand() == null) {
        // "sendTextMessage"/"sendMultipartTextMessage" in the code with no operand
        return;
    }

    StrictListAccessor<Expression, MethodInvocation> args = node.astArguments();
    if (args.size() == 5) {
        Expression destinationAddress = args.first();
        if (destinationAddress instanceof StringLiteral) {
            String number = ((StringLiteral) destinationAddress).astValue();

            if (!number.startsWith("+")) {  //$NON-NLS-1$
               context.report(ISSUE, node, context.getLocation(destinationAddress),
                   "To make sure the SMS can be sent by all users, please start the SMS number " +
                   "with a + and a country code or restrict the code invocation to people in the country " +
                   "you are targeting.");
            }
        }
    }
}
 
Example #9
Source File: WrongCallDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {

    // Call is only allowed if it is both only called on the super class (invoke special)
    // as well as within the same overriding method (e.g. you can't call super.onLayout
    // from the onMeasure method)
    Expression operand = node.astOperand();
    if (!(operand instanceof Super)) {
        report(context, node);
        return;
    }

    Node method = StringFormatDetector.getParentMethod(node);
    if (!(method instanceof MethodDeclaration) ||
            !((MethodDeclaration)method).astMethodName().astValue().equals(
                    node.astName().astValue())) {
        report(context, node);
    }
}
 
Example #10
Source File: HashMapForJDK7Detector.java    From MeituanLintDemo with Apache License 2.0 6 votes vote down vote up
@Override
public AstVisitor createJavaVisitor(final @NonNull JavaContext context) {
    return new ForwardingAstVisitor() {

        @Override
        public boolean visitConstructorInvocation(ConstructorInvocation node) {
            TypeReference reference = node.astTypeReference();
            String typeName = reference.astParts().last().astIdentifier().astValue();
            // TODO: Should we handle factory method constructions of HashMaps as well,
            // e.g. via Guava? This is a bit trickier since we need to infer the type
            // arguments from the calling context.
            if (typeName.equals(HASH_MAP)) {
                checkHashMap(context, node, reference);
            }
            return super.visitConstructorInvocation(node);
        }
    };
}
 
Example #11
Source File: SetJavaScriptEnabledDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {
    if (node.astArguments().size() == 1
            && !node.astArguments().first().toString().equals("false")) { //$NON-NLS-1$
        context.report(ISSUE, node, context.getLocation(node),
                "Using `setJavaScriptEnabled` can introduce XSS vulnerabilities " +
                        "into you application, review carefully.");
    }
}
 
Example #12
Source File: SecurityDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {
    StrictListAccessor<Expression,MethodInvocation> args = node.astArguments();
    for (Expression arg : args) {
        arg.accept(visitor);
    }
}
 
Example #13
Source File: CallSuperDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public AstVisitor createJavaVisitor(@NonNull final JavaContext context) {
    return new ForwardingAstVisitor() {
        @Override
        public boolean visitMethodDeclaration(MethodDeclaration node) {
            ResolvedNode resolved = context.resolve(node);
            if (resolved instanceof ResolvedMethod) {
                ResolvedMethod method = (ResolvedMethod) resolved;
                checkCallSuper(context, node, method);
            }

            return false;
        }
    };
}
 
Example #14
Source File: RtlDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public AstVisitor createJavaVisitor(@NonNull JavaContext context) {
    if (rtlApplies(context)) {
        return new IdentifierChecker(context);
    }

    return new ForwardingAstVisitor() { };
}
 
Example #15
Source File: CleanupDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {

    String name = node.astName().astValue();
    if (BEGIN_TRANSACTION.equals(name)) {
        checkTransactionCommits(context, node);
    } else {
        checkResourceRecycled(context, node, name);
    }
}
 
Example #16
Source File: ServiceCastDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {
    if (node.getParent() instanceof Cast) {
        Cast cast = (Cast) node.getParent();
        StrictListAccessor<Expression, MethodInvocation> args = node.astArguments();
        if (args.size() == 1) {
            String name = stripPackage(args.first().toString());
            String expectedClass = getExpectedType(name);
            if (expectedClass != null) {
                String castType = cast.astTypeReference().getTypeName();
                if (castType.indexOf('.') == -1) {
                    expectedClass = stripPackage(expectedClass);
                }
                if (!castType.equals(expectedClass)) {
                    // It's okay to mix and match
                    // 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, node, context.getLocation(cast), message);
                }
            }

        }
    }
}
 
Example #17
Source File: StringFormatDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {
    if (mFormatStrings == null && !context.getClient().supportsProjectResources()) {
        return;
    }

    String methodName = node.astName().astValue();
    if (methodName.equals(FORMAT_METHOD)) {
        // String.format(getResources().getString(R.string.foo), arg1, arg2, ...)
        // Check that the arguments in R.string.foo match arg1, arg2, ...
        if (node.astOperand() instanceof VariableReference) {
            VariableReference ref = (VariableReference) node.astOperand();
            if ("String".equals(ref.astIdentifier().astValue())) { //$NON-NLS-1$
                // Found a String.format call
                // Look inside to see if we can find an R string
                // Find surrounding method
                checkFormatCall(context, node);
            }
        }
    } else {
        // getResources().getString(R.string.foo, arg1, arg2, ...)
        // Check that the arguments in R.string.foo match arg1, arg2, ...
        if (node.astArguments().size() > 1 && node.astOperand() != null ) {
            checkFormatCall(context, node);
        }
    }
}
 
Example #18
Source File: UnusedResourceDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public AstVisitor createJavaVisitor(@NonNull JavaContext context) {
    if (mReferences != null) {
        return new UnusedResourceVisitor();
    } else {
        // Second pass, computing resource declaration locations: No need to look at Java
        return null;
    }
}
 
Example #19
Source File: UnusedResourceDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitResourceReference(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull lombok.ast.Node node, @NonNull String type, @NonNull String name,
        boolean isFramework) {
    if (mReferences != null && !isFramework) {
        String reference = R_PREFIX + type + '.' + name;
        mReferences.add(reference);
    }
}
 
Example #20
Source File: AssertDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public AstVisitor createJavaVisitor(@NonNull final JavaContext context) {
    return new ForwardingAstVisitor() {
        @Override
        public boolean visitAssert(Assert node) {
            if (!context.getMainProject().isAndroidProject()) {
                return true;
            }

            Expression assertion = node.astAssertion();
            // Allow "assert true"; it's basically a no-op
            if (assertion instanceof BooleanLiteral) {
                Boolean b = ((BooleanLiteral) assertion).astValue();
                if (b != null && b) {
                    return false;
                }
            } else {
                // Allow assertions of the form "assert foo != null" because they are often used
                // to make statements to tools about known nullness properties. For example,
                // findViewById() may technically return null in some cases, but a developer
                // may know that it won't be when it's called correctly, so the assertion helps
                // to clear nullness warnings.
                if (isNullCheck(assertion)) {
                    return false;
                }
            }
            String message
                    = "Assertions are unreliable. Use `BuildConfig.DEBUG` conditional checks instead.";
            context.report(ISSUE, node, context.getLocation(node), message);
            return false;
        }
    };
}
 
Example #21
Source File: AddJavascriptInterfaceDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {
    // Ignore the issue if we never build for any API less than 17.
    if (context.getMainProject().getMinSdk() >= 17) {
        return;
    }

    // Ignore if the method doesn't fit our description.
    ResolvedNode resolved = context.resolve(node);
    if (!(resolved instanceof ResolvedMethod)) {
        return;
    }
    ResolvedMethod method = (ResolvedMethod) resolved;
    if (!method.getContainingClass().isSubclassOf(WEB_VIEW, false)) {
        return;
    }
    if (method.getArgumentCount() != 2
            || !method.getArgumentType(0).matchesName(TYPE_OBJECT)
            || !method.getArgumentType(1).matchesName(TYPE_STRING)) {
        return;
    }

    String message = "`WebView.addJavascriptInterface` should not be called with minSdkVersion < 17 for security reasons: " +
                     "JavaScript can use reflection to manipulate application";
    context.report(ISSUE, node, context.getLocation(node.astName()), message);
}
 
Example #22
Source File: LayoutConsistencyDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitResourceReference(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull lombok.ast.Node node, @NonNull String type, @NonNull String name,
        boolean isFramework) {
    if (!isFramework && type.equals(ResourceType.ID.getName())) {
        mRelevantIds.add(name);
    }
}
 
Example #23
Source File: SQLiteDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {
    ResolvedNode resolved = context.resolve(node);
    if (!(resolved instanceof ResolvedMethod)) {
        return;
    }

    ResolvedMethod method = (ResolvedMethod) resolved;
    if (!method.getContainingClass().matches("android.database.sqlite.SQLiteDatabase")) {
        return;
    }

    // Try to resolve the String and look for STRING keys
    if (method.getArgumentCount() > 0
            && method.getArgumentType(0).matchesSignature(TYPE_STRING)
            && node.astArguments().size() == method.getArgumentCount()) {
        Iterator<Expression> iterator = node.astArguments().iterator();
        Node argument = iterator.next();
        String sql = ConstantEvaluator.evaluateString(context, argument, true);
        if (sql != null && (sql.startsWith("CREATE TABLE") || sql.startsWith("ALTER TABLE"))
                && sql.matches(".*\\bSTRING\\b.*")) {
            String message = "Using column type STRING; did you mean to use TEXT? "
                    + "(STRING is a numeric type and its value can be adjusted; for example,"
                    + "strings that look like integers can drop leading zeroes. See issue "
                    + "explanation for details.)";
            context.report(ISSUE, node, context.getLocation(node), message);
        }
    }
}
 
Example #24
Source File: ToastDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {
    assert node.astName().astValue().equals("makeText");
    if (node.astOperand() == null) {
        // "makeText()" in the code with no operand
        return;
    }

    String operand = node.astOperand().toString();
    if (!(operand.equals("Toast") || operand.endsWith(".Toast"))) {
        return;
    }

    // Make sure you pass the right kind of duration: it's not a delay, it's
    //  LENGTH_SHORT or LENGTH_LONG
    // (see http://code.google.com/p/android/issues/detail?id=3655)
    StrictListAccessor<Expression, MethodInvocation> args = node.astArguments();
    if (args.size() == 3) {
        Expression duration = args.last();
        if (duration instanceof IntegralLiteral) {
            context.report(ISSUE, duration, context.getLocation(duration),
                    "Expected duration `Toast.LENGTH_SHORT` or `Toast.LENGTH_LONG`, a custom " +
                    "duration value is not supported");
        }
    }

    Node method = JavaContext.findSurroundingMethod(node.getParent());
    if (method == null) {
        return;
    }

    ShowFinder finder = new ShowFinder(node);
    method.accept(finder);
    if (!finder.isShowCalled()) {
        context.report(ISSUE, node, context.getLocation(node),
                "Toast created but not shown: did you forget to call `show()` ?");
    }
}
 
Example #25
Source File: UnsafeAndroidDetector.java    From SafelyAndroid with MIT License 5 votes vote down vote up
@Override
public void visitMethod(JavaContext context, AstVisitor visitor, MethodInvocation node) {
    String name = node.astName().astValue();
    if (DISMISS.equals(name)) {
        checkUnsafeDismiss(context, node);
    } else {
        checkUnsafeCommit(context, node);
    }
}
 
Example #26
Source File: DateFormatDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitConstructor(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull ConstructorInvocation node, @NonNull ResolvedMethod constructor) {
    if (!specifiesLocale(constructor)) {
        Location location = context.getLocation(node);
        String message =
                "To get local formatting use `getDateInstance()`, `getDateTimeInstance()`, " +
                "or `getTimeInstance()`, or use `new SimpleDateFormat(String template, " +
                "Locale locale)` with for example `Locale.US` for ASCII dates.";
        context.report(DATE_FORMAT, node, location, message);
    }
}
 
Example #27
Source File: AlarmDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor,
        @NonNull MethodInvocation node) {
    ResolvedNode resolved = context.resolve(node);
    if (resolved instanceof ResolvedMethod) {
        ResolvedMethod method = (ResolvedMethod) resolved;
        if (method.getContainingClass().matches("android.app.AlarmManager")
                && method.getArgumentCount() == 4) {
            ensureAtLeast(context, node, 1, 5000L);
            ensureAtLeast(context, node, 2, 60000L);
        }
    }
}
 
Example #28
Source File: ApiDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
@Override
public AstVisitor createJavaVisitor(@NonNull JavaContext context) {
    if (mApiDatabase == null) {
        return new ForwardingAstVisitor() {
        };
    }
    return new ApiVisitor(context);
}
 
Example #29
Source File: OverdrawDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public AstVisitor createJavaVisitor(@NonNull JavaContext context) {
    if (!context.getProject().getReportIssues()) {
        return null;
    }
    return new OverdrawVisitor();
}
 
Example #30
Source File: Detector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("javadoc")
public void visitConstructor(
        @NonNull JavaContext context,
        @Nullable AstVisitor visitor,
        @NonNull ConstructorInvocation node,
        @NonNull ResolvedMethod constructor) {
}