5 /// **What it does:** This lint finds classic underflow / overflow checks.
7 /// **Why is this bad?** Most classic C underflow / overflow checks will fail in Rust. Users can use functions like `overflowing_*` and `wrapping_*` instead.
9 /// **Known problems:** None.
11 /// **Example:** `a + b < a`
13 declare_lint!(pub OVERFLOW_CHECK_CONDITIONAL, Warn,
14 "Using overflow checks which are likely to panic");
16 #[derive(Copy, Clone)]
17 pub struct OverflowCheckConditional;
19 impl LintPass for OverflowCheckConditional {
20 fn get_lints(&self) -> LintArray {
21 lint_array!(OVERFLOW_CHECK_CONDITIONAL)
25 impl LateLintPass for OverflowCheckConditional {
26 // a + b < a, a > a + b, a < a - b, a - b > a
27 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
29 let Expr_::ExprBinary(ref op, ref first, ref second) = expr.node,
30 let Expr_::ExprBinary(ref op2, ref ident1, ref ident2) = first.node,
31 let Expr_::ExprPath(_,ref path1) = ident1.node,
32 let Expr_::ExprPath(_, ref path2) = ident2.node,
33 let Expr_::ExprPath(_, ref path3) = second.node,
34 &path1.segments[0] == &path3.segments[0] || &path2.segments[0] == &path3.segments[0],
35 cx.tcx.expr_ty(ident1).is_integral(),
36 cx.tcx.expr_ty(ident2).is_integral()
38 if let BinOp_::BiLt = op.node {
39 if let BinOp_::BiAdd = op2.node {
40 span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span, "You are trying to use classic C overflow conditions that will fail in Rust.");
43 if let BinOp_::BiGt = op.node {
44 if let BinOp_::BiSub = op2.node {
45 span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span, "You are trying to use classic C underflow conditions that will fail in Rust.");
51 let Expr_::ExprBinary(ref op, ref first, ref second) = expr.node,
52 let Expr_::ExprBinary(ref op2, ref ident1, ref ident2) = second.node,
53 let Expr_::ExprPath(_,ref path1) = ident1.node,
54 let Expr_::ExprPath(_, ref path2) = ident2.node,
55 let Expr_::ExprPath(_, ref path3) = first.node,
56 &path1.segments[0] == &path3.segments[0] || &path2.segments[0] == &path3.segments[0],
57 cx.tcx.expr_ty(ident1).is_integral(),
58 cx.tcx.expr_ty(ident2).is_integral()
60 if let BinOp_::BiGt = op.node {
61 if let BinOp_::BiAdd = op2.node {
62 span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span, "You are trying to use classic C overflow conditions that will fail in Rust.");
65 if let BinOp_::BiLt = op.node {
66 if let BinOp_::BiSub = op2.node {
67 span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span, "You are trying to use classic C underflow conditions that will fail in Rust.");