1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 package com.qulice.pmd.rules;
32
33 import java.util.List;
34 import java.util.Map;
35 import net.sourceforge.pmd.lang.java.ast.ASTArgumentList;
36 import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
37 import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement;
38 import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator;
39 import net.sourceforge.pmd.lang.java.ast.JavaNode;
40 import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
41 import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
42 import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
43
44
45
46
47
48
49 public final class UnnecessaryLocalRule extends AbstractJavaRule {
50 @Override
51 public Object visit(final ASTMethodDeclaration meth, final Object data) {
52 Object ndata = data;
53 if (!meth.isAbstract() && !meth.isNative()) {
54 ndata = super.visit(meth, data);
55 }
56 return ndata;
57 }
58
59 @Override
60 public Object visit(final ASTReturnStatement rtn, final Object data) {
61 final ASTVariableDeclarator name =
62 rtn.getFirstChildOfType(ASTVariableDeclarator.class);
63 if (name != null) {
64 this.usages(rtn, data, name);
65 }
66 return data;
67 }
68
69 @Override
70 public Object visit(final ASTArgumentList rtn, final Object data) {
71 final List<ASTVariableDeclarator> names =
72 rtn.findChildrenOfType(ASTVariableDeclarator.class);
73 for (final ASTVariableDeclarator name : names) {
74 this.usages(rtn, data, name);
75 }
76 return data;
77 }
78
79
80
81
82
83
84
85 private void usages(final JavaNode node, final Object data,
86 final ASTVariableDeclarator name) {
87 final Map<NameDeclaration, List<NameOccurrence>> vars = name
88 .getScope().getDeclarations();
89 for (final Map.Entry<NameDeclaration, List<NameOccurrence>> entry
90 : vars.entrySet()) {
91 final List<NameOccurrence> usages = entry.getValue();
92 if (usages.size() > 1) {
93 continue;
94 }
95 for (final NameOccurrence occ: usages) {
96 if (occ.getLocation().equals(name)) {
97 this.asCtx(data).addViolation(
98 node, name.getImage()
99 );
100 }
101 }
102 }
103 }
104 }