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, LitKind};
10 use rustc_errors::Applicability;
11 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
12 use rustc_middle::lint::in_external_macro;
13 use rustc_session::{declare_tool_lint, impl_lint_pass};
17 declare_clippy_lint! {
19 /// Warns if a long integral or floating-point constant does
20 /// not contain underscores.
22 /// ### Why is this bad?
23 /// Reading long numbers is difficult without separators.
35 /// 61_864_918_973_511
38 #[clippy::version = "pre 1.29.0"]
39 pub UNREADABLE_LITERAL,
41 "long literal without underscores"
44 declare_clippy_lint! {
46 /// Warns for mistyped suffix in literals
48 /// ### Why is this bad?
49 /// This is most probably a typo
51 /// ### Known problems
52 /// - Does not match on integers too large to fit in the corresponding unsigned type
53 /// - Does not match on `_127` since that is a valid grouping for decimal and octal numbers
58 /// `250_8 => `250_u8`
60 #[clippy::version = "1.30.0"]
61 pub MISTYPED_LITERAL_SUFFIXES,
63 "mistyped literal suffix"
66 declare_clippy_lint! {
68 /// Warns if an integral or floating-point constant is
69 /// grouped inconsistently with underscores.
71 /// ### Why is this bad?
72 /// Readers may incorrectly interpret inconsistently
78 /// 618_64_9189_73_511
85 /// 61_864_918_973_511
88 #[clippy::version = "pre 1.29.0"]
89 pub INCONSISTENT_DIGIT_GROUPING,
91 "integer literals with digits grouped inconsistently"
94 declare_clippy_lint! {
96 /// Warns if hexadecimal or binary literals are not grouped
97 /// by nibble or byte.
99 /// ### Why is this bad?
100 /// Negatively impacts readability.
104 /// let x: u32 = 0xFFF_FFF;
105 /// let y: u8 = 0b01_011_101;
107 #[clippy::version = "1.49.0"]
108 pub UNUSUAL_BYTE_GROUPINGS,
110 "binary or hex literals that aren't grouped by four"
113 declare_clippy_lint! {
115 /// Warns if the digits of an integral or floating-point
116 /// constant are grouped into groups that
119 /// ### Why is this bad?
120 /// Negatively impacts readability.
124 /// let x: u64 = 6186491_8973511;
126 #[clippy::version = "pre 1.29.0"]
127 pub LARGE_DIGIT_GROUPS,
129 "grouping digits into groups that are too large"
132 declare_clippy_lint! {
134 /// Warns if there is a better representation for a numeric literal.
136 /// ### Why is this bad?
137 /// Especially for big powers of 2 a hexadecimal representation is more
138 /// readable than a decimal representation.
143 /// `65_535` => `0xFFFF`
144 /// `4_042_322_160` => `0xF0F0_F0F0`
146 #[clippy::version = "pre 1.29.0"]
147 pub DECIMAL_LITERAL_REPRESENTATION,
149 "using decimal representation when hexadecimal would be better"
154 InconsistentDigitGrouping,
156 DecimalRepresentation,
157 MistypedLiteralSuffix,
158 UnusualByteGroupings,
162 fn display(&self, suggested_format: String, cx: &EarlyContext<'_>, span: rustc_span::Span) {
164 Self::MistypedLiteralSuffix => span_lint_and_sugg(
166 MISTYPED_LITERAL_SUFFIXES,
168 "mistyped literal suffix",
169 "did you mean to write",
171 Applicability::MaybeIncorrect,
173 Self::UnreadableLiteral => span_lint_and_sugg(
177 "long literal lacking separators",
180 Applicability::MachineApplicable,
182 Self::LargeDigitGroups => span_lint_and_sugg(
186 "digit groups should be smaller",
189 Applicability::MachineApplicable,
191 Self::InconsistentDigitGrouping => span_lint_and_sugg(
193 INCONSISTENT_DIGIT_GROUPING,
195 "digits grouped inconsistently by underscores",
198 Applicability::MachineApplicable,
200 Self::DecimalRepresentation => span_lint_and_sugg(
202 DECIMAL_LITERAL_REPRESENTATION,
204 "integer literal has a better hexadecimal representation",
207 Applicability::MachineApplicable,
209 Self::UnusualByteGroupings => span_lint_and_sugg(
211 UNUSUAL_BYTE_GROUPINGS,
213 "digits of hex or binary literal not grouped by four",
216 Applicability::MachineApplicable,
222 #[derive(Copy, Clone)]
223 pub struct LiteralDigitGrouping {
224 lint_fraction_readability: bool,
227 impl_lint_pass!(LiteralDigitGrouping => [
229 INCONSISTENT_DIGIT_GROUPING,
231 MISTYPED_LITERAL_SUFFIXES,
232 UNUSUAL_BYTE_GROUPINGS,
235 impl EarlyLintPass for LiteralDigitGrouping {
236 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
237 if in_external_macro(cx.sess(), expr.span) {
241 if let ExprKind::Lit(lit) = expr.kind {
242 self.check_lit(cx, lit, expr.span);
247 // Length of each UUID hyphenated group in hex digits.
248 const UUID_GROUP_LENS: [usize; 5] = [8, 4, 4, 4, 12];
250 impl LiteralDigitGrouping {
251 pub fn new(lint_fraction_readability: bool) -> Self {
253 lint_fraction_readability,
257 fn check_lit(self, cx: &EarlyContext<'_>, lit: token::Lit, span: Span) {
259 if let Some(src) = snippet_opt(cx, span);
260 if let Ok(lit_kind) = LitKind::from_token_lit(lit);
261 if let Some(mut num_lit) = NumericLiteral::from_lit_kind(&src, &lit_kind);
263 if !Self::check_for_mistyped_suffix(cx, span, &mut num_lit) {
267 if Self::is_literal_uuid_formatted(&mut num_lit) {
273 let integral_group_size = Self::get_group_size(num_lit.integer.split('_'), num_lit.radix, true)?;
274 if let Some(fraction) = num_lit.fraction {
275 let fractional_group_size = Self::get_group_size(
276 fraction.rsplit('_'),
278 self.lint_fraction_readability)?;
280 let consistent = Self::parts_consistent(integral_group_size,
281 fractional_group_size,
282 num_lit.integer.len(),
285 return Err(WarningType::InconsistentDigitGrouping);
293 if let Err(warning_type) = result {
294 let should_warn = match warning_type {
295 | WarningType::UnreadableLiteral
296 | WarningType::InconsistentDigitGrouping
297 | WarningType::UnusualByteGroupings
298 | WarningType::LargeDigitGroups => {
299 !span.from_expansion()
301 WarningType::DecimalRepresentation | WarningType::MistypedLiteralSuffix => {
306 warning_type.display(num_lit.format(), cx, span);
313 // Returns `false` if the check fails
314 fn check_for_mistyped_suffix(
315 cx: &EarlyContext<'_>,
316 span: rustc_span::Span,
317 num_lit: &mut NumericLiteral<'_>,
319 if num_lit.suffix.is_some() {
323 let (part, mistyped_suffixes, is_float) = if let Some((_, exponent)) = &mut num_lit.exponent {
324 (exponent, &["32", "64"][..], true)
325 } else if num_lit.fraction.is_some() {
328 (&mut num_lit.integer, &["8", "16", "32", "64"][..], false)
331 let mut split = part.rsplit('_');
332 let last_group = split.next().expect("At least one group");
333 if split.next().is_some() && mistyped_suffixes.contains(&last_group) {
334 let main_part = &part[..part.len() - last_group.len()];
339 let radix = match num_lit.radix {
342 Radix::Decimal => 10,
343 Radix::Hexadecimal => 16,
345 if let Ok(int) = u64::from_str_radix(&main_part.replace('_', ""), radix) {
346 missing_char = match (last_group, int) {
347 ("8", i) if i8::try_from(i).is_ok() => 'i',
348 ("16", i) if i16::try_from(i).is_ok() => 'i',
349 ("32", i) if i32::try_from(i).is_ok() => 'i',
350 ("64", i) if i64::try_from(i).is_ok() => 'i',
351 ("8", u) if u8::try_from(u).is_ok() => 'u',
352 ("16", u) if u16::try_from(u).is_ok() => 'u',
353 ("32", u) if u32::try_from(u).is_ok() => 'u',
364 let mut sugg = num_lit.format();
366 sugg.push(missing_char);
367 sugg.push_str(last_group);
368 WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
375 /// Checks whether the numeric literal matches the formatting of a UUID.
377 /// Returns `true` if the radix is hexadecimal, and the groups match the
378 /// UUID format of 8-4-4-4-12.
379 fn is_literal_uuid_formatted(num_lit: &mut NumericLiteral<'_>) -> bool {
380 if num_lit.radix != Radix::Hexadecimal {
384 // UUIDs should not have a fraction
385 if num_lit.fraction.is_some() {
389 let group_sizes: Vec<usize> = num_lit.integer.split('_').map(str::len).collect();
390 if UUID_GROUP_LENS.len() == group_sizes.len() {
391 iter::zip(&UUID_GROUP_LENS, &group_sizes).all(|(&a, &b)| a == b)
397 /// Given the sizes of the digit groups of both integral and fractional
398 /// parts, and the length
399 /// of both parts, determine if the digits have been grouped consistently.
402 int_group_size: Option<usize>,
403 frac_group_size: Option<usize>,
407 match (int_group_size, frac_group_size) {
408 // No groups on either side of decimal point - trivially consistent.
409 (None, None) => true,
410 // Integral part has grouped digits, fractional part does not.
411 (Some(int_group_size), None) => frac_size <= int_group_size,
412 // Fractional part has grouped digits, integral part does not.
413 (None, Some(frac_group_size)) => int_size <= frac_group_size,
414 // Both parts have grouped digits. Groups should be the same size.
415 (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
419 /// Returns the size of the digit groups (or None if ungrouped) if successful,
420 /// otherwise returns a `WarningType` for linting.
421 fn get_group_size<'a>(
422 groups: impl Iterator<Item = &'a str>,
424 lint_unreadable: bool,
425 ) -> Result<Option<usize>, WarningType> {
426 let mut groups = groups.map(str::len);
428 let first = groups.next().expect("At least one group");
430 if (radix == Radix::Binary || radix == Radix::Hexadecimal) && groups.any(|i| i != 4 && i != 2) {
431 return Err(WarningType::UnusualByteGroupings);
434 if let Some(second) = groups.next() {
435 if !groups.all(|x| x == second) || first > second {
436 Err(WarningType::InconsistentDigitGrouping)
437 } else if second > 4 {
438 Err(WarningType::LargeDigitGroups)
442 } else if first > 5 && lint_unreadable {
443 Err(WarningType::UnreadableLiteral)
450 #[expect(clippy::module_name_repetitions)]
451 #[derive(Copy, Clone)]
452 pub struct DecimalLiteralRepresentation {
456 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
458 impl EarlyLintPass for DecimalLiteralRepresentation {
459 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
460 if in_external_macro(cx.sess(), expr.span) {
464 if let ExprKind::Lit(lit) = expr.kind {
465 self.check_lit(cx, lit, expr.span);
470 impl DecimalLiteralRepresentation {
472 pub fn new(threshold: u64) -> Self {
475 fn check_lit(self, cx: &EarlyContext<'_>, lit: token::Lit, span: Span) {
476 // Lint integral literals.
478 if let Ok(lit_kind) = LitKind::from_token_lit(lit);
479 if let LitKind::Int(val, _) = lit_kind;
480 if let Some(src) = snippet_opt(cx, span);
481 if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit_kind);
482 if num_lit.radix == Radix::Decimal;
483 if val >= u128::from(self.threshold);
485 let hex = format!("{val:#X}");
486 let num_lit = NumericLiteral::new(&hex, num_lit.suffix, false);
487 let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
488 warning_type.display(num_lit.format(), cx, span);
494 fn do_lint(digits: &str) -> Result<(), WarningType> {
495 if digits.len() == 1 {
496 // Lint for 1 digit literals, if someone really sets the threshold that low
505 return Err(WarningType::DecimalRepresentation);
507 } else if digits.len() < 4 {
508 // Lint for Literals with a hex-representation of 2 or 3 digits
509 let f = &digits[0..1]; // first digit
510 let s = &digits[1..]; // suffix
513 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
514 // Powers of 2 minus 1
515 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
517 return Err(WarningType::DecimalRepresentation);
520 // Lint for Literals with a hex-representation of 4 digits or more
521 let f = &digits[0..1]; // first digit
522 let m = &digits[1..digits.len() - 1]; // middle digits, except last
523 let s = &digits[1..]; // suffix
525 // Powers of 2 with a margin of +15/-16
526 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
527 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
528 // Lint for representations with only 0s and Fs, while allowing 7 as the first
530 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
532 return Err(WarningType::DecimalRepresentation);