Created
February 12, 2015 13:30
-
-
Save sebastianmonte/d867e7aa1dee7fb7c50c to your computer and use it in GitHub Desktop.
DivZero Bug Checker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DivZero extends BugChecker | |
implements BinaryTreeMatcher, CompoundAssignmentTreeMatcher { | |
@Override | |
public Description matchBinary(BinaryTree tree, VisitorState state) { | |
return matchDivZero(tree, tree.getRightOperand(), state); | |
} | |
@Override | |
public Description matchCompoundAssignment(CompoundAssignmentTree tree, VisitorState state) { | |
return matchDivZero(tree, tree.getExpression(), state); | |
} | |
private Description matchDivZero(Tree tree, ExpressionTree operand, VisitorState state) { | |
if (!anyOf(kindIs(Kind.DIVIDE), kindIs(Kind.DIVIDE_ASSIGNMENT)).matches(tree, state)) { | |
return Description.NO_MATCH; | |
} | |
if (!kindIs(Kind.INT_LITERAL).matches(operand, state)) { | |
return Description.NO_MATCH; | |
} | |
LiteralTree rightOperand = (LiteralTree) operand; | |
if (((Integer) rightOperand.getValue()) != 0) { | |
return Description.NO_MATCH; | |
} | |
// Find and replace enclosing Statement. | |
StatementTree enclosingStmt = | |
ASTHelpers.findEnclosingNode(state.getPath(), StatementTree.class); | |
return (enclosingStmt != null) | |
? describeMatch(tree, | |
SuggestedFix.replace(enclosingStmt, "throw new ArithmeticException(\"/ by zero\");")) | |
: describeMatch(tree); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment