]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/literal_representation.rs
Rollup merge of #5419 - dtolnay:unreadable, r=flip1995
[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 impl LiteralDigitGrouping {
190     fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
191         if_chain! {
192             if let Some(src) = snippet_opt(cx, lit.span);
193             if let Some(mut num_lit) = NumericLiteral::from_lit(&src, &lit);
194             then {
195                 if !Self::check_for_mistyped_suffix(cx, lit.span, &mut num_lit) {
196                     return;
197                 }
198
199                 let result = (|| {
200
201                     let integral_group_size = Self::get_group_size(num_lit.integer.split('_'))?;
202                     if let Some(fraction) = num_lit.fraction {
203                         let fractional_group_size = Self::get_group_size(fraction.rsplit('_'))?;
204
205                         let consistent = Self::parts_consistent(integral_group_size,
206                                                                 fractional_group_size,
207                                                                 num_lit.integer.len(),
208                                                                 fraction.len());
209                         if !consistent {
210                             return Err(WarningType::InconsistentDigitGrouping);
211                         };
212                     }
213                     Ok(())
214                 })();
215
216
217                 if let Err(warning_type) = result {
218                     let should_warn = match warning_type {
219                         | WarningType::UnreadableLiteral
220                         | WarningType::InconsistentDigitGrouping
221                         | WarningType::LargeDigitGroups => {
222                             !in_macro(lit.span)
223                         }
224                         WarningType::DecimalRepresentation | WarningType::MistypedLiteralSuffix => {
225                             true
226                         }
227                     };
228                     if should_warn {
229                         warning_type.display(num_lit.format(), cx, lit.span)
230                     }
231                 }
232             }
233         }
234     }
235
236     // Returns `false` if the check fails
237     fn check_for_mistyped_suffix(
238         cx: &EarlyContext<'_>,
239         span: rustc_span::Span,
240         num_lit: &mut NumericLiteral<'_>,
241     ) -> bool {
242         if num_lit.suffix.is_some() {
243             return true;
244         }
245
246         let (part, mistyped_suffixes, missing_char) = if let Some((_, exponent)) = &mut num_lit.exponent {
247             (exponent, &["32", "64"][..], 'f')
248         } else if let Some(fraction) = &mut num_lit.fraction {
249             (fraction, &["32", "64"][..], 'f')
250         } else {
251             (&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i')
252         };
253
254         let mut split = part.rsplit('_');
255         let last_group = split.next().expect("At least one group");
256         if split.next().is_some() && mistyped_suffixes.contains(&last_group) {
257             *part = &part[..part.len() - last_group.len()];
258             let mut sugg = num_lit.format();
259             sugg.push('_');
260             sugg.push(missing_char);
261             sugg.push_str(last_group);
262             WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
263             false
264         } else {
265             true
266         }
267     }
268
269     /// Given the sizes of the digit groups of both integral and fractional
270     /// parts, and the length
271     /// of both parts, determine if the digits have been grouped consistently.
272     #[must_use]
273     fn parts_consistent(
274         int_group_size: Option<usize>,
275         frac_group_size: Option<usize>,
276         int_size: usize,
277         frac_size: usize,
278     ) -> bool {
279         match (int_group_size, frac_group_size) {
280             // No groups on either side of decimal point - trivially consistent.
281             (None, None) => true,
282             // Integral part has grouped digits, fractional part does not.
283             (Some(int_group_size), None) => frac_size <= int_group_size,
284             // Fractional part has grouped digits, integral part does not.
285             (None, Some(frac_group_size)) => int_size <= frac_group_size,
286             // Both parts have grouped digits. Groups should be the same size.
287             (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
288         }
289     }
290
291     /// Returns the size of the digit groups (or None if ungrouped) if successful,
292     /// otherwise returns a `WarningType` for linting.
293     fn get_group_size<'a>(groups: impl Iterator<Item = &'a str>) -> Result<Option<usize>, WarningType> {
294         let mut groups = groups.map(str::len);
295
296         let first = groups.next().expect("At least one group");
297
298         if let Some(second) = groups.next() {
299             if !groups.all(|x| x == second) || first > second {
300                 Err(WarningType::InconsistentDigitGrouping)
301             } else if second > 4 {
302                 Err(WarningType::LargeDigitGroups)
303             } else {
304                 Ok(Some(second))
305             }
306         } else if first > 5 {
307             Err(WarningType::UnreadableLiteral)
308         } else {
309             Ok(None)
310         }
311     }
312 }
313
314 #[allow(clippy::module_name_repetitions)]
315 #[derive(Copy, Clone)]
316 pub struct DecimalLiteralRepresentation {
317     threshold: u64,
318 }
319
320 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
321
322 impl EarlyLintPass for DecimalLiteralRepresentation {
323     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
324         if in_external_macro(cx.sess(), expr.span) {
325             return;
326         }
327
328         if let ExprKind::Lit(ref lit) = expr.kind {
329             self.check_lit(cx, lit)
330         }
331     }
332 }
333
334 impl DecimalLiteralRepresentation {
335     #[must_use]
336     pub fn new(threshold: u64) -> Self {
337         Self { threshold }
338     }
339     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
340         // Lint integral literals.
341         if_chain! {
342             if let LitKind::Int(val, _) = lit.kind;
343             if let Some(src) = snippet_opt(cx, lit.span);
344             if let Some(num_lit) = NumericLiteral::from_lit(&src, &lit);
345             if num_lit.radix == Radix::Decimal;
346             if val >= u128::from(self.threshold);
347             then {
348                 let hex = format!("{:#X}", val);
349                 let num_lit = NumericLiteral::new(&hex, num_lit.suffix, false);
350                 let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
351                     warning_type.display(num_lit.format(), cx, lit.span)
352                 });
353             }
354         }
355     }
356
357     fn do_lint(digits: &str) -> Result<(), WarningType> {
358         if digits.len() == 1 {
359             // Lint for 1 digit literals, if someone really sets the threshold that low
360             if digits == "1"
361                 || digits == "2"
362                 || digits == "4"
363                 || digits == "8"
364                 || digits == "3"
365                 || digits == "7"
366                 || digits == "F"
367             {
368                 return Err(WarningType::DecimalRepresentation);
369             }
370         } else if digits.len() < 4 {
371             // Lint for Literals with a hex-representation of 2 or 3 digits
372             let f = &digits[0..1]; // first digit
373             let s = &digits[1..]; // suffix
374
375             // Powers of 2
376             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
377                 // Powers of 2 minus 1
378                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
379             {
380                 return Err(WarningType::DecimalRepresentation);
381             }
382         } else {
383             // Lint for Literals with a hex-representation of 4 digits or more
384             let f = &digits[0..1]; // first digit
385             let m = &digits[1..digits.len() - 1]; // middle digits, except last
386             let s = &digits[1..]; // suffix
387
388             // Powers of 2 with a margin of +15/-16
389             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
390                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
391                 // Lint for representations with only 0s and Fs, while allowing 7 as the first
392                 // digit
393                 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
394             {
395                 return Err(WarningType::DecimalRepresentation);
396             }
397         }
398
399         Ok(())
400     }
401 }