]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/literal_representation.rs
literal representation restructure 11
[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 NumericLiteral<'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 }
142
143 impl<'a> NumericLiteral<'a> {
144     fn from_lit(src: &'a str, lit: &Lit) -> Option<NumericLiteral<'a>> {
145         if lit.kind.is_numeric() && src.chars().next().map_or(false, |c| c.is_digit(10)) {
146             let (unsuffixed, suffix) = split_suffix(&src, &lit.kind);
147             let float = if let LitKind::Float(..) = lit.kind { true } else { false };
148             Some(NumericLiteral::new(unsuffixed, suffix, float))
149         } else {
150             None
151         }
152     }
153
154     #[must_use]
155     crate fn new(lit: &'a str, suffix: Option<&'a str>, float: bool) -> Self {
156         // Determine delimiter for radix prefix, if present, and radix.
157         let radix = if lit.starts_with("0x") {
158             Radix::Hexadecimal
159         } else if lit.starts_with("0b") {
160             Radix::Binary
161         } else if lit.starts_with("0o") {
162             Radix::Octal
163         } else {
164             Radix::Decimal
165         };
166
167         // Grab part of the literal after prefix, if present.
168         let (prefix, mut sans_prefix) = if let Radix::Decimal = radix {
169             (None, lit)
170         } else {
171             let (p, s) = lit.split_at(2);
172             (Some(p), s)
173         };
174
175         if suffix.is_some() && sans_prefix.ends_with('_') {
176             // The '_' before the suffix isn't part of the digits
177             sans_prefix = &sans_prefix[..sans_prefix.len() - 1];
178         }
179
180         let (integer, fraction, exponent) = Self::split_digit_parts(sans_prefix, float);
181
182         Self {
183             radix,
184             prefix,
185             integer,
186             fraction,
187             exponent,
188             suffix,
189         }
190     }
191
192     fn split_digit_parts(digits: &str, float: bool) -> (&str, Option<&str>, Option<(char, &str)>) {
193         let mut integer = digits;
194         let mut fraction = None;
195         let mut exponent = None;
196
197         if float {
198             for (i, c) in digits.char_indices() {
199                 match c {
200                     '.' => {
201                         integer = &digits[..i];
202                         fraction = Some(&digits[i + 1..]);
203                     },
204                     'e' | 'E' => {
205                         if integer.len() > i {
206                             integer = &digits[..i];
207                         } else {
208                             fraction = Some(&digits[integer.len() + 1..i]);
209                         };
210                         exponent = Some((c, &digits[i + 1..]));
211                         break;
212                     },
213                     _ => {},
214                 }
215             }
216         }
217
218         (integer, fraction, exponent)
219     }
220
221     /// Returns literal formatted in a sensible way.
222     crate fn format(&self) -> String {
223         let mut output = String::new();
224
225         if let Some(prefix) = self.prefix {
226             output.push_str(prefix);
227         }
228
229         let group_size = self.radix.suggest_grouping();
230
231         Self::group_digits(
232             &mut output,
233             self.integer,
234             group_size,
235             true,
236             self.radix == Radix::Hexadecimal,
237         );
238
239         if let Some(fraction) = self.fraction {
240             output.push('.');
241             Self::group_digits(&mut output, fraction, group_size, false, false);
242         }
243
244         if let Some((separator, exponent)) = self.exponent {
245             output.push(separator);
246             Self::group_digits(&mut output, exponent, group_size, true, false);
247         }
248
249         if let Some(suffix) = self.suffix {
250             output.push('_');
251             output.push_str(suffix);
252         }
253
254         output
255     }
256
257     fn group_digits(output: &mut String, input: &str, group_size: usize, partial_group_first: bool, pad: bool) {
258         debug_assert!(group_size > 0);
259
260         let mut digits = input.chars().filter(|&c| c != '_');
261
262         let first_group_size;
263
264         if partial_group_first {
265             first_group_size = (digits.clone().count() + group_size - 1) % group_size + 1;
266             if pad {
267                 for _ in 0..group_size - first_group_size {
268                     output.push('0');
269                 }
270             }
271         } else {
272             first_group_size = group_size;
273         }
274
275         for _ in 0..first_group_size {
276             if let Some(digit) = digits.next() {
277                 output.push(digit);
278             }
279         }
280
281         for (c, i) in digits.zip((0..group_size).cycle()) {
282             if i == 0 {
283                 output.push('_');
284             }
285             output.push(c);
286         }
287     }
288 }
289
290 fn split_suffix<'a>(src: &'a str, lit_kind: &LitKind) -> (&'a str, Option<&'a str>) {
291     debug_assert!(lit_kind.is_numeric());
292     if let Some(suffix_length) = lit_suffix_length(lit_kind) {
293         let (unsuffixed, suffix) = src.split_at(src.len() - suffix_length);
294         (unsuffixed, Some(suffix))
295     } else {
296         (src, None)
297     }
298 }
299
300 fn lit_suffix_length(lit_kind: &LitKind) -> Option<usize> {
301     debug_assert!(lit_kind.is_numeric());
302     let suffix = match lit_kind {
303         LitKind::Int(_, int_lit_kind) => match int_lit_kind {
304             LitIntType::Signed(int_ty) => Some(int_ty.name_str()),
305             LitIntType::Unsigned(uint_ty) => Some(uint_ty.name_str()),
306             LitIntType::Unsuffixed => None,
307         },
308         LitKind::Float(_, float_lit_kind) => match float_lit_kind {
309             LitFloatType::Suffixed(float_ty) => Some(float_ty.name_str()),
310             LitFloatType::Unsuffixed => None,
311         },
312         _ => None,
313     };
314
315     suffix.map(str::len)
316 }
317
318 enum WarningType {
319     UnreadableLiteral,
320     InconsistentDigitGrouping,
321     LargeDigitGroups,
322     DecimalRepresentation,
323     MistypedLiteralSuffix,
324 }
325
326 impl WarningType {
327     crate fn display(&self, suggested_format: String, cx: &EarlyContext<'_>, span: syntax_pos::Span) {
328         match self {
329             Self::MistypedLiteralSuffix => span_lint_and_sugg(
330                 cx,
331                 MISTYPED_LITERAL_SUFFIXES,
332                 span,
333                 "mistyped literal suffix",
334                 "did you mean to write",
335                 suggested_format,
336                 Applicability::MaybeIncorrect,
337             ),
338             Self::UnreadableLiteral => span_lint_and_sugg(
339                 cx,
340                 UNREADABLE_LITERAL,
341                 span,
342                 "long literal lacking separators",
343                 "consider",
344                 suggested_format,
345                 Applicability::MachineApplicable,
346             ),
347             Self::LargeDigitGroups => span_lint_and_sugg(
348                 cx,
349                 LARGE_DIGIT_GROUPS,
350                 span,
351                 "digit groups should be smaller",
352                 "consider",
353                 suggested_format,
354                 Applicability::MachineApplicable,
355             ),
356             Self::InconsistentDigitGrouping => span_lint_and_sugg(
357                 cx,
358                 INCONSISTENT_DIGIT_GROUPING,
359                 span,
360                 "digits grouped inconsistently by underscores",
361                 "consider",
362                 suggested_format,
363                 Applicability::MachineApplicable,
364             ),
365             Self::DecimalRepresentation => span_lint_and_sugg(
366                 cx,
367                 DECIMAL_LITERAL_REPRESENTATION,
368                 span,
369                 "integer literal has a better hexadecimal representation",
370                 "consider",
371                 suggested_format,
372                 Applicability::MachineApplicable,
373             ),
374         };
375     }
376 }
377
378 declare_lint_pass!(LiteralDigitGrouping => [
379     UNREADABLE_LITERAL,
380     INCONSISTENT_DIGIT_GROUPING,
381     LARGE_DIGIT_GROUPS,
382     MISTYPED_LITERAL_SUFFIXES,
383 ]);
384
385 impl EarlyLintPass for LiteralDigitGrouping {
386     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
387         if in_external_macro(cx.sess(), expr.span) {
388             return;
389         }
390
391         if let ExprKind::Lit(ref lit) = expr.kind {
392             Self::check_lit(cx, lit)
393         }
394     }
395 }
396
397 impl LiteralDigitGrouping {
398     fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
399         let in_macro = in_macro(lit.span);
400
401         if_chain! {
402             if let Some(src) = snippet_opt(cx, lit.span);
403             if let Some(mut num_lit) = NumericLiteral::from_lit(&src, &lit);
404             then {
405                 if !Self::check_for_mistyped_suffix(cx, lit.span, &mut num_lit) {
406                     return;
407                 }
408
409                 let result = (|| {
410
411                     let integral_group_size = Self::get_group_size(num_lit.integer.split('_'), in_macro)?;
412                     if let Some(fraction) = num_lit.fraction {
413                         let fractional_group_size = Self::get_group_size(fraction.rsplit('_'), in_macro)?;
414
415                         let consistent = Self::parts_consistent(integral_group_size,
416                                                                 fractional_group_size,
417                                                                 num_lit.integer.len(),
418                                                                 fraction.len());
419                         if !consistent {
420                             return Err(WarningType::InconsistentDigitGrouping);
421                         };
422                     }
423                     Ok(())
424                 })();
425
426
427                 if let Err(warning_type) = result {
428                     warning_type.display(num_lit.format(), cx, lit.span)
429                 }
430             }
431         }
432     }
433
434     // Returns `false` if the check fails
435     fn check_for_mistyped_suffix(
436         cx: &EarlyContext<'_>,
437         span: syntax_pos::Span,
438         num_lit: &mut NumericLiteral<'_>,
439     ) -> bool {
440         if num_lit.suffix.is_some() {
441             return true;
442         }
443
444         let (part, mistyped_suffixes, missing_char) = if let Some((_, exponent)) = &mut num_lit.exponent {
445             (exponent, &["32", "64"][..], 'f')
446         } else if let Some(fraction) = &mut num_lit.fraction {
447             (fraction, &["32", "64"][..], 'f')
448         } else {
449             (&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i')
450         };
451
452         let mut split = part.rsplit('_');
453         let last_group = split.next().expect("At least one group");
454         if split.next().is_some() && mistyped_suffixes.contains(&last_group) {
455             *part = &part[..part.len() - last_group.len()];
456             let mut sugg = num_lit.format();
457             sugg.push('_');
458             sugg.push(missing_char);
459             sugg.push_str(last_group);
460             WarningType::MistypedLiteralSuffix.display(sugg, cx, span);
461             false
462         } else {
463             true
464         }
465     }
466
467     /// Given the sizes of the digit groups of both integral and fractional
468     /// parts, and the length
469     /// of both parts, determine if the digits have been grouped consistently.
470     #[must_use]
471     fn parts_consistent(
472         int_group_size: Option<usize>,
473         frac_group_size: Option<usize>,
474         int_size: usize,
475         frac_size: usize,
476     ) -> bool {
477         match (int_group_size, frac_group_size) {
478             // No groups on either side of decimal point - trivially consistent.
479             (None, None) => true,
480             // Integral part has grouped digits, fractional part does not.
481             (Some(int_group_size), None) => frac_size <= int_group_size,
482             // Fractional part has grouped digits, integral part does not.
483             (None, Some(frac_group_size)) => int_size <= frac_group_size,
484             // Both parts have grouped digits. Groups should be the same size.
485             (Some(int_group_size), Some(frac_group_size)) => int_group_size == frac_group_size,
486         }
487     }
488
489     /// Returns the size of the digit groups (or None if ungrouped) if successful,
490     /// otherwise returns a `WarningType` for linting.
491     fn get_group_size<'a>(groups: impl Iterator<Item = &'a str>, in_macro: bool) -> Result<Option<usize>, WarningType> {
492         let mut groups = groups.map(str::len);
493
494         let first = groups.next().expect("At least one group");
495
496         if let Some(second) = groups.next() {
497             if !groups.all(|x| x == second) || first > second {
498                 Err(WarningType::InconsistentDigitGrouping)
499             } else if second > 4 {
500                 Err(WarningType::LargeDigitGroups)
501             } else {
502                 Ok(Some(second))
503             }
504         } else if first > 5 && !in_macro {
505             Err(WarningType::UnreadableLiteral)
506         } else {
507             Ok(None)
508         }
509     }
510 }
511
512 #[allow(clippy::module_name_repetitions)]
513 #[derive(Copy, Clone)]
514 pub struct DecimalLiteralRepresentation {
515     threshold: u64,
516 }
517
518 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
519
520 impl EarlyLintPass for DecimalLiteralRepresentation {
521     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
522         if in_external_macro(cx.sess(), expr.span) {
523             return;
524         }
525
526         if let ExprKind::Lit(ref lit) = expr.kind {
527             self.check_lit(cx, lit)
528         }
529     }
530 }
531
532 impl DecimalLiteralRepresentation {
533     #[must_use]
534     pub fn new(threshold: u64) -> Self {
535         Self { threshold }
536     }
537     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
538         // Lint integral literals.
539         if_chain! {
540             if let LitKind::Int(val, _) = lit.kind;
541             if let Some(src) = snippet_opt(cx, lit.span);
542             if let Some(num_lit) = NumericLiteral::from_lit(&src, &lit);
543             if num_lit.radix == Radix::Decimal;
544             if val >= u128::from(self.threshold);
545             then {
546                 let hex = format!("{:#X}", val);
547                 let num_lit = NumericLiteral::new(&hex, None, false);
548                 let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
549                     warning_type.display(num_lit.format(), cx, lit.span)
550                 });
551             }
552         }
553     }
554
555     fn do_lint(digits: &str) -> Result<(), WarningType> {
556         if digits.len() == 1 {
557             // Lint for 1 digit literals, if someone really sets the threshold that low
558             if digits == "1"
559                 || digits == "2"
560                 || digits == "4"
561                 || digits == "8"
562                 || digits == "3"
563                 || digits == "7"
564                 || digits == "F"
565             {
566                 return Err(WarningType::DecimalRepresentation);
567             }
568         } else if digits.len() < 4 {
569             // Lint for Literals with a hex-representation of 2 or 3 digits
570             let f = &digits[0..1]; // first digit
571             let s = &digits[1..]; // suffix
572
573             // Powers of 2
574             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
575                 // Powers of 2 minus 1
576                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
577             {
578                 return Err(WarningType::DecimalRepresentation);
579             }
580         } else {
581             // Lint for Literals with a hex-representation of 4 digits or more
582             let f = &digits[0..1]; // first digit
583             let m = &digits[1..digits.len() - 1]; // middle digits, except last
584             let s = &digits[1..]; // suffix
585
586             // Powers of 2 with a margin of +15/-16
587             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
588                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
589                 // Lint for representations with only 0s and Fs, while allowing 7 as the first
590                 // digit
591                 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
592             {
593                 return Err(WarningType::DecimalRepresentation);
594             }
595         }
596
597         Ok(())
598     }
599 }