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_lint_pass, 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 integer 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 the digits of an integral or floating-point
87 /// constant are grouped into groups that
90 /// **Why is this bad?** Negatively impacts readability.
92 /// **Known problems:** None.
97 /// let x: u64 = 6186491_8973511;
99 pub LARGE_DIGIT_GROUPS,
101 "grouping digits into groups that are too large"
104 declare_clippy_lint! {
105 /// **What it does:** Warns if there is a better representation for a numeric literal.
107 /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
108 /// readable than a decimal representation.
110 /// **Known problems:** None.
115 /// `65_535` => `0xFFFF`
116 /// `4_042_322_160` => `0xF0F0_F0F0`
117 pub DECIMAL_LITERAL_REPRESENTATION,
119 "using decimal representation when hexadecimal would be better"
124 InconsistentDigitGrouping,
126 DecimalRepresentation,
127 MistypedLiteralSuffix,
131 fn display(&self, suggested_format: String, cx: &EarlyContext<'_>, span: rustc_span::Span) {
133 Self::MistypedLiteralSuffix => span_lint_and_sugg(
135 MISTYPED_LITERAL_SUFFIXES,
137 "mistyped literal suffix",
138 "did you mean to write",
140 Applicability::MaybeIncorrect,
142 Self::UnreadableLiteral => span_lint_and_sugg(
146 "long literal lacking separators",
149 Applicability::MachineApplicable,
151 Self::LargeDigitGroups => span_lint_and_sugg(
155 "digit groups should be smaller",
158 Applicability::MachineApplicable,
160 Self::InconsistentDigitGrouping => span_lint_and_sugg(
162 INCONSISTENT_DIGIT_GROUPING,
164 "digits grouped inconsistently by underscores",
167 Applicability::MachineApplicable,
169 Self::DecimalRepresentation => span_lint_and_sugg(
171 DECIMAL_LITERAL_REPRESENTATION,
173 "integer literal has a better hexadecimal representation",
176 Applicability::MachineApplicable,
182 declare_lint_pass!(LiteralDigitGrouping => [
184 INCONSISTENT_DIGIT_GROUPING,
186 MISTYPED_LITERAL_SUFFIXES,
189 impl EarlyLintPass for LiteralDigitGrouping {
190 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
191 if in_external_macro(cx.sess(), expr.span) {
195 if let ExprKind::Lit(ref lit) = expr.kind {
196 Self::check_lit(cx, lit)
201 // Length of each UUID hyphenated group in hex digits.
202 const UUID_GROUP_LENS: [usize; 5] = [8, 4, 4, 4, 12];
204 impl LiteralDigitGrouping {
205 fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
207 if let Some(src) = snippet_opt(cx, lit.span);
208 if let Some(mut num_lit) = NumericLiteral::from_lit(&src, &lit);
210 if !Self::check_for_mistyped_suffix(cx, lit.span, &mut num_lit) {
214 if Self::is_literal_uuid_formatted(&mut num_lit) {
220 let integral_group_size = Self::get_group_size(num_lit.integer.split('_'))?;
221 if let Some(fraction) = num_lit.fraction {
222 let fractional_group_size = Self::get_group_size(fraction.rsplit('_'))?;
224 let consistent = Self::parts_consistent(integral_group_size,
225 fractional_group_size,
226 num_lit.integer.len(),
229 return Err(WarningType::InconsistentDigitGrouping);
236 if let Err(warning_type) = result {
237 let should_warn = match warning_type {
238 | WarningType::UnreadableLiteral
239 | WarningType::InconsistentDigitGrouping
240 | WarningType::LargeDigitGroups => {
243 WarningType::DecimalRepresentation | WarningType::MistypedLiteralSuffix => {
248 warning_type.display(num_lit.format(), cx, lit.span)
255 // Returns `false` if the check fails
256 fn check_for_mistyped_suffix(
257 cx: &EarlyContext<'_>,
258 span: rustc_span::Span,
259 num_lit: &mut NumericLiteral<'_>,
261 if num_lit.suffix.is_some() {
265 let (part, mistyped_suffixes, missing_char) = if let Some((_, exponent)) = &mut num_lit.exponent {
266 (exponent, &["32", "64"][..], 'f')
271 .map_or((&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i'), |fraction| {
272 (fraction, &["32", "64"][..], 'f')
276 let mut split = part.rsplit('_');
277 let last_group = split.next().expect("At least one group");
278 if split.next().is_some() && mistyped_suffixes.contains(&last_group) {
279 *part = &part[..part.len() - last_group.len()];
280 let mut sugg = num_lit.format();
282 sugg.push(missing_char);
283 sugg.push_str(last_group);
284 WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
291 /// Checks whether the numeric literal matches the formatting of a UUID.
293 /// Returns `true` if the radix is hexadecimal, and the groups match the
294 /// UUID format of 8-4-4-4-12.
295 fn is_literal_uuid_formatted(num_lit: &mut NumericLiteral<'_>) -> bool {
296 if num_lit.radix != Radix::Hexadecimal {
300 // UUIDs should not have a fraction
301 if num_lit.fraction.is_some() {
305 let group_sizes: Vec<usize> = num_lit.integer.split('_').map(str::len).collect();
306 if UUID_GROUP_LENS.len() == group_sizes.len() {
307 UUID_GROUP_LENS.iter().zip(&group_sizes).all(|(&a, &b)| a == b)
313 /// Given the sizes of the digit groups of both integral and fractional
314 /// parts, and the length
315 /// of both parts, determine if the digits have been grouped consistently.
318 int_group_size: Option<usize>,
319 frac_group_size: Option<usize>,
323 match (int_group_size, frac_group_size) {
324 // No groups on either side of decimal point - trivially consistent.
325 (None, None) => true,
326 // Integral part has grouped digits, fractional part does not.
327 (Some(int_group_size), None) => frac_size <= int_group_size,
328 // Fractional part has grouped digits, integral part does not.
329 (None, Some(frac_group_size)) => int_size <= frac_group_size,
330 // Both parts have grouped digits. Groups should be the same size.
331 (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
335 /// Returns the size of the digit groups (or None if ungrouped) if successful,
336 /// otherwise returns a `WarningType` for linting.
337 fn get_group_size<'a>(groups: impl Iterator<Item = &'a str>) -> Result<Option<usize>, WarningType> {
338 let mut groups = groups.map(str::len);
340 let first = groups.next().expect("At least one group");
342 if let Some(second) = groups.next() {
343 if !groups.all(|x| x == second) || first > second {
344 Err(WarningType::InconsistentDigitGrouping)
345 } else if second > 4 {
346 Err(WarningType::LargeDigitGroups)
350 } else if first > 5 {
351 Err(WarningType::UnreadableLiteral)
358 #[allow(clippy::module_name_repetitions)]
359 #[derive(Copy, Clone)]
360 pub struct DecimalLiteralRepresentation {
364 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
366 impl EarlyLintPass for DecimalLiteralRepresentation {
367 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
368 if in_external_macro(cx.sess(), expr.span) {
372 if let ExprKind::Lit(ref lit) = expr.kind {
373 self.check_lit(cx, lit)
378 impl DecimalLiteralRepresentation {
380 pub fn new(threshold: u64) -> Self {
383 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
384 // Lint integral literals.
386 if let LitKind::Int(val, _) = lit.kind;
387 if let Some(src) = snippet_opt(cx, lit.span);
388 if let Some(num_lit) = NumericLiteral::from_lit(&src, &lit);
389 if num_lit.radix == Radix::Decimal;
390 if val >= u128::from(self.threshold);
392 let hex = format!("{:#X}", val);
393 let num_lit = NumericLiteral::new(&hex, num_lit.suffix, false);
394 let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
395 warning_type.display(num_lit.format(), cx, lit.span)
401 fn do_lint(digits: &str) -> Result<(), WarningType> {
402 if digits.len() == 1 {
403 // Lint for 1 digit literals, if someone really sets the threshold that low
412 return Err(WarningType::DecimalRepresentation);
414 } else if digits.len() < 4 {
415 // Lint for Literals with a hex-representation of 2 or 3 digits
416 let f = &digits[0..1]; // first digit
417 let s = &digits[1..]; // suffix
420 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
421 // Powers of 2 minus 1
422 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
424 return Err(WarningType::DecimalRepresentation);
427 // Lint for Literals with a hex-representation of 4 digits or more
428 let f = &digits[0..1]; // first digit
429 let m = &digits[1..digits.len() - 1]; // middle digits, except last
430 let s = &digits[1..]; // suffix
432 // Powers of 2 with a margin of +15/-16
433 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
434 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
435 // Lint for representations with only 0s and Fs, while allowing 7 as the first
437 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
439 return Err(WarningType::DecimalRepresentation);