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_help_and_lint};
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"
74 /// Return a reasonable digit group size for this radix.
75 pub fn suggest_grouping(&self) -> usize {
77 Radix::Binary | Radix::Hexadecimal => 4,
78 Radix::Octal | Radix::Decimal => 3,
84 struct DigitInfo<'a> {
85 /// Characters of a literal between the radix prefix and type suffix.
87 /// Which radix the literal was represented in.
89 /// The radix prefix, if present.
90 pub prefix: Option<&'a str>,
91 /// The type suffix, including preceding underscore if present.
92 pub suffix: Option<&'a str>,
93 /// True for floating-point literals.
97 impl<'a> DigitInfo<'a> {
98 pub fn new(lit: &'a str, float: bool) -> Self {
99 // Determine delimiter for radix prefix, if present, and radix.
100 let radix = if lit.starts_with("0x") {
102 } else if lit.starts_with("0b") {
104 } else if lit.starts_with("0o") {
110 // Grab part of the literal after prefix, if present.
111 let (prefix, sans_prefix) = if let Radix::Decimal = radix {
114 let (p, s) = lit.split_at(2);
118 let mut last_d = '\0';
119 for (d_idx, d) in sans_prefix.char_indices() {
120 if !float && (d == 'i' || d == 'u') || float && d == 'f' {
121 let suffix_start = if last_d == '_' { d_idx - 1 } else { d_idx };
122 let (digits, suffix) = sans_prefix.split_at(suffix_start);
127 suffix: Some(suffix),
144 /// Returns digits grouped in a sensible way.
145 fn grouping_hint(&self) -> String {
146 let group_size = self.radix.suggest_grouping();
147 if self.digits.contains('.') {
148 let mut parts = self.digits.split('.');
149 let int_part_hint = parts
151 .expect("split always returns at least one element")
154 .filter(|&c| c != '_')
157 .map(|chunk| chunk.into_iter().rev().collect())
159 .collect::<Vec<String>>()
161 let frac_part_hint = parts
163 .expect("already checked that there is a `.`")
165 .filter(|&c| c != '_')
168 .map(|chunk| chunk.into_iter().collect())
169 .collect::<Vec<String>>()
171 format!("{}.{}{}", int_part_hint, frac_part_hint, self.suffix.unwrap_or(""))
173 let hint = self.digits
176 .filter(|&c| c != '_')
179 .map(|chunk| chunk.into_iter().rev().collect())
181 .collect::<Vec<String>>()
183 format!("{}{}{}", self.prefix.unwrap_or(""), hint, self.suffix.unwrap_or(""))
190 InconsistentDigitGrouping,
196 pub fn display(&self, grouping_hint: &str, cx: &EarlyContext, span: &syntax_pos::Span) {
198 WarningType::UnreadableLiteral => span_help_and_lint(
202 "long literal lacking separators",
203 &format!("consider: {}", grouping_hint),
205 WarningType::LargeDigitGroups => span_help_and_lint(
209 "digit groups should be smaller",
210 &format!("consider: {}", grouping_hint),
212 WarningType::InconsistentDigitGrouping => span_help_and_lint(
214 INCONSISTENT_DIGIT_GROUPING,
216 "digits grouped inconsistently by underscores",
217 &format!("consider: {}", grouping_hint),
223 #[derive(Copy, Clone)]
224 pub struct LiteralDigitGrouping;
226 impl LintPass for LiteralDigitGrouping {
227 fn get_lints(&self) -> LintArray {
228 lint_array!(UNREADABLE_LITERAL, INCONSISTENT_DIGIT_GROUPING, LARGE_DIGIT_GROUPS)
232 impl EarlyLintPass for LiteralDigitGrouping {
233 fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
234 if in_external_macro(cx, expr.span) {
238 if let ExprKind::Lit(ref lit) = expr.node {
239 self.check_lit(cx, lit)
244 impl LiteralDigitGrouping {
245 fn check_lit(&self, cx: &EarlyContext, lit: &Lit) {
246 // Lint integral literals.
248 if let LitKind::Int(..) = lit.node;
249 if let Some(src) = snippet_opt(cx, lit.span);
250 if let Some(firstch) = src.chars().next();
251 if char::to_digit(firstch, 10).is_some();
253 let digit_info = DigitInfo::new(&src, false);
254 let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
255 warning_type.display(&digit_info.grouping_hint(), cx, &lit.span)
260 // Lint floating-point literals.
262 if let LitKind::Float(..) = lit.node;
263 if let Some(src) = snippet_opt(cx, lit.span);
264 if let Some(firstch) = src.chars().next();
265 if char::to_digit(firstch, 10).is_some();
267 let digit_info = DigitInfo::new(&src, true);
268 // Separate digits into integral and fractional parts.
269 let parts: Vec<&str> = digit_info
271 .split_terminator('.')
274 // Lint integral and fractional parts separately, and then check consistency of digit
275 // groups if both pass.
276 let _ = Self::do_lint(parts[0])
277 .map(|integral_group_size| {
279 // Lint the fractional part of literal just like integral part, but reversed.
280 let fractional_part = &parts[1].chars().rev().collect::<String>();
281 let _ = Self::do_lint(fractional_part)
282 .map(|fractional_group_size| {
283 let consistent = Self::parts_consistent(integral_group_size,
284 fractional_group_size,
288 WarningType::InconsistentDigitGrouping.display(&digit_info.grouping_hint(),
293 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(),
298 .map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(), cx, &lit.span));
303 /// Given the sizes of the digit groups of both integral and fractional
304 /// parts, and the length
305 /// of both parts, determine if the digits have been grouped consistently.
306 fn parts_consistent(int_group_size: usize, frac_group_size: usize, int_size: usize, frac_size: usize) -> bool {
307 match (int_group_size, frac_group_size) {
308 // No groups on either side of decimal point - trivially consistent.
310 // Integral part has grouped digits, fractional part does not.
311 (_, 0) => frac_size <= int_group_size,
312 // Fractional part has grouped digits, integral part does not.
313 (0, _) => int_size <= frac_group_size,
314 // Both parts have grouped digits. Groups should be the same size.
315 (_, _) => int_group_size == frac_group_size,
319 /// Performs lint on `digits` (no decimal point) and returns the group
320 /// size on success or `WarningType` when emitting a warning.
321 fn do_lint(digits: &str) -> Result<usize, WarningType> {
322 // Grab underscore indices with respect to the units digit.
323 let underscore_positions: Vec<usize> = digits
327 .filter_map(|(idx, digit)| if digit == '_' { Some(idx) } else { None })
330 if underscore_positions.is_empty() {
331 // Check if literal needs underscores.
332 if digits.len() > 4 {
333 Err(WarningType::UnreadableLiteral)
338 // Check consistency and the sizes of the groups.
339 let group_size = underscore_positions[0];
340 let consistent = underscore_positions
342 .all(|ps| ps[1] - ps[0] == group_size + 1)
343 // number of digits to the left of the last group cannot be bigger than group size.
344 && (digits.len() - underscore_positions.last()
345 .expect("there's at least one element") <= group_size + 1);
348 return Err(WarningType::InconsistentDigitGrouping);
349 } else if group_size > 4 {
350 return Err(WarningType::LargeDigitGroups);