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