]> git.lizzy.rs Git - rust.git/blob - src/approx_const.rs
added helpful links to lints that have wiki entries
[rust.git] / src / approx_const.rs
1 use rustc::lint::*;
2 use syntax::ast::*;
3 use syntax::codemap::Span;
4 use std::f64::consts as f64;
5
6 use utils::span_help_and_lint;
7
8 declare_lint! {
9     pub APPROX_CONSTANT,
10     Warn,
11     "the approximate of a known float constant (in `std::f64::consts` or `std::f32::consts`) \
12      is found; suggests to use the constant"
13 }
14
15 const KNOWN_CONSTS : &'static [(f64, &'static str)] = &[(f64::E, "E"), (f64::FRAC_1_PI, "FRAC_1_PI"),
16     (f64::FRAC_1_SQRT_2, "FRAC_1_SQRT_2"), (f64::FRAC_2_PI, "FRAC_2_PI"),
17     (f64::FRAC_2_SQRT_PI, "FRAC_2_SQRT_PI"), (f64::FRAC_PI_2, "FRAC_PI_2"), (f64::FRAC_PI_3, "FRAC_PI_3"),
18     (f64::FRAC_PI_4, "FRAC_PI_4"), (f64::FRAC_PI_6, "FRAC_PI_6"), (f64::FRAC_PI_8, "FRAC_PI_8"),
19     (f64::LN_10, "LN_10"), (f64::LN_2, "LN_2"), (f64::LOG10_E, "LOG10_E"), (f64::LOG2_E, "LOG2_E"),
20     (f64::PI, "PI"), (f64::SQRT_2, "SQRT_2")];
21
22 const EPSILON_DIVISOR : f64 = 8192f64; //TODO: test to find a good value
23
24 #[derive(Copy,Clone)]
25 pub struct ApproxConstant;
26
27 impl LintPass for ApproxConstant {
28     fn get_lints(&self) -> LintArray {
29         lint_array!(APPROX_CONSTANT)
30     }
31
32     fn check_expr(&mut self, cx: &Context, e: &Expr) {
33         if let &ExprLit(ref lit) = &e.node {
34             check_lit(cx, lit, e.span);
35         }
36     }
37 }
38
39 fn check_lit(cx: &Context, lit: &Lit, span: Span) {
40     match lit.node {
41         LitFloat(ref str, TyF32) => check_known_consts(cx, span, str, "f32"),
42         LitFloat(ref str, TyF64) => check_known_consts(cx, span, str, "f64"),
43         LitFloatUnsuffixed(ref str) => 
44             check_known_consts(cx, span, str, "f{32, 64}"),
45         _ => ()
46     }
47 }
48
49 fn check_known_consts(cx: &Context, span: Span, str: &str, module: &str) {
50     if let Ok(value) = str.parse::<f64>() {
51         for &(constant, name) in KNOWN_CONSTS {
52             if within_epsilon(constant, value) {
53                 span_help_and_lint(cx, APPROX_CONSTANT, span, &format!(
54                     "approximate value of `{}::{}` found. \
55                     Consider using it directly", module, &name),
56                     "for further information see https://github.com/\
57                      Manishearth/rust-clippy/wiki#approx_constant");
58             }
59         }
60     }
61 }
62
63 fn within_epsilon(target: f64, value: f64) -> bool {
64     f64::abs(value - target) < f64::abs(if target > value { 
65                                             target 
66                                         } else { value }) / EPSILON_DIVISOR
67 }