1
2
3
4 package net.sourceforge.pmd.lang.java.rule.strings;
5
6 import net.sourceforge.pmd.lang.java.ast.ASTName;
7 import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
8 import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
9 import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix;
10 import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
11 import net.sourceforge.pmd.lang.ast.Node;
12
13 public class UnnecessaryCaseChangeRule extends AbstractJavaRule {
14
15 public Object visit(ASTPrimaryExpression exp, Object data) {
16 int n = exp.jjtGetNumChildren();
17 if (n < 4) {
18 return data;
19 }
20
21 int first = getBadPrefixOrNull(exp, n);
22 if (first == -1) {
23 return data;
24 }
25
26 String second = getBadSuffixOrNull(exp, first + 2);
27 if (second == null) {
28 return data;
29 }
30
31 if (!(exp.jjtGetChild(first + 1) instanceof ASTPrimarySuffix)) {
32 return data;
33 }
34 ASTPrimarySuffix methodCall = (ASTPrimarySuffix)exp.jjtGetChild(first + 1);
35 if (!methodCall.isArguments() || methodCall.getArgumentCount() > 0) {
36 return data;
37 }
38
39 addViolation(data, exp);
40 return data;
41 }
42
43 private int getBadPrefixOrNull(ASTPrimaryExpression exp, int childrenCount) {
44
45 for(int i = 0; i < childrenCount - 3; i++) {
46 Node child = exp.jjtGetChild(i);
47 String image;
48 if (child instanceof ASTPrimaryPrefix) {
49 if (child.jjtGetNumChildren() != 1 || !(child.jjtGetChild(0) instanceof ASTName)) {
50 continue;
51 }
52
53 ASTName name = (ASTName) child.jjtGetChild(0);
54 image = name.getImage();
55 } else if (child instanceof ASTPrimarySuffix) {
56 image = ((ASTPrimarySuffix) child).getImage();
57 } else {
58 continue;
59 }
60
61 if (image == null || !(image.endsWith("toUpperCase") || image.endsWith("toLowerCase"))) {
62 continue;
63 } else {
64 return i;
65 }
66 }
67 return -1;
68 }
69
70 private String getBadSuffixOrNull(ASTPrimaryExpression exp, int equalsPosition) {
71
72 if (!(exp.jjtGetChild(equalsPosition) instanceof ASTPrimarySuffix)) {
73 return null;
74 }
75
76 ASTPrimarySuffix suffix = (ASTPrimarySuffix) exp.jjtGetChild(equalsPosition);
77 if (suffix.getImage() == null || !(suffix.hasImageEqualTo("equals") || suffix.hasImageEqualTo("equalsIgnoreCase"))) {
78 return null;
79 }
80 return suffix.getImage();
81 }
82
83 }