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