1 use crate::utils::span_lint_and_sugg;
2 use if_chain::if_chain;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7 use rustc_errors::Applicability;
12 use syntax_pos::symbol::Symbol;
14 declare_clippy_lint! {
15 /// **What it does:** Checks for float literals with a precision greater
16 /// than that supported by the underlying type
18 /// **Why is this bad?** Rust will truncate the literal silently.
20 /// **Known problems:** None.
26 /// let v: f32 = 0.123_456_789_9;
27 /// println!("{}", v); // 0.123_456_789
30 /// let v: f64 = 0.123_456_789_9;
31 /// println!("{}", v); // 0.123_456_789_9
33 pub EXCESSIVE_PRECISION,
35 "excessive precision for float literal"
38 declare_lint_pass!(ExcessivePrecision => [EXCESSIVE_PRECISION]);
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExcessivePrecision {
41 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
43 let ty = cx.tables.expr_ty(expr);
44 if let ty::Float(fty) = ty.kind;
45 if let hir::ExprKind::Lit(ref lit) = expr.kind;
46 if let LitKind::Float(sym, _) = lit.node;
47 if let Some(sugg) = Self::check(sym, fty);
53 "float has excessive precision",
54 "consider changing the type or truncating it to",
56 Applicability::MachineApplicable,
63 impl ExcessivePrecision {
64 // None if nothing to lint, Some(suggestion) if lint necessary
66 fn check(sym: Symbol, fty: FloatTy) -> Option<String> {
67 let max = max_digits(fty);
68 let sym_str = sym.as_str();
69 if dot_zero_exclusion(&sym_str) {
72 // Try to bail out if the float is for sure fine.
73 // If its within the 2 decimal digits of being out of precision we
74 // check if the parsed representation is the same as the string
75 // since we'll need the truncated string anyway.
76 let digits = count_digits(&sym_str);
77 if digits > max as usize {
78 let formatter = FloatFormat::new(&sym_str);
80 FloatTy::F32 => sym_str.parse::<f32>().map(|f| formatter.format(f)),
81 FloatTy::F64 => sym_str.parse::<f64>().map(|f| formatter.format(f)),
83 // We know this will parse since we are in LatePass
89 let di = super::literal_representation::DigitInfo::new(&s, true);
90 Some(di.grouping_hint())
98 /// Should we exclude the float because it has a `.0` or `.` suffix
99 /// Ex `1_000_000_000.0`
100 /// Ex `1_000_000_000.`
102 fn dot_zero_exclusion(s: &str) -> bool {
103 s.split('.').nth(1).map_or(false, |after_dec| {
104 let mut decpart = after_dec.chars().take_while(|c| *c != 'e' || *c != 'E');
106 match decpart.next() {
107 Some('0') => decpart.count() == 0,
115 fn max_digits(fty: FloatTy) -> u32 {
117 FloatTy::F32 => f32::DIGITS,
118 FloatTy::F64 => f64::DIGITS,
122 /// Counts the digits excluding leading zeros
124 fn count_digits(s: &str) -> usize {
125 // Note that s does not contain the f32/64 suffix, and underscores have been stripped
127 .filter(|c| *c != '-' && *c != '.')
128 .take_while(|c| *c != 'e' && *c != 'E')
129 .fold(0, |count, c| {
131 if c == '0' && count == 0 {
146 fn new(s: &str) -> Self {
148 .find_map(|x| match x {
149 'e' => Some(Self::LowerExp),
150 'E' => Some(Self::UpperExp),
153 .unwrap_or(Self::Normal)
155 fn format<T>(&self, f: T) -> String
157 T: fmt::UpperExp + fmt::LowerExp + fmt::Display,
160 Self::LowerExp => format!("{:e}", f),
161 Self::UpperExp => format!("{:E}", f),
162 Self::Normal => format!("{}", f),