Search in sources :

Example 26 with NameOccurrence

use of net.sourceforge.pmd.lang.symboltable.NameOccurrence in project pmd by pmd.

the class ConsecutiveLiteralAppendsRule method visit.

@Override
public Object visit(ASTVariableDeclaratorId node, Object data) {
    if (!isStringBuffer(node)) {
        return data;
    }
    threshold = getProperty(THRESHOLD_DESCRIPTOR);
    int concurrentCount = checkConstructor(node, data);
    if (hasInitializer(node)) {
        concurrentCount += checkInitializerExpressions(node);
    }
    Node lastBlock = getFirstParentBlock(node);
    Node currentBlock = lastBlock;
    Map<VariableNameDeclaration, List<NameOccurrence>> decls = node.getScope().getDeclarations(VariableNameDeclaration.class);
    Node rootNode = null;
    // only want the constructor flagged if it's really containing strings
    if (concurrentCount >= 1) {
        rootNode = node;
    }
    for (List<NameOccurrence> decl : decls.values()) {
        for (NameOccurrence no : decl) {
            JavaNameOccurrence jno = (JavaNameOccurrence) no;
            Node n = jno.getLocation();
            // variable
            if (!node.getImage().equals(jno.getImage())) {
                continue;
            }
            currentBlock = getFirstParentBlock(n);
            if (!InefficientStringBufferingRule.isInStringBufferOperation(n, 3, "append")) {
                if (!jno.isPartOfQualifiedName()) {
                    checkForViolation(rootNode, data, concurrentCount);
                    concurrentCount = 0;
                }
                continue;
            }
            ASTPrimaryExpression s = n.getFirstParentOfType(ASTPrimaryExpression.class);
            int numChildren = s.jjtGetNumChildren();
            for (int jx = 0; jx < numChildren; jx++) {
                Node sn = s.jjtGetChild(jx);
                if (!(sn instanceof ASTPrimarySuffix) || sn.getImage() != null) {
                    continue;
                }
                // see if it changed blocks
                if (currentBlock != null && lastBlock != null && !currentBlock.equals(lastBlock) || currentBlock == null ^ lastBlock == null) {
                    checkForViolation(rootNode, data, concurrentCount);
                    concurrentCount = 0;
                }
                // here
                if (concurrentCount == 0) {
                    rootNode = sn;
                }
                if (isAdditive(sn)) {
                    concurrentCount = processAdditive(data, concurrentCount, sn, rootNode);
                    if (concurrentCount != 0) {
                        rootNode = sn;
                    }
                } else if (!isAppendingStringLiteral(sn)) {
                    checkForViolation(rootNode, data, concurrentCount);
                    concurrentCount = 0;
                } else {
                    concurrentCount++;
                }
                lastBlock = currentBlock;
            }
        }
    }
    checkForViolation(rootNode, data, concurrentCount);
    return data;
}
Also used : VariableNameDeclaration(net.sourceforge.pmd.lang.java.symboltable.VariableNameDeclaration) JavaNameOccurrence(net.sourceforge.pmd.lang.java.symboltable.JavaNameOccurrence) TypeNode(net.sourceforge.pmd.lang.java.ast.TypeNode) Node(net.sourceforge.pmd.lang.ast.Node) ASTPrimaryExpression(net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression) ASTArgumentList(net.sourceforge.pmd.lang.java.ast.ASTArgumentList) List(java.util.List) ASTPrimarySuffix(net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix) JavaNameOccurrence(net.sourceforge.pmd.lang.java.symboltable.JavaNameOccurrence) NameOccurrence(net.sourceforge.pmd.lang.symboltable.NameOccurrence)

Example 27 with NameOccurrence

use of net.sourceforge.pmd.lang.symboltable.NameOccurrence in project pmd by pmd.

the class UselessOperationOnImmutableRule method visit.

@Override
public Object visit(ASTLocalVariableDeclaration node, Object data) {
    ASTVariableDeclaratorId var = getDeclaration(node);
    if (var == null) {
        return super.visit(node, data);
    }
    String variableName = var.getImage();
    for (NameOccurrence no : var.getUsages()) {
        // FIXME - getUsages will return everything with the same name as
        // the variable,
        // see JUnit test, case 6. Changing to Node below, revisit when
        // getUsages is fixed
        Node sn = no.getLocation();
        Node primaryExpression = sn.jjtGetParent().jjtGetParent();
        Class<? extends Node> parentClass = primaryExpression.jjtGetParent().getClass();
        if (parentClass.equals(ASTStatementExpression.class)) {
            String methodCall = sn.getImage().substring(variableName.length());
            ASTType nodeType = node.getTypeNode();
            if (nodeType != null) {
                if (MAP_CLASSES.get(nodeType.getTypeImage()).contains(methodCall)) {
                    addViolation(data, sn);
                }
            }
        }
    }
    return super.visit(node, data);
}
Also used : ASTType(net.sourceforge.pmd.lang.java.ast.ASTType) ASTVariableDeclaratorId(net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId) Node(net.sourceforge.pmd.lang.ast.Node) NameOccurrence(net.sourceforge.pmd.lang.symboltable.NameOccurrence)

Example 28 with NameOccurrence

use of net.sourceforge.pmd.lang.symboltable.NameOccurrence in project pmd by pmd.

the class UnnecessaryCastRule method process.

private Object process(Node node, Object data) {
    ASTClassOrInterfaceType cit = node.getFirstDescendantOfType(ASTClassOrInterfaceType.class);
    if (cit == null || !implClassNames.contains(cit.getImage())) {
        return data;
    }
    cit = cit.getFirstDescendantOfType(ASTClassOrInterfaceType.class);
    if (cit == null) {
        return data;
    }
    ASTVariableDeclaratorId decl = node.getFirstDescendantOfType(ASTVariableDeclaratorId.class);
    List<NameOccurrence> usages = decl.getUsages();
    for (NameOccurrence no : usages) {
        ASTName name = (ASTName) no.getLocation();
        Node n = name.jjtGetParent().jjtGetParent().jjtGetParent();
        if (n instanceof ASTCastExpression) {
            addViolation(data, n);
        }
    }
    return null;
}
Also used : ASTCastExpression(net.sourceforge.pmd.lang.java.ast.ASTCastExpression) ASTVariableDeclaratorId(net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId) ASTName(net.sourceforge.pmd.lang.java.ast.ASTName) Node(net.sourceforge.pmd.lang.ast.Node) ASTClassOrInterfaceType(net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType) NameOccurrence(net.sourceforge.pmd.lang.symboltable.NameOccurrence)

Example 29 with NameOccurrence

use of net.sourceforge.pmd.lang.symboltable.NameOccurrence in project pmd by pmd.

the class SingularFieldRule method visit.

@SuppressWarnings("PMD.CompareObjectsWithEquals")
@Override
public Object visit(ASTFieldDeclaration node, Object data) {
    boolean checkInnerClasses = getProperty(CHECK_INNER_CLASSES);
    boolean disallowNotAssignment = getProperty(DISALLOW_NOT_ASSIGNMENT);
    if (node.isPrivate() && !node.isStatic() && !hasClassLombokAnnotation() && !hasLombokAnnotation(node)) {
        for (ASTVariableDeclarator declarator : node.findChildrenOfType(ASTVariableDeclarator.class)) {
            ASTVariableDeclaratorId declaration = (ASTVariableDeclaratorId) declarator.jjtGetChild(0);
            List<NameOccurrence> usages = declaration.getUsages();
            Node decl = null;
            boolean violation = true;
            for (int ix = 0; ix < usages.size(); ix++) {
                NameOccurrence no = usages.get(ix);
                Node location = no.getLocation();
                ASTPrimaryExpression primaryExpressionParent = location.getFirstParentOfType(ASTPrimaryExpression.class);
                if (ix == 0 && !disallowNotAssignment) {
                    if (primaryExpressionParent.getFirstParentOfType(ASTIfStatement.class) != null) {
                        // the first usage is in an if, so it may be skipped
                        // on
                        // later calls to the method. So this might be legit
                        // code
                        // that simply stores an object for later use.
                        violation = false;
                        // Optimization
                        break;
                    }
                    // Is the first usage in an assignment?
                    Node potentialStatement = primaryExpressionParent.jjtGetParent();
                    // Check that the assignment is not to a field inside
                    // the field object
                    boolean assignmentToField = no.getImage().equals(location.getImage());
                    if (!assignmentToField || !isInAssignment(potentialStatement)) {
                        violation = false;
                        // Optimization
                        break;
                    } else {
                        if (usages.size() > ix + 1) {
                            Node secondUsageLocation = usages.get(ix + 1).getLocation();
                            List<ASTStatementExpression> parentStatements = secondUsageLocation.getParentsOfType(ASTStatementExpression.class);
                            for (ASTStatementExpression statementExpression : parentStatements) {
                                if (statementExpression != null && statementExpression.equals(potentialStatement)) {
                                    // The second usage is in the assignment
                                    // of the first usage, which is allowed
                                    violation = false;
                                    // Optimization
                                    break;
                                }
                            }
                        }
                    }
                }
                if (!checkInnerClasses) {
                    // Skip inner classes because the field can be used in
                    // the outer class and checking this is too difficult
                    ASTClassOrInterfaceDeclaration clazz = location.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
                    if (clazz != null && clazz.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class) != null) {
                        violation = false;
                        // Optimization
                        break;
                    }
                }
                if (primaryExpressionParent.jjtGetParent() instanceof ASTSynchronizedStatement) {
                    // This usage is directly in an expression of a
                    // synchronized block
                    violation = false;
                    // Optimization
                    break;
                }
                if (location.getFirstParentOfType(ASTLambdaExpression.class) != null) {
                    // This usage is inside a lambda expression
                    violation = false;
                    // Optimization
                    break;
                }
                Node method = location.getFirstParentOfType(ASTMethodDeclaration.class);
                if (method == null) {
                    method = location.getFirstParentOfType(ASTConstructorDeclaration.class);
                    if (method == null) {
                        method = location.getFirstParentOfType(ASTInitializer.class);
                        if (method == null) {
                            continue;
                        }
                    }
                }
                if (decl == null) {
                    decl = method;
                    continue;
                } else if (decl != method && // handle inner classes
                decl.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class) == method.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class)) {
                    violation = false;
                    // Optimization
                    break;
                }
            }
            if (violation && !usages.isEmpty()) {
                addViolation(data, node, new Object[] { declaration.getImage() });
            }
        }
    }
    return data;
}
Also used : ASTConstructorDeclaration(net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration) Node(net.sourceforge.pmd.lang.ast.Node) ASTIfStatement(net.sourceforge.pmd.lang.java.ast.ASTIfStatement) ASTPrimaryExpression(net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression) ASTSynchronizedStatement(net.sourceforge.pmd.lang.java.ast.ASTSynchronizedStatement) ASTInitializer(net.sourceforge.pmd.lang.java.ast.ASTInitializer) ASTStatementExpression(net.sourceforge.pmd.lang.java.ast.ASTStatementExpression) ASTLambdaExpression(net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression) ASTClassOrInterfaceDeclaration(net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration) ASTVariableDeclaratorId(net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId) ASTVariableDeclarator(net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator) NameOccurrence(net.sourceforge.pmd.lang.symboltable.NameOccurrence)

Example 30 with NameOccurrence

use of net.sourceforge.pmd.lang.symboltable.NameOccurrence in project pmd by pmd.

the class PreserveStackTraceRule method visit.

@Override
public Object visit(ASTCatchStatement catchStmt, Object data) {
    String target = catchStmt.jjtGetChild(0).findChildrenOfType(ASTVariableDeclaratorId.class).get(0).getImage();
    // Inspect all the throw stmt inside the catch stmt
    List<ASTThrowStatement> lstThrowStatements = catchStmt.findDescendantsOfType(ASTThrowStatement.class);
    for (ASTThrowStatement throwStatement : lstThrowStatements) {
        Node n = throwStatement.jjtGetChild(0).jjtGetChild(0);
        if (n instanceof ASTCastExpression) {
            ASTPrimaryExpression expr = (ASTPrimaryExpression) n.jjtGetChild(1);
            if (expr.jjtGetNumChildren() > 1 && expr.jjtGetChild(1) instanceof ASTPrimaryPrefix) {
                RuleContext ctx = (RuleContext) data;
                addViolation(ctx, throwStatement);
            }
            continue;
        }
        // Retrieve all argument for the throw exception (to see if the
        // original exception is preserved)
        ASTArgumentList args = throwStatement.getFirstDescendantOfType(ASTArgumentList.class);
        if (args != null) {
            Node parent = args.jjtGetParent().jjtGetParent();
            if (parent instanceof ASTAllocationExpression) {
                // maybe it is used inside a anonymous class
                ck(data, target, throwStatement, parent);
            } else {
                // Check all arguments used in the throw statement
                ck(data, target, throwStatement, throwStatement);
            }
        } else {
            Node child = throwStatement.jjtGetChild(0);
            while (child != null && child.jjtGetNumChildren() > 0 && !(child instanceof ASTName)) {
                child = child.jjtGetChild(0);
            }
            if (child != null) {
                if (child instanceof ASTName && !target.equals(child.getImage()) && !child.hasImageEqualTo(target + FILL_IN_STACKTRACE)) {
                    Map<VariableNameDeclaration, List<NameOccurrence>> vars = ((ASTName) child).getScope().getDeclarations(VariableNameDeclaration.class);
                    for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry : vars.entrySet()) {
                        VariableNameDeclaration decl = entry.getKey();
                        List<NameOccurrence> occurrences = entry.getValue();
                        if (decl.getImage().equals(child.getImage())) {
                            if (!isInitCauseCalled(target, occurrences)) {
                                // Check how the variable is initialized
                                ASTVariableInitializer initializer = decl.getNode().jjtGetParent().getFirstDescendantOfType(ASTVariableInitializer.class);
                                if (initializer != null) {
                                    args = initializer.getFirstDescendantOfType(ASTArgumentList.class);
                                    if (args != null) {
                                        // constructor with args?
                                        ck(data, target, throwStatement, args);
                                    } else if (!isFillInStackTraceCalled(target, initializer)) {
                                        addViolation(data, throwStatement);
                                    }
                                }
                            }
                        }
                    }
                } else if (child instanceof ASTClassOrInterfaceType) {
                    addViolation(data, throwStatement);
                }
            }
        }
    }
    return super.visit(catchStmt, data);
}
Also used : ASTPrimaryPrefix(net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix) ASTCastExpression(net.sourceforge.pmd.lang.java.ast.ASTCastExpression) RuleContext(net.sourceforge.pmd.RuleContext) VariableNameDeclaration(net.sourceforge.pmd.lang.java.symboltable.VariableNameDeclaration) ASTVariableInitializer(net.sourceforge.pmd.lang.java.ast.ASTVariableInitializer) Node(net.sourceforge.pmd.lang.ast.Node) ASTPrimaryExpression(net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression) ASTAllocationExpression(net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression) ASTClassOrInterfaceType(net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType) ASTArgumentList(net.sourceforge.pmd.lang.java.ast.ASTArgumentList) ASTThrowStatement(net.sourceforge.pmd.lang.java.ast.ASTThrowStatement) ASTName(net.sourceforge.pmd.lang.java.ast.ASTName) ASTArgumentList(net.sourceforge.pmd.lang.java.ast.ASTArgumentList) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) NameOccurrence(net.sourceforge.pmd.lang.symboltable.NameOccurrence)

Aggregations

NameOccurrence (net.sourceforge.pmd.lang.symboltable.NameOccurrence)40 Node (net.sourceforge.pmd.lang.ast.Node)20 List (java.util.List)19 Map (java.util.Map)15 NameDeclaration (net.sourceforge.pmd.lang.symboltable.NameDeclaration)13 JavaNameOccurrence (net.sourceforge.pmd.lang.java.symboltable.JavaNameOccurrence)10 Test (org.junit.Test)10 ASTVariableDeclaratorId (net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId)9 ASTName (net.sourceforge.pmd.lang.java.ast.ASTName)8 VariableNameDeclaration (net.sourceforge.pmd.lang.java.symboltable.VariableNameDeclaration)8 ArrayList (java.util.ArrayList)7 ASTMethodDeclaration (net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration)7 ASTPrimaryExpression (net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression)7 ASTArgumentList (net.sourceforge.pmd.lang.java.ast.ASTArgumentList)4 Scope (net.sourceforge.pmd.lang.symboltable.Scope)4 HashSet (java.util.HashSet)3 ASTClassOrInterfaceDeclaration (net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration)3 ASTClassOrInterfaceType (net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType)3 ASTConstructorDeclaration (net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration)3 ASTStatementExpression (net.sourceforge.pmd.lang.java.ast.ASTStatementExpression)3