]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/literal_representation.rs
Auto merge of #73490 - CAD97:range-unchecked-stepping, r=Amanieu
[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 the digits of an integral or floating-point
87     /// constant are grouped into groups that
88     /// are too large.
89     ///
90     /// **Why is this bad?** Negatively impacts readability.
91     ///
92     /// **Known problems:** None.
93     ///
94     /// **Example:**
95     ///
96     /// ```rust
97     /// let x: u64 = 6186491_8973511;
98     /// ```
99     pub LARGE_DIGIT_GROUPS,
100     pedantic,
101     "grouping digits into groups that are too large"
102 }
103
104 declare_clippy_lint! {
105     /// **What it does:** Warns if there is a better representation for a numeric literal.
106     ///
107     /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
108     /// readable than a decimal representation.
109     ///
110     /// **Known problems:** None.
111     ///
112     /// **Example:**
113     ///
114     /// `255` => `0xFF`
115     /// `65_535` => `0xFFFF`
116     /// `4_042_322_160` => `0xF0F0_F0F0`
117     pub DECIMAL_LITERAL_REPRESENTATION,
118     restriction,
119     "using decimal representation when hexadecimal would be better"
120 }
121
122 enum WarningType {
123     UnreadableLiteral,
124     InconsistentDigitGrouping,
125     LargeDigitGroups,
126     DecimalRepresentation,
127     MistypedLiteralSuffix,
128 }
129
130 impl WarningType {
131     fn display(&self, suggested_format: String, cx: &EarlyContext<'_>, span: rustc_span::Span) {
132         match self {
133             Self::MistypedLiteralSuffix => span_lint_and_sugg(
134                 cx,
135                 MISTYPED_LITERAL_SUFFIXES,
136                 span,
137                 "mistyped literal suffix",
138                 "did you mean to write",
139                 suggested_format,
140                 Applicability::MaybeIncorrect,
141             ),
142             Self::UnreadableLiteral => span_lint_and_sugg(
143                 cx,
144                 UNREADABLE_LITERAL,
145                 span,
146                 "long literal lacking separators",
147                 "consider",
148                 suggested_format,
149                 Applicability::MachineApplicable,
150             ),
151             Self::LargeDigitGroups => span_lint_and_sugg(
152                 cx,
153                 LARGE_DIGIT_GROUPS,
154                 span,
155                 "digit groups should be smaller",
156                 "consider",
157                 suggested_format,
158                 Applicability::MachineApplicable,
159             ),
160             Self::InconsistentDigitGrouping => span_lint_and_sugg(
161                 cx,
162                 INCONSISTENT_DIGIT_GROUPING,
163                 span,
164                 "digits grouped inconsistently by underscores",
165                 "consider",
166                 suggested_format,
167                 Applicability::MachineApplicable,
168             ),
169             Self::DecimalRepresentation => span_lint_and_sugg(
170                 cx,
171                 DECIMAL_LITERAL_REPRESENTATION,
172                 span,
173                 "integer literal has a better hexadecimal representation",
174                 "consider",
175                 suggested_format,
176                 Applicability::MachineApplicable,
177             ),
178         };
179     }
180 }
181
182 declare_lint_pass!(LiteralDigitGrouping => [
183     UNREADABLE_LITERAL,
184     INCONSISTENT_DIGIT_GROUPING,
185     LARGE_DIGIT_GROUPS,
186     MISTYPED_LITERAL_SUFFIXES,
187 ]);
188
189 impl EarlyLintPass for LiteralDigitGrouping {
190     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
191         if in_external_macro(cx.sess(), expr.span) {
192             return;
193         }
194
195         if let ExprKind::Lit(ref lit) = expr.kind {
196             Self::check_lit(cx, lit)
197         }
198     }
199 }
200
201 // Length of each UUID hyphenated group in hex digits.
202 const UUID_GROUP_LENS: [usize; 5] = [8, 4, 4, 4, 12];
203
204 impl LiteralDigitGrouping {
205     fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
206         if_chain! {
207             if let Some(src) = snippet_opt(cx, lit.span);
208             if let Some(mut num_lit) = NumericLiteral::from_lit(&src, &lit);
209             then {
210                 if !Self::check_for_mistyped_suffix(cx, lit.span, &mut num_lit) {
211                     return;
212                 }
213
214                 if Self::is_literal_uuid_formatted(&mut num_lit) {
215                     return;
216                 }
217
218                 let result = (|| {
219
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('_'))?;
223
224                         let consistent = Self::parts_consistent(integral_group_size,
225                                                                 fractional_group_size,
226                                                                 num_lit.integer.len(),
227                                                                 fraction.len());
228                         if !consistent {
229                             return Err(WarningType::InconsistentDigitGrouping);
230                         };
231                     }
232                     Ok(())
233                 })();
234
235
236                 if let Err(warning_type) = result {
237                     let should_warn = match warning_type {
238                         | WarningType::UnreadableLiteral
239                         | WarningType::InconsistentDigitGrouping
240                         | WarningType::LargeDigitGroups => {
241                             !in_macro(lit.span)
242                         }
243                         WarningType::DecimalRepresentation | WarningType::MistypedLiteralSuffix => {
244                             true
245                         }
246                     };
247                     if should_warn {
248                         warning_type.display(num_lit.format(), cx, lit.span)
249                     }
250                 }
251             }
252         }
253     }
254
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<'_>,
260     ) -> bool {
261         if num_lit.suffix.is_some() {
262             return true;
263         }
264
265         let (part, mistyped_suffixes, missing_char) = if let Some((_, exponent)) = &mut num_lit.exponent {
266             (exponent, &["32", "64"][..], 'f')
267         } else if let Some(fraction) = &mut num_lit.fraction {
268             (fraction, &["32", "64"][..], 'f')
269         } else {
270             (&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i')
271         };
272
273         let mut split = part.rsplit('_');
274         let last_group = split.next().expect("At least one group");
275         if split.next().is_some() && mistyped_suffixes.contains(&last_group) {
276             *part = &part[..part.len() - last_group.len()];
277             let mut sugg = num_lit.format();
278             sugg.push('_');
279             sugg.push(missing_char);
280             sugg.push_str(last_group);
281             WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
282             false
283         } else {
284             true
285         }
286     }
287
288     /// Checks whether the numeric literal matches the formatting of a UUID.
289     ///
290     /// Returns `true` if the radix is hexadecimal, and the groups match the
291     /// UUID format of 8-4-4-4-12.
292     fn is_literal_uuid_formatted(num_lit: &mut NumericLiteral<'_>) -> bool {
293         if num_lit.radix != Radix::Hexadecimal {
294             return false;
295         }
296
297         // UUIDs should not have a fraction
298         if num_lit.fraction.is_some() {
299             return false;
300         }
301
302         let group_sizes: Vec<usize> = num_lit.integer.split('_').map(str::len).collect();
303         if UUID_GROUP_LENS.len() == group_sizes.len() {
304             UUID_GROUP_LENS.iter().zip(&group_sizes).all(|(&a, &b)| a == b)
305         } else {
306             false
307         }
308     }
309
310     /// Given the sizes of the digit groups of both integral and fractional
311     /// parts, and the length
312     /// of both parts, determine if the digits have been grouped consistently.
313     #[must_use]
314     fn parts_consistent(
315         int_group_size: Option<usize>,
316         frac_group_size: Option<usize>,
317         int_size: usize,
318         frac_size: usize,
319     ) -> bool {
320         match (int_group_size, frac_group_size) {
321             // No groups on either side of decimal point - trivially consistent.
322             (None, None) => true,
323             // Integral part has grouped digits, fractional part does not.
324             (Some(int_group_size), None) => frac_size <= int_group_size,
325             // Fractional part has grouped digits, integral part does not.
326             (None, Some(frac_group_size)) => int_size <= frac_group_size,
327             // Both parts have grouped digits. Groups should be the same size.
328             (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
329         }
330     }
331
332     /// Returns the size of the digit groups (or None if ungrouped) if successful,
333     /// otherwise returns a `WarningType` for linting.
334     fn get_group_size<'a>(groups: impl Iterator<Item = &'a str>) -> Result<Option<usize>, WarningType> {
335         let mut groups = groups.map(str::len);
336
337         let first = groups.next().expect("At least one group");
338
339         if let Some(second) = groups.next() {
340             if !groups.all(|x| x == second) || first > second {
341                 Err(WarningType::InconsistentDigitGrouping)
342             } else if second > 4 {
343                 Err(WarningType::LargeDigitGroups)
344             } else {
345                 Ok(Some(second))
346             }
347         } else if first > 5 {
348             Err(WarningType::UnreadableLiteral)
349         } else {
350             Ok(None)
351         }
352     }
353 }
354
355 #[allow(clippy::module_name_repetitions)]
356 #[derive(Copy, Clone)]
357 pub struct DecimalLiteralRepresentation {
358     threshold: u64,
359 }
360
361 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
362
363 impl EarlyLintPass for DecimalLiteralRepresentation {
364     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
365         if in_external_macro(cx.sess(), expr.span) {
366             return;
367         }
368
369         if let ExprKind::Lit(ref lit) = expr.kind {
370             self.check_lit(cx, lit)
371         }
372     }
373 }
374
375 impl DecimalLiteralRepresentation {
376     #[must_use]
377     pub fn new(threshold: u64) -> Self {
378         Self { threshold }
379     }
380     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
381         // Lint integral literals.
382         if_chain! {
383             if let LitKind::Int(val, _) = lit.kind;
384             if let Some(src) = snippet_opt(cx, lit.span);
385             if let Some(num_lit) = NumericLiteral::from_lit(&src, &lit);
386             if num_lit.radix == Radix::Decimal;
387             if val >= u128::from(self.threshold);
388             then {
389                 let hex = format!("{:#X}", val);
390                 let num_lit = NumericLiteral::new(&hex, num_lit.suffix, false);
391                 let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
392                     warning_type.display(num_lit.format(), cx, lit.span)
393                 });
394             }
395         }
396     }
397
398     fn do_lint(digits: &str) -> Result<(), WarningType> {
399         if digits.len() == 1 {
400             // Lint for 1 digit literals, if someone really sets the threshold that low
401             if digits == "1"
402                 || digits == "2"
403                 || digits == "4"
404                 || digits == "8"
405                 || digits == "3"
406                 || digits == "7"
407                 || digits == "F"
408             {
409                 return Err(WarningType::DecimalRepresentation);
410             }
411         } else if digits.len() < 4 {
412             // Lint for Literals with a hex-representation of 2 or 3 digits
413             let f = &digits[0..1]; // first digit
414             let s = &digits[1..]; // suffix
415
416             // Powers of 2
417             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
418                 // Powers of 2 minus 1
419                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
420             {
421                 return Err(WarningType::DecimalRepresentation);
422             }
423         } else {
424             // Lint for Literals with a hex-representation of 4 digits or more
425             let f = &digits[0..1]; // first digit
426             let m = &digits[1..digits.len() - 1]; // middle digits, except last
427             let s = &digits[1..]; // suffix
428
429             // Powers of 2 with a margin of +15/-16
430             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
431                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
432                 // Lint for representations with only 0s and Fs, while allowing 7 as the first
433                 // digit
434                 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
435             {
436                 return Err(WarningType::DecimalRepresentation);
437             }
438         }
439
440         Ok(())
441     }
442 }