]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/approx_const.rs
Auto merge of #3597 - xfix:match-ergonomics, r=phansch
[rust.git] / clippy_lints / src / approx_const.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::utils::span_lint;
11 use rustc::hir::*;
12 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use rustc::{declare_tool_lint, lint_array};
14 use std::f64::consts as f64;
15 use syntax::ast::{FloatTy, Lit, LitKind};
16 use syntax::symbol;
17
18 /// **What it does:** Checks for floating point literals that approximate
19 /// constants which are defined in
20 /// [`std::f32::consts`](https://doc.rust-lang.org/stable/std/f32/consts/#constants)
21 /// or
22 /// [`std::f64::consts`](https://doc.rust-lang.org/stable/std/f64/consts/#constants),
23 /// respectively, suggesting to use the predefined constant.
24 ///
25 /// **Why is this bad?** Usually, the definition in the standard library is more
26 /// precise than what people come up with. If you find that your definition is
27 /// actually more precise, please [file a Rust
28 /// issue](https://github.com/rust-lang/rust/issues).
29 ///
30 /// **Known problems:** If you happen to have a value that is within 1/8192 of a
31 /// known constant, but is not *and should not* be the same, this lint will
32 /// report your value anyway. We have not yet noticed any false positives in
33 /// code we tested clippy with (this includes servo), but YMMV.
34 ///
35 /// **Example:**
36 /// ```rust
37 /// let x = 3.14;
38 /// ```
39 declare_clippy_lint! {
40     pub APPROX_CONSTANT,
41     correctness,
42     "the approximate of a known float constant (in `std::fXX::consts`)"
43 }
44
45 // Tuples are of the form (constant, name, min_digits)
46 const KNOWN_CONSTS: &[(f64, &str, usize)] = &[
47     (f64::E, "E", 4),
48     (f64::FRAC_1_PI, "FRAC_1_PI", 4),
49     (f64::FRAC_1_SQRT_2, "FRAC_1_SQRT_2", 5),
50     (f64::FRAC_2_PI, "FRAC_2_PI", 5),
51     (f64::FRAC_2_SQRT_PI, "FRAC_2_SQRT_PI", 5),
52     (f64::FRAC_PI_2, "FRAC_PI_2", 5),
53     (f64::FRAC_PI_3, "FRAC_PI_3", 5),
54     (f64::FRAC_PI_4, "FRAC_PI_4", 5),
55     (f64::FRAC_PI_6, "FRAC_PI_6", 5),
56     (f64::FRAC_PI_8, "FRAC_PI_8", 5),
57     (f64::LN_10, "LN_10", 5),
58     (f64::LN_2, "LN_2", 5),
59     (f64::LOG10_E, "LOG10_E", 5),
60     (f64::LOG2_E, "LOG2_E", 5),
61     (f64::PI, "PI", 3),
62     (f64::SQRT_2, "SQRT_2", 5),
63 ];
64
65 #[derive(Copy, Clone)]
66 pub struct Pass;
67
68 impl LintPass for Pass {
69     fn get_lints(&self) -> LintArray {
70         lint_array!(APPROX_CONSTANT)
71     }
72 }
73
74 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
75     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
76         if let ExprKind::Lit(lit) = &e.node {
77             check_lit(cx, lit, e);
78         }
79     }
80 }
81
82 fn check_lit(cx: &LateContext<'_, '_>, lit: &Lit, e: &Expr) {
83     match lit.node {
84         LitKind::Float(s, FloatTy::F32) => check_known_consts(cx, e, s, "f32"),
85         LitKind::Float(s, FloatTy::F64) => check_known_consts(cx, e, s, "f64"),
86         LitKind::FloatUnsuffixed(s) => check_known_consts(cx, e, s, "f{32, 64}"),
87         _ => (),
88     }
89 }
90
91 fn check_known_consts(cx: &LateContext<'_, '_>, e: &Expr, s: symbol::Symbol, module: &str) {
92     let s = s.as_str();
93     if s.parse::<f64>().is_ok() {
94         for &(constant, name, min_digits) in KNOWN_CONSTS {
95             if is_approx_const(constant, &s, min_digits) {
96                 span_lint(
97                     cx,
98                     APPROX_CONSTANT,
99                     e.span,
100                     &format!(
101                         "approximate value of `{}::consts::{}` found. \
102                          Consider using it directly",
103                         module, &name
104                     ),
105                 );
106                 return;
107             }
108         }
109     }
110 }
111
112 /// Returns false if the number of significant figures in `value` are
113 /// less than `min_digits`; otherwise, returns true if `value` is equal
114 /// to `constant`, rounded to the number of digits present in `value`.
115 fn is_approx_const(constant: f64, value: &str, min_digits: usize) -> bool {
116     if value.len() <= min_digits {
117         false
118     } else {
119         let round_const = format!("{:.*}", value.len() - 2, constant);
120
121         let mut trunc_const = constant.to_string();
122         if trunc_const.len() > value.len() {
123             trunc_const.truncate(value.len());
124         }
125
126         (value == round_const) || (value == trunc_const)
127     }
128 }