View Javadoc
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 net.sourceforge.pmd.AbstractRule; 7 import net.sourceforge.pmd.Rule; 8 import net.sourceforge.pmd.RuleContext; 9 import net.sourceforge.pmd.ast.ASTAllocationExpression; 10 import net.sourceforge.pmd.ast.ASTName; 11 import net.sourceforge.pmd.ast.ASTPrimaryExpression; 12 import net.sourceforge.pmd.ast.ASTPrimarySuffix; 13 import net.sourceforge.pmd.ast.SimpleNode; 14 15 import java.util.HashSet; 16 import java.util.Set; 17 18 public class UnnecessaryConversionTemporaryRule extends AbstractRule implements Rule { 19 20 private boolean inPrimaryExpressionContext; 21 private boolean usingPrimitiveWrapperAllocation; 22 private Set primitiveWrappers = new HashSet(); 23 24 public UnnecessaryConversionTemporaryRule() { 25 primitiveWrappers.add("Integer"); 26 primitiveWrappers.add("Boolean"); 27 primitiveWrappers.add("Double"); 28 primitiveWrappers.add("Long"); 29 primitiveWrappers.add("Short"); 30 primitiveWrappers.add("Byte"); 31 primitiveWrappers.add("Float"); 32 } 33 34 public Object visit(ASTPrimaryExpression node, Object data) { 35 if (node.jjtGetNumChildren() == 0 || (node.jjtGetChild(0)).jjtGetNumChildren() == 0 || !(node.jjtGetChild(0).jjtGetChild(0) 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 || !(node.jjtGetChild(0) instanceof ASTName)) { 48 return super.visit(node, data); 49 } 50 if (!primitiveWrappers.contains(((SimpleNode) node.jjtGetChild(0)).getImage())) { 51 return super.visit(node, data); 52 } 53 usingPrimitiveWrapperAllocation = true; 54 return super.visit(node, data); 55 } 56 57 public Object visit(ASTPrimarySuffix node, Object data) { 58 if (!inPrimaryExpressionContext || !usingPrimitiveWrapperAllocation) { 59 return super.visit(node, data); 60 } 61 if (node.getImage() != null && node.getImage().equals("toString")) { 62 RuleContext ctx = (RuleContext) data; 63 ctx.getReport().addRuleViolation(createRuleViolation(ctx, node.getBeginLine())); 64 } 65 return super.visit(node, data); 66 } 67 68 }

This page was automatically generated by Maven