]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/approx_const.rs
Auto merge of #4093 - rust-lang:rustup, r=oli-obk
[rust.git] / clippy_lints / src / approx_const.rs
1 use crate::utils::span_lint;
2 use crate::utils::sym;
3 use lazy_static::lazy_static;
4 use rustc::hir::*;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7 use std::f64::consts as f64;
8 use syntax::ast::{FloatTy, LitKind};
9 use syntax::symbol;
10 use syntax::symbol::Symbol;
11
12 declare_clippy_lint! {
13     /// **What it does:** 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?** Usually, the definition in the standard library is more
21     /// precise than what people come up with. If you find that your definition is
22     /// actually more precise, please [file a Rust
23     /// issue](https://github.com/rust-lang/rust/issues).
24     ///
25     /// **Known problems:** None.
26     ///
27     /// **Example:**
28     /// ```rust
29     /// let x = 3.14;
30     /// ```
31     pub APPROX_CONSTANT,
32     correctness,
33     "the approximate of a known float constant (in `std::fXX::consts`)"
34 }
35
36 lazy_static! {
37 // Tuples are of the form (constant, name, min_digits)
38 static ref KNOWN_CONSTS: [(f64, Symbol, usize); 16] = [
39     (f64::E, *sym::E, 4),
40     (f64::FRAC_1_PI, *sym::FRAC_1_PI, 4),
41     (f64::FRAC_1_SQRT_2, *sym::FRAC_1_SQRT_2, 5),
42     (f64::FRAC_2_PI, *sym::FRAC_2_PI, 5),
43     (f64::FRAC_2_SQRT_PI, *sym::FRAC_2_SQRT_PI, 5),
44     (f64::FRAC_PI_2, *sym::FRAC_PI_2, 5),
45     (f64::FRAC_PI_3, *sym::FRAC_PI_3, 5),
46     (f64::FRAC_PI_4, *sym::FRAC_PI_4, 5),
47     (f64::FRAC_PI_6, *sym::FRAC_PI_6, 5),
48     (f64::FRAC_PI_8, *sym::FRAC_PI_8, 5),
49     (f64::LN_10, *sym::LN_10, 5),
50     (f64::LN_2, *sym::LN_2, 5),
51     (f64::LOG10_E, *sym::LOG10_E, 5),
52     (f64::LOG2_E, *sym::LOG2_E, 5),
53     (f64::PI, *sym::PI, 3),
54     (f64::SQRT_2, *sym::SQRT_2, 5),
55 ];
56 }
57
58 declare_lint_pass!(ApproxConstant => [APPROX_CONSTANT]);
59
60 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ApproxConstant {
61     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
62         if let ExprKind::Lit(lit) = &e.node {
63             check_lit(cx, &lit.node, e);
64         }
65     }
66 }
67
68 fn check_lit(cx: &LateContext<'_, '_>, lit: &LitKind, e: &Expr) {
69     match *lit {
70         LitKind::Float(s, FloatTy::F32) => check_known_consts(cx, e, s, "f32"),
71         LitKind::Float(s, FloatTy::F64) => check_known_consts(cx, e, s, "f64"),
72         LitKind::FloatUnsuffixed(s) => check_known_consts(cx, e, s, "f{32, 64}"),
73         _ => (),
74     }
75 }
76
77 fn check_known_consts(cx: &LateContext<'_, '_>, e: &Expr, s: symbol::Symbol, module: &str) {
78     let s = s.as_str();
79     if s.parse::<f64>().is_ok() {
80         for &(constant, name, min_digits) in KNOWN_CONSTS.iter() {
81             if is_approx_const(constant, &s, min_digits) {
82                 span_lint(
83                     cx,
84                     APPROX_CONSTANT,
85                     e.span,
86                     &format!(
87                         "approximate value of `{}::consts::{}` found. \
88                          Consider using it directly",
89                         module, &name
90                     ),
91                 );
92                 return;
93             }
94         }
95     }
96 }
97
98 /// Returns `false` if the number of significant figures in `value` are
99 /// less than `min_digits`; otherwise, returns true if `value` is equal
100 /// to `constant`, rounded to the number of digits present in `value`.
101 fn is_approx_const(constant: f64, value: &str, min_digits: usize) -> bool {
102     if value.len() <= min_digits {
103         false
104     } else {
105         let round_const = format!("{:.*}", value.len() - 2, constant);
106
107         let mut trunc_const = constant.to_string();
108         if trunc_const.len() > value.len() {
109             trunc_const.truncate(value.len());
110         }
111
112         (value == round_const) || (value == trunc_const)
113     }
114 }