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