]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/literal_representation.rs
literal representation restructure 8
[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::{in_macro, snippet_opt, span_lint_and_sugg};
5 use if_chain::if_chain;
6 use rustc::lint::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
7 use rustc::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
8 use rustc_errors::Applicability;
9 use syntax::ast::*;
10 use syntax_pos;
11
12 declare_clippy_lint! {
13     /// **What it does:** Warns if a long integral or floating-point constant does
14     /// not contain underscores.
15     ///
16     /// **Why is this bad?** Reading long numbers is difficult without separators.
17     ///
18     /// **Known problems:** None.
19     ///
20     /// **Example:**
21     ///
22     /// ```rust
23     /// let x: u64 = 61864918973511;
24     /// ```
25     pub UNREADABLE_LITERAL,
26     style,
27     "long integer literal without underscores"
28 }
29
30 declare_clippy_lint! {
31     /// **What it does:** Warns for mistyped suffix in literals
32     ///
33     /// **Why is this bad?** This is most probably a typo
34     ///
35     /// **Known problems:**
36     /// - Recommends a signed suffix, even though the number might be too big and an unsigned
37     ///   suffix is required
38     /// - Does not match on `_128` since that is a valid grouping for decimal and octal numbers
39     ///
40     /// **Example:**
41     ///
42     /// ```rust
43     /// 2_32;
44     /// ```
45     pub MISTYPED_LITERAL_SUFFIXES,
46     correctness,
47     "mistyped literal suffix"
48 }
49
50 declare_clippy_lint! {
51     /// **What it does:** Warns if an integral or floating-point constant is
52     /// grouped inconsistently with underscores.
53     ///
54     /// **Why is this bad?** Readers may incorrectly interpret inconsistently
55     /// grouped digits.
56     ///
57     /// **Known problems:** None.
58     ///
59     /// **Example:**
60     ///
61     /// ```rust
62     /// let x: u64 = 618_64_9189_73_511;
63     /// ```
64     pub INCONSISTENT_DIGIT_GROUPING,
65     style,
66     "integer literals with digits grouped inconsistently"
67 }
68
69 declare_clippy_lint! {
70     /// **What it does:** Warns if the digits of an integral or floating-point
71     /// constant are grouped into groups that
72     /// are too large.
73     ///
74     /// **Why is this bad?** Negatively impacts readability.
75     ///
76     /// **Known problems:** None.
77     ///
78     /// **Example:**
79     ///
80     /// ```rust
81     /// let x: u64 = 6186491_8973511;
82     /// ```
83     pub LARGE_DIGIT_GROUPS,
84     pedantic,
85     "grouping digits into groups that are too large"
86 }
87
88 declare_clippy_lint! {
89     /// **What it does:** Warns if there is a better representation for a numeric literal.
90     ///
91     /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
92     /// readable than a decimal representation.
93     ///
94     /// **Known problems:** None.
95     ///
96     /// **Example:**
97     ///
98     /// `255` => `0xFF`
99     /// `65_535` => `0xFFFF`
100     /// `4_042_322_160` => `0xF0F0_F0F0`
101     pub DECIMAL_LITERAL_REPRESENTATION,
102     restriction,
103     "using decimal representation when hexadecimal would be better"
104 }
105
106 #[derive(Debug, PartialEq)]
107 pub(super) enum Radix {
108     Binary,
109     Octal,
110     Decimal,
111     Hexadecimal,
112 }
113
114 impl Radix {
115     /// Returns a reasonable digit group size for this radix.
116     #[must_use]
117     crate fn suggest_grouping(&self) -> usize {
118         match *self {
119             Self::Binary | Self::Hexadecimal => 4,
120             Self::Octal | Self::Decimal => 3,
121         }
122     }
123 }
124
125 #[derive(Debug)]
126 pub(super) struct DigitInfo<'a> {
127     /// Which radix the literal was represented in.
128     crate radix: Radix,
129     /// The radix prefix, if present.
130     crate prefix: Option<&'a str>,
131
132     /// The integer part of the number.
133     integer: &'a str,
134     /// The fraction part of the number.
135     fraction: Option<&'a str>,
136     /// The character used as exponent seperator (b'e' or b'E') and the exponent part.
137     exponent: Option<(char, &'a str)>,
138
139     /// The type suffix, including preceding underscore if present.
140     crate suffix: Option<&'a str>,
141     /// True for floating-point literals.
142     crate float: bool,
143 }
144
145 impl<'a> DigitInfo<'a> {
146     #[must_use]
147     crate fn new(lit: &'a str, float: bool) -> Self {
148         // Determine delimiter for radix prefix, if present, and radix.
149         let radix = if lit.starts_with("0x") {
150             Radix::Hexadecimal
151         } else if lit.starts_with("0b") {
152             Radix::Binary
153         } else if lit.starts_with("0o") {
154             Radix::Octal
155         } else {
156             Radix::Decimal
157         };
158
159         // Grab part of the literal after prefix, if present.
160         let (prefix, sans_prefix) = if let Radix::Decimal = radix {
161             (None, lit)
162         } else {
163             let (p, s) = lit.split_at(2);
164             (Some(p), s)
165         };
166
167         let mut digits = sans_prefix;
168         let mut suffix = None;
169
170         let len = sans_prefix.len();
171         let mut last_d = '\0';
172         for (d_idx, d) in sans_prefix.char_indices() {
173             let suffix_start = if last_d == '_' { d_idx - 1 } else { d_idx };
174             if float
175                 && (d == 'f'
176                     || is_possible_float_suffix_index(&sans_prefix, suffix_start, len)
177                     || ((d == 'E' || d == 'e') && !has_possible_float_suffix(&sans_prefix)))
178                 || !float && (d == 'i' || d == 'u' || is_possible_suffix_index(&sans_prefix, suffix_start, len))
179             {
180                 let (d, s) = sans_prefix.split_at(suffix_start);
181                 digits = d;
182                 suffix = Some(s);
183                 break;
184             }
185             last_d = d
186         }
187
188         let (integer, fraction, exponent) = Self::split_digit_parts(digits, float);
189
190         Self {
191             radix,
192             prefix,
193             integer,
194             fraction,
195             exponent,
196             suffix,
197             float,
198         }
199     }
200
201     fn split_digit_parts(digits: &str, float: bool) -> (&str, Option<&str>, Option<(char, &str)>) {
202         let mut integer = digits;
203         let mut fraction = None;
204         let mut exponent = None;
205
206         if float {
207             for (i, c) in digits.char_indices() {
208                 match c {
209                     '.' => {
210                         integer = &digits[..i];
211                         fraction = Some(&digits[i + 1..]);
212                     },
213                     'e' | 'E' => {
214                         if integer.len() > i {
215                             integer = &digits[..i];
216                         } else {
217                             fraction = Some(&digits[integer.len() + 1..i]);
218                         };
219                         exponent = Some((c, &digits[i + 1..]));
220                         break;
221                     },
222                     _ => {},
223                 }
224             }
225         }
226
227         (integer, fraction, exponent)
228     }
229
230     /// Returns literal formatted in a sensible way.
231     crate fn grouping_hint(&self) -> String {
232         let mut output = String::new();
233
234         if let Some(prefix) = self.prefix {
235             output.push_str(prefix);
236         }
237
238         let group_size = self.radix.suggest_grouping();
239
240         Self::group_digits(
241             &mut output,
242             self.integer,
243             group_size,
244             true,
245             self.radix == Radix::Hexadecimal,
246         );
247
248         if let Some(fraction) = self.fraction {
249             output.push('.');
250             Self::group_digits(&mut output, fraction, group_size, false, false);
251         }
252
253         if let Some((separator, exponent)) = self.exponent {
254             output.push(separator);
255             Self::group_digits(&mut output, exponent, group_size, true, false);
256         }
257
258         if let Some(suffix) = self.suffix {
259             if self.float && is_mistyped_float_suffix(suffix) {
260                 output.push_str("_f");
261                 output.push_str(&suffix[1..]);
262             } else if is_mistyped_suffix(suffix) {
263                 output.push_str("_i");
264                 output.push_str(&suffix[1..]);
265             } else {
266                 output.push_str(suffix);
267             }
268         }
269
270         output
271     }
272
273     fn group_digits(output: &mut String, input: &str, group_size: usize, partial_group_first: bool, pad: bool) {
274         debug_assert!(group_size > 0);
275
276         let mut digits = input.chars().filter(|&c| c != '_');
277
278         let first_group_size;
279
280         if partial_group_first {
281             first_group_size = (digits.clone().count() + group_size - 1) % group_size + 1;
282             if pad {
283                 for _ in 0..group_size - first_group_size {
284                     output.push('0');
285                 }
286             }
287         } else {
288             first_group_size = group_size;
289         }
290
291         for _ in 0..first_group_size {
292             if let Some(digit) = digits.next() {
293                 output.push(digit);
294             }
295         }
296
297         for (c, i) in digits.zip((0..group_size).cycle()) {
298             if i == 0 {
299                 output.push('_');
300             }
301             output.push(c);
302         }
303     }
304 }
305
306 enum WarningType {
307     UnreadableLiteral,
308     InconsistentDigitGrouping,
309     LargeDigitGroups,
310     DecimalRepresentation,
311     MistypedLiteralSuffix,
312 }
313
314 impl WarningType {
315     crate fn display(&self, grouping_hint: &str, cx: &EarlyContext<'_>, span: syntax_pos::Span) {
316         match self {
317             Self::MistypedLiteralSuffix => span_lint_and_sugg(
318                 cx,
319                 MISTYPED_LITERAL_SUFFIXES,
320                 span,
321                 "mistyped literal suffix",
322                 "did you mean to write",
323                 grouping_hint.to_string(),
324                 Applicability::MaybeIncorrect,
325             ),
326             Self::UnreadableLiteral => span_lint_and_sugg(
327                 cx,
328                 UNREADABLE_LITERAL,
329                 span,
330                 "long literal lacking separators",
331                 "consider",
332                 grouping_hint.to_owned(),
333                 Applicability::MachineApplicable,
334             ),
335             Self::LargeDigitGroups => span_lint_and_sugg(
336                 cx,
337                 LARGE_DIGIT_GROUPS,
338                 span,
339                 "digit groups should be smaller",
340                 "consider",
341                 grouping_hint.to_owned(),
342                 Applicability::MachineApplicable,
343             ),
344             Self::InconsistentDigitGrouping => span_lint_and_sugg(
345                 cx,
346                 INCONSISTENT_DIGIT_GROUPING,
347                 span,
348                 "digits grouped inconsistently by underscores",
349                 "consider",
350                 grouping_hint.to_owned(),
351                 Applicability::MachineApplicable,
352             ),
353             Self::DecimalRepresentation => span_lint_and_sugg(
354                 cx,
355                 DECIMAL_LITERAL_REPRESENTATION,
356                 span,
357                 "integer literal has a better hexadecimal representation",
358                 "consider",
359                 grouping_hint.to_owned(),
360                 Applicability::MachineApplicable,
361             ),
362         };
363     }
364 }
365
366 declare_lint_pass!(LiteralDigitGrouping => [
367     UNREADABLE_LITERAL,
368     INCONSISTENT_DIGIT_GROUPING,
369     LARGE_DIGIT_GROUPS,
370     MISTYPED_LITERAL_SUFFIXES,
371 ]);
372
373 impl EarlyLintPass for LiteralDigitGrouping {
374     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
375         if in_external_macro(cx.sess(), expr.span) {
376             return;
377         }
378
379         if let ExprKind::Lit(ref lit) = expr.kind {
380             Self::check_lit(cx, lit)
381         }
382     }
383 }
384
385 impl LiteralDigitGrouping {
386     fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
387         let in_macro = in_macro(lit.span);
388
389         if_chain! {
390             if let Some(src) = snippet_opt(cx, lit.span);
391             if let Some(firstch) = src.chars().next();
392             if char::is_digit(firstch, 10);
393             then {
394
395                 let digit_info = match lit.kind {
396                         LitKind::Int(..) => DigitInfo::new(&src, false),
397                         LitKind::Float(..) => DigitInfo::new(&src, true),
398                         _ => return,
399                 };
400
401                 let result = (|| {
402                     if let Some(suffix) = digit_info.suffix {
403                         if is_mistyped_suffix(suffix) {
404                             return Err(WarningType::MistypedLiteralSuffix);
405                         }
406                     }
407
408                     let integral_group_size = Self::get_group_size(digit_info.integer.split('_'), in_macro)?;
409                     if let Some(fraction) = digit_info.fraction {
410                         let fractional_group_size = Self::get_group_size(fraction.rsplit('_'), in_macro)?;
411
412                         let consistent = Self::parts_consistent(integral_group_size,
413                                                                 fractional_group_size,
414                                                                 digit_info.integer.len(),
415                                                                 fraction.len());
416                         if !consistent {
417                             return Err(WarningType::InconsistentDigitGrouping);
418                         };
419                     }
420                     Ok(())
421                 })();
422
423
424                 if let Err(warning_type) = result {
425                     warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
426                 }
427             }
428         }
429     }
430
431     /// Given the sizes of the digit groups of both integral and fractional
432     /// parts, and the length
433     /// of both parts, determine if the digits have been grouped consistently.
434     #[must_use]
435     fn parts_consistent(
436         int_group_size: Option<usize>,
437         frac_group_size: Option<usize>,
438         int_size: usize,
439         frac_size: usize,
440     ) -> bool {
441         match (int_group_size, frac_group_size) {
442             // No groups on either side of decimal point - trivially consistent.
443             (None, None) => true,
444             // Integral part has grouped digits, fractional part does not.
445             (Some(int_group_size), None) => frac_size <= int_group_size,
446             // Fractional part has grouped digits, integral part does not.
447             (None, Some(frac_group_size)) => int_size <= frac_group_size,
448             // Both parts have grouped digits. Groups should be the same size.
449             (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
450         }
451     }
452
453     /// Returns the size of the digit groups (or None if ungrouped) if successful,
454     /// otherwise returns a `WarningType` for linting.
455     fn get_group_size<'a>(groups: impl Iterator<Item = &'a str>, in_macro: bool) -> Result<Option<usize>, WarningType> {
456         let mut groups = groups.map(str::len);
457
458         let first = groups.next().expect("At least one group");
459
460         if let Some(second) = groups.next() {
461             if !groups.all(|x| x == second) || first > second {
462                 Err(WarningType::InconsistentDigitGrouping)
463             } else if second > 4 {
464                 Err(WarningType::LargeDigitGroups)
465             } else {
466                 Ok(Some(second))
467             }
468         } else if first > 5 && !in_macro {
469             Err(WarningType::UnreadableLiteral)
470         } else {
471             Ok(None)
472         }
473     }
474 }
475
476 #[allow(clippy::module_name_repetitions)]
477 #[derive(Copy, Clone)]
478 pub struct DecimalLiteralRepresentation {
479     threshold: u64,
480 }
481
482 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
483
484 impl EarlyLintPass for DecimalLiteralRepresentation {
485     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
486         if in_external_macro(cx.sess(), expr.span) {
487             return;
488         }
489
490         if let ExprKind::Lit(ref lit) = expr.kind {
491             self.check_lit(cx, lit)
492         }
493     }
494 }
495
496 impl DecimalLiteralRepresentation {
497     #[must_use]
498     pub fn new(threshold: u64) -> Self {
499         Self { threshold }
500     }
501     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
502         // Lint integral literals.
503         if_chain! {
504             if let LitKind::Int(val, _) = lit.kind;
505             if let Some(src) = snippet_opt(cx, lit.span);
506             if let Some(firstch) = src.chars().next();
507             if char::is_digit(firstch, 10);
508             let digit_info = DigitInfo::new(&src, false);
509             if digit_info.radix == Radix::Decimal;
510             if val >= u128::from(self.threshold);
511             then {
512                 let hex = format!("{:#X}", val);
513                 let digit_info = DigitInfo::new(&hex, false);
514                 let _ = Self::do_lint(digit_info.integer).map_err(|warning_type| {
515                     warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
516                 });
517             }
518         }
519     }
520
521     fn do_lint(digits: &str) -> Result<(), WarningType> {
522         if digits.len() == 1 {
523             // Lint for 1 digit literals, if someone really sets the threshold that low
524             if digits == "1"
525                 || digits == "2"
526                 || digits == "4"
527                 || digits == "8"
528                 || digits == "3"
529                 || digits == "7"
530                 || digits == "F"
531             {
532                 return Err(WarningType::DecimalRepresentation);
533             }
534         } else if digits.len() < 4 {
535             // Lint for Literals with a hex-representation of 2 or 3 digits
536             let f = &digits[0..1]; // first digit
537             let s = &digits[1..]; // suffix
538
539             // Powers of 2
540             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
541                 // Powers of 2 minus 1
542                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
543             {
544                 return Err(WarningType::DecimalRepresentation);
545             }
546         } else {
547             // Lint for Literals with a hex-representation of 4 digits or more
548             let f = &digits[0..1]; // first digit
549             let m = &digits[1..digits.len() - 1]; // middle digits, except last
550             let s = &digits[1..]; // suffix
551
552             // Powers of 2 with a margin of +15/-16
553             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
554                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
555                 // Lint for representations with only 0s and Fs, while allowing 7 as the first
556                 // digit
557                 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
558             {
559                 return Err(WarningType::DecimalRepresentation);
560             }
561         }
562
563         Ok(())
564     }
565 }
566
567 #[must_use]
568 fn is_mistyped_suffix(suffix: &str) -> bool {
569     ["_8", "_16", "_32", "_64"].contains(&suffix)
570 }
571
572 #[must_use]
573 fn is_possible_suffix_index(lit: &str, idx: usize, len: usize) -> bool {
574     ((len > 3 && idx == len - 3) || (len > 2 && idx == len - 2)) && is_mistyped_suffix(lit.split_at(idx).1)
575 }
576
577 #[must_use]
578 fn is_mistyped_float_suffix(suffix: &str) -> bool {
579     ["_32", "_64"].contains(&suffix)
580 }
581
582 #[must_use]
583 fn is_possible_float_suffix_index(lit: &str, idx: usize, len: usize) -> bool {
584     (len > 3 && idx == len - 3) && is_mistyped_float_suffix(lit.split_at(idx).1)
585 }
586
587 #[must_use]
588 fn has_possible_float_suffix(lit: &str) -> bool {
589     lit.ends_with("_32") || lit.ends_with("_64")
590 }