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