@@ -3,10 +3,10 @@ use clippy_utils::macros::{PanicExpn, find_assert_args, root_macro_call_first_no
33use clippy_utils:: source:: snippet_with_context;
44use clippy_utils:: ty:: { has_debug_impl, is_copy, is_type_diagnostic_item} ;
55use clippy_utils:: usage:: local_used_after_expr;
6- use clippy_utils:: { is_expr_final_block_expr , path_res, sym} ;
6+ use clippy_utils:: { path_res, sym} ;
77use rustc_errors:: Applicability ;
88use rustc_hir:: def:: Res ;
9- use rustc_hir:: { Expr , ExprKind } ;
9+ use rustc_hir:: { Expr , ExprKind , Node } ;
1010use rustc_lint:: { LateContext , LateLintPass } ;
1111use rustc_middle:: ty:: { self , Ty } ;
1212use rustc_session:: declare_lint_pass;
@@ -77,17 +77,20 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates {
7777 _ => return ,
7878 } ;
7979 span_lint_and_then ( cx, ASSERTIONS_ON_RESULT_STATES , macro_call. span , message, |diag| {
80- let semicolon = if is_expr_final_block_expr ( cx. tcx , e) { ";" } else { "" } ;
8180 let mut app = Applicability :: MachineApplicable ;
82- diag. span_suggestion (
83- macro_call. span ,
84- "replace with" ,
85- format ! (
86- "{}.{replacement}(){semicolon}" ,
87- snippet_with_context( cx, recv. span, condition. span. ctxt( ) , ".." , & mut app) . 0
88- ) ,
89- app,
90- ) ;
81+ let recv = snippet_with_context ( cx, recv. span , condition. span . ctxt ( ) , ".." , & mut app) . 0 ;
82+
83+ // `assert!` doesn't return anything, but `Result::unwrap(_err)` does, so we might need to add a
84+ // semicolon to the suggestion to avoid leaking the type
85+ let sugg = match cx. tcx . parent_hir_node ( e. hir_id ) {
86+ // trailing expr of a block
87+ Node :: Block ( ..) => format ! ( "{recv}.{replacement}();" ) ,
88+ // already has a trailing semicolon
89+ Node :: Stmt ( ..) => format ! ( "{recv}.{replacement}()" ) ,
90+ // this is the last-resort option, because it's rather verbose
91+ _ => format ! ( "{{ {recv}.{replacement}(); }}" ) ,
92+ } ;
93+ diag. span_suggestion ( macro_call. span , "replace with" , sugg, app) ;
9194 } ) ;
9295 }
9396 }
0 commit comments