Skip to content

Commit 63a46b1

Browse files
authored
Merge pull request #3129 from mipli/3091-numeric-typo
Add lint for misstyped literal casting
2 parents cafef7b + 7bf8d8b commit 63a46b1

File tree

6 files changed

+150
-18
lines changed

6 files changed

+150
-18
lines changed

CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,7 @@ All notable changes to this project will be documented in this file.
645645
[`cmp_owned`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#cmp_owned
646646
[`collapsible_if`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#collapsible_if
647647
[`const_static_lifetime`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#const_static_lifetime
648+
[`copy_iterator`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#copy_iterator
648649
[`crosspointer_transmute`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#crosspointer_transmute
649650
[`cyclomatic_complexity`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#cyclomatic_complexity
650651
[`decimal_literal_representation`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#decimal_literal_representation
@@ -748,6 +749,7 @@ All notable changes to this project will be documented in this file.
748749
[`misrefactored_assign_op`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#misrefactored_assign_op
749750
[`missing_docs_in_private_items`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#missing_docs_in_private_items
750751
[`missing_inline_in_public_items`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#missing_inline_in_public_items
752+
[`mistyped_literal_suffixes`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#mistyped_literal_suffixes
751753
[`mixed_case_hex_literals`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#mixed_case_hex_literals
752754
[`module_inception`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#module_inception
753755
[`modulo_one`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#modulo_one
@@ -800,6 +802,7 @@ All notable changes to this project will be documented in this file.
800802
[`print_with_newline`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#print_with_newline
801803
[`println_empty_string`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#println_empty_string
802804
[`ptr_arg`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#ptr_arg
805+
[`ptr_offset_with_cast`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#ptr_offset_with_cast
803806
[`pub_enum_variant_names`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#pub_enum_variant_names
804807
[`question_mark`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#question_mark
805808
[`range_minus_one`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#range_minus_one

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ We are currently in the process of discussing Clippy 1.0 via the RFC process in
99

1010
A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.
1111

12-
[There are 273 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)
12+
[There are 275 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)
1313

1414
We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:
1515

clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -545,6 +545,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
545545
lifetimes::NEEDLESS_LIFETIMES,
546546
literal_representation::INCONSISTENT_DIGIT_GROUPING,
547547
literal_representation::LARGE_DIGIT_GROUPS,
548+
literal_representation::MISTYPED_LITERAL_SUFFIXES,
548549
literal_representation::UNREADABLE_LITERAL,
549550
loops::EMPTY_LOOP,
550551
loops::EXPLICIT_COUNTER_LOOP,
@@ -868,6 +869,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
868869
infinite_iter::INFINITE_ITER,
869870
inline_fn_without_body::INLINE_FN_WITHOUT_BODY,
870871
invalid_ref::INVALID_REF,
872+
literal_representation::MISTYPED_LITERAL_SUFFIXES,
871873
loops::FOR_LOOP_OVER_OPTION,
872874
loops::FOR_LOOP_OVER_RESULT,
873875
loops::ITER_NEXT_LOOP,

clippy_lints/src/literal_representation.rs

+74-16
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,26 @@ declare_clippy_lint! {
2626
"long integer literal without underscores"
2727
}
2828

29+
/// **What it does:** Warns for mistyped suffix in literals
30+
///
31+
/// **Why is this bad?** This is most probably a typo
32+
///
33+
/// **Known problems:**
34+
/// - Recommends a signed suffix, even though the number might be too big and an unsigned
35+
/// suffix is required
36+
/// - Does not match on `_128` since that is a valid grouping for decimal and octal numbers
37+
///
38+
/// **Example:**
39+
///
40+
/// ```rust
41+
/// 2_32
42+
/// ```
43+
declare_clippy_lint! {
44+
pub MISTYPED_LITERAL_SUFFIXES,
45+
correctness,
46+
"mistyped literal suffix"
47+
}
48+
2949
/// **What it does:** Warns if an integral or floating-point constant is
3050
/// grouped inconsistently with underscores.
3151
///
@@ -135,18 +155,24 @@ impl<'a> DigitInfo<'a> {
135155
(Some(p), s)
136156
};
137157

158+
let len = sans_prefix.len();
138159
let mut last_d = '\0';
139160
for (d_idx, d) in sans_prefix.char_indices() {
140-
if !float && (d == 'i' || d == 'u') || float && (d == 'f' || d == 'e' || d == 'E') {
141-
let suffix_start = if last_d == '_' { d_idx - 1 } else { d_idx };
142-
let (digits, suffix) = sans_prefix.split_at(suffix_start);
143-
return Self {
144-
digits,
145-
radix,
146-
prefix,
147-
suffix: Some(suffix),
148-
float,
149-
};
161+
let suffix_start = if last_d == '_' {
162+
d_idx - 1
163+
} else {
164+
d_idx
165+
};
166+
if float && (d == 'f' || d == 'e' || d == 'E') ||
167+
!float && (d == 'i' || d == 'u' || is_possible_suffix_index(&sans_prefix, suffix_start, len)) {
168+
let (digits, suffix) = sans_prefix.split_at(suffix_start);
169+
return Self {
170+
digits,
171+
radix,
172+
prefix,
173+
suffix: Some(suffix),
174+
float,
175+
};
150176
}
151177
last_d = d
152178
}
@@ -161,7 +187,7 @@ impl<'a> DigitInfo<'a> {
161187
}
162188
}
163189

164-
/// Returns digits grouped in a sensible way.
190+
/// Returns literal formatted in a sensible way.
165191
crate fn grouping_hint(&self) -> String {
166192
let group_size = self.radix.suggest_grouping();
167193
if self.digits.contains('.') {
@@ -211,11 +237,18 @@ impl<'a> DigitInfo<'a> {
211237
if self.radix == Radix::Hexadecimal && nb_digits_to_fill != 0 {
212238
hint = format!("{:0>4}{}", &hint[..nb_digits_to_fill], &hint[nb_digits_to_fill..]);
213239
}
240+
let suffix_hint = match self.suffix {
241+
Some(suffix) if is_mistyped_suffix(suffix) => {
242+
format!("_i{}", &suffix[1..])
243+
},
244+
Some(suffix) => suffix.to_string(),
245+
None => String::new()
246+
};
214247
format!(
215248
"{}{}{}",
216249
self.prefix.unwrap_or(""),
217250
hint,
218-
self.suffix.unwrap_or("")
251+
suffix_hint
219252
)
220253
}
221254
}
@@ -226,11 +259,22 @@ enum WarningType {
226259
InconsistentDigitGrouping,
227260
LargeDigitGroups,
228261
DecimalRepresentation,
262+
MistypedLiteralSuffix
229263
}
230264

231265
impl WarningType {
232266
crate fn display(&self, grouping_hint: &str, cx: &EarlyContext<'_>, span: syntax_pos::Span) {
233267
match self {
268+
WarningType::MistypedLiteralSuffix => {
269+
span_lint_and_sugg(
270+
cx,
271+
MISTYPED_LITERAL_SUFFIXES,
272+
span,
273+
"mistyped literal suffix",
274+
"did you mean to write",
275+
grouping_hint.to_string()
276+
)
277+
},
234278
WarningType::UnreadableLiteral => span_lint_and_sugg(
235279
cx,
236280
UNREADABLE_LITERAL,
@@ -303,7 +347,7 @@ impl LiteralDigitGrouping {
303347
if char::to_digit(firstch, 10).is_some();
304348
then {
305349
let digit_info = DigitInfo::new(&src, false);
306-
let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
350+
let _ = Self::do_lint(digit_info.digits, digit_info.suffix).map_err(|warning_type| {
307351
warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
308352
});
309353
}
@@ -325,12 +369,12 @@ impl LiteralDigitGrouping {
325369

326370
// Lint integral and fractional parts separately, and then check consistency of digit
327371
// groups if both pass.
328-
let _ = Self::do_lint(parts[0])
372+
let _ = Self::do_lint(parts[0], None)
329373
.map(|integral_group_size| {
330374
if parts.len() > 1 {
331375
// Lint the fractional part of literal just like integral part, but reversed.
332376
let fractional_part = &parts[1].chars().rev().collect::<String>();
333-
let _ = Self::do_lint(fractional_part)
377+
let _ = Self::do_lint(fractional_part, None)
334378
.map(|fractional_group_size| {
335379
let consistent = Self::parts_consistent(integral_group_size,
336380
fractional_group_size,
@@ -373,7 +417,12 @@ impl LiteralDigitGrouping {
373417

374418
/// Performs lint on `digits` (no decimal point) and returns the group
375419
/// size on success or `WarningType` when emitting a warning.
376-
fn do_lint(digits: &str) -> Result<usize, WarningType> {
420+
fn do_lint(digits: &str, suffix: Option<&str>) -> Result<usize, WarningType> {
421+
if let Some(suffix) = suffix {
422+
if is_mistyped_suffix(suffix) {
423+
return Err(WarningType::MistypedLiteralSuffix);
424+
}
425+
}
377426
// Grab underscore indices with respect to the units digit.
378427
let underscore_positions: Vec<usize> = digits
379428
.chars()
@@ -504,3 +553,12 @@ impl LiteralRepresentation {
504553
Ok(())
505554
}
506555
}
556+
557+
fn is_mistyped_suffix(suffix: &str) -> bool {
558+
["_8", "_16", "_32", "_64"].contains(&suffix)
559+
}
560+
561+
fn is_possible_suffix_index(lit: &str, idx: usize, len: usize) -> bool {
562+
((len > 3 && idx == len - 3) || (len > 2 && idx == len - 2)) &&
563+
is_mistyped_suffix(lit.split_at(idx).1)
564+
}

tests/ui/literals.rs

+11
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,15 @@ fn main() {
4343
let fail11 = 0xabcdeff;
4444
let fail12 = 0xabcabcabcabcabcabc;
4545
let fail13 = 0x1_23456_78901_usize;
46+
47+
let fail14 = 2_32;
48+
let fail15 = 4_64;
49+
let fail16 = 7_8;
50+
let fail17 = 23_16;
51+
let ok18 = 23_128;
52+
let fail19 = 12_3456_21;
53+
let fail20 = 2__8;
54+
let fail21 = 4___16;
55+
let fail22 = 3__4___23;
56+
let fail23 = 3__16___23;
4657
}

tests/ui/literals.stderr

+59-1
Original file line numberDiff line numberDiff line change
@@ -120,5 +120,63 @@ error: digit groups should be smaller
120120
|
121121
= note: `-D clippy::large-digit-groups` implied by `-D warnings`
122122

123-
error: aborting due to 16 previous errors
123+
error: mistyped literal suffix
124+
--> $DIR/literals.rs:47:18
125+
|
126+
47 | let fail14 = 2_32;
127+
| ^^^^ help: did you mean to write: `2_i32`
128+
|
129+
= note: #[deny(clippy::mistyped_literal_suffixes)] on by default
130+
131+
error: mistyped literal suffix
132+
--> $DIR/literals.rs:48:18
133+
|
134+
48 | let fail15 = 4_64;
135+
| ^^^^ help: did you mean to write: `4_i64`
136+
137+
error: mistyped literal suffix
138+
--> $DIR/literals.rs:49:18
139+
|
140+
49 | let fail16 = 7_8;
141+
| ^^^ help: did you mean to write: `7_i8`
142+
143+
error: mistyped literal suffix
144+
--> $DIR/literals.rs:50:18
145+
|
146+
50 | let fail17 = 23_16;
147+
| ^^^^^ help: did you mean to write: `23_i16`
148+
149+
error: digits grouped inconsistently by underscores
150+
--> $DIR/literals.rs:52:18
151+
|
152+
52 | let fail19 = 12_3456_21;
153+
| ^^^^^^^^^^ help: consider: `12_345_621`
154+
|
155+
= note: `-D clippy::inconsistent-digit-grouping` implied by `-D warnings`
156+
157+
error: mistyped literal suffix
158+
--> $DIR/literals.rs:53:18
159+
|
160+
53 | let fail20 = 2__8;
161+
| ^^^^ help: did you mean to write: `2_i8`
162+
163+
error: mistyped literal suffix
164+
--> $DIR/literals.rs:54:18
165+
|
166+
54 | let fail21 = 4___16;
167+
| ^^^^^^ help: did you mean to write: `4_i16`
168+
169+
error: digits grouped inconsistently by underscores
170+
--> $DIR/literals.rs:55:18
171+
|
172+
55 | let fail22 = 3__4___23;
173+
| ^^^^^^^^^ help: consider: `3_423`
174+
175+
error: digits grouped inconsistently by underscores
176+
--> $DIR/literals.rs:56:18
177+
|
178+
56 | let fail23 = 3__16___23;
179+
| ^^^^^^^^^^ help: consider: `31_623`
180+
181+
error: aborting due to 25 previous errors
124182

0 commit comments

Comments
 (0)