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