3 use syntax::codemap::Span;
4 use std::f64::consts as f64;
11 "the approximate of a known float constant (in `std::f64::consts` or `std::f32::consts`) \
12 is found; suggests to use the constant"
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")];
22 const EPSILON_DIVISOR : f64 = 8192f64; //TODO: test to find a good value
25 pub struct ApproxConstant;
27 impl LintPass for ApproxConstant {
28 fn get_lints(&self) -> LintArray {
29 lint_array!(APPROX_CONSTANT)
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);
39 fn check_lit(cx: &Context, lit: &Lit, span: Span) {
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}"),
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));
59 fn within_epsilon(target: f64, value: f64) -> bool {
60 f64::abs(value - target) < f64::abs((if target > value { target } else { value })) / EPSILON_DIVISOR