Search in sources :

Example 21 with ASTVariableDeclaratorId

use of net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId 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 22 with ASTVariableDeclaratorId

use of net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId 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 23 with ASTVariableDeclaratorId

use of net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId 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 24 with ASTVariableDeclaratorId

use of net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId in project pmd by pmd.

the class UselessOverridingMethodRule method visit.

@Override
public Object visit(ASTMethodDeclaration node, Object data) {
    // them.
    if (node.isAbstract() || node.isFinal() || node.isNative() || node.isSynchronized()) {
        return super.visit(node, data);
    }
    // implement them anyway ( see bug 1522517)
    if (CLONE.equals(node.getMethodName()) && node.isPublic() && !this.hasArguments(node) && this.isMethodType(node, OBJECT) && this.isMethodThrowingType(node, exceptions)) {
        return super.visit(node, data);
    }
    ASTBlock block = node.getBlock();
    if (block == null) {
        return super.visit(node, data);
    }
    // Only process functions with one BlockStatement
    if (block.jjtGetNumChildren() != 1 || block.findDescendantsOfType(ASTStatement.class).size() != 1) {
        return super.visit(node, data);
    }
    Node statement = block.jjtGetChild(0).jjtGetChild(0);
    if (statement.jjtGetChild(0).jjtGetNumChildren() == 0) {
        // skips empty return statements
        return data;
    }
    Node statementGrandChild = statement.jjtGetChild(0).jjtGetChild(0);
    ASTPrimaryExpression primaryExpression;
    if (statementGrandChild instanceof ASTPrimaryExpression) {
        primaryExpression = (ASTPrimaryExpression) statementGrandChild;
    } else {
        List<ASTPrimaryExpression> primaryExpressions = findFirstDegreeChildrenOfType(statementGrandChild, ASTPrimaryExpression.class);
        if (primaryExpressions.size() != 1) {
            return super.visit(node, data);
        }
        primaryExpression = primaryExpressions.get(0);
    }
    ASTPrimaryPrefix primaryPrefix = findFirstDegreeChildrenOfType(primaryExpression, ASTPrimaryPrefix.class).get(0);
    if (!primaryPrefix.usesSuperModifier()) {
        return super.visit(node, data);
    }
    List<ASTPrimarySuffix> primarySuffixList = findFirstDegreeChildrenOfType(primaryExpression, ASTPrimarySuffix.class);
    if (primarySuffixList.size() != 2) {
        // extra method call on result of super method
        return super.visit(node, data);
    }
    ASTMethodDeclarator methodDeclarator = findFirstDegreeChildrenOfType(node, ASTMethodDeclarator.class).get(0);
    ASTPrimarySuffix primarySuffix = primarySuffixList.get(0);
    if (!primarySuffix.hasImageEqualTo(methodDeclarator.getImage())) {
        return super.visit(node, data);
    }
    // Process arguments
    primarySuffix = primarySuffixList.get(1);
    ASTArguments arguments = (ASTArguments) primarySuffix.jjtGetChild(0);
    ASTFormalParameters formalParameters = (ASTFormalParameters) methodDeclarator.jjtGetChild(0);
    if (formalParameters.jjtGetNumChildren() != arguments.jjtGetNumChildren()) {
        return super.visit(node, data);
    }
    if (!ignoreAnnotations) {
        ASTClassOrInterfaceBodyDeclaration parent = (ASTClassOrInterfaceBodyDeclaration) node.jjtGetParent();
        for (int i = 0; i < parent.jjtGetNumChildren(); i++) {
            Node n = parent.jjtGetChild(i);
            if (n instanceof ASTAnnotation) {
                if (n.jjtGetChild(0) instanceof ASTMarkerAnnotation) {
                    // @Override is ignored
                    if ("Override".equals(((ASTName) n.jjtGetChild(0).jjtGetChild(0)).getImage())) {
                        continue;
                    }
                }
                return super.visit(node, data);
            }
        }
    }
    if (arguments.jjtGetNumChildren() == 0) {
        addViolation(data, node, getMessage());
    } else {
        ASTArgumentList argumentList = (ASTArgumentList) arguments.jjtGetChild(0);
        for (int i = 0; i < argumentList.jjtGetNumChildren(); i++) {
            Node expressionChild = argumentList.jjtGetChild(i).jjtGetChild(0);
            if (!(expressionChild instanceof ASTPrimaryExpression) || expressionChild.jjtGetNumChildren() != 1) {
                // The arguments are not simply passed through
                return super.visit(node, data);
            }
            ASTPrimaryExpression argumentPrimaryExpression = (ASTPrimaryExpression) expressionChild;
            ASTPrimaryPrefix argumentPrimaryPrefix = (ASTPrimaryPrefix) argumentPrimaryExpression.jjtGetChild(0);
            if (argumentPrimaryPrefix.jjtGetNumChildren() == 0) {
                // The arguments are not simply passed through (using "this" for instance)
                return super.visit(node, data);
            }
            Node argumentPrimaryPrefixChild = argumentPrimaryPrefix.jjtGetChild(0);
            if (!(argumentPrimaryPrefixChild instanceof ASTName)) {
                // The arguments are not simply passed through
                return super.visit(node, data);
            }
            if (formalParameters.jjtGetNumChildren() < i + 1) {
                // different number of args
                return super.visit(node, data);
            }
            ASTName argumentName = (ASTName) argumentPrimaryPrefixChild;
            ASTFormalParameter formalParameter = (ASTFormalParameter) formalParameters.jjtGetChild(i);
            ASTVariableDeclaratorId variableId = findFirstDegreeChildrenOfType(formalParameter, ASTVariableDeclaratorId.class).get(0);
            if (!argumentName.hasImageEqualTo(variableId.getImage())) {
                // The arguments are not simply passed through
                return super.visit(node, data);
            }
        }
        // All arguments are passed through directly
        addViolation(data, node, getMessage());
    }
    return super.visit(node, data);
}
Also used : ASTPrimaryPrefix(net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix) Node(net.sourceforge.pmd.lang.ast.Node) ASTFormalParameters(net.sourceforge.pmd.lang.java.ast.ASTFormalParameters) ASTPrimaryExpression(net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression) ASTArguments(net.sourceforge.pmd.lang.java.ast.ASTArguments) ASTClassOrInterfaceBodyDeclaration(net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceBodyDeclaration) ASTFormalParameter(net.sourceforge.pmd.lang.java.ast.ASTFormalParameter) ASTPrimarySuffix(net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix) ASTMarkerAnnotation(net.sourceforge.pmd.lang.java.ast.ASTMarkerAnnotation) ASTStatement(net.sourceforge.pmd.lang.java.ast.ASTStatement) ASTArgumentList(net.sourceforge.pmd.lang.java.ast.ASTArgumentList) ASTMethodDeclarator(net.sourceforge.pmd.lang.java.ast.ASTMethodDeclarator) ASTVariableDeclaratorId(net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId) ASTBlock(net.sourceforge.pmd.lang.java.ast.ASTBlock) ASTName(net.sourceforge.pmd.lang.java.ast.ASTName) ASTAnnotation(net.sourceforge.pmd.lang.java.ast.ASTAnnotation)

Example 25 with ASTVariableDeclaratorId

use of net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId in project pmd by pmd.

the class ClassTypeResolverTest method testFullyQualifiedType.

/**
 * The type should be filled also on the ASTVariableDeclaratorId node, not
 * only on the variable name declaration.
 */
@Test
public void testFullyQualifiedType() {
    String source = "public class Foo {\n" + "    public void bar() {\n" + "        java.util.StringTokenizer st = new StringTokenizer(\"a.b.c.d\", \".\");\n" + "        while (st.hasMoreTokens()) {\n" + "            System.out.println(st.nextToken());\n" + "        }\n" + "    }\n" + "}";
    ASTCompilationUnit acu = parseAndTypeResolveForString(source, "1.5");
    List<ASTName> names = acu.findDescendantsOfType(ASTName.class);
    ASTName theStringTokenizer = null;
    for (ASTName name : names) {
        if (name.hasImageEqualTo("st.hasMoreTokens")) {
            theStringTokenizer = name;
            break;
        }
    }
    Assert.assertNotNull(theStringTokenizer);
    VariableNameDeclaration declaration = (VariableNameDeclaration) theStringTokenizer.getNameDeclaration();
    Assert.assertNotNull(declaration);
    Assert.assertEquals("java.util.StringTokenizer", declaration.getTypeImage());
    Assert.assertNotNull(declaration.getType());
    Assert.assertSame(StringTokenizer.class, declaration.getType());
    ASTVariableDeclaratorId id = (ASTVariableDeclaratorId) declaration.getNode();
    Assert.assertNotNull(id.getType());
    Assert.assertSame(StringTokenizer.class, id.getType());
}
Also used : ASTCompilationUnit(net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit) VariableNameDeclaration(net.sourceforge.pmd.lang.java.symboltable.VariableNameDeclaration) ASTVariableDeclaratorId(net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId) ASTName(net.sourceforge.pmd.lang.java.ast.ASTName) Test(org.junit.Test)

Aggregations

ASTVariableDeclaratorId (net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId)28 Test (org.junit.Test)13 Node (net.sourceforge.pmd.lang.ast.Node)10 NameOccurrence (net.sourceforge.pmd.lang.symboltable.NameOccurrence)9 ASTType (net.sourceforge.pmd.lang.java.ast.ASTType)6 NameDeclaration (net.sourceforge.pmd.lang.symboltable.NameDeclaration)6 ASTClassOrInterfaceType (net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType)5 ASTName (net.sourceforge.pmd.lang.java.ast.ASTName)5 ASTFormalParameter (net.sourceforge.pmd.lang.java.ast.ASTFormalParameter)4 ASTPrimaryExpression (net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression)4 List (java.util.List)3 ASTStatementExpression (net.sourceforge.pmd.lang.java.ast.ASTStatementExpression)3 ASTVariableDeclarator (net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator)3 ArrayList (java.util.ArrayList)2 ASTConstructorDeclaration (net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration)2 ASTExpression (net.sourceforge.pmd.lang.java.ast.ASTExpression)2 ASTFormalParameters (net.sourceforge.pmd.lang.java.ast.ASTFormalParameters)2 ASTLocalVariableDeclaration (net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration)2 ASTMethodDeclaration (net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration)2 ASTMethodDeclarator (net.sourceforge.pmd.lang.java.ast.ASTMethodDeclarator)2