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