]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/literal_representation.rs
Use `summary_opts()` in another spot
[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 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_lint_pass, 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 integer 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 declare_lint_pass!(LiteralDigitGrouping => [
212     UNREADABLE_LITERAL,
213     INCONSISTENT_DIGIT_GROUPING,
214     LARGE_DIGIT_GROUPS,
215     MISTYPED_LITERAL_SUFFIXES,
216     UNUSUAL_BYTE_GROUPINGS,
217 ]);
218
219 impl EarlyLintPass for LiteralDigitGrouping {
220     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
221         if in_external_macro(cx.sess(), expr.span) {
222             return;
223         }
224
225         if let ExprKind::Lit(ref lit) = expr.kind {
226             Self::check_lit(cx, lit)
227         }
228     }
229 }
230
231 // Length of each UUID hyphenated group in hex digits.
232 const UUID_GROUP_LENS: [usize; 5] = [8, 4, 4, 4, 12];
233
234 impl LiteralDigitGrouping {
235     fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
236         if_chain! {
237             if let Some(src) = snippet_opt(cx, lit.span);
238             if let Some(mut num_lit) = NumericLiteral::from_lit(&src, &lit);
239             then {
240                 if !Self::check_for_mistyped_suffix(cx, lit.span, &mut num_lit) {
241                     return;
242                 }
243
244                 if Self::is_literal_uuid_formatted(&mut num_lit) {
245                     return;
246                 }
247
248                 let result = (|| {
249
250                     let integral_group_size = Self::get_group_size(num_lit.integer.split('_'), num_lit.radix)?;
251                     if let Some(fraction) = num_lit.fraction {
252                         let fractional_group_size = Self::get_group_size(fraction.rsplit('_'), num_lit.radix)?;
253
254                         let consistent = Self::parts_consistent(integral_group_size,
255                                                                 fractional_group_size,
256                                                                 num_lit.integer.len(),
257                                                                 fraction.len());
258                         if !consistent {
259                             return Err(WarningType::InconsistentDigitGrouping);
260                         };
261                     }
262
263                     Ok(())
264                 })();
265
266
267                 if let Err(warning_type) = result {
268                     let should_warn = match warning_type {
269                         | WarningType::UnreadableLiteral
270                         | WarningType::InconsistentDigitGrouping
271                         | WarningType::UnusualByteGroupings
272                         | WarningType::LargeDigitGroups => {
273                             !in_macro(lit.span)
274                         }
275                         WarningType::DecimalRepresentation | WarningType::MistypedLiteralSuffix => {
276                             true
277                         }
278                     };
279                     if should_warn {
280                         warning_type.display(num_lit.format(), cx, lit.span)
281                     }
282                 }
283             }
284         }
285     }
286
287     // Returns `false` if the check fails
288     fn check_for_mistyped_suffix(
289         cx: &EarlyContext<'_>,
290         span: rustc_span::Span,
291         num_lit: &mut NumericLiteral<'_>,
292     ) -> bool {
293         if num_lit.suffix.is_some() {
294             return true;
295         }
296
297         let (part, mistyped_suffixes, missing_char) = if let Some((_, exponent)) = &mut num_lit.exponent {
298             (exponent, &["32", "64"][..], 'f')
299         } else if num_lit.fraction.is_some() {
300             (&mut num_lit.integer, &["32", "64"][..], 'f')
301         } else {
302             (&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i')
303         };
304
305         let mut split = part.rsplit('_');
306         let last_group = split.next().expect("At least one group");
307         if split.next().is_some() && mistyped_suffixes.contains(&last_group) {
308             *part = &part[..part.len() - last_group.len()];
309             let mut sugg = num_lit.format();
310             sugg.push('_');
311             sugg.push(missing_char);
312             sugg.push_str(last_group);
313             WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
314             false
315         } else {
316             true
317         }
318     }
319
320     /// Checks whether the numeric literal matches the formatting of a UUID.
321     ///
322     /// Returns `true` if the radix is hexadecimal, and the groups match the
323     /// UUID format of 8-4-4-4-12.
324     fn is_literal_uuid_formatted(num_lit: &mut NumericLiteral<'_>) -> bool {
325         if num_lit.radix != Radix::Hexadecimal {
326             return false;
327         }
328
329         // UUIDs should not have a fraction
330         if num_lit.fraction.is_some() {
331             return false;
332         }
333
334         let group_sizes: Vec<usize> = num_lit.integer.split('_').map(str::len).collect();
335         if UUID_GROUP_LENS.len() == group_sizes.len() {
336             UUID_GROUP_LENS.iter().zip(&group_sizes).all(|(&a, &b)| a == b)
337         } else {
338             false
339         }
340     }
341
342     /// Given the sizes of the digit groups of both integral and fractional
343     /// parts, and the length
344     /// of both parts, determine if the digits have been grouped consistently.
345     #[must_use]
346     fn parts_consistent(
347         int_group_size: Option<usize>,
348         frac_group_size: Option<usize>,
349         int_size: usize,
350         frac_size: usize,
351     ) -> bool {
352         match (int_group_size, frac_group_size) {
353             // No groups on either side of decimal point - trivially consistent.
354             (None, None) => true,
355             // Integral part has grouped digits, fractional part does not.
356             (Some(int_group_size), None) => frac_size <= int_group_size,
357             // Fractional part has grouped digits, integral part does not.
358             (None, Some(frac_group_size)) => int_size <= frac_group_size,
359             // Both parts have grouped digits. Groups should be the same size.
360             (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
361         }
362     }
363
364     /// Returns the size of the digit groups (or None if ungrouped) if successful,
365     /// otherwise returns a `WarningType` for linting.
366     fn get_group_size<'a>(groups: impl Iterator<Item = &'a str>, radix: Radix) -> Result<Option<usize>, WarningType> {
367         let mut groups = groups.map(str::len);
368
369         let first = groups.next().expect("At least one group");
370
371         if (radix == Radix::Binary || radix == Radix::Hexadecimal) && groups.any(|i| i != 4 && i != 2) {
372             return Err(WarningType::UnusualByteGroupings);
373         }
374
375         if let Some(second) = groups.next() {
376             if !groups.all(|x| x == second) || first > second {
377                 Err(WarningType::InconsistentDigitGrouping)
378             } else if second > 4 {
379                 Err(WarningType::LargeDigitGroups)
380             } else {
381                 Ok(Some(second))
382             }
383         } else if first > 5 {
384             Err(WarningType::UnreadableLiteral)
385         } else {
386             Ok(None)
387         }
388     }
389 }
390
391 #[allow(clippy::module_name_repetitions)]
392 #[derive(Copy, Clone)]
393 pub struct DecimalLiteralRepresentation {
394     threshold: u64,
395 }
396
397 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
398
399 impl EarlyLintPass for DecimalLiteralRepresentation {
400     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
401         if in_external_macro(cx.sess(), expr.span) {
402             return;
403         }
404
405         if let ExprKind::Lit(ref lit) = expr.kind {
406             self.check_lit(cx, lit)
407         }
408     }
409 }
410
411 impl DecimalLiteralRepresentation {
412     #[must_use]
413     pub fn new(threshold: u64) -> Self {
414         Self { threshold }
415     }
416     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
417         // Lint integral literals.
418         if_chain! {
419             if let LitKind::Int(val, _) = lit.kind;
420             if let Some(src) = snippet_opt(cx, lit.span);
421             if let Some(num_lit) = NumericLiteral::from_lit(&src, &lit);
422             if num_lit.radix == Radix::Decimal;
423             if val >= u128::from(self.threshold);
424             then {
425                 let hex = format!("{:#X}", val);
426                 let num_lit = NumericLiteral::new(&hex, num_lit.suffix, false);
427                 let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
428                     warning_type.display(num_lit.format(), cx, lit.span)
429                 });
430             }
431         }
432     }
433
434     fn do_lint(digits: &str) -> Result<(), WarningType> {
435         if digits.len() == 1 {
436             // Lint for 1 digit literals, if someone really sets the threshold that low
437             if digits == "1"
438                 || digits == "2"
439                 || digits == "4"
440                 || digits == "8"
441                 || digits == "3"
442                 || digits == "7"
443                 || digits == "F"
444             {
445                 return Err(WarningType::DecimalRepresentation);
446             }
447         } else if digits.len() < 4 {
448             // Lint for Literals with a hex-representation of 2 or 3 digits
449             let f = &digits[0..1]; // first digit
450             let s = &digits[1..]; // suffix
451
452             // Powers of 2
453             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
454                 // Powers of 2 minus 1
455                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
456             {
457                 return Err(WarningType::DecimalRepresentation);
458             }
459         } else {
460             // Lint for Literals with a hex-representation of 4 digits or more
461             let f = &digits[0..1]; // first digit
462             let m = &digits[1..digits.len() - 1]; // middle digits, except last
463             let s = &digits[1..]; // suffix
464
465             // Powers of 2 with a margin of +15/-16
466             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
467                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
468                 // Lint for representations with only 0s and Fs, while allowing 7 as the first
469                 // digit
470                 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
471             {
472                 return Err(WarningType::DecimalRepresentation);
473             }
474         }
475
476         Ok(())
477     }
478 }