@@ -4586,6 +4586,58 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
4586
4586
_ => "/* value */" . to_string ( ) ,
4587
4587
} )
4588
4588
}
4589
+
4590
+ fn suggest_add_result_as_return_type (
4591
+ & self ,
4592
+ obligation : & PredicateObligation < ' tcx > ,
4593
+ err : & mut Diag < ' _ > ,
4594
+ trait_ref : ty:: PolyTraitRef < ' tcx > ,
4595
+ ) {
4596
+ if ObligationCauseCode :: QuestionMark != * obligation. cause . code ( ) . peel_derives ( ) {
4597
+ return ;
4598
+ }
4599
+
4600
+ let node = self . tcx . hir_node_by_def_id ( obligation. cause . body_id ) ;
4601
+ if let hir:: Node :: Item ( item) = node
4602
+ && let hir:: ItemKind :: Fn ( sig, _, body_id) = item. kind
4603
+ && let hir:: FnRetTy :: DefaultReturn ( ret_span) = sig. decl . output
4604
+ && trait_ref. skip_binder ( ) . args . len ( ) == 2
4605
+ && let ty:: Tuple ( l) = trait_ref. skip_binder ( ) . args . type_at ( 0 ) . kind ( )
4606
+ && l. len ( ) == 0
4607
+ && let ty:: Adt ( def, _) = trait_ref. skip_binder ( ) . args . type_at ( 1 ) . kind ( )
4608
+ && self . tcx . is_diagnostic_item ( sym:: Result , def. did ( ) )
4609
+ {
4610
+ let body = self . tcx . hir ( ) . body ( body_id) ;
4611
+ let mut sugg_spans =
4612
+ vec ! [ ( ret_span, " -> Result<(), Box<dyn std::error::Error>>" . to_string( ) ) ] ;
4613
+
4614
+ if let hir:: ExprKind :: Block ( b, _) = body. value . kind
4615
+ && b. expr . is_none ( )
4616
+ && let Some ( s) = b. stmts . last ( )
4617
+ && !is_ret_expr ( s)
4618
+ {
4619
+ sugg_spans. push ( (
4620
+ s. span . shrink_to_hi ( ) . until ( body. value . span . shrink_to_hi ( ) ) ,
4621
+ "\n \n return Ok(());\n }" . to_string ( ) ,
4622
+ ) ) ;
4623
+ }
4624
+ err. multipart_suggestion_verbose (
4625
+ format ! ( "consider adding return type" ) ,
4626
+ sugg_spans,
4627
+ Applicability :: MaybeIncorrect ,
4628
+ ) ;
4629
+ }
4630
+
4631
+ fn is_ret_expr < ' hir > ( stmt : & hir:: Stmt < ' hir > ) -> bool {
4632
+ if let hir:: StmtKind :: Semi ( expr) = stmt. kind
4633
+ && let hir:: ExprKind :: Ret ( Some ( _) ) = expr. kind
4634
+ {
4635
+ true
4636
+ } else {
4637
+ false
4638
+ }
4639
+ }
4640
+ }
4589
4641
}
4590
4642
4591
4643
/// Add a hint to add a missing borrow or remove an unnecessary one.
0 commit comments