]> git.lizzy.rs Git - rust.git/blob - src/approx_const.rs
3e0ba4eb669f8e20941033c4c6b3558da1c2f5e6
[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_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) => check_known_consts(cx, span, str, "f{32, 64}"),
44         _ => ()
45     }
46 }
47
48 fn check_known_consts(cx: &Context, span: Span, str: &str, module: &str) {
49     if let Ok(value) = str.parse::<f64>() {
50         for &(constant, name) in KNOWN_CONSTS {
51             if within_epsilon(constant, value) {
52                 span_lint(cx, APPROX_CONSTANT, span, &format!(
53                     "approximate value of `{}::{}` found. Consider using it directly", module, &name));
54             }
55         }
56     }
57 }
58
59 fn within_epsilon(target: f64, value: f64) -> bool {
60     f64::abs(value - target) < f64::abs((if target > value { target } else { value })) / EPSILON_DIVISOR
61 }