diff options
| author | Dharma Saputra Wijaya <dswijj@gmail.com> | 2021-08-01 17:47:29 +0800 |
|---|---|---|
| committer | Dharma Saputra Wijaya <dswijj@gmail.com> | 2021-08-01 17:47:54 +0800 |
| commit | 69d439065eccef7f554e7506236fafa0b4af19eb (patch) | |
| tree | 3d7a68bcf2f4c5066feda997042ec8ec949a29bf /clippy_lints | |
| parent | 05fa78fd3edaf19a2508db9a74dbaa4cb009f236 (diff) | |
| download | rust-69d439065eccef7f554e7506236fafa0b4af19eb.tar.gz rust-69d439065eccef7f554e7506236fafa0b4af19eb.zip | |
Handle `Result` on `map_flatten` lint
Adds a check on `.map(..).flatten()` on `Result` type that follows the behaviour on `Option` type.
Diffstat (limited to 'clippy_lints')
| -rw-r--r-- | clippy_lints/src/methods/map_flatten.rs | 42 |
1 files changed, 28 insertions, 14 deletions
diff --git a/clippy_lints/src/methods/map_flatten.rs b/clippy_lints/src/methods/map_flatten.rs index e8ad16bc0de..08d3a7ce92b 100644 --- a/clippy_lints/src/methods/map_flatten.rs +++ b/clippy_lints/src/methods/map_flatten.rs @@ -52,18 +52,32 @@ pub(super) fn check<'tcx>( ); } - // lint if caller of `.map().flatten()` is an Option - if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::option_type) { - let func_snippet = snippet(cx, map_arg.span, ".."); - let hint = format!(".and_then({})", func_snippet); - span_lint_and_sugg( - cx, - MAP_FLATTEN, - expr.span.with_lo(recv.span.hi()), - "called `map(..).flatten()` on an `Option`", - "try using `and_then` instead", - hint, - Applicability::MachineApplicable, - ); - } + // lint if caller of `.map().flatten()` is an Option or Result + let caller_type = match cx.typeck_results().expr_ty(recv).kind() { + ty::Adt(adt, _) => { + if cx.tcx.is_diagnostic_item(sym::option_type, adt.did) { + "Option" + } else if cx.tcx.is_diagnostic_item(sym::result_type, adt.did) { + "Result" + } else { + return; + } + }, + _ => { + return; + }, + }; + + let func_snippet = snippet(cx, map_arg.span, ".."); + let hint = format!(".and_then({})", func_snippet); + let lint_info = format!("called `map(..).flatten()` on an `{}`", caller_type); + span_lint_and_sugg( + cx, + MAP_FLATTEN, + expr.span.with_lo(recv.span.hi()), + &lint_info, + "try using `and_then` instead", + hint, + Applicability::MachineApplicable, + ); } |
