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