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