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