]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/arithmetic.rs
Update existing arithmetic lint and add new tests related to it.
[rust.git] / 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                     match op.node {
92                         hir::BinOpKind::Div | hir::BinOpKind::Rem => match &r.kind {
93                             hir::ExprKind::Lit(lit) => {
94                                 if let rustc_ast::ast::LitKind::Int(0, _) = lit.node {
95                                     span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected");
96                                     self.expr_span = Some(expr.span);
97                                 }
98                             },
99                             hir::ExprKind::Unary(hir::UnOp::UnNeg, expr) => {
100                                 if let hir::ExprKind::Lit(lit) = &expr.kind {
101                                     if let rustc_ast::ast::LitKind::Int(1, _) = lit.node {
102                                         span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected");
103                                         self.expr_span = Some(expr.span);
104                                     }
105                                 }
106                             },
107                             _ => {
108                                 span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected");
109                                 self.expr_span = Some(expr.span);
110                             },
111                         },
112                         _ => {
113                             span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected");
114                             self.expr_span = Some(expr.span);
115                         },
116                     }
117                 } else if r_ty.peel_refs().is_floating_point() && r_ty.peel_refs().is_floating_point() {
118                     span_lint(cx, FLOAT_ARITHMETIC, expr.span, "floating-point arithmetic detected");
119                     self.expr_span = Some(expr.span);
120                 }
121             },
122             hir::ExprKind::Unary(hir::UnOp::UnNeg, arg) => {
123                 let ty = cx.typeck_results().expr_ty(arg);
124                 if constant_simple(cx, cx.typeck_results(), expr).is_none() {
125                     if ty.is_integral() {
126                         span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected");
127                         self.expr_span = Some(expr.span);
128                     } else if ty.is_floating_point() {
129                         span_lint(cx, FLOAT_ARITHMETIC, expr.span, "floating-point arithmetic detected");
130                         self.expr_span = Some(expr.span);
131                     }
132                 }
133             },
134             _ => (),
135         }
136     }
137
138     fn check_expr_post(&mut self, _: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
139         if Some(expr.span) == self.expr_span {
140             self.expr_span = None;
141         }
142     }
143
144     fn check_body(&mut self, cx: &LateContext<'_>, body: &hir::Body<'_>) {
145         let body_owner = cx.tcx.hir().body_owner(body.id());
146
147         match cx.tcx.hir().body_owner_kind(body_owner) {
148             hir::BodyOwnerKind::Static(_) | hir::BodyOwnerKind::Const => {
149                 let body_span = cx.tcx.hir().span(body_owner);
150
151                 if let Some(span) = self.const_span {
152                     if span.contains(body_span) {
153                         return;
154                     }
155                 }
156                 self.const_span = Some(body_span);
157             },
158             hir::BodyOwnerKind::Fn | hir::BodyOwnerKind::Closure => (),
159         }
160     }
161
162     fn check_body_post(&mut self, cx: &LateContext<'_>, body: &hir::Body<'_>) {
163         let body_owner = cx.tcx.hir().body_owner(body.id());
164         let body_span = cx.tcx.hir().span(body_owner);
165
166         if let Some(span) = self.const_span {
167             if span.contains(body_span) {
168                 return;
169             }
170         }
171         self.const_span = None;
172     }
173 }