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