]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/literal_representation.rs
Rollup merge of #83571 - a1phyr:feature_const_slice_first_last, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / literal_representation.rs
1 //! Lints concerned with the grouping of digits with underscores in integral or
2 //! floating-point literal expressions.
3
4 use clippy_utils::diagnostics::span_lint_and_sugg;
5 use clippy_utils::source::snippet_opt;
6 use clippy_utils::{
7     in_macro,
8     numeric_literal::{NumericLiteral, Radix},
9 };
10 use if_chain::if_chain;
11 use rustc_ast::ast::{Expr, ExprKind, Lit, LitKind};
12 use rustc_errors::Applicability;
13 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
14 use rustc_middle::lint::in_external_macro;
15 use rustc_session::{declare_tool_lint, impl_lint_pass};
16 use std::iter;
17
18 declare_clippy_lint! {
19     /// **What it does:** Warns if a long integral or floating-point constant does
20     /// not contain underscores.
21     ///
22     /// **Why is this bad?** Reading long numbers is difficult without separators.
23     ///
24     /// **Known problems:** None.
25     ///
26     /// **Example:**
27     ///
28     /// ```rust
29     /// // Bad
30     /// let x: u64 = 61864918973511;
31     ///
32     /// // Good
33     /// let x: u64 = 61_864_918_973_511;
34     /// ```
35     pub UNREADABLE_LITERAL,
36     pedantic,
37     "long literal without underscores"
38 }
39
40 declare_clippy_lint! {
41     /// **What it does:** Warns for mistyped suffix in literals
42     ///
43     /// **Why is this bad?** This is most probably a typo
44     ///
45     /// **Known problems:**
46     /// - Recommends a signed suffix, even though the number might be too big and an unsigned
47     ///   suffix is required
48     /// - Does not match on `_127` since that is a valid grouping for decimal and octal numbers
49     ///
50     /// **Example:**
51     ///
52     /// ```rust
53     /// // Probably mistyped
54     /// 2_32;
55     ///
56     /// // Good
57     /// 2_i32;
58     /// ```
59     pub MISTYPED_LITERAL_SUFFIXES,
60     correctness,
61     "mistyped literal suffix"
62 }
63
64 declare_clippy_lint! {
65     /// **What it does:** Warns if an integral or floating-point constant is
66     /// grouped inconsistently with underscores.
67     ///
68     /// **Why is this bad?** Readers may incorrectly interpret inconsistently
69     /// grouped digits.
70     ///
71     /// **Known problems:** None.
72     ///
73     /// **Example:**
74     ///
75     /// ```rust
76     /// // Bad
77     /// let x: u64 = 618_64_9189_73_511;
78     ///
79     /// // Good
80     /// let x: u64 = 61_864_918_973_511;
81     /// ```
82     pub INCONSISTENT_DIGIT_GROUPING,
83     style,
84     "integer literals with digits grouped inconsistently"
85 }
86
87 declare_clippy_lint! {
88     /// **What it does:** Warns if hexadecimal or binary literals are not grouped
89     /// by nibble or byte.
90     ///
91     /// **Why is this bad?** Negatively impacts readability.
92     ///
93     /// **Known problems:** None.
94     ///
95     /// **Example:**
96     ///
97     /// ```rust
98     /// let x: u32 = 0xFFF_FFF;
99     /// let y: u8 = 0b01_011_101;
100     /// ```
101     pub UNUSUAL_BYTE_GROUPINGS,
102     style,
103     "binary or hex literals that aren't grouped by four"
104 }
105
106 declare_clippy_lint! {
107     /// **What it does:** Warns if the digits of an integral or floating-point
108     /// constant are grouped into groups that
109     /// are too large.
110     ///
111     /// **Why is this bad?** Negatively impacts readability.
112     ///
113     /// **Known problems:** None.
114     ///
115     /// **Example:**
116     ///
117     /// ```rust
118     /// let x: u64 = 6186491_8973511;
119     /// ```
120     pub LARGE_DIGIT_GROUPS,
121     pedantic,
122     "grouping digits into groups that are too large"
123 }
124
125 declare_clippy_lint! {
126     /// **What it does:** Warns if there is a better representation for a numeric literal.
127     ///
128     /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
129     /// readable than a decimal representation.
130     ///
131     /// **Known problems:** None.
132     ///
133     /// **Example:**
134     ///
135     /// `255` => `0xFF`
136     /// `65_535` => `0xFFFF`
137     /// `4_042_322_160` => `0xF0F0_F0F0`
138     pub DECIMAL_LITERAL_REPRESENTATION,
139     restriction,
140     "using decimal representation when hexadecimal would be better"
141 }
142
143 enum WarningType {
144     UnreadableLiteral,
145     InconsistentDigitGrouping,
146     LargeDigitGroups,
147     DecimalRepresentation,
148     MistypedLiteralSuffix,
149     UnusualByteGroupings,
150 }
151
152 impl WarningType {
153     fn display(&self, suggested_format: String, cx: &EarlyContext<'_>, span: rustc_span::Span) {
154         match self {
155             Self::MistypedLiteralSuffix => span_lint_and_sugg(
156                 cx,
157                 MISTYPED_LITERAL_SUFFIXES,
158                 span,
159                 "mistyped literal suffix",
160                 "did you mean to write",
161                 suggested_format,
162                 Applicability::MaybeIncorrect,
163             ),
164             Self::UnreadableLiteral => span_lint_and_sugg(
165                 cx,
166                 UNREADABLE_LITERAL,
167                 span,
168                 "long literal lacking separators",
169                 "consider",
170                 suggested_format,
171                 Applicability::MachineApplicable,
172             ),
173             Self::LargeDigitGroups => span_lint_and_sugg(
174                 cx,
175                 LARGE_DIGIT_GROUPS,
176                 span,
177                 "digit groups should be smaller",
178                 "consider",
179                 suggested_format,
180                 Applicability::MachineApplicable,
181             ),
182             Self::InconsistentDigitGrouping => span_lint_and_sugg(
183                 cx,
184                 INCONSISTENT_DIGIT_GROUPING,
185                 span,
186                 "digits grouped inconsistently by underscores",
187                 "consider",
188                 suggested_format,
189                 Applicability::MachineApplicable,
190             ),
191             Self::DecimalRepresentation => span_lint_and_sugg(
192                 cx,
193                 DECIMAL_LITERAL_REPRESENTATION,
194                 span,
195                 "integer literal has a better hexadecimal representation",
196                 "consider",
197                 suggested_format,
198                 Applicability::MachineApplicable,
199             ),
200             Self::UnusualByteGroupings => span_lint_and_sugg(
201                 cx,
202                 UNUSUAL_BYTE_GROUPINGS,
203                 span,
204                 "digits of hex or binary literal not grouped by four",
205                 "consider",
206                 suggested_format,
207                 Applicability::MachineApplicable,
208             ),
209         };
210     }
211 }
212
213 #[allow(clippy::module_name_repetitions)]
214 #[derive(Copy, Clone)]
215 pub struct LiteralDigitGrouping {
216     lint_fraction_readability: bool,
217 }
218
219 impl_lint_pass!(LiteralDigitGrouping => [
220     UNREADABLE_LITERAL,
221     INCONSISTENT_DIGIT_GROUPING,
222     LARGE_DIGIT_GROUPS,
223     MISTYPED_LITERAL_SUFFIXES,
224     UNUSUAL_BYTE_GROUPINGS,
225 ]);
226
227 impl EarlyLintPass for LiteralDigitGrouping {
228     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
229         if in_external_macro(cx.sess(), expr.span) {
230             return;
231         }
232
233         if let ExprKind::Lit(ref lit) = expr.kind {
234             self.check_lit(cx, lit)
235         }
236     }
237 }
238
239 // Length of each UUID hyphenated group in hex digits.
240 const UUID_GROUP_LENS: [usize; 5] = [8, 4, 4, 4, 12];
241
242 impl LiteralDigitGrouping {
243     pub fn new(lint_fraction_readability: bool) -> Self {
244         Self {
245             lint_fraction_readability,
246         }
247     }
248
249     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
250         if_chain! {
251             if let Some(src) = snippet_opt(cx, lit.span);
252             if let Some(mut num_lit) = NumericLiteral::from_lit(&src, &lit);
253             then {
254                 if !Self::check_for_mistyped_suffix(cx, lit.span, &mut num_lit) {
255                     return;
256                 }
257
258                 if Self::is_literal_uuid_formatted(&mut num_lit) {
259                     return;
260                 }
261
262                 let result = (|| {
263
264                     let integral_group_size = Self::get_group_size(num_lit.integer.split('_'), num_lit.radix, true)?;
265                     if let Some(fraction) = num_lit.fraction {
266                         let fractional_group_size = Self::get_group_size(
267                             fraction.rsplit('_'),
268                             num_lit.radix,
269                             self.lint_fraction_readability)?;
270
271                         let consistent = Self::parts_consistent(integral_group_size,
272                                                                 fractional_group_size,
273                                                                 num_lit.integer.len(),
274                                                                 fraction.len());
275                         if !consistent {
276                             return Err(WarningType::InconsistentDigitGrouping);
277                         };
278                     }
279
280                     Ok(())
281                 })();
282
283
284                 if let Err(warning_type) = result {
285                     let should_warn = match warning_type {
286                         | WarningType::UnreadableLiteral
287                         | WarningType::InconsistentDigitGrouping
288                         | WarningType::UnusualByteGroupings
289                         | WarningType::LargeDigitGroups => {
290                             !in_macro(lit.span)
291                         }
292                         WarningType::DecimalRepresentation | WarningType::MistypedLiteralSuffix => {
293                             true
294                         }
295                     };
296                     if should_warn {
297                         warning_type.display(num_lit.format(), cx, lit.span)
298                     }
299                 }
300             }
301         }
302     }
303
304     // Returns `false` if the check fails
305     fn check_for_mistyped_suffix(
306         cx: &EarlyContext<'_>,
307         span: rustc_span::Span,
308         num_lit: &mut NumericLiteral<'_>,
309     ) -> bool {
310         if num_lit.suffix.is_some() {
311             return true;
312         }
313
314         let (part, mistyped_suffixes, missing_char) = if let Some((_, exponent)) = &mut num_lit.exponent {
315             (exponent, &["32", "64"][..], 'f')
316         } else if num_lit.fraction.is_some() {
317             (&mut num_lit.integer, &["32", "64"][..], 'f')
318         } else {
319             (&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i')
320         };
321
322         let mut split = part.rsplit('_');
323         let last_group = split.next().expect("At least one group");
324         if split.next().is_some() && mistyped_suffixes.contains(&last_group) {
325             *part = &part[..part.len() - last_group.len()];
326             let mut sugg = num_lit.format();
327             sugg.push('_');
328             sugg.push(missing_char);
329             sugg.push_str(last_group);
330             WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
331             false
332         } else {
333             true
334         }
335     }
336
337     /// Checks whether the numeric literal matches the formatting of a UUID.
338     ///
339     /// Returns `true` if the radix is hexadecimal, and the groups match the
340     /// UUID format of 8-4-4-4-12.
341     fn is_literal_uuid_formatted(num_lit: &mut NumericLiteral<'_>) -> bool {
342         if num_lit.radix != Radix::Hexadecimal {
343             return false;
344         }
345
346         // UUIDs should not have a fraction
347         if num_lit.fraction.is_some() {
348             return false;
349         }
350
351         let group_sizes: Vec<usize> = num_lit.integer.split('_').map(str::len).collect();
352         if UUID_GROUP_LENS.len() == group_sizes.len() {
353             iter::zip(&UUID_GROUP_LENS, &group_sizes).all(|(&a, &b)| a == b)
354         } else {
355             false
356         }
357     }
358
359     /// Given the sizes of the digit groups of both integral and fractional
360     /// parts, and the length
361     /// of both parts, determine if the digits have been grouped consistently.
362     #[must_use]
363     fn parts_consistent(
364         int_group_size: Option<usize>,
365         frac_group_size: Option<usize>,
366         int_size: usize,
367         frac_size: usize,
368     ) -> bool {
369         match (int_group_size, frac_group_size) {
370             // No groups on either side of decimal point - trivially consistent.
371             (None, None) => true,
372             // Integral part has grouped digits, fractional part does not.
373             (Some(int_group_size), None) => frac_size <= int_group_size,
374             // Fractional part has grouped digits, integral part does not.
375             (None, Some(frac_group_size)) => int_size <= frac_group_size,
376             // Both parts have grouped digits. Groups should be the same size.
377             (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
378         }
379     }
380
381     /// Returns the size of the digit groups (or None if ungrouped) if successful,
382     /// otherwise returns a `WarningType` for linting.
383     fn get_group_size<'a>(
384         groups: impl Iterator<Item = &'a str>,
385         radix: Radix,
386         lint_unreadable: bool,
387     ) -> Result<Option<usize>, WarningType> {
388         let mut groups = groups.map(str::len);
389
390         let first = groups.next().expect("At least one group");
391
392         if (radix == Radix::Binary || radix == Radix::Hexadecimal) && groups.any(|i| i != 4 && i != 2) {
393             return Err(WarningType::UnusualByteGroupings);
394         }
395
396         if let Some(second) = groups.next() {
397             if !groups.all(|x| x == second) || first > second {
398                 Err(WarningType::InconsistentDigitGrouping)
399             } else if second > 4 {
400                 Err(WarningType::LargeDigitGroups)
401             } else {
402                 Ok(Some(second))
403             }
404         } else if first > 5 && lint_unreadable {
405             Err(WarningType::UnreadableLiteral)
406         } else {
407             Ok(None)
408         }
409     }
410 }
411
412 #[allow(clippy::module_name_repetitions)]
413 #[derive(Copy, Clone)]
414 pub struct DecimalLiteralRepresentation {
415     threshold: u64,
416 }
417
418 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
419
420 impl EarlyLintPass for DecimalLiteralRepresentation {
421     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
422         if in_external_macro(cx.sess(), expr.span) {
423             return;
424         }
425
426         if let ExprKind::Lit(ref lit) = expr.kind {
427             self.check_lit(cx, lit)
428         }
429     }
430 }
431
432 impl DecimalLiteralRepresentation {
433     #[must_use]
434     pub fn new(threshold: u64) -> Self {
435         Self { threshold }
436     }
437     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
438         // Lint integral literals.
439         if_chain! {
440             if let LitKind::Int(val, _) = lit.kind;
441             if let Some(src) = snippet_opt(cx, lit.span);
442             if let Some(num_lit) = NumericLiteral::from_lit(&src, &lit);
443             if num_lit.radix == Radix::Decimal;
444             if val >= u128::from(self.threshold);
445             then {
446                 let hex = format!("{:#X}", val);
447                 let num_lit = NumericLiteral::new(&hex, num_lit.suffix, false);
448                 let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
449                     warning_type.display(num_lit.format(), cx, lit.span)
450                 });
451             }
452         }
453     }
454
455     fn do_lint(digits: &str) -> Result<(), WarningType> {
456         if digits.len() == 1 {
457             // Lint for 1 digit literals, if someone really sets the threshold that low
458             if digits == "1"
459                 || digits == "2"
460                 || digits == "4"
461                 || digits == "8"
462                 || digits == "3"
463                 || digits == "7"
464                 || digits == "F"
465             {
466                 return Err(WarningType::DecimalRepresentation);
467             }
468         } else if digits.len() < 4 {
469             // Lint for Literals with a hex-representation of 2 or 3 digits
470             let f = &digits[0..1]; // first digit
471             let s = &digits[1..]; // suffix
472
473             // Powers of 2
474             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
475                 // Powers of 2 minus 1
476                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
477             {
478                 return Err(WarningType::DecimalRepresentation);
479             }
480         } else {
481             // Lint for Literals with a hex-representation of 4 digits or more
482             let f = &digits[0..1]; // first digit
483             let m = &digits[1..digits.len() - 1]; // middle digits, except last
484             let s = &digits[1..]; // suffix
485
486             // Powers of 2 with a margin of +15/-16
487             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
488                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
489                 // Lint for representations with only 0s and Fs, while allowing 7 as the first
490                 // digit
491                 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
492             {
493                 return Err(WarningType::DecimalRepresentation);
494             }
495         }
496
497         Ok(())
498     }
499 }