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