01: package net.sourceforge.pmd.rules.strings;
02:
03: import net.sourceforge.pmd.AbstractRule;
04: import net.sourceforge.pmd.ast.ASTName;
05: import net.sourceforge.pmd.ast.ASTPrimaryExpression;
06: import net.sourceforge.pmd.ast.ASTPrimaryPrefix;
07: import net.sourceforge.pmd.ast.ASTPrimarySuffix;
08: import net.sourceforge.pmd.ast.Node;
09:
10: public class UnnecessaryCaseChange extends AbstractRule {
11:
12: public Object visit(ASTPrimaryExpression exp, Object data) {
13: int n = exp.jjtGetNumChildren();
14: if (n < 4) {
15: return data;
16: }
17:
18: int first = getBadPrefixOrNull(exp, n);
19: if (first == -1) {
20: return data;
21: }
22:
23: String second = getBadSuffixOrNull(exp, first + 2);
24: if (second == null) {
25: return data;
26: }
27:
28: if (!(exp.jjtGetChild(first + 1) instanceof ASTPrimarySuffix)) {
29: return data;
30: }
31: ASTPrimarySuffix methodCall = (ASTPrimarySuffix) exp
32: .jjtGetChild(first + 1);
33: if (!methodCall.isArguments()
34: || methodCall.getArgumentCount() > 0) {
35: return data;
36: }
37:
38: addViolation(data, exp);
39: return data;
40: }
41:
42: private int getBadPrefixOrNull(ASTPrimaryExpression exp,
43: int childrenCount) {
44: // verify PrimaryPrefix/Name[ends-with(@Image, 'toUpperCase']
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
50: || !(child.jjtGetChild(0) instanceof ASTName)) {
51: continue;
52: }
53:
54: ASTName name = (ASTName) child.jjtGetChild(0);
55: image = name.getImage();
56: } else if (child instanceof ASTPrimarySuffix) {
57: image = ((ASTPrimarySuffix) child).getImage();
58: } else {
59: continue;
60: }
61:
62: if (image == null
63: || !(image.endsWith("toUpperCase") || image
64: .endsWith("toLowerCase"))) {
65: continue;
66: }
67: return i;
68: }
69: return -1;
70: }
71:
72: private String getBadSuffixOrNull(ASTPrimaryExpression exp,
73: int equalsPosition) {
74: // verify PrimarySuffix[@Image='equals']
75: if (!(exp.jjtGetChild(equalsPosition) instanceof ASTPrimarySuffix)) {
76: return null;
77: }
78:
79: ASTPrimarySuffix suffix = (ASTPrimarySuffix) exp
80: .jjtGetChild(equalsPosition);
81: if (suffix.getImage() == null
82: || !(suffix.hasImageEqualTo("equals") || suffix
83: .hasImageEqualTo("equalsIgnoreCase"))) {
84: return null;
85: }
86: return suffix.getImage();
87: }
88:
89: }
|