1 //! Lints concerned with the grouping of digits with underscores in integral or
2 //! floating-point literal expressions.
6 numeric_literal::{NumericLiteral, Radix},
7 snippet_opt, span_lint_and_sugg,
9 use if_chain::if_chain;
10 use rustc_ast::ast::{Expr, ExprKind, Lit, LitKind};
11 use rustc_errors::Applicability;
12 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
13 use rustc_middle::lint::in_external_macro;
14 use rustc_session::{declare_tool_lint, impl_lint_pass};
16 declare_clippy_lint! {
17 /// **What it does:** Warns if a long integral or floating-point constant does
18 /// not contain underscores.
20 /// **Why is this bad?** Reading long numbers is difficult without separators.
22 /// **Known problems:** None.
28 /// let x: u64 = 61864918973511;
31 /// let x: u64 = 61_864_918_973_511;
33 pub UNREADABLE_LITERAL,
35 "long literal without underscores"
38 declare_clippy_lint! {
39 /// **What it does:** Warns for mistyped suffix in literals
41 /// **Why is this bad?** This is most probably a typo
43 /// **Known problems:**
44 /// - Recommends a signed suffix, even though the number might be too big and an unsigned
45 /// suffix is required
46 /// - Does not match on `_127` since that is a valid grouping for decimal and octal numbers
51 /// // Probably mistyped
57 pub MISTYPED_LITERAL_SUFFIXES,
59 "mistyped literal suffix"
62 declare_clippy_lint! {
63 /// **What it does:** Warns if an integral or floating-point constant is
64 /// grouped inconsistently with underscores.
66 /// **Why is this bad?** Readers may incorrectly interpret inconsistently
69 /// **Known problems:** None.
75 /// let x: u64 = 618_64_9189_73_511;
78 /// let x: u64 = 61_864_918_973_511;
80 pub INCONSISTENT_DIGIT_GROUPING,
82 "integer literals with digits grouped inconsistently"
85 declare_clippy_lint! {
86 /// **What it does:** Warns if hexadecimal or binary literals are not grouped
87 /// by nibble or byte.
89 /// **Why is this bad?** Negatively impacts readability.
91 /// **Known problems:** None.
96 /// let x: u32 = 0xFFF_FFF;
97 /// let y: u8 = 0b01_011_101;
99 pub UNUSUAL_BYTE_GROUPINGS,
101 "binary or hex literals that aren't grouped by four"
104 declare_clippy_lint! {
105 /// **What it does:** Warns if the digits of an integral or floating-point
106 /// constant are grouped into groups that
109 /// **Why is this bad?** Negatively impacts readability.
111 /// **Known problems:** None.
116 /// let x: u64 = 6186491_8973511;
118 pub LARGE_DIGIT_GROUPS,
120 "grouping digits into groups that are too large"
123 declare_clippy_lint! {
124 /// **What it does:** Warns if there is a better representation for a numeric literal.
126 /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
127 /// readable than a decimal representation.
129 /// **Known problems:** None.
134 /// `65_535` => `0xFFFF`
135 /// `4_042_322_160` => `0xF0F0_F0F0`
136 pub DECIMAL_LITERAL_REPRESENTATION,
138 "using decimal representation when hexadecimal would be better"
143 InconsistentDigitGrouping,
145 DecimalRepresentation,
146 MistypedLiteralSuffix,
147 UnusualByteGroupings,
151 fn display(&self, suggested_format: String, cx: &EarlyContext<'_>, span: rustc_span::Span) {
153 Self::MistypedLiteralSuffix => span_lint_and_sugg(
155 MISTYPED_LITERAL_SUFFIXES,
157 "mistyped literal suffix",
158 "did you mean to write",
160 Applicability::MaybeIncorrect,
162 Self::UnreadableLiteral => span_lint_and_sugg(
166 "long literal lacking separators",
169 Applicability::MachineApplicable,
171 Self::LargeDigitGroups => span_lint_and_sugg(
175 "digit groups should be smaller",
178 Applicability::MachineApplicable,
180 Self::InconsistentDigitGrouping => span_lint_and_sugg(
182 INCONSISTENT_DIGIT_GROUPING,
184 "digits grouped inconsistently by underscores",
187 Applicability::MachineApplicable,
189 Self::DecimalRepresentation => span_lint_and_sugg(
191 DECIMAL_LITERAL_REPRESENTATION,
193 "integer literal has a better hexadecimal representation",
196 Applicability::MachineApplicable,
198 Self::UnusualByteGroupings => span_lint_and_sugg(
200 UNUSUAL_BYTE_GROUPINGS,
202 "digits of hex or binary literal not grouped by four",
205 Applicability::MachineApplicable,
211 #[allow(clippy::module_name_repetitions)]
212 #[derive(Copy, Clone)]
213 pub struct LiteralDigitGrouping {
214 lint_fraction_readability: bool,
217 impl_lint_pass!(LiteralDigitGrouping => [
219 INCONSISTENT_DIGIT_GROUPING,
221 MISTYPED_LITERAL_SUFFIXES,
222 UNUSUAL_BYTE_GROUPINGS,
225 impl EarlyLintPass for LiteralDigitGrouping {
226 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
227 if in_external_macro(cx.sess(), expr.span) {
231 if let ExprKind::Lit(ref lit) = expr.kind {
232 self.check_lit(cx, lit)
237 // Length of each UUID hyphenated group in hex digits.
238 const UUID_GROUP_LENS: [usize; 5] = [8, 4, 4, 4, 12];
240 impl LiteralDigitGrouping {
241 pub fn new(lint_fraction_readability: bool) -> Self {
243 lint_fraction_readability,
247 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
249 if let Some(src) = snippet_opt(cx, lit.span);
250 if let Some(mut num_lit) = NumericLiteral::from_lit(&src, &lit);
252 if !Self::check_for_mistyped_suffix(cx, lit.span, &mut num_lit) {
256 if Self::is_literal_uuid_formatted(&mut num_lit) {
262 let integral_group_size = Self::get_group_size(num_lit.integer.split('_'), num_lit.radix, true)?;
263 if let Some(fraction) = num_lit.fraction {
264 let fractional_group_size = Self::get_group_size(
265 fraction.rsplit('_'),
267 self.lint_fraction_readability)?;
269 let consistent = Self::parts_consistent(integral_group_size,
270 fractional_group_size,
271 num_lit.integer.len(),
274 return Err(WarningType::InconsistentDigitGrouping);
282 if let Err(warning_type) = result {
283 let should_warn = match warning_type {
284 | WarningType::UnreadableLiteral
285 | WarningType::InconsistentDigitGrouping
286 | WarningType::UnusualByteGroupings
287 | WarningType::LargeDigitGroups => {
290 WarningType::DecimalRepresentation | WarningType::MistypedLiteralSuffix => {
295 warning_type.display(num_lit.format(), cx, lit.span)
302 // Returns `false` if the check fails
303 fn check_for_mistyped_suffix(
304 cx: &EarlyContext<'_>,
305 span: rustc_span::Span,
306 num_lit: &mut NumericLiteral<'_>,
308 if num_lit.suffix.is_some() {
312 let (part, mistyped_suffixes, missing_char) = if let Some((_, exponent)) = &mut num_lit.exponent {
313 (exponent, &["32", "64"][..], 'f')
314 } else if num_lit.fraction.is_some() {
315 (&mut num_lit.integer, &["32", "64"][..], 'f')
317 (&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i')
320 let mut split = part.rsplit('_');
321 let last_group = split.next().expect("At least one group");
322 if split.next().is_some() && mistyped_suffixes.contains(&last_group) {
323 *part = &part[..part.len() - last_group.len()];
324 let mut sugg = num_lit.format();
326 sugg.push(missing_char);
327 sugg.push_str(last_group);
328 WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
335 /// Checks whether the numeric literal matches the formatting of a UUID.
337 /// Returns `true` if the radix is hexadecimal, and the groups match the
338 /// UUID format of 8-4-4-4-12.
339 fn is_literal_uuid_formatted(num_lit: &mut NumericLiteral<'_>) -> bool {
340 if num_lit.radix != Radix::Hexadecimal {
344 // UUIDs should not have a fraction
345 if num_lit.fraction.is_some() {
349 let group_sizes: Vec<usize> = num_lit.integer.split('_').map(str::len).collect();
350 if UUID_GROUP_LENS.len() == group_sizes.len() {
351 UUID_GROUP_LENS.iter().zip(&group_sizes).all(|(&a, &b)| a == b)
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.
362 int_group_size: Option<usize>,
363 frac_group_size: Option<usize>,
367 match (int_group_size, frac_group_size) {
368 // No groups on either side of decimal point - trivially consistent.
369 (None, None) => true,
370 // Integral part has grouped digits, fractional part does not.
371 (Some(int_group_size), None) => frac_size <= int_group_size,
372 // Fractional part has grouped digits, integral part does not.
373 (None, Some(frac_group_size)) => int_size <= frac_group_size,
374 // Both parts have grouped digits. Groups should be the same size.
375 (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
379 /// Returns the size of the digit groups (or None if ungrouped) if successful,
380 /// otherwise returns a `WarningType` for linting.
381 fn get_group_size<'a>(
382 groups: impl Iterator<Item = &'a str>,
384 lint_unreadable: bool,
385 ) -> Result<Option<usize>, WarningType> {
386 let mut groups = groups.map(str::len);
388 let first = groups.next().expect("At least one group");
390 if (radix == Radix::Binary || radix == Radix::Hexadecimal) && groups.any(|i| i != 4 && i != 2) {
391 return Err(WarningType::UnusualByteGroupings);
394 if let Some(second) = groups.next() {
395 if !groups.all(|x| x == second) || first > second {
396 Err(WarningType::InconsistentDigitGrouping)
397 } else if second > 4 {
398 Err(WarningType::LargeDigitGroups)
402 } else if first > 5 && lint_unreadable {
403 Err(WarningType::UnreadableLiteral)
410 #[allow(clippy::module_name_repetitions)]
411 #[derive(Copy, Clone)]
412 pub struct DecimalLiteralRepresentation {
416 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
418 impl EarlyLintPass for DecimalLiteralRepresentation {
419 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
420 if in_external_macro(cx.sess(), expr.span) {
424 if let ExprKind::Lit(ref lit) = expr.kind {
425 self.check_lit(cx, lit)
430 impl DecimalLiteralRepresentation {
432 pub fn new(threshold: u64) -> Self {
435 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
436 // Lint integral literals.
438 if let LitKind::Int(val, _) = lit.kind;
439 if let Some(src) = snippet_opt(cx, lit.span);
440 if let Some(num_lit) = NumericLiteral::from_lit(&src, &lit);
441 if num_lit.radix == Radix::Decimal;
442 if val >= u128::from(self.threshold);
444 let hex = format!("{:#X}", val);
445 let num_lit = NumericLiteral::new(&hex, num_lit.suffix, false);
446 let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
447 warning_type.display(num_lit.format(), cx, lit.span)
453 fn do_lint(digits: &str) -> Result<(), WarningType> {
454 if digits.len() == 1 {
455 // Lint for 1 digit literals, if someone really sets the threshold that low
464 return Err(WarningType::DecimalRepresentation);
466 } else if digits.len() < 4 {
467 // Lint for Literals with a hex-representation of 2 or 3 digits
468 let f = &digits[0..1]; // first digit
469 let s = &digits[1..]; // suffix
472 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
473 // Powers of 2 minus 1
474 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
476 return Err(WarningType::DecimalRepresentation);
479 // Lint for Literals with a hex-representation of 4 digits or more
480 let f = &digits[0..1]; // first digit
481 let m = &digits[1..digits.len() - 1]; // middle digits, except last
482 let s = &digits[1..]; // suffix
484 // Powers of 2 with a margin of +15/-16
485 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
486 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
487 // Lint for representations with only 0s and Fs, while allowing 7 as the first
489 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
491 return Err(WarningType::DecimalRepresentation);