Skip to content

Instantly share code, notes, and snippets.

@sebastianmonte
Created February 12, 2015 13:30
Show Gist options
  • Save sebastianmonte/d867e7aa1dee7fb7c50c to your computer and use it in GitHub Desktop.
Save sebastianmonte/d867e7aa1dee7fb7c50c to your computer and use it in GitHub Desktop.
DivZero Bug Checker
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