01 package net.sourceforge.pmd.lang.java.rule.strings;
02
03 import java.util.HashSet;
04 import java.util.List;
05 import java.util.Set;
06
07 import net.sourceforge.pmd.lang.ast.Node;
08 import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
09 import net.sourceforge.pmd.lang.java.ast.ASTLiteral;
10 import net.sourceforge.pmd.lang.java.ast.ASTName;
11 import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
12 import net.sourceforge.pmd.lang.java.symboltable.NameDeclaration;
13 import net.sourceforge.pmd.lang.java.symboltable.VariableNameDeclaration;
14 import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper;
15
16
17 /**
18 * This rule finds places where StringBuffer.toString() is called just to see if
19 * the string is 0 length by either using .equals("") or toString().length()
20 * <p/>
21 * <pre>
22 * StringBuffer sb = new StringBuffer("some string");
23 * if (sb.toString().equals("")) {
24 * // this is wrong
25 * }
26 * if (sb.length() == 0) {
27 * // this is right
28 * }
29 * </pre>
30 *
31 * @author acaplan
32 */
33 public class UseStringBufferLengthRule extends AbstractJavaRule {
34
35 // FIXME Need to remove this somehow.
36 /*
37 Specifically, we need a symbol tree that can be traversed downwards, so that instead
38 of visiting each name and then visiting the declaration for that name, we should visit all
39 the declarations and check their usages.
40 With that in place, this rule would be reduced to:
41 - find all StringBuffer declarations
42 - check each usage
43 - flag those that involve variable.toString()
44 */
45 private Set<VariableNameDeclaration> alreadySeen = new HashSet<VariableNameDeclaration>();
46
47 @Override
48 public Object visit(ASTCompilationUnit acu, Object data) {
49 alreadySeen.clear();
50 return super.visit(acu, data);
51 }
52
53 @Override
54 public Object visit(ASTName decl, Object data) {
55 if (!decl.getImage().endsWith("toString")) {
56 return data;
57 }
58 NameDeclaration nd = decl.getNameDeclaration();
59 if (!(nd instanceof VariableNameDeclaration)) {
60 return data;
61 }
62 VariableNameDeclaration vnd = (VariableNameDeclaration) nd;
63 if (alreadySeen.contains(vnd) || !TypeHelper.isA(vnd, StringBuffer.class)) {
64 return data;
65 }
66 alreadySeen.add(vnd);
67
68 Node parent = decl.jjtGetParent().jjtGetParent();
69 for (int jx = 0; jx < parent.jjtGetNumChildren(); jx++) {
70 Node achild = parent.jjtGetChild(jx);
71 if (isViolation(parent, achild)) {
72 addViolation(data, decl);
73 }
74 }
75
76 return data;
77 }
78
79 /**
80 * Check the given node if it calls either .equals or .length we need to check the target
81 */
82 private boolean isViolation(Node parent, Node achild) {
83 if ("equals".equals(achild.getImage())) {
84 List<ASTLiteral> literals = parent.findDescendantsOfType(ASTLiteral.class);
85 return !literals.isEmpty() && "\"\"".equals(literals.get(0).getImage());
86 } else if ("length".equals(achild.getImage())) {
87 return true;
88 }
89 return false;
90 }
91
92
93 }
|