1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::numeric_literal;
3 use if_chain::if_chain;
4 use rustc_ast::ast::{self, LitFloatType, LitKind};
5 use rustc_errors::Applicability;
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::ty::{self, FloatTy};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 declare_clippy_lint! {
14 /// Checks for float literals with a precision greater
15 /// than that supported by the underlying type.
17 /// ### Why is this bad?
18 /// Rust will truncate the literal silently.
23 /// let v: f32 = 0.123_456_789_9;
24 /// println!("{}", v); // 0.123_456_789
27 /// let v: f64 = 0.123_456_789_9;
28 /// println!("{}", v); // 0.123_456_789_9
30 pub EXCESSIVE_PRECISION,
32 "excessive precision for float literal"
35 declare_clippy_lint! {
37 /// Checks for whole number float literals that
38 /// cannot be represented as the underlying type without loss.
40 /// ### Why is this bad?
41 /// Rust will silently lose precision during
42 /// conversion to a float.
47 /// let _: f32 = 16_777_217.0; // 16_777_216.0
50 /// let _: f32 = 16_777_216.0;
51 /// let _: f64 = 16_777_217.0;
53 pub LOSSY_FLOAT_LITERAL,
55 "lossy whole number float literals"
58 declare_lint_pass!(FloatLiteral => [EXCESSIVE_PRECISION, LOSSY_FLOAT_LITERAL]);
60 impl<'tcx> LateLintPass<'tcx> for FloatLiteral {
61 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
62 let ty = cx.typeck_results().expr_ty(expr);
64 if let ty::Float(fty) = *ty.kind();
65 if let hir::ExprKind::Lit(ref lit) = expr.kind;
66 if let LitKind::Float(sym, lit_float_ty) = lit.node;
68 let sym_str = sym.as_str();
69 let formatter = FloatFormat::new(&sym_str);
70 // Try to bail out if the float is for sure fine.
71 // If its within the 2 decimal digits of being out of precision we
72 // check if the parsed representation is the same as the string
73 // since we'll need the truncated string anyway.
74 let digits = count_digits(&sym_str);
75 let max = max_digits(fty);
76 let type_suffix = match lit_float_ty {
77 LitFloatType::Suffixed(ast::FloatTy::F32) => Some("f32"),
78 LitFloatType::Suffixed(ast::FloatTy::F64) => Some("f64"),
79 LitFloatType::Unsuffixed => None
81 let (is_whole, mut float_str) = match fty {
83 let value = sym_str.parse::<f32>().unwrap();
85 (value.fract() == 0.0, formatter.format(value))
88 let value = sym_str.parse::<f64>().unwrap();
90 (value.fract() == 0.0, formatter.format(value))
94 if is_whole && !sym_str.contains(|c| c == 'e' || c == 'E') {
95 // Normalize the literal by stripping the fractional portion
96 if sym_str.split('.').next().unwrap() != float_str {
97 // If the type suffix is missing the suggestion would be
98 // incorrectly interpreted as an integer so adding a `.0`
99 // suffix to prevent that.
100 if type_suffix.is_none() {
101 float_str.push_str(".0");
108 "literal cannot be represented as the underlying type without loss of precision",
109 "consider changing the type or replacing it with",
110 numeric_literal::format(&float_str, type_suffix, true),
111 Applicability::MachineApplicable,
114 } else if digits > max as usize && sym_str != float_str {
119 "float has excessive precision",
120 "consider changing the type or truncating it to",
121 numeric_literal::format(&float_str, type_suffix, true),
122 Applicability::MachineApplicable,
131 fn max_digits(fty: FloatTy) -> u32 {
133 FloatTy::F32 => f32::DIGITS,
134 FloatTy::F64 => f64::DIGITS,
138 /// Counts the digits excluding leading zeros
140 fn count_digits(s: &str) -> usize {
141 // Note that s does not contain the f32/64 suffix, and underscores have been stripped
143 .filter(|c| *c != '-' && *c != '.')
144 .take_while(|c| *c != 'e' && *c != 'E')
145 .fold(0, |count, c| {
147 if c == '0' && count == 0 { count } else { count + 1 }
158 fn new(s: &str) -> Self {
160 .find_map(|x| match x {
161 'e' => Some(Self::LowerExp),
162 'E' => Some(Self::UpperExp),
165 .unwrap_or(Self::Normal)
167 fn format<T>(&self, f: T) -> String
169 T: fmt::UpperExp + fmt::LowerExp + fmt::Display,
172 Self::LowerExp => format!("{:e}", f),
173 Self::UpperExp => format!("{:E}", f),
174 Self::Normal => format!("{}", f),