]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/literal_representation.rs
Lint for numeric literals that have a better representation in another format
[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 utils::{in_external_macro, snippet_opt, span_help_and_lint};
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_lint! {
22     pub UNREADABLE_LITERAL,
23     Warn,
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_lint! {
41     pub INCONSISTENT_DIGIT_GROUPING,
42     Warn,
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_lint! {
60     pub LARGE_DIGIT_GROUPS,
61     Warn,
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_lint! {
78     pub BAD_LITERAL_REPRESENTATION,
79     Warn,
80     "using decimal representation when hexadecimal would be better"
81 }
82
83 #[derive(Debug, PartialEq)]
84 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     pub 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 struct DigitInfo<'a> {
103     /// Characters of a literal between the radix prefix and type suffix.
104     pub digits: &'a str,
105     /// Which radix the literal was represented in.
106     pub radix: Radix,
107     /// The radix prefix, if present.
108     pub prefix: Option<&'a str>,
109     /// The type suffix, including preceding underscore if present.
110     pub suffix: Option<&'a str>,
111     /// True for floating-point literals.
112     pub float: bool,
113 }
114
115 impl<'a> DigitInfo<'a> {
116     pub 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' {
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: digits,
143                     radix: radix,
144                     prefix: prefix,
145                     suffix: Some(suffix),
146                     float: float,
147                 };
148             }
149             last_d = d
150         }
151
152         // No suffix found
153         Self {
154             digits: sans_prefix,
155             radix: radix,
156             prefix: prefix,
157             suffix: None,
158             float: float,
159         }
160     }
161
162     /// Returns digits grouped in a sensible way.
163     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 hint = self.digits
197                 .chars()
198                 .rev()
199                 .filter(|&c| c != '_')
200                 .collect::<Vec<_>>()
201                 .chunks(group_size)
202                 .map(|chunk| chunk.into_iter().rev().collect())
203                 .rev()
204                 .collect::<Vec<String>>()
205                 .join("_");
206             format!(
207                 "{}{}{}",
208                 self.prefix.unwrap_or(""),
209                 hint,
210                 self.suffix.unwrap_or("")
211             )
212         }
213     }
214 }
215
216 enum WarningType {
217     UnreadableLiteral,
218     InconsistentDigitGrouping,
219     LargeDigitGroups,
220     BadRepresentation,
221 }
222
223 impl WarningType {
224     pub fn display(&self, grouping_hint: &str, cx: &EarlyContext, span: &syntax_pos::Span) {
225         match *self {
226             WarningType::UnreadableLiteral => span_help_and_lint(
227                 cx,
228                 UNREADABLE_LITERAL,
229                 *span,
230                 "long literal lacking separators",
231                 &format!("consider: {}", grouping_hint),
232             ),
233             WarningType::LargeDigitGroups => span_help_and_lint(
234                 cx,
235                 LARGE_DIGIT_GROUPS,
236                 *span,
237                 "digit groups should be smaller",
238                 &format!("consider: {}", grouping_hint),
239             ),
240             WarningType::InconsistentDigitGrouping => span_help_and_lint(
241                 cx,
242                 INCONSISTENT_DIGIT_GROUPING,
243                 *span,
244                 "digits grouped inconsistently by underscores",
245                 &format!("consider: {}", grouping_hint),
246             ),
247             WarningType::BadRepresentation => span_help_and_lint(
248                 cx,
249                 BAD_LITERAL_REPRESENTATION,
250                 *span,
251                 "bad representation of integer literal",
252                 &format!("consider: {}", grouping_hint),
253             ),
254         };
255     }
256 }
257
258 #[derive(Copy, Clone)]
259 pub struct LiteralDigitGrouping;
260
261 impl LintPass for LiteralDigitGrouping {
262     fn get_lints(&self) -> LintArray {
263         lint_array!(
264             UNREADABLE_LITERAL,
265             INCONSISTENT_DIGIT_GROUPING,
266             LARGE_DIGIT_GROUPS
267         )
268     }
269 }
270
271 impl EarlyLintPass for LiteralDigitGrouping {
272     fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
273         if in_external_macro(cx, expr.span) {
274             return;
275         }
276
277         if let ExprKind::Lit(ref lit) = expr.node {
278             self.check_lit(cx, lit)
279         }
280     }
281 }
282
283 impl LiteralDigitGrouping {
284     fn check_lit(&self, cx: &EarlyContext, lit: &Lit) {
285         // Lint integral literals.
286         if_chain! {
287             if let LitKind::Int(..) = lit.node;
288             if let Some(src) = snippet_opt(cx, lit.span);
289             if let Some(firstch) = src.chars().next();
290             if char::to_digit(firstch, 10).is_some();
291             then {
292                 let digit_info = DigitInfo::new(&src, false);
293                 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
294                     warning_type.display(&digit_info.grouping_hint(), cx, &lit.span)
295                 });
296             }
297         }
298
299         // Lint floating-point literals.
300         if_chain! {
301             if let LitKind::Float(..) = lit.node;
302             if let Some(src) = snippet_opt(cx, lit.span);
303             if let Some(firstch) = src.chars().next();
304             if char::to_digit(firstch, 10).is_some();
305             then {
306                 let digit_info = DigitInfo::new(&src, true);
307                 // Separate digits into integral and fractional parts.
308                 let parts: Vec<&str> = digit_info
309                     .digits
310                     .split_terminator('.')
311                     .collect();
312
313                 // Lint integral and fractional parts separately, and then check consistency of digit
314                 // groups if both pass.
315                 let _ = Self::do_lint(parts[0])
316                     .map(|integral_group_size| {
317                         if parts.len() > 1 {
318                             // Lint the fractional part of literal just like integral part, but reversed.
319                             let fractional_part = &parts[1].chars().rev().collect::<String>();
320                             let _ = Self::do_lint(fractional_part)
321                                 .map(|fractional_group_size| {
322                                     let consistent = Self::parts_consistent(integral_group_size,
323                                                                             fractional_group_size,
324                                                                             parts[0].len(),
325                                                                             parts[1].len());
326                                     if !consistent {
327                                         WarningType::InconsistentDigitGrouping.display(&digit_info.grouping_hint(),
328                                                                                        cx,
329                                                                                        &lit.span);
330                                     }
331                                 })
332                                 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(),
333                                                                              cx,
334                                                                              &lit.span));
335                         }
336                     })
337                     .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(), cx, &lit.span));
338             }
339         }
340     }
341
342     /// Given the sizes of the digit groups of both integral and fractional
343     /// parts, and the length
344     /// of both parts, determine if the digits have been grouped consistently.
345     fn parts_consistent(int_group_size: usize, frac_group_size: usize, int_size: usize, frac_size: usize) -> bool {
346         match (int_group_size, frac_group_size) {
347             // No groups on either side of decimal point - trivially consistent.
348             (0, 0) => true,
349             // Integral part has grouped digits, fractional part does not.
350             (_, 0) => frac_size <= int_group_size,
351             // Fractional part has grouped digits, integral part does not.
352             (0, _) => int_size <= frac_group_size,
353             // Both parts have grouped digits. Groups should be the same size.
354             (_, _) => int_group_size == frac_group_size,
355         }
356     }
357
358     /// Performs lint on `digits` (no decimal point) and returns the group
359     /// size on success or `WarningType` when emitting a warning.
360     fn do_lint(digits: &str) -> Result<usize, WarningType> {
361         // Grab underscore indices with respect to the units digit.
362         let underscore_positions: Vec<usize> = digits
363             .chars()
364             .rev()
365             .enumerate()
366             .filter_map(|(idx, digit)| if digit == '_' { Some(idx) } else { None })
367             .collect();
368
369         if underscore_positions.is_empty() {
370             // Check if literal needs underscores.
371             if digits.len() > 4 {
372                 Err(WarningType::UnreadableLiteral)
373             } else {
374                 Ok(0)
375             }
376         } else {
377             // Check consistency and the sizes of the groups.
378             let group_size = underscore_positions[0];
379             let consistent = underscore_positions
380                 .windows(2)
381                 .all(|ps| ps[1] - ps[0] == group_size + 1)
382                 // number of digits to the left of the last group cannot be bigger than group size.
383                 && (digits.len() - underscore_positions.last()
384                                                        .expect("there's at least one element") <= group_size + 1);
385
386             if !consistent {
387                 return Err(WarningType::InconsistentDigitGrouping);
388             } else if group_size > 4 {
389                 return Err(WarningType::LargeDigitGroups);
390             }
391             Ok(group_size)
392         }
393     }
394 }
395
396 #[derive(Copy, Clone)]
397 pub struct LiteralRepresentation;
398
399 impl LintPass for LiteralRepresentation {
400     fn get_lints(&self) -> LintArray {
401         lint_array!(BAD_LITERAL_REPRESENTATION)
402     }
403 }
404
405 impl EarlyLintPass for LiteralRepresentation {
406     fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
407         if in_external_macro(cx, expr.span) {
408             return;
409         }
410
411         if let ExprKind::Lit(ref lit) = expr.node {
412             self.check_lit(cx, lit)
413         }
414     }
415 }
416
417 impl LiteralRepresentation {
418     fn check_lit(&self, cx: &EarlyContext, lit: &Lit) {
419         // Lint integral literals.
420         if_chain! {
421             if let LitKind::Int(..) = lit.node;
422             if let Some(src) = snippet_opt(cx, lit.span);
423             if let Some(firstch) = src.chars().next();
424             if char::to_digit(firstch, 10).is_some();
425             then {
426                 let digit_info = DigitInfo::new(&src, false);
427                 if digit_info.radix == Radix::Decimal {
428                     let hex = format!("{:#X}", digit_info.digits
429                                                             .chars()
430                                                             .filter(|&c| c != '_')
431                                                             .collect::<String>()
432                                                             .parse::<u128>().unwrap());
433                     let digit_info = DigitInfo::new(&hex[..], false);
434                     let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
435                         warning_type.display(&digit_info.grouping_hint(), cx, &lit.span)
436                     });
437                 }
438             }
439         }
440     }
441
442     fn do_lint(digits: &str) -> Result<(), WarningType> {
443         if digits.len() == 2 && digits == "FF" {
444             return Err(WarningType::BadRepresentation);
445         } else if digits.len() == 3 {
446             // Lint for Literals with a hex-representation of 3 digits
447             let f = &digits[0..1]; // first digit
448             let s = &digits[1..]; // suffix
449                                   // Powers of 2 minus 1
450             if (f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.eq("FF") {
451                 return Err(WarningType::BadRepresentation);
452             }
453         } else if digits.len() > 3 {
454             // Lint for Literals with a hex-representation of 4 digits or more
455             let f = &digits[0..1]; // first digit
456             let m = &digits[1..digits.len() - 1]; // middle digits, except last
457             let s = &digits[1..]; // suffix
458                                   // Powers of 2 with a margin of +15/-16
459             if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
460                 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
461                 // Lint for representations with only 0s and Fs, while allowing 7 as the first
462                 // digit
463                 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
464             {
465                 return Err(WarningType::BadRepresentation);
466             }
467         }
468
469         Ok(())
470     }
471 }