]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/integer_division.rs
Auto merge of #4809 - iankronquist:patch-1, r=flip1995
[rust.git] / clippy_lints / src / integer_division.rs
1 use crate::utils::span_lint_and_help;
2 use if_chain::if_chain;
3 use rustc_hir as hir;
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6
7 declare_clippy_lint! {
8     /// **What it does:** Checks for division of integers
9     ///
10     /// **Why is this bad?** When outside of some very specific algorithms,
11     /// integer division is very often a mistake because it discards the
12     /// remainder.
13     ///
14     /// **Known problems:** None.
15     ///
16     /// **Example:**
17     /// ```rust
18     /// fn main() {
19     ///     let x = 3 / 2;
20     ///     println!("{}", x);
21     /// }
22     /// ```
23     pub INTEGER_DIVISION,
24     restriction,
25     "integer division may cause loss of precision"
26 }
27
28 declare_lint_pass!(IntegerDivision => [INTEGER_DIVISION]);
29
30 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IntegerDivision {
31     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) {
32         if is_integer_division(cx, expr) {
33             span_lint_and_help(
34                 cx,
35                 INTEGER_DIVISION,
36                 expr.span,
37                 "integer division",
38                 "division of integers may cause loss of precision. consider using floats.",
39             );
40         }
41     }
42 }
43
44 fn is_integer_division<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) -> bool {
45     if_chain! {
46         if let hir::ExprKind::Binary(binop, left, right) = &expr.kind;
47         if let hir::BinOpKind::Div = &binop.node;
48         then {
49             let (left_ty, right_ty) = (cx.tables.expr_ty(left), cx.tables.expr_ty(right));
50             return left_ty.is_integral() && right_ty.is_integral();
51         }
52     }
53
54     false
55 }