View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.java.rule.basic;
5   
6   import java.math.BigDecimal;
7   import java.math.BigInteger;
8   
9   import net.sourceforge.pmd.RuleContext;
10  import net.sourceforge.pmd.lang.LanguageVersion;
11  import net.sourceforge.pmd.lang.ast.Node;
12  import net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression;
13  import net.sourceforge.pmd.lang.java.ast.ASTArguments;
14  import net.sourceforge.pmd.lang.java.ast.ASTArrayDimsAndInits;
15  import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType;
16  import net.sourceforge.pmd.lang.java.ast.ASTLiteral;
17  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
18  import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper;
19  
20  /**
21   * Rule that marks instantiations of new {@link BigInteger} or {@link BigDecimal} objects,
22   * when there is a well-known constant available, such as {@link BigInteger#ZERO}.
23   */
24  public class BigIntegerInstantiationRule extends AbstractJavaRule {
25  
26      @Override
27      public Object visit(ASTAllocationExpression node, Object data) {
28          Node type = node.jjtGetChild(0);
29  
30          if (!(type instanceof ASTClassOrInterfaceType)) {
31              return super.visit(node, data);
32          }
33  
34          boolean jdk15 = ((RuleContext) data).getLanguageVersion().compareTo(LanguageVersion.JAVA_15) >= 0;
35          if ((TypeHelper.isA((ASTClassOrInterfaceType) type, BigInteger.class) || jdk15 && TypeHelper.isA((ASTClassOrInterfaceType) type, BigDecimal.class)) &&
36                  !node.hasDescendantOfType(ASTArrayDimsAndInits.class)
37          ) {
38              ASTArguments args = node.getFirstChildOfType(ASTArguments.class);
39              if (args.getArgumentCount() == 1) {
40                  ASTLiteral literal = node.getFirstDescendantOfType(ASTLiteral.class);
41                  if (literal == null || literal.jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent() != args) {
42                      return super.visit(node, data);
43                  }
44  
45                  String img = literal.getImage();
46                  if (literal.isStringLiteral()) {
47                      img = img.substring(1, img.length() - 1);
48                  }
49  
50                  if ("0".equals(img) || "1".equals(img) || jdk15 && "10".equals(img)) {
51                      addViolation(data, node);
52                      return data;
53                  }
54              }
55          }
56          return super.visit(node, data);
57      }
58  
59  }