]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/arithmetic.rs
Rollup merge of #74021 - 1011X:master, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / arithmetic.rs
1 use crate::consts::constant_simple;
2 use crate::utils::span_lint;
3 use rustc_hir as hir;
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_tool_lint, impl_lint_pass};
6 use rustc_span::source_map::Span;
7
8 declare_clippy_lint! {
9     /// **What it does:** Checks for integer arithmetic operations which could overflow or panic.
10     ///
11     /// Specifically, checks for any operators (`+`, `-`, `*`, `<<`, etc) which are capable
12     /// of overflowing according to the [Rust
13     /// Reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow),
14     /// or which can panic (`/`, `%`). No bounds analysis or sophisticated reasoning is
15     /// attempted.
16     ///
17     /// **Why is this bad?** Integer overflow will trigger a panic in debug builds or will wrap in
18     /// release mode. Division by zero will cause a panic in either mode. In some applications one
19     /// wants explicitly checked, wrapping or saturating arithmetic.
20     ///
21     /// **Known problems:** None.
22     ///
23     /// **Example:**
24     /// ```rust
25     /// # let a = 0;
26     /// a + 1;
27     /// ```
28     pub INTEGER_ARITHMETIC,
29     restriction,
30     "any integer arithmetic expression which could overflow or panic"
31 }
32
33 declare_clippy_lint! {
34     /// **What it does:** Checks for float arithmetic.
35     ///
36     /// **Why is this bad?** For some embedded systems or kernel development, it
37     /// can be useful to rule out floating-point numbers.
38     ///
39     /// **Known problems:** None.
40     ///
41     /// **Example:**
42     /// ```rust
43     /// # let a = 0.0;
44     /// a + 1.0;
45     /// ```
46     pub FLOAT_ARITHMETIC,
47     restriction,
48     "any floating-point arithmetic statement"
49 }
50
51 #[derive(Copy, Clone, Default)]
52 pub struct Arithmetic {
53     expr_span: Option<Span>,
54     /// This field is used to check whether expressions are constants, such as in enum discriminants
55     /// and consts
56     const_span: Option<Span>,
57 }
58
59 impl_lint_pass!(Arithmetic => [INTEGER_ARITHMETIC, FLOAT_ARITHMETIC]);
60
61 impl<'tcx> LateLintPass<'tcx> for Arithmetic {
62     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
63         if self.expr_span.is_some() {
64             return;
65         }
66
67         if let Some(span) = self.const_span {
68             if span.contains(expr.span) {
69                 return;
70             }
71         }
72         match &expr.kind {
73             hir::ExprKind::Binary(op, l, r) | hir::ExprKind::AssignOp(op, l, r) => {
74                 match op.node {
75                     hir::BinOpKind::And
76                     | hir::BinOpKind::Or
77                     | hir::BinOpKind::BitAnd
78                     | hir::BinOpKind::BitOr
79                     | hir::BinOpKind::BitXor
80                     | hir::BinOpKind::Eq
81                     | hir::BinOpKind::Lt
82                     | hir::BinOpKind::Le
83                     | hir::BinOpKind::Ne
84                     | hir::BinOpKind::Ge
85                     | hir::BinOpKind::Gt => return,
86                     _ => (),
87                 }
88
89                 let (l_ty, r_ty) = (cx.typeck_results().expr_ty(l), cx.typeck_results().expr_ty(r));
90                 if l_ty.peel_refs().is_integral() && r_ty.peel_refs().is_integral() {
91                     span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected");
92                     self.expr_span = Some(expr.span);
93                 } else if l_ty.peel_refs().is_floating_point() && r_ty.peel_refs().is_floating_point() {
94                     span_lint(cx, FLOAT_ARITHMETIC, expr.span, "floating-point arithmetic detected");
95                     self.expr_span = Some(expr.span);
96                 }
97             },
98             hir::ExprKind::Unary(hir::UnOp::UnNeg, arg) => {
99                 let ty = cx.typeck_results().expr_ty(arg);
100                 if constant_simple(cx, cx.typeck_results(), expr).is_none() {
101                     if ty.is_integral() {
102                         span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected");
103                         self.expr_span = Some(expr.span);
104                     } else if ty.is_floating_point() {
105                         span_lint(cx, FLOAT_ARITHMETIC, expr.span, "floating-point arithmetic detected");
106                         self.expr_span = Some(expr.span);
107                     }
108                 }
109             },
110             _ => (),
111         }
112     }
113
114     fn check_expr_post(&mut self, _: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
115         if Some(expr.span) == self.expr_span {
116             self.expr_span = None;
117         }
118     }
119
120     fn check_body(&mut self, cx: &LateContext<'_>, body: &hir::Body<'_>) {
121         let body_owner = cx.tcx.hir().body_owner(body.id());
122
123         match cx.tcx.hir().body_owner_kind(body_owner) {
124             hir::BodyOwnerKind::Static(_) | hir::BodyOwnerKind::Const => {
125                 let body_span = cx.tcx.hir().span(body_owner);
126
127                 if let Some(span) = self.const_span {
128                     if span.contains(body_span) {
129                         return;
130                     }
131                 }
132                 self.const_span = Some(body_span);
133             },
134             hir::BodyOwnerKind::Fn | hir::BodyOwnerKind::Closure => (),
135         }
136     }
137
138     fn check_body_post(&mut self, cx: &LateContext<'_>, body: &hir::Body<'_>) {
139         let body_owner = cx.tcx.hir().body_owner(body.id());
140         let body_span = cx.tcx.hir().span(body_owner);
141
142         if let Some(span) = self.const_span {
143             if span.contains(body_span) {
144                 return;
145             }
146         }
147         self.const_span = None;
148     }
149 }