View Javadoc

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