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