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 #[clippy::version = "pre 1.29.0"]
31 pub EXCESSIVE_PRECISION,
33 "excessive precision for float literal"
36 declare_clippy_lint! {
38 /// Checks for whole number float literals that
39 /// cannot be represented as the underlying type without loss.
41 /// ### Why is this bad?
42 /// Rust will silently lose precision during
43 /// conversion to a float.
48 /// let _: f32 = 16_777_217.0; // 16_777_216.0
51 /// let _: f32 = 16_777_216.0;
52 /// let _: f64 = 16_777_217.0;
54 #[clippy::version = "1.43.0"]
55 pub LOSSY_FLOAT_LITERAL,
57 "lossy whole number float literals"
60 declare_lint_pass!(FloatLiteral => [EXCESSIVE_PRECISION, LOSSY_FLOAT_LITERAL]);
62 impl<'tcx> LateLintPass<'tcx> for FloatLiteral {
63 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
64 let ty = cx.typeck_results().expr_ty(expr);
66 if let ty::Float(fty) = *ty.kind();
67 if let hir::ExprKind::Lit(ref lit) = expr.kind;
68 if let LitKind::Float(sym, lit_float_ty) = lit.node;
70 let sym_str = sym.as_str();
71 let formatter = FloatFormat::new(&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 let max = max_digits(fty);
78 let type_suffix = match lit_float_ty {
79 LitFloatType::Suffixed(ast::FloatTy::F32) => Some("f32"),
80 LitFloatType::Suffixed(ast::FloatTy::F64) => Some("f64"),
81 LitFloatType::Unsuffixed => None
83 let (is_whole, mut float_str) = match fty {
85 let value = sym_str.parse::<f32>().unwrap();
87 (value.fract() == 0.0, formatter.format(value))
90 let value = sym_str.parse::<f64>().unwrap();
92 (value.fract() == 0.0, formatter.format(value))
96 if is_whole && !sym_str.contains(|c| c == 'e' || c == 'E') {
97 // Normalize the literal by stripping the fractional portion
98 if sym_str.split('.').next().unwrap() != float_str {
99 // If the type suffix is missing the suggestion would be
100 // incorrectly interpreted as an integer so adding a `.0`
101 // suffix to prevent that.
102 if type_suffix.is_none() {
103 float_str.push_str(".0");
110 "literal cannot be represented as the underlying type without loss of precision",
111 "consider changing the type or replacing it with",
112 numeric_literal::format(&float_str, type_suffix, true),
113 Applicability::MachineApplicable,
116 } else if digits > max as usize && float_str.len() < sym_str.len() {
121 "float has excessive precision",
122 "consider changing the type or truncating it to",
123 numeric_literal::format(&float_str, type_suffix, true),
124 Applicability::MachineApplicable,
133 fn max_digits(fty: FloatTy) -> u32 {
135 FloatTy::F32 => f32::DIGITS,
136 FloatTy::F64 => f64::DIGITS,
140 /// Counts the digits excluding leading zeros
142 fn count_digits(s: &str) -> usize {
143 // Note that s does not contain the f32/64 suffix, and underscores have been stripped
145 .filter(|c| *c != '-' && *c != '.')
146 .take_while(|c| *c != 'e' && *c != 'E')
147 .fold(0, |count, c| {
149 if c == '0' && count == 0 { count } else { count + 1 }
160 fn new(s: &str) -> Self {
162 .find_map(|x| match x {
163 'e' => Some(Self::LowerExp),
164 'E' => Some(Self::UpperExp),
167 .unwrap_or(Self::Normal)
169 fn format<T>(&self, f: T) -> String
171 T: fmt::UpperExp + fmt::LowerExp + fmt::Display,
174 Self::LowerExp => format!("{:e}", f),
175 Self::UpperExp => format!("{:E}", f),
176 Self::Normal => format!("{}", f),