1 //! Lints concerned with the grouping of digits with underscores in integral or
2 //! floating-point literal expressions.
4 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass, in_external_macro, LintContext};
5 use crate::rustc::{declare_tool_lint, lint_array};
6 use if_chain::if_chain;
7 use crate::syntax::ast::*;
9 use crate::utils::{snippet_opt, span_lint_and_sugg};
11 /// **What it does:** Warns if a long integral or floating-point constant does
12 /// not contain underscores.
14 /// **Why is this bad?** Reading long numbers is difficult without separators.
16 /// **Known problems:** None.
23 declare_clippy_lint! {
24 pub UNREADABLE_LITERAL,
26 "long integer literal without underscores"
29 /// **What it does:** Warns for mistyped suffix in literals
31 /// **Why is this bad?** This is most probably a typo
33 /// **Known problems:**
34 /// - Recommends a signed suffix, even though the number might be too big and an unsigned
35 /// suffix is required
36 /// - Does not match on `_128` since that is a valid grouping for decimal and octal numbers
43 declare_clippy_lint! {
44 pub MISTYPED_LITERAL_SUFFIXES,
46 "mistyped literal suffix"
49 /// **What it does:** Warns if an integral or floating-point constant is
50 /// grouped inconsistently with underscores.
52 /// **Why is this bad?** Readers may incorrectly interpret inconsistently
55 /// **Known problems:** None.
60 /// 618_64_9189_73_511
62 declare_clippy_lint! {
63 pub INCONSISTENT_DIGIT_GROUPING,
65 "integer literals with digits grouped inconsistently"
68 /// **What it does:** Warns if the digits of an integral or floating-point
69 /// constant are grouped into groups that
72 /// **Why is this bad?** Negatively impacts readability.
74 /// **Known problems:** None.
81 declare_clippy_lint! {
82 pub LARGE_DIGIT_GROUPS,
84 "grouping digits into groups that are too large"
87 /// **What it does:** Warns if there is a better representation for a numeric literal.
89 /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
90 /// readable than a decimal representation.
92 /// **Known problems:** None.
97 /// `65_535` => `0xFFFF`
98 /// `4_042_322_160` => `0xF0F0_F0F0`
99 declare_clippy_lint! {
100 pub DECIMAL_LITERAL_REPRESENTATION,
102 "using decimal representation when hexadecimal would be better"
105 #[derive(Debug, PartialEq)]
106 pub(super) enum Radix {
114 /// Return a reasonable digit group size for this radix.
115 crate fn suggest_grouping(&self) -> usize {
117 Radix::Binary | Radix::Hexadecimal => 4,
118 Radix::Octal | Radix::Decimal => 3,
124 pub(super) struct DigitInfo<'a> {
125 /// Characters of a literal between the radix prefix and type suffix.
126 crate digits: &'a str,
127 /// Which radix the literal was represented in.
129 /// The radix prefix, if present.
130 crate prefix: Option<&'a str>,
131 /// The type suffix, including preceding underscore if present.
132 crate suffix: Option<&'a str>,
133 /// True for floating-point literals.
137 impl<'a> DigitInfo<'a> {
138 crate fn new(lit: &'a str, float: bool) -> Self {
139 // Determine delimiter for radix prefix, if present, and radix.
140 let radix = if lit.starts_with("0x") {
142 } else if lit.starts_with("0b") {
144 } else if lit.starts_with("0o") {
150 // Grab part of the literal after prefix, if present.
151 let (prefix, sans_prefix) = if let Radix::Decimal = radix {
154 let (p, s) = lit.split_at(2);
158 let len = sans_prefix.len();
159 let mut last_d = '\0';
160 for (d_idx, d) in sans_prefix.char_indices() {
161 let suffix_start = if last_d == '_' {
166 if float && (d == 'f' || d == 'e' || d == 'E') ||
167 !float && (d == 'i' || d == 'u' || is_possible_suffix_index(&sans_prefix, suffix_start, len)) {
168 let (digits, suffix) = sans_prefix.split_at(suffix_start);
173 suffix: Some(suffix),
190 /// Returns literal formatted in a sensible way.
191 crate fn grouping_hint(&self) -> String {
192 let group_size = self.radix.suggest_grouping();
193 if self.digits.contains('.') {
194 let mut parts = self.digits.split('.');
195 let int_part_hint = parts
197 .expect("split always returns at least one element")
200 .filter(|&c| c != '_')
203 .map(|chunk| chunk.into_iter().rev().collect())
205 .collect::<Vec<String>>()
207 let frac_part_hint = parts
209 .expect("already checked that there is a `.`")
211 .filter(|&c| c != '_')
214 .map(|chunk| chunk.into_iter().collect())
215 .collect::<Vec<String>>()
221 self.suffix.unwrap_or("")
224 let filtered_digits_vec = self.digits
226 .filter(|&c| c != '_')
228 .collect::<Vec<_>>();
229 let mut hint = filtered_digits_vec
231 .map(|chunk| chunk.into_iter().rev().collect())
233 .collect::<Vec<String>>()
235 // Forces hexadecimal values to be grouped by 4 being filled with zeroes (e.g 0x00ab_cdef)
236 let nb_digits_to_fill = filtered_digits_vec.len() % 4;
237 if self.radix == Radix::Hexadecimal && nb_digits_to_fill != 0 {
238 hint = format!("{:0>4}{}", &hint[..nb_digits_to_fill], &hint[nb_digits_to_fill..]);
240 let suffix_hint = match self.suffix {
241 Some(suffix) if is_mistyped_suffix(suffix) => {
242 format!("_i{}", &suffix[1..])
244 Some(suffix) => suffix.to_string(),
245 None => String::new()
249 self.prefix.unwrap_or(""),
259 InconsistentDigitGrouping,
261 DecimalRepresentation,
262 MistypedLiteralSuffix
266 crate fn display(&self, grouping_hint: &str, cx: &EarlyContext<'_>, span: syntax_pos::Span) {
268 WarningType::MistypedLiteralSuffix => {
271 MISTYPED_LITERAL_SUFFIXES,
273 "mistyped literal suffix",
274 "did you mean to write",
275 grouping_hint.to_string()
278 WarningType::UnreadableLiteral => span_lint_and_sugg(
282 "long literal lacking separators",
284 grouping_hint.to_owned(),
286 WarningType::LargeDigitGroups => span_lint_and_sugg(
290 "digit groups should be smaller",
292 grouping_hint.to_owned(),
294 WarningType::InconsistentDigitGrouping => span_lint_and_sugg(
296 INCONSISTENT_DIGIT_GROUPING,
298 "digits grouped inconsistently by underscores",
300 grouping_hint.to_owned(),
302 WarningType::DecimalRepresentation => span_lint_and_sugg(
304 DECIMAL_LITERAL_REPRESENTATION,
306 "integer literal has a better hexadecimal representation",
308 grouping_hint.to_owned(),
314 #[derive(Copy, Clone)]
315 pub struct LiteralDigitGrouping;
317 impl LintPass for LiteralDigitGrouping {
318 fn get_lints(&self) -> LintArray {
321 INCONSISTENT_DIGIT_GROUPING,
327 impl EarlyLintPass for LiteralDigitGrouping {
328 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
329 if in_external_macro(cx.sess(), expr.span) {
333 if let ExprKind::Lit(ref lit) = expr.node {
334 self.check_lit(cx, lit)
339 impl LiteralDigitGrouping {
340 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
342 LitKind::Int(..) => {
343 // Lint integral literals.
345 if let Some(src) = snippet_opt(cx, lit.span);
346 if let Some(firstch) = src.chars().next();
347 if char::to_digit(firstch, 10).is_some();
349 let digit_info = DigitInfo::new(&src, false);
350 let _ = Self::do_lint(digit_info.digits, digit_info.suffix).map_err(|warning_type| {
351 warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
356 LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => {
357 // Lint floating-point literals.
359 if let Some(src) = snippet_opt(cx, lit.span);
360 if let Some(firstch) = src.chars().next();
361 if char::to_digit(firstch, 10).is_some();
363 let digit_info = DigitInfo::new(&src, true);
364 // Separate digits into integral and fractional parts.
365 let parts: Vec<&str> = digit_info
367 .split_terminator('.')
370 // Lint integral and fractional parts separately, and then check consistency of digit
371 // groups if both pass.
372 let _ = Self::do_lint(parts[0], None)
373 .map(|integral_group_size| {
375 // Lint the fractional part of literal just like integral part, but reversed.
376 let fractional_part = &parts[1].chars().rev().collect::<String>();
377 let _ = Self::do_lint(fractional_part, None)
378 .map(|fractional_group_size| {
379 let consistent = Self::parts_consistent(integral_group_size,
380 fractional_group_size,
384 WarningType::InconsistentDigitGrouping.display(&digit_info.grouping_hint(),
389 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(),
394 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(), cx, lit.span));
402 /// Given the sizes of the digit groups of both integral and fractional
403 /// parts, and the length
404 /// of both parts, determine if the digits have been grouped consistently.
405 fn parts_consistent(int_group_size: usize, frac_group_size: usize, int_size: usize, frac_size: usize) -> bool {
406 match (int_group_size, frac_group_size) {
407 // No groups on either side of decimal point - trivially consistent.
409 // Integral part has grouped digits, fractional part does not.
410 (_, 0) => frac_size <= int_group_size,
411 // Fractional part has grouped digits, integral part does not.
412 (0, _) => int_size <= frac_group_size,
413 // Both parts have grouped digits. Groups should be the same size.
414 (_, _) => int_group_size == frac_group_size,
418 /// Performs lint on `digits` (no decimal point) and returns the group
419 /// size on success or `WarningType` when emitting a warning.
420 fn do_lint(digits: &str, suffix: Option<&str>) -> Result<usize, WarningType> {
421 if let Some(suffix) = suffix {
422 if is_mistyped_suffix(suffix) {
423 return Err(WarningType::MistypedLiteralSuffix);
426 // Grab underscore indices with respect to the units digit.
427 let underscore_positions: Vec<usize> = digits
431 .filter_map(|(idx, digit)| if digit == '_' { Some(idx) } else { None })
434 if underscore_positions.is_empty() {
435 // Check if literal needs underscores.
436 if digits.len() > 5 {
437 Err(WarningType::UnreadableLiteral)
442 // Check consistency and the sizes of the groups.
443 let group_size = underscore_positions[0];
444 let consistent = underscore_positions
446 .all(|ps| ps[1] - ps[0] == group_size + 1)
447 // number of digits to the left of the last group cannot be bigger than group size.
448 && (digits.len() - underscore_positions.last()
449 .expect("there's at least one element") <= group_size + 1);
452 return Err(WarningType::InconsistentDigitGrouping);
453 } else if group_size > 4 {
454 return Err(WarningType::LargeDigitGroups);
461 #[derive(Copy, Clone)]
462 pub struct LiteralRepresentation {
466 impl LintPass for LiteralRepresentation {
467 fn get_lints(&self) -> LintArray {
468 lint_array!(DECIMAL_LITERAL_REPRESENTATION)
472 impl EarlyLintPass for LiteralRepresentation {
473 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
474 if in_external_macro(cx.sess(), expr.span) {
478 if let ExprKind::Lit(ref lit) = expr.node {
479 self.check_lit(cx, lit)
484 impl LiteralRepresentation {
485 pub fn new(threshold: u64) -> Self {
490 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
491 // Lint integral literals.
493 if let LitKind::Int(..) = lit.node;
494 if let Some(src) = snippet_opt(cx, lit.span);
495 if let Some(firstch) = src.chars().next();
496 if char::to_digit(firstch, 10).is_some();
498 let digit_info = DigitInfo::new(&src, false);
499 if digit_info.radix == Radix::Decimal {
500 let val = digit_info.digits
502 .filter(|&c| c != '_')
504 .parse::<u128>().unwrap();
505 if val < u128::from(self.threshold) {
508 let hex = format!("{:#X}", val);
509 let digit_info = DigitInfo::new(&hex[..], false);
510 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
511 warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
518 fn do_lint(digits: &str) -> Result<(), WarningType> {
519 if digits.len() == 1 {
520 // Lint for 1 digit literals, if someone really sets the threshold that low
521 if digits == "1" || digits == "2" || digits == "4" || digits == "8" || digits == "3" || digits == "7"
524 return Err(WarningType::DecimalRepresentation);
526 } else if digits.len() < 4 {
527 // Lint for Literals with a hex-representation of 2 or 3 digits
528 let f = &digits[0..1]; // first digit
529 let s = &digits[1..]; // suffix
531 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
532 // Powers of 2 minus 1
533 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
535 return Err(WarningType::DecimalRepresentation);
538 // Lint for Literals with a hex-representation of 4 digits or more
539 let f = &digits[0..1]; // first digit
540 let m = &digits[1..digits.len() - 1]; // middle digits, except last
541 let s = &digits[1..]; // suffix
542 // Powers of 2 with a margin of +15/-16
543 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
544 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
545 // Lint for representations with only 0s and Fs, while allowing 7 as the first
547 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
549 return Err(WarningType::DecimalRepresentation);
557 fn is_mistyped_suffix(suffix: &str) -> bool {
558 ["_8", "_16", "_32", "_64"].contains(&suffix)
561 fn is_possible_suffix_index(lit: &str, idx: usize, len: usize) -> bool {
562 ((len > 3 && idx == len - 3) || (len > 2 && idx == len - 2)) &&
563 is_mistyped_suffix(lit.split_at(idx).1)