]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs
Rollup merge of #87266 - hellow554:issue87076, r=Mark-Simulacrum
[rust.git] / compiler / rustc_trait_selection / src / traits / error_reporting / suggestions.rs
1 use super::{
2     EvaluationResult, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation,
3     SelectionContext,
4 };
5
6 use crate::autoderef::Autoderef;
7 use crate::infer::InferCtxt;
8 use crate::traits::normalize_projection_type;
9
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_data_structures::stack::ensure_sufficient_stack;
12 use rustc_errors::{error_code, struct_span_err, Applicability, DiagnosticBuilder, Style};
13 use rustc_hir as hir;
14 use rustc_hir::def::DefKind;
15 use rustc_hir::def_id::DefId;
16 use rustc_hir::intravisit::Visitor;
17 use rustc_hir::lang_items::LangItem;
18 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
19 use rustc_middle::ty::{
20     self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
21     Infer, InferTy, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
22 };
23 use rustc_middle::ty::{TypeAndMut, TypeckResults};
24 use rustc_span::def_id::LOCAL_CRATE;
25 use rustc_span::symbol::{kw, sym, Ident, Symbol};
26 use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP};
27 use rustc_target::spec::abi;
28 use std::fmt;
29
30 use super::InferCtxtPrivExt;
31 use crate::infer::InferCtxtExt as _;
32 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
33 use rustc_middle::ty::print::with_no_trimmed_paths;
34
35 #[derive(Debug)]
36 pub enum GeneratorInteriorOrUpvar {
37     // span of interior type
38     Interior(Span),
39     // span of upvar
40     Upvar(Span),
41 }
42
43 // This trait is public to expose the diagnostics methods to clippy.
44 pub trait InferCtxtExt<'tcx> {
45     fn suggest_restricting_param_bound(
46         &self,
47         err: &mut DiagnosticBuilder<'_>,
48         trait_ref: ty::PolyTraitRef<'tcx>,
49         body_id: hir::HirId,
50     );
51
52     fn suggest_dereferences(
53         &self,
54         obligation: &PredicateObligation<'tcx>,
55         err: &mut DiagnosticBuilder<'tcx>,
56         trait_ref: ty::PolyTraitRef<'tcx>,
57         points_at_arg: bool,
58     );
59
60     fn get_closure_name(
61         &self,
62         def_id: DefId,
63         err: &mut DiagnosticBuilder<'_>,
64         msg: &str,
65     ) -> Option<String>;
66
67     fn suggest_fn_call(
68         &self,
69         obligation: &PredicateObligation<'tcx>,
70         err: &mut DiagnosticBuilder<'_>,
71         trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
72         points_at_arg: bool,
73     );
74
75     fn suggest_add_reference_to_arg(
76         &self,
77         obligation: &PredicateObligation<'tcx>,
78         err: &mut DiagnosticBuilder<'_>,
79         trait_ref: &ty::Binder<'tcx, ty::TraitRef<'tcx>>,
80         points_at_arg: bool,
81         has_custom_message: bool,
82     ) -> bool;
83
84     fn suggest_remove_reference(
85         &self,
86         obligation: &PredicateObligation<'tcx>,
87         err: &mut DiagnosticBuilder<'_>,
88         trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
89     );
90
91     fn suggest_change_mut(
92         &self,
93         obligation: &PredicateObligation<'tcx>,
94         err: &mut DiagnosticBuilder<'_>,
95         trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
96         points_at_arg: bool,
97     );
98
99     fn suggest_semicolon_removal(
100         &self,
101         obligation: &PredicateObligation<'tcx>,
102         err: &mut DiagnosticBuilder<'_>,
103         span: Span,
104         trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
105     );
106
107     fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
108
109     fn suggest_impl_trait(
110         &self,
111         err: &mut DiagnosticBuilder<'_>,
112         span: Span,
113         obligation: &PredicateObligation<'tcx>,
114         trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
115     ) -> bool;
116
117     fn point_at_returns_when_relevant(
118         &self,
119         err: &mut DiagnosticBuilder<'_>,
120         obligation: &PredicateObligation<'tcx>,
121     );
122
123     fn report_closure_arg_mismatch(
124         &self,
125         span: Span,
126         found_span: Option<Span>,
127         expected_ref: ty::PolyTraitRef<'tcx>,
128         found: ty::PolyTraitRef<'tcx>,
129     ) -> DiagnosticBuilder<'tcx>;
130
131     fn suggest_fully_qualified_path(
132         &self,
133         err: &mut DiagnosticBuilder<'_>,
134         def_id: DefId,
135         span: Span,
136         trait_ref: DefId,
137     );
138
139     fn maybe_note_obligation_cause_for_async_await(
140         &self,
141         err: &mut DiagnosticBuilder<'_>,
142         obligation: &PredicateObligation<'tcx>,
143     ) -> bool;
144
145     fn note_obligation_cause_for_async_await(
146         &self,
147         err: &mut DiagnosticBuilder<'_>,
148         interior_or_upvar_span: GeneratorInteriorOrUpvar,
149         interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
150         inner_generator_body: Option<&hir::Body<'tcx>>,
151         outer_generator: Option<DefId>,
152         trait_ref: ty::TraitRef<'tcx>,
153         target_ty: Ty<'tcx>,
154         typeck_results: &ty::TypeckResults<'tcx>,
155         obligation: &PredicateObligation<'tcx>,
156         next_code: Option<&ObligationCauseCode<'tcx>>,
157     );
158
159     fn note_obligation_cause_code<T>(
160         &self,
161         err: &mut DiagnosticBuilder<'_>,
162         predicate: &T,
163         cause_code: &ObligationCauseCode<'tcx>,
164         obligated_types: &mut Vec<&ty::TyS<'tcx>>,
165         seen_requirements: &mut FxHashSet<DefId>,
166     ) where
167         T: fmt::Display;
168
169     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>);
170
171     /// Suggest to await before try: future? => future.await?
172     fn suggest_await_before_try(
173         &self,
174         err: &mut DiagnosticBuilder<'_>,
175         obligation: &PredicateObligation<'tcx>,
176         trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
177         span: Span,
178     );
179 }
180
181 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
182     (
183         generics.where_clause.tail_span_for_suggestion(),
184         format!(
185             "{} {}",
186             if !generics.where_clause.predicates.is_empty() { "," } else { " where" },
187             pred,
188         ),
189     )
190 }
191
192 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
193 /// it can also be an `impl Trait` param that needs to be decomposed to a type
194 /// param for cleaner code.
195 fn suggest_restriction(
196     tcx: TyCtxt<'tcx>,
197     generics: &hir::Generics<'tcx>,
198     msg: &str,
199     err: &mut DiagnosticBuilder<'_>,
200     fn_sig: Option<&hir::FnSig<'_>>,
201     projection: Option<&ty::ProjectionTy<'_>>,
202     trait_ref: ty::PolyTraitRef<'tcx>,
203     super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
204 ) {
205     // When we are dealing with a trait, `super_traits` will be `Some`:
206     // Given `trait T: A + B + C {}`
207     //              -  ^^^^^^^^^ GenericBounds
208     //              |
209     //              &Ident
210     let span = generics.where_clause.span_for_predicates_or_empty_place();
211     if span.from_expansion() || span.desugaring_kind().is_some() {
212         return;
213     }
214     // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
215     if let Some((bound_str, fn_sig)) =
216         fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
217             // Shenanigans to get the `Trait` from the `impl Trait`.
218             ty::Param(param) => {
219                 // `fn foo(t: impl Trait)`
220                 //                 ^^^^^ get this string
221                 param.name.as_str().strip_prefix("impl").map(|s| (s.trim_start().to_string(), sig))
222             }
223             _ => None,
224         })
225     {
226         // We know we have an `impl Trait` that doesn't satisfy a required projection.
227
228         // Find all of the ocurrences of `impl Trait` for `Trait` in the function arguments'
229         // types. There should be at least one, but there might be *more* than one. In that
230         // case we could just ignore it and try to identify which one needs the restriction,
231         // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
232         // where `T: Trait`.
233         let mut ty_spans = vec![];
234         let impl_trait_str = format!("impl {}", bound_str);
235         for input in fn_sig.decl.inputs {
236             if let hir::TyKind::Path(hir::QPath::Resolved(
237                 None,
238                 hir::Path { segments: [segment], .. },
239             )) = input.kind
240             {
241                 if segment.ident.as_str() == impl_trait_str.as_str() {
242                     // `fn foo(t: impl Trait)`
243                     //            ^^^^^^^^^^ get this to suggest `T` instead
244
245                     // There might be more than one `impl Trait`.
246                     ty_spans.push(input.span);
247                 }
248             }
249         }
250
251         let type_param_name = generics.params.next_type_param_name(Some(&bound_str));
252         // The type param `T: Trait` we will suggest to introduce.
253         let type_param = format!("{}: {}", type_param_name, bound_str);
254
255         // FIXME: modify the `trait_ref` instead of string shenanigans.
256         // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
257         let pred = trait_ref.without_const().to_predicate(tcx).to_string();
258         let pred = pred.replace(&impl_trait_str, &type_param_name);
259         let mut sugg = vec![
260             // Find the last of the generic parameters contained within the span of
261             // the generics
262             match generics
263                 .params
264                 .iter()
265                 .map(|p| p.bounds_span().unwrap_or(p.span))
266                 .filter(|&span| generics.span.contains(span) && span.desugaring_kind().is_none())
267                 .max_by_key(|span| span.hi())
268             {
269                 // `fn foo(t: impl Trait)`
270                 //        ^ suggest `<T: Trait>` here
271                 None => (generics.span, format!("<{}>", type_param)),
272                 // `fn foo<A>(t: impl Trait)`
273                 //        ^^^ suggest `<A, T: Trait>` here
274                 Some(span) => (span.shrink_to_hi(), format!(", {}", type_param)),
275             },
276             // `fn foo(t: impl Trait)`
277             //                       ^ suggest `where <T as Trait>::A: Bound`
278             predicate_constraint(generics, pred),
279         ];
280         sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
281
282         // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
283         // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
284         // `fn foo(t: impl Trait<A: Bound>)` instead.
285         err.multipart_suggestion(
286             "introduce a type parameter with a trait bound instead of using `impl Trait`",
287             sugg,
288             Applicability::MaybeIncorrect,
289         );
290     } else {
291         // Trivial case: `T` needs an extra bound: `T: Bound`.
292         let (sp, suggestion) = match (
293             generics
294                 .params
295                 .iter()
296                 .filter(|p| {
297                     !matches!(p.kind, hir::GenericParamKind::Type { synthetic: Some(_), .. })
298                 })
299                 .next(),
300             super_traits,
301         ) {
302             (_, None) => predicate_constraint(
303                 generics,
304                 trait_ref.without_const().to_predicate(tcx).to_string(),
305             ),
306             (None, Some((ident, []))) => (
307                 ident.span.shrink_to_hi(),
308                 format!(": {}", trait_ref.print_only_trait_path().to_string()),
309             ),
310             (_, Some((_, [.., bounds]))) => (
311                 bounds.span().shrink_to_hi(),
312                 format!(" + {}", trait_ref.print_only_trait_path().to_string()),
313             ),
314             (Some(_), Some((_, []))) => (
315                 generics.span.shrink_to_hi(),
316                 format!(": {}", trait_ref.print_only_trait_path().to_string()),
317             ),
318         };
319
320         err.span_suggestion_verbose(
321             sp,
322             &format!("consider further restricting {}", msg),
323             suggestion,
324             Applicability::MachineApplicable,
325         );
326     }
327 }
328
329 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
330     fn suggest_restricting_param_bound(
331         &self,
332         mut err: &mut DiagnosticBuilder<'_>,
333         trait_ref: ty::PolyTraitRef<'tcx>,
334         body_id: hir::HirId,
335     ) {
336         let self_ty = trait_ref.skip_binder().self_ty();
337         let (param_ty, projection) = match self_ty.kind() {
338             ty::Param(_) => (true, None),
339             ty::Projection(projection) => (false, Some(projection)),
340             _ => (false, None),
341         };
342
343         // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
344         //        don't suggest `T: Sized + ?Sized`.
345         let mut hir_id = body_id;
346         while let Some(node) = self.tcx.hir().find(hir_id) {
347             match node {
348                 hir::Node::Item(hir::Item {
349                     ident,
350                     kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
351                     ..
352                 }) if self_ty == self.tcx.types.self_param => {
353                     assert!(param_ty);
354                     // Restricting `Self` for a single method.
355                     suggest_restriction(
356                         self.tcx,
357                         &generics,
358                         "`Self`",
359                         err,
360                         None,
361                         projection,
362                         trait_ref,
363                         Some((ident, bounds)),
364                     );
365                     return;
366                 }
367
368                 hir::Node::TraitItem(hir::TraitItem {
369                     generics,
370                     kind: hir::TraitItemKind::Fn(..),
371                     ..
372                 }) if self_ty == self.tcx.types.self_param => {
373                     assert!(param_ty);
374                     // Restricting `Self` for a single method.
375                     suggest_restriction(
376                         self.tcx, &generics, "`Self`", err, None, projection, trait_ref, None,
377                     );
378                     return;
379                 }
380
381                 hir::Node::TraitItem(hir::TraitItem {
382                     generics,
383                     kind: hir::TraitItemKind::Fn(fn_sig, ..),
384                     ..
385                 })
386                 | hir::Node::ImplItem(hir::ImplItem {
387                     generics,
388                     kind: hir::ImplItemKind::Fn(fn_sig, ..),
389                     ..
390                 })
391                 | hir::Node::Item(hir::Item {
392                     kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
393                 }) if projection.is_some() => {
394                     // Missing restriction on associated type of type parameter (unmet projection).
395                     suggest_restriction(
396                         self.tcx,
397                         &generics,
398                         "the associated type",
399                         err,
400                         Some(fn_sig),
401                         projection,
402                         trait_ref,
403                         None,
404                     );
405                     return;
406                 }
407                 hir::Node::Item(hir::Item {
408                     kind:
409                         hir::ItemKind::Trait(_, _, generics, _, _)
410                         | hir::ItemKind::Impl(hir::Impl { generics, .. }),
411                     ..
412                 }) if projection.is_some() => {
413                     // Missing restriction on associated type of type parameter (unmet projection).
414                     suggest_restriction(
415                         self.tcx,
416                         &generics,
417                         "the associated type",
418                         err,
419                         None,
420                         projection,
421                         trait_ref,
422                         None,
423                     );
424                     return;
425                 }
426
427                 hir::Node::Item(hir::Item {
428                     kind:
429                         hir::ItemKind::Struct(_, generics)
430                         | hir::ItemKind::Enum(_, generics)
431                         | hir::ItemKind::Union(_, generics)
432                         | hir::ItemKind::Trait(_, _, generics, ..)
433                         | hir::ItemKind::Impl(hir::Impl { generics, .. })
434                         | hir::ItemKind::Fn(_, generics, _)
435                         | hir::ItemKind::TyAlias(_, generics)
436                         | hir::ItemKind::TraitAlias(generics, _)
437                         | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
438                     ..
439                 })
440                 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
441                 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
442                     if param_ty =>
443                 {
444                     // Missing generic type parameter bound.
445                     let param_name = self_ty.to_string();
446                     let constraint =
447                         with_no_trimmed_paths(|| trait_ref.print_only_trait_path().to_string());
448                     if suggest_constraining_type_param(
449                         self.tcx,
450                         generics,
451                         &mut err,
452                         &param_name,
453                         &constraint,
454                         Some(trait_ref.def_id()),
455                     ) {
456                         return;
457                     }
458                 }
459
460                 hir::Node::Item(hir::Item {
461                     kind:
462                         hir::ItemKind::Struct(_, generics)
463                         | hir::ItemKind::Enum(_, generics)
464                         | hir::ItemKind::Union(_, generics)
465                         | hir::ItemKind::Trait(_, _, generics, ..)
466                         | hir::ItemKind::Impl(hir::Impl { generics, .. })
467                         | hir::ItemKind::Fn(_, generics, _)
468                         | hir::ItemKind::TyAlias(_, generics)
469                         | hir::ItemKind::TraitAlias(generics, _)
470                         | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
471                     ..
472                 }) if !param_ty => {
473                     // Missing generic type parameter bound.
474                     let param_name = self_ty.to_string();
475                     let constraint = trait_ref.print_only_trait_path().to_string();
476                     if suggest_arbitrary_trait_bound(generics, &mut err, &param_name, &constraint) {
477                         return;
478                     }
479                 }
480                 hir::Node::Crate(..) => return,
481
482                 _ => {}
483             }
484
485             hir_id = self.tcx.hir().get_parent_item(hir_id);
486         }
487     }
488
489     /// When after several dereferencing, the reference satisfies the trait
490     /// binding. This function provides dereference suggestion for this
491     /// specific situation.
492     fn suggest_dereferences(
493         &self,
494         obligation: &PredicateObligation<'tcx>,
495         err: &mut DiagnosticBuilder<'tcx>,
496         trait_ref: ty::PolyTraitRef<'tcx>,
497         points_at_arg: bool,
498     ) {
499         // It only make sense when suggesting dereferences for arguments
500         if !points_at_arg {
501             return;
502         }
503         let param_env = obligation.param_env;
504         let body_id = obligation.cause.body_id;
505         let span = obligation.cause.span;
506         let real_trait_ref = match &obligation.cause.code {
507             ObligationCauseCode::ImplDerivedObligation(cause)
508             | ObligationCauseCode::DerivedObligation(cause)
509             | ObligationCauseCode::BuiltinDerivedObligation(cause) => cause.parent_trait_ref,
510             _ => trait_ref,
511         };
512         let real_ty = match real_trait_ref.self_ty().no_bound_vars() {
513             Some(ty) => ty,
514             None => return,
515         };
516
517         if let ty::Ref(region, base_ty, mutbl) = *real_ty.kind() {
518             let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty, span);
519             if let Some(steps) = autoderef.find_map(|(ty, steps)| {
520                 // Re-add the `&`
521                 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
522                 let obligation =
523                     self.mk_trait_obligation_with_new_self_ty(param_env, real_trait_ref, ty);
524                 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
525             }) {
526                 if steps > 0 {
527                     if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
528                         // Don't care about `&mut` because `DerefMut` is used less
529                         // often and user will not expect autoderef happens.
530                         if src.starts_with('&') && !src.starts_with("&mut ") {
531                             let derefs = "*".repeat(steps);
532                             err.span_suggestion(
533                                 span,
534                                 "consider adding dereference here",
535                                 format!("&{}{}", derefs, &src[1..]),
536                                 Applicability::MachineApplicable,
537                             );
538                         }
539                     }
540                 }
541             }
542         }
543     }
544
545     /// Given a closure's `DefId`, return the given name of the closure.
546     ///
547     /// This doesn't account for reassignments, but it's only used for suggestions.
548     fn get_closure_name(
549         &self,
550         def_id: DefId,
551         err: &mut DiagnosticBuilder<'_>,
552         msg: &str,
553     ) -> Option<String> {
554         let get_name =
555             |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
556                 // Get the local name of this closure. This can be inaccurate because
557                 // of the possibility of reassignment, but this should be good enough.
558                 match &kind {
559                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
560                         Some(format!("{}", name))
561                     }
562                     _ => {
563                         err.note(&msg);
564                         None
565                     }
566                 }
567             };
568
569         let hir = self.tcx.hir();
570         let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
571         let parent_node = hir.get_parent_node(hir_id);
572         match hir.find(parent_node) {
573             Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
574                 get_name(err, &local.pat.kind)
575             }
576             // Different to previous arm because one is `&hir::Local` and the other
577             // is `P<hir::Local>`.
578             Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
579             _ => None,
580         }
581     }
582
583     /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
584     /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
585     /// it: `bar(foo)` â†’ `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
586     fn suggest_fn_call(
587         &self,
588         obligation: &PredicateObligation<'tcx>,
589         err: &mut DiagnosticBuilder<'_>,
590         trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
591         points_at_arg: bool,
592     ) {
593         let self_ty = match trait_ref.self_ty().no_bound_vars() {
594             None => return,
595             Some(ty) => ty,
596         };
597
598         let (def_id, output_ty, callable) = match *self_ty.kind() {
599             ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
600             ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
601             _ => return,
602         };
603         let msg = format!("use parentheses to call the {}", callable);
604
605         // `mk_trait_obligation_with_new_self_ty` only works for types with no escaping bound
606         // variables, so bail out if we have any.
607         let output_ty = match output_ty.no_bound_vars() {
608             Some(ty) => ty,
609             None => return,
610         };
611
612         let new_obligation =
613             self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_ref, output_ty);
614
615         match self.evaluate_obligation(&new_obligation) {
616             Ok(
617                 EvaluationResult::EvaluatedToOk
618                 | EvaluationResult::EvaluatedToOkModuloRegions
619                 | EvaluationResult::EvaluatedToAmbig,
620             ) => {}
621             _ => return,
622         }
623         let hir = self.tcx.hir();
624         // Get the name of the callable and the arguments to be used in the suggestion.
625         let (snippet, sugg) = match hir.get_if_local(def_id) {
626             Some(hir::Node::Expr(hir::Expr {
627                 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
628                 ..
629             })) => {
630                 err.span_label(*span, "consider calling this closure");
631                 let name = match self.get_closure_name(def_id, err, &msg) {
632                     Some(name) => name,
633                     None => return,
634                 };
635                 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
636                 let sugg = format!("({})", args);
637                 (format!("{}{}", name, sugg), sugg)
638             }
639             Some(hir::Node::Item(hir::Item {
640                 ident,
641                 kind: hir::ItemKind::Fn(.., body_id),
642                 ..
643             })) => {
644                 err.span_label(ident.span, "consider calling this function");
645                 let body = hir.body(*body_id);
646                 let args = body
647                     .params
648                     .iter()
649                     .map(|arg| match &arg.pat.kind {
650                         hir::PatKind::Binding(_, _, ident, None)
651                         // FIXME: provide a better suggestion when encountering `SelfLower`, it
652                         // should suggest a method call.
653                         if ident.name != kw::SelfLower => ident.to_string(),
654                         _ => "_".to_string(),
655                     })
656                     .collect::<Vec<_>>()
657                     .join(", ");
658                 let sugg = format!("({})", args);
659                 (format!("{}{}", ident, sugg), sugg)
660             }
661             _ => return,
662         };
663         if points_at_arg {
664             // When the obligation error has been ensured to have been caused by
665             // an argument, the `obligation.cause.span` points at the expression
666             // of the argument, so we can provide a suggestion. This is signaled
667             // by `points_at_arg`. Otherwise, we give a more general note.
668             err.span_suggestion_verbose(
669                 obligation.cause.span.shrink_to_hi(),
670                 &msg,
671                 sugg,
672                 Applicability::HasPlaceholders,
673             );
674         } else {
675             err.help(&format!("{}: `{}`", msg, snippet));
676         }
677     }
678
679     fn suggest_add_reference_to_arg(
680         &self,
681         obligation: &PredicateObligation<'tcx>,
682         err: &mut DiagnosticBuilder<'_>,
683         trait_ref: &ty::Binder<'tcx, ty::TraitRef<'tcx>>,
684         points_at_arg: bool,
685         has_custom_message: bool,
686     ) -> bool {
687         if !points_at_arg {
688             return false;
689         }
690
691         // List of traits for which it would be nonsensical to suggest borrowing.
692         // For instance, immutable references are always Copy, so suggesting to
693         // borrow would always succeed, but it's probably not what the user wanted.
694         let mut never_suggest_borrow: Vec<_> =
695             [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
696                 .iter()
697                 .filter_map(|lang_item| self.tcx.lang_items().require(*lang_item).ok())
698                 .collect();
699
700         never_suggest_borrow.push(self.tcx.get_diagnostic_item(sym::send_trait).unwrap());
701
702         let span = obligation.cause.span;
703         let param_env = obligation.param_env;
704         let trait_ref = trait_ref.skip_binder();
705
706         let found_ty = trait_ref.self_ty();
707         let found_ty_str = found_ty.to_string();
708         let imm_borrowed_found_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, found_ty);
709         let imm_substs = self.tcx.mk_substs_trait(imm_borrowed_found_ty, &[]);
710         let mut_borrowed_found_ty = self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, found_ty);
711         let mut_substs = self.tcx.mk_substs_trait(mut_borrowed_found_ty, &[]);
712
713         // Try to apply the original trait binding obligation by borrowing.
714         let mut try_borrowing = |new_trait_ref: ty::TraitRef<'tcx>,
715                                  expected_trait_ref: ty::TraitRef<'tcx>,
716                                  mtbl: bool,
717                                  blacklist: &[DefId]|
718          -> bool {
719             if blacklist.contains(&expected_trait_ref.def_id) {
720                 return false;
721             }
722
723             let new_obligation = Obligation::new(
724                 ObligationCause::dummy(),
725                 param_env,
726                 new_trait_ref.without_const().to_predicate(self.tcx),
727             );
728
729             if self.predicate_must_hold_modulo_regions(&new_obligation) {
730                 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
731                     // We have a very specific type of error, where just borrowing this argument
732                     // might solve the problem. In cases like this, the important part is the
733                     // original type obligation, not the last one that failed, which is arbitrary.
734                     // Because of this, we modify the error to refer to the original obligation and
735                     // return early in the caller.
736
737                     let msg = format!(
738                         "the trait bound `{}: {}` is not satisfied",
739                         found_ty_str,
740                         expected_trait_ref.print_only_trait_path(),
741                     );
742                     if has_custom_message {
743                         err.note(&msg);
744                     } else {
745                         err.message = vec![(msg, Style::NoStyle)];
746                     }
747                     if snippet.starts_with('&') {
748                         // This is already a literal borrow and the obligation is failing
749                         // somewhere else in the obligation chain. Do not suggest non-sense.
750                         return false;
751                     }
752                     err.span_label(
753                         span,
754                         &format!(
755                             "expected an implementor of trait `{}`",
756                             expected_trait_ref.print_only_trait_path(),
757                         ),
758                     );
759
760                     // This if is to prevent a special edge-case
761                     if !span.from_expansion() {
762                         // We don't want a borrowing suggestion on the fields in structs,
763                         // ```
764                         // struct Foo {
765                         //  the_foos: Vec<Foo>
766                         // }
767                         // ```
768
769                         err.span_suggestion(
770                             span,
771                             &format!(
772                                 "consider{} borrowing here",
773                                 if mtbl { " mutably" } else { "" }
774                             ),
775                             format!("&{}{}", if mtbl { "mut " } else { "" }, snippet),
776                             Applicability::MaybeIncorrect,
777                         );
778                     }
779                     return true;
780                 }
781             }
782             return false;
783         };
784
785         if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
786             let expected_trait_ref = obligation.parent_trait_ref.skip_binder();
787             let new_imm_trait_ref =
788                 ty::TraitRef::new(obligation.parent_trait_ref.def_id(), imm_substs);
789             let new_mut_trait_ref =
790                 ty::TraitRef::new(obligation.parent_trait_ref.def_id(), mut_substs);
791             if try_borrowing(new_imm_trait_ref, expected_trait_ref, false, &[]) {
792                 return true;
793             } else {
794                 return try_borrowing(new_mut_trait_ref, expected_trait_ref, true, &[]);
795             }
796         } else if let ObligationCauseCode::BindingObligation(_, _)
797         | ObligationCauseCode::ItemObligation(_) = &obligation.cause.code
798         {
799             if try_borrowing(
800                 ty::TraitRef::new(trait_ref.def_id, imm_substs),
801                 trait_ref,
802                 false,
803                 &never_suggest_borrow[..],
804             ) {
805                 return true;
806             } else {
807                 return try_borrowing(
808                     ty::TraitRef::new(trait_ref.def_id, mut_substs),
809                     trait_ref,
810                     true,
811                     &never_suggest_borrow[..],
812                 );
813             }
814         } else {
815             false
816         }
817     }
818
819     /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
820     /// suggest removing these references until we reach a type that implements the trait.
821     fn suggest_remove_reference(
822         &self,
823         obligation: &PredicateObligation<'tcx>,
824         err: &mut DiagnosticBuilder<'_>,
825         trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
826     ) {
827         let span = obligation.cause.span;
828
829         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
830             let refs_number =
831                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
832             if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
833                 // Do not suggest removal of borrow from type arguments.
834                 return;
835             }
836
837             let mut suggested_ty = match trait_ref.self_ty().no_bound_vars() {
838                 Some(ty) => ty,
839                 None => return,
840             };
841
842             for refs_remaining in 0..refs_number {
843                 if let ty::Ref(_, inner_ty, _) = suggested_ty.kind() {
844                     suggested_ty = inner_ty;
845
846                     let new_obligation = self.mk_trait_obligation_with_new_self_ty(
847                         obligation.param_env,
848                         trait_ref,
849                         suggested_ty,
850                     );
851
852                     if self.predicate_may_hold(&new_obligation) {
853                         let sp = self
854                             .tcx
855                             .sess
856                             .source_map()
857                             .span_take_while(span, |c| c.is_whitespace() || *c == '&');
858
859                         let remove_refs = refs_remaining + 1;
860
861                         let msg = if remove_refs == 1 {
862                             "consider removing the leading `&`-reference".to_string()
863                         } else {
864                             format!("consider removing {} leading `&`-references", remove_refs)
865                         };
866
867                         err.span_suggestion_short(
868                             sp,
869                             &msg,
870                             String::new(),
871                             Applicability::MachineApplicable,
872                         );
873                         break;
874                     }
875                 } else {
876                     break;
877                 }
878             }
879         }
880     }
881
882     /// Check if the trait bound is implemented for a different mutability and note it in the
883     /// final error.
884     fn suggest_change_mut(
885         &self,
886         obligation: &PredicateObligation<'tcx>,
887         err: &mut DiagnosticBuilder<'_>,
888         trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
889         points_at_arg: bool,
890     ) {
891         let span = obligation.cause.span;
892         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
893             let refs_number =
894                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
895             if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
896                 // Do not suggest removal of borrow from type arguments.
897                 return;
898             }
899             let trait_ref = self.resolve_vars_if_possible(trait_ref);
900             if trait_ref.has_infer_types_or_consts() {
901                 // Do not ICE while trying to find if a reborrow would succeed on a trait with
902                 // unresolved bindings.
903                 return;
904             }
905
906             if let ty::Ref(region, t_type, mutability) = *trait_ref.skip_binder().self_ty().kind() {
907                 if region.is_late_bound() || t_type.has_escaping_bound_vars() {
908                     // Avoid debug assertion in `mk_obligation_for_def_id`.
909                     //
910                     // If the self type has escaping bound vars then it's not
911                     // going to be the type of an expression, so the suggestion
912                     // probably won't apply anyway.
913                     return;
914                 }
915
916                 let suggested_ty = match mutability {
917                     hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
918                     hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
919                 };
920
921                 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
922                     obligation.param_env,
923                     trait_ref,
924                     suggested_ty,
925                 );
926                 let suggested_ty_would_satisfy_obligation = self
927                     .evaluate_obligation_no_overflow(&new_obligation)
928                     .must_apply_modulo_regions();
929                 if suggested_ty_would_satisfy_obligation {
930                     let sp = self
931                         .tcx
932                         .sess
933                         .source_map()
934                         .span_take_while(span, |c| c.is_whitespace() || *c == '&');
935                     if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
936                         err.span_suggestion_verbose(
937                             sp,
938                             "consider changing this borrow's mutability",
939                             "&mut ".to_string(),
940                             Applicability::MachineApplicable,
941                         );
942                     } else {
943                         err.note(&format!(
944                             "`{}` is implemented for `{:?}`, but not for `{:?}`",
945                             trait_ref.print_only_trait_path(),
946                             suggested_ty,
947                             trait_ref.skip_binder().self_ty(),
948                         ));
949                     }
950                 }
951             }
952         }
953     }
954
955     fn suggest_semicolon_removal(
956         &self,
957         obligation: &PredicateObligation<'tcx>,
958         err: &mut DiagnosticBuilder<'_>,
959         span: Span,
960         trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
961     ) {
962         let is_empty_tuple =
963             |ty: ty::Binder<'tcx, Ty<'_>>| *ty.skip_binder().kind() == ty::Tuple(ty::List::empty());
964
965         let hir = self.tcx.hir();
966         let parent_node = hir.get_parent_node(obligation.cause.body_id);
967         let node = hir.find(parent_node);
968         if let Some(hir::Node::Item(hir::Item {
969             kind: hir::ItemKind::Fn(sig, _, body_id), ..
970         })) = node
971         {
972             let body = hir.body(*body_id);
973             if let hir::ExprKind::Block(blk, _) = &body.value.kind {
974                 if sig.decl.output.span().overlaps(span)
975                     && blk.expr.is_none()
976                     && is_empty_tuple(trait_ref.self_ty())
977                 {
978                     // FIXME(estebank): When encountering a method with a trait
979                     // bound not satisfied in the return type with a body that has
980                     // no return, suggest removal of semicolon on last statement.
981                     // Once that is added, close #54771.
982                     if let Some(ref stmt) = blk.stmts.last() {
983                         if let hir::StmtKind::Semi(_) = stmt.kind {
984                             let sp = self.tcx.sess.source_map().end_point(stmt.span);
985                             err.span_label(sp, "consider removing this semicolon");
986                         }
987                     }
988                 }
989             }
990         }
991     }
992
993     fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
994         let hir = self.tcx.hir();
995         let parent_node = hir.get_parent_node(obligation.cause.body_id);
996         let sig = match hir.find(parent_node) {
997             Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) => sig,
998             _ => return None,
999         };
1000
1001         if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1002     }
1003
1004     /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1005     /// applicable and signal that the error has been expanded appropriately and needs to be
1006     /// emitted.
1007     fn suggest_impl_trait(
1008         &self,
1009         err: &mut DiagnosticBuilder<'_>,
1010         span: Span,
1011         obligation: &PredicateObligation<'tcx>,
1012         trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
1013     ) -> bool {
1014         match obligation.cause.code.peel_derives() {
1015             // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1016             ObligationCauseCode::SizedReturnType => {}
1017             _ => return false,
1018         }
1019
1020         let hir = self.tcx.hir();
1021         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1022         let node = hir.find(parent_node);
1023         let (sig, body_id) = if let Some(hir::Node::Item(hir::Item {
1024             kind: hir::ItemKind::Fn(sig, _, body_id),
1025             ..
1026         })) = node
1027         {
1028             (sig, body_id)
1029         } else {
1030             return false;
1031         };
1032         let body = hir.body(*body_id);
1033         let trait_ref = self.resolve_vars_if_possible(trait_ref);
1034         let ty = trait_ref.skip_binder().self_ty();
1035         let is_object_safe = match ty.kind() {
1036             ty::Dynamic(predicates, _) => {
1037                 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1038                 predicates
1039                     .principal_def_id()
1040                     .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1041             }
1042             // We only want to suggest `impl Trait` to `dyn Trait`s.
1043             // For example, `fn foo() -> str` needs to be filtered out.
1044             _ => return false,
1045         };
1046
1047         let ret_ty = if let hir::FnRetTy::Return(ret_ty) = sig.decl.output {
1048             ret_ty
1049         } else {
1050             return false;
1051         };
1052
1053         // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1054         // cases like `fn foo() -> (dyn Trait, i32) {}`.
1055         // Recursively look for `TraitObject` types and if there's only one, use that span to
1056         // suggest `impl Trait`.
1057
1058         // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1059         // otherwise suggest using `Box<dyn Trait>` or an enum.
1060         let mut visitor = ReturnsVisitor::default();
1061         visitor.visit_body(&body);
1062
1063         let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1064
1065         let mut ret_types = visitor
1066             .returns
1067             .iter()
1068             .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1069             .map(|ty| self.resolve_vars_if_possible(ty));
1070         let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1071             (None, true, true),
1072             |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1073              ty| {
1074                 let ty = self.resolve_vars_if_possible(ty);
1075                 same &=
1076                     !matches!(ty.kind(), ty::Error(_))
1077                         && last_ty.map_or(true, |last_ty| {
1078                             // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1079                             // *after* in the dependency graph.
1080                             match (ty.kind(), last_ty.kind()) {
1081                                 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1082                                 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1083                                 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1084                                 | (
1085                                     Infer(InferTy::FreshFloatTy(_)),
1086                                     Infer(InferTy::FreshFloatTy(_)),
1087                                 ) => true,
1088                                 _ => ty == last_ty,
1089                             }
1090                         });
1091                 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1092             },
1093         );
1094         let all_returns_conform_to_trait =
1095             if let Some(ty_ret_ty) = typeck_results.node_type_opt(ret_ty.hir_id) {
1096                 match ty_ret_ty.kind() {
1097                     ty::Dynamic(predicates, _) => {
1098                         let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
1099                         let param_env = ty::ParamEnv::empty();
1100                         only_never_return
1101                             || ret_types.all(|returned_ty| {
1102                                 predicates.iter().all(|predicate| {
1103                                     let pred = predicate.with_self_ty(self.tcx, returned_ty);
1104                                     let obl = Obligation::new(cause.clone(), param_env, pred);
1105                                     self.predicate_may_hold(&obl)
1106                                 })
1107                             })
1108                     }
1109                     _ => false,
1110                 }
1111             } else {
1112                 true
1113             };
1114
1115         let sm = self.tcx.sess.source_map();
1116         let snippet = if let (true, hir::TyKind::TraitObject(..), Ok(snippet), true) = (
1117             // Verify that we're dealing with a return `dyn Trait`
1118             ret_ty.span.overlaps(span),
1119             &ret_ty.kind,
1120             sm.span_to_snippet(ret_ty.span),
1121             // If any of the return types does not conform to the trait, then we can't
1122             // suggest `impl Trait` nor trait objects: it is a type mismatch error.
1123             all_returns_conform_to_trait,
1124         ) {
1125             snippet
1126         } else {
1127             return false;
1128         };
1129         err.code(error_code!(E0746));
1130         err.set_primary_message("return type cannot have an unboxed trait object");
1131         err.children.clear();
1132         let impl_trait_msg = "for information on `impl Trait`, see \
1133             <https://doc.rust-lang.org/book/ch10-02-traits.html\
1134             #returning-types-that-implement-traits>";
1135         let trait_obj_msg = "for information on trait objects, see \
1136             <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1137             #using-trait-objects-that-allow-for-values-of-different-types>";
1138         let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1139         let trait_obj = if has_dyn { &snippet[4..] } else { &snippet[..] };
1140         if only_never_return {
1141             // No return paths, probably using `panic!()` or similar.
1142             // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1143             suggest_trait_object_return_type_alternatives(
1144                 err,
1145                 ret_ty.span,
1146                 trait_obj,
1147                 is_object_safe,
1148             );
1149         } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1150             // Suggest `-> impl Trait`.
1151             err.span_suggestion(
1152                 ret_ty.span,
1153                 &format!(
1154                     "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1155                      which implements `{1}`",
1156                     last_ty, trait_obj,
1157                 ),
1158                 format!("impl {}", trait_obj),
1159                 Applicability::MachineApplicable,
1160             );
1161             err.note(impl_trait_msg);
1162         } else {
1163             if is_object_safe {
1164                 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1165                 // Get all the return values and collect their span and suggestion.
1166                 if let Some(mut suggestions) = visitor
1167                     .returns
1168                     .iter()
1169                     .map(|expr| {
1170                         let snip = sm.span_to_snippet(expr.span).ok()?;
1171                         Some((expr.span, format!("Box::new({})", snip)))
1172                     })
1173                     .collect::<Option<Vec<_>>>()
1174                 {
1175                     // Add the suggestion for the return type.
1176                     suggestions.push((ret_ty.span, format!("Box<dyn {}>", trait_obj)));
1177                     err.multipart_suggestion(
1178                         "return a boxed trait object instead",
1179                         suggestions,
1180                         Applicability::MaybeIncorrect,
1181                     );
1182                 }
1183             } else {
1184                 // This is currently not possible to trigger because E0038 takes precedence, but
1185                 // leave it in for completeness in case anything changes in an earlier stage.
1186                 err.note(&format!(
1187                     "if trait `{}` were object-safe, you could return a trait object",
1188                     trait_obj,
1189                 ));
1190             }
1191             err.note(trait_obj_msg);
1192             err.note(&format!(
1193                 "if all the returned values were of the same type you could use `impl {}` as the \
1194                  return type",
1195                 trait_obj,
1196             ));
1197             err.note(impl_trait_msg);
1198             err.note("you can create a new `enum` with a variant for each returned type");
1199         }
1200         true
1201     }
1202
1203     fn point_at_returns_when_relevant(
1204         &self,
1205         err: &mut DiagnosticBuilder<'_>,
1206         obligation: &PredicateObligation<'tcx>,
1207     ) {
1208         match obligation.cause.code.peel_derives() {
1209             ObligationCauseCode::SizedReturnType => {}
1210             _ => return,
1211         }
1212
1213         let hir = self.tcx.hir();
1214         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1215         let node = hir.find(parent_node);
1216         if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1217             node
1218         {
1219             let body = hir.body(*body_id);
1220             // Point at all the `return`s in the function as they have failed trait bounds.
1221             let mut visitor = ReturnsVisitor::default();
1222             visitor.visit_body(&body);
1223             let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1224             for expr in &visitor.returns {
1225                 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1226                     let ty = self.resolve_vars_if_possible(returned_ty);
1227                     err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1228                 }
1229             }
1230         }
1231     }
1232
1233     fn report_closure_arg_mismatch(
1234         &self,
1235         span: Span,
1236         found_span: Option<Span>,
1237         expected_ref: ty::PolyTraitRef<'tcx>,
1238         found: ty::PolyTraitRef<'tcx>,
1239     ) -> DiagnosticBuilder<'tcx> {
1240         crate fn build_fn_sig_string<'tcx>(
1241             tcx: TyCtxt<'tcx>,
1242             trait_ref: ty::PolyTraitRef<'tcx>,
1243         ) -> String {
1244             let inputs = trait_ref.skip_binder().substs.type_at(1);
1245             let sig = if let ty::Tuple(inputs) = inputs.kind() {
1246                 tcx.mk_fn_sig(
1247                     inputs.iter().map(|k| k.expect_ty()),
1248                     tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1249                     false,
1250                     hir::Unsafety::Normal,
1251                     abi::Abi::Rust,
1252                 )
1253             } else {
1254                 tcx.mk_fn_sig(
1255                     std::iter::once(inputs),
1256                     tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1257                     false,
1258                     hir::Unsafety::Normal,
1259                     abi::Abi::Rust,
1260                 )
1261             };
1262             trait_ref.rebind(sig).to_string()
1263         }
1264
1265         let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1266         let mut err = struct_span_err!(
1267             self.tcx.sess,
1268             span,
1269             E0631,
1270             "type mismatch in {} arguments",
1271             if argument_is_closure { "closure" } else { "function" }
1272         );
1273
1274         let found_str = format!("expected signature of `{}`", build_fn_sig_string(self.tcx, found));
1275         err.span_label(span, found_str);
1276
1277         let found_span = found_span.unwrap_or(span);
1278         let expected_str =
1279             format!("found signature of `{}`", build_fn_sig_string(self.tcx, expected_ref));
1280         err.span_label(found_span, expected_str);
1281
1282         err
1283     }
1284
1285     fn suggest_fully_qualified_path(
1286         &self,
1287         err: &mut DiagnosticBuilder<'_>,
1288         def_id: DefId,
1289         span: Span,
1290         trait_ref: DefId,
1291     ) {
1292         if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
1293             if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1294                 err.note(&format!(
1295                     "{}s cannot be accessed directly on a `trait`, they can only be \
1296                         accessed through a specific `impl`",
1297                     assoc_item.kind.as_def_kind().descr(def_id)
1298                 ));
1299                 err.span_suggestion(
1300                     span,
1301                     "use the fully qualified path to an implementation",
1302                     format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.ident),
1303                     Applicability::HasPlaceholders,
1304                 );
1305             }
1306         }
1307     }
1308
1309     /// Adds an async-await specific note to the diagnostic when the future does not implement
1310     /// an auto trait because of a captured type.
1311     ///
1312     /// ```text
1313     /// note: future does not implement `Qux` as this value is used across an await
1314     ///   --> $DIR/issue-64130-3-other.rs:17:5
1315     ///    |
1316     /// LL |     let x = Foo;
1317     ///    |         - has type `Foo`
1318     /// LL |     baz().await;
1319     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1320     /// LL | }
1321     ///    | - `x` is later dropped here
1322     /// ```
1323     ///
1324     /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1325     /// is "replaced" with a different message and a more specific error.
1326     ///
1327     /// ```text
1328     /// error: future cannot be sent between threads safely
1329     ///   --> $DIR/issue-64130-2-send.rs:21:5
1330     ///    |
1331     /// LL | fn is_send<T: Send>(t: T) { }
1332     ///    |               ---- required by this bound in `is_send`
1333     /// ...
1334     /// LL |     is_send(bar());
1335     ///    |     ^^^^^^^ future returned by `bar` is not send
1336     ///    |
1337     ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1338     ///            implemented for `Foo`
1339     /// note: future is not send as this value is used across an await
1340     ///   --> $DIR/issue-64130-2-send.rs:15:5
1341     ///    |
1342     /// LL |     let x = Foo;
1343     ///    |         - has type `Foo`
1344     /// LL |     baz().await;
1345     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1346     /// LL | }
1347     ///    | - `x` is later dropped here
1348     /// ```
1349     ///
1350     /// Returns `true` if an async-await specific note was added to the diagnostic.
1351     fn maybe_note_obligation_cause_for_async_await(
1352         &self,
1353         err: &mut DiagnosticBuilder<'_>,
1354         obligation: &PredicateObligation<'tcx>,
1355     ) -> bool {
1356         debug!(
1357             "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1358                 obligation.cause.span={:?}",
1359             obligation.predicate, obligation.cause.span
1360         );
1361         let hir = self.tcx.hir();
1362
1363         // Attempt to detect an async-await error by looking at the obligation causes, looking
1364         // for a generator to be present.
1365         //
1366         // When a future does not implement a trait because of a captured type in one of the
1367         // generators somewhere in the call stack, then the result is a chain of obligations.
1368         //
1369         // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
1370         // future is passed as an argument to a function C which requires a `Send` type, then the
1371         // chain looks something like this:
1372         //
1373         // - `BuiltinDerivedObligation` with a generator witness (B)
1374         // - `BuiltinDerivedObligation` with a generator (B)
1375         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1376         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1377         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1378         // - `BuiltinDerivedObligation` with a generator witness (A)
1379         // - `BuiltinDerivedObligation` with a generator (A)
1380         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1381         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1382         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1383         // - `BindingObligation` with `impl_send (Send requirement)
1384         //
1385         // The first obligation in the chain is the most useful and has the generator that captured
1386         // the type. The last generator (`outer_generator` below) has information about where the
1387         // bound was introduced. At least one generator should be present for this diagnostic to be
1388         // modified.
1389         let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1390             ty::PredicateKind::Trait(p, _) => (Some(p.trait_ref), Some(p.self_ty())),
1391             _ => (None, None),
1392         };
1393         let mut generator = None;
1394         let mut outer_generator = None;
1395         let mut next_code = Some(&obligation.cause.code);
1396
1397         let mut seen_upvar_tys_infer_tuple = false;
1398
1399         while let Some(code) = next_code {
1400             debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1401             match code {
1402                 ObligationCauseCode::DerivedObligation(derived_obligation)
1403                 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
1404                 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
1405                     let ty = derived_obligation.parent_trait_ref.skip_binder().self_ty();
1406                     debug!(
1407                         "maybe_note_obligation_cause_for_async_await: \
1408                             parent_trait_ref={:?} self_ty.kind={:?}",
1409                         derived_obligation.parent_trait_ref,
1410                         ty.kind()
1411                     );
1412
1413                     match *ty.kind() {
1414                         ty::Generator(did, ..) => {
1415                             generator = generator.or(Some(did));
1416                             outer_generator = Some(did);
1417                         }
1418                         ty::GeneratorWitness(..) => {}
1419                         ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1420                             // By introducing a tuple of upvar types into the chain of obligations
1421                             // of a generator, the first non-generator item is now the tuple itself,
1422                             // we shall ignore this.
1423
1424                             seen_upvar_tys_infer_tuple = true;
1425                         }
1426                         _ if generator.is_none() => {
1427                             trait_ref = Some(derived_obligation.parent_trait_ref.skip_binder());
1428                             target_ty = Some(ty);
1429                         }
1430                         _ => {}
1431                     }
1432
1433                     next_code = Some(derived_obligation.parent_code.as_ref());
1434                 }
1435                 _ => break,
1436             }
1437         }
1438
1439         // Only continue if a generator was found.
1440         debug!(
1441             "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
1442                 target_ty={:?}",
1443             generator, trait_ref, target_ty
1444         );
1445         let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
1446             (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
1447                 (generator_did, trait_ref, target_ty)
1448             }
1449             _ => return false,
1450         };
1451
1452         let span = self.tcx.def_span(generator_did);
1453
1454         // Do not ICE on closure typeck (#66868).
1455         if !generator_did.is_local() {
1456             return false;
1457         }
1458
1459         // Get the typeck results from the infcx if the generator is the function we are
1460         // currently type-checking; otherwise, get them by performing a query.
1461         // This is needed to avoid cycles.
1462         let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow());
1463         let generator_did_root = self.tcx.closure_base_def_id(generator_did);
1464         debug!(
1465             "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1466              generator_did_root={:?} in_progress_typeck_results.hir_owner={:?} span={:?}",
1467             generator_did,
1468             generator_did_root,
1469             in_progress_typeck_results.as_ref().map(|t| t.hir_owner),
1470             span
1471         );
1472         let query_typeck_results;
1473         let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
1474             Some(t) if t.hir_owner.to_def_id() == generator_did_root => t,
1475             _ => {
1476                 query_typeck_results = self.tcx.typeck(generator_did.expect_local());
1477                 &query_typeck_results
1478             }
1479         };
1480
1481         let generator_body = generator_did
1482             .as_local()
1483             .map(|def_id| hir.local_def_id_to_hir_id(def_id))
1484             .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1485             .map(|body_id| hir.body(body_id));
1486         let mut visitor = AwaitsVisitor::default();
1487         if let Some(body) = generator_body {
1488             visitor.visit_body(body);
1489         }
1490         debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1491
1492         // Look for a type inside the generator interior that matches the target type to get
1493         // a span.
1494         let target_ty_erased = self.tcx.erase_regions(target_ty);
1495         let ty_matches = |ty| -> bool {
1496             // Careful: the regions for types that appear in the
1497             // generator interior are not generally known, so we
1498             // want to erase them when comparing (and anyway,
1499             // `Send` and other bounds are generally unaffected by
1500             // the choice of region).  When erasing regions, we
1501             // also have to erase late-bound regions. This is
1502             // because the types that appear in the generator
1503             // interior generally contain "bound regions" to
1504             // represent regions that are part of the suspended
1505             // generator frame. Bound regions are preserved by
1506             // `erase_regions` and so we must also call
1507             // `erase_late_bound_regions`.
1508             let ty_erased = self.tcx.erase_late_bound_regions(ty);
1509             let ty_erased = self.tcx.erase_regions(ty_erased);
1510             let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
1511             debug!(
1512                 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1513                     target_ty_erased={:?} eq={:?}",
1514                 ty_erased, target_ty_erased, eq
1515             );
1516             eq
1517         };
1518
1519         let mut interior_or_upvar_span = None;
1520         let mut interior_extra_info = None;
1521
1522         if let Some(upvars) = self.tcx.upvars_mentioned(generator_did) {
1523             interior_or_upvar_span = upvars.iter().find_map(|(upvar_id, upvar)| {
1524                 let upvar_ty = typeck_results.node_type(*upvar_id);
1525                 let upvar_ty = self.resolve_vars_if_possible(upvar_ty);
1526                 if ty_matches(ty::Binder::dummy(upvar_ty)) {
1527                     Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
1528                 } else {
1529                     None
1530                 }
1531             });
1532         };
1533
1534         // The generator interior types share the same binders
1535         if let Some(cause) =
1536             typeck_results.generator_interior_types.as_ref().skip_binder().iter().find(
1537                 |ty::GeneratorInteriorTypeCause { ty, .. }| {
1538                     ty_matches(typeck_results.generator_interior_types.rebind(ty))
1539                 },
1540             )
1541         {
1542             // Check to see if any awaited expressions have the target type.
1543             let from_awaited_ty = visitor
1544                 .awaits
1545                 .into_iter()
1546                 .map(|id| hir.expect_expr(id))
1547                 .find(|await_expr| {
1548                     let ty = typeck_results.expr_ty_adjusted(&await_expr);
1549                     debug!(
1550                         "maybe_note_obligation_cause_for_async_await: await_expr={:?}",
1551                         await_expr
1552                     );
1553                     ty_matches(ty::Binder::dummy(ty))
1554                 })
1555                 .map(|expr| expr.span);
1556             let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
1557
1558             interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
1559             interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
1560         };
1561
1562         debug!(
1563             "maybe_note_obligation_cause_for_async_await: interior_or_upvar={:?} \
1564                 generator_interior_types={:?}",
1565             interior_or_upvar_span, typeck_results.generator_interior_types
1566         );
1567         if let Some(interior_or_upvar_span) = interior_or_upvar_span {
1568             self.note_obligation_cause_for_async_await(
1569                 err,
1570                 interior_or_upvar_span,
1571                 interior_extra_info,
1572                 generator_body,
1573                 outer_generator,
1574                 trait_ref,
1575                 target_ty,
1576                 typeck_results,
1577                 obligation,
1578                 next_code,
1579             );
1580             true
1581         } else {
1582             false
1583         }
1584     }
1585
1586     /// Unconditionally adds the diagnostic note described in
1587     /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1588     fn note_obligation_cause_for_async_await(
1589         &self,
1590         err: &mut DiagnosticBuilder<'_>,
1591         interior_or_upvar_span: GeneratorInteriorOrUpvar,
1592         interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
1593         inner_generator_body: Option<&hir::Body<'tcx>>,
1594         outer_generator: Option<DefId>,
1595         trait_ref: ty::TraitRef<'tcx>,
1596         target_ty: Ty<'tcx>,
1597         typeck_results: &ty::TypeckResults<'tcx>,
1598         obligation: &PredicateObligation<'tcx>,
1599         next_code: Option<&ObligationCauseCode<'tcx>>,
1600     ) {
1601         let source_map = self.tcx.sess.source_map();
1602
1603         let is_async = inner_generator_body
1604             .and_then(|body| body.generator_kind())
1605             .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1606             .unwrap_or(false);
1607         let (await_or_yield, an_await_or_yield) =
1608             if is_async { ("await", "an await") } else { ("yield", "a yield") };
1609         let future_or_generator = if is_async { "future" } else { "generator" };
1610
1611         // Special case the primary error message when send or sync is the trait that was
1612         // not implemented.
1613         let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
1614         let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
1615         let hir = self.tcx.hir();
1616         let trait_explanation = if is_send || is_sync {
1617             let (trait_name, trait_verb) =
1618                 if is_send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1619
1620             err.clear_code();
1621             err.set_primary_message(format!(
1622                 "{} cannot be {} between threads safely",
1623                 future_or_generator, trait_verb
1624             ));
1625
1626             let original_span = err.span.primary_span().unwrap();
1627             let mut span = MultiSpan::from_span(original_span);
1628
1629             let message = outer_generator
1630                 .and_then(|generator_did| {
1631                     Some(match self.tcx.generator_kind(generator_did).unwrap() {
1632                         GeneratorKind::Gen => format!("generator is not {}", trait_name),
1633                         GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1634                             .tcx
1635                             .parent(generator_did)
1636                             .and_then(|parent_did| parent_did.as_local())
1637                             .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
1638                             .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1639                             .map(|name| {
1640                                 format!("future returned by `{}` is not {}", name, trait_name)
1641                             })?,
1642                         GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1643                             format!("future created by async block is not {}", trait_name)
1644                         }
1645                         GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1646                             format!("future created by async closure is not {}", trait_name)
1647                         }
1648                     })
1649                 })
1650                 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1651
1652             span.push_span_label(original_span, message);
1653             err.set_span(span);
1654
1655             format!("is not {}", trait_name)
1656         } else {
1657             format!("does not implement `{}`", trait_ref.print_only_trait_path())
1658         };
1659
1660         let mut explain_yield =
1661             |interior_span: Span, yield_span: Span, scope_span: Option<Span>| {
1662                 let mut span = MultiSpan::from_span(yield_span);
1663                 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
1664                     // #70935: If snippet contains newlines, display "the value" instead
1665                     // so that we do not emit complex diagnostics.
1666                     let snippet = &format!("`{}`", snippet);
1667                     let snippet = if snippet.contains('\n') { "the value" } else { snippet };
1668                     // The multispan can be complex here, like:
1669                     // note: future is not `Send` as this value is used across an await
1670                     //   --> $DIR/issue-70935-complex-spans.rs:13:9
1671                     //    |
1672                     // LL |            baz(|| async{
1673                     //    |  __________^___-
1674                     //    | | _________|
1675                     //    | ||
1676                     // LL | ||             foo(tx.clone());
1677                     // LL | ||         }).await;
1678                     //    | ||         -      ^- value is later dropped here
1679                     //    | ||_________|______|
1680                     //    | |__________|      await occurs here, with value maybe used later
1681                     //    |            has type `closure` which is not `Send`
1682                     //
1683                     // So, detect it and separate into some notes, like:
1684                     //
1685                     // note: future is not `Send` as this value is used across an await
1686                     //   --> $DIR/issue-70935-complex-spans.rs:13:9
1687                     //    |
1688                     // LL | /         baz(|| async{
1689                     // LL | |             foo(tx.clone());
1690                     // LL | |         }).await;
1691                     //    | |________________^ first, await occurs here, with the value maybe used later...
1692                     // note: the value is later dropped here
1693                     //   --> $DIR/issue-70935-complex-spans.rs:15:17
1694                     //    |
1695                     // LL |         }).await;
1696                     //    |                 ^
1697                     //
1698                     // If available, use the scope span to annotate the drop location.
1699                     if let Some(scope_span) = scope_span {
1700                         let scope_span = source_map.end_point(scope_span);
1701                         let is_overlapped =
1702                             yield_span.overlaps(scope_span) || yield_span.overlaps(interior_span);
1703                         if is_overlapped {
1704                             span.push_span_label(
1705                                 yield_span,
1706                                 format!(
1707                                     "first, {} occurs here, with {} maybe used later...",
1708                                     await_or_yield, snippet
1709                                 ),
1710                             );
1711                             err.span_note(
1712                                 span,
1713                                 &format!(
1714                                     "{} {} as this value is used across {}",
1715                                     future_or_generator, trait_explanation, an_await_or_yield
1716                                 ),
1717                             );
1718                             if source_map.is_multiline(interior_span) {
1719                                 err.span_note(
1720                                     scope_span,
1721                                     &format!("{} is later dropped here", snippet),
1722                                 );
1723                                 err.span_note(
1724                                     interior_span,
1725                                     &format!(
1726                                         "this has type `{}` which {}",
1727                                         target_ty, trait_explanation
1728                                     ),
1729                                 );
1730                             } else {
1731                                 let mut span = MultiSpan::from_span(scope_span);
1732                                 span.push_span_label(
1733                                     interior_span,
1734                                     format!("has type `{}` which {}", target_ty, trait_explanation),
1735                                 );
1736                                 err.span_note(span, &format!("{} is later dropped here", snippet));
1737                             }
1738                         } else {
1739                             span.push_span_label(
1740                                 yield_span,
1741                                 format!(
1742                                     "{} occurs here, with {} maybe used later",
1743                                     await_or_yield, snippet
1744                                 ),
1745                             );
1746                             span.push_span_label(
1747                                 scope_span,
1748                                 format!("{} is later dropped here", snippet),
1749                             );
1750                             span.push_span_label(
1751                                 interior_span,
1752                                 format!("has type `{}` which {}", target_ty, trait_explanation),
1753                             );
1754                             err.span_note(
1755                                 span,
1756                                 &format!(
1757                                     "{} {} as this value is used across {}",
1758                                     future_or_generator, trait_explanation, an_await_or_yield
1759                                 ),
1760                             );
1761                         }
1762                     } else {
1763                         span.push_span_label(
1764                             yield_span,
1765                             format!(
1766                                 "{} occurs here, with {} maybe used later",
1767                                 await_or_yield, snippet
1768                             ),
1769                         );
1770                         span.push_span_label(
1771                             interior_span,
1772                             format!("has type `{}` which {}", target_ty, trait_explanation),
1773                         );
1774                         err.span_note(
1775                             span,
1776                             &format!(
1777                                 "{} {} as this value is used across {}",
1778                                 future_or_generator, trait_explanation, an_await_or_yield
1779                             ),
1780                         );
1781                     }
1782                 }
1783             };
1784         match interior_or_upvar_span {
1785             GeneratorInteriorOrUpvar::Interior(interior_span) => {
1786                 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
1787                     if let Some(await_span) = from_awaited_ty {
1788                         // The type causing this obligation is one being awaited at await_span.
1789                         let mut span = MultiSpan::from_span(await_span);
1790                         span.push_span_label(
1791                             await_span,
1792                             format!(
1793                                 "await occurs here on type `{}`, which {}",
1794                                 target_ty, trait_explanation
1795                             ),
1796                         );
1797                         err.span_note(
1798                             span,
1799                             &format!(
1800                                 "future {not_trait} as it awaits another future which {not_trait}",
1801                                 not_trait = trait_explanation
1802                             ),
1803                         );
1804                     } else {
1805                         // Look at the last interior type to get a span for the `.await`.
1806                         debug!(
1807                             "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
1808                             typeck_results.generator_interior_types
1809                         );
1810                         explain_yield(interior_span, yield_span, scope_span);
1811                     }
1812
1813                     if let Some(expr_id) = expr {
1814                         let expr = hir.expect_expr(expr_id);
1815                         debug!("target_ty evaluated from {:?}", expr);
1816
1817                         let parent = hir.get_parent_node(expr_id);
1818                         if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1819                             let parent_span = hir.span(parent);
1820                             let parent_did = parent.owner.to_def_id();
1821                             // ```rust
1822                             // impl T {
1823                             //     fn foo(&self) -> i32 {}
1824                             // }
1825                             // T.foo();
1826                             // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
1827                             // ```
1828                             //
1829                             let is_region_borrow = typeck_results
1830                                 .expr_adjustments(expr)
1831                                 .iter()
1832                                 .any(|adj| adj.is_region_borrow());
1833
1834                             // ```rust
1835                             // struct Foo(*const u8);
1836                             // bar(Foo(std::ptr::null())).await;
1837                             //     ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
1838                             // ```
1839                             debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
1840                             let is_raw_borrow_inside_fn_like_call =
1841                                 match self.tcx.def_kind(parent_did) {
1842                                     DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
1843                                     _ => false,
1844                                 };
1845
1846                             if (typeck_results.is_method_call(e) && is_region_borrow)
1847                                 || is_raw_borrow_inside_fn_like_call
1848                             {
1849                                 err.span_help(
1850                                     parent_span,
1851                                     "consider moving this into a `let` \
1852                         binding to create a shorter lived borrow",
1853                                 );
1854                             }
1855                         }
1856                     }
1857                 }
1858             }
1859             GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
1860                 let mut span = MultiSpan::from_span(upvar_span);
1861                 span.push_span_label(
1862                     upvar_span,
1863                     format!("has type `{}` which {}", target_ty, trait_explanation),
1864                 );
1865                 err.span_note(span, &format!("captured value {}", trait_explanation));
1866             }
1867         }
1868
1869         // Add a note for the item obligation that remains - normally a note pointing to the
1870         // bound that introduced the obligation (e.g. `T: Send`).
1871         debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
1872         self.note_obligation_cause_code(
1873             err,
1874             &obligation.predicate,
1875             next_code.unwrap(),
1876             &mut Vec::new(),
1877             &mut Default::default(),
1878         );
1879     }
1880
1881     fn note_obligation_cause_code<T>(
1882         &self,
1883         err: &mut DiagnosticBuilder<'_>,
1884         predicate: &T,
1885         cause_code: &ObligationCauseCode<'tcx>,
1886         obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1887         seen_requirements: &mut FxHashSet<DefId>,
1888     ) where
1889         T: fmt::Display,
1890     {
1891         let tcx = self.tcx;
1892         match *cause_code {
1893             ObligationCauseCode::ExprAssignable
1894             | ObligationCauseCode::MatchExpressionArm { .. }
1895             | ObligationCauseCode::Pattern { .. }
1896             | ObligationCauseCode::IfExpression { .. }
1897             | ObligationCauseCode::IfExpressionWithNoElse
1898             | ObligationCauseCode::MainFunctionType
1899             | ObligationCauseCode::StartFunctionType
1900             | ObligationCauseCode::IntrinsicType
1901             | ObligationCauseCode::MethodReceiver
1902             | ObligationCauseCode::ReturnNoExpression
1903             | ObligationCauseCode::UnifyReceiver(..)
1904             | ObligationCauseCode::OpaqueType
1905             | ObligationCauseCode::MiscObligation
1906             | ObligationCauseCode::WellFormed(..)
1907             | ObligationCauseCode::MatchImpl(..) => {}
1908             ObligationCauseCode::SliceOrArrayElem => {
1909                 err.note("slice and array elements must have `Sized` type");
1910             }
1911             ObligationCauseCode::TupleElem => {
1912                 err.note("only the last element of a tuple may have a dynamically sized type");
1913             }
1914             ObligationCauseCode::ProjectionWf(data) => {
1915                 err.note(&format!("required so that the projection `{}` is well-formed", data,));
1916             }
1917             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1918                 err.note(&format!(
1919                     "required so that reference `{}` does not outlive its referent",
1920                     ref_ty,
1921                 ));
1922             }
1923             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1924                 err.note(&format!(
1925                     "required so that the lifetime bound of `{}` for `{}` is satisfied",
1926                     region, object_ty,
1927                 ));
1928             }
1929             ObligationCauseCode::ItemObligation(item_def_id) => {
1930                 let item_name = tcx.def_path_str(item_def_id);
1931                 let msg = format!("required by `{}`", item_name);
1932                 let sp = tcx
1933                     .hir()
1934                     .span_if_local(item_def_id)
1935                     .unwrap_or_else(|| tcx.def_span(item_def_id));
1936                 let sp = tcx.sess.source_map().guess_head_span(sp);
1937                 err.span_note(sp, &msg);
1938             }
1939             ObligationCauseCode::BindingObligation(item_def_id, span) => {
1940                 let item_name = tcx.def_path_str(item_def_id);
1941                 let msg = format!("required by this bound in `{}`", item_name);
1942                 if let Some(ident) = tcx.opt_item_name(item_def_id) {
1943                     let sm = tcx.sess.source_map();
1944                     let same_line =
1945                         match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
1946                             (Ok(l), Ok(r)) => l.line == r.line,
1947                             _ => true,
1948                         };
1949                     if !ident.span.overlaps(span) && !same_line {
1950                         err.span_label(ident.span, "required by a bound in this");
1951                     }
1952                 }
1953                 if span != DUMMY_SP {
1954                     err.span_label(span, &msg);
1955                 } else {
1956                     err.span_note(
1957                         tcx.def_span(item_def_id),
1958                         &format!("required by a bound in `{}`", item_name),
1959                     );
1960                 }
1961             }
1962             ObligationCauseCode::ObjectCastObligation(object_ty) => {
1963                 err.note(&format!(
1964                     "required for the cast to the object type `{}`",
1965                     self.ty_to_string(object_ty)
1966                 ));
1967             }
1968             ObligationCauseCode::Coercion { source: _, target } => {
1969                 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
1970             }
1971             ObligationCauseCode::RepeatVec(is_const_fn) => {
1972                 err.note(
1973                     "the `Copy` trait is required because the repeated element will be copied",
1974                 );
1975
1976                 if is_const_fn {
1977                     err.help(
1978                         "consider creating a new `const` item and initializing it with the result \
1979                         of the function call to be used in the repeat position, like \
1980                         `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
1981                     );
1982                 }
1983
1984                 if self.tcx.sess.is_nightly_build() && is_const_fn {
1985                     err.help(
1986                         "create an inline `const` block, see RFC #2920 \
1987                          <https://github.com/rust-lang/rfcs/pull/2920> for more information",
1988                     );
1989                 }
1990             }
1991             ObligationCauseCode::VariableType(hir_id) => {
1992                 let parent_node = self.tcx.hir().get_parent_node(hir_id);
1993                 match self.tcx.hir().find(parent_node) {
1994                     Some(Node::Local(hir::Local {
1995                         init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
1996                         ..
1997                     })) => {
1998                         // When encountering an assignment of an unsized trait, like
1999                         // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2000                         // order to use have a slice instead.
2001                         err.span_suggestion_verbose(
2002                             span.shrink_to_lo(),
2003                             "consider borrowing here",
2004                             "&".to_owned(),
2005                             Applicability::MachineApplicable,
2006                         );
2007                         err.note("all local variables must have a statically known size");
2008                     }
2009                     Some(Node::Param(param)) => {
2010                         err.span_suggestion_verbose(
2011                             param.ty_span.shrink_to_lo(),
2012                             "function arguments must have a statically known size, borrowed types \
2013                             always have a known size",
2014                             "&".to_owned(),
2015                             Applicability::MachineApplicable,
2016                         );
2017                     }
2018                     _ => {
2019                         err.note("all local variables must have a statically known size");
2020                     }
2021                 }
2022                 if !self.tcx.features().unsized_locals {
2023                     err.help("unsized locals are gated as an unstable feature");
2024                 }
2025             }
2026             ObligationCauseCode::SizedArgumentType(sp) => {
2027                 if let Some(span) = sp {
2028                     err.span_suggestion_verbose(
2029                         span.shrink_to_lo(),
2030                         "function arguments must have a statically known size, borrowed types \
2031                          always have a known size",
2032                         "&".to_string(),
2033                         Applicability::MachineApplicable,
2034                     );
2035                 } else {
2036                     err.note("all function arguments must have a statically known size");
2037                 }
2038                 if tcx.sess.opts.unstable_features.is_nightly_build()
2039                     && !self.tcx.features().unsized_fn_params
2040                 {
2041                     err.help("unsized fn params are gated as an unstable feature");
2042                 }
2043             }
2044             ObligationCauseCode::SizedReturnType => {
2045                 err.note("the return type of a function must have a statically known size");
2046             }
2047             ObligationCauseCode::SizedYieldType => {
2048                 err.note("the yield type of a generator must have a statically known size");
2049             }
2050             ObligationCauseCode::AssignmentLhsSized => {
2051                 err.note("the left-hand-side of an assignment must have a statically known size");
2052             }
2053             ObligationCauseCode::TupleInitializerSized => {
2054                 err.note("tuples must have a statically known size to be initialized");
2055             }
2056             ObligationCauseCode::StructInitializerSized => {
2057                 err.note("structs must have a statically known size to be initialized");
2058             }
2059             ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2060                 match *item {
2061                     AdtKind::Struct => {
2062                         if last {
2063                             err.note(
2064                                 "the last field of a packed struct may only have a \
2065                                 dynamically sized type if it does not need drop to be run",
2066                             );
2067                         } else {
2068                             err.note(
2069                                 "only the last field of a struct may have a dynamically sized type",
2070                             );
2071                         }
2072                     }
2073                     AdtKind::Union => {
2074                         err.note("no field of a union may have a dynamically sized type");
2075                     }
2076                     AdtKind::Enum => {
2077                         err.note("no field of an enum variant may have a dynamically sized type");
2078                     }
2079                 }
2080                 err.help("change the field's type to have a statically known size");
2081                 err.span_suggestion(
2082                     span.shrink_to_lo(),
2083                     "borrowed types always have a statically known size",
2084                     "&".to_string(),
2085                     Applicability::MachineApplicable,
2086                 );
2087                 err.multipart_suggestion(
2088                     "the `Box` type always has a statically known size and allocates its contents \
2089                      in the heap",
2090                     vec![
2091                         (span.shrink_to_lo(), "Box<".to_string()),
2092                         (span.shrink_to_hi(), ">".to_string()),
2093                     ],
2094                     Applicability::MachineApplicable,
2095                 );
2096             }
2097             ObligationCauseCode::ConstSized => {
2098                 err.note("constant expressions must have a statically known size");
2099             }
2100             ObligationCauseCode::InlineAsmSized => {
2101                 err.note("all inline asm arguments must have a statically known size");
2102             }
2103             ObligationCauseCode::ConstPatternStructural => {
2104                 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2105             }
2106             ObligationCauseCode::SharedStatic => {
2107                 err.note("shared static variables must have a type that implements `Sync`");
2108             }
2109             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2110                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2111                 let ty = parent_trait_ref.skip_binder().self_ty();
2112                 if parent_trait_ref.references_error() {
2113                     err.cancel();
2114                     return;
2115                 }
2116
2117                 // If the obligation for a tuple is set directly by a Generator or Closure,
2118                 // then the tuple must be the one containing capture types.
2119                 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2120                     false
2121                 } else {
2122                     if let ObligationCauseCode::BuiltinDerivedObligation(ref data) =
2123                         *data.parent_code
2124                     {
2125                         let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2126                         let ty = parent_trait_ref.skip_binder().self_ty();
2127                         matches!(ty.kind(), ty::Generator(..))
2128                             || matches!(ty.kind(), ty::Closure(..))
2129                     } else {
2130                         false
2131                     }
2132                 };
2133
2134                 // Don't print the tuple of capture types
2135                 if !is_upvar_tys_infer_tuple {
2136                     let msg = format!("required because it appears within the type `{}`", ty);
2137                     match ty.kind() {
2138                         ty::Adt(def, _) => match self.tcx.opt_item_name(def.did) {
2139                             Some(ident) => err.span_note(ident.span, &msg),
2140                             None => err.note(&msg),
2141                         },
2142                         _ => err.note(&msg),
2143                     };
2144                 }
2145
2146                 obligated_types.push(ty);
2147
2148                 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
2149                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2150                     // #74711: avoid a stack overflow
2151                     ensure_sufficient_stack(|| {
2152                         self.note_obligation_cause_code(
2153                             err,
2154                             &parent_predicate,
2155                             &data.parent_code,
2156                             obligated_types,
2157                             seen_requirements,
2158                         )
2159                     });
2160                 }
2161             }
2162             ObligationCauseCode::ImplDerivedObligation(ref data) => {
2163                 let mut parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2164                 let parent_def_id = parent_trait_ref.def_id();
2165                 let msg = format!(
2166                     "required because of the requirements on the impl of `{}` for `{}`",
2167                     parent_trait_ref.print_only_trait_path(),
2168                     parent_trait_ref.skip_binder().self_ty()
2169                 );
2170                 let mut candidates = vec![];
2171                 self.tcx.for_each_relevant_impl(
2172                     parent_def_id,
2173                     parent_trait_ref.self_ty().skip_binder(),
2174                     |impl_def_id| match self.tcx.hir().get_if_local(impl_def_id) {
2175                         Some(Node::Item(hir::Item {
2176                             kind: hir::ItemKind::Impl(hir::Impl { .. }),
2177                             ..
2178                         })) => {
2179                             candidates.push(impl_def_id);
2180                         }
2181                         _ => {}
2182                     },
2183                 );
2184                 match &candidates[..] {
2185                     [def_id] => match self.tcx.hir().get_if_local(*def_id) {
2186                         Some(Node::Item(hir::Item {
2187                             kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2188                             ..
2189                         })) => {
2190                             let mut spans = Vec::with_capacity(2);
2191                             if let Some(trait_ref) = of_trait {
2192                                 spans.push(trait_ref.path.span);
2193                             }
2194                             spans.push(self_ty.span);
2195                             err.span_note(spans, &msg)
2196                         }
2197                         _ => err.note(&msg),
2198                     },
2199                     _ => err.note(&msg),
2200                 };
2201
2202                 let mut parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
2203                 let mut data = data;
2204                 let mut count = 0;
2205                 seen_requirements.insert(parent_def_id);
2206                 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2207                     // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2208                     let child_trait_ref = self.resolve_vars_if_possible(child.parent_trait_ref);
2209                     let child_def_id = child_trait_ref.def_id();
2210                     if seen_requirements.insert(child_def_id) {
2211                         break;
2212                     }
2213                     count += 1;
2214                     data = child;
2215                     parent_predicate = child_trait_ref.without_const().to_predicate(tcx);
2216                     parent_trait_ref = child_trait_ref;
2217                 }
2218                 if count > 0 {
2219                     err.note(&format!("{} redundant requirements hidden", count));
2220                     err.note(&format!(
2221                         "required because of the requirements on the impl of `{}` for `{}`",
2222                         parent_trait_ref.print_only_trait_path(),
2223                         parent_trait_ref.skip_binder().self_ty()
2224                     ));
2225                 }
2226                 // #74711: avoid a stack overflow
2227                 ensure_sufficient_stack(|| {
2228                     self.note_obligation_cause_code(
2229                         err,
2230                         &parent_predicate,
2231                         &data.parent_code,
2232                         obligated_types,
2233                         seen_requirements,
2234                     )
2235                 });
2236             }
2237             ObligationCauseCode::DerivedObligation(ref data) => {
2238                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2239                 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
2240                 // #74711: avoid a stack overflow
2241                 ensure_sufficient_stack(|| {
2242                     self.note_obligation_cause_code(
2243                         err,
2244                         &parent_predicate,
2245                         &data.parent_code,
2246                         obligated_types,
2247                         seen_requirements,
2248                     )
2249                 });
2250             }
2251             ObligationCauseCode::CompareImplMethodObligation {
2252                 item_name,
2253                 trait_item_def_id,
2254                 ..
2255             } => {
2256                 let msg = format!(
2257                     "the requirement `{}` appears on the impl method `{}` but not on the \
2258                      corresponding trait method",
2259                     predicate, item_name,
2260                 );
2261                 let sp = self
2262                     .tcx
2263                     .opt_item_name(trait_item_def_id)
2264                     .map(|i| i.span)
2265                     .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2266                 let mut assoc_span: MultiSpan = sp.into();
2267                 assoc_span.push_span_label(
2268                     sp,
2269                     format!("this trait method doesn't have the requirement `{}`", predicate),
2270                 );
2271                 if let Some(ident) = self
2272                     .tcx
2273                     .opt_associated_item(trait_item_def_id)
2274                     .and_then(|i| self.tcx.opt_item_name(i.container.id()))
2275                 {
2276                     assoc_span.push_span_label(ident.span, "in this trait".into());
2277                 }
2278                 err.span_note(assoc_span, &msg);
2279             }
2280             ObligationCauseCode::CompareImplTypeObligation {
2281                 item_name, trait_item_def_id, ..
2282             } => {
2283                 let msg = format!(
2284                     "the requirement `{}` appears on the associated impl type `{}` but not on the \
2285                      corresponding associated trait type",
2286                     predicate, item_name,
2287                 );
2288                 let sp = self.tcx.def_span(trait_item_def_id);
2289                 let mut assoc_span: MultiSpan = sp.into();
2290                 assoc_span.push_span_label(
2291                     sp,
2292                     format!(
2293                         "this trait associated type doesn't have the requirement `{}`",
2294                         predicate,
2295                     ),
2296                 );
2297                 if let Some(ident) = self
2298                     .tcx
2299                     .opt_associated_item(trait_item_def_id)
2300                     .and_then(|i| self.tcx.opt_item_name(i.container.id()))
2301                 {
2302                     assoc_span.push_span_label(ident.span, "in this trait".into());
2303                 }
2304                 err.span_note(assoc_span, &msg);
2305             }
2306             ObligationCauseCode::CompareImplConstObligation => {
2307                 err.note(&format!(
2308                     "the requirement `{}` appears on the associated impl constant \
2309                      but not on the corresponding associated trait constant",
2310                     predicate
2311                 ));
2312             }
2313             ObligationCauseCode::ReturnType
2314             | ObligationCauseCode::ReturnValue(_)
2315             | ObligationCauseCode::BlockTailExpression(_) => (),
2316             ObligationCauseCode::TrivialBound => {
2317                 err.help("see issue #48214");
2318                 if tcx.sess.opts.unstable_features.is_nightly_build() {
2319                     err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2320                 }
2321             }
2322         }
2323     }
2324
2325     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2326         let current_limit = self.tcx.recursion_limit();
2327         let suggested_limit = current_limit * 2;
2328         err.help(&format!(
2329             "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate (`{}`)",
2330             suggested_limit,
2331             self.tcx.crate_name(LOCAL_CRATE),
2332         ));
2333     }
2334
2335     fn suggest_await_before_try(
2336         &self,
2337         err: &mut DiagnosticBuilder<'_>,
2338         obligation: &PredicateObligation<'tcx>,
2339         trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2340         span: Span,
2341     ) {
2342         debug!(
2343             "suggest_await_before_try: obligation={:?}, span={:?}, trait_ref={:?}, trait_ref_self_ty={:?}",
2344             obligation,
2345             span,
2346             trait_ref,
2347             trait_ref.self_ty()
2348         );
2349         let body_hir_id = obligation.cause.body_id;
2350         let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2351
2352         if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(item_id) {
2353             let body = self.tcx.hir().body(body_id);
2354             if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2355                 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2356
2357                 let self_ty = self.resolve_vars_if_possible(trait_ref.self_ty());
2358
2359                 // Do not check on infer_types to avoid panic in evaluate_obligation.
2360                 if self_ty.has_infer_types() {
2361                     return;
2362                 }
2363                 let self_ty = self.tcx.erase_regions(self_ty);
2364
2365                 let impls_future = self.type_implements_trait(
2366                     future_trait,
2367                     self_ty.skip_binder(),
2368                     ty::List::empty(),
2369                     obligation.param_env,
2370                 );
2371
2372                 let item_def_id = self
2373                     .tcx
2374                     .associated_items(future_trait)
2375                     .in_definition_order()
2376                     .next()
2377                     .unwrap()
2378                     .def_id;
2379                 // `<T as Future>::Output`
2380                 let projection_ty = ty::ProjectionTy {
2381                     // `T`
2382                     substs: self.tcx.mk_substs_trait(
2383                         trait_ref.self_ty().skip_binder(),
2384                         self.fresh_substs_for_item(span, item_def_id),
2385                     ),
2386                     // `Future::Output`
2387                     item_def_id,
2388                 };
2389
2390                 let mut selcx = SelectionContext::new(self);
2391
2392                 let mut obligations = vec![];
2393                 let normalized_ty = normalize_projection_type(
2394                     &mut selcx,
2395                     obligation.param_env,
2396                     projection_ty,
2397                     obligation.cause.clone(),
2398                     0,
2399                     &mut obligations,
2400                 );
2401
2402                 debug!(
2403                     "suggest_await_before_try: normalized_projection_type {:?}",
2404                     self.resolve_vars_if_possible(normalized_ty)
2405                 );
2406                 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2407                     obligation.param_env,
2408                     trait_ref,
2409                     normalized_ty,
2410                 );
2411                 debug!("suggest_await_before_try: try_trait_obligation {:?}", try_obligation);
2412                 if self.predicate_may_hold(&try_obligation)
2413                     && impls_future.must_apply_modulo_regions()
2414                 {
2415                     if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2416                         if snippet.ends_with('?') {
2417                             err.span_suggestion_verbose(
2418                                 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2419                                 "consider `await`ing on the `Future`",
2420                                 ".await".to_string(),
2421                                 Applicability::MaybeIncorrect,
2422                             );
2423                         }
2424                     }
2425                 }
2426             }
2427         }
2428     }
2429 }
2430
2431 /// Collect all the returned expressions within the input expression.
2432 /// Used to point at the return spans when we want to suggest some change to them.
2433 #[derive(Default)]
2434 pub struct ReturnsVisitor<'v> {
2435     pub returns: Vec<&'v hir::Expr<'v>>,
2436     in_block_tail: bool,
2437 }
2438
2439 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
2440     type Map = hir::intravisit::ErasedMap<'v>;
2441
2442     fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
2443         hir::intravisit::NestedVisitorMap::None
2444     }
2445
2446     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2447         // Visit every expression to detect `return` paths, either through the function's tail
2448         // expression or `return` statements. We walk all nodes to find `return` statements, but
2449         // we only care about tail expressions when `in_block_tail` is `true`, which means that
2450         // they're in the return path of the function body.
2451         match ex.kind {
2452             hir::ExprKind::Ret(Some(ex)) => {
2453                 self.returns.push(ex);
2454             }
2455             hir::ExprKind::Block(block, _) if self.in_block_tail => {
2456                 self.in_block_tail = false;
2457                 for stmt in block.stmts {
2458                     hir::intravisit::walk_stmt(self, stmt);
2459                 }
2460                 self.in_block_tail = true;
2461                 if let Some(expr) = block.expr {
2462                     self.visit_expr(expr);
2463                 }
2464             }
2465             hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
2466                 self.visit_expr(then);
2467                 if let Some(el) = else_opt {
2468                     self.visit_expr(el);
2469                 }
2470             }
2471             hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
2472                 for arm in arms {
2473                     self.visit_expr(arm.body);
2474                 }
2475             }
2476             // We need to walk to find `return`s in the entire body.
2477             _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
2478             _ => self.returns.push(ex),
2479         }
2480     }
2481
2482     fn visit_body(&mut self, body: &'v hir::Body<'v>) {
2483         assert!(!self.in_block_tail);
2484         if body.generator_kind().is_none() {
2485             if let hir::ExprKind::Block(block, None) = body.value.kind {
2486                 if block.expr.is_some() {
2487                     self.in_block_tail = true;
2488                 }
2489             }
2490         }
2491         hir::intravisit::walk_body(self, body);
2492     }
2493 }
2494
2495 /// Collect all the awaited expressions within the input expression.
2496 #[derive(Default)]
2497 struct AwaitsVisitor {
2498     awaits: Vec<hir::HirId>,
2499 }
2500
2501 impl<'v> Visitor<'v> for AwaitsVisitor {
2502     type Map = hir::intravisit::ErasedMap<'v>;
2503
2504     fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
2505         hir::intravisit::NestedVisitorMap::None
2506     }
2507
2508     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2509         if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
2510             self.awaits.push(id)
2511         }
2512         hir::intravisit::walk_expr(self, ex)
2513     }
2514 }
2515
2516 pub trait NextTypeParamName {
2517     fn next_type_param_name(&self, name: Option<&str>) -> String;
2518 }
2519
2520 impl NextTypeParamName for &[hir::GenericParam<'_>] {
2521     fn next_type_param_name(&self, name: Option<&str>) -> String {
2522         // This is the list of possible parameter names that we might suggest.
2523         let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
2524         let name = name.as_deref();
2525         let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
2526         let used_names = self
2527             .iter()
2528             .filter_map(|p| match p.name {
2529                 hir::ParamName::Plain(ident) => Some(ident.name),
2530                 _ => None,
2531             })
2532             .collect::<Vec<_>>();
2533
2534         possible_names
2535             .iter()
2536             .find(|n| !used_names.contains(&Symbol::intern(n)))
2537             .unwrap_or(&"ParamName")
2538             .to_string()
2539     }
2540 }
2541
2542 fn suggest_trait_object_return_type_alternatives(
2543     err: &mut DiagnosticBuilder<'_>,
2544     ret_ty: Span,
2545     trait_obj: &str,
2546     is_object_safe: bool,
2547 ) {
2548     err.span_suggestion(
2549         ret_ty,
2550         "use some type `T` that is `T: Sized` as the return type if all return paths have the \
2551             same type",
2552         "T".to_string(),
2553         Applicability::MaybeIncorrect,
2554     );
2555     err.span_suggestion(
2556         ret_ty,
2557         &format!(
2558             "use `impl {}` as the return type if all return paths have the same type but you \
2559                 want to expose only the trait in the signature",
2560             trait_obj,
2561         ),
2562         format!("impl {}", trait_obj),
2563         Applicability::MaybeIncorrect,
2564     );
2565     if is_object_safe {
2566         err.span_suggestion(
2567             ret_ty,
2568             &format!(
2569                 "use a boxed trait object if all return paths implement trait `{}`",
2570                 trait_obj,
2571             ),
2572             format!("Box<dyn {}>", trait_obj),
2573             Applicability::MaybeIncorrect,
2574         );
2575     }
2576 }