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.
116 crate fn suggest_grouping(&self) -> usize {
118 Radix::Binary | Radix::Hexadecimal => 4,
119 Radix::Octal | Radix::Decimal => 3,
125 pub(super) struct DigitInfo<'a> {
126 /// Characters of a literal between the radix prefix and type suffix.
127 crate digits: &'a str,
128 /// Which radix the literal was represented in.
130 /// The radix prefix, if present.
131 crate prefix: Option<&'a str>,
132 /// The type suffix, including preceding underscore if present.
133 crate suffix: Option<&'a str>,
134 /// True for floating-point literals.
138 impl<'a> DigitInfo<'a> {
139 crate fn new(lit: &'a str, float: bool) -> Self {
140 // Determine delimiter for radix prefix, if present, and radix.
141 let radix = if lit.starts_with("0x") {
143 } else if lit.starts_with("0b") {
145 } else if lit.starts_with("0o") {
151 // Grab part of the literal after prefix, if present.
152 let (prefix, sans_prefix) = if let Radix::Decimal = radix {
155 let (p, s) = lit.split_at(2);
159 let len = sans_prefix.len();
160 let mut last_d = '\0';
161 for (d_idx, d) in sans_prefix.char_indices() {
162 let suffix_start = if last_d == '_' { d_idx - 1 } else { d_idx };
165 || is_possible_float_suffix_index(&sans_prefix, suffix_start, len)
166 || ((d == 'E' || d == 'e') && !has_possible_float_suffix(&sans_prefix)))
167 || !float && (d == 'i' || d == 'u' || is_possible_suffix_index(&sans_prefix, suffix_start, len))
169 let (digits, suffix) = sans_prefix.split_at(suffix_start);
174 suffix: Some(suffix),
191 /// Returns literal formatted in a sensible way.
192 crate fn grouping_hint(&self) -> String {
193 let group_size = self.radix.suggest_grouping();
194 if self.digits.contains('.') {
195 let mut parts = self.digits.split('.');
196 let int_part_hint = parts
198 .expect("split always returns at least one element")
201 .filter(|&c| c != '_')
204 .map(|chunk| chunk.iter().rev().collect())
206 .collect::<Vec<String>>()
208 let frac_part_hint = parts
210 .expect("already checked that there is a `.`")
212 .filter(|&c| c != '_')
215 .map(|chunk| chunk.iter().collect())
216 .collect::<Vec<String>>()
218 let suffix_hint = match self.suffix {
219 Some(suffix) if is_mistyped_float_suffix(suffix) => format!("_f{}", &suffix[1..]),
220 Some(suffix) => suffix.to_string(),
221 None => String::new(),
223 format!("{}.{}{}", int_part_hint, frac_part_hint, suffix_hint)
224 } else if self.float && (self.digits.contains('E') || self.digits.contains('e')) {
225 let which_e = if self.digits.contains('E') { 'E' } else { 'e' };
226 let parts: Vec<&str> = self.digits.split(which_e).collect();
227 let filtered_digits_vec_0 = parts[0].chars().filter(|&c| c != '_').rev().collect::<Vec<_>>();
228 let filtered_digits_vec_1 = parts[1].chars().filter(|&c| c != '_').rev().collect::<Vec<_>>();
229 let before_e_hint = filtered_digits_vec_0
231 .map(|chunk| chunk.iter().rev().collect())
233 .collect::<Vec<String>>()
235 let after_e_hint = filtered_digits_vec_1
237 .map(|chunk| chunk.iter().rev().collect())
239 .collect::<Vec<String>>()
241 let suffix_hint = match self.suffix {
242 Some(suffix) if is_mistyped_float_suffix(suffix) => format!("_f{}", &suffix[1..]),
243 Some(suffix) => suffix.to_string(),
244 None => String::new(),
248 self.prefix.unwrap_or(""),
255 let filtered_digits_vec = self.digits.chars().filter(|&c| c != '_').rev().collect::<Vec<_>>();
256 let mut hint = filtered_digits_vec
258 .map(|chunk| chunk.iter().rev().collect())
260 .collect::<Vec<String>>()
262 // Forces hexadecimal values to be grouped by 4 being filled with zeroes (e.g 0x00ab_cdef)
263 let nb_digits_to_fill = filtered_digits_vec.len() % 4;
264 if self.radix == Radix::Hexadecimal && nb_digits_to_fill != 0 {
265 hint = format!("{:0>4}{}", &hint[..nb_digits_to_fill], &hint[nb_digits_to_fill..]);
267 let suffix_hint = match self.suffix {
268 Some(suffix) if is_mistyped_suffix(suffix) => format!("_i{}", &suffix[1..]),
269 Some(suffix) => suffix.to_string(),
270 None => String::new(),
272 format!("{}{}{}", self.prefix.unwrap_or(""), hint, suffix_hint)
279 InconsistentDigitGrouping,
281 DecimalRepresentation,
282 MistypedLiteralSuffix,
286 crate fn display(&self, grouping_hint: &str, cx: &EarlyContext<'_>, span: syntax_pos::Span) {
288 WarningType::MistypedLiteralSuffix => span_lint_and_sugg(
290 MISTYPED_LITERAL_SUFFIXES,
292 "mistyped literal suffix",
293 "did you mean to write",
294 grouping_hint.to_string(),
295 Applicability::MaybeIncorrect,
297 WarningType::UnreadableLiteral => span_lint_and_sugg(
301 "long literal lacking separators",
303 grouping_hint.to_owned(),
304 Applicability::MachineApplicable,
306 WarningType::LargeDigitGroups => span_lint_and_sugg(
310 "digit groups should be smaller",
312 grouping_hint.to_owned(),
313 Applicability::MachineApplicable,
315 WarningType::InconsistentDigitGrouping => span_lint_and_sugg(
317 INCONSISTENT_DIGIT_GROUPING,
319 "digits grouped inconsistently by underscores",
321 grouping_hint.to_owned(),
322 Applicability::MachineApplicable,
324 WarningType::DecimalRepresentation => span_lint_and_sugg(
326 DECIMAL_LITERAL_REPRESENTATION,
328 "integer literal has a better hexadecimal representation",
330 grouping_hint.to_owned(),
331 Applicability::MachineApplicable,
337 declare_lint_pass!(LiteralDigitGrouping => [
339 INCONSISTENT_DIGIT_GROUPING,
341 MISTYPED_LITERAL_SUFFIXES,
344 impl EarlyLintPass for LiteralDigitGrouping {
345 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
346 if in_external_macro(cx.sess(), expr.span) {
350 if let ExprKind::Lit(ref lit) = expr.node {
351 self.check_lit(cx, lit)
356 impl LiteralDigitGrouping {
357 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
358 let in_macro = in_macro(lit.span);
360 LitKind::Int(..) => {
361 // Lint integral literals.
363 if let Some(src) = snippet_opt(cx, lit.span);
364 if let Some(firstch) = src.chars().next();
365 if char::to_digit(firstch, 10).is_some();
367 let digit_info = DigitInfo::new(&src, false);
368 let _ = Self::do_lint(digit_info.digits, digit_info.suffix, in_macro).map_err(|warning_type| {
369 warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
374 LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => {
375 // Lint floating-point literals.
377 if let Some(src) = snippet_opt(cx, lit.span);
378 if let Some(firstch) = src.chars().next();
379 if char::to_digit(firstch, 10).is_some();
381 let digit_info = DigitInfo::new(&src, true);
382 // Separate digits into integral and fractional parts.
383 let parts: Vec<&str> = digit_info
385 .split_terminator('.')
388 // Lint integral and fractional parts separately, and then check consistency of digit
389 // groups if both pass.
390 let _ = Self::do_lint(parts[0], digit_info.suffix, in_macro)
391 .map(|integral_group_size| {
393 // Lint the fractional part of literal just like integral part, but reversed.
394 let fractional_part = &parts[1].chars().rev().collect::<String>();
395 let _ = Self::do_lint(fractional_part, None, in_macro)
396 .map(|fractional_group_size| {
397 let consistent = Self::parts_consistent(integral_group_size,
398 fractional_group_size,
402 WarningType::InconsistentDigitGrouping.display(
403 &digit_info.grouping_hint(),
409 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(),
414 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(), cx, lit.span));
422 /// Given the sizes of the digit groups of both integral and fractional
423 /// parts, and the length
424 /// of both parts, determine if the digits have been grouped consistently.
425 fn parts_consistent(int_group_size: usize, frac_group_size: usize, int_size: usize, frac_size: usize) -> bool {
426 match (int_group_size, frac_group_size) {
427 // No groups on either side of decimal point - trivially consistent.
429 // Integral part has grouped digits, fractional part does not.
430 (_, 0) => frac_size <= int_group_size,
431 // Fractional part has grouped digits, integral part does not.
432 (0, _) => int_size <= frac_group_size,
433 // Both parts have grouped digits. Groups should be the same size.
434 (_, _) => int_group_size == frac_group_size,
438 /// Performs lint on `digits` (no decimal point) and returns the group
439 /// size on success or `WarningType` when emitting a warning.
440 fn do_lint(digits: &str, suffix: Option<&str>, in_macro: bool) -> Result<usize, WarningType> {
441 if let Some(suffix) = suffix {
442 if is_mistyped_suffix(suffix) {
443 return Err(WarningType::MistypedLiteralSuffix);
446 // Grab underscore indices with respect to the units digit.
447 let underscore_positions: Vec<usize> = digits
451 .filter_map(|(idx, digit)| if digit == '_' { Some(idx) } else { None })
454 if underscore_positions.is_empty() {
455 // Check if literal needs underscores.
456 if !in_macro && digits.len() > 5 {
457 Err(WarningType::UnreadableLiteral)
462 // Check consistency and the sizes of the groups.
463 let group_size = underscore_positions[0];
464 let consistent = underscore_positions
466 .all(|ps| ps[1] - ps[0] == group_size + 1)
467 // number of digits to the left of the last group cannot be bigger than group size.
468 && (digits.len() - underscore_positions.last()
469 .expect("there's at least one element") <= group_size + 1);
472 return Err(WarningType::InconsistentDigitGrouping);
473 } else if group_size > 4 {
474 return Err(WarningType::LargeDigitGroups);
481 #[allow(clippy::module_name_repetitions)]
482 #[derive(Copy, Clone)]
483 pub struct DecimalLiteralRepresentation {
487 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
489 impl EarlyLintPass for DecimalLiteralRepresentation {
490 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
491 if in_external_macro(cx.sess(), expr.span) {
495 if let ExprKind::Lit(ref lit) = expr.node {
496 self.check_lit(cx, lit)
501 impl DecimalLiteralRepresentation {
502 pub fn new(threshold: u64) -> Self {
505 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
506 // Lint integral literals.
508 if let LitKind::Int(..) = lit.node;
509 if let Some(src) = snippet_opt(cx, lit.span);
510 if let Some(firstch) = src.chars().next();
511 if char::to_digit(firstch, 10).is_some();
512 let digit_info = DigitInfo::new(&src, false);
513 if digit_info.radix == Radix::Decimal;
514 if let Ok(val) = digit_info.digits
516 .filter(|&c| c != '_')
519 if val >= u128::from(self.threshold);
521 let hex = format!("{:#X}", val);
522 let digit_info = DigitInfo::new(&hex, false);
523 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
524 warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
530 fn do_lint(digits: &str) -> Result<(), WarningType> {
531 if digits.len() == 1 {
532 // Lint for 1 digit literals, if someone really sets the threshold that low
541 return Err(WarningType::DecimalRepresentation);
543 } else if digits.len() < 4 {
544 // Lint for Literals with a hex-representation of 2 or 3 digits
545 let f = &digits[0..1]; // first digit
546 let s = &digits[1..]; // suffix
549 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
550 // Powers of 2 minus 1
551 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
553 return Err(WarningType::DecimalRepresentation);
556 // Lint for Literals with a hex-representation of 4 digits or more
557 let f = &digits[0..1]; // first digit
558 let m = &digits[1..digits.len() - 1]; // middle digits, except last
559 let s = &digits[1..]; // suffix
561 // Powers of 2 with a margin of +15/-16
562 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
563 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
564 // Lint for representations with only 0s and Fs, while allowing 7 as the first
566 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
568 return Err(WarningType::DecimalRepresentation);
576 fn is_mistyped_suffix(suffix: &str) -> bool {
577 ["_8", "_16", "_32", "_64"].contains(&suffix)
580 fn is_possible_suffix_index(lit: &str, idx: usize, len: usize) -> bool {
581 ((len > 3 && idx == len - 3) || (len > 2 && idx == len - 2)) && is_mistyped_suffix(lit.split_at(idx).1)
584 fn is_mistyped_float_suffix(suffix: &str) -> bool {
585 ["_32", "_64"].contains(&suffix)
588 fn is_possible_float_suffix_index(lit: &str, idx: usize, len: usize) -> bool {
589 (len > 3 && idx == len - 3) && is_mistyped_float_suffix(lit.split_at(idx).1)
592 fn has_possible_float_suffix(lit: &str) -> bool {
593 lit.ends_with("_32") || lit.ends_with("_64")