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_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 if an integral or floating-point constant is
30 /// grouped inconsistently with underscores.
32 /// **Why is this bad?** Readers may incorrectly interpret inconsistently
35 /// **Known problems:** None.
40 /// 618_64_9189_73_511
42 declare_clippy_lint! {
43 pub INCONSISTENT_DIGIT_GROUPING,
45 "integer literals with digits grouped inconsistently"
48 /// **What it does:** Warns if the digits of an integral or floating-point
49 /// constant are grouped into groups that
52 /// **Why is this bad?** Negatively impacts readability.
54 /// **Known problems:** None.
61 declare_clippy_lint! {
62 pub LARGE_DIGIT_GROUPS,
64 "grouping digits into groups that are too large"
67 /// **What it does:** Warns if there is a better representation for a numeric literal.
69 /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
70 /// readable than a decimal representation.
72 /// **Known problems:** None.
77 /// `65_535` => `0xFFFF`
78 /// `4_042_322_160` => `0xF0F0_F0F0`
79 declare_clippy_lint! {
80 pub DECIMAL_LITERAL_REPRESENTATION,
82 "using decimal representation when hexadecimal would be better"
85 #[derive(Debug, PartialEq)]
86 pub(super) enum Radix {
94 /// Return a reasonable digit group size for this radix.
95 crate fn suggest_grouping(&self) -> usize {
97 Radix::Binary | Radix::Hexadecimal => 4,
98 Radix::Octal | Radix::Decimal => 3,
104 pub(super) struct DigitInfo<'a> {
105 /// Characters of a literal between the radix prefix and type suffix.
106 crate digits: &'a str,
107 /// Which radix the literal was represented in.
109 /// The radix prefix, if present.
110 crate prefix: Option<&'a str>,
111 /// The type suffix, including preceding underscore if present.
112 crate suffix: Option<&'a str>,
113 /// True for floating-point literals.
117 impl<'a> DigitInfo<'a> {
118 crate fn new(lit: &'a str, float: bool) -> Self {
119 // Determine delimiter for radix prefix, if present, and radix.
120 let radix = if lit.starts_with("0x") {
122 } else if lit.starts_with("0b") {
124 } else if lit.starts_with("0o") {
130 // Grab part of the literal after prefix, if present.
131 let (prefix, sans_prefix) = if let Radix::Decimal = radix {
134 let (p, s) = lit.split_at(2);
138 let mut last_d = '\0';
139 for (d_idx, d) in sans_prefix.char_indices() {
140 if !float && (d == 'i' || d == 'u') || float && (d == 'f' || d == 'e' || d == 'E') {
141 let suffix_start = if last_d == '_' { d_idx - 1 } else { d_idx };
142 let (digits, suffix) = sans_prefix.split_at(suffix_start);
147 suffix: Some(suffix),
164 /// Returns digits grouped in a sensible way.
165 crate fn grouping_hint(&self) -> String {
166 let group_size = self.radix.suggest_grouping();
167 if self.digits.contains('.') {
168 let mut parts = self.digits.split('.');
169 let int_part_hint = parts
171 .expect("split always returns at least one element")
174 .filter(|&c| c != '_')
177 .map(|chunk| chunk.into_iter().rev().collect())
179 .collect::<Vec<String>>()
181 let frac_part_hint = parts
183 .expect("already checked that there is a `.`")
185 .filter(|&c| c != '_')
188 .map(|chunk| chunk.into_iter().collect())
189 .collect::<Vec<String>>()
195 self.suffix.unwrap_or("")
198 let filtered_digits_vec = self.digits
200 .filter(|&c| c != '_')
202 .collect::<Vec<_>>();
203 let mut hint = filtered_digits_vec
205 .map(|chunk| chunk.into_iter().rev().collect())
207 .collect::<Vec<String>>()
209 // Forces hexadecimal values to be grouped by 4 being filled with zeroes (e.g 0x00ab_cdef)
210 let nb_digits_to_fill = filtered_digits_vec.len() % 4;
211 if self.radix == Radix::Hexadecimal && nb_digits_to_fill != 0 {
212 hint = format!("{:0>4}{}", &hint[..nb_digits_to_fill], &hint[nb_digits_to_fill..]);
216 self.prefix.unwrap_or(""),
218 self.suffix.unwrap_or("")
226 InconsistentDigitGrouping,
228 DecimalRepresentation,
232 crate fn display(&self, grouping_hint: &str, cx: &EarlyContext<'_>, span: syntax_pos::Span) {
234 WarningType::UnreadableLiteral => span_lint_and_sugg(
238 "long literal lacking separators",
240 grouping_hint.to_owned(),
242 WarningType::LargeDigitGroups => span_lint_and_sugg(
246 "digit groups should be smaller",
248 grouping_hint.to_owned(),
250 WarningType::InconsistentDigitGrouping => span_lint_and_sugg(
252 INCONSISTENT_DIGIT_GROUPING,
254 "digits grouped inconsistently by underscores",
256 grouping_hint.to_owned(),
258 WarningType::DecimalRepresentation => span_lint_and_sugg(
260 DECIMAL_LITERAL_REPRESENTATION,
262 "integer literal has a better hexadecimal representation",
264 grouping_hint.to_owned(),
270 #[derive(Copy, Clone)]
271 pub struct LiteralDigitGrouping;
273 impl LintPass for LiteralDigitGrouping {
274 fn get_lints(&self) -> LintArray {
277 INCONSISTENT_DIGIT_GROUPING,
283 impl EarlyLintPass for LiteralDigitGrouping {
284 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
285 if in_external_macro(cx.sess(), expr.span) {
289 if let ExprKind::Lit(ref lit) = expr.node {
290 self.check_lit(cx, lit)
295 impl LiteralDigitGrouping {
296 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
298 LitKind::Int(..) => {
299 // Lint integral literals.
301 if let Some(src) = snippet_opt(cx, lit.span);
302 if let Some(firstch) = src.chars().next();
303 if char::to_digit(firstch, 10).is_some();
305 let digit_info = DigitInfo::new(&src, false);
306 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
307 warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
312 LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => {
313 // Lint floating-point literals.
315 if let Some(src) = snippet_opt(cx, lit.span);
316 if let Some(firstch) = src.chars().next();
317 if char::to_digit(firstch, 10).is_some();
319 let digit_info = DigitInfo::new(&src, true);
320 // Separate digits into integral and fractional parts.
321 let parts: Vec<&str> = digit_info
323 .split_terminator('.')
326 // Lint integral and fractional parts separately, and then check consistency of digit
327 // groups if both pass.
328 let _ = Self::do_lint(parts[0])
329 .map(|integral_group_size| {
331 // Lint the fractional part of literal just like integral part, but reversed.
332 let fractional_part = &parts[1].chars().rev().collect::<String>();
333 let _ = Self::do_lint(fractional_part)
334 .map(|fractional_group_size| {
335 let consistent = Self::parts_consistent(integral_group_size,
336 fractional_group_size,
340 WarningType::InconsistentDigitGrouping.display(&digit_info.grouping_hint(),
345 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(),
350 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(), cx, lit.span));
358 /// Given the sizes of the digit groups of both integral and fractional
359 /// parts, and the length
360 /// of both parts, determine if the digits have been grouped consistently.
361 fn parts_consistent(int_group_size: usize, frac_group_size: usize, int_size: usize, frac_size: usize) -> bool {
362 match (int_group_size, frac_group_size) {
363 // No groups on either side of decimal point - trivially consistent.
365 // Integral part has grouped digits, fractional part does not.
366 (_, 0) => frac_size <= int_group_size,
367 // Fractional part has grouped digits, integral part does not.
368 (0, _) => int_size <= frac_group_size,
369 // Both parts have grouped digits. Groups should be the same size.
370 (_, _) => int_group_size == frac_group_size,
374 /// Performs lint on `digits` (no decimal point) and returns the group
375 /// size on success or `WarningType` when emitting a warning.
376 fn do_lint(digits: &str) -> Result<usize, WarningType> {
377 // Grab underscore indices with respect to the units digit.
378 let underscore_positions: Vec<usize> = digits
382 .filter_map(|(idx, digit)| if digit == '_' { Some(idx) } else { None })
385 if underscore_positions.is_empty() {
386 // Check if literal needs underscores.
387 if digits.len() > 5 {
388 Err(WarningType::UnreadableLiteral)
393 // Check consistency and the sizes of the groups.
394 let group_size = underscore_positions[0];
395 let consistent = underscore_positions
397 .all(|ps| ps[1] - ps[0] == group_size + 1)
398 // number of digits to the left of the last group cannot be bigger than group size.
399 && (digits.len() - underscore_positions.last()
400 .expect("there's at least one element") <= group_size + 1);
403 return Err(WarningType::InconsistentDigitGrouping);
404 } else if group_size > 4 {
405 return Err(WarningType::LargeDigitGroups);
412 #[derive(Copy, Clone)]
413 pub struct LiteralRepresentation {
417 impl LintPass for LiteralRepresentation {
418 fn get_lints(&self) -> LintArray {
419 lint_array!(DECIMAL_LITERAL_REPRESENTATION)
423 impl EarlyLintPass for LiteralRepresentation {
424 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
425 if in_external_macro(cx.sess(), expr.span) {
429 if let ExprKind::Lit(ref lit) = expr.node {
430 self.check_lit(cx, lit)
435 impl LiteralRepresentation {
436 pub fn new(threshold: u64) -> Self {
441 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
442 // Lint integral literals.
444 if let LitKind::Int(..) = lit.node;
445 if let Some(src) = snippet_opt(cx, lit.span);
446 if let Some(firstch) = src.chars().next();
447 if char::to_digit(firstch, 10).is_some();
449 let digit_info = DigitInfo::new(&src, false);
450 if digit_info.radix == Radix::Decimal {
451 let val = digit_info.digits
453 .filter(|&c| c != '_')
455 .parse::<u128>().unwrap();
456 if val < u128::from(self.threshold) {
459 let hex = format!("{:#X}", val);
460 let digit_info = DigitInfo::new(&hex[..], false);
461 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
462 warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
469 fn do_lint(digits: &str) -> Result<(), WarningType> {
470 if digits.len() == 1 {
471 // Lint for 1 digit literals, if someone really sets the threshold that low
472 if digits == "1" || digits == "2" || digits == "4" || digits == "8" || digits == "3" || digits == "7"
475 return Err(WarningType::DecimalRepresentation);
477 } else if digits.len() < 4 {
478 // Lint for Literals with a hex-representation of 2 or 3 digits
479 let f = &digits[0..1]; // first digit
480 let s = &digits[1..]; // suffix
482 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
483 // Powers of 2 minus 1
484 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
486 return Err(WarningType::DecimalRepresentation);
489 // Lint for Literals with a hex-representation of 4 digits or more
490 let f = &digits[0..1]; // first digit
491 let m = &digits[1..digits.len() - 1]; // middle digits, except last
492 let s = &digits[1..]; // suffix
493 // Powers of 2 with a margin of +15/-16
494 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
495 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
496 // Lint for representations with only 0s and Fs, while allowing 7 as the first
498 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
500 return Err(WarningType::DecimalRepresentation);