]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs
91da690a00056d58fc9fcfec0746d832c01de720
[rust.git] / compiler / rustc_trait_selection / src / traits / error_reporting / suggestions.rs
1 // ignore-tidy-filelength
2
3 use super::{
4     DefIdOrName, FindExprBySpan, Obligation, ObligationCause, ObligationCauseCode,
5     PredicateObligation,
6 };
7
8 use crate::infer::InferCtxt;
9 use crate::traits::{NormalizeExt, ObligationCtxt};
10
11 use hir::def::CtorOf;
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_data_structures::stack::ensure_sufficient_stack;
14 use rustc_errors::{
15     error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
16     ErrorGuaranteed, MultiSpan, Style,
17 };
18 use rustc_hir as hir;
19 use rustc_hir::def::DefKind;
20 use rustc_hir::def_id::DefId;
21 use rustc_hir::intravisit::Visitor;
22 use rustc_hir::lang_items::LangItem;
23 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
24 use rustc_hir::{Expr, HirId};
25 use rustc_infer::infer::error_reporting::TypeErrCtxt;
26 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
27 use rustc_infer::infer::{InferOk, LateBoundRegionConversionTime};
28 use rustc_middle::hir::map;
29 use rustc_middle::ty::error::TypeError::{self, Sorts};
30 use rustc_middle::ty::relate::TypeRelation;
31 use rustc_middle::ty::{
32     self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
33     GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, InternalSubsts,
34     IsSuggestable, ToPredicate, Ty, TyCtxt, TypeAndMut, TypeFoldable, TypeFolder,
35     TypeSuperFoldable, TypeVisitable, TypeckResults,
36 };
37 use rustc_span::def_id::LocalDefId;
38 use rustc_span::symbol::{sym, Ident, Symbol};
39 use rustc_span::{BytePos, DesugaringKind, ExpnKind, MacroKind, Span, DUMMY_SP};
40 use rustc_target::spec::abi;
41 use std::ops::Deref;
42
43 use super::method_chain::CollectAllMismatches;
44 use super::InferCtxtPrivExt;
45 use crate::infer::InferCtxtExt as _;
46 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
47 use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
48
49 #[derive(Debug)]
50 pub enum GeneratorInteriorOrUpvar {
51     // span of interior type
52     Interior(Span, Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>),
53     // span of upvar
54     Upvar(Span),
55 }
56
57 // This type provides a uniform interface to retrieve data on generators, whether it originated from
58 // the local crate being compiled or from a foreign crate.
59 #[derive(Debug)]
60 pub enum GeneratorData<'tcx, 'a> {
61     Local(&'a TypeckResults<'tcx>),
62     Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
63 }
64
65 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
66     // Try to get information about variables captured by the generator that matches a type we are
67     // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
68     // meet an obligation
69     fn try_get_upvar_span<F>(
70         &self,
71         infer_context: &InferCtxt<'tcx>,
72         generator_did: DefId,
73         ty_matches: F,
74     ) -> Option<GeneratorInteriorOrUpvar>
75     where
76         F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
77     {
78         match self {
79             GeneratorData::Local(typeck_results) => {
80                 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
81                     upvars.iter().find_map(|(upvar_id, upvar)| {
82                         let upvar_ty = typeck_results.node_type(*upvar_id);
83                         let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
84                         if ty_matches(ty::Binder::dummy(upvar_ty)) {
85                             Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
86                         } else {
87                             None
88                         }
89                     })
90                 })
91             }
92             GeneratorData::Foreign(_) => None,
93         }
94     }
95
96     // Try to get the span of a type being awaited on that matches the type we are looking with the
97     // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
98     // obligation
99     fn get_from_await_ty<F>(
100         &self,
101         visitor: AwaitsVisitor,
102         hir: map::Map<'tcx>,
103         ty_matches: F,
104     ) -> Option<Span>
105     where
106         F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
107     {
108         match self {
109             GeneratorData::Local(typeck_results) => visitor
110                 .awaits
111                 .into_iter()
112                 .map(|id| hir.expect_expr(id))
113                 .find(|await_expr| {
114                     ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
115                 })
116                 .map(|expr| expr.span),
117             GeneratorData::Foreign(generator_diagnostic_data) => visitor
118                 .awaits
119                 .into_iter()
120                 .map(|id| hir.expect_expr(id))
121                 .find(|await_expr| {
122                     ty_matches(ty::Binder::dummy(
123                         generator_diagnostic_data
124                             .adjustments
125                             .get(&await_expr.hir_id.local_id)
126                             .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
127                             .last()
128                             .map_or_else::<Ty<'tcx>, _, _>(
129                                 || {
130                                     generator_diagnostic_data
131                                         .nodes_types
132                                         .get(&await_expr.hir_id.local_id)
133                                         .cloned()
134                                         .unwrap_or_else(|| {
135                                             bug!(
136                                                 "node_type: no type for node {}",
137                                                 ty::tls::with(|tcx| tcx
138                                                     .hir()
139                                                     .node_to_string(await_expr.hir_id))
140                                             )
141                                         })
142                                 },
143                                 |adj| adj.target,
144                             ),
145                     ))
146                 })
147                 .map(|expr| expr.span),
148         }
149     }
150
151     /// Get the type, expression, span and optional scope span of all types
152     /// that are live across the yield of this generator
153     fn get_generator_interior_types(
154         &self,
155     ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
156         match self {
157             GeneratorData::Local(typeck_result) => {
158                 typeck_result.generator_interior_types.as_deref()
159             }
160             GeneratorData::Foreign(generator_diagnostic_data) => {
161                 generator_diagnostic_data.generator_interior_types.as_deref()
162             }
163         }
164     }
165
166     // Used to get the source of the data, note we don't have as much information for generators
167     // originated from foreign crates
168     fn is_foreign(&self) -> bool {
169         match self {
170             GeneratorData::Local(_) => false,
171             GeneratorData::Foreign(_) => true,
172         }
173     }
174 }
175
176 // This trait is public to expose the diagnostics methods to clippy.
177 pub trait TypeErrCtxtExt<'tcx> {
178     fn suggest_restricting_param_bound(
179         &self,
180         err: &mut Diagnostic,
181         trait_pred: ty::PolyTraitPredicate<'tcx>,
182         associated_item: Option<(&'static str, Ty<'tcx>)>,
183         body_id: LocalDefId,
184     );
185
186     fn suggest_dereferences(
187         &self,
188         obligation: &PredicateObligation<'tcx>,
189         err: &mut Diagnostic,
190         trait_pred: ty::PolyTraitPredicate<'tcx>,
191     ) -> bool;
192
193     fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
194
195     fn suggest_fn_call(
196         &self,
197         obligation: &PredicateObligation<'tcx>,
198         err: &mut Diagnostic,
199         trait_pred: ty::PolyTraitPredicate<'tcx>,
200     ) -> bool;
201
202     fn check_for_binding_assigned_block_without_tail_expression(
203         &self,
204         obligation: &PredicateObligation<'tcx>,
205         err: &mut Diagnostic,
206         trait_pred: ty::PolyTraitPredicate<'tcx>,
207     );
208
209     fn suggest_add_clone_to_arg(
210         &self,
211         obligation: &PredicateObligation<'tcx>,
212         err: &mut Diagnostic,
213         trait_pred: ty::PolyTraitPredicate<'tcx>,
214     ) -> bool;
215
216     fn extract_callable_info(
217         &self,
218         hir_id: HirId,
219         param_env: ty::ParamEnv<'tcx>,
220         found: Ty<'tcx>,
221     ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)>;
222
223     fn suggest_add_reference_to_arg(
224         &self,
225         obligation: &PredicateObligation<'tcx>,
226         err: &mut Diagnostic,
227         trait_pred: ty::PolyTraitPredicate<'tcx>,
228         has_custom_message: bool,
229     ) -> bool;
230
231     fn suggest_borrowing_for_object_cast(
232         &self,
233         err: &mut Diagnostic,
234         obligation: &PredicateObligation<'tcx>,
235         self_ty: Ty<'tcx>,
236         object_ty: Ty<'tcx>,
237     );
238
239     fn suggest_remove_reference(
240         &self,
241         obligation: &PredicateObligation<'tcx>,
242         err: &mut Diagnostic,
243         trait_pred: ty::PolyTraitPredicate<'tcx>,
244     ) -> bool;
245
246     fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
247
248     fn suggest_change_mut(
249         &self,
250         obligation: &PredicateObligation<'tcx>,
251         err: &mut Diagnostic,
252         trait_pred: ty::PolyTraitPredicate<'tcx>,
253     );
254
255     fn suggest_semicolon_removal(
256         &self,
257         obligation: &PredicateObligation<'tcx>,
258         err: &mut Diagnostic,
259         span: Span,
260         trait_pred: ty::PolyTraitPredicate<'tcx>,
261     ) -> bool;
262
263     fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
264
265     fn suggest_impl_trait(
266         &self,
267         err: &mut Diagnostic,
268         span: Span,
269         obligation: &PredicateObligation<'tcx>,
270         trait_pred: ty::PolyTraitPredicate<'tcx>,
271     ) -> bool;
272
273     fn point_at_returns_when_relevant(
274         &self,
275         err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
276         obligation: &PredicateObligation<'tcx>,
277     );
278
279     fn report_closure_arg_mismatch(
280         &self,
281         span: Span,
282         found_span: Option<Span>,
283         found: ty::PolyTraitRef<'tcx>,
284         expected: ty::PolyTraitRef<'tcx>,
285         cause: &ObligationCauseCode<'tcx>,
286         found_node: Option<Node<'_>>,
287         param_env: ty::ParamEnv<'tcx>,
288     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
289
290     fn note_conflicting_closure_bounds(
291         &self,
292         cause: &ObligationCauseCode<'tcx>,
293         err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
294     );
295
296     fn suggest_fully_qualified_path(
297         &self,
298         err: &mut Diagnostic,
299         item_def_id: DefId,
300         span: Span,
301         trait_ref: DefId,
302     );
303
304     fn maybe_note_obligation_cause_for_async_await(
305         &self,
306         err: &mut Diagnostic,
307         obligation: &PredicateObligation<'tcx>,
308     ) -> bool;
309
310     fn note_obligation_cause_for_async_await(
311         &self,
312         err: &mut Diagnostic,
313         interior_or_upvar_span: GeneratorInteriorOrUpvar,
314         is_async: bool,
315         outer_generator: Option<DefId>,
316         trait_pred: ty::TraitPredicate<'tcx>,
317         target_ty: Ty<'tcx>,
318         typeck_results: Option<&ty::TypeckResults<'tcx>>,
319         obligation: &PredicateObligation<'tcx>,
320         next_code: Option<&ObligationCauseCode<'tcx>>,
321     );
322
323     fn note_obligation_cause_code<T>(
324         &self,
325         err: &mut Diagnostic,
326         predicate: T,
327         param_env: ty::ParamEnv<'tcx>,
328         cause_code: &ObligationCauseCode<'tcx>,
329         obligated_types: &mut Vec<Ty<'tcx>>,
330         seen_requirements: &mut FxHashSet<DefId>,
331     ) where
332         T: ToPredicate<'tcx>;
333
334     /// Suggest to await before try: future? => future.await?
335     fn suggest_await_before_try(
336         &self,
337         err: &mut Diagnostic,
338         obligation: &PredicateObligation<'tcx>,
339         trait_pred: ty::PolyTraitPredicate<'tcx>,
340         span: Span,
341     );
342
343     fn suggest_floating_point_literal(
344         &self,
345         obligation: &PredicateObligation<'tcx>,
346         err: &mut Diagnostic,
347         trait_ref: &ty::PolyTraitRef<'tcx>,
348     );
349
350     fn suggest_derive(
351         &self,
352         obligation: &PredicateObligation<'tcx>,
353         err: &mut Diagnostic,
354         trait_pred: ty::PolyTraitPredicate<'tcx>,
355     );
356
357     fn suggest_dereferencing_index(
358         &self,
359         obligation: &PredicateObligation<'tcx>,
360         err: &mut Diagnostic,
361         trait_pred: ty::PolyTraitPredicate<'tcx>,
362     );
363     fn note_function_argument_obligation(
364         &self,
365         arg_hir_id: HirId,
366         err: &mut Diagnostic,
367         parent_code: &ObligationCauseCode<'tcx>,
368         param_env: ty::ParamEnv<'tcx>,
369         predicate: ty::Predicate<'tcx>,
370         call_hir_id: HirId,
371     );
372     fn point_at_chain(
373         &self,
374         expr: &hir::Expr<'_>,
375         typeck_results: &TypeckResults<'tcx>,
376         type_diffs: Vec<TypeError<'tcx>>,
377         param_env: ty::ParamEnv<'tcx>,
378         err: &mut Diagnostic,
379     );
380     fn probe_assoc_types_at_expr(
381         &self,
382         type_diffs: &[TypeError<'tcx>],
383         span: Span,
384         prev_ty: Ty<'tcx>,
385         body_id: hir::HirId,
386         param_env: ty::ParamEnv<'tcx>,
387     ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>>;
388 }
389
390 fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
391     (
392         generics.tail_span_for_predicate_suggestion(),
393         format!("{} {}", generics.add_where_or_trailing_comma(), pred),
394     )
395 }
396
397 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
398 /// it can also be an `impl Trait` param that needs to be decomposed to a type
399 /// param for cleaner code.
400 fn suggest_restriction<'tcx>(
401     tcx: TyCtxt<'tcx>,
402     item_id: LocalDefId,
403     hir_generics: &hir::Generics<'tcx>,
404     msg: &str,
405     err: &mut Diagnostic,
406     fn_sig: Option<&hir::FnSig<'_>>,
407     projection: Option<&ty::AliasTy<'_>>,
408     trait_pred: ty::PolyTraitPredicate<'tcx>,
409     // When we are dealing with a trait, `super_traits` will be `Some`:
410     // Given `trait T: A + B + C {}`
411     //              -  ^^^^^^^^^ GenericBounds
412     //              |
413     //              &Ident
414     super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
415 ) {
416     if hir_generics.where_clause_span.from_expansion()
417         || hir_generics.where_clause_span.desugaring_kind().is_some()
418     {
419         return;
420     }
421     let generics = tcx.generics_of(item_id);
422     // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
423     if let Some((param, bound_str, fn_sig)) =
424         fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
425             // Shenanigans to get the `Trait` from the `impl Trait`.
426             ty::Param(param) => {
427                 let param_def = generics.type_param(param, tcx);
428                 if param_def.kind.is_synthetic() {
429                     let bound_str =
430                         param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
431                     return Some((param_def, bound_str, sig));
432                 }
433                 None
434             }
435             _ => None,
436         })
437     {
438         let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
439         let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
440             tcx,
441             param,
442             replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
443                 .to_ty(tcx),
444         });
445         if !trait_pred.is_suggestable(tcx, false) {
446             return;
447         }
448         // We know we have an `impl Trait` that doesn't satisfy a required projection.
449
450         // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
451         // types. There should be at least one, but there might be *more* than one. In that
452         // case we could just ignore it and try to identify which one needs the restriction,
453         // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
454         // where `T: Trait`.
455         let mut ty_spans = vec![];
456         for input in fn_sig.decl.inputs {
457             ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
458                 .visit_ty(input);
459         }
460         // The type param `T: Trait` we will suggest to introduce.
461         let type_param = format!("{}: {}", type_param_name, bound_str);
462
463         let mut sugg = vec![
464             if let Some(span) = hir_generics.span_for_param_suggestion() {
465                 (span, format!(", {}", type_param))
466             } else {
467                 (hir_generics.span, format!("<{}>", type_param))
468             },
469             // `fn foo(t: impl Trait)`
470             //                       ^ suggest `where <T as Trait>::A: Bound`
471             predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
472         ];
473         sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
474
475         // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
476         // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
477         // `fn foo(t: impl Trait<A: Bound>)` instead.
478         err.multipart_suggestion(
479             "introduce a type parameter with a trait bound instead of using `impl Trait`",
480             sugg,
481             Applicability::MaybeIncorrect,
482         );
483     } else {
484         if !trait_pred.is_suggestable(tcx, false) {
485             return;
486         }
487         // Trivial case: `T` needs an extra bound: `T: Bound`.
488         let (sp, suggestion) = match (
489             hir_generics
490                 .params
491                 .iter()
492                 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
493             super_traits,
494         ) {
495             (_, None) => predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
496             (None, Some((ident, []))) => (
497                 ident.span.shrink_to_hi(),
498                 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
499             ),
500             (_, Some((_, [.., bounds]))) => (
501                 bounds.span().shrink_to_hi(),
502                 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
503             ),
504             (Some(_), Some((_, []))) => (
505                 hir_generics.span.shrink_to_hi(),
506                 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
507             ),
508         };
509
510         err.span_suggestion_verbose(
511             sp,
512             &format!("consider further restricting {}", msg),
513             suggestion,
514             Applicability::MachineApplicable,
515         );
516     }
517 }
518
519 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
520     fn suggest_restricting_param_bound(
521         &self,
522         mut err: &mut Diagnostic,
523         trait_pred: ty::PolyTraitPredicate<'tcx>,
524         associated_ty: Option<(&'static str, Ty<'tcx>)>,
525         mut body_id: LocalDefId,
526     ) {
527         let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
528
529         let self_ty = trait_pred.skip_binder().self_ty();
530         let (param_ty, projection) = match self_ty.kind() {
531             ty::Param(_) => (true, None),
532             ty::Alias(ty::Projection, projection) => (false, Some(projection)),
533             _ => (false, None),
534         };
535
536         // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
537         //        don't suggest `T: Sized + ?Sized`.
538         while let Some(node) = self.tcx.hir().find_by_def_id(body_id) {
539             match node {
540                 hir::Node::Item(hir::Item {
541                     ident,
542                     kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
543                     ..
544                 }) if self_ty == self.tcx.types.self_param => {
545                     assert!(param_ty);
546                     // Restricting `Self` for a single method.
547                     suggest_restriction(
548                         self.tcx,
549                         body_id,
550                         &generics,
551                         "`Self`",
552                         err,
553                         None,
554                         projection,
555                         trait_pred,
556                         Some((ident, bounds)),
557                     );
558                     return;
559                 }
560
561                 hir::Node::TraitItem(hir::TraitItem {
562                     generics,
563                     kind: hir::TraitItemKind::Fn(..),
564                     ..
565                 }) if self_ty == self.tcx.types.self_param => {
566                     assert!(param_ty);
567                     // Restricting `Self` for a single method.
568                     suggest_restriction(
569                         self.tcx, body_id, &generics, "`Self`", err, None, projection, trait_pred,
570                         None,
571                     );
572                     return;
573                 }
574
575                 hir::Node::TraitItem(hir::TraitItem {
576                     generics,
577                     kind: hir::TraitItemKind::Fn(fn_sig, ..),
578                     ..
579                 })
580                 | hir::Node::ImplItem(hir::ImplItem {
581                     generics,
582                     kind: hir::ImplItemKind::Fn(fn_sig, ..),
583                     ..
584                 })
585                 | hir::Node::Item(hir::Item {
586                     kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
587                 }) if projection.is_some() => {
588                     // Missing restriction on associated type of type parameter (unmet projection).
589                     suggest_restriction(
590                         self.tcx,
591                         body_id,
592                         &generics,
593                         "the associated type",
594                         err,
595                         Some(fn_sig),
596                         projection,
597                         trait_pred,
598                         None,
599                     );
600                     return;
601                 }
602                 hir::Node::Item(hir::Item {
603                     kind:
604                         hir::ItemKind::Trait(_, _, generics, ..)
605                         | hir::ItemKind::Impl(hir::Impl { generics, .. }),
606                     ..
607                 }) if projection.is_some() => {
608                     // Missing restriction on associated type of type parameter (unmet projection).
609                     suggest_restriction(
610                         self.tcx,
611                         body_id,
612                         &generics,
613                         "the associated type",
614                         err,
615                         None,
616                         projection,
617                         trait_pred,
618                         None,
619                     );
620                     return;
621                 }
622
623                 hir::Node::Item(hir::Item {
624                     kind:
625                         hir::ItemKind::Struct(_, generics)
626                         | hir::ItemKind::Enum(_, generics)
627                         | hir::ItemKind::Union(_, generics)
628                         | hir::ItemKind::Trait(_, _, generics, ..)
629                         | hir::ItemKind::Impl(hir::Impl { generics, .. })
630                         | hir::ItemKind::Fn(_, generics, _)
631                         | hir::ItemKind::TyAlias(_, generics)
632                         | hir::ItemKind::TraitAlias(generics, _)
633                         | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
634                     ..
635                 })
636                 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
637                 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
638                     if param_ty =>
639                 {
640                     // We skip the 0'th subst (self) because we do not want
641                     // to consider the predicate as not suggestible if the
642                     // self type is an arg position `impl Trait` -- instead,
643                     // we handle that by adding ` + Bound` below.
644                     // FIXME(compiler-errors): It would be nice to do the same
645                     // this that we do in `suggest_restriction` and pull the
646                     // `impl Trait` into a new generic if it shows up somewhere
647                     // else in the predicate.
648                     if !trait_pred.skip_binder().trait_ref.substs[1..]
649                         .iter()
650                         .all(|g| g.is_suggestable(self.tcx, false))
651                     {
652                         return;
653                     }
654                     // Missing generic type parameter bound.
655                     let param_name = self_ty.to_string();
656                     let mut constraint = with_no_trimmed_paths!(
657                         trait_pred.print_modifiers_and_trait_path().to_string()
658                     );
659
660                     if let Some((name, term)) = associated_ty {
661                         // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
662                         // That should be extracted into a helper function.
663                         if constraint.ends_with('>') {
664                             constraint = format!(
665                                 "{}, {} = {}>",
666                                 &constraint[..constraint.len() - 1],
667                                 name,
668                                 term
669                             );
670                         } else {
671                             constraint.push_str(&format!("<{} = {}>", name, term));
672                         }
673                     }
674
675                     if suggest_constraining_type_param(
676                         self.tcx,
677                         generics,
678                         &mut err,
679                         &param_name,
680                         &constraint,
681                         Some(trait_pred.def_id()),
682                         None,
683                     ) {
684                         return;
685                     }
686                 }
687
688                 hir::Node::Item(hir::Item {
689                     kind:
690                         hir::ItemKind::Struct(_, generics)
691                         | hir::ItemKind::Enum(_, generics)
692                         | hir::ItemKind::Union(_, generics)
693                         | hir::ItemKind::Trait(_, _, generics, ..)
694                         | hir::ItemKind::Impl(hir::Impl { generics, .. })
695                         | hir::ItemKind::Fn(_, generics, _)
696                         | hir::ItemKind::TyAlias(_, generics)
697                         | hir::ItemKind::TraitAlias(generics, _)
698                         | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
699                     ..
700                 }) if !param_ty => {
701                     // Missing generic type parameter bound.
702                     if suggest_arbitrary_trait_bound(
703                         self.tcx,
704                         generics,
705                         &mut err,
706                         trait_pred,
707                         associated_ty,
708                     ) {
709                         return;
710                     }
711                 }
712                 hir::Node::Crate(..) => return,
713
714                 _ => {}
715             }
716             body_id = self.tcx.local_parent(body_id);
717         }
718     }
719
720     /// When after several dereferencing, the reference satisfies the trait
721     /// binding. This function provides dereference suggestion for this
722     /// specific situation.
723     fn suggest_dereferences(
724         &self,
725         obligation: &PredicateObligation<'tcx>,
726         err: &mut Diagnostic,
727         trait_pred: ty::PolyTraitPredicate<'tcx>,
728     ) -> bool {
729         // It only make sense when suggesting dereferences for arguments
730         let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, call_hir_id, .. } = obligation.cause.code()
731             else { return false; };
732         let Some(typeck_results) = &self.typeck_results
733             else { return false; };
734         let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
735             else { return false; };
736         let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
737             else { return false; };
738
739         let span = obligation.cause.span;
740         let mut real_trait_pred = trait_pred;
741         let mut code = obligation.cause.code();
742         while let Some((parent_code, parent_trait_pred)) = code.parent() {
743             code = parent_code;
744             if let Some(parent_trait_pred) = parent_trait_pred {
745                 real_trait_pred = parent_trait_pred;
746             }
747
748             let real_ty = real_trait_pred.self_ty();
749             // We `erase_late_bound_regions` here because `make_subregion` does not handle
750             // `ReLateBound`, and we don't particularly care about the regions.
751             if self
752                 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
753                 .is_err()
754             {
755                 continue;
756             }
757
758             if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
759                 let autoderef = (self.autoderef_steps)(base_ty);
760                 if let Some(steps) =
761                     autoderef.into_iter().enumerate().find_map(|(steps, (ty, obligations))| {
762                         // Re-add the `&`
763                         let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
764
765                         // Remapping bound vars here
766                         let real_trait_pred_and_ty =
767                             real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
768                         let obligation = self.mk_trait_obligation_with_new_self_ty(
769                             obligation.param_env,
770                             real_trait_pred_and_ty,
771                         );
772                         if obligations
773                             .iter()
774                             .chain([&obligation])
775                             .all(|obligation| self.predicate_may_hold(obligation))
776                         {
777                             Some(steps)
778                         } else {
779                             None
780                         }
781                     })
782                 {
783                     if steps > 0 {
784                         // Don't care about `&mut` because `DerefMut` is used less
785                         // often and user will not expect autoderef happens.
786                         if let Some(hir::Node::Expr(hir::Expr {
787                             kind:
788                                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
789                             ..
790                         })) = self.tcx.hir().find(*arg_hir_id)
791                         {
792                             let derefs = "*".repeat(steps);
793                             err.span_suggestion_verbose(
794                                 expr.span.shrink_to_lo(),
795                                 "consider dereferencing here",
796                                 derefs,
797                                 Applicability::MachineApplicable,
798                             );
799                             return true;
800                         }
801                     }
802                 } else if real_trait_pred != trait_pred {
803                     // This branch addresses #87437.
804
805                     // Remapping bound vars here
806                     let real_trait_pred_and_base_ty =
807                         real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
808                     let obligation = self.mk_trait_obligation_with_new_self_ty(
809                         obligation.param_env,
810                         real_trait_pred_and_base_ty,
811                     );
812                     if self.predicate_may_hold(&obligation) {
813                         let call_node = self.tcx.hir().get(*call_hir_id);
814                         let msg = "consider dereferencing here";
815                         let is_receiver = matches!(
816                             call_node,
817                             Node::Expr(hir::Expr {
818                                 kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
819                                 ..
820                             })
821                             if receiver_expr.hir_id == *arg_hir_id
822                         );
823                         if is_receiver {
824                             err.multipart_suggestion_verbose(
825                                 msg,
826                                 vec![
827                                     (span.shrink_to_lo(), "(*".to_string()),
828                                     (span.shrink_to_hi(), ")".to_string()),
829                                 ],
830                                 Applicability::MachineApplicable,
831                             )
832                         } else {
833                             err.span_suggestion_verbose(
834                                 span.shrink_to_lo(),
835                                 msg,
836                                 '*',
837                                 Applicability::MachineApplicable,
838                             )
839                         };
840                         return true;
841                     }
842                 }
843             }
844         }
845         false
846     }
847
848     /// Given a closure's `DefId`, return the given name of the closure.
849     ///
850     /// This doesn't account for reassignments, but it's only used for suggestions.
851     fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
852         let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
853             // Get the local name of this closure. This can be inaccurate because
854             // of the possibility of reassignment, but this should be good enough.
855             match &kind {
856                 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
857                     Some(ident.name)
858                 }
859                 _ => {
860                     err.note(msg);
861                     None
862                 }
863             }
864         };
865
866         let hir = self.tcx.hir();
867         let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
868         match hir.find_parent(hir_id) {
869             Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
870                 get_name(err, &local.pat.kind)
871             }
872             // Different to previous arm because one is `&hir::Local` and the other
873             // is `P<hir::Local>`.
874             Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
875             _ => None,
876         }
877     }
878
879     /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
880     /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
881     /// it: `bar(foo)` â†’ `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
882     fn suggest_fn_call(
883         &self,
884         obligation: &PredicateObligation<'tcx>,
885         err: &mut Diagnostic,
886         trait_pred: ty::PolyTraitPredicate<'tcx>,
887     ) -> bool {
888         // It doesn't make sense to make this suggestion outside of typeck...
889         // (also autoderef will ICE...)
890         if self.typeck_results.is_none() {
891             return false;
892         }
893
894         if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = obligation.predicate.kind().skip_binder()
895             && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
896         {
897             // Don't suggest calling to turn an unsized type into a sized type
898             return false;
899         }
900
901         let self_ty = self.replace_bound_vars_with_fresh_vars(
902             DUMMY_SP,
903             LateBoundRegionConversionTime::FnCall,
904             trait_pred.self_ty(),
905         );
906
907         let body_hir_id = self.tcx.hir().local_def_id_to_hir_id(obligation.cause.body_id);
908         let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(
909             body_hir_id,
910             obligation.param_env,
911             self_ty,
912         ) else { return false; };
913
914         // Remapping bound vars here
915         let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
916
917         let new_obligation =
918             self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
919         if !self.predicate_must_hold_modulo_regions(&new_obligation) {
920             return false;
921         }
922
923         // Get the name of the callable and the arguments to be used in the suggestion.
924         let hir = self.tcx.hir();
925
926         let msg = match def_id_or_name {
927             DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
928                 DefKind::Ctor(CtorOf::Struct, _) => {
929                     "use parentheses to construct this tuple struct".to_string()
930                 }
931                 DefKind::Ctor(CtorOf::Variant, _) => {
932                     "use parentheses to construct this tuple variant".to_string()
933                 }
934                 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
935             },
936             DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
937         };
938
939         let args = inputs
940             .into_iter()
941             .map(|ty| {
942                 if ty.is_suggestable(self.tcx, false) {
943                     format!("/* {ty} */")
944                 } else {
945                     "/* value */".to_string()
946                 }
947             })
948             .collect::<Vec<_>>()
949             .join(", ");
950
951         if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
952             && obligation.cause.span.can_be_used_for_suggestions()
953         {
954             // When the obligation error has been ensured to have been caused by
955             // an argument, the `obligation.cause.span` points at the expression
956             // of the argument, so we can provide a suggestion. Otherwise, we give
957             // a more general note.
958             err.span_suggestion_verbose(
959                 obligation.cause.span.shrink_to_hi(),
960                 &msg,
961                 format!("({args})"),
962                 Applicability::HasPlaceholders,
963             );
964         } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
965             let name = match hir.get_if_local(def_id) {
966                 Some(hir::Node::Expr(hir::Expr {
967                     kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
968                     ..
969                 })) => {
970                     err.span_label(*fn_decl_span, "consider calling this closure");
971                     let Some(name) = self.get_closure_name(def_id, err, &msg) else {
972                         return false;
973                     };
974                     name.to_string()
975                 }
976                 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
977                     err.span_label(ident.span, "consider calling this function");
978                     ident.to_string()
979                 }
980                 Some(hir::Node::Ctor(..)) => {
981                     let name = self.tcx.def_path_str(def_id);
982                     err.span_label(
983                         self.tcx.def_span(def_id),
984                         format!("consider calling the constructor for `{}`", name),
985                     );
986                     name
987                 }
988                 _ => return false,
989             };
990             err.help(&format!("{msg}: `{name}({args})`"));
991         }
992         true
993     }
994
995     fn check_for_binding_assigned_block_without_tail_expression(
996         &self,
997         obligation: &PredicateObligation<'tcx>,
998         err: &mut Diagnostic,
999         trait_pred: ty::PolyTraitPredicate<'tcx>,
1000     ) {
1001         let mut span = obligation.cause.span;
1002         while span.from_expansion() {
1003             // Remove all the desugaring and macro contexts.
1004             span.remove_mark();
1005         }
1006         let mut expr_finder = FindExprBySpan::new(span);
1007         let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else { return; };
1008         let body = self.tcx.hir().body(body_id);
1009         expr_finder.visit_expr(body.value);
1010         let Some(expr) = expr_finder.result else { return; };
1011         let Some(typeck) = &self.typeck_results else { return; };
1012         let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else { return; };
1013         if !ty.is_unit() {
1014             return;
1015         };
1016         let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { return; };
1017         let hir::def::Res::Local(hir_id) = path.res else { return; };
1018         let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(hir_id) else {
1019             return;
1020         };
1021         let Some(hir::Node::Local(hir::Local {
1022             ty: None,
1023             init: Some(init),
1024             ..
1025         })) = self.tcx.hir().find_parent(pat.hir_id) else { return; };
1026         let hir::ExprKind::Block(block, None) = init.kind else { return; };
1027         if block.expr.is_some() {
1028             return;
1029         }
1030         let [.., stmt] = block.stmts else {
1031             err.span_label(block.span, "this empty block is missing a tail expression");
1032             return;
1033         };
1034         let hir::StmtKind::Semi(tail_expr) = stmt.kind else { return; };
1035         let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
1036             err.span_label(block.span, "this block is missing a tail expression");
1037             return;
1038         };
1039         let ty = self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(ty));
1040         let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
1041
1042         let new_obligation =
1043             self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1044         if self.predicate_must_hold_modulo_regions(&new_obligation) {
1045             err.span_suggestion_short(
1046                 stmt.span.with_lo(tail_expr.span.hi()),
1047                 "remove this semicolon",
1048                 "",
1049                 Applicability::MachineApplicable,
1050             );
1051         } else {
1052             err.span_label(block.span, "this block is missing a tail expression");
1053         }
1054     }
1055
1056     fn suggest_add_clone_to_arg(
1057         &self,
1058         obligation: &PredicateObligation<'tcx>,
1059         err: &mut Diagnostic,
1060         trait_pred: ty::PolyTraitPredicate<'tcx>,
1061     ) -> bool {
1062         let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
1063         let ty = self.tcx.erase_late_bound_regions(self_ty);
1064         let Some(generics) = self.tcx.hir().get_generics(obligation.cause.body_id) else { return false };
1065         let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
1066         let ty::Param(param) = inner_ty.kind() else { return false };
1067         let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code() else { return false };
1068         let arg_node = self.tcx.hir().get(*arg_hir_id);
1069         let Node::Expr(Expr { kind: hir::ExprKind::Path(_), ..}) = arg_node else { return false };
1070
1071         let clone_trait = self.tcx.require_lang_item(LangItem::Clone, None);
1072         let has_clone = |ty| {
1073             self.type_implements_trait(clone_trait, [ty], obligation.param_env)
1074                 .must_apply_modulo_regions()
1075         };
1076
1077         let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1078             obligation.param_env,
1079             trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)),
1080         );
1081
1082         if self.predicate_may_hold(&new_obligation) && has_clone(ty) {
1083             if !has_clone(param.to_ty(self.tcx)) {
1084                 suggest_constraining_type_param(
1085                     self.tcx,
1086                     generics,
1087                     err,
1088                     param.name.as_str(),
1089                     "Clone",
1090                     Some(clone_trait),
1091                     None,
1092                 );
1093             }
1094             err.span_suggestion_verbose(
1095                 obligation.cause.span.shrink_to_hi(),
1096                 "consider using clone here",
1097                 ".clone()".to_string(),
1098                 Applicability::MaybeIncorrect,
1099             );
1100             return true;
1101         }
1102         false
1103     }
1104
1105     /// Extracts information about a callable type for diagnostics. This is a
1106     /// heuristic -- it doesn't necessarily mean that a type is always callable,
1107     /// because the callable type must also be well-formed to be called.
1108     // FIXME(vincenzopalazzo): move the HirId to a LocalDefId
1109     fn extract_callable_info(
1110         &self,
1111         hir_id: HirId,
1112         param_env: ty::ParamEnv<'tcx>,
1113         found: Ty<'tcx>,
1114     ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
1115         // Autoderef is useful here because sometimes we box callables, etc.
1116         let Some((def_id_or_name, output, inputs)) = (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| {
1117             match *found.kind() {
1118                 ty::FnPtr(fn_sig) =>
1119                     Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs())),
1120                 ty::FnDef(def_id, _) => {
1121                     let fn_sig = found.fn_sig(self.tcx);
1122                     Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
1123                 }
1124                 ty::Closure(def_id, substs) => {
1125                     let fn_sig = substs.as_closure().sig();
1126                     Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs().map_bound(|inputs| &inputs[1..])))
1127                 }
1128                 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
1129                     self.tcx.item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
1130                         if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
1131                         && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
1132                         // args tuple will always be substs[1]
1133                         && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
1134                         {
1135                             Some((
1136                                 DefIdOrName::DefId(def_id),
1137                                 pred.kind().rebind(proj.term.ty().unwrap()),
1138                                 pred.kind().rebind(args.as_slice()),
1139                             ))
1140                         } else {
1141                             None
1142                         }
1143                     })
1144                 }
1145                 ty::Dynamic(data, _, ty::Dyn) => {
1146                     data.iter().find_map(|pred| {
1147                         if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
1148                         && Some(proj.def_id) == self.tcx.lang_items().fn_once_output()
1149                         // for existential projection, substs are shifted over by 1
1150                         && let ty::Tuple(args) = proj.substs.type_at(0).kind()
1151                         {
1152                             Some((
1153                                 DefIdOrName::Name("trait object"),
1154                                 pred.rebind(proj.term.ty().unwrap()),
1155                                 pred.rebind(args.as_slice()),
1156                             ))
1157                         } else {
1158                             None
1159                         }
1160                     })
1161                 }
1162                 ty::Param(param) => {
1163                     let generics = self.tcx.generics_of(hir_id.owner.to_def_id());
1164                     let name = if generics.count() > param.index as usize
1165                         && let def = generics.param_at(param.index as usize, self.tcx)
1166                         && matches!(def.kind, ty::GenericParamDefKind::Type { .. })
1167                         && def.name == param.name
1168                     {
1169                         DefIdOrName::DefId(def.def_id)
1170                     } else {
1171                         DefIdOrName::Name("type parameter")
1172                     };
1173                     param_env.caller_bounds().iter().find_map(|pred| {
1174                         if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
1175                         && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
1176                         && proj.projection_ty.self_ty() == found
1177                         // args tuple will always be substs[1]
1178                         && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
1179                         {
1180                             Some((
1181                                 name,
1182                                 pred.kind().rebind(proj.term.ty().unwrap()),
1183                                 pred.kind().rebind(args.as_slice()),
1184                             ))
1185                         } else {
1186                             None
1187                         }
1188                     })
1189                 }
1190                 _ => None,
1191             }
1192         }) else { return None; };
1193
1194         let output = self.replace_bound_vars_with_fresh_vars(
1195             DUMMY_SP,
1196             LateBoundRegionConversionTime::FnCall,
1197             output,
1198         );
1199         let inputs = inputs
1200             .skip_binder()
1201             .iter()
1202             .map(|ty| {
1203                 self.replace_bound_vars_with_fresh_vars(
1204                     DUMMY_SP,
1205                     LateBoundRegionConversionTime::FnCall,
1206                     inputs.rebind(*ty),
1207                 )
1208             })
1209             .collect();
1210
1211         // We don't want to register any extra obligations, which should be
1212         // implied by wf, but also because that would possibly result in
1213         // erroneous errors later on.
1214         let InferOk { value: output, obligations: _ } =
1215             self.at(&ObligationCause::dummy(), param_env).normalize(output);
1216
1217         if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
1218     }
1219
1220     fn suggest_add_reference_to_arg(
1221         &self,
1222         obligation: &PredicateObligation<'tcx>,
1223         err: &mut Diagnostic,
1224         poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1225         has_custom_message: bool,
1226     ) -> bool {
1227         let span = obligation.cause.span;
1228
1229         let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
1230             obligation.cause.code()
1231         {
1232             &parent_code
1233         } else if let ObligationCauseCode::ItemObligation(_)
1234         | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1235         {
1236             obligation.cause.code()
1237         } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1238             span.ctxt().outer_expn_data().kind
1239         {
1240             obligation.cause.code()
1241         } else {
1242             return false;
1243         };
1244
1245         // List of traits for which it would be nonsensical to suggest borrowing.
1246         // For instance, immutable references are always Copy, so suggesting to
1247         // borrow would always succeed, but it's probably not what the user wanted.
1248         let mut never_suggest_borrow: Vec<_> =
1249             [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1250                 .iter()
1251                 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1252                 .collect();
1253
1254         if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1255             never_suggest_borrow.push(def_id);
1256         }
1257
1258         let param_env = obligation.param_env;
1259
1260         // Try to apply the original trait binding obligation by borrowing.
1261         let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1262                                  blacklist: &[DefId]|
1263          -> bool {
1264             if blacklist.contains(&old_pred.def_id()) {
1265                 return false;
1266             }
1267             // We map bounds to `&T` and `&mut T`
1268             let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1269                 (
1270                     trait_pred,
1271                     self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1272                 )
1273             });
1274             let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1275                 (
1276                     trait_pred,
1277                     self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1278                 )
1279             });
1280
1281             let mk_result = |trait_pred_and_new_ty| {
1282                 let obligation =
1283                     self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1284                 self.predicate_must_hold_modulo_regions(&obligation)
1285             };
1286             let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1287             let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1288
1289             let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1290                 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1291                     && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1292                 {
1293                     (
1294                         mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1295                         mutability.is_mut(),
1296                     )
1297                 } else {
1298                     (false, false)
1299                 };
1300
1301             if imm_ref_self_ty_satisfies_pred
1302                 || mut_ref_self_ty_satisfies_pred
1303                 || ref_inner_ty_satisfies_pred
1304             {
1305                 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1306                     // We don't want a borrowing suggestion on the fields in structs,
1307                     // ```
1308                     // struct Foo {
1309                     //  the_foos: Vec<Foo>
1310                     // }
1311                     // ```
1312                     if !matches!(
1313                         span.ctxt().outer_expn_data().kind,
1314                         ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1315                     ) {
1316                         return false;
1317                     }
1318                     if snippet.starts_with('&') {
1319                         // This is already a literal borrow and the obligation is failing
1320                         // somewhere else in the obligation chain. Do not suggest non-sense.
1321                         return false;
1322                     }
1323                     // We have a very specific type of error, where just borrowing this argument
1324                     // might solve the problem. In cases like this, the important part is the
1325                     // original type obligation, not the last one that failed, which is arbitrary.
1326                     // Because of this, we modify the error to refer to the original obligation and
1327                     // return early in the caller.
1328
1329                     let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1330                     if has_custom_message {
1331                         err.note(&msg);
1332                     } else {
1333                         err.message =
1334                             vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1335                     }
1336                     err.span_label(
1337                         span,
1338                         format!(
1339                             "the trait `{}` is not implemented for `{}`",
1340                             old_pred.print_modifiers_and_trait_path(),
1341                             old_pred.self_ty().skip_binder(),
1342                         ),
1343                     );
1344
1345                     if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1346                         err.span_suggestions(
1347                             span.shrink_to_lo(),
1348                             "consider borrowing here",
1349                             ["&".to_string(), "&mut ".to_string()],
1350                             Applicability::MaybeIncorrect,
1351                         );
1352                     } else {
1353                         let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1354                         err.span_suggestion_verbose(
1355                             span.shrink_to_lo(),
1356                             &format!(
1357                                 "consider{} borrowing here",
1358                                 if is_mut { " mutably" } else { "" }
1359                             ),
1360                             format!("&{}", if is_mut { "mut " } else { "" }),
1361                             Applicability::MaybeIncorrect,
1362                         );
1363                     }
1364                     return true;
1365                 }
1366             }
1367             return false;
1368         };
1369
1370         if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1371             try_borrowing(cause.derived.parent_trait_pred, &[])
1372         } else if let ObligationCauseCode::BindingObligation(_, _)
1373         | ObligationCauseCode::ItemObligation(_)
1374         | ObligationCauseCode::ExprItemObligation(..)
1375         | ObligationCauseCode::ExprBindingObligation(..) = code
1376         {
1377             try_borrowing(poly_trait_pred, &never_suggest_borrow)
1378         } else {
1379             false
1380         }
1381     }
1382
1383     // Suggest borrowing the type
1384     fn suggest_borrowing_for_object_cast(
1385         &self,
1386         err: &mut Diagnostic,
1387         obligation: &PredicateObligation<'tcx>,
1388         self_ty: Ty<'tcx>,
1389         object_ty: Ty<'tcx>,
1390     ) {
1391         let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1392         let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1393
1394         for predicate in predicates.iter() {
1395             if !self.predicate_must_hold_modulo_regions(
1396                 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1397             ) {
1398                 return;
1399             }
1400         }
1401
1402         err.span_suggestion(
1403             obligation.cause.span.shrink_to_lo(),
1404             &format!(
1405                 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1406             ),
1407             "&",
1408             Applicability::MaybeIncorrect,
1409         );
1410     }
1411
1412     /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1413     /// suggest removing these references until we reach a type that implements the trait.
1414     fn suggest_remove_reference(
1415         &self,
1416         obligation: &PredicateObligation<'tcx>,
1417         err: &mut Diagnostic,
1418         trait_pred: ty::PolyTraitPredicate<'tcx>,
1419     ) -> bool {
1420         let mut span = obligation.cause.span;
1421         let mut trait_pred = trait_pred;
1422         let mut code = obligation.cause.code();
1423         while let Some((c, Some(parent_trait_pred))) = code.parent() {
1424             // We want the root obligation, in order to detect properly handle
1425             // `for _ in &mut &mut vec![] {}`.
1426             code = c;
1427             trait_pred = parent_trait_pred;
1428         }
1429         while span.desugaring_kind().is_some() {
1430             // Remove all the hir desugaring contexts while maintaining the macro contexts.
1431             span.remove_mark();
1432         }
1433         let mut expr_finder = super::FindExprBySpan::new(span);
1434         let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else {
1435             return false;
1436         };
1437         let body = self.tcx.hir().body(body_id);
1438         expr_finder.visit_expr(body.value);
1439         let mut maybe_suggest = |suggested_ty, count, suggestions| {
1440             // Remapping bound vars here
1441             let trait_pred_and_suggested_ty =
1442                 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1443
1444             let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1445                 obligation.param_env,
1446                 trait_pred_and_suggested_ty,
1447             );
1448
1449             if self.predicate_may_hold(&new_obligation) {
1450                 let msg = if count == 1 {
1451                     "consider removing the leading `&`-reference".to_string()
1452                 } else {
1453                     format!("consider removing {count} leading `&`-references")
1454                 };
1455
1456                 err.multipart_suggestion_verbose(
1457                     &msg,
1458                     suggestions,
1459                     Applicability::MachineApplicable,
1460                 );
1461                 true
1462             } else {
1463                 false
1464             }
1465         };
1466
1467         // Maybe suggest removal of borrows from types in type parameters, like in
1468         // `src/test/ui/not-panic/not-panic-safe.rs`.
1469         let mut count = 0;
1470         let mut suggestions = vec![];
1471         // Skipping binder here, remapping below
1472         let mut suggested_ty = trait_pred.self_ty().skip_binder();
1473         if let Some(mut hir_ty) = expr_finder.ty_result {
1474             while let hir::TyKind::Ref(_, mut_ty) = &hir_ty.kind {
1475                 count += 1;
1476                 let span = hir_ty.span.until(mut_ty.ty.span);
1477                 suggestions.push((span, String::new()));
1478
1479                 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1480                     break;
1481                 };
1482                 suggested_ty = *inner_ty;
1483
1484                 hir_ty = mut_ty.ty;
1485
1486                 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1487                     return true;
1488                 }
1489             }
1490         }
1491
1492         // Maybe suggest removal of borrows from expressions, like in `for i in &&&foo {}`.
1493         let Some(mut expr) = expr_finder.result else { return false; };
1494         let mut count = 0;
1495         let mut suggestions = vec![];
1496         // Skipping binder here, remapping below
1497         let mut suggested_ty = trait_pred.self_ty().skip_binder();
1498         'outer: loop {
1499             while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
1500                 count += 1;
1501                 let span = if expr.span.eq_ctxt(borrowed.span) {
1502                     expr.span.until(borrowed.span)
1503                 } else {
1504                     expr.span.with_hi(expr.span.lo() + BytePos(1))
1505                 };
1506                 suggestions.push((span, String::new()));
1507
1508                 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1509                     break 'outer;
1510                 };
1511                 suggested_ty = *inner_ty;
1512
1513                 expr = borrowed;
1514
1515                 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1516                     return true;
1517                 }
1518             }
1519             if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1520                 && let hir::def::Res::Local(hir_id) = path.res
1521                 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(hir_id)
1522                 && let Some(hir::Node::Local(local)) = self.tcx.hir().find_parent(binding.hir_id)
1523                 && let None = local.ty
1524                 && let Some(binding_expr) = local.init
1525             {
1526                 expr = binding_expr;
1527             } else {
1528                 break 'outer;
1529             }
1530         }
1531         false
1532     }
1533
1534     fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1535         let span = obligation.cause.span;
1536
1537         if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1538             let hir = self.tcx.hir();
1539             if let Some(hir::Node::Expr(expr)) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1540                 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1541                 // and if not maybe suggest doing something else? If we kept the expression around we
1542                 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1543                 // it is from the local crate.
1544                 err.span_suggestion(
1545                     span,
1546                     "remove the `.await`",
1547                     "",
1548                     Applicability::MachineApplicable,
1549                 );
1550                 // FIXME: account for associated `async fn`s.
1551                 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1552                     if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) =
1553                         obligation.predicate.kind().skip_binder()
1554                     {
1555                         err.span_label(*span, &format!("this call returns `{}`", pred.self_ty()));
1556                     }
1557                     if let Some(typeck_results) = &self.typeck_results
1558                             && let ty = typeck_results.expr_ty_adjusted(base)
1559                             && let ty::FnDef(def_id, _substs) = ty.kind()
1560                             && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1561                                 hir.get_if_local(*def_id)
1562                         {
1563                             let msg = format!(
1564                                 "alternatively, consider making `fn {}` asynchronous",
1565                                 ident
1566                             );
1567                             if vis_span.is_empty() {
1568                                 err.span_suggestion_verbose(
1569                                     span.shrink_to_lo(),
1570                                     &msg,
1571                                     "async ",
1572                                     Applicability::MaybeIncorrect,
1573                                 );
1574                             } else {
1575                                 err.span_suggestion_verbose(
1576                                     vis_span.shrink_to_hi(),
1577                                     &msg,
1578                                     " async",
1579                                     Applicability::MaybeIncorrect,
1580                                 );
1581                             }
1582                         }
1583                 }
1584             }
1585         }
1586     }
1587
1588     /// Check if the trait bound is implemented for a different mutability and note it in the
1589     /// final error.
1590     fn suggest_change_mut(
1591         &self,
1592         obligation: &PredicateObligation<'tcx>,
1593         err: &mut Diagnostic,
1594         trait_pred: ty::PolyTraitPredicate<'tcx>,
1595     ) {
1596         let points_at_arg = matches!(
1597             obligation.cause.code(),
1598             ObligationCauseCode::FunctionArgumentObligation { .. },
1599         );
1600
1601         let span = obligation.cause.span;
1602         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1603             let refs_number =
1604                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1605             if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1606                 // Do not suggest removal of borrow from type arguments.
1607                 return;
1608             }
1609             let trait_pred = self.resolve_vars_if_possible(trait_pred);
1610             if trait_pred.has_non_region_infer() {
1611                 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1612                 // unresolved bindings.
1613                 return;
1614             }
1615
1616             // Skipping binder here, remapping below
1617             if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1618             {
1619                 let suggested_ty = match mutability {
1620                     hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1621                     hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1622                 };
1623
1624                 // Remapping bound vars here
1625                 let trait_pred_and_suggested_ty =
1626                     trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1627
1628                 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1629                     obligation.param_env,
1630                     trait_pred_and_suggested_ty,
1631                 );
1632                 let suggested_ty_would_satisfy_obligation = self
1633                     .evaluate_obligation_no_overflow(&new_obligation)
1634                     .must_apply_modulo_regions();
1635                 if suggested_ty_would_satisfy_obligation {
1636                     let sp = self
1637                         .tcx
1638                         .sess
1639                         .source_map()
1640                         .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1641                     if points_at_arg && mutability.is_not() && refs_number > 0 {
1642                         // If we have a call like foo(&mut buf), then don't suggest foo(&mut mut buf)
1643                         if snippet
1644                             .trim_start_matches(|c: char| c.is_whitespace() || c == '&')
1645                             .starts_with("mut")
1646                         {
1647                             return;
1648                         }
1649                         err.span_suggestion_verbose(
1650                             sp,
1651                             "consider changing this borrow's mutability",
1652                             "&mut ",
1653                             Applicability::MachineApplicable,
1654                         );
1655                     } else {
1656                         err.note(&format!(
1657                             "`{}` is implemented for `{:?}`, but not for `{:?}`",
1658                             trait_pred.print_modifiers_and_trait_path(),
1659                             suggested_ty,
1660                             trait_pred.skip_binder().self_ty(),
1661                         ));
1662                     }
1663                 }
1664             }
1665         }
1666     }
1667
1668     fn suggest_semicolon_removal(
1669         &self,
1670         obligation: &PredicateObligation<'tcx>,
1671         err: &mut Diagnostic,
1672         span: Span,
1673         trait_pred: ty::PolyTraitPredicate<'tcx>,
1674     ) -> bool {
1675         let hir = self.tcx.hir();
1676         let node = hir.find_by_def_id(obligation.cause.body_id);
1677         if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1678             && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1679             && sig.decl.output.span().overlaps(span)
1680             && blk.expr.is_none()
1681             && trait_pred.self_ty().skip_binder().is_unit()
1682             && let Some(stmt) = blk.stmts.last()
1683             && let hir::StmtKind::Semi(expr) = stmt.kind
1684             // Only suggest this if the expression behind the semicolon implements the predicate
1685             && let Some(typeck_results) = &self.typeck_results
1686             && let Some(ty) = typeck_results.expr_ty_opt(expr)
1687             && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1688                 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1689             ))
1690         {
1691             err.span_label(
1692                 expr.span,
1693                 &format!(
1694                     "this expression has type `{}`, which implements `{}`",
1695                     ty,
1696                     trait_pred.print_modifiers_and_trait_path()
1697                 )
1698             );
1699             err.span_suggestion(
1700                 self.tcx.sess.source_map().end_point(stmt.span),
1701                 "remove this semicolon",
1702                 "",
1703                 Applicability::MachineApplicable
1704             );
1705             return true;
1706         }
1707         false
1708     }
1709
1710     fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1711         let hir = self.tcx.hir();
1712         let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find_by_def_id(obligation.cause.body_id) else {
1713             return None;
1714         };
1715
1716         if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1717     }
1718
1719     /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1720     /// applicable and signal that the error has been expanded appropriately and needs to be
1721     /// emitted.
1722     fn suggest_impl_trait(
1723         &self,
1724         err: &mut Diagnostic,
1725         span: Span,
1726         obligation: &PredicateObligation<'tcx>,
1727         trait_pred: ty::PolyTraitPredicate<'tcx>,
1728     ) -> bool {
1729         match obligation.cause.code().peel_derives() {
1730             // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1731             ObligationCauseCode::SizedReturnType => {}
1732             _ => return false,
1733         }
1734
1735         let hir = self.tcx.hir();
1736         let fn_hir_id = hir.local_def_id_to_hir_id(obligation.cause.body_id);
1737         let node = hir.find_by_def_id(obligation.cause.body_id);
1738         let Some(hir::Node::Item(hir::Item {
1739             kind: hir::ItemKind::Fn(sig, _, body_id),
1740             ..
1741         })) = node
1742         else {
1743             return false;
1744         };
1745         let body = hir.body(*body_id);
1746         let trait_pred = self.resolve_vars_if_possible(trait_pred);
1747         let ty = trait_pred.skip_binder().self_ty();
1748         let is_object_safe = match ty.kind() {
1749             ty::Dynamic(predicates, _, ty::Dyn) => {
1750                 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1751                 predicates
1752                     .principal_def_id()
1753                     .map_or(true, |def_id| self.tcx.check_is_object_safe(def_id))
1754             }
1755             // We only want to suggest `impl Trait` to `dyn Trait`s.
1756             // For example, `fn foo() -> str` needs to be filtered out.
1757             _ => return false,
1758         };
1759
1760         let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1761             return false;
1762         };
1763
1764         // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1765         // cases like `fn foo() -> (dyn Trait, i32) {}`.
1766         // Recursively look for `TraitObject` types and if there's only one, use that span to
1767         // suggest `impl Trait`.
1768
1769         // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1770         // otherwise suggest using `Box<dyn Trait>` or an enum.
1771         let mut visitor = ReturnsVisitor::default();
1772         visitor.visit_body(&body);
1773
1774         let typeck_results = self.typeck_results.as_ref().unwrap();
1775         let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1776
1777         let ret_types = visitor
1778             .returns
1779             .iter()
1780             .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1781             .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1782         let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1783             (None, true, true),
1784             |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1785              (_, ty)| {
1786                 let ty = self.resolve_vars_if_possible(ty);
1787                 same &=
1788                     !matches!(ty.kind(), ty::Error(_))
1789                         && last_ty.map_or(true, |last_ty| {
1790                             // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1791                             // *after* in the dependency graph.
1792                             match (ty.kind(), last_ty.kind()) {
1793                                 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1794                                 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1795                                 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1796                                 | (
1797                                     Infer(InferTy::FreshFloatTy(_)),
1798                                     Infer(InferTy::FreshFloatTy(_)),
1799                                 ) => true,
1800                                 _ => ty == last_ty,
1801                             }
1802                         });
1803                 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1804             },
1805         );
1806         let mut spans_and_needs_box = vec![];
1807
1808         match liberated_sig.output().kind() {
1809             ty::Dynamic(predicates, _, ty::Dyn) => {
1810                 let cause = ObligationCause::misc(ret_ty.span, obligation.cause.body_id);
1811                 let param_env = ty::ParamEnv::empty();
1812
1813                 if !only_never_return {
1814                     for (expr_span, return_ty) in ret_types {
1815                         let self_ty_satisfies_dyn_predicates = |self_ty| {
1816                             predicates.iter().all(|predicate| {
1817                                 let pred = predicate.with_self_ty(self.tcx, self_ty);
1818                                 let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred);
1819                                 self.predicate_may_hold(&obl)
1820                             })
1821                         };
1822
1823                         if let ty::Adt(def, substs) = return_ty.kind()
1824                             && def.is_box()
1825                             && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1826                         {
1827                             spans_and_needs_box.push((expr_span, false));
1828                         } else if self_ty_satisfies_dyn_predicates(return_ty) {
1829                             spans_and_needs_box.push((expr_span, true));
1830                         } else {
1831                             return false;
1832                         }
1833                     }
1834                 }
1835             }
1836             _ => return false,
1837         };
1838
1839         let sm = self.tcx.sess.source_map();
1840         if !ret_ty.span.overlaps(span) {
1841             return false;
1842         }
1843         let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1844             if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1845                 snippet
1846             } else {
1847                 return false;
1848             }
1849         } else {
1850             // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1851             let name = liberated_sig.output().to_string();
1852             let name =
1853                 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1854             if !name.starts_with("dyn ") {
1855                 return false;
1856             }
1857             name.to_owned()
1858         };
1859
1860         err.code(error_code!(E0746));
1861         err.set_primary_message("return type cannot have an unboxed trait object");
1862         err.children.clear();
1863         let impl_trait_msg = "for information on `impl Trait`, see \
1864             <https://doc.rust-lang.org/book/ch10-02-traits.html\
1865             #returning-types-that-implement-traits>";
1866         let trait_obj_msg = "for information on trait objects, see \
1867             <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1868             #using-trait-objects-that-allow-for-values-of-different-types>";
1869
1870         let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1871         let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1872         if only_never_return {
1873             // No return paths, probably using `panic!()` or similar.
1874             // Suggest `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1875             suggest_trait_object_return_type_alternatives(
1876                 err,
1877                 ret_ty.span,
1878                 trait_obj,
1879                 is_object_safe,
1880             );
1881         } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1882             // Suggest `-> impl Trait`.
1883             err.span_suggestion(
1884                 ret_ty.span,
1885                 &format!(
1886                     "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1887                      which implements `{1}`",
1888                     last_ty, trait_obj,
1889                 ),
1890                 format!("impl {}", trait_obj),
1891                 Applicability::MachineApplicable,
1892             );
1893             err.note(impl_trait_msg);
1894         } else {
1895             if is_object_safe {
1896                 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1897                 err.multipart_suggestion(
1898                     "return a boxed trait object instead",
1899                     vec![
1900                         (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1901                         (span.shrink_to_hi(), ">".to_string()),
1902                     ],
1903                     Applicability::MaybeIncorrect,
1904                 );
1905                 for (span, needs_box) in spans_and_needs_box {
1906                     if needs_box {
1907                         err.multipart_suggestion(
1908                             "... and box this value",
1909                             vec![
1910                                 (span.shrink_to_lo(), "Box::new(".to_string()),
1911                                 (span.shrink_to_hi(), ")".to_string()),
1912                             ],
1913                             Applicability::MaybeIncorrect,
1914                         );
1915                     }
1916                 }
1917             } else {
1918                 // This is currently not possible to trigger because E0038 takes precedence, but
1919                 // leave it in for completeness in case anything changes in an earlier stage.
1920                 err.note(&format!(
1921                     "if trait `{}` were object-safe, you could return a trait object",
1922                     trait_obj,
1923                 ));
1924             }
1925             err.note(trait_obj_msg);
1926             err.note(&format!(
1927                 "if all the returned values were of the same type you could use `impl {}` as the \
1928                  return type",
1929                 trait_obj,
1930             ));
1931             err.note(impl_trait_msg);
1932             err.note("you can create a new `enum` with a variant for each returned type");
1933         }
1934         true
1935     }
1936
1937     fn point_at_returns_when_relevant(
1938         &self,
1939         err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1940         obligation: &PredicateObligation<'tcx>,
1941     ) {
1942         match obligation.cause.code().peel_derives() {
1943             ObligationCauseCode::SizedReturnType => {}
1944             _ => return,
1945         }
1946
1947         let hir = self.tcx.hir();
1948         let node = hir.find_by_def_id(obligation.cause.body_id);
1949         if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1950             node
1951         {
1952             let body = hir.body(*body_id);
1953             // Point at all the `return`s in the function as they have failed trait bounds.
1954             let mut visitor = ReturnsVisitor::default();
1955             visitor.visit_body(&body);
1956             let typeck_results = self.typeck_results.as_ref().unwrap();
1957             for expr in &visitor.returns {
1958                 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1959                     let ty = self.resolve_vars_if_possible(returned_ty);
1960                     if ty.references_error() {
1961                         // don't print out the [type error] here
1962                         err.delay_as_bug();
1963                     } else {
1964                         err.span_label(
1965                             expr.span,
1966                             &format!("this returned value is of type `{}`", ty),
1967                         );
1968                     }
1969                 }
1970             }
1971         }
1972     }
1973
1974     fn report_closure_arg_mismatch(
1975         &self,
1976         span: Span,
1977         found_span: Option<Span>,
1978         found: ty::PolyTraitRef<'tcx>,
1979         expected: ty::PolyTraitRef<'tcx>,
1980         cause: &ObligationCauseCode<'tcx>,
1981         found_node: Option<Node<'_>>,
1982         param_env: ty::ParamEnv<'tcx>,
1983     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1984         pub(crate) fn build_fn_sig_ty<'tcx>(
1985             infcx: &InferCtxt<'tcx>,
1986             trait_ref: ty::PolyTraitRef<'tcx>,
1987         ) -> Ty<'tcx> {
1988             let inputs = trait_ref.skip_binder().substs.type_at(1);
1989             let sig = match inputs.kind() {
1990                 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id()) => {
1991                     infcx.tcx.mk_fn_sig(
1992                         inputs.iter(),
1993                         infcx.next_ty_var(TypeVariableOrigin {
1994                             span: DUMMY_SP,
1995                             kind: TypeVariableOriginKind::MiscVariable,
1996                         }),
1997                         false,
1998                         hir::Unsafety::Normal,
1999                         abi::Abi::Rust,
2000                     )
2001                 }
2002                 _ => infcx.tcx.mk_fn_sig(
2003                     std::iter::once(inputs),
2004                     infcx.next_ty_var(TypeVariableOrigin {
2005                         span: DUMMY_SP,
2006                         kind: TypeVariableOriginKind::MiscVariable,
2007                     }),
2008                     false,
2009                     hir::Unsafety::Normal,
2010                     abi::Abi::Rust,
2011                 ),
2012             };
2013
2014             infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
2015         }
2016
2017         let argument_kind = match expected.skip_binder().self_ty().kind() {
2018             ty::Closure(..) => "closure",
2019             ty::Generator(..) => "generator",
2020             _ => "function",
2021         };
2022         let mut err = struct_span_err!(
2023             self.tcx.sess,
2024             span,
2025             E0631,
2026             "type mismatch in {argument_kind} arguments",
2027         );
2028
2029         err.span_label(span, "expected due to this");
2030
2031         let found_span = found_span.unwrap_or(span);
2032         err.span_label(found_span, "found signature defined here");
2033
2034         let expected = build_fn_sig_ty(self, expected);
2035         let found = build_fn_sig_ty(self, found);
2036
2037         let (expected_str, found_str) = self.cmp(expected, found);
2038
2039         let signature_kind = format!("{argument_kind} signature");
2040         err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
2041
2042         self.note_conflicting_closure_bounds(cause, &mut err);
2043
2044         if let Some(found_node) = found_node {
2045             hint_missing_borrow(self, param_env, span, found, expected, found_node, &mut err);
2046         }
2047
2048         err
2049     }
2050
2051     // Add a note if there are two `Fn`-family bounds that have conflicting argument
2052     // requirements, which will always cause a closure to have a type error.
2053     fn note_conflicting_closure_bounds(
2054         &self,
2055         cause: &ObligationCauseCode<'tcx>,
2056         err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
2057     ) {
2058         // First, look for an `ExprBindingObligation`, which means we can get
2059         // the unsubstituted predicate list of the called function. And check
2060         // that the predicate that we failed to satisfy is a `Fn`-like trait.
2061         if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
2062             && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
2063             && let Some(pred) = predicates.predicates.get(*idx)
2064             && let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder()
2065             && self.tcx.is_fn_trait(trait_pred.def_id())
2066         {
2067             let expected_self =
2068                 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.self_ty()));
2069             let expected_substs = self
2070                 .tcx
2071                 .anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.substs));
2072
2073             // Find another predicate whose self-type is equal to the expected self type,
2074             // but whose substs don't match.
2075             let other_pred = predicates.into_iter()
2076                 .enumerate()
2077                 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
2078                     ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
2079                         if self.tcx.is_fn_trait(trait_pred.def_id())
2080                             && other_idx != idx
2081                             // Make sure that the self type matches
2082                             // (i.e. constraining this closure)
2083                             && expected_self
2084                                 == self.tcx.anonymize_bound_vars(
2085                                     pred.kind().rebind(trait_pred.self_ty()),
2086                                 )
2087                             // But the substs don't match (i.e. incompatible args)
2088                             && expected_substs
2089                                 != self.tcx.anonymize_bound_vars(
2090                                     pred.kind().rebind(trait_pred.trait_ref.substs),
2091                                 ) =>
2092                     {
2093                         true
2094                     }
2095                     _ => false,
2096                 });
2097             // If we found one, then it's very likely the cause of the error.
2098             if let Some((_, (_, other_pred_span))) = other_pred {
2099                 err.span_note(
2100                     other_pred_span,
2101                     "closure inferred to have a different signature due to this bound",
2102                 );
2103             }
2104         }
2105     }
2106
2107     fn suggest_fully_qualified_path(
2108         &self,
2109         err: &mut Diagnostic,
2110         item_def_id: DefId,
2111         span: Span,
2112         trait_ref: DefId,
2113     ) {
2114         if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
2115             if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
2116                 err.note(&format!(
2117                     "{}s cannot be accessed directly on a `trait`, they can only be \
2118                         accessed through a specific `impl`",
2119                     assoc_item.kind.as_def_kind().descr(item_def_id)
2120                 ));
2121                 err.span_suggestion(
2122                     span,
2123                     "use the fully qualified path to an implementation",
2124                     format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
2125                     Applicability::HasPlaceholders,
2126                 );
2127             }
2128         }
2129     }
2130
2131     /// Adds an async-await specific note to the diagnostic when the future does not implement
2132     /// an auto trait because of a captured type.
2133     ///
2134     /// ```text
2135     /// note: future does not implement `Qux` as this value is used across an await
2136     ///   --> $DIR/issue-64130-3-other.rs:17:5
2137     ///    |
2138     /// LL |     let x = Foo;
2139     ///    |         - has type `Foo`
2140     /// LL |     baz().await;
2141     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2142     /// LL | }
2143     ///    | - `x` is later dropped here
2144     /// ```
2145     ///
2146     /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
2147     /// is "replaced" with a different message and a more specific error.
2148     ///
2149     /// ```text
2150     /// error: future cannot be sent between threads safely
2151     ///   --> $DIR/issue-64130-2-send.rs:21:5
2152     ///    |
2153     /// LL | fn is_send<T: Send>(t: T) { }
2154     ///    |               ---- required by this bound in `is_send`
2155     /// ...
2156     /// LL |     is_send(bar());
2157     ///    |     ^^^^^^^ future returned by `bar` is not send
2158     ///    |
2159     ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
2160     ///            implemented for `Foo`
2161     /// note: future is not send as this value is used across an await
2162     ///   --> $DIR/issue-64130-2-send.rs:15:5
2163     ///    |
2164     /// LL |     let x = Foo;
2165     ///    |         - has type `Foo`
2166     /// LL |     baz().await;
2167     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2168     /// LL | }
2169     ///    | - `x` is later dropped here
2170     /// ```
2171     ///
2172     /// Returns `true` if an async-await specific note was added to the diagnostic.
2173     #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
2174     fn maybe_note_obligation_cause_for_async_await(
2175         &self,
2176         err: &mut Diagnostic,
2177         obligation: &PredicateObligation<'tcx>,
2178     ) -> bool {
2179         let hir = self.tcx.hir();
2180
2181         // Attempt to detect an async-await error by looking at the obligation causes, looking
2182         // for a generator to be present.
2183         //
2184         // When a future does not implement a trait because of a captured type in one of the
2185         // generators somewhere in the call stack, then the result is a chain of obligations.
2186         //
2187         // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
2188         // future is passed as an argument to a function C which requires a `Send` type, then the
2189         // chain looks something like this:
2190         //
2191         // - `BuiltinDerivedObligation` with a generator witness (B)
2192         // - `BuiltinDerivedObligation` with a generator (B)
2193         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2194         // - `BuiltinDerivedObligation` with a generator witness (A)
2195         // - `BuiltinDerivedObligation` with a generator (A)
2196         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2197         // - `BindingObligation` with `impl_send (Send requirement)
2198         //
2199         // The first obligation in the chain is the most useful and has the generator that captured
2200         // the type. The last generator (`outer_generator` below) has information about where the
2201         // bound was introduced. At least one generator should be present for this diagnostic to be
2202         // modified.
2203         let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
2204             ty::PredicateKind::Clause(ty::Clause::Trait(p)) => (Some(p), Some(p.self_ty())),
2205             _ => (None, None),
2206         };
2207         let mut generator = None;
2208         let mut outer_generator = None;
2209         let mut next_code = Some(obligation.cause.code());
2210
2211         let mut seen_upvar_tys_infer_tuple = false;
2212
2213         while let Some(code) = next_code {
2214             debug!(?code);
2215             match code {
2216                 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
2217                     next_code = Some(parent_code);
2218                 }
2219                 ObligationCauseCode::ImplDerivedObligation(cause) => {
2220                     let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
2221                     debug!(
2222                         parent_trait_ref = ?cause.derived.parent_trait_pred,
2223                         self_ty.kind = ?ty.kind(),
2224                         "ImplDerived",
2225                     );
2226
2227                     match *ty.kind() {
2228                         ty::Generator(did, ..) | ty::GeneratorWitnessMIR(did, _) => {
2229                             generator = generator.or(Some(did));
2230                             outer_generator = Some(did);
2231                         }
2232                         ty::GeneratorWitness(..) => {}
2233                         ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2234                             // By introducing a tuple of upvar types into the chain of obligations
2235                             // of a generator, the first non-generator item is now the tuple itself,
2236                             // we shall ignore this.
2237
2238                             seen_upvar_tys_infer_tuple = true;
2239                         }
2240                         _ if generator.is_none() => {
2241                             trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
2242                             target_ty = Some(ty);
2243                         }
2244                         _ => {}
2245                     }
2246
2247                     next_code = Some(&cause.derived.parent_code);
2248                 }
2249                 ObligationCauseCode::DerivedObligation(derived_obligation)
2250                 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
2251                     let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
2252                     debug!(
2253                         parent_trait_ref = ?derived_obligation.parent_trait_pred,
2254                         self_ty.kind = ?ty.kind(),
2255                     );
2256
2257                     match *ty.kind() {
2258                         ty::Generator(did, ..) | ty::GeneratorWitnessMIR(did, ..) => {
2259                             generator = generator.or(Some(did));
2260                             outer_generator = Some(did);
2261                         }
2262                         ty::GeneratorWitness(..) => {}
2263                         ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2264                             // By introducing a tuple of upvar types into the chain of obligations
2265                             // of a generator, the first non-generator item is now the tuple itself,
2266                             // we shall ignore this.
2267
2268                             seen_upvar_tys_infer_tuple = true;
2269                         }
2270                         _ if generator.is_none() => {
2271                             trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
2272                             target_ty = Some(ty);
2273                         }
2274                         _ => {}
2275                     }
2276
2277                     next_code = Some(&derived_obligation.parent_code);
2278                 }
2279                 _ => break,
2280             }
2281         }
2282
2283         // Only continue if a generator was found.
2284         debug!(?generator, ?trait_ref, ?target_ty);
2285         let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
2286             return false;
2287         };
2288
2289         let span = self.tcx.def_span(generator_did);
2290
2291         let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
2292         debug!(
2293             ?generator_did,
2294             ?generator_did_root,
2295             typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2296             ?span,
2297         );
2298
2299         let generator_body = generator_did
2300             .as_local()
2301             .and_then(|def_id| hir.maybe_body_owned_by(def_id))
2302             .map(|body_id| hir.body(body_id));
2303         let mut visitor = AwaitsVisitor::default();
2304         if let Some(body) = generator_body {
2305             visitor.visit_body(body);
2306         }
2307         debug!(awaits = ?visitor.awaits);
2308
2309         // Look for a type inside the generator interior that matches the target type to get
2310         // a span.
2311         let target_ty_erased = self.tcx.erase_regions(target_ty);
2312         let ty_matches = |ty| -> bool {
2313             // Careful: the regions for types that appear in the
2314             // generator interior are not generally known, so we
2315             // want to erase them when comparing (and anyway,
2316             // `Send` and other bounds are generally unaffected by
2317             // the choice of region). When erasing regions, we
2318             // also have to erase late-bound regions. This is
2319             // because the types that appear in the generator
2320             // interior generally contain "bound regions" to
2321             // represent regions that are part of the suspended
2322             // generator frame. Bound regions are preserved by
2323             // `erase_regions` and so we must also call
2324             // `erase_late_bound_regions`.
2325             let ty_erased = self.tcx.erase_late_bound_regions(ty);
2326             let ty_erased = self.tcx.erase_regions(ty_erased);
2327             let eq = ty_erased == target_ty_erased;
2328             debug!(?ty_erased, ?target_ty_erased, ?eq);
2329             eq
2330         };
2331
2332         // Get the typeck results from the infcx if the generator is the function we are currently
2333         // type-checking; otherwise, get them by performing a query. This is needed to avoid
2334         // cycles. If we can't use resolved types because the generator comes from another crate,
2335         // we still provide a targeted error but without all the relevant spans.
2336         let generator_data = match &self.typeck_results {
2337             Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2338             _ if generator_did.is_local() => {
2339                 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2340             }
2341             _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2342                 GeneratorData::Foreign(generator_diag_data)
2343             }
2344             _ => return false,
2345         };
2346
2347         let generator_within_in_progress_typeck = match &self.typeck_results {
2348             Some(t) => t.hir_owner.to_def_id() == generator_did_root,
2349             _ => false,
2350         };
2351
2352         let mut interior_or_upvar_span = None;
2353
2354         let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2355         debug!(?from_awaited_ty);
2356
2357         // The generator interior types share the same binders
2358         if let Some(cause) =
2359             generator_data.get_generator_interior_types().skip_binder().iter().find(
2360                 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2361                     ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2362                 },
2363             )
2364         {
2365             let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2366
2367             interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2368                 *span,
2369                 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2370             ));
2371
2372             if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2373                 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span, None));
2374             }
2375         } else if self.tcx.sess.opts.unstable_opts.drop_tracking_mir
2376             // Avoid disclosing internal information to downstream crates.
2377             && generator_did.is_local()
2378             // Try to avoid cycles.
2379             && !generator_within_in_progress_typeck
2380         {
2381             let generator_info = &self.tcx.mir_generator_witnesses(generator_did);
2382             debug!(?generator_info);
2383
2384             'find_source: for (variant, source_info) in
2385                 generator_info.variant_fields.iter().zip(&generator_info.variant_source_info)
2386             {
2387                 debug!(?variant);
2388                 for &local in variant {
2389                     let decl = &generator_info.field_tys[local];
2390                     debug!(?decl);
2391                     if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits {
2392                         interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2393                             decl.source_info.span,
2394                             Some((None, source_info.span, None, from_awaited_ty)),
2395                         ));
2396                         break 'find_source;
2397                     }
2398                 }
2399             }
2400         }
2401
2402         if interior_or_upvar_span.is_none() {
2403             interior_or_upvar_span =
2404                 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2405         }
2406
2407         if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2408             interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2409         }
2410
2411         debug!(?interior_or_upvar_span);
2412         if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2413             let is_async = self.tcx.generator_is_async(generator_did);
2414             let typeck_results = match generator_data {
2415                 GeneratorData::Local(typeck_results) => Some(typeck_results),
2416                 GeneratorData::Foreign(_) => None,
2417             };
2418             self.note_obligation_cause_for_async_await(
2419                 err,
2420                 interior_or_upvar_span,
2421                 is_async,
2422                 outer_generator,
2423                 trait_ref,
2424                 target_ty,
2425                 typeck_results,
2426                 obligation,
2427                 next_code,
2428             );
2429             true
2430         } else {
2431             false
2432         }
2433     }
2434
2435     /// Unconditionally adds the diagnostic note described in
2436     /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2437     #[instrument(level = "debug", skip_all)]
2438     fn note_obligation_cause_for_async_await(
2439         &self,
2440         err: &mut Diagnostic,
2441         interior_or_upvar_span: GeneratorInteriorOrUpvar,
2442         is_async: bool,
2443         outer_generator: Option<DefId>,
2444         trait_pred: ty::TraitPredicate<'tcx>,
2445         target_ty: Ty<'tcx>,
2446         typeck_results: Option<&ty::TypeckResults<'tcx>>,
2447         obligation: &PredicateObligation<'tcx>,
2448         next_code: Option<&ObligationCauseCode<'tcx>>,
2449     ) {
2450         let source_map = self.tcx.sess.source_map();
2451
2452         let (await_or_yield, an_await_or_yield) =
2453             if is_async { ("await", "an await") } else { ("yield", "a yield") };
2454         let future_or_generator = if is_async { "future" } else { "generator" };
2455
2456         // Special case the primary error message when send or sync is the trait that was
2457         // not implemented.
2458         let hir = self.tcx.hir();
2459         let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2460             self.tcx.get_diagnostic_name(trait_pred.def_id())
2461         {
2462             let (trait_name, trait_verb) =
2463                 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2464
2465             err.clear_code();
2466             err.set_primary_message(format!(
2467                 "{} cannot be {} between threads safely",
2468                 future_or_generator, trait_verb
2469             ));
2470
2471             let original_span = err.span.primary_span().unwrap();
2472             let mut span = MultiSpan::from_span(original_span);
2473
2474             let message = outer_generator
2475                 .and_then(|generator_did| {
2476                     Some(match self.tcx.generator_kind(generator_did).unwrap() {
2477                         GeneratorKind::Gen => format!("generator is not {}", trait_name),
2478                         GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2479                             .tcx
2480                             .parent(generator_did)
2481                             .as_local()
2482                             .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2483                             .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2484                             .map(|name| {
2485                                 format!("future returned by `{}` is not {}", name, trait_name)
2486                             })?,
2487                         GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2488                             format!("future created by async block is not {}", trait_name)
2489                         }
2490                         GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2491                             format!("future created by async closure is not {}", trait_name)
2492                         }
2493                     })
2494                 })
2495                 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2496
2497             span.push_span_label(original_span, message);
2498             err.set_span(span);
2499
2500             format!("is not {}", trait_name)
2501         } else {
2502             format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2503         };
2504
2505         let mut explain_yield =
2506             |interior_span: Span, yield_span: Span, scope_span: Option<Span>| {
2507                 let mut span = MultiSpan::from_span(yield_span);
2508                 let snippet = match source_map.span_to_snippet(interior_span) {
2509                     // #70935: If snippet contains newlines, display "the value" instead
2510                     // so that we do not emit complex diagnostics.
2511                     Ok(snippet) if !snippet.contains('\n') => format!("`{}`", snippet),
2512                     _ => "the value".to_string(),
2513                 };
2514                 // note: future is not `Send` as this value is used across an await
2515                 //   --> $DIR/issue-70935-complex-spans.rs:13:9
2516                 //    |
2517                 // LL |            baz(|| async {
2518                 //    |  ______________-
2519                 //    | |
2520                 //    | |
2521                 // LL | |              foo(tx.clone());
2522                 // LL | |          }).await;
2523                 //    | |          - ^^^^^^ await occurs here, with value maybe used later
2524                 //    | |__________|
2525                 //    |            has type `closure` which is not `Send`
2526                 // note: value is later dropped here
2527                 // LL | |          }).await;
2528                 //    | |                  ^
2529                 //
2530                 span.push_span_label(
2531                     yield_span,
2532                     format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2533                 );
2534                 span.push_span_label(
2535                     interior_span,
2536                     format!("has type `{}` which {}", target_ty, trait_explanation),
2537                 );
2538                 if let Some(scope_span) = scope_span {
2539                     let scope_span = source_map.end_point(scope_span);
2540
2541                     let msg = format!("{} is later dropped here", snippet);
2542                     span.push_span_label(scope_span, msg);
2543                 }
2544                 err.span_note(
2545                     span,
2546                     &format!(
2547                         "{} {} as this value is used across {}",
2548                         future_or_generator, trait_explanation, an_await_or_yield
2549                     ),
2550                 );
2551             };
2552         match interior_or_upvar_span {
2553             GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2554                 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2555                     if let Some(await_span) = from_awaited_ty {
2556                         // The type causing this obligation is one being awaited at await_span.
2557                         let mut span = MultiSpan::from_span(await_span);
2558                         span.push_span_label(
2559                             await_span,
2560                             format!(
2561                                 "await occurs here on type `{}`, which {}",
2562                                 target_ty, trait_explanation
2563                             ),
2564                         );
2565                         err.span_note(
2566                             span,
2567                             &format!(
2568                                 "future {not_trait} as it awaits another future which {not_trait}",
2569                                 not_trait = trait_explanation
2570                             ),
2571                         );
2572                     } else {
2573                         // Look at the last interior type to get a span for the `.await`.
2574                         debug!(
2575                             generator_interior_types = ?format_args!(
2576                                 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2577                             ),
2578                         );
2579                         explain_yield(interior_span, yield_span, scope_span);
2580                     }
2581
2582                     if let Some(expr_id) = expr {
2583                         let expr = hir.expect_expr(expr_id);
2584                         debug!("target_ty evaluated from {:?}", expr);
2585
2586                         let parent = hir.parent_id(expr_id);
2587                         if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2588                             let parent_span = hir.span(parent);
2589                             let parent_did = parent.owner.to_def_id();
2590                             // ```rust
2591                             // impl T {
2592                             //     fn foo(&self) -> i32 {}
2593                             // }
2594                             // T.foo();
2595                             // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2596                             // ```
2597                             //
2598                             let is_region_borrow = if let Some(typeck_results) = typeck_results {
2599                                 typeck_results
2600                                     .expr_adjustments(expr)
2601                                     .iter()
2602                                     .any(|adj| adj.is_region_borrow())
2603                             } else {
2604                                 false
2605                             };
2606
2607                             // ```rust
2608                             // struct Foo(*const u8);
2609                             // bar(Foo(std::ptr::null())).await;
2610                             //     ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2611                             // ```
2612                             debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2613                             let is_raw_borrow_inside_fn_like_call =
2614                                 match self.tcx.def_kind(parent_did) {
2615                                     DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2616                                     _ => false,
2617                                 };
2618                             if let Some(typeck_results) = typeck_results {
2619                                 if (typeck_results.is_method_call(e) && is_region_borrow)
2620                                     || is_raw_borrow_inside_fn_like_call
2621                                 {
2622                                     err.span_help(
2623                                         parent_span,
2624                                         "consider moving this into a `let` \
2625                         binding to create a shorter lived borrow",
2626                                     );
2627                                 }
2628                             }
2629                         }
2630                     }
2631                 }
2632             }
2633             GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2634                 // `Some((ref_ty, is_mut))` if `target_ty` is `&T` or `&mut T` and fails to impl `Send`
2635                 let non_send = match target_ty.kind() {
2636                     ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(&obligation) {
2637                         Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
2638                         _ => None,
2639                     },
2640                     _ => None,
2641                 };
2642
2643                 let (span_label, span_note) = match non_send {
2644                     // if `target_ty` is `&T` or `&mut T` and fails to impl `Send`,
2645                     // include suggestions to make `T: Sync` so that `&T: Send`,
2646                     // or to make `T: Send` so that `&mut T: Send`
2647                     Some((ref_ty, is_mut)) => {
2648                         let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
2649                         let ref_kind = if is_mut { "&mut" } else { "&" };
2650                         (
2651                             format!(
2652                                 "has type `{}` which {}, because `{}` is not `{}`",
2653                                 target_ty, trait_explanation, ref_ty, ref_ty_trait
2654                             ),
2655                             format!(
2656                                 "captured value {} because `{}` references cannot be sent unless their referent is `{}`",
2657                                 trait_explanation, ref_kind, ref_ty_trait
2658                             ),
2659                         )
2660                     }
2661                     None => (
2662                         format!("has type `{}` which {}", target_ty, trait_explanation),
2663                         format!("captured value {}", trait_explanation),
2664                     ),
2665                 };
2666
2667                 let mut span = MultiSpan::from_span(upvar_span);
2668                 span.push_span_label(upvar_span, span_label);
2669                 err.span_note(span, &span_note);
2670             }
2671         }
2672
2673         // Add a note for the item obligation that remains - normally a note pointing to the
2674         // bound that introduced the obligation (e.g. `T: Send`).
2675         debug!(?next_code);
2676         self.note_obligation_cause_code(
2677             err,
2678             obligation.predicate,
2679             obligation.param_env,
2680             next_code.unwrap(),
2681             &mut Vec::new(),
2682             &mut Default::default(),
2683         );
2684     }
2685
2686     fn note_obligation_cause_code<T>(
2687         &self,
2688         err: &mut Diagnostic,
2689         predicate: T,
2690         param_env: ty::ParamEnv<'tcx>,
2691         cause_code: &ObligationCauseCode<'tcx>,
2692         obligated_types: &mut Vec<Ty<'tcx>>,
2693         seen_requirements: &mut FxHashSet<DefId>,
2694     ) where
2695         T: ToPredicate<'tcx>,
2696     {
2697         let tcx = self.tcx;
2698         let predicate = predicate.to_predicate(tcx);
2699         match *cause_code {
2700             ObligationCauseCode::ExprAssignable
2701             | ObligationCauseCode::MatchExpressionArm { .. }
2702             | ObligationCauseCode::Pattern { .. }
2703             | ObligationCauseCode::IfExpression { .. }
2704             | ObligationCauseCode::IfExpressionWithNoElse
2705             | ObligationCauseCode::MainFunctionType
2706             | ObligationCauseCode::StartFunctionType
2707             | ObligationCauseCode::IntrinsicType
2708             | ObligationCauseCode::MethodReceiver
2709             | ObligationCauseCode::ReturnNoExpression
2710             | ObligationCauseCode::UnifyReceiver(..)
2711             | ObligationCauseCode::OpaqueType
2712             | ObligationCauseCode::MiscObligation
2713             | ObligationCauseCode::WellFormed(..)
2714             | ObligationCauseCode::MatchImpl(..)
2715             | ObligationCauseCode::ReturnType
2716             | ObligationCauseCode::ReturnValue(_)
2717             | ObligationCauseCode::BlockTailExpression(_)
2718             | ObligationCauseCode::AwaitableExpr(_)
2719             | ObligationCauseCode::ForLoopIterator
2720             | ObligationCauseCode::QuestionMark
2721             | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2722             | ObligationCauseCode::LetElse
2723             | ObligationCauseCode::BinOp { .. }
2724             | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2725             | ObligationCauseCode::RustCall => {}
2726             ObligationCauseCode::SliceOrArrayElem => {
2727                 err.note("slice and array elements must have `Sized` type");
2728             }
2729             ObligationCauseCode::TupleElem => {
2730                 err.note("only the last element of a tuple may have a dynamically sized type");
2731             }
2732             ObligationCauseCode::ProjectionWf(data) => {
2733                 err.note(&format!("required so that the projection `{data}` is well-formed"));
2734             }
2735             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2736                 err.note(&format!(
2737                     "required so that reference `{ref_ty}` does not outlive its referent"
2738                 ));
2739             }
2740             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2741                 err.note(&format!(
2742                     "required so that the lifetime bound of `{}` for `{}` is satisfied",
2743                     region, object_ty,
2744                 ));
2745             }
2746             ObligationCauseCode::ItemObligation(_)
2747             | ObligationCauseCode::ExprItemObligation(..) => {
2748                 // We hold the `DefId` of the item introducing the obligation, but displaying it
2749                 // doesn't add user usable information. It always point at an associated item.
2750             }
2751             ObligationCauseCode::BindingObligation(item_def_id, span)
2752             | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2753                 let item_name = tcx.def_path_str(item_def_id);
2754                 let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2755                 let mut multispan = MultiSpan::from(span);
2756                 let sm = tcx.sess.source_map();
2757                 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2758                     let same_line =
2759                         match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2760                             (Ok(l), Ok(r)) => l.line == r.line,
2761                             _ => true,
2762                         };
2763                     if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2764                         multispan.push_span_label(ident.span, "required by a bound in this");
2765                     }
2766                 }
2767                 let descr = format!("required by a bound in `{item_name}`");
2768                 if span.is_visible(sm) {
2769                     let msg = format!("required by this bound in `{short_item_name}`");
2770                     multispan.push_span_label(span, msg);
2771                     err.span_note(multispan, &descr);
2772                 } else {
2773                     err.span_note(tcx.def_span(item_def_id), &descr);
2774                 }
2775             }
2776             ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2777                 let (concrete_ty, concrete_file) =
2778                     self.tcx.short_ty_string(self.resolve_vars_if_possible(concrete_ty));
2779                 let (object_ty, object_file) =
2780                     self.tcx.short_ty_string(self.resolve_vars_if_possible(object_ty));
2781                 err.note(&with_forced_trimmed_paths!(format!(
2782                     "required for the cast from `{concrete_ty}` to the object type `{object_ty}`",
2783                 )));
2784                 if let Some(file) = concrete_file {
2785                     err.note(&format!(
2786                         "the full name for the casted type has been written to '{}'",
2787                         file.display(),
2788                     ));
2789                 }
2790                 if let Some(file) = object_file {
2791                     err.note(&format!(
2792                         "the full name for the object type has been written to '{}'",
2793                         file.display(),
2794                     ));
2795                 }
2796             }
2797             ObligationCauseCode::Coercion { source: _, target } => {
2798                 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2799             }
2800             ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2801                 err.note(
2802                     "the `Copy` trait is required because this value will be copied for each element of the array",
2803                 );
2804
2805                 if is_const_fn {
2806                     err.help(
2807                         "consider creating a new `const` item and initializing it with the result \
2808                         of the function call to be used in the repeat position, like \
2809                         `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2810                     );
2811                 }
2812
2813                 if self.tcx.sess.is_nightly_build() && is_const_fn {
2814                     err.help(
2815                         "create an inline `const` block, see RFC #2920 \
2816                          <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2817                     );
2818                 }
2819             }
2820             ObligationCauseCode::VariableType(hir_id) => {
2821                 let parent_node = self.tcx.hir().parent_id(hir_id);
2822                 match self.tcx.hir().find(parent_node) {
2823                     Some(Node::Local(hir::Local { ty: Some(ty), .. })) => {
2824                         err.span_suggestion_verbose(
2825                             ty.span.shrink_to_lo(),
2826                             "consider borrowing here",
2827                             "&",
2828                             Applicability::MachineApplicable,
2829                         );
2830                         err.note("all local variables must have a statically known size");
2831                     }
2832                     Some(Node::Local(hir::Local {
2833                         init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2834                         ..
2835                     })) => {
2836                         // When encountering an assignment of an unsized trait, like
2837                         // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2838                         // order to use have a slice instead.
2839                         err.span_suggestion_verbose(
2840                             span.shrink_to_lo(),
2841                             "consider borrowing here",
2842                             "&",
2843                             Applicability::MachineApplicable,
2844                         );
2845                         err.note("all local variables must have a statically known size");
2846                     }
2847                     Some(Node::Param(param)) => {
2848                         err.span_suggestion_verbose(
2849                             param.ty_span.shrink_to_lo(),
2850                             "function arguments must have a statically known size, borrowed types \
2851                             always have a known size",
2852                             "&",
2853                             Applicability::MachineApplicable,
2854                         );
2855                     }
2856                     _ => {
2857                         err.note("all local variables must have a statically known size");
2858                     }
2859                 }
2860                 if !self.tcx.features().unsized_locals {
2861                     err.help("unsized locals are gated as an unstable feature");
2862                 }
2863             }
2864             ObligationCauseCode::SizedArgumentType(sp) => {
2865                 if let Some(span) = sp {
2866                     if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder()
2867                         && let ty::Clause::Trait(trait_pred) = clause
2868                         && let ty::Dynamic(..) = trait_pred.self_ty().kind()
2869                     {
2870                         let span = if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2871                             && snippet.starts_with("dyn ")
2872                         {
2873                             let pos = snippet.len() - snippet[3..].trim_start().len();
2874                             span.with_hi(span.lo() + BytePos(pos as u32))
2875                         } else {
2876                             span.shrink_to_lo()
2877                         };
2878                         err.span_suggestion_verbose(
2879                             span,
2880                             "you can use `impl Trait` as the argument type",
2881                             "impl ".to_string(),
2882                             Applicability::MaybeIncorrect,
2883                         );
2884                     }
2885                     err.span_suggestion_verbose(
2886                         span.shrink_to_lo(),
2887                         "function arguments must have a statically known size, borrowed types \
2888                          always have a known size",
2889                         "&",
2890                         Applicability::MachineApplicable,
2891                     );
2892                 } else {
2893                     err.note("all function arguments must have a statically known size");
2894                 }
2895                 if tcx.sess.opts.unstable_features.is_nightly_build()
2896                     && !self.tcx.features().unsized_fn_params
2897                 {
2898                     err.help("unsized fn params are gated as an unstable feature");
2899                 }
2900             }
2901             ObligationCauseCode::SizedReturnType => {
2902                 err.note("the return type of a function must have a statically known size");
2903             }
2904             ObligationCauseCode::SizedYieldType => {
2905                 err.note("the yield type of a generator must have a statically known size");
2906             }
2907             ObligationCauseCode::SizedBoxType => {
2908                 err.note("the type of a box expression must have a statically known size");
2909             }
2910             ObligationCauseCode::AssignmentLhsSized => {
2911                 err.note("the left-hand-side of an assignment must have a statically known size");
2912             }
2913             ObligationCauseCode::TupleInitializerSized => {
2914                 err.note("tuples must have a statically known size to be initialized");
2915             }
2916             ObligationCauseCode::StructInitializerSized => {
2917                 err.note("structs must have a statically known size to be initialized");
2918             }
2919             ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2920                 match *item {
2921                     AdtKind::Struct => {
2922                         if last {
2923                             err.note(
2924                                 "the last field of a packed struct may only have a \
2925                                 dynamically sized type if it does not need drop to be run",
2926                             );
2927                         } else {
2928                             err.note(
2929                                 "only the last field of a struct may have a dynamically sized type",
2930                             );
2931                         }
2932                     }
2933                     AdtKind::Union => {
2934                         err.note("no field of a union may have a dynamically sized type");
2935                     }
2936                     AdtKind::Enum => {
2937                         err.note("no field of an enum variant may have a dynamically sized type");
2938                     }
2939                 }
2940                 err.help("change the field's type to have a statically known size");
2941                 err.span_suggestion(
2942                     span.shrink_to_lo(),
2943                     "borrowed types always have a statically known size",
2944                     "&",
2945                     Applicability::MachineApplicable,
2946                 );
2947                 err.multipart_suggestion(
2948                     "the `Box` type always has a statically known size and allocates its contents \
2949                      in the heap",
2950                     vec![
2951                         (span.shrink_to_lo(), "Box<".to_string()),
2952                         (span.shrink_to_hi(), ">".to_string()),
2953                     ],
2954                     Applicability::MachineApplicable,
2955                 );
2956             }
2957             ObligationCauseCode::ConstSized => {
2958                 err.note("constant expressions must have a statically known size");
2959             }
2960             ObligationCauseCode::InlineAsmSized => {
2961                 err.note("all inline asm arguments must have a statically known size");
2962             }
2963             ObligationCauseCode::ConstPatternStructural => {
2964                 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2965             }
2966             ObligationCauseCode::SharedStatic => {
2967                 err.note("shared static variables must have a type that implements `Sync`");
2968             }
2969             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2970                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2971                 let ty = parent_trait_ref.skip_binder().self_ty();
2972                 if parent_trait_ref.references_error() {
2973                     // NOTE(eddyb) this was `.cancel()`, but `err`
2974                     // is borrowed, so we can't fully defuse it.
2975                     err.downgrade_to_delayed_bug();
2976                     return;
2977                 }
2978
2979                 // If the obligation for a tuple is set directly by a Generator or Closure,
2980                 // then the tuple must be the one containing capture types.
2981                 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2982                     false
2983                 } else {
2984                     if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2985                     {
2986                         let parent_trait_ref =
2987                             self.resolve_vars_if_possible(data.parent_trait_pred);
2988                         let nested_ty = parent_trait_ref.skip_binder().self_ty();
2989                         matches!(nested_ty.kind(), ty::Generator(..))
2990                             || matches!(nested_ty.kind(), ty::Closure(..))
2991                     } else {
2992                         false
2993                     }
2994                 };
2995
2996                 let identity_future = tcx.require_lang_item(LangItem::IdentityFuture, None);
2997
2998                 // Don't print the tuple of capture types
2999                 'print: {
3000                     if !is_upvar_tys_infer_tuple {
3001                         let msg = with_forced_trimmed_paths!(format!(
3002                             "required because it appears within the type `{ty}`",
3003                         ));
3004                         match ty.kind() {
3005                             ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
3006                                 Some(ident) => err.span_note(ident.span, &msg),
3007                                 None => err.note(&msg),
3008                             },
3009                             ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
3010                                 // Avoid printing the future from `core::future::identity_future`, it's not helpful
3011                                 if tcx.parent(*def_id) == identity_future {
3012                                     break 'print;
3013                                 }
3014
3015                                 // If the previous type is `identity_future`, this is the future generated by the body of an async function.
3016                                 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
3017                                 let is_future = tcx.ty_is_opaque_future(ty);
3018                                 debug!(
3019                                     ?obligated_types,
3020                                     ?is_future,
3021                                     "note_obligation_cause_code: check for async fn"
3022                                 );
3023                                 if is_future
3024                                     && obligated_types.last().map_or(false, |ty| match ty.kind() {
3025                                         ty::Generator(last_def_id, ..) => {
3026                                             tcx.generator_is_async(*last_def_id)
3027                                         }
3028                                         _ => false,
3029                                     })
3030                                 {
3031                                     break 'print;
3032                                 }
3033                                 err.span_note(self.tcx.def_span(def_id), &msg)
3034                             }
3035                             ty::GeneratorWitness(bound_tys) => {
3036                                 use std::fmt::Write;
3037
3038                                 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
3039                                 // Maybe we should just remove this note altogether?
3040                                 // FIXME: only print types which don't meet the trait requirement
3041                                 let mut msg =
3042                                     "required because it captures the following types: ".to_owned();
3043                                 for ty in bound_tys.skip_binder() {
3044                                     with_forced_trimmed_paths!(write!(msg, "`{}`, ", ty).unwrap());
3045                                 }
3046                                 err.note(msg.trim_end_matches(", "))
3047                             }
3048                             ty::GeneratorWitnessMIR(def_id, substs) => {
3049                                 use std::fmt::Write;
3050
3051                                 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
3052                                 // Maybe we should just remove this note altogether?
3053                                 // FIXME: only print types which don't meet the trait requirement
3054                                 let mut msg =
3055                                     "required because it captures the following types: ".to_owned();
3056                                 for bty in tcx.generator_hidden_types(*def_id) {
3057                                     let ty = bty.subst(tcx, substs);
3058                                     write!(msg, "`{}`, ", ty).unwrap();
3059                                 }
3060                                 err.note(msg.trim_end_matches(", "))
3061                             }
3062                             ty::Generator(def_id, _, _) => {
3063                                 let sp = self.tcx.def_span(def_id);
3064
3065                                 // Special-case this to say "async block" instead of `[static generator]`.
3066                                 let kind = tcx.generator_kind(def_id).unwrap().descr();
3067                                 err.span_note(
3068                                     sp,
3069                                     with_forced_trimmed_paths!(&format!(
3070                                         "required because it's used within this {kind}",
3071                                     )),
3072                                 )
3073                             }
3074                             ty::Closure(def_id, _) => err.span_note(
3075                                 self.tcx.def_span(def_id),
3076                                 "required because it's used within this closure",
3077                             ),
3078                             _ => err.note(&msg),
3079                         };
3080                     }
3081                 }
3082
3083                 obligated_types.push(ty);
3084
3085                 let parent_predicate = parent_trait_ref;
3086                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
3087                     // #74711: avoid a stack overflow
3088                     ensure_sufficient_stack(|| {
3089                         self.note_obligation_cause_code(
3090                             err,
3091                             parent_predicate,
3092                             param_env,
3093                             &data.parent_code,
3094                             obligated_types,
3095                             seen_requirements,
3096                         )
3097                     });
3098                 } else {
3099                     ensure_sufficient_stack(|| {
3100                         self.note_obligation_cause_code(
3101                             err,
3102                             parent_predicate,
3103                             param_env,
3104                             cause_code.peel_derives(),
3105                             obligated_types,
3106                             seen_requirements,
3107                         )
3108                     });
3109                 }
3110             }
3111             ObligationCauseCode::ImplDerivedObligation(ref data) => {
3112                 let mut parent_trait_pred =
3113                     self.resolve_vars_if_possible(data.derived.parent_trait_pred);
3114                 parent_trait_pred.remap_constness_diag(param_env);
3115                 let parent_def_id = parent_trait_pred.def_id();
3116                 let (self_ty, file) =
3117                     self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
3118                 let msg = format!(
3119                     "required for `{self_ty}` to implement `{}`",
3120                     parent_trait_pred.print_modifiers_and_trait_path()
3121                 );
3122                 let mut is_auto_trait = false;
3123                 match self.tcx.hir().get_if_local(data.impl_def_id) {
3124                     Some(Node::Item(hir::Item {
3125                         kind: hir::ItemKind::Trait(is_auto, ..),
3126                         ident,
3127                         ..
3128                     })) => {
3129                         // FIXME: we should do something else so that it works even on crate foreign
3130                         // auto traits.
3131                         is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
3132                         err.span_note(ident.span, &msg);
3133                     }
3134                     Some(Node::Item(hir::Item {
3135                         kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
3136                         ..
3137                     })) => {
3138                         let mut spans = Vec::with_capacity(2);
3139                         if let Some(trait_ref) = of_trait {
3140                             spans.push(trait_ref.path.span);
3141                         }
3142                         spans.push(self_ty.span);
3143                         let mut spans: MultiSpan = spans.into();
3144                         if matches!(
3145                             self_ty.span.ctxt().outer_expn_data().kind,
3146                             ExpnKind::Macro(MacroKind::Derive, _)
3147                         ) || matches!(
3148                             of_trait.as_ref().map(|t| t.path.span.ctxt().outer_expn_data().kind),
3149                             Some(ExpnKind::Macro(MacroKind::Derive, _))
3150                         ) {
3151                             spans.push_span_label(
3152                                 data.span,
3153                                 "unsatisfied trait bound introduced in this `derive` macro",
3154                             );
3155                         } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
3156                             spans.push_span_label(
3157                                 data.span,
3158                                 "unsatisfied trait bound introduced here",
3159                             );
3160                         }
3161                         err.span_note(spans, &msg);
3162                     }
3163                     _ => {
3164                         err.note(&msg);
3165                     }
3166                 };
3167
3168                 if let Some(file) = file {
3169                     err.note(&format!(
3170                         "the full type name has been written to '{}'",
3171                         file.display(),
3172                     ));
3173                 }
3174                 let mut parent_predicate = parent_trait_pred;
3175                 let mut data = &data.derived;
3176                 let mut count = 0;
3177                 seen_requirements.insert(parent_def_id);
3178                 if is_auto_trait {
3179                     // We don't want to point at the ADT saying "required because it appears within
3180                     // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
3181                     while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
3182                         &*data.parent_code
3183                     {
3184                         let child_trait_ref =
3185                             self.resolve_vars_if_possible(derived.parent_trait_pred);
3186                         let child_def_id = child_trait_ref.def_id();
3187                         if seen_requirements.insert(child_def_id) {
3188                             break;
3189                         }
3190                         data = derived;
3191                         parent_predicate = child_trait_ref.to_predicate(tcx);
3192                         parent_trait_pred = child_trait_ref;
3193                     }
3194                 }
3195                 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
3196                     // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
3197                     let child_trait_pred =
3198                         self.resolve_vars_if_possible(child.derived.parent_trait_pred);
3199                     let child_def_id = child_trait_pred.def_id();
3200                     if seen_requirements.insert(child_def_id) {
3201                         break;
3202                     }
3203                     count += 1;
3204                     data = &child.derived;
3205                     parent_predicate = child_trait_pred.to_predicate(tcx);
3206                     parent_trait_pred = child_trait_pred;
3207                 }
3208                 if count > 0 {
3209                     err.note(&format!(
3210                         "{} redundant requirement{} hidden",
3211                         count,
3212                         pluralize!(count)
3213                     ));
3214                     let (self_ty, file) =
3215                         self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
3216                     err.note(&format!(
3217                         "required for `{self_ty}` to implement `{}`",
3218                         parent_trait_pred.print_modifiers_and_trait_path()
3219                     ));
3220                     if let Some(file) = file {
3221                         err.note(&format!(
3222                             "the full type name has been written to '{}'",
3223                             file.display(),
3224                         ));
3225                     }
3226                 }
3227                 // #74711: avoid a stack overflow
3228                 ensure_sufficient_stack(|| {
3229                     self.note_obligation_cause_code(
3230                         err,
3231                         parent_predicate,
3232                         param_env,
3233                         &data.parent_code,
3234                         obligated_types,
3235                         seen_requirements,
3236                     )
3237                 });
3238             }
3239             ObligationCauseCode::DerivedObligation(ref data) => {
3240                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3241                 let parent_predicate = parent_trait_ref;
3242                 // #74711: avoid a stack overflow
3243                 ensure_sufficient_stack(|| {
3244                     self.note_obligation_cause_code(
3245                         err,
3246                         parent_predicate,
3247                         param_env,
3248                         &data.parent_code,
3249                         obligated_types,
3250                         seen_requirements,
3251                     )
3252                 });
3253             }
3254             ObligationCauseCode::FunctionArgumentObligation {
3255                 arg_hir_id,
3256                 call_hir_id,
3257                 ref parent_code,
3258                 ..
3259             } => {
3260                 self.note_function_argument_obligation(
3261                     arg_hir_id,
3262                     err,
3263                     parent_code,
3264                     param_env,
3265                     predicate,
3266                     call_hir_id,
3267                 );
3268                 ensure_sufficient_stack(|| {
3269                     self.note_obligation_cause_code(
3270                         err,
3271                         predicate,
3272                         param_env,
3273                         &parent_code,
3274                         obligated_types,
3275                         seen_requirements,
3276                     )
3277                 });
3278             }
3279             ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
3280                 let item_name = self.tcx.item_name(trait_item_def_id);
3281                 let msg = format!(
3282                     "the requirement `{predicate}` appears on the `impl`'s {kind} \
3283                      `{item_name}` but not on the corresponding trait's {kind}",
3284                 );
3285                 let sp = self
3286                     .tcx
3287                     .opt_item_ident(trait_item_def_id)
3288                     .map(|i| i.span)
3289                     .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
3290                 let mut assoc_span: MultiSpan = sp.into();
3291                 assoc_span.push_span_label(
3292                     sp,
3293                     format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
3294                 );
3295                 if let Some(ident) = self
3296                     .tcx
3297                     .opt_associated_item(trait_item_def_id)
3298                     .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
3299                 {
3300                     assoc_span.push_span_label(ident.span, "in this trait");
3301                 }
3302                 err.span_note(assoc_span, &msg);
3303             }
3304             ObligationCauseCode::TrivialBound => {
3305                 err.help("see issue #48214");
3306                 if tcx.sess.opts.unstable_features.is_nightly_build() {
3307                     err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
3308                 }
3309             }
3310             ObligationCauseCode::OpaqueReturnType(expr_info) => {
3311                 if let Some((expr_ty, expr_span)) = expr_info {
3312                     let expr_ty = with_forced_trimmed_paths!(self.ty_to_string(expr_ty));
3313                     err.span_label(
3314                         expr_span,
3315                         with_forced_trimmed_paths!(format!(
3316                             "return type was inferred to be `{expr_ty}` here",
3317                         )),
3318                     );
3319                 }
3320             }
3321         }
3322     }
3323
3324     #[instrument(
3325         level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
3326     )]
3327     fn suggest_await_before_try(
3328         &self,
3329         err: &mut Diagnostic,
3330         obligation: &PredicateObligation<'tcx>,
3331         trait_pred: ty::PolyTraitPredicate<'tcx>,
3332         span: Span,
3333     ) {
3334         if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) {
3335             let body = self.tcx.hir().body(body_id);
3336             if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
3337                 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
3338
3339                 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
3340                 let impls_future = self.type_implements_trait(
3341                     future_trait,
3342                     [self.tcx.erase_late_bound_regions(self_ty)],
3343                     obligation.param_env,
3344                 );
3345                 if !impls_future.must_apply_modulo_regions() {
3346                     return;
3347                 }
3348
3349                 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
3350                 // `<T as Future>::Output`
3351                 let projection_ty = trait_pred.map_bound(|trait_pred| {
3352                     self.tcx.mk_projection(
3353                         item_def_id,
3354                         // Future::Output has no substs
3355                         [trait_pred.self_ty()],
3356                     )
3357                 });
3358                 let InferOk { value: projection_ty, .. } =
3359                     self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
3360
3361                 debug!(
3362                     normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
3363                 );
3364                 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3365                     obligation.param_env,
3366                     trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3367                 );
3368                 debug!(try_trait_obligation = ?try_obligation);
3369                 if self.predicate_may_hold(&try_obligation)
3370                     && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3371                     && snippet.ends_with('?')
3372                 {
3373                     err.span_suggestion_verbose(
3374                         span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3375                         "consider `await`ing on the `Future`",
3376                         ".await",
3377                         Applicability::MaybeIncorrect,
3378                     );
3379                 }
3380             }
3381         }
3382     }
3383
3384     fn suggest_floating_point_literal(
3385         &self,
3386         obligation: &PredicateObligation<'tcx>,
3387         err: &mut Diagnostic,
3388         trait_ref: &ty::PolyTraitRef<'tcx>,
3389     ) {
3390         let rhs_span = match obligation.cause.code() {
3391             ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3392             _ => return,
3393         };
3394         if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3395             && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3396         {
3397             err.span_suggestion_verbose(
3398                 rhs_span.shrink_to_hi(),
3399                 "consider using a floating-point literal by writing it with `.0`",
3400                 ".0",
3401                 Applicability::MaybeIncorrect,
3402             );
3403         }
3404     }
3405
3406     fn suggest_derive(
3407         &self,
3408         obligation: &PredicateObligation<'tcx>,
3409         err: &mut Diagnostic,
3410         trait_pred: ty::PolyTraitPredicate<'tcx>,
3411     ) {
3412         let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3413             return;
3414         };
3415         let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3416             ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3417             _ => return,
3418         };
3419         let can_derive = {
3420             let is_derivable_trait = match diagnostic_name {
3421                 sym::Default => !adt.is_enum(),
3422                 sym::PartialEq | sym::PartialOrd => {
3423                     let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3424                     trait_pred.skip_binder().self_ty() == rhs_ty
3425                 }
3426                 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3427                 _ => false,
3428             };
3429             is_derivable_trait &&
3430                 // Ensure all fields impl the trait.
3431                 adt.all_fields().all(|field| {
3432                     let field_ty = field.ty(self.tcx, substs);
3433                     let trait_substs = match diagnostic_name {
3434                         sym::PartialEq | sym::PartialOrd => {
3435                             Some(field_ty)
3436                         }
3437                         _ => None,
3438                     };
3439                     let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3440                         trait_ref: self.tcx.mk_trait_ref(
3441                             trait_pred.def_id(),
3442                             [field_ty].into_iter().chain(trait_substs),
3443                         ),
3444                         ..*tr
3445                     });
3446                     let field_obl = Obligation::new(
3447                         self.tcx,
3448                         obligation.cause.clone(),
3449                         obligation.param_env,
3450                         trait_pred,
3451                     );
3452                     self.predicate_must_hold_modulo_regions(&field_obl)
3453                 })
3454         };
3455         if can_derive {
3456             err.span_suggestion_verbose(
3457                 self.tcx.def_span(adt.did()).shrink_to_lo(),
3458                 &format!(
3459                     "consider annotating `{}` with `#[derive({})]`",
3460                     trait_pred.skip_binder().self_ty(),
3461                     diagnostic_name,
3462                 ),
3463                 format!("#[derive({})]\n", diagnostic_name),
3464                 Applicability::MaybeIncorrect,
3465             );
3466         }
3467     }
3468
3469     fn suggest_dereferencing_index(
3470         &self,
3471         obligation: &PredicateObligation<'tcx>,
3472         err: &mut Diagnostic,
3473         trait_pred: ty::PolyTraitPredicate<'tcx>,
3474     ) {
3475         if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3476             && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3477             && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3478             && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3479             && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3480         {
3481             err.span_suggestion_verbose(
3482                 obligation.cause.span.shrink_to_lo(),
3483             "dereference this index",
3484             '*',
3485                 Applicability::MachineApplicable,
3486             );
3487         }
3488     }
3489     fn note_function_argument_obligation(
3490         &self,
3491         arg_hir_id: HirId,
3492         err: &mut Diagnostic,
3493         parent_code: &ObligationCauseCode<'tcx>,
3494         param_env: ty::ParamEnv<'tcx>,
3495         failed_pred: ty::Predicate<'tcx>,
3496         call_hir_id: HirId,
3497     ) {
3498         let tcx = self.tcx;
3499         let hir = tcx.hir();
3500         if let Some(Node::Expr(expr)) = hir.find(arg_hir_id)
3501             && let Some(typeck_results) = &self.typeck_results
3502         {
3503             if let hir::Expr { kind: hir::ExprKind::Block(..), .. } = expr {
3504                 let expr = expr.peel_blocks();
3505                 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
3506                 let span = expr.span;
3507                 if Some(span) != err.span.primary_span() {
3508                     err.span_label(
3509                         span,
3510                         if ty.references_error() {
3511                             String::new()
3512                         } else {
3513                             let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3514                             format!("this tail expression is of type `{ty}`")
3515                         },
3516                     );
3517                 }
3518             }
3519
3520             // FIXME: visit the ty to see if there's any closure involved, and if there is,
3521             // check whether its evaluated return type is the same as the one corresponding
3522             // to an associated type (as seen from `trait_pred`) in the predicate. Like in
3523             // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
3524             let mut type_diffs = vec![];
3525
3526             if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = parent_code.deref()
3527                 && let Some(node_substs) = typeck_results.node_substs_opt(call_hir_id)
3528                 && let where_clauses = self.tcx.predicates_of(def_id).instantiate(self.tcx, node_substs)
3529                 && let Some(where_pred) = where_clauses.predicates.get(*idx)
3530             {
3531                 if let Some(where_pred) = where_pred.to_opt_poly_trait_pred()
3532                     && let Some(failed_pred) = failed_pred.to_opt_poly_trait_pred()
3533                 {
3534                     let mut c = CollectAllMismatches {
3535                         infcx: self.infcx,
3536                         param_env,
3537                         errors: vec![],
3538                     };
3539                     if let Ok(_) = c.relate(where_pred, failed_pred) {
3540                         type_diffs = c.errors;
3541                     }
3542                 } else if let Some(where_pred) = where_pred.to_opt_poly_projection_pred()
3543                     && let Some(failed_pred) = failed_pred.to_opt_poly_projection_pred()
3544                     && let Some(found) = failed_pred.skip_binder().term.ty()
3545                 {
3546                     type_diffs = vec![
3547                         Sorts(ty::error::ExpectedFound {
3548                             expected: self.tcx.mk_ty(ty::Alias(ty::Projection, where_pred.skip_binder().projection_ty)),
3549                             found,
3550                         }),
3551                     ];
3552                 }
3553             }
3554             if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3555                 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3556                 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3557                 && let parent_hir_id = self.tcx.hir().parent_id(binding.hir_id)
3558                 && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3559                 && let Some(binding_expr) = local.init
3560             {
3561                 // If the expression we're calling on is a binding, we want to point at the
3562                 // `let` when talking about the type. Otherwise we'll point at every part
3563                 // of the method chain with the type.
3564                 self.point_at_chain(binding_expr, &typeck_results, type_diffs, param_env, err);
3565             } else {
3566                 self.point_at_chain(expr, &typeck_results, type_diffs, param_env, err);
3567             }
3568         }
3569         let call_node = hir.find(call_hir_id);
3570         if let Some(Node::Expr(hir::Expr {
3571             kind: hir::ExprKind::MethodCall(path, rcvr, ..), ..
3572         })) = call_node
3573         {
3574             if Some(rcvr.span) == err.span.primary_span() {
3575                 err.replace_span_with(path.ident.span, true);
3576             }
3577         }
3578         if let Some(Node::Expr(hir::Expr {
3579             kind:
3580                 hir::ExprKind::Call(hir::Expr { span, .. }, _)
3581                 | hir::ExprKind::MethodCall(hir::PathSegment { ident: Ident { span, .. }, .. }, ..),
3582             ..
3583         })) = hir.find(call_hir_id)
3584         {
3585             if Some(*span) != err.span.primary_span() {
3586                 err.span_label(*span, "required by a bound introduced by this call");
3587             }
3588         }
3589     }
3590
3591     fn point_at_chain(
3592         &self,
3593         expr: &hir::Expr<'_>,
3594         typeck_results: &TypeckResults<'tcx>,
3595         type_diffs: Vec<TypeError<'tcx>>,
3596         param_env: ty::ParamEnv<'tcx>,
3597         err: &mut Diagnostic,
3598     ) {
3599         let mut primary_spans = vec![];
3600         let mut span_labels = vec![];
3601
3602         let tcx = self.tcx;
3603
3604         let mut print_root_expr = true;
3605         let mut assocs = vec![];
3606         let mut expr = expr;
3607         let mut prev_ty = self.resolve_vars_if_possible(
3608             typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3609         );
3610         while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, span) = expr.kind {
3611             // Point at every method call in the chain with the resulting type.
3612             // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3613             //               ^^^^^^ ^^^^^^^^^^^
3614             expr = rcvr_expr;
3615             let assocs_in_this_method =
3616                 self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
3617             assocs.push(assocs_in_this_method);
3618             prev_ty = self.resolve_vars_if_possible(
3619                 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3620             );
3621
3622             if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3623                 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3624                 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3625                 && let Some(parent) = self.tcx.hir().find_parent(binding.hir_id)
3626             {
3627                 // We've reached the root of the method call chain...
3628                 if let hir::Node::Local(local) = parent
3629                     && let Some(binding_expr) = local.init
3630                 {
3631                     // ...and it is a binding. Get the binding creation and continue the chain.
3632                     expr = binding_expr;
3633                 }
3634                 if let hir::Node::Param(param) = parent {
3635                     // ...and it is a an fn argument.
3636                     let prev_ty = self.resolve_vars_if_possible(
3637                         typeck_results.node_type_opt(param.hir_id).unwrap_or(tcx.ty_error()),
3638                     );
3639                     let assocs_in_this_method = self.probe_assoc_types_at_expr(&type_diffs, param.ty_span, prev_ty, param.hir_id, param_env);
3640                     if assocs_in_this_method.iter().any(|a| a.is_some()) {
3641                         assocs.push(assocs_in_this_method);
3642                         print_root_expr = false;
3643                     }
3644                     break;
3645                 }
3646             }
3647         }
3648         // We want the type before deref coercions, otherwise we talk about `&[_]`
3649         // instead of `Vec<_>`.
3650         if let Some(ty) = typeck_results.expr_ty_opt(expr) && print_root_expr {
3651             let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3652             // Point at the root expression
3653             // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3654             // ^^^^^^^^^^^^^
3655             span_labels.push((expr.span, format!("this expression has type `{ty}`")));
3656         };
3657         // Only show this if it is not a "trivial" expression (not a method
3658         // chain) and there are associated types to talk about.
3659         let mut assocs = assocs.into_iter().peekable();
3660         while let Some(assocs_in_method) = assocs.next() {
3661             let Some(prev_assoc_in_method) = assocs.peek() else {
3662                 for entry in assocs_in_method {
3663                     let Some((span, (assoc, ty))) = entry else { continue; };
3664                     if primary_spans.is_empty() || type_diffs.iter().any(|diff| {
3665                         let Sorts(expected_found) = diff else { return false; };
3666                         self.can_eq(param_env, expected_found.found, ty).is_ok()
3667                     }) {
3668                         // FIXME: this doesn't quite work for `Iterator::collect`
3669                         // because we have `Vec<i32>` and `()`, but we'd want `i32`
3670                         // to point at the `.into_iter()` call, but as long as we
3671                         // still point at the other method calls that might have
3672                         // introduced the issue, this is fine for now.
3673                         primary_spans.push(span);
3674                     }
3675                     span_labels.push((
3676                         span,
3677                         with_forced_trimmed_paths!(format!(
3678                             "`{}` is `{ty}` here",
3679                             self.tcx.def_path_str(assoc),
3680                         )),
3681                     ));
3682                 }
3683                 break;
3684             };
3685             for (entry, prev_entry) in
3686                 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
3687             {
3688                 match (entry, prev_entry) {
3689                     (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
3690                         let ty_str = with_forced_trimmed_paths!(self.ty_to_string(ty));
3691
3692                         let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
3693                         if self.can_eq(param_env, ty, *prev_ty).is_err() {
3694                             if type_diffs.iter().any(|diff| {
3695                                 let Sorts(expected_found) = diff else { return false; };
3696                                 self.can_eq(param_env, expected_found.found, ty).is_ok()
3697                             }) {
3698                                 primary_spans.push(span);
3699                             }
3700                             span_labels
3701                                 .push((span, format!("`{assoc}` changed to `{ty_str}` here")));
3702                         } else {
3703                             span_labels.push((span, format!("`{assoc}` remains `{ty_str}` here")));
3704                         }
3705                     }
3706                     (Some((span, (assoc, ty))), None) => {
3707                         span_labels.push((
3708                             span,
3709                             with_forced_trimmed_paths!(format!(
3710                                 "`{}` is `{}` here",
3711                                 self.tcx.def_path_str(assoc),
3712                                 self.ty_to_string(ty),
3713                             )),
3714                         ));
3715                     }
3716                     (None, Some(_)) | (None, None) => {}
3717                 }
3718             }
3719         }
3720         if !primary_spans.is_empty() {
3721             let mut multi_span: MultiSpan = primary_spans.into();
3722             for (span, label) in span_labels {
3723                 multi_span.push_span_label(span, label);
3724             }
3725             err.span_note(
3726                 multi_span,
3727                 "the method call chain might not have had the expected associated types",
3728             );
3729         }
3730     }
3731
3732     fn probe_assoc_types_at_expr(
3733         &self,
3734         type_diffs: &[TypeError<'tcx>],
3735         span: Span,
3736         prev_ty: Ty<'tcx>,
3737         body_id: hir::HirId,
3738         param_env: ty::ParamEnv<'tcx>,
3739     ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
3740         let ocx = ObligationCtxt::new_in_snapshot(self.infcx);
3741         let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
3742         for diff in type_diffs {
3743             let Sorts(expected_found) = diff else { continue; };
3744             let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else { continue; };
3745
3746             let origin = TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span };
3747             let trait_def_id = proj.trait_def_id(self.tcx);
3748             // Make `Self` be equivalent to the type of the call chain
3749             // expression we're looking at now, so that we can tell what
3750             // for example `Iterator::Item` is at this point in the chain.
3751             let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
3752                 match param.kind {
3753                     ty::GenericParamDefKind::Type { .. } => {
3754                         if param.index == 0 {
3755                             return prev_ty.into();
3756                         }
3757                     }
3758                     ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Const { .. } => {}
3759                 }
3760                 self.var_for_def(span, param)
3761             });
3762             // This will hold the resolved type of the associated type, if the
3763             // current expression implements the trait that associated type is
3764             // in. For example, this would be what `Iterator::Item` is here.
3765             let ty_var = self.infcx.next_ty_var(origin);
3766             // This corresponds to `<ExprTy as Iterator>::Item = _`.
3767             let projection = ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::Projection(
3768                 ty::ProjectionPredicate {
3769                     projection_ty: self.tcx.mk_alias_ty(proj.def_id, substs),
3770                     term: ty_var.into(),
3771                 },
3772             )));
3773             let body_def_id = self.tcx.hir().enclosing_body_owner(body_id);
3774             // Add `<ExprTy as Iterator>::Item = _` obligation.
3775             ocx.register_obligation(Obligation::misc(
3776                 self.tcx,
3777                 span,
3778                 body_def_id,
3779                 param_env,
3780                 projection,
3781             ));
3782             if ocx.select_where_possible().is_empty() {
3783                 // `ty_var` now holds the type that `Item` is for `ExprTy`.
3784                 let ty_var = self.resolve_vars_if_possible(ty_var);
3785                 assocs_in_this_method.push(Some((span, (proj.def_id, ty_var))));
3786             } else {
3787                 // `<ExprTy as Iterator>` didn't select, so likely we've
3788                 // reached the end of the iterator chain, like the originating
3789                 // `Vec<_>`.
3790                 // Keep the space consistent for later zipping.
3791                 assocs_in_this_method.push(None);
3792             }
3793         }
3794         assocs_in_this_method
3795     }
3796 }
3797
3798 /// Add a hint to add a missing borrow or remove an unnecessary one.
3799 fn hint_missing_borrow<'tcx>(
3800     infcx: &InferCtxt<'tcx>,
3801     param_env: ty::ParamEnv<'tcx>,
3802     span: Span,
3803     found: Ty<'tcx>,
3804     expected: Ty<'tcx>,
3805     found_node: Node<'_>,
3806     err: &mut Diagnostic,
3807 ) {
3808     let found_args = match found.kind() {
3809         ty::FnPtr(f) => infcx.replace_bound_vars_with_placeholders(*f).inputs().iter(),
3810         kind => {
3811             span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
3812         }
3813     };
3814     let expected_args = match expected.kind() {
3815         ty::FnPtr(f) => infcx.replace_bound_vars_with_placeholders(*f).inputs().iter(),
3816         kind => {
3817             span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
3818         }
3819     };
3820
3821     // This could be a variant constructor, for example.
3822     let Some(fn_decl) = found_node.fn_decl() else { return; };
3823
3824     let args = fn_decl.inputs.iter().map(|ty| ty);
3825
3826     fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
3827         let mut refs = vec![];
3828
3829         while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
3830             ty = *new_ty;
3831             refs.push(*mutbl);
3832         }
3833
3834         (ty, refs)
3835     }
3836
3837     let mut to_borrow = Vec::new();
3838     let mut remove_borrow = Vec::new();
3839
3840     for ((found_arg, expected_arg), arg) in found_args.zip(expected_args).zip(args) {
3841         let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
3842         let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
3843
3844         if infcx.can_eq(param_env, found_ty, expected_ty).is_ok() {
3845             // FIXME: This could handle more exotic cases like mutability mismatches too!
3846             if found_refs.len() < expected_refs.len()
3847                 && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
3848             {
3849                 to_borrow.push((
3850                     arg.span.shrink_to_lo(),
3851                     expected_refs[..expected_refs.len() - found_refs.len()]
3852                         .iter()
3853                         .map(|mutbl| format!("&{}", mutbl.prefix_str()))
3854                         .collect::<Vec<_>>()
3855                         .join(""),
3856                 ));
3857             } else if found_refs.len() > expected_refs.len() {
3858                 let mut span = arg.span.shrink_to_lo();
3859                 let mut left = found_refs.len() - expected_refs.len();
3860                 let mut ty = arg;
3861                 while let hir::TyKind::Ref(_, mut_ty) = &ty.kind && left > 0 {
3862                     span = span.with_hi(mut_ty.ty.span.lo());
3863                     ty = mut_ty.ty;
3864                     left -= 1;
3865                 }
3866                 let sugg = if left == 0 {
3867                     (span, String::new())
3868                 } else {
3869                     (arg.span, expected_arg.to_string())
3870                 };
3871                 remove_borrow.push(sugg);
3872             }
3873         }
3874     }
3875
3876     if !to_borrow.is_empty() {
3877         err.multipart_suggestion_verbose(
3878             "consider borrowing the argument",
3879             to_borrow,
3880             Applicability::MaybeIncorrect,
3881         );
3882     }
3883
3884     if !remove_borrow.is_empty() {
3885         err.multipart_suggestion_verbose(
3886             "do not borrow the argument",
3887             remove_borrow,
3888             Applicability::MaybeIncorrect,
3889         );
3890     }
3891 }
3892
3893 /// Collect all the returned expressions within the input expression.
3894 /// Used to point at the return spans when we want to suggest some change to them.
3895 #[derive(Default)]
3896 pub struct ReturnsVisitor<'v> {
3897     pub returns: Vec<&'v hir::Expr<'v>>,
3898     in_block_tail: bool,
3899 }
3900
3901 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3902     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3903         // Visit every expression to detect `return` paths, either through the function's tail
3904         // expression or `return` statements. We walk all nodes to find `return` statements, but
3905         // we only care about tail expressions when `in_block_tail` is `true`, which means that
3906         // they're in the return path of the function body.
3907         match ex.kind {
3908             hir::ExprKind::Ret(Some(ex)) => {
3909                 self.returns.push(ex);
3910             }
3911             hir::ExprKind::Block(block, _) if self.in_block_tail => {
3912                 self.in_block_tail = false;
3913                 for stmt in block.stmts {
3914                     hir::intravisit::walk_stmt(self, stmt);
3915                 }
3916                 self.in_block_tail = true;
3917                 if let Some(expr) = block.expr {
3918                     self.visit_expr(expr);
3919                 }
3920             }
3921             hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3922                 self.visit_expr(then);
3923                 if let Some(el) = else_opt {
3924                     self.visit_expr(el);
3925                 }
3926             }
3927             hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3928                 for arm in arms {
3929                     self.visit_expr(arm.body);
3930                 }
3931             }
3932             // We need to walk to find `return`s in the entire body.
3933             _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3934             _ => self.returns.push(ex),
3935         }
3936     }
3937
3938     fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3939         assert!(!self.in_block_tail);
3940         if body.generator_kind().is_none() {
3941             if let hir::ExprKind::Block(block, None) = body.value.kind {
3942                 if block.expr.is_some() {
3943                     self.in_block_tail = true;
3944                 }
3945             }
3946         }
3947         hir::intravisit::walk_body(self, body);
3948     }
3949 }
3950
3951 /// Collect all the awaited expressions within the input expression.
3952 #[derive(Default)]
3953 struct AwaitsVisitor {
3954     awaits: Vec<hir::HirId>,
3955 }
3956
3957 impl<'v> Visitor<'v> for AwaitsVisitor {
3958     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3959         if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3960             self.awaits.push(id)
3961         }
3962         hir::intravisit::walk_expr(self, ex)
3963     }
3964 }
3965
3966 pub trait NextTypeParamName {
3967     fn next_type_param_name(&self, name: Option<&str>) -> String;
3968 }
3969
3970 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3971     fn next_type_param_name(&self, name: Option<&str>) -> String {
3972         // This is the list of possible parameter names that we might suggest.
3973         let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3974         let name = name.as_deref();
3975         let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3976         let used_names = self
3977             .iter()
3978             .filter_map(|p| match p.name {
3979                 hir::ParamName::Plain(ident) => Some(ident.name),
3980                 _ => None,
3981             })
3982             .collect::<Vec<_>>();
3983
3984         possible_names
3985             .iter()
3986             .find(|n| !used_names.contains(&Symbol::intern(n)))
3987             .unwrap_or(&"ParamName")
3988             .to_string()
3989     }
3990 }
3991
3992 fn suggest_trait_object_return_type_alternatives(
3993     err: &mut Diagnostic,
3994     ret_ty: Span,
3995     trait_obj: &str,
3996     is_object_safe: bool,
3997 ) {
3998     err.span_suggestion(
3999         ret_ty,
4000         &format!(
4001             "use `impl {}` as the return type if all return paths have the same type but you \
4002                 want to expose only the trait in the signature",
4003             trait_obj,
4004         ),
4005         format!("impl {}", trait_obj),
4006         Applicability::MaybeIncorrect,
4007     );
4008     if is_object_safe {
4009         err.multipart_suggestion(
4010             &format!(
4011                 "use a boxed trait object if all return paths implement trait `{}`",
4012                 trait_obj,
4013             ),
4014             vec![
4015                 (ret_ty.shrink_to_lo(), "Box<".to_string()),
4016                 (ret_ty.shrink_to_hi(), ">".to_string()),
4017             ],
4018             Applicability::MaybeIncorrect,
4019         );
4020     }
4021 }
4022
4023 /// Collect the spans that we see the generic param `param_did`
4024 struct ReplaceImplTraitVisitor<'a> {
4025     ty_spans: &'a mut Vec<Span>,
4026     param_did: DefId,
4027 }
4028
4029 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
4030     fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
4031         if let hir::TyKind::Path(hir::QPath::Resolved(
4032             None,
4033             hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
4034         )) = t.kind
4035         {
4036             if self.param_did == *segment_did {
4037                 // `fn foo(t: impl Trait)`
4038                 //            ^^^^^^^^^^ get this to suggest `T` instead
4039
4040                 // There might be more than one `impl Trait`.
4041                 self.ty_spans.push(t.span);
4042                 return;
4043             }
4044         }
4045
4046         hir::intravisit::walk_ty(self, t);
4047     }
4048 }
4049
4050 // Replace `param` with `replace_ty`
4051 struct ReplaceImplTraitFolder<'tcx> {
4052     tcx: TyCtxt<'tcx>,
4053     param: &'tcx ty::GenericParamDef,
4054     replace_ty: Ty<'tcx>,
4055 }
4056
4057 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
4058     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
4059         if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
4060             if self.param.index == *index {
4061                 return self.replace_ty;
4062             }
4063         }
4064         t.super_fold_with(self)
4065     }
4066
4067     fn tcx(&self) -> TyCtxt<'tcx> {
4068         self.tcx
4069     }
4070 }