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