View Javadoc

1   /***
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.rules;
5   
6   import net.sourceforge.pmd.AbstractRule;
7   import net.sourceforge.pmd.ast.ASTPrimitiveType;
8   import net.sourceforge.pmd.ast.ASTVariableDeclaratorId;
9   import net.sourceforge.pmd.ast.SimpleNode;
10  import net.sourceforge.pmd.symboltable.NameOccurrence;
11  import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
12  
13  import java.util.Iterator;
14  import java.util.List;
15  import java.util.Map;
16  
17  public class StringToStringRule extends AbstractRule {
18  
19      public Object visit(ASTVariableDeclaratorId node, Object data) {
20          SimpleNode nameNode = node.getTypeNameNode();
21          if (nameNode instanceof ASTPrimitiveType) {
22              return data;
23          }
24          
25          if (!((SimpleNode)(nameNode.jjtGetChild(0))).getImage().equals("String")) {
26              return data;
27          }
28          
29          // now we know we're at a variable declaration of type String
30          Map decls = node.getScope().getVariableDeclarations();
31          for (Iterator i = decls.keySet().iterator(); i.hasNext();) {
32              VariableNameDeclaration decl = (VariableNameDeclaration) i.next();
33              if (!decl.getImage().equals(node.getImage())) {
34                  continue;
35              }
36              List usages = (List) decls.get(decl);
37              for (Iterator j = usages.iterator(); j.hasNext();) {
38                  NameOccurrence occ = (NameOccurrence) j.next();
39                  if (occ.getNameForWhichThisIsAQualifier() != null && occ.getNameForWhichThisIsAQualifier().getImage().indexOf("toString") != -1) {
40                      addViolation(data, occ.getLocation());
41                  }
42              }
43          }
44          return data;
45      }
46  }