assertions_on_result_states fix suggestion when assert! not in a statement

This commit is contained in:
kraktus 2022-09-10 10:30:19 +02:00
parent 5652ccbc0f
commit cd69d86c89
4 changed files with 27 additions and 6 deletions

View file

@ -1,9 +1,9 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::macros::{find_assert_args, root_macro_call_first_node, PanicExpn};
use clippy_utils::path_res;
use clippy_utils::source::snippet_with_context;
use clippy_utils::ty::{implements_trait, is_copy, is_type_diagnostic_item};
use clippy_utils::usage::local_used_after_expr;
use clippy_utils::{is_expr_final_block_expr, path_res};
use rustc_errors::Applicability;
use rustc_hir::def::Res;
use rustc_hir::{Expr, ExprKind};
@ -58,6 +58,7 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates {
return;
}
}
let semicolon = if is_expr_final_block_expr(cx.tcx, e) {";"} else {""};
let mut app = Applicability::MachineApplicable;
match method_segment.ident.as_str() {
"is_ok" if type_suitable_to_unwrap(cx, substs.type_at(1)) => {
@ -68,8 +69,9 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates {
"called `assert!` with `Result::is_ok`",
"replace with",
format!(
"{}.unwrap()",
snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0
"{}.unwrap(){}",
snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0,
semicolon
),
app,
);
@ -82,8 +84,9 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates {
"called `assert!` with `Result::is_err`",
"replace with",
format!(
"{}.unwrap_err()",
snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0
"{}.unwrap_err(){}",
snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0,
semicolon
),
app,
);

View file

@ -75,3 +75,9 @@ fn main() {
let r: Result<Foo, Foo> = Err(Foo);
assert!(r.is_err());
}
#[allow(dead_code)]
fn issue9450() {
let res: Result<i32, i32> = Ok(1);
res.unwrap_err();
}

View file

@ -75,3 +75,9 @@ fn main() {
let r: Result<Foo, Foo> = Err(Foo);
assert!(r.is_err());
}
#[allow(dead_code)]
fn issue9450() {
let res: Result<i32, i32> = Ok(1);
assert!(res.is_err())
}

View file

@ -36,5 +36,11 @@ error: called `assert!` with `Result::is_err`
LL | assert!(r.is_err());
| ^^^^^^^^^^^^^^^^^^^ help: replace with: `r.unwrap_err()`
error: aborting due to 6 previous errors
error: called `assert!` with `Result::is_err`
--> $DIR/assertions_on_result_states.rs:82:5
|
LL | assert!(res.is_err())
| ^^^^^^^^^^^^^^^^^^^^^ help: replace with: `res.unwrap_err();`
error: aborting due to 7 previous errors