01: package org.acm.seguin.pmd.rules;
02:
03: import org.acm.seguin.pmd.AbstractRule;
04: import org.acm.seguin.pmd.Rule;
05: import org.acm.seguin.pmd.RuleContext;
06: import net.sourceforge.jrefactory.ast.ASTAllocationExpression;
07: import net.sourceforge.jrefactory.ast.ASTName;
08: import net.sourceforge.jrefactory.ast.ASTPrimaryExpression;
09: import net.sourceforge.jrefactory.ast.ASTPrimarySuffix;
10: import net.sourceforge.jrefactory.ast.SimpleNode;
11:
12: import java.util.HashSet;
13: import java.util.Set;
14:
15: public class UnnecessaryConversionTemporaryRule extends AbstractRule
16: implements Rule {
17:
18: private boolean inPrimaryExpressionContext;
19: private boolean usingPrimitiveWrapperAllocation;
20: private Set primitiveWrappers = new HashSet();
21:
22: public UnnecessaryConversionTemporaryRule() {
23: primitiveWrappers.add("Integer");
24: primitiveWrappers.add("Boolean");
25: primitiveWrappers.add("Double");
26: primitiveWrappers.add("Long");
27: primitiveWrappers.add("Short");
28: primitiveWrappers.add("Byte");
29: primitiveWrappers.add("Float");
30: }
31:
32: public Object visit(ASTPrimaryExpression node, Object data) {
33: if (node.jjtGetNumChildren() == 0
34: || (node.jjtGetFirstChild()).jjtGetNumChildren() == 0
35: || !(node.jjtGetFirstChild().jjtGetFirstChild() instanceof ASTAllocationExpression)) {
36: return super .visit(node, data);
37: }
38: // TODO... hmmm... is this inPrimaryExpressionContext gibberish necessary?
39: inPrimaryExpressionContext = true;
40: Object report = super .visit(node, data);
41: inPrimaryExpressionContext = false;
42: usingPrimitiveWrapperAllocation = false;
43: return report;
44: }
45:
46: public Object visit(ASTAllocationExpression node, Object data) {
47: if (!inPrimaryExpressionContext
48: || !(node.jjtGetFirstChild() instanceof ASTName)) {
49: return super .visit(node, data);
50: }
51: if (!primitiveWrappers.contains(((SimpleNode) node
52: .jjtGetFirstChild()).getImage())) {
53: return super .visit(node, data);
54: }
55: usingPrimitiveWrapperAllocation = true;
56: return super .visit(node, data);
57: }
58:
59: public Object visit(ASTPrimarySuffix node, Object data) {
60: if (!inPrimaryExpressionContext
61: || !usingPrimitiveWrapperAllocation) {
62: return super .visit(node, data);
63: }
64: if (node.getImage() != null
65: && node.getImage().equals("toString")) {
66: RuleContext ctx = (RuleContext) data;
67: ctx.getReport().addRuleViolation(
68: createRuleViolation(ctx, node.getBeginLine()));
69: }
70: return super.visit(node, data);
71: }
72:
73: }
|