1 use clippy_utils::diagnostics::span_lint_and_help;
2 use if_chain::if_chain;
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 /// Checks for division of integers
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
19 /// println!("{}", x);
24 /// let x = 3f32 / 2f32;
25 /// println!("{}", x);
27 #[clippy::version = "1.37.0"]
30 "integer division may cause loss of precision"
33 declare_lint_pass!(IntegerDivision => [INTEGER_DIVISION]);
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) {
44 "division of integers may cause loss of precision. consider using floats",
50 fn is_integer_division<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) -> bool {
52 if let hir::ExprKind::Binary(binop, left, right) = &expr.kind;
53 if binop.node == hir::BinOpKind::Div;
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();