lombok.ast.MethodDeclaration Java Examples

The following examples show how to use lombok.ast.MethodDeclaration. 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: 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 #2
Source File: JavaPerformanceDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns true if this method looks like it's overriding android.view.View's
 * {@code public void layout(int l, int t, int r, int b)}
 */
private static boolean isLayoutMethod(MethodDeclaration node) {
    if (LAYOUT.equals(node.astMethodName().astValue())) {
        StrictListAccessor<VariableDefinition, MethodDeclaration> parameters =
                node.astParameters();
        if (parameters != null && parameters.size() == 4) {
            Iterator<VariableDefinition> iterator = parameters.iterator();
            for (int i = 0; i < 4; i++) {
                if (!iterator.hasNext()) {
                    return false;
                }
                VariableDefinition next = iterator.next();
                TypeReferencePart type = next.astTypeReference().astParts().last();
                if (!TYPE_INT.equals(type.getTypeName())) {
                    return false;
                }
            }
            return true;
        }
    }

    return false;
}
 
Example #3
Source File: SharedPrefsDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
private static VariableDefinition getLhs(@NonNull Node node) {
    while (node != null) {
        Class<? extends Node> type = node.getClass();
        // The Lombok AST uses a flat hierarchy of node type implementation classes
        // so no need to do instanceof stuff here.
        if (type == MethodDeclaration.class || type == ConstructorDeclaration.class) {
            return null;
        }
        if (type == VariableDefinition.class) {
            return (VariableDefinition) node;
        }

        node = node.getParent();
    }

    return null;
}
 
Example #4
Source File: JavaPerformanceDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns true if this method looks like it's overriding android.view.View's
 * {@code protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)}
 */
private static boolean isOnMeasureMethod(MethodDeclaration node) {
    if (ON_MEASURE.equals(node.astMethodName().astValue())) {
        StrictListAccessor<VariableDefinition, MethodDeclaration> parameters =
                node.astParameters();
        if (parameters != null && parameters.size() == 2) {
            VariableDefinition arg0 = parameters.first();
            VariableDefinition arg1 = parameters.last();
            TypeReferencePart type1 = arg0.astTypeReference().astParts().last();
            TypeReferencePart type2 = arg1.astTypeReference().astParts().last();
            return TYPE_INT.equals(type1.getTypeName())
                    && TYPE_INT.equals(type2.getTypeName());
        }
    }

    return false;
}
 
Example #5
Source File: JavaPerformanceDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns true if this method looks like it's overriding android.view.View's
 * {@code protected void onDraw(Canvas canvas)}
 */
private static boolean isOnDrawMethod(MethodDeclaration node) {
    if (ON_DRAW.equals(node.astMethodName().astValue())) {
        StrictListAccessor<VariableDefinition, MethodDeclaration> parameters =
                node.astParameters();
        if (parameters != null && parameters.size() == 1) {
            VariableDefinition arg0 = parameters.first();
            TypeReferencePart type = arg0.astTypeReference().astParts().last();
            String typeName = type.getTypeName();
            if (typeName.equals(CANVAS)) {
                return true;
            }
        }
    }

    return false;
}
 
Example #6
Source File: JavaVisitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visitMethodDeclaration(MethodDeclaration node) {
    List<VisitingDetector> list = mNodeTypeDetectors.get(MethodDeclaration.class);
    if (list != null) {
        for (VisitingDetector v : list) {
            v.getVisitor().visitMethodDeclaration(node);
        }
    }
    return false;
}
 
Example #7
Source File: JavaVariablesDetector.java    From lewis with Apache License 2.0 5 votes vote down vote up
/**
 * Check if a variable declaration if inside a class scope (skip other local variables).
 *
 * @param variableDeclaration represents the variable.
 * @return true if it is inside a class, false if not.
 */
private boolean hasClassParent(VariableDeclaration variableDeclaration) {
    MethodDeclaration methodDeclaration = variableDeclaration.astDefinition().upIfParameterToMethodDeclaration();
    ConstructorDeclaration constructorDeclaration = variableDeclaration.astDefinition().upIfParameterToConstructorDeclaration();
    Block block = variableDeclaration.astDefinition().upUpIfLocalVariableToBlock();
    return methodDeclaration == null && constructorDeclaration == null && block == null;
}
 
Example #8
Source File: ToastDetector.java    From MeituanLintDemo with Apache License 2.0 5 votes vote down vote up
public static Node findSurroundingMethod(Node scope) {
    while(true) {
        if(scope != null) {
            Class type = scope.getClass();
            if(type != MethodDeclaration.class && type != ConstructorDeclaration.class && !isLambdaExpression(type)) {
                scope = scope.getParent();
                continue;
            }

            return scope;
        }

        return null;
    }
}
 
Example #9
Source File: CallSuperDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public static boolean callsSuper(
        @NonNull JavaContext context,
        @NonNull MethodDeclaration methodDeclaration,
        @NonNull ResolvedMethod method) {
    SuperCallVisitor visitor = new SuperCallVisitor(context, method);
    methodDeclaration.accept(visitor);
    return visitor.mCallsSuper;
}
 
Example #10
Source File: CallSuperDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private static void checkCallSuper(@NonNull JavaContext context,
        @NonNull MethodDeclaration declaration,
        @NonNull ResolvedMethod method) {

    ResolvedMethod superMethod = getRequiredSuperMethod(method);
    if (superMethod != null) {
        if (!SuperCallVisitor.callsSuper(context, declaration, superMethod)) {
            String methodName = method.getName();
            String message = "Overriding method should call `super."
                    + methodName + "`";
            Location location = context.getLocation(declaration.astMethodName());
            context.report(ISSUE, declaration, location, message);
        }
    }
}
 
Example #11
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 #12
Source File: StringFormatDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/** Returns the parent method of the given AST node */
@Nullable
public static lombok.ast.Node getParentMethod(@NonNull lombok.ast.Node node) {
    lombok.ast.Node current = node.getParent();
    while (current != null
            && !(current instanceof MethodDeclaration)
            && !(current instanceof ConstructorDeclaration)) {
        current = current.getParent();
    }

    return current;
}
 
Example #13
Source File: JavaPerformanceDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns true if this method looks like it's overriding
 * android.view.View's
 * {@code protected void onLayout(boolean changed, int left, int top,
 *      int right, int bottom)}
 */
private static boolean isOnLayoutMethod(MethodDeclaration node) {
    if (ON_LAYOUT.equals(node.astMethodName().astValue())) {
        StrictListAccessor<VariableDefinition, MethodDeclaration> parameters =
                node.astParameters();
        if (parameters != null && parameters.size() == 5) {
            Iterator<VariableDefinition> iterator = parameters.iterator();
            if (!iterator.hasNext()) {
                return false;
            }

            // Ensure that the argument list matches boolean, int, int, int, int
            TypeReferencePart type = iterator.next().astTypeReference().astParts().last();
            if (!type.getTypeName().equals(TYPE_BOOLEAN) || !iterator.hasNext()) {
                return false;
            }
            for (int i = 0; i < 4; i++) {
                type = iterator.next().astTypeReference().astParts().last();
                if (!type.getTypeName().equals(TYPE_INT)) {
                    return false;
                }
                if (!iterator.hasNext()) {
                    return i == 3;
                }
            }
        }
    }

    return false;
}
 
Example #14
Source File: JavaPerformanceDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check whether the given invocation is done as a lazy initialization,
 * e.g. {@code if (foo == null) foo = new Foo();}.
 * <p>
 * This tries to also handle the scenario where the check is on some
 * <b>other</b> variable - e.g.
 * <pre>
 *    if (foo == null) {
 *        foo == init1();
 *        bar = new Bar();
 *    }
 * </pre>
 * or
 * <pre>
 *    if (!initialized) {
 *        initialized = true;
 *        bar = new Bar();
 *    }
 * </pre>
 */
private static boolean isLazilyInitialized(Node node) {
    Node curr = node.getParent();
    while (curr != null) {
        if (curr instanceof MethodDeclaration) {
            return false;
        } else if (curr instanceof If) {
            If ifNode = (If) curr;
            // See if the if block represents a lazy initialization:
            // compute all variable names seen in the condition
            // (e.g. for "if (foo == null || bar != foo)" the result is "foo,bar"),
            // and then compute all variables assigned to in the if body,
            // and if there is an overlap, we'll consider the whole if block
            // guarded (so lazily initialized and an allocation we won't complain
            // about.)
            List<String> assignments = new ArrayList<String>();
            AssignmentTracker visitor = new AssignmentTracker(assignments);
            ifNode.astStatement().accept(visitor);
            if (!assignments.isEmpty()) {
                List<String> references = new ArrayList<String>();
                addReferencedVariables(references, ifNode.astCondition());
                if (!references.isEmpty()) {
                    SetView<String> intersection = Sets.intersection(
                            new HashSet<String>(assignments),
                            new HashSet<String>(references));
                    return !intersection.isEmpty();
                }
            }
            return false;

        }
        curr = curr.getParent();
    }

    return false;
}
 
Example #15
Source File: JavaPerformanceDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<Class<? extends Node>> getApplicableNodeTypes() {
    List<Class<? extends Node>> types = new ArrayList<Class<? extends Node>>(3);
    types.add(ConstructorInvocation.class);
    types.add(MethodDeclaration.class);
    types.add(MethodInvocation.class);
    return types;
}
 
Example #16
Source File: IconDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visitMethodDeclaration(MethodDeclaration node) {
    if (ON_CREATE_OPTIONS_MENU.equals(node.astMethodName().astValue())) {
        // Gather any R.menu references found in this method
        node.accept(new MenuFinder());
    }

    return super.visitMethodDeclaration(node);
}
 
Example #17
Source File: IconDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Nullable
public List<Class<? extends Node>> getApplicableNodeTypes() {
    List<Class<? extends Node>> types = new ArrayList<Class<? extends Node>>(3);
    types.add(MethodDeclaration.class);
    types.add(ConstructorInvocation.class);
    return types;
}
 
Example #18
Source File: ViewHolderDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visitMethodDeclaration(MethodDeclaration node) {
    if (isViewAdapterMethod(node)) {
        InflationVisitor visitor = new InflationVisitor(mContext);
        node.accept(visitor);
        visitor.finish();
    }
    return super.visitMethodDeclaration(node);
}
 
Example #19
Source File: ApiDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
@Override
public List<Class<? extends lombok.ast.Node>> getApplicableNodeTypes() {
    List<Class<? extends lombok.ast.Node>> types =
            new ArrayList<Class<? extends lombok.ast.Node>>(2);
    types.add(ImportDeclaration.class);
    types.add(Select.class);
    types.add(MethodDeclaration.class);
    types.add(ConstructorDeclaration.class);
    types.add(VariableDefinitionEntry.class);
    types.add(VariableReference.class);
    types.add(Try.class);
    return types;
}
 
Example #20
Source File: JavaContext.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
public static Node findSurroundingMethod(Node scope) {
    while (scope != null) {
        Class<? extends Node> type = scope.getClass();
        // The Lombok AST uses a flat hierarchy of node type implementation classes
        // so no need to do instanceof stuff here.
        if (type == MethodDeclaration.class || type == ConstructorDeclaration.class) {
            return scope;
        }

        scope = scope.getParent();
    }

    return null;
}
 
Example #21
Source File: JavaPerformanceDetector.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns whether the given method declaration represents a method
 * where allocating objects is not allowed for performance reasons
 */
private static boolean isBlockedAllocationMethod(MethodDeclaration node) {
    return isOnDrawMethod(node) || isOnMeasureMethod(node) || isOnLayoutMethod(node)
            || isLayoutMethod(node);
}
 
Example #22
Source File: JavaPerformanceDetector.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean visitMethodDeclaration(MethodDeclaration node) {
    mFlagAllocations = isBlockedAllocationMethod(node);

    return super.visitMethodDeclaration(node);
}
 
Example #23
Source File: SharedPrefsDetector.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean visitMethodInvocation(MethodInvocation node) {
    if (node == mTarget) {
        mSeenTarget = true;
    } else if (mAllowCommitBeforeTarget || mSeenTarget || node.astOperand() == mTarget) {
        String name = node.astName().astValue();
        boolean isCommit = "commit".equals(name);
        if (isCommit || "apply".equals(name)) { //$NON-NLS-1$ //$NON-NLS-2$
            // TODO: Do more flow analysis to see whether we're really calling commit/apply
            // on the right type of object?
            mFound = true;

            ResolvedNode resolved = mContext.resolve(node);
            if (resolved instanceof JavaParser.ResolvedMethod) {
                ResolvedMethod method = (ResolvedMethod) resolved;
                JavaParser.ResolvedClass clz = method.getContainingClass();
                if (clz.isSubclassOf("android.content.SharedPreferences.Editor", false)
                        && mContext.getProject().getMinSdkVersion().getApiLevel() >= 9) {
                    // See if the return value is read: can only replace commit with
                    // apply if the return value is not considered
                    Node parent = node.getParent();
                    boolean returnValueIgnored = false;
                    if (parent instanceof MethodDeclaration ||
                            parent instanceof ConstructorDeclaration ||
                            parent instanceof ClassDeclaration ||
                            parent instanceof Block ||
                            parent instanceof ExpressionStatement) {
                        returnValueIgnored = true;
                    } else if (parent instanceof Statement) {
                        if (parent instanceof If) {
                            returnValueIgnored = ((If) parent).astCondition() != node;
                        } else if (parent instanceof Return) {
                            returnValueIgnored = false;
                        } else if (parent instanceof VariableDeclaration) {
                            returnValueIgnored = false;
                        } else if (parent instanceof For) {
                            returnValueIgnored = ((For) parent).astCondition() != node;
                        } else if (parent instanceof While) {
                            returnValueIgnored = ((While) parent).astCondition() != node;
                        } else if (parent instanceof DoWhile) {
                            returnValueIgnored = ((DoWhile) parent).astCondition() != node;
                        } else if (parent instanceof Case) {
                            returnValueIgnored = ((Case) parent).astCondition() != node;
                        } else if (parent instanceof Assert) {
                            returnValueIgnored = ((Assert) parent).astAssertion() != node;
                        } else {
                            returnValueIgnored = true;
                        }
                    }
                    if (returnValueIgnored && isCommit) {
                        String message = "Consider using `apply()` instead; `commit` writes "
                                + "its data to persistent storage immediately, whereas "
                                + "`apply` will handle it in the background";
                        mContext.report(ISSUE, node, mContext.getLocation(node), message);
                    }
                }
            }
        }
    }

    return super.visitMethodInvocation(node);
}
 
Example #24
Source File: AnnotationDetector.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
private boolean checkId(Annotation node, String id) {
    IssueRegistry registry = mContext.getDriver().getRegistry();
    Issue issue = registry.getIssue(id);
    // Special-case the ApiDetector issue, since it does both source file analysis
    // only on field references, and class file analysis on the rest, so we allow
    // annotations outside of methods only on fields
    if (issue != null && !issue.getImplementation().getScope().contains(Scope.JAVA_FILE)
            || issue == ApiDetector.UNSUPPORTED) {
        // Ensure that this isn't a field
        Node parent = node.getParent();
        while (parent != null) {
            if (parent instanceof MethodDeclaration
                    || parent instanceof ConstructorDeclaration
                    || parent instanceof Block) {
                break;
            } else if (parent instanceof TypeBody) { // It's a field
                return true;
            } else if (issue == ApiDetector.UNSUPPORTED
                    && parent instanceof VariableDefinition) {
                VariableDefinition definition = (VariableDefinition) parent;
                for (VariableDefinitionEntry entry : definition.astVariables()) {
                    Expression initializer = entry.astInitializer();
                    if (initializer instanceof Select) {
                        return true;
                    }
                }
            }
            parent = parent.getParent();
            if (parent == null) {
                return true;
            }
        }

        // This issue doesn't have AST access: annotations are not
        // available for local variables or parameters
        Node scope = getAnnotationScope(node);
        mContext.report(INSIDE_METHOD, scope, mContext.getLocation(node), String.format(
            "The `@SuppressLint` annotation cannot be used on a local " +
            "variable with the lint check '%1$s': move out to the " +
            "surrounding method", id));
        return false;
    }

    return true;
}
 
Example #25
Source File: ViewHolderDetector.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns true if this method looks like it's overriding android.widget.Adapter's getView
 * method: getView(int position, View convertView, ViewGroup parent)
 */
private static boolean isViewAdapterMethod(MethodDeclaration node) {
    if (GET_VIEW.equals(node.astMethodName().astValue())) {
        StrictListAccessor<VariableDefinition, MethodDeclaration> parameters =
                node.astParameters();
        if (parameters != null && parameters.size() == 3) {
            Iterator<VariableDefinition> iterator = parameters.iterator();
            if (!iterator.hasNext()) {
                return false;
            }

            VariableDefinition first = iterator.next();
            if (!first.astTypeReference().astParts().last().getTypeName().equals(
                    TYPE_INT)) {
                return false;
            }

            if (!iterator.hasNext()) {
                return false;
            }

            VariableDefinition second = iterator.next();
            if (!second.astTypeReference().astParts().last().getTypeName().equals(
                    VIEW)) {
                return false;
            }

            if (!iterator.hasNext()) {
                return false;
            }

            VariableDefinition third = iterator.next();
            //noinspection RedundantIfStatement
            if (!third.astTypeReference().astParts().last().getTypeName().equals(
                    VIEW_GROUP)) {
                return false;
            }

            return true;
        }
    }

    return false;
}
 
Example #26
Source File: CallSuperDetector.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<Class<? extends Node>> getApplicableNodeTypes() {
    return Collections.<Class<? extends Node>>singletonList(MethodDeclaration.class);
}
 
Example #27
Source File: ViewHolderDetector.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<Class<? extends Node>> getApplicableNodeTypes() {
    return Collections.<Class<? extends Node>>singletonList(MethodDeclaration.class);
}
 
Example #28
Source File: ApiDetector.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean visitMethodDeclaration(MethodDeclaration node) {
    mLocalVars = null;
    mCurrentMethod = node;
    return super.visitMethodDeclaration(node);
}