-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: new lint for
and_then
when returning Option or Result (#14051)
close #6436 changelog: [`return_and_then`]: new lint
- Loading branch information
Showing
8 changed files
with
356 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
use rustc_errors::Applicability; | ||
use rustc_hir as hir; | ||
use rustc_lint::LateContext; | ||
use rustc_middle::ty::{self, GenericArg, Ty}; | ||
use rustc_span::sym; | ||
use std::ops::ControlFlow; | ||
|
||
use clippy_utils::diagnostics::span_lint_and_sugg; | ||
use clippy_utils::source::{indent_of, reindent_multiline, snippet_with_applicability}; | ||
use clippy_utils::ty::get_type_diagnostic_name; | ||
use clippy_utils::visitors::for_each_unconsumed_temporary; | ||
use clippy_utils::{is_expr_final_block_expr, peel_blocks}; | ||
|
||
use super::RETURN_AND_THEN; | ||
|
||
/// lint if `and_then` is the last expression in a block, and | ||
/// there are no references or temporaries in the receiver | ||
pub(super) fn check<'tcx>( | ||
cx: &LateContext<'tcx>, | ||
expr: &hir::Expr<'_>, | ||
recv: &'tcx hir::Expr<'tcx>, | ||
arg: &'tcx hir::Expr<'_>, | ||
) { | ||
if !is_expr_final_block_expr(cx.tcx, expr) { | ||
return; | ||
} | ||
|
||
let recv_type = cx.typeck_results().expr_ty(recv); | ||
if !matches!(get_type_diagnostic_name(cx, recv_type), Some(sym::Option | sym::Result)) { | ||
return; | ||
} | ||
|
||
let has_ref_type = matches!(recv_type.kind(), ty::Adt(_, args) if args | ||
.first() | ||
.and_then(|arg0: &GenericArg<'tcx>| GenericArg::as_type(*arg0)) | ||
.is_some_and(Ty::is_ref)); | ||
let has_temporaries = for_each_unconsumed_temporary(cx, recv, |_| ControlFlow::Break(())).is_break(); | ||
if has_ref_type && has_temporaries { | ||
return; | ||
} | ||
|
||
let hir::ExprKind::Closure(&hir::Closure { body, fn_decl, .. }) = arg.kind else { | ||
return; | ||
}; | ||
|
||
let closure_arg = fn_decl.inputs[0]; | ||
let closure_expr = peel_blocks(cx.tcx.hir().body(body).value); | ||
|
||
let mut applicability = Applicability::MachineApplicable; | ||
let arg_snip = snippet_with_applicability(cx, closure_arg.span, "_", &mut applicability); | ||
let recv_snip = snippet_with_applicability(cx, recv.span, "_", &mut applicability); | ||
let body_snip = snippet_with_applicability(cx, closure_expr.span, "..", &mut applicability); | ||
let inner = match body_snip.strip_prefix('{').and_then(|s| s.strip_suffix('}')) { | ||
Some(s) => s.trim_start_matches('\n').trim_end(), | ||
None => &body_snip, | ||
}; | ||
|
||
let msg = "use the question mark operator instead of an `and_then` call"; | ||
let sugg = format!( | ||
"let {} = {}?;\n{}", | ||
arg_snip, | ||
recv_snip, | ||
reindent_multiline(inner.into(), false, indent_of(cx, expr.span)) | ||
); | ||
|
||
span_lint_and_sugg(cx, RETURN_AND_THEN, expr.span, msg, "try", sugg, applicability); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
#![warn(clippy::return_and_then)] | ||
|
||
fn main() { | ||
fn test_opt_block(opt: Option<i32>) -> Option<i32> { | ||
let n = opt?; | ||
let mut ret = n + 1; | ||
ret += n; | ||
if n > 1 { Some(ret) } else { None } | ||
} | ||
|
||
fn test_opt_func(opt: Option<i32>) -> Option<i32> { | ||
let n = opt?; | ||
test_opt_block(Some(n)) | ||
} | ||
|
||
fn test_call_chain() -> Option<i32> { | ||
let n = gen_option(1)?; | ||
test_opt_block(Some(n)) | ||
} | ||
|
||
fn test_res_block(opt: Result<i32, i32>) -> Result<i32, i32> { | ||
let n = opt?; | ||
if n > 1 { Ok(n + 1) } else { Err(n) } | ||
} | ||
|
||
fn test_res_func(opt: Result<i32, i32>) -> Result<i32, i32> { | ||
let n = opt?; | ||
test_res_block(Ok(n)) | ||
} | ||
|
||
fn test_ref_only() -> Option<i32> { | ||
// ref: empty string | ||
let x = Some("")?; | ||
if x.len() > 2 { Some(3) } else { None } | ||
} | ||
|
||
fn test_tmp_only() -> Option<i32> { | ||
// unused temporary: vec![1, 2, 4] | ||
let x = Some(match (vec![1, 2, 3], vec![1, 2, 4]) { | ||
(a, _) if a.len() > 1 => a, | ||
(_, b) => b, | ||
})?; | ||
if x.len() > 2 { Some(3) } else { None } | ||
} | ||
|
||
// should not lint | ||
fn test_tmp_ref() -> Option<String> { | ||
String::from("<BOOM>") | ||
.strip_prefix("<") | ||
.and_then(|s| s.strip_suffix(">").map(String::from)) | ||
} | ||
|
||
// should not lint | ||
fn test_unconsumed_tmp() -> Option<i32> { | ||
[1, 2, 3] | ||
.iter() | ||
.map(|x| x + 1) | ||
.collect::<Vec<_>>() // temporary Vec created here | ||
.as_slice() // creates temporary slice | ||
.first() // creates temporary reference | ||
.and_then(|x| test_opt_block(Some(*x))) | ||
} | ||
} | ||
|
||
fn gen_option(n: i32) -> Option<i32> { | ||
Some(n) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
#![warn(clippy::return_and_then)] | ||
|
||
fn main() { | ||
fn test_opt_block(opt: Option<i32>) -> Option<i32> { | ||
opt.and_then(|n| { | ||
let mut ret = n + 1; | ||
ret += n; | ||
if n > 1 { Some(ret) } else { None } | ||
}) | ||
} | ||
|
||
fn test_opt_func(opt: Option<i32>) -> Option<i32> { | ||
opt.and_then(|n| test_opt_block(Some(n))) | ||
} | ||
|
||
fn test_call_chain() -> Option<i32> { | ||
gen_option(1).and_then(|n| test_opt_block(Some(n))) | ||
} | ||
|
||
fn test_res_block(opt: Result<i32, i32>) -> Result<i32, i32> { | ||
opt.and_then(|n| if n > 1 { Ok(n + 1) } else { Err(n) }) | ||
} | ||
|
||
fn test_res_func(opt: Result<i32, i32>) -> Result<i32, i32> { | ||
opt.and_then(|n| test_res_block(Ok(n))) | ||
} | ||
|
||
fn test_ref_only() -> Option<i32> { | ||
// ref: empty string | ||
Some("").and_then(|x| if x.len() > 2 { Some(3) } else { None }) | ||
} | ||
|
||
fn test_tmp_only() -> Option<i32> { | ||
// unused temporary: vec![1, 2, 4] | ||
Some(match (vec![1, 2, 3], vec![1, 2, 4]) { | ||
(a, _) if a.len() > 1 => a, | ||
(_, b) => b, | ||
}) | ||
.and_then(|x| if x.len() > 2 { Some(3) } else { None }) | ||
} | ||
|
||
// should not lint | ||
fn test_tmp_ref() -> Option<String> { | ||
String::from("<BOOM>") | ||
.strip_prefix("<") | ||
.and_then(|s| s.strip_suffix(">").map(String::from)) | ||
} | ||
|
||
// should not lint | ||
fn test_unconsumed_tmp() -> Option<i32> { | ||
[1, 2, 3] | ||
.iter() | ||
.map(|x| x + 1) | ||
.collect::<Vec<_>>() // temporary Vec created here | ||
.as_slice() // creates temporary slice | ||
.first() // creates temporary reference | ||
.and_then(|x| test_opt_block(Some(*x))) | ||
} | ||
} | ||
|
||
fn gen_option(n: i32) -> Option<i32> { | ||
Some(n) | ||
} |
Oops, something went wrong.