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