]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs
Auto merge of #105667 - matthiaskrgr:rollup-fexlc0b, r=matthiaskrgr
[rust.git] / compiler / rustc_trait_selection / src / traits / error_reporting / mod.rs
1 mod ambiguity;
2 pub mod method_chain;
3 pub mod on_unimplemented;
4 pub mod suggestions;
5
6 use super::{
7     FulfillmentError, FulfillmentErrorCode, MismatchedProjectionTypes, Obligation, ObligationCause,
8     ObligationCauseCode, ObligationCtxt, OutputTypeParameterMismatch, Overflow,
9     PredicateObligation, SelectionContext, SelectionError, TraitNotObjectSafe,
10 };
11 use crate::infer::error_reporting::{TyCategory, TypeAnnotationNeeded as ErrorCode};
12 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
13 use crate::infer::{self, InferCtxt};
14 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
15 use crate::traits::query::normalize::QueryNormalizeExt as _;
16 use crate::traits::specialize::to_pretty_impl_header;
17 use crate::traits::NormalizeExt;
18 use on_unimplemented::OnUnimplementedNote;
19 use on_unimplemented::TypeErrCtxtExt as _;
20 use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
21 use rustc_errors::{
22     pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
23     MultiSpan, Style,
24 };
25 use rustc_hir as hir;
26 use rustc_hir::def::Namespace;
27 use rustc_hir::def_id::DefId;
28 use rustc_hir::intravisit::Visitor;
29 use rustc_hir::GenericParam;
30 use rustc_hir::Item;
31 use rustc_hir::Node;
32 use rustc_infer::infer::error_reporting::TypeErrCtxt;
33 use rustc_infer::infer::{InferOk, TypeTrace};
34 use rustc_middle::traits::select::OverflowError;
35 use rustc_middle::ty::abstract_const::NotConstEvaluatable;
36 use rustc_middle::ty::error::ExpectedFound;
37 use rustc_middle::ty::fold::{TypeFolder, TypeSuperFoldable};
38 use rustc_middle::ty::print::{FmtPrinter, Print};
39 use rustc_middle::ty::{
40     self, SubtypePredicate, ToPolyTraitRef, ToPredicate, TraitRef, Ty, TyCtxt, TypeFoldable,
41     TypeVisitable,
42 };
43 use rustc_session::Limit;
44 use rustc_span::def_id::LOCAL_CRATE;
45 use rustc_span::symbol::{kw, sym};
46 use rustc_span::{ExpnKind, Span, DUMMY_SP};
47 use std::fmt;
48 use std::iter;
49 use std::ops::ControlFlow;
50 use suggestions::TypeErrCtxtExt as _;
51
52 pub use rustc_infer::traits::error_reporting::*;
53
54 // When outputting impl candidates, prefer showing those that are more similar.
55 //
56 // We also compare candidates after skipping lifetimes, which has a lower
57 // priority than exact matches.
58 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
59 pub enum CandidateSimilarity {
60     Exact { ignoring_lifetimes: bool },
61     Fuzzy { ignoring_lifetimes: bool },
62 }
63
64 #[derive(Debug, Clone, Copy)]
65 pub struct ImplCandidate<'tcx> {
66     pub trait_ref: ty::TraitRef<'tcx>,
67     pub similarity: CandidateSimilarity,
68 }
69
70 pub trait InferCtxtExt<'tcx> {
71     /// Given some node representing a fn-like thing in the HIR map,
72     /// returns a span and `ArgKind` information that describes the
73     /// arguments it expects. This can be supplied to
74     /// `report_arg_count_mismatch`.
75     fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Option<Span>, Vec<ArgKind>)>;
76
77     /// Reports an error when the number of arguments needed by a
78     /// trait match doesn't match the number that the expression
79     /// provides.
80     fn report_arg_count_mismatch(
81         &self,
82         span: Span,
83         found_span: Option<Span>,
84         expected_args: Vec<ArgKind>,
85         found_args: Vec<ArgKind>,
86         is_closure: bool,
87         closure_pipe_span: Option<Span>,
88     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
89
90     /// Checks if the type implements one of `Fn`, `FnMut`, or `FnOnce`
91     /// in that order, and returns the generic type corresponding to the
92     /// argument of that trait (corresponding to the closure arguments).
93     fn type_implements_fn_trait(
94         &self,
95         param_env: ty::ParamEnv<'tcx>,
96         ty: ty::Binder<'tcx, Ty<'tcx>>,
97         constness: ty::BoundConstness,
98         polarity: ty::ImplPolarity,
99     ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()>;
100 }
101
102 pub trait TypeErrCtxtExt<'tcx> {
103     fn report_overflow_error<T>(
104         &self,
105         predicate: &T,
106         span: Span,
107         suggest_increasing_limit: bool,
108         mutate: impl FnOnce(&mut Diagnostic),
109     ) -> !
110     where
111         T: fmt::Display
112             + TypeFoldable<'tcx>
113             + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>,
114         <T as Print<'tcx, FmtPrinter<'tcx, 'tcx>>>::Error: std::fmt::Debug;
115
116     fn report_fulfillment_errors(
117         &self,
118         errors: &[FulfillmentError<'tcx>],
119         body_id: Option<hir::BodyId>,
120     ) -> ErrorGuaranteed;
121
122     fn report_overflow_obligation<T>(
123         &self,
124         obligation: &Obligation<'tcx, T>,
125         suggest_increasing_limit: bool,
126     ) -> !
127     where
128         T: ToPredicate<'tcx> + Clone;
129
130     fn suggest_new_overflow_limit(&self, err: &mut Diagnostic);
131
132     fn report_overflow_obligation_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> !;
133
134     /// The `root_obligation` parameter should be the `root_obligation` field
135     /// from a `FulfillmentError`. If no `FulfillmentError` is available,
136     /// then it should be the same as `obligation`.
137     fn report_selection_error(
138         &self,
139         obligation: PredicateObligation<'tcx>,
140         root_obligation: &PredicateObligation<'tcx>,
141         error: &SelectionError<'tcx>,
142     );
143 }
144
145 impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> {
146     /// Given some node representing a fn-like thing in the HIR map,
147     /// returns a span and `ArgKind` information that describes the
148     /// arguments it expects. This can be supplied to
149     /// `report_arg_count_mismatch`.
150     fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Option<Span>, Vec<ArgKind>)> {
151         let sm = self.tcx.sess.source_map();
152         let hir = self.tcx.hir();
153         Some(match node {
154             Node::Expr(&hir::Expr {
155                 kind: hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, fn_arg_span, .. }),
156                 ..
157             }) => (
158                 fn_decl_span,
159                 fn_arg_span,
160                 hir.body(body)
161                     .params
162                     .iter()
163                     .map(|arg| {
164                         if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
165                             *arg.pat
166                         {
167                             Some(ArgKind::Tuple(
168                                 Some(span),
169                                 args.iter()
170                                     .map(|pat| {
171                                         sm.span_to_snippet(pat.span)
172                                             .ok()
173                                             .map(|snippet| (snippet, "_".to_owned()))
174                                     })
175                                     .collect::<Option<Vec<_>>>()?,
176                             ))
177                         } else {
178                             let name = sm.span_to_snippet(arg.pat.span).ok()?;
179                             Some(ArgKind::Arg(name, "_".to_owned()))
180                         }
181                     })
182                     .collect::<Option<Vec<ArgKind>>>()?,
183             ),
184             Node::Item(&hir::Item { kind: hir::ItemKind::Fn(ref sig, ..), .. })
185             | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(ref sig, _), .. })
186             | Node::TraitItem(&hir::TraitItem {
187                 kind: hir::TraitItemKind::Fn(ref sig, _), ..
188             }) => (
189                 sig.span,
190                 None,
191                 sig.decl
192                     .inputs
193                     .iter()
194                     .map(|arg| match arg.kind {
195                         hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
196                             Some(arg.span),
197                             vec![("_".to_owned(), "_".to_owned()); tys.len()],
198                         ),
199                         _ => ArgKind::empty(),
200                     })
201                     .collect::<Vec<ArgKind>>(),
202             ),
203             Node::Ctor(ref variant_data) => {
204                 let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| hir.span(id));
205                 (span, None, vec![ArgKind::empty(); variant_data.fields().len()])
206             }
207             _ => panic!("non-FnLike node found: {:?}", node),
208         })
209     }
210
211     /// Reports an error when the number of arguments needed by a
212     /// trait match doesn't match the number that the expression
213     /// provides.
214     fn report_arg_count_mismatch(
215         &self,
216         span: Span,
217         found_span: Option<Span>,
218         expected_args: Vec<ArgKind>,
219         found_args: Vec<ArgKind>,
220         is_closure: bool,
221         closure_arg_span: Option<Span>,
222     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
223         let kind = if is_closure { "closure" } else { "function" };
224
225         let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
226             let arg_length = arguments.len();
227             let distinct = matches!(other, &[ArgKind::Tuple(..)]);
228             match (arg_length, arguments.get(0)) {
229                 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
230                     format!("a single {}-tuple as argument", fields.len())
231                 }
232                 _ => format!(
233                     "{} {}argument{}",
234                     arg_length,
235                     if distinct && arg_length > 1 { "distinct " } else { "" },
236                     pluralize!(arg_length)
237                 ),
238             }
239         };
240
241         let expected_str = args_str(&expected_args, &found_args);
242         let found_str = args_str(&found_args, &expected_args);
243
244         let mut err = struct_span_err!(
245             self.tcx.sess,
246             span,
247             E0593,
248             "{} is expected to take {}, but it takes {}",
249             kind,
250             expected_str,
251             found_str,
252         );
253
254         err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
255
256         if let Some(found_span) = found_span {
257             err.span_label(found_span, format!("takes {}", found_str));
258
259             // Suggest to take and ignore the arguments with expected_args_length `_`s if
260             // found arguments is empty (assume the user just wants to ignore args in this case).
261             // For example, if `expected_args_length` is 2, suggest `|_, _|`.
262             if found_args.is_empty() && is_closure {
263                 let underscores = vec!["_"; expected_args.len()].join(", ");
264                 err.span_suggestion_verbose(
265                     closure_arg_span.unwrap_or(found_span),
266                     &format!(
267                         "consider changing the closure to take and ignore the expected argument{}",
268                         pluralize!(expected_args.len())
269                     ),
270                     format!("|{}|", underscores),
271                     Applicability::MachineApplicable,
272                 );
273             }
274
275             if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
276                 if fields.len() == expected_args.len() {
277                     let sugg = fields
278                         .iter()
279                         .map(|(name, _)| name.to_owned())
280                         .collect::<Vec<String>>()
281                         .join(", ");
282                     err.span_suggestion_verbose(
283                         found_span,
284                         "change the closure to take multiple arguments instead of a single tuple",
285                         format!("|{}|", sugg),
286                         Applicability::MachineApplicable,
287                     );
288                 }
289             }
290             if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..]
291                 && fields.len() == found_args.len()
292                 && is_closure
293             {
294                 let sugg = format!(
295                     "|({}){}|",
296                     found_args
297                         .iter()
298                         .map(|arg| match arg {
299                             ArgKind::Arg(name, _) => name.to_owned(),
300                             _ => "_".to_owned(),
301                         })
302                         .collect::<Vec<String>>()
303                         .join(", "),
304                     // add type annotations if available
305                     if found_args.iter().any(|arg| match arg {
306                         ArgKind::Arg(_, ty) => ty != "_",
307                         _ => false,
308                     }) {
309                         format!(
310                             ": ({})",
311                             fields
312                                 .iter()
313                                 .map(|(_, ty)| ty.to_owned())
314                                 .collect::<Vec<String>>()
315                                 .join(", ")
316                         )
317                     } else {
318                         String::new()
319                     },
320                 );
321                 err.span_suggestion_verbose(
322                     found_span,
323                     "change the closure to accept a tuple instead of individual arguments",
324                     sugg,
325                     Applicability::MachineApplicable,
326                 );
327             }
328         }
329
330         err
331     }
332
333     fn type_implements_fn_trait(
334         &self,
335         param_env: ty::ParamEnv<'tcx>,
336         ty: ty::Binder<'tcx, Ty<'tcx>>,
337         constness: ty::BoundConstness,
338         polarity: ty::ImplPolarity,
339     ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> {
340         self.commit_if_ok(|_| {
341             for trait_def_id in [
342                 self.tcx.lang_items().fn_trait(),
343                 self.tcx.lang_items().fn_mut_trait(),
344                 self.tcx.lang_items().fn_once_trait(),
345             ] {
346                 let Some(trait_def_id) = trait_def_id else { continue };
347                 // Make a fresh inference variable so we can determine what the substitutions
348                 // of the trait are.
349                 let var = self.next_ty_var(TypeVariableOrigin {
350                     span: DUMMY_SP,
351                     kind: TypeVariableOriginKind::MiscVariable,
352                 });
353                 let trait_ref = self.tcx.mk_trait_ref(trait_def_id, [ty.skip_binder(), var]);
354                 let obligation = Obligation::new(
355                     self.tcx,
356                     ObligationCause::dummy(),
357                     param_env,
358                     ty.rebind(ty::TraitPredicate { trait_ref, constness, polarity }),
359                 );
360                 let ocx = ObligationCtxt::new_in_snapshot(self);
361                 ocx.register_obligation(obligation);
362                 if ocx.select_all_or_error().is_empty() {
363                     return Ok((
364                         self.tcx
365                             .fn_trait_kind_from_def_id(trait_def_id)
366                             .expect("expected to map DefId to ClosureKind"),
367                         ty.rebind(self.resolve_vars_if_possible(var)),
368                     ));
369                 }
370             }
371
372             Err(())
373         })
374     }
375 }
376 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
377     fn report_fulfillment_errors(
378         &self,
379         errors: &[FulfillmentError<'tcx>],
380         body_id: Option<hir::BodyId>,
381     ) -> ErrorGuaranteed {
382         #[derive(Debug)]
383         struct ErrorDescriptor<'tcx> {
384             predicate: ty::Predicate<'tcx>,
385             index: Option<usize>, // None if this is an old error
386         }
387
388         let mut error_map: FxIndexMap<_, Vec<_>> = self
389             .reported_trait_errors
390             .borrow()
391             .iter()
392             .map(|(&span, predicates)| {
393                 (
394                     span,
395                     predicates
396                         .iter()
397                         .map(|&predicate| ErrorDescriptor { predicate, index: None })
398                         .collect(),
399                 )
400             })
401             .collect();
402
403         for (index, error) in errors.iter().enumerate() {
404             // We want to ignore desugarings here: spans are equivalent even
405             // if one is the result of a desugaring and the other is not.
406             let mut span = error.obligation.cause.span;
407             let expn_data = span.ctxt().outer_expn_data();
408             if let ExpnKind::Desugaring(_) = expn_data.kind {
409                 span = expn_data.call_site;
410             }
411
412             error_map.entry(span).or_default().push(ErrorDescriptor {
413                 predicate: error.obligation.predicate,
414                 index: Some(index),
415             });
416
417             self.reported_trait_errors
418                 .borrow_mut()
419                 .entry(span)
420                 .or_default()
421                 .push(error.obligation.predicate);
422         }
423
424         // We do this in 2 passes because we want to display errors in order, though
425         // maybe it *is* better to sort errors by span or something.
426         let mut is_suppressed = vec![false; errors.len()];
427         for (_, error_set) in error_map.iter() {
428             // We want to suppress "duplicate" errors with the same span.
429             for error in error_set {
430                 if let Some(index) = error.index {
431                     // Suppress errors that are either:
432                     // 1) strictly implied by another error.
433                     // 2) implied by an error with a smaller index.
434                     for error2 in error_set {
435                         if error2.index.map_or(false, |index2| is_suppressed[index2]) {
436                             // Avoid errors being suppressed by already-suppressed
437                             // errors, to prevent all errors from being suppressed
438                             // at once.
439                             continue;
440                         }
441
442                         if self.error_implies(error2.predicate, error.predicate)
443                             && !(error2.index >= error.index
444                                 && self.error_implies(error.predicate, error2.predicate))
445                         {
446                             info!("skipping {:?} (implied by {:?})", error, error2);
447                             is_suppressed[index] = true;
448                             break;
449                         }
450                     }
451                 }
452             }
453         }
454
455         for (error, suppressed) in iter::zip(errors, is_suppressed) {
456             if !suppressed {
457                 self.report_fulfillment_error(error, body_id);
458             }
459         }
460
461         self.tcx.sess.delay_span_bug(DUMMY_SP, "expected fullfillment errors")
462     }
463
464     /// Reports that an overflow has occurred and halts compilation. We
465     /// halt compilation unconditionally because it is important that
466     /// overflows never be masked -- they basically represent computations
467     /// whose result could not be truly determined and thus we can't say
468     /// if the program type checks or not -- and they are unusual
469     /// occurrences in any case.
470     fn report_overflow_error<T>(
471         &self,
472         predicate: &T,
473         span: Span,
474         suggest_increasing_limit: bool,
475         mutate: impl FnOnce(&mut Diagnostic),
476     ) -> !
477     where
478         T: fmt::Display
479             + TypeFoldable<'tcx>
480             + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>,
481         <T as Print<'tcx, FmtPrinter<'tcx, 'tcx>>>::Error: std::fmt::Debug,
482     {
483         let predicate = self.resolve_vars_if_possible(predicate.clone());
484         let mut pred_str = predicate.to_string();
485
486         if pred_str.len() > 50 {
487             // We don't need to save the type to a file, we will be talking about this type already
488             // in a separate note when we explain the obligation, so it will be available that way.
489             pred_str = predicate
490                 .print(FmtPrinter::new_with_limit(
491                     self.tcx,
492                     Namespace::TypeNS,
493                     rustc_session::Limit(6),
494                 ))
495                 .unwrap()
496                 .into_buffer();
497         }
498         let mut err = struct_span_err!(
499             self.tcx.sess,
500             span,
501             E0275,
502             "overflow evaluating the requirement `{}`",
503             pred_str,
504         );
505
506         if suggest_increasing_limit {
507             self.suggest_new_overflow_limit(&mut err);
508         }
509
510         mutate(&mut err);
511
512         err.emit();
513         self.tcx.sess.abort_if_errors();
514         bug!();
515     }
516
517     /// Reports that an overflow has occurred and halts compilation. We
518     /// halt compilation unconditionally because it is important that
519     /// overflows never be masked -- they basically represent computations
520     /// whose result could not be truly determined and thus we can't say
521     /// if the program type checks or not -- and they are unusual
522     /// occurrences in any case.
523     fn report_overflow_obligation<T>(
524         &self,
525         obligation: &Obligation<'tcx, T>,
526         suggest_increasing_limit: bool,
527     ) -> !
528     where
529         T: ToPredicate<'tcx> + Clone,
530     {
531         let predicate = obligation.predicate.clone().to_predicate(self.tcx);
532         let predicate = self.resolve_vars_if_possible(predicate);
533         self.report_overflow_error(
534             &predicate,
535             obligation.cause.span,
536             suggest_increasing_limit,
537             |err| {
538                 self.note_obligation_cause_code(
539                     err,
540                     predicate,
541                     obligation.param_env,
542                     obligation.cause.code(),
543                     &mut vec![],
544                     &mut Default::default(),
545                 );
546             },
547         );
548     }
549
550     fn suggest_new_overflow_limit(&self, err: &mut Diagnostic) {
551         let suggested_limit = match self.tcx.recursion_limit() {
552             Limit(0) => Limit(2),
553             limit => limit * 2,
554         };
555         err.help(&format!(
556             "consider increasing the recursion limit by adding a \
557              `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
558             suggested_limit,
559             self.tcx.crate_name(LOCAL_CRATE),
560         ));
561     }
562
563     /// Reports that a cycle was detected which led to overflow and halts
564     /// compilation. This is equivalent to `report_overflow_obligation` except
565     /// that we can give a more helpful error message (and, in particular,
566     /// we do not suggest increasing the overflow limit, which is not
567     /// going to help).
568     fn report_overflow_obligation_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
569         let cycle = self.resolve_vars_if_possible(cycle.to_owned());
570         assert!(!cycle.is_empty());
571
572         debug!(?cycle, "report_overflow_error_cycle");
573
574         // The 'deepest' obligation is most likely to have a useful
575         // cause 'backtrace'
576         self.report_overflow_obligation(
577             cycle.iter().max_by_key(|p| p.recursion_depth).unwrap(),
578             false,
579         );
580     }
581
582     fn report_selection_error(
583         &self,
584         mut obligation: PredicateObligation<'tcx>,
585         root_obligation: &PredicateObligation<'tcx>,
586         error: &SelectionError<'tcx>,
587     ) {
588         let tcx = self.tcx;
589         let mut span = obligation.cause.span;
590         // FIXME: statically guarantee this by tainting after the diagnostic is emitted
591         self.set_tainted_by_errors(
592             tcx.sess.delay_span_bug(span, "`report_selection_error` did not emit an error"),
593         );
594
595         let mut err = match *error {
596             SelectionError::Unimplemented => {
597                 // If this obligation was generated as a result of well-formedness checking, see if we
598                 // can get a better error message by performing HIR-based well-formedness checking.
599                 if let ObligationCauseCode::WellFormed(Some(wf_loc)) =
600                     root_obligation.cause.code().peel_derives()
601                     && !obligation.predicate.has_non_region_infer()
602                 {
603                     if let Some(cause) = self
604                         .tcx
605                         .diagnostic_hir_wf_check((tcx.erase_regions(obligation.predicate), *wf_loc))
606                     {
607                         obligation.cause = cause.clone();
608                         span = obligation.cause.span;
609                     }
610                 }
611                 if let ObligationCauseCode::CompareImplItemObligation {
612                     impl_item_def_id,
613                     trait_item_def_id,
614                     kind: _,
615                 } = *obligation.cause.code()
616                 {
617                     self.report_extra_impl_obligation(
618                         span,
619                         impl_item_def_id,
620                         trait_item_def_id,
621                         &format!("`{}`", obligation.predicate),
622                     )
623                     .emit();
624                     return;
625                 }
626
627                 let bound_predicate = obligation.predicate.kind();
628                 match bound_predicate.skip_binder() {
629                     ty::PredicateKind::Clause(ty::Clause::Trait(trait_predicate)) => {
630                         let trait_predicate = bound_predicate.rebind(trait_predicate);
631                         let mut trait_predicate = self.resolve_vars_if_possible(trait_predicate);
632
633                         trait_predicate.remap_constness_diag(obligation.param_env);
634                         let predicate_is_const = ty::BoundConstness::ConstIfConst
635                             == trait_predicate.skip_binder().constness;
636
637                         if self.tcx.sess.has_errors().is_some()
638                             && trait_predicate.references_error()
639                         {
640                             return;
641                         }
642                         let trait_ref = trait_predicate.to_poly_trait_ref();
643                         let (post_message, pre_message, type_def) = self
644                             .get_parent_trait_ref(obligation.cause.code())
645                             .map(|(t, s)| {
646                                 (
647                                     format!(" in `{}`", t),
648                                     format!("within `{}`, ", t),
649                                     s.map(|s| (format!("within this `{}`", t), s)),
650                                 )
651                             })
652                             .unwrap_or_default();
653
654                         let OnUnimplementedNote {
655                             message,
656                             label,
657                             note,
658                             parent_label,
659                             append_const_msg,
660                         } = self.on_unimplemented_note(trait_ref, &obligation);
661                         let have_alt_message = message.is_some() || label.is_some();
662                         let is_try_conversion = self.is_try_conversion(span, trait_ref.def_id());
663                         let is_unsize =
664                             Some(trait_ref.def_id()) == self.tcx.lang_items().unsize_trait();
665                         let (message, note, append_const_msg) = if is_try_conversion {
666                             (
667                                 Some(format!(
668                                     "`?` couldn't convert the error to `{}`",
669                                     trait_ref.skip_binder().self_ty(),
670                                 )),
671                                 Some(
672                                     "the question mark operation (`?`) implicitly performs a \
673                                      conversion on the error value using the `From` trait"
674                                         .to_owned(),
675                                 ),
676                                 Some(None),
677                             )
678                         } else {
679                             (message, note, append_const_msg)
680                         };
681
682                         let mut err = struct_span_err!(
683                             self.tcx.sess,
684                             span,
685                             E0277,
686                             "{}",
687                             message
688                                 .and_then(|cannot_do_this| {
689                                     match (predicate_is_const, append_const_msg) {
690                                         // do nothing if predicate is not const
691                                         (false, _) => Some(cannot_do_this),
692                                         // suggested using default post message
693                                         (true, Some(None)) => {
694                                             Some(format!("{cannot_do_this} in const contexts"))
695                                         }
696                                         // overridden post message
697                                         (true, Some(Some(post_message))) => {
698                                             Some(format!("{cannot_do_this}{post_message}"))
699                                         }
700                                         // fallback to generic message
701                                         (true, None) => None,
702                                     }
703                                 })
704                                 .unwrap_or_else(|| format!(
705                                     "the trait bound `{}` is not satisfied{}",
706                                     trait_predicate, post_message,
707                                 ))
708                         );
709
710                         if is_try_conversion && let Some(ret_span) = self.return_type_span(&obligation) {
711                             err.span_label(
712                                 ret_span,
713                                 &format!(
714                                     "expected `{}` because of this",
715                                     trait_ref.skip_binder().self_ty()
716                                 ),
717                             );
718                         }
719
720                         if Some(trait_ref.def_id()) == tcx.lang_items().tuple_trait() {
721                             match obligation.cause.code().peel_derives() {
722                                 ObligationCauseCode::RustCall => {
723                                     err.set_primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
724                                 }
725                                 ObligationCauseCode::BindingObligation(def_id, _)
726                                 | ObligationCauseCode::ItemObligation(def_id)
727                                     if tcx.is_fn_trait(*def_id) =>
728                                 {
729                                     err.code(rustc_errors::error_code!(E0059));
730                                     err.set_primary_message(format!(
731                                         "type parameter to bare `{}` trait must be a tuple",
732                                         tcx.def_path_str(*def_id)
733                                     ));
734                                 }
735                                 _ => {}
736                             }
737                         }
738
739                         if Some(trait_ref.def_id()) == tcx.lang_items().drop_trait()
740                             && predicate_is_const
741                         {
742                             err.note("`~const Drop` was renamed to `~const Destruct`");
743                             err.note("See <https://github.com/rust-lang/rust/pull/94901> for more details");
744                         }
745
746                         let explanation = if let ObligationCauseCode::MainFunctionType =
747                             obligation.cause.code()
748                         {
749                             "consider using `()`, or a `Result`".to_owned()
750                         } else {
751                             let ty_desc = match trait_ref.skip_binder().self_ty().kind() {
752                                 ty::FnDef(_, _) => Some("fn item"),
753                                 ty::Closure(_, _) => Some("closure"),
754                                 _ => None,
755                             };
756
757                             match ty_desc {
758                                 Some(desc) => format!(
759                                     "{}the trait `{}` is not implemented for {} `{}`",
760                                     pre_message,
761                                     trait_predicate.print_modifiers_and_trait_path(),
762                                     desc,
763                                     trait_ref.skip_binder().self_ty(),
764                                 ),
765                                 None => format!(
766                                     "{}the trait `{}` is not implemented for `{}`",
767                                     pre_message,
768                                     trait_predicate.print_modifiers_and_trait_path(),
769                                     trait_ref.skip_binder().self_ty(),
770                                 ),
771                             }
772                         };
773
774                         if self.suggest_add_reference_to_arg(
775                             &obligation,
776                             &mut err,
777                             trait_predicate,
778                             have_alt_message,
779                         ) {
780                             self.note_obligation_cause(&mut err, &obligation);
781                             err.emit();
782                             return;
783                         }
784                         if let Some(ref s) = label {
785                             // If it has a custom `#[rustc_on_unimplemented]`
786                             // error message, let's display it as the label!
787                             err.span_label(span, s);
788                             if !matches!(trait_ref.skip_binder().self_ty().kind(), ty::Param(_)) {
789                                 // When the self type is a type param We don't need to "the trait
790                                 // `std::marker::Sized` is not implemented for `T`" as we will point
791                                 // at the type param with a label to suggest constraining it.
792                                 err.help(&explanation);
793                             }
794                         } else {
795                             err.span_label(span, explanation);
796                         }
797
798                         if let ObligationCauseCode::ObjectCastObligation(concrete_ty, obj_ty) = obligation.cause.code().peel_derives() &&
799                             Some(trait_ref.def_id()) == self.tcx.lang_items().sized_trait() {
800                             self.suggest_borrowing_for_object_cast(&mut err, &root_obligation, *concrete_ty, *obj_ty);
801                         }
802
803                         let mut unsatisfied_const = false;
804                         if trait_predicate.is_const_if_const() && obligation.param_env.is_const() {
805                             let non_const_predicate = trait_ref.without_const();
806                             let non_const_obligation = Obligation {
807                                 cause: obligation.cause.clone(),
808                                 param_env: obligation.param_env.without_const(),
809                                 predicate: non_const_predicate.to_predicate(tcx),
810                                 recursion_depth: obligation.recursion_depth,
811                             };
812                             if self.predicate_may_hold(&non_const_obligation) {
813                                 unsatisfied_const = true;
814                                 err.span_note(
815                                     span,
816                                     &format!(
817                                         "the trait `{}` is implemented for `{}`, \
818                                         but that implementation is not `const`",
819                                         non_const_predicate.print_modifiers_and_trait_path(),
820                                         trait_ref.skip_binder().self_ty(),
821                                     ),
822                                 );
823                             }
824                         }
825
826                         if let Some((msg, span)) = type_def {
827                             err.span_label(span, &msg);
828                         }
829                         if let Some(ref s) = note {
830                             // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
831                             err.note(s.as_str());
832                         }
833                         if let Some(ref s) = parent_label {
834                             let body = tcx
835                                 .hir()
836                                 .opt_local_def_id(obligation.cause.body_id)
837                                 .unwrap_or_else(|| {
838                                     tcx.hir().body_owner_def_id(hir::BodyId {
839                                         hir_id: obligation.cause.body_id,
840                                     })
841                                 });
842                             err.span_label(tcx.def_span(body), s);
843                         }
844
845                         self.suggest_floating_point_literal(&obligation, &mut err, &trait_ref);
846                         self.suggest_dereferencing_index(&obligation, &mut err, trait_predicate);
847                         let mut suggested =
848                             self.suggest_dereferences(&obligation, &mut err, trait_predicate);
849                         suggested |= self.suggest_fn_call(&obligation, &mut err, trait_predicate);
850                         suggested |=
851                             self.suggest_remove_reference(&obligation, &mut err, trait_predicate);
852                         suggested |= self.suggest_semicolon_removal(
853                             &obligation,
854                             &mut err,
855                             span,
856                             trait_predicate,
857                         );
858                         self.note_version_mismatch(&mut err, &trait_ref);
859                         self.suggest_remove_await(&obligation, &mut err);
860                         self.suggest_derive(&obligation, &mut err, trait_predicate);
861
862                         if Some(trait_ref.def_id()) == tcx.lang_items().try_trait() {
863                             self.suggest_await_before_try(
864                                 &mut err,
865                                 &obligation,
866                                 trait_predicate,
867                                 span,
868                             );
869                         }
870
871                         if self.suggest_impl_trait(&mut err, span, &obligation, trait_predicate) {
872                             err.emit();
873                             return;
874                         }
875
876                         if is_unsize {
877                             // If the obligation failed due to a missing implementation of the
878                             // `Unsize` trait, give a pointer to why that might be the case
879                             err.note(
880                                 "all implementations of `Unsize` are provided \
881                                 automatically by the compiler, see \
882                                 <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
883                                 for more information",
884                             );
885                         }
886
887                         let is_fn_trait = tcx.is_fn_trait(trait_ref.def_id());
888                         let is_target_feature_fn = if let ty::FnDef(def_id, _) =
889                             *trait_ref.skip_binder().self_ty().kind()
890                         {
891                             !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
892                         } else {
893                             false
894                         };
895                         if is_fn_trait && is_target_feature_fn {
896                             err.note(
897                                 "`#[target_feature]` functions do not implement the `Fn` traits",
898                             );
899                         }
900
901                         // Try to report a help message
902                         if is_fn_trait
903                             && let Ok((implemented_kind, params)) = self.type_implements_fn_trait(
904                             obligation.param_env,
905                             trait_ref.self_ty(),
906                             trait_predicate.skip_binder().constness,
907                             trait_predicate.skip_binder().polarity,
908                         )
909                         {
910                             // If the type implements `Fn`, `FnMut`, or `FnOnce`, suppress the following
911                             // suggestion to add trait bounds for the type, since we only typically implement
912                             // these traits once.
913
914                             // Note if the `FnMut` or `FnOnce` is less general than the trait we're trying
915                             // to implement.
916                             let selected_kind =
917                                 self.tcx.fn_trait_kind_from_def_id(trait_ref.def_id())
918                                     .expect("expected to map DefId to ClosureKind");
919                             if !implemented_kind.extends(selected_kind) {
920                                 err.note(
921                                     &format!(
922                                         "`{}` implements `{}`, but it must implement `{}`, which is more general",
923                                         trait_ref.skip_binder().self_ty(),
924                                         implemented_kind,
925                                         selected_kind
926                                     )
927                                 );
928                             }
929
930                             // Note any argument mismatches
931                             let given_ty = params.skip_binder();
932                             let expected_ty = trait_ref.skip_binder().substs.type_at(1);
933                             if let ty::Tuple(given) = given_ty.kind()
934                                 && let ty::Tuple(expected) = expected_ty.kind()
935                             {
936                                 if expected.len() != given.len() {
937                                     // Note number of types that were expected and given
938                                     err.note(
939                                         &format!(
940                                             "expected a closure taking {} argument{}, but one taking {} argument{} was given",
941                                             given.len(),
942                                             pluralize!(given.len()),
943                                             expected.len(),
944                                             pluralize!(expected.len()),
945                                         )
946                                     );
947                                 } else if !self.same_type_modulo_infer(given_ty, expected_ty) {
948                                     // Print type mismatch
949                                     let (expected_args, given_args) =
950                                         self.cmp(given_ty, expected_ty);
951                                     err.note_expected_found(
952                                         &"a closure with arguments",
953                                         expected_args,
954                                         &"a closure with arguments",
955                                         given_args,
956                                     );
957                                 }
958                             }
959                         } else if !trait_ref.has_non_region_infer()
960                             && self.predicate_can_apply(obligation.param_env, trait_predicate)
961                         {
962                             // If a where-clause may be useful, remind the
963                             // user that they can add it.
964                             //
965                             // don't display an on-unimplemented note, as
966                             // these notes will often be of the form
967                             //     "the type `T` can't be frobnicated"
968                             // which is somewhat confusing.
969                             self.suggest_restricting_param_bound(
970                                 &mut err,
971                                 trait_predicate,
972                                 None,
973                                 obligation.cause.body_id,
974                             );
975                         } else if !suggested && !unsatisfied_const {
976                             // Can't show anything else useful, try to find similar impls.
977                             let impl_candidates = self.find_similar_impl_candidates(trait_predicate);
978                             if !self.report_similar_impl_candidates(
979                                 impl_candidates,
980                                 trait_ref,
981                                 obligation.cause.body_id,
982                                 &mut err,
983                             ) {
984                                 // This is *almost* equivalent to
985                                 // `obligation.cause.code().peel_derives()`, but it gives us the
986                                 // trait predicate for that corresponding root obligation. This
987                                 // lets us get a derived obligation from a type parameter, like
988                                 // when calling `string.strip_suffix(p)` where `p` is *not* an
989                                 // implementer of `Pattern<'_>`.
990                                 let mut code = obligation.cause.code();
991                                 let mut trait_pred = trait_predicate;
992                                 let mut peeled = false;
993                                 while let Some((parent_code, parent_trait_pred)) = code.parent() {
994                                     code = parent_code;
995                                     if let Some(parent_trait_pred) = parent_trait_pred {
996                                         trait_pred = parent_trait_pred;
997                                         peeled = true;
998                                     }
999                                 }
1000                                 let def_id = trait_pred.def_id();
1001                                 // Mention *all* the `impl`s for the *top most* obligation, the
1002                                 // user might have meant to use one of them, if any found. We skip
1003                                 // auto-traits or fundamental traits that might not be exactly what
1004                                 // the user might expect to be presented with. Instead this is
1005                                 // useful for less general traits.
1006                                 if peeled
1007                                     && !self.tcx.trait_is_auto(def_id)
1008                                     && !self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
1009                                 {
1010                                     let trait_ref = trait_pred.to_poly_trait_ref();
1011                                     let impl_candidates =
1012                                         self.find_similar_impl_candidates(trait_pred);
1013                                     self.report_similar_impl_candidates(
1014                                         impl_candidates,
1015                                         trait_ref,
1016                                         obligation.cause.body_id,
1017                                         &mut err,
1018                                     );
1019                                 }
1020                             }
1021                         }
1022
1023                         // Changing mutability doesn't make a difference to whether we have
1024                         // an `Unsize` impl (Fixes ICE in #71036)
1025                         if !is_unsize {
1026                             self.suggest_change_mut(&obligation, &mut err, trait_predicate);
1027                         }
1028
1029                         // If this error is due to `!: Trait` not implemented but `(): Trait` is
1030                         // implemented, and fallback has occurred, then it could be due to a
1031                         // variable that used to fallback to `()` now falling back to `!`. Issue a
1032                         // note informing about the change in behaviour.
1033                         if trait_predicate.skip_binder().self_ty().is_never()
1034                             && self.fallback_has_occurred
1035                         {
1036                             let predicate = trait_predicate.map_bound(|trait_pred| {
1037                                 trait_pred.with_self_type(self.tcx, self.tcx.mk_unit())
1038                             });
1039                             let unit_obligation = obligation.with(tcx, predicate);
1040                             if self.predicate_may_hold(&unit_obligation) {
1041                                 err.note(
1042                                     "this error might have been caused by changes to \
1043                                     Rust's type-inference algorithm (see issue #48950 \
1044                                     <https://github.com/rust-lang/rust/issues/48950> \
1045                                     for more information)",
1046                                 );
1047                                 err.help("did you intend to use the type `()` here instead?");
1048                             }
1049                         }
1050
1051                         // Return early if the trait is Debug or Display and the invocation
1052                         // originates within a standard library macro, because the output
1053                         // is otherwise overwhelming and unhelpful (see #85844 for an
1054                         // example).
1055
1056                         let in_std_macro =
1057                             match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
1058                                 Some(macro_def_id) => {
1059                                     let crate_name = tcx.crate_name(macro_def_id.krate);
1060                                     crate_name == sym::std || crate_name == sym::core
1061                                 }
1062                                 None => false,
1063                             };
1064
1065                         if in_std_macro
1066                             && matches!(
1067                                 self.tcx.get_diagnostic_name(trait_ref.def_id()),
1068                                 Some(sym::Debug | sym::Display)
1069                             )
1070                         {
1071                             err.emit();
1072                             return;
1073                         }
1074
1075                         err
1076                     }
1077
1078                     ty::PredicateKind::Subtype(predicate) => {
1079                         // Errors for Subtype predicates show up as
1080                         // `FulfillmentErrorCode::CodeSubtypeError`,
1081                         // not selection error.
1082                         span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
1083                     }
1084
1085                     ty::PredicateKind::Coerce(predicate) => {
1086                         // Errors for Coerce predicates show up as
1087                         // `FulfillmentErrorCode::CodeSubtypeError`,
1088                         // not selection error.
1089                         span_bug!(span, "coerce requirement gave wrong error: `{:?}`", predicate)
1090                     }
1091
1092                     ty::PredicateKind::Clause(ty::Clause::RegionOutlives(..))
1093                     | ty::PredicateKind::Clause(ty::Clause::Projection(..))
1094                     | ty::PredicateKind::Clause(ty::Clause::TypeOutlives(..)) => {
1095                         let predicate = self.resolve_vars_if_possible(obligation.predicate);
1096                         struct_span_err!(
1097                             self.tcx.sess,
1098                             span,
1099                             E0280,
1100                             "the requirement `{}` is not satisfied",
1101                             predicate
1102                         )
1103                     }
1104
1105                     ty::PredicateKind::ObjectSafe(trait_def_id) => {
1106                         let violations = self.tcx.object_safety_violations(trait_def_id);
1107                         report_object_safety_error(self.tcx, span, trait_def_id, violations)
1108                     }
1109
1110                     ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
1111                         let found_kind = self.closure_kind(closure_substs).unwrap();
1112                         let closure_span = self.tcx.def_span(closure_def_id);
1113                         let mut err = struct_span_err!(
1114                             self.tcx.sess,
1115                             closure_span,
1116                             E0525,
1117                             "expected a closure that implements the `{}` trait, \
1118                              but this closure only implements `{}`",
1119                             kind,
1120                             found_kind
1121                         );
1122
1123                         err.span_label(
1124                             closure_span,
1125                             format!("this closure implements `{}`, not `{}`", found_kind, kind),
1126                         );
1127                         err.span_label(
1128                             obligation.cause.span,
1129                             format!("the requirement to implement `{}` derives from here", kind),
1130                         );
1131
1132                         // Additional context information explaining why the closure only implements
1133                         // a particular trait.
1134                         if let Some(typeck_results) = &self.typeck_results {
1135                             let hir_id = self
1136                                 .tcx
1137                                 .hir()
1138                                 .local_def_id_to_hir_id(closure_def_id.expect_local());
1139                             match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
1140                                 (ty::ClosureKind::FnOnce, Some((span, place))) => {
1141                                     err.span_label(
1142                                         *span,
1143                                         format!(
1144                                             "closure is `FnOnce` because it moves the \
1145                                          variable `{}` out of its environment",
1146                                             ty::place_to_string_for_capture(tcx, place)
1147                                         ),
1148                                     );
1149                                 }
1150                                 (ty::ClosureKind::FnMut, Some((span, place))) => {
1151                                     err.span_label(
1152                                         *span,
1153                                         format!(
1154                                             "closure is `FnMut` because it mutates the \
1155                                          variable `{}` here",
1156                                             ty::place_to_string_for_capture(tcx, place)
1157                                         ),
1158                                     );
1159                                 }
1160                                 _ => {}
1161                             }
1162                         }
1163
1164                         err
1165                     }
1166
1167                     ty::PredicateKind::WellFormed(ty) => {
1168                         if !self.tcx.sess.opts.unstable_opts.chalk {
1169                             // WF predicates cannot themselves make
1170                             // errors. They can only block due to
1171                             // ambiguity; otherwise, they always
1172                             // degenerate into other obligations
1173                             // (which may fail).
1174                             span_bug!(span, "WF predicate not satisfied for {:?}", ty);
1175                         } else {
1176                             // FIXME: we'll need a better message which takes into account
1177                             // which bounds actually failed to hold.
1178                             self.tcx.sess.struct_span_err(
1179                                 span,
1180                                 &format!("the type `{}` is not well-formed (chalk)", ty),
1181                             )
1182                         }
1183                     }
1184
1185                     ty::PredicateKind::ConstEvaluatable(..) => {
1186                         // Errors for `ConstEvaluatable` predicates show up as
1187                         // `SelectionError::ConstEvalFailure`,
1188                         // not `Unimplemented`.
1189                         span_bug!(
1190                             span,
1191                             "const-evaluatable requirement gave wrong error: `{:?}`",
1192                             obligation
1193                         )
1194                     }
1195
1196                     ty::PredicateKind::ConstEquate(..) => {
1197                         // Errors for `ConstEquate` predicates show up as
1198                         // `SelectionError::ConstEvalFailure`,
1199                         // not `Unimplemented`.
1200                         span_bug!(
1201                             span,
1202                             "const-equate requirement gave wrong error: `{:?}`",
1203                             obligation
1204                         )
1205                     }
1206
1207                     ty::PredicateKind::Ambiguous => span_bug!(span, "ambiguous"),
1208
1209                     ty::PredicateKind::TypeWellFormedFromEnv(..) => span_bug!(
1210                         span,
1211                         "TypeWellFormedFromEnv predicate should only exist in the environment"
1212                     ),
1213                 }
1214             }
1215
1216             OutputTypeParameterMismatch(found_trait_ref, expected_trait_ref, _) => {
1217                 let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
1218                 let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
1219
1220                 if expected_trait_ref.self_ty().references_error() {
1221                     return;
1222                 }
1223
1224                 let Some(found_trait_ty) = found_trait_ref.self_ty().no_bound_vars() else {
1225                     return;
1226                 };
1227
1228                 let found_did = match *found_trait_ty.kind() {
1229                     ty::Closure(did, _)
1230                     | ty::Foreign(did)
1231                     | ty::FnDef(did, _)
1232                     | ty::Generator(did, ..) => Some(did),
1233                     ty::Adt(def, _) => Some(def.did()),
1234                     _ => None,
1235                 };
1236
1237                 let found_node = found_did.and_then(|did| self.tcx.hir().get_if_local(did));
1238                 let found_span = found_did.and_then(|did| self.tcx.hir().span_if_local(did));
1239
1240                 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
1241                     // We check closures twice, with obligations flowing in different directions,
1242                     // but we want to complain about them only once.
1243                     return;
1244                 }
1245
1246                 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
1247
1248                 let mut not_tupled = false;
1249
1250                 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind() {
1251                     ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
1252                     _ => {
1253                         not_tupled = true;
1254                         vec![ArgKind::empty()]
1255                     }
1256                 };
1257
1258                 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
1259                 let expected = match expected_ty.kind() {
1260                     ty::Tuple(ref tys) => {
1261                         tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
1262                     }
1263                     _ => {
1264                         not_tupled = true;
1265                         vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())]
1266                     }
1267                 };
1268
1269                 // If this is a `Fn` family trait and either the expected or found
1270                 // is not tupled, then fall back to just a regular mismatch error.
1271                 // This shouldn't be common unless manually implementing one of the
1272                 // traits manually, but don't make it more confusing when it does
1273                 // happen.
1274                 if Some(expected_trait_ref.def_id()) != tcx.lang_items().gen_trait() && not_tupled {
1275                     self.report_and_explain_type_error(
1276                         TypeTrace::poly_trait_refs(
1277                             &obligation.cause,
1278                             true,
1279                             expected_trait_ref,
1280                             found_trait_ref,
1281                         ),
1282                         ty::error::TypeError::Mismatch,
1283                     )
1284                 } else if found.len() == expected.len() {
1285                     self.report_closure_arg_mismatch(
1286                         span,
1287                         found_span,
1288                         found_trait_ref,
1289                         expected_trait_ref,
1290                         obligation.cause.code(),
1291                         found_node,
1292                     )
1293                 } else {
1294                     let (closure_span, closure_arg_span, found) = found_did
1295                         .and_then(|did| {
1296                             let node = self.tcx.hir().get_if_local(did)?;
1297                             let (found_span, closure_arg_span, found) =
1298                                 self.get_fn_like_arguments(node)?;
1299                             Some((Some(found_span), closure_arg_span, found))
1300                         })
1301                         .unwrap_or((found_span, None, found));
1302
1303                     self.report_arg_count_mismatch(
1304                         span,
1305                         closure_span,
1306                         expected,
1307                         found,
1308                         found_trait_ty.is_closure(),
1309                         closure_arg_span,
1310                     )
1311                 }
1312             }
1313
1314             TraitNotObjectSafe(did) => {
1315                 let violations = self.tcx.object_safety_violations(did);
1316                 report_object_safety_error(self.tcx, span, did, violations)
1317             }
1318
1319             SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsInfer) => {
1320                 bug!(
1321                     "MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"
1322                 )
1323             }
1324             SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsParam) => {
1325                 if !self.tcx.features().generic_const_exprs {
1326                     let mut err = self.tcx.sess.struct_span_err(
1327                         span,
1328                         "constant expression depends on a generic parameter",
1329                     );
1330                     // FIXME(const_generics): we should suggest to the user how they can resolve this
1331                     // issue. However, this is currently not actually possible
1332                     // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
1333                     //
1334                     // Note that with `feature(generic_const_exprs)` this case should not
1335                     // be reachable.
1336                     err.note("this may fail depending on what value the parameter takes");
1337                     err.emit();
1338                     return;
1339                 }
1340
1341                 match obligation.predicate.kind().skip_binder() {
1342                     ty::PredicateKind::ConstEvaluatable(ct) => {
1343                         let ty::ConstKind::Unevaluated(uv) = ct.kind() else {
1344                             bug!("const evaluatable failed for non-unevaluated const `{ct:?}`");
1345                         };
1346                         let mut err =
1347                             self.tcx.sess.struct_span_err(span, "unconstrained generic constant");
1348                         let const_span = self.tcx.def_span(uv.def.did);
1349                         match self.tcx.sess.source_map().span_to_snippet(const_span) {
1350                             Ok(snippet) => err.help(&format!(
1351                                 "try adding a `where` bound using this expression: `where [(); {}]:`",
1352                                 snippet
1353                             )),
1354                             _ => err.help("consider adding a `where` bound using this expression"),
1355                         };
1356                         err
1357                     }
1358                     _ => {
1359                         span_bug!(
1360                             span,
1361                             "unexpected non-ConstEvaluatable predicate, this should not be reachable"
1362                         )
1363                     }
1364                 }
1365             }
1366
1367             // Already reported in the query.
1368             SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(_)) => {
1369                 // FIXME(eddyb) remove this once `ErrorGuaranteed` becomes a proof token.
1370                 self.tcx.sess.delay_span_bug(span, "`ErrorGuaranteed` without an error");
1371                 return;
1372             }
1373             // Already reported.
1374             Overflow(OverflowError::Error(_)) => {
1375                 self.tcx.sess.delay_span_bug(span, "`OverflowError` has been reported");
1376                 return;
1377             }
1378             Overflow(_) => {
1379                 bug!("overflow should be handled before the `report_selection_error` path");
1380             }
1381             SelectionError::ErrorReporting => {
1382                 bug!("ErrorReporting Overflow should not reach `report_selection_err` call")
1383             }
1384         };
1385
1386         self.note_obligation_cause(&mut err, &obligation);
1387         self.point_at_returns_when_relevant(&mut err, &obligation);
1388
1389         err.emit();
1390     }
1391 }
1392
1393 trait InferCtxtPrivExt<'tcx> {
1394     // returns if `cond` not occurring implies that `error` does not occur - i.e., that
1395     // `error` occurring implies that `cond` occurs.
1396     fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool;
1397
1398     fn report_fulfillment_error(
1399         &self,
1400         error: &FulfillmentError<'tcx>,
1401         body_id: Option<hir::BodyId>,
1402     );
1403
1404     fn report_projection_error(
1405         &self,
1406         obligation: &PredicateObligation<'tcx>,
1407         error: &MismatchedProjectionTypes<'tcx>,
1408     );
1409
1410     fn maybe_detailed_projection_msg(
1411         &self,
1412         pred: ty::ProjectionPredicate<'tcx>,
1413         normalized_ty: ty::Term<'tcx>,
1414         expected_ty: ty::Term<'tcx>,
1415     ) -> Option<String>;
1416
1417     fn fuzzy_match_tys(
1418         &self,
1419         a: Ty<'tcx>,
1420         b: Ty<'tcx>,
1421         ignoring_lifetimes: bool,
1422     ) -> Option<CandidateSimilarity>;
1423
1424     fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str>;
1425
1426     fn find_similar_impl_candidates(
1427         &self,
1428         trait_pred: ty::PolyTraitPredicate<'tcx>,
1429     ) -> Vec<ImplCandidate<'tcx>>;
1430
1431     fn report_similar_impl_candidates(
1432         &self,
1433         impl_candidates: Vec<ImplCandidate<'tcx>>,
1434         trait_ref: ty::PolyTraitRef<'tcx>,
1435         body_id: hir::HirId,
1436         err: &mut Diagnostic,
1437     ) -> bool;
1438
1439     /// Gets the parent trait chain start
1440     fn get_parent_trait_ref(
1441         &self,
1442         code: &ObligationCauseCode<'tcx>,
1443     ) -> Option<(String, Option<Span>)>;
1444
1445     /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1446     /// with the same path as `trait_ref`, a help message about
1447     /// a probable version mismatch is added to `err`
1448     fn note_version_mismatch(
1449         &self,
1450         err: &mut Diagnostic,
1451         trait_ref: &ty::PolyTraitRef<'tcx>,
1452     ) -> bool;
1453
1454     /// Creates a `PredicateObligation` with `new_self_ty` replacing the existing type in the
1455     /// `trait_ref`.
1456     ///
1457     /// For this to work, `new_self_ty` must have no escaping bound variables.
1458     fn mk_trait_obligation_with_new_self_ty(
1459         &self,
1460         param_env: ty::ParamEnv<'tcx>,
1461         trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>,
1462     ) -> PredicateObligation<'tcx>;
1463
1464     fn maybe_report_ambiguity(
1465         &self,
1466         obligation: &PredicateObligation<'tcx>,
1467         body_id: Option<hir::BodyId>,
1468     );
1469
1470     fn predicate_can_apply(
1471         &self,
1472         param_env: ty::ParamEnv<'tcx>,
1473         pred: ty::PolyTraitPredicate<'tcx>,
1474     ) -> bool;
1475
1476     fn note_obligation_cause(&self, err: &mut Diagnostic, obligation: &PredicateObligation<'tcx>);
1477
1478     fn suggest_unsized_bound_if_applicable(
1479         &self,
1480         err: &mut Diagnostic,
1481         obligation: &PredicateObligation<'tcx>,
1482     );
1483
1484     fn annotate_source_of_ambiguity(
1485         &self,
1486         err: &mut Diagnostic,
1487         impls: &[DefId],
1488         predicate: ty::Predicate<'tcx>,
1489     );
1490
1491     fn maybe_suggest_unsized_generics(&self, err: &mut Diagnostic, span: Span, node: Node<'tcx>);
1492
1493     fn maybe_indirection_for_unsized(
1494         &self,
1495         err: &mut Diagnostic,
1496         item: &'tcx Item<'tcx>,
1497         param: &'tcx GenericParam<'tcx>,
1498     ) -> bool;
1499
1500     fn is_recursive_obligation(
1501         &self,
1502         obligated_types: &mut Vec<Ty<'tcx>>,
1503         cause_code: &ObligationCauseCode<'tcx>,
1504     ) -> bool;
1505 }
1506
1507 impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
1508     // returns if `cond` not occurring implies that `error` does not occur - i.e., that
1509     // `error` occurring implies that `cond` occurs.
1510     fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool {
1511         if cond == error {
1512             return true;
1513         }
1514
1515         // FIXME: It should be possible to deal with `ForAll` in a cleaner way.
1516         let bound_error = error.kind();
1517         let (cond, error) = match (cond.kind().skip_binder(), bound_error.skip_binder()) {
1518             (
1519                 ty::PredicateKind::Clause(ty::Clause::Trait(..)),
1520                 ty::PredicateKind::Clause(ty::Clause::Trait(error)),
1521             ) => (cond, bound_error.rebind(error)),
1522             _ => {
1523                 // FIXME: make this work in other cases too.
1524                 return false;
1525             }
1526         };
1527
1528         for obligation in super::elaborate_predicates(self.tcx, std::iter::once(cond)) {
1529             let bound_predicate = obligation.predicate.kind();
1530             if let ty::PredicateKind::Clause(ty::Clause::Trait(implication)) =
1531                 bound_predicate.skip_binder()
1532             {
1533                 let error = error.to_poly_trait_ref();
1534                 let implication = bound_predicate.rebind(implication.trait_ref);
1535                 // FIXME: I'm just not taking associated types at all here.
1536                 // Eventually I'll need to implement param-env-aware
1537                 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
1538                 let param_env = ty::ParamEnv::empty();
1539                 if self.can_sub(param_env, error, implication).is_ok() {
1540                     debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
1541                     return true;
1542                 }
1543             }
1544         }
1545
1546         false
1547     }
1548
1549     #[instrument(skip(self), level = "debug")]
1550     fn report_fulfillment_error(
1551         &self,
1552         error: &FulfillmentError<'tcx>,
1553         body_id: Option<hir::BodyId>,
1554     ) {
1555         match error.code {
1556             FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
1557                 self.report_selection_error(
1558                     error.obligation.clone(),
1559                     &error.root_obligation,
1560                     selection_error,
1561                 );
1562             }
1563             FulfillmentErrorCode::CodeProjectionError(ref e) => {
1564                 self.report_projection_error(&error.obligation, e);
1565             }
1566             FulfillmentErrorCode::CodeAmbiguity => {
1567                 self.maybe_report_ambiguity(&error.obligation, body_id);
1568             }
1569             FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
1570                 self.report_mismatched_types(
1571                     &error.obligation.cause,
1572                     expected_found.expected,
1573                     expected_found.found,
1574                     err.clone(),
1575                 )
1576                 .emit();
1577             }
1578             FulfillmentErrorCode::CodeConstEquateError(ref expected_found, ref err) => {
1579                 let mut diag = self.report_mismatched_consts(
1580                     &error.obligation.cause,
1581                     expected_found.expected,
1582                     expected_found.found,
1583                     err.clone(),
1584                 );
1585                 let code = error.obligation.cause.code().peel_derives().peel_match_impls();
1586                 if let ObligationCauseCode::BindingObligation(..)
1587                 | ObligationCauseCode::ItemObligation(..)
1588                 | ObligationCauseCode::ExprBindingObligation(..)
1589                 | ObligationCauseCode::ExprItemObligation(..) = code
1590                 {
1591                     self.note_obligation_cause_code(
1592                         &mut diag,
1593                         error.obligation.predicate,
1594                         error.obligation.param_env,
1595                         code,
1596                         &mut vec![],
1597                         &mut Default::default(),
1598                     );
1599                 }
1600                 diag.emit();
1601             }
1602             FulfillmentErrorCode::CodeCycle(ref cycle) => {
1603                 self.report_overflow_obligation_cycle(cycle);
1604             }
1605         }
1606     }
1607
1608     #[instrument(level = "debug", skip_all)]
1609     fn report_projection_error(
1610         &self,
1611         obligation: &PredicateObligation<'tcx>,
1612         error: &MismatchedProjectionTypes<'tcx>,
1613     ) {
1614         let predicate = self.resolve_vars_if_possible(obligation.predicate);
1615
1616         if predicate.references_error() {
1617             return;
1618         }
1619
1620         self.probe(|_| {
1621             let ocx = ObligationCtxt::new_in_snapshot(self);
1622
1623             // try to find the mismatched types to report the error with.
1624             //
1625             // this can fail if the problem was higher-ranked, in which
1626             // cause I have no idea for a good error message.
1627             let bound_predicate = predicate.kind();
1628             let (values, err) = if let ty::PredicateKind::Clause(ty::Clause::Projection(data)) =
1629                 bound_predicate.skip_binder()
1630             {
1631                 let data = self.replace_bound_vars_with_fresh_vars(
1632                     obligation.cause.span,
1633                     infer::LateBoundRegionConversionTime::HigherRankedType,
1634                     bound_predicate.rebind(data),
1635                 );
1636                 let normalized_ty = ocx.normalize(
1637                     &obligation.cause,
1638                     obligation.param_env,
1639                     self.tcx
1640                         .mk_projection(data.projection_ty.item_def_id, data.projection_ty.substs),
1641                 );
1642
1643                 debug!(?obligation.cause, ?obligation.param_env);
1644
1645                 debug!(?normalized_ty, data.ty = ?data.term);
1646
1647                 let is_normalized_ty_expected = !matches!(
1648                     obligation.cause.code().peel_derives(),
1649                     ObligationCauseCode::ItemObligation(_)
1650                         | ObligationCauseCode::BindingObligation(_, _)
1651                         | ObligationCauseCode::ExprItemObligation(..)
1652                         | ObligationCauseCode::ExprBindingObligation(..)
1653                         | ObligationCauseCode::ObjectCastObligation(..)
1654                         | ObligationCauseCode::OpaqueType
1655                 );
1656                 let expected_ty = data.term.ty().unwrap_or_else(|| self.tcx.ty_error());
1657
1658                 // constrain inference variables a bit more to nested obligations from normalize so
1659                 // we can have more helpful errors.
1660                 ocx.select_where_possible();
1661
1662                 if let Err(new_err) = ocx.eq_exp(
1663                     &obligation.cause,
1664                     obligation.param_env,
1665                     is_normalized_ty_expected,
1666                     normalized_ty,
1667                     expected_ty,
1668                 ) {
1669                     (Some((data, is_normalized_ty_expected, normalized_ty, expected_ty)), new_err)
1670                 } else {
1671                     (None, error.err)
1672                 }
1673             } else {
1674                 (None, error.err)
1675             };
1676
1677             let msg = values
1678                 .and_then(|(predicate, _, normalized_ty, expected_ty)| {
1679                     self.maybe_detailed_projection_msg(
1680                         predicate,
1681                         normalized_ty.into(),
1682                         expected_ty.into(),
1683                     )
1684                 })
1685                 .unwrap_or_else(|| format!("type mismatch resolving `{}`", predicate));
1686             let mut diag = struct_span_err!(self.tcx.sess, obligation.cause.span, E0271, "{msg}");
1687
1688             let secondary_span = match predicate.kind().skip_binder() {
1689                 ty::PredicateKind::Clause(ty::Clause::Projection(proj)) => self
1690                     .tcx
1691                     .opt_associated_item(proj.projection_ty.item_def_id)
1692                     .and_then(|trait_assoc_item| {
1693                         self.tcx
1694                             .trait_of_item(proj.projection_ty.item_def_id)
1695                             .map(|id| (trait_assoc_item, id))
1696                     })
1697                     .and_then(|(trait_assoc_item, id)| {
1698                         let trait_assoc_ident = trait_assoc_item.ident(self.tcx);
1699                         self.tcx.find_map_relevant_impl(id, proj.projection_ty.self_ty(), |did| {
1700                             self.tcx
1701                                 .associated_items(did)
1702                                 .in_definition_order()
1703                                 .find(|assoc| assoc.ident(self.tcx) == trait_assoc_ident)
1704                         })
1705                     })
1706                     .and_then(|item| match self.tcx.hir().get_if_local(item.def_id) {
1707                         Some(
1708                             hir::Node::TraitItem(hir::TraitItem {
1709                                 kind: hir::TraitItemKind::Type(_, Some(ty)),
1710                                 ..
1711                             })
1712                             | hir::Node::ImplItem(hir::ImplItem {
1713                                 kind: hir::ImplItemKind::Type(ty),
1714                                 ..
1715                             }),
1716                         ) => Some((ty.span, format!("type mismatch resolving `{}`", predicate))),
1717                         _ => None,
1718                     }),
1719                 _ => None,
1720             };
1721             self.note_type_err(
1722                 &mut diag,
1723                 &obligation.cause,
1724                 secondary_span,
1725                 values.map(|(_, is_normalized_ty_expected, normalized_ty, expected_ty)| {
1726                     infer::ValuePairs::Terms(ExpectedFound::new(
1727                         is_normalized_ty_expected,
1728                         normalized_ty.into(),
1729                         expected_ty.into(),
1730                     ))
1731                 }),
1732                 err,
1733                 true,
1734                 false,
1735             );
1736             self.note_obligation_cause(&mut diag, obligation);
1737             diag.emit();
1738         });
1739     }
1740
1741     fn maybe_detailed_projection_msg(
1742         &self,
1743         pred: ty::ProjectionPredicate<'tcx>,
1744         normalized_ty: ty::Term<'tcx>,
1745         expected_ty: ty::Term<'tcx>,
1746     ) -> Option<String> {
1747         let trait_def_id = pred.projection_ty.trait_def_id(self.tcx);
1748         let self_ty = pred.projection_ty.self_ty();
1749
1750         if Some(pred.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output() {
1751             Some(format!(
1752                 "expected `{self_ty}` to be a {fn_kind} that returns `{expected_ty}`, but it returns `{normalized_ty}`",
1753                 fn_kind = self_ty.prefix_string(self.tcx)
1754             ))
1755         } else if Some(trait_def_id) == self.tcx.lang_items().future_trait() {
1756             Some(format!(
1757                 "expected `{self_ty}` to be a future that resolves to `{expected_ty}`, but it resolves to `{normalized_ty}`"
1758             ))
1759         } else if Some(trait_def_id) == self.tcx.get_diagnostic_item(sym::Iterator) {
1760             Some(format!(
1761                 "expected `{self_ty}` to be an iterator that yields `{expected_ty}`, but it yields `{normalized_ty}`"
1762             ))
1763         } else {
1764             None
1765         }
1766     }
1767
1768     fn fuzzy_match_tys(
1769         &self,
1770         mut a: Ty<'tcx>,
1771         mut b: Ty<'tcx>,
1772         ignoring_lifetimes: bool,
1773     ) -> Option<CandidateSimilarity> {
1774         /// returns the fuzzy category of a given type, or None
1775         /// if the type can be equated to any type.
1776         fn type_category(tcx: TyCtxt<'_>, t: Ty<'_>) -> Option<u32> {
1777             match t.kind() {
1778                 ty::Bool => Some(0),
1779                 ty::Char => Some(1),
1780                 ty::Str => Some(2),
1781                 ty::Adt(def, _) if Some(def.did()) == tcx.lang_items().string() => Some(2),
1782                 ty::Int(..)
1783                 | ty::Uint(..)
1784                 | ty::Float(..)
1785                 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) => Some(4),
1786                 ty::Ref(..) | ty::RawPtr(..) => Some(5),
1787                 ty::Array(..) | ty::Slice(..) => Some(6),
1788                 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1789                 ty::Dynamic(..) => Some(8),
1790                 ty::Closure(..) => Some(9),
1791                 ty::Tuple(..) => Some(10),
1792                 ty::Param(..) => Some(11),
1793                 ty::Projection(..) => Some(12),
1794                 ty::Opaque(..) => Some(13),
1795                 ty::Never => Some(14),
1796                 ty::Adt(..) => Some(15),
1797                 ty::Generator(..) => Some(16),
1798                 ty::Foreign(..) => Some(17),
1799                 ty::GeneratorWitness(..) => Some(18),
1800                 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1801             }
1802         }
1803
1804         let strip_references = |mut t: Ty<'tcx>| -> Ty<'tcx> {
1805             loop {
1806                 match t.kind() {
1807                     ty::Ref(_, inner, _) | ty::RawPtr(ty::TypeAndMut { ty: inner, .. }) => {
1808                         t = *inner
1809                     }
1810                     _ => break t,
1811                 }
1812             }
1813         };
1814
1815         if !ignoring_lifetimes {
1816             a = strip_references(a);
1817             b = strip_references(b);
1818         }
1819
1820         let cat_a = type_category(self.tcx, a)?;
1821         let cat_b = type_category(self.tcx, b)?;
1822         if a == b {
1823             Some(CandidateSimilarity::Exact { ignoring_lifetimes })
1824         } else if cat_a == cat_b {
1825             match (a.kind(), b.kind()) {
1826                 (ty::Adt(def_a, _), ty::Adt(def_b, _)) => def_a == def_b,
1827                 (ty::Foreign(def_a), ty::Foreign(def_b)) => def_a == def_b,
1828                 // Matching on references results in a lot of unhelpful
1829                 // suggestions, so let's just not do that for now.
1830                 //
1831                 // We still upgrade successful matches to `ignoring_lifetimes: true`
1832                 // to prioritize that impl.
1833                 (ty::Ref(..) | ty::RawPtr(..), ty::Ref(..) | ty::RawPtr(..)) => {
1834                     self.fuzzy_match_tys(a, b, true).is_some()
1835                 }
1836                 _ => true,
1837             }
1838             .then_some(CandidateSimilarity::Fuzzy { ignoring_lifetimes })
1839         } else if ignoring_lifetimes {
1840             None
1841         } else {
1842             self.fuzzy_match_tys(a, b, true)
1843         }
1844     }
1845
1846     fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
1847         self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind {
1848             hir::GeneratorKind::Gen => "a generator",
1849             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
1850             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
1851             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
1852         })
1853     }
1854
1855     fn find_similar_impl_candidates(
1856         &self,
1857         trait_pred: ty::PolyTraitPredicate<'tcx>,
1858     ) -> Vec<ImplCandidate<'tcx>> {
1859         let mut candidates: Vec<_> = self
1860             .tcx
1861             .all_impls(trait_pred.def_id())
1862             .filter_map(|def_id| {
1863                 if self.tcx.impl_polarity(def_id) == ty::ImplPolarity::Negative
1864                     || !trait_pred
1865                         .skip_binder()
1866                         .is_constness_satisfied_by(self.tcx.constness(def_id))
1867                 {
1868                     return None;
1869                 }
1870
1871                 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
1872
1873                 self.fuzzy_match_tys(trait_pred.skip_binder().self_ty(), imp.self_ty(), false)
1874                     .map(|similarity| ImplCandidate { trait_ref: imp, similarity })
1875             })
1876             .collect();
1877         if candidates.iter().any(|c| matches!(c.similarity, CandidateSimilarity::Exact { .. })) {
1878             // If any of the candidates is a perfect match, we don't want to show all of them.
1879             // This is particularly relevant for the case of numeric types (as they all have the
1880             // same cathegory).
1881             candidates.retain(|c| matches!(c.similarity, CandidateSimilarity::Exact { .. }));
1882         }
1883         candidates
1884     }
1885
1886     fn report_similar_impl_candidates(
1887         &self,
1888         impl_candidates: Vec<ImplCandidate<'tcx>>,
1889         trait_ref: ty::PolyTraitRef<'tcx>,
1890         body_id: hir::HirId,
1891         err: &mut Diagnostic,
1892     ) -> bool {
1893         let report = |mut candidates: Vec<TraitRef<'tcx>>, err: &mut Diagnostic| {
1894             candidates.sort();
1895             candidates.dedup();
1896             let len = candidates.len();
1897             if candidates.len() == 0 {
1898                 return false;
1899             }
1900             if candidates.len() == 1 {
1901                 let ty_desc = match candidates[0].self_ty().kind() {
1902                     ty::FnPtr(_) => Some("fn pointer"),
1903                     _ => None,
1904                 };
1905                 let the_desc = match ty_desc {
1906                     Some(desc) => format!(" implemented for {} `", desc),
1907                     None => " implemented for `".to_string(),
1908                 };
1909                 err.highlighted_help(vec![
1910                     (
1911                         format!("the trait `{}` ", candidates[0].print_only_trait_path()),
1912                         Style::NoStyle,
1913                     ),
1914                     ("is".to_string(), Style::Highlight),
1915                     (the_desc, Style::NoStyle),
1916                     (candidates[0].self_ty().to_string(), Style::Highlight),
1917                     ("`".to_string(), Style::NoStyle),
1918                 ]);
1919                 return true;
1920             }
1921             let trait_ref = TraitRef::identity(self.tcx, candidates[0].def_id);
1922             // Check if the trait is the same in all cases. If so, we'll only show the type.
1923             let mut traits: Vec<_> =
1924                 candidates.iter().map(|c| c.print_only_trait_path().to_string()).collect();
1925             traits.sort();
1926             traits.dedup();
1927
1928             let mut candidates: Vec<String> = candidates
1929                 .into_iter()
1930                 .map(|c| {
1931                     if traits.len() == 1 {
1932                         format!("\n  {}", c.self_ty())
1933                     } else {
1934                         format!("\n  {}", c)
1935                     }
1936                 })
1937                 .collect();
1938
1939             candidates.sort();
1940             candidates.dedup();
1941             let end = if candidates.len() <= 9 { candidates.len() } else { 8 };
1942             err.help(&format!(
1943                 "the following other types implement trait `{}`:{}{}",
1944                 trait_ref.print_only_trait_path(),
1945                 candidates[..end].join(""),
1946                 if len > 9 { format!("\nand {} others", len - 8) } else { String::new() }
1947             ));
1948             true
1949         };
1950
1951         let def_id = trait_ref.def_id();
1952         if impl_candidates.is_empty() {
1953             if self.tcx.trait_is_auto(def_id)
1954                 || self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
1955                 || self.tcx.get_diagnostic_name(def_id).is_some()
1956             {
1957                 // Mentioning implementers of `Copy`, `Debug` and friends is not useful.
1958                 return false;
1959             }
1960             let normalized_impl_candidates: Vec<_> = self
1961                 .tcx
1962                 .all_impls(def_id)
1963                 // Ignore automatically derived impls and `!Trait` impls.
1964                 .filter(|&def_id| {
1965                     self.tcx.impl_polarity(def_id) != ty::ImplPolarity::Negative
1966                         || self.tcx.is_builtin_derive(def_id)
1967                 })
1968                 .filter_map(|def_id| self.tcx.impl_trait_ref(def_id))
1969                 .filter(|trait_ref| {
1970                     let self_ty = trait_ref.self_ty();
1971                     // Avoid mentioning type parameters.
1972                     if let ty::Param(_) = self_ty.kind() {
1973                         false
1974                     }
1975                     // Avoid mentioning types that are private to another crate
1976                     else if let ty::Adt(def, _) = self_ty.peel_refs().kind() {
1977                         // FIXME(compiler-errors): This could be generalized, both to
1978                         // be more granular, and probably look past other `#[fundamental]`
1979                         // types, too.
1980                         self.tcx
1981                             .visibility(def.did())
1982                             .is_accessible_from(body_id.owner.def_id, self.tcx)
1983                     } else {
1984                         true
1985                     }
1986                 })
1987                 .collect();
1988             return report(normalized_impl_candidates, err);
1989         }
1990
1991         // Sort impl candidates so that ordering is consistent for UI tests.
1992         // because the ordering of `impl_candidates` may not be deterministic:
1993         // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
1994         //
1995         // Prefer more similar candidates first, then sort lexicographically
1996         // by their normalized string representation.
1997         let mut normalized_impl_candidates_and_similarities = impl_candidates
1998             .into_iter()
1999             .map(|ImplCandidate { trait_ref, similarity }| {
2000                 // FIXME(compiler-errors): This should be using `NormalizeExt::normalize`
2001                 let normalized = self
2002                     .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
2003                     .query_normalize(trait_ref)
2004                     .map_or(trait_ref, |normalized| normalized.value);
2005                 (similarity, normalized)
2006             })
2007             .collect::<Vec<_>>();
2008         normalized_impl_candidates_and_similarities.sort();
2009         normalized_impl_candidates_and_similarities.dedup();
2010
2011         let normalized_impl_candidates = normalized_impl_candidates_and_similarities
2012             .into_iter()
2013             .map(|(_, normalized)| normalized)
2014             .collect::<Vec<_>>();
2015
2016         report(normalized_impl_candidates, err)
2017     }
2018
2019     /// Gets the parent trait chain start
2020     fn get_parent_trait_ref(
2021         &self,
2022         code: &ObligationCauseCode<'tcx>,
2023     ) -> Option<(String, Option<Span>)> {
2024         match code {
2025             ObligationCauseCode::BuiltinDerivedObligation(data) => {
2026                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2027                 match self.get_parent_trait_ref(&data.parent_code) {
2028                     Some(t) => Some(t),
2029                     None => {
2030                         let ty = parent_trait_ref.skip_binder().self_ty();
2031                         let span = TyCategory::from_ty(self.tcx, ty)
2032                             .map(|(_, def_id)| self.tcx.def_span(def_id));
2033                         Some((ty.to_string(), span))
2034                     }
2035                 }
2036             }
2037             ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
2038                 self.get_parent_trait_ref(&parent_code)
2039             }
2040             _ => None,
2041         }
2042     }
2043
2044     /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
2045     /// with the same path as `trait_ref`, a help message about
2046     /// a probable version mismatch is added to `err`
2047     fn note_version_mismatch(
2048         &self,
2049         err: &mut Diagnostic,
2050         trait_ref: &ty::PolyTraitRef<'tcx>,
2051     ) -> bool {
2052         let get_trait_impl = |trait_def_id| {
2053             self.tcx.find_map_relevant_impl(trait_def_id, trait_ref.skip_binder().self_ty(), Some)
2054         };
2055         let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
2056         let traits_with_same_path: std::collections::BTreeSet<_> = self
2057             .tcx
2058             .all_traits()
2059             .filter(|trait_def_id| *trait_def_id != trait_ref.def_id())
2060             .filter(|trait_def_id| self.tcx.def_path_str(*trait_def_id) == required_trait_path)
2061             .collect();
2062         let mut suggested = false;
2063         for trait_with_same_path in traits_with_same_path {
2064             if let Some(impl_def_id) = get_trait_impl(trait_with_same_path) {
2065                 let impl_span = self.tcx.def_span(impl_def_id);
2066                 err.span_help(impl_span, "trait impl with same name found");
2067                 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
2068                 let crate_msg = format!(
2069                     "perhaps two different versions of crate `{}` are being used?",
2070                     trait_crate
2071                 );
2072                 err.note(&crate_msg);
2073                 suggested = true;
2074             }
2075         }
2076         suggested
2077     }
2078
2079     fn mk_trait_obligation_with_new_self_ty(
2080         &self,
2081         param_env: ty::ParamEnv<'tcx>,
2082         trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>,
2083     ) -> PredicateObligation<'tcx> {
2084         let trait_pred = trait_ref_and_ty
2085             .map_bound(|(tr, new_self_ty)| tr.with_self_type(self.tcx, new_self_ty));
2086
2087         Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred)
2088     }
2089
2090     #[instrument(skip(self), level = "debug")]
2091     fn maybe_report_ambiguity(
2092         &self,
2093         obligation: &PredicateObligation<'tcx>,
2094         body_id: Option<hir::BodyId>,
2095     ) {
2096         // Unable to successfully determine, probably means
2097         // insufficient type information, but could mean
2098         // ambiguous impls. The latter *ought* to be a
2099         // coherence violation, so we don't report it here.
2100
2101         let predicate = self.resolve_vars_if_possible(obligation.predicate);
2102         let span = obligation.cause.span;
2103
2104         debug!(?predicate, obligation.cause.code = ?obligation.cause.code());
2105
2106         // Ambiguity errors are often caused as fallout from earlier errors.
2107         // We ignore them if this `infcx` is tainted in some cases below.
2108
2109         let bound_predicate = predicate.kind();
2110         let mut err = match bound_predicate.skip_binder() {
2111             ty::PredicateKind::Clause(ty::Clause::Trait(data)) => {
2112                 let trait_ref = bound_predicate.rebind(data.trait_ref);
2113                 debug!(?trait_ref);
2114
2115                 if predicate.references_error() {
2116                     return;
2117                 }
2118
2119                 // This is kind of a hack: it frequently happens that some earlier
2120                 // error prevents types from being fully inferred, and then we get
2121                 // a bunch of uninteresting errors saying something like "<generic
2122                 // #0> doesn't implement Sized".  It may even be true that we
2123                 // could just skip over all checks where the self-ty is an
2124                 // inference variable, but I was afraid that there might be an
2125                 // inference variable created, registered as an obligation, and
2126                 // then never forced by writeback, and hence by skipping here we'd
2127                 // be ignoring the fact that we don't KNOW the type works
2128                 // out. Though even that would probably be harmless, given that
2129                 // we're only talking about builtin traits, which are known to be
2130                 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
2131                 // avoid inundating the user with unnecessary errors, but we now
2132                 // check upstream for type errors and don't add the obligations to
2133                 // begin with in those cases.
2134                 if self.tcx.lang_items().sized_trait() == Some(trait_ref.def_id()) {
2135                     if let None = self.tainted_by_errors() {
2136                         self.emit_inference_failure_err(
2137                             body_id,
2138                             span,
2139                             trait_ref.self_ty().skip_binder().into(),
2140                             ErrorCode::E0282,
2141                             false,
2142                         )
2143                         .emit();
2144                     }
2145                     return;
2146                 }
2147
2148                 // Typically, this ambiguity should only happen if
2149                 // there are unresolved type inference variables
2150                 // (otherwise it would suggest a coherence
2151                 // failure). But given #21974 that is not necessarily
2152                 // the case -- we can have multiple where clauses that
2153                 // are only distinguished by a region, which results
2154                 // in an ambiguity even when all types are fully
2155                 // known, since we don't dispatch based on region
2156                 // relationships.
2157
2158                 // Pick the first substitution that still contains inference variables as the one
2159                 // we're going to emit an error for. If there are none (see above), fall back to
2160                 // a more general error.
2161                 let subst = data.trait_ref.substs.iter().find(|s| s.has_non_region_infer());
2162
2163                 let mut err = if let Some(subst) = subst {
2164                     self.emit_inference_failure_err(body_id, span, subst, ErrorCode::E0283, true)
2165                 } else {
2166                     struct_span_err!(
2167                         self.tcx.sess,
2168                         span,
2169                         E0283,
2170                         "type annotations needed: cannot satisfy `{}`",
2171                         predicate,
2172                     )
2173                 };
2174
2175                 let obligation = obligation.with(self.tcx, trait_ref);
2176                 let mut selcx = SelectionContext::new(&self);
2177                 match selcx.select_from_obligation(&obligation) {
2178                     Ok(None) => {
2179                         let impls = ambiguity::recompute_applicable_impls(self.infcx, &obligation);
2180                         let has_non_region_infer =
2181                             trait_ref.skip_binder().substs.types().any(|t| !t.is_ty_infer());
2182                         // It doesn't make sense to talk about applicable impls if there are more
2183                         // than a handful of them.
2184                         if impls.len() > 1 && impls.len() < 5 && has_non_region_infer {
2185                             self.annotate_source_of_ambiguity(&mut err, &impls, predicate);
2186                         } else {
2187                             if self.tainted_by_errors().is_some() {
2188                                 err.cancel();
2189                                 return;
2190                             }
2191                             err.note(&format!("cannot satisfy `{}`", predicate));
2192                         }
2193                     }
2194                     _ => {
2195                         if self.tainted_by_errors().is_some() {
2196                             err.cancel();
2197                             return;
2198                         }
2199                         err.note(&format!("cannot satisfy `{}`", predicate));
2200                     }
2201                 }
2202
2203                 if let ObligationCauseCode::ItemObligation(def_id) | ObligationCauseCode::ExprItemObligation(def_id, ..) = *obligation.cause.code() {
2204                     self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id());
2205                 } else if let Ok(snippet) = &self.tcx.sess.source_map().span_to_snippet(span)
2206                     && let ObligationCauseCode::BindingObligation(def_id, _) | ObligationCauseCode::ExprBindingObligation(def_id, ..)
2207                         = *obligation.cause.code()
2208                 {
2209                     let generics = self.tcx.generics_of(def_id);
2210                     if generics.params.iter().any(|p| p.name != kw::SelfUpper)
2211                         && !snippet.ends_with('>')
2212                         && !generics.has_impl_trait()
2213                         && !self.tcx.is_fn_trait(def_id)
2214                     {
2215                         // FIXME: To avoid spurious suggestions in functions where type arguments
2216                         // where already supplied, we check the snippet to make sure it doesn't
2217                         // end with a turbofish. Ideally we would have access to a `PathSegment`
2218                         // instead. Otherwise we would produce the following output:
2219                         //
2220                         // error[E0283]: type annotations needed
2221                         //   --> $DIR/issue-54954.rs:3:24
2222                         //    |
2223                         // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
2224                         //    |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^
2225                         //    |                        |
2226                         //    |                        cannot infer type
2227                         //    |                        help: consider specifying the type argument
2228                         //    |                        in the function call:
2229                         //    |                        `Tt::const_val::<[i8; 123]>::<T>`
2230                         // ...
2231                         // LL |     const fn const_val<T: Sized>() -> usize {
2232                         //    |                        - required by this bound in `Tt::const_val`
2233                         //    |
2234                         //    = note: cannot satisfy `_: Tt`
2235
2236                         // Clear any more general suggestions in favor of our specific one
2237                         err.clear_suggestions();
2238
2239                         err.span_suggestion_verbose(
2240                             span.shrink_to_hi(),
2241                             &format!(
2242                                 "consider specifying the type argument{} in the function call",
2243                                 pluralize!(generics.params.len()),
2244                             ),
2245                             format!(
2246                                 "::<{}>",
2247                                 generics
2248                                     .params
2249                                     .iter()
2250                                     .map(|p| p.name.to_string())
2251                                     .collect::<Vec<String>>()
2252                                     .join(", ")
2253                             ),
2254                             Applicability::HasPlaceholders,
2255                         );
2256                     }
2257                 }
2258
2259                 if let (Some(body_id), Some(ty::subst::GenericArgKind::Type(_))) =
2260                     (body_id, subst.map(|subst| subst.unpack()))
2261                 {
2262                     struct FindExprBySpan<'hir> {
2263                         span: Span,
2264                         result: Option<&'hir hir::Expr<'hir>>,
2265                     }
2266
2267                     impl<'v> hir::intravisit::Visitor<'v> for FindExprBySpan<'v> {
2268                         fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2269                             if self.span == ex.span {
2270                                 self.result = Some(ex);
2271                             } else {
2272                                 hir::intravisit::walk_expr(self, ex);
2273                             }
2274                         }
2275                     }
2276
2277                     let mut expr_finder = FindExprBySpan { span, result: None };
2278
2279                     expr_finder.visit_expr(&self.tcx.hir().body(body_id).value);
2280
2281                     if let Some(hir::Expr {
2282                         kind: hir::ExprKind::Path(hir::QPath::Resolved(None, path)), .. }
2283                     ) = expr_finder.result
2284                         && let [
2285                             ..,
2286                             trait_path_segment @ hir::PathSegment {
2287                                 res: rustc_hir::def::Res::Def(rustc_hir::def::DefKind::Trait, trait_id),
2288                                 ..
2289                             },
2290                             hir::PathSegment {
2291                                 ident: assoc_item_name,
2292                                 res: rustc_hir::def::Res::Def(_, item_id),
2293                                 ..
2294                             }
2295                         ] = path.segments
2296                         && data.trait_ref.def_id == *trait_id
2297                         && self.tcx.trait_of_item(*item_id) == Some(*trait_id)
2298                         && let None = self.tainted_by_errors()
2299                     {
2300                         let (verb, noun) = match self.tcx.associated_item(item_id).kind {
2301                             ty::AssocKind::Const => ("refer to the", "constant"),
2302                             ty::AssocKind::Fn => ("call", "function"),
2303                             ty::AssocKind::Type => ("refer to the", "type"), // this is already covered by E0223, but this single match arm doesn't hurt here
2304                         };
2305
2306                         // Replace the more general E0283 with a more specific error
2307                         err.cancel();
2308                         err = self.tcx.sess.struct_span_err_with_code(
2309                             span,
2310                             &format!(
2311                                 "cannot {verb} associated {noun} on trait without specifying the corresponding `impl` type",
2312                              ),
2313                             rustc_errors::error_code!(E0790),
2314                         );
2315
2316                         if let Some(local_def_id) = data.trait_ref.def_id.as_local()
2317                             && let Some(hir::Node::Item(hir::Item { ident: trait_name, kind: hir::ItemKind::Trait(_, _, _, _, trait_item_refs), .. })) = self.tcx.hir().find_by_def_id(local_def_id)
2318                             && let Some(method_ref) = trait_item_refs.iter().find(|item_ref| item_ref.ident == *assoc_item_name) {
2319                             err.span_label(method_ref.span, format!("`{}::{}` defined here", trait_name, assoc_item_name));
2320                         }
2321
2322                         err.span_label(span, format!("cannot {verb} associated {noun} of trait"));
2323
2324                         let trait_impls = self.tcx.trait_impls_of(data.trait_ref.def_id);
2325
2326                         if trait_impls.blanket_impls().is_empty()
2327                             && let Some((impl_ty, _)) = trait_impls.non_blanket_impls().iter().next()
2328                             && let Some(impl_def_id) = impl_ty.def() {
2329                             let message = if trait_impls.non_blanket_impls().len() == 1 {
2330                                 "use the fully-qualified path to the only available implementation".to_string()
2331                             } else {
2332                                 format!(
2333                                     "use a fully-qualified path to a specific available implementation ({} found)",
2334                                     trait_impls.non_blanket_impls().len()
2335                                 )
2336                             };
2337                             let mut suggestions = vec![(
2338                                 trait_path_segment.ident.span.shrink_to_lo(),
2339                                 format!("<{} as ", self.tcx.type_of(impl_def_id))
2340                             )];
2341                             if let Some(generic_arg) = trait_path_segment.args {
2342                                 let between_span = trait_path_segment.ident.span.between(generic_arg.span_ext);
2343                                 // get rid of :: between Trait and <type>
2344                                 // must be '::' between them, otherwise the parser won't accept the code
2345                                 suggestions.push((between_span, "".to_string(),));
2346                                 suggestions.push((generic_arg.span_ext.shrink_to_hi(), format!(">")));
2347                             } else {
2348                                 suggestions.push((trait_path_segment.ident.span.shrink_to_hi(), format!(">")));
2349                             }
2350                             err.multipart_suggestion(
2351                                 message,
2352                                 suggestions,
2353                                 Applicability::MaybeIncorrect
2354                             );
2355                         }
2356                     }
2357                 };
2358
2359                 err
2360             }
2361
2362             ty::PredicateKind::WellFormed(arg) => {
2363                 // Same hacky approach as above to avoid deluging user
2364                 // with error messages.
2365                 if arg.references_error()
2366                     || self.tcx.sess.has_errors().is_some()
2367                     || self.tainted_by_errors().is_some()
2368                 {
2369                     return;
2370                 }
2371
2372                 self.emit_inference_failure_err(body_id, span, arg, ErrorCode::E0282, false)
2373             }
2374
2375             ty::PredicateKind::Subtype(data) => {
2376                 if data.references_error()
2377                     || self.tcx.sess.has_errors().is_some()
2378                     || self.tainted_by_errors().is_some()
2379                 {
2380                     // no need to overload user in such cases
2381                     return;
2382                 }
2383                 let SubtypePredicate { a_is_expected: _, a, b } = data;
2384                 // both must be type variables, or the other would've been instantiated
2385                 assert!(a.is_ty_var() && b.is_ty_var());
2386                 self.emit_inference_failure_err(body_id, span, a.into(), ErrorCode::E0282, true)
2387             }
2388             ty::PredicateKind::Clause(ty::Clause::Projection(data)) => {
2389                 if predicate.references_error() || self.tainted_by_errors().is_some() {
2390                     return;
2391                 }
2392                 let subst = data
2393                     .projection_ty
2394                     .substs
2395                     .iter()
2396                     .chain(Some(data.term.into_arg()))
2397                     .find(|g| g.has_non_region_infer());
2398                 if let Some(subst) = subst {
2399                     let mut err = self.emit_inference_failure_err(
2400                         body_id,
2401                         span,
2402                         subst,
2403                         ErrorCode::E0284,
2404                         true,
2405                     );
2406                     err.note(&format!("cannot satisfy `{}`", predicate));
2407                     err
2408                 } else {
2409                     // If we can't find a substitution, just print a generic error
2410                     let mut err = struct_span_err!(
2411                         self.tcx.sess,
2412                         span,
2413                         E0284,
2414                         "type annotations needed: cannot satisfy `{}`",
2415                         predicate,
2416                     );
2417                     err.span_label(span, &format!("cannot satisfy `{}`", predicate));
2418                     err
2419                 }
2420             }
2421
2422             ty::PredicateKind::ConstEvaluatable(data) => {
2423                 if predicate.references_error() || self.tainted_by_errors().is_some() {
2424                     return;
2425                 }
2426                 let subst = data.walk().find(|g| g.is_non_region_infer());
2427                 if let Some(subst) = subst {
2428                     let err = self.emit_inference_failure_err(
2429                         body_id,
2430                         span,
2431                         subst,
2432                         ErrorCode::E0284,
2433                         true,
2434                     );
2435                     err
2436                 } else {
2437                     // If we can't find a substitution, just print a generic error
2438                     let mut err = struct_span_err!(
2439                         self.tcx.sess,
2440                         span,
2441                         E0284,
2442                         "type annotations needed: cannot satisfy `{}`",
2443                         predicate,
2444                     );
2445                     err.span_label(span, &format!("cannot satisfy `{}`", predicate));
2446                     err
2447                 }
2448             }
2449             _ => {
2450                 if self.tcx.sess.has_errors().is_some() || self.tainted_by_errors().is_some() {
2451                     return;
2452                 }
2453                 let mut err = struct_span_err!(
2454                     self.tcx.sess,
2455                     span,
2456                     E0284,
2457                     "type annotations needed: cannot satisfy `{}`",
2458                     predicate,
2459                 );
2460                 err.span_label(span, &format!("cannot satisfy `{}`", predicate));
2461                 err
2462             }
2463         };
2464         self.note_obligation_cause(&mut err, obligation);
2465         err.emit();
2466     }
2467
2468     fn annotate_source_of_ambiguity(
2469         &self,
2470         err: &mut Diagnostic,
2471         impls: &[DefId],
2472         predicate: ty::Predicate<'tcx>,
2473     ) {
2474         let mut spans = vec![];
2475         let mut crates = vec![];
2476         let mut post = vec![];
2477         for def_id in impls {
2478             match self.tcx.span_of_impl(*def_id) {
2479                 Ok(span) => spans.push(span),
2480                 Err(name) => {
2481                     crates.push(name);
2482                     if let Some(header) = to_pretty_impl_header(self.tcx, *def_id) {
2483                         post.push(header);
2484                     }
2485                 }
2486             }
2487         }
2488         let mut crate_names: Vec<_> = crates.iter().map(|n| format!("`{}`", n)).collect();
2489         crate_names.sort();
2490         crate_names.dedup();
2491         post.sort();
2492         post.dedup();
2493
2494         if self.tainted_by_errors().is_some()
2495             && (crate_names.len() == 1
2496                 && spans.len() == 0
2497                 && ["`core`", "`alloc`", "`std`"].contains(&crate_names[0].as_str())
2498                 || predicate.visit_with(&mut HasNumericInferVisitor).is_break())
2499         {
2500             // Avoid complaining about other inference issues for expressions like
2501             // `42 >> 1`, where the types are still `{integer}`, but we want to
2502             // Do we need `trait_ref.skip_binder().self_ty().is_numeric() &&` too?
2503             // NOTE(eddyb) this was `.cancel()`, but `err`
2504             // is borrowed, so we can't fully defuse it.
2505             err.downgrade_to_delayed_bug();
2506             return;
2507         }
2508
2509         let msg = format!("multiple `impl`s satisfying `{}` found", predicate);
2510         let post = if post.len() > 1 || (post.len() == 1 && post[0].contains('\n')) {
2511             format!(":\n{}", post.iter().map(|p| format!("- {}", p)).collect::<Vec<_>>().join("\n"),)
2512         } else if post.len() == 1 {
2513             format!(": `{}`", post[0])
2514         } else {
2515             String::new()
2516         };
2517
2518         match (spans.len(), crates.len(), crate_names.len()) {
2519             (0, 0, 0) => {
2520                 err.note(&format!("cannot satisfy `{}`", predicate));
2521             }
2522             (0, _, 1) => {
2523                 err.note(&format!("{} in the `{}` crate{}", msg, crates[0], post,));
2524             }
2525             (0, _, _) => {
2526                 err.note(&format!(
2527                     "{} in the following crates: {}{}",
2528                     msg,
2529                     crate_names.join(", "),
2530                     post,
2531                 ));
2532             }
2533             (_, 0, 0) => {
2534                 let span: MultiSpan = spans.into();
2535                 err.span_note(span, &msg);
2536             }
2537             (_, 1, 1) => {
2538                 let span: MultiSpan = spans.into();
2539                 err.span_note(span, &msg);
2540                 err.note(
2541                     &format!("and another `impl` found in the `{}` crate{}", crates[0], post,),
2542                 );
2543             }
2544             _ => {
2545                 let span: MultiSpan = spans.into();
2546                 err.span_note(span, &msg);
2547                 err.note(&format!(
2548                     "and more `impl`s found in the following crates: {}{}",
2549                     crate_names.join(", "),
2550                     post,
2551                 ));
2552             }
2553         }
2554     }
2555
2556     /// Returns `true` if the trait predicate may apply for *some* assignment
2557     /// to the type parameters.
2558     fn predicate_can_apply(
2559         &self,
2560         param_env: ty::ParamEnv<'tcx>,
2561         pred: ty::PolyTraitPredicate<'tcx>,
2562     ) -> bool {
2563         struct ParamToVarFolder<'a, 'tcx> {
2564             infcx: &'a InferCtxt<'tcx>,
2565             var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2566         }
2567
2568         impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
2569             fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2570                 self.infcx.tcx
2571             }
2572
2573             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2574                 if let ty::Param(ty::ParamTy { name, .. }) = *ty.kind() {
2575                     let infcx = self.infcx;
2576                     *self.var_map.entry(ty).or_insert_with(|| {
2577                         infcx.next_ty_var(TypeVariableOrigin {
2578                             kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
2579                             span: DUMMY_SP,
2580                         })
2581                     })
2582                 } else {
2583                     ty.super_fold_with(self)
2584                 }
2585             }
2586         }
2587
2588         self.probe(|_| {
2589             let cleaned_pred =
2590                 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2591
2592             let InferOk { value: cleaned_pred, .. } =
2593                 self.infcx.at(&ObligationCause::dummy(), param_env).normalize(cleaned_pred);
2594
2595             let obligation =
2596                 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, cleaned_pred);
2597
2598             self.predicate_may_hold(&obligation)
2599         })
2600     }
2601
2602     fn note_obligation_cause(&self, err: &mut Diagnostic, obligation: &PredicateObligation<'tcx>) {
2603         // First, attempt to add note to this error with an async-await-specific
2604         // message, and fall back to regular note otherwise.
2605         if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2606             self.note_obligation_cause_code(
2607                 err,
2608                 obligation.predicate,
2609                 obligation.param_env,
2610                 obligation.cause.code(),
2611                 &mut vec![],
2612                 &mut Default::default(),
2613             );
2614             self.suggest_unsized_bound_if_applicable(err, obligation);
2615         }
2616     }
2617
2618     #[instrument(level = "debug", skip_all)]
2619     fn suggest_unsized_bound_if_applicable(
2620         &self,
2621         err: &mut Diagnostic,
2622         obligation: &PredicateObligation<'tcx>,
2623     ) {
2624         let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) = obligation.predicate.kind().skip_binder() else { return; };
2625         let (ObligationCauseCode::BindingObligation(item_def_id, span)
2626         | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..))
2627             = *obligation.cause.code().peel_derives() else { return; };
2628         debug!(?pred, ?item_def_id, ?span);
2629
2630         let (Some(node), true) = (
2631             self.tcx.hir().get_if_local(item_def_id),
2632             Some(pred.def_id()) == self.tcx.lang_items().sized_trait(),
2633         ) else {
2634             return;
2635         };
2636         self.maybe_suggest_unsized_generics(err, span, node);
2637     }
2638
2639     #[instrument(level = "debug", skip_all)]
2640     fn maybe_suggest_unsized_generics(&self, err: &mut Diagnostic, span: Span, node: Node<'tcx>) {
2641         let Some(generics) = node.generics() else {
2642             return;
2643         };
2644         let sized_trait = self.tcx.lang_items().sized_trait();
2645         debug!(?generics.params);
2646         debug!(?generics.predicates);
2647         let Some(param) = generics.params.iter().find(|param| param.span == span) else {
2648             return;
2649         };
2650         // Check that none of the explicit trait bounds is `Sized`. Assume that an explicit
2651         // `Sized` bound is there intentionally and we don't need to suggest relaxing it.
2652         let explicitly_sized = generics
2653             .bounds_for_param(param.def_id)
2654             .flat_map(|bp| bp.bounds)
2655             .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
2656         if explicitly_sized {
2657             return;
2658         }
2659         debug!(?param);
2660         match node {
2661             hir::Node::Item(
2662                 item @ hir::Item {
2663                     // Only suggest indirection for uses of type parameters in ADTs.
2664                     kind:
2665                         hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
2666                     ..
2667                 },
2668             ) => {
2669                 if self.maybe_indirection_for_unsized(err, item, param) {
2670                     return;
2671                 }
2672             }
2673             _ => {}
2674         };
2675         // Didn't add an indirection suggestion, so add a general suggestion to relax `Sized`.
2676         let (span, separator) = if let Some(s) = generics.bounds_span_for_suggestions(param.def_id)
2677         {
2678             (s, " +")
2679         } else {
2680             (span.shrink_to_hi(), ":")
2681         };
2682         err.span_suggestion_verbose(
2683             span,
2684             "consider relaxing the implicit `Sized` restriction",
2685             format!("{} ?Sized", separator),
2686             Applicability::MachineApplicable,
2687         );
2688     }
2689
2690     fn maybe_indirection_for_unsized(
2691         &self,
2692         err: &mut Diagnostic,
2693         item: &Item<'tcx>,
2694         param: &GenericParam<'tcx>,
2695     ) -> bool {
2696         // Suggesting `T: ?Sized` is only valid in an ADT if `T` is only used in a
2697         // borrow. `struct S<'a, T: ?Sized>(&'a T);` is valid, `struct S<T: ?Sized>(T);`
2698         // is not. Look for invalid "bare" parameter uses, and suggest using indirection.
2699         let mut visitor =
2700             FindTypeParam { param: param.name.ident().name, invalid_spans: vec![], nested: false };
2701         visitor.visit_item(item);
2702         if visitor.invalid_spans.is_empty() {
2703             return false;
2704         }
2705         let mut multispan: MultiSpan = param.span.into();
2706         multispan.push_span_label(
2707             param.span,
2708             format!("this could be changed to `{}: ?Sized`...", param.name.ident()),
2709         );
2710         for sp in visitor.invalid_spans {
2711             multispan.push_span_label(
2712                 sp,
2713                 format!("...if indirection were used here: `Box<{}>`", param.name.ident()),
2714             );
2715         }
2716         err.span_help(
2717             multispan,
2718             &format!(
2719                 "you could relax the implicit `Sized` bound on `{T}` if it were \
2720                 used through indirection like `&{T}` or `Box<{T}>`",
2721                 T = param.name.ident(),
2722             ),
2723         );
2724         true
2725     }
2726
2727     fn is_recursive_obligation(
2728         &self,
2729         obligated_types: &mut Vec<Ty<'tcx>>,
2730         cause_code: &ObligationCauseCode<'tcx>,
2731     ) -> bool {
2732         if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
2733             let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2734             let self_ty = parent_trait_ref.skip_binder().self_ty();
2735             if obligated_types.iter().any(|ot| ot == &self_ty) {
2736                 return true;
2737             }
2738             if let ty::Adt(def, substs) = self_ty.kind()
2739                 && let [arg] = &substs[..]
2740                 && let ty::subst::GenericArgKind::Type(ty) = arg.unpack()
2741                 && let ty::Adt(inner_def, _) = ty.kind()
2742                 && inner_def == def
2743             {
2744                 return true;
2745             }
2746         }
2747         false
2748     }
2749 }
2750
2751 /// Look for type `param` in an ADT being used only through a reference to confirm that suggesting
2752 /// `param: ?Sized` would be a valid constraint.
2753 struct FindTypeParam {
2754     param: rustc_span::Symbol,
2755     invalid_spans: Vec<Span>,
2756     nested: bool,
2757 }
2758
2759 impl<'v> Visitor<'v> for FindTypeParam {
2760     fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
2761         // Skip where-clauses, to avoid suggesting indirection for type parameters found there.
2762     }
2763
2764     fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2765         // We collect the spans of all uses of the "bare" type param, like in `field: T` or
2766         // `field: (T, T)` where we could make `T: ?Sized` while skipping cases that are known to be
2767         // valid like `field: &'a T` or `field: *mut T` and cases that *might* have further `Sized`
2768         // obligations like `Box<T>` and `Vec<T>`, but we perform no extra analysis for those cases
2769         // and suggest `T: ?Sized` regardless of their obligations. This is fine because the errors
2770         // in that case should make what happened clear enough.
2771         match ty.kind {
2772             hir::TyKind::Ptr(_) | hir::TyKind::Rptr(..) | hir::TyKind::TraitObject(..) => {}
2773             hir::TyKind::Path(hir::QPath::Resolved(None, path))
2774                 if path.segments.len() == 1 && path.segments[0].ident.name == self.param =>
2775             {
2776                 if !self.nested {
2777                     debug!(?ty, "FindTypeParam::visit_ty");
2778                     self.invalid_spans.push(ty.span);
2779                 }
2780             }
2781             hir::TyKind::Path(_) => {
2782                 let prev = self.nested;
2783                 self.nested = true;
2784                 hir::intravisit::walk_ty(self, ty);
2785                 self.nested = prev;
2786             }
2787             _ => {
2788                 hir::intravisit::walk_ty(self, ty);
2789             }
2790         }
2791     }
2792 }
2793
2794 /// Summarizes information
2795 #[derive(Clone)]
2796 pub enum ArgKind {
2797     /// An argument of non-tuple type. Parameters are (name, ty)
2798     Arg(String, String),
2799
2800     /// An argument of tuple type. For a "found" argument, the span is
2801     /// the location in the source of the pattern. For an "expected"
2802     /// argument, it will be None. The vector is a list of (name, ty)
2803     /// strings for the components of the tuple.
2804     Tuple(Option<Span>, Vec<(String, String)>),
2805 }
2806
2807 impl ArgKind {
2808     fn empty() -> ArgKind {
2809         ArgKind::Arg("_".to_owned(), "_".to_owned())
2810     }
2811
2812     /// Creates an `ArgKind` from the expected type of an
2813     /// argument. It has no name (`_`) and an optional source span.
2814     pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
2815         match t.kind() {
2816             ty::Tuple(tys) => ArgKind::Tuple(
2817                 span,
2818                 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
2819             ),
2820             _ => ArgKind::Arg("_".to_owned(), t.to_string()),
2821         }
2822     }
2823 }
2824
2825 struct HasNumericInferVisitor;
2826
2827 impl<'tcx> ty::TypeVisitor<'tcx> for HasNumericInferVisitor {
2828     type BreakTy = ();
2829
2830     fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2831         if matches!(ty.kind(), ty::Infer(ty::FloatVar(_) | ty::IntVar(_))) {
2832             ControlFlow::Break(())
2833         } else {
2834             ControlFlow::CONTINUE
2835         }
2836     }
2837 }
2838
2839 pub enum DefIdOrName {
2840     DefId(DefId),
2841     Name(&'static str),
2842 }