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