1 //! Lints concerned with the grouping of digits with underscores in integral or
2 //! floating-point literal expressions.
4 use clippy_utils::diagnostics::span_lint_and_sugg;
5 use clippy_utils::numeric_literal::{NumericLiteral, Radix};
6 use clippy_utils::source::snippet_opt;
7 use if_chain::if_chain;
8 use rustc_ast::ast::{Expr, ExprKind, Lit, LitKind};
9 use rustc_errors::Applicability;
10 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
11 use rustc_middle::lint::in_external_macro;
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
15 declare_clippy_lint! {
17 /// Warns if a long integral or floating-point constant does
18 /// not contain underscores.
20 /// ### Why is this bad?
21 /// Reading long numbers is difficult without separators.
33 /// 61_864_918_973_511
36 #[clippy::version = "pre 1.29.0"]
37 pub UNREADABLE_LITERAL,
39 "long literal without underscores"
42 declare_clippy_lint! {
44 /// Warns for mistyped suffix in literals
46 /// ### Why is this bad?
47 /// This is most probably a typo
49 /// ### Known problems
50 /// - Does not match on integers too large to fit in the corresponding unsigned type
51 /// - Does not match on `_127` since that is a valid grouping for decimal and octal numbers
56 /// `250_8 => `250_u8`
58 #[clippy::version = "1.30.0"]
59 pub MISTYPED_LITERAL_SUFFIXES,
61 "mistyped literal suffix"
64 declare_clippy_lint! {
66 /// Warns if an integral or floating-point constant is
67 /// grouped inconsistently with underscores.
69 /// ### Why is this bad?
70 /// Readers may incorrectly interpret inconsistently
76 /// 618_64_9189_73_511
83 /// 61_864_918_973_511
86 #[clippy::version = "pre 1.29.0"]
87 pub INCONSISTENT_DIGIT_GROUPING,
89 "integer literals with digits grouped inconsistently"
92 declare_clippy_lint! {
94 /// Warns if hexadecimal or binary literals are not grouped
95 /// by nibble or byte.
97 /// ### Why is this bad?
98 /// Negatively impacts readability.
102 /// let x: u32 = 0xFFF_FFF;
103 /// let y: u8 = 0b01_011_101;
105 #[clippy::version = "1.49.0"]
106 pub UNUSUAL_BYTE_GROUPINGS,
108 "binary or hex literals that aren't grouped by four"
111 declare_clippy_lint! {
113 /// Warns if the digits of an integral or floating-point
114 /// constant are grouped into groups that
117 /// ### Why is this bad?
118 /// Negatively impacts readability.
122 /// let x: u64 = 6186491_8973511;
124 #[clippy::version = "pre 1.29.0"]
125 pub LARGE_DIGIT_GROUPS,
127 "grouping digits into groups that are too large"
130 declare_clippy_lint! {
132 /// Warns if there is a better representation for a numeric literal.
134 /// ### Why is this bad?
135 /// Especially for big powers of 2 a hexadecimal representation is more
136 /// readable than a decimal representation.
141 /// `65_535` => `0xFFFF`
142 /// `4_042_322_160` => `0xF0F0_F0F0`
144 #[clippy::version = "pre 1.29.0"]
145 pub DECIMAL_LITERAL_REPRESENTATION,
147 "using decimal representation when hexadecimal would be better"
152 InconsistentDigitGrouping,
154 DecimalRepresentation,
155 MistypedLiteralSuffix,
156 UnusualByteGroupings,
160 fn display(&self, suggested_format: String, cx: &EarlyContext<'_>, span: rustc_span::Span) {
162 Self::MistypedLiteralSuffix => span_lint_and_sugg(
164 MISTYPED_LITERAL_SUFFIXES,
166 "mistyped literal suffix",
167 "did you mean to write",
169 Applicability::MaybeIncorrect,
171 Self::UnreadableLiteral => span_lint_and_sugg(
175 "long literal lacking separators",
178 Applicability::MachineApplicable,
180 Self::LargeDigitGroups => span_lint_and_sugg(
184 "digit groups should be smaller",
187 Applicability::MachineApplicable,
189 Self::InconsistentDigitGrouping => span_lint_and_sugg(
191 INCONSISTENT_DIGIT_GROUPING,
193 "digits grouped inconsistently by underscores",
196 Applicability::MachineApplicable,
198 Self::DecimalRepresentation => span_lint_and_sugg(
200 DECIMAL_LITERAL_REPRESENTATION,
202 "integer literal has a better hexadecimal representation",
205 Applicability::MachineApplicable,
207 Self::UnusualByteGroupings => span_lint_and_sugg(
209 UNUSUAL_BYTE_GROUPINGS,
211 "digits of hex or binary literal not grouped by four",
214 Applicability::MachineApplicable,
220 #[derive(Copy, Clone)]
221 pub struct LiteralDigitGrouping {
222 lint_fraction_readability: bool,
225 impl_lint_pass!(LiteralDigitGrouping => [
227 INCONSISTENT_DIGIT_GROUPING,
229 MISTYPED_LITERAL_SUFFIXES,
230 UNUSUAL_BYTE_GROUPINGS,
233 impl EarlyLintPass for LiteralDigitGrouping {
234 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
235 if in_external_macro(cx.sess(), expr.span) {
239 if let ExprKind::Lit(ref lit) = expr.kind {
240 self.check_lit(cx, lit);
245 // Length of each UUID hyphenated group in hex digits.
246 const UUID_GROUP_LENS: [usize; 5] = [8, 4, 4, 4, 12];
248 impl LiteralDigitGrouping {
249 pub fn new(lint_fraction_readability: bool) -> Self {
251 lint_fraction_readability,
255 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
257 if let Some(src) = snippet_opt(cx, lit.span);
258 if let Some(mut num_lit) = NumericLiteral::from_lit(&src, lit);
260 if !Self::check_for_mistyped_suffix(cx, lit.span, &mut num_lit) {
264 if Self::is_literal_uuid_formatted(&mut num_lit) {
270 let integral_group_size = Self::get_group_size(num_lit.integer.split('_'), num_lit.radix, true)?;
271 if let Some(fraction) = num_lit.fraction {
272 let fractional_group_size = Self::get_group_size(
273 fraction.rsplit('_'),
275 self.lint_fraction_readability)?;
277 let consistent = Self::parts_consistent(integral_group_size,
278 fractional_group_size,
279 num_lit.integer.len(),
282 return Err(WarningType::InconsistentDigitGrouping);
290 if let Err(warning_type) = result {
291 let should_warn = match warning_type {
292 | WarningType::UnreadableLiteral
293 | WarningType::InconsistentDigitGrouping
294 | WarningType::UnusualByteGroupings
295 | WarningType::LargeDigitGroups => {
296 !lit.span.from_expansion()
298 WarningType::DecimalRepresentation | WarningType::MistypedLiteralSuffix => {
303 warning_type.display(num_lit.format(), cx, lit.span);
310 // Returns `false` if the check fails
311 fn check_for_mistyped_suffix(
312 cx: &EarlyContext<'_>,
313 span: rustc_span::Span,
314 num_lit: &mut NumericLiteral<'_>,
316 if num_lit.suffix.is_some() {
320 let (part, mistyped_suffixes, is_float) = if let Some((_, exponent)) = &mut num_lit.exponent {
321 (exponent, &["32", "64"][..], true)
322 } else if num_lit.fraction.is_some() {
325 (&mut num_lit.integer, &["8", "16", "32", "64"][..], false)
328 let mut split = part.rsplit('_');
329 let last_group = split.next().expect("At least one group");
330 if split.next().is_some() && mistyped_suffixes.contains(&last_group) {
331 let main_part = &part[..part.len() - last_group.len()];
336 let radix = match num_lit.radix {
339 Radix::Decimal => 10,
340 Radix::Hexadecimal => 16,
342 if let Ok(int) = u64::from_str_radix(&main_part.replace('_', ""), radix) {
343 missing_char = match (last_group, int) {
344 ("8", i) if i8::try_from(i).is_ok() => 'i',
345 ("16", i) if i16::try_from(i).is_ok() => 'i',
346 ("32", i) if i32::try_from(i).is_ok() => 'i',
347 ("64", i) if i64::try_from(i).is_ok() => 'i',
348 ("8", u) if u8::try_from(u).is_ok() => 'u',
349 ("16", u) if u16::try_from(u).is_ok() => 'u',
350 ("32", u) if u32::try_from(u).is_ok() => 'u',
361 let mut sugg = num_lit.format();
363 sugg.push(missing_char);
364 sugg.push_str(last_group);
365 WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
372 /// Checks whether the numeric literal matches the formatting of a UUID.
374 /// Returns `true` if the radix is hexadecimal, and the groups match the
375 /// UUID format of 8-4-4-4-12.
376 fn is_literal_uuid_formatted(num_lit: &mut NumericLiteral<'_>) -> bool {
377 if num_lit.radix != Radix::Hexadecimal {
381 // UUIDs should not have a fraction
382 if num_lit.fraction.is_some() {
386 let group_sizes: Vec<usize> = num_lit.integer.split('_').map(str::len).collect();
387 if UUID_GROUP_LENS.len() == group_sizes.len() {
388 iter::zip(&UUID_GROUP_LENS, &group_sizes).all(|(&a, &b)| a == b)
394 /// Given the sizes of the digit groups of both integral and fractional
395 /// parts, and the length
396 /// of both parts, determine if the digits have been grouped consistently.
399 int_group_size: Option<usize>,
400 frac_group_size: Option<usize>,
404 match (int_group_size, frac_group_size) {
405 // No groups on either side of decimal point - trivially consistent.
406 (None, None) => true,
407 // Integral part has grouped digits, fractional part does not.
408 (Some(int_group_size), None) => frac_size <= int_group_size,
409 // Fractional part has grouped digits, integral part does not.
410 (None, Some(frac_group_size)) => int_size <= frac_group_size,
411 // Both parts have grouped digits. Groups should be the same size.
412 (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
416 /// Returns the size of the digit groups (or None if ungrouped) if successful,
417 /// otherwise returns a `WarningType` for linting.
418 fn get_group_size<'a>(
419 groups: impl Iterator<Item = &'a str>,
421 lint_unreadable: bool,
422 ) -> Result<Option<usize>, WarningType> {
423 let mut groups = groups.map(str::len);
425 let first = groups.next().expect("At least one group");
427 if (radix == Radix::Binary || radix == Radix::Hexadecimal) && groups.any(|i| i != 4 && i != 2) {
428 return Err(WarningType::UnusualByteGroupings);
431 if let Some(second) = groups.next() {
432 if !groups.all(|x| x == second) || first > second {
433 Err(WarningType::InconsistentDigitGrouping)
434 } else if second > 4 {
435 Err(WarningType::LargeDigitGroups)
439 } else if first > 5 && lint_unreadable {
440 Err(WarningType::UnreadableLiteral)
447 #[expect(clippy::module_name_repetitions)]
448 #[derive(Copy, Clone)]
449 pub struct DecimalLiteralRepresentation {
453 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
455 impl EarlyLintPass for DecimalLiteralRepresentation {
456 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
457 if in_external_macro(cx.sess(), expr.span) {
461 if let ExprKind::Lit(ref lit) = expr.kind {
462 self.check_lit(cx, lit);
467 impl DecimalLiteralRepresentation {
469 pub fn new(threshold: u64) -> Self {
472 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
473 // Lint integral literals.
475 if let LitKind::Int(val, _) = lit.kind;
476 if let Some(src) = snippet_opt(cx, lit.span);
477 if let Some(num_lit) = NumericLiteral::from_lit(&src, lit);
478 if num_lit.radix == Radix::Decimal;
479 if val >= u128::from(self.threshold);
481 let hex = format!("{:#X}", val);
482 let num_lit = NumericLiteral::new(&hex, num_lit.suffix, false);
483 let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
484 warning_type.display(num_lit.format(), cx, lit.span);
490 fn do_lint(digits: &str) -> Result<(), WarningType> {
491 if digits.len() == 1 {
492 // Lint for 1 digit literals, if someone really sets the threshold that low
501 return Err(WarningType::DecimalRepresentation);
503 } else if digits.len() < 4 {
504 // Lint for Literals with a hex-representation of 2 or 3 digits
505 let f = &digits[0..1]; // first digit
506 let s = &digits[1..]; // suffix
509 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
510 // Powers of 2 minus 1
511 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
513 return Err(WarningType::DecimalRepresentation);
516 // Lint for Literals with a hex-representation of 4 digits or more
517 let f = &digits[0..1]; // first digit
518 let m = &digits[1..digits.len() - 1]; // middle digits, except last
519 let s = &digits[1..]; // suffix
521 // Powers of 2 with a margin of +15/-16
522 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
523 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
524 // Lint for representations with only 0s and Fs, while allowing 7 as the first
526 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
528 return Err(WarningType::DecimalRepresentation);