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