]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/integer_division.rs
Rollup merge of #97798 - WaffleLapkin:allow_for_suggestions_that_are_quite_far_away_f...
[rust.git] / clippy_lints / src / integer_division.rs
1 use clippy_utils::diagnostics::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
9     /// Checks for division of integers
10     ///
11     /// ### Why is this bad?
12     /// When outside of some very specific algorithms,
13     /// integer division is very often a mistake because it discards the
14     /// remainder.
15     ///
16     /// ### Example
17     /// ```rust
18     /// let x = 3 / 2;
19     /// println!("{}", x);
20     /// ```
21     ///
22     /// Use instead:
23     /// ```rust
24     /// let x = 3f32 / 2f32;
25     /// println!("{}", x);
26     /// ```
27     #[clippy::version = "1.37.0"]
28     pub INTEGER_DIVISION,
29     restriction,
30     "integer division may cause loss of precision"
31 }
32
33 declare_lint_pass!(IntegerDivision => [INTEGER_DIVISION]);
34
35 impl<'tcx> LateLintPass<'tcx> for IntegerDivision {
36     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
37         if is_integer_division(cx, expr) {
38             span_lint_and_help(
39                 cx,
40                 INTEGER_DIVISION,
41                 expr.span,
42                 "integer division",
43                 None,
44                 "division of integers may cause loss of precision. consider using floats",
45             );
46         }
47     }
48 }
49
50 fn is_integer_division<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) -> bool {
51     if_chain! {
52         if let hir::ExprKind::Binary(binop, left, right) = &expr.kind;
53         if binop.node == hir::BinOpKind::Div;
54         then {
55             let (left_ty, right_ty) = (cx.typeck_results().expr_ty(left), cx.typeck_results().expr_ty(right));
56             return left_ty.is_integral() && right_ty.is_integral();
57         }
58     }
59
60     false
61 }