]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/literal_representation.rs
Merge commit '4911ab124c481430672a3833b37075e6435ec34d' into clippyup
[rust.git] / 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 crate::utils::{
5     in_macro,
6     numeric_literal::{NumericLiteral, Radix},
7     snippet_opt, span_lint_and_sugg,
8 };
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};
15
16 declare_clippy_lint! {
17     /// **What it does:** Warns if a long integral or floating-point constant does
18     /// not contain underscores.
19     ///
20     /// **Why is this bad?** Reading long numbers is difficult without separators.
21     ///
22     /// **Known problems:** None.
23     ///
24     /// **Example:**
25     ///
26     /// ```rust
27     /// // Bad
28     /// let x: u64 = 61864918973511;
29     ///
30     /// // Good
31     /// let x: u64 = 61_864_918_973_511;
32     /// ```
33     pub UNREADABLE_LITERAL,
34     pedantic,
35     "long literal without underscores"
36 }
37
38 declare_clippy_lint! {
39     /// **What it does:** Warns for mistyped suffix in literals
40     ///
41     /// **Why is this bad?** This is most probably a typo
42     ///
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
47     ///
48     /// **Example:**
49     ///
50     /// ```rust
51     /// // Probably mistyped
52     /// 2_32;
53     ///
54     /// // Good
55     /// 2_i32;
56     /// ```
57     pub MISTYPED_LITERAL_SUFFIXES,
58     correctness,
59     "mistyped literal suffix"
60 }
61
62 declare_clippy_lint! {
63     /// **What it does:** Warns if an integral or floating-point constant is
64     /// grouped inconsistently with underscores.
65     ///
66     /// **Why is this bad?** Readers may incorrectly interpret inconsistently
67     /// grouped digits.
68     ///
69     /// **Known problems:** None.
70     ///
71     /// **Example:**
72     ///
73     /// ```rust
74     /// // Bad
75     /// let x: u64 = 618_64_9189_73_511;
76     ///
77     /// // Good
78     /// let x: u64 = 61_864_918_973_511;
79     /// ```
80     pub INCONSISTENT_DIGIT_GROUPING,
81     style,
82     "integer literals with digits grouped inconsistently"
83 }
84
85 declare_clippy_lint! {
86     /// **What it does:** Warns if hexadecimal or binary literals are not grouped
87     /// by nibble or byte.
88     ///
89     /// **Why is this bad?** Negatively impacts readability.
90     ///
91     /// **Known problems:** None.
92     ///
93     /// **Example:**
94     ///
95     /// ```rust
96     /// let x: u32 = 0xFFF_FFF;
97     /// let y: u8 = 0b01_011_101;
98     /// ```
99     pub UNUSUAL_BYTE_GROUPINGS,
100     style,
101     "binary or hex literals that aren't grouped by four"
102 }
103
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
107     /// are too large.
108     ///
109     /// **Why is this bad?** Negatively impacts readability.
110     ///
111     /// **Known problems:** None.
112     ///
113     /// **Example:**
114     ///
115     /// ```rust
116     /// let x: u64 = 6186491_8973511;
117     /// ```
118     pub LARGE_DIGIT_GROUPS,
119     pedantic,
120     "grouping digits into groups that are too large"
121 }
122
123 declare_clippy_lint! {
124     /// **What it does:** Warns if there is a better representation for a numeric literal.
125     ///
126     /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
127     /// readable than a decimal representation.
128     ///
129     /// **Known problems:** None.
130     ///
131     /// **Example:**
132     ///
133     /// `255` => `0xFF`
134     /// `65_535` => `0xFFFF`
135     /// `4_042_322_160` => `0xF0F0_F0F0`
136     pub DECIMAL_LITERAL_REPRESENTATION,
137     restriction,
138     "using decimal representation when hexadecimal would be better"
139 }
140
141 enum WarningType {
142     UnreadableLiteral,
143     InconsistentDigitGrouping,
144     LargeDigitGroups,
145     DecimalRepresentation,
146     MistypedLiteralSuffix,
147     UnusualByteGroupings,
148 }
149
150 impl WarningType {
151     fn display(&self, suggested_format: String, cx: &EarlyContext<'_>, span: rustc_span::Span) {
152         match self {
153             Self::MistypedLiteralSuffix => span_lint_and_sugg(
154                 cx,
155                 MISTYPED_LITERAL_SUFFIXES,
156                 span,
157                 "mistyped literal suffix",
158                 "did you mean to write",
159                 suggested_format,
160                 Applicability::MaybeIncorrect,
161             ),
162             Self::UnreadableLiteral => span_lint_and_sugg(
163                 cx,
164                 UNREADABLE_LITERAL,
165                 span,
166                 "long literal lacking separators",
167                 "consider",
168                 suggested_format,
169                 Applicability::MachineApplicable,
170             ),
171             Self::LargeDigitGroups => span_lint_and_sugg(
172                 cx,
173                 LARGE_DIGIT_GROUPS,
174                 span,
175                 "digit groups should be smaller",
176                 "consider",
177                 suggested_format,
178                 Applicability::MachineApplicable,
179             ),
180             Self::InconsistentDigitGrouping => span_lint_and_sugg(
181                 cx,
182                 INCONSISTENT_DIGIT_GROUPING,
183                 span,
184                 "digits grouped inconsistently by underscores",
185                 "consider",
186                 suggested_format,
187                 Applicability::MachineApplicable,
188             ),
189             Self::DecimalRepresentation => span_lint_and_sugg(
190                 cx,
191                 DECIMAL_LITERAL_REPRESENTATION,
192                 span,
193                 "integer literal has a better hexadecimal representation",
194                 "consider",
195                 suggested_format,
196                 Applicability::MachineApplicable,
197             ),
198             Self::UnusualByteGroupings => span_lint_and_sugg(
199                 cx,
200                 UNUSUAL_BYTE_GROUPINGS,
201                 span,
202                 "digits of hex or binary literal not grouped by four",
203                 "consider",
204                 suggested_format,
205                 Applicability::MachineApplicable,
206             ),
207         };
208     }
209 }
210
211 #[allow(clippy::module_name_repetitions)]
212 #[derive(Copy, Clone)]
213 pub struct LiteralDigitGrouping {
214     lint_fraction_readability: bool,
215 }
216
217 impl_lint_pass!(LiteralDigitGrouping => [
218     UNREADABLE_LITERAL,
219     INCONSISTENT_DIGIT_GROUPING,
220     LARGE_DIGIT_GROUPS,
221     MISTYPED_LITERAL_SUFFIXES,
222     UNUSUAL_BYTE_GROUPINGS,
223 ]);
224
225 impl EarlyLintPass for LiteralDigitGrouping {
226     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
227         if in_external_macro(cx.sess(), expr.span) {
228             return;
229         }
230
231         if let ExprKind::Lit(ref lit) = expr.kind {
232             self.check_lit(cx, lit)
233         }
234     }
235 }
236
237 // Length of each UUID hyphenated group in hex digits.
238 const UUID_GROUP_LENS: [usize; 5] = [8, 4, 4, 4, 12];
239
240 impl LiteralDigitGrouping {
241     pub fn new(lint_fraction_readability: bool) -> Self {
242         Self {
243             lint_fraction_readability,
244         }
245     }
246
247     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
248         if_chain! {
249             if let Some(src) = snippet_opt(cx, lit.span);
250             if let Some(mut num_lit) = NumericLiteral::from_lit(&src, &lit);
251             then {
252                 if !Self::check_for_mistyped_suffix(cx, lit.span, &mut num_lit) {
253                     return;
254                 }
255
256                 if Self::is_literal_uuid_formatted(&mut num_lit) {
257                     return;
258                 }
259
260                 let result = (|| {
261
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('_'),
266                             num_lit.radix,
267                             self.lint_fraction_readability)?;
268
269                         let consistent = Self::parts_consistent(integral_group_size,
270                                                                 fractional_group_size,
271                                                                 num_lit.integer.len(),
272                                                                 fraction.len());
273                         if !consistent {
274                             return Err(WarningType::InconsistentDigitGrouping);
275                         };
276                     }
277
278                     Ok(())
279                 })();
280
281
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 => {
288                             !in_macro(lit.span)
289                         }
290                         WarningType::DecimalRepresentation | WarningType::MistypedLiteralSuffix => {
291                             true
292                         }
293                     };
294                     if should_warn {
295                         warning_type.display(num_lit.format(), cx, lit.span)
296                     }
297                 }
298             }
299         }
300     }
301
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<'_>,
307     ) -> bool {
308         if num_lit.suffix.is_some() {
309             return true;
310         }
311
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')
316         } else {
317             (&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i')
318         };
319
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();
325             sugg.push('_');
326             sugg.push(missing_char);
327             sugg.push_str(last_group);
328             WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
329             false
330         } else {
331             true
332         }
333     }
334
335     /// Checks whether the numeric literal matches the formatting of a UUID.
336     ///
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 {
341             return false;
342         }
343
344         // UUIDs should not have a fraction
345         if num_lit.fraction.is_some() {
346             return false;
347         }
348
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)
352         } else {
353             false
354         }
355     }
356
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.
360     #[must_use]
361     fn parts_consistent(
362         int_group_size: Option<usize>,
363         frac_group_size: Option<usize>,
364         int_size: usize,
365         frac_size: usize,
366     ) -> bool {
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,
376         }
377     }
378
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>,
383         radix: Radix,
384         lint_unreadable: bool,
385     ) -> Result<Option<usize>, WarningType> {
386         let mut groups = groups.map(str::len);
387
388         let first = groups.next().expect("At least one group");
389
390         if (radix == Radix::Binary || radix == Radix::Hexadecimal) && groups.any(|i| i != 4 && i != 2) {
391             return Err(WarningType::UnusualByteGroupings);
392         }
393
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)
399             } else {
400                 Ok(Some(second))
401             }
402         } else if first > 5 && lint_unreadable {
403             Err(WarningType::UnreadableLiteral)
404         } else {
405             Ok(None)
406         }
407     }
408 }
409
410 #[allow(clippy::module_name_repetitions)]
411 #[derive(Copy, Clone)]
412 pub struct DecimalLiteralRepresentation {
413     threshold: u64,
414 }
415
416 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
417
418 impl EarlyLintPass for DecimalLiteralRepresentation {
419     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
420         if in_external_macro(cx.sess(), expr.span) {
421             return;
422         }
423
424         if let ExprKind::Lit(ref lit) = expr.kind {
425             self.check_lit(cx, lit)
426         }
427     }
428 }
429
430 impl DecimalLiteralRepresentation {
431     #[must_use]
432     pub fn new(threshold: u64) -> Self {
433         Self { threshold }
434     }
435     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
436         // Lint integral literals.
437         if_chain! {
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);
443             then {
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)
448                 });
449             }
450         }
451     }
452
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
456             if digits == "1"
457                 || digits == "2"
458                 || digits == "4"
459                 || digits == "8"
460                 || digits == "3"
461                 || digits == "7"
462                 || digits == "F"
463             {
464                 return Err(WarningType::DecimalRepresentation);
465             }
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
470
471             // Powers of 2
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'))
475             {
476                 return Err(WarningType::DecimalRepresentation);
477             }
478         } else {
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
483
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
488                 // digit
489                 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
490             {
491                 return Err(WarningType::DecimalRepresentation);
492             }
493         }
494
495         Ok(())
496     }
497 }