1 /***
2 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3 */
4 package net.sourceforge.pmd.rules;
5
6 import java.util.Set;
7
8 import net.sourceforge.pmd.AbstractRule;
9 import net.sourceforge.pmd.Rule;
10 import net.sourceforge.pmd.ast.ASTAllocationExpression;
11 import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
12 import net.sourceforge.pmd.ast.ASTPrimaryExpression;
13 import net.sourceforge.pmd.ast.ASTPrimarySuffix;
14 import net.sourceforge.pmd.ast.SimpleNode;
15 import net.sourceforge.pmd.util.CollectionUtil;
16
17 public class UnnecessaryConversionTemporary extends AbstractRule implements Rule {
18
19 private boolean inPrimaryExpressionContext;
20 private ASTPrimaryExpression primary;
21 private boolean usingPrimitiveWrapperAllocation;
22
23 private static final Set primitiveWrappers = CollectionUtil.asSet(
24 new String[] {"Integer", "Boolean", "Double", "Long", "Short", "Byte", "Float"}
25 );
26
27 public UnnecessaryConversionTemporary() {
28 }
29
30 public Object visit(ASTPrimaryExpression node, Object data) {
31 if (node.jjtGetNumChildren() == 0 || (node.jjtGetChild(0)).jjtGetNumChildren() == 0 || !(node.jjtGetChild(0).jjtGetChild(0) instanceof ASTAllocationExpression)) {
32 return super.visit(node, data);
33 }
34
35 inPrimaryExpressionContext = true;
36 primary = node;
37 super.visit(node, data);
38 inPrimaryExpressionContext = false;
39 usingPrimitiveWrapperAllocation = false;
40 return data;
41 }
42
43 public Object visit(ASTAllocationExpression node, Object data) {
44 if (!inPrimaryExpressionContext || !(node.jjtGetChild(0) instanceof ASTClassOrInterfaceType)) {
45 return super.visit(node, data);
46 }
47 if (!primitiveWrappers.contains(((SimpleNode) node.jjtGetChild(0)).getImage())) {
48 return super.visit(node, data);
49 }
50 usingPrimitiveWrapperAllocation = true;
51 return super.visit(node, data);
52 }
53
54 public Object visit(ASTPrimarySuffix node, Object data) {
55 if (inPrimaryExpressionContext && usingPrimitiveWrapperAllocation) {
56 if (node.hasImageEqualTo("toString")) {
57 if (node.jjtGetParent() == primary) {
58 addViolation(data, node);
59 }
60 }
61 }
62 return super.visit(node, data);
63 }
64
65 }