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.
27 /// let x: u64 = 61864918973511;
29 pub UNREADABLE_LITERAL,
31 "long integer literal without underscores"
34 declare_clippy_lint! {
35 /// **What it does:** Warns for mistyped suffix in literals
37 /// **Why is this bad?** This is most probably a typo
39 /// **Known problems:**
40 /// - Recommends a signed suffix, even though the number might be too big and an unsigned
41 /// suffix is required
42 /// - Does not match on `_127` since that is a valid grouping for decimal and octal numbers
49 pub MISTYPED_LITERAL_SUFFIXES,
51 "mistyped literal suffix"
54 declare_clippy_lint! {
55 /// **What it does:** Warns if an integral or floating-point constant is
56 /// grouped inconsistently with underscores.
58 /// **Why is this bad?** Readers may incorrectly interpret inconsistently
61 /// **Known problems:** None.
66 /// let x: u64 = 618_64_9189_73_511;
68 pub INCONSISTENT_DIGIT_GROUPING,
70 "integer literals with digits grouped inconsistently"
73 declare_clippy_lint! {
74 /// **What it does:** Warns if the digits of an integral or floating-point
75 /// constant are grouped into groups that
78 /// **Why is this bad?** Negatively impacts readability.
80 /// **Known problems:** None.
85 /// let x: u64 = 6186491_8973511;
87 pub LARGE_DIGIT_GROUPS,
89 "grouping digits into groups that are too large"
92 declare_clippy_lint! {
93 /// **What it does:** Warns if there is a better representation for a numeric literal.
95 /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
96 /// readable than a decimal representation.
98 /// **Known problems:** None.
103 /// `65_535` => `0xFFFF`
104 /// `4_042_322_160` => `0xF0F0_F0F0`
105 pub DECIMAL_LITERAL_REPRESENTATION,
107 "using decimal representation when hexadecimal would be better"
112 InconsistentDigitGrouping,
114 DecimalRepresentation,
115 MistypedLiteralSuffix,
119 fn display(&self, suggested_format: String, cx: &EarlyContext<'_>, span: rustc_span::Span) {
121 Self::MistypedLiteralSuffix => span_lint_and_sugg(
123 MISTYPED_LITERAL_SUFFIXES,
125 "mistyped literal suffix",
126 "did you mean to write",
128 Applicability::MaybeIncorrect,
130 Self::UnreadableLiteral => span_lint_and_sugg(
134 "long literal lacking separators",
137 Applicability::MachineApplicable,
139 Self::LargeDigitGroups => span_lint_and_sugg(
143 "digit groups should be smaller",
146 Applicability::MachineApplicable,
148 Self::InconsistentDigitGrouping => span_lint_and_sugg(
150 INCONSISTENT_DIGIT_GROUPING,
152 "digits grouped inconsistently by underscores",
155 Applicability::MachineApplicable,
157 Self::DecimalRepresentation => span_lint_and_sugg(
159 DECIMAL_LITERAL_REPRESENTATION,
161 "integer literal has a better hexadecimal representation",
164 Applicability::MachineApplicable,
170 declare_lint_pass!(LiteralDigitGrouping => [
172 INCONSISTENT_DIGIT_GROUPING,
174 MISTYPED_LITERAL_SUFFIXES,
177 impl EarlyLintPass for LiteralDigitGrouping {
178 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
179 if in_external_macro(cx.sess(), expr.span) {
183 if let ExprKind::Lit(ref lit) = expr.kind {
184 Self::check_lit(cx, lit)
189 // Length of each UUID hyphenated group in hex digits.
190 const UUID_GROUP_LENS: [usize; 5] = [8, 4, 4, 4, 12];
192 impl LiteralDigitGrouping {
193 fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
195 if let Some(src) = snippet_opt(cx, lit.span);
196 if let Some(mut num_lit) = NumericLiteral::from_lit(&src, &lit);
198 if !Self::check_for_mistyped_suffix(cx, lit.span, &mut num_lit) {
202 if Self::is_literal_uuid_formatted(&mut num_lit) {
208 let integral_group_size = Self::get_group_size(num_lit.integer.split('_'))?;
209 if let Some(fraction) = num_lit.fraction {
210 let fractional_group_size = Self::get_group_size(fraction.rsplit('_'))?;
212 let consistent = Self::parts_consistent(integral_group_size,
213 fractional_group_size,
214 num_lit.integer.len(),
217 return Err(WarningType::InconsistentDigitGrouping);
224 if let Err(warning_type) = result {
225 let should_warn = match warning_type {
226 | WarningType::UnreadableLiteral
227 | WarningType::InconsistentDigitGrouping
228 | WarningType::LargeDigitGroups => {
231 WarningType::DecimalRepresentation | WarningType::MistypedLiteralSuffix => {
236 warning_type.display(num_lit.format(), cx, lit.span)
243 // Returns `false` if the check fails
244 fn check_for_mistyped_suffix(
245 cx: &EarlyContext<'_>,
246 span: rustc_span::Span,
247 num_lit: &mut NumericLiteral<'_>,
249 if num_lit.suffix.is_some() {
253 let (part, mistyped_suffixes, missing_char) = if let Some((_, exponent)) = &mut num_lit.exponent {
254 (exponent, &["32", "64"][..], 'f')
255 } else if let Some(fraction) = &mut num_lit.fraction {
256 (fraction, &["32", "64"][..], 'f')
258 (&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i')
261 let mut split = part.rsplit('_');
262 let last_group = split.next().expect("At least one group");
263 if split.next().is_some() && mistyped_suffixes.contains(&last_group) {
264 *part = &part[..part.len() - last_group.len()];
265 let mut sugg = num_lit.format();
267 sugg.push(missing_char);
268 sugg.push_str(last_group);
269 WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
276 /// Checks whether the numeric literal matches the formatting of a UUID.
278 /// Returns `true` if the radix is hexadecimal, and the groups match the
279 /// UUID format of 8-4-4-4-12.
280 fn is_literal_uuid_formatted(num_lit: &mut NumericLiteral<'_>) -> bool {
281 if num_lit.radix != Radix::Hexadecimal {
285 // UUIDs should not have a fraction
286 if num_lit.fraction.is_some() {
290 let group_sizes: Vec<usize> = num_lit.integer.split('_').map(str::len).collect();
291 if UUID_GROUP_LENS.len() == group_sizes.len() {
292 UUID_GROUP_LENS.iter().zip(&group_sizes).all(|(&a, &b)| a == b)
298 /// Given the sizes of the digit groups of both integral and fractional
299 /// parts, and the length
300 /// of both parts, determine if the digits have been grouped consistently.
303 int_group_size: Option<usize>,
304 frac_group_size: Option<usize>,
308 match (int_group_size, frac_group_size) {
309 // No groups on either side of decimal point - trivially consistent.
310 (None, None) => true,
311 // Integral part has grouped digits, fractional part does not.
312 (Some(int_group_size), None) => frac_size <= int_group_size,
313 // Fractional part has grouped digits, integral part does not.
314 (None, Some(frac_group_size)) => int_size <= frac_group_size,
315 // Both parts have grouped digits. Groups should be the same size.
316 (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
320 /// Returns the size of the digit groups (or None if ungrouped) if successful,
321 /// otherwise returns a `WarningType` for linting.
322 fn get_group_size<'a>(groups: impl Iterator<Item = &'a str>) -> Result<Option<usize>, WarningType> {
323 let mut groups = groups.map(str::len);
325 let first = groups.next().expect("At least one group");
327 if let Some(second) = groups.next() {
328 if !groups.all(|x| x == second) || first > second {
329 Err(WarningType::InconsistentDigitGrouping)
330 } else if second > 4 {
331 Err(WarningType::LargeDigitGroups)
335 } else if first > 5 {
336 Err(WarningType::UnreadableLiteral)
343 #[allow(clippy::module_name_repetitions)]
344 #[derive(Copy, Clone)]
345 pub struct DecimalLiteralRepresentation {
349 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
351 impl EarlyLintPass for DecimalLiteralRepresentation {
352 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
353 if in_external_macro(cx.sess(), expr.span) {
357 if let ExprKind::Lit(ref lit) = expr.kind {
358 self.check_lit(cx, lit)
363 impl DecimalLiteralRepresentation {
365 pub fn new(threshold: u64) -> Self {
368 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
369 // Lint integral literals.
371 if let LitKind::Int(val, _) = lit.kind;
372 if let Some(src) = snippet_opt(cx, lit.span);
373 if let Some(num_lit) = NumericLiteral::from_lit(&src, &lit);
374 if num_lit.radix == Radix::Decimal;
375 if val >= u128::from(self.threshold);
377 let hex = format!("{:#X}", val);
378 let num_lit = NumericLiteral::new(&hex, num_lit.suffix, false);
379 let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
380 warning_type.display(num_lit.format(), cx, lit.span)
386 fn do_lint(digits: &str) -> Result<(), WarningType> {
387 if digits.len() == 1 {
388 // Lint for 1 digit literals, if someone really sets the threshold that low
397 return Err(WarningType::DecimalRepresentation);
399 } else if digits.len() < 4 {
400 // Lint for Literals with a hex-representation of 2 or 3 digits
401 let f = &digits[0..1]; // first digit
402 let s = &digits[1..]; // suffix
405 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
406 // Powers of 2 minus 1
407 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
409 return Err(WarningType::DecimalRepresentation);
412 // Lint for Literals with a hex-representation of 4 digits or more
413 let f = &digits[0..1]; // first digit
414 let m = &digits[1..digits.len() - 1]; // middle digits, except last
415 let s = &digits[1..]; // suffix
417 // Powers of 2 with a margin of +15/-16
418 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
419 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
420 // Lint for representations with only 0s and Fs, while allowing 7 as the first
422 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
424 return Err(WarningType::DecimalRepresentation);