Skip to content

Commit 20fec19

Browse files
author
Michael A. Plikk
committed
Add lint for misstyped literal casting
1 parent 131c8f8 commit 20fec19

File tree

6 files changed

+74
-8
lines changed

6 files changed

+74
-8
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
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

Lines changed: 1 addition & 1 deletion
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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -543,6 +543,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
543543
lifetimes::NEEDLESS_LIFETIMES,
544544
literal_representation::INCONSISTENT_DIGIT_GROUPING,
545545
literal_representation::LARGE_DIGIT_GROUPS,
546+
literal_representation::MISTYPED_LITERAL_SUFFIXES,
546547
literal_representation::UNREADABLE_LITERAL,
547548
loops::EMPTY_LOOP,
548549
loops::EXPLICIT_COUNTER_LOOP,
@@ -869,6 +870,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
869870
infinite_iter::INFINITE_ITER,
870871
inline_fn_without_body::INLINE_FN_WITHOUT_BODY,
871872
invalid_ref::INVALID_REF,
873+
literal_representation::MISTYPED_LITERAL_SUFFIXES,
872874
loops::FOR_LOOP_OVER_OPTION,
873875
loops::FOR_LOOP_OVER_RESULT,
874876
loops::ITER_NEXT_LOOP,

clippy_lints/src/literal_representation.rs

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,24 @@ 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:** Recommends unsigned suffix even if it's a negative number. Should only
34+
/// recommend the signed suffix on those cases.
35+
///
36+
/// **Example:**
37+
///
38+
/// ```rust
39+
/// 2_32
40+
/// ```
41+
declare_clippy_lint! {
42+
pub MISTYPED_LITERAL_SUFFIXES,
43+
correctness,
44+
"mistyped literal suffix"
45+
}
46+
2947
/// **What it does:** Warns if an integral or floating-point constant is
3048
/// grouped inconsistently with underscores.
3149
///
@@ -136,8 +154,11 @@ impl<'a> DigitInfo<'a> {
136154
};
137155

138156
let mut last_d = '\0';
157+
let len = sans_prefix.len();
139158
for (d_idx, d) in sans_prefix.char_indices() {
140-
if !float && (d == 'i' || d == 'u') || float && (d == 'f' || d == 'e' || d == 'E') {
159+
if !float && (d == 'i' || d == 'u') ||
160+
float && (d == 'f' || d == 'e' || d == 'E') ||
161+
(!float && d == '_' && (d_idx == len -3 || d_idx == len - 2)) {
141162
let suffix_start = if last_d == '_' { d_idx - 1 } else { d_idx };
142163
let (digits, suffix) = sans_prefix.split_at(suffix_start);
143164
return Self {
@@ -211,11 +232,18 @@ impl<'a> DigitInfo<'a> {
211232
if self.radix == Radix::Hexadecimal && nb_digits_to_fill != 0 {
212233
hint = format!("{:0>4}{}", &hint[..nb_digits_to_fill], &hint[nb_digits_to_fill..]);
213234
}
235+
let suffix_hint = match self.suffix {
236+
Some(suffix) if suffix == "_32" || suffix == "_64" => {
237+
format!("_i{}` or `{}_u{}", &suffix[1..], hint, &suffix[1..])
238+
},
239+
Some(suffix) => suffix.to_string(),
240+
None => String::new()
241+
};
214242
format!(
215243
"{}{}{}",
216244
self.prefix.unwrap_or(""),
217245
hint,
218-
self.suffix.unwrap_or("")
246+
suffix_hint
219247
)
220248
}
221249
}
@@ -226,11 +254,22 @@ enum WarningType {
226254
InconsistentDigitGrouping,
227255
LargeDigitGroups,
228256
DecimalRepresentation,
257+
MistypedLiteralSuffix
229258
}
230259

231260
impl WarningType {
232261
crate fn display(&self, grouping_hint: &str, cx: &EarlyContext<'_>, span: syntax_pos::Span) {
233262
match self {
263+
WarningType::MistypedLiteralSuffix => {
264+
span_lint_and_sugg(
265+
cx,
266+
MISTYPED_LITERAL_SUFFIXES,
267+
span,
268+
"mistyped literal suffix",
269+
"did you mean to write",
270+
grouping_hint.to_string()
271+
)
272+
},
234273
WarningType::UnreadableLiteral => span_lint_and_sugg(
235274
cx,
236275
UNREADABLE_LITERAL,
@@ -303,7 +342,7 @@ impl LiteralDigitGrouping {
303342
if char::to_digit(firstch, 10).is_some();
304343
then {
305344
let digit_info = DigitInfo::new(&src, false);
306-
let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
345+
let _ = Self::do_lint(digit_info.digits, digit_info.suffix).map_err(|warning_type| {
307346
warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
308347
});
309348
}
@@ -325,12 +364,12 @@ impl LiteralDigitGrouping {
325364

326365
// Lint integral and fractional parts separately, and then check consistency of digit
327366
// groups if both pass.
328-
let _ = Self::do_lint(parts[0])
367+
let _ = Self::do_lint(parts[0], None)
329368
.map(|integral_group_size| {
330369
if parts.len() > 1 {
331370
// Lint the fractional part of literal just like integral part, but reversed.
332371
let fractional_part = &parts[1].chars().rev().collect::<String>();
333-
let _ = Self::do_lint(fractional_part)
372+
let _ = Self::do_lint(fractional_part, None)
334373
.map(|fractional_group_size| {
335374
let consistent = Self::parts_consistent(integral_group_size,
336375
fractional_group_size,
@@ -373,7 +412,12 @@ impl LiteralDigitGrouping {
373412

374413
/// Performs lint on `digits` (no decimal point) and returns the group
375414
/// size on success or `WarningType` when emitting a warning.
376-
fn do_lint(digits: &str) -> Result<usize, WarningType> {
415+
fn do_lint(digits: &str, suffix: Option<&str>) -> Result<usize, WarningType> {
416+
if let Some(suffix) = suffix {
417+
if ["_8", "_32", "_64"].contains(&suffix) {
418+
return Err(WarningType::MistypedLiteralSuffix);
419+
}
420+
}
377421
// Grab underscore indices with respect to the units digit.
378422
let underscore_positions: Vec<usize> = digits
379423
.chars()

tests/ui/literals.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,7 @@ 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;
4649
}

tests/ui/literals.stderr

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,5 +120,19 @@ 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` or `2_u32`
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` or `4_u64`
136+
137+
error: aborting due to 18 previous errors
124138

0 commit comments

Comments
 (0)