Search in sources :

Example 1 with ASTClassOrInterfaceType

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

the class ClassTypeResolverTest method testInnerClassNotCompiled.

/**
 * If we don't have the auxclasspath, we might not find the inner class. In
 * that case, we'll need to search by name for a match.
 *
 * @throws Exception
 */
@Test
public void testInnerClassNotCompiled() throws Exception {
    Node acu = parseAndTypeResolveForString("public class TestInnerClass {\n" + "    public void foo() {\n" + "        Statement statement = new Statement();\n" + "    " + "}\n" + "    static class Statement {\n" + "    }\n" + "}", "1.8");
    ASTClassOrInterfaceType statement = acu.getFirstDescendantOfType(ASTClassOrInterfaceType.class);
    Assert.assertTrue(statement.isReferenceToClassSameCompilationUnit());
}
Also used : TypeNode(net.sourceforge.pmd.lang.java.ast.TypeNode) Node(net.sourceforge.pmd.lang.ast.Node) AbstractJavaNode(net.sourceforge.pmd.lang.java.ast.AbstractJavaNode) AbstractJavaTypeNode(net.sourceforge.pmd.lang.java.ast.AbstractJavaTypeNode) ASTClassOrInterfaceType(net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType) Test(org.junit.Test)

Example 2 with ASTClassOrInterfaceType

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

the class StringInstantiationRule method visit.

@Override
public Object visit(ASTAllocationExpression node, Object data) {
    if (!(node.jjtGetChild(0) instanceof ASTClassOrInterfaceType)) {
        return data;
    }
    if (!TypeHelper.isA((ASTClassOrInterfaceType) node.jjtGetChild(0), String.class)) {
        return data;
    }
    List<ASTExpression> exp = node.findDescendantsOfType(ASTExpression.class);
    if (exp.size() >= 2) {
        return data;
    }
    if (node.hasDescendantOfAnyType(ASTArrayDimsAndInits.class, ASTAdditiveExpression.class)) {
        return data;
    }
    ASTName name = node.getFirstDescendantOfType(ASTName.class);
    // Literal, i.e., new String("foo")
    if (name == null) {
        addViolation(data, node);
        return data;
    }
    NameDeclaration nd = name.getNameDeclaration();
    if (nd == null) {
        return data;
    }
    if (nd instanceof TypedNameDeclaration && TypeHelper.isA((TypedNameDeclaration) nd, String.class)) {
        addViolation(data, node);
    }
    return data;
}
Also used : ASTName(net.sourceforge.pmd.lang.java.ast.ASTName) NameDeclaration(net.sourceforge.pmd.lang.symboltable.NameDeclaration) TypedNameDeclaration(net.sourceforge.pmd.lang.java.symboltable.TypedNameDeclaration) TypedNameDeclaration(net.sourceforge.pmd.lang.java.symboltable.TypedNameDeclaration) ASTClassOrInterfaceType(net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType) ASTExpression(net.sourceforge.pmd.lang.java.ast.ASTExpression)

Example 3 with ASTClassOrInterfaceType

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

the class CloseResourceRule method checkForResources.

private void checkForResources(Node node, Object data) {
    List<ASTLocalVariableDeclaration> vars = node.findDescendantsOfType(ASTLocalVariableDeclaration.class);
    List<ASTVariableDeclaratorId> ids = new ArrayList<>();
    // find all variable references to Connection objects
    for (ASTLocalVariableDeclaration var : vars) {
        ASTType type = var.getTypeNode();
        if (type.jjtGetChild(0) instanceof ASTReferenceType) {
            ASTReferenceType ref = (ASTReferenceType) type.jjtGetChild(0);
            if (ref.jjtGetChild(0) instanceof ASTClassOrInterfaceType) {
                ASTClassOrInterfaceType clazz = (ASTClassOrInterfaceType) ref.jjtGetChild(0);
                if (clazz.getType() != null && types.contains(clazz.getType().getName()) || clazz.getType() == null && simpleTypes.contains(toSimpleType(clazz.getImage())) && !clazz.isReferenceToClassSameCompilationUnit() || types.contains(clazz.getImage()) && !clazz.isReferenceToClassSameCompilationUnit()) {
                    ASTVariableDeclaratorId id = var.getFirstDescendantOfType(ASTVariableDeclaratorId.class);
                    ids.add(id);
                }
            }
        }
    }
    // if there are connections, ensure each is closed.
    for (ASTVariableDeclaratorId x : ids) {
        ensureClosed((ASTLocalVariableDeclaration) x.jjtGetParent().jjtGetParent(), x, data);
    }
}
Also used : ASTType(net.sourceforge.pmd.lang.java.ast.ASTType) ASTVariableDeclaratorId(net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId) ASTLocalVariableDeclaration(net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration) ArrayList(java.util.ArrayList) ASTReferenceType(net.sourceforge.pmd.lang.java.ast.ASTReferenceType) ASTClassOrInterfaceType(net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType)

Example 4 with ASTClassOrInterfaceType

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

the class CloseResourceRule method ensureClosed.

private void ensureClosed(ASTLocalVariableDeclaration var, ASTVariableDeclaratorId id, Object data) {
    // What are the chances of a Connection being instantiated in a
    // for-loop init block? Anyway, I'm lazy!
    String variableToClose = id.getImage();
    Node n = var;
    while (!(n instanceof ASTBlock) && !(n instanceof ASTConstructorDeclaration)) {
        n = n.jjtGetParent();
    }
    Node top = n;
    List<ASTTryStatement> tryblocks = top.findDescendantsOfType(ASTTryStatement.class);
    boolean closed = false;
    ASTBlockStatement parentBlock = id.getFirstParentOfType(ASTBlockStatement.class);
    // block.
    for (ASTTryStatement t : tryblocks) {
        // verifies that there are no critical statements between the
        // variable declaration and
        // the beginning of the try block.
        ASTBlockStatement tryBlock = t.getFirstParentOfType(ASTBlockStatement.class);
        // the variable has been initialized with null
        if (!hasNullInitializer(var) && parentBlock.jjtGetParent() == tryBlock.jjtGetParent()) {
            List<ASTBlockStatement> blocks = parentBlock.jjtGetParent().findChildrenOfType(ASTBlockStatement.class);
            int parentBlockIndex = blocks.indexOf(parentBlock);
            int tryBlockIndex = blocks.indexOf(tryBlock);
            boolean criticalStatements = false;
            for (int i = parentBlockIndex + 1; i < tryBlockIndex; i++) {
                // assume variable declarations are not critical
                ASTLocalVariableDeclaration varDecl = blocks.get(i).getFirstDescendantOfType(ASTLocalVariableDeclaration.class);
                if (varDecl == null) {
                    criticalStatements = true;
                    break;
                }
            }
            if (criticalStatements) {
                break;
            }
        }
        if (t.getBeginLine() > id.getBeginLine() && t.hasFinally()) {
            ASTBlock f = (ASTBlock) t.getFinally().jjtGetChild(0);
            List<ASTName> names = f.findDescendantsOfType(ASTName.class);
            for (ASTName oName : names) {
                String name = oName.getImage();
                if (name != null && name.contains(".")) {
                    String[] parts = name.split("\\.");
                    if (parts.length == 2) {
                        String methodName = parts[1];
                        String varName = parts[0];
                        if (varName.equals(variableToClose) && closeTargets.contains(methodName) && nullCheckIfCondition(f, oName, varName)) {
                            closed = true;
                            break;
                        }
                    }
                }
            }
            if (closed) {
                break;
            }
            List<ASTStatementExpression> exprs = new ArrayList<>();
            f.findDescendantsOfType(ASTStatementExpression.class, exprs, true);
            for (ASTStatementExpression stmt : exprs) {
                ASTPrimaryExpression expr = stmt.getFirstChildOfType(ASTPrimaryExpression.class);
                if (expr != null) {
                    ASTPrimaryPrefix prefix = expr.getFirstChildOfType(ASTPrimaryPrefix.class);
                    ASTPrimarySuffix suffix = expr.getFirstChildOfType(ASTPrimarySuffix.class);
                    if (prefix != null && suffix != null) {
                        if (prefix.getImage() == null) {
                            ASTName prefixName = prefix.getFirstChildOfType(ASTName.class);
                            if (prefixName != null && closeTargets.contains(prefixName.getImage())) {
                                // Found a call to a "close target" that is
                                // a direct
                                // method call without a "ClassName."
                                // prefix.
                                closed = variableIsPassedToMethod(expr, variableToClose);
                                if (closed) {
                                    break;
                                }
                            }
                        } else if (suffix.getImage() != null) {
                            String prefixPlusSuffix = prefix.getImage() + "." + suffix.getImage();
                            if (closeTargets.contains(prefixPlusSuffix)) {
                                // Found a call to a "close target" that is
                                // a method call
                                // in the form "ClassName.methodName".
                                closed = variableIsPassedToMethod(expr, variableToClose);
                                if (closed) {
                                    break;
                                }
                            }
                        }
                        // really check it.
                        if (!closed) {
                            List<ASTPrimarySuffix> suffixes = new ArrayList<>();
                            expr.findDescendantsOfType(ASTPrimarySuffix.class, suffixes, true);
                            for (ASTPrimarySuffix oSuffix : suffixes) {
                                String suff = oSuffix.getImage();
                                if (closeTargets.contains(suff)) {
                                    closed = variableIsPassedToMethod(expr, variableToClose);
                                    if (closed) {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (closed) {
                break;
            }
        }
    }
    if (!closed) {
        // See if the variable is returned by the method, which means the
        // method is a utility for creating the db resource, which means of
        // course it can't be closed by the method, so it isn't an error.
        List<ASTReturnStatement> returns = new ArrayList<>();
        top.findDescendantsOfType(ASTReturnStatement.class, returns, true);
        for (ASTReturnStatement returnStatement : returns) {
            ASTName name = returnStatement.getFirstDescendantOfType(ASTName.class);
            if (name != null && name.getImage().equals(variableToClose)) {
                closed = true;
                break;
            }
        }
    }
    // if all is not well, complain
    if (!closed) {
        ASTType type = var.getFirstChildOfType(ASTType.class);
        ASTReferenceType ref = (ASTReferenceType) type.jjtGetChild(0);
        ASTClassOrInterfaceType clazz = (ASTClassOrInterfaceType) ref.jjtGetChild(0);
        addViolation(data, id, clazz.getImage());
    }
}
Also used : ASTConstructorDeclaration(net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration) ASTLocalVariableDeclaration(net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration) Node(net.sourceforge.pmd.lang.ast.Node) ArrayList(java.util.ArrayList) ASTStatementExpression(net.sourceforge.pmd.lang.java.ast.ASTStatementExpression) ASTClassOrInterfaceType(net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType) ASTName(net.sourceforge.pmd.lang.java.ast.ASTName) ASTBlockStatement(net.sourceforge.pmd.lang.java.ast.ASTBlockStatement) ASTReferenceType(net.sourceforge.pmd.lang.java.ast.ASTReferenceType) ASTPrimaryPrefix(net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix) ASTType(net.sourceforge.pmd.lang.java.ast.ASTType) ASTTryStatement(net.sourceforge.pmd.lang.java.ast.ASTTryStatement) ASTPrimaryExpression(net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression) ASTPrimarySuffix(net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix) ASTBlock(net.sourceforge.pmd.lang.java.ast.ASTBlock) ASTReturnStatement(net.sourceforge.pmd.lang.java.ast.ASTReturnStatement)

Example 5 with ASTClassOrInterfaceType

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

the class BigIntegerInstantiationRule method visit.

@Override
public Object visit(ASTAllocationExpression node, Object data) {
    Node type = node.jjtGetChild(0);
    if (!(type instanceof ASTClassOrInterfaceType)) {
        return super.visit(node, data);
    }
    boolean jdk15 = ((RuleContext) data).getLanguageVersion().compareTo(LanguageRegistry.getLanguage(JavaLanguageModule.NAME).getVersion("1.5")) >= 0;
    if ((TypeHelper.isA((ASTClassOrInterfaceType) type, BigInteger.class) || jdk15 && TypeHelper.isA((ASTClassOrInterfaceType) type, BigDecimal.class)) && !node.hasDescendantOfType(ASTArrayDimsAndInits.class)) {
        ASTArguments args = node.getFirstChildOfType(ASTArguments.class);
        if (args.getArgumentCount() == 1) {
            ASTLiteral literal = node.getFirstDescendantOfType(ASTLiteral.class);
            if (literal == null || literal.jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent() != args) {
                return super.visit(node, data);
            }
            String img = literal.getImage();
            if (literal.isStringLiteral()) {
                img = img.substring(1, img.length() - 1);
            }
            if ("0".equals(img) || "1".equals(img) || jdk15 && "10".equals(img)) {
                addViolation(data, node);
                return data;
            }
        }
    }
    return super.visit(node, data);
}
Also used : RuleContext(net.sourceforge.pmd.RuleContext) Node(net.sourceforge.pmd.lang.ast.Node) BigInteger(java.math.BigInteger) ASTArguments(net.sourceforge.pmd.lang.java.ast.ASTArguments) ASTLiteral(net.sourceforge.pmd.lang.java.ast.ASTLiteral) ASTClassOrInterfaceType(net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType)

Aggregations

ASTClassOrInterfaceType (net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType)25 Node (net.sourceforge.pmd.lang.ast.Node)13 ASTName (net.sourceforge.pmd.lang.java.ast.ASTName)7 ASTType (net.sourceforge.pmd.lang.java.ast.ASTType)7 ASTExtendsList (net.sourceforge.pmd.lang.java.ast.ASTExtendsList)5 ASTImplementsList (net.sourceforge.pmd.lang.java.ast.ASTImplementsList)5 ASTVariableDeclaratorId (net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId)5 ArrayList (java.util.ArrayList)4 ASTMethodDeclaration (net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration)4 ASTReferenceType (net.sourceforge.pmd.lang.java.ast.ASTReferenceType)4 List (java.util.List)3 ASTAllocationExpression (net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression)3 ASTClassOrInterfaceDeclaration (net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration)3 ASTConstructorDeclaration (net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration)3 ASTFormalParameter (net.sourceforge.pmd.lang.java.ast.ASTFormalParameter)3 ASTPrimaryPrefix (net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix)3 NameOccurrence (net.sourceforge.pmd.lang.symboltable.NameOccurrence)3 Map (java.util.Map)2 RuleContext (net.sourceforge.pmd.RuleContext)2 ASTArgumentList (net.sourceforge.pmd.lang.java.ast.ASTArgumentList)2