]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/literal_representation.rs
5b234948f241445f82e0f8bcf84b9e1e0cd7e2b6
[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     /// Characters of a literal between the radix prefix and type suffix.
128     crate digits: &'a str,
129     /// Which radix the literal was represented in.
130     crate radix: Radix,
131     /// The radix prefix, if present.
132     crate prefix: Option<&'a str>,
133     /// The type suffix, including preceding underscore if present.
134     crate suffix: Option<&'a str>,
135     /// True for floating-point literals.
136     crate float: bool,
137 }
138
139 impl<'a> DigitInfo<'a> {
140     #[must_use]
141     crate fn new(lit: &'a str, float: bool) -> Self {
142         // Determine delimiter for radix prefix, if present, and radix.
143         let radix = if lit.starts_with("0x") {
144             Radix::Hexadecimal
145         } else if lit.starts_with("0b") {
146             Radix::Binary
147         } else if lit.starts_with("0o") {
148             Radix::Octal
149         } else {
150             Radix::Decimal
151         };
152
153         // Grab part of the literal after prefix, if present.
154         let (prefix, sans_prefix) = if let Radix::Decimal = radix {
155             (None, lit)
156         } else {
157             let (p, s) = lit.split_at(2);
158             (Some(p), s)
159         };
160
161         let len = sans_prefix.len();
162         let mut last_d = '\0';
163         for (d_idx, d) in sans_prefix.char_indices() {
164             let suffix_start = if last_d == '_' { d_idx - 1 } else { d_idx };
165             if float
166                 && (d == 'f'
167                     || is_possible_float_suffix_index(&sans_prefix, suffix_start, len)
168                     || ((d == 'E' || d == 'e') && !has_possible_float_suffix(&sans_prefix)))
169                 || !float && (d == 'i' || d == 'u' || is_possible_suffix_index(&sans_prefix, suffix_start, len))
170             {
171                 let (digits, suffix) = sans_prefix.split_at(suffix_start);
172                 return Self {
173                     digits,
174                     radix,
175                     prefix,
176                     suffix: Some(suffix),
177                     float,
178                 };
179             }
180             last_d = d
181         }
182
183         // No suffix found
184         Self {
185             digits: sans_prefix,
186             radix,
187             prefix,
188             suffix: None,
189             float,
190         }
191     }
192
193     /// Returns literal formatted in a sensible way.
194     crate fn grouping_hint(&self) -> String {
195         let group_size = self.radix.suggest_grouping();
196         if self.digits.contains('.') {
197             let mut parts = self.digits.split('.');
198             let int_part_hint = parts
199                 .next()
200                 .expect("split always returns at least one element")
201                 .chars()
202                 .rev()
203                 .filter(|&c| c != '_')
204                 .collect::<Vec<_>>()
205                 .chunks(group_size)
206                 .map(|chunk| chunk.iter().rev().collect())
207                 .rev()
208                 .collect::<Vec<String>>()
209                 .join("_");
210             let frac_part_hint = parts
211                 .next()
212                 .expect("already checked that there is a `.`")
213                 .chars()
214                 .filter(|&c| c != '_')
215                 .collect::<Vec<_>>()
216                 .chunks(group_size)
217                 .map(|chunk| chunk.iter().collect())
218                 .collect::<Vec<String>>()
219                 .join("_");
220             let suffix_hint = match self.suffix {
221                 Some(suffix) if is_mistyped_float_suffix(suffix) => format!("_f{}", &suffix[1..]),
222                 Some(suffix) => suffix.to_string(),
223                 None => String::new(),
224             };
225             format!("{}.{}{}", int_part_hint, frac_part_hint, suffix_hint)
226         } else if self.float && (self.digits.contains('E') || self.digits.contains('e')) {
227             let which_e = if self.digits.contains('E') { 'E' } else { 'e' };
228             let parts: Vec<&str> = self.digits.split(which_e).collect();
229             let filtered_digits_vec_0 = parts[0].chars().filter(|&c| c != '_').rev().collect::<Vec<_>>();
230             let filtered_digits_vec_1 = parts[1].chars().filter(|&c| c != '_').rev().collect::<Vec<_>>();
231             let before_e_hint = filtered_digits_vec_0
232                 .chunks(group_size)
233                 .map(|chunk| chunk.iter().rev().collect())
234                 .rev()
235                 .collect::<Vec<String>>()
236                 .join("_");
237             let after_e_hint = filtered_digits_vec_1
238                 .chunks(group_size)
239                 .map(|chunk| chunk.iter().rev().collect())
240                 .rev()
241                 .collect::<Vec<String>>()
242                 .join("_");
243             let suffix_hint = match self.suffix {
244                 Some(suffix) if is_mistyped_float_suffix(suffix) => format!("_f{}", &suffix[1..]),
245                 Some(suffix) => suffix.to_string(),
246                 None => String::new(),
247             };
248             format!(
249                 "{}{}{}{}{}",
250                 self.prefix.unwrap_or(""),
251                 before_e_hint,
252                 which_e,
253                 after_e_hint,
254                 suffix_hint
255             )
256         } else {
257             let filtered_digits_vec = self.digits.chars().filter(|&c| c != '_').rev().collect::<Vec<_>>();
258             let mut hint = filtered_digits_vec
259                 .chunks(group_size)
260                 .map(|chunk| chunk.iter().rev().collect())
261                 .rev()
262                 .collect::<Vec<String>>()
263                 .join("_");
264             // Forces hexadecimal values to be grouped by 4 being filled with zeroes (e.g 0x00ab_cdef)
265             let nb_digits_to_fill = filtered_digits_vec.len() % 4;
266             if self.radix == Radix::Hexadecimal && nb_digits_to_fill != 0 {
267                 hint = format!("{:0>4}{}", &hint[..nb_digits_to_fill], &hint[nb_digits_to_fill..]);
268             }
269             let suffix_hint = match self.suffix {
270                 Some(suffix) if is_mistyped_suffix(suffix) => format!("_i{}", &suffix[1..]),
271                 Some(suffix) => suffix.to_string(),
272                 None => String::new(),
273             };
274             format!("{}{}{}", self.prefix.unwrap_or(""), hint, suffix_hint)
275         }
276     }
277 }
278
279 enum WarningType {
280     UnreadableLiteral,
281     InconsistentDigitGrouping,
282     LargeDigitGroups,
283     DecimalRepresentation,
284     MistypedLiteralSuffix,
285 }
286
287 impl WarningType {
288     crate fn display(&self, grouping_hint: &str, cx: &EarlyContext<'_>, span: syntax_pos::Span) {
289         match self {
290             Self::MistypedLiteralSuffix => span_lint_and_sugg(
291                 cx,
292                 MISTYPED_LITERAL_SUFFIXES,
293                 span,
294                 "mistyped literal suffix",
295                 "did you mean to write",
296                 grouping_hint.to_string(),
297                 Applicability::MaybeIncorrect,
298             ),
299             Self::UnreadableLiteral => span_lint_and_sugg(
300                 cx,
301                 UNREADABLE_LITERAL,
302                 span,
303                 "long literal lacking separators",
304                 "consider",
305                 grouping_hint.to_owned(),
306                 Applicability::MachineApplicable,
307             ),
308             Self::LargeDigitGroups => span_lint_and_sugg(
309                 cx,
310                 LARGE_DIGIT_GROUPS,
311                 span,
312                 "digit groups should be smaller",
313                 "consider",
314                 grouping_hint.to_owned(),
315                 Applicability::MachineApplicable,
316             ),
317             Self::InconsistentDigitGrouping => span_lint_and_sugg(
318                 cx,
319                 INCONSISTENT_DIGIT_GROUPING,
320                 span,
321                 "digits grouped inconsistently by underscores",
322                 "consider",
323                 grouping_hint.to_owned(),
324                 Applicability::MachineApplicable,
325             ),
326             Self::DecimalRepresentation => span_lint_and_sugg(
327                 cx,
328                 DECIMAL_LITERAL_REPRESENTATION,
329                 span,
330                 "integer literal has a better hexadecimal representation",
331                 "consider",
332                 grouping_hint.to_owned(),
333                 Applicability::MachineApplicable,
334             ),
335         };
336     }
337 }
338
339 declare_lint_pass!(LiteralDigitGrouping => [
340     UNREADABLE_LITERAL,
341     INCONSISTENT_DIGIT_GROUPING,
342     LARGE_DIGIT_GROUPS,
343     MISTYPED_LITERAL_SUFFIXES,
344 ]);
345
346 impl EarlyLintPass for LiteralDigitGrouping {
347     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
348         if in_external_macro(cx.sess(), expr.span) {
349             return;
350         }
351
352         if let ExprKind::Lit(ref lit) = expr.kind {
353             Self::check_lit(cx, lit)
354         }
355     }
356 }
357
358 impl LiteralDigitGrouping {
359     fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
360         let in_macro = in_macro(lit.span);
361
362         if_chain! {
363             if let Some(src) = snippet_opt(cx, lit.span);
364             if let Some(firstch) = src.chars().next();
365             if char::is_digit(firstch, 10);
366             then {
367
368                 let digit_info = match lit.kind {
369                         LitKind::Int(..) => DigitInfo::new(&src, false),
370                         LitKind::Float(..) => DigitInfo::new(&src, true),
371                         _ => return,
372                 };
373
374                 let result = (|| {
375                     if let Some(suffix) = digit_info.suffix {
376                         if is_mistyped_suffix(suffix) {
377                             return Err(WarningType::MistypedLiteralSuffix);
378                         }
379                     }
380
381                     match lit.kind {
382                         LitKind::Int(..) => {
383                             Self::do_lint(digit_info.digits, in_macro)?;
384                         },
385                         LitKind::Float(..) => {
386                             // Separate digits into integral and fractional parts.
387                             let parts: Vec<&str> = digit_info
388                                 .digits
389                                 .split_terminator('.')
390                                 .collect();
391
392                             // Lint integral and fractional parts separately, and then check consistency of digit
393                             // groups if both pass.
394                             let integral_group_size = Self::do_lint(parts[0], in_macro)?;
395                             if parts.len() > 1 {
396                                 // Lint the fractional part of literal just like integral part, but reversed.
397                                 let fractional_part = &parts[1].chars().rev().collect::<String>();
398                                 let fractional_group_size = Self::do_lint(fractional_part, in_macro)?;
399                                 let consistent = Self::parts_consistent(integral_group_size,
400                                                                         fractional_group_size,
401                                                                         parts[0].len(),
402                                                                         parts[1].len());
403                                 if !consistent {
404                                     return Err(WarningType::InconsistentDigitGrouping);
405                                 };
406                             };
407                         },
408                         _ => (),
409                     }
410
411                     Ok(())
412                 })();
413
414
415                 if let Err(warning_type) = result {
416                     warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
417                 }
418             }
419         }
420     }
421
422     /// Given the sizes of the digit groups of both integral and fractional
423     /// parts, and the length
424     /// of both parts, determine if the digits have been grouped consistently.
425     #[must_use]
426     fn parts_consistent(int_group_size: usize, frac_group_size: usize, int_size: usize, frac_size: usize) -> bool {
427         match (int_group_size, frac_group_size) {
428             // No groups on either side of decimal point - trivially consistent.
429             (0, 0) => true,
430             // Integral part has grouped digits, fractional part does not.
431             (_, 0) => frac_size <= int_group_size,
432             // Fractional part has grouped digits, integral part does not.
433             (0, _) => int_size <= frac_group_size,
434             // Both parts have grouped digits. Groups should be the same size.
435             (_, _) => int_group_size == frac_group_size,
436         }
437     }
438
439     /// Performs lint on `digits` (no decimal point) and returns the group
440     /// size on success or `WarningType` when emitting a warning.
441     fn do_lint(digits: &str, in_macro: bool) -> Result<usize, WarningType> {
442         // Grab underscore indices with respect to the units digit.
443         let underscore_positions: Vec<usize> = digits
444             .chars()
445             .rev()
446             .enumerate()
447             .filter_map(|(idx, digit)| if digit == '_' { Some(idx) } else { None })
448             .collect();
449
450         if underscore_positions.is_empty() {
451             // Check if literal needs underscores.
452             if !in_macro && digits.len() > 5 {
453                 Err(WarningType::UnreadableLiteral)
454             } else {
455                 Ok(0)
456             }
457         } else {
458             // Check consistency and the sizes of the groups.
459             let group_size = underscore_positions[0];
460             let consistent = underscore_positions
461                 .windows(2)
462                 .all(|ps| ps[1] - ps[0] == group_size + 1)
463                 // number of digits to the left of the last group cannot be bigger than group size.
464                 && (digits.len() - underscore_positions.last()
465                                                        .expect("there's at least one element") <= group_size + 1);
466
467             if !consistent {
468                 return Err(WarningType::InconsistentDigitGrouping);
469             } else if group_size > 4 {
470                 return Err(WarningType::LargeDigitGroups);
471             }
472             Ok(group_size)
473         }
474     }
475 }
476
477 #[allow(clippy::module_name_repetitions)]
478 #[derive(Copy, Clone)]
479 pub struct DecimalLiteralRepresentation {
480     threshold: u64,
481 }
482
483 impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
484
485 impl EarlyLintPass for DecimalLiteralRepresentation {
486     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
487         if in_external_macro(cx.sess(), expr.span) {
488             return;
489         }
490
491         if let ExprKind::Lit(ref lit) = expr.kind {
492             self.check_lit(cx, lit)
493         }
494     }
495 }
496
497 impl DecimalLiteralRepresentation {
498     #[must_use]
499     pub fn new(threshold: u64) -> Self {
500         Self { threshold }
501     }
502     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
503         // Lint integral literals.
504         if_chain! {
505             if let LitKind::Int(val, _) = lit.kind;
506             if let Some(src) = snippet_opt(cx, lit.span);
507             if let Some(firstch) = src.chars().next();
508             if char::is_digit(firstch, 10);
509             let digit_info = DigitInfo::new(&src, false);
510             if digit_info.radix == Radix::Decimal;
511             if val >= u128::from(self.threshold);
512             then {
513                 let hex = format!("{:#X}", val);
514                 let digit_info = DigitInfo::new(&hex, false);
515                 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
516                     warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
517                 });
518             }
519         }
520     }
521
522     fn do_lint(digits: &str) -> Result<(), WarningType> {
523         if digits.len() == 1 {
524             // Lint for 1 digit literals, if someone really sets the threshold that low
525             if digits == "1"
526                 || digits == "2"
527                 || digits == "4"
528                 || digits == "8"
529                 || digits == "3"
530                 || digits == "7"
531                 || digits == "F"
532             {
533                 return Err(WarningType::DecimalRepresentation);
534             }
535         } else if digits.len() < 4 {
536             // Lint for Literals with a hex-representation of 2 or 3 digits
537             let f = &digits[0..1]; // first digit
538             let s = &digits[1..]; // suffix
539
540             // Powers of 2
541             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
542                 // Powers of 2 minus 1
543                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
544             {
545                 return Err(WarningType::DecimalRepresentation);
546             }
547         } else {
548             // Lint for Literals with a hex-representation of 4 digits or more
549             let f = &digits[0..1]; // first digit
550             let m = &digits[1..digits.len() - 1]; // middle digits, except last
551             let s = &digits[1..]; // suffix
552
553             // Powers of 2 with a margin of +15/-16
554             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
555                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
556                 // Lint for representations with only 0s and Fs, while allowing 7 as the first
557                 // digit
558                 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
559             {
560                 return Err(WarningType::DecimalRepresentation);
561             }
562         }
563
564         Ok(())
565     }
566 }
567
568 #[must_use]
569 fn is_mistyped_suffix(suffix: &str) -> bool {
570     ["_8", "_16", "_32", "_64"].contains(&suffix)
571 }
572
573 #[must_use]
574 fn is_possible_suffix_index(lit: &str, idx: usize, len: usize) -> bool {
575     ((len > 3 && idx == len - 3) || (len > 2 && idx == len - 2)) && is_mistyped_suffix(lit.split_at(idx).1)
576 }
577
578 #[must_use]
579 fn is_mistyped_float_suffix(suffix: &str) -> bool {
580     ["_32", "_64"].contains(&suffix)
581 }
582
583 #[must_use]
584 fn is_possible_float_suffix_index(lit: &str, idx: usize, len: usize) -> bool {
585     (len > 3 && idx == len - 3) && is_mistyped_float_suffix(lit.split_at(idx).1)
586 }
587
588 #[must_use]
589 fn has_possible_float_suffix(lit: &str) -> bool {
590     lit.ends_with("_32") || lit.ends_with("_64")
591 }