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::source::snippet_opt;
8 numeric_literal::{NumericLiteral, Radix},
10 use if_chain::if_chain;
11 use rustc_ast::ast::{Expr, ExprKind, Lit, LitKind};
12 use rustc_errors::Applicability;
13 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
14 use rustc_middle::lint::in_external_macro;
15 use rustc_session::{declare_tool_lint, impl_lint_pass};
18 declare_clippy_lint! {
19 /// **What it does:** Warns if a long integral or floating-point constant does
20 /// not contain underscores.
22 /// **Why is this bad?** Reading long numbers is difficult without separators.
24 /// **Known problems:** None.
30 /// let x: u64 = 61864918973511;
33 /// let x: u64 = 61_864_918_973_511;
35 pub UNREADABLE_LITERAL,
37 "long literal without underscores"
40 declare_clippy_lint! {
41 /// **What it does:** Warns for mistyped suffix in literals
43 /// **Why is this bad?** This is most probably a typo
45 /// **Known problems:**
46 /// - Recommends a signed suffix, even though the number might be too big and an unsigned
47 /// suffix is required
48 /// - Does not match on `_127` since that is a valid grouping for decimal and octal numbers
53 /// // Probably mistyped
59 pub MISTYPED_LITERAL_SUFFIXES,
61 "mistyped literal suffix"
64 declare_clippy_lint! {
65 /// **What it does:** Warns if an integral or floating-point constant is
66 /// grouped inconsistently with underscores.
68 /// **Why is this bad?** Readers may incorrectly interpret inconsistently
71 /// **Known problems:** None.
77 /// let x: u64 = 618_64_9189_73_511;
80 /// let x: u64 = 61_864_918_973_511;
82 pub INCONSISTENT_DIGIT_GROUPING,
84 "integer literals with digits grouped inconsistently"
87 declare_clippy_lint! {
88 /// **What it does:** Warns if hexadecimal or binary literals are not grouped
89 /// by nibble or byte.
91 /// **Why is this bad?** Negatively impacts readability.
93 /// **Known problems:** None.
98 /// let x: u32 = 0xFFF_FFF;
99 /// let y: u8 = 0b01_011_101;
101 pub UNUSUAL_BYTE_GROUPINGS,
103 "binary or hex literals that aren't grouped by four"
106 declare_clippy_lint! {
107 /// **What it does:** Warns if the digits of an integral or floating-point
108 /// constant are grouped into groups that
111 /// **Why is this bad?** Negatively impacts readability.
113 /// **Known problems:** None.
118 /// let x: u64 = 6186491_8973511;
120 pub LARGE_DIGIT_GROUPS,
122 "grouping digits into groups that are too large"
125 declare_clippy_lint! {
126 /// **What it does:** Warns if there is a better representation for a numeric literal.
128 /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
129 /// readable than a decimal representation.
131 /// **Known problems:** None.
136 /// `65_535` => `0xFFFF`
137 /// `4_042_322_160` => `0xF0F0_F0F0`
138 pub DECIMAL_LITERAL_REPRESENTATION,
140 "using decimal representation when hexadecimal would be better"
145 InconsistentDigitGrouping,
147 DecimalRepresentation,
148 MistypedLiteralSuffix,
149 UnusualByteGroupings,
153 fn display(&self, suggested_format: String, cx: &EarlyContext<'_>, span: rustc_span::Span) {
155 Self::MistypedLiteralSuffix => span_lint_and_sugg(
157 MISTYPED_LITERAL_SUFFIXES,
159 "mistyped literal suffix",
160 "did you mean to write",
162 Applicability::MaybeIncorrect,
164 Self::UnreadableLiteral => span_lint_and_sugg(
168 "long literal lacking separators",
171 Applicability::MachineApplicable,
173 Self::LargeDigitGroups => span_lint_and_sugg(
177 "digit groups should be smaller",
180 Applicability::MachineApplicable,
182 Self::InconsistentDigitGrouping => span_lint_and_sugg(
184 INCONSISTENT_DIGIT_GROUPING,
186 "digits grouped inconsistently by underscores",
189 Applicability::MachineApplicable,
191 Self::DecimalRepresentation => span_lint_and_sugg(
193 DECIMAL_LITERAL_REPRESENTATION,
195 "integer literal has a better hexadecimal representation",
198 Applicability::MachineApplicable,
200 Self::UnusualByteGroupings => span_lint_and_sugg(
202 UNUSUAL_BYTE_GROUPINGS,
204 "digits of hex or binary literal not grouped by four",
207 Applicability::MachineApplicable,
213 #[allow(clippy::module_name_repetitions)]
214 #[derive(Copy, Clone)]
215 pub struct LiteralDigitGrouping {
216 lint_fraction_readability: bool,
219 impl_lint_pass!(LiteralDigitGrouping => [
221 INCONSISTENT_DIGIT_GROUPING,
223 MISTYPED_LITERAL_SUFFIXES,
224 UNUSUAL_BYTE_GROUPINGS,
227 impl EarlyLintPass for LiteralDigitGrouping {
228 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
229 if in_external_macro(cx.sess(), expr.span) {
233 if let ExprKind::Lit(ref lit) = expr.kind {
234 self.check_lit(cx, lit)
239 // Length of each UUID hyphenated group in hex digits.
240 const UUID_GROUP_LENS: [usize; 5] = [8, 4, 4, 4, 12];
242 impl LiteralDigitGrouping {
243 pub fn new(lint_fraction_readability: bool) -> Self {
245 lint_fraction_readability,
249 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
251 if let Some(src) = snippet_opt(cx, lit.span);
252 if let Some(mut num_lit) = NumericLiteral::from_lit(&src, &lit);
254 if !Self::check_for_mistyped_suffix(cx, lit.span, &mut num_lit) {
258 if Self::is_literal_uuid_formatted(&mut num_lit) {
264 let integral_group_size = Self::get_group_size(num_lit.integer.split('_'), num_lit.radix, true)?;
265 if let Some(fraction) = num_lit.fraction {
266 let fractional_group_size = Self::get_group_size(
267 fraction.rsplit('_'),
269 self.lint_fraction_readability)?;
271 let consistent = Self::parts_consistent(integral_group_size,
272 fractional_group_size,
273 num_lit.integer.len(),
276 return Err(WarningType::InconsistentDigitGrouping);
284 if let Err(warning_type) = result {
285 let should_warn = match warning_type {
286 | WarningType::UnreadableLiteral
287 | WarningType::InconsistentDigitGrouping
288 | WarningType::UnusualByteGroupings
289 | WarningType::LargeDigitGroups => {
292 WarningType::DecimalRepresentation | WarningType::MistypedLiteralSuffix => {
297 warning_type.display(num_lit.format(), cx, lit.span)
304 // Returns `false` if the check fails
305 fn check_for_mistyped_suffix(
306 cx: &EarlyContext<'_>,
307 span: rustc_span::Span,
308 num_lit: &mut NumericLiteral<'_>,
310 if num_lit.suffix.is_some() {
314 let (part, mistyped_suffixes, missing_char) = if let Some((_, exponent)) = &mut num_lit.exponent {
315 (exponent, &["32", "64"][..], 'f')
316 } else if num_lit.fraction.is_some() {
317 (&mut num_lit.integer, &["32", "64"][..], 'f')
319 (&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i')
322 let mut split = part.rsplit('_');
323 let last_group = split.next().expect("At least one group");
324 if split.next().is_some() && mistyped_suffixes.contains(&last_group) {
325 *part = &part[..part.len() - last_group.len()];
326 let mut sugg = num_lit.format();
328 sugg.push(missing_char);
329 sugg.push_str(last_group);
330 WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
337 /// Checks whether the numeric literal matches the formatting of a UUID.
339 /// Returns `true` if the radix is hexadecimal, and the groups match the
340 /// UUID format of 8-4-4-4-12.
341 fn is_literal_uuid_formatted(num_lit: &mut NumericLiteral<'_>) -> bool {
342 if num_lit.radix != Radix::Hexadecimal {
346 // UUIDs should not have a fraction
347 if num_lit.fraction.is_some() {
351 let group_sizes: Vec<usize> = num_lit.integer.split('_').map(str::len).collect();
352 if UUID_GROUP_LENS.len() == group_sizes.len() {
353 iter::zip(&UUID_GROUP_LENS, &group_sizes).all(|(&a, &b)| a == b)
359 /// Given the sizes of the digit groups of both integral and fractional
360 /// parts, and the length
361 /// of both parts, determine if the digits have been grouped consistently.
364 int_group_size: Option<usize>,
365 frac_group_size: Option<usize>,
369 match (int_group_size, frac_group_size) {
370 // No groups on either side of decimal point - trivially consistent.
371 (None, None) => true,
372 // Integral part has grouped digits, fractional part does not.
373 (Some(int_group_size), None) => frac_size <= int_group_size,
374 // Fractional part has grouped digits, integral part does not.
375 (None, Some(frac_group_size)) => int_size <= frac_group_size,
376 // Both parts have grouped digits. Groups should be the same size.
377 (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
381 /// Returns the size of the digit groups (or None if ungrouped) if successful,
382 /// otherwise returns a `WarningType` for linting.
383 fn get_group_size<'a>(
384 groups: impl Iterator<Item = &'a str>,
386 lint_unreadable: bool,
387 ) -> Result<Option<usize>, WarningType> {
388 let mut groups = groups.map(str::len);
390 let first = groups.next().expect("At least one group");
392 if (radix == Radix::Binary || radix == Radix::Hexadecimal) && groups.any(|i| i != 4 && i != 2) {
393 return Err(WarningType::UnusualByteGroupings);
396 if let Some(second) = groups.next() {
397 if !groups.all(|x| x == second) || first > second {
398 Err(WarningType::InconsistentDigitGrouping)
399 } else if second > 4 {
400 Err(WarningType::LargeDigitGroups)
404 } else if first > 5 && lint_unreadable {
405 Err(WarningType::UnreadableLiteral)
412 #[allow(clippy::module_name_repetitions)]
413 #[derive(Copy, Clone)]
414 pub struct DecimalLiteralRepresentation {
418 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
420 impl EarlyLintPass for DecimalLiteralRepresentation {
421 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
422 if in_external_macro(cx.sess(), expr.span) {
426 if let ExprKind::Lit(ref lit) = expr.kind {
427 self.check_lit(cx, lit)
432 impl DecimalLiteralRepresentation {
434 pub fn new(threshold: u64) -> Self {
437 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
438 // Lint integral literals.
440 if let LitKind::Int(val, _) = lit.kind;
441 if let Some(src) = snippet_opt(cx, lit.span);
442 if let Some(num_lit) = NumericLiteral::from_lit(&src, &lit);
443 if num_lit.radix == Radix::Decimal;
444 if val >= u128::from(self.threshold);
446 let hex = format!("{:#X}", val);
447 let num_lit = NumericLiteral::new(&hex, num_lit.suffix, false);
448 let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
449 warning_type.display(num_lit.format(), cx, lit.span)
455 fn do_lint(digits: &str) -> Result<(), WarningType> {
456 if digits.len() == 1 {
457 // Lint for 1 digit literals, if someone really sets the threshold that low
466 return Err(WarningType::DecimalRepresentation);
468 } else if digits.len() < 4 {
469 // Lint for Literals with a hex-representation of 2 or 3 digits
470 let f = &digits[0..1]; // first digit
471 let s = &digits[1..]; // suffix
474 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
475 // Powers of 2 minus 1
476 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
478 return Err(WarningType::DecimalRepresentation);
481 // Lint for Literals with a hex-representation of 4 digits or more
482 let f = &digits[0..1]; // first digit
483 let m = &digits[1..digits.len() - 1]; // middle digits, except last
484 let s = &digits[1..]; // suffix
486 // Powers of 2 with a margin of +15/-16
487 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
488 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
489 // Lint for representations with only 0s and Fs, while allowing 7 as the first
491 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
493 return Err(WarningType::DecimalRepresentation);