• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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, 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};
13 use crate::solve::{GenerateProofTree, InferCtxtEvalExt, UseGlobalCache};
14 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
15 use crate::traits::specialize::to_pretty_impl_header;
16 use crate::traits::NormalizeExt;
17 use on_unimplemented::{AppendConstMessage, OnUnimplementedNote, TypeErrCtxtExt as _};
18 use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
19 use rustc_errors::{
20     pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
21     MultiSpan, Style,
22 };
23 use rustc_hir as hir;
24 use rustc_hir::def::Namespace;
25 use rustc_hir::def_id::{DefId, LocalDefId};
26 use rustc_hir::intravisit::Visitor;
27 use rustc_hir::{GenericParam, Item, Node};
28 use rustc_infer::infer::error_reporting::TypeErrCtxt;
29 use rustc_infer::infer::{InferOk, TypeTrace};
30 use rustc_middle::traits::select::OverflowError;
31 use rustc_middle::traits::solve::Goal;
32 use rustc_middle::traits::{DefiningAnchor, SelectionOutputTypeParameterMismatch};
33 use rustc_middle::ty::abstract_const::NotConstEvaluatable;
34 use rustc_middle::ty::error::{ExpectedFound, TypeError};
35 use rustc_middle::ty::fold::{BottomUpFolder, TypeFolder, TypeSuperFoldable};
36 use rustc_middle::ty::print::{with_forced_trimmed_paths, FmtPrinter, Print};
37 use rustc_middle::ty::{
38     self, SubtypePredicate, ToPolyTraitRef, ToPredicate, TraitRef, Ty, TyCtxt, TypeFoldable,
39     TypeVisitable, TypeVisitableExt,
40 };
41 use rustc_session::config::{DumpSolverProofTree, TraitSolver};
42 use rustc_session::Limit;
43 use rustc_span::def_id::LOCAL_CRATE;
44 use rustc_span::symbol::sym;
45 use rustc_span::{ExpnKind, Span, DUMMY_SP};
46 use std::borrow::Cow;
47 use std::fmt;
48 use std::io::Write;
49 use std::iter;
50 use std::ops::ControlFlow;
51 use suggestions::TypeErrCtxtExt as _;
52 
53 pub use rustc_infer::traits::error_reporting::*;
54 
55 // When outputting impl candidates, prefer showing those that are more similar.
56 //
57 // We also compare candidates after skipping lifetimes, which has a lower
58 // priority than exact matches.
59 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
60 pub enum CandidateSimilarity {
61     Exact { ignoring_lifetimes: bool },
62     Fuzzy { ignoring_lifetimes: bool },
63 }
64 
65 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
66 pub struct ImplCandidate<'tcx> {
67     pub trait_ref: ty::TraitRef<'tcx>,
68     pub similarity: CandidateSimilarity,
69 }
70 
71 enum GetSafeTransmuteErrorAndReason {
72     Silent,
73     Error { err_msg: String, safe_transmute_explanation: String },
74 }
75 
76 pub trait InferCtxtExt<'tcx> {
77     /// Given some node representing a fn-like thing in the HIR map,
78     /// returns a span and `ArgKind` information that describes the
79     /// arguments it expects. This can be supplied to
80     /// `report_arg_count_mismatch`.
get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Option<Span>, Vec<ArgKind>)>81     fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Option<Span>, Vec<ArgKind>)>;
82 
83     /// Reports an error when the number of arguments needed by a
84     /// trait match doesn't match the number that the expression
85     /// provides.
report_arg_count_mismatch( &self, span: Span, found_span: Option<Span>, expected_args: Vec<ArgKind>, found_args: Vec<ArgKind>, is_closure: bool, closure_pipe_span: Option<Span>, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>86     fn report_arg_count_mismatch(
87         &self,
88         span: Span,
89         found_span: Option<Span>,
90         expected_args: Vec<ArgKind>,
91         found_args: Vec<ArgKind>,
92         is_closure: bool,
93         closure_pipe_span: Option<Span>,
94     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
95 
96     /// Checks if the type implements one of `Fn`, `FnMut`, or `FnOnce`
97     /// in that order, and returns the generic type corresponding to the
98     /// argument of that trait (corresponding to the closure arguments).
type_implements_fn_trait( &self, param_env: ty::ParamEnv<'tcx>, ty: ty::Binder<'tcx, Ty<'tcx>>, constness: ty::BoundConstness, polarity: ty::ImplPolarity, ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()>99     fn type_implements_fn_trait(
100         &self,
101         param_env: ty::ParamEnv<'tcx>,
102         ty: ty::Binder<'tcx, Ty<'tcx>>,
103         constness: ty::BoundConstness,
104         polarity: ty::ImplPolarity,
105     ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()>;
106 }
107 
108 pub trait TypeErrCtxtExt<'tcx> {
build_overflow_error<T>( &self, predicate: &T, span: Span, suggest_increasing_limit: bool, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> where T: fmt::Display + TypeFoldable<TyCtxt<'tcx>> + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>, <T as Print<'tcx, FmtPrinter<'tcx, 'tcx>>>::Error: std::fmt::Debug109     fn build_overflow_error<T>(
110         &self,
111         predicate: &T,
112         span: Span,
113         suggest_increasing_limit: bool,
114     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>
115     where
116         T: fmt::Display
117             + TypeFoldable<TyCtxt<'tcx>>
118             + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>,
119         <T as Print<'tcx, FmtPrinter<'tcx, 'tcx>>>::Error: std::fmt::Debug;
120 
report_overflow_error<T>( &self, predicate: &T, span: Span, suggest_increasing_limit: bool, mutate: impl FnOnce(&mut Diagnostic), ) -> ! where T: fmt::Display + TypeFoldable<TyCtxt<'tcx>> + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>, <T as Print<'tcx, FmtPrinter<'tcx, 'tcx>>>::Error: std::fmt::Debug121     fn report_overflow_error<T>(
122         &self,
123         predicate: &T,
124         span: Span,
125         suggest_increasing_limit: bool,
126         mutate: impl FnOnce(&mut Diagnostic),
127     ) -> !
128     where
129         T: fmt::Display
130             + TypeFoldable<TyCtxt<'tcx>>
131             + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>,
132         <T as Print<'tcx, FmtPrinter<'tcx, 'tcx>>>::Error: std::fmt::Debug;
133 
report_overflow_no_abort(&self, obligation: PredicateObligation<'tcx>) -> ErrorGuaranteed134     fn report_overflow_no_abort(&self, obligation: PredicateObligation<'tcx>) -> ErrorGuaranteed;
135 
report_fulfillment_errors(&self, errors: &[FulfillmentError<'tcx>]) -> ErrorGuaranteed136     fn report_fulfillment_errors(&self, errors: &[FulfillmentError<'tcx>]) -> ErrorGuaranteed;
137 
report_overflow_obligation<T>( &self, obligation: &Obligation<'tcx, T>, suggest_increasing_limit: bool, ) -> ! where T: ToPredicate<'tcx> + Clone138     fn report_overflow_obligation<T>(
139         &self,
140         obligation: &Obligation<'tcx, T>,
141         suggest_increasing_limit: bool,
142     ) -> !
143     where
144         T: ToPredicate<'tcx> + Clone;
145 
suggest_new_overflow_limit(&self, err: &mut Diagnostic)146     fn suggest_new_overflow_limit(&self, err: &mut Diagnostic);
147 
report_overflow_obligation_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> !148     fn report_overflow_obligation_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> !;
149 
150     /// The `root_obligation` parameter should be the `root_obligation` field
151     /// from a `FulfillmentError`. If no `FulfillmentError` is available,
152     /// then it should be the same as `obligation`.
report_selection_error( &self, obligation: PredicateObligation<'tcx>, root_obligation: &PredicateObligation<'tcx>, error: &SelectionError<'tcx>, )153     fn report_selection_error(
154         &self,
155         obligation: PredicateObligation<'tcx>,
156         root_obligation: &PredicateObligation<'tcx>,
157         error: &SelectionError<'tcx>,
158     );
159 
report_const_param_not_wf( &self, ty: Ty<'tcx>, obligation: &PredicateObligation<'tcx>, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>160     fn report_const_param_not_wf(
161         &self,
162         ty: Ty<'tcx>,
163         obligation: &PredicateObligation<'tcx>,
164     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
165 }
166 
167 impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> {
168     /// Given some node representing a fn-like thing in the HIR map,
169     /// returns a span and `ArgKind` information that describes the
170     /// arguments it expects. This can be supplied to
171     /// `report_arg_count_mismatch`.
get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Option<Span>, Vec<ArgKind>)>172     fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Option<Span>, Vec<ArgKind>)> {
173         let sm = self.tcx.sess.source_map();
174         let hir = self.tcx.hir();
175         Some(match node {
176             Node::Expr(&hir::Expr {
177                 kind: hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, fn_arg_span, .. }),
178                 ..
179             }) => (
180                 fn_decl_span,
181                 fn_arg_span,
182                 hir.body(body)
183                     .params
184                     .iter()
185                     .map(|arg| {
186                         if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
187                             *arg.pat
188                         {
189                             Some(ArgKind::Tuple(
190                                 Some(span),
191                                 args.iter()
192                                     .map(|pat| {
193                                         sm.span_to_snippet(pat.span)
194                                             .ok()
195                                             .map(|snippet| (snippet, "_".to_owned()))
196                                     })
197                                     .collect::<Option<Vec<_>>>()?,
198                             ))
199                         } else {
200                             let name = sm.span_to_snippet(arg.pat.span).ok()?;
201                             Some(ArgKind::Arg(name, "_".to_owned()))
202                         }
203                     })
204                     .collect::<Option<Vec<ArgKind>>>()?,
205             ),
206             Node::Item(&hir::Item { kind: hir::ItemKind::Fn(ref sig, ..), .. })
207             | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(ref sig, _), .. })
208             | Node::TraitItem(&hir::TraitItem {
209                 kind: hir::TraitItemKind::Fn(ref sig, _), ..
210             }) => (
211                 sig.span,
212                 None,
213                 sig.decl
214                     .inputs
215                     .iter()
216                     .map(|arg| match arg.kind {
217                         hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
218                             Some(arg.span),
219                             vec![("_".to_owned(), "_".to_owned()); tys.len()],
220                         ),
221                         _ => ArgKind::empty(),
222                     })
223                     .collect::<Vec<ArgKind>>(),
224             ),
225             Node::Ctor(ref variant_data) => {
226                 let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| hir.span(id));
227                 (span, None, vec![ArgKind::empty(); variant_data.fields().len()])
228             }
229             _ => panic!("non-FnLike node found: {:?}", node),
230         })
231     }
232 
233     /// Reports an error when the number of arguments needed by a
234     /// trait match doesn't match the number that the expression
235     /// provides.
report_arg_count_mismatch( &self, span: Span, found_span: Option<Span>, expected_args: Vec<ArgKind>, found_args: Vec<ArgKind>, is_closure: bool, closure_arg_span: Option<Span>, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>236     fn report_arg_count_mismatch(
237         &self,
238         span: Span,
239         found_span: Option<Span>,
240         expected_args: Vec<ArgKind>,
241         found_args: Vec<ArgKind>,
242         is_closure: bool,
243         closure_arg_span: Option<Span>,
244     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
245         let kind = if is_closure { "closure" } else { "function" };
246 
247         let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
248             let arg_length = arguments.len();
249             let distinct = matches!(other, &[ArgKind::Tuple(..)]);
250             match (arg_length, arguments.get(0)) {
251                 (1, Some(ArgKind::Tuple(_, fields))) => {
252                     format!("a single {}-tuple as argument", fields.len())
253                 }
254                 _ => format!(
255                     "{} {}argument{}",
256                     arg_length,
257                     if distinct && arg_length > 1 { "distinct " } else { "" },
258                     pluralize!(arg_length)
259                 ),
260             }
261         };
262 
263         let expected_str = args_str(&expected_args, &found_args);
264         let found_str = args_str(&found_args, &expected_args);
265 
266         let mut err = struct_span_err!(
267             self.tcx.sess,
268             span,
269             E0593,
270             "{} is expected to take {}, but it takes {}",
271             kind,
272             expected_str,
273             found_str,
274         );
275 
276         err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
277 
278         if let Some(found_span) = found_span {
279             err.span_label(found_span, format!("takes {}", found_str));
280 
281             // Suggest to take and ignore the arguments with expected_args_length `_`s if
282             // found arguments is empty (assume the user just wants to ignore args in this case).
283             // For example, if `expected_args_length` is 2, suggest `|_, _|`.
284             if found_args.is_empty() && is_closure {
285                 let underscores = vec!["_"; expected_args.len()].join(", ");
286                 err.span_suggestion_verbose(
287                     closure_arg_span.unwrap_or(found_span),
288                     format!(
289                         "consider changing the closure to take and ignore the expected argument{}",
290                         pluralize!(expected_args.len())
291                     ),
292                     format!("|{}|", underscores),
293                     Applicability::MachineApplicable,
294                 );
295             }
296 
297             if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
298                 if fields.len() == expected_args.len() {
299                     let sugg = fields
300                         .iter()
301                         .map(|(name, _)| name.to_owned())
302                         .collect::<Vec<String>>()
303                         .join(", ");
304                     err.span_suggestion_verbose(
305                         found_span,
306                         "change the closure to take multiple arguments instead of a single tuple",
307                         format!("|{}|", sugg),
308                         Applicability::MachineApplicable,
309                     );
310                 }
311             }
312             if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..]
313                 && fields.len() == found_args.len()
314                 && is_closure
315             {
316                 let sugg = format!(
317                     "|({}){}|",
318                     found_args
319                         .iter()
320                         .map(|arg| match arg {
321                             ArgKind::Arg(name, _) => name.to_owned(),
322                             _ => "_".to_owned(),
323                         })
324                         .collect::<Vec<String>>()
325                         .join(", "),
326                     // add type annotations if available
327                     if found_args.iter().any(|arg| match arg {
328                         ArgKind::Arg(_, ty) => ty != "_",
329                         _ => false,
330                     }) {
331                         format!(
332                             ": ({})",
333                             fields
334                                 .iter()
335                                 .map(|(_, ty)| ty.to_owned())
336                                 .collect::<Vec<String>>()
337                                 .join(", ")
338                         )
339                     } else {
340                         String::new()
341                     },
342                 );
343                 err.span_suggestion_verbose(
344                     found_span,
345                     "change the closure to accept a tuple instead of individual arguments",
346                     sugg,
347                     Applicability::MachineApplicable,
348                 );
349             }
350         }
351 
352         err
353     }
354 
type_implements_fn_trait( &self, param_env: ty::ParamEnv<'tcx>, ty: ty::Binder<'tcx, Ty<'tcx>>, constness: ty::BoundConstness, polarity: ty::ImplPolarity, ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()>355     fn type_implements_fn_trait(
356         &self,
357         param_env: ty::ParamEnv<'tcx>,
358         ty: ty::Binder<'tcx, Ty<'tcx>>,
359         constness: ty::BoundConstness,
360         polarity: ty::ImplPolarity,
361     ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> {
362         self.commit_if_ok(|_| {
363             for trait_def_id in [
364                 self.tcx.lang_items().fn_trait(),
365                 self.tcx.lang_items().fn_mut_trait(),
366                 self.tcx.lang_items().fn_once_trait(),
367             ] {
368                 let Some(trait_def_id) = trait_def_id else { continue };
369                 // Make a fresh inference variable so we can determine what the substitutions
370                 // of the trait are.
371                 let var = self.next_ty_var(TypeVariableOrigin {
372                     span: DUMMY_SP,
373                     kind: TypeVariableOriginKind::MiscVariable,
374                 });
375                 let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, [ty.skip_binder(), var]);
376                 let obligation = Obligation::new(
377                     self.tcx,
378                     ObligationCause::dummy(),
379                     param_env,
380                     ty.rebind(ty::TraitPredicate { trait_ref, constness, polarity }),
381                 );
382                 let ocx = ObligationCtxt::new(self);
383                 ocx.register_obligation(obligation);
384                 if ocx.select_all_or_error().is_empty() {
385                     return Ok((
386                         self.tcx
387                             .fn_trait_kind_from_def_id(trait_def_id)
388                             .expect("expected to map DefId to ClosureKind"),
389                         ty.rebind(self.resolve_vars_if_possible(var)),
390                     ));
391                 }
392             }
393 
394             Err(())
395         })
396     }
397 }
398 
399 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
report_fulfillment_errors(&self, errors: &[FulfillmentError<'tcx>]) -> ErrorGuaranteed400     fn report_fulfillment_errors(&self, errors: &[FulfillmentError<'tcx>]) -> ErrorGuaranteed {
401         #[derive(Debug)]
402         struct ErrorDescriptor<'tcx> {
403             predicate: ty::Predicate<'tcx>,
404             index: Option<usize>, // None if this is an old error
405         }
406 
407         let mut error_map: FxIndexMap<_, Vec<_>> = self
408             .reported_trait_errors
409             .borrow()
410             .iter()
411             .map(|(&span, predicates)| {
412                 (
413                     span,
414                     predicates
415                         .iter()
416                         .map(|&predicate| ErrorDescriptor { predicate, index: None })
417                         .collect(),
418                 )
419             })
420             .collect();
421 
422         for (index, error) in errors.iter().enumerate() {
423             // We want to ignore desugarings here: spans are equivalent even
424             // if one is the result of a desugaring and the other is not.
425             let mut span = error.obligation.cause.span;
426             let expn_data = span.ctxt().outer_expn_data();
427             if let ExpnKind::Desugaring(_) = expn_data.kind {
428                 span = expn_data.call_site;
429             }
430 
431             error_map.entry(span).or_default().push(ErrorDescriptor {
432                 predicate: error.obligation.predicate,
433                 index: Some(index),
434             });
435 
436             self.reported_trait_errors
437                 .borrow_mut()
438                 .entry(span)
439                 .or_default()
440                 .push(error.obligation.predicate);
441         }
442 
443         // We do this in 2 passes because we want to display errors in order, though
444         // maybe it *is* better to sort errors by span or something.
445         let mut is_suppressed = vec![false; errors.len()];
446         for (_, error_set) in error_map.iter() {
447             // We want to suppress "duplicate" errors with the same span.
448             for error in error_set {
449                 if let Some(index) = error.index {
450                     // Suppress errors that are either:
451                     // 1) strictly implied by another error.
452                     // 2) implied by an error with a smaller index.
453                     for error2 in error_set {
454                         if error2.index.is_some_and(|index2| is_suppressed[index2]) {
455                             // Avoid errors being suppressed by already-suppressed
456                             // errors, to prevent all errors from being suppressed
457                             // at once.
458                             continue;
459                         }
460 
461                         if self.error_implies(error2.predicate, error.predicate)
462                             && !(error2.index >= error.index
463                                 && self.error_implies(error.predicate, error2.predicate))
464                         {
465                             info!("skipping {:?} (implied by {:?})", error, error2);
466                             is_suppressed[index] = true;
467                             break;
468                         }
469                     }
470                 }
471             }
472         }
473 
474         for from_expansion in [false, true] {
475             for (error, suppressed) in iter::zip(errors, &is_suppressed) {
476                 if !suppressed && error.obligation.cause.span.from_expansion() == from_expansion {
477                     self.report_fulfillment_error(error);
478                 }
479             }
480         }
481 
482         self.tcx.sess.delay_span_bug(DUMMY_SP, "expected fulfillment errors")
483     }
484 
485     /// Reports that an overflow has occurred and halts compilation. We
486     /// halt compilation unconditionally because it is important that
487     /// overflows never be masked -- they basically represent computations
488     /// whose result could not be truly determined and thus we can't say
489     /// if the program type checks or not -- and they are unusual
490     /// occurrences in any case.
report_overflow_error<T>( &self, predicate: &T, span: Span, suggest_increasing_limit: bool, mutate: impl FnOnce(&mut Diagnostic), ) -> ! where T: fmt::Display + TypeFoldable<TyCtxt<'tcx>> + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>, <T as Print<'tcx, FmtPrinter<'tcx, 'tcx>>>::Error: std::fmt::Debug,491     fn report_overflow_error<T>(
492         &self,
493         predicate: &T,
494         span: Span,
495         suggest_increasing_limit: bool,
496         mutate: impl FnOnce(&mut Diagnostic),
497     ) -> !
498     where
499         T: fmt::Display
500             + TypeFoldable<TyCtxt<'tcx>>
501             + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>,
502         <T as Print<'tcx, FmtPrinter<'tcx, 'tcx>>>::Error: std::fmt::Debug,
503     {
504         let mut err = self.build_overflow_error(predicate, span, suggest_increasing_limit);
505         mutate(&mut err);
506         err.emit();
507 
508         self.tcx.sess.abort_if_errors();
509         bug!();
510     }
511 
build_overflow_error<T>( &self, predicate: &T, span: Span, suggest_increasing_limit: bool, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> where T: fmt::Display + TypeFoldable<TyCtxt<'tcx>> + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>, <T as Print<'tcx, FmtPrinter<'tcx, 'tcx>>>::Error: std::fmt::Debug,512     fn build_overflow_error<T>(
513         &self,
514         predicate: &T,
515         span: Span,
516         suggest_increasing_limit: bool,
517     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>
518     where
519         T: fmt::Display
520             + TypeFoldable<TyCtxt<'tcx>>
521             + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>,
522         <T as Print<'tcx, FmtPrinter<'tcx, 'tcx>>>::Error: std::fmt::Debug,
523     {
524         let predicate = self.resolve_vars_if_possible(predicate.clone());
525         let mut pred_str = predicate.to_string();
526 
527         if pred_str.len() > 50 {
528             // We don't need to save the type to a file, we will be talking about this type already
529             // in a separate note when we explain the obligation, so it will be available that way.
530             pred_str = predicate
531                 .print(FmtPrinter::new_with_limit(
532                     self.tcx,
533                     Namespace::TypeNS,
534                     rustc_session::Limit(6),
535                 ))
536                 .unwrap()
537                 .into_buffer();
538         }
539         let mut err = struct_span_err!(
540             self.tcx.sess,
541             span,
542             E0275,
543             "overflow evaluating the requirement `{}`",
544             pred_str,
545         );
546 
547         if suggest_increasing_limit {
548             self.suggest_new_overflow_limit(&mut err);
549         }
550 
551         err
552     }
553 
554     /// Reports that an overflow has occurred and halts compilation. We
555     /// halt compilation unconditionally because it is important that
556     /// overflows never be masked -- they basically represent computations
557     /// whose result could not be truly determined and thus we can't say
558     /// if the program type checks or not -- and they are unusual
559     /// occurrences in any case.
report_overflow_obligation<T>( &self, obligation: &Obligation<'tcx, T>, suggest_increasing_limit: bool, ) -> ! where T: ToPredicate<'tcx> + Clone,560     fn report_overflow_obligation<T>(
561         &self,
562         obligation: &Obligation<'tcx, T>,
563         suggest_increasing_limit: bool,
564     ) -> !
565     where
566         T: ToPredicate<'tcx> + Clone,
567     {
568         let predicate = obligation.predicate.clone().to_predicate(self.tcx);
569         let predicate = self.resolve_vars_if_possible(predicate);
570         self.report_overflow_error(
571             &predicate,
572             obligation.cause.span,
573             suggest_increasing_limit,
574             |err| {
575                 self.note_obligation_cause_code(
576                     obligation.cause.body_id,
577                     err,
578                     predicate,
579                     obligation.param_env,
580                     obligation.cause.code(),
581                     &mut vec![],
582                     &mut Default::default(),
583                 );
584             },
585         );
586     }
587 
suggest_new_overflow_limit(&self, err: &mut Diagnostic)588     fn suggest_new_overflow_limit(&self, err: &mut Diagnostic) {
589         let suggested_limit = match self.tcx.recursion_limit() {
590             Limit(0) => Limit(2),
591             limit => limit * 2,
592         };
593         err.help(format!(
594             "consider increasing the recursion limit by adding a \
595              `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
596             suggested_limit,
597             self.tcx.crate_name(LOCAL_CRATE),
598         ));
599     }
600 
601     /// Reports that a cycle was detected which led to overflow and halts
602     /// compilation. This is equivalent to `report_overflow_obligation` except
603     /// that we can give a more helpful error message (and, in particular,
604     /// we do not suggest increasing the overflow limit, which is not
605     /// going to help).
report_overflow_obligation_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> !606     fn report_overflow_obligation_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
607         let cycle = self.resolve_vars_if_possible(cycle.to_owned());
608         assert!(!cycle.is_empty());
609 
610         debug!(?cycle, "report_overflow_error_cycle");
611 
612         // The 'deepest' obligation is most likely to have a useful
613         // cause 'backtrace'
614         self.report_overflow_obligation(
615             cycle.iter().max_by_key(|p| p.recursion_depth).unwrap(),
616             false,
617         );
618     }
619 
report_overflow_no_abort(&self, obligation: PredicateObligation<'tcx>) -> ErrorGuaranteed620     fn report_overflow_no_abort(&self, obligation: PredicateObligation<'tcx>) -> ErrorGuaranteed {
621         let obligation = self.resolve_vars_if_possible(obligation);
622         let mut err = self.build_overflow_error(&obligation.predicate, obligation.cause.span, true);
623         self.note_obligation_cause(&mut err, &obligation);
624         self.point_at_returns_when_relevant(&mut err, &obligation);
625         err.emit()
626     }
627 
report_selection_error( &self, mut obligation: PredicateObligation<'tcx>, root_obligation: &PredicateObligation<'tcx>, error: &SelectionError<'tcx>, )628     fn report_selection_error(
629         &self,
630         mut obligation: PredicateObligation<'tcx>,
631         root_obligation: &PredicateObligation<'tcx>,
632         error: &SelectionError<'tcx>,
633     ) {
634         let tcx = self.tcx;
635 
636         if tcx.sess.opts.unstable_opts.dump_solver_proof_tree == DumpSolverProofTree::OnError {
637             dump_proof_tree(root_obligation, self.infcx);
638         }
639 
640         let mut span = obligation.cause.span;
641         // FIXME: statically guarantee this by tainting after the diagnostic is emitted
642         self.set_tainted_by_errors(
643             tcx.sess.delay_span_bug(span, "`report_selection_error` did not emit an error"),
644         );
645 
646         let mut err = match *error {
647             SelectionError::Unimplemented => {
648                 // If this obligation was generated as a result of well-formedness checking, see if we
649                 // can get a better error message by performing HIR-based well-formedness checking.
650                 if let ObligationCauseCode::WellFormed(Some(wf_loc)) =
651                     root_obligation.cause.code().peel_derives()
652                     && !obligation.predicate.has_non_region_infer()
653                 {
654                     if let Some(cause) = self
655                         .tcx
656                         .diagnostic_hir_wf_check((tcx.erase_regions(obligation.predicate), *wf_loc))
657                     {
658                         obligation.cause = cause.clone();
659                         span = obligation.cause.span;
660                     }
661                 }
662 
663                 if let ObligationCauseCode::CompareImplItemObligation {
664                     impl_item_def_id,
665                     trait_item_def_id,
666                     kind: _,
667                 } = *obligation.cause.code()
668                 {
669                     self.report_extra_impl_obligation(
670                         span,
671                         impl_item_def_id,
672                         trait_item_def_id,
673                         &format!("`{}`", obligation.predicate),
674                     )
675                     .emit();
676                     return;
677                 }
678 
679                 // Report a const-param specific error
680                 if let ObligationCauseCode::ConstParam(ty) = *obligation.cause.code().peel_derives()
681                 {
682                     self.report_const_param_not_wf(ty, &obligation).emit();
683                     return;
684                 }
685 
686                 let bound_predicate = obligation.predicate.kind();
687                 match bound_predicate.skip_binder() {
688                     ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_predicate)) => {
689                         let trait_predicate = bound_predicate.rebind(trait_predicate);
690                         let mut trait_predicate = self.resolve_vars_if_possible(trait_predicate);
691 
692                         trait_predicate.remap_constness_diag(obligation.param_env);
693                         let predicate_is_const = ty::BoundConstness::ConstIfConst
694                             == trait_predicate.skip_binder().constness;
695 
696                         if self.tcx.sess.has_errors().is_some()
697                             && trait_predicate.references_error()
698                         {
699                             return;
700                         }
701                         let trait_ref = trait_predicate.to_poly_trait_ref();
702 
703                         let (post_message, pre_message, type_def) = self
704                             .get_parent_trait_ref(obligation.cause.code())
705                             .map(|(t, s)| {
706                                 (
707                                     format!(" in `{}`", t),
708                                     format!("within `{}`, ", t),
709                                     s.map(|s| (format!("within this `{}`", t), s)),
710                                 )
711                             })
712                             .unwrap_or_default();
713 
714                         let OnUnimplementedNote {
715                             message,
716                             label,
717                             note,
718                             parent_label,
719                             append_const_msg,
720                         } = self.on_unimplemented_note(trait_ref, &obligation);
721                         let have_alt_message = message.is_some() || label.is_some();
722                         let is_try_conversion = self.is_try_conversion(span, trait_ref.def_id());
723                         let is_unsize =
724                             Some(trait_ref.def_id()) == self.tcx.lang_items().unsize_trait();
725                         let (message, note, append_const_msg) = if is_try_conversion {
726                             (
727                                 Some(format!(
728                                     "`?` couldn't convert the error to `{}`",
729                                     trait_ref.skip_binder().self_ty(),
730                                 )),
731                                 Some(
732                                     "the question mark operation (`?`) implicitly performs a \
733                                      conversion on the error value using the `From` trait"
734                                         .to_owned(),
735                                 ),
736                                 Some(AppendConstMessage::Default),
737                             )
738                         } else {
739                             (message, note, append_const_msg)
740                         };
741 
742                         let err_msg = self.get_standard_error_message(
743                             &trait_predicate,
744                             message,
745                             predicate_is_const,
746                             append_const_msg,
747                             post_message,
748                         );
749 
750                         let (err_msg, safe_transmute_explanation) = if Some(trait_ref.def_id())
751                             == self.tcx.lang_items().transmute_trait()
752                         {
753                             // Recompute the safe transmute reason and use that for the error reporting
754                             match self.get_safe_transmute_error_and_reason(
755                                 obligation.clone(),
756                                 trait_ref,
757                                 span,
758                             ) {
759                                 GetSafeTransmuteErrorAndReason::Silent => return,
760                                 GetSafeTransmuteErrorAndReason::Error {
761                                     err_msg,
762                                     safe_transmute_explanation,
763                                 } => (err_msg, Some(safe_transmute_explanation)),
764                             }
765                         } else {
766                             (err_msg, None)
767                         };
768 
769                         let mut err = struct_span_err!(self.tcx.sess, span, E0277, "{}", err_msg);
770 
771                         if is_try_conversion && let Some(ret_span) = self.return_type_span(&obligation) {
772                             err.span_label(
773                                 ret_span,
774                                 format!(
775                                     "expected `{}` because of this",
776                                     trait_ref.skip_binder().self_ty()
777                                 ),
778                             );
779                         }
780 
781                         if Some(trait_ref.def_id()) == tcx.lang_items().tuple_trait() {
782                             self.add_tuple_trait_message(
783                                 &obligation.cause.code().peel_derives(),
784                                 &mut err,
785                             );
786                         }
787 
788                         if Some(trait_ref.def_id()) == tcx.lang_items().drop_trait()
789                             && predicate_is_const
790                         {
791                             err.note("`~const Drop` was renamed to `~const Destruct`");
792                             err.note("See <https://github.com/rust-lang/rust/pull/94901> for more details");
793                         }
794 
795                         let explanation = get_explanation_based_on_obligation(
796                             &obligation,
797                             trait_ref,
798                             &trait_predicate,
799                             pre_message,
800                         );
801 
802                         self.check_for_binding_assigned_block_without_tail_expression(
803                             &obligation,
804                             &mut err,
805                             trait_predicate,
806                         );
807                         if self.suggest_add_reference_to_arg(
808                             &obligation,
809                             &mut err,
810                             trait_predicate,
811                             have_alt_message,
812                         ) {
813                             self.note_obligation_cause(&mut err, &obligation);
814                             err.emit();
815                             return;
816                         }
817                         if let Some(s) = label {
818                             // If it has a custom `#[rustc_on_unimplemented]`
819                             // error message, let's display it as the label!
820                             err.span_label(span, s);
821                             if !matches!(trait_ref.skip_binder().self_ty().kind(), ty::Param(_)) {
822                                 // When the self type is a type param We don't need to "the trait
823                                 // `std::marker::Sized` is not implemented for `T`" as we will point
824                                 // at the type param with a label to suggest constraining it.
825                                 err.help(explanation);
826                             }
827                         } else if let Some(custom_explanation) = safe_transmute_explanation {
828                             err.span_label(span, custom_explanation);
829                         } else {
830                             err.span_label(span, explanation);
831                         }
832 
833                         if let ObligationCauseCode::Coercion { source, target } =
834                             *obligation.cause.code().peel_derives()
835                         {
836                             if Some(trait_ref.def_id()) == self.tcx.lang_items().sized_trait() {
837                                 self.suggest_borrowing_for_object_cast(
838                                     &mut err,
839                                     &root_obligation,
840                                     source,
841                                     target,
842                                 );
843                             }
844                         }
845 
846                         let UnsatisfiedConst(unsatisfied_const) = self
847                             .maybe_add_note_for_unsatisfied_const(
848                                 &obligation,
849                                 trait_ref,
850                                 &trait_predicate,
851                                 &mut err,
852                                 span,
853                             );
854 
855                         if let Some((msg, span)) = type_def {
856                             err.span_label(span, msg);
857                         }
858                         if let Some(s) = note {
859                             // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
860                             err.note(s);
861                         }
862                         if let Some(s) = parent_label {
863                             let body = obligation.cause.body_id;
864                             err.span_label(tcx.def_span(body), s);
865                         }
866 
867                         self.suggest_floating_point_literal(&obligation, &mut err, &trait_ref);
868                         self.suggest_dereferencing_index(&obligation, &mut err, trait_predicate);
869                         let mut suggested =
870                             self.suggest_dereferences(&obligation, &mut err, trait_predicate);
871                         suggested |= self.suggest_fn_call(&obligation, &mut err, trait_predicate);
872                         let impl_candidates = self.find_similar_impl_candidates(trait_predicate);
873                         suggested = if let &[cand] = &impl_candidates[..] {
874                             let cand = cand.trait_ref;
875                             if let (ty::FnPtr(_), ty::FnDef(..)) =
876                                 (cand.self_ty().kind(), trait_ref.self_ty().skip_binder().kind())
877                             {
878                                 err.span_suggestion(
879                                     span.shrink_to_hi(),
880                                     format!(
881                                         "the trait `{}` is implemented for fn pointer `{}`, try casting using `as`",
882                                         cand.print_only_trait_path(),
883                                         cand.self_ty(),
884                                     ),
885                                     format!(" as {}", cand.self_ty()),
886                                     Applicability::MaybeIncorrect,
887                                 );
888                                 true
889                             } else {
890                                 false
891                             }
892                         } else {
893                             false
894                         } || suggested;
895                         suggested |=
896                             self.suggest_remove_reference(&obligation, &mut err, trait_predicate);
897                         suggested |= self.suggest_semicolon_removal(
898                             &obligation,
899                             &mut err,
900                             span,
901                             trait_predicate,
902                         );
903                         self.note_version_mismatch(&mut err, &trait_ref);
904                         self.suggest_remove_await(&obligation, &mut err);
905                         self.suggest_derive(&obligation, &mut err, trait_predicate);
906 
907                         if Some(trait_ref.def_id()) == tcx.lang_items().try_trait() {
908                             self.suggest_await_before_try(
909                                 &mut err,
910                                 &obligation,
911                                 trait_predicate,
912                                 span,
913                             );
914                         }
915 
916                         if self.suggest_add_clone_to_arg(&obligation, &mut err, trait_predicate) {
917                             err.emit();
918                             return;
919                         }
920 
921                         if self.suggest_impl_trait(&mut err, &obligation, trait_predicate) {
922                             err.emit();
923                             return;
924                         }
925 
926                         if is_unsize {
927                             // If the obligation failed due to a missing implementation of the
928                             // `Unsize` trait, give a pointer to why that might be the case
929                             err.note(
930                                 "all implementations of `Unsize` are provided \
931                                 automatically by the compiler, see \
932                                 <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
933                                 for more information",
934                             );
935                         }
936 
937                         let is_fn_trait = tcx.is_fn_trait(trait_ref.def_id());
938                         let is_target_feature_fn = if let ty::FnDef(def_id, _) =
939                             *trait_ref.skip_binder().self_ty().kind()
940                         {
941                             !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
942                         } else {
943                             false
944                         };
945                         if is_fn_trait && is_target_feature_fn {
946                             err.note(
947                                 "`#[target_feature]` functions do not implement the `Fn` traits",
948                             );
949                         }
950 
951                         self.try_to_add_help_message(
952                             &obligation,
953                             trait_ref,
954                             &trait_predicate,
955                             &mut err,
956                             span,
957                             is_fn_trait,
958                             suggested,
959                             unsatisfied_const,
960                         );
961 
962                         // Changing mutability doesn't make a difference to whether we have
963                         // an `Unsize` impl (Fixes ICE in #71036)
964                         if !is_unsize {
965                             self.suggest_change_mut(&obligation, &mut err, trait_predicate);
966                         }
967 
968                         // If this error is due to `!: Trait` not implemented but `(): Trait` is
969                         // implemented, and fallback has occurred, then it could be due to a
970                         // variable that used to fallback to `()` now falling back to `!`. Issue a
971                         // note informing about the change in behaviour.
972                         if trait_predicate.skip_binder().self_ty().is_never()
973                             && self.fallback_has_occurred
974                         {
975                             let predicate = trait_predicate.map_bound(|trait_pred| {
976                                 trait_pred.with_self_ty(self.tcx, Ty::new_unit(self.tcx))
977                             });
978                             let unit_obligation = obligation.with(tcx, predicate);
979                             if self.predicate_may_hold(&unit_obligation) {
980                                 err.note(
981                                     "this error might have been caused by changes to \
982                                     Rust's type-inference algorithm (see issue #48950 \
983                                     <https://github.com/rust-lang/rust/issues/48950> \
984                                     for more information)",
985                                 );
986                                 err.help("did you intend to use the type `()` here instead?");
987                             }
988                         }
989 
990                         // Return early if the trait is Debug or Display and the invocation
991                         // originates within a standard library macro, because the output
992                         // is otherwise overwhelming and unhelpful (see #85844 for an
993                         // example).
994 
995                         let in_std_macro =
996                             match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
997                                 Some(macro_def_id) => {
998                                     let crate_name = tcx.crate_name(macro_def_id.krate);
999                                     crate_name == sym::std || crate_name == sym::core
1000                                 }
1001                                 None => false,
1002                             };
1003 
1004                         if in_std_macro
1005                             && matches!(
1006                                 self.tcx.get_diagnostic_name(trait_ref.def_id()),
1007                                 Some(sym::Debug | sym::Display)
1008                             )
1009                         {
1010                             err.emit();
1011                             return;
1012                         }
1013 
1014                         err
1015                     }
1016 
1017                     ty::PredicateKind::Subtype(predicate) => {
1018                         // Errors for Subtype predicates show up as
1019                         // `FulfillmentErrorCode::CodeSubtypeError`,
1020                         // not selection error.
1021                         span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
1022                     }
1023 
1024                     ty::PredicateKind::Coerce(predicate) => {
1025                         // Errors for Coerce predicates show up as
1026                         // `FulfillmentErrorCode::CodeSubtypeError`,
1027                         // not selection error.
1028                         span_bug!(span, "coerce requirement gave wrong error: `{:?}`", predicate)
1029                     }
1030 
1031                     ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(..))
1032                     | ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(..)) => {
1033                         span_bug!(
1034                             span,
1035                             "outlives clauses should not error outside borrowck. obligation: `{:?}`",
1036                             obligation
1037                         )
1038                     }
1039 
1040                     ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) => {
1041                         span_bug!(
1042                             span,
1043                             "projection clauses should be implied from elsewhere. obligation: `{:?}`",
1044                             obligation
1045                         )
1046                     }
1047 
1048                     ty::PredicateKind::ObjectSafe(trait_def_id) => {
1049                         let violations = self.tcx.object_safety_violations(trait_def_id);
1050                         report_object_safety_error(self.tcx, span, trait_def_id, violations)
1051                     }
1052 
1053                     ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
1054                         let found_kind = self.closure_kind(closure_substs).unwrap();
1055                         self.report_closure_error(&obligation, closure_def_id, found_kind, kind)
1056                     }
1057 
1058                     ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(ty)) => {
1059                         let ty = self.resolve_vars_if_possible(ty);
1060                         match self.tcx.sess.opts.unstable_opts.trait_solver {
1061                             TraitSolver::Classic => {
1062                                 // WF predicates cannot themselves make
1063                                 // errors. They can only block due to
1064                                 // ambiguity; otherwise, they always
1065                                 // degenerate into other obligations
1066                                 // (which may fail).
1067                                 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
1068                             }
1069                             TraitSolver::Next | TraitSolver::NextCoherence => {
1070                                 // FIXME: we'll need a better message which takes into account
1071                                 // which bounds actually failed to hold.
1072                                 self.tcx.sess.struct_span_err(
1073                                     span,
1074                                     format!("the type `{}` is not well-formed", ty),
1075                                 )
1076                             }
1077                         }
1078                     }
1079 
1080                     ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) => {
1081                         // Errors for `ConstEvaluatable` predicates show up as
1082                         // `SelectionError::ConstEvalFailure`,
1083                         // not `Unimplemented`.
1084                         span_bug!(
1085                             span,
1086                             "const-evaluatable requirement gave wrong error: `{:?}`",
1087                             obligation
1088                         )
1089                     }
1090 
1091                     ty::PredicateKind::ConstEquate(..) => {
1092                         // Errors for `ConstEquate` predicates show up as
1093                         // `SelectionError::ConstEvalFailure`,
1094                         // not `Unimplemented`.
1095                         span_bug!(
1096                             span,
1097                             "const-equate requirement gave wrong error: `{:?}`",
1098                             obligation
1099                         )
1100                     }
1101 
1102                     ty::PredicateKind::Ambiguous => span_bug!(span, "ambiguous"),
1103 
1104                     ty::PredicateKind::AliasRelate(..) => span_bug!(
1105                         span,
1106                         "AliasRelate predicate should never be the predicate cause of a SelectionError"
1107                     ),
1108 
1109                     ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
1110                         let mut diag = self.tcx.sess.struct_span_err(
1111                             span,
1112                             format!("the constant `{}` is not of type `{}`", ct, ty),
1113                         );
1114                         self.note_type_err(
1115                             &mut diag,
1116                             &obligation.cause,
1117                             None,
1118                             None,
1119                             TypeError::Sorts(ty::error::ExpectedFound::new(true, ty, ct.ty())),
1120                             false,
1121                             false,
1122                         );
1123                         diag
1124                     }
1125                 }
1126             }
1127 
1128             OutputTypeParameterMismatch(box SelectionOutputTypeParameterMismatch {
1129                 found_trait_ref,
1130                 expected_trait_ref,
1131                 terr: terr @ TypeError::CyclicTy(_),
1132             }) => self.report_type_parameter_mismatch_cyclic_type_error(
1133                 &obligation,
1134                 found_trait_ref,
1135                 expected_trait_ref,
1136                 terr,
1137             ),
1138             OutputTypeParameterMismatch(box SelectionOutputTypeParameterMismatch {
1139                 found_trait_ref,
1140                 expected_trait_ref,
1141                 terr: _,
1142             }) => {
1143                 match self.report_type_parameter_mismatch_error(
1144                     &obligation,
1145                     span,
1146                     found_trait_ref,
1147                     expected_trait_ref,
1148                 ) {
1149                     Some(err) => err,
1150                     None => return,
1151                 }
1152             }
1153 
1154             SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id) => self.report_opaque_type_auto_trait_leakage(
1155                 &obligation,
1156                 def_id,
1157             ),
1158 
1159             TraitNotObjectSafe(did) => {
1160                 let violations = self.tcx.object_safety_violations(did);
1161                 report_object_safety_error(self.tcx, span, did, violations)
1162             }
1163 
1164             SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsInfer) => {
1165                 bug!(
1166                     "MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"
1167                 )
1168             }
1169             SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsParam) => {
1170                 match self.report_not_const_evaluatable_error(&obligation, span) {
1171                     Some(err) => err,
1172                     None => return,
1173                 }
1174             }
1175 
1176             // Already reported in the query.
1177             SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(_)) |
1178             // Already reported.
1179             Overflow(OverflowError::Error(_)) => return,
1180 
1181             Overflow(_) => {
1182                 bug!("overflow should be handled before the `report_selection_error` path");
1183             }
1184             SelectionError::ErrorReporting => {
1185                 bug!("ErrorReporting Overflow should not reach `report_selection_err` call")
1186             }
1187         };
1188 
1189         self.note_obligation_cause(&mut err, &obligation);
1190         self.point_at_returns_when_relevant(&mut err, &obligation);
1191         err.emit();
1192     }
1193 
report_const_param_not_wf( &self, ty: Ty<'tcx>, obligation: &PredicateObligation<'tcx>, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>1194     fn report_const_param_not_wf(
1195         &self,
1196         ty: Ty<'tcx>,
1197         obligation: &PredicateObligation<'tcx>,
1198     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1199         let span = obligation.cause.span;
1200 
1201         let mut diag = match ty.kind() {
1202             _ if ty.has_param() => {
1203                 span_bug!(span, "const param tys cannot mention other generic parameters");
1204             }
1205             ty::Float(_) => {
1206                 struct_span_err!(
1207                     self.tcx.sess,
1208                     span,
1209                     E0741,
1210                     "`{ty}` is forbidden as the type of a const generic parameter",
1211                 )
1212             }
1213             ty::FnPtr(_) => {
1214                 struct_span_err!(
1215                     self.tcx.sess,
1216                     span,
1217                     E0741,
1218                     "using function pointers as const generic parameters is forbidden",
1219                 )
1220             }
1221             ty::RawPtr(_) => {
1222                 struct_span_err!(
1223                     self.tcx.sess,
1224                     span,
1225                     E0741,
1226                     "using raw pointers as const generic parameters is forbidden",
1227                 )
1228             }
1229             ty::Adt(def, _) => {
1230                 // We should probably see if we're *allowed* to derive `ConstParamTy` on the type...
1231                 let mut diag = struct_span_err!(
1232                     self.tcx.sess,
1233                     span,
1234                     E0741,
1235                     "`{ty}` must implement `ConstParamTy` to be used as the type of a const generic parameter",
1236                 );
1237                 // Only suggest derive if this isn't a derived obligation,
1238                 // and the struct is local.
1239                 if let Some(span) = self.tcx.hir().span_if_local(def.did())
1240                     && obligation.cause.code().parent().is_none()
1241                 {
1242                     if ty.is_structural_eq_shallow(self.tcx) {
1243                         diag.span_suggestion(
1244                             span,
1245                             "add `#[derive(ConstParamTy)]` to the struct",
1246                             "#[derive(ConstParamTy)]\n",
1247                             Applicability::MachineApplicable,
1248                         );
1249                     } else {
1250                         // FIXME(adt_const_params): We should check there's not already an
1251                         // overlapping `Eq`/`PartialEq` impl.
1252                         diag.span_suggestion(
1253                             span,
1254                             "add `#[derive(ConstParamTy, PartialEq, Eq)]` to the struct",
1255                             "#[derive(ConstParamTy, PartialEq, Eq)]\n",
1256                             Applicability::MachineApplicable,
1257                         );
1258                     }
1259                 }
1260                 diag
1261             }
1262             _ => {
1263                 struct_span_err!(
1264                     self.tcx.sess,
1265                     span,
1266                     E0741,
1267                     "`{ty}` can't be used as a const parameter type",
1268                 )
1269             }
1270         };
1271 
1272         let mut code = obligation.cause.code();
1273         let mut pred = obligation.predicate.to_opt_poly_trait_pred();
1274         while let Some((next_code, next_pred)) = code.parent() {
1275             if let Some(pred) = pred {
1276                 let pred = self.instantiate_binder_with_placeholders(pred);
1277                 diag.note(format!(
1278                     "`{}` must implement `{}`, but it does not",
1279                     pred.self_ty(),
1280                     pred.print_modifiers_and_trait_path()
1281                 ));
1282             }
1283             code = next_code;
1284             pred = next_pred;
1285         }
1286 
1287         diag
1288     }
1289 }
1290 
1291 trait InferCtxtPrivExt<'tcx> {
1292     // returns if `cond` not occurring implies that `error` does not occur - i.e., that
1293     // `error` occurring implies that `cond` occurs.
error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool1294     fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool;
1295 
report_fulfillment_error(&self, error: &FulfillmentError<'tcx>)1296     fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>);
1297 
report_projection_error( &self, obligation: &PredicateObligation<'tcx>, error: &MismatchedProjectionTypes<'tcx>, )1298     fn report_projection_error(
1299         &self,
1300         obligation: &PredicateObligation<'tcx>,
1301         error: &MismatchedProjectionTypes<'tcx>,
1302     );
1303 
maybe_detailed_projection_msg( &self, pred: ty::ProjectionPredicate<'tcx>, normalized_ty: ty::Term<'tcx>, expected_ty: ty::Term<'tcx>, ) -> Option<String>1304     fn maybe_detailed_projection_msg(
1305         &self,
1306         pred: ty::ProjectionPredicate<'tcx>,
1307         normalized_ty: ty::Term<'tcx>,
1308         expected_ty: ty::Term<'tcx>,
1309     ) -> Option<String>;
1310 
fuzzy_match_tys( &self, a: Ty<'tcx>, b: Ty<'tcx>, ignoring_lifetimes: bool, ) -> Option<CandidateSimilarity>1311     fn fuzzy_match_tys(
1312         &self,
1313         a: Ty<'tcx>,
1314         b: Ty<'tcx>,
1315         ignoring_lifetimes: bool,
1316     ) -> Option<CandidateSimilarity>;
1317 
describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str>1318     fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str>;
1319 
find_similar_impl_candidates( &self, trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> Vec<ImplCandidate<'tcx>>1320     fn find_similar_impl_candidates(
1321         &self,
1322         trait_pred: ty::PolyTraitPredicate<'tcx>,
1323     ) -> Vec<ImplCandidate<'tcx>>;
1324 
report_similar_impl_candidates( &self, impl_candidates: &[ImplCandidate<'tcx>], trait_ref: ty::PolyTraitRef<'tcx>, body_def_id: LocalDefId, err: &mut Diagnostic, other: bool, ) -> bool1325     fn report_similar_impl_candidates(
1326         &self,
1327         impl_candidates: &[ImplCandidate<'tcx>],
1328         trait_ref: ty::PolyTraitRef<'tcx>,
1329         body_def_id: LocalDefId,
1330         err: &mut Diagnostic,
1331         other: bool,
1332     ) -> bool;
1333 
report_similar_impl_candidates_for_root_obligation( &self, obligation: &PredicateObligation<'tcx>, trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>, body_def_id: LocalDefId, err: &mut Diagnostic, )1334     fn report_similar_impl_candidates_for_root_obligation(
1335         &self,
1336         obligation: &PredicateObligation<'tcx>,
1337         trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
1338         body_def_id: LocalDefId,
1339         err: &mut Diagnostic,
1340     );
1341 
1342     /// Gets the parent trait chain start
get_parent_trait_ref( &self, code: &ObligationCauseCode<'tcx>, ) -> Option<(String, Option<Span>)>1343     fn get_parent_trait_ref(
1344         &self,
1345         code: &ObligationCauseCode<'tcx>,
1346     ) -> Option<(String, Option<Span>)>;
1347 
1348     /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1349     /// with the same path as `trait_ref`, a help message about
1350     /// a probable version mismatch is added to `err`
note_version_mismatch( &self, err: &mut Diagnostic, trait_ref: &ty::PolyTraitRef<'tcx>, ) -> bool1351     fn note_version_mismatch(
1352         &self,
1353         err: &mut Diagnostic,
1354         trait_ref: &ty::PolyTraitRef<'tcx>,
1355     ) -> bool;
1356 
1357     /// Creates a `PredicateObligation` with `new_self_ty` replacing the existing type in the
1358     /// `trait_ref`.
1359     ///
1360     /// For this to work, `new_self_ty` must have no escaping bound variables.
mk_trait_obligation_with_new_self_ty( &self, param_env: ty::ParamEnv<'tcx>, trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>, ) -> PredicateObligation<'tcx>1361     fn mk_trait_obligation_with_new_self_ty(
1362         &self,
1363         param_env: ty::ParamEnv<'tcx>,
1364         trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>,
1365     ) -> PredicateObligation<'tcx>;
1366 
maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>)1367     fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>);
1368 
predicate_can_apply( &self, param_env: ty::ParamEnv<'tcx>, pred: ty::PolyTraitPredicate<'tcx>, ) -> bool1369     fn predicate_can_apply(
1370         &self,
1371         param_env: ty::ParamEnv<'tcx>,
1372         pred: ty::PolyTraitPredicate<'tcx>,
1373     ) -> bool;
1374 
note_obligation_cause(&self, err: &mut Diagnostic, obligation: &PredicateObligation<'tcx>)1375     fn note_obligation_cause(&self, err: &mut Diagnostic, obligation: &PredicateObligation<'tcx>);
1376 
suggest_unsized_bound_if_applicable( &self, err: &mut Diagnostic, obligation: &PredicateObligation<'tcx>, )1377     fn suggest_unsized_bound_if_applicable(
1378         &self,
1379         err: &mut Diagnostic,
1380         obligation: &PredicateObligation<'tcx>,
1381     );
1382 
annotate_source_of_ambiguity( &self, err: &mut Diagnostic, impls: &[ambiguity::Ambiguity], predicate: ty::Predicate<'tcx>, )1383     fn annotate_source_of_ambiguity(
1384         &self,
1385         err: &mut Diagnostic,
1386         impls: &[ambiguity::Ambiguity],
1387         predicate: ty::Predicate<'tcx>,
1388     );
1389 
maybe_suggest_unsized_generics(&self, err: &mut Diagnostic, span: Span, node: Node<'tcx>)1390     fn maybe_suggest_unsized_generics(&self, err: &mut Diagnostic, span: Span, node: Node<'tcx>);
1391 
maybe_indirection_for_unsized( &self, err: &mut Diagnostic, item: &'tcx Item<'tcx>, param: &'tcx GenericParam<'tcx>, ) -> bool1392     fn maybe_indirection_for_unsized(
1393         &self,
1394         err: &mut Diagnostic,
1395         item: &'tcx Item<'tcx>,
1396         param: &'tcx GenericParam<'tcx>,
1397     ) -> bool;
1398 
is_recursive_obligation( &self, obligated_types: &mut Vec<Ty<'tcx>>, cause_code: &ObligationCauseCode<'tcx>, ) -> bool1399     fn is_recursive_obligation(
1400         &self,
1401         obligated_types: &mut Vec<Ty<'tcx>>,
1402         cause_code: &ObligationCauseCode<'tcx>,
1403     ) -> bool;
1404 
get_standard_error_message( &self, trait_predicate: &ty::PolyTraitPredicate<'tcx>, message: Option<String>, predicate_is_const: bool, append_const_msg: Option<AppendConstMessage>, post_message: String, ) -> String1405     fn get_standard_error_message(
1406         &self,
1407         trait_predicate: &ty::PolyTraitPredicate<'tcx>,
1408         message: Option<String>,
1409         predicate_is_const: bool,
1410         append_const_msg: Option<AppendConstMessage>,
1411         post_message: String,
1412     ) -> String;
1413 
get_safe_transmute_error_and_reason( &self, obligation: PredicateObligation<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>, span: Span, ) -> GetSafeTransmuteErrorAndReason1414     fn get_safe_transmute_error_and_reason(
1415         &self,
1416         obligation: PredicateObligation<'tcx>,
1417         trait_ref: ty::PolyTraitRef<'tcx>,
1418         span: Span,
1419     ) -> GetSafeTransmuteErrorAndReason;
1420 
add_tuple_trait_message( &self, obligation_cause_code: &ObligationCauseCode<'tcx>, err: &mut Diagnostic, )1421     fn add_tuple_trait_message(
1422         &self,
1423         obligation_cause_code: &ObligationCauseCode<'tcx>,
1424         err: &mut Diagnostic,
1425     );
1426 
try_to_add_help_message( &self, obligation: &PredicateObligation<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>, trait_predicate: &ty::PolyTraitPredicate<'tcx>, err: &mut Diagnostic, span: Span, is_fn_trait: bool, suggested: bool, unsatisfied_const: bool, )1427     fn try_to_add_help_message(
1428         &self,
1429         obligation: &PredicateObligation<'tcx>,
1430         trait_ref: ty::PolyTraitRef<'tcx>,
1431         trait_predicate: &ty::PolyTraitPredicate<'tcx>,
1432         err: &mut Diagnostic,
1433         span: Span,
1434         is_fn_trait: bool,
1435         suggested: bool,
1436         unsatisfied_const: bool,
1437     );
1438 
add_help_message_for_fn_trait( &self, trait_ref: ty::PolyTraitRef<'tcx>, err: &mut Diagnostic, implemented_kind: ty::ClosureKind, params: ty::Binder<'tcx, Ty<'tcx>>, )1439     fn add_help_message_for_fn_trait(
1440         &self,
1441         trait_ref: ty::PolyTraitRef<'tcx>,
1442         err: &mut Diagnostic,
1443         implemented_kind: ty::ClosureKind,
1444         params: ty::Binder<'tcx, Ty<'tcx>>,
1445     );
1446 
maybe_add_note_for_unsatisfied_const( &self, obligation: &PredicateObligation<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>, trait_predicate: &ty::PolyTraitPredicate<'tcx>, err: &mut Diagnostic, span: Span, ) -> UnsatisfiedConst1447     fn maybe_add_note_for_unsatisfied_const(
1448         &self,
1449         obligation: &PredicateObligation<'tcx>,
1450         trait_ref: ty::PolyTraitRef<'tcx>,
1451         trait_predicate: &ty::PolyTraitPredicate<'tcx>,
1452         err: &mut Diagnostic,
1453         span: Span,
1454     ) -> UnsatisfiedConst;
1455 
report_closure_error( &self, obligation: &PredicateObligation<'tcx>, closure_def_id: DefId, found_kind: ty::ClosureKind, kind: ty::ClosureKind, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>1456     fn report_closure_error(
1457         &self,
1458         obligation: &PredicateObligation<'tcx>,
1459         closure_def_id: DefId,
1460         found_kind: ty::ClosureKind,
1461         kind: ty::ClosureKind,
1462     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
1463 
report_type_parameter_mismatch_cyclic_type_error( &self, obligation: &PredicateObligation<'tcx>, found_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>, expected_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>, terr: TypeError<'tcx>, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>1464     fn report_type_parameter_mismatch_cyclic_type_error(
1465         &self,
1466         obligation: &PredicateObligation<'tcx>,
1467         found_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
1468         expected_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
1469         terr: TypeError<'tcx>,
1470     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
1471 
report_opaque_type_auto_trait_leakage( &self, obligation: &PredicateObligation<'tcx>, def_id: DefId, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>1472     fn report_opaque_type_auto_trait_leakage(
1473         &self,
1474         obligation: &PredicateObligation<'tcx>,
1475         def_id: DefId,
1476     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
1477 
report_type_parameter_mismatch_error( &self, obligation: &PredicateObligation<'tcx>, span: Span, found_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>, expected_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>, ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>>1478     fn report_type_parameter_mismatch_error(
1479         &self,
1480         obligation: &PredicateObligation<'tcx>,
1481         span: Span,
1482         found_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
1483         expected_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
1484     ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>>;
1485 
report_not_const_evaluatable_error( &self, obligation: &PredicateObligation<'tcx>, span: Span, ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>>1486     fn report_not_const_evaluatable_error(
1487         &self,
1488         obligation: &PredicateObligation<'tcx>,
1489         span: Span,
1490     ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>>;
1491 }
1492 
1493 impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
1494     // returns if `cond` not occurring implies that `error` does not occur - i.e., that
1495     // `error` occurring implies that `cond` occurs.
error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool1496     fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool {
1497         if cond == error {
1498             return true;
1499         }
1500 
1501         // FIXME: It should be possible to deal with `ForAll` in a cleaner way.
1502         let bound_error = error.kind();
1503         let (cond, error) = match (cond.kind().skip_binder(), bound_error.skip_binder()) {
1504             (
1505                 ty::PredicateKind::Clause(ty::ClauseKind::Trait(..)),
1506                 ty::PredicateKind::Clause(ty::ClauseKind::Trait(error)),
1507             ) => (cond, bound_error.rebind(error)),
1508             _ => {
1509                 // FIXME: make this work in other cases too.
1510                 return false;
1511             }
1512         };
1513 
1514         for pred in super::elaborate(self.tcx, std::iter::once(cond)) {
1515             let bound_predicate = pred.kind();
1516             if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(implication)) =
1517                 bound_predicate.skip_binder()
1518             {
1519                 let error = error.to_poly_trait_ref();
1520                 let implication = bound_predicate.rebind(implication.trait_ref);
1521                 // FIXME: I'm just not taking associated types at all here.
1522                 // Eventually I'll need to implement param-env-aware
1523                 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
1524                 let param_env = ty::ParamEnv::empty();
1525                 if self.can_sub(param_env, error, implication) {
1526                     debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
1527                     return true;
1528                 }
1529             }
1530         }
1531 
1532         false
1533     }
1534 
1535     #[instrument(skip(self), level = "debug")]
report_fulfillment_error(&self, error: &FulfillmentError<'tcx>)1536     fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>) {
1537         if self.tcx.sess.opts.unstable_opts.dump_solver_proof_tree == DumpSolverProofTree::OnError {
1538             dump_proof_tree(&error.root_obligation, self.infcx);
1539         }
1540 
1541         match error.code {
1542             FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
1543                 self.report_selection_error(
1544                     error.obligation.clone(),
1545                     &error.root_obligation,
1546                     selection_error,
1547                 );
1548             }
1549             FulfillmentErrorCode::CodeProjectionError(ref e) => {
1550                 self.report_projection_error(&error.obligation, e);
1551             }
1552             FulfillmentErrorCode::CodeAmbiguity { overflow: false } => {
1553                 self.maybe_report_ambiguity(&error.obligation);
1554             }
1555             FulfillmentErrorCode::CodeAmbiguity { overflow: true } => {
1556                 self.report_overflow_no_abort(error.obligation.clone());
1557             }
1558             FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
1559                 self.report_mismatched_types(
1560                     &error.obligation.cause,
1561                     expected_found.expected,
1562                     expected_found.found,
1563                     *err,
1564                 )
1565                 .emit();
1566             }
1567             FulfillmentErrorCode::CodeConstEquateError(ref expected_found, ref err) => {
1568                 let mut diag = self.report_mismatched_consts(
1569                     &error.obligation.cause,
1570                     expected_found.expected,
1571                     expected_found.found,
1572                     *err,
1573                 );
1574                 let code = error.obligation.cause.code().peel_derives().peel_match_impls();
1575                 if let ObligationCauseCode::BindingObligation(..)
1576                 | ObligationCauseCode::ItemObligation(..)
1577                 | ObligationCauseCode::ExprBindingObligation(..)
1578                 | ObligationCauseCode::ExprItemObligation(..) = code
1579                 {
1580                     self.note_obligation_cause_code(
1581                         error.obligation.cause.body_id,
1582                         &mut diag,
1583                         error.obligation.predicate,
1584                         error.obligation.param_env,
1585                         code,
1586                         &mut vec![],
1587                         &mut Default::default(),
1588                     );
1589                 }
1590                 diag.emit();
1591             }
1592             FulfillmentErrorCode::CodeCycle(ref cycle) => {
1593                 self.report_overflow_obligation_cycle(cycle);
1594             }
1595         }
1596     }
1597 
1598     #[instrument(level = "debug", skip_all)]
report_projection_error( &self, obligation: &PredicateObligation<'tcx>, error: &MismatchedProjectionTypes<'tcx>, )1599     fn report_projection_error(
1600         &self,
1601         obligation: &PredicateObligation<'tcx>,
1602         error: &MismatchedProjectionTypes<'tcx>,
1603     ) {
1604         let predicate = self.resolve_vars_if_possible(obligation.predicate);
1605 
1606         if predicate.references_error() {
1607             return;
1608         }
1609 
1610         self.probe(|_| {
1611             let ocx = ObligationCtxt::new(self);
1612 
1613             // try to find the mismatched types to report the error with.
1614             //
1615             // this can fail if the problem was higher-ranked, in which
1616             // cause I have no idea for a good error message.
1617             let bound_predicate = predicate.kind();
1618             let (values, err) = if let ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) =
1619                 bound_predicate.skip_binder()
1620             {
1621                 let data = self.instantiate_binder_with_fresh_vars(
1622                     obligation.cause.span,
1623                     infer::LateBoundRegionConversionTime::HigherRankedType,
1624                     bound_predicate.rebind(data),
1625                 );
1626                 let unnormalized_term = match data.term.unpack() {
1627                     ty::TermKind::Ty(_) => Ty::new_projection(
1628                         self.tcx,
1629                         data.projection_ty.def_id,
1630                         data.projection_ty.substs,
1631                     )
1632                     .into(),
1633                     ty::TermKind::Const(ct) => ty::Const::new_unevaluated(
1634                         self.tcx,
1635                         ty::UnevaluatedConst {
1636                             def: data.projection_ty.def_id,
1637                             substs: data.projection_ty.substs,
1638                         },
1639                         ct.ty(),
1640                     )
1641                     .into(),
1642                 };
1643                 let normalized_term =
1644                     ocx.normalize(&obligation.cause, obligation.param_env, unnormalized_term);
1645 
1646                 debug!(?obligation.cause, ?obligation.param_env);
1647 
1648                 debug!(?normalized_term, data.ty = ?data.term);
1649 
1650                 let is_normalized_term_expected = !matches!(
1651                     obligation.cause.code().peel_derives(),
1652                     ObligationCauseCode::ItemObligation(_)
1653                         | ObligationCauseCode::BindingObligation(_, _)
1654                         | ObligationCauseCode::ExprItemObligation(..)
1655                         | ObligationCauseCode::ExprBindingObligation(..)
1656                         | ObligationCauseCode::Coercion { .. }
1657                         | ObligationCauseCode::OpaqueType
1658                 );
1659 
1660                 // constrain inference variables a bit more to nested obligations from normalize so
1661                 // we can have more helpful errors.
1662                 //
1663                 // we intentionally drop errors from normalization here,
1664                 // since the normalization is just done to improve the error message.
1665                 let _ = ocx.select_where_possible();
1666 
1667                 if let Err(new_err) = ocx.eq_exp(
1668                     &obligation.cause,
1669                     obligation.param_env,
1670                     is_normalized_term_expected,
1671                     normalized_term,
1672                     data.term,
1673                 ) {
1674                     (Some((data, is_normalized_term_expected, normalized_term, data.term)), new_err)
1675                 } else {
1676                     (None, error.err)
1677                 }
1678             } else {
1679                 (None, error.err)
1680             };
1681 
1682             let msg = values
1683                 .and_then(|(predicate, _, normalized_term, expected_term)| {
1684                     self.maybe_detailed_projection_msg(predicate, normalized_term, expected_term)
1685                 })
1686                 .unwrap_or_else(|| {
1687                     with_forced_trimmed_paths!(format!(
1688                         "type mismatch resolving `{}`",
1689                         self.resolve_vars_if_possible(predicate)
1690                             .print(FmtPrinter::new_with_limit(
1691                                 self.tcx,
1692                                 Namespace::TypeNS,
1693                                 rustc_session::Limit(10),
1694                             ))
1695                             .unwrap()
1696                             .into_buffer()
1697                     ))
1698                 });
1699             let mut diag = struct_span_err!(self.tcx.sess, obligation.cause.span, E0271, "{msg}");
1700 
1701             let secondary_span = (|| {
1702                 let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
1703                     predicate.kind().skip_binder()
1704                 else {
1705                     return None;
1706                 };
1707 
1708                 let trait_assoc_item = self.tcx.opt_associated_item(proj.projection_ty.def_id)?;
1709                 let trait_assoc_ident = trait_assoc_item.ident(self.tcx);
1710 
1711                 let mut associated_items = vec![];
1712                 self.tcx.for_each_relevant_impl(
1713                     self.tcx.trait_of_item(proj.projection_ty.def_id)?,
1714                     proj.projection_ty.self_ty(),
1715                     |impl_def_id| {
1716                         associated_items.extend(
1717                             self.tcx
1718                                 .associated_items(impl_def_id)
1719                                 .in_definition_order()
1720                                 .find(|assoc| assoc.ident(self.tcx) == trait_assoc_ident),
1721                         );
1722                     },
1723                 );
1724 
1725                 let [associated_item]: &[ty::AssocItem] = &associated_items[..] else {
1726                     return None;
1727                 };
1728                 match self.tcx.hir().get_if_local(associated_item.def_id) {
1729                     Some(
1730                         hir::Node::TraitItem(hir::TraitItem {
1731                             kind: hir::TraitItemKind::Type(_, Some(ty)),
1732                             ..
1733                         })
1734                         | hir::Node::ImplItem(hir::ImplItem {
1735                             kind: hir::ImplItemKind::Type(ty),
1736                             ..
1737                         }),
1738                     ) => Some((
1739                         ty.span,
1740                         with_forced_trimmed_paths!(Cow::from(format!(
1741                             "type mismatch resolving `{}`",
1742                             self.resolve_vars_if_possible(predicate)
1743                                 .print(FmtPrinter::new_with_limit(
1744                                     self.tcx,
1745                                     Namespace::TypeNS,
1746                                     rustc_session::Limit(5),
1747                                 ))
1748                                 .unwrap()
1749                                 .into_buffer()
1750                         ))),
1751                     )),
1752                     _ => None,
1753                 }
1754             })();
1755 
1756             self.note_type_err(
1757                 &mut diag,
1758                 &obligation.cause,
1759                 secondary_span,
1760                 values.map(|(_, is_normalized_ty_expected, normalized_ty, expected_ty)| {
1761                     infer::ValuePairs::Terms(ExpectedFound::new(
1762                         is_normalized_ty_expected,
1763                         normalized_ty,
1764                         expected_ty,
1765                     ))
1766                 }),
1767                 err,
1768                 true,
1769                 false,
1770             );
1771             self.note_obligation_cause(&mut diag, obligation);
1772             diag.emit();
1773         });
1774     }
1775 
maybe_detailed_projection_msg( &self, pred: ty::ProjectionPredicate<'tcx>, normalized_ty: ty::Term<'tcx>, expected_ty: ty::Term<'tcx>, ) -> Option<String>1776     fn maybe_detailed_projection_msg(
1777         &self,
1778         pred: ty::ProjectionPredicate<'tcx>,
1779         normalized_ty: ty::Term<'tcx>,
1780         expected_ty: ty::Term<'tcx>,
1781     ) -> Option<String> {
1782         let trait_def_id = pred.projection_ty.trait_def_id(self.tcx);
1783         let self_ty = pred.projection_ty.self_ty();
1784 
1785         with_forced_trimmed_paths! {
1786             if Some(pred.projection_ty.def_id) == self.tcx.lang_items().fn_once_output() {
1787                 let fn_kind = self_ty.prefix_string(self.tcx);
1788                 let item = match self_ty.kind() {
1789                     ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
1790                     _ => self_ty.to_string(),
1791                 };
1792                 Some(format!(
1793                     "expected `{item}` to be a {fn_kind} that returns `{expected_ty}`, but it \
1794                      returns `{normalized_ty}`",
1795                 ))
1796             } else if Some(trait_def_id) == self.tcx.lang_items().future_trait() {
1797                 Some(format!(
1798                     "expected `{self_ty}` to be a future that resolves to `{expected_ty}`, but it \
1799                      resolves to `{normalized_ty}`"
1800                 ))
1801             } else if Some(trait_def_id) == self.tcx.get_diagnostic_item(sym::Iterator) {
1802                 Some(format!(
1803                     "expected `{self_ty}` to be an iterator that yields `{expected_ty}`, but it \
1804                      yields `{normalized_ty}`"
1805                 ))
1806             } else {
1807                 None
1808             }
1809         }
1810     }
1811 
fuzzy_match_tys( &self, mut a: Ty<'tcx>, mut b: Ty<'tcx>, ignoring_lifetimes: bool, ) -> Option<CandidateSimilarity>1812     fn fuzzy_match_tys(
1813         &self,
1814         mut a: Ty<'tcx>,
1815         mut b: Ty<'tcx>,
1816         ignoring_lifetimes: bool,
1817     ) -> Option<CandidateSimilarity> {
1818         /// returns the fuzzy category of a given type, or None
1819         /// if the type can be equated to any type.
1820         fn type_category(tcx: TyCtxt<'_>, t: Ty<'_>) -> Option<u32> {
1821             match t.kind() {
1822                 ty::Bool => Some(0),
1823                 ty::Char => Some(1),
1824                 ty::Str => Some(2),
1825                 ty::Adt(def, _) if Some(def.did()) == tcx.lang_items().string() => Some(2),
1826                 ty::Int(..)
1827                 | ty::Uint(..)
1828                 | ty::Float(..)
1829                 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) => Some(4),
1830                 ty::Ref(..) | ty::RawPtr(..) => Some(5),
1831                 ty::Array(..) | ty::Slice(..) => Some(6),
1832                 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1833                 ty::Dynamic(..) => Some(8),
1834                 ty::Closure(..) => Some(9),
1835                 ty::Tuple(..) => Some(10),
1836                 ty::Param(..) => Some(11),
1837                 ty::Alias(ty::Projection, ..) => Some(12),
1838                 ty::Alias(ty::Inherent, ..) => Some(13),
1839                 ty::Alias(ty::Opaque, ..) => Some(14),
1840                 ty::Alias(ty::Weak, ..) => Some(15),
1841                 ty::Never => Some(16),
1842                 ty::Adt(..) => Some(17),
1843                 ty::Generator(..) => Some(18),
1844                 ty::Foreign(..) => Some(19),
1845                 ty::GeneratorWitness(..) => Some(20),
1846                 ty::GeneratorWitnessMIR(..) => Some(21),
1847                 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1848             }
1849         }
1850 
1851         let strip_references = |mut t: Ty<'tcx>| -> Ty<'tcx> {
1852             loop {
1853                 match t.kind() {
1854                     ty::Ref(_, inner, _) | ty::RawPtr(ty::TypeAndMut { ty: inner, .. }) => {
1855                         t = *inner
1856                     }
1857                     _ => break t,
1858                 }
1859             }
1860         };
1861 
1862         if !ignoring_lifetimes {
1863             a = strip_references(a);
1864             b = strip_references(b);
1865         }
1866 
1867         let cat_a = type_category(self.tcx, a)?;
1868         let cat_b = type_category(self.tcx, b)?;
1869         if a == b {
1870             Some(CandidateSimilarity::Exact { ignoring_lifetimes })
1871         } else if cat_a == cat_b {
1872             match (a.kind(), b.kind()) {
1873                 (ty::Adt(def_a, _), ty::Adt(def_b, _)) => def_a == def_b,
1874                 (ty::Foreign(def_a), ty::Foreign(def_b)) => def_a == def_b,
1875                 // Matching on references results in a lot of unhelpful
1876                 // suggestions, so let's just not do that for now.
1877                 //
1878                 // We still upgrade successful matches to `ignoring_lifetimes: true`
1879                 // to prioritize that impl.
1880                 (ty::Ref(..) | ty::RawPtr(..), ty::Ref(..) | ty::RawPtr(..)) => {
1881                     self.fuzzy_match_tys(a, b, true).is_some()
1882                 }
1883                 _ => true,
1884             }
1885             .then_some(CandidateSimilarity::Fuzzy { ignoring_lifetimes })
1886         } else if ignoring_lifetimes {
1887             None
1888         } else {
1889             self.fuzzy_match_tys(a, b, true)
1890         }
1891     }
1892 
describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str>1893     fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
1894         self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind {
1895             hir::GeneratorKind::Gen => "a generator",
1896             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
1897             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
1898             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
1899         })
1900     }
1901 
find_similar_impl_candidates( &self, trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> Vec<ImplCandidate<'tcx>>1902     fn find_similar_impl_candidates(
1903         &self,
1904         trait_pred: ty::PolyTraitPredicate<'tcx>,
1905     ) -> Vec<ImplCandidate<'tcx>> {
1906         let mut candidates: Vec<_> = self
1907             .tcx
1908             .all_impls(trait_pred.def_id())
1909             .filter_map(|def_id| {
1910                 if self.tcx.impl_polarity(def_id) == ty::ImplPolarity::Negative
1911                     || !trait_pred
1912                         .skip_binder()
1913                         .is_constness_satisfied_by(self.tcx.constness(def_id))
1914                     || !self.tcx.is_user_visible_dep(def_id.krate)
1915                 {
1916                     return None;
1917                 }
1918 
1919                 let imp = self.tcx.impl_trait_ref(def_id).unwrap().skip_binder();
1920 
1921                 self.fuzzy_match_tys(trait_pred.skip_binder().self_ty(), imp.self_ty(), false)
1922                     .map(|similarity| ImplCandidate { trait_ref: imp, similarity })
1923             })
1924             .collect();
1925         if candidates.iter().any(|c| matches!(c.similarity, CandidateSimilarity::Exact { .. })) {
1926             // If any of the candidates is a perfect match, we don't want to show all of them.
1927             // This is particularly relevant for the case of numeric types (as they all have the
1928             // same category).
1929             candidates.retain(|c| matches!(c.similarity, CandidateSimilarity::Exact { .. }));
1930         }
1931         candidates
1932     }
1933 
report_similar_impl_candidates( &self, impl_candidates: &[ImplCandidate<'tcx>], trait_ref: ty::PolyTraitRef<'tcx>, body_def_id: LocalDefId, err: &mut Diagnostic, other: bool, ) -> bool1934     fn report_similar_impl_candidates(
1935         &self,
1936         impl_candidates: &[ImplCandidate<'tcx>],
1937         trait_ref: ty::PolyTraitRef<'tcx>,
1938         body_def_id: LocalDefId,
1939         err: &mut Diagnostic,
1940         other: bool,
1941     ) -> bool {
1942         let other = if other { "other " } else { "" };
1943         let report = |candidates: Vec<TraitRef<'tcx>>, err: &mut Diagnostic| {
1944             if candidates.is_empty() {
1945                 return false;
1946             }
1947             if let &[cand] = &candidates[..] {
1948                 let (desc, mention_castable) =
1949                     match (cand.self_ty().kind(), trait_ref.self_ty().skip_binder().kind()) {
1950                         (ty::FnPtr(_), ty::FnDef(..)) => {
1951                             (" implemented for fn pointer `", ", cast using `as`")
1952                         }
1953                         (ty::FnPtr(_), _) => (" implemented for fn pointer `", ""),
1954                         _ => (" implemented for `", ""),
1955                     };
1956                 err.highlighted_help(vec![
1957                     (format!("the trait `{}` ", cand.print_only_trait_path()), Style::NoStyle),
1958                     ("is".to_string(), Style::Highlight),
1959                     (desc.to_string(), Style::NoStyle),
1960                     (cand.self_ty().to_string(), Style::Highlight),
1961                     ("`".to_string(), Style::NoStyle),
1962                     (mention_castable.to_string(), Style::NoStyle),
1963                 ]);
1964                 return true;
1965             }
1966             let trait_ref = TraitRef::identity(self.tcx, candidates[0].def_id);
1967             // Check if the trait is the same in all cases. If so, we'll only show the type.
1968             let mut traits: Vec<_> =
1969                 candidates.iter().map(|c| c.print_only_trait_path().to_string()).collect();
1970             traits.sort();
1971             traits.dedup();
1972             // FIXME: this could use a better heuristic, like just checking
1973             // that substs[1..] is the same.
1974             let all_traits_equal = traits.len() == 1;
1975 
1976             let candidates: Vec<String> = candidates
1977                 .into_iter()
1978                 .map(|c| {
1979                     if all_traits_equal {
1980                         format!("\n  {}", c.self_ty())
1981                     } else {
1982                         format!("\n  {}", c)
1983                     }
1984                 })
1985                 .collect();
1986 
1987             let end = if candidates.len() <= 9 { candidates.len() } else { 8 };
1988             err.help(format!(
1989                 "the following {other}types implement trait `{}`:{}{}",
1990                 trait_ref.print_only_trait_path(),
1991                 candidates[..end].join(""),
1992                 if candidates.len() > 9 {
1993                     format!("\nand {} others", candidates.len() - 8)
1994                 } else {
1995                     String::new()
1996                 }
1997             ));
1998             true
1999         };
2000 
2001         let def_id = trait_ref.def_id();
2002         if impl_candidates.is_empty() {
2003             if self.tcx.trait_is_auto(def_id)
2004                 || self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2005                 || self.tcx.get_diagnostic_name(def_id).is_some()
2006             {
2007                 // Mentioning implementers of `Copy`, `Debug` and friends is not useful.
2008                 return false;
2009             }
2010             let mut impl_candidates: Vec<_> = self
2011                 .tcx
2012                 .all_impls(def_id)
2013                 // Ignore automatically derived impls and `!Trait` impls.
2014                 .filter(|&def_id| {
2015                     self.tcx.impl_polarity(def_id) != ty::ImplPolarity::Negative
2016                         || self.tcx.is_automatically_derived(def_id)
2017                 })
2018                 .filter_map(|def_id| self.tcx.impl_trait_ref(def_id))
2019                 .map(ty::EarlyBinder::subst_identity)
2020                 .filter(|trait_ref| {
2021                     let self_ty = trait_ref.self_ty();
2022                     // Avoid mentioning type parameters.
2023                     if let ty::Param(_) = self_ty.kind() {
2024                         false
2025                     }
2026                     // Avoid mentioning types that are private to another crate
2027                     else if let ty::Adt(def, _) = self_ty.peel_refs().kind() {
2028                         // FIXME(compiler-errors): This could be generalized, both to
2029                         // be more granular, and probably look past other `#[fundamental]`
2030                         // types, too.
2031                         self.tcx.visibility(def.did()).is_accessible_from(body_def_id, self.tcx)
2032                     } else {
2033                         true
2034                     }
2035                 })
2036                 .collect();
2037 
2038             impl_candidates.sort();
2039             impl_candidates.dedup();
2040             return report(impl_candidates, err);
2041         }
2042 
2043         // Sort impl candidates so that ordering is consistent for UI tests.
2044         // because the ordering of `impl_candidates` may not be deterministic:
2045         // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
2046         //
2047         // Prefer more similar candidates first, then sort lexicographically
2048         // by their normalized string representation.
2049         let mut impl_candidates: Vec<_> = impl_candidates
2050             .iter()
2051             .cloned()
2052             .map(|mut cand| {
2053                 // Fold the consts so that they shows up as, e.g., `10`
2054                 // instead of `core::::array::{impl#30}::{constant#0}`.
2055                 cand.trait_ref = cand.trait_ref.fold_with(&mut BottomUpFolder {
2056                     tcx: self.tcx,
2057                     ty_op: |ty| ty,
2058                     lt_op: |lt| lt,
2059                     ct_op: |ct| ct.eval(self.tcx, ty::ParamEnv::empty()),
2060                 });
2061                 cand
2062             })
2063             .collect();
2064         impl_candidates.sort_by_key(|cand| (cand.similarity, cand.trait_ref));
2065         impl_candidates.dedup();
2066 
2067         report(impl_candidates.into_iter().map(|cand| cand.trait_ref).collect(), err)
2068     }
2069 
report_similar_impl_candidates_for_root_obligation( &self, obligation: &PredicateObligation<'tcx>, trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>, body_def_id: LocalDefId, err: &mut Diagnostic, )2070     fn report_similar_impl_candidates_for_root_obligation(
2071         &self,
2072         obligation: &PredicateObligation<'tcx>,
2073         trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2074         body_def_id: LocalDefId,
2075         err: &mut Diagnostic,
2076     ) {
2077         // This is *almost* equivalent to
2078         // `obligation.cause.code().peel_derives()`, but it gives us the
2079         // trait predicate for that corresponding root obligation. This
2080         // lets us get a derived obligation from a type parameter, like
2081         // when calling `string.strip_suffix(p)` where `p` is *not* an
2082         // implementer of `Pattern<'_>`.
2083         let mut code = obligation.cause.code();
2084         let mut trait_pred = trait_predicate;
2085         let mut peeled = false;
2086         while let Some((parent_code, parent_trait_pred)) = code.parent() {
2087             code = parent_code;
2088             if let Some(parent_trait_pred) = parent_trait_pred {
2089                 trait_pred = parent_trait_pred;
2090                 peeled = true;
2091             }
2092         }
2093         let def_id = trait_pred.def_id();
2094         // Mention *all* the `impl`s for the *top most* obligation, the
2095         // user might have meant to use one of them, if any found. We skip
2096         // auto-traits or fundamental traits that might not be exactly what
2097         // the user might expect to be presented with. Instead this is
2098         // useful for less general traits.
2099         if peeled
2100             && !self.tcx.trait_is_auto(def_id)
2101             && !self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2102         {
2103             let trait_ref = trait_pred.to_poly_trait_ref();
2104             let impl_candidates = self.find_similar_impl_candidates(trait_pred);
2105             self.report_similar_impl_candidates(
2106                 &impl_candidates,
2107                 trait_ref,
2108                 body_def_id,
2109                 err,
2110                 true,
2111             );
2112         }
2113     }
2114 
2115     /// Gets the parent trait chain start
get_parent_trait_ref( &self, code: &ObligationCauseCode<'tcx>, ) -> Option<(String, Option<Span>)>2116     fn get_parent_trait_ref(
2117         &self,
2118         code: &ObligationCauseCode<'tcx>,
2119     ) -> Option<(String, Option<Span>)> {
2120         match code {
2121             ObligationCauseCode::BuiltinDerivedObligation(data) => {
2122                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2123                 match self.get_parent_trait_ref(&data.parent_code) {
2124                     Some(t) => Some(t),
2125                     None => {
2126                         let ty = parent_trait_ref.skip_binder().self_ty();
2127                         let span = TyCategory::from_ty(self.tcx, ty)
2128                             .map(|(_, def_id)| self.tcx.def_span(def_id));
2129                         Some((ty.to_string(), span))
2130                     }
2131                 }
2132             }
2133             ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
2134                 self.get_parent_trait_ref(&parent_code)
2135             }
2136             _ => None,
2137         }
2138     }
2139 
2140     /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
2141     /// with the same path as `trait_ref`, a help message about
2142     /// a probable version mismatch is added to `err`
note_version_mismatch( &self, err: &mut Diagnostic, trait_ref: &ty::PolyTraitRef<'tcx>, ) -> bool2143     fn note_version_mismatch(
2144         &self,
2145         err: &mut Diagnostic,
2146         trait_ref: &ty::PolyTraitRef<'tcx>,
2147     ) -> bool {
2148         let get_trait_impls = |trait_def_id| {
2149             let mut trait_impls = vec![];
2150             self.tcx.for_each_relevant_impl(
2151                 trait_def_id,
2152                 trait_ref.skip_binder().self_ty(),
2153                 |impl_def_id| {
2154                     trait_impls.push(impl_def_id);
2155                 },
2156             );
2157             trait_impls
2158         };
2159 
2160         let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
2161         let traits_with_same_path: std::collections::BTreeSet<_> = self
2162             .tcx
2163             .all_traits()
2164             .filter(|trait_def_id| *trait_def_id != trait_ref.def_id())
2165             .filter(|trait_def_id| self.tcx.def_path_str(*trait_def_id) == required_trait_path)
2166             .collect();
2167         let mut suggested = false;
2168         for trait_with_same_path in traits_with_same_path {
2169             let trait_impls = get_trait_impls(trait_with_same_path);
2170             if trait_impls.is_empty() {
2171                 continue;
2172             }
2173             let impl_spans: Vec<_> =
2174                 trait_impls.iter().map(|impl_def_id| self.tcx.def_span(*impl_def_id)).collect();
2175             err.span_help(
2176                 impl_spans,
2177                 format!("trait impl{} with same name found", pluralize!(trait_impls.len())),
2178             );
2179             let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
2180             let crate_msg = format!(
2181                 "perhaps two different versions of crate `{}` are being used?",
2182                 trait_crate
2183             );
2184             err.note(crate_msg);
2185             suggested = true;
2186         }
2187         suggested
2188     }
2189 
mk_trait_obligation_with_new_self_ty( &self, param_env: ty::ParamEnv<'tcx>, trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>, ) -> PredicateObligation<'tcx>2190     fn mk_trait_obligation_with_new_self_ty(
2191         &self,
2192         param_env: ty::ParamEnv<'tcx>,
2193         trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>,
2194     ) -> PredicateObligation<'tcx> {
2195         let trait_pred =
2196             trait_ref_and_ty.map_bound(|(tr, new_self_ty)| tr.with_self_ty(self.tcx, new_self_ty));
2197 
2198         Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred)
2199     }
2200 
2201     #[instrument(skip(self), level = "debug")]
maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>)2202     fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>) {
2203         // Unable to successfully determine, probably means
2204         // insufficient type information, but could mean
2205         // ambiguous impls. The latter *ought* to be a
2206         // coherence violation, so we don't report it here.
2207 
2208         let predicate = self.resolve_vars_if_possible(obligation.predicate);
2209         let span = obligation.cause.span;
2210 
2211         debug!(?predicate, obligation.cause.code = ?obligation.cause.code());
2212 
2213         // Ambiguity errors are often caused as fallout from earlier errors.
2214         // We ignore them if this `infcx` is tainted in some cases below.
2215 
2216         let bound_predicate = predicate.kind();
2217         let mut err = match bound_predicate.skip_binder() {
2218             ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => {
2219                 let trait_ref = bound_predicate.rebind(data.trait_ref);
2220                 debug!(?trait_ref);
2221 
2222                 if predicate.references_error() {
2223                     return;
2224                 }
2225 
2226                 // This is kind of a hack: it frequently happens that some earlier
2227                 // error prevents types from being fully inferred, and then we get
2228                 // a bunch of uninteresting errors saying something like "<generic
2229                 // #0> doesn't implement Sized". It may even be true that we
2230                 // could just skip over all checks where the self-ty is an
2231                 // inference variable, but I was afraid that there might be an
2232                 // inference variable created, registered as an obligation, and
2233                 // then never forced by writeback, and hence by skipping here we'd
2234                 // be ignoring the fact that we don't KNOW the type works
2235                 // out. Though even that would probably be harmless, given that
2236                 // we're only talking about builtin traits, which are known to be
2237                 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
2238                 // avoid inundating the user with unnecessary errors, but we now
2239                 // check upstream for type errors and don't add the obligations to
2240                 // begin with in those cases.
2241                 if self.tcx.lang_items().sized_trait() == Some(trait_ref.def_id()) {
2242                     if let None = self.tainted_by_errors() {
2243                         self.emit_inference_failure_err(
2244                             obligation.cause.body_id,
2245                             span,
2246                             trait_ref.self_ty().skip_binder().into(),
2247                             ErrorCode::E0282,
2248                             false,
2249                         )
2250                         .emit();
2251                     }
2252                     return;
2253                 }
2254 
2255                 // Typically, this ambiguity should only happen if
2256                 // there are unresolved type inference variables
2257                 // (otherwise it would suggest a coherence
2258                 // failure). But given #21974 that is not necessarily
2259                 // the case -- we can have multiple where clauses that
2260                 // are only distinguished by a region, which results
2261                 // in an ambiguity even when all types are fully
2262                 // known, since we don't dispatch based on region
2263                 // relationships.
2264 
2265                 // Pick the first substitution that still contains inference variables as the one
2266                 // we're going to emit an error for. If there are none (see above), fall back to
2267                 // a more general error.
2268                 let subst = data.trait_ref.substs.iter().find(|s| s.has_non_region_infer());
2269 
2270                 let mut err = if let Some(subst) = subst {
2271                     self.emit_inference_failure_err(
2272                         obligation.cause.body_id,
2273                         span,
2274                         subst,
2275                         ErrorCode::E0283,
2276                         true,
2277                     )
2278                 } else {
2279                     struct_span_err!(
2280                         self.tcx.sess,
2281                         span,
2282                         E0283,
2283                         "type annotations needed: cannot satisfy `{}`",
2284                         predicate,
2285                     )
2286                 };
2287 
2288                 let ambiguities = ambiguity::recompute_applicable_impls(
2289                     self.infcx,
2290                     &obligation.with(self.tcx, trait_ref),
2291                 );
2292                 let has_non_region_infer =
2293                     trait_ref.skip_binder().substs.types().any(|t| !t.is_ty_or_numeric_infer());
2294                 // It doesn't make sense to talk about applicable impls if there are more
2295                 // than a handful of them.
2296                 if ambiguities.len() > 1 && ambiguities.len() < 10 && has_non_region_infer {
2297                     if self.tainted_by_errors().is_some() && subst.is_none() {
2298                         // If `subst.is_none()`, then this is probably two param-env
2299                         // candidates or impl candidates that are equal modulo lifetimes.
2300                         // Therefore, if we've already emitted an error, just skip this
2301                         // one, since it's not particularly actionable.
2302                         err.cancel();
2303                         return;
2304                     }
2305                     self.annotate_source_of_ambiguity(&mut err, &ambiguities, predicate);
2306                 } else {
2307                     if self.tainted_by_errors().is_some() {
2308                         err.cancel();
2309                         return;
2310                     }
2311                     err.note(format!("cannot satisfy `{}`", predicate));
2312                     let impl_candidates = self
2313                         .find_similar_impl_candidates(predicate.to_opt_poly_trait_pred().unwrap());
2314                     if impl_candidates.len() < 10 {
2315                         self.report_similar_impl_candidates(
2316                             impl_candidates.as_slice(),
2317                             trait_ref,
2318                             obligation.cause.body_id,
2319                             &mut err,
2320                             false,
2321                         );
2322                     }
2323                 }
2324 
2325                 if let ObligationCauseCode::ItemObligation(def_id)
2326                 | ObligationCauseCode::ExprItemObligation(def_id, ..) = *obligation.cause.code()
2327                 {
2328                     self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id());
2329                 }
2330 
2331                 if let Some(ty::subst::GenericArgKind::Type(_)) = subst.map(|subst| subst.unpack())
2332                     && let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id)
2333                 {
2334                     let mut expr_finder = FindExprBySpan::new(span);
2335                     expr_finder.visit_expr(&self.tcx.hir().body(body_id).value);
2336 
2337                     if let Some(hir::Expr {
2338                         kind: hir::ExprKind::Path(hir::QPath::Resolved(None, path)), .. }
2339                     ) = expr_finder.result
2340                         && let [
2341                             ..,
2342                             trait_path_segment @ hir::PathSegment {
2343                                 res: rustc_hir::def::Res::Def(rustc_hir::def::DefKind::Trait, trait_id),
2344                                 ..
2345                             },
2346                             hir::PathSegment {
2347                                 ident: assoc_item_name,
2348                                 res: rustc_hir::def::Res::Def(_, item_id),
2349                                 ..
2350                             }
2351                         ] = path.segments
2352                         && data.trait_ref.def_id == *trait_id
2353                         && self.tcx.trait_of_item(*item_id) == Some(*trait_id)
2354                         && let None = self.tainted_by_errors()
2355                     {
2356                         let (verb, noun) = match self.tcx.associated_item(item_id).kind {
2357                             ty::AssocKind::Const => ("refer to the", "constant"),
2358                             ty::AssocKind::Fn => ("call", "function"),
2359                             ty::AssocKind::Type => ("refer to the", "type"), // this is already covered by E0223, but this single match arm doesn't hurt here
2360                         };
2361 
2362                         // Replace the more general E0283 with a more specific error
2363                         err.cancel();
2364                         err = self.tcx.sess.struct_span_err_with_code(
2365                             span,
2366                             format!(
2367                                 "cannot {verb} associated {noun} on trait without specifying the corresponding `impl` type",
2368                             ),
2369                             rustc_errors::error_code!(E0790),
2370                         );
2371 
2372                         if let Some(local_def_id) = data.trait_ref.def_id.as_local()
2373                             && 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)
2374                             && let Some(method_ref) = trait_item_refs.iter().find(|item_ref| item_ref.ident == *assoc_item_name) {
2375                             err.span_label(method_ref.span, format!("`{}::{}` defined here", trait_name, assoc_item_name));
2376                         }
2377 
2378                         err.span_label(span, format!("cannot {verb} associated {noun} of trait"));
2379 
2380                         let trait_impls = self.tcx.trait_impls_of(data.trait_ref.def_id);
2381 
2382                         if trait_impls.blanket_impls().is_empty()
2383                             && let Some(impl_def_id) = trait_impls.non_blanket_impls().values().flatten().next()
2384                         {
2385                             let non_blanket_impl_count = trait_impls.non_blanket_impls().values().flatten().count();
2386                             // If there is only one implementation of the trait, suggest using it.
2387                             // Otherwise, use a placeholder comment for the implementation.
2388                             let (message, impl_suggestion) = if non_blanket_impl_count == 1 {(
2389                                 "use the fully-qualified path to the only available implementation".to_string(),
2390                                 format!("<{} as ", self.tcx.type_of(impl_def_id).subst_identity())
2391                             )} else {(
2392                                 format!(
2393                                     "use a fully-qualified path to a specific available implementation ({} found)",
2394                                     non_blanket_impl_count
2395                                 ),
2396                                 "</* self type */ as ".to_string()
2397                             )};
2398                             let mut suggestions = vec![(
2399                                 path.span.shrink_to_lo(),
2400                                 impl_suggestion
2401                             )];
2402                             if let Some(generic_arg) = trait_path_segment.args {
2403                                 let between_span = trait_path_segment.ident.span.between(generic_arg.span_ext);
2404                                 // get rid of :: between Trait and <type>
2405                                 // must be '::' between them, otherwise the parser won't accept the code
2406                                 suggestions.push((between_span, "".to_string(),));
2407                                 suggestions.push((generic_arg.span_ext.shrink_to_hi(), ">".to_string()));
2408                             } else {
2409                                 suggestions.push((trait_path_segment.ident.span.shrink_to_hi(), ">".to_string()));
2410                             }
2411                             err.multipart_suggestion(
2412                                 message,
2413                                 suggestions,
2414                                 Applicability::MaybeIncorrect
2415                             );
2416                         }
2417                     }
2418                 };
2419 
2420                 err
2421             }
2422 
2423             ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
2424                 // Same hacky approach as above to avoid deluging user
2425                 // with error messages.
2426                 if arg.references_error()
2427                     || self.tcx.sess.has_errors().is_some()
2428                     || self.tainted_by_errors().is_some()
2429                 {
2430                     return;
2431                 }
2432 
2433                 self.emit_inference_failure_err(
2434                     obligation.cause.body_id,
2435                     span,
2436                     arg,
2437                     ErrorCode::E0282,
2438                     false,
2439                 )
2440             }
2441 
2442             ty::PredicateKind::Subtype(data) => {
2443                 if data.references_error()
2444                     || self.tcx.sess.has_errors().is_some()
2445                     || self.tainted_by_errors().is_some()
2446                 {
2447                     // no need to overload user in such cases
2448                     return;
2449                 }
2450                 let SubtypePredicate { a_is_expected: _, a, b } = data;
2451                 // both must be type variables, or the other would've been instantiated
2452                 assert!(a.is_ty_var() && b.is_ty_var());
2453                 self.emit_inference_failure_err(
2454                     obligation.cause.body_id,
2455                     span,
2456                     a.into(),
2457                     ErrorCode::E0282,
2458                     true,
2459                 )
2460             }
2461             ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
2462                 if predicate.references_error() || self.tainted_by_errors().is_some() {
2463                     return;
2464                 }
2465                 let subst = data
2466                     .projection_ty
2467                     .substs
2468                     .iter()
2469                     .chain(Some(data.term.into_arg()))
2470                     .find(|g| g.has_non_region_infer());
2471                 if let Some(subst) = subst {
2472                     let mut err = self.emit_inference_failure_err(
2473                         obligation.cause.body_id,
2474                         span,
2475                         subst,
2476                         ErrorCode::E0284,
2477                         true,
2478                     );
2479                     err.note(format!("cannot satisfy `{}`", predicate));
2480                     err
2481                 } else {
2482                     // If we can't find a substitution, just print a generic error
2483                     let mut err = struct_span_err!(
2484                         self.tcx.sess,
2485                         span,
2486                         E0284,
2487                         "type annotations needed: cannot satisfy `{}`",
2488                         predicate,
2489                     );
2490                     err.span_label(span, format!("cannot satisfy `{}`", predicate));
2491                     err
2492                 }
2493             }
2494 
2495             ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(data)) => {
2496                 if predicate.references_error() || self.tainted_by_errors().is_some() {
2497                     return;
2498                 }
2499                 let subst = data.walk().find(|g| g.is_non_region_infer());
2500                 if let Some(subst) = subst {
2501                     let err = self.emit_inference_failure_err(
2502                         obligation.cause.body_id,
2503                         span,
2504                         subst,
2505                         ErrorCode::E0284,
2506                         true,
2507                     );
2508                     err
2509                 } else {
2510                     // If we can't find a substitution, just print a generic error
2511                     let mut err = struct_span_err!(
2512                         self.tcx.sess,
2513                         span,
2514                         E0284,
2515                         "type annotations needed: cannot satisfy `{}`",
2516                         predicate,
2517                     );
2518                     err.span_label(span, format!("cannot satisfy `{}`", predicate));
2519                     err
2520                 }
2521             }
2522             _ => {
2523                 if self.tcx.sess.has_errors().is_some() || self.tainted_by_errors().is_some() {
2524                     return;
2525                 }
2526                 let mut err = struct_span_err!(
2527                     self.tcx.sess,
2528                     span,
2529                     E0284,
2530                     "type annotations needed: cannot satisfy `{}`",
2531                     predicate,
2532                 );
2533                 err.span_label(span, format!("cannot satisfy `{}`", predicate));
2534                 err
2535             }
2536         };
2537         self.note_obligation_cause(&mut err, obligation);
2538         err.emit();
2539     }
2540 
annotate_source_of_ambiguity( &self, err: &mut Diagnostic, ambiguities: &[ambiguity::Ambiguity], predicate: ty::Predicate<'tcx>, )2541     fn annotate_source_of_ambiguity(
2542         &self,
2543         err: &mut Diagnostic,
2544         ambiguities: &[ambiguity::Ambiguity],
2545         predicate: ty::Predicate<'tcx>,
2546     ) {
2547         let mut spans = vec![];
2548         let mut crates = vec![];
2549         let mut post = vec![];
2550         let mut has_param_env = false;
2551         for ambiguity in ambiguities {
2552             match ambiguity {
2553                 ambiguity::Ambiguity::DefId(impl_def_id) => {
2554                     match self.tcx.span_of_impl(*impl_def_id) {
2555                         Ok(span) => spans.push(span),
2556                         Err(name) => {
2557                             crates.push(name);
2558                             if let Some(header) = to_pretty_impl_header(self.tcx, *impl_def_id) {
2559                                 post.push(header);
2560                             }
2561                         }
2562                     }
2563                 }
2564                 ambiguity::Ambiguity::ParamEnv(span) => {
2565                     has_param_env = true;
2566                     spans.push(*span);
2567                 }
2568             }
2569         }
2570         let mut crate_names: Vec<_> = crates.iter().map(|n| format!("`{}`", n)).collect();
2571         crate_names.sort();
2572         crate_names.dedup();
2573         post.sort();
2574         post.dedup();
2575 
2576         if self.tainted_by_errors().is_some()
2577             && (crate_names.len() == 1
2578                 && spans.len() == 0
2579                 && ["`core`", "`alloc`", "`std`"].contains(&crate_names[0].as_str())
2580                 || predicate.visit_with(&mut HasNumericInferVisitor).is_break())
2581         {
2582             // Avoid complaining about other inference issues for expressions like
2583             // `42 >> 1`, where the types are still `{integer}`, but we want to
2584             // Do we need `trait_ref.skip_binder().self_ty().is_numeric() &&` too?
2585             // NOTE(eddyb) this was `.cancel()`, but `err`
2586             // is borrowed, so we can't fully defuse it.
2587             err.downgrade_to_delayed_bug();
2588             return;
2589         }
2590 
2591         let msg = format!(
2592             "multiple `impl`s{} satisfying `{}` found",
2593             if has_param_env { " or `where` clauses" } else { "" },
2594             predicate
2595         );
2596         let post = if post.len() > 1 || (post.len() == 1 && post[0].contains('\n')) {
2597             format!(":\n{}", post.iter().map(|p| format!("- {}", p)).collect::<Vec<_>>().join("\n"),)
2598         } else if post.len() == 1 {
2599             format!(": `{}`", post[0])
2600         } else {
2601             String::new()
2602         };
2603 
2604         match (spans.len(), crates.len(), crate_names.len()) {
2605             (0, 0, 0) => {
2606                 err.note(format!("cannot satisfy `{}`", predicate));
2607             }
2608             (0, _, 1) => {
2609                 err.note(format!("{} in the `{}` crate{}", msg, crates[0], post,));
2610             }
2611             (0, _, _) => {
2612                 err.note(format!(
2613                     "{} in the following crates: {}{}",
2614                     msg,
2615                     crate_names.join(", "),
2616                     post,
2617                 ));
2618             }
2619             (_, 0, 0) => {
2620                 let span: MultiSpan = spans.into();
2621                 err.span_note(span, msg);
2622             }
2623             (_, 1, 1) => {
2624                 let span: MultiSpan = spans.into();
2625                 err.span_note(span, msg);
2626                 err.note(format!("and another `impl` found in the `{}` crate{}", crates[0], post,));
2627             }
2628             _ => {
2629                 let span: MultiSpan = spans.into();
2630                 err.span_note(span, msg);
2631                 err.note(format!(
2632                     "and more `impl`s found in the following crates: {}{}",
2633                     crate_names.join(", "),
2634                     post,
2635                 ));
2636             }
2637         }
2638     }
2639 
2640     /// Returns `true` if the trait predicate may apply for *some* assignment
2641     /// to the type parameters.
predicate_can_apply( &self, param_env: ty::ParamEnv<'tcx>, pred: ty::PolyTraitPredicate<'tcx>, ) -> bool2642     fn predicate_can_apply(
2643         &self,
2644         param_env: ty::ParamEnv<'tcx>,
2645         pred: ty::PolyTraitPredicate<'tcx>,
2646     ) -> bool {
2647         struct ParamToVarFolder<'a, 'tcx> {
2648             infcx: &'a InferCtxt<'tcx>,
2649             var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2650         }
2651 
2652         impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ParamToVarFolder<'a, 'tcx> {
2653             fn interner(&self) -> TyCtxt<'tcx> {
2654                 self.infcx.tcx
2655             }
2656 
2657             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2658                 if let ty::Param(_) = *ty.kind() {
2659                     let infcx = self.infcx;
2660                     *self.var_map.entry(ty).or_insert_with(|| {
2661                         infcx.next_ty_var(TypeVariableOrigin {
2662                             kind: TypeVariableOriginKind::MiscVariable,
2663                             span: DUMMY_SP,
2664                         })
2665                     })
2666                 } else {
2667                     ty.super_fold_with(self)
2668                 }
2669             }
2670         }
2671 
2672         self.probe(|_| {
2673             let cleaned_pred =
2674                 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2675 
2676             let InferOk { value: cleaned_pred, .. } =
2677                 self.infcx.at(&ObligationCause::dummy(), param_env).normalize(cleaned_pred);
2678 
2679             let obligation =
2680                 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, cleaned_pred);
2681 
2682             self.predicate_may_hold(&obligation)
2683         })
2684     }
2685 
note_obligation_cause(&self, err: &mut Diagnostic, obligation: &PredicateObligation<'tcx>)2686     fn note_obligation_cause(&self, err: &mut Diagnostic, obligation: &PredicateObligation<'tcx>) {
2687         // First, attempt to add note to this error with an async-await-specific
2688         // message, and fall back to regular note otherwise.
2689         if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2690             self.note_obligation_cause_code(
2691                 obligation.cause.body_id,
2692                 err,
2693                 obligation.predicate,
2694                 obligation.param_env,
2695                 obligation.cause.code(),
2696                 &mut vec![],
2697                 &mut Default::default(),
2698             );
2699             self.suggest_unsized_bound_if_applicable(err, obligation);
2700         }
2701     }
2702 
2703     #[instrument(level = "debug", skip_all)]
suggest_unsized_bound_if_applicable( &self, err: &mut Diagnostic, obligation: &PredicateObligation<'tcx>, )2704     fn suggest_unsized_bound_if_applicable(
2705         &self,
2706         err: &mut Diagnostic,
2707         obligation: &PredicateObligation<'tcx>,
2708     ) {
2709         let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) = obligation.predicate.kind().skip_binder() else { return; };
2710         let (ObligationCauseCode::BindingObligation(item_def_id, span)
2711         | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..))
2712             = *obligation.cause.code().peel_derives() else { return; };
2713         debug!(?pred, ?item_def_id, ?span);
2714 
2715         let (Some(node), true) = (
2716             self.tcx.hir().get_if_local(item_def_id),
2717             Some(pred.def_id()) == self.tcx.lang_items().sized_trait(),
2718         ) else {
2719             return;
2720         };
2721         self.maybe_suggest_unsized_generics(err, span, node);
2722     }
2723 
2724     #[instrument(level = "debug", skip_all)]
maybe_suggest_unsized_generics(&self, err: &mut Diagnostic, span: Span, node: Node<'tcx>)2725     fn maybe_suggest_unsized_generics(&self, err: &mut Diagnostic, span: Span, node: Node<'tcx>) {
2726         let Some(generics) = node.generics() else {
2727             return;
2728         };
2729         let sized_trait = self.tcx.lang_items().sized_trait();
2730         debug!(?generics.params);
2731         debug!(?generics.predicates);
2732         let Some(param) = generics.params.iter().find(|param| param.span == span) else {
2733             return;
2734         };
2735         // Check that none of the explicit trait bounds is `Sized`. Assume that an explicit
2736         // `Sized` bound is there intentionally and we don't need to suggest relaxing it.
2737         let explicitly_sized = generics
2738             .bounds_for_param(param.def_id)
2739             .flat_map(|bp| bp.bounds)
2740             .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
2741         if explicitly_sized {
2742             return;
2743         }
2744         debug!(?param);
2745         match node {
2746             hir::Node::Item(
2747                 item @ hir::Item {
2748                     // Only suggest indirection for uses of type parameters in ADTs.
2749                     kind:
2750                         hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
2751                     ..
2752                 },
2753             ) => {
2754                 if self.maybe_indirection_for_unsized(err, item, param) {
2755                     return;
2756                 }
2757             }
2758             _ => {}
2759         };
2760         // Didn't add an indirection suggestion, so add a general suggestion to relax `Sized`.
2761         let (span, separator) = if let Some(s) = generics.bounds_span_for_suggestions(param.def_id)
2762         {
2763             (s, " +")
2764         } else {
2765             (span.shrink_to_hi(), ":")
2766         };
2767         err.span_suggestion_verbose(
2768             span,
2769             "consider relaxing the implicit `Sized` restriction",
2770             format!("{} ?Sized", separator),
2771             Applicability::MachineApplicable,
2772         );
2773     }
2774 
maybe_indirection_for_unsized( &self, err: &mut Diagnostic, item: &Item<'tcx>, param: &GenericParam<'tcx>, ) -> bool2775     fn maybe_indirection_for_unsized(
2776         &self,
2777         err: &mut Diagnostic,
2778         item: &Item<'tcx>,
2779         param: &GenericParam<'tcx>,
2780     ) -> bool {
2781         // Suggesting `T: ?Sized` is only valid in an ADT if `T` is only used in a
2782         // borrow. `struct S<'a, T: ?Sized>(&'a T);` is valid, `struct S<T: ?Sized>(T);`
2783         // is not. Look for invalid "bare" parameter uses, and suggest using indirection.
2784         let mut visitor =
2785             FindTypeParam { param: param.name.ident().name, invalid_spans: vec![], nested: false };
2786         visitor.visit_item(item);
2787         if visitor.invalid_spans.is_empty() {
2788             return false;
2789         }
2790         let mut multispan: MultiSpan = param.span.into();
2791         multispan.push_span_label(
2792             param.span,
2793             format!("this could be changed to `{}: ?Sized`...", param.name.ident()),
2794         );
2795         for sp in visitor.invalid_spans {
2796             multispan.push_span_label(
2797                 sp,
2798                 format!("...if indirection were used here: `Box<{}>`", param.name.ident()),
2799             );
2800         }
2801         err.span_help(
2802             multispan,
2803             format!(
2804                 "you could relax the implicit `Sized` bound on `{T}` if it were \
2805                 used through indirection like `&{T}` or `Box<{T}>`",
2806                 T = param.name.ident(),
2807             ),
2808         );
2809         true
2810     }
2811 
is_recursive_obligation( &self, obligated_types: &mut Vec<Ty<'tcx>>, cause_code: &ObligationCauseCode<'tcx>, ) -> bool2812     fn is_recursive_obligation(
2813         &self,
2814         obligated_types: &mut Vec<Ty<'tcx>>,
2815         cause_code: &ObligationCauseCode<'tcx>,
2816     ) -> bool {
2817         if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
2818             let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2819             let self_ty = parent_trait_ref.skip_binder().self_ty();
2820             if obligated_types.iter().any(|ot| ot == &self_ty) {
2821                 return true;
2822             }
2823             if let ty::Adt(def, substs) = self_ty.kind()
2824                 && let [arg] = &substs[..]
2825                 && let ty::subst::GenericArgKind::Type(ty) = arg.unpack()
2826                 && let ty::Adt(inner_def, _) = ty.kind()
2827                 && inner_def == def
2828             {
2829                 return true;
2830             }
2831         }
2832         false
2833     }
2834 
get_standard_error_message( &self, trait_predicate: &ty::PolyTraitPredicate<'tcx>, message: Option<String>, predicate_is_const: bool, append_const_msg: Option<AppendConstMessage>, post_message: String, ) -> String2835     fn get_standard_error_message(
2836         &self,
2837         trait_predicate: &ty::PolyTraitPredicate<'tcx>,
2838         message: Option<String>,
2839         predicate_is_const: bool,
2840         append_const_msg: Option<AppendConstMessage>,
2841         post_message: String,
2842     ) -> String {
2843         message
2844             .and_then(|cannot_do_this| {
2845                 match (predicate_is_const, append_const_msg) {
2846                     // do nothing if predicate is not const
2847                     (false, _) => Some(cannot_do_this),
2848                     // suggested using default post message
2849                     (true, Some(AppendConstMessage::Default)) => {
2850                         Some(format!("{cannot_do_this} in const contexts"))
2851                     }
2852                     // overridden post message
2853                     (true, Some(AppendConstMessage::Custom(custom_msg))) => {
2854                         Some(format!("{cannot_do_this}{custom_msg}"))
2855                     }
2856                     // fallback to generic message
2857                     (true, None) => None,
2858                 }
2859             })
2860             .unwrap_or_else(|| {
2861                 format!("the trait bound `{}` is not satisfied{}", trait_predicate, post_message)
2862             })
2863     }
2864 
get_safe_transmute_error_and_reason( &self, obligation: PredicateObligation<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>, span: Span, ) -> GetSafeTransmuteErrorAndReason2865     fn get_safe_transmute_error_and_reason(
2866         &self,
2867         obligation: PredicateObligation<'tcx>,
2868         trait_ref: ty::PolyTraitRef<'tcx>,
2869         span: Span,
2870     ) -> GetSafeTransmuteErrorAndReason {
2871         use rustc_transmute::Answer;
2872 
2873         // Erase regions because layout code doesn't particularly care about regions.
2874         let trait_ref = self.tcx.erase_regions(self.tcx.erase_late_bound_regions(trait_ref));
2875 
2876         let src_and_dst = rustc_transmute::Types {
2877             dst: trait_ref.substs.type_at(0),
2878             src: trait_ref.substs.type_at(1),
2879         };
2880         let scope = trait_ref.substs.type_at(2);
2881         let Some(assume) =
2882             rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, trait_ref.substs.const_at(3)) else {
2883                 span_bug!(span, "Unable to construct rustc_transmute::Assume where it was previously possible");
2884             };
2885 
2886         match rustc_transmute::TransmuteTypeEnv::new(self.infcx).is_transmutable(
2887             obligation.cause,
2888             src_and_dst,
2889             scope,
2890             assume,
2891         ) {
2892             Answer::No(reason) => {
2893                 let dst = trait_ref.substs.type_at(0);
2894                 let src = trait_ref.substs.type_at(1);
2895                 let err_msg = format!(
2896                     "`{src}` cannot be safely transmuted into `{dst}` in the defining scope of `{scope}`"
2897                 );
2898                 let safe_transmute_explanation = match reason {
2899                     rustc_transmute::Reason::SrcIsUnspecified => {
2900                         format!("`{src}` does not have a well-specified layout")
2901                     }
2902 
2903                     rustc_transmute::Reason::DstIsUnspecified => {
2904                         format!("`{dst}` does not have a well-specified layout")
2905                     }
2906 
2907                     rustc_transmute::Reason::DstIsBitIncompatible => {
2908                         format!("At least one value of `{src}` isn't a bit-valid value of `{dst}`")
2909                     }
2910 
2911                     rustc_transmute::Reason::DstIsPrivate => format!(
2912                         "`{dst}` is or contains a type or field that is not visible in that scope"
2913                     ),
2914                     rustc_transmute::Reason::DstIsTooBig => {
2915                         format!("The size of `{src}` is smaller than the size of `{dst}`")
2916                     }
2917                     rustc_transmute::Reason::DstHasStricterAlignment {
2918                         src_min_align,
2919                         dst_min_align,
2920                     } => {
2921                         format!(
2922                             "The minimum alignment of `{src}` ({src_min_align}) should be greater than that of `{dst}` ({dst_min_align})"
2923                         )
2924                     }
2925                     rustc_transmute::Reason::DstIsMoreUnique => {
2926                         format!("`{src}` is a shared reference, but `{dst}` is a unique reference")
2927                     }
2928                     // Already reported by rustc
2929                     rustc_transmute::Reason::TypeError => {
2930                         return GetSafeTransmuteErrorAndReason::Silent;
2931                     }
2932                     rustc_transmute::Reason::SrcLayoutUnknown => {
2933                         format!("`{src}` has an unknown layout")
2934                     }
2935                     rustc_transmute::Reason::DstLayoutUnknown => {
2936                         format!("`{dst}` has an unknown layout")
2937                     }
2938                 };
2939                 GetSafeTransmuteErrorAndReason::Error { err_msg, safe_transmute_explanation }
2940             }
2941             // Should never get a Yes at this point! We already ran it before, and did not get a Yes.
2942             Answer::Yes => span_bug!(
2943                 span,
2944                 "Inconsistent rustc_transmute::is_transmutable(...) result, got Yes",
2945             ),
2946             other => span_bug!(span, "Unsupported rustc_transmute::Answer variant: `{other:?}`"),
2947         }
2948     }
2949 
add_tuple_trait_message( &self, obligation_cause_code: &ObligationCauseCode<'tcx>, err: &mut Diagnostic, )2950     fn add_tuple_trait_message(
2951         &self,
2952         obligation_cause_code: &ObligationCauseCode<'tcx>,
2953         err: &mut Diagnostic,
2954     ) {
2955         match obligation_cause_code {
2956             ObligationCauseCode::RustCall => {
2957                 err.set_primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
2958             }
2959             ObligationCauseCode::BindingObligation(def_id, _)
2960             | ObligationCauseCode::ItemObligation(def_id)
2961                 if self.tcx.is_fn_trait(*def_id) =>
2962             {
2963                 err.code(rustc_errors::error_code!(E0059));
2964                 err.set_primary_message(format!(
2965                     "type parameter to bare `{}` trait must be a tuple",
2966                     self.tcx.def_path_str(*def_id)
2967                 ));
2968             }
2969             _ => {}
2970         }
2971     }
2972 
try_to_add_help_message( &self, obligation: &PredicateObligation<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>, trait_predicate: &ty::PolyTraitPredicate<'tcx>, err: &mut Diagnostic, span: Span, is_fn_trait: bool, suggested: bool, unsatisfied_const: bool, )2973     fn try_to_add_help_message(
2974         &self,
2975         obligation: &PredicateObligation<'tcx>,
2976         trait_ref: ty::PolyTraitRef<'tcx>,
2977         trait_predicate: &ty::PolyTraitPredicate<'tcx>,
2978         err: &mut Diagnostic,
2979         span: Span,
2980         is_fn_trait: bool,
2981         suggested: bool,
2982         unsatisfied_const: bool,
2983     ) {
2984         let body_def_id = obligation.cause.body_id;
2985         // Try to report a help message
2986         if is_fn_trait
2987             && let Ok((implemented_kind, params)) = self.type_implements_fn_trait(
2988             obligation.param_env,
2989             trait_ref.self_ty(),
2990             trait_predicate.skip_binder().constness,
2991             trait_predicate.skip_binder().polarity,
2992         )
2993         {
2994             self.add_help_message_for_fn_trait(trait_ref, err, implemented_kind, params);
2995         } else if !trait_ref.has_non_region_infer()
2996             && self.predicate_can_apply(obligation.param_env, *trait_predicate)
2997         {
2998             // If a where-clause may be useful, remind the
2999             // user that they can add it.
3000             //
3001             // don't display an on-unimplemented note, as
3002             // these notes will often be of the form
3003             //     "the type `T` can't be frobnicated"
3004             // which is somewhat confusing.
3005             self.suggest_restricting_param_bound(
3006                 err,
3007                 *trait_predicate,
3008                 None,
3009                 obligation.cause.body_id,
3010             );
3011         } else if !suggested && !unsatisfied_const {
3012             // Can't show anything else useful, try to find similar impls.
3013             let impl_candidates = self.find_similar_impl_candidates(*trait_predicate);
3014             if !self.report_similar_impl_candidates(
3015                 &impl_candidates,
3016                 trait_ref,
3017                 body_def_id,
3018                 err,
3019                 true,
3020             ) {
3021                 self.report_similar_impl_candidates_for_root_obligation(&obligation, *trait_predicate, body_def_id, err);
3022             }
3023 
3024             self.maybe_suggest_convert_to_slice(
3025                 err,
3026                 trait_ref,
3027                 impl_candidates.as_slice(),
3028                 span,
3029             );
3030         }
3031     }
3032 
add_help_message_for_fn_trait( &self, trait_ref: ty::PolyTraitRef<'tcx>, err: &mut Diagnostic, implemented_kind: ty::ClosureKind, params: ty::Binder<'tcx, Ty<'tcx>>, )3033     fn add_help_message_for_fn_trait(
3034         &self,
3035         trait_ref: ty::PolyTraitRef<'tcx>,
3036         err: &mut Diagnostic,
3037         implemented_kind: ty::ClosureKind,
3038         params: ty::Binder<'tcx, Ty<'tcx>>,
3039     ) {
3040         // If the type implements `Fn`, `FnMut`, or `FnOnce`, suppress the following
3041         // suggestion to add trait bounds for the type, since we only typically implement
3042         // these traits once.
3043 
3044         // Note if the `FnMut` or `FnOnce` is less general than the trait we're trying
3045         // to implement.
3046         let selected_kind = self
3047             .tcx
3048             .fn_trait_kind_from_def_id(trait_ref.def_id())
3049             .expect("expected to map DefId to ClosureKind");
3050         if !implemented_kind.extends(selected_kind) {
3051             err.note(format!(
3052                 "`{}` implements `{}`, but it must implement `{}`, which is more general",
3053                 trait_ref.skip_binder().self_ty(),
3054                 implemented_kind,
3055                 selected_kind
3056             ));
3057         }
3058 
3059         // Note any argument mismatches
3060         let given_ty = params.skip_binder();
3061         let expected_ty = trait_ref.skip_binder().substs.type_at(1);
3062         if let ty::Tuple(given) = given_ty.kind()
3063             && let ty::Tuple(expected) = expected_ty.kind()
3064         {
3065             if expected.len() != given.len() {
3066                 // Note number of types that were expected and given
3067                 err.note(
3068                     format!(
3069                         "expected a closure taking {} argument{}, but one taking {} argument{} was given",
3070                         given.len(),
3071                         pluralize!(given.len()),
3072                         expected.len(),
3073                         pluralize!(expected.len()),
3074                     )
3075                 );
3076             } else if !self.same_type_modulo_infer(given_ty, expected_ty) {
3077                 // Print type mismatch
3078                 let (expected_args, given_args) =
3079                     self.cmp(given_ty, expected_ty);
3080                 err.note_expected_found(
3081                     &"a closure with arguments",
3082                     expected_args,
3083                     &"a closure with arguments",
3084                     given_args,
3085                 );
3086             }
3087         }
3088     }
3089 
maybe_add_note_for_unsatisfied_const( &self, obligation: &PredicateObligation<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>, trait_predicate: &ty::PolyTraitPredicate<'tcx>, err: &mut Diagnostic, span: Span, ) -> UnsatisfiedConst3090     fn maybe_add_note_for_unsatisfied_const(
3091         &self,
3092         obligation: &PredicateObligation<'tcx>,
3093         trait_ref: ty::PolyTraitRef<'tcx>,
3094         trait_predicate: &ty::PolyTraitPredicate<'tcx>,
3095         err: &mut Diagnostic,
3096         span: Span,
3097     ) -> UnsatisfiedConst {
3098         let mut unsatisfied_const = UnsatisfiedConst(false);
3099         if trait_predicate.is_const_if_const() && obligation.param_env.is_const() {
3100             let non_const_predicate = trait_ref.without_const();
3101             let non_const_obligation = Obligation {
3102                 cause: obligation.cause.clone(),
3103                 param_env: obligation.param_env.without_const(),
3104                 predicate: non_const_predicate.to_predicate(self.tcx),
3105                 recursion_depth: obligation.recursion_depth,
3106             };
3107             if self.predicate_may_hold(&non_const_obligation) {
3108                 unsatisfied_const = UnsatisfiedConst(true);
3109                 err.span_note(
3110                     span,
3111                     format!(
3112                         "the trait `{}` is implemented for `{}`, \
3113                         but that implementation is not `const`",
3114                         non_const_predicate.print_modifiers_and_trait_path(),
3115                         trait_ref.skip_binder().self_ty(),
3116                     ),
3117                 );
3118             }
3119         }
3120         unsatisfied_const
3121     }
3122 
report_closure_error( &self, obligation: &PredicateObligation<'tcx>, closure_def_id: DefId, found_kind: ty::ClosureKind, kind: ty::ClosureKind, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>3123     fn report_closure_error(
3124         &self,
3125         obligation: &PredicateObligation<'tcx>,
3126         closure_def_id: DefId,
3127         found_kind: ty::ClosureKind,
3128         kind: ty::ClosureKind,
3129     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
3130         let closure_span = self.tcx.def_span(closure_def_id);
3131         let mut err = struct_span_err!(
3132             self.tcx.sess,
3133             closure_span,
3134             E0525,
3135             "expected a closure that implements the `{}` trait, \
3136                 but this closure only implements `{}`",
3137             kind,
3138             found_kind
3139         );
3140 
3141         err.span_label(
3142             closure_span,
3143             format!("this closure implements `{}`, not `{}`", found_kind, kind),
3144         );
3145         err.span_label(
3146             obligation.cause.span,
3147             format!("the requirement to implement `{}` derives from here", kind),
3148         );
3149 
3150         // Additional context information explaining why the closure only implements
3151         // a particular trait.
3152         if let Some(typeck_results) = &self.typeck_results {
3153             let hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_def_id.expect_local());
3154             match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
3155                 (ty::ClosureKind::FnOnce, Some((span, place))) => {
3156                     err.span_label(
3157                         *span,
3158                         format!(
3159                             "closure is `FnOnce` because it moves the \
3160                             variable `{}` out of its environment",
3161                             ty::place_to_string_for_capture(self.tcx, place)
3162                         ),
3163                     );
3164                 }
3165                 (ty::ClosureKind::FnMut, Some((span, place))) => {
3166                     err.span_label(
3167                         *span,
3168                         format!(
3169                             "closure is `FnMut` because it mutates the \
3170                             variable `{}` here",
3171                             ty::place_to_string_for_capture(self.tcx, place)
3172                         ),
3173                     );
3174                 }
3175                 _ => {}
3176             }
3177         }
3178 
3179         err
3180     }
3181 
report_type_parameter_mismatch_cyclic_type_error( &self, obligation: &PredicateObligation<'tcx>, found_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>, expected_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>, terr: TypeError<'tcx>, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>3182     fn report_type_parameter_mismatch_cyclic_type_error(
3183         &self,
3184         obligation: &PredicateObligation<'tcx>,
3185         found_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
3186         expected_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
3187         terr: TypeError<'tcx>,
3188     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
3189         let self_ty = found_trait_ref.self_ty().skip_binder();
3190         let (cause, terr) = if let ty::Closure(def_id, _) = self_ty.kind() {
3191             (
3192                 ObligationCause::dummy_with_span(self.tcx.def_span(def_id)),
3193                 TypeError::CyclicTy(self_ty),
3194             )
3195         } else {
3196             (obligation.cause.clone(), terr)
3197         };
3198         self.report_and_explain_type_error(
3199             TypeTrace::poly_trait_refs(&cause, true, expected_trait_ref, found_trait_ref),
3200             terr,
3201         )
3202     }
3203 
report_opaque_type_auto_trait_leakage( &self, obligation: &PredicateObligation<'tcx>, def_id: DefId, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>3204     fn report_opaque_type_auto_trait_leakage(
3205         &self,
3206         obligation: &PredicateObligation<'tcx>,
3207         def_id: DefId,
3208     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
3209         let name = match self.tcx.opaque_type_origin(def_id.expect_local()) {
3210             hir::OpaqueTyOrigin::FnReturn(_) | hir::OpaqueTyOrigin::AsyncFn(_) => {
3211                 format!("opaque type")
3212             }
3213             hir::OpaqueTyOrigin::TyAlias { .. } => {
3214                 format!("`{}`", self.tcx.def_path_debug_str(def_id))
3215             }
3216         };
3217         let mut err = self.tcx.sess.struct_span_err(
3218             obligation.cause.span,
3219             format!("cannot check whether the hidden type of {name} satisfies auto traits"),
3220         );
3221         err.span_note(self.tcx.def_span(def_id), "opaque type is declared here");
3222         match self.defining_use_anchor {
3223             DefiningAnchor::Bubble | DefiningAnchor::Error => {}
3224             DefiningAnchor::Bind(bind) => {
3225                 err.span_note(
3226                     self.tcx.def_ident_span(bind).unwrap_or_else(|| self.tcx.def_span(bind)),
3227                     "this item depends on auto traits of the hidden type, \
3228                     but may also be registering the hidden type. \
3229                     This is not supported right now. \
3230                     You can try moving the opaque type and the item that actually registers a hidden type into a new submodule".to_string(),
3231                 );
3232             }
3233         };
3234         err
3235     }
3236 
report_type_parameter_mismatch_error( &self, obligation: &PredicateObligation<'tcx>, span: Span, found_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>, expected_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>, ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>>3237     fn report_type_parameter_mismatch_error(
3238         &self,
3239         obligation: &PredicateObligation<'tcx>,
3240         span: Span,
3241         found_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
3242         expected_trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
3243     ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
3244         let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
3245         let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
3246 
3247         if expected_trait_ref.self_ty().references_error() {
3248             return None;
3249         }
3250 
3251         let Some(found_trait_ty) = found_trait_ref.self_ty().no_bound_vars() else {
3252             return None;
3253         };
3254 
3255         let found_did = match *found_trait_ty.kind() {
3256             ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) | ty::Generator(did, ..) => {
3257                 Some(did)
3258             }
3259             ty::Adt(def, _) => Some(def.did()),
3260             _ => None,
3261         };
3262 
3263         let found_node = found_did.and_then(|did| self.tcx.hir().get_if_local(did));
3264         let found_span = found_did.and_then(|did| self.tcx.hir().span_if_local(did));
3265 
3266         if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
3267             // We check closures twice, with obligations flowing in different directions,
3268             // but we want to complain about them only once.
3269             return None;
3270         }
3271 
3272         self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
3273 
3274         let mut not_tupled = false;
3275 
3276         let found = match found_trait_ref.skip_binder().substs.type_at(1).kind() {
3277             ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
3278             _ => {
3279                 not_tupled = true;
3280                 vec![ArgKind::empty()]
3281             }
3282         };
3283 
3284         let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
3285         let expected = match expected_ty.kind() {
3286             ty::Tuple(ref tys) => {
3287                 tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
3288             }
3289             _ => {
3290                 not_tupled = true;
3291                 vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())]
3292             }
3293         };
3294 
3295         // If this is a `Fn` family trait and either the expected or found
3296         // is not tupled, then fall back to just a regular mismatch error.
3297         // This shouldn't be common unless manually implementing one of the
3298         // traits manually, but don't make it more confusing when it does
3299         // happen.
3300         Some(
3301             if Some(expected_trait_ref.def_id()) != self.tcx.lang_items().gen_trait() && not_tupled
3302             {
3303                 self.report_and_explain_type_error(
3304                     TypeTrace::poly_trait_refs(
3305                         &obligation.cause,
3306                         true,
3307                         expected_trait_ref,
3308                         found_trait_ref,
3309                     ),
3310                     ty::error::TypeError::Mismatch,
3311                 )
3312             } else if found.len() == expected.len() {
3313                 self.report_closure_arg_mismatch(
3314                     span,
3315                     found_span,
3316                     found_trait_ref,
3317                     expected_trait_ref,
3318                     obligation.cause.code(),
3319                     found_node,
3320                     obligation.param_env,
3321                 )
3322             } else {
3323                 let (closure_span, closure_arg_span, found) = found_did
3324                     .and_then(|did| {
3325                         let node = self.tcx.hir().get_if_local(did)?;
3326                         let (found_span, closure_arg_span, found) =
3327                             self.get_fn_like_arguments(node)?;
3328                         Some((Some(found_span), closure_arg_span, found))
3329                     })
3330                     .unwrap_or((found_span, None, found));
3331 
3332                 self.report_arg_count_mismatch(
3333                     span,
3334                     closure_span,
3335                     expected,
3336                     found,
3337                     found_trait_ty.is_closure(),
3338                     closure_arg_span,
3339                 )
3340             },
3341         )
3342     }
3343 
report_not_const_evaluatable_error( &self, obligation: &PredicateObligation<'tcx>, span: Span, ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>>3344     fn report_not_const_evaluatable_error(
3345         &self,
3346         obligation: &PredicateObligation<'tcx>,
3347         span: Span,
3348     ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
3349         if !self.tcx.features().generic_const_exprs {
3350             let mut err = self
3351                 .tcx
3352                 .sess
3353                 .struct_span_err(span, "constant expression depends on a generic parameter");
3354             // FIXME(const_generics): we should suggest to the user how they can resolve this
3355             // issue. However, this is currently not actually possible
3356             // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
3357             //
3358             // Note that with `feature(generic_const_exprs)` this case should not
3359             // be reachable.
3360             err.note("this may fail depending on what value the parameter takes");
3361             err.emit();
3362             return None;
3363         }
3364 
3365         match obligation.predicate.kind().skip_binder() {
3366             ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => {
3367                 let ty::ConstKind::Unevaluated(uv) = ct.kind() else {
3368                     bug!("const evaluatable failed for non-unevaluated const `{ct:?}`");
3369                 };
3370                 let mut err = self.tcx.sess.struct_span_err(span, "unconstrained generic constant");
3371                 let const_span = self.tcx.def_span(uv.def);
3372                 match self.tcx.sess.source_map().span_to_snippet(const_span) {
3373                     Ok(snippet) => err.help(format!(
3374                         "try adding a `where` bound using this expression: `where [(); {}]:`",
3375                         snippet
3376                     )),
3377                     _ => err.help("consider adding a `where` bound using this expression"),
3378                 };
3379                 Some(err)
3380             }
3381             _ => {
3382                 span_bug!(
3383                     span,
3384                     "unexpected non-ConstEvaluatable predicate, this should not be reachable"
3385                 )
3386             }
3387         }
3388     }
3389 }
3390 
3391 struct UnsatisfiedConst(pub bool);
3392 
get_explanation_based_on_obligation<'tcx>( obligation: &PredicateObligation<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>, trait_predicate: &ty::PolyTraitPredicate<'tcx>, pre_message: String, ) -> String3393 fn get_explanation_based_on_obligation<'tcx>(
3394     obligation: &PredicateObligation<'tcx>,
3395     trait_ref: ty::PolyTraitRef<'tcx>,
3396     trait_predicate: &ty::PolyTraitPredicate<'tcx>,
3397     pre_message: String,
3398 ) -> String {
3399     if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
3400         "consider using `()`, or a `Result`".to_owned()
3401     } else {
3402         let ty_desc = match trait_ref.skip_binder().self_ty().kind() {
3403             ty::FnDef(_, _) => Some("fn item"),
3404             ty::Closure(_, _) => Some("closure"),
3405             _ => None,
3406         };
3407 
3408         match ty_desc {
3409             Some(desc) => format!(
3410                 "{}the trait `{}` is not implemented for {} `{}`",
3411                 pre_message,
3412                 trait_predicate.print_modifiers_and_trait_path(),
3413                 desc,
3414                 trait_ref.skip_binder().self_ty(),
3415             ),
3416             None => format!(
3417                 "{}the trait `{}` is not implemented for `{}`",
3418                 pre_message,
3419                 trait_predicate.print_modifiers_and_trait_path(),
3420                 trait_ref.skip_binder().self_ty(),
3421             ),
3422         }
3423     }
3424 }
3425 /// Crude way of getting back an `Expr` from a `Span`.
3426 pub struct FindExprBySpan<'hir> {
3427     pub span: Span,
3428     pub result: Option<&'hir hir::Expr<'hir>>,
3429     pub ty_result: Option<&'hir hir::Ty<'hir>>,
3430 }
3431 
3432 impl<'hir> FindExprBySpan<'hir> {
new(span: Span) -> Self3433     pub fn new(span: Span) -> Self {
3434         Self { span, result: None, ty_result: None }
3435     }
3436 }
3437 
3438 impl<'v> Visitor<'v> for FindExprBySpan<'v> {
visit_expr(&mut self, ex: &'v hir::Expr<'v>)3439     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3440         if self.span == ex.span {
3441             self.result = Some(ex);
3442         } else {
3443             hir::intravisit::walk_expr(self, ex);
3444         }
3445     }
visit_ty(&mut self, ty: &'v hir::Ty<'v>)3446     fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
3447         if self.span == ty.span {
3448             self.ty_result = Some(ty);
3449         } else {
3450             hir::intravisit::walk_ty(self, ty);
3451         }
3452     }
3453 }
3454 
3455 /// Look for type `param` in an ADT being used only through a reference to confirm that suggesting
3456 /// `param: ?Sized` would be a valid constraint.
3457 struct FindTypeParam {
3458     param: rustc_span::Symbol,
3459     invalid_spans: Vec<Span>,
3460     nested: bool,
3461 }
3462 
3463 impl<'v> Visitor<'v> for FindTypeParam {
visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>)3464     fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
3465         // Skip where-clauses, to avoid suggesting indirection for type parameters found there.
3466     }
3467 
visit_ty(&mut self, ty: &hir::Ty<'_>)3468     fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
3469         // We collect the spans of all uses of the "bare" type param, like in `field: T` or
3470         // `field: (T, T)` where we could make `T: ?Sized` while skipping cases that are known to be
3471         // valid like `field: &'a T` or `field: *mut T` and cases that *might* have further `Sized`
3472         // obligations like `Box<T>` and `Vec<T>`, but we perform no extra analysis for those cases
3473         // and suggest `T: ?Sized` regardless of their obligations. This is fine because the errors
3474         // in that case should make what happened clear enough.
3475         match ty.kind {
3476             hir::TyKind::Ptr(_) | hir::TyKind::Ref(..) | hir::TyKind::TraitObject(..) => {}
3477             hir::TyKind::Path(hir::QPath::Resolved(None, path))
3478                 if path.segments.len() == 1 && path.segments[0].ident.name == self.param =>
3479             {
3480                 if !self.nested {
3481                     debug!(?ty, "FindTypeParam::visit_ty");
3482                     self.invalid_spans.push(ty.span);
3483                 }
3484             }
3485             hir::TyKind::Path(_) => {
3486                 let prev = self.nested;
3487                 self.nested = true;
3488                 hir::intravisit::walk_ty(self, ty);
3489                 self.nested = prev;
3490             }
3491             _ => {
3492                 hir::intravisit::walk_ty(self, ty);
3493             }
3494         }
3495     }
3496 }
3497 
3498 /// Summarizes information
3499 #[derive(Clone)]
3500 pub enum ArgKind {
3501     /// An argument of non-tuple type. Parameters are (name, ty)
3502     Arg(String, String),
3503 
3504     /// An argument of tuple type. For a "found" argument, the span is
3505     /// the location in the source of the pattern. For an "expected"
3506     /// argument, it will be None. The vector is a list of (name, ty)
3507     /// strings for the components of the tuple.
3508     Tuple(Option<Span>, Vec<(String, String)>),
3509 }
3510 
3511 impl ArgKind {
empty() -> ArgKind3512     fn empty() -> ArgKind {
3513         ArgKind::Arg("_".to_owned(), "_".to_owned())
3514     }
3515 
3516     /// Creates an `ArgKind` from the expected type of an
3517     /// argument. It has no name (`_`) and an optional source span.
from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind3518     pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
3519         match t.kind() {
3520             ty::Tuple(tys) => ArgKind::Tuple(
3521                 span,
3522                 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
3523             ),
3524             _ => ArgKind::Arg("_".to_owned(), t.to_string()),
3525         }
3526     }
3527 }
3528 
3529 struct HasNumericInferVisitor;
3530 
3531 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for HasNumericInferVisitor {
3532     type BreakTy = ();
3533 
visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy>3534     fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
3535         if matches!(ty.kind(), ty::Infer(ty::FloatVar(_) | ty::IntVar(_))) {
3536             ControlFlow::Break(())
3537         } else {
3538             ControlFlow::Continue(())
3539         }
3540     }
3541 }
3542 
3543 #[derive(Copy, Clone)]
3544 pub enum DefIdOrName {
3545     DefId(DefId),
3546     Name(&'static str),
3547 }
3548 
dump_proof_tree<'tcx>(o: &Obligation<'tcx, ty::Predicate<'tcx>>, infcx: &InferCtxt<'tcx>)3549 pub fn dump_proof_tree<'tcx>(o: &Obligation<'tcx, ty::Predicate<'tcx>>, infcx: &InferCtxt<'tcx>) {
3550     infcx.probe(|_| {
3551         let goal = Goal { predicate: o.predicate, param_env: o.param_env };
3552         let tree = infcx
3553             .evaluate_root_goal(goal, GenerateProofTree::Yes(UseGlobalCache::No))
3554             .1
3555             .expect("proof tree should have been generated");
3556         let mut lock = std::io::stdout().lock();
3557         let _ = lock.write_fmt(format_args!("{tree:?}"));
3558         let _ = lock.flush();
3559     });
3560 }
3561