01 /**
02 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03 */
04 package net.sourceforge.pmd.lang.java.rule.unnecessary;
05
06 import java.util.Set;
07
08 import net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression;
09 import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType;
10 import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
11 import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix;
12 import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
13 import net.sourceforge.pmd.util.CollectionUtil;
14
15 public class UnnecessaryConversionTemporaryRule extends AbstractJavaRule {
16
17 private boolean inPrimaryExpressionContext;
18 private ASTPrimaryExpression primary;
19 private boolean usingPrimitiveWrapperAllocation;
20
21 private static final Set<String> PRIMITIVE_WRAPPERS = CollectionUtil.asSet(
22 new String[] {"Integer", "Boolean", "Double", "Long", "Short", "Byte", "Float"}
23 );
24
25 public Object visit(ASTPrimaryExpression node, Object data) {
26 if (node.jjtGetNumChildren() == 0 || (node.jjtGetChild(0)).jjtGetNumChildren() == 0 || !(node.jjtGetChild(0).jjtGetChild(0) instanceof ASTAllocationExpression)) {
27 return super.visit(node, data);
28 }
29 // TODO... hmmm... is this inPrimaryExpressionContext gibberish necessary?
30 inPrimaryExpressionContext = true;
31 primary = node;
32 super.visit(node, data);
33 inPrimaryExpressionContext = false;
34 usingPrimitiveWrapperAllocation = false;
35 return data;
36 }
37
38 public Object visit(ASTAllocationExpression node, Object data) {
39 if (!inPrimaryExpressionContext || !(node.jjtGetChild(0) instanceof ASTClassOrInterfaceType)) {
40 return super.visit(node, data);
41 }
42 if (!PRIMITIVE_WRAPPERS.contains(node.jjtGetChild(0).getImage())) {
43 return super.visit(node, data);
44 }
45 usingPrimitiveWrapperAllocation = true;
46 return super.visit(node, data);
47 }
48
49 public Object visit(ASTPrimarySuffix node, Object data) {
50 if (inPrimaryExpressionContext && usingPrimitiveWrapperAllocation) {
51 if (node.hasImageEqualTo("toString")) {
52 if (node.jjtGetParent() == primary) {
53 addViolation(data, node);
54 }
55 }
56 }
57 return super.visit(node, data);
58 }
59
60 }
|