un-double return on try_err

This commit is contained in:
Andre Bogus 2021-04-18 23:49:54 +02:00
parent e441b33ba0
commit 243dc46250
4 changed files with 32 additions and 5 deletions

View File

@ -1,7 +1,7 @@
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::{snippet, snippet_with_macro_callsite}; use clippy_utils::source::{snippet, snippet_with_macro_callsite};
use clippy_utils::ty::is_type_diagnostic_item; use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{differing_macro_contexts, in_macro, is_lang_ctor, match_def_path, paths}; use clippy_utils::{differing_macro_contexts, get_parent_expr, in_macro, is_lang_ctor, match_def_path, paths};
use if_chain::if_chain; use if_chain::if_chain;
use rustc_errors::Applicability; use rustc_errors::Applicability;
use rustc_hir::LangItem::ResultErr; use rustc_hir::LangItem::ResultErr;
@ -102,10 +102,15 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
} else { } else {
snippet(cx, err_arg.span, "_") snippet(cx, err_arg.span, "_")
}; };
let suggestion = if err_ty == expr_err_ty { let ret_prefix = if get_parent_expr(cx, expr).map_or(false, |e| matches!(e.kind, ExprKind::Ret(_))) {
format!("return {}{}{}", prefix, origin_snippet, suffix) "" // already returns
} else { } else {
format!("return {}{}.into(){}", prefix, origin_snippet, suffix) "return "
};
let suggestion = if err_ty == expr_err_ty {
format!("{}{}{}{}", ret_prefix, prefix, origin_snippet, suffix)
} else {
format!("{}{}{}.into(){}", ret_prefix, prefix, origin_snippet, suffix)
}; };
span_lint_and_sugg( span_lint_and_sugg(

View File

@ -160,3 +160,11 @@ pub fn poll_next(ready: bool) -> Poll<Option<io::Result<()>>> {
Poll::Ready(None) Poll::Ready(None)
} }
// Tests that `return` is not duplicated
pub fn try_return(x: bool) -> Result<i32, i32> {
if x {
return Err(42);
}
Ok(0)
}

View File

@ -160,3 +160,11 @@ pub fn poll_next(ready: bool) -> Poll<Option<io::Result<()>>> {
Poll::Ready(None) Poll::Ready(None)
} }
// Tests that `return` is not duplicated
pub fn try_return(x: bool) -> Result<i32, i32> {
if x {
return Err(42)?;
}
Ok(0)
}

View File

@ -74,5 +74,11 @@ error: returning an `Err(_)` with the `?` operator
LL | Err(io::ErrorKind::NotFound)? LL | Err(io::ErrorKind::NotFound)?
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `return Poll::Ready(Some(Err(io::ErrorKind::NotFound.into())))` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `return Poll::Ready(Some(Err(io::ErrorKind::NotFound.into())))`
error: aborting due to 10 previous errors error: returning an `Err(_)` with the `?` operator
--> $DIR/try_err.rs:167:16
|
LL | return Err(42)?;
| ^^^^^^^^ help: try this: `Err(42)`
error: aborting due to 11 previous errors