1 //! Lints concerned with the grouping of digits with underscores in integral or
2 //! floating-point literal expressions.
7 use utils::{in_external_macro, snippet_opt, span_lint_and_sugg};
9 /// **What it does:** Warns if a long integral or floating-point constant does
10 /// not contain underscores.
12 /// **Why is this bad?** Reading long numbers is difficult without separators.
14 /// **Known problems:** None.
22 pub UNREADABLE_LITERAL,
24 "long integer literal without underscores"
27 /// **What it does:** Warns if an integral or floating-point constant is
28 /// grouped inconsistently with underscores.
30 /// **Why is this bad?** Readers may incorrectly interpret inconsistently
33 /// **Known problems:** None.
38 /// 618_64_9189_73_511
41 pub INCONSISTENT_DIGIT_GROUPING,
43 "integer literals with digits grouped inconsistently"
46 /// **What it does:** Warns if the digits of an integral or floating-point
47 /// constant are grouped into groups that
50 /// **Why is this bad?** Negatively impacts readability.
52 /// **Known problems:** None.
60 pub LARGE_DIGIT_GROUPS,
62 "grouping digits into groups that are too large"
65 /// **What it does:** Warns if there is a better representation for a numeric literal.
67 /// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
68 /// readable than a decimal representation.
70 /// **Known problems:** None.
75 /// `65_535` => `0xFFFF`
76 /// `4_042_322_160` => `0xF0F0_F0F0`
77 declare_restriction_lint! {
78 pub DECIMAL_LITERAL_REPRESENTATION,
79 "using decimal representation when hexadecimal would be better"
82 #[derive(Debug, PartialEq)]
91 /// Return a reasonable digit group size for this radix.
92 pub fn suggest_grouping(&self) -> usize {
94 Radix::Binary | Radix::Hexadecimal => 4,
95 Radix::Octal | Radix::Decimal => 3,
101 struct DigitInfo<'a> {
102 /// Characters of a literal between the radix prefix and type suffix.
104 /// Which radix the literal was represented in.
106 /// The radix prefix, if present.
107 pub prefix: Option<&'a str>,
108 /// The type suffix, including preceding underscore if present.
109 pub suffix: Option<&'a str>,
110 /// True for floating-point literals.
114 impl<'a> DigitInfo<'a> {
115 pub fn new(lit: &'a str, float: bool) -> Self {
116 // Determine delimiter for radix prefix, if present, and radix.
117 let radix = if lit.starts_with("0x") {
119 } else if lit.starts_with("0b") {
121 } else if lit.starts_with("0o") {
127 // Grab part of the literal after prefix, if present.
128 let (prefix, sans_prefix) = if let Radix::Decimal = radix {
131 let (p, s) = lit.split_at(2);
135 let mut last_d = '\0';
136 for (d_idx, d) in sans_prefix.char_indices() {
137 if !float && (d == 'i' || d == 'u') || float && d == 'f' {
138 let suffix_start = if last_d == '_' { d_idx - 1 } else { d_idx };
139 let (digits, suffix) = sans_prefix.split_at(suffix_start);
144 suffix: Some(suffix),
161 /// Returns digits grouped in a sensible way.
162 fn grouping_hint(&self) -> String {
163 let group_size = self.radix.suggest_grouping();
164 if self.digits.contains('.') {
165 let mut parts = self.digits.split('.');
166 let int_part_hint = parts
168 .expect("split always returns at least one element")
171 .filter(|&c| c != '_')
174 .map(|chunk| chunk.into_iter().rev().collect())
176 .collect::<Vec<String>>()
178 let frac_part_hint = parts
180 .expect("already checked that there is a `.`")
182 .filter(|&c| c != '_')
185 .map(|chunk| chunk.into_iter().collect())
186 .collect::<Vec<String>>()
192 self.suffix.unwrap_or("")
195 let hint = self.digits
198 .filter(|&c| c != '_')
201 .map(|chunk| chunk.into_iter().rev().collect())
203 .collect::<Vec<String>>()
207 self.prefix.unwrap_or(""),
209 self.suffix.unwrap_or("")
217 InconsistentDigitGrouping,
219 DecimalRepresentation,
223 pub fn display(&self, grouping_hint: &str, cx: &EarlyContext, span: &syntax_pos::Span) {
225 WarningType::UnreadableLiteral => span_lint_and_sugg(
229 "long literal lacking separators",
231 grouping_hint.to_owned(),
233 WarningType::LargeDigitGroups => span_lint_and_sugg(
237 "digit groups should be smaller",
239 grouping_hint.to_owned(),
241 WarningType::InconsistentDigitGrouping => span_lint_and_sugg(
243 INCONSISTENT_DIGIT_GROUPING,
245 "digits grouped inconsistently by underscores",
247 grouping_hint.to_owned(),
249 WarningType::DecimalRepresentation => span_lint_and_sugg(
251 DECIMAL_LITERAL_REPRESENTATION,
253 "integer literal has a better hexadecimal representation",
255 grouping_hint.to_owned(),
261 #[derive(Copy, Clone)]
262 pub struct LiteralDigitGrouping;
264 impl LintPass for LiteralDigitGrouping {
265 fn get_lints(&self) -> LintArray {
268 INCONSISTENT_DIGIT_GROUPING,
274 impl EarlyLintPass for LiteralDigitGrouping {
275 fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
276 if in_external_macro(cx, expr.span) {
280 if let ExprKind::Lit(ref lit) = expr.node {
281 self.check_lit(cx, lit)
286 impl LiteralDigitGrouping {
287 fn check_lit(&self, cx: &EarlyContext, lit: &Lit) {
288 // Lint integral literals.
290 if let LitKind::Int(..) = lit.node;
291 if let Some(src) = snippet_opt(cx, lit.span);
292 if let Some(firstch) = src.chars().next();
293 if char::to_digit(firstch, 10).is_some();
295 let digit_info = DigitInfo::new(&src, false);
296 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
297 warning_type.display(&digit_info.grouping_hint(), cx, &lit.span)
302 // Lint floating-point literals.
304 if let LitKind::Float(..) = lit.node;
305 if let Some(src) = snippet_opt(cx, lit.span);
306 if let Some(firstch) = src.chars().next();
307 if char::to_digit(firstch, 10).is_some();
309 let digit_info = DigitInfo::new(&src, true);
310 // Separate digits into integral and fractional parts.
311 let parts: Vec<&str> = digit_info
313 .split_terminator('.')
316 // Lint integral and fractional parts separately, and then check consistency of digit
317 // groups if both pass.
318 let _ = Self::do_lint(parts[0])
319 .map(|integral_group_size| {
321 // Lint the fractional part of literal just like integral part, but reversed.
322 let fractional_part = &parts[1].chars().rev().collect::<String>();
323 let _ = Self::do_lint(fractional_part)
324 .map(|fractional_group_size| {
325 let consistent = Self::parts_consistent(integral_group_size,
326 fractional_group_size,
330 WarningType::InconsistentDigitGrouping.display(&digit_info.grouping_hint(),
335 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(),
340 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(), cx, &lit.span));
345 /// Given the sizes of the digit groups of both integral and fractional
346 /// parts, and the length
347 /// of both parts, determine if the digits have been grouped consistently.
348 fn parts_consistent(int_group_size: usize, frac_group_size: usize, int_size: usize, frac_size: usize) -> bool {
349 match (int_group_size, frac_group_size) {
350 // No groups on either side of decimal point - trivially consistent.
352 // Integral part has grouped digits, fractional part does not.
353 (_, 0) => frac_size <= int_group_size,
354 // Fractional part has grouped digits, integral part does not.
355 (0, _) => int_size <= frac_group_size,
356 // Both parts have grouped digits. Groups should be the same size.
357 (_, _) => int_group_size == frac_group_size,
361 /// Performs lint on `digits` (no decimal point) and returns the group
362 /// size on success or `WarningType` when emitting a warning.
363 fn do_lint(digits: &str) -> Result<usize, WarningType> {
364 // Grab underscore indices with respect to the units digit.
365 let underscore_positions: Vec<usize> = digits
369 .filter_map(|(idx, digit)| if digit == '_' { Some(idx) } else { None })
372 if underscore_positions.is_empty() {
373 // Check if literal needs underscores.
374 if digits.len() > 4 {
375 Err(WarningType::UnreadableLiteral)
380 // Check consistency and the sizes of the groups.
381 let group_size = underscore_positions[0];
382 let consistent = underscore_positions
384 .all(|ps| ps[1] - ps[0] == group_size + 1)
385 // number of digits to the left of the last group cannot be bigger than group size.
386 && (digits.len() - underscore_positions.last()
387 .expect("there's at least one element") <= group_size + 1);
390 return Err(WarningType::InconsistentDigitGrouping);
391 } else if group_size > 4 {
392 return Err(WarningType::LargeDigitGroups);
399 #[derive(Copy, Clone)]
400 pub struct LiteralRepresentation {
404 impl LintPass for LiteralRepresentation {
405 fn get_lints(&self) -> LintArray {
406 lint_array!(DECIMAL_LITERAL_REPRESENTATION)
410 impl EarlyLintPass for LiteralRepresentation {
411 fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
412 if in_external_macro(cx, expr.span) {
416 if let ExprKind::Lit(ref lit) = expr.node {
417 self.check_lit(cx, lit)
422 impl LiteralRepresentation {
423 pub fn new(threshold: u64) -> Self {
425 threshold: threshold,
428 fn check_lit(&self, cx: &EarlyContext, lit: &Lit) {
429 // Lint integral literals.
431 if let LitKind::Int(..) = lit.node;
432 if let Some(src) = snippet_opt(cx, lit.span);
433 if let Some(firstch) = src.chars().next();
434 if char::to_digit(firstch, 10).is_some();
436 let digit_info = DigitInfo::new(&src, false);
437 if digit_info.radix == Radix::Decimal {
438 let val = digit_info.digits
440 .filter(|&c| c != '_')
442 .parse::<u128>().unwrap();
443 if val < self.threshold as u128 {
446 let hex = format!("{:#X}", val);
447 let digit_info = DigitInfo::new(&hex[..], false);
448 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
449 warning_type.display(&digit_info.grouping_hint(), cx, &lit.span)
456 fn do_lint(digits: &str) -> Result<(), WarningType> {
457 if digits.len() == 1 {
458 // Lint for 1 digit literals, if someone really sets the threshold that low
459 if digits == "1" || digits == "2" || digits == "4" || digits == "8" || digits == "3" || digits == "7"
462 return Err(WarningType::DecimalRepresentation);
464 } else if digits.len() < 4 {
465 // Lint for Literals with a hex-representation of 2 or 3 digits
466 let f = &digits[0..1]; // first digit
467 let s = &digits[1..]; // suffix
469 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
470 // Powers of 2 minus 1
471 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
473 return Err(WarningType::DecimalRepresentation);
476 // Lint for Literals with a hex-representation of 4 digits or more
477 let f = &digits[0..1]; // first digit
478 let m = &digits[1..digits.len() - 1]; // middle digits, except last
479 let s = &digits[1..]; // suffix
480 // Powers of 2 with a margin of +15/-16
481 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
482 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
483 // Lint for representations with only 0s and Fs, while allowing 7 as the first
485 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
487 return Err(WarningType::DecimalRepresentation);