]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unused_rounding.rs
use get_diagnostic_name for checking macro_call
[rust.git] / clippy_lints / src / unused_rounding.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use rustc_ast::ast::{Expr, ExprKind, LitFloatType, LitKind};
3 use rustc_errors::Applicability;
4 use rustc_lint::{EarlyContext, EarlyLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6
7 declare_clippy_lint! {
8     /// ### What it does
9     ///
10     /// Detects cases where a whole-number literal float is being rounded, using
11     /// the `floor`, `ceil`, or `round` methods.
12     ///
13     /// ### Why is this bad?
14     ///
15     /// This is unnecessary and confusing to the reader. Doing this is probably a mistake.
16     ///
17     /// ### Example
18     /// ```rust
19     /// let x = 1f32.ceil();
20     /// ```
21     /// Use instead:
22     /// ```rust
23     /// let x = 1f32;
24     /// ```
25     #[clippy::version = "1.62.0"]
26     pub UNUSED_ROUNDING,
27     nursery,
28     "Uselessly rounding a whole number floating-point literal"
29 }
30 declare_lint_pass!(UnusedRounding => [UNUSED_ROUNDING]);
31
32 fn is_useless_rounding(expr: &Expr) -> Option<(&str, String)> {
33     if let ExprKind::MethodCall(name_ident, args, _) = &expr.kind
34         && let method_name = name_ident.ident.name.as_str()
35         && (method_name == "ceil" || method_name == "round" || method_name == "floor")
36         && !args.is_empty()
37         && let ExprKind::Lit(spanned) = &args[0].kind
38         && let LitKind::Float(symbol, ty) = spanned.kind {
39             let f = symbol.as_str().parse::<f64>().unwrap();
40             let f_str = symbol.to_string() + if let LitFloatType::Suffixed(ty) = ty {
41                 ty.name_str()
42             } else {
43                 ""
44             };
45             if f.fract() == 0.0 {
46                 Some((method_name, f_str))
47             } else {
48                 None
49             }
50         } else {
51             None
52         }
53 }
54
55 impl EarlyLintPass for UnusedRounding {
56     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
57         if let Some((method_name, float)) = is_useless_rounding(expr) {
58             span_lint_and_sugg(
59                 cx,
60                 UNUSED_ROUNDING,
61                 expr.span,
62                 &format!("used the `{}` method with a whole number float", method_name),
63                 &format!("remove the `{}` method call", method_name),
64                 float,
65                 Applicability::MachineApplicable,
66             );
67         }
68     }
69 }