3 use crate::utils::{span_lint, SpanlessEq};
5 /// **What it does:** Detects classic underflow/overflow checks.
7 /// **Why is this bad?** Most classic C underflow/overflow checks will fail in
8 /// Rust. Users can use functions like `overflowing_*` and `wrapping_*` instead.
10 /// **Known problems:** None.
16 declare_clippy_lint! {
17 pub OVERFLOW_CHECK_CONDITIONAL,
19 "overflow checks inspired by C which are likely to panic"
22 #[derive(Copy, Clone)]
23 pub struct OverflowCheckConditional;
25 impl LintPass for OverflowCheckConditional {
26 fn get_lints(&self) -> LintArray {
27 lint_array!(OVERFLOW_CHECK_CONDITIONAL)
31 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OverflowCheckConditional {
32 // a + b < a, a > a + b, a < a - b, a - b > a
33 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
34 let eq = |l, r| SpanlessEq::new(cx).eq_path_segment(l, r);
36 if let ExprKind::Binary(ref op, ref first, ref second) = expr.node;
37 if let ExprKind::Binary(ref op2, ref ident1, ref ident2) = first.node;
38 if let ExprKind::Path(QPath::Resolved(_, ref path1)) = ident1.node;
39 if let ExprKind::Path(QPath::Resolved(_, ref path2)) = ident2.node;
40 if let ExprKind::Path(QPath::Resolved(_, ref path3)) = second.node;
41 if eq(&path1.segments[0], &path3.segments[0]) || eq(&path2.segments[0], &path3.segments[0]);
42 if cx.tables.expr_ty(ident1).is_integral();
43 if cx.tables.expr_ty(ident2).is_integral();
45 if let BinOpKind::Lt = op.node {
46 if let BinOpKindAdd = op2.node {
47 span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span,
48 "You are trying to use classic C overflow conditions that will fail in Rust.");
51 if let BinOpKind::Gt = op.node {
52 if let BinOpKind::Sub = op2.node {
53 span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span,
54 "You are trying to use classic C underflow conditions that will fail in Rust.");
61 if let ExprKind::Binary(ref op, ref first, ref second) = expr.node;
62 if let ExprKind::Binary(ref op2, ref ident1, ref ident2) = second.node;
63 if let ExprKind::Path(QPath::Resolved(_, ref path1)) = ident1.node;
64 if let ExprKind::Path(QPath::Resolved(_, ref path2)) = ident2.node;
65 if let ExprKind::Path(QPath::Resolved(_, ref path3)) = first.node;
66 if eq(&path1.segments[0], &path3.segments[0]) || eq(&path2.segments[0], &path3.segments[0]);
67 if cx.tables.expr_ty(ident1).is_integral();
68 if cx.tables.expr_ty(ident2).is_integral();
70 if let BinOpKind::Gt = op.node {
71 if let BinOpKindAdd = op2.node {
72 span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span,
73 "You are trying to use classic C overflow conditions that will fail in Rust.");
76 if let BinOpKind::Lt = op.node {
77 if let BinOpKind::Sub = op2.node {
78 span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span,
79 "You are trying to use classic C underflow conditions that will fail in Rust.");