Skip to content

Commit f6b64d1

Browse files
committed
new lint: unnecessary_fallible_conversions
1 parent c40359d commit f6b64d1

11 files changed

+252
-22
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5527,6 +5527,7 @@ Released 2018-09-13
55275527
[`unknown_clippy_lints`]: https://rust-lang.github.io/rust-clippy/master/index.html#unknown_clippy_lints
55285528
[`unnecessary_box_returns`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_box_returns
55295529
[`unnecessary_cast`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast
5530+
[`unnecessary_fallible_conversions`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_fallible_conversions
55305531
[`unnecessary_filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_filter_map
55315532
[`unnecessary_find_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_find_map
55325533
[`unnecessary_fold`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_fold

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
427427
crate::methods::TYPE_ID_ON_BOX_INFO,
428428
crate::methods::UNINIT_ASSUMED_INIT_INFO,
429429
crate::methods::UNIT_HASH_INFO,
430+
crate::methods::UNNECESSARY_FALLIBLE_CONVERSIONS_INFO,
430431
crate::methods::UNNECESSARY_FILTER_MAP_INFO,
431432
crate::methods::UNNECESSARY_FIND_MAP_INFO,
432433
crate::methods::UNNECESSARY_FOLD_INFO,

clippy_lints/src/implicit_saturating_add.rs

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

Lines changed: 36 additions & 0 deletions
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;
@@ -3632,6 +3633,36 @@ declare_clippy_lint! {
36323633
"`as_str` used to call a method on `str` that is also available on `String`"
36333634
}
36343635

3636+
declare_clippy_lint! {
3637+
/// ### What it does
3638+
/// Looks for one of two kinds of expressions:
3639+
/// - Calling `<T as TryInto<U>>::try_into` where `T` also implements `Into<U>`
3640+
/// - Calling `<T as TryFrom<U>>::try_from` where `T` also implements `From<U>`
3641+
///
3642+
/// ### Why is this bad?
3643+
/// In those cases, the `TryInto` and `TryFrom` trait implementation is a blanket impl which forwards
3644+
/// to `Into` or `From`, which always succeeds.
3645+
/// Indeed, its associated `Error` type is the empty enum `Infallible`,
3646+
/// which is impossible to construct by nature, so the error handling that is then imposed by
3647+
/// the `Result<_, Infallible>` is unnecessary and can be avoided simply by calling `.into()` or `::from`
3648+
/// directly in the first place.
3649+
///
3650+
/// ### Example
3651+
/// ```rust
3652+
/// let _: Result<i64, _> = 1i32.try_into();
3653+
/// let _: Result<i64, _> = <_>::try_from(1i32);
3654+
/// ```
3655+
/// Use instead:
3656+
/// ```rust
3657+
/// let _: i64 = 1i32.into();
3658+
/// let _: i64 = <_>::from(1i32);
3659+
/// ```
3660+
#[clippy::version = "1.75.0"]
3661+
pub UNNECESSARY_FALLIBLE_CONVERSIONS,
3662+
style,
3663+
"calling the `try_from` and `try_into` trait methods when `From`/`Into` is implemented"
3664+
}
3665+
36353666
pub struct Methods {
36363667
avoid_breaking_exported_api: bool,
36373668
msrv: Msrv,
@@ -3777,6 +3808,7 @@ impl_lint_pass!(Methods => [
37773808
ITER_OUT_OF_BOUNDS,
37783809
PATH_ENDS_WITH_EXT,
37793810
REDUNDANT_AS_STR,
3811+
UNNECESSARY_FALLIBLE_CONVERSIONS,
37803812
]);
37813813

37823814
/// Extracts a method call name, args, and `Span` of the method name.
@@ -3803,6 +3835,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
38033835
match expr.kind {
38043836
hir::ExprKind::Call(func, args) => {
38053837
from_iter_instead_of_collect::check(cx, expr, args, func);
3838+
unnecessary_fallible_conversions::check_function(cx, expr, func);
38063839
},
38073840
hir::ExprKind::MethodCall(method_call, receiver, args, _) => {
38083841
let method_span = method_call.ident.span;
@@ -4292,6 +4325,9 @@ impl Methods {
42924325
}
42934326
unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
42944327
},
4328+
("try_into", []) if is_trait_method(cx, expr, sym::TryInto) => {
4329+
unnecessary_fallible_conversions::check_method(cx, expr);
4330+
}
42954331
("to_owned", []) => {
42964332
if !suspicious_to_owned::check(cx, expr, recv) {
42974333
implicit_clone::check(cx, name, expr, recv);
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
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()`
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.
44+
&& implements_trait(cx, self_ty, from_into_trait, &[other_ty])
45+
// Avoid linting if this is an argument to a function: `f(i32.try_into())`.
46+
// The function expects a `Result` either way, so users would need to wrap it back in `Ok(..)`
47+
// and save on nothing
48+
&& get_parent_expr(cx, expr).map_or(true, |parent| !matches!(parent.kind, ExprKind::Call(..)))
49+
{
50+
span_lint_and_sugg(
51+
cx,
52+
UNNECESSARY_FALLIBLE_CONVERSIONS,
53+
primary_span,
54+
match kind {
55+
FunctionKind::TryFromFunction => "calling `TryFrom::try_from` when `From` could be used",
56+
FunctionKind::TryIntoMethod
57+
| FunctionKind::TryIntoFunction => "calling `TryInto::try_into` when `Into` could be used",
58+
},
59+
"use",
60+
match kind {
61+
FunctionKind::TryFromFunction => "From::from".into(),
62+
FunctionKind::TryIntoFunction => "Into::into".into(),
63+
FunctionKind::TryIntoMethod => "into".into(),
64+
},
65+
// Suggestion likely results in compile errors, so it needs to be adjusted a bit by the user
66+
// (e.g. removing `unwrap()`s as a result, changing type annotations, ...)
67+
Applicability::Unspecified
68+
);
69+
}
70+
}
71+
72+
/// Checks method call exprs:
73+
/// - `0i32.try_into()`
74+
pub(super) fn check_method(cx: &LateContext<'_>, expr: &Expr<'_>) {
75+
if let ExprKind::MethodCall(path, ..) = expr.kind {
76+
check(
77+
cx,
78+
expr,
79+
cx.typeck_results().node_args(expr.hir_id),
80+
FunctionKind::TryIntoMethod,
81+
path.ident.span,
82+
);
83+
}
84+
}
85+
86+
/// Checks function call exprs:
87+
/// - `<i64 as TryFrom<_>>::try_from(0i32)`
88+
/// - `<_ as TryInto<i64>>::try_into(0i32)`
89+
pub(super) fn check_function(cx: &LateContext<'_>, expr: &Expr<'_>, callee: &Expr<'_>) {
90+
if let ExprKind::Path(ref qpath) = callee.kind
91+
&& let Some(item_def_id) = cx.qpath_res(qpath, callee.hir_id).opt_def_id()
92+
&& let Some(trait_def_id) = cx.tcx.trait_of_item(item_def_id)
93+
{
94+
check(
95+
cx,
96+
expr,
97+
cx.typeck_results().node_args(callee.hir_id),
98+
match cx.tcx.get_diagnostic_name(trait_def_id) {
99+
Some(sym::TryFrom) => FunctionKind::TryFromFunction,
100+
Some(sym::TryInto) => FunctionKind::TryIntoFunction,
101+
_ => return,
102+
},
103+
callee.span,
104+
);
105+
}
106+
}

tests/ui/manual_string_new.fixed

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

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

Lines changed: 9 additions & 9 deletions
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()`
Lines changed: 43 additions & 0 deletions
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: calling `TryInto::try_into` when `Into` could be used
29+
let _: Result<Foo, _> = i64::try_into(0i64);
30+
//~^ ERROR: calling `TryInto::try_into` when `Into` could be used
31+
let _: Result<Foo, _> = Foo::try_from(0i64);
32+
//~^ ERROR: calling `TryFrom::try_from` when `From` could be used
33+
34+
let _: Result<i64, _> = 0i32.try_into();
35+
//~^ ERROR: calling `TryInto::try_into` when `Into` could be used
36+
let _: Result<i64, _> = i32::try_into(0i32);
37+
//~^ ERROR: calling `TryInto::try_into` when `Into` could be used
38+
let _: Result<i64, _> = <_>::try_from(0i32);
39+
//~^ ERROR: calling `TryFrom::try_from` when `From` could be used
40+
41+
// From a macro
42+
let _: Result<i64, _> = proc_macros::external!(0i32).try_into();
43+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
error: calling `TryInto::try_into` when `Into` could be used
2+
--> $DIR/unnecessary_fallible_conversions.rs:27:34
3+
|
4+
LL | let _: Result<Foo, _> = 0i64.try_into();
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: calling `TryInto::try_into` when `Into` could be used
11+
--> $DIR/unnecessary_fallible_conversions.rs:29:29
12+
|
13+
LL | let _: Result<Foo, _> = i64::try_into(0i64);
14+
| ^^^^^^^^^^^^^ help: use: `Into::into`
15+
16+
error: calling `TryFrom::try_from` when `From` could be used
17+
--> $DIR/unnecessary_fallible_conversions.rs:31:29
18+
|
19+
LL | let _: Result<Foo, _> = Foo::try_from(0i64);
20+
| ^^^^^^^^^^^^^ help: use: `From::from`
21+
22+
error: calling `TryInto::try_into` when `Into` could be used
23+
--> $DIR/unnecessary_fallible_conversions.rs:34:34
24+
|
25+
LL | let _: Result<i64, _> = 0i32.try_into();
26+
| ^^^^^^^^ help: use: `into`
27+
28+
error: calling `TryInto::try_into` when `Into` could be used
29+
--> $DIR/unnecessary_fallible_conversions.rs:36:29
30+
|
31+
LL | let _: Result<i64, _> = i32::try_into(0i32);
32+
| ^^^^^^^^^^^^^ help: use: `Into::into`
33+
34+
error: calling `TryFrom::try_from` when `From` could be used
35+
--> $DIR/unnecessary_fallible_conversions.rs:38:29
36+
|
37+
LL | let _: Result<i64, _> = <_>::try_from(0i32);
38+
| ^^^^^^^^^^^^^ help: use: `From::from`
39+
40+
error: aborting due to 6 previous errors
41+

0 commit comments

Comments
 (0)