]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/approx_const.rs
Auto merge of #88214 - notriddle:notriddle/for-loop-span-drop-temps-mut, r=nagisa
[rust.git] / clippy_lints / src / approx_const.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::{meets_msrv, msrvs};
3 use rustc_ast::ast::{FloatTy, LitFloatType, LitKind};
4 use rustc_hir::{Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass, LintContext};
6 use rustc_semver::RustcVersion;
7 use rustc_session::{declare_tool_lint, impl_lint_pass};
8 use rustc_span::symbol;
9 use std::f64::consts as f64;
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// Checks for floating point literals that approximate
14     /// constants which are defined in
15     /// [`std::f32::consts`](https://doc.rust-lang.org/stable/std/f32/consts/#constants)
16     /// or
17     /// [`std::f64::consts`](https://doc.rust-lang.org/stable/std/f64/consts/#constants),
18     /// respectively, suggesting to use the predefined constant.
19     ///
20     /// ### Why is this bad?
21     /// Usually, the definition in the standard library is more
22     /// precise than what people come up with. If you find that your definition is
23     /// actually more precise, please [file a Rust
24     /// issue](https://github.com/rust-lang/rust/issues).
25     ///
26     /// ### Example
27     /// ```rust
28     /// let x = 3.14;
29     /// let y = 1_f64 / x;
30     /// ```
31     /// Use predefined constants instead:
32     /// ```rust
33     /// let x = std::f32::consts::PI;
34     /// let y = std::f64::consts::FRAC_1_PI;
35     /// ```
36     pub APPROX_CONSTANT,
37     correctness,
38     "the approximate of a known float constant (in `std::fXX::consts`)"
39 }
40
41 // Tuples are of the form (constant, name, min_digits, msrv)
42 const KNOWN_CONSTS: [(f64, &str, usize, Option<RustcVersion>); 19] = [
43     (f64::E, "E", 4, None),
44     (f64::FRAC_1_PI, "FRAC_1_PI", 4, None),
45     (f64::FRAC_1_SQRT_2, "FRAC_1_SQRT_2", 5, None),
46     (f64::FRAC_2_PI, "FRAC_2_PI", 5, None),
47     (f64::FRAC_2_SQRT_PI, "FRAC_2_SQRT_PI", 5, None),
48     (f64::FRAC_PI_2, "FRAC_PI_2", 5, None),
49     (f64::FRAC_PI_3, "FRAC_PI_3", 5, None),
50     (f64::FRAC_PI_4, "FRAC_PI_4", 5, None),
51     (f64::FRAC_PI_6, "FRAC_PI_6", 5, None),
52     (f64::FRAC_PI_8, "FRAC_PI_8", 5, None),
53     (f64::LN_2, "LN_2", 5, None),
54     (f64::LN_10, "LN_10", 5, None),
55     (f64::LOG2_10, "LOG2_10", 5, Some(msrvs::LOG2_10)),
56     (f64::LOG2_E, "LOG2_E", 5, None),
57     (f64::LOG10_2, "LOG10_2", 5, Some(msrvs::LOG10_2)),
58     (f64::LOG10_E, "LOG10_E", 5, None),
59     (f64::PI, "PI", 3, None),
60     (f64::SQRT_2, "SQRT_2", 5, None),
61     (f64::TAU, "TAU", 3, Some(msrvs::TAU)),
62 ];
63
64 pub struct ApproxConstant {
65     msrv: Option<RustcVersion>,
66 }
67
68 impl ApproxConstant {
69     #[must_use]
70     pub fn new(msrv: Option<RustcVersion>) -> Self {
71         Self { msrv }
72     }
73
74     fn check_lit(&self, cx: &LateContext<'_>, lit: &LitKind, e: &Expr<'_>) {
75         match *lit {
76             LitKind::Float(s, LitFloatType::Suffixed(fty)) => match fty {
77                 FloatTy::F32 => self.check_known_consts(cx, e, s, "f32"),
78                 FloatTy::F64 => self.check_known_consts(cx, e, s, "f64"),
79             },
80             LitKind::Float(s, LitFloatType::Unsuffixed) => self.check_known_consts(cx, e, s, "f{32, 64}"),
81             _ => (),
82         }
83     }
84
85     fn check_known_consts(&self, cx: &LateContext<'_>, e: &Expr<'_>, s: symbol::Symbol, module: &str) {
86         let s = s.as_str();
87         if s.parse::<f64>().is_ok() {
88             for &(constant, name, min_digits, msrv) in &KNOWN_CONSTS {
89                 if is_approx_const(constant, &s, min_digits)
90                     && msrv.as_ref().map_or(true, |msrv| meets_msrv(self.msrv.as_ref(), msrv))
91                 {
92                     span_lint_and_help(
93                         cx,
94                         APPROX_CONSTANT,
95                         e.span,
96                         &format!("approximate value of `{}::consts::{}` found", module, &name),
97                         None,
98                         "consider using the constant directly",
99                     );
100                     return;
101                 }
102             }
103         }
104     }
105 }
106
107 impl_lint_pass!(ApproxConstant => [APPROX_CONSTANT]);
108
109 impl<'tcx> LateLintPass<'tcx> for ApproxConstant {
110     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
111         if let ExprKind::Lit(lit) = &e.kind {
112             self.check_lit(cx, &lit.node, e);
113         }
114     }
115
116     extract_msrv_attr!(LateContext);
117 }
118
119 /// Returns `false` if the number of significant figures in `value` are
120 /// less than `min_digits`; otherwise, returns true if `value` is equal
121 /// to `constant`, rounded to the number of digits present in `value`.
122 #[must_use]
123 fn is_approx_const(constant: f64, value: &str, min_digits: usize) -> bool {
124     if value.len() <= min_digits {
125         false
126     } else if constant.to_string().starts_with(value) {
127         // The value is a truncated constant
128         true
129     } else {
130         let round_const = format!("{:.*}", value.len() - 2, constant);
131         value == round_const
132     }
133 }