1 //! Lints concerned with the grouping of digits with underscores in integral or
2 //! floating-point literal expressions.
5 use rustc::{declare_lint, lint_array};
8 use crate::utils::{in_external_macro, snippet_opt, span_lint_and_sugg};
10 /// **What it does:** Warns if a long integral or floating-point constant does
11 /// not contain underscores.
13 /// **Why is this bad?** Reading long numbers is difficult without separators.
15 /// **Known problems:** None.
22 declare_clippy_lint! {
23 pub UNREADABLE_LITERAL,
25 "long integer literal without underscores"
28 /// **What it does:** Warns if an integral or floating-point constant is
29 /// grouped inconsistently with underscores.
31 /// **Why is this bad?** Readers may incorrectly interpret inconsistently
34 /// **Known problems:** None.
39 /// 618_64_9189_73_511
41 declare_clippy_lint! {
42 pub INCONSISTENT_DIGIT_GROUPING,
44 "integer literals with digits grouped inconsistently"
47 /// **What it does:** Warns if the digits of an integral or floating-point
48 /// constant are grouped into groups that
51 /// **Why is this bad?** Negatively impacts readability.
53 /// **Known problems:** None.
60 declare_clippy_lint! {
61 pub LARGE_DIGIT_GROUPS,
63 "grouping digits into groups that are too large"
66 /// **What it does:** Warns if there is a better representation for a numeric literal.
68 /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
69 /// readable than a decimal representation.
71 /// **Known problems:** None.
76 /// `65_535` => `0xFFFF`
77 /// `4_042_322_160` => `0xF0F0_F0F0`
78 declare_clippy_lint! {
79 pub DECIMAL_LITERAL_REPRESENTATION,
81 "using decimal representation when hexadecimal would be better"
84 #[derive(Debug, PartialEq)]
85 pub(super) enum Radix {
93 /// Return a reasonable digit group size for this radix.
94 crate fn suggest_grouping(&self) -> usize {
96 Radix::Binary | Radix::Hexadecimal => 4,
97 Radix::Octal | Radix::Decimal => 3,
103 pub(super) struct DigitInfo<'a> {
104 /// Characters of a literal between the radix prefix and type suffix.
105 crate digits: &'a str,
106 /// Which radix the literal was represented in.
108 /// The radix prefix, if present.
109 crate prefix: Option<&'a str>,
110 /// The type suffix, including preceding underscore if present.
111 crate suffix: Option<&'a str>,
112 /// True for floating-point literals.
116 impl<'a> DigitInfo<'a> {
117 crate fn new(lit: &'a str, float: bool) -> Self {
118 // Determine delimiter for radix prefix, if present, and radix.
119 let radix = if lit.starts_with("0x") {
121 } else if lit.starts_with("0b") {
123 } else if lit.starts_with("0o") {
129 // Grab part of the literal after prefix, if present.
130 let (prefix, sans_prefix) = if let Radix::Decimal = radix {
133 let (p, s) = lit.split_at(2);
137 let mut last_d = '\0';
138 for (d_idx, d) in sans_prefix.char_indices() {
139 if !float && (d == 'i' || d == 'u') || float && (d == 'f' || d == 'e' || d == 'E') {
140 let suffix_start = if last_d == '_' { d_idx - 1 } else { d_idx };
141 let (digits, suffix) = sans_prefix.split_at(suffix_start);
146 suffix: Some(suffix),
163 /// Returns digits grouped in a sensible way.
164 crate fn grouping_hint(&self) -> String {
165 let group_size = self.radix.suggest_grouping();
166 if self.digits.contains('.') {
167 let mut parts = self.digits.split('.');
168 let int_part_hint = parts
170 .expect("split always returns at least one element")
173 .filter(|&c| c != '_')
176 .map(|chunk| chunk.into_iter().rev().collect())
178 .collect::<Vec<String>>()
180 let frac_part_hint = parts
182 .expect("already checked that there is a `.`")
184 .filter(|&c| c != '_')
187 .map(|chunk| chunk.into_iter().collect())
188 .collect::<Vec<String>>()
194 self.suffix.unwrap_or("")
197 let filtered_digits_vec = self.digits
199 .filter(|&c| c != '_')
201 .collect::<Vec<_>>();
202 let mut hint = filtered_digits_vec
204 .map(|chunk| chunk.into_iter().rev().collect())
206 .collect::<Vec<String>>()
208 // Forces hexadecimal values to be grouped by 4 being filled with zeroes (e.g 0x00ab_cdef)
209 let nb_digits_to_fill = filtered_digits_vec.len() % 4;
210 if self.radix == Radix::Hexadecimal && nb_digits_to_fill != 0 {
211 hint = format!("{:0>4}{}", &hint[..nb_digits_to_fill], &hint[nb_digits_to_fill..]);
215 self.prefix.unwrap_or(""),
217 self.suffix.unwrap_or("")
225 InconsistentDigitGrouping,
227 DecimalRepresentation,
231 crate fn display(&self, grouping_hint: &str, cx: &EarlyContext, span: syntax_pos::Span) {
233 WarningType::UnreadableLiteral => span_lint_and_sugg(
237 "long literal lacking separators",
239 grouping_hint.to_owned(),
241 WarningType::LargeDigitGroups => span_lint_and_sugg(
245 "digit groups should be smaller",
247 grouping_hint.to_owned(),
249 WarningType::InconsistentDigitGrouping => span_lint_and_sugg(
251 INCONSISTENT_DIGIT_GROUPING,
253 "digits grouped inconsistently by underscores",
255 grouping_hint.to_owned(),
257 WarningType::DecimalRepresentation => span_lint_and_sugg(
259 DECIMAL_LITERAL_REPRESENTATION,
261 "integer literal has a better hexadecimal representation",
263 grouping_hint.to_owned(),
269 #[derive(Copy, Clone)]
270 pub struct LiteralDigitGrouping;
272 impl LintPass for LiteralDigitGrouping {
273 fn get_lints(&self) -> LintArray {
276 INCONSISTENT_DIGIT_GROUPING,
282 impl EarlyLintPass for LiteralDigitGrouping {
283 fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
284 if in_external_macro(cx, expr.span) {
288 if let ExprKind::Lit(ref lit) = expr.node {
289 self.check_lit(cx, lit)
294 impl LiteralDigitGrouping {
295 fn check_lit(self, cx: &EarlyContext, lit: &Lit) {
297 LitKind::Int(..) => {
298 // Lint integral literals.
300 if let Some(src) = snippet_opt(cx, lit.span);
301 if let Some(firstch) = src.chars().next();
302 if char::to_digit(firstch, 10).is_some();
304 let digit_info = DigitInfo::new(&src, false);
305 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
306 warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
311 LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => {
312 // Lint floating-point literals.
314 if let Some(src) = snippet_opt(cx, lit.span);
315 if let Some(firstch) = src.chars().next();
316 if char::to_digit(firstch, 10).is_some();
318 let digit_info = DigitInfo::new(&src, true);
319 // Separate digits into integral and fractional parts.
320 let parts: Vec<&str> = digit_info
322 .split_terminator('.')
325 // Lint integral and fractional parts separately, and then check consistency of digit
326 // groups if both pass.
327 let _ = Self::do_lint(parts[0])
328 .map(|integral_group_size| {
330 // Lint the fractional part of literal just like integral part, but reversed.
331 let fractional_part = &parts[1].chars().rev().collect::<String>();
332 let _ = Self::do_lint(fractional_part)
333 .map(|fractional_group_size| {
334 let consistent = Self::parts_consistent(integral_group_size,
335 fractional_group_size,
339 WarningType::InconsistentDigitGrouping.display(&digit_info.grouping_hint(),
344 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(),
349 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(), cx, lit.span));
357 /// Given the sizes of the digit groups of both integral and fractional
358 /// parts, and the length
359 /// of both parts, determine if the digits have been grouped consistently.
360 fn parts_consistent(int_group_size: usize, frac_group_size: usize, int_size: usize, frac_size: usize) -> bool {
361 match (int_group_size, frac_group_size) {
362 // No groups on either side of decimal point - trivially consistent.
364 // Integral part has grouped digits, fractional part does not.
365 (_, 0) => frac_size <= int_group_size,
366 // Fractional part has grouped digits, integral part does not.
367 (0, _) => int_size <= frac_group_size,
368 // Both parts have grouped digits. Groups should be the same size.
369 (_, _) => int_group_size == frac_group_size,
373 /// Performs lint on `digits` (no decimal point) and returns the group
374 /// size on success or `WarningType` when emitting a warning.
375 fn do_lint(digits: &str) -> Result<usize, WarningType> {
376 // Grab underscore indices with respect to the units digit.
377 let underscore_positions: Vec<usize> = digits
381 .filter_map(|(idx, digit)| if digit == '_' { Some(idx) } else { None })
384 if underscore_positions.is_empty() {
385 // Check if literal needs underscores.
386 if digits.len() > 5 {
387 Err(WarningType::UnreadableLiteral)
392 // Check consistency and the sizes of the groups.
393 let group_size = underscore_positions[0];
394 let consistent = underscore_positions
396 .all(|ps| ps[1] - ps[0] == group_size + 1)
397 // number of digits to the left of the last group cannot be bigger than group size.
398 && (digits.len() - underscore_positions.last()
399 .expect("there's at least one element") <= group_size + 1);
402 return Err(WarningType::InconsistentDigitGrouping);
403 } else if group_size > 4 {
404 return Err(WarningType::LargeDigitGroups);
411 #[derive(Copy, Clone)]
412 pub struct LiteralRepresentation {
416 impl LintPass for LiteralRepresentation {
417 fn get_lints(&self) -> LintArray {
418 lint_array!(DECIMAL_LITERAL_REPRESENTATION)
422 impl EarlyLintPass for LiteralRepresentation {
423 fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
424 if in_external_macro(cx, expr.span) {
428 if let ExprKind::Lit(ref lit) = expr.node {
429 self.check_lit(cx, lit)
434 impl LiteralRepresentation {
435 pub fn new(threshold: u64) -> Self {
440 fn check_lit(self, cx: &EarlyContext, lit: &Lit) {
441 // Lint integral literals.
443 if let LitKind::Int(..) = lit.node;
444 if let Some(src) = snippet_opt(cx, lit.span);
445 if let Some(firstch) = src.chars().next();
446 if char::to_digit(firstch, 10).is_some();
448 let digit_info = DigitInfo::new(&src, false);
449 if digit_info.radix == Radix::Decimal {
450 let val = digit_info.digits
452 .filter(|&c| c != '_')
454 .parse::<u128>().unwrap();
455 if val < u128::from(self.threshold) {
458 let hex = format!("{:#X}", val);
459 let digit_info = DigitInfo::new(&hex[..], false);
460 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
461 warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
468 fn do_lint(digits: &str) -> Result<(), WarningType> {
469 if digits.len() == 1 {
470 // Lint for 1 digit literals, if someone really sets the threshold that low
471 if digits == "1" || digits == "2" || digits == "4" || digits == "8" || digits == "3" || digits == "7"
474 return Err(WarningType::DecimalRepresentation);
476 } else if digits.len() < 4 {
477 // Lint for Literals with a hex-representation of 2 or 3 digits
478 let f = &digits[0..1]; // first digit
479 let s = &digits[1..]; // suffix
481 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
482 // Powers of 2 minus 1
483 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
485 return Err(WarningType::DecimalRepresentation);
488 // Lint for Literals with a hex-representation of 4 digits or more
489 let f = &digits[0..1]; // first digit
490 let m = &digits[1..digits.len() - 1]; // middle digits, except last
491 let s = &digits[1..]; // suffix
492 // Powers of 2 with a margin of +15/-16
493 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
494 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
495 // Lint for representations with only 0s and Fs, while allowing 7 as the first
497 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
499 return Err(WarningType::DecimalRepresentation);