@@ -732,12 +732,13 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
732732 true
733733 } ;
734734
735+ let sm = self . tcx . sess . source_map ( ) ;
735736 let ( snippet, last_ty) =
736737 if let ( true , hir:: TyKind :: TraitObject ( ..) , Ok ( snippet) , true , Some ( last_ty) ) = (
737738 // Verify that we're dealing with a return `dyn Trait`
738739 ret_ty. span . overlaps ( span) ,
739740 & ret_ty. kind ,
740- self . tcx . sess . source_map ( ) . span_to_snippet ( ret_ty. span ) ,
741+ sm . span_to_snippet ( ret_ty. span ) ,
741742 // If any of the return types does not conform to the trait, then we can't
742743 // suggest `impl Trait` nor trait objects, it is a type mismatch error.
743744 all_returns_conform_to_trait,
@@ -775,26 +776,23 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
775776 if is_object_safe {
776777 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
777778 // Get all the return values and collect their span and suggestion.
778- let mut suggestions = visitor
779+ if let Some ( mut suggestions) = visitor
779780 . returns
780781 . iter ( )
781782 . map ( |expr| {
782- (
783- expr. span ,
784- format ! (
785- "Box::new({})" ,
786- self . tcx. sess. source_map( ) . span_to_snippet( expr. span) . unwrap( )
787- ) ,
788- )
783+ let snip = sm. span_to_snippet ( expr. span ) . ok ( ) ?;
784+ Some ( ( expr. span , format ! ( "Box::new({})" , snip) ) )
789785 } )
790- . collect :: < Vec < _ > > ( ) ;
791- // Add the suggestion for the return type.
792- suggestions. push ( ( ret_ty. span , format ! ( "Box<dyn {}>" , trait_obj) ) ) ;
793- err. multipart_suggestion (
794- "return a boxed trait object instead" ,
795- suggestions,
796- Applicability :: MaybeIncorrect ,
797- ) ;
786+ . collect :: < Option < Vec < _ > > > ( )
787+ {
788+ // Add the suggestion for the return type.
789+ suggestions. push ( ( ret_ty. span , format ! ( "Box<dyn {}>" , trait_obj) ) ) ;
790+ err. multipart_suggestion (
791+ "return a boxed trait object instead" ,
792+ suggestions,
793+ Applicability :: MaybeIncorrect ,
794+ ) ;
795+ }
798796 } else {
799797 // This is currently not possible to trigger because E0038 takes precedence, but
800798 // leave it in for completeness in case anything changes in an earlier stage.
0 commit comments