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' || d == 'e' || d == 'E') {
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) {
289 LitKind::Int(..) => {
290 // Lint integral literals.
292 if let Some(src) = snippet_opt(cx, lit.span);
293 if let Some(firstch) = src.chars().next();
294 if char::to_digit(firstch, 10).is_some();
296 let digit_info = DigitInfo::new(&src, false);
297 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
298 warning_type.display(&digit_info.grouping_hint(), cx, &lit.span)
303 LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => {
304 // Lint floating-point literals.
306 if let Some(src) = snippet_opt(cx, lit.span);
307 if let Some(firstch) = src.chars().next();
308 if char::to_digit(firstch, 10).is_some();
310 let digit_info = DigitInfo::new(&src, true);
311 // Separate digits into integral and fractional parts.
312 let parts: Vec<&str> = digit_info
314 .split_terminator('.')
317 // Lint integral and fractional parts separately, and then check consistency of digit
318 // groups if both pass.
319 let _ = Self::do_lint(parts[0])
320 .map(|integral_group_size| {
322 // Lint the fractional part of literal just like integral part, but reversed.
323 let fractional_part = &parts[1].chars().rev().collect::<String>();
324 let _ = Self::do_lint(fractional_part)
325 .map(|fractional_group_size| {
326 let consistent = Self::parts_consistent(integral_group_size,
327 fractional_group_size,
331 WarningType::InconsistentDigitGrouping.display(&digit_info.grouping_hint(),
336 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(),
341 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(), cx, &lit.span));
349 /// Given the sizes of the digit groups of both integral and fractional
350 /// parts, and the length
351 /// of both parts, determine if the digits have been grouped consistently.
352 fn parts_consistent(int_group_size: usize, frac_group_size: usize, int_size: usize, frac_size: usize) -> bool {
353 match (int_group_size, frac_group_size) {
354 // No groups on either side of decimal point - trivially consistent.
356 // Integral part has grouped digits, fractional part does not.
357 (_, 0) => frac_size <= int_group_size,
358 // Fractional part has grouped digits, integral part does not.
359 (0, _) => int_size <= frac_group_size,
360 // Both parts have grouped digits. Groups should be the same size.
361 (_, _) => int_group_size == frac_group_size,
365 /// Performs lint on `digits` (no decimal point) and returns the group
366 /// size on success or `WarningType` when emitting a warning.
367 fn do_lint(digits: &str) -> Result<usize, WarningType> {
368 // Grab underscore indices with respect to the units digit.
369 let underscore_positions: Vec<usize> = digits
373 .filter_map(|(idx, digit)| if digit == '_' { Some(idx) } else { None })
376 if underscore_positions.is_empty() {
377 // Check if literal needs underscores.
378 if digits.len() > 5 {
379 Err(WarningType::UnreadableLiteral)
384 // Check consistency and the sizes of the groups.
385 let group_size = underscore_positions[0];
386 let consistent = underscore_positions
388 .all(|ps| ps[1] - ps[0] == group_size + 1)
389 // number of digits to the left of the last group cannot be bigger than group size.
390 && (digits.len() - underscore_positions.last()
391 .expect("there's at least one element") <= group_size + 1);
394 return Err(WarningType::InconsistentDigitGrouping);
395 } else if group_size > 4 {
396 return Err(WarningType::LargeDigitGroups);
403 #[derive(Copy, Clone)]
404 pub struct LiteralRepresentation {
408 impl LintPass for LiteralRepresentation {
409 fn get_lints(&self) -> LintArray {
410 lint_array!(DECIMAL_LITERAL_REPRESENTATION)
414 impl EarlyLintPass for LiteralRepresentation {
415 fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
416 if in_external_macro(cx, expr.span) {
420 if let ExprKind::Lit(ref lit) = expr.node {
421 self.check_lit(cx, lit)
426 impl LiteralRepresentation {
427 pub fn new(threshold: u64) -> Self {
429 threshold: threshold,
432 fn check_lit(&self, cx: &EarlyContext, lit: &Lit) {
433 // Lint integral literals.
435 if let LitKind::Int(..) = lit.node;
436 if let Some(src) = snippet_opt(cx, lit.span);
437 if let Some(firstch) = src.chars().next();
438 if char::to_digit(firstch, 10).is_some();
440 let digit_info = DigitInfo::new(&src, false);
441 if digit_info.radix == Radix::Decimal {
442 let val = digit_info.digits
444 .filter(|&c| c != '_')
446 .parse::<u128>().unwrap();
447 if val < self.threshold as u128 {
450 let hex = format!("{:#X}", val);
451 let digit_info = DigitInfo::new(&hex[..], false);
452 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
453 warning_type.display(&digit_info.grouping_hint(), cx, &lit.span)
460 fn do_lint(digits: &str) -> Result<(), WarningType> {
461 if digits.len() == 1 {
462 // Lint for 1 digit literals, if someone really sets the threshold that low
463 if digits == "1" || digits == "2" || digits == "4" || digits == "8" || digits == "3" || digits == "7"
466 return Err(WarningType::DecimalRepresentation);
468 } else if digits.len() < 4 {
469 // Lint for Literals with a hex-representation of 2 or 3 digits
470 let f = &digits[0..1]; // first digit
471 let s = &digits[1..]; // suffix
473 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
474 // Powers of 2 minus 1
475 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
477 return Err(WarningType::DecimalRepresentation);
480 // Lint for Literals with a hex-representation of 4 digits or more
481 let f = &digits[0..1]; // first digit
482 let m = &digits[1..digits.len() - 1]; // middle digits, except last
483 let s = &digits[1..]; // suffix
484 // Powers of 2 with a margin of +15/-16
485 if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
486 || ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
487 // Lint for representations with only 0s and Fs, while allowing 7 as the first
489 || ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
491 return Err(WarningType::DecimalRepresentation);