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