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