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