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 crate fn suggest_grouping(&self) -> usize {
119 Self::Binary | Self::Hexadecimal => 4,
120 Self::Octal | Self::Decimal => 3,
126 pub(super) struct DigitInfo<'a> {
127 /// Which radix the literal was represented in.
129 /// The radix prefix, if present.
130 crate prefix: Option<&'a str>,
132 /// The integer part of the number.
134 /// The fraction part of the number.
135 fraction: Option<&'a str>,
136 /// The character used as exponent seperator (b'e' or b'E') and the exponent part.
137 exponent: Option<(char, &'a str)>,
139 /// The type suffix, including preceding underscore if present.
140 crate suffix: Option<&'a str>,
141 /// True for floating-point literals.
145 impl<'a> DigitInfo<'a> {
147 crate fn new(lit: &'a str, float: bool) -> Self {
148 // Determine delimiter for radix prefix, if present, and radix.
149 let radix = if lit.starts_with("0x") {
151 } else if lit.starts_with("0b") {
153 } else if lit.starts_with("0o") {
159 // Grab part of the literal after prefix, if present.
160 let (prefix, sans_prefix) = if let Radix::Decimal = radix {
163 let (p, s) = lit.split_at(2);
167 let mut digits = sans_prefix;
168 let mut suffix = None;
170 let len = sans_prefix.len();
171 let mut last_d = '\0';
172 for (d_idx, d) in sans_prefix.char_indices() {
173 let suffix_start = if last_d == '_' { d_idx - 1 } else { d_idx };
176 || is_possible_float_suffix_index(&sans_prefix, suffix_start, len)
177 || ((d == 'E' || d == 'e') && !has_possible_float_suffix(&sans_prefix)))
178 || !float && (d == 'i' || d == 'u' || is_possible_suffix_index(&sans_prefix, suffix_start, len))
180 let (d, s) = sans_prefix.split_at(suffix_start);
188 let (integer, fraction, exponent) = Self::split_digit_parts(digits, float);
201 fn split_digit_parts(digits: &str, float: bool) -> (&str, Option<&str>, Option<(char, &str)>) {
202 let mut integer = digits;
203 let mut fraction = None;
204 let mut exponent = None;
207 for (i, c) in digits.char_indices() {
210 integer = &digits[..i];
211 fraction = Some(&digits[i + 1..]);
214 if integer.len() > i {
215 integer = &digits[..i];
217 fraction = Some(&digits[integer.len() + 1..i]);
219 exponent = Some((c, &digits[i + 1..]));
227 (integer, fraction, exponent)
230 /// Returns literal formatted in a sensible way.
231 crate fn grouping_hint(&self) -> String {
232 let mut output = String::new();
234 if let Some(prefix) = self.prefix {
235 output.push_str(prefix);
238 let group_size = self.radix.suggest_grouping();
245 self.radix == Radix::Hexadecimal,
248 if let Some(fraction) = self.fraction {
250 Self::group_digits(&mut output, fraction, group_size, false, false);
253 if let Some((separator, exponent)) = self.exponent {
254 output.push(separator);
255 Self::group_digits(&mut output, exponent, group_size, true, false);
258 if let Some(suffix) = self.suffix {
259 if self.float && is_mistyped_float_suffix(suffix) {
260 output.push_str("_f");
261 output.push_str(&suffix[1..]);
262 } else if is_mistyped_suffix(suffix) {
263 output.push_str("_i");
264 output.push_str(&suffix[1..]);
266 output.push_str(suffix);
273 fn group_digits(output: &mut String, input: &str, group_size: usize, partial_group_first: bool, pad: bool) {
274 debug_assert!(group_size > 0);
276 let mut digits = input.chars().filter(|&c| c != '_');
278 let first_group_size;
280 if partial_group_first {
281 first_group_size = (digits.clone().count() + group_size - 1) % group_size + 1;
283 for _ in 0..group_size - first_group_size {
288 first_group_size = group_size;
291 for _ in 0..first_group_size {
292 if let Some(digit) = digits.next() {
297 for (c, i) in digits.zip((0..group_size).cycle()) {
308 InconsistentDigitGrouping,
310 DecimalRepresentation,
311 MistypedLiteralSuffix,
315 crate fn display(&self, grouping_hint: &str, cx: &EarlyContext<'_>, span: syntax_pos::Span) {
317 Self::MistypedLiteralSuffix => span_lint_and_sugg(
319 MISTYPED_LITERAL_SUFFIXES,
321 "mistyped literal suffix",
322 "did you mean to write",
323 grouping_hint.to_string(),
324 Applicability::MaybeIncorrect,
326 Self::UnreadableLiteral => span_lint_and_sugg(
330 "long literal lacking separators",
332 grouping_hint.to_owned(),
333 Applicability::MachineApplicable,
335 Self::LargeDigitGroups => span_lint_and_sugg(
339 "digit groups should be smaller",
341 grouping_hint.to_owned(),
342 Applicability::MachineApplicable,
344 Self::InconsistentDigitGrouping => span_lint_and_sugg(
346 INCONSISTENT_DIGIT_GROUPING,
348 "digits grouped inconsistently by underscores",
350 grouping_hint.to_owned(),
351 Applicability::MachineApplicable,
353 Self::DecimalRepresentation => span_lint_and_sugg(
355 DECIMAL_LITERAL_REPRESENTATION,
357 "integer literal has a better hexadecimal representation",
359 grouping_hint.to_owned(),
360 Applicability::MachineApplicable,
366 declare_lint_pass!(LiteralDigitGrouping => [
368 INCONSISTENT_DIGIT_GROUPING,
370 MISTYPED_LITERAL_SUFFIXES,
373 impl EarlyLintPass for LiteralDigitGrouping {
374 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
375 if in_external_macro(cx.sess(), expr.span) {
379 if let ExprKind::Lit(ref lit) = expr.kind {
380 Self::check_lit(cx, lit)
385 impl LiteralDigitGrouping {
386 fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
387 let in_macro = in_macro(lit.span);
390 if let Some(src) = snippet_opt(cx, lit.span);
391 if let Some(firstch) = src.chars().next();
392 if char::is_digit(firstch, 10);
395 let digit_info = match lit.kind {
396 LitKind::Int(..) => DigitInfo::new(&src, false),
397 LitKind::Float(..) => DigitInfo::new(&src, true),
402 if let Some(suffix) = digit_info.suffix {
403 if is_mistyped_suffix(suffix) {
404 return Err(WarningType::MistypedLiteralSuffix);
408 let integral_group_size = Self::get_group_size(digit_info.integer.split('_'), in_macro)?;
409 if let Some(fraction) = digit_info.fraction {
410 let fractional_group_size = Self::get_group_size(fraction.rsplit('_'), in_macro)?;
412 let consistent = Self::parts_consistent(integral_group_size,
413 fractional_group_size,
414 digit_info.integer.len(),
417 return Err(WarningType::InconsistentDigitGrouping);
424 if let Err(warning_type) = result {
425 warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
431 /// Given the sizes of the digit groups of both integral and fractional
432 /// parts, and the length
433 /// of both parts, determine if the digits have been grouped consistently.
436 int_group_size: Option<usize>,
437 frac_group_size: Option<usize>,
441 match (int_group_size, frac_group_size) {
442 // No groups on either side of decimal point - trivially consistent.
443 (None, None) => true,
444 // Integral part has grouped digits, fractional part does not.
445 (Some(int_group_size), None) => frac_size <= int_group_size,
446 // Fractional part has grouped digits, integral part does not.
447 (None, Some(frac_group_size)) => int_size <= frac_group_size,
448 // Both parts have grouped digits. Groups should be the same size.
449 (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
453 /// Returns the size of the digit groups (or None if ungrouped) if successful,
454 /// otherwise returns a `WarningType` for linting.
455 fn get_group_size<'a>(groups: impl Iterator<Item = &'a str>, in_macro: bool) -> Result<Option<usize>, WarningType> {
456 let mut groups = groups.map(str::len);
458 let first = groups.next().expect("At least one group");
460 if let Some(second) = groups.next() {
461 if !groups.all(|x| x == second) || first > second {
462 Err(WarningType::InconsistentDigitGrouping)
463 } else if second > 4 {
464 Err(WarningType::LargeDigitGroups)
468 } else if first > 5 && !in_macro {
469 Err(WarningType::UnreadableLiteral)
476 #[allow(clippy::module_name_repetitions)]
477 #[derive(Copy, Clone)]
478 pub struct DecimalLiteralRepresentation {
482 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
484 impl EarlyLintPass for DecimalLiteralRepresentation {
485 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
486 if in_external_macro(cx.sess(), expr.span) {
490 if let ExprKind::Lit(ref lit) = expr.kind {
491 self.check_lit(cx, lit)
496 impl DecimalLiteralRepresentation {
498 pub fn new(threshold: u64) -> Self {
501 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
502 // Lint integral literals.
504 if let LitKind::Int(val, _) = lit.kind;
505 if let Some(src) = snippet_opt(cx, lit.span);
506 if let Some(firstch) = src.chars().next();
507 if char::is_digit(firstch, 10);
508 let digit_info = DigitInfo::new(&src, false);
509 if digit_info.radix == Radix::Decimal;
510 if val >= u128::from(self.threshold);
512 let hex = format!("{:#X}", val);
513 let digit_info = DigitInfo::new(&hex, false);
514 let _ = Self::do_lint(digit_info.integer).map_err(|warning_type| {
515 warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
521 fn do_lint(digits: &str) -> Result<(), WarningType> {
522 if digits.len() == 1 {
523 // Lint for 1 digit literals, if someone really sets the threshold that low
532 return Err(WarningType::DecimalRepresentation);
534 } else if digits.len() < 4 {
535 // Lint for Literals with a hex-representation of 2 or 3 digits
536 let f = &digits[0..1]; // first digit
537 let s = &digits[1..]; // suffix
540 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
541 // Powers of 2 minus 1
542 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
544 return Err(WarningType::DecimalRepresentation);
547 // Lint for Literals with a hex-representation of 4 digits or more
548 let f = &digits[0..1]; // first digit
549 let m = &digits[1..digits.len() - 1]; // middle digits, except last
550 let s = &digits[1..]; // suffix
552 // Powers of 2 with a margin of +15/-16
553 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
554 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
555 // Lint for representations with only 0s and Fs, while allowing 7 as the first
557 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
559 return Err(WarningType::DecimalRepresentation);
568 fn is_mistyped_suffix(suffix: &str) -> bool {
569 ["_8", "_16", "_32", "_64"].contains(&suffix)
573 fn is_possible_suffix_index(lit: &str, idx: usize, len: usize) -> bool {
574 ((len > 3 && idx == len - 3) || (len > 2 && idx == len - 2)) && is_mistyped_suffix(lit.split_at(idx).1)
578 fn is_mistyped_float_suffix(suffix: &str) -> bool {
579 ["_32", "_64"].contains(&suffix)
583 fn is_possible_float_suffix_index(lit: &str, idx: usize, len: usize) -> bool {
584 (len > 3 && idx == len - 3) && is_mistyped_float_suffix(lit.split_at(idx).1)
588 fn has_possible_float_suffix(lit: &str) -> bool {
589 lit.ends_with("_32") || lit.ends_with("_64")