]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/literal_representation.rs
Allow UUID style formatting for `inconsistent_digit_grouping` lint
[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_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     /// let x: u64 = 61864918973511;
28     /// ```
29     pub UNREADABLE_LITERAL,
30     pedantic,
31     "long integer literal without underscores"
32 }
33
34 declare_clippy_lint! {
35     /// **What it does:** Warns for mistyped suffix in literals
36     ///
37     /// **Why is this bad?** This is most probably a typo
38     ///
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
43     ///
44     /// **Example:**
45     ///
46     /// ```rust
47     /// 2_32;
48     /// ```
49     pub MISTYPED_LITERAL_SUFFIXES,
50     correctness,
51     "mistyped literal suffix"
52 }
53
54 declare_clippy_lint! {
55     /// **What it does:** Warns if an integral or floating-point constant is
56     /// grouped inconsistently with underscores.
57     ///
58     /// **Why is this bad?** Readers may incorrectly interpret inconsistently
59     /// grouped digits.
60     ///
61     /// **Known problems:** None.
62     ///
63     /// **Example:**
64     ///
65     /// ```rust
66     /// let x: u64 = 618_64_9189_73_511;
67     /// ```
68     pub INCONSISTENT_DIGIT_GROUPING,
69     style,
70     "integer literals with digits grouped inconsistently"
71 }
72
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
76     /// are too large.
77     ///
78     /// **Why is this bad?** Negatively impacts readability.
79     ///
80     /// **Known problems:** None.
81     ///
82     /// **Example:**
83     ///
84     /// ```rust
85     /// let x: u64 = 6186491_8973511;
86     /// ```
87     pub LARGE_DIGIT_GROUPS,
88     pedantic,
89     "grouping digits into groups that are too large"
90 }
91
92 declare_clippy_lint! {
93     /// **What it does:** Warns if there is a better representation for a numeric literal.
94     ///
95     /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
96     /// readable than a decimal representation.
97     ///
98     /// **Known problems:** None.
99     ///
100     /// **Example:**
101     ///
102     /// `255` => `0xFF`
103     /// `65_535` => `0xFFFF`
104     /// `4_042_322_160` => `0xF0F0_F0F0`
105     pub DECIMAL_LITERAL_REPRESENTATION,
106     restriction,
107     "using decimal representation when hexadecimal would be better"
108 }
109
110 enum WarningType {
111     UnreadableLiteral,
112     InconsistentDigitGrouping,
113     LargeDigitGroups,
114     DecimalRepresentation,
115     MistypedLiteralSuffix,
116 }
117
118 impl WarningType {
119     fn display(&self, suggested_format: String, cx: &EarlyContext<'_>, span: rustc_span::Span) {
120         match self {
121             Self::MistypedLiteralSuffix => span_lint_and_sugg(
122                 cx,
123                 MISTYPED_LITERAL_SUFFIXES,
124                 span,
125                 "mistyped literal suffix",
126                 "did you mean to write",
127                 suggested_format,
128                 Applicability::MaybeIncorrect,
129             ),
130             Self::UnreadableLiteral => span_lint_and_sugg(
131                 cx,
132                 UNREADABLE_LITERAL,
133                 span,
134                 "long literal lacking separators",
135                 "consider",
136                 suggested_format,
137                 Applicability::MachineApplicable,
138             ),
139             Self::LargeDigitGroups => span_lint_and_sugg(
140                 cx,
141                 LARGE_DIGIT_GROUPS,
142                 span,
143                 "digit groups should be smaller",
144                 "consider",
145                 suggested_format,
146                 Applicability::MachineApplicable,
147             ),
148             Self::InconsistentDigitGrouping => span_lint_and_sugg(
149                 cx,
150                 INCONSISTENT_DIGIT_GROUPING,
151                 span,
152                 "digits grouped inconsistently by underscores",
153                 "consider",
154                 suggested_format,
155                 Applicability::MachineApplicable,
156             ),
157             Self::DecimalRepresentation => span_lint_and_sugg(
158                 cx,
159                 DECIMAL_LITERAL_REPRESENTATION,
160                 span,
161                 "integer literal has a better hexadecimal representation",
162                 "consider",
163                 suggested_format,
164                 Applicability::MachineApplicable,
165             ),
166         };
167     }
168 }
169
170 declare_lint_pass!(LiteralDigitGrouping => [
171     UNREADABLE_LITERAL,
172     INCONSISTENT_DIGIT_GROUPING,
173     LARGE_DIGIT_GROUPS,
174     MISTYPED_LITERAL_SUFFIXES,
175 ]);
176
177 impl EarlyLintPass for LiteralDigitGrouping {
178     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
179         if in_external_macro(cx.sess(), expr.span) {
180             return;
181         }
182
183         if let ExprKind::Lit(ref lit) = expr.kind {
184             Self::check_lit(cx, lit)
185         }
186     }
187 }
188
189 // Length of each UUID hyphenated group in hex digits.
190 const UUID_GROUP_LENS: [usize; 5] = [8, 4, 4, 4, 12];
191
192 impl LiteralDigitGrouping {
193     fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
194         if_chain! {
195             if let Some(src) = snippet_opt(cx, lit.span);
196             if let Some(mut num_lit) = NumericLiteral::from_lit(&src, &lit);
197             then {
198                 if !Self::check_for_mistyped_suffix(cx, lit.span, &mut num_lit) {
199                     return;
200                 }
201
202                 if Self::is_literal_uuid_formatted(&mut num_lit) {
203                     return;
204                 }
205
206                 let result = (|| {
207
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('_'))?;
211
212                         let consistent = Self::parts_consistent(integral_group_size,
213                                                                 fractional_group_size,
214                                                                 num_lit.integer.len(),
215                                                                 fraction.len());
216                         if !consistent {
217                             return Err(WarningType::InconsistentDigitGrouping);
218                         };
219                     }
220                     Ok(())
221                 })();
222
223
224                 if let Err(warning_type) = result {
225                     let should_warn = match warning_type {
226                         | WarningType::UnreadableLiteral
227                         | WarningType::InconsistentDigitGrouping
228                         | WarningType::LargeDigitGroups => {
229                             !in_macro(lit.span)
230                         }
231                         WarningType::DecimalRepresentation | WarningType::MistypedLiteralSuffix => {
232                             true
233                         }
234                     };
235                     if should_warn {
236                         warning_type.display(num_lit.format(), cx, lit.span)
237                     }
238                 }
239             }
240         }
241     }
242
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<'_>,
248     ) -> bool {
249         if num_lit.suffix.is_some() {
250             return true;
251         }
252
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')
257         } else {
258             (&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i')
259         };
260
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();
266             sugg.push('_');
267             sugg.push(missing_char);
268             sugg.push_str(last_group);
269             WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
270             false
271         } else {
272             true
273         }
274     }
275
276     /// Checks whether the numeric literal matches the formatting of a UUID.
277     ///
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 {
282             return false;
283         }
284
285         // UUIDs should not have a fraction
286         if num_lit.fraction.is_some() {
287             return false;
288         }
289
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)
293         } else {
294             false
295         }
296     }
297
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.
301     #[must_use]
302     fn parts_consistent(
303         int_group_size: Option<usize>,
304         frac_group_size: Option<usize>,
305         int_size: usize,
306         frac_size: usize,
307     ) -> bool {
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,
317         }
318     }
319
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);
324
325         let first = groups.next().expect("At least one group");
326
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)
332             } else {
333                 Ok(Some(second))
334             }
335         } else if first > 5 {
336             Err(WarningType::UnreadableLiteral)
337         } else {
338             Ok(None)
339         }
340     }
341 }
342
343 #[allow(clippy::module_name_repetitions)]
344 #[derive(Copy, Clone)]
345 pub struct DecimalLiteralRepresentation {
346     threshold: u64,
347 }
348
349 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
350
351 impl EarlyLintPass for DecimalLiteralRepresentation {
352     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
353         if in_external_macro(cx.sess(), expr.span) {
354             return;
355         }
356
357         if let ExprKind::Lit(ref lit) = expr.kind {
358             self.check_lit(cx, lit)
359         }
360     }
361 }
362
363 impl DecimalLiteralRepresentation {
364     #[must_use]
365     pub fn new(threshold: u64) -> Self {
366         Self { threshold }
367     }
368     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
369         // Lint integral literals.
370         if_chain! {
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);
376             then {
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)
381                 });
382             }
383         }
384     }
385
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
389             if digits == "1"
390                 || digits == "2"
391                 || digits == "4"
392                 || digits == "8"
393                 || digits == "3"
394                 || digits == "7"
395                 || digits == "F"
396             {
397                 return Err(WarningType::DecimalRepresentation);
398             }
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
403
404             // Powers of 2
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'))
408             {
409                 return Err(WarningType::DecimalRepresentation);
410             }
411         } else {
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
416
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
421                 // digit
422                 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
423             {
424                 return Err(WarningType::DecimalRepresentation);
425             }
426         }
427
428         Ok(())
429     }
430 }