]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs
ecbeb9d79b118923057e35e56b48e91f911e1de2
[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_to;
9
10 use hir::HirId;
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_data_structures::stack::ensure_sufficient_stack;
13 use rustc_errors::{
14     error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
15     ErrorGuaranteed, MultiSpan, Style,
16 };
17 use rustc_hir as hir;
18 use rustc_hir::def::DefKind;
19 use rustc_hir::def_id::DefId;
20 use rustc_hir::intravisit::Visitor;
21 use rustc_hir::lang_items::LangItem;
22 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
23 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
24 use rustc_middle::hir::map;
25 use rustc_middle::ty::{
26     self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
27     GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, IsSuggestable,
28     ToPredicate, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
29 };
30 use rustc_middle::ty::{TypeAndMut, TypeckResults};
31 use rustc_session::Limit;
32 use rustc_span::def_id::LOCAL_CRATE;
33 use rustc_span::symbol::{kw, sym, Ident, Symbol};
34 use rustc_span::{BytePos, DesugaringKind, ExpnKind, Span, DUMMY_SP};
35 use rustc_target::spec::abi;
36 use std::fmt;
37
38 use super::InferCtxtPrivExt;
39 use crate::infer::InferCtxtExt as _;
40 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
41 use rustc_middle::ty::print::with_no_trimmed_paths;
42
43 #[derive(Debug)]
44 pub enum GeneratorInteriorOrUpvar {
45     // span of interior type
46     Interior(Span),
47     // span of upvar
48     Upvar(Span),
49 }
50
51 // This type provides a uniform interface to retrieve data on generators, whether it originated from
52 // the local crate being compiled or from a foreign crate.
53 #[derive(Debug)]
54 pub enum GeneratorData<'tcx, 'a> {
55     Local(&'a TypeckResults<'tcx>),
56     Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
57 }
58
59 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
60     // Try to get information about variables captured by the generator that matches a type we are
61     // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
62     // meet an obligation
63     fn try_get_upvar_span<F>(
64         &self,
65         infer_context: &InferCtxt<'a, 'tcx>,
66         generator_did: DefId,
67         ty_matches: F,
68     ) -> Option<GeneratorInteriorOrUpvar>
69     where
70         F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
71     {
72         match self {
73             GeneratorData::Local(typeck_results) => {
74                 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
75                     upvars.iter().find_map(|(upvar_id, upvar)| {
76                         let upvar_ty = typeck_results.node_type(*upvar_id);
77                         let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
78                         if ty_matches(ty::Binder::dummy(upvar_ty)) {
79                             Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
80                         } else {
81                             None
82                         }
83                     })
84                 })
85             }
86             GeneratorData::Foreign(_) => None,
87         }
88     }
89
90     // Try to get the span of a type being awaited on that matches the type we are looking with the
91     // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
92     // obligation
93     fn get_from_await_ty<F>(
94         &self,
95         visitor: AwaitsVisitor,
96         hir: map::Map<'tcx>,
97         ty_matches: F,
98     ) -> Option<Span>
99     where
100         F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
101     {
102         match self {
103             GeneratorData::Local(typeck_results) => visitor
104                 .awaits
105                 .into_iter()
106                 .map(|id| hir.expect_expr(id))
107                 .find(|await_expr| {
108                     ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
109                 })
110                 .map(|expr| expr.span),
111             GeneratorData::Foreign(generator_diagnostic_data) => visitor
112                 .awaits
113                 .into_iter()
114                 .map(|id| hir.expect_expr(id))
115                 .find(|await_expr| {
116                     ty_matches(ty::Binder::dummy(
117                         generator_diagnostic_data
118                             .adjustments
119                             .get(&await_expr.hir_id.local_id)
120                             .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
121                             .last()
122                             .map_or_else::<Ty<'tcx>, _, _>(
123                                 || {
124                                     generator_diagnostic_data
125                                         .nodes_types
126                                         .get(&await_expr.hir_id.local_id)
127                                         .cloned()
128                                         .unwrap_or_else(|| {
129                                             bug!(
130                                                 "node_type: no type for node `{}`",
131                                                 ty::tls::with(|tcx| tcx
132                                                     .hir()
133                                                     .node_to_string(await_expr.hir_id))
134                                             )
135                                         })
136                                 },
137                                 |adj| adj.target,
138                             ),
139                     ))
140                 })
141                 .map(|expr| expr.span),
142         }
143     }
144
145     /// Get the type, expression, span and optional scope span of all types
146     /// that are live across the yield of this generator
147     fn get_generator_interior_types(
148         &self,
149     ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
150         match self {
151             GeneratorData::Local(typeck_result) => {
152                 typeck_result.generator_interior_types.as_deref()
153             }
154             GeneratorData::Foreign(generator_diagnostic_data) => {
155                 generator_diagnostic_data.generator_interior_types.as_deref()
156             }
157         }
158     }
159
160     // Used to get the source of the data, note we don't have as much information for generators
161     // originated from foreign crates
162     fn is_foreign(&self) -> bool {
163         match self {
164             GeneratorData::Local(_) => false,
165             GeneratorData::Foreign(_) => true,
166         }
167     }
168 }
169
170 // This trait is public to expose the diagnostics methods to clippy.
171 pub trait InferCtxtExt<'tcx> {
172     fn suggest_restricting_param_bound(
173         &self,
174         err: &mut Diagnostic,
175         trait_pred: ty::PolyTraitPredicate<'tcx>,
176         associated_item: Option<(&'static str, Ty<'tcx>)>,
177         body_id: hir::HirId,
178     );
179
180     fn suggest_dereferences(
181         &self,
182         obligation: &PredicateObligation<'tcx>,
183         err: &mut Diagnostic,
184         trait_pred: ty::PolyTraitPredicate<'tcx>,
185     ) -> bool;
186
187     fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
188
189     fn suggest_fn_call(
190         &self,
191         obligation: &PredicateObligation<'tcx>,
192         err: &mut Diagnostic,
193         trait_pred: ty::PolyTraitPredicate<'tcx>,
194     ) -> bool;
195
196     fn suggest_add_reference_to_arg(
197         &self,
198         obligation: &PredicateObligation<'tcx>,
199         err: &mut Diagnostic,
200         trait_pred: ty::PolyTraitPredicate<'tcx>,
201         has_custom_message: bool,
202     ) -> bool;
203
204     fn suggest_borrowing_for_object_cast(
205         &self,
206         err: &mut Diagnostic,
207         obligation: &PredicateObligation<'tcx>,
208         self_ty: Ty<'tcx>,
209         object_ty: Ty<'tcx>,
210     );
211
212     fn suggest_remove_reference(
213         &self,
214         obligation: &PredicateObligation<'tcx>,
215         err: &mut Diagnostic,
216         trait_pred: ty::PolyTraitPredicate<'tcx>,
217     ) -> bool;
218
219     fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
220
221     fn suggest_change_mut(
222         &self,
223         obligation: &PredicateObligation<'tcx>,
224         err: &mut Diagnostic,
225         trait_pred: ty::PolyTraitPredicate<'tcx>,
226     );
227
228     fn suggest_semicolon_removal(
229         &self,
230         obligation: &PredicateObligation<'tcx>,
231         err: &mut Diagnostic,
232         span: Span,
233         trait_pred: ty::PolyTraitPredicate<'tcx>,
234     ) -> bool;
235
236     fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
237
238     fn suggest_impl_trait(
239         &self,
240         err: &mut Diagnostic,
241         span: Span,
242         obligation: &PredicateObligation<'tcx>,
243         trait_pred: ty::PolyTraitPredicate<'tcx>,
244     ) -> bool;
245
246     fn point_at_returns_when_relevant(
247         &self,
248         err: &mut Diagnostic,
249         obligation: &PredicateObligation<'tcx>,
250     );
251
252     fn report_closure_arg_mismatch(
253         &self,
254         span: Span,
255         found_span: Option<Span>,
256         found: ty::PolyTraitRef<'tcx>,
257         expected: ty::PolyTraitRef<'tcx>,
258     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
259
260     fn suggest_fully_qualified_path(
261         &self,
262         err: &mut Diagnostic,
263         item_def_id: DefId,
264         span: Span,
265         trait_ref: DefId,
266     );
267
268     fn maybe_note_obligation_cause_for_async_await(
269         &self,
270         err: &mut Diagnostic,
271         obligation: &PredicateObligation<'tcx>,
272     ) -> bool;
273
274     fn note_obligation_cause_for_async_await(
275         &self,
276         err: &mut Diagnostic,
277         interior_or_upvar_span: GeneratorInteriorOrUpvar,
278         interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
279         is_async: bool,
280         outer_generator: Option<DefId>,
281         trait_pred: ty::TraitPredicate<'tcx>,
282         target_ty: Ty<'tcx>,
283         typeck_results: Option<&ty::TypeckResults<'tcx>>,
284         obligation: &PredicateObligation<'tcx>,
285         next_code: Option<&ObligationCauseCode<'tcx>>,
286     );
287
288     fn note_obligation_cause_code<T>(
289         &self,
290         err: &mut Diagnostic,
291         predicate: &T,
292         param_env: ty::ParamEnv<'tcx>,
293         cause_code: &ObligationCauseCode<'tcx>,
294         obligated_types: &mut Vec<Ty<'tcx>>,
295         seen_requirements: &mut FxHashSet<DefId>,
296     ) where
297         T: fmt::Display;
298
299     fn suggest_new_overflow_limit(&self, err: &mut Diagnostic);
300
301     /// Suggest to await before try: future? => future.await?
302     fn suggest_await_before_try(
303         &self,
304         err: &mut Diagnostic,
305         obligation: &PredicateObligation<'tcx>,
306         trait_pred: ty::PolyTraitPredicate<'tcx>,
307         span: Span,
308     );
309
310     fn suggest_floating_point_literal(
311         &self,
312         obligation: &PredicateObligation<'tcx>,
313         err: &mut Diagnostic,
314         trait_ref: &ty::PolyTraitRef<'tcx>,
315     );
316
317     fn suggest_derive(
318         &self,
319         obligation: &PredicateObligation<'tcx>,
320         err: &mut Diagnostic,
321         trait_pred: ty::PolyTraitPredicate<'tcx>,
322     );
323
324     fn suggest_dereferencing_index(
325         &self,
326         obligation: &PredicateObligation<'tcx>,
327         err: &mut Diagnostic,
328         trait_pred: ty::PolyTraitPredicate<'tcx>,
329     );
330 }
331
332 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
333     (
334         generics.tail_span_for_predicate_suggestion(),
335         format!("{} {}", generics.add_where_or_trailing_comma(), pred),
336     )
337 }
338
339 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
340 /// it can also be an `impl Trait` param that needs to be decomposed to a type
341 /// param for cleaner code.
342 fn suggest_restriction<'tcx>(
343     tcx: TyCtxt<'tcx>,
344     hir_id: HirId,
345     hir_generics: &hir::Generics<'tcx>,
346     msg: &str,
347     err: &mut Diagnostic,
348     fn_sig: Option<&hir::FnSig<'_>>,
349     projection: Option<&ty::ProjectionTy<'_>>,
350     trait_pred: ty::PolyTraitPredicate<'tcx>,
351     // When we are dealing with a trait, `super_traits` will be `Some`:
352     // Given `trait T: A + B + C {}`
353     //              -  ^^^^^^^^^ GenericBounds
354     //              |
355     //              &Ident
356     super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
357 ) {
358     if hir_generics.where_clause_span.from_expansion()
359         || hir_generics.where_clause_span.desugaring_kind().is_some()
360     {
361         return;
362     }
363     let Some(item_id) = hir_id.as_owner() else { return; };
364     let generics = tcx.generics_of(item_id);
365     // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
366     if let Some((param, bound_str, fn_sig)) =
367         fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
368             // Shenanigans to get the `Trait` from the `impl Trait`.
369             ty::Param(param) => {
370                 let param_def = generics.type_param(param, tcx);
371                 if param_def.kind.is_synthetic() {
372                     let bound_str =
373                         param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
374                     return Some((param_def, bound_str, sig));
375                 }
376                 None
377             }
378             _ => None,
379         })
380     {
381         let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
382         let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
383             tcx,
384             param,
385             replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
386                 .to_ty(tcx),
387         });
388         if !trait_pred.is_suggestable(tcx, false) {
389             return;
390         }
391         // We know we have an `impl Trait` that doesn't satisfy a required projection.
392
393         // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
394         // types. There should be at least one, but there might be *more* than one. In that
395         // case we could just ignore it and try to identify which one needs the restriction,
396         // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
397         // where `T: Trait`.
398         let mut ty_spans = vec![];
399         for input in fn_sig.decl.inputs {
400             ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
401                 .visit_ty(input);
402         }
403         // The type param `T: Trait` we will suggest to introduce.
404         let type_param = format!("{}: {}", type_param_name, bound_str);
405
406         let mut sugg = vec![
407             if let Some(span) = hir_generics.span_for_param_suggestion() {
408                 (span, format!(", {}", type_param))
409             } else {
410                 (hir_generics.span, format!("<{}>", type_param))
411             },
412             // `fn foo(t: impl Trait)`
413             //                       ^ suggest `where <T as Trait>::A: Bound`
414             predicate_constraint(hir_generics, trait_pred.to_predicate(tcx).to_string()),
415         ];
416         sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
417
418         // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
419         // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
420         // `fn foo(t: impl Trait<A: Bound>)` instead.
421         err.multipart_suggestion(
422             "introduce a type parameter with a trait bound instead of using `impl Trait`",
423             sugg,
424             Applicability::MaybeIncorrect,
425         );
426     } else {
427         if !trait_pred.is_suggestable(tcx, false) {
428             return;
429         }
430         // Trivial case: `T` needs an extra bound: `T: Bound`.
431         let (sp, suggestion) = match (
432             hir_generics
433                 .params
434                 .iter()
435                 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
436             super_traits,
437         ) {
438             (_, None) => {
439                 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx).to_string())
440             }
441             (None, Some((ident, []))) => (
442                 ident.span.shrink_to_hi(),
443                 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
444             ),
445             (_, Some((_, [.., bounds]))) => (
446                 bounds.span().shrink_to_hi(),
447                 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
448             ),
449             (Some(_), Some((_, []))) => (
450                 hir_generics.span.shrink_to_hi(),
451                 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
452             ),
453         };
454
455         err.span_suggestion_verbose(
456             sp,
457             &format!("consider further restricting {}", msg),
458             suggestion,
459             Applicability::MachineApplicable,
460         );
461     }
462 }
463
464 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
465     fn suggest_restricting_param_bound(
466         &self,
467         mut err: &mut Diagnostic,
468         trait_pred: ty::PolyTraitPredicate<'tcx>,
469         associated_ty: Option<(&'static str, Ty<'tcx>)>,
470         body_id: hir::HirId,
471     ) {
472         let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
473
474         let self_ty = trait_pred.skip_binder().self_ty();
475         let (param_ty, projection) = match self_ty.kind() {
476             ty::Param(_) => (true, None),
477             ty::Projection(projection) => (false, Some(projection)),
478             _ => (false, None),
479         };
480
481         // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
482         //        don't suggest `T: Sized + ?Sized`.
483         let mut hir_id = body_id;
484         while let Some(node) = self.tcx.hir().find(hir_id) {
485             match node {
486                 hir::Node::Item(hir::Item {
487                     ident,
488                     kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
489                     ..
490                 }) if self_ty == self.tcx.types.self_param => {
491                     assert!(param_ty);
492                     // Restricting `Self` for a single method.
493                     suggest_restriction(
494                         self.tcx,
495                         hir_id,
496                         &generics,
497                         "`Self`",
498                         err,
499                         None,
500                         projection,
501                         trait_pred,
502                         Some((ident, bounds)),
503                     );
504                     return;
505                 }
506
507                 hir::Node::TraitItem(hir::TraitItem {
508                     generics,
509                     kind: hir::TraitItemKind::Fn(..),
510                     ..
511                 }) if self_ty == self.tcx.types.self_param => {
512                     assert!(param_ty);
513                     // Restricting `Self` for a single method.
514                     suggest_restriction(
515                         self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
516                         None,
517                     );
518                     return;
519                 }
520
521                 hir::Node::TraitItem(hir::TraitItem {
522                     generics,
523                     kind: hir::TraitItemKind::Fn(fn_sig, ..),
524                     ..
525                 })
526                 | hir::Node::ImplItem(hir::ImplItem {
527                     generics,
528                     kind: hir::ImplItemKind::Fn(fn_sig, ..),
529                     ..
530                 })
531                 | hir::Node::Item(hir::Item {
532                     kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
533                 }) if projection.is_some() => {
534                     // Missing restriction on associated type of type parameter (unmet projection).
535                     suggest_restriction(
536                         self.tcx,
537                         hir_id,
538                         &generics,
539                         "the associated type",
540                         err,
541                         Some(fn_sig),
542                         projection,
543                         trait_pred,
544                         None,
545                     );
546                     return;
547                 }
548                 hir::Node::Item(hir::Item {
549                     kind:
550                         hir::ItemKind::Trait(_, _, generics, ..)
551                         | hir::ItemKind::Impl(hir::Impl { generics, .. }),
552                     ..
553                 }) if projection.is_some() => {
554                     // Missing restriction on associated type of type parameter (unmet projection).
555                     suggest_restriction(
556                         self.tcx,
557                         hir_id,
558                         &generics,
559                         "the associated type",
560                         err,
561                         None,
562                         projection,
563                         trait_pred,
564                         None,
565                     );
566                     return;
567                 }
568
569                 hir::Node::Item(hir::Item {
570                     kind:
571                         hir::ItemKind::Struct(_, generics)
572                         | hir::ItemKind::Enum(_, generics)
573                         | hir::ItemKind::Union(_, generics)
574                         | hir::ItemKind::Trait(_, _, generics, ..)
575                         | hir::ItemKind::Impl(hir::Impl { generics, .. })
576                         | hir::ItemKind::Fn(_, generics, _)
577                         | hir::ItemKind::TyAlias(_, generics)
578                         | hir::ItemKind::TraitAlias(generics, _)
579                         | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
580                     ..
581                 })
582                 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
583                 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
584                     if param_ty =>
585                 {
586                     // We skip the 0'th subst (self) because we do not want
587                     // to consider the predicate as not suggestible if the
588                     // self type is an arg position `impl Trait` -- instead,
589                     // we handle that by adding ` + Bound` below.
590                     // FIXME(compiler-errors): It would be nice to do the same
591                     // this that we do in `suggest_restriction` and pull the
592                     // `impl Trait` into a new generic if it shows up somewhere
593                     // else in the predicate.
594                     if !trait_pred.skip_binder().trait_ref.substs[1..]
595                         .iter()
596                         .all(|g| g.is_suggestable(self.tcx, false))
597                     {
598                         return;
599                     }
600                     // Missing generic type parameter bound.
601                     let param_name = self_ty.to_string();
602                     let mut constraint = with_no_trimmed_paths!(
603                         trait_pred.print_modifiers_and_trait_path().to_string()
604                     );
605
606                     if let Some((name, term)) = associated_ty {
607                         // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
608                         // That should be extracted into a helper function.
609                         if constraint.ends_with('>') {
610                             constraint = format!(
611                                 "{}, {} = {}>",
612                                 &constraint[..constraint.len() - 1],
613                                 name,
614                                 term
615                             );
616                         } else {
617                             constraint.push_str(&format!("<{} = {}>", name, term));
618                         }
619                     }
620
621                     if suggest_constraining_type_param(
622                         self.tcx,
623                         generics,
624                         &mut err,
625                         &param_name,
626                         &constraint,
627                         Some(trait_pred.def_id()),
628                     ) {
629                         return;
630                     }
631                 }
632
633                 hir::Node::Item(hir::Item {
634                     kind:
635                         hir::ItemKind::Struct(_, generics)
636                         | hir::ItemKind::Enum(_, generics)
637                         | hir::ItemKind::Union(_, generics)
638                         | hir::ItemKind::Trait(_, _, generics, ..)
639                         | hir::ItemKind::Impl(hir::Impl { generics, .. })
640                         | hir::ItemKind::Fn(_, generics, _)
641                         | hir::ItemKind::TyAlias(_, generics)
642                         | hir::ItemKind::TraitAlias(generics, _)
643                         | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
644                     ..
645                 }) if !param_ty => {
646                     // Missing generic type parameter bound.
647                     if suggest_arbitrary_trait_bound(
648                         self.tcx,
649                         generics,
650                         &mut err,
651                         trait_pred,
652                         associated_ty,
653                     ) {
654                         return;
655                     }
656                 }
657                 hir::Node::Crate(..) => return,
658
659                 _ => {}
660             }
661
662             hir_id = self.tcx.hir().local_def_id_to_hir_id(self.tcx.hir().get_parent_item(hir_id));
663         }
664     }
665
666     /// When after several dereferencing, the reference satisfies the trait
667     /// binding. This function provides dereference suggestion for this
668     /// specific situation.
669     fn suggest_dereferences(
670         &self,
671         obligation: &PredicateObligation<'tcx>,
672         err: &mut Diagnostic,
673         trait_pred: ty::PolyTraitPredicate<'tcx>,
674     ) -> bool {
675         // It only make sense when suggesting dereferences for arguments
676         let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code()
677             else { return false; };
678         let Some(typeck_results) = self.in_progress_typeck_results
679             else { return false; };
680         let typeck_results = typeck_results.borrow();
681         let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
682             else { return false; };
683         let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
684             else { return false; };
685
686         let span = obligation.cause.span;
687         let mut real_trait_pred = trait_pred;
688         let mut code = obligation.cause.code();
689         while let Some((parent_code, parent_trait_pred)) = code.parent() {
690             code = parent_code;
691             if let Some(parent_trait_pred) = parent_trait_pred {
692                 real_trait_pred = parent_trait_pred;
693             }
694
695             let real_ty = real_trait_pred.self_ty();
696             // We `erase_late_bound_regions` here because `make_subregion` does not handle
697             // `ReLateBound`, and we don't particularly care about the regions.
698             if self
699                 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
700                 .is_err()
701             {
702                 continue;
703             }
704
705             if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
706                 let mut autoderef = Autoderef::new(
707                     self,
708                     obligation.param_env,
709                     obligation.cause.body_id,
710                     span,
711                     base_ty,
712                     span,
713                 );
714                 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
715                     // Re-add the `&`
716                     let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
717
718                     // Remapping bound vars here
719                     let real_trait_pred_and_ty =
720                         real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
721                     let obligation = self.mk_trait_obligation_with_new_self_ty(
722                         obligation.param_env,
723                         real_trait_pred_and_ty,
724                     );
725                     Some(steps).filter(|_| self.predicate_may_hold(&obligation))
726                 }) {
727                     if steps > 0 {
728                         // Don't care about `&mut` because `DerefMut` is used less
729                         // often and user will not expect autoderef happens.
730                         if let Some(hir::Node::Expr(hir::Expr {
731                             kind:
732                                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
733                             ..
734                         })) = self.tcx.hir().find(*arg_hir_id)
735                         {
736                             let derefs = "*".repeat(steps);
737                             err.span_suggestion_verbose(
738                                 expr.span.shrink_to_lo(),
739                                 "consider dereferencing here",
740                                 derefs,
741                                 Applicability::MachineApplicable,
742                             );
743                             return true;
744                         }
745                     }
746                 } else if real_trait_pred != trait_pred {
747                     // This branch addresses #87437.
748
749                     // Remapping bound vars here
750                     let real_trait_pred_and_base_ty =
751                         real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
752                     let obligation = self.mk_trait_obligation_with_new_self_ty(
753                         obligation.param_env,
754                         real_trait_pred_and_base_ty,
755                     );
756                     if self.predicate_may_hold(&obligation) {
757                         err.span_suggestion_verbose(
758                             span.shrink_to_lo(),
759                             "consider dereferencing here",
760                             "*",
761                             Applicability::MachineApplicable,
762                         );
763                         return true;
764                     }
765                 }
766             }
767         }
768         false
769     }
770
771     /// Given a closure's `DefId`, return the given name of the closure.
772     ///
773     /// This doesn't account for reassignments, but it's only used for suggestions.
774     fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
775         let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
776             // Get the local name of this closure. This can be inaccurate because
777             // of the possibility of reassignment, but this should be good enough.
778             match &kind {
779                 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
780                     Some(ident.name)
781                 }
782                 _ => {
783                     err.note(msg);
784                     None
785                 }
786             }
787         };
788
789         let hir = self.tcx.hir();
790         let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
791         let parent_node = hir.get_parent_node(hir_id);
792         match hir.find(parent_node) {
793             Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
794                 get_name(err, &local.pat.kind)
795             }
796             // Different to previous arm because one is `&hir::Local` and the other
797             // is `P<hir::Local>`.
798             Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
799             _ => None,
800         }
801     }
802
803     /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
804     /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
805     /// it: `bar(foo)` â†’ `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
806     fn suggest_fn_call(
807         &self,
808         obligation: &PredicateObligation<'tcx>,
809         err: &mut Diagnostic,
810         trait_pred: ty::PolyTraitPredicate<'tcx>,
811     ) -> bool {
812         // Skipping binder here, remapping below
813         let self_ty = trait_pred.self_ty().skip_binder();
814
815         let (def_id, output_ty, callable) = match *self_ty.kind() {
816             ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
817             ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
818             _ => return false,
819         };
820         let msg = format!("use parentheses to call the {}", callable);
821
822         // "We should really create a single list of bound vars from the combined vars
823         // from the predicate and function, but instead we just liberate the function bound vars"
824         let output_ty = self.tcx.liberate_late_bound_regions(def_id, output_ty);
825
826         // Remapping bound vars here
827         let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output_ty));
828
829         let new_obligation =
830             self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
831
832         match self.evaluate_obligation(&new_obligation) {
833             Ok(
834                 EvaluationResult::EvaluatedToOk
835                 | EvaluationResult::EvaluatedToOkModuloRegions
836                 | EvaluationResult::EvaluatedToOkModuloOpaqueTypes
837                 | EvaluationResult::EvaluatedToAmbig,
838             ) => {}
839             _ => return false,
840         }
841         let hir = self.tcx.hir();
842         // Get the name of the callable and the arguments to be used in the suggestion.
843         let (snippet, sugg) = match hir.get_if_local(def_id) {
844             Some(hir::Node::Expr(hir::Expr {
845                 kind: hir::ExprKind::Closure(hir::Closure { fn_decl, fn_decl_span, .. }),
846                 ..
847             })) => {
848                 err.span_label(*fn_decl_span, "consider calling this closure");
849                 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
850                     return false;
851                 };
852                 let args = fn_decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
853                 let sugg = format!("({})", args);
854                 (format!("{}{}", name, sugg), sugg)
855             }
856             Some(hir::Node::Item(hir::Item {
857                 ident,
858                 kind: hir::ItemKind::Fn(.., body_id),
859                 ..
860             })) => {
861                 err.span_label(ident.span, "consider calling this function");
862                 let body = hir.body(*body_id);
863                 let args = body
864                     .params
865                     .iter()
866                     .map(|arg| match &arg.pat.kind {
867                         hir::PatKind::Binding(_, _, ident, None)
868                         // FIXME: provide a better suggestion when encountering `SelfLower`, it
869                         // should suggest a method call.
870                         if ident.name != kw::SelfLower => ident.to_string(),
871                         _ => "_".to_string(),
872                     })
873                     .collect::<Vec<_>>()
874                     .join(", ");
875                 let sugg = format!("({})", args);
876                 (format!("{}{}", ident, sugg), sugg)
877             }
878             _ => return false,
879         };
880         if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
881             && obligation.cause.span.can_be_used_for_suggestions()
882         {
883             // When the obligation error has been ensured to have been caused by
884             // an argument, the `obligation.cause.span` points at the expression
885             // of the argument, so we can provide a suggestion. Otherwise, we give
886             // a more general note.
887             err.span_suggestion_verbose(
888                 obligation.cause.span.shrink_to_hi(),
889                 &msg,
890                 sugg,
891                 Applicability::HasPlaceholders,
892             );
893         } else {
894             err.help(&format!("{}: `{}`", msg, snippet));
895         }
896         true
897     }
898
899     fn suggest_add_reference_to_arg(
900         &self,
901         obligation: &PredicateObligation<'tcx>,
902         err: &mut Diagnostic,
903         poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
904         has_custom_message: bool,
905     ) -> bool {
906         let span = obligation.cause.span;
907
908         let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
909             obligation.cause.code()
910         {
911             &parent_code
912         } else if let ObligationCauseCode::ItemObligation(_)
913         | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
914         {
915             obligation.cause.code()
916         } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
917             span.ctxt().outer_expn_data().kind
918         {
919             obligation.cause.code()
920         } else {
921             return false;
922         };
923
924         // List of traits for which it would be nonsensical to suggest borrowing.
925         // For instance, immutable references are always Copy, so suggesting to
926         // borrow would always succeed, but it's probably not what the user wanted.
927         let mut never_suggest_borrow: Vec<_> =
928             [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
929                 .iter()
930                 .filter_map(|lang_item| self.tcx.lang_items().require(*lang_item).ok())
931                 .collect();
932
933         if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
934             never_suggest_borrow.push(def_id);
935         }
936
937         let param_env = obligation.param_env;
938
939         // Try to apply the original trait binding obligation by borrowing.
940         let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
941                                  blacklist: &[DefId]|
942          -> bool {
943             if blacklist.contains(&old_pred.def_id()) {
944                 return false;
945             }
946             // We map bounds to `&T` and `&mut T`
947             let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
948                 (
949                     trait_pred,
950                     self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
951                 )
952             });
953             let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
954                 (
955                     trait_pred,
956                     self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
957                 )
958             });
959
960             let mk_result = |trait_pred_and_new_ty| {
961                 let obligation =
962                     self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
963                 self.predicate_must_hold_modulo_regions(&obligation)
964             };
965             let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
966             let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
967
968             let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
969                 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
970                     && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
971                 {
972                     (
973                         mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
974                         matches!(mutability, hir::Mutability::Mut),
975                     )
976                 } else {
977                     (false, false)
978                 };
979
980             if imm_ref_self_ty_satisfies_pred
981                 || mut_ref_self_ty_satisfies_pred
982                 || ref_inner_ty_satisfies_pred
983             {
984                 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
985                     // We don't want a borrowing suggestion on the fields in structs,
986                     // ```
987                     // struct Foo {
988                     //  the_foos: Vec<Foo>
989                     // }
990                     // ```
991                     if !matches!(
992                         span.ctxt().outer_expn_data().kind,
993                         ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
994                     ) {
995                         return false;
996                     }
997                     if snippet.starts_with('&') {
998                         // This is already a literal borrow and the obligation is failing
999                         // somewhere else in the obligation chain. Do not suggest non-sense.
1000                         return false;
1001                     }
1002                     // We have a very specific type of error, where just borrowing this argument
1003                     // might solve the problem. In cases like this, the important part is the
1004                     // original type obligation, not the last one that failed, which is arbitrary.
1005                     // Because of this, we modify the error to refer to the original obligation and
1006                     // return early in the caller.
1007
1008                     let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1009                     if has_custom_message {
1010                         err.note(&msg);
1011                     } else {
1012                         err.message =
1013                             vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1014                     }
1015                     err.span_label(
1016                         span,
1017                         format!(
1018                             "the trait `{}` is not implemented for `{}`",
1019                             old_pred.print_modifiers_and_trait_path(),
1020                             old_pred.self_ty().skip_binder(),
1021                         ),
1022                     );
1023
1024                     if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1025                         err.span_suggestions(
1026                             span.shrink_to_lo(),
1027                             "consider borrowing here",
1028                             ["&".to_string(), "&mut ".to_string()].into_iter(),
1029                             Applicability::MaybeIncorrect,
1030                         );
1031                     } else {
1032                         let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1033                         err.span_suggestion_verbose(
1034                             span.shrink_to_lo(),
1035                             &format!(
1036                                 "consider{} borrowing here",
1037                                 if is_mut { " mutably" } else { "" }
1038                             ),
1039                             format!("&{}", if is_mut { "mut " } else { "" }),
1040                             Applicability::MaybeIncorrect,
1041                         );
1042                     }
1043                     return true;
1044                 }
1045             }
1046             return false;
1047         };
1048
1049         if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1050             try_borrowing(cause.derived.parent_trait_pred, &[])
1051         } else if let ObligationCauseCode::BindingObligation(_, _)
1052         | ObligationCauseCode::ItemObligation(_)
1053         | ObligationCauseCode::ExprItemObligation(..)
1054         | ObligationCauseCode::ExprBindingObligation(..) = code
1055         {
1056             try_borrowing(poly_trait_pred, &never_suggest_borrow)
1057         } else {
1058             false
1059         }
1060     }
1061
1062     // Suggest borrowing the type
1063     fn suggest_borrowing_for_object_cast(
1064         &self,
1065         err: &mut Diagnostic,
1066         obligation: &PredicateObligation<'tcx>,
1067         self_ty: Ty<'tcx>,
1068         object_ty: Ty<'tcx>,
1069     ) {
1070         let ty::Dynamic(predicates, _) = object_ty.kind() else { return; };
1071         let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1072
1073         for predicate in predicates.iter() {
1074             if !self.predicate_must_hold_modulo_regions(
1075                 &obligation.with(predicate.with_self_ty(self.tcx, self_ref_ty)),
1076             ) {
1077                 return;
1078             }
1079         }
1080
1081         err.span_suggestion(
1082             obligation.cause.span.shrink_to_lo(),
1083             &format!(
1084                 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1085             ),
1086             "&",
1087             Applicability::MaybeIncorrect,
1088         );
1089     }
1090
1091     /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1092     /// suggest removing these references until we reach a type that implements the trait.
1093     fn suggest_remove_reference(
1094         &self,
1095         obligation: &PredicateObligation<'tcx>,
1096         err: &mut Diagnostic,
1097         trait_pred: ty::PolyTraitPredicate<'tcx>,
1098     ) -> bool {
1099         let span = obligation.cause.span;
1100
1101         let mut suggested = false;
1102         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1103             let refs_number =
1104                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1105             if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1106                 // Do not suggest removal of borrow from type arguments.
1107                 return false;
1108             }
1109
1110             // Skipping binder here, remapping below
1111             let mut suggested_ty = trait_pred.self_ty().skip_binder();
1112
1113             for refs_remaining in 0..refs_number {
1114                 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1115                     break;
1116                 };
1117                 suggested_ty = *inner_ty;
1118
1119                 // Remapping bound vars here
1120                 let trait_pred_and_suggested_ty =
1121                     trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1122
1123                 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1124                     obligation.param_env,
1125                     trait_pred_and_suggested_ty,
1126                 );
1127
1128                 if self.predicate_may_hold(&new_obligation) {
1129                     let sp = self
1130                         .tcx
1131                         .sess
1132                         .source_map()
1133                         .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1134
1135                     let remove_refs = refs_remaining + 1;
1136
1137                     let msg = if remove_refs == 1 {
1138                         "consider removing the leading `&`-reference".to_string()
1139                     } else {
1140                         format!("consider removing {} leading `&`-references", remove_refs)
1141                     };
1142
1143                     err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1144                     suggested = true;
1145                     break;
1146                 }
1147             }
1148         }
1149         suggested
1150     }
1151
1152     fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1153         let span = obligation.cause.span;
1154
1155         if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1156             let hir = self.tcx.hir();
1157             if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1158                 if let hir::Node::Expr(expr) = node {
1159                     // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1160                     // and if not maybe suggest doing something else? If we kept the expression around we
1161                     // could also check if it is an fn call (very likely) and suggest changing *that*, if
1162                     // it is from the local crate.
1163                     err.span_suggestion_verbose(
1164                         expr.span.shrink_to_hi().with_hi(span.hi()),
1165                         "remove the `.await`",
1166                         "",
1167                         Applicability::MachineApplicable,
1168                     );
1169                     // FIXME: account for associated `async fn`s.
1170                     if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1171                         if let ty::PredicateKind::Trait(pred) =
1172                             obligation.predicate.kind().skip_binder()
1173                         {
1174                             err.span_label(
1175                                 *span,
1176                                 &format!("this call returns `{}`", pred.self_ty()),
1177                             );
1178                         }
1179                         if let Some(typeck_results) =
1180                             self.in_progress_typeck_results.map(|t| t.borrow())
1181                             && let ty = typeck_results.expr_ty_adjusted(base)
1182                             && let ty::FnDef(def_id, _substs) = ty.kind()
1183                             && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1184                                 hir.get_if_local(*def_id)
1185                         {
1186                             let msg = format!(
1187                                 "alternatively, consider making `fn {}` asynchronous",
1188                                 ident
1189                             );
1190                             if vis_span.is_empty() {
1191                                 err.span_suggestion_verbose(
1192                                     span.shrink_to_lo(),
1193                                     &msg,
1194                                     "async ",
1195                                     Applicability::MaybeIncorrect,
1196                                 );
1197                             } else {
1198                                 err.span_suggestion_verbose(
1199                                     vis_span.shrink_to_hi(),
1200                                     &msg,
1201                                     " async",
1202                                     Applicability::MaybeIncorrect,
1203                                 );
1204                             }
1205                         }
1206                     }
1207                 }
1208             }
1209         }
1210     }
1211
1212     /// Check if the trait bound is implemented for a different mutability and note it in the
1213     /// final error.
1214     fn suggest_change_mut(
1215         &self,
1216         obligation: &PredicateObligation<'tcx>,
1217         err: &mut Diagnostic,
1218         trait_pred: ty::PolyTraitPredicate<'tcx>,
1219     ) {
1220         let points_at_arg = matches!(
1221             obligation.cause.code(),
1222             ObligationCauseCode::FunctionArgumentObligation { .. },
1223         );
1224
1225         let span = obligation.cause.span;
1226         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1227             let refs_number =
1228                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1229             if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1230                 // Do not suggest removal of borrow from type arguments.
1231                 return;
1232             }
1233             let trait_pred = self.resolve_vars_if_possible(trait_pred);
1234             if trait_pred.has_infer_types_or_consts() {
1235                 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1236                 // unresolved bindings.
1237                 return;
1238             }
1239
1240             // Skipping binder here, remapping below
1241             if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1242             {
1243                 let suggested_ty = match mutability {
1244                     hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1245                     hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1246                 };
1247
1248                 // Remapping bound vars here
1249                 let trait_pred_and_suggested_ty =
1250                     trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1251
1252                 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1253                     obligation.param_env,
1254                     trait_pred_and_suggested_ty,
1255                 );
1256                 let suggested_ty_would_satisfy_obligation = self
1257                     .evaluate_obligation_no_overflow(&new_obligation)
1258                     .must_apply_modulo_regions();
1259                 if suggested_ty_would_satisfy_obligation {
1260                     let sp = self
1261                         .tcx
1262                         .sess
1263                         .source_map()
1264                         .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1265                     if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
1266                         err.span_suggestion_verbose(
1267                             sp,
1268                             "consider changing this borrow's mutability",
1269                             "&mut ",
1270                             Applicability::MachineApplicable,
1271                         );
1272                     } else {
1273                         err.note(&format!(
1274                             "`{}` is implemented for `{:?}`, but not for `{:?}`",
1275                             trait_pred.print_modifiers_and_trait_path(),
1276                             suggested_ty,
1277                             trait_pred.skip_binder().self_ty(),
1278                         ));
1279                     }
1280                 }
1281             }
1282         }
1283     }
1284
1285     fn suggest_semicolon_removal(
1286         &self,
1287         obligation: &PredicateObligation<'tcx>,
1288         err: &mut Diagnostic,
1289         span: Span,
1290         trait_pred: ty::PolyTraitPredicate<'tcx>,
1291     ) -> bool {
1292         let hir = self.tcx.hir();
1293         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1294         let node = hir.find(parent_node);
1295         if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1296             && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1297             && sig.decl.output.span().overlaps(span)
1298             && blk.expr.is_none()
1299             && trait_pred.self_ty().skip_binder().is_unit()
1300             && let Some(stmt) = blk.stmts.last()
1301             && let hir::StmtKind::Semi(expr) = stmt.kind
1302             // Only suggest this if the expression behind the semicolon implements the predicate
1303             && let Some(typeck_results) = self.in_progress_typeck_results
1304             && let Some(ty) = typeck_results.borrow().expr_ty_opt(expr)
1305             && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1306                 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1307             ))
1308         {
1309             err.span_label(
1310                 expr.span,
1311                 &format!(
1312                     "this expression has type `{}`, which implements `{}`",
1313                     ty,
1314                     trait_pred.print_modifiers_and_trait_path()
1315                 )
1316             );
1317             err.span_suggestion(
1318                 self.tcx.sess.source_map().end_point(stmt.span),
1319                 "remove this semicolon",
1320                 "",
1321                 Applicability::MachineApplicable
1322             );
1323             return true;
1324         }
1325         false
1326     }
1327
1328     fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1329         let hir = self.tcx.hir();
1330         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1331         let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1332             return None;
1333         };
1334
1335         if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1336     }
1337
1338     /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1339     /// applicable and signal that the error has been expanded appropriately and needs to be
1340     /// emitted.
1341     fn suggest_impl_trait(
1342         &self,
1343         err: &mut Diagnostic,
1344         span: Span,
1345         obligation: &PredicateObligation<'tcx>,
1346         trait_pred: ty::PolyTraitPredicate<'tcx>,
1347     ) -> bool {
1348         match obligation.cause.code().peel_derives() {
1349             // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1350             ObligationCauseCode::SizedReturnType => {}
1351             _ => return false,
1352         }
1353
1354         let hir = self.tcx.hir();
1355         let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1356         let node = hir.find(fn_hir_id);
1357         let Some(hir::Node::Item(hir::Item {
1358             kind: hir::ItemKind::Fn(sig, _, body_id),
1359             ..
1360         })) = node
1361         else {
1362             return false;
1363         };
1364         let body = hir.body(*body_id);
1365         let trait_pred = self.resolve_vars_if_possible(trait_pred);
1366         let ty = trait_pred.skip_binder().self_ty();
1367         let is_object_safe = match ty.kind() {
1368             ty::Dynamic(predicates, _) => {
1369                 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1370                 predicates
1371                     .principal_def_id()
1372                     .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1373             }
1374             // We only want to suggest `impl Trait` to `dyn Trait`s.
1375             // For example, `fn foo() -> str` needs to be filtered out.
1376             _ => return false,
1377         };
1378
1379         let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1380             return false;
1381         };
1382
1383         // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1384         // cases like `fn foo() -> (dyn Trait, i32) {}`.
1385         // Recursively look for `TraitObject` types and if there's only one, use that span to
1386         // suggest `impl Trait`.
1387
1388         // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1389         // otherwise suggest using `Box<dyn Trait>` or an enum.
1390         let mut visitor = ReturnsVisitor::default();
1391         visitor.visit_body(&body);
1392
1393         let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1394         let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1395
1396         let ret_types = visitor
1397             .returns
1398             .iter()
1399             .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1400             .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1401         let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1402             (None, true, true),
1403             |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1404              (_, ty)| {
1405                 let ty = self.resolve_vars_if_possible(ty);
1406                 same &=
1407                     !matches!(ty.kind(), ty::Error(_))
1408                         && last_ty.map_or(true, |last_ty| {
1409                             // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1410                             // *after* in the dependency graph.
1411                             match (ty.kind(), last_ty.kind()) {
1412                                 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1413                                 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1414                                 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1415                                 | (
1416                                     Infer(InferTy::FreshFloatTy(_)),
1417                                     Infer(InferTy::FreshFloatTy(_)),
1418                                 ) => true,
1419                                 _ => ty == last_ty,
1420                             }
1421                         });
1422                 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1423             },
1424         );
1425         let mut spans_and_needs_box = vec![];
1426
1427         match liberated_sig.output().kind() {
1428             ty::Dynamic(predicates, _) => {
1429                 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1430                 let param_env = ty::ParamEnv::empty();
1431
1432                 if !only_never_return {
1433                     for (expr_span, return_ty) in ret_types {
1434                         let self_ty_satisfies_dyn_predicates = |self_ty| {
1435                             predicates.iter().all(|predicate| {
1436                                 let pred = predicate.with_self_ty(self.tcx, self_ty);
1437                                 let obl = Obligation::new(cause.clone(), param_env, pred);
1438                                 self.predicate_may_hold(&obl)
1439                             })
1440                         };
1441
1442                         if let ty::Adt(def, substs) = return_ty.kind()
1443                             && def.is_box()
1444                             && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1445                         {
1446                             spans_and_needs_box.push((expr_span, false));
1447                         } else if self_ty_satisfies_dyn_predicates(return_ty) {
1448                             spans_and_needs_box.push((expr_span, true));
1449                         } else {
1450                             return false;
1451                         }
1452                     }
1453                 }
1454             }
1455             _ => return false,
1456         };
1457
1458         let sm = self.tcx.sess.source_map();
1459         if !ret_ty.span.overlaps(span) {
1460             return false;
1461         }
1462         let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1463             if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1464                 snippet
1465             } else {
1466                 return false;
1467             }
1468         } else {
1469             // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1470             let name = liberated_sig.output().to_string();
1471             let name =
1472                 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1473             if !name.starts_with("dyn ") {
1474                 return false;
1475             }
1476             name.to_owned()
1477         };
1478
1479         err.code(error_code!(E0746));
1480         err.set_primary_message("return type cannot have an unboxed trait object");
1481         err.children.clear();
1482         let impl_trait_msg = "for information on `impl Trait`, see \
1483             <https://doc.rust-lang.org/book/ch10-02-traits.html\
1484             #returning-types-that-implement-traits>";
1485         let trait_obj_msg = "for information on trait objects, see \
1486             <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1487             #using-trait-objects-that-allow-for-values-of-different-types>";
1488
1489         let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1490         let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1491         if only_never_return {
1492             // No return paths, probably using `panic!()` or similar.
1493             // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1494             suggest_trait_object_return_type_alternatives(
1495                 err,
1496                 ret_ty.span,
1497                 trait_obj,
1498                 is_object_safe,
1499             );
1500         } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1501             // Suggest `-> impl Trait`.
1502             err.span_suggestion(
1503                 ret_ty.span,
1504                 &format!(
1505                     "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1506                      which implements `{1}`",
1507                     last_ty, trait_obj,
1508                 ),
1509                 format!("impl {}", trait_obj),
1510                 Applicability::MachineApplicable,
1511             );
1512             err.note(impl_trait_msg);
1513         } else {
1514             if is_object_safe {
1515                 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1516                 err.multipart_suggestion(
1517                     "return a boxed trait object instead",
1518                     vec![
1519                         (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1520                         (span.shrink_to_hi(), ">".to_string()),
1521                     ],
1522                     Applicability::MaybeIncorrect,
1523                 );
1524                 for (span, needs_box) in spans_and_needs_box {
1525                     if needs_box {
1526                         err.multipart_suggestion(
1527                             "... and box this value",
1528                             vec![
1529                                 (span.shrink_to_lo(), "Box::new(".to_string()),
1530                                 (span.shrink_to_hi(), ")".to_string()),
1531                             ],
1532                             Applicability::MaybeIncorrect,
1533                         );
1534                     }
1535                 }
1536             } else {
1537                 // This is currently not possible to trigger because E0038 takes precedence, but
1538                 // leave it in for completeness in case anything changes in an earlier stage.
1539                 err.note(&format!(
1540                     "if trait `{}` were object-safe, you could return a trait object",
1541                     trait_obj,
1542                 ));
1543             }
1544             err.note(trait_obj_msg);
1545             err.note(&format!(
1546                 "if all the returned values were of the same type you could use `impl {}` as the \
1547                  return type",
1548                 trait_obj,
1549             ));
1550             err.note(impl_trait_msg);
1551             err.note("you can create a new `enum` with a variant for each returned type");
1552         }
1553         true
1554     }
1555
1556     fn point_at_returns_when_relevant(
1557         &self,
1558         err: &mut Diagnostic,
1559         obligation: &PredicateObligation<'tcx>,
1560     ) {
1561         match obligation.cause.code().peel_derives() {
1562             ObligationCauseCode::SizedReturnType => {}
1563             _ => return,
1564         }
1565
1566         let hir = self.tcx.hir();
1567         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1568         let node = hir.find(parent_node);
1569         if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1570             node
1571         {
1572             let body = hir.body(*body_id);
1573             // Point at all the `return`s in the function as they have failed trait bounds.
1574             let mut visitor = ReturnsVisitor::default();
1575             visitor.visit_body(&body);
1576             let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1577             for expr in &visitor.returns {
1578                 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1579                     let ty = self.resolve_vars_if_possible(returned_ty);
1580                     err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1581                 }
1582             }
1583         }
1584     }
1585
1586     fn report_closure_arg_mismatch(
1587         &self,
1588         span: Span,
1589         found_span: Option<Span>,
1590         found: ty::PolyTraitRef<'tcx>,
1591         expected: ty::PolyTraitRef<'tcx>,
1592     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1593         pub(crate) fn build_fn_sig_ty<'tcx>(
1594             infcx: &InferCtxt<'_, 'tcx>,
1595             trait_ref: ty::PolyTraitRef<'tcx>,
1596         ) -> Ty<'tcx> {
1597             let inputs = trait_ref.skip_binder().substs.type_at(1);
1598             let sig = match inputs.kind() {
1599                 ty::Tuple(inputs)
1600                     if infcx.tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some() =>
1601                 {
1602                     infcx.tcx.mk_fn_sig(
1603                         inputs.iter(),
1604                         infcx.next_ty_var(TypeVariableOrigin {
1605                             span: DUMMY_SP,
1606                             kind: TypeVariableOriginKind::MiscVariable,
1607                         }),
1608                         false,
1609                         hir::Unsafety::Normal,
1610                         abi::Abi::Rust,
1611                     )
1612                 }
1613                 _ => infcx.tcx.mk_fn_sig(
1614                     std::iter::once(inputs),
1615                     infcx.next_ty_var(TypeVariableOrigin {
1616                         span: DUMMY_SP,
1617                         kind: TypeVariableOriginKind::MiscVariable,
1618                     }),
1619                     false,
1620                     hir::Unsafety::Normal,
1621                     abi::Abi::Rust,
1622                 ),
1623             };
1624
1625             infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1626         }
1627
1628         let argument_kind = match expected.skip_binder().self_ty().kind() {
1629             ty::Closure(..) => "closure",
1630             ty::Generator(..) => "generator",
1631             _ => "function",
1632         };
1633         let mut err = struct_span_err!(
1634             self.tcx.sess,
1635             span,
1636             E0631,
1637             "type mismatch in {argument_kind} arguments",
1638         );
1639
1640         err.span_label(span, "expected due to this");
1641
1642         let found_span = found_span.unwrap_or(span);
1643         err.span_label(found_span, "found signature defined here");
1644
1645         let expected = build_fn_sig_ty(self, expected);
1646         let found = build_fn_sig_ty(self, found);
1647
1648         let (expected_str, found_str) = self.cmp(expected, found);
1649
1650         let signature_kind = format!("{argument_kind} signature");
1651         err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1652
1653         err
1654     }
1655
1656     fn suggest_fully_qualified_path(
1657         &self,
1658         err: &mut Diagnostic,
1659         item_def_id: DefId,
1660         span: Span,
1661         trait_ref: DefId,
1662     ) {
1663         if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1664             if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1665                 err.note(&format!(
1666                     "{}s cannot be accessed directly on a `trait`, they can only be \
1667                         accessed through a specific `impl`",
1668                     assoc_item.kind.as_def_kind().descr(item_def_id)
1669                 ));
1670                 err.span_suggestion(
1671                     span,
1672                     "use the fully qualified path to an implementation",
1673                     format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1674                     Applicability::HasPlaceholders,
1675                 );
1676             }
1677         }
1678     }
1679
1680     /// Adds an async-await specific note to the diagnostic when the future does not implement
1681     /// an auto trait because of a captured type.
1682     ///
1683     /// ```text
1684     /// note: future does not implement `Qux` as this value is used across an await
1685     ///   --> $DIR/issue-64130-3-other.rs:17:5
1686     ///    |
1687     /// LL |     let x = Foo;
1688     ///    |         - has type `Foo`
1689     /// LL |     baz().await;
1690     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1691     /// LL | }
1692     ///    | - `x` is later dropped here
1693     /// ```
1694     ///
1695     /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1696     /// is "replaced" with a different message and a more specific error.
1697     ///
1698     /// ```text
1699     /// error: future cannot be sent between threads safely
1700     ///   --> $DIR/issue-64130-2-send.rs:21:5
1701     ///    |
1702     /// LL | fn is_send<T: Send>(t: T) { }
1703     ///    |               ---- required by this bound in `is_send`
1704     /// ...
1705     /// LL |     is_send(bar());
1706     ///    |     ^^^^^^^ future returned by `bar` is not send
1707     ///    |
1708     ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1709     ///            implemented for `Foo`
1710     /// note: future is not send as this value is used across an await
1711     ///   --> $DIR/issue-64130-2-send.rs:15:5
1712     ///    |
1713     /// LL |     let x = Foo;
1714     ///    |         - has type `Foo`
1715     /// LL |     baz().await;
1716     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1717     /// LL | }
1718     ///    | - `x` is later dropped here
1719     /// ```
1720     ///
1721     /// Returns `true` if an async-await specific note was added to the diagnostic.
1722     #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
1723     fn maybe_note_obligation_cause_for_async_await(
1724         &self,
1725         err: &mut Diagnostic,
1726         obligation: &PredicateObligation<'tcx>,
1727     ) -> bool {
1728         let hir = self.tcx.hir();
1729
1730         // Attempt to detect an async-await error by looking at the obligation causes, looking
1731         // for a generator to be present.
1732         //
1733         // When a future does not implement a trait because of a captured type in one of the
1734         // generators somewhere in the call stack, then the result is a chain of obligations.
1735         //
1736         // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1737         // future is passed as an argument to a function C which requires a `Send` type, then the
1738         // chain looks something like this:
1739         //
1740         // - `BuiltinDerivedObligation` with a generator witness (B)
1741         // - `BuiltinDerivedObligation` with a generator (B)
1742         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1743         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1744         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1745         // - `BuiltinDerivedObligation` with a generator witness (A)
1746         // - `BuiltinDerivedObligation` with a generator (A)
1747         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1748         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1749         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1750         // - `BindingObligation` with `impl_send (Send requirement)
1751         //
1752         // The first obligation in the chain is the most useful and has the generator that captured
1753         // the type. The last generator (`outer_generator` below) has information about where the
1754         // bound was introduced. At least one generator should be present for this diagnostic to be
1755         // modified.
1756         let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1757             ty::PredicateKind::Trait(p) => (Some(p), Some(p.self_ty())),
1758             _ => (None, None),
1759         };
1760         let mut generator = None;
1761         let mut outer_generator = None;
1762         let mut next_code = Some(obligation.cause.code());
1763
1764         let mut seen_upvar_tys_infer_tuple = false;
1765
1766         while let Some(code) = next_code {
1767             debug!(?code);
1768             match code {
1769                 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1770                     next_code = Some(parent_code);
1771                 }
1772                 ObligationCauseCode::ImplDerivedObligation(cause) => {
1773                     let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1774                     debug!(
1775                         parent_trait_ref = ?cause.derived.parent_trait_pred,
1776                         self_ty.kind = ?ty.kind(),
1777                         "ImplDerived",
1778                     );
1779
1780                     match *ty.kind() {
1781                         ty::Generator(did, ..) => {
1782                             generator = generator.or(Some(did));
1783                             outer_generator = Some(did);
1784                         }
1785                         ty::GeneratorWitness(..) => {}
1786                         ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1787                             // By introducing a tuple of upvar types into the chain of obligations
1788                             // of a generator, the first non-generator item is now the tuple itself,
1789                             // we shall ignore this.
1790
1791                             seen_upvar_tys_infer_tuple = true;
1792                         }
1793                         _ if generator.is_none() => {
1794                             trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1795                             target_ty = Some(ty);
1796                         }
1797                         _ => {}
1798                     }
1799
1800                     next_code = Some(&cause.derived.parent_code);
1801                 }
1802                 ObligationCauseCode::DerivedObligation(derived_obligation)
1803                 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1804                     let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1805                     debug!(
1806                         parent_trait_ref = ?derived_obligation.parent_trait_pred,
1807                         self_ty.kind = ?ty.kind(),
1808                     );
1809
1810                     match *ty.kind() {
1811                         ty::Generator(did, ..) => {
1812                             generator = generator.or(Some(did));
1813                             outer_generator = Some(did);
1814                         }
1815                         ty::GeneratorWitness(..) => {}
1816                         ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1817                             // By introducing a tuple of upvar types into the chain of obligations
1818                             // of a generator, the first non-generator item is now the tuple itself,
1819                             // we shall ignore this.
1820
1821                             seen_upvar_tys_infer_tuple = true;
1822                         }
1823                         _ if generator.is_none() => {
1824                             trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1825                             target_ty = Some(ty);
1826                         }
1827                         _ => {}
1828                     }
1829
1830                     next_code = Some(&derived_obligation.parent_code);
1831                 }
1832                 _ => break,
1833             }
1834         }
1835
1836         // Only continue if a generator was found.
1837         debug!(?generator, ?trait_ref, ?target_ty);
1838         let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
1839             return false;
1840         };
1841
1842         let span = self.tcx.def_span(generator_did);
1843
1844         let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow());
1845         let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1846         debug!(
1847             ?generator_did,
1848             ?generator_did_root,
1849             in_progress_typeck_results.hir_owner = ?in_progress_typeck_results.as_ref().map(|t| t.hir_owner),
1850             ?span,
1851         );
1852
1853         let generator_body = generator_did
1854             .as_local()
1855             .and_then(|def_id| hir.maybe_body_owned_by(def_id))
1856             .map(|body_id| hir.body(body_id));
1857         let is_async = match generator_did.as_local() {
1858             Some(_) => generator_body
1859                 .and_then(|body| body.generator_kind())
1860                 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1861                 .unwrap_or(false),
1862             None => self
1863                 .tcx
1864                 .generator_kind(generator_did)
1865                 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1866                 .unwrap_or(false),
1867         };
1868         let mut visitor = AwaitsVisitor::default();
1869         if let Some(body) = generator_body {
1870             visitor.visit_body(body);
1871         }
1872         debug!(awaits = ?visitor.awaits);
1873
1874         // Look for a type inside the generator interior that matches the target type to get
1875         // a span.
1876         let target_ty_erased = self.tcx.erase_regions(target_ty);
1877         let ty_matches = |ty| -> bool {
1878             // Careful: the regions for types that appear in the
1879             // generator interior are not generally known, so we
1880             // want to erase them when comparing (and anyway,
1881             // `Send` and other bounds are generally unaffected by
1882             // the choice of region).  When erasing regions, we
1883             // also have to erase late-bound regions. This is
1884             // because the types that appear in the generator
1885             // interior generally contain "bound regions" to
1886             // represent regions that are part of the suspended
1887             // generator frame. Bound regions are preserved by
1888             // `erase_regions` and so we must also call
1889             // `erase_late_bound_regions`.
1890             let ty_erased = self.tcx.erase_late_bound_regions(ty);
1891             let ty_erased = self.tcx.erase_regions(ty_erased);
1892             let eq = ty_erased == target_ty_erased;
1893             debug!(?ty_erased, ?target_ty_erased, ?eq);
1894             eq
1895         };
1896
1897         let mut interior_or_upvar_span = None;
1898         let mut interior_extra_info = None;
1899
1900         // Get the typeck results from the infcx if the generator is the function we are currently
1901         // type-checking; otherwise, get them by performing a query.  This is needed to avoid
1902         // cycles. If we can't use resolved types because the generator comes from another crate,
1903         // we still provide a targeted error but without all the relevant spans.
1904         let generator_data: Option<GeneratorData<'tcx, '_>> = match &in_progress_typeck_results {
1905             Some(t) if t.hir_owner.to_def_id() == generator_did_root => {
1906                 Some(GeneratorData::Local(&t))
1907             }
1908             _ if generator_did.is_local() => {
1909                 Some(GeneratorData::Local(self.tcx.typeck(generator_did.expect_local())))
1910             }
1911             _ => self
1912                 .tcx
1913                 .generator_diagnostic_data(generator_did)
1914                 .as_ref()
1915                 .map(|generator_diag_data| GeneratorData::Foreign(generator_diag_data)),
1916         };
1917
1918         if let Some(generator_data) = generator_data.as_ref() {
1919             interior_or_upvar_span =
1920                 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
1921
1922             // The generator interior types share the same binders
1923             if let Some(cause) =
1924                 generator_data.get_generator_interior_types().skip_binder().iter().find(
1925                     |ty::GeneratorInteriorTypeCause { ty, .. }| {
1926                         ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
1927                     },
1928                 )
1929             {
1930                 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
1931                 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1932                     cause;
1933
1934                 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
1935                 interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
1936             }
1937
1938             if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
1939                 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span));
1940             }
1941         }
1942
1943         if let Some(interior_or_upvar_span) = interior_or_upvar_span {
1944             let typeck_results = generator_data.and_then(|generator_data| match generator_data {
1945                 GeneratorData::Local(typeck_results) => Some(typeck_results),
1946                 GeneratorData::Foreign(_) => None,
1947             });
1948             self.note_obligation_cause_for_async_await(
1949                 err,
1950                 interior_or_upvar_span,
1951                 interior_extra_info,
1952                 is_async,
1953                 outer_generator,
1954                 trait_ref,
1955                 target_ty,
1956                 typeck_results,
1957                 obligation,
1958                 next_code,
1959             );
1960             true
1961         } else {
1962             false
1963         }
1964     }
1965
1966     /// Unconditionally adds the diagnostic note described in
1967     /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1968     #[instrument(level = "debug", skip_all)]
1969     fn note_obligation_cause_for_async_await(
1970         &self,
1971         err: &mut Diagnostic,
1972         interior_or_upvar_span: GeneratorInteriorOrUpvar,
1973         interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
1974         is_async: bool,
1975         outer_generator: Option<DefId>,
1976         trait_pred: ty::TraitPredicate<'tcx>,
1977         target_ty: Ty<'tcx>,
1978         typeck_results: Option<&ty::TypeckResults<'tcx>>,
1979         obligation: &PredicateObligation<'tcx>,
1980         next_code: Option<&ObligationCauseCode<'tcx>>,
1981     ) {
1982         let source_map = self.tcx.sess.source_map();
1983
1984         let (await_or_yield, an_await_or_yield) =
1985             if is_async { ("await", "an await") } else { ("yield", "a yield") };
1986         let future_or_generator = if is_async { "future" } else { "generator" };
1987
1988         // Special case the primary error message when send or sync is the trait that was
1989         // not implemented.
1990         let hir = self.tcx.hir();
1991         let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
1992             self.tcx.get_diagnostic_name(trait_pred.def_id())
1993         {
1994             let (trait_name, trait_verb) =
1995                 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1996
1997             err.clear_code();
1998             err.set_primary_message(format!(
1999                 "{} cannot be {} between threads safely",
2000                 future_or_generator, trait_verb
2001             ));
2002
2003             let original_span = err.span.primary_span().unwrap();
2004             let mut span = MultiSpan::from_span(original_span);
2005
2006             let message = outer_generator
2007                 .and_then(|generator_did| {
2008                     Some(match self.tcx.generator_kind(generator_did).unwrap() {
2009                         GeneratorKind::Gen => format!("generator is not {}", trait_name),
2010                         GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2011                             .tcx
2012                             .parent(generator_did)
2013                             .as_local()
2014                             .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2015                             .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2016                             .map(|name| {
2017                                 format!("future returned by `{}` is not {}", name, trait_name)
2018                             })?,
2019                         GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2020                             format!("future created by async block is not {}", trait_name)
2021                         }
2022                         GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2023                             format!("future created by async closure is not {}", trait_name)
2024                         }
2025                     })
2026                 })
2027                 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2028
2029             span.push_span_label(original_span, message);
2030             err.set_span(span);
2031
2032             format!("is not {}", trait_name)
2033         } else {
2034             format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2035         };
2036
2037         let mut explain_yield = |interior_span: Span,
2038                                  yield_span: Span,
2039                                  scope_span: Option<Span>| {
2040             let mut span = MultiSpan::from_span(yield_span);
2041             if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
2042                 // #70935: If snippet contains newlines, display "the value" instead
2043                 // so that we do not emit complex diagnostics.
2044                 let snippet = &format!("`{}`", snippet);
2045                 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
2046                 // note: future is not `Send` as this value is used across an await
2047                 //   --> $DIR/issue-70935-complex-spans.rs:13:9
2048                 //    |
2049                 // LL |            baz(|| async {
2050                 //    |  ______________-
2051                 //    | |
2052                 //    | |
2053                 // LL | |              foo(tx.clone());
2054                 // LL | |          }).await;
2055                 //    | |          - ^^^^^^ await occurs here, with value maybe used later
2056                 //    | |__________|
2057                 //    |            has type `closure` which is not `Send`
2058                 // note: value is later dropped here
2059                 // LL | |          }).await;
2060                 //    | |                  ^
2061                 //
2062                 span.push_span_label(
2063                     yield_span,
2064                     format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2065                 );
2066                 span.push_span_label(
2067                     interior_span,
2068                     format!("has type `{}` which {}", target_ty, trait_explanation),
2069                 );
2070                 // If available, use the scope span to annotate the drop location.
2071                 let mut scope_note = None;
2072                 if let Some(scope_span) = scope_span {
2073                     let scope_span = source_map.end_point(scope_span);
2074
2075                     let msg = format!("{} is later dropped here", snippet);
2076                     if source_map.is_multiline(yield_span.between(scope_span)) {
2077                         span.push_span_label(scope_span, msg);
2078                     } else {
2079                         scope_note = Some((scope_span, msg));
2080                     }
2081                 }
2082                 err.span_note(
2083                     span,
2084                     &format!(
2085                         "{} {} as this value is used across {}",
2086                         future_or_generator, trait_explanation, an_await_or_yield
2087                     ),
2088                 );
2089                 if let Some((span, msg)) = scope_note {
2090                     err.span_note(span, &msg);
2091                 }
2092             }
2093         };
2094         match interior_or_upvar_span {
2095             GeneratorInteriorOrUpvar::Interior(interior_span) => {
2096                 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2097                     if let Some(await_span) = from_awaited_ty {
2098                         // The type causing this obligation is one being awaited at await_span.
2099                         let mut span = MultiSpan::from_span(await_span);
2100                         span.push_span_label(
2101                             await_span,
2102                             format!(
2103                                 "await occurs here on type `{}`, which {}",
2104                                 target_ty, trait_explanation
2105                             ),
2106                         );
2107                         err.span_note(
2108                             span,
2109                             &format!(
2110                                 "future {not_trait} as it awaits another future which {not_trait}",
2111                                 not_trait = trait_explanation
2112                             ),
2113                         );
2114                     } else {
2115                         // Look at the last interior type to get a span for the `.await`.
2116                         debug!(
2117                             generator_interior_types = ?format_args!(
2118                                 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2119                             ),
2120                         );
2121                         explain_yield(interior_span, yield_span, scope_span);
2122                     }
2123
2124                     if let Some(expr_id) = expr {
2125                         let expr = hir.expect_expr(expr_id);
2126                         debug!("target_ty evaluated from {:?}", expr);
2127
2128                         let parent = hir.get_parent_node(expr_id);
2129                         if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2130                             let parent_span = hir.span(parent);
2131                             let parent_did = parent.owner.to_def_id();
2132                             // ```rust
2133                             // impl T {
2134                             //     fn foo(&self) -> i32 {}
2135                             // }
2136                             // T.foo();
2137                             // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2138                             // ```
2139                             //
2140                             let is_region_borrow = if let Some(typeck_results) = typeck_results {
2141                                 typeck_results
2142                                     .expr_adjustments(expr)
2143                                     .iter()
2144                                     .any(|adj| adj.is_region_borrow())
2145                             } else {
2146                                 false
2147                             };
2148
2149                             // ```rust
2150                             // struct Foo(*const u8);
2151                             // bar(Foo(std::ptr::null())).await;
2152                             //     ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2153                             // ```
2154                             debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2155                             let is_raw_borrow_inside_fn_like_call =
2156                                 match self.tcx.def_kind(parent_did) {
2157                                     DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2158                                     _ => false,
2159                                 };
2160                             if let Some(typeck_results) = typeck_results {
2161                                 if (typeck_results.is_method_call(e) && is_region_borrow)
2162                                     || is_raw_borrow_inside_fn_like_call
2163                                 {
2164                                     err.span_help(
2165                                         parent_span,
2166                                         "consider moving this into a `let` \
2167                         binding to create a shorter lived borrow",
2168                                     );
2169                                 }
2170                             }
2171                         }
2172                     }
2173                 }
2174             }
2175             GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2176                 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2177                 let refers_to_non_sync = match target_ty.kind() {
2178                     ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2179                         Ok(eval) if !eval.may_apply() => Some(ref_ty),
2180                         _ => None,
2181                     },
2182                     _ => None,
2183                 };
2184
2185                 let (span_label, span_note) = match refers_to_non_sync {
2186                     // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2187                     // include suggestions to make `T: Sync` so that `&T: Send`
2188                     Some(ref_ty) => (
2189                         format!(
2190                             "has type `{}` which {}, because `{}` is not `Sync`",
2191                             target_ty, trait_explanation, ref_ty
2192                         ),
2193                         format!(
2194                             "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2195                             trait_explanation
2196                         ),
2197                     ),
2198                     None => (
2199                         format!("has type `{}` which {}", target_ty, trait_explanation),
2200                         format!("captured value {}", trait_explanation),
2201                     ),
2202                 };
2203
2204                 let mut span = MultiSpan::from_span(upvar_span);
2205                 span.push_span_label(upvar_span, span_label);
2206                 err.span_note(span, &span_note);
2207             }
2208         }
2209
2210         // Add a note for the item obligation that remains - normally a note pointing to the
2211         // bound that introduced the obligation (e.g. `T: Send`).
2212         debug!(?next_code);
2213         self.note_obligation_cause_code(
2214             err,
2215             &obligation.predicate,
2216             obligation.param_env,
2217             next_code.unwrap(),
2218             &mut Vec::new(),
2219             &mut Default::default(),
2220         );
2221     }
2222
2223     fn note_obligation_cause_code<T>(
2224         &self,
2225         err: &mut Diagnostic,
2226         predicate: &T,
2227         param_env: ty::ParamEnv<'tcx>,
2228         cause_code: &ObligationCauseCode<'tcx>,
2229         obligated_types: &mut Vec<Ty<'tcx>>,
2230         seen_requirements: &mut FxHashSet<DefId>,
2231     ) where
2232         T: fmt::Display,
2233     {
2234         let tcx = self.tcx;
2235         match *cause_code {
2236             ObligationCauseCode::ExprAssignable
2237             | ObligationCauseCode::MatchExpressionArm { .. }
2238             | ObligationCauseCode::Pattern { .. }
2239             | ObligationCauseCode::IfExpression { .. }
2240             | ObligationCauseCode::IfExpressionWithNoElse
2241             | ObligationCauseCode::MainFunctionType
2242             | ObligationCauseCode::StartFunctionType
2243             | ObligationCauseCode::IntrinsicType
2244             | ObligationCauseCode::MethodReceiver
2245             | ObligationCauseCode::ReturnNoExpression
2246             | ObligationCauseCode::UnifyReceiver(..)
2247             | ObligationCauseCode::OpaqueType
2248             | ObligationCauseCode::MiscObligation
2249             | ObligationCauseCode::WellFormed(..)
2250             | ObligationCauseCode::MatchImpl(..)
2251             | ObligationCauseCode::ReturnType
2252             | ObligationCauseCode::ReturnValue(_)
2253             | ObligationCauseCode::BlockTailExpression(_)
2254             | ObligationCauseCode::AwaitableExpr(_)
2255             | ObligationCauseCode::ForLoopIterator
2256             | ObligationCauseCode::QuestionMark
2257             | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2258             | ObligationCauseCode::LetElse
2259             | ObligationCauseCode::BinOp { .. } => {}
2260             ObligationCauseCode::SliceOrArrayElem => {
2261                 err.note("slice and array elements must have `Sized` type");
2262             }
2263             ObligationCauseCode::TupleElem => {
2264                 err.note("only the last element of a tuple may have a dynamically sized type");
2265             }
2266             ObligationCauseCode::ProjectionWf(data) => {
2267                 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2268             }
2269             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2270                 err.note(&format!(
2271                     "required so that reference `{}` does not outlive its referent",
2272                     ref_ty,
2273                 ));
2274             }
2275             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2276                 err.note(&format!(
2277                     "required so that the lifetime bound of `{}` for `{}` is satisfied",
2278                     region, object_ty,
2279                 ));
2280             }
2281             ObligationCauseCode::ItemObligation(_)
2282             | ObligationCauseCode::ExprItemObligation(..) => {
2283                 // We hold the `DefId` of the item introducing the obligation, but displaying it
2284                 // doesn't add user usable information. It always point at an associated item.
2285             }
2286             ObligationCauseCode::BindingObligation(item_def_id, span)
2287             | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2288                 let item_name = tcx.def_path_str(item_def_id);
2289                 let mut multispan = MultiSpan::from(span);
2290                 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2291                     let sm = tcx.sess.source_map();
2292                     let same_line =
2293                         match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2294                             (Ok(l), Ok(r)) => l.line == r.line,
2295                             _ => true,
2296                         };
2297                     if !ident.span.overlaps(span) && !same_line {
2298                         multispan.push_span_label(ident.span, "required by a bound in this");
2299                     }
2300                 }
2301                 let descr = format!("required by a bound in `{}`", item_name);
2302                 if span != DUMMY_SP {
2303                     let msg = format!("required by this bound in `{}`", item_name);
2304                     multispan.push_span_label(span, msg);
2305                     err.span_note(multispan, &descr);
2306                 } else {
2307                     err.span_note(tcx.def_span(item_def_id), &descr);
2308                 }
2309             }
2310             ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2311                 err.note(&format!(
2312                     "required for the cast from `{}` to the object type `{}`",
2313                     self.ty_to_string(concrete_ty),
2314                     self.ty_to_string(object_ty)
2315                 ));
2316             }
2317             ObligationCauseCode::Coercion { source: _, target } => {
2318                 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2319             }
2320             ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2321                 err.note(
2322                     "the `Copy` trait is required because this value will be copied for each element of the array",
2323                 );
2324
2325                 if is_const_fn {
2326                     err.help(
2327                         "consider creating a new `const` item and initializing it with the result \
2328                         of the function call to be used in the repeat position, like \
2329                         `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2330                     );
2331                 }
2332
2333                 if self.tcx.sess.is_nightly_build() && is_const_fn {
2334                     err.help(
2335                         "create an inline `const` block, see RFC #2920 \
2336                          <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2337                     );
2338                 }
2339             }
2340             ObligationCauseCode::VariableType(hir_id) => {
2341                 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2342                 match self.tcx.hir().find(parent_node) {
2343                     Some(Node::Local(hir::Local {
2344                         init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2345                         ..
2346                     })) => {
2347                         // When encountering an assignment of an unsized trait, like
2348                         // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2349                         // order to use have a slice instead.
2350                         err.span_suggestion_verbose(
2351                             span.shrink_to_lo(),
2352                             "consider borrowing here",
2353                             "&",
2354                             Applicability::MachineApplicable,
2355                         );
2356                         err.note("all local variables must have a statically known size");
2357                     }
2358                     Some(Node::Param(param)) => {
2359                         err.span_suggestion_verbose(
2360                             param.ty_span.shrink_to_lo(),
2361                             "function arguments must have a statically known size, borrowed types \
2362                             always have a known size",
2363                             "&",
2364                             Applicability::MachineApplicable,
2365                         );
2366                     }
2367                     _ => {
2368                         err.note("all local variables must have a statically known size");
2369                     }
2370                 }
2371                 if !self.tcx.features().unsized_locals {
2372                     err.help("unsized locals are gated as an unstable feature");
2373                 }
2374             }
2375             ObligationCauseCode::SizedArgumentType(sp) => {
2376                 if let Some(span) = sp {
2377                     err.span_suggestion_verbose(
2378                         span.shrink_to_lo(),
2379                         "function arguments must have a statically known size, borrowed types \
2380                          always have a known size",
2381                         "&",
2382                         Applicability::MachineApplicable,
2383                     );
2384                 } else {
2385                     err.note("all function arguments must have a statically known size");
2386                 }
2387                 if tcx.sess.opts.unstable_features.is_nightly_build()
2388                     && !self.tcx.features().unsized_fn_params
2389                 {
2390                     err.help("unsized fn params are gated as an unstable feature");
2391                 }
2392             }
2393             ObligationCauseCode::SizedReturnType => {
2394                 err.note("the return type of a function must have a statically known size");
2395             }
2396             ObligationCauseCode::SizedYieldType => {
2397                 err.note("the yield type of a generator must have a statically known size");
2398             }
2399             ObligationCauseCode::SizedBoxType => {
2400                 err.note("the type of a box expression must have a statically known size");
2401             }
2402             ObligationCauseCode::AssignmentLhsSized => {
2403                 err.note("the left-hand-side of an assignment must have a statically known size");
2404             }
2405             ObligationCauseCode::TupleInitializerSized => {
2406                 err.note("tuples must have a statically known size to be initialized");
2407             }
2408             ObligationCauseCode::StructInitializerSized => {
2409                 err.note("structs must have a statically known size to be initialized");
2410             }
2411             ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2412                 match *item {
2413                     AdtKind::Struct => {
2414                         if last {
2415                             err.note(
2416                                 "the last field of a packed struct may only have a \
2417                                 dynamically sized type if it does not need drop to be run",
2418                             );
2419                         } else {
2420                             err.note(
2421                                 "only the last field of a struct may have a dynamically sized type",
2422                             );
2423                         }
2424                     }
2425                     AdtKind::Union => {
2426                         err.note("no field of a union may have a dynamically sized type");
2427                     }
2428                     AdtKind::Enum => {
2429                         err.note("no field of an enum variant may have a dynamically sized type");
2430                     }
2431                 }
2432                 err.help("change the field's type to have a statically known size");
2433                 err.span_suggestion(
2434                     span.shrink_to_lo(),
2435                     "borrowed types always have a statically known size",
2436                     "&",
2437                     Applicability::MachineApplicable,
2438                 );
2439                 err.multipart_suggestion(
2440                     "the `Box` type always has a statically known size and allocates its contents \
2441                      in the heap",
2442                     vec![
2443                         (span.shrink_to_lo(), "Box<".to_string()),
2444                         (span.shrink_to_hi(), ">".to_string()),
2445                     ],
2446                     Applicability::MachineApplicable,
2447                 );
2448             }
2449             ObligationCauseCode::ConstSized => {
2450                 err.note("constant expressions must have a statically known size");
2451             }
2452             ObligationCauseCode::InlineAsmSized => {
2453                 err.note("all inline asm arguments must have a statically known size");
2454             }
2455             ObligationCauseCode::ConstPatternStructural => {
2456                 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2457             }
2458             ObligationCauseCode::SharedStatic => {
2459                 err.note("shared static variables must have a type that implements `Sync`");
2460             }
2461             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2462                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2463                 let ty = parent_trait_ref.skip_binder().self_ty();
2464                 if parent_trait_ref.references_error() {
2465                     // NOTE(eddyb) this was `.cancel()`, but `err`
2466                     // is borrowed, so we can't fully defuse it.
2467                     err.downgrade_to_delayed_bug();
2468                     return;
2469                 }
2470
2471                 // If the obligation for a tuple is set directly by a Generator or Closure,
2472                 // then the tuple must be the one containing capture types.
2473                 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2474                     false
2475                 } else {
2476                     if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2477                     {
2478                         let parent_trait_ref =
2479                             self.resolve_vars_if_possible(data.parent_trait_pred);
2480                         let nested_ty = parent_trait_ref.skip_binder().self_ty();
2481                         matches!(nested_ty.kind(), ty::Generator(..))
2482                             || matches!(nested_ty.kind(), ty::Closure(..))
2483                     } else {
2484                         false
2485                     }
2486                 };
2487
2488                 let from_generator = tcx.lang_items().from_generator_fn().unwrap();
2489
2490                 // Don't print the tuple of capture types
2491                 'print: {
2492                     if !is_upvar_tys_infer_tuple {
2493                         let msg = format!("required because it appears within the type `{}`", ty);
2494                         match ty.kind() {
2495                             ty::Adt(def, _) => {
2496                                 // `gen_future` is used in all async functions; it doesn't add any additional info.
2497                                 if self.tcx.is_diagnostic_item(sym::gen_future, def.did()) {
2498                                     break 'print;
2499                                 }
2500                                 match self.tcx.opt_item_ident(def.did()) {
2501                                     Some(ident) => err.span_note(ident.span, &msg),
2502                                     None => err.note(&msg),
2503                                 }
2504                             }
2505                             ty::Opaque(def_id, _) => {
2506                                 // Avoid printing the future from `core::future::from_generator`, it's not helpful
2507                                 if tcx.parent(*def_id) == from_generator {
2508                                     break 'print;
2509                                 }
2510
2511                                 // If the previous type is `from_generator`, this is the future generated by the body of an async function.
2512                                 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2513                                 let is_future = tcx.ty_is_opaque_future(ty);
2514                                 debug!(
2515                                     ?obligated_types,
2516                                     ?is_future,
2517                                     "note_obligation_cause_code: check for async fn"
2518                                 );
2519                                 if is_future
2520                                     && obligated_types.last().map_or(false, |ty| match ty.kind() {
2521                                         ty::Opaque(last_def_id, _) => {
2522                                             tcx.parent(*last_def_id) == from_generator
2523                                         }
2524                                         _ => false,
2525                                     })
2526                                 {
2527                                     break 'print;
2528                                 }
2529                                 err.span_note(self.tcx.def_span(def_id), &msg)
2530                             }
2531                             ty::GeneratorWitness(bound_tys) => {
2532                                 use std::fmt::Write;
2533
2534                                 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2535                                 // Maybe we should just remove this note altogether?
2536                                 // FIXME: only print types which don't meet the trait requirement
2537                                 let mut msg =
2538                                     "required because it captures the following types: ".to_owned();
2539                                 for ty in bound_tys.skip_binder() {
2540                                     write!(msg, "`{}`, ", ty).unwrap();
2541                                 }
2542                                 err.note(msg.trim_end_matches(", "))
2543                             }
2544                             ty::Generator(def_id, _, _) => {
2545                                 let sp = self.tcx.def_span(def_id);
2546
2547                                 // Special-case this to say "async block" instead of `[static generator]`.
2548                                 let kind = tcx.generator_kind(def_id).unwrap();
2549                                 err.span_note(
2550                                     sp,
2551                                     &format!("required because it's used within this {}", kind),
2552                                 )
2553                             }
2554                             ty::Closure(def_id, _) => err.span_note(
2555                                 self.tcx.def_span(def_id),
2556                                 &format!("required because it's used within this closure"),
2557                             ),
2558                             _ => err.note(&msg),
2559                         };
2560                     }
2561                 }
2562
2563                 obligated_types.push(ty);
2564
2565                 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2566                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2567                     // #74711: avoid a stack overflow
2568                     ensure_sufficient_stack(|| {
2569                         self.note_obligation_cause_code(
2570                             err,
2571                             &parent_predicate,
2572                             param_env,
2573                             &data.parent_code,
2574                             obligated_types,
2575                             seen_requirements,
2576                         )
2577                     });
2578                 } else {
2579                     ensure_sufficient_stack(|| {
2580                         self.note_obligation_cause_code(
2581                             err,
2582                             &parent_predicate,
2583                             param_env,
2584                             cause_code.peel_derives(),
2585                             obligated_types,
2586                             seen_requirements,
2587                         )
2588                     });
2589                 }
2590             }
2591             ObligationCauseCode::ImplDerivedObligation(ref data) => {
2592                 let mut parent_trait_pred =
2593                     self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2594                 parent_trait_pred.remap_constness_diag(param_env);
2595                 let parent_def_id = parent_trait_pred.def_id();
2596                 let msg = format!(
2597                     "required for `{}` to implement `{}`",
2598                     parent_trait_pred.skip_binder().self_ty(),
2599                     parent_trait_pred.print_modifiers_and_trait_path()
2600                 );
2601                 let mut is_auto_trait = false;
2602                 match self.tcx.hir().get_if_local(data.impl_def_id) {
2603                     Some(Node::Item(hir::Item {
2604                         kind: hir::ItemKind::Trait(is_auto, ..),
2605                         ident,
2606                         ..
2607                     })) => {
2608                         // FIXME: we should do something else so that it works even on crate foreign
2609                         // auto traits.
2610                         is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2611                         err.span_note(ident.span, &msg)
2612                     }
2613                     Some(Node::Item(hir::Item {
2614                         kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2615                         ..
2616                     })) => {
2617                         let mut spans = Vec::with_capacity(2);
2618                         if let Some(trait_ref) = of_trait {
2619                             spans.push(trait_ref.path.span);
2620                         }
2621                         spans.push(self_ty.span);
2622                         err.span_note(spans, &msg)
2623                     }
2624                     _ => err.note(&msg),
2625                 };
2626
2627                 let mut parent_predicate = parent_trait_pred.to_predicate(tcx);
2628                 let mut data = &data.derived;
2629                 let mut count = 0;
2630                 seen_requirements.insert(parent_def_id);
2631                 if is_auto_trait {
2632                     // We don't want to point at the ADT saying "required because it appears within
2633                     // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2634                     while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2635                         &*data.parent_code
2636                     {
2637                         let child_trait_ref =
2638                             self.resolve_vars_if_possible(derived.parent_trait_pred);
2639                         let child_def_id = child_trait_ref.def_id();
2640                         if seen_requirements.insert(child_def_id) {
2641                             break;
2642                         }
2643                         data = derived;
2644                         parent_predicate = child_trait_ref.to_predicate(tcx);
2645                         parent_trait_pred = child_trait_ref;
2646                     }
2647                 }
2648                 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2649                     // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2650                     let child_trait_pred =
2651                         self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2652                     let child_def_id = child_trait_pred.def_id();
2653                     if seen_requirements.insert(child_def_id) {
2654                         break;
2655                     }
2656                     count += 1;
2657                     data = &child.derived;
2658                     parent_predicate = child_trait_pred.to_predicate(tcx);
2659                     parent_trait_pred = child_trait_pred;
2660                 }
2661                 if count > 0 {
2662                     err.note(&format!(
2663                         "{} redundant requirement{} hidden",
2664                         count,
2665                         pluralize!(count)
2666                     ));
2667                     err.note(&format!(
2668                         "required for `{}` to implement `{}`",
2669                         parent_trait_pred.skip_binder().self_ty(),
2670                         parent_trait_pred.print_modifiers_and_trait_path()
2671                     ));
2672                 }
2673                 // #74711: avoid a stack overflow
2674                 ensure_sufficient_stack(|| {
2675                     self.note_obligation_cause_code(
2676                         err,
2677                         &parent_predicate,
2678                         param_env,
2679                         &data.parent_code,
2680                         obligated_types,
2681                         seen_requirements,
2682                     )
2683                 });
2684             }
2685             ObligationCauseCode::DerivedObligation(ref data) => {
2686                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2687                 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2688                 // #74711: avoid a stack overflow
2689                 ensure_sufficient_stack(|| {
2690                     self.note_obligation_cause_code(
2691                         err,
2692                         &parent_predicate,
2693                         param_env,
2694                         &data.parent_code,
2695                         obligated_types,
2696                         seen_requirements,
2697                     )
2698                 });
2699             }
2700             ObligationCauseCode::FunctionArgumentObligation {
2701                 arg_hir_id,
2702                 call_hir_id,
2703                 ref parent_code,
2704             } => {
2705                 let hir = self.tcx.hir();
2706                 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2707                     hir.find(arg_hir_id)
2708                 {
2709                     let in_progress_typeck_results =
2710                         self.in_progress_typeck_results.map(|t| t.borrow());
2711                     let parent_id = hir.get_parent_item(arg_hir_id);
2712                     let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
2713                         Some(t) if t.hir_owner == parent_id => t,
2714                         _ => self.tcx.typeck(parent_id),
2715                     };
2716                     let ty = typeck_results.expr_ty_adjusted(expr);
2717                     let span = expr.peel_blocks().span;
2718                     if Some(span) != err.span.primary_span() {
2719                         err.span_label(
2720                             span,
2721                             &if ty.references_error() {
2722                                 String::new()
2723                             } else {
2724                                 format!("this tail expression is of type `{:?}`", ty)
2725                             },
2726                         );
2727                     }
2728                 }
2729                 if let Some(Node::Expr(hir::Expr {
2730                     kind:
2731                         hir::ExprKind::Call(hir::Expr { span, .. }, _)
2732                         | hir::ExprKind::MethodCall(
2733                             hir::PathSegment { ident: Ident { span, .. }, .. },
2734                             ..,
2735                         ),
2736                     ..
2737                 })) = hir.find(call_hir_id)
2738                 {
2739                     if Some(*span) != err.span.primary_span() {
2740                         err.span_label(*span, "required by a bound introduced by this call");
2741                     }
2742                 }
2743                 ensure_sufficient_stack(|| {
2744                     self.note_obligation_cause_code(
2745                         err,
2746                         predicate,
2747                         param_env,
2748                         &parent_code,
2749                         obligated_types,
2750                         seen_requirements,
2751                     )
2752                 });
2753             }
2754             ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
2755                 let item_name = self.tcx.item_name(trait_item_def_id);
2756                 let msg = format!(
2757                     "the requirement `{}` appears on the `impl`'s {kind} `{}` but not on the \
2758                      corresponding trait's {kind}",
2759                     predicate, item_name,
2760                 );
2761                 let sp = self
2762                     .tcx
2763                     .opt_item_ident(trait_item_def_id)
2764                     .map(|i| i.span)
2765                     .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2766                 let mut assoc_span: MultiSpan = sp.into();
2767                 assoc_span.push_span_label(
2768                     sp,
2769                     format!("this trait's {kind} doesn't have the requirement `{}`", predicate),
2770                 );
2771                 if let Some(ident) = self
2772                     .tcx
2773                     .opt_associated_item(trait_item_def_id)
2774                     .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
2775                 {
2776                     assoc_span.push_span_label(ident.span, "in this trait");
2777                 }
2778                 err.span_note(assoc_span, &msg);
2779             }
2780             ObligationCauseCode::TrivialBound => {
2781                 err.help("see issue #48214");
2782                 if tcx.sess.opts.unstable_features.is_nightly_build() {
2783                     err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2784                 }
2785             }
2786             ObligationCauseCode::OpaqueReturnType(expr_info) => {
2787                 if let Some((expr_ty, expr_span)) = expr_info {
2788                     let expr_ty = self.resolve_vars_if_possible(expr_ty);
2789                     err.span_label(
2790                         expr_span,
2791                         format!("return type was inferred to be `{expr_ty}` here"),
2792                     );
2793                 }
2794             }
2795         }
2796     }
2797
2798     fn suggest_new_overflow_limit(&self, err: &mut Diagnostic) {
2799         let suggested_limit = match self.tcx.recursion_limit() {
2800             Limit(0) => Limit(2),
2801             limit => limit * 2,
2802         };
2803         err.help(&format!(
2804             "consider increasing the recursion limit by adding a \
2805              `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
2806             suggested_limit,
2807             self.tcx.crate_name(LOCAL_CRATE),
2808         ));
2809     }
2810
2811     #[instrument(
2812         level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
2813     )]
2814     fn suggest_await_before_try(
2815         &self,
2816         err: &mut Diagnostic,
2817         obligation: &PredicateObligation<'tcx>,
2818         trait_pred: ty::PolyTraitPredicate<'tcx>,
2819         span: Span,
2820     ) {
2821         let body_hir_id = obligation.cause.body_id;
2822         let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2823
2824         if let Some(body_id) =
2825             self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
2826         {
2827             let body = self.tcx.hir().body(body_id);
2828             if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2829                 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2830
2831                 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2832                 let impls_future = self.type_implements_trait(
2833                     future_trait,
2834                     self.tcx.erase_late_bound_regions(self_ty),
2835                     ty::List::empty(),
2836                     obligation.param_env,
2837                 );
2838                 if !impls_future.must_apply_modulo_regions() {
2839                     return;
2840                 }
2841
2842                 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2843                 // `<T as Future>::Output`
2844                 let projection_ty = trait_pred.map_bound(|trait_pred| {
2845                     self.tcx.mk_projection(
2846                         item_def_id,
2847                         // Future::Output has no substs
2848                         self.tcx.mk_substs_trait(trait_pred.self_ty(), &[]),
2849                     )
2850                 });
2851                 let projection_ty = normalize_to(
2852                     &mut SelectionContext::new(self),
2853                     obligation.param_env,
2854                     obligation.cause.clone(),
2855                     projection_ty,
2856                     &mut vec![],
2857                 );
2858
2859                 debug!(
2860                     normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
2861                 );
2862                 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2863                     obligation.param_env,
2864                     trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
2865                 );
2866                 debug!(try_trait_obligation = ?try_obligation);
2867                 if self.predicate_may_hold(&try_obligation)
2868                     && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2869                     && snippet.ends_with('?')
2870                 {
2871                     err.span_suggestion_verbose(
2872                         span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2873                         "consider `await`ing on the `Future`",
2874                         ".await",
2875                         Applicability::MaybeIncorrect,
2876                     );
2877                 }
2878             }
2879         }
2880     }
2881
2882     fn suggest_floating_point_literal(
2883         &self,
2884         obligation: &PredicateObligation<'tcx>,
2885         err: &mut Diagnostic,
2886         trait_ref: &ty::PolyTraitRef<'tcx>,
2887     ) {
2888         let rhs_span = match obligation.cause.code() {
2889             ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
2890             _ => return,
2891         };
2892         match (
2893             trait_ref.skip_binder().self_ty().kind(),
2894             trait_ref.skip_binder().substs.type_at(1).kind(),
2895         ) {
2896             (ty::Float(_), ty::Infer(InferTy::IntVar(_))) => {
2897                 err.span_suggestion_verbose(
2898                     rhs_span.shrink_to_hi(),
2899                     "consider using a floating-point literal by writing it with `.0`",
2900                     ".0",
2901                     Applicability::MaybeIncorrect,
2902                 );
2903             }
2904             _ => {}
2905         }
2906     }
2907
2908     fn suggest_derive(
2909         &self,
2910         obligation: &PredicateObligation<'tcx>,
2911         err: &mut Diagnostic,
2912         trait_pred: ty::PolyTraitPredicate<'tcx>,
2913     ) {
2914         let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
2915             return;
2916         };
2917         let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
2918             ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
2919             _ => return,
2920         };
2921         let can_derive = {
2922             let is_derivable_trait = match diagnostic_name {
2923                 sym::Default => !adt.is_enum(),
2924                 sym::PartialEq | sym::PartialOrd => {
2925                     let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
2926                     trait_pred.skip_binder().self_ty() == rhs_ty
2927                 }
2928                 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
2929                 _ => false,
2930             };
2931             is_derivable_trait &&
2932                 // Ensure all fields impl the trait.
2933                 adt.all_fields().all(|field| {
2934                     let field_ty = field.ty(self.tcx, substs);
2935                     let trait_substs = match diagnostic_name {
2936                         sym::PartialEq | sym::PartialOrd => {
2937                             self.tcx.mk_substs_trait(field_ty, &[field_ty.into()])
2938                         }
2939                         _ => self.tcx.mk_substs_trait(field_ty, &[]),
2940                     };
2941                     let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
2942                         trait_ref: ty::TraitRef {
2943                             substs: trait_substs,
2944                             ..trait_pred.skip_binder().trait_ref
2945                         },
2946                         ..*tr
2947                     });
2948                     let field_obl = Obligation::new(
2949                         obligation.cause.clone(),
2950                         obligation.param_env,
2951                         trait_pred.to_predicate(self.tcx),
2952                     );
2953                     self.predicate_must_hold_modulo_regions(&field_obl)
2954                 })
2955         };
2956         if can_derive {
2957             err.span_suggestion_verbose(
2958                 self.tcx.def_span(adt.did()).shrink_to_lo(),
2959                 &format!(
2960                     "consider annotating `{}` with `#[derive({})]`",
2961                     trait_pred.skip_binder().self_ty(),
2962                     diagnostic_name,
2963                 ),
2964                 format!("#[derive({})]\n", diagnostic_name),
2965                 Applicability::MaybeIncorrect,
2966             );
2967         }
2968     }
2969
2970     fn suggest_dereferencing_index(
2971         &self,
2972         obligation: &PredicateObligation<'tcx>,
2973         err: &mut Diagnostic,
2974         trait_pred: ty::PolyTraitPredicate<'tcx>,
2975     ) {
2976         if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
2977             && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
2978             && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
2979             && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
2980             && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
2981         {
2982             err.span_suggestion_verbose(
2983                 obligation.cause.span.shrink_to_lo(),
2984             "dereference this index",
2985             '*',
2986                 Applicability::MachineApplicable,
2987             );
2988         }
2989     }
2990 }
2991
2992 /// Collect all the returned expressions within the input expression.
2993 /// Used to point at the return spans when we want to suggest some change to them.
2994 #[derive(Default)]
2995 pub struct ReturnsVisitor<'v> {
2996     pub returns: Vec<&'v hir::Expr<'v>>,
2997     in_block_tail: bool,
2998 }
2999
3000 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3001     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3002         // Visit every expression to detect `return` paths, either through the function's tail
3003         // expression or `return` statements. We walk all nodes to find `return` statements, but
3004         // we only care about tail expressions when `in_block_tail` is `true`, which means that
3005         // they're in the return path of the function body.
3006         match ex.kind {
3007             hir::ExprKind::Ret(Some(ex)) => {
3008                 self.returns.push(ex);
3009             }
3010             hir::ExprKind::Block(block, _) if self.in_block_tail => {
3011                 self.in_block_tail = false;
3012                 for stmt in block.stmts {
3013                     hir::intravisit::walk_stmt(self, stmt);
3014                 }
3015                 self.in_block_tail = true;
3016                 if let Some(expr) = block.expr {
3017                     self.visit_expr(expr);
3018                 }
3019             }
3020             hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3021                 self.visit_expr(then);
3022                 if let Some(el) = else_opt {
3023                     self.visit_expr(el);
3024                 }
3025             }
3026             hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3027                 for arm in arms {
3028                     self.visit_expr(arm.body);
3029                 }
3030             }
3031             // We need to walk to find `return`s in the entire body.
3032             _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3033             _ => self.returns.push(ex),
3034         }
3035     }
3036
3037     fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3038         assert!(!self.in_block_tail);
3039         if body.generator_kind().is_none() {
3040             if let hir::ExprKind::Block(block, None) = body.value.kind {
3041                 if block.expr.is_some() {
3042                     self.in_block_tail = true;
3043                 }
3044             }
3045         }
3046         hir::intravisit::walk_body(self, body);
3047     }
3048 }
3049
3050 /// Collect all the awaited expressions within the input expression.
3051 #[derive(Default)]
3052 struct AwaitsVisitor {
3053     awaits: Vec<hir::HirId>,
3054 }
3055
3056 impl<'v> Visitor<'v> for AwaitsVisitor {
3057     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3058         if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3059             self.awaits.push(id)
3060         }
3061         hir::intravisit::walk_expr(self, ex)
3062     }
3063 }
3064
3065 pub trait NextTypeParamName {
3066     fn next_type_param_name(&self, name: Option<&str>) -> String;
3067 }
3068
3069 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3070     fn next_type_param_name(&self, name: Option<&str>) -> String {
3071         // This is the list of possible parameter names that we might suggest.
3072         let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3073         let name = name.as_deref();
3074         let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3075         let used_names = self
3076             .iter()
3077             .filter_map(|p| match p.name {
3078                 hir::ParamName::Plain(ident) => Some(ident.name),
3079                 _ => None,
3080             })
3081             .collect::<Vec<_>>();
3082
3083         possible_names
3084             .iter()
3085             .find(|n| !used_names.contains(&Symbol::intern(n)))
3086             .unwrap_or(&"ParamName")
3087             .to_string()
3088     }
3089 }
3090
3091 fn suggest_trait_object_return_type_alternatives(
3092     err: &mut Diagnostic,
3093     ret_ty: Span,
3094     trait_obj: &str,
3095     is_object_safe: bool,
3096 ) {
3097     err.span_suggestion(
3098         ret_ty,
3099         "use some type `T` that is `T: Sized` as the return type if all return paths have the \
3100             same type",
3101         "T",
3102         Applicability::MaybeIncorrect,
3103     );
3104     err.span_suggestion(
3105         ret_ty,
3106         &format!(
3107             "use `impl {}` as the return type if all return paths have the same type but you \
3108                 want to expose only the trait in the signature",
3109             trait_obj,
3110         ),
3111         format!("impl {}", trait_obj),
3112         Applicability::MaybeIncorrect,
3113     );
3114     if is_object_safe {
3115         err.multipart_suggestion(
3116             &format!(
3117                 "use a boxed trait object if all return paths implement trait `{}`",
3118                 trait_obj,
3119             ),
3120             vec![
3121                 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3122                 (ret_ty.shrink_to_hi(), ">".to_string()),
3123             ],
3124             Applicability::MaybeIncorrect,
3125         );
3126     }
3127 }
3128
3129 /// Collect the spans that we see the generic param `param_did`
3130 struct ReplaceImplTraitVisitor<'a> {
3131     ty_spans: &'a mut Vec<Span>,
3132     param_did: DefId,
3133 }
3134
3135 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3136     fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3137         if let hir::TyKind::Path(hir::QPath::Resolved(
3138             None,
3139             hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3140         )) = t.kind
3141         {
3142             if self.param_did == *segment_did {
3143                 // `fn foo(t: impl Trait)`
3144                 //            ^^^^^^^^^^ get this to suggest `T` instead
3145
3146                 // There might be more than one `impl Trait`.
3147                 self.ty_spans.push(t.span);
3148                 return;
3149             }
3150         }
3151
3152         hir::intravisit::walk_ty(self, t);
3153     }
3154 }
3155
3156 // Replace `param` with `replace_ty`
3157 struct ReplaceImplTraitFolder<'tcx> {
3158     tcx: TyCtxt<'tcx>,
3159     param: &'tcx ty::GenericParamDef,
3160     replace_ty: Ty<'tcx>,
3161 }
3162
3163 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3164     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3165         if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3166             if self.param.index == *index {
3167                 return self.replace_ty;
3168             }
3169         }
3170         t.super_fold_with(self)
3171     }
3172
3173     fn tcx(&self) -> TyCtxt<'tcx> {
3174         self.tcx
3175     }
3176 }