01 package net.sourceforge.pmd.lang.java.rule.controversial;
02
03 import net.sourceforge.pmd.lang.ast.Node;
04 import net.sourceforge.pmd.lang.java.ast.ASTAssignmentOperator;
05 import net.sourceforge.pmd.lang.java.ast.ASTExpression;
06 import net.sourceforge.pmd.lang.java.ast.ASTForStatement;
07 import net.sourceforge.pmd.lang.java.ast.ASTIfStatement;
08 import net.sourceforge.pmd.lang.java.ast.ASTPostfixExpression;
09 import net.sourceforge.pmd.lang.java.ast.ASTPreDecrementExpression;
10 import net.sourceforge.pmd.lang.java.ast.ASTPreIncrementExpression;
11 import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement;
12 import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
13 import net.sourceforge.pmd.lang.rule.properties.BooleanProperty;
14
15 public class AssignmentInOperandRule extends AbstractJavaRule {
16
17 private static final BooleanProperty ALLOW_IF_DESCRIPTOR = new BooleanProperty("allowIf",
18 "Allow assignment within the conditional expression of an if statement", false, 1.0f);
19
20 private static final BooleanProperty ALLOW_FOR_DESCRIPTOR = new BooleanProperty("allowFor",
21 "Allow assignment within the conditional expression of a for statement", false, 2.0f);
22
23 private static final BooleanProperty ALLOW_WHILE_DESCRIPTOR = new BooleanProperty("allowWhile",
24 "Allow assignment within the conditional expression of a while statement", false, 3.0f);
25
26 private static final BooleanProperty ALLOW_INCREMENT_DECREMENT_DESCRIPTOR = new BooleanProperty(
27 "allowIncrementDecrement",
28 "Allow increment or decrement operators within the conditional expression of an if, for, or while statement",
29 false, 4.0f);
30
31 public AssignmentInOperandRule() {
32 definePropertyDescriptor(ALLOW_IF_DESCRIPTOR);
33 definePropertyDescriptor(ALLOW_FOR_DESCRIPTOR);
34 definePropertyDescriptor(ALLOW_WHILE_DESCRIPTOR);
35 definePropertyDescriptor(ALLOW_INCREMENT_DECREMENT_DESCRIPTOR);
36 }
37
38 public Object visit(ASTExpression node, Object data) {
39 Node parent = node.jjtGetParent();
40 if (((parent instanceof ASTIfStatement && !getProperty(ALLOW_IF_DESCRIPTOR))
41 || (parent instanceof ASTWhileStatement && !getProperty(ALLOW_WHILE_DESCRIPTOR)) || (parent instanceof ASTForStatement
42 && parent.jjtGetChild(1) == node && !getProperty(ALLOW_FOR_DESCRIPTOR)))
43 && (node.hasDescendantOfType(ASTAssignmentOperator.class) || (!getProperty(ALLOW_INCREMENT_DECREMENT_DESCRIPTOR) && (node
44 .hasDescendantOfType(ASTPreIncrementExpression.class)
45 || node.hasDescendantOfType(ASTPreDecrementExpression.class) || node
46 .hasDescendantOfType(ASTPostfixExpression.class))))) {
47 addViolation(data, node);
48 return data;
49 }
50 return super.visit(node, data);
51 }
52 }
|