3 use rustc::ty::TypeVariants;
8 use syntax_pos::symbol::Symbol;
9 use crate::utils::span_lint_and_sugg;
11 /// **What it does:** Checks for float literals with a precision greater
12 /// than that supported by the underlying type
14 /// **Why is this bad?** Rust will truncate the literal silently.
16 /// **Known problems:** None.
22 /// let v: f32 = 0.123_456_789_9;
23 /// println!("{}", v); // 0.123_456_789
26 /// let v: f64 = 0.123_456_789_9;
27 /// println!("{}", v); // 0.123_456_789_9
29 declare_clippy_lint! {
30 pub EXCESSIVE_PRECISION,
32 "excessive precision for float literal"
35 pub struct ExcessivePrecision;
37 impl LintPass for ExcessivePrecision {
38 fn get_lints(&self) -> LintArray {
39 lint_array!(EXCESSIVE_PRECISION)
43 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExcessivePrecision {
44 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
46 let ty = cx.tables.expr_ty(expr);
47 if let TypeVariants::TyFloat(fty) = ty.sty;
48 if let hir::ExprKind::Lit(ref lit) = expr.node;
49 if let LitKind::Float(sym, _) | LitKind::FloatUnsuffixed(sym) = lit.node;
50 if let Some(sugg) = self.check(sym, fty);
56 "float has excessive precision",
57 "consider changing the type or truncating it to",
65 impl ExcessivePrecision {
66 // None if nothing to lint, Some(suggestion) if lint neccessary
67 fn check(&self, sym: Symbol, fty: FloatTy) -> Option<String> {
68 let max = max_digits(fty);
69 let sym_str = sym.as_str();
70 if dot_zero_exclusion(&sym_str) {
73 // Try to bail out if the float is for sure fine.
74 // If its within the 2 decimal digits of being out of precision we
75 // check if the parsed representation is the same as the string
76 // since we'll need the truncated string anyway.
77 let digits = count_digits(&sym_str);
78 if digits > max as usize {
79 let formatter = FloatFormat::new(&sym_str);
81 FloatTy::F32 => sym_str.parse::<f32>().map(|f| formatter.format(f)),
82 FloatTy::F64 => sym_str.parse::<f64>().map(|f| formatter.format(f)),
84 // We know this will parse since we are in LatePass
90 let di = super::literal_representation::DigitInfo::new(&s, true);
91 Some(di.grouping_hint())
99 /// Should we exclude the float because it has a .0 suffix
100 /// Ex 1_000_000_000.0
101 fn dot_zero_exclusion(s: &str) -> bool {
102 if let Some(after_dec) = s.split('.').nth(1) {
103 let mut decpart = after_dec
105 .take_while(|c| *c != 'e' || *c != 'E');
107 match decpart.next() {
108 Some('0') => decpart.count() == 0,
116 fn max_digits(fty: FloatTy) -> u32 {
118 FloatTy::F32 => f32::DIGITS,
119 FloatTy::F64 => f64::DIGITS,
123 /// Counts the digits excluding leading zeros
124 fn count_digits(s: &str) -> usize {
125 // Note that s does not contain the f32/64 suffix
127 .filter(|c| *c != '-' || *c != '.')
128 .take_while(|c| *c != 'e' || *c != 'E')
129 .fold(0, |count, c| {
131 if c == '0' && count == 0 {
145 fn new(s: &str) -> Self {
147 .find_map(|x| match x {
148 'e' => Some(FloatFormat::LowerExp),
149 'E' => Some(FloatFormat::UpperExp),
152 .unwrap_or(FloatFormat::Normal)
154 fn format<T>(&self, f: T) -> String
155 where T: fmt::UpperExp + fmt::LowerExp + fmt::Display {
157 FloatFormat::LowerExp => format!("{:e}", f),
158 FloatFormat::UpperExp => format!("{:E}", f),
159 FloatFormat::Normal => format!("{}", f),