View Javadoc

1   package net.sourceforge.pmd.lang.java.rule.basic;
2   
3   import java.io.InputStream;
4   
5   import net.sourceforge.pmd.lang.java.ast.ASTExpression;
6   import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
7   import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
8   import net.sourceforge.pmd.lang.java.ast.ASTStatementExpression;
9   import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
10  import net.sourceforge.pmd.lang.java.ast.JavaNode;
11  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
12  import net.sourceforge.pmd.lang.java.symboltable.NameOccurrence;
13  import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper;
14  
15  public class CheckSkipResultRule extends AbstractJavaRule {
16      
17      public Object visit(ASTVariableDeclaratorId node, Object data) {
18          if (!TypeHelper.isA(node.getTypeNode(), InputStream.class)) {
19              return data;
20          }
21          for (NameOccurrence occ: node.getUsages()) {
22              NameOccurrence qualifier = occ.getNameForWhichThisIsAQualifier();
23              if (qualifier != null && "skip".equals(qualifier.getImage())) {
24                  JavaNode loc = occ.getLocation();
25                  if ( loc != null ) {
26                      ASTPrimaryExpression exp = loc.getFirstParentOfType(ASTPrimaryExpression.class);
27                      while (exp != null) {
28                          if (exp.jjtGetParent() instanceof ASTStatementExpression) {
29                              // if exp is in a bare statement,
30                              // the returned value is not used
31                              addViolation(data, occ.getLocation());
32                              break;
33                          } else if (exp.jjtGetParent() instanceof ASTExpression &&
34                                     exp.jjtGetParent().jjtGetParent() instanceof ASTPrimaryPrefix) {
35                              // if exp is enclosed in a pair of parenthesis
36                              // let's have a look at the enclosing expression
37                              // we'll see if it's in a bare statement
38                              exp = exp.getFirstParentOfType(ASTPrimaryExpression.class);
39                          } else {
40                              // if exp is neither in a bare statement
41                              // or between a pair of parentheses,
42                              // it's in some other kind of statement
43                              // or assignement so the returned value is used
44                              break;
45                          }
46                      }
47                  }
48              }
49          }
50          return data;
51      }
52      
53  }