01: /**
02: * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03: */package net.sourceforge.pmd.rules.design;
04:
05: import net.sourceforge.pmd.AbstractRule;
06: import net.sourceforge.pmd.ast.ASTAssignmentOperator;
07: import net.sourceforge.pmd.ast.ASTConditionalExpression;
08: import net.sourceforge.pmd.ast.ASTEqualityExpression;
09: import net.sourceforge.pmd.ast.ASTName;
10: import net.sourceforge.pmd.ast.ASTNullLiteral;
11: import net.sourceforge.pmd.ast.ASTStatementExpression;
12: import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
13:
14: // TODO - should check that this is not the first assignment. e.g., this is OK:
15: // Object x;
16: // x = null;
17: public class NullAssignmentRule extends AbstractRule {
18:
19: public Object visit(ASTNullLiteral node, Object data) {
20:
21: if (node.getNthParent(5) instanceof ASTStatementExpression) {
22: ASTStatementExpression n = (ASTStatementExpression) node
23: .getNthParent(5);
24:
25: if (isAssignmentToFinalField(n)) {
26: return data;
27: }
28:
29: if (n.jjtGetNumChildren() > 2
30: && n.jjtGetChild(1) instanceof ASTAssignmentOperator) {
31: addViolation(data, node);
32: }
33: } else if (node.getNthParent(4) instanceof ASTConditionalExpression) {
34: if (isBadTernary((ASTConditionalExpression) node
35: .getNthParent(4))) {
36: addViolation(data, node);
37: }
38: } else if (node.getNthParent(5) instanceof ASTConditionalExpression) {
39: if (isBadTernary((ASTConditionalExpression) node
40: .getNthParent(5))) {
41: addViolation(data, node);
42: }
43: }
44:
45: return data;
46: }
47:
48: private boolean isAssignmentToFinalField(ASTStatementExpression n) {
49: ASTName name = n.getFirstChildOfType(ASTName.class);
50: return name != null
51: && name.getNameDeclaration() instanceof VariableNameDeclaration
52: && ((VariableNameDeclaration) name.getNameDeclaration())
53: .getAccessNodeParent().isFinal();
54: }
55:
56: private boolean isBadTernary(ASTConditionalExpression n) {
57: return n.isTernary()
58: && !(n.jjtGetChild(0) instanceof ASTEqualityExpression);
59: }
60: }
|