Skip to content

Commit 69c3b9c

Browse files
committed
new lint: unnecessary_fallible_conversions
1 parent cdc4d56 commit 69c3b9c

14 files changed

+291
-22
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -5528,6 +5528,7 @@ Released 2018-09-13
55285528
[`unknown_clippy_lints`]: https://rust-lang.github.io/rust-clippy/master/index.html#unknown_clippy_lints
55295529
[`unnecessary_box_returns`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_box_returns
55305530
[`unnecessary_cast`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast
5531+
[`unnecessary_fallible_conversions`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_fallible_conversions
55315532
[`unnecessary_filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_filter_map
55325533
[`unnecessary_find_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_find_map
55335534
[`unnecessary_fold`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_fold

clippy_lints/src/declared_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
430430
crate::methods::TYPE_ID_ON_BOX_INFO,
431431
crate::methods::UNINIT_ASSUMED_INIT_INFO,
432432
crate::methods::UNIT_HASH_INFO,
433+
crate::methods::UNNECESSARY_FALLIBLE_CONVERSIONS_INFO,
433434
crate::methods::UNNECESSARY_FILTER_MAP_INFO,
434435
crate::methods::UNNECESSARY_FIND_MAP_INFO,
435436
crate::methods::UNNECESSARY_FOLD_INFO,

clippy_lints/src/implicit_saturating_add.rs

+12-12
Original file line numberDiff line numberDiff line change
@@ -82,18 +82,18 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingAdd {
8282

8383
fn get_int_max(ty: Ty<'_>) -> Option<u128> {
8484
match ty.peel_refs().kind() {
85-
Int(IntTy::I8) => i8::max_value().try_into().ok(),
86-
Int(IntTy::I16) => i16::max_value().try_into().ok(),
87-
Int(IntTy::I32) => i32::max_value().try_into().ok(),
88-
Int(IntTy::I64) => i64::max_value().try_into().ok(),
89-
Int(IntTy::I128) => i128::max_value().try_into().ok(),
90-
Int(IntTy::Isize) => isize::max_value().try_into().ok(),
91-
Uint(UintTy::U8) => u8::max_value().try_into().ok(),
92-
Uint(UintTy::U16) => u16::max_value().try_into().ok(),
93-
Uint(UintTy::U32) => u32::max_value().try_into().ok(),
94-
Uint(UintTy::U64) => u64::max_value().try_into().ok(),
95-
Uint(UintTy::U128) => Some(u128::max_value()),
96-
Uint(UintTy::Usize) => usize::max_value().try_into().ok(),
85+
Int(IntTy::I8) => i8::MAX.try_into().ok(),
86+
Int(IntTy::I16) => i16::MAX.try_into().ok(),
87+
Int(IntTy::I32) => i32::MAX.try_into().ok(),
88+
Int(IntTy::I64) => i64::MAX.try_into().ok(),
89+
Int(IntTy::I128) => i128::MAX.try_into().ok(),
90+
Int(IntTy::Isize) => isize::MAX.try_into().ok(),
91+
Uint(UintTy::U8) => Some(u8::MAX.into()),
92+
Uint(UintTy::U16) => Some(u16::MAX.into()),
93+
Uint(UintTy::U32) => Some(u32::MAX.into()),
94+
Uint(UintTy::U64) => Some(u64::MAX.into()),
95+
Uint(UintTy::U128) => Some(u128::MAX),
96+
Uint(UintTy::Usize) => usize::MAX.try_into().ok(),
9797
_ => None,
9898
}
9999
}

clippy_lints/src/methods/mod.rs

+33
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ mod suspicious_to_owned;
9999
mod type_id_on_box;
100100
mod uninit_assumed_init;
101101
mod unit_hash;
102+
mod unnecessary_fallible_conversions;
102103
mod unnecessary_filter_map;
103104
mod unnecessary_fold;
104105
mod unnecessary_iter_cloned;
@@ -3655,6 +3656,33 @@ declare_clippy_lint! {
36553656
"cloning a `Waker` only to wake it"
36563657
}
36573658

3659+
declare_clippy_lint! {
3660+
/// ### What it does
3661+
/// Checks for calls to `TryInto::try_into` and `TryFrom::try_from` when their infallible counterparts
3662+
/// could be used.
3663+
///
3664+
/// ### Why is this bad?
3665+
/// In those cases, the `TryInto` and `TryFrom` trait implementation is a blanket impl that forwards
3666+
/// to `Into` or `From`, which always succeeds.
3667+
/// The returned `Result<_, Infallible>` requires error handling to get the contained value
3668+
/// even though the conversion can never fail.
3669+
///
3670+
/// ### Example
3671+
/// ```rust
3672+
/// let _: Result<i64, _> = 1i32.try_into();
3673+
/// let _: Result<i64, _> = <_>::try_from(1i32);
3674+
/// ```
3675+
/// Use `from`/`into` instead:
3676+
/// ```rust
3677+
/// let _: i64 = 1i32.into();
3678+
/// let _: i64 = <_>::from(1i32);
3679+
/// ```
3680+
#[clippy::version = "1.75.0"]
3681+
pub UNNECESSARY_FALLIBLE_CONVERSIONS,
3682+
style,
3683+
"calling the `try_from` and `try_into` trait methods when `From`/`Into` is implemented"
3684+
}
3685+
36583686
pub struct Methods {
36593687
avoid_breaking_exported_api: bool,
36603688
msrv: Msrv,
@@ -3801,6 +3829,7 @@ impl_lint_pass!(Methods => [
38013829
PATH_ENDS_WITH_EXT,
38023830
REDUNDANT_AS_STR,
38033831
WAKER_CLONE_WAKE,
3832+
UNNECESSARY_FALLIBLE_CONVERSIONS,
38043833
]);
38053834

38063835
/// Extracts a method call name, args, and `Span` of the method name.
@@ -3827,6 +3856,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
38273856
match expr.kind {
38283857
hir::ExprKind::Call(func, args) => {
38293858
from_iter_instead_of_collect::check(cx, expr, args, func);
3859+
unnecessary_fallible_conversions::check_function(cx, expr, func);
38303860
},
38313861
hir::ExprKind::MethodCall(method_call, receiver, args, _) => {
38323862
let method_span = method_call.ident.span;
@@ -4316,6 +4346,9 @@ impl Methods {
43164346
}
43174347
unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
43184348
},
4349+
("try_into", []) if is_trait_method(cx, expr, sym::TryInto) => {
4350+
unnecessary_fallible_conversions::check_method(cx, expr);
4351+
}
43194352
("to_owned", []) => {
43204353
if !suspicious_to_owned::check(cx, expr, recv) {
43214354
implicit_clone::check(cx, name, expr, recv);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
use clippy_utils::diagnostics::span_lint_and_sugg;
2+
use clippy_utils::get_parent_expr;
3+
use clippy_utils::ty::implements_trait;
4+
use rustc_errors::Applicability;
5+
use rustc_hir::{Expr, ExprKind};
6+
use rustc_lint::LateContext;
7+
use rustc_middle::ty;
8+
use rustc_span::{sym, Span};
9+
10+
use super::UNNECESSARY_FALLIBLE_CONVERSIONS;
11+
12+
/// What function is being called and whether that call is written as a method call or a function
13+
/// call
14+
#[derive(Copy, Clone)]
15+
#[expect(clippy::enum_variant_names)]
16+
enum FunctionKind {
17+
/// `T::try_from(U)`
18+
TryFromFunction,
19+
/// `t.try_into()`
20+
TryIntoMethod,
21+
/// `U::try_into(t)`
22+
TryIntoFunction,
23+
}
24+
25+
fn check<'tcx>(
26+
cx: &LateContext<'tcx>,
27+
expr: &Expr<'_>,
28+
node_args: ty::GenericArgsRef<'tcx>,
29+
kind: FunctionKind,
30+
primary_span: Span,
31+
) {
32+
if let &[self_ty, other_ty] = node_args.as_slice()
33+
// useless_conversion already warns `T::try_from(T)`, so ignore it here
34+
&& self_ty != other_ty
35+
&& let Some(self_ty) = self_ty.as_type()
36+
&& let Some(from_into_trait) = cx.tcx.get_diagnostic_item(match kind {
37+
FunctionKind::TryFromFunction => sym::From,
38+
FunctionKind::TryIntoMethod | FunctionKind::TryIntoFunction => sym::Into,
39+
})
40+
// If `T: TryFrom<U>` and `T: From<U>` both exist, then that means that the `TryFrom`
41+
// _must_ be from the blanket impl and cannot have been manually implemented
42+
// (else there would be conflicting impls, even with #![feature(spec)]), so we don't even need to check
43+
// what `<T as TryFrom<U>>::Error` is: it's always `Infallible`
44+
&& implements_trait(cx, self_ty, from_into_trait, &[other_ty])
45+
{
46+
let parent_unwrap_call = get_parent_expr(cx, expr)
47+
.and_then(|parent| {
48+
if let ExprKind::MethodCall(path, .., span) = parent.kind
49+
&& let sym::unwrap | sym::expect = path.ident.name
50+
{
51+
Some(span)
52+
} else {
53+
None
54+
}
55+
});
56+
57+
let (sugg, span, applicability) = match kind {
58+
FunctionKind::TryIntoMethod if let Some(unwrap_span) = parent_unwrap_call => {
59+
// Extend the span to include the unwrap/expect call:
60+
// `foo.try_into().expect("..")`
61+
// ^^^^^^^^^^^^^^^^^^^^^^^
62+
//
63+
// `try_into().unwrap()` specifically can be trivially replaced with just `into()`,
64+
// so that can be machine-applicable
65+
66+
("into()", primary_span.with_hi(unwrap_span.hi()), Applicability::MachineApplicable)
67+
}
68+
FunctionKind::TryFromFunction => ("From::from", primary_span, Applicability::Unspecified),
69+
FunctionKind::TryIntoFunction => ("Into::into", primary_span, Applicability::Unspecified),
70+
FunctionKind::TryIntoMethod => ("into", primary_span, Applicability::Unspecified),
71+
};
72+
73+
span_lint_and_sugg(
74+
cx,
75+
UNNECESSARY_FALLIBLE_CONVERSIONS,
76+
span,
77+
"use of a fallible conversion when an infallible one could be used",
78+
"use",
79+
sugg.into(),
80+
applicability
81+
);
82+
}
83+
}
84+
85+
/// Checks method call exprs:
86+
/// - `0i32.try_into()`
87+
pub(super) fn check_method(cx: &LateContext<'_>, expr: &Expr<'_>) {
88+
if let ExprKind::MethodCall(path, ..) = expr.kind {
89+
check(
90+
cx,
91+
expr,
92+
cx.typeck_results().node_args(expr.hir_id),
93+
FunctionKind::TryIntoMethod,
94+
path.ident.span,
95+
);
96+
}
97+
}
98+
99+
/// Checks function call exprs:
100+
/// - `<i64 as TryFrom<_>>::try_from(0i32)`
101+
/// - `<_ as TryInto<i64>>::try_into(0i32)`
102+
pub(super) fn check_function(cx: &LateContext<'_>, expr: &Expr<'_>, callee: &Expr<'_>) {
103+
if let ExprKind::Path(ref qpath) = callee.kind
104+
&& let Some(item_def_id) = cx.qpath_res(qpath, callee.hir_id).opt_def_id()
105+
&& let Some(trait_def_id) = cx.tcx.trait_of_item(item_def_id)
106+
{
107+
check(
108+
cx,
109+
expr,
110+
cx.typeck_results().node_args(callee.hir_id),
111+
match cx.tcx.get_diagnostic_name(trait_def_id) {
112+
Some(sym::TryFrom) => FunctionKind::TryFromFunction,
113+
Some(sym::TryInto) => FunctionKind::TryIntoFunction,
114+
_ => return,
115+
},
116+
callee.span,
117+
);
118+
}
119+
}

tests/ui/manual_string_new.fixed

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#![warn(clippy::manual_string_new)]
2+
#![allow(clippy::unnecessary_fallible_conversions)]
23

34
macro_rules! create_strings_from_macro {
45
// When inside a macro, nothing should warn to prevent false positives.

tests/ui/manual_string_new.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#![warn(clippy::manual_string_new)]
2+
#![allow(clippy::unnecessary_fallible_conversions)]
23

34
macro_rules! create_strings_from_macro {
45
// When inside a macro, nothing should warn to prevent false positives.

tests/ui/manual_string_new.stderr

+9-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error: empty String is being created manually
2-
--> $DIR/manual_string_new.rs:13:13
2+
--> $DIR/manual_string_new.rs:14:13
33
|
44
LL | let _ = "".to_string();
55
| ^^^^^^^^^^^^^^ help: consider using: `String::new()`
@@ -8,49 +8,49 @@ LL | let _ = "".to_string();
88
= help: to override `-D warnings` add `#[allow(clippy::manual_string_new)]`
99

1010
error: empty String is being created manually
11-
--> $DIR/manual_string_new.rs:16:13
11+
--> $DIR/manual_string_new.rs:17:13
1212
|
1313
LL | let _ = "".to_owned();
1414
| ^^^^^^^^^^^^^ help: consider using: `String::new()`
1515

1616
error: empty String is being created manually
17-
--> $DIR/manual_string_new.rs:19:21
17+
--> $DIR/manual_string_new.rs:20:21
1818
|
1919
LL | let _: String = "".into();
2020
| ^^^^^^^^^ help: consider using: `String::new()`
2121

2222
error: empty String is being created manually
23-
--> $DIR/manual_string_new.rs:26:13
23+
--> $DIR/manual_string_new.rs:27:13
2424
|
2525
LL | let _ = String::from("");
2626
| ^^^^^^^^^^^^^^^^ help: consider using: `String::new()`
2727

2828
error: empty String is being created manually
29-
--> $DIR/manual_string_new.rs:27:13
29+
--> $DIR/manual_string_new.rs:28:13
3030
|
3131
LL | let _ = <String>::from("");
3232
| ^^^^^^^^^^^^^^^^^^ help: consider using: `String::new()`
3333

3434
error: empty String is being created manually
35-
--> $DIR/manual_string_new.rs:32:13
35+
--> $DIR/manual_string_new.rs:33:13
3636
|
3737
LL | let _ = String::try_from("").unwrap();
3838
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `String::new()`
3939

4040
error: empty String is being created manually
41-
--> $DIR/manual_string_new.rs:38:21
41+
--> $DIR/manual_string_new.rs:39:21
4242
|
4343
LL | let _: String = From::from("");
4444
| ^^^^^^^^^^^^^^ help: consider using: `String::new()`
4545

4646
error: empty String is being created manually
47-
--> $DIR/manual_string_new.rs:43:21
47+
--> $DIR/manual_string_new.rs:44:21
4848
|
4949
LL | let _: String = TryFrom::try_from("").unwrap();
5050
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `String::new()`
5151

5252
error: empty String is being created manually
53-
--> $DIR/manual_string_new.rs:46:21
53+
--> $DIR/manual_string_new.rs:47:21
5454
|
5555
LL | let _: String = TryFrom::try_from("").expect("this should warn");
5656
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `String::new()`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#![warn(clippy::unnecessary_fallible_conversions)]
2+
3+
fn main() {
4+
let _: i64 = 0i32.into();
5+
let _: i64 = 0i32.into();
6+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#![warn(clippy::unnecessary_fallible_conversions)]
2+
3+
fn main() {
4+
let _: i64 = 0i32.try_into().unwrap();
5+
let _: i64 = 0i32.try_into().expect("can't happen");
6+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
error: use of a fallible conversion when an infallible one could be used
2+
--> $DIR/unnecessary_fallible_conversions.rs:4:23
3+
|
4+
LL | let _: i64 = 0i32.try_into().unwrap();
5+
| ^^^^^^^^^^^^^^^^^^^ help: use: `into()`
6+
|
7+
= note: `-D clippy::unnecessary-fallible-conversions` implied by `-D warnings`
8+
= help: to override `-D warnings` add `#[allow(clippy::unnecessary_fallible_conversions)]`
9+
10+
error: use of a fallible conversion when an infallible one could be used
11+
--> $DIR/unnecessary_fallible_conversions.rs:5:23
12+
|
13+
LL | let _: i64 = 0i32.try_into().expect("can't happen");
14+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `into()`
15+
16+
error: aborting due to 2 previous errors
17+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//@aux-build:proc_macros.rs
2+
//@no-rustfix
3+
#![warn(clippy::unnecessary_fallible_conversions)]
4+
5+
extern crate proc_macros;
6+
7+
struct Foo;
8+
impl TryFrom<i32> for Foo {
9+
type Error = ();
10+
fn try_from(_: i32) -> Result<Self, Self::Error> {
11+
Ok(Foo)
12+
}
13+
}
14+
impl From<i64> for Foo {
15+
fn from(_: i64) -> Self {
16+
Foo
17+
}
18+
}
19+
20+
fn main() {
21+
// `Foo` only implements `TryFrom<i32>` and not `From<i32>`, so don't lint
22+
let _: Result<Foo, _> = 0i32.try_into();
23+
let _: Result<Foo, _> = i32::try_into(0i32);
24+
let _: Result<Foo, _> = Foo::try_from(0i32);
25+
26+
// ... it does impl From<i64> however
27+
let _: Result<Foo, _> = 0i64.try_into();
28+
//~^ ERROR: use of a fallible conversion when an infallible one could be used
29+
let _: Result<Foo, _> = i64::try_into(0i64);
30+
//~^ ERROR: use of a fallible conversion when an infallible one could be used
31+
let _: Result<Foo, _> = Foo::try_from(0i64);
32+
//~^ ERROR: use of a fallible conversion when an infallible one could be used
33+
34+
let _: Result<i64, _> = 0i32.try_into();
35+
//~^ ERROR: use of a fallible conversion when an infallible one could be used
36+
let _: Result<i64, _> = i32::try_into(0i32);
37+
//~^ ERROR: use of a fallible conversion when an infallible one could be used
38+
let _: Result<i64, _> = <_>::try_from(0i32);
39+
//~^ ERROR: use of a fallible conversion when an infallible one could be used
40+
41+
// From a macro
42+
let _: Result<i64, _> = proc_macros::external!(0i32).try_into();
43+
}

0 commit comments

Comments
 (0)