]> git.lizzy.rs Git - rust.git/blob - src/approx_const.rs
3ae579a74b9fdc264fa4a3e4762dfd1d8741788e
[rust.git] / src / approx_const.rs
1 use rustc::plugin::Registry;
2 use rustc::lint::*;
3 use rustc::middle::const_eval::lookup_const_by_id;
4 use rustc::middle::def::*;
5 use syntax::ast::*;
6 use syntax::ast_util::{is_comparison_binop, binop_to_string};
7 use syntax::ptr::P;
8 use syntax::codemap::Span;
9 use std::f64::consts as f64;
10 use utils::span_lint;
11
12 declare_lint! {
13     pub APPROX_CONSTANT,
14     Warn,
15     "Warn if a user writes an approximate known constant in their code"
16 }
17
18 const KNOWN_CONSTS : &'static [(f64, &'static str)] = &[(f64::E, "E"), (f64::FRAC_1_PI, "FRAC_1_PI"),
19     (f64::FRAC_1_SQRT_2, "FRAC_1_SQRT_2"), (f64::FRAC_2_PI, "FRAC_2_PI"),
20     (f64::FRAC_2_SQRT_PI, "FRAC_2_SQRT_PI"), (f64::FRAC_PI_2, "FRAC_PI_2"), (f64::FRAC_PI_3, "FRAC_PI_3"),
21     (f64::FRAC_PI_4, "FRAC_PI_4"), (f64::FRAC_PI_6, "FRAC_PI_6"), (f64::FRAC_PI_8, "FRAC_PI_8"),
22     (f64::LN_10, "LN_10"), (f64::LN_2, "LN_2"), (f64::LOG10_E, "LOG10_E"), (f64::LOG2_E, "LOG2_E"),
23     (f64::PI, "PI"), (f64::SQRT_2, "SQRT_2")];
24
25 const EPSILON_DIVISOR : f64 = 8192f64; //TODO: test to find a good value
26
27 #[derive(Copy,Clone)]
28 pub struct ApproxConstant;
29
30 impl LintPass for ApproxConstant {
31     fn get_lints(&self) -> LintArray {
32         lint_array!(APPROX_CONSTANT)
33     }
34
35     fn check_expr(&mut self, cx: &Context, e: &Expr) {
36         if let &ExprLit(ref lit) = &e.node {
37             check_lit(cx, lit, e.span);
38         }
39     }
40 }
41
42 fn check_lit(cx: &Context, lit: &Lit, span: Span) {
43     match &lit.node {
44         &LitFloat(ref str, TyF32) => check_known_consts(cx, span, str, "f32"),
45         &LitFloat(ref str, TyF64) => check_known_consts(cx, span, str, "f64"),
46         &LitFloatUnsuffixed(ref str) => check_known_consts(cx, span, str, "f{32, 64}"),
47         _ => ()
48     }
49 }
50
51 fn check_known_consts(cx: &Context, span: Span, str: &str, module: &str) {
52     if let Ok(value) = str.parse::<f64>() {
53         for &(constant, name) in KNOWN_CONSTS {
54             if within_epsilon(constant, value) {
55                 span_lint(cx, APPROX_CONSTANT, span, &format!(
56                     "Approximate value of {}::{} found, consider using it directly.", module, &name));
57             }
58         }
59     }
60 }
61
62 fn within_epsilon(target: f64, value: f64) -> bool {
63     f64::abs(value - target) < f64::abs((if target > value { target } else { value })) / EPSILON_DIVISOR
64 }