1 package net.sourceforge.pmd.rules.basic;
2
3 import net.sourceforge.pmd.AbstractRule;
4 import net.sourceforge.pmd.RuleContext;
5 import net.sourceforge.pmd.SourceType;
6 import net.sourceforge.pmd.ast.ASTAllocationExpression;
7 import net.sourceforge.pmd.ast.ASTArguments;
8 import net.sourceforge.pmd.ast.ASTArrayDimsAndInits;
9 import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
10 import net.sourceforge.pmd.ast.ASTLiteral;
11 import net.sourceforge.pmd.ast.Node;
12
13 public class BigIntegerInstantiation extends AbstractRule {
14
15 public Object visit(ASTAllocationExpression node, Object data) {
16 Node type = node.jjtGetChild(0);
17
18 if (!(type instanceof ASTClassOrInterfaceType)) {
19 return super.visit(node, data);
20 }
21
22 String img = ((ASTClassOrInterfaceType) type).getImage();
23 if (img.startsWith("java.math.")) {
24 img = img.substring(10);
25 }
26
27 boolean jdk15 = ((RuleContext) data).getSourceType().compareTo(SourceType.JAVA_15) >= 0;
28
29 if (("BigInteger".equals(img) || (jdk15 && "BigDecimal".equals(img))) &&
30 (node.getFirstChildOfType(ASTArrayDimsAndInits.class) == null)
31 ) {
32 ASTArguments args = (ASTArguments) node.getFirstChildOfType(ASTArguments.class);
33 if (args.getArgumentCount() == 1) {
34 ASTLiteral literal = (ASTLiteral) node.getFirstChildOfType(ASTLiteral.class);
35 if (literal == null || literal.jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent() != args) {
36 return super.visit(node, data);
37 }
38
39 img = literal.getImage();
40 if ((img.length() > 2 && img.charAt(0) == '"')) {
41 img = img.substring(1, img.length() - 1);
42 }
43
44 if ("0".equals(img) || "1".equals(img) || (jdk15 && "10".equals(img))) {
45 addViolation(data, node);
46 return data;
47 }
48 }
49 }
50 return super.visit(node, data);
51 }
52
53 }