2 use rustc::{declare_lint, lint_array};
3 use if_chain::if_chain;
5 use crate::utils::{span_lint, SpanlessEq};
7 /// **What it does:** Detects classic underflow/overflow checks.
9 /// **Why is this bad?** Most classic C underflow/overflow checks will fail in
10 /// Rust. Users can use functions like `overflowing_*` and `wrapping_*` instead.
12 /// **Known problems:** None.
18 declare_clippy_lint! {
19 pub OVERFLOW_CHECK_CONDITIONAL,
21 "overflow checks inspired by C which are likely to panic"
24 #[derive(Copy, Clone)]
25 pub struct OverflowCheckConditional;
27 impl LintPass for OverflowCheckConditional {
28 fn get_lints(&self) -> LintArray {
29 lint_array!(OVERFLOW_CHECK_CONDITIONAL)
33 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OverflowCheckConditional {
34 // a + b < a, a > a + b, a < a - b, a - b > a
35 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
36 let eq = |l, r| SpanlessEq::new(cx).eq_path_segment(l, r);
38 if let ExprKind::Binary(ref op, ref first, ref second) = expr.node;
39 if let ExprKind::Binary(ref op2, ref ident1, ref ident2) = first.node;
40 if let ExprKind::Path(QPath::Resolved(_, ref path1)) = ident1.node;
41 if let ExprKind::Path(QPath::Resolved(_, ref path2)) = ident2.node;
42 if let ExprKind::Path(QPath::Resolved(_, ref path3)) = second.node;
43 if eq(&path1.segments[0], &path3.segments[0]) || eq(&path2.segments[0], &path3.segments[0]);
44 if cx.tables.expr_ty(ident1).is_integral();
45 if cx.tables.expr_ty(ident2).is_integral();
47 if let BinOpKind::Lt = op.node {
48 if let BinOpKind::Add = op2.node {
49 span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span,
50 "You are trying to use classic C overflow conditions that will fail in Rust.");
53 if let BinOpKind::Gt = op.node {
54 if let BinOpKind::Sub = op2.node {
55 span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span,
56 "You are trying to use classic C underflow conditions that will fail in Rust.");
63 if let ExprKind::Binary(ref op, ref first, ref second) = expr.node;
64 if let ExprKind::Binary(ref op2, ref ident1, ref ident2) = second.node;
65 if let ExprKind::Path(QPath::Resolved(_, ref path1)) = ident1.node;
66 if let ExprKind::Path(QPath::Resolved(_, ref path2)) = ident2.node;
67 if let ExprKind::Path(QPath::Resolved(_, ref path3)) = first.node;
68 if eq(&path1.segments[0], &path3.segments[0]) || eq(&path2.segments[0], &path3.segments[0]);
69 if cx.tables.expr_ty(ident1).is_integral();
70 if cx.tables.expr_ty(ident2).is_integral();
72 if let BinOpKind::Gt = op.node {
73 if let BinOpKind::Add = op2.node {
74 span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span,
75 "You are trying to use classic C overflow conditions that will fail in Rust.");
78 if let BinOpKind::Lt = op.node {
79 if let BinOpKind::Sub = op2.node {
80 span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span,
81 "You are trying to use classic C underflow conditions that will fail in Rust.");