1 package net.sourceforge.pmd.rules;
2
3 import net.sourceforge.pmd.AbstractRule;
4 import net.sourceforge.pmd.Rule;
5 import net.sourceforge.pmd.RuleContext;
6 import net.sourceforge.pmd.ast.ASTAllocationExpression;
7 import net.sourceforge.pmd.ast.ASTName;
8 import net.sourceforge.pmd.ast.ASTPrimaryExpression;
9 import net.sourceforge.pmd.ast.ASTPrimarySuffix;
10 import net.sourceforge.pmd.ast.SimpleNode;
11
12 import java.util.HashSet;
13 import java.util.Set;
14
15 public class UnnecessaryConversionTemporaryRule extends AbstractRule implements Rule {
16
17 private boolean inPrimaryExpressionContext;
18 private boolean usingPrimitiveWrapperAllocation;
19 private Set primitiveWrappers = new HashSet();
20
21 public UnnecessaryConversionTemporaryRule() {
22 primitiveWrappers.add("Integer");
23 primitiveWrappers.add("Boolean");
24 primitiveWrappers.add("Double");
25 primitiveWrappers.add("Long");
26 primitiveWrappers.add("Short");
27 primitiveWrappers.add("Byte");
28 primitiveWrappers.add("Float");
29 }
30
31 public Object visit(ASTPrimaryExpression node, Object data) {
32 if (node.jjtGetNumChildren() == 0 || (node.jjtGetChild(0)).jjtGetNumChildren() == 0 || !(node.jjtGetChild(0).jjtGetChild(0) instanceof ASTAllocationExpression)) {
33 return super.visit(node, data);
34 }
35 // TODO... hmmm... is this inPrimaryExpressionContext gibberish necessary?
36 inPrimaryExpressionContext = true;
37 Object report = super.visit(node, data);
38 inPrimaryExpressionContext = false;
39 usingPrimitiveWrapperAllocation = false;
40 return report;
41 }
42
43 public Object visit(ASTAllocationExpression node, Object data) {
44 if (!inPrimaryExpressionContext || !(node.jjtGetChild(0) instanceof ASTName)) {
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 return super.visit(node, data);
57 }
58 if (node.getImage() != null && node.getImage().equals("toString")) {
59 RuleContext ctx = (RuleContext) data;
60 ctx.getReport().addRuleViolation(createRuleViolation(ctx, node.getBeginLine()));
61 }
62 return super.visit(node, data);
63 }
64
65 }
This page was automatically generated by Maven