@@ -732,12 +732,13 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
732
732
true
733
733
} ;
734
734
735
+ let sm = self . tcx . sess . source_map ( ) ;
735
736
let ( snippet, last_ty) =
736
737
if let ( true , hir:: TyKind :: TraitObject ( ..) , Ok ( snippet) , true , Some ( last_ty) ) = (
737
738
// Verify that we're dealing with a return `dyn Trait`
738
739
ret_ty. span . overlaps ( span) ,
739
740
& ret_ty. kind ,
740
- self . tcx . sess . source_map ( ) . span_to_snippet ( ret_ty. span ) ,
741
+ sm . span_to_snippet ( ret_ty. span ) ,
741
742
// If any of the return types does not conform to the trait, then we can't
742
743
// suggest `impl Trait` nor trait objects, it is a type mismatch error.
743
744
all_returns_conform_to_trait,
@@ -775,26 +776,23 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
775
776
if is_object_safe {
776
777
// Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
777
778
// Get all the return values and collect their span and suggestion.
778
- let mut suggestions = visitor
779
+ if let Some ( mut suggestions) = visitor
779
780
. returns
780
781
. iter ( )
781
782
. 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) ) )
789
785
} )
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
+ }
798
796
} else {
799
797
// This is currently not possible to trigger because E0038 takes precedence, but
800
798
// leave it in for completeness in case anything changes in an earlier stage.
0 commit comments