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.RuleContext;
8   import net.sourceforge.pmd.ast.ASTPrimitiveType;
9   import net.sourceforge.pmd.ast.ASTVariableDeclaratorId;
10  import net.sourceforge.pmd.ast.SimpleNode;
11  import net.sourceforge.pmd.symboltable.NameOccurrence;
12  import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
13  
14  import java.util.Iterator;
15  import java.util.List;
16  import java.util.Map;
17  
18  public class StringToStringRule extends AbstractRule {
19  
20      public Object visit(ASTVariableDeclaratorId node, Object data) {
21          SimpleNode nameNode = node.getTypeNameNode();
22          if (nameNode instanceof ASTPrimitiveType) {
23              return data;
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                      RuleContext ctx = (RuleContext) data;
41                      ctx.getReport().addRuleViolation(createRuleViolation(ctx, occ));
42                  }
43              }
44          }
45          return data;
46      }
47  }