1 //! Lints concerned with the grouping of digits with underscores in integral or
2 //! floating-point literal expressions.
4 use crate::utils::{in_macro, snippet_opt, span_lint_and_sugg};
5 use if_chain::if_chain;
6 use rustc::lint::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
7 use rustc::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
8 use rustc_errors::Applicability;
12 declare_clippy_lint! {
13 /// **What it does:** Warns if a long integral or floating-point constant does
14 /// not contain underscores.
16 /// **Why is this bad?** Reading long numbers is difficult without separators.
18 /// **Known problems:** None.
23 /// let x: u64 = 61864918973511;
25 pub UNREADABLE_LITERAL,
27 "long integer literal without underscores"
30 declare_clippy_lint! {
31 /// **What it does:** Warns for mistyped suffix in literals
33 /// **Why is this bad?** This is most probably a typo
35 /// **Known problems:**
36 /// - Recommends a signed suffix, even though the number might be too big and an unsigned
37 /// suffix is required
38 /// - Does not match on `_128` since that is a valid grouping for decimal and octal numbers
45 pub MISTYPED_LITERAL_SUFFIXES,
47 "mistyped literal suffix"
50 declare_clippy_lint! {
51 /// **What it does:** Warns if an integral or floating-point constant is
52 /// grouped inconsistently with underscores.
54 /// **Why is this bad?** Readers may incorrectly interpret inconsistently
57 /// **Known problems:** None.
62 /// let x: u64 = 618_64_9189_73_511;
64 pub INCONSISTENT_DIGIT_GROUPING,
66 "integer literals with digits grouped inconsistently"
69 declare_clippy_lint! {
70 /// **What it does:** Warns if the digits of an integral or floating-point
71 /// constant are grouped into groups that
74 /// **Why is this bad?** Negatively impacts readability.
76 /// **Known problems:** None.
81 /// let x: u64 = 6186491_8973511;
83 pub LARGE_DIGIT_GROUPS,
85 "grouping digits into groups that are too large"
88 declare_clippy_lint! {
89 /// **What it does:** Warns if there is a better representation for a numeric literal.
91 /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
92 /// readable than a decimal representation.
94 /// **Known problems:** None.
99 /// `65_535` => `0xFFFF`
100 /// `4_042_322_160` => `0xF0F0_F0F0`
101 pub DECIMAL_LITERAL_REPRESENTATION,
103 "using decimal representation when hexadecimal would be better"
106 #[derive(Debug, PartialEq)]
107 pub(super) enum Radix {
115 /// Returns a reasonable digit group size for this radix.
117 fn suggest_grouping(&self) -> usize {
119 Self::Binary | Self::Hexadecimal => 4,
120 Self::Octal | Self::Decimal => 3,
125 /// A helper method to format numeric literals with digit grouping.
126 /// `lit` must be a valid numeric literal without suffix.
127 pub fn format_numeric_literal(lit: &str, type_suffix: Option<&str>, float: bool) -> String {
128 NumericLiteral::new(lit, type_suffix, float).format()
132 pub(super) struct NumericLiteral<'a> {
133 /// Which radix the literal was represented in.
135 /// The radix prefix, if present.
136 prefix: Option<&'a str>,
138 /// The integer part of the number.
140 /// The fraction part of the number.
141 fraction: Option<&'a str>,
142 /// The character used as exponent seperator (b'e' or b'E') and the exponent part.
143 exponent: Option<(char, &'a str)>,
145 /// The type suffix, including preceding underscore if present.
146 suffix: Option<&'a str>,
149 impl<'a> NumericLiteral<'a> {
150 fn from_lit(src: &'a str, lit: &Lit) -> Option<NumericLiteral<'a>> {
151 if lit.kind.is_numeric() && src.chars().next().map_or(false, |c| c.is_digit(10)) {
152 let (unsuffixed, suffix) = split_suffix(&src, &lit.kind);
153 let float = if let LitKind::Float(..) = lit.kind { true } else { false };
154 Some(NumericLiteral::new(unsuffixed, suffix, float))
161 fn new(lit: &'a str, suffix: Option<&'a str>, float: bool) -> Self {
162 // Determine delimiter for radix prefix, if present, and radix.
163 let radix = if lit.starts_with("0x") {
165 } else if lit.starts_with("0b") {
167 } else if lit.starts_with("0o") {
173 // Grab part of the literal after prefix, if present.
174 let (prefix, mut sans_prefix) = if let Radix::Decimal = radix {
177 let (p, s) = lit.split_at(2);
181 if suffix.is_some() && sans_prefix.ends_with('_') {
182 // The '_' before the suffix isn't part of the digits
183 sans_prefix = &sans_prefix[..sans_prefix.len() - 1];
186 let (integer, fraction, exponent) = Self::split_digit_parts(sans_prefix, float);
198 fn split_digit_parts(digits: &str, float: bool) -> (&str, Option<&str>, Option<(char, &str)>) {
199 let mut integer = digits;
200 let mut fraction = None;
201 let mut exponent = None;
204 for (i, c) in digits.char_indices() {
207 integer = &digits[..i];
208 fraction = Some(&digits[i + 1..]);
211 if integer.len() > i {
212 integer = &digits[..i];
214 fraction = Some(&digits[integer.len() + 1..i]);
216 exponent = Some((c, &digits[i + 1..]));
224 (integer, fraction, exponent)
227 /// Returns literal formatted in a sensible way.
228 fn format(&self) -> String {
229 let mut output = String::new();
231 if let Some(prefix) = self.prefix {
232 output.push_str(prefix);
235 let group_size = self.radix.suggest_grouping();
242 self.radix == Radix::Hexadecimal,
245 if let Some(fraction) = self.fraction {
247 Self::group_digits(&mut output, fraction, group_size, false, false);
250 if let Some((separator, exponent)) = self.exponent {
251 output.push(separator);
252 Self::group_digits(&mut output, exponent, group_size, true, false);
255 if let Some(suffix) = self.suffix {
257 output.push_str(suffix);
263 fn group_digits(output: &mut String, input: &str, group_size: usize, partial_group_first: bool, pad: bool) {
264 debug_assert!(group_size > 0);
266 let mut digits = input.chars().filter(|&c| c != '_');
268 let first_group_size;
270 if partial_group_first {
271 first_group_size = (digits.clone().count() - 1) % group_size + 1;
273 for _ in 0..group_size - first_group_size {
278 first_group_size = group_size;
281 for _ in 0..first_group_size {
282 if let Some(digit) = digits.next() {
287 for (c, i) in digits.zip((0..group_size).cycle()) {
296 fn split_suffix<'a>(src: &'a str, lit_kind: &LitKind) -> (&'a str, Option<&'a str>) {
297 debug_assert!(lit_kind.is_numeric());
298 if let Some(suffix_length) = lit_suffix_length(lit_kind) {
299 let (unsuffixed, suffix) = src.split_at(src.len() - suffix_length);
300 (unsuffixed, Some(suffix))
306 fn lit_suffix_length(lit_kind: &LitKind) -> Option<usize> {
307 debug_assert!(lit_kind.is_numeric());
308 let suffix = match lit_kind {
309 LitKind::Int(_, int_lit_kind) => match int_lit_kind {
310 LitIntType::Signed(int_ty) => Some(int_ty.name_str()),
311 LitIntType::Unsigned(uint_ty) => Some(uint_ty.name_str()),
312 LitIntType::Unsuffixed => None,
314 LitKind::Float(_, float_lit_kind) => match float_lit_kind {
315 LitFloatType::Suffixed(float_ty) => Some(float_ty.name_str()),
316 LitFloatType::Unsuffixed => None,
326 InconsistentDigitGrouping,
328 DecimalRepresentation,
329 MistypedLiteralSuffix,
333 fn display(&self, suggested_format: String, cx: &EarlyContext<'_>, span: syntax_pos::Span) {
335 Self::MistypedLiteralSuffix => span_lint_and_sugg(
337 MISTYPED_LITERAL_SUFFIXES,
339 "mistyped literal suffix",
340 "did you mean to write",
342 Applicability::MaybeIncorrect,
344 Self::UnreadableLiteral => span_lint_and_sugg(
348 "long literal lacking separators",
351 Applicability::MachineApplicable,
353 Self::LargeDigitGroups => span_lint_and_sugg(
357 "digit groups should be smaller",
360 Applicability::MachineApplicable,
362 Self::InconsistentDigitGrouping => span_lint_and_sugg(
364 INCONSISTENT_DIGIT_GROUPING,
366 "digits grouped inconsistently by underscores",
369 Applicability::MachineApplicable,
371 Self::DecimalRepresentation => span_lint_and_sugg(
373 DECIMAL_LITERAL_REPRESENTATION,
375 "integer literal has a better hexadecimal representation",
378 Applicability::MachineApplicable,
384 declare_lint_pass!(LiteralDigitGrouping => [
386 INCONSISTENT_DIGIT_GROUPING,
388 MISTYPED_LITERAL_SUFFIXES,
391 impl EarlyLintPass for LiteralDigitGrouping {
392 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
393 if in_external_macro(cx.sess(), expr.span) {
397 if let ExprKind::Lit(ref lit) = expr.kind {
398 Self::check_lit(cx, lit)
403 impl LiteralDigitGrouping {
404 fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
406 if let Some(src) = snippet_opt(cx, lit.span);
407 if let Some(mut num_lit) = NumericLiteral::from_lit(&src, &lit);
409 if !Self::check_for_mistyped_suffix(cx, lit.span, &mut num_lit) {
415 let integral_group_size = Self::get_group_size(num_lit.integer.split('_'))?;
416 if let Some(fraction) = num_lit.fraction {
417 let fractional_group_size = Self::get_group_size(fraction.rsplit('_'))?;
419 let consistent = Self::parts_consistent(integral_group_size,
420 fractional_group_size,
421 num_lit.integer.len(),
424 return Err(WarningType::InconsistentDigitGrouping);
431 if let Err(warning_type) = result {
432 let should_warn = match warning_type {
433 | WarningType::UnreadableLiteral
434 | WarningType::InconsistentDigitGrouping
435 | WarningType::LargeDigitGroups => {
438 WarningType::DecimalRepresentation | WarningType::MistypedLiteralSuffix => {
443 warning_type.display(num_lit.format(), cx, lit.span)
450 // Returns `false` if the check fails
451 fn check_for_mistyped_suffix(
452 cx: &EarlyContext<'_>,
453 span: syntax_pos::Span,
454 num_lit: &mut NumericLiteral<'_>,
456 if num_lit.suffix.is_some() {
460 let (part, mistyped_suffixes, missing_char) = if let Some((_, exponent)) = &mut num_lit.exponent {
461 (exponent, &["32", "64"][..], 'f')
462 } else if let Some(fraction) = &mut num_lit.fraction {
463 (fraction, &["32", "64"][..], 'f')
465 (&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i')
468 let mut split = part.rsplit('_');
469 let last_group = split.next().expect("At least one group");
470 if split.next().is_some() && mistyped_suffixes.contains(&last_group) {
471 *part = &part[..part.len() - last_group.len()];
472 let mut sugg = num_lit.format();
474 sugg.push(missing_char);
475 sugg.push_str(last_group);
476 WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
483 /// Given the sizes of the digit groups of both integral and fractional
484 /// parts, and the length
485 /// of both parts, determine if the digits have been grouped consistently.
488 int_group_size: Option<usize>,
489 frac_group_size: Option<usize>,
493 match (int_group_size, frac_group_size) {
494 // No groups on either side of decimal point - trivially consistent.
495 (None, None) => true,
496 // Integral part has grouped digits, fractional part does not.
497 (Some(int_group_size), None) => frac_size <= int_group_size,
498 // Fractional part has grouped digits, integral part does not.
499 (None, Some(frac_group_size)) => int_size <= frac_group_size,
500 // Both parts have grouped digits. Groups should be the same size.
501 (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
505 /// Returns the size of the digit groups (or None if ungrouped) if successful,
506 /// otherwise returns a `WarningType` for linting.
507 fn get_group_size<'a>(groups: impl Iterator<Item = &'a str>) -> Result<Option<usize>, WarningType> {
508 let mut groups = groups.map(str::len);
510 let first = groups.next().expect("At least one group");
512 if let Some(second) = groups.next() {
513 if !groups.all(|x| x == second) || first > second {
514 Err(WarningType::InconsistentDigitGrouping)
515 } else if second > 4 {
516 Err(WarningType::LargeDigitGroups)
520 } else if first > 5 {
521 Err(WarningType::UnreadableLiteral)
528 #[allow(clippy::module_name_repetitions)]
529 #[derive(Copy, Clone)]
530 pub struct DecimalLiteralRepresentation {
534 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
536 impl EarlyLintPass for DecimalLiteralRepresentation {
537 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
538 if in_external_macro(cx.sess(), expr.span) {
542 if let ExprKind::Lit(ref lit) = expr.kind {
543 self.check_lit(cx, lit)
548 impl DecimalLiteralRepresentation {
550 pub fn new(threshold: u64) -> Self {
553 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
554 // Lint integral literals.
556 if let LitKind::Int(val, _) = lit.kind;
557 if let Some(src) = snippet_opt(cx, lit.span);
558 if let Some(num_lit) = NumericLiteral::from_lit(&src, &lit);
559 if num_lit.radix == Radix::Decimal;
560 if val >= u128::from(self.threshold);
562 let hex = format!("{:#X}", val);
563 let num_lit = NumericLiteral::new(&hex, None, false);
564 let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
565 warning_type.display(num_lit.format(), cx, lit.span)
571 fn do_lint(digits: &str) -> Result<(), WarningType> {
572 if digits.len() == 1 {
573 // Lint for 1 digit literals, if someone really sets the threshold that low
582 return Err(WarningType::DecimalRepresentation);
584 } else if digits.len() < 4 {
585 // Lint for Literals with a hex-representation of 2 or 3 digits
586 let f = &digits[0..1]; // first digit
587 let s = &digits[1..]; // suffix
590 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
591 // Powers of 2 minus 1
592 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
594 return Err(WarningType::DecimalRepresentation);
597 // Lint for Literals with a hex-representation of 4 digits or more
598 let f = &digits[0..1]; // first digit
599 let m = &digits[1..digits.len() - 1]; // middle digits, except last
600 let s = &digits[1..]; // suffix
602 // Powers of 2 with a margin of +15/-16
603 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
604 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
605 // Lint for representations with only 0s and Fs, while allowing 7 as the first
607 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
609 return Err(WarningType::DecimalRepresentation);