1 //! Lints concerned with the grouping of digits with underscores in integral or
2 //! floating-point literal expressions.
4 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass, in_external_macro, LintContext};
5 use rustc::{declare_tool_lint, lint_array};
6 use if_chain::if_chain;
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 == 'i' || d == 'u') ||
167 float && (d == 'f' || d == 'e' || d == 'E') ||
168 !float && 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.into_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.into_iter().collect())
216 .collect::<Vec<String>>()
222 self.suffix.unwrap_or("")
225 let filtered_digits_vec = self.digits
227 .filter(|&c| c != '_')
229 .collect::<Vec<_>>();
230 let mut hint = filtered_digits_vec
232 .map(|chunk| chunk.into_iter().rev().collect())
234 .collect::<Vec<String>>()
236 // Forces hexadecimal values to be grouped by 4 being filled with zeroes (e.g 0x00ab_cdef)
237 let nb_digits_to_fill = filtered_digits_vec.len() % 4;
238 if self.radix == Radix::Hexadecimal && nb_digits_to_fill != 0 {
239 hint = format!("{:0>4}{}", &hint[..nb_digits_to_fill], &hint[nb_digits_to_fill..]);
241 let suffix_hint = match self.suffix {
242 Some(suffix) if is_mistyped_suffix(suffix) => {
243 format!("_i{}", &suffix[1..])
245 Some(suffix) => suffix.to_string(),
246 None => String::new()
250 self.prefix.unwrap_or(""),
260 InconsistentDigitGrouping,
262 DecimalRepresentation,
263 MistypedLiteralSuffix
267 crate fn display(&self, grouping_hint: &str, cx: &EarlyContext<'_>, span: syntax_pos::Span) {
269 WarningType::MistypedLiteralSuffix => {
272 MISTYPED_LITERAL_SUFFIXES,
274 "mistyped literal suffix",
275 "did you mean to write",
276 grouping_hint.to_string()
279 WarningType::UnreadableLiteral => span_lint_and_sugg(
283 "long literal lacking separators",
285 grouping_hint.to_owned(),
287 WarningType::LargeDigitGroups => span_lint_and_sugg(
291 "digit groups should be smaller",
293 grouping_hint.to_owned(),
295 WarningType::InconsistentDigitGrouping => span_lint_and_sugg(
297 INCONSISTENT_DIGIT_GROUPING,
299 "digits grouped inconsistently by underscores",
301 grouping_hint.to_owned(),
303 WarningType::DecimalRepresentation => span_lint_and_sugg(
305 DECIMAL_LITERAL_REPRESENTATION,
307 "integer literal has a better hexadecimal representation",
309 grouping_hint.to_owned(),
315 #[derive(Copy, Clone)]
316 pub struct LiteralDigitGrouping;
318 impl LintPass for LiteralDigitGrouping {
319 fn get_lints(&self) -> LintArray {
322 INCONSISTENT_DIGIT_GROUPING,
328 impl EarlyLintPass for LiteralDigitGrouping {
329 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
330 if in_external_macro(cx.sess(), expr.span) {
334 if let ExprKind::Lit(ref lit) = expr.node {
335 self.check_lit(cx, lit)
340 impl LiteralDigitGrouping {
341 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
343 LitKind::Int(..) => {
344 // Lint integral literals.
346 if let Some(src) = snippet_opt(cx, lit.span);
347 if let Some(firstch) = src.chars().next();
348 if char::to_digit(firstch, 10).is_some();
350 let digit_info = DigitInfo::new(&src, false);
351 let _ = Self::do_lint(digit_info.digits, digit_info.suffix).map_err(|warning_type| {
352 warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
357 LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => {
358 // Lint floating-point literals.
360 if let Some(src) = snippet_opt(cx, lit.span);
361 if let Some(firstch) = src.chars().next();
362 if char::to_digit(firstch, 10).is_some();
364 let digit_info = DigitInfo::new(&src, true);
365 // Separate digits into integral and fractional parts.
366 let parts: Vec<&str> = digit_info
368 .split_terminator('.')
371 // Lint integral and fractional parts separately, and then check consistency of digit
372 // groups if both pass.
373 let _ = Self::do_lint(parts[0], None)
374 .map(|integral_group_size| {
376 // Lint the fractional part of literal just like integral part, but reversed.
377 let fractional_part = &parts[1].chars().rev().collect::<String>();
378 let _ = Self::do_lint(fractional_part, None)
379 .map(|fractional_group_size| {
380 let consistent = Self::parts_consistent(integral_group_size,
381 fractional_group_size,
385 WarningType::InconsistentDigitGrouping.display(&digit_info.grouping_hint(),
390 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(),
395 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(), cx, lit.span));
403 /// Given the sizes of the digit groups of both integral and fractional
404 /// parts, and the length
405 /// of both parts, determine if the digits have been grouped consistently.
406 fn parts_consistent(int_group_size: usize, frac_group_size: usize, int_size: usize, frac_size: usize) -> bool {
407 match (int_group_size, frac_group_size) {
408 // No groups on either side of decimal point - trivially consistent.
410 // Integral part has grouped digits, fractional part does not.
411 (_, 0) => frac_size <= int_group_size,
412 // Fractional part has grouped digits, integral part does not.
413 (0, _) => int_size <= frac_group_size,
414 // Both parts have grouped digits. Groups should be the same size.
415 (_, _) => int_group_size == frac_group_size,
419 /// Performs lint on `digits` (no decimal point) and returns the group
420 /// size on success or `WarningType` when emitting a warning.
421 fn do_lint(digits: &str, suffix: Option<&str>) -> Result<usize, WarningType> {
422 if let Some(suffix) = suffix {
423 if is_mistyped_suffix(suffix) {
424 return Err(WarningType::MistypedLiteralSuffix);
427 // Grab underscore indices with respect to the units digit.
428 let underscore_positions: Vec<usize> = digits
432 .filter_map(|(idx, digit)| if digit == '_' { Some(idx) } else { None })
435 if underscore_positions.is_empty() {
436 // Check if literal needs underscores.
437 if digits.len() > 5 {
438 Err(WarningType::UnreadableLiteral)
443 // Check consistency and the sizes of the groups.
444 let group_size = underscore_positions[0];
445 let consistent = underscore_positions
447 .all(|ps| ps[1] - ps[0] == group_size + 1)
448 // number of digits to the left of the last group cannot be bigger than group size.
449 && (digits.len() - underscore_positions.last()
450 .expect("there's at least one element") <= group_size + 1);
453 return Err(WarningType::InconsistentDigitGrouping);
454 } else if group_size > 4 {
455 return Err(WarningType::LargeDigitGroups);
462 #[derive(Copy, Clone)]
463 pub struct LiteralRepresentation {
467 impl LintPass for LiteralRepresentation {
468 fn get_lints(&self) -> LintArray {
469 lint_array!(DECIMAL_LITERAL_REPRESENTATION)
473 impl EarlyLintPass for LiteralRepresentation {
474 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
475 if in_external_macro(cx.sess(), expr.span) {
479 if let ExprKind::Lit(ref lit) = expr.node {
480 self.check_lit(cx, lit)
485 impl LiteralRepresentation {
486 pub fn new(threshold: u64) -> Self {
491 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
492 // Lint integral literals.
494 if let LitKind::Int(..) = lit.node;
495 if let Some(src) = snippet_opt(cx, lit.span);
496 if let Some(firstch) = src.chars().next();
497 if char::to_digit(firstch, 10).is_some();
499 let digit_info = DigitInfo::new(&src, false);
500 if digit_info.radix == Radix::Decimal {
501 let val = digit_info.digits
503 .filter(|&c| c != '_')
505 .parse::<u128>().unwrap();
506 if val < u128::from(self.threshold) {
509 let hex = format!("{:#X}", val);
510 let digit_info = DigitInfo::new(&hex[..], false);
511 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
512 warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
519 fn do_lint(digits: &str) -> Result<(), WarningType> {
520 if digits.len() == 1 {
521 // Lint for 1 digit literals, if someone really sets the threshold that low
522 if digits == "1" || digits == "2" || digits == "4" || digits == "8" || digits == "3" || digits == "7"
525 return Err(WarningType::DecimalRepresentation);
527 } else if digits.len() < 4 {
528 // Lint for Literals with a hex-representation of 2 or 3 digits
529 let f = &digits[0..1]; // first digit
530 let s = &digits[1..]; // suffix
532 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
533 // Powers of 2 minus 1
534 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
536 return Err(WarningType::DecimalRepresentation);
539 // Lint for Literals with a hex-representation of 4 digits or more
540 let f = &digits[0..1]; // first digit
541 let m = &digits[1..digits.len() - 1]; // middle digits, except last
542 let s = &digits[1..]; // suffix
543 // Powers of 2 with a margin of +15/-16
544 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
545 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
546 // Lint for representations with only 0s and Fs, while allowing 7 as the first
548 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
550 return Err(WarningType::DecimalRepresentation);
558 fn is_mistyped_suffix(suffix: &str) -> bool {
559 ["_8", "_16", "_32", "_64"].contains(&suffix)
562 fn is_possible_suffix_index(lit: &str, idx: usize, len: usize) -> bool {
563 ((len > 3 && idx == len - 3) || (len > 2 && idx == len - 2)) &&
564 is_mistyped_suffix(lit.split_at(idx).1)