Skip to main content

rustc_trait_selection/error_reporting/traits/
fulfillment_errors.rs

1// ignore-tidy-file-filelength
2use core::ops::ControlFlow;
3use std::borrow::Cow;
4use std::collections::hash_set;
5use std::path::PathBuf;
6
7use rustc_ast::ast::LitKind;
8use rustc_ast::{LitIntType, TraitObjectSyntax};
9use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10use rustc_data_structures::unord::UnordSet;
11use rustc_errors::codes::*;
12use rustc_errors::{
13    Applicability, Diag, ErrorGuaranteed, Level, MultiSpan, StashKey, StringPart, Suggestions, msg,
14    pluralize, struct_span_code_err,
15};
16use rustc_hir::attrs::diagnostic::CustomDiagnostic;
17use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
18use rustc_hir::intravisit::Visitor;
19use rustc_hir::{self as hir, LangItem, Node, expr_needs_parens, find_attr};
20use rustc_infer::infer::{InferOk, TypeTrace};
21use rustc_infer::traits::ImplSource;
22use rustc_infer::traits::solve::Goal;
23use rustc_middle::traits::SignatureMismatchData;
24use rustc_middle::traits::select::OverflowError;
25use rustc_middle::ty::abstract_const::NotConstEvaluatable;
26use rustc_middle::ty::error::{ExpectedFound, TypeError};
27use rustc_middle::ty::print::{
28    PrintPolyTraitPredicateExt, PrintPolyTraitRefExt as _, PrintTraitPredicateExt as _,
29    PrintTraitRefExt as _, with_forced_trimmed_paths,
30};
31use rustc_middle::ty::{
32    self, GenericArgKind, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeFoldable, TypeFolder,
33    TypeSuperFoldable, TypeVisitableExt, Unnormalized, Upcast,
34};
35use rustc_middle::{bug, span_bug};
36use rustc_span::def_id::CrateNum;
37use rustc_span::{BytePos, DUMMY_SP, STDLIB_STABLE_CRATES, Span, Symbol, sym};
38use tracing::{debug, instrument};
39
40use super::suggestions::get_explanation_based_on_obligation;
41use super::{ArgKind, CandidateSimilarity, GetSafeTransmuteErrorAndReason, ImplCandidate};
42use crate::diagnostics::{
43    ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch, CoroClosureNotFn,
44};
45use crate::error_reporting::TypeErrCtxt;
46use crate::error_reporting::infer::TyCategory;
47use crate::error_reporting::traits::report_dyn_incompatibility;
48use crate::infer::{self, InferCtxt, InferCtxtExt as _};
49use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
50use crate::traits::{
51    MismatchedProjectionTypes, NormalizeExt, Obligation, ObligationCause, ObligationCauseCode,
52    ObligationCtxt, PredicateObligation, SelectionContext, SelectionError, elaborate,
53    specialization_graph,
54};
55
56impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
57    /// The `root_obligation` parameter should be the `root_obligation` field
58    /// from a `FulfillmentError`. If no `FulfillmentError` is available,
59    /// then it should be the same as `obligation`.
60    pub fn report_selection_error(
61        &self,
62        mut obligation: PredicateObligation<'tcx>,
63        root_obligation: &PredicateObligation<'tcx>,
64        error: &SelectionError<'tcx>,
65    ) -> ErrorGuaranteed {
66        let tcx = self.tcx;
67        let mut span = obligation.cause.span;
68        let mut long_ty_file = None;
69
70        let mut err = match *error {
71            SelectionError::Unimplemented => {
72                // If this obligation was generated as a result of well-formedness checking, see if we
73                // can get a better error message by performing HIR-based well-formedness checking.
74                if let ObligationCauseCode::WellFormed(Some(wf_loc)) =
75                    root_obligation.cause.code().peel_derives()
76                    && !obligation.predicate.has_non_region_infer()
77                {
78                    if let Some(cause) = self.tcx.diagnostic_hir_wf_check((
79                        tcx.erase_and_anonymize_regions(obligation.predicate),
80                        *wf_loc,
81                    )) {
82                        obligation.cause = cause.clone();
83                        span = obligation.cause.span;
84                    }
85                }
86
87                if let ObligationCauseCode::CompareImplItem {
88                    impl_item_def_id,
89                    trait_item_def_id,
90                    kind: _,
91                } = *obligation.cause.code()
92                {
93                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs:93",
                        "rustc_trait_selection::error_reporting::traits::fulfillment_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(93u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::fulfillment_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ObligationCauseCode::CompareImplItemObligation")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("ObligationCauseCode::CompareImplItemObligation");
94                    return self
95                        .report_extra_impl_obligation(
96                            span,
97                            impl_item_def_id,
98                            trait_item_def_id,
99                            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", obligation.predicate))
    })format!("`{}`", obligation.predicate),
100                        )
101                        .emit();
102                }
103
104                // Report a const-param specific error
105                if let ObligationCauseCode::ConstParam(ty) = *obligation.cause.code().peel_derives()
106                {
107                    return self.report_const_param_not_wf(ty, &obligation).emit();
108                }
109
110                let bound_predicate = obligation.predicate.kind();
111                match bound_predicate.skip_binder() {
112                    ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_predicate)) => {
113                        let leaf_trait_predicate =
114                            self.resolve_vars_if_possible(bound_predicate.rebind(trait_predicate));
115
116                        // Let's use the root obligation as the main message, when we care about the
117                        // most general case ("X doesn't implement Pattern<'_>") over the case that
118                        // happened to fail ("char doesn't implement Fn(&mut char)").
119                        //
120                        // We rely on a few heuristics to identify cases where this root
121                        // obligation is more important than the leaf obligation:
122                        let (main_trait_predicate, main_obligation) =
123                            if let ty::PredicateKind::Clause(
124                            ty::ClauseKind::Trait(root_pred)
125                        ) = root_obligation.predicate.kind().skip_binder()
126                            && !leaf_trait_predicate.self_ty().skip_binder().has_escaping_bound_vars()
127                            && !root_pred.self_ty().has_escaping_bound_vars()
128                            // The type of the leaf predicate is (roughly) the same as the type
129                            // from the root predicate, as a proxy for "we care about the root"
130                            // FIXME: this doesn't account for trivial derefs, but works as a first
131                            // approximation.
132                            && (
133                                // `T: Trait` && `&&T: OtherTrait`, we want `OtherTrait`
134                                self.can_eq(
135                                    obligation.param_env,
136                                    leaf_trait_predicate.self_ty().skip_binder(),
137                                    root_pred.self_ty().peel_refs(),
138                                )
139                                // `&str: Iterator` && `&str: IntoIterator`, we want `IntoIterator`
140                                || self.can_eq(
141                                    obligation.param_env,
142                                    leaf_trait_predicate.self_ty().skip_binder(),
143                                    root_pred.self_ty(),
144                                )
145                            )
146                            // The leaf trait and the root trait are different, so as to avoid
147                            // talking about `&mut T: Trait` and instead remain talking about
148                            // `T: Trait` instead
149                            && leaf_trait_predicate.def_id() != root_pred.def_id()
150                            // The root trait is not `Unsize`, as to avoid talking about it in
151                            // `tests/ui/coercion/coerce-issue-49593-box-never.rs`.
152                            && !self.tcx.is_lang_item(root_pred.def_id(), LangItem::Unsize)
153                            {
154                                (
155                                    self.resolve_vars_if_possible(
156                                        root_obligation.predicate.kind().rebind(root_pred),
157                                    ),
158                                    root_obligation,
159                                )
160                            } else {
161                                (leaf_trait_predicate, &obligation)
162                            };
163
164                        if let Some(guar) = self
165                            .emit_specialized_closure_kind_error(&obligation, leaf_trait_predicate)
166                        {
167                            return guar;
168                        }
169
170                        if let Err(guar) = leaf_trait_predicate.error_reported() {
171                            return guar;
172                        }
173                        // Silence redundant errors on binding access that are already
174                        // reported on the binding definition (#56607).
175                        if let Err(guar) = self.fn_arg_obligation(&obligation) {
176                            return guar;
177                        }
178                        let (post_message, pre_message, type_def) = self
179                            .get_parent_trait_ref(obligation.cause.code())
180                            .map(|(t, s)| {
181                                let t = self.tcx.short_string(t, &mut long_ty_file);
182                                (
183                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" in `{0}`", t))
    })format!(" in `{t}`"),
184                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("within `{0}`, ", t))
    })format!("within `{t}`, "),
185                                    s.map(|s| (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("within this `{0}`", t))
    })format!("within this `{t}`"), s)),
186                                )
187                            })
188                            .unwrap_or_default();
189
190                        let CustomDiagnostic { message, label, notes, parent_label } = self
191                            .on_unimplemented_note(
192                                main_trait_predicate,
193                                main_obligation,
194                                &mut long_ty_file,
195                            );
196
197                        let have_alt_message = message.is_some() || label.is_some();
198
199                        let message = message.unwrap_or_else(|| {
200                            self.get_standard_error_message(
201                                main_trait_predicate,
202                                None,
203                                post_message,
204                                &mut long_ty_file,
205                            )
206                        });
207                        let is_try_conversion =
208                            self.is_try_conversion(span, main_trait_predicate.def_id());
209                        let is_question_mark = #[allow(non_exhaustive_omitted_patterns)] match root_obligation.cause.code().peel_derives()
    {
    ObligationCauseCode::QuestionMark => true,
    _ => false,
}matches!(
210                            root_obligation.cause.code().peel_derives(),
211                            ObligationCauseCode::QuestionMark,
212                        ) && !(self
213                            .tcx
214                            .is_diagnostic_item(sym::FromResidual, main_trait_predicate.def_id())
215                            || self.tcx.is_lang_item(main_trait_predicate.def_id(), LangItem::Try));
216                        let is_unsize =
217                            self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Unsize);
218                        let question_mark_message = "the question mark operation (`?`) implicitly \
219                                                     performs a conversion on the error value \
220                                                     using the `From` trait";
221                        let (message, notes) = if is_try_conversion {
222                            let ty = self.tcx.short_string(
223                                main_trait_predicate.skip_binder().self_ty(),
224                                &mut long_ty_file,
225                            );
226                            // We have a `-> Result<_, E1>` and `gives_E2()?`.
227                            (
228                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`?` couldn\'t convert the error to `{0}`",
                ty))
    })format!("`?` couldn't convert the error to `{ty}`"),
229                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [question_mark_message.to_owned()]))vec![question_mark_message.to_owned()],
230                            )
231                        } else if is_question_mark {
232                            let main_trait_predicate =
233                                self.tcx.short_string(main_trait_predicate, &mut long_ty_file);
234                            // Similar to the case above, but in this case the conversion is for a
235                            // trait object: `-> Result<_, Box<dyn Error>` and `gives_E()?` when
236                            // `E: Error` isn't met.
237                            (
238                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`?` couldn\'t convert the error: `{0}` is not satisfied",
                main_trait_predicate))
    })format!(
239                                    "`?` couldn't convert the error: `{main_trait_predicate}` is \
240                                     not satisfied",
241                                ),
242                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [question_mark_message.to_owned()]))vec![question_mark_message.to_owned()],
243                            )
244                        } else {
245                            (message, notes)
246                        };
247
248                        let (err_msg, safe_transmute_explanation) = if self
249                            .tcx
250                            .is_lang_item(main_trait_predicate.def_id(), LangItem::TransmuteTrait)
251                        {
252                            // Recompute the safe transmute reason and use that for the error reporting
253                            let (report_obligation, report_pred) = self
254                                .select_transmute_obligation_for_reporting(
255                                    &obligation,
256                                    main_trait_predicate,
257                                    root_obligation,
258                                );
259
260                            match self.get_safe_transmute_error_and_reason(
261                                report_obligation,
262                                report_pred,
263                                span,
264                            ) {
265                                GetSafeTransmuteErrorAndReason::Silent => {
266                                    return self
267                                        .dcx()
268                                        .span_delayed_bug(span, "silent safe transmute error");
269                                }
270                                GetSafeTransmuteErrorAndReason::Default => (message, None),
271                                GetSafeTransmuteErrorAndReason::Error {
272                                    err_msg,
273                                    safe_transmute_explanation,
274                                } => (err_msg, safe_transmute_explanation),
275                            }
276                        } else {
277                            (message, None)
278                        };
279
280                        let mut err = {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0}", err_msg))
                })).with_code(E0277)
}struct_span_code_err!(self.dcx(), span, E0277, "{}", err_msg);
281
282                        let trait_def_id = main_trait_predicate.def_id();
283                        let leaf_trait_def_id = leaf_trait_predicate.def_id();
284                        if (self.tcx.is_diagnostic_item(sym::From, trait_def_id)
285                            || self.tcx.is_diagnostic_item(sym::TryFrom, trait_def_id))
286                            && (self.tcx.is_diagnostic_item(sym::From, leaf_trait_def_id)
287                                || self.tcx.is_diagnostic_item(sym::TryFrom, leaf_trait_def_id))
288                            && let Some(trait_ref) =
289                                leaf_trait_predicate.no_bound_vars().map(|pred| pred.trait_ref)
290                            && let Some(found_ty) =
291                                trait_ref.args.get(1).and_then(|arg| arg.as_type())
292                            && let Some(ty) =
293                                main_trait_predicate.no_bound_vars().map(|pred| pred.self_ty())
294                            && let Some(cast_ty) =
295                                self.find_explicit_cast_type(obligation.param_env, found_ty, ty)
296                        {
297                            let found_ty_str = self.tcx.short_string(found_ty, &mut long_ty_file);
298                            let cast_ty_str = self.tcx.short_string(cast_ty, &mut long_ty_file);
299
300                            err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider casting the `{0}` value to `{1}`",
                found_ty_str, cast_ty_str))
    })format!(
301                                "consider casting the `{found_ty_str}` value to `{cast_ty_str}`",
302                            ));
303                        }
304
305                        *err.long_ty_path() = long_ty_file;
306
307                        let mut suggested = false;
308                        let mut noted_missing_impl = false;
309                        if is_try_conversion || is_question_mark {
310                            (suggested, noted_missing_impl) = self.try_conversion_context(
311                                &obligation,
312                                main_trait_predicate,
313                                &mut err,
314                            );
315                        }
316
317                        suggested |= self.detect_negative_literal(
318                            &obligation,
319                            main_trait_predicate,
320                            &mut err,
321                        );
322
323                        if let Some(ret_span) = self.return_type_span(&obligation) {
324                            if is_try_conversion {
325                                let ty = self.tcx.short_string(
326                                    main_trait_predicate.skip_binder().self_ty(),
327                                    err.long_ty_path(),
328                                );
329                                err.span_label(
330                                    ret_span,
331                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}` because of this",
                ty))
    })format!("expected `{ty}` because of this"),
332                                );
333                            } else if is_question_mark {
334                                let main_trait_predicate =
335                                    self.tcx.short_string(main_trait_predicate, err.long_ty_path());
336                                err.span_label(
337                                    ret_span,
338                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required `{0}` because of this",
                main_trait_predicate))
    })format!("required `{main_trait_predicate}` because of this"),
339                                );
340                            }
341                        }
342
343                        if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Tuple) {
344                            self.add_tuple_trait_message(
345                                obligation.cause.code().peel_derives(),
346                                &mut err,
347                            );
348                        }
349
350                        let explanation = get_explanation_based_on_obligation(
351                            self.tcx,
352                            &obligation,
353                            leaf_trait_predicate,
354                            pre_message,
355                            err.long_ty_path(),
356                        );
357
358                        self.check_for_binding_assigned_block_without_tail_expression(
359                            &obligation,
360                            &mut err,
361                            leaf_trait_predicate,
362                        );
363                        self.suggest_add_result_as_return_type(
364                            &obligation,
365                            &mut err,
366                            leaf_trait_predicate,
367                        );
368
369                        if self.suggest_add_reference_to_arg(
370                            &obligation,
371                            &mut err,
372                            leaf_trait_predicate,
373                            have_alt_message,
374                        ) {
375                            self.note_obligation_cause(&mut err, &obligation);
376                            return err.emit();
377                        }
378
379                        let ty_span = match leaf_trait_predicate.self_ty().skip_binder().kind() {
380                            ty::Adt(def, _)
381                                if def.did().is_local()
382                                    && !self
383                                        .can_suggest_derive(&obligation, leaf_trait_predicate) =>
384                            {
385                                self.tcx.def_span(def.did())
386                            }
387                            _ => DUMMY_SP,
388                        };
389                        if let Some(s) = label {
390                            // If it has a custom `#[rustc_on_unimplemented]`
391                            // error message, let's display it as the label!
392                            err.span_label(span, s);
393                            if !#[allow(non_exhaustive_omitted_patterns)] match leaf_trait_predicate.skip_binder().self_ty().kind()
    {
    ty::Param(_) => true,
    _ => false,
}matches!(leaf_trait_predicate.skip_binder().self_ty().kind(), ty::Param(_))
394                                // When the self type is a type param We don't need to "the trait
395                                // `std::marker::Sized` is not implemented for `T`" as we will point
396                                // at the type param with a label to suggest constraining it.
397                                && !self.tcx.is_diagnostic_item(sym::FromResidual, leaf_trait_predicate.def_id())
398                            // Don't say "the trait `FromResidual<Option<Infallible>>` is
399                            // not implemented for `Result<T, E>`".
400                            {
401                                // We do this just so that the JSON output's `help` position is the
402                                // right one and not `file.rs:1:1`. The render is the same.
403                                if ty_span == DUMMY_SP {
404                                    err.help(explanation);
405                                } else {
406                                    err.span_help(ty_span, explanation);
407                                }
408                            }
409                        } else if let Some(custom_explanation) = safe_transmute_explanation {
410                            err.span_label(span, custom_explanation);
411                        } else if (explanation.len() > self.tcx.sess.diagnostic_width()
412                            || ty_span != DUMMY_SP)
413                            && !noted_missing_impl
414                        {
415                            // Really long types don't look good as span labels, instead move it
416                            // to a `help`.
417                            err.span_label(span, "unsatisfied trait bound");
418
419                            // We do this just so that the JSON output's `help` position is the
420                            // right one and not `file.rs:1:1`. The render is the same.
421                            if ty_span == DUMMY_SP {
422                                err.help(explanation);
423                            } else {
424                                err.span_help(ty_span, explanation);
425                            }
426                        } else {
427                            err.span_label(span, explanation);
428                        }
429
430                        if let ObligationCauseCode::Coercion { source, target } =
431                            *obligation.cause.code().peel_derives()
432                        {
433                            if self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Sized)
434                            {
435                                self.suggest_borrowing_for_object_cast(
436                                    &mut err,
437                                    root_obligation,
438                                    source,
439                                    target,
440                                );
441                            }
442                        }
443
444                        if let Some((msg, span)) = type_def {
445                            err.span_label(span, msg);
446                        }
447                        // `#[rustc_on_unimplemented]` notes for derivable traits (e.g. `Debug`'s
448                        // "add `#[derive(Debug)]` to `X` or manually `impl Debug for X`") duplicate
449                        // the `consider annotating X with #[derive(..)]` suggestion that
450                        // `suggest_derive` emits below, so skip them when that suggestion will be
451                        // shown. We keep the note otherwise (e.g. when a field isn't `Debug`, so
452                        // the derive can't be suggested) to avoid leaving the diagnostic without
453                        // actionable guidance.
454                        let derive_suggestion_will_be_shown = main_trait_predicate
455                            == leaf_trait_predicate
456                            && self.can_suggest_derive(&obligation, leaf_trait_predicate);
457                        if !derive_suggestion_will_be_shown {
458                            for note in notes {
459                                // If it has a custom `#[rustc_on_unimplemented]` note, let's display
460                                // it.
461                                err.note(note);
462                            }
463                        }
464                        if let Some(s) = parent_label {
465                            let body = obligation.cause.body_def_id;
466                            err.span_label(tcx.def_span(body), s);
467                        }
468
469                        self.suggest_floating_point_literal(
470                            &obligation,
471                            &mut err,
472                            leaf_trait_predicate,
473                        );
474                        self.suggest_dereferencing_index(
475                            &obligation,
476                            &mut err,
477                            leaf_trait_predicate,
478                        );
479                        suggested |=
480                            self.suggest_dereferences(&obligation, &mut err, leaf_trait_predicate);
481                        suggested |=
482                            self.suggest_fn_call(&obligation, &mut err, leaf_trait_predicate);
483                        suggested |= self.suggest_cast_to_fn_pointer(
484                            &obligation,
485                            &mut err,
486                            leaf_trait_predicate,
487                            main_trait_predicate,
488                            span,
489                        );
490                        suggested |= self.suggest_remove_reference(
491                            &obligation,
492                            &mut err,
493                            leaf_trait_predicate,
494                        );
495                        suggested |= self.suggest_semicolon_removal(
496                            &obligation,
497                            &mut err,
498                            span,
499                            leaf_trait_predicate,
500                        );
501                        self.note_different_trait_with_same_name(
502                            &mut err,
503                            &obligation,
504                            leaf_trait_predicate,
505                        );
506                        self.note_adt_version_mismatch(&mut err, leaf_trait_predicate);
507                        self.suggest_remove_await(&obligation, &mut err);
508                        self.suggest_derive(&obligation, &mut err, leaf_trait_predicate);
509
510                        if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Try) {
511                            self.suggest_await_before_try(
512                                &mut err,
513                                &obligation,
514                                leaf_trait_predicate,
515                                span,
516                            );
517                        }
518
519                        if self.suggest_add_clone_to_arg(
520                            &obligation,
521                            &mut err,
522                            leaf_trait_predicate,
523                        ) {
524                            return err.emit();
525                        }
526
527                        if self.suggest_impl_trait(&mut err, &obligation, leaf_trait_predicate) {
528                            return err.emit();
529                        }
530
531                        if is_unsize {
532                            // If the obligation failed due to a missing implementation of the
533                            // `Unsize` trait, give a pointer to why that might be the case
534                            err.note(
535                                "all implementations of `Unsize` are provided \
536                                automatically by the compiler, see \
537                                <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
538                                for more information",
539                            );
540                        }
541
542                        let is_fn_trait = tcx.is_fn_trait(leaf_trait_predicate.def_id());
543                        let is_target_feature_fn = if let ty::FnDef(def_id, _) =
544                            *leaf_trait_predicate.skip_binder().self_ty().kind()
545                        {
546                            !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
547                        } else {
548                            false
549                        };
550                        if is_fn_trait && is_target_feature_fn {
551                            err.note(
552                                "`#[target_feature(..)]` functions do not implement the `Fn` traits",
553                            );
554                            err.note(
555                                "try casting the function to a `fn` pointer or wrapping it in a closure",
556                            );
557                        }
558
559                        self.note_field_shadowed_by_private_candidate_in_cause(
560                            &mut err,
561                            &obligation.cause,
562                            obligation.param_env,
563                        );
564                        self.try_to_add_help_message(
565                            &root_obligation,
566                            &obligation,
567                            leaf_trait_predicate,
568                            &mut err,
569                            span,
570                            is_fn_trait,
571                            suggested,
572                        );
573
574                        // Changing mutability doesn't make a difference to whether we have
575                        // an `Unsize` impl (Fixes ICE in #71036)
576                        if !is_unsize {
577                            self.suggest_change_mut(&obligation, &mut err, leaf_trait_predicate);
578                        }
579
580                        // If this error is due to `!: Trait` not implemented but `(): Trait` is
581                        // implemented, and fallback has occurred, then it could be due to a
582                        // variable that used to fallback to `()` now falling back to `!`. Issue a
583                        // note informing about the change in behaviour.
584                        if leaf_trait_predicate.skip_binder().self_ty().is_never()
585                            && self.diverging_fallback_has_occurred
586                        {
587                            let predicate = leaf_trait_predicate.map_bound(|trait_pred| {
588                                trait_pred.with_replaced_self_ty(self.tcx, tcx.types.unit)
589                            });
590                            let unit_obligation = obligation.with(tcx, predicate);
591                            if self.predicate_may_hold(&unit_obligation) {
592                                err.note(
593                                    "this error might have been caused by changes to \
594                                    Rust's type-inference algorithm (see issue #148922 \
595                                    <https://github.com/rust-lang/rust/issues/148922> \
596                                    for more information)",
597                                );
598                                err.help(
599                                    "you might have intended to use the type `()` here instead",
600                                );
601                            }
602                        }
603
604                        self.explain_hrtb_projection(
605                            &mut err,
606                            leaf_trait_predicate,
607                            obligation.param_env,
608                            &obligation.cause,
609                        );
610                        self.suggest_desugaring_async_fn_in_trait(&mut err, main_trait_predicate);
611
612                        // Return early if the trait is Debug or Display and the invocation
613                        // originates within a standard library macro, because the output
614                        // is otherwise overwhelming and unhelpful (see #85844 for an
615                        // example).
616
617                        let in_std_macro =
618                            match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
619                                Some(macro_def_id) => {
620                                    let crate_name = tcx.crate_name(macro_def_id.krate);
621                                    STDLIB_STABLE_CRATES.contains(&crate_name)
622                                }
623                                None => false,
624                            };
625
626                        if in_std_macro
627                            && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.get_diagnostic_name(leaf_trait_predicate.def_id())
    {
    Some(sym::Debug | sym::Display) => true,
    _ => false,
}matches!(
628                                self.tcx.get_diagnostic_name(leaf_trait_predicate.def_id()),
629                                Some(sym::Debug | sym::Display)
630                            )
631                        {
632                            return err.emit();
633                        }
634
635                        err
636                    }
637
638                    ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => self
639                        .report_host_effect_error(
640                            bound_predicate.rebind(predicate),
641                            &obligation,
642                            span,
643                        ),
644
645                    ty::PredicateKind::Subtype(predicate) => {
646                        // Errors for Subtype predicates show up as
647                        // `FulfillmentErrorCode::SubtypeError`,
648                        // not selection error.
649                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("subtype requirement gave wrong error: `{0:?}`", predicate))span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
650                    }
651
652                    ty::PredicateKind::Coerce(predicate) => {
653                        // Errors for Coerce predicates show up as
654                        // `FulfillmentErrorCode::SubtypeError`,
655                        // not selection error.
656                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("coerce requirement gave wrong error: `{0:?}`", predicate))span_bug!(span, "coerce requirement gave wrong error: `{:?}`", predicate)
657                    }
658
659                    ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(..))
660                    | ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(..)) => {
661                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("outlives clauses should not error outside borrowck. obligation: `{0:?}`",
        obligation))span_bug!(
662                            span,
663                            "outlives clauses should not error outside borrowck. obligation: `{:?}`",
664                            obligation
665                        )
666                    }
667
668                    ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) => {
669                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("projection clauses should be implied from elsewhere. obligation: `{0:?}`",
        obligation))span_bug!(
670                            span,
671                            "projection clauses should be implied from elsewhere. obligation: `{:?}`",
672                            obligation
673                        )
674                    }
675
676                    ty::PredicateKind::DynCompatible(trait_def_id) => {
677                        let violations = self.tcx.dyn_compatibility_violations(trait_def_id);
678                        let mut err = report_dyn_incompatibility(
679                            self.tcx,
680                            span,
681                            None,
682                            trait_def_id,
683                            violations,
684                        );
685                        if let hir::Node::Item(item) =
686                            self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
687                            && let hir::ItemKind::Impl(impl_) = item.kind
688                            && let None = impl_.of_trait
689                            && let hir::TyKind::TraitObject(_, tagged_ptr) = impl_.self_ty.kind
690                            && let TraitObjectSyntax::None = tagged_ptr.tag()
691                            && impl_.self_ty.span.edition().at_least_rust_2021()
692                        {
693                            // Silence the dyn-compatibility error in favor of the missing dyn on
694                            // self type error. #131051.
695                            err.downgrade_to_delayed_bug();
696                        }
697                        err
698                    }
699
700                    ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(ty)) => {
701                        let ty = self.resolve_vars_if_possible(ty);
702                        if self.next_trait_solver() {
703                            if let Err(guar) = ty.error_reported() {
704                                return guar;
705                            }
706
707                            // FIXME: we'll need a better message which takes into account
708                            // which bounds actually failed to hold.
709                            self.dcx().struct_span_err(
710                                span,
711                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the type `{0}` is not well-formed",
                ty))
    })format!("the type `{ty}` is not well-formed"),
712                            )
713                        } else {
714                            // WF predicates cannot themselves make
715                            // errors. They can only block due to
716                            // ambiguity; otherwise, they always
717                            // degenerate into other obligations
718                            // (which may fail).
719                            ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("WF predicate not satisfied for {0:?}", ty));span_bug!(span, "WF predicate not satisfied for {:?}", ty);
720                        }
721                    }
722
723                    // Errors for `ConstEvaluatable`, `ConstEquate` predicates show up as
724                    // `SelectionError::ConstEvalFailure`, not `Unimplemented`.
725                    // Ambiguous predicates should never error.
726                    // We never return `Err` when proving `UnstableFeature` goal.
727                    ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
728                    | ty::PredicateKind::ConstEquate { .. }
729                    | ty::PredicateKind::Ambiguous
730                    | ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature { .. })
731                    | ty::PredicateKind::NormalizesTo { .. }
732                    | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType { .. }) => {
733                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("Unexpected `Predicate` for `SelectionError`: `{0:?}`",
        obligation))span_bug!(
734                            span,
735                            "Unexpected `Predicate` for `SelectionError`: `{:?}`",
736                            obligation
737                        )
738                    }
739                }
740            }
741
742            SelectionError::SignatureMismatch(SignatureMismatchData {
743                found_trait_ref,
744                expected_trait_ref,
745                terr: terr @ TypeError::CyclicTy(_),
746            }) => self.report_cyclic_signature_error(
747                &obligation,
748                found_trait_ref,
749                expected_trait_ref,
750                terr,
751            ),
752            SelectionError::SignatureMismatch(SignatureMismatchData {
753                found_trait_ref,
754                expected_trait_ref,
755                terr: _,
756            }) => {
757                match self.report_signature_mismatch_error(
758                    &obligation,
759                    span,
760                    found_trait_ref,
761                    expected_trait_ref,
762                ) {
763                    Ok(err) => err,
764                    Err(guar) => return guar,
765                }
766            }
767
768            SelectionError::TraitDynIncompatible(did) => {
769                let violations = self.tcx.dyn_compatibility_violations(did);
770                report_dyn_incompatibility(self.tcx, span, None, did, violations)
771            }
772
773            SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsInfer) => {
774                ::rustc_middle::util::bug::bug_fmt(format_args!("MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"))bug!(
775                    "MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"
776                )
777            }
778            SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsParam) => {
779                match self.report_not_const_evaluatable_error(&obligation, span) {
780                    Ok(err) => err,
781                    Err(guar) => return guar,
782                }
783            }
784
785            // Already reported in the query.
786            SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(guar))
787            | SelectionError::Overflow(OverflowError::Error(guar)) => {
788                self.set_tainted_by_errors(guar);
789                return guar;
790            }
791
792            SelectionError::Overflow(_) => {
793                ::rustc_middle::util::bug::bug_fmt(format_args!("overflow should be handled before the `report_selection_error` path"));bug!("overflow should be handled before the `report_selection_error` path");
794            }
795
796            SelectionError::ConstArgHasWrongType { ct, ct_ty, expected_ty } => {
797                let expected_ty_str = self.tcx.short_string(expected_ty, &mut long_ty_file);
798                let ct_str = self.tcx.short_string(ct, &mut long_ty_file);
799                let mut diag = self.dcx().struct_span_err(
800                    span,
801                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the constant `{0}` is not of type `{1}`",
                ct_str, expected_ty_str))
    })format!("the constant `{ct_str}` is not of type `{expected_ty_str}`"),
802                );
803                diag.long_ty_path = long_ty_file;
804
805                self.note_type_err(
806                    &mut diag,
807                    &obligation.cause,
808                    None,
809                    None,
810                    TypeError::Sorts(ty::error::ExpectedFound::new(expected_ty, ct_ty)),
811                    false,
812                    None,
813                );
814                diag
815            }
816        };
817
818        self.note_obligation_cause(&mut err, &obligation);
819        err.emit()
820    }
821}
822
823impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
824    pub(super) fn apply_do_not_recommend(
825        &self,
826        obligation: &mut PredicateObligation<'tcx>,
827        root_obligation: &PredicateObligation<'tcx>,
828    ) -> bool {
829        let mut base_cause = obligation.cause.code().clone();
830        let mut applied_do_not_recommend = false;
831        loop {
832            if let ObligationCauseCode::ImplDerived(ref c) = base_cause {
833                if self.tcx.do_not_recommend_impl(c.impl_or_alias_def_id) {
834                    let code = (*c.derived.parent_code).clone();
835                    // Keep more precise spans that still point within the parent obligation,
836                    // but do not let hidden impl details move the span outside of it.
837                    if code == *root_obligation.cause.code()
838                        && root_obligation.cause.span.eq_ctxt(obligation.cause.span)
839                        && !root_obligation.cause.span.contains(obligation.cause.span)
840                    {
841                        obligation.cause.span = root_obligation.cause.span;
842                    }
843                    obligation.cause.map_code(|_| code);
844                    obligation.predicate = c.derived.parent_trait_pred.upcast(self.tcx);
845                    applied_do_not_recommend = true;
846                }
847            }
848            if let Some(parent_cause) = base_cause.parent() {
849                base_cause = parent_cause.clone();
850            } else {
851                break;
852            }
853        }
854
855        applied_do_not_recommend
856    }
857
858    fn report_host_effect_error(
859        &self,
860        predicate: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
861        main_obligation: &PredicateObligation<'tcx>,
862        span: Span,
863    ) -> Diag<'a> {
864        // FIXME(const_trait_impl): We should recompute the predicate with `[const]`
865        // if it's `const`, and if it holds, explain that this bound only
866        // *conditionally* holds.
867        let trait_ref = predicate.map_bound(|predicate| ty::TraitPredicate {
868            trait_ref: predicate.trait_ref,
869            polarity: ty::PredicatePolarity::Positive,
870        });
871        let mut file = None;
872
873        let err_msg = self.get_standard_error_message(
874            trait_ref,
875            Some(predicate.constness()),
876            String::new(),
877            &mut file,
878        );
879        let mut diag = {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0}", err_msg))
                })).with_code(E0277)
}struct_span_code_err!(self.dcx(), span, E0277, "{}", err_msg);
880        *diag.long_ty_path() = file;
881        let obligation = Obligation::new(
882            self.tcx,
883            ObligationCause::dummy(),
884            main_obligation.param_env,
885            trait_ref,
886        );
887        if !self.predicate_may_hold(&obligation) {
888            diag.downgrade_to_delayed_bug();
889        }
890
891        if let Ok(Some(ImplSource::UserDefined(impl_data))) =
892            self.enter_forall(trait_ref, |trait_ref_for_select| {
893                SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref_for_select))
894            })
895        {
896            let impl_did = impl_data.impl_def_id;
897            let trait_did = trait_ref.def_id();
898            let impl_span = self.tcx.def_span(impl_did);
899            let trait_name = self.tcx.item_name(trait_did);
900
901            if self.tcx.is_const_trait(trait_did) && !self.tcx.is_const_trait_impl(impl_did) {
902                if !impl_did.is_local() {
903                    diag.span_note(
904                        impl_span,
905                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("trait `{0}` is implemented but not `const`",
                trait_name))
    })format!("trait `{trait_name}` is implemented but not `const`"),
906                    );
907                }
908
909                if let Some(command) =
910                    {
    {
        'done:
            {
            for i in
                ::rustc_hir::attrs::HasAttrs::get_attrs(impl_did, &self.tcx) {
                #[allow(unused_imports)]
                use ::rustc_hir::attrs::AttributeKind::*;
                let i: &::rustc_hir::Attribute = i;
                match i {
                    ::rustc_hir::Attribute::Parsed(OnConst { directive, .. }) =>
                        {
                        break 'done Some(directive.as_deref());
                    }
                    ::rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(self.tcx, impl_did, OnConst {directive, ..} => directive.as_deref())
911                        .flatten()
912                {
913                    let (_, mut format_args) = self.on_unimplemented_components(
914                        trait_ref,
915                        main_obligation,
916                        diag.long_ty_path(),
917                        false,
918                    );
919                    if let ty::Adt(def, args) = trait_ref.self_ty().skip_binder().kind() {
920                        for param in self.tcx.generics_of(def.did()).own_params.iter() {
921                            match param.kind {
922                                GenericParamDefKind::Type { .. }
923                                | GenericParamDefKind::Const { .. } => {
924                                    format_args
925                                        .generic_args
926                                        .push((param.name, args[param.index as usize].to_string()));
927                                }
928                                _ => continue,
929                            }
930                        }
931                    }
932                    let CustomDiagnostic { message, label, notes, parent_label: _ } =
933                        command.eval(None, &format_args);
934
935                    if let Some(message) = message {
936                        diag.primary_message(message);
937                    }
938                    if let Some(label) = label {
939                        diag.span_label(span, label);
940                    }
941                    for note in notes {
942                        diag.note(note);
943                    }
944                } else if let Some(impl_did) = impl_did.as_local()
945                    && let item = self.tcx.hir_expect_item(impl_did)
946                    && let hir::ItemKind::Impl(impl_) = item.kind
947                    && impl_.of_trait.is_some()
948                {
949                    // trait is const, impl is local and not const
950                    diag.span_suggestion_verbose(
951                        item.span.shrink_to_lo(),
952                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("make the `impl` of trait `{0}` `const`",
                trait_name))
    })format!("make the `impl` of trait `{trait_name}` `const`"),
953                        "const ".to_string(),
954                        Applicability::MaybeIncorrect,
955                    );
956                }
957            }
958        } else if let ty::Param(param) = trait_ref.self_ty().skip_binder().kind()
959            && let Some(generics) =
960                self.tcx.hir_node_by_def_id(main_obligation.cause.body_def_id).generics()
961        {
962            let constraint = {
    let _guard = NoTrimmedGuard::new();
    ::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("[const] {0}",
                    trait_ref.map_bound(|tr|
                                tr.trait_ref).print_trait_sugared()))
        })
}ty::print::with_no_trimmed_paths!(format!(
963                "[const] {}",
964                trait_ref.map_bound(|tr| tr.trait_ref).print_trait_sugared(),
965            ));
966            ty::suggest_constraining_type_param(
967                self.tcx,
968                generics,
969                &mut diag,
970                param.name.as_str(),
971                &constraint,
972                Some(trait_ref.def_id()),
973                None,
974            );
975        }
976        diag
977    }
978
979    fn emit_specialized_closure_kind_error(
980        &self,
981        obligation: &PredicateObligation<'tcx>,
982        mut trait_pred: ty::PolyTraitPredicate<'tcx>,
983    ) -> Option<ErrorGuaranteed> {
984        // If we end up on an `AsyncFnKindHelper` goal, try to unwrap the parent
985        // `AsyncFn*` goal.
986        if self.tcx.is_lang_item(trait_pred.def_id(), LangItem::AsyncFnKindHelper) {
987            let mut code = obligation.cause.code();
988            // Unwrap a `FunctionArg` cause, which has been refined from a derived obligation.
989            if let ObligationCauseCode::FunctionArg { parent_code, .. } = code {
990                code = &**parent_code;
991            }
992            // If we have a derived obligation, then the parent will be a `AsyncFn*` goal.
993            if let Some((_, Some(parent))) = code.parent_with_predicate() {
994                trait_pred = parent;
995            }
996        }
997
998        let self_ty = trait_pred.self_ty().skip_binder();
999
1000        let (expected_kind, trait_prefix) =
1001            if let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) {
1002                (expected_kind, "")
1003            } else if let Some(expected_kind) =
1004                self.tcx.async_fn_trait_kind_from_def_id(trait_pred.def_id())
1005            {
1006                (expected_kind, "Async")
1007            } else {
1008                return None;
1009            };
1010
1011        let (closure_def_id, found_args, has_self_borrows) = match *self_ty.kind() {
1012            ty::Closure(def_id, args) => {
1013                (def_id, args.as_closure().sig().map_bound(|sig| sig.inputs()[0]), false)
1014            }
1015            ty::CoroutineClosure(def_id, args) => (
1016                def_id,
1017                args.as_coroutine_closure()
1018                    .coroutine_closure_sig()
1019                    .map_bound(|sig| sig.tupled_inputs_ty),
1020                !args.as_coroutine_closure().tupled_upvars_ty().is_ty_var()
1021                    && args.as_coroutine_closure().has_self_borrows(),
1022            ),
1023            _ => return None,
1024        };
1025
1026        let expected_args = trait_pred.map_bound(|trait_pred| trait_pred.trait_ref.args.type_at(1));
1027
1028        // Verify that the arguments are compatible. If the signature is
1029        // mismatched, then we have a totally different error to report.
1030        if self.enter_forall(found_args, |found_args| {
1031            self.enter_forall(expected_args, |expected_args| {
1032                !self.can_eq(obligation.param_env, expected_args, found_args)
1033            })
1034        }) {
1035            return None;
1036        }
1037
1038        if let Some(found_kind) = self.closure_kind(self_ty)
1039            && !found_kind.extends(expected_kind)
1040        {
1041            let mut err = self.report_closure_error(
1042                &obligation,
1043                closure_def_id,
1044                found_kind,
1045                expected_kind,
1046                trait_prefix,
1047            );
1048            self.note_obligation_cause(&mut err, &obligation);
1049            return Some(err.emit());
1050        }
1051
1052        // If the closure has captures, then perhaps the reason that the trait
1053        // is unimplemented is because async closures don't implement `Fn`/`FnMut`
1054        // if they have captures.
1055        if has_self_borrows && expected_kind != ty::ClosureKind::FnOnce {
1056            let coro_kind = match self
1057                .tcx
1058                .coroutine_kind(self.tcx.coroutine_for_closure(closure_def_id))
1059                .unwrap()
1060            {
1061                rustc_hir::CoroutineKind::Desugared(desugaring, _) => desugaring.to_string(),
1062                coro => coro.to_string(),
1063            };
1064            let mut err = self.dcx().create_err(CoroClosureNotFn {
1065                span: self.tcx.def_span(closure_def_id),
1066                kind: expected_kind.as_str(),
1067                coro_kind,
1068            });
1069            self.note_obligation_cause(&mut err, &obligation);
1070            return Some(err.emit());
1071        }
1072
1073        None
1074    }
1075
1076    fn fn_arg_obligation(
1077        &self,
1078        obligation: &PredicateObligation<'tcx>,
1079    ) -> Result<(), ErrorGuaranteed> {
1080        if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1081            && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
1082            && let arg = arg.peel_borrows()
1083            && let hir::ExprKind::Path(hir::QPath::Resolved(
1084                None,
1085                hir::Path { res: hir::def::Res::Local(hir_id), .. },
1086            )) = arg.kind
1087            && let Node::Pat(pat) = self.tcx.hir_node(*hir_id)
1088            && let Some((preds, guar)) = self.reported_trait_errors.borrow().get(&pat.span)
1089            && preds.contains(&obligation.as_goal())
1090        {
1091            return Err(*guar);
1092        }
1093        Ok(())
1094    }
1095
1096    fn detect_negative_literal(
1097        &self,
1098        obligation: &PredicateObligation<'tcx>,
1099        trait_pred: ty::PolyTraitPredicate<'tcx>,
1100        err: &mut Diag<'_>,
1101    ) -> bool {
1102        if let ObligationCauseCode::UnOp { hir_id, .. } = obligation.cause.code()
1103            && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1104            && let hir::ExprKind::Unary(hir::UnOp::Neg, inner) = expr.kind
1105            && let hir::ExprKind::Lit(lit) = inner.kind
1106            && let LitKind::Int(_, LitIntType::Unsuffixed) = lit.node
1107        {
1108            err.span_suggestion_verbose(
1109                lit.span.shrink_to_hi(),
1110                "consider specifying an integer type that can be negative",
1111                match trait_pred.skip_binder().self_ty().kind() {
1112                    ty::Uint(ty::UintTy::Usize) => "isize",
1113                    ty::Uint(ty::UintTy::U8) => "i8",
1114                    ty::Uint(ty::UintTy::U16) => "i16",
1115                    ty::Uint(ty::UintTy::U32) => "i32",
1116                    ty::Uint(ty::UintTy::U64) => "i64",
1117                    ty::Uint(ty::UintTy::U128) => "i128",
1118                    _ => "i64",
1119                }
1120                .to_string(),
1121                Applicability::MaybeIncorrect,
1122            );
1123            return true;
1124        }
1125        false
1126    }
1127
1128    /// When the `E` of the resulting `Result<T, E>` in an expression `foo().bar().baz()?`,
1129    /// identify those method chain sub-expressions that could or could not have been annotated
1130    /// with `?`.
1131    fn try_conversion_context(
1132        &self,
1133        obligation: &PredicateObligation<'tcx>,
1134        trait_pred: ty::PolyTraitPredicate<'tcx>,
1135        err: &mut Diag<'_>,
1136    ) -> (bool, bool) {
1137        let span = obligation.cause.span;
1138        /// Look for the (direct) sub-expr of `?`, and return it if it's a `.` method call.
1139        struct FindMethodSubexprOfTry {
1140            search_span: Span,
1141        }
1142        impl<'v> Visitor<'v> for FindMethodSubexprOfTry {
1143            type Result = ControlFlow<&'v hir::Expr<'v>>;
1144            fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
1145                if let hir::ExprKind::Match(expr, _arms, hir::MatchSource::TryDesugar(_)) = ex.kind
1146                    && ex.span.with_lo(ex.span.hi() - BytePos(1)).source_equal(self.search_span)
1147                    && let hir::ExprKind::Call(_, [expr, ..]) = expr.kind
1148                {
1149                    ControlFlow::Break(expr)
1150                } else {
1151                    hir::intravisit::walk_expr(self, ex)
1152                }
1153            }
1154        }
1155        let hir_id = self.tcx.local_def_id_to_hir_id(obligation.cause.body_def_id);
1156        let Some(body_id) = self.tcx.hir_node(hir_id).body_id() else { return (false, false) };
1157        let ControlFlow::Break(expr) =
1158            (FindMethodSubexprOfTry { search_span: span }).visit_body(self.tcx.hir_body(body_id))
1159        else {
1160            return (false, false);
1161        };
1162        let Some(typeck) = &self.typeck_results else {
1163            return (false, false);
1164        };
1165        let ObligationCauseCode::QuestionMark = obligation.cause.code().peel_derives() else {
1166            return (false, false);
1167        };
1168        let self_ty = trait_pred.skip_binder().self_ty();
1169        let found_ty = trait_pred.skip_binder().trait_ref.args.get(1).and_then(|a| a.as_type());
1170        let noted_missing_impl =
1171            self.note_missing_impl_for_question_mark(err, self_ty, found_ty, trait_pred);
1172
1173        let mut prev_ty = self.resolve_vars_if_possible(
1174            typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1175        );
1176
1177        // We always look at the `E` type, because that's the only one affected by `?`. If the
1178        // incorrect `Result<T, E>` is because of the `T`, we'll get an E0308 on the whole
1179        // expression, after the `?` has "unwrapped" the `T`.
1180        let get_e_type = |prev_ty: Ty<'tcx>| -> Option<Ty<'tcx>> {
1181            let ty::Adt(def, args) = prev_ty.kind() else {
1182                return None;
1183            };
1184            let Some(arg) = args.get(1) else {
1185                return None;
1186            };
1187            if !self.tcx.is_diagnostic_item(sym::Result, def.did()) {
1188                return None;
1189            }
1190            arg.as_type()
1191        };
1192
1193        let mut suggested = false;
1194        let mut chain = ::alloc::vec::Vec::new()vec![];
1195
1196        // The following logic is similar to `point_at_chain`, but that's focused on associated types
1197        let mut expr = expr;
1198        while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
1199            // Point at every method call in the chain with the `Result` type.
1200            // let foo = bar.iter().map(mapper)?;
1201            //               ------ -----------
1202            expr = rcvr_expr;
1203            chain.push((span, prev_ty));
1204
1205            let next_ty = self.resolve_vars_if_possible(
1206                typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1207            );
1208
1209            let is_diagnostic_item = |symbol: Symbol, ty: Ty<'tcx>| {
1210                let ty::Adt(def, _) = ty.kind() else {
1211                    return false;
1212                };
1213                self.tcx.is_diagnostic_item(symbol, def.did())
1214            };
1215            // For each method in the chain, see if this is `Result::map_err` or
1216            // `Option::ok_or_else` and if it is, see if the closure passed to it has an incorrect
1217            // trailing `;`.
1218            if let Some(ty) = get_e_type(prev_ty)
1219                && let Some(found_ty) = found_ty
1220                // Ideally we would instead use `FnCtxt::lookup_method_for_diagnostic` for 100%
1221                // accurate check, but we are in the wrong stage to do that and looking for
1222                // `Result::map_err` by checking the Self type and the path segment is enough.
1223                // sym::ok_or_else
1224                && (
1225                    ( // Result::map_err
1226                        path_segment.ident.name == sym::map_err
1227                            && is_diagnostic_item(sym::Result, next_ty)
1228                    ) || ( // Option::ok_or_else
1229                        path_segment.ident.name == sym::ok_or_else
1230                            && is_diagnostic_item(sym::Option, next_ty)
1231                    )
1232                )
1233                // Found `Result<_, ()>?`
1234                && let ty::Tuple(tys) = found_ty.kind()
1235                && tys.is_empty()
1236                // The current method call returns `Result<_, ()>`
1237                && self.can_eq(obligation.param_env, ty, found_ty)
1238                // There's a single argument in the method call and it is a closure
1239                && let [arg] = args
1240                && let hir::ExprKind::Closure(closure) = arg.kind
1241                // The closure has a block for its body with no tail expression
1242                && let body = self.tcx.hir_body(closure.body)
1243                && let hir::ExprKind::Block(block, _) = body.value.kind
1244                && let None = block.expr
1245                // The last statement is of a type that can be converted to the return error type
1246                && let [.., stmt] = block.stmts
1247                && let hir::StmtKind::Semi(expr) = stmt.kind
1248                && let expr_ty = self.resolve_vars_if_possible(
1249                    typeck.expr_ty_adjusted_opt(expr)
1250                        .unwrap_or(Ty::new_misc_error(self.tcx)),
1251                )
1252                && self
1253                    .infcx
1254                    .type_implements_trait(
1255                        self.tcx.get_diagnostic_item(sym::From).unwrap(),
1256                        [self_ty, expr_ty],
1257                        obligation.param_env,
1258                    )
1259                    .must_apply_modulo_regions()
1260            {
1261                suggested = true;
1262                err.span_suggestion_short(
1263                    stmt.span.with_lo(expr.span.hi()),
1264                    "remove this semicolon",
1265                    String::new(),
1266                    Applicability::MachineApplicable,
1267                );
1268            }
1269
1270            prev_ty = next_ty;
1271
1272            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1273                && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
1274                && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
1275            {
1276                let parent = self.tcx.parent_hir_node(binding.hir_id);
1277                // We've reached the root of the method call chain...
1278                if let hir::Node::LetStmt(local) = parent
1279                    && let Some(binding_expr) = local.init
1280                {
1281                    // ...and it is a binding. Get the binding creation and continue the chain.
1282                    expr = binding_expr;
1283                }
1284                if let hir::Node::Param(_param) = parent {
1285                    // ...and it is an fn argument.
1286                    break;
1287                }
1288            }
1289        }
1290        // `expr` is now the "root" expression of the method call chain, which can be any
1291        // expression kind, like a method call or a path. If this expression is `Result<T, E>` as
1292        // well, then we also point at it.
1293        prev_ty = self.resolve_vars_if_possible(
1294            typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1295        );
1296        chain.push((expr.span, prev_ty));
1297
1298        let mut prev = None;
1299        let mut iter = chain.into_iter().rev().peekable();
1300        while let Some((span, err_ty)) = iter.next() {
1301            let is_last = iter.peek().is_none();
1302            let err_ty = get_e_type(err_ty);
1303            let err_ty = match (err_ty, prev) {
1304                (Some(err_ty), Some(prev)) if !self.can_eq(obligation.param_env, err_ty, prev) => {
1305                    err_ty
1306                }
1307                (Some(err_ty), None) => err_ty,
1308                _ => {
1309                    prev = err_ty;
1310                    continue;
1311                }
1312            };
1313
1314            let implements_from = self
1315                .infcx
1316                .type_implements_trait(
1317                    self.tcx.get_diagnostic_item(sym::From).unwrap(),
1318                    [self_ty, err_ty],
1319                    obligation.param_env,
1320                )
1321                .must_apply_modulo_regions();
1322
1323            let err_ty_str = self.tcx.short_string(err_ty, err.long_ty_path());
1324            let label = if !implements_from && is_last {
1325                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this can\'t be annotated with `?` because it has type `Result<_, {0}>`",
                err_ty_str))
    })format!(
1326                    "this can't be annotated with `?` because it has type `Result<_, {err_ty_str}>`"
1327                )
1328            } else {
1329                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this has type `Result<_, {0}>`",
                err_ty_str))
    })format!("this has type `Result<_, {err_ty_str}>`")
1330            };
1331
1332            if !suggested || !implements_from {
1333                err.span_label(span, label);
1334            }
1335            prev = Some(err_ty);
1336        }
1337        (suggested, noted_missing_impl)
1338    }
1339
1340    fn note_missing_impl_for_question_mark(
1341        &self,
1342        err: &mut Diag<'_>,
1343        self_ty: Ty<'_>,
1344        found_ty: Option<Ty<'_>>,
1345        trait_pred: ty::PolyTraitPredicate<'tcx>,
1346    ) -> bool {
1347        match (self_ty.kind(), found_ty) {
1348            (ty::Adt(def, _), Some(ty))
1349                if let ty::Adt(found, _) = ty.kind()
1350                    && def.did().is_local()
1351                    && found.did().is_local() =>
1352            {
1353                err.span_note(
1354                    self.tcx.def_span(def.did()),
1355                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` needs to implement `From<{1}>`",
                self_ty, ty))
    })format!("`{self_ty}` needs to implement `From<{ty}>`"),
1356                );
1357            }
1358            (ty::Adt(def, _), None) if def.did().is_local() => {
1359                let trait_path = self.tcx.short_string(
1360                    trait_pred.skip_binder().trait_ref.print_only_trait_path(),
1361                    err.long_ty_path(),
1362                );
1363                err.span_note(
1364                    self.tcx.def_span(def.did()),
1365                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` needs to implement `{1}`",
                self_ty, trait_path))
    })format!("`{self_ty}` needs to implement `{trait_path}`"),
1366                );
1367            }
1368            (ty::Adt(def, _), Some(ty)) if def.did().is_local() => {
1369                err.span_note(
1370                    self.tcx.def_span(def.did()),
1371                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` needs to implement `From<{1}>`",
                self_ty, ty))
    })format!("`{self_ty}` needs to implement `From<{ty}>`"),
1372                );
1373            }
1374            (_, Some(ty))
1375                if let ty::Adt(def, _) = ty.kind()
1376                    && def.did().is_local() =>
1377            {
1378                err.span_note(
1379                    self.tcx.def_span(def.did()),
1380                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` needs to implement `Into<{1}>`",
                ty, self_ty))
    })format!("`{ty}` needs to implement `Into<{self_ty}>`"),
1381                );
1382            }
1383            _ => return false,
1384        }
1385        true
1386    }
1387
1388    fn report_const_param_not_wf(
1389        &self,
1390        ty: Ty<'tcx>,
1391        obligation: &PredicateObligation<'tcx>,
1392    ) -> Diag<'a> {
1393        let def_id = obligation.cause.body_def_id;
1394        let span = self.tcx.ty_span(def_id);
1395
1396        let mut file = None;
1397        let ty_str = self.tcx.short_string(ty, &mut file);
1398        let mut diag = match ty.kind() {
1399            ty::Float(_) => {
1400                {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
                            ty_str))
                })).with_code(E0741)
}struct_span_code_err!(
1401                    self.dcx(),
1402                    span,
1403                    E0741,
1404                    "`{ty_str}` is forbidden as the type of a const generic parameter",
1405                )
1406            }
1407            ty::FnPtr(..) => {
1408                {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("using function pointers as const generic parameters is forbidden"))
                })).with_code(E0741)
}struct_span_code_err!(
1409                    self.dcx(),
1410                    span,
1411                    E0741,
1412                    "using function pointers as const generic parameters is forbidden",
1413                )
1414            }
1415            ty::RawPtr(_, _) => {
1416                {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("using raw pointers as const generic parameters is forbidden"))
                })).with_code(E0741)
}struct_span_code_err!(
1417                    self.dcx(),
1418                    span,
1419                    E0741,
1420                    "using raw pointers as const generic parameters is forbidden",
1421                )
1422            }
1423            ty::Adt(def, _) => {
1424                // We should probably see if we're *allowed* to derive `ConstParamTy` on the type...
1425                let mut diag = {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` must implement `ConstParamTy` to be used as the type of a const generic parameter",
                            ty_str))
                })).with_code(E0741)
}struct_span_code_err!(
1426                    self.dcx(),
1427                    span,
1428                    E0741,
1429                    "`{ty_str}` must implement `ConstParamTy` to be used as the type of a const generic parameter",
1430                );
1431                // Only suggest derive if this isn't a derived obligation,
1432                // and the struct is local.
1433                if let Some(span) = self.tcx.hir_span_if_local(def.did())
1434                    && obligation.cause.code().parent().is_none()
1435                {
1436                    if ty.is_structural_eq_shallow(self.tcx) {
1437                        diag.span_suggestion(
1438                            span.shrink_to_lo(),
1439                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add `#[derive(ConstParamTy)]` to the {0}",
                def.descr()))
    })format!("add `#[derive(ConstParamTy)]` to the {}", def.descr()),
1440                            "#[derive(ConstParamTy)]\n",
1441                            Applicability::MachineApplicable,
1442                        );
1443                    } else {
1444                        // FIXME(adt_const_params): We should check there's not already an
1445                        // overlapping `Eq`/`PartialEq` impl.
1446                        diag.span_suggestion(
1447                            span.shrink_to_lo(),
1448                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {0}",
                def.descr()))
    })format!(
1449                                "add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {}",
1450                                def.descr()
1451                            ),
1452                            "#[derive(ConstParamTy, PartialEq, Eq)]\n",
1453                            Applicability::MachineApplicable,
1454                        );
1455                    }
1456                }
1457                diag
1458            }
1459            _ => {
1460                {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` can\'t be used as a const parameter type",
                            ty_str))
                })).with_code(E0741)
}struct_span_code_err!(
1461                    self.dcx(),
1462                    span,
1463                    E0741,
1464                    "`{ty_str}` can't be used as a const parameter type",
1465                )
1466            }
1467        };
1468        diag.long_ty_path = file;
1469
1470        let mut code = obligation.cause.code();
1471        let mut pred = obligation.predicate.as_trait_clause();
1472        while let Some((next_code, next_pred)) = code.parent_with_predicate() {
1473            if let Some(pred) = pred {
1474                self.enter_forall(pred, |pred| {
1475                    let ty = self.tcx.short_string(pred.self_ty(), diag.long_ty_path());
1476                    let trait_path = self
1477                        .tcx
1478                        .short_string(pred.print_modifiers_and_trait_path(), diag.long_ty_path());
1479                    diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` must implement `{1}`, but it does not",
                ty, trait_path))
    })format!("`{ty}` must implement `{trait_path}`, but it does not"));
1480                })
1481            }
1482            code = next_code;
1483            pred = next_pred;
1484        }
1485
1486        diag
1487    }
1488}
1489
1490impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
1491    fn can_match_trait(
1492        &self,
1493        param_env: ty::ParamEnv<'tcx>,
1494        goal: ty::TraitPredicate<'tcx>,
1495        assumption: ty::PolyTraitPredicate<'tcx>,
1496    ) -> bool {
1497        // Fast path
1498        if goal.polarity != assumption.polarity() {
1499            return false;
1500        }
1501
1502        let trait_assumption = self.instantiate_binder_with_fresh_vars(
1503            DUMMY_SP,
1504            infer::BoundRegionConversionTime::HigherRankedType,
1505            assumption,
1506        );
1507
1508        self.can_eq(param_env, goal.trait_ref, trait_assumption.trait_ref)
1509    }
1510
1511    fn can_match_host_effect(
1512        &self,
1513        param_env: ty::ParamEnv<'tcx>,
1514        goal: ty::HostEffectPredicate<'tcx>,
1515        assumption: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
1516    ) -> bool {
1517        let assumption = self.instantiate_binder_with_fresh_vars(
1518            DUMMY_SP,
1519            infer::BoundRegionConversionTime::HigherRankedType,
1520            assumption,
1521        );
1522
1523        assumption.constness.satisfies(goal.constness)
1524            && self.can_eq(param_env, goal.trait_ref, assumption.trait_ref)
1525    }
1526
1527    fn as_host_effect_clause(
1528        predicate: ty::Predicate<'tcx>,
1529    ) -> Option<ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>> {
1530        predicate.as_clause().and_then(|clause| match clause.kind().skip_binder() {
1531            ty::ClauseKind::HostEffect(pred) => Some(clause.kind().rebind(pred)),
1532            _ => None,
1533        })
1534    }
1535
1536    fn can_match_projection(
1537        &self,
1538        param_env: ty::ParamEnv<'tcx>,
1539        goal: ty::ProjectionPredicate<'tcx>,
1540        assumption: ty::PolyProjectionPredicate<'tcx>,
1541    ) -> bool {
1542        let assumption = self.instantiate_binder_with_fresh_vars(
1543            DUMMY_SP,
1544            infer::BoundRegionConversionTime::HigherRankedType,
1545            assumption,
1546        );
1547
1548        self.can_eq(param_env, goal.projection_term, assumption.projection_term)
1549            && self.can_eq(param_env, goal.term, assumption.term)
1550    }
1551
1552    // returns if `cond` not occurring implies that `error` does not occur - i.e., that
1553    // `error` occurring implies that `cond` occurs.
1554    x;#[instrument(level = "debug", skip(self), ret)]
1555    pub(super) fn error_implies(
1556        &self,
1557        cond: Goal<'tcx, ty::Predicate<'tcx>>,
1558        error: Goal<'tcx, ty::Predicate<'tcx>>,
1559    ) -> bool {
1560        if cond == error {
1561            return true;
1562        }
1563
1564        // FIXME: We could be smarter about this, i.e. if cond's param-env is a
1565        // subset of error's param-env. This only matters when binders will carry
1566        // predicates though, and obviously only matters for error reporting.
1567        if cond.param_env != error.param_env {
1568            return false;
1569        }
1570        let param_env = error.param_env;
1571
1572        if let Some(error) = error.predicate.as_trait_clause() {
1573            self.enter_forall(error, |error| {
1574                elaborate(self.tcx, std::iter::once(cond.predicate))
1575                    .filter_map(|implied| implied.as_trait_clause())
1576                    .any(|implied| self.can_match_trait(param_env, error, implied))
1577            })
1578        } else if let Some(error) = Self::as_host_effect_clause(error.predicate) {
1579            self.enter_forall(error, |error| {
1580                elaborate(self.tcx, std::iter::once(cond.predicate))
1581                    .filter_map(Self::as_host_effect_clause)
1582                    .any(|implied| self.can_match_host_effect(param_env, error, implied))
1583            })
1584        } else if let Some(error) = error.predicate.as_projection_clause() {
1585            self.enter_forall(error, |error| {
1586                elaborate(self.tcx, std::iter::once(cond.predicate))
1587                    .filter_map(|implied| implied.as_projection_clause())
1588                    .any(|implied| self.can_match_projection(param_env, error, implied))
1589            })
1590        } else {
1591            false
1592        }
1593    }
1594
1595    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("report_projection_error",
                                    "rustc_trait_selection::error_reporting::traits::fulfillment_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1595u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::fulfillment_errors"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ErrorGuaranteed = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let predicate =
                self.resolve_vars_if_possible(obligation.predicate);
            if let Err(e) = predicate.error_reported() { return e; }
            self.probe(|_|
                    {
                        let bound_predicate = predicate.kind();
                        let (values, err) =
                            match bound_predicate.skip_binder() {
                                ty::PredicateKind::Clause(ty::ClauseKind::Projection(data))
                                    => {
                                    let ocx = ObligationCtxt::new(self);
                                    let data =
                                        self.instantiate_binder_with_fresh_vars(obligation.cause.span,
                                            infer::BoundRegionConversionTime::HigherRankedType,
                                            bound_predicate.rebind(data));
                                    let unnormalized_term =
                                        data.projection_term.to_term(self.tcx, ty::IsRigid::No);
                                    let normalized_term =
                                        ocx.normalize(&obligation.cause, obligation.param_env,
                                            Unnormalized::new_wip(unnormalized_term));
                                    let _ = ocx.try_evaluate_obligations();
                                    if let Err(new_err) =
                                            ocx.eq(&obligation.cause, obligation.param_env, data.term,
                                                normalized_term) {
                                        (Some((data.projection_term,
                                                    self.resolve_vars_if_possible(normalized_term), data.term)),
                                            new_err)
                                    } else { (None, error.err) }
                                }
                                _ => (None, error.err),
                            };
                        let mut file = None;
                        let (msg, span, closure_span) =
                            values.and_then(|(predicate, normalized_term,
                                            expected_term)|
                                        {
                                            self.maybe_detailed_projection_msg(obligation.cause.span,
                                                predicate, normalized_term, expected_term, &mut file)
                                        }).unwrap_or_else(||
                                    {
                                        ({
                                                let _guard = ForceTrimmedGuard::new();
                                                ::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("type mismatch resolving `{0}`",
                                                                self.tcx.short_string(self.resolve_vars_if_possible(predicate),
                                                                    &mut file)))
                                                    })
                                            }, obligation.cause.span, None)
                                    });
                        let mut diag =
                            {
                                self.dcx().struct_span_err(span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("{0}", msg))
                                            })).with_code(E0271)
                            };
                        *diag.long_ty_path() = file;
                        let mut mention_bounds = true;
                        if let Some(span) = closure_span {
                            if let Some((_, _, expected_ty)) = values &&
                                                    let Some(expected_ty) = expected_ty.as_type() &&
                                                let ty::Closure(def_id, _) = expected_ty.kind() &&
                                            self.tcx.def_span(*def_id).overlaps(span) &&
                                        let ObligationCauseCode::FunctionArg {
                                            parent_code, arg_hir_id, .. } = obligation.cause.code() &&
                                    let ObligationCauseCode::WhereClauseInExpr(def_id, span, _,
                                        _) | ObligationCauseCode::WhereClause(def_id, span) =
                                        &**parent_code {
                                let mut multispan: MultiSpan = (*span).into();
                                multispan.push_span_label(*span,
                                    "this requires the closure to return itself");
                                if let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) {
                                    multispan.push_span_label(arg.span,
                                        "this closure would have to return itself");
                                }
                                let in_the_item =
                                    match self.tcx.opt_item_name(*def_id) {
                                        Some(name) =>
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("in `{0}`", name))
                                                }),
                                        None => String::new(),
                                    };
                                diag.span_note(multispan,
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("a bound {0} requires that a closure return itself, which is not possible",
                                                    in_the_item))
                                        }));
                                mention_bounds = false;
                            } else {
                                diag.span_label(span, "this closure");
                                if !span.overlaps(obligation.cause.span) {
                                    diag.span_label(obligation.cause.span, "closure used here");
                                }
                            }
                        }
                        let secondary_span =
                            self.probe(|_|
                                    {
                                        let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
                                            predicate.kind().skip_binder() else { return None; };
                                        if !proj.projection_term.kind.is_trait_projection() {
                                            return None;
                                        }
                                        let trait_ref =
                                            self.enter_forall_and_leak_universe(predicate.kind().rebind(proj.projection_term.trait_ref(self.tcx)));
                                        let Ok(Some(ImplSource::UserDefined(impl_data))) =
                                            SelectionContext::new(self).select(&obligation.with(self.tcx,
                                                        trait_ref)) else { return None; };
                                        let Ok(node) =
                                            specialization_graph::assoc_def(self.tcx,
                                                impl_data.impl_def_id, proj.def_id()) else { return None; };
                                        if !node.is_final() { return None; }
                                        match self.tcx.hir_get_if_local(node.item.def_id) {
                                            Some(hir::Node::TraitItem(hir::TraitItem {
                                                kind: hir::TraitItemKind::Type(_, Some(ty)), .. }) |
                                                hir::Node::ImplItem(hir::ImplItem {
                                                kind: hir::ImplItemKind::Type(ty), .. })) =>
                                                Some((ty.span,
                                                        {
                                                            let _guard = ForceTrimmedGuard::new();
                                                            Cow::from(::alloc::__export::must_use({
                                                                        ::alloc::fmt::format(format_args!("type mismatch resolving `{0}`",
                                                                                self.tcx.short_string(self.resolve_vars_if_possible(predicate),
                                                                                    diag.long_ty_path())))
                                                                    }))
                                                        }, true)),
                                            _ => None,
                                        }
                                    });
                        self.note_type_err(&mut diag, &obligation.cause,
                            secondary_span,
                            values.map(|(_, normalized_ty, expected_ty)|
                                    {
                                        obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(expected_ty,
                                                    normalized_ty)))
                                    }), err, false, Some(span));
                        if mention_bounds {
                            self.note_obligation_cause(&mut diag, obligation);
                        }
                        diag.emit()
                    })
        }
    }
}#[instrument(level = "debug", skip_all)]
1596    pub(super) fn report_projection_error(
1597        &self,
1598        obligation: &PredicateObligation<'tcx>,
1599        error: &MismatchedProjectionTypes<'tcx>,
1600    ) -> ErrorGuaranteed {
1601        let predicate = self.resolve_vars_if_possible(obligation.predicate);
1602
1603        if let Err(e) = predicate.error_reported() {
1604            return e;
1605        }
1606
1607        self.probe(|_| {
1608            // try to find the mismatched types to report the error with.
1609            //
1610            // this can fail if the problem was higher-ranked, in which
1611            // cause I have no idea for a good error message.
1612            let bound_predicate = predicate.kind();
1613            let (values, err) = match bound_predicate.skip_binder() {
1614                ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
1615                    let ocx = ObligationCtxt::new(self);
1616
1617                    let data = self.instantiate_binder_with_fresh_vars(
1618                        obligation.cause.span,
1619                        infer::BoundRegionConversionTime::HigherRankedType,
1620                        bound_predicate.rebind(data),
1621                    );
1622                    let unnormalized_term = data.projection_term.to_term(self.tcx, ty::IsRigid::No);
1623                    // FIXME(-Znext-solver): For diagnostic purposes, it would be nice
1624                    // to deeply normalize this type.
1625                    let normalized_term = ocx.normalize(
1626                        &obligation.cause,
1627                        obligation.param_env,
1628                        Unnormalized::new_wip(unnormalized_term),
1629                    );
1630
1631                    // constrain inference variables a bit more to nested obligations from normalize so
1632                    // we can have more helpful errors.
1633                    //
1634                    // we intentionally drop errors from normalization here,
1635                    // since the normalization is just done to improve the error message.
1636                    let _ = ocx.try_evaluate_obligations();
1637
1638                    if let Err(new_err) =
1639                        ocx.eq(&obligation.cause, obligation.param_env, data.term, normalized_term)
1640                    {
1641                        (
1642                            Some((
1643                                data.projection_term,
1644                                self.resolve_vars_if_possible(normalized_term),
1645                                data.term,
1646                            )),
1647                            new_err,
1648                        )
1649                    } else {
1650                        (None, error.err)
1651                    }
1652                }
1653                _ => (None, error.err),
1654            };
1655
1656            let mut file = None;
1657            let (msg, span, closure_span) = values
1658                .and_then(|(predicate, normalized_term, expected_term)| {
1659                    self.maybe_detailed_projection_msg(
1660                        obligation.cause.span,
1661                        predicate,
1662                        normalized_term,
1663                        expected_term,
1664                        &mut file,
1665                    )
1666                })
1667                .unwrap_or_else(|| {
1668                    (
1669                        with_forced_trimmed_paths!(format!(
1670                            "type mismatch resolving `{}`",
1671                            self.tcx
1672                                .short_string(self.resolve_vars_if_possible(predicate), &mut file),
1673                        )),
1674                        obligation.cause.span,
1675                        None,
1676                    )
1677                });
1678            let mut diag = struct_span_code_err!(self.dcx(), span, E0271, "{msg}");
1679            *diag.long_ty_path() = file;
1680            let mut mention_bounds = true;
1681            if let Some(span) = closure_span {
1682                if let Some((_, _, expected_ty)) = values
1683                    && let Some(expected_ty) = expected_ty.as_type()
1684                    && let ty::Closure(def_id, _) = expected_ty.kind()
1685                    && self.tcx.def_span(*def_id).overlaps(span)
1686                    && let ObligationCauseCode::FunctionArg { parent_code, arg_hir_id, .. } =
1687                        obligation.cause.code()
1688                    && let ObligationCauseCode::WhereClauseInExpr(def_id, span, _, _)
1689                    | ObligationCauseCode::WhereClause(def_id, span) = &**parent_code
1690                {
1691                    // We have a trait bound for a closure to return itself, like
1692                    // `T: FnOnce() -> T`. This is nonsensical, but as far as the type system is
1693                    // concerned, valid. This is quite an edge case, but lets produce a reasonable
1694                    // diagnostic even in the face of an unreasonable user :)
1695                    let mut multispan: MultiSpan = (*span).into();
1696                    multispan.push_span_label(*span, "this requires the closure to return itself");
1697                    if let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) {
1698                        multispan
1699                            .push_span_label(arg.span, "this closure would have to return itself");
1700                    }
1701                    let in_the_item = match self.tcx.opt_item_name(*def_id) {
1702                        Some(name) => format!("in `{name}`"),
1703                        None => String::new(),
1704                    };
1705                    diag.span_note(
1706                        multispan,
1707                        format!(
1708                            "a bound {in_the_item} requires that a closure return itself, which is \
1709                             not possible",
1710                        ),
1711                    );
1712                    mention_bounds = false;
1713                } else {
1714                    // Mark the closure decl so that it is seen even if we are pointing at the
1715                    // return type or expression.
1716                    //
1717                    // error[E0271]: expected `{closure@foo.rs:41:16}` to be a closure that returns
1718                    //               `Unit3`, but it returns `Unit4`
1719                    //   --> $DIR/foo.rs:43:17
1720                    //    |
1721                    // LL |     let v = Unit2.m(
1722                    //    |                   - required by a bound introduced by this call
1723                    // ...
1724                    // LL |             f: |x| {
1725                    //    |                --- /* this span */
1726                    // LL |                 drop(x);
1727                    // LL |                 Unit4
1728                    //    |                 ^^^^^ expected `Unit3`, found `Unit4`
1729                    //    |
1730                    diag.span_label(span, "this closure");
1731                    if !span.overlaps(obligation.cause.span) {
1732                        // Point at the binding corresponding to the closure where it is used.
1733                        diag.span_label(obligation.cause.span, "closure used here");
1734                    }
1735                }
1736            }
1737
1738            let secondary_span = self.probe(|_| {
1739                let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
1740                    predicate.kind().skip_binder()
1741                else {
1742                    return None;
1743                };
1744                if !proj.projection_term.kind.is_trait_projection() {
1745                    return None;
1746                }
1747
1748                let trait_ref = self.enter_forall_and_leak_universe(
1749                    predicate.kind().rebind(proj.projection_term.trait_ref(self.tcx)),
1750                );
1751                let Ok(Some(ImplSource::UserDefined(impl_data))) =
1752                    SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref))
1753                else {
1754                    return None;
1755                };
1756
1757                let Ok(node) =
1758                    specialization_graph::assoc_def(self.tcx, impl_data.impl_def_id, proj.def_id())
1759                else {
1760                    return None;
1761                };
1762
1763                if !node.is_final() {
1764                    return None;
1765                }
1766
1767                match self.tcx.hir_get_if_local(node.item.def_id) {
1768                    Some(
1769                        hir::Node::TraitItem(hir::TraitItem {
1770                            kind: hir::TraitItemKind::Type(_, Some(ty)),
1771                            ..
1772                        })
1773                        | hir::Node::ImplItem(hir::ImplItem {
1774                            kind: hir::ImplItemKind::Type(ty),
1775                            ..
1776                        }),
1777                    ) => Some((
1778                        ty.span,
1779                        with_forced_trimmed_paths!(Cow::from(format!(
1780                            "type mismatch resolving `{}`",
1781                            self.tcx.short_string(
1782                                self.resolve_vars_if_possible(predicate),
1783                                diag.long_ty_path()
1784                            ),
1785                        ))),
1786                        true,
1787                    )),
1788                    _ => None,
1789                }
1790            });
1791
1792            self.note_type_err(
1793                &mut diag,
1794                &obligation.cause,
1795                secondary_span,
1796                values.map(|(_, normalized_ty, expected_ty)| {
1797                    obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(
1798                        expected_ty,
1799                        normalized_ty,
1800                    )))
1801                }),
1802                err,
1803                false,
1804                Some(span),
1805            );
1806            if mention_bounds {
1807                self.note_obligation_cause(&mut diag, obligation);
1808            }
1809            diag.emit()
1810        })
1811    }
1812
1813    fn maybe_detailed_projection_msg(
1814        &self,
1815        mut span: Span,
1816        projection_term: ty::AliasTerm<'tcx>,
1817        normalized_ty: ty::Term<'tcx>,
1818        expected_ty: ty::Term<'tcx>,
1819        long_ty_path: &mut Option<PathBuf>,
1820    ) -> Option<(String, Span, Option<Span>)> {
1821        if !projection_term.kind.is_trait_projection() {
1822            return None;
1823        }
1824
1825        let projection_def_id = projection_term.expect_projection_def_id();
1826        let trait_def_id = projection_term.trait_def_id(self.tcx);
1827        let self_ty = projection_term.self_ty();
1828
1829        {
    let _guard = ForceTrimmedGuard::new();
    if self.tcx.is_lang_item(projection_def_id, LangItem::FnOnceOutput) {
        let (span, closure_span) =
            if let ty::Closure(def_id, _) = *self_ty.kind() {
                let def_span = self.tcx.def_span(def_id);
                if let Some(local_def_id) = def_id.as_local() &&
                                let node = self.tcx.hir_node_by_def_id(local_def_id) &&
                            let Some(fn_decl) = node.fn_decl() &&
                        let Some(id) = node.body_id() {
                    span =
                        match fn_decl.output {
                            hir::FnRetTy::Return(ty) => ty.span,
                            hir::FnRetTy::DefaultReturn(_) => {
                                let body = self.tcx.hir_body(id);
                                match body.value.kind {
                                    hir::ExprKind::Block(hir::Block { expr: Some(expr), .. }, _)
                                        => expr.span,
                                    hir::ExprKind::Block(hir::Block {
                                        expr: None, stmts: [.., last], .. }, _) => last.span,
                                    _ => body.value.span,
                                }
                            }
                        };
                }
                (span, Some(def_span))
            } else { (span, None) };
        let item =
            match self_ty.kind() {
                ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
                _ => self.tcx.short_string(self_ty, long_ty_path),
            };
        let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
        let normalized_ty =
            self.tcx.short_string(normalized_ty, long_ty_path);
        Some((::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("expected `{0}` to return `{1}`, but it returns `{2}`",
                                item, expected_ty, normalized_ty))
                    }), span, closure_span))
    } else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
        let self_ty = self.tcx.short_string(self_ty, long_ty_path);
        let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
        let normalized_ty =
            self.tcx.short_string(normalized_ty, long_ty_path);
        Some((::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("expected `{0}` to be a future that resolves to `{1}`, but it resolves to `{2}`",
                                self_ty, expected_ty, normalized_ty))
                    }), span, None))
    } else if Some(trait_def_id) ==
            self.tcx.get_diagnostic_item(sym::Iterator) {
        let self_ty = self.tcx.short_string(self_ty, long_ty_path);
        let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
        let normalized_ty =
            self.tcx.short_string(normalized_ty, long_ty_path);
        Some((::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("expected `{0}` to be an iterator that yields `{1}`, but it yields `{2}`",
                                self_ty, expected_ty, normalized_ty))
                    }), span, None))
    } else { None }
}with_forced_trimmed_paths! {
1830            if self.tcx.is_lang_item(projection_def_id, LangItem::FnOnceOutput) {
1831                let (span, closure_span) = if let ty::Closure(def_id, _) = *self_ty.kind() {
1832                    let def_span = self.tcx.def_span(def_id);
1833                    if let Some(local_def_id) = def_id.as_local()
1834                        && let node = self.tcx.hir_node_by_def_id(local_def_id)
1835                        && let Some(fn_decl) = node.fn_decl()
1836                        && let Some(id) = node.body_id()
1837                    {
1838                        span = match fn_decl.output {
1839                            hir::FnRetTy::Return(ty) => ty.span,
1840                            hir::FnRetTy::DefaultReturn(_) => {
1841                                let body = self.tcx.hir_body(id);
1842                                match body.value.kind {
1843                                    hir::ExprKind::Block(
1844                                        hir::Block { expr: Some(expr), .. },
1845                                        _,
1846                                    ) => expr.span,
1847                                    hir::ExprKind::Block(
1848                                        hir::Block {
1849                                            expr: None, stmts: [.., last], ..
1850                                        },
1851                                        _,
1852                                    ) => last.span,
1853                                    _ => body.value.span,
1854                                }
1855                            }
1856                        };
1857                    }
1858                    (span, Some(def_span))
1859                } else {
1860                    (span, None)
1861                };
1862                let item = match self_ty.kind() {
1863                    ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
1864                    _ => self.tcx.short_string(self_ty, long_ty_path),
1865                };
1866                let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1867                let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1868                Some((format!(
1869                    "expected `{item}` to return `{expected_ty}`, but it returns `{normalized_ty}`",
1870                ), span, closure_span))
1871            } else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
1872                let self_ty = self.tcx.short_string(self_ty, long_ty_path);
1873                let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1874                let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1875                Some((format!(
1876                    "expected `{self_ty}` to be a future that resolves to `{expected_ty}`, but it \
1877                     resolves to `{normalized_ty}`"
1878                ), span, None))
1879            } else if Some(trait_def_id) == self.tcx.get_diagnostic_item(sym::Iterator) {
1880                let self_ty = self.tcx.short_string(self_ty, long_ty_path);
1881                let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1882                let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1883                Some((format!(
1884                    "expected `{self_ty}` to be an iterator that yields `{expected_ty}`, but it \
1885                     yields `{normalized_ty}`"
1886                ), span, None))
1887            } else {
1888                None
1889            }
1890        }
1891    }
1892
1893    pub fn fuzzy_match_tys(
1894        &self,
1895        mut a: Ty<'tcx>,
1896        mut b: Ty<'tcx>,
1897        ignoring_lifetimes: bool,
1898    ) -> Option<CandidateSimilarity> {
1899        /// returns the fuzzy category of a given type, or None
1900        /// if the type can be equated to any type.
1901        fn type_category(tcx: TyCtxt<'_>, t: Ty<'_>) -> Option<u32> {
1902            match t.kind() {
1903                ty::Bool => Some(0),
1904                ty::Char => Some(1),
1905                ty::Str => Some(2),
1906                ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => Some(2),
1907                ty::Int(..)
1908                | ty::Uint(..)
1909                | ty::Float(..)
1910                | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) => Some(4),
1911                ty::Ref(..) | ty::RawPtr(..) => Some(5),
1912                ty::Array(..) | ty::Slice(..) => Some(6),
1913                ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1914                ty::Dynamic(..) => Some(8),
1915                ty::Closure(..) => Some(9),
1916                ty::Tuple(..) => Some(10),
1917                ty::Param(..) => Some(11),
1918                ty::Alias(_, ty::AliasTy { kind: ty::Projection { .. }, .. }) => Some(12),
1919                ty::Alias(_, ty::AliasTy { kind: ty::Inherent { .. }, .. }) => Some(13),
1920                ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => Some(14),
1921                ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) => Some(15),
1922                ty::Never => Some(16),
1923                ty::Adt(..) => Some(17),
1924                ty::Coroutine(..) => Some(18),
1925                ty::Foreign(..) => Some(19),
1926                ty::CoroutineWitness(..) => Some(20),
1927                ty::CoroutineClosure(..) => Some(21),
1928                ty::Pat(..) => Some(22),
1929                ty::UnsafeBinder(..) => Some(23),
1930                ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1931            }
1932        }
1933
1934        let strip_references = |mut t: Ty<'tcx>| -> Ty<'tcx> {
1935            loop {
1936                match t.kind() {
1937                    ty::Ref(_, inner, _) | ty::RawPtr(inner, _) => t = *inner,
1938                    _ => break t,
1939                }
1940            }
1941        };
1942
1943        if !ignoring_lifetimes {
1944            a = strip_references(a);
1945            b = strip_references(b);
1946        }
1947
1948        let cat_a = type_category(self.tcx, a)?;
1949        let cat_b = type_category(self.tcx, b)?;
1950        if a == b {
1951            Some(CandidateSimilarity::Exact { ignoring_lifetimes })
1952        } else if cat_a == cat_b {
1953            match (a.kind(), b.kind()) {
1954                (ty::Adt(def_a, _), ty::Adt(def_b, _)) => def_a == def_b,
1955                (ty::Foreign(def_a), ty::Foreign(def_b)) => def_a == def_b,
1956                // Matching on references results in a lot of unhelpful
1957                // suggestions, so let's just not do that for now.
1958                //
1959                // We still upgrade successful matches to `ignoring_lifetimes: true`
1960                // to prioritize that impl.
1961                (ty::Ref(..) | ty::RawPtr(..), ty::Ref(..) | ty::RawPtr(..)) => {
1962                    self.fuzzy_match_tys(a, b, true).is_some()
1963                }
1964                _ => true,
1965            }
1966            .then_some(CandidateSimilarity::Fuzzy { ignoring_lifetimes })
1967        } else if ignoring_lifetimes {
1968            None
1969        } else {
1970            self.fuzzy_match_tys(a, b, true)
1971        }
1972    }
1973
1974    pub(super) fn describe_closure(&self, kind: hir::ClosureKind) -> &'static str {
1975        match kind {
1976            hir::ClosureKind::Closure => "a closure",
1977            hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => "a coroutine",
1978            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1979                hir::CoroutineDesugaring::Async,
1980                hir::CoroutineSource::Block,
1981            )) => "an async block",
1982            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1983                hir::CoroutineDesugaring::Async,
1984                hir::CoroutineSource::Fn,
1985            )) => "an async function",
1986            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1987                hir::CoroutineDesugaring::Async,
1988                hir::CoroutineSource::Closure,
1989            ))
1990            | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
1991                "an async closure"
1992            }
1993            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1994                hir::CoroutineDesugaring::AsyncGen,
1995                hir::CoroutineSource::Block,
1996            )) => "an async gen block",
1997            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1998                hir::CoroutineDesugaring::AsyncGen,
1999                hir::CoroutineSource::Fn,
2000            )) => "an async gen function",
2001            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2002                hir::CoroutineDesugaring::AsyncGen,
2003                hir::CoroutineSource::Closure,
2004            ))
2005            | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
2006                "an async gen closure"
2007            }
2008            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2009                hir::CoroutineDesugaring::Gen,
2010                hir::CoroutineSource::Block,
2011            )) => "a gen block",
2012            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2013                hir::CoroutineDesugaring::Gen,
2014                hir::CoroutineSource::Fn,
2015            )) => "a gen function",
2016            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2017                hir::CoroutineDesugaring::Gen,
2018                hir::CoroutineSource::Closure,
2019            ))
2020            | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => "a gen closure",
2021        }
2022    }
2023
2024    pub(super) fn find_similar_impl_candidates(
2025        &self,
2026        trait_pred: ty::PolyTraitPredicate<'tcx>,
2027    ) -> Vec<ImplCandidate<'tcx>> {
2028        let mut candidates: Vec<_> = self
2029            .tcx
2030            .all_impls(trait_pred.def_id())
2031            .filter_map(|def_id| {
2032                let imp = self.tcx.impl_trait_header(def_id);
2033                if imp.polarity != ty::ImplPolarity::Positive
2034                    || !self.tcx.is_user_visible_dep(def_id.krate)
2035                {
2036                    return None;
2037                }
2038                let imp = imp.trait_ref.skip_binder();
2039
2040                self.fuzzy_match_tys(trait_pred.skip_binder().self_ty(), imp.self_ty(), false).map(
2041                    |similarity| ImplCandidate { trait_ref: imp, similarity, impl_def_id: def_id },
2042                )
2043            })
2044            .collect();
2045        if candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
    CandidateSimilarity::Exact { .. } => true,
    _ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. })) {
2046            // If any of the candidates is a perfect match, we don't want to show all of them.
2047            // This is particularly relevant for the case of numeric types (as they all have the
2048            // same category).
2049            candidates.retain(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
    CandidateSimilarity::Exact { .. } => true,
    _ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. }));
2050        }
2051        candidates
2052    }
2053
2054    pub(super) fn report_similar_impl_candidates(
2055        &self,
2056        impl_candidates: &[ImplCandidate<'tcx>],
2057        obligation: &PredicateObligation<'tcx>,
2058        trait_pred: ty::PolyTraitPredicate<'tcx>,
2059        body_def_id: LocalDefId,
2060        err: &mut Diag<'_>,
2061        other: bool,
2062        param_env: ty::ParamEnv<'tcx>,
2063    ) -> bool {
2064        let parent_map = self.tcx.visible_parent_map(());
2065        let alternative_candidates = |def_id: DefId| {
2066            let mut impl_candidates: Vec<_> = self
2067                .tcx
2068                .all_impls(def_id)
2069                // ignore `do_not_recommend` items
2070                .filter(|def_id| !self.tcx.do_not_recommend_impl(*def_id))
2071                // Ignore automatically derived impls and `!Trait` impls.
2072                .map(|def_id| (self.tcx.impl_trait_header(def_id), def_id))
2073                .filter_map(|(header, def_id)| {
2074                    (header.polarity == ty::ImplPolarity::Positive
2075                        || self.tcx.is_automatically_derived(def_id))
2076                    .then(|| (header.trait_ref.instantiate_identity().skip_norm_wip(), def_id))
2077                })
2078                .filter(|(trait_ref, _)| {
2079                    let self_ty = trait_ref.self_ty();
2080                    // Avoid mentioning type parameters.
2081                    if let ty::Param(_) = self_ty.kind() {
2082                        false
2083                    }
2084                    // Avoid mentioning types that are private to another crate
2085                    else if let ty::Adt(def, _) = self_ty.peel_refs().kind() {
2086                        // FIXME(compiler-errors): This could be generalized, both to
2087                        // be more granular, and probably look past other `#[fundamental]`
2088                        // types, too.
2089                        let mut did = def.did();
2090                        if self.tcx.visibility(did).is_accessible_from(body_def_id, self.tcx) {
2091                            // don't suggest foreign `#[doc(hidden)]` types
2092                            if !did.is_local() {
2093                                let mut previously_seen_dids: FxHashSet<DefId> = Default::default();
2094                                previously_seen_dids.insert(did);
2095                                while let Some(&parent) = parent_map.get(&did)
2096                                    && let hash_set::Entry::Vacant(v) =
2097                                        previously_seen_dids.entry(parent)
2098                                {
2099                                    if self.tcx.is_doc_hidden(did) {
2100                                        return false;
2101                                    }
2102                                    v.insert();
2103                                    did = parent;
2104                                }
2105                            }
2106                            true
2107                        } else {
2108                            false
2109                        }
2110                    } else {
2111                        true
2112                    }
2113                })
2114                .collect();
2115
2116            impl_candidates.sort_by_key(|(tr, _)| tr.to_string());
2117            impl_candidates.dedup();
2118            impl_candidates
2119        };
2120
2121        if let [single] = &impl_candidates {
2122            let self_ty = trait_pred.skip_binder().self_ty();
2123            if !self_ty.has_escaping_bound_vars() {
2124                let self_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
2125                if let ty::Ref(_, inner_ty, _) = self_ty.kind()
2126                    && self.can_eq(param_env, single.trait_ref.self_ty(), *inner_ty)
2127                    && !self.where_clause_expr_matches_failed_self_ty(obligation, self_ty)
2128                {
2129                    // Avoid pointing at a nearby impl like `String: Borrow<str>` when the
2130                    // failing obligation comes from something nested inside an enclosing call
2131                    // expression such as `foo(&[String::from("a")])`.
2132                    return true;
2133                }
2134            }
2135
2136            // If we have a single implementation, try to unify it with the trait ref
2137            // that failed. This should uncover a better hint for what *is* implemented.
2138            if self.probe(|_| {
2139                let ocx = ObligationCtxt::new(self);
2140
2141                self.enter_forall(trait_pred, |obligation_trait_ref| {
2142                    let impl_args = self.fresh_args_for_item(DUMMY_SP, single.impl_def_id);
2143                    let impl_trait_ref = ocx.normalize(
2144                        &ObligationCause::dummy(),
2145                        param_env,
2146                        ty::EarlyBinder::bind(self.tcx, single.trait_ref)
2147                            .instantiate(self.tcx, impl_args),
2148                    );
2149
2150                    ocx.register_obligations(
2151                        self.tcx
2152                            .clauses_of(single.impl_def_id)
2153                            .instantiate(self.tcx, impl_args)
2154                            .into_iter()
2155                            .map(|(clause, _)| {
2156                                Obligation::new(
2157                                    self.tcx,
2158                                    ObligationCause::dummy(),
2159                                    param_env,
2160                                    clause.skip_norm_wip(),
2161                                )
2162                            }),
2163                    );
2164                    if !ocx.try_evaluate_obligations().is_empty() {
2165                        return false;
2166                    }
2167
2168                    let mut terrs = ::alloc::vec::Vec::new()vec![];
2169                    for (obligation_arg, impl_arg) in
2170                        std::iter::zip(obligation_trait_ref.trait_ref.args, impl_trait_ref.args)
2171                    {
2172                        if (obligation_arg, impl_arg).references_error() {
2173                            return false;
2174                        }
2175                        if let Err(terr) =
2176                            ocx.eq(&ObligationCause::dummy(), param_env, impl_arg, obligation_arg)
2177                        {
2178                            terrs.push(terr);
2179                        }
2180                        if !ocx.try_evaluate_obligations().is_empty() {
2181                            return false;
2182                        }
2183                    }
2184
2185                    // Literally nothing unified, just give up.
2186                    if terrs.len() == impl_trait_ref.args.len() {
2187                        return false;
2188                    }
2189
2190                    let impl_trait_ref = self.resolve_vars_if_possible(impl_trait_ref);
2191                    if impl_trait_ref.references_error() {
2192                        return false;
2193                    }
2194
2195                    if let [child, ..] = &err.children[..]
2196                        && child.level == Level::Help
2197                        && let Some(line) = child.messages.get(0)
2198                        && let Some(line) = line.0.as_str()
2199                        && line.starts_with("the trait")
2200                        && line.contains("is not implemented for")
2201                    {
2202                        // HACK(estebank): we remove the pre-existing
2203                        // "the trait `X` is not implemented for" note, which only happens if there
2204                        // was a custom label. We do this because we want that note to always be the
2205                        // first, and making this logic run earlier will get tricky. For now, we
2206                        // instead keep the logic the same and modify the already constructed error
2207                        // to avoid the wording duplication.
2208                        err.children.remove(0);
2209                    }
2210
2211                    let traits = self.cmp_traits(
2212                        obligation_trait_ref.def_id(),
2213                        &obligation_trait_ref.trait_ref.args[1..],
2214                        impl_trait_ref.def_id,
2215                        &impl_trait_ref.args[1..],
2216                    );
2217                    let traits_content = (traits.0.content(), traits.1.content());
2218                    let types = self.cmp(obligation_trait_ref.self_ty(), impl_trait_ref.self_ty());
2219                    let types_content = (types.0.content(), types.1.content());
2220                    let mut msg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [StringPart::normal("the trait `")]))vec![StringPart::normal("the trait `")];
2221                    if traits_content.0 == traits_content.1 {
2222                        msg.push(StringPart::normal(
2223                            impl_trait_ref.print_trait_sugared().to_string(),
2224                        ));
2225                    } else {
2226                        msg.extend(traits.0.0);
2227                    }
2228                    msg.extend([
2229                        StringPart::normal("` "),
2230                        StringPart::highlighted("is not"),
2231                        StringPart::normal(" implemented for `"),
2232                    ]);
2233                    if types_content.0 == types_content.1 {
2234                        let ty = self
2235                            .tcx
2236                            .short_string(obligation_trait_ref.self_ty(), err.long_ty_path());
2237                        msg.push(StringPart::normal(ty));
2238                    } else {
2239                        msg.extend(types.0.0);
2240                    }
2241                    msg.push(StringPart::normal("`"));
2242                    if types_content.0 == types_content.1 {
2243                        msg.push(StringPart::normal("\nbut trait `"));
2244                        msg.extend(traits.1.0);
2245                        msg.extend([
2246                            StringPart::normal("` "),
2247                            StringPart::highlighted("is"),
2248                            StringPart::normal(" implemented for it"),
2249                        ]);
2250                    } else if traits_content.0 == traits_content.1 {
2251                        msg.extend([
2252                            StringPart::normal("\nbut it "),
2253                            StringPart::highlighted("is"),
2254                            StringPart::normal(" implemented for `"),
2255                        ]);
2256                        msg.extend(types.1.0);
2257                        msg.push(StringPart::normal("`"));
2258                    } else {
2259                        msg.push(StringPart::normal("\nbut trait `"));
2260                        msg.extend(traits.1.0);
2261                        msg.extend([
2262                            StringPart::normal("` "),
2263                            StringPart::highlighted("is"),
2264                            StringPart::normal(" implemented for `"),
2265                        ]);
2266                        msg.extend(types.1.0);
2267                        msg.push(StringPart::normal("`"));
2268                    }
2269                    err.highlighted_span_help(self.tcx.def_span(single.impl_def_id), msg);
2270
2271                    if let [TypeError::Sorts(exp_found)] = &terrs[..] {
2272                        let exp_found = self.resolve_vars_if_possible(*exp_found);
2273                        let expected =
2274                            self.tcx.short_string(exp_found.expected, err.long_ty_path());
2275                        let found = self.tcx.short_string(exp_found.found, err.long_ty_path());
2276                        err.highlighted_help(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [StringPart::normal("for that trait implementation, "),
                StringPart::normal("expected `"),
                StringPart::highlighted(expected),
                StringPart::normal("`, found `"),
                StringPart::highlighted(found), StringPart::normal("`")]))vec![
2277                            StringPart::normal("for that trait implementation, "),
2278                            StringPart::normal("expected `"),
2279                            StringPart::highlighted(expected),
2280                            StringPart::normal("`, found `"),
2281                            StringPart::highlighted(found),
2282                            StringPart::normal("`"),
2283                        ]);
2284                        self.suggest_function_pointers_impl(None, &exp_found, err);
2285                    }
2286
2287                    if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2288                        && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2289                        && !crates.is_empty()
2290                    {
2291                        self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2292                        err.help("you can use `cargo tree` to explore your dependency tree");
2293                    }
2294                    true
2295                })
2296            }) {
2297                return true;
2298            }
2299        }
2300
2301        let other = if other { "other " } else { "" };
2302        let report = |mut candidates: Vec<(TraitRef<'tcx>, DefId)>, err: &mut Diag<'_>| {
2303            candidates.retain(|(tr, _)| !tr.references_error());
2304            if candidates.is_empty() {
2305                return false;
2306            }
2307            let mut specific_candidates = candidates.clone();
2308            specific_candidates.retain(|(tr, _)| {
2309                tr.with_replaced_self_ty(self.tcx, trait_pred.skip_binder().self_ty())
2310                    == trait_pred.skip_binder().trait_ref
2311            });
2312            if !specific_candidates.is_empty() {
2313                // We have found a subset of impls that fully satisfy the expected trait, only
2314                // mention those types.
2315                candidates = specific_candidates;
2316            }
2317            if let &[(cand, def_id)] = &candidates[..] {
2318                if self.tcx.is_diagnostic_item(sym::FromResidual, cand.def_id)
2319                    && !self.tcx.features().enabled(sym::try_trait_v2)
2320                {
2321                    return false;
2322                }
2323                let mut multi_span = MultiSpan::from_span(self.tcx.def_span(def_id));
2324                let (desc, mention_castable) =
2325                    match (cand.self_ty().kind(), trait_pred.self_ty().skip_binder().kind()) {
2326                        (ty::FnPtr(..), ty::FnDef(..)) => {
2327                            (" implemented for fn pointer `", ", cast using `as`")
2328                        }
2329                        (ty::FnPtr(..), _) => (" implemented for fn pointer `", ""),
2330                        _ => {
2331                            let evaluate_obligations = || {
2332                                let ocx = ObligationCtxt::new_with_diagnostics(self);
2333                                self.enter_forall(trait_pred, |obligation_trait_ref| {
2334                                    let impl_args = self.fresh_args_for_item(DUMMY_SP, def_id);
2335                                    let impl_trait_ref = ocx.normalize(
2336                                        &ObligationCause::dummy(),
2337                                        param_env,
2338                                        ty::EarlyBinder::bind(self.tcx, cand)
2339                                            .instantiate(self.tcx, impl_args),
2340                                    );
2341                                    if ocx
2342                                        .eq(
2343                                            &ObligationCause::dummy(),
2344                                            param_env,
2345                                            obligation_trait_ref.trait_ref,
2346                                            impl_trait_ref,
2347                                        )
2348                                        .is_err()
2349                                    {
2350                                        return Vec::new();
2351                                    }
2352                                    ocx.register_obligations(
2353                                        self.tcx
2354                                            .clauses_of(def_id)
2355                                            .instantiate(self.tcx, impl_args)
2356                                            .into_iter()
2357                                            .map(|(clause, span)| {
2358                                                Obligation::new(
2359                                                    self.tcx,
2360                                                    ObligationCause::dummy_with_span(span),
2361                                                    param_env,
2362                                                    clause.skip_normalization(),
2363                                                )
2364                                            }),
2365                                    );
2366                                    ocx.try_evaluate_obligations()
2367                                })
2368                            };
2369                            let failing_obligations =
2370                                if !self.tcx.clauses_of(def_id).clauses.is_empty() {
2371                                    self.probe(|_| evaluate_obligations())
2372                                } else {
2373                                    Vec::new()
2374                                };
2375
2376                            if failing_obligations.is_empty() {
2377                                (" implemented for `", "")
2378                            } else {
2379                                for error in failing_obligations {
2380                                    multi_span.push_span_label(
2381                                        error.root_obligation.cause.span,
2382                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unsatisfied requirement introduced here: `{0}`",
                error.root_obligation.predicate))
    })format!(
2383                                            "unsatisfied requirement introduced here: `{}`",
2384                                            error.root_obligation.predicate,
2385                                        ),
2386                                    );
2387                                }
2388
2389                                (" conditionally implemented for `", "")
2390                            }
2391                        }
2392                    };
2393                let trait_ = self.tcx.short_string(cand.print_trait_sugared(), err.long_ty_path());
2394                let self_ty = self.tcx.short_string(cand.self_ty(), err.long_ty_path());
2395                err.highlighted_span_help(
2396                    multi_span,
2397                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [StringPart::normal(::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("the trait `{0}` ",
                                    trait_))
                        })), StringPart::highlighted("is"),
                StringPart::normal(desc), StringPart::highlighted(self_ty),
                StringPart::normal("`"),
                StringPart::normal(mention_castable)]))vec![
2398                        StringPart::normal(format!("the trait `{trait_}` ")),
2399                        StringPart::highlighted("is"),
2400                        StringPart::normal(desc),
2401                        StringPart::highlighted(self_ty),
2402                        StringPart::normal("`"),
2403                        StringPart::normal(mention_castable),
2404                    ],
2405                );
2406                return true;
2407            }
2408            let trait_ref = TraitRef::identity(self.tcx, candidates[0].0.def_id);
2409            // Check if the trait is the same in all cases. If so, we'll only show the type.
2410            let mut traits: Vec<_> =
2411                candidates.iter().map(|(c, _)| c.print_only_trait_path().to_string()).collect();
2412            traits.sort();
2413            traits.dedup();
2414            // FIXME: this could use a better heuristic, like just checking
2415            // that args[1..] is the same.
2416            let all_traits_equal = traits.len() == 1;
2417            let mut types: Vec<_> =
2418                candidates.iter().map(|(c, _)| c.self_ty().to_string()).collect();
2419            types.sort();
2420            types.dedup();
2421            let all_types_equal = types.len() == 1;
2422
2423            let end = if candidates.len() <= 9 || self.tcx.sess.opts.verbose {
2424                candidates.len()
2425            } else {
2426                8
2427            };
2428            if candidates.len() < 5 {
2429                let spans: Vec<_> =
2430                    candidates.iter().map(|&(_, def_id)| self.tcx.def_span(def_id)).collect();
2431                let mut span: MultiSpan = spans.into();
2432                for (c, def_id) in &candidates {
2433                    let msg = if all_traits_equal {
2434                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`",
                self.tcx.short_string(c.self_ty(), err.long_ty_path())))
    })format!("`{}`", self.tcx.short_string(c.self_ty(), err.long_ty_path()))
2435                    } else if all_types_equal {
2436                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`",
                self.tcx.short_string(c.print_only_trait_path(),
                    err.long_ty_path())))
    })format!(
2437                            "`{}`",
2438                            self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path())
2439                        )
2440                    } else {
2441                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` implements `{1}`",
                self.tcx.short_string(c.self_ty(), err.long_ty_path()),
                self.tcx.short_string(c.print_only_trait_path(),
                    err.long_ty_path())))
    })format!(
2442                            "`{}` implements `{}`",
2443                            self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2444                            self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path()),
2445                        )
2446                    };
2447                    span.push_span_label(self.tcx.def_span(*def_id), msg);
2448                }
2449                let msg = if all_types_equal {
2450                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` implements trait `{1}`",
                self.tcx.short_string(candidates[0].0.self_ty(),
                    err.long_ty_path()),
                self.tcx.short_string(trait_ref.print_trait_sugared(),
                    err.long_ty_path())))
    })format!(
2451                        "`{}` implements trait `{}`",
2452                        self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2453                        self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2454                    )
2455                } else {
2456                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the following {1}types implement trait `{0}`",
                self.tcx.short_string(trait_ref.print_trait_sugared(),
                    err.long_ty_path()), other))
    })format!(
2457                        "the following {other}types implement trait `{}`",
2458                        self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2459                    )
2460                };
2461                err.span_help(span, msg);
2462            } else {
2463                // When more than 5 tuples implement the same trait, the output might be very verbose
2464                // Instead of displaying each of these, we sort the candidates by arity in ascending
2465                // order, then we compute the min and the max arity, ensuring that the arities are
2466                // consecutive (by step of one). If these conditions are met, then the output is shown
2467                // as a range of tuples [tuple_min_arity:tuple_max_arity]
2468                let mut tuple_min_arity = usize::MAX;
2469                let mut tuple_max_arity = 0_usize;
2470                let mut last_arity = None;
2471                let mut all_types_tuples_cont_arity = true;
2472                candidates.sort_by(|(c1, _), (c2, _)| {
2473                    if let ty::Tuple(tys1) = c1.self_ty().kind()
2474                        && let ty::Tuple(tys2) = c2.self_ty().kind()
2475                    {
2476                        tys1.len().cmp(&tys2.len())
2477                    } else {
2478                        std::cmp::Ordering::Equal
2479                    }
2480                });
2481                let candidate_names: Vec<String> = candidates
2482                    .iter()
2483                    .map(|(c, _)| {
2484                        if all_traits_equal {
2485                            if all_types_tuples_cont_arity
2486                                && let ty::Tuple(tys) = c.self_ty().kind()
2487                                && last_arity.map_or(1, |a: usize| a.abs_diff(tys.len())) == 1
2488                            {
2489                                last_arity = Some(tys.len());
2490                                if tys.len() > tuple_max_arity {
2491                                    tuple_max_arity = tys.len();
2492                                }
2493                                if tys.len() < tuple_min_arity {
2494                                    tuple_min_arity = tys.len();
2495                                }
2496                            } else {
2497                                all_types_tuples_cont_arity = false;
2498                            }
2499                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n  {0}",
                self.tcx.short_string(c.self_ty(), err.long_ty_path())))
    })format!(
2500                                "\n  {}",
2501                                self.tcx.short_string(c.self_ty(), err.long_ty_path())
2502                            )
2503                        } else if all_types_equal {
2504                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n  {0}",
                self.tcx.short_string(c.print_only_trait_path(),
                    err.long_ty_path())))
    })format!(
2505                                "\n  {}",
2506                                self.tcx
2507                                    .short_string(c.print_only_trait_path(), err.long_ty_path())
2508                            )
2509                        } else {
2510                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n  `{0}` implements `{1}`",
                self.tcx.short_string(c.self_ty(), err.long_ty_path()),
                self.tcx.short_string(c.print_only_trait_path(),
                    err.long_ty_path())))
    })format!(
2511                                "\n  `{}` implements `{}`",
2512                                self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2513                                self.tcx
2514                                    .short_string(c.print_only_trait_path(), err.long_ty_path()),
2515                            )
2516                        }
2517                    })
2518                    .collect();
2519
2520                let details = if all_traits_equal && all_types_tuples_cont_arity {
2521                    if tuple_min_arity == 0 {
2522                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("up to tuples of arity {0}",
                tuple_max_arity))
    })format!("up to tuples of arity {tuple_max_arity}")
2523                    } else {
2524                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("for tuples of arity {0} up to and including {1}",
                tuple_min_arity, tuple_max_arity))
    })format!(
2525                            "for tuples of arity {tuple_min_arity} up to and including {tuple_max_arity}"
2526                        )
2527                    }
2528                } else {
2529                    String::new()
2530                };
2531                let (candidate_names, end) = if all_traits_equal && all_types_tuples_cont_arity {
2532                    (
2533                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("\n  (T₁, T₂, …, Tₙ) {0}",
                                details))
                    })]))vec![
2534                            // (T₁, T₂, …, Tₙ)
2535                            format!("\n  (T\u{2081}, T\u{2082}, …, T\u{2099}) {details}"),
2536                        ],
2537                        1,
2538                    )
2539                } else {
2540                    (candidate_names, end)
2541                };
2542                let msg = if all_types_equal {
2543                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` implements trait `{1}`",
                self.tcx.short_string(candidates[0].0.self_ty(),
                    err.long_ty_path()),
                self.tcx.short_string(trait_ref.print_trait_sugared(),
                    err.long_ty_path())))
    })format!(
2544                        "`{}` implements trait `{}`",
2545                        self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2546                        self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2547                    )
2548                } else {
2549                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the following {1}types implement trait `{0}`",
                self.tcx.short_string(trait_ref.print_trait_sugared(),
                    err.long_ty_path()), other))
    })format!(
2550                        "the following {other}types implement trait `{}`",
2551                        self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2552                    )
2553                };
2554
2555                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{2}:{0}{1}",
                candidate_names[..end].join(""),
                if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("\nand {0} others",
                                    candidates.len() - 8))
                        })
                } else { String::new() }, msg))
    })format!(
2556                    "{msg}:{}{}",
2557                    candidate_names[..end].join(""),
2558                    if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
2559                        format!("\nand {} others", candidates.len() - 8)
2560                    } else {
2561                        String::new()
2562                    }
2563                ));
2564            }
2565
2566            if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2567                && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2568                && !crates.is_empty()
2569            {
2570                self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2571                err.help("you can use `cargo tree` to explore your dependency tree");
2572            }
2573            true
2574        };
2575
2576        // we filter before checking if `impl_candidates` is empty
2577        // to get the fallback solution if we filtered out any impls
2578        let impl_candidates = impl_candidates
2579            .into_iter()
2580            .cloned()
2581            .filter(|cand| !self.tcx.do_not_recommend_impl(cand.impl_def_id))
2582            .collect::<Vec<_>>();
2583
2584        let def_id = trait_pred.def_id();
2585        if impl_candidates.is_empty() {
2586            if self.tcx.trait_is_auto(def_id)
2587                || self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2588                || self.tcx.get_diagnostic_name(def_id).is_some()
2589            {
2590                // Mentioning implementers of `Copy`, `Debug` and friends is not useful.
2591                return false;
2592            }
2593            return report(alternative_candidates(def_id), err);
2594        }
2595
2596        // Sort impl candidates so that ordering is consistent for UI tests.
2597        // because the ordering of `impl_candidates` may not be deterministic:
2598        // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
2599        //
2600        // Prefer more similar candidates first, then sort lexicographically
2601        // by their normalized string representation.
2602        let mut impl_candidates: Vec<_> = impl_candidates
2603            .iter()
2604            .cloned()
2605            .filter(|cand| !cand.trait_ref.references_error())
2606            .map(|mut cand| {
2607                // Normalize the trait ref in its *own* param-env so
2608                // that consts are folded and any trivial projections
2609                // are normalized.
2610                cand.trait_ref = self
2611                    .tcx
2612                    .try_normalize_erasing_regions(
2613                        ty::TypingEnv::non_body_analysis(self.tcx, cand.impl_def_id),
2614                        Unnormalized::new_wip(cand.trait_ref),
2615                    )
2616                    .unwrap_or(cand.trait_ref);
2617                cand
2618            })
2619            .collect();
2620        impl_candidates.sort_by_key(|cand| {
2621            // When suggesting array types, sort them by the length of the array, not lexicographically (#135098)
2622            let len = if let GenericArgKind::Type(ty) = cand.trait_ref.args[0].kind()
2623                && let ty::Array(_, len) = ty.kind()
2624            {
2625                // Deprioritize suggestions for parameterized arrays.
2626                len.try_to_target_usize(self.tcx).unwrap_or(u64::MAX)
2627            } else {
2628                0
2629            };
2630
2631            (cand.similarity, len, cand.trait_ref.to_string())
2632        });
2633        let mut impl_candidates: Vec<_> =
2634            impl_candidates.into_iter().map(|cand| (cand.trait_ref, cand.impl_def_id)).collect();
2635        impl_candidates.dedup();
2636
2637        report(impl_candidates, err)
2638    }
2639
2640    fn report_similar_impl_candidates_for_root_obligation(
2641        &self,
2642        obligation: &PredicateObligation<'tcx>,
2643        trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2644        body_def_id: LocalDefId,
2645        err: &mut Diag<'_>,
2646    ) {
2647        // This is *almost* equivalent to
2648        // `obligation.cause.code().peel_derives()`, but it gives us the
2649        // trait predicate for that corresponding root obligation. This
2650        // lets us get a derived obligation from a type parameter, like
2651        // when calling `string.strip_suffix(p)` where `p` is *not* an
2652        // implementer of `Pattern<'_>`.
2653        let mut code = obligation.cause.code();
2654        let mut trait_pred = trait_predicate;
2655        let mut peeled = false;
2656        while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
2657            code = parent_code;
2658            if let Some(parent_trait_pred) = parent_trait_pred {
2659                trait_pred = parent_trait_pred;
2660                peeled = true;
2661            }
2662        }
2663        let def_id = trait_pred.def_id();
2664        // Mention *all* the `impl`s for the *top most* obligation, the
2665        // user might have meant to use one of them, if any found. We skip
2666        // auto-traits or fundamental traits that might not be exactly what
2667        // the user might expect to be presented with. Instead this is
2668        // useful for less general traits.
2669        if peeled && !self.tcx.trait_is_auto(def_id) && self.tcx.as_lang_item(def_id).is_none() {
2670            let impl_candidates = self.find_similar_impl_candidates(trait_pred);
2671            self.report_similar_impl_candidates(
2672                &impl_candidates,
2673                obligation,
2674                trait_pred,
2675                body_def_id,
2676                err,
2677                true,
2678                obligation.param_env,
2679            );
2680        }
2681    }
2682
2683    /// Gets the parent trait chain start
2684    fn get_parent_trait_ref(
2685        &self,
2686        code: &ObligationCauseCode<'tcx>,
2687    ) -> Option<(Ty<'tcx>, Option<Span>)> {
2688        match code {
2689            ObligationCauseCode::BuiltinDerived(data) => {
2690                let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2691                match self.get_parent_trait_ref(&data.parent_code) {
2692                    Some(t) => Some(t),
2693                    None => {
2694                        let ty = parent_trait_ref.skip_binder().self_ty();
2695                        let span = TyCategory::from_ty(self.tcx, ty)
2696                            .map(|(_, def_id)| self.tcx.def_span(def_id));
2697                        Some((ty, span))
2698                    }
2699                }
2700            }
2701            ObligationCauseCode::FunctionArg { parent_code, .. } => {
2702                self.get_parent_trait_ref(parent_code)
2703            }
2704            _ => None,
2705        }
2706    }
2707
2708    fn check_same_trait_different_version(
2709        &self,
2710        err: &mut Diag<'_>,
2711        trait_pred: ty::PolyTraitPredicate<'tcx>,
2712    ) -> bool {
2713        let get_trait_impls = |trait_def_id| {
2714            let mut trait_impls = ::alloc::vec::Vec::new()vec![];
2715            self.tcx.for_each_relevant_impl(
2716                trait_def_id,
2717                trait_pred.skip_binder().self_ty(),
2718                |impl_def_id| {
2719                    let impl_trait_header = self.tcx.impl_trait_header(impl_def_id);
2720                    trait_impls
2721                        .push(self.tcx.def_span(impl_trait_header.trait_ref.skip_binder().def_id));
2722                },
2723            );
2724            trait_impls
2725        };
2726        self.check_same_definition_different_crate(
2727            err,
2728            trait_pred.def_id(),
2729            self.tcx.visible_traits(),
2730            get_trait_impls,
2731            "trait",
2732        )
2733    }
2734
2735    pub fn note_two_crate_versions(
2736        &self,
2737        krate: CrateNum,
2738        sp: impl Into<MultiSpan>,
2739        err: &mut Diag<'_>,
2740    ) {
2741        let crate_name = self.tcx.crate_name(krate);
2742        let crate_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("there are multiple different versions of crate `{0}` in the dependency graph",
                crate_name))
    })format!(
2743            "there are multiple different versions of crate `{crate_name}` in the dependency graph"
2744        );
2745        err.span_note(sp, crate_msg);
2746    }
2747
2748    fn note_adt_version_mismatch(
2749        &self,
2750        err: &mut Diag<'_>,
2751        trait_pred: ty::PolyTraitPredicate<'tcx>,
2752    ) {
2753        let ty::Adt(impl_self_def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2754        else {
2755            return;
2756        };
2757
2758        let impl_self_did = impl_self_def.did();
2759
2760        // We only want to warn about different versions of a dependency.
2761        // If no dependency is involved, bail.
2762        if impl_self_did.krate == LOCAL_CRATE {
2763            return;
2764        }
2765
2766        let impl_self_path = self.comparable_path(impl_self_did);
2767        let impl_self_crate_name = self.tcx.crate_name(impl_self_did.krate);
2768        let similar_items: UnordSet<_> = self
2769            .tcx
2770            .visible_parent_map(())
2771            .items()
2772            .filter_map(|(&item, _)| {
2773                // If we found ourselves, ignore.
2774                if impl_self_did == item {
2775                    return None;
2776                }
2777                // We only want to warn about different versions of a dependency.
2778                // Ignore items from our own crate.
2779                if item.krate == LOCAL_CRATE {
2780                    return None;
2781                }
2782                // We want to warn about different versions of a dependency.
2783                // So make sure the crate names are the same.
2784                if impl_self_crate_name != self.tcx.crate_name(item.krate) {
2785                    return None;
2786                }
2787                // Filter out e.g. constructors that often have the same path
2788                // str as the relevant ADT.
2789                if !self.tcx.def_kind(item).is_adt() {
2790                    return None;
2791                }
2792                let path = self.comparable_path(item);
2793                // We don't know if our item or the one we found is the re-exported one.
2794                // Check both cases.
2795                let is_similar = path.ends_with(&impl_self_path) || impl_self_path.ends_with(&path);
2796                is_similar.then_some((item, path))
2797            })
2798            .collect();
2799
2800        let mut similar_items =
2801            similar_items.into_items().into_sorted_stable_ord_by_key(|(_, path)| path);
2802        similar_items.dedup();
2803
2804        for (similar_item, _) in similar_items {
2805            err.span_help(self.tcx.def_span(similar_item), "item with same name found");
2806            self.note_two_crate_versions(similar_item.krate, MultiSpan::new(), err);
2807        }
2808    }
2809
2810    fn check_same_name_different_path(
2811        &self,
2812        err: &mut Diag<'_>,
2813        obligation: &PredicateObligation<'tcx>,
2814        trait_pred: ty::PolyTraitPredicate<'tcx>,
2815    ) -> bool {
2816        let mut suggested = false;
2817        let trait_def_id = trait_pred.def_id();
2818        let trait_has_same_params = |other_trait_def_id: DefId| -> bool {
2819            let trait_generics = self.tcx.generics_of(trait_def_id);
2820            let other_trait_generics = self.tcx.generics_of(other_trait_def_id);
2821
2822            if trait_generics.count() != other_trait_generics.count() {
2823                return false;
2824            }
2825            trait_generics.own_params.iter().zip(other_trait_generics.own_params.iter()).all(
2826                |(a, b)| match (&a.kind, &b.kind) {
2827                    (ty::GenericParamDefKind::Lifetime, ty::GenericParamDefKind::Lifetime)
2828                    | (
2829                        ty::GenericParamDefKind::Type { .. },
2830                        ty::GenericParamDefKind::Type { .. },
2831                    )
2832                    | (
2833                        ty::GenericParamDefKind::Const { .. },
2834                        ty::GenericParamDefKind::Const { .. },
2835                    ) => true,
2836                    _ => false,
2837                },
2838            )
2839        };
2840        let trait_name = self.tcx.item_name(trait_def_id);
2841        if let Some(other_trait_def_id) = self.tcx.all_traits_including_private().find(|&def_id| {
2842            trait_def_id != def_id
2843                && trait_name == self.tcx.item_name(def_id)
2844                && trait_has_same_params(def_id)
2845                // `PointeeSized` is removed during lowering.
2846                && !self.tcx.is_lang_item(def_id, LangItem::PointeeSized)
2847                && self.predicate_must_hold_modulo_regions(&Obligation::new(
2848                    self.tcx,
2849                    obligation.cause.clone(),
2850                    obligation.param_env,
2851                    trait_pred.map_bound(|tr| ty::TraitPredicate {
2852                        trait_ref: ty::TraitRef::new(self.tcx, def_id, tr.trait_ref.args),
2853                        ..tr
2854                    }),
2855                ))
2856        }) {
2857            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` implements similarly named trait `{1}`, but not `{2}`",
                trait_pred.self_ty(),
                self.tcx.def_path_str(other_trait_def_id),
                trait_pred.print_modifiers_and_trait_path()))
    })format!(
2858                "`{}` implements similarly named trait `{}`, but not `{}`",
2859                trait_pred.self_ty(),
2860                self.tcx.def_path_str(other_trait_def_id),
2861                trait_pred.print_modifiers_and_trait_path()
2862            ));
2863            suggested = true;
2864        }
2865        suggested
2866    }
2867
2868    /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
2869    /// with the same path as `trait_ref`, a help message about a multiple different
2870    /// versions of the same crate is added to `err`. Otherwise if it implements another
2871    /// trait with the same name, a note message about a similarly named trait is added to `err`.
2872    pub fn note_different_trait_with_same_name(
2873        &self,
2874        err: &mut Diag<'_>,
2875        obligation: &PredicateObligation<'tcx>,
2876        trait_pred: ty::PolyTraitPredicate<'tcx>,
2877    ) -> bool {
2878        if self.check_same_trait_different_version(err, trait_pred) {
2879            return true;
2880        }
2881        self.check_same_name_different_path(err, obligation, trait_pred)
2882    }
2883
2884    /// Add a `::` prefix when comparing paths so that paths with just one item
2885    /// like "Foo" does not equal the end of "OtherFoo".
2886    fn comparable_path(&self, did: DefId) -> String {
2887        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("::{0}",
                self.tcx.def_path_str(did)))
    })format!("::{}", self.tcx.def_path_str(did))
2888    }
2889
2890    /// Creates a `PredicateObligation` with `new_self_ty` replacing the existing type in the
2891    /// `trait_ref`.
2892    ///
2893    /// For this to work, `new_self_ty` must have no escaping bound variables.
2894    pub(super) fn mk_trait_obligation_with_new_self_ty(
2895        &self,
2896        param_env: ty::ParamEnv<'tcx>,
2897        trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>,
2898    ) -> PredicateObligation<'tcx> {
2899        let trait_pred = trait_ref_and_ty
2900            .map_bound(|(tr, new_self_ty)| tr.with_replaced_self_ty(self.tcx, new_self_ty));
2901
2902        Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred)
2903    }
2904
2905    /// Returns `true` if the trait predicate may apply for *some* assignment
2906    /// to the type parameters.
2907    fn predicate_can_apply(
2908        &self,
2909        param_env: ty::ParamEnv<'tcx>,
2910        pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + TypeFoldable<TyCtxt<'tcx>>,
2911    ) -> bool {
2912        struct ParamToVarFolder<'a, 'tcx> {
2913            infcx: &'a InferCtxt<'tcx>,
2914            var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2915        }
2916
2917        impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ParamToVarFolder<'a, 'tcx> {
2918            fn cx(&self) -> TyCtxt<'tcx> {
2919                self.infcx.tcx
2920            }
2921
2922            // FIXME: why don't we also instantiate const and region params with infer vars
2923            // here? Because diagnostics isn't soundness critical and no one bothers to be
2924            // pedantic yet.
2925            fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2926                match ty.kind() {
2927                    ty::Param(_) => {
2928                        let infcx = self.infcx;
2929                        *self.var_map.entry(ty).or_insert_with(|| infcx.next_ty_var(DUMMY_SP))
2930                    }
2931                    // FIXME(#155345): This should automatically
2932                    // handled by type folders instead of needing to do it
2933                    // manually here.
2934                    &ty::Alias(is_rigid, alias)
2935                        if is_rigid == ty::IsRigid::Yes
2936                            && ty.has_type_flags(ty::TypeFlags::HAS_TY_PARAM) =>
2937                    {
2938                        let alias = alias.fold_with(self);
2939                        Ty::new_alias(self.cx(), ty::IsRigid::No, alias)
2940                    }
2941                    _ => ty.super_fold_with(self),
2942                }
2943            }
2944        }
2945
2946        self.probe(|_| {
2947            let cleaned_pred =
2948                pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2949
2950            let InferOk { value: cleaned_pred, .. } = self
2951                .infcx
2952                .at(&ObligationCause::dummy(), param_env)
2953                .normalize(Unnormalized::new_wip(cleaned_pred));
2954
2955            let obligation =
2956                Obligation::new(self.tcx, ObligationCause::dummy(), param_env, cleaned_pred);
2957
2958            self.predicate_may_hold(&obligation)
2959        })
2960    }
2961
2962    pub fn note_obligation_cause(
2963        &self,
2964        err: &mut Diag<'_>,
2965        obligation: &PredicateObligation<'tcx>,
2966    ) {
2967        // First, attempt to add note to this error with an async-await-specific
2968        // message, and fall back to regular note otherwise.
2969        if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2970            self.note_obligation_cause_code(
2971                obligation.cause.body_def_id,
2972                err,
2973                obligation.predicate,
2974                obligation.param_env,
2975                obligation.cause.code(),
2976                &mut ::alloc::vec::Vec::new()vec![],
2977                &mut Default::default(),
2978            );
2979            self.suggest_swapping_lhs_and_rhs(
2980                err,
2981                obligation.predicate,
2982                obligation.param_env,
2983                obligation.cause.code(),
2984            );
2985            self.suggest_borrow_for_unsized_closure_return(
2986                obligation.cause.body_def_id,
2987                err,
2988                obligation.predicate,
2989            );
2990            self.suggest_unsized_bound_if_applicable(err, obligation);
2991            if let Some(span) = err.span.primary_span()
2992                && let Some(mut diag) =
2993                    self.dcx().steal_non_err(span, StashKey::AssociatedTypeSuggestion)
2994                && let Suggestions::Enabled(ref mut s1) = err.suggestions
2995                && let Suggestions::Enabled(ref mut s2) = diag.suggestions
2996            {
2997                s1.append(s2);
2998                diag.cancel()
2999            }
3000        }
3001    }
3002
3003    pub(super) fn is_recursive_obligation(
3004        &self,
3005        obligated_types: &mut Vec<Ty<'tcx>>,
3006        cause_code: &ObligationCauseCode<'tcx>,
3007    ) -> bool {
3008        if let ObligationCauseCode::BuiltinDerived(data) = cause_code {
3009            let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3010            let self_ty = parent_trait_ref.skip_binder().self_ty();
3011            if obligated_types.iter().any(|ot| ot == &self_ty) {
3012                return true;
3013            }
3014            if let ty::Adt(def, args) = self_ty.kind()
3015                && let [arg] = &args[..]
3016                && let ty::GenericArgKind::Type(ty) = arg.kind()
3017                && let ty::Adt(inner_def, _) = ty.kind()
3018                && inner_def == def
3019            {
3020                return true;
3021            }
3022        }
3023        false
3024    }
3025
3026    fn get_standard_error_message(
3027        &self,
3028        trait_predicate: ty::PolyTraitPredicate<'tcx>,
3029        predicate_constness: Option<ty::BoundConstness>,
3030        post_message: String,
3031        long_ty_path: &mut Option<PathBuf>,
3032    ) -> String {
3033        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the trait bound `{0}` is not satisfied{1}",
                self.tcx.short_string(trait_predicate.print_with_bound_constness(predicate_constness),
                    long_ty_path), post_message))
    })format!(
3034            "the trait bound `{}` is not satisfied{post_message}",
3035            self.tcx.short_string(
3036                trait_predicate.print_with_bound_constness(predicate_constness),
3037                long_ty_path,
3038            ),
3039        )
3040    }
3041
3042    fn select_transmute_obligation_for_reporting(
3043        &self,
3044        obligation: &PredicateObligation<'tcx>,
3045        trait_predicate: ty::PolyTraitPredicate<'tcx>,
3046        root_obligation: &PredicateObligation<'tcx>,
3047    ) -> (PredicateObligation<'tcx>, ty::PolyTraitPredicate<'tcx>) {
3048        if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
3049            return (obligation.clone(), trait_predicate);
3050        }
3051
3052        let ocx = ObligationCtxt::new(self);
3053        let normalized_predicate = self.tcx.erase_and_anonymize_regions(
3054            self.tcx.instantiate_bound_regions_with_erased(trait_predicate),
3055        );
3056        let trait_ref = normalized_predicate.trait_ref;
3057
3058        let assume = ocx.normalize(
3059            &obligation.cause,
3060            obligation.param_env,
3061            Unnormalized::new_wip(trait_ref.args.const_at(2)),
3062        );
3063
3064        let Some(assume) = rustc_transmute::Assume::from_const(self.tcx, assume) else {
3065            return (obligation.clone(), trait_predicate);
3066        };
3067
3068        let is_normalized_yes = #[allow(non_exhaustive_omitted_patterns)] match rustc_transmute::TransmuteTypeEnv::new(self.tcx).is_transmutable(trait_ref.args.type_at(1),
        trait_ref.args.type_at(0), assume) {
    rustc_transmute::Answer::Yes => true,
    _ => false,
}matches!(
3069            rustc_transmute::TransmuteTypeEnv::new(self.tcx).is_transmutable(
3070                trait_ref.args.type_at(1),
3071                trait_ref.args.type_at(0),
3072                assume,
3073            ),
3074            rustc_transmute::Answer::Yes,
3075        );
3076
3077        // If the normalized check unexpectedly passes, fall back to root obligation for reporting.
3078        if is_normalized_yes
3079            && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3080                root_obligation.predicate.kind().skip_binder()
3081            && root_pred.def_id() == trait_predicate.def_id()
3082        {
3083            return (root_obligation.clone(), root_obligation.predicate.kind().rebind(root_pred));
3084        }
3085
3086        (obligation.clone(), trait_predicate)
3087    }
3088
3089    fn get_safe_transmute_error_and_reason(
3090        &self,
3091        obligation: PredicateObligation<'tcx>,
3092        trait_pred: ty::PolyTraitPredicate<'tcx>,
3093        span: Span,
3094    ) -> GetSafeTransmuteErrorAndReason {
3095        use rustc_transmute::Answer;
3096        self.probe(|_| {
3097            // We don't assemble a transmutability candidate for types that are generic
3098            // and we should have ambiguity for types that still have non-region infer.
3099            if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
3100                return GetSafeTransmuteErrorAndReason::Default;
3101            }
3102
3103            // Erase regions because layout code doesn't particularly care about regions.
3104            let trait_pred = self.tcx.erase_and_anonymize_regions(
3105                self.tcx.instantiate_bound_regions_with_erased(trait_pred),
3106            );
3107
3108            let ocx = ObligationCtxt::new(self);
3109            let assume = ocx.normalize(
3110                &obligation.cause,
3111                obligation.param_env,
3112                Unnormalized::new_wip(trait_pred.trait_ref.args.const_at(2)),
3113            );
3114
3115            let Some(assume) = rustc_transmute::Assume::from_const(self.infcx.tcx, assume) else {
3116                self.dcx().span_delayed_bug(
3117                    span,
3118                    "Unable to construct rustc_transmute::Assume where it was previously possible",
3119                );
3120                return GetSafeTransmuteErrorAndReason::Silent;
3121            };
3122
3123            let dst = trait_pred.trait_ref.args.type_at(0);
3124            let src = trait_pred.trait_ref.args.type_at(1);
3125            let err_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` cannot be safely transmuted into `{1}`",
                src, dst))
    })format!("`{src}` cannot be safely transmuted into `{dst}`");
3126
3127            match rustc_transmute::TransmuteTypeEnv::new(self.infcx.tcx)
3128                .is_transmutable(src, dst, assume)
3129            {
3130                Answer::No(reason) => {
3131                    let safe_transmute_explanation = match reason {
3132                        rustc_transmute::Reason::SrcIsNotYetSupported => {
3133                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("analyzing the transmutability of `{0}` is not yet supported",
                src))
    })format!("analyzing the transmutability of `{src}` is not yet supported")
3134                        }
3135                        rustc_transmute::Reason::DstIsNotYetSupported => {
3136                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("analyzing the transmutability of `{0}` is not yet supported",
                dst))
    })format!("analyzing the transmutability of `{dst}` is not yet supported")
3137                        }
3138                        rustc_transmute::Reason::DstIsBitIncompatible => {
3139                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("at least one value of `{0}` isn\'t a bit-valid value of `{1}`",
                src, dst))
    })format!(
3140                                "at least one value of `{src}` isn't a bit-valid value of `{dst}`"
3141                            )
3142                        }
3143                        rustc_transmute::Reason::DstUninhabited => {
3144                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is uninhabited", dst))
    })format!("`{dst}` is uninhabited")
3145                        }
3146                        rustc_transmute::Reason::DstMayHaveSafetyInvariants => {
3147                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` may carry safety invariants",
                dst))
    })format!("`{dst}` may carry safety invariants")
3148                        }
3149                        rustc_transmute::Reason::DstIsTooBig => {
3150                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the size of `{0}` is smaller than the size of `{1}`",
                src, dst))
    })format!("the size of `{src}` is smaller than the size of `{dst}`")
3151                        }
3152                        rustc_transmute::Reason::DstRefIsTooBig {
3153                            src,
3154                            src_size,
3155                            dst,
3156                            dst_size,
3157                        } => {
3158                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the size of `{0}` ({1} bytes) is smaller than that of `{2}` ({3} bytes)",
                src, src_size, dst, dst_size))
    })format!(
3159                                "the size of `{src}` ({src_size} bytes) \
3160                        is smaller than that of `{dst}` ({dst_size} bytes)"
3161                            )
3162                        }
3163                        rustc_transmute::Reason::SrcSizeOverflow => {
3164                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
                src))
    })format!(
3165                                "values of the type `{src}` are too big for the target architecture"
3166                            )
3167                        }
3168                        rustc_transmute::Reason::DstSizeOverflow => {
3169                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
                dst))
    })format!(
3170                                "values of the type `{dst}` are too big for the target architecture"
3171                            )
3172                        }
3173                        rustc_transmute::Reason::DstHasStricterAlignment {
3174                            src_min_align,
3175                            dst_min_align,
3176                        } => {
3177                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the minimum alignment of `{0}` ({1}) should be greater than that of `{2}` ({3})",
                src, src_min_align, dst, dst_min_align))
    })format!(
3178                                "the minimum alignment of `{src}` ({src_min_align}) should be \
3179                                 greater than that of `{dst}` ({dst_min_align})"
3180                            )
3181                        }
3182                        rustc_transmute::Reason::DstIsMoreUnique => {
3183                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is a shared reference, but `{1}` is a unique reference",
                src, dst))
    })format!(
3184                                "`{src}` is a shared reference, but `{dst}` is a unique reference"
3185                            )
3186                        }
3187                        // Already reported by rustc
3188                        rustc_transmute::Reason::TypeError => {
3189                            return GetSafeTransmuteErrorAndReason::Silent;
3190                        }
3191                        rustc_transmute::Reason::SrcLayoutUnknown => {
3192                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` has an unknown layout", src))
    })format!("`{src}` has an unknown layout")
3193                        }
3194                        rustc_transmute::Reason::DstLayoutUnknown => {
3195                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` has an unknown layout", dst))
    })format!("`{dst}` has an unknown layout")
3196                        }
3197                    };
3198                    GetSafeTransmuteErrorAndReason::Error {
3199                        err_msg,
3200                        safe_transmute_explanation: Some(safe_transmute_explanation),
3201                    }
3202                }
3203                // Should never get a Yes at this point! We already ran it before, and did not get a Yes.
3204                Answer::Yes => ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("Inconsistent rustc_transmute::is_transmutable(...) result, got Yes"))span_bug!(
3205                    span,
3206                    "Inconsistent rustc_transmute::is_transmutable(...) result, got Yes",
3207                ),
3208                // Reached when a different obligation (namely `Freeze`) causes the
3209                // transmutability analysis to fail. In this case, silence the
3210                // transmutability error message in favor of that more specific
3211                // error.
3212                Answer::If(_) => GetSafeTransmuteErrorAndReason::Error {
3213                    err_msg,
3214                    safe_transmute_explanation: None,
3215                },
3216            }
3217        })
3218    }
3219
3220    /// If `found_ty` is a reference that can be explicitly cast to another reference type for which
3221    /// a `From` / `TryFrom` impl exists for `self_ty`, return that type.
3222    fn find_explicit_cast_type(
3223        &self,
3224        param_env: ty::ParamEnv<'tcx>,
3225        found_ty: Ty<'tcx>,
3226        self_ty: Ty<'tcx>,
3227    ) -> Option<Ty<'tcx>> {
3228        let ty::Ref(region, inner_ty, mutbl) = *found_ty.kind() else {
3229            return None;
3230        };
3231
3232        let mut derefs = (self.autoderef_steps)(inner_ty).into_iter();
3233        derefs.next(); // skip the first one, which is inner_ty itself
3234        let deref_target = derefs.into_iter().next()?.0;
3235
3236        let cast_ty = Ty::new_ref(self.tcx, region, deref_target, mutbl);
3237
3238        let Some(from_def_id) = self.tcx.get_diagnostic_item(sym::From) else {
3239            return None;
3240        };
3241        let Some(try_from_def_id) = self.tcx.get_diagnostic_item(sym::TryFrom) else {
3242            return None;
3243        };
3244
3245        if self.has_impl_for_type(
3246            param_env,
3247            ty::TraitRef::new(
3248                self.tcx,
3249                from_def_id,
3250                self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3251            ),
3252        ) {
3253            Some(cast_ty)
3254        } else if self.has_impl_for_type(
3255            param_env,
3256            ty::TraitRef::new(
3257                self.tcx,
3258                try_from_def_id,
3259                self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3260            ),
3261        ) {
3262            Some(cast_ty)
3263        } else {
3264            None
3265        }
3266    }
3267
3268    fn has_impl_for_type(
3269        &self,
3270        param_env: ty::ParamEnv<'tcx>,
3271        trait_ref: ty::TraitRef<'tcx>,
3272    ) -> bool {
3273        let obligation = Obligation::new(
3274            self.tcx,
3275            ObligationCause::dummy(),
3276            param_env,
3277            ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive },
3278        );
3279
3280        self.predicate_must_hold_modulo_regions(&obligation)
3281    }
3282
3283    fn add_tuple_trait_message(
3284        &self,
3285        obligation_cause_code: &ObligationCauseCode<'tcx>,
3286        err: &mut Diag<'_>,
3287    ) {
3288        match obligation_cause_code {
3289            ObligationCauseCode::RustCall => {
3290                err.primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
3291            }
3292            ObligationCauseCode::WhereClause(def_id, _) if self.tcx.is_fn_trait(*def_id) => {
3293                err.code(E0059);
3294                err.primary_message(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type parameter to bare `{0}` trait must be a tuple",
                self.tcx.def_path_str(*def_id)))
    })format!(
3295                    "type parameter to bare `{}` trait must be a tuple",
3296                    self.tcx.def_path_str(*def_id)
3297                ));
3298            }
3299            _ => {}
3300        }
3301    }
3302
3303    fn try_to_add_help_message(
3304        &self,
3305        root_obligation: &PredicateObligation<'tcx>,
3306        obligation: &PredicateObligation<'tcx>,
3307        trait_predicate: ty::PolyTraitPredicate<'tcx>,
3308        err: &mut Diag<'_>,
3309        span: Span,
3310        is_fn_trait: bool,
3311        suggested: bool,
3312    ) {
3313        let body_def_id = obligation.cause.body_def_id;
3314        let span = if let ObligationCauseCode::BinOp { rhs_span, .. } = obligation.cause.code() {
3315            *rhs_span
3316        } else {
3317            span
3318        };
3319
3320        // Try to report a help message
3321        let trait_def_id = trait_predicate.def_id();
3322        if is_fn_trait
3323            && let Ok((implemented_kind, params)) = self.type_implements_fn_trait(
3324                obligation.param_env,
3325                trait_predicate.self_ty(),
3326                trait_predicate.skip_binder().polarity,
3327            )
3328        {
3329            self.add_help_message_for_fn_trait(trait_predicate, err, implemented_kind, params);
3330        } else if !trait_predicate.has_non_region_infer()
3331            && self.predicate_can_apply(obligation.param_env, trait_predicate)
3332        {
3333            // If a where-clause may be useful, remind the
3334            // user that they can add it.
3335            //
3336            // don't display an on-unimplemented note, as
3337            // these notes will often be of the form
3338            //     "the type `T` can't be frobnicated"
3339            // which is somewhat confusing.
3340            self.suggest_restricting_param_bound(
3341                err,
3342                trait_predicate,
3343                None,
3344                obligation.cause.body_def_id,
3345            );
3346        } else if trait_def_id.is_local()
3347            && self.tcx.trait_impls_of(trait_def_id).is_empty()
3348            && !self.tcx.trait_is_auto(trait_def_id)
3349            && !self.tcx.trait_is_alias(trait_def_id)
3350            && trait_predicate.polarity() == ty::PredicatePolarity::Positive
3351        {
3352            err.span_help(
3353                self.tcx.def_span(trait_def_id),
3354                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this trait has no implementations, consider adding one"))msg!("this trait has no implementations, consider adding one"),
3355            );
3356        } else if !suggested && trait_predicate.polarity() == ty::PredicatePolarity::Positive {
3357            // Can't show anything else useful, try to find similar impls.
3358            let impl_candidates = self.find_similar_impl_candidates(trait_predicate);
3359            if !self.report_similar_impl_candidates(
3360                &impl_candidates,
3361                obligation,
3362                trait_predicate,
3363                body_def_id,
3364                err,
3365                true,
3366                obligation.param_env,
3367            ) {
3368                self.report_similar_impl_candidates_for_root_obligation(
3369                    obligation,
3370                    trait_predicate,
3371                    body_def_id,
3372                    err,
3373                );
3374            }
3375
3376            self.suggest_convert_to_slice(
3377                err,
3378                obligation,
3379                trait_predicate,
3380                impl_candidates.as_slice(),
3381                span,
3382            );
3383
3384            self.suggest_tuple_wrapping(err, root_obligation, obligation);
3385        }
3386        self.suggest_shadowed_inherent_method(err, obligation, trait_predicate);
3387    }
3388
3389    fn add_help_message_for_fn_trait(
3390        &self,
3391        trait_pred: ty::PolyTraitPredicate<'tcx>,
3392        err: &mut Diag<'_>,
3393        implemented_kind: ty::ClosureKind,
3394        params: ty::Binder<'tcx, Ty<'tcx>>,
3395    ) {
3396        // If the type implements `Fn`, `FnMut`, or `FnOnce`, suppress the following
3397        // suggestion to add trait bounds for the type, since we only typically implement
3398        // these traits once.
3399
3400        // Note if the `FnMut` or `FnOnce` is less general than the trait we're trying
3401        // to implement.
3402        let selected_kind = self
3403            .tcx
3404            .fn_trait_kind_from_def_id(trait_pred.def_id())
3405            .expect("expected to map DefId to ClosureKind");
3406        if !implemented_kind.extends(selected_kind) {
3407            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` implements `{1}`, but it must implement `{2}`, which is more general",
                trait_pred.skip_binder().self_ty(), implemented_kind,
                selected_kind))
    })format!(
3408                "`{}` implements `{}`, but it must implement `{}`, which is more general",
3409                trait_pred.skip_binder().self_ty(),
3410                implemented_kind,
3411                selected_kind
3412            ));
3413        }
3414
3415        // Note any argument mismatches
3416        let ty::Tuple(given) = *params.skip_binder().kind() else {
3417            return;
3418        };
3419
3420        let expected_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
3421        let ty::Tuple(expected) = *expected_ty.kind() else {
3422            return;
3423        };
3424
3425        if expected.len() != given.len() {
3426            // Note number of types that were expected and given
3427            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected a closure taking {0} argument{1}, but one taking {2} argument{3} was given",
                given.len(), if given.len() == 1 { "" } else { "s" },
                expected.len(), if expected.len() == 1 { "" } else { "s" }))
    })format!(
3428                "expected a closure taking {} argument{}, but one taking {} argument{} was given",
3429                given.len(),
3430                pluralize!(given.len()),
3431                expected.len(),
3432                pluralize!(expected.len()),
3433            ));
3434            return;
3435        }
3436
3437        let given_ty = Ty::new_fn_ptr(
3438            self.tcx,
3439            params.rebind(self.tcx.mk_fn_sig_safe_rust_abi(given, self.tcx.types.unit)),
3440        );
3441        let expected_ty = Ty::new_fn_ptr(
3442            self.tcx,
3443            trait_pred.rebind(self.tcx.mk_fn_sig_safe_rust_abi(expected, self.tcx.types.unit)),
3444        );
3445
3446        if !self.same_type_modulo_infer(given_ty, expected_ty) {
3447            // Print type mismatch
3448            let (expected_args, given_args) = self.cmp(expected_ty, given_ty);
3449            err.note_expected_found(
3450                "a closure with signature",
3451                expected_args,
3452                "a closure with signature",
3453                given_args,
3454            );
3455        }
3456    }
3457
3458    fn report_closure_error(
3459        &self,
3460        obligation: &PredicateObligation<'tcx>,
3461        closure_def_id: DefId,
3462        found_kind: ty::ClosureKind,
3463        kind: ty::ClosureKind,
3464        trait_prefix: &'static str,
3465    ) -> Diag<'a> {
3466        let closure_span = self.tcx.def_span(closure_def_id);
3467
3468        let mut err = ClosureKindMismatch {
3469            closure_span,
3470            expected: kind,
3471            found: found_kind,
3472            cause_span: obligation.cause.span,
3473            trait_prefix,
3474            fn_once_label: None,
3475            fn_mut_label: None,
3476        };
3477
3478        // Additional context information explaining why the closure only implements
3479        // a particular trait.
3480        if let Some(typeck_results) = &self.typeck_results {
3481            let hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id.expect_local());
3482            match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
3483                (ty::ClosureKind::FnOnce, Some((span, place))) => {
3484                    err.fn_once_label = Some(ClosureFnOnceLabel {
3485                        span: *span,
3486                        place: ty::place_to_string_for_capture(self.tcx, place),
3487                        trait_prefix,
3488                    })
3489                }
3490                (ty::ClosureKind::FnMut, Some((span, place))) => {
3491                    err.fn_mut_label = Some(ClosureFnMutLabel {
3492                        span: *span,
3493                        place: ty::place_to_string_for_capture(self.tcx, place),
3494                        trait_prefix,
3495                    })
3496                }
3497                _ => {}
3498            }
3499        }
3500
3501        self.dcx().create_err(err)
3502    }
3503
3504    fn report_cyclic_signature_error(
3505        &self,
3506        obligation: &PredicateObligation<'tcx>,
3507        found_trait_ref: ty::TraitRef<'tcx>,
3508        expected_trait_ref: ty::TraitRef<'tcx>,
3509        terr: TypeError<'tcx>,
3510    ) -> Diag<'a> {
3511        let self_ty = found_trait_ref.self_ty();
3512        let (cause, terr) = if let ty::Closure(def_id, _) = *self_ty.kind() {
3513            (
3514                ObligationCause::dummy_with_span(self.tcx.def_span(def_id)),
3515                TypeError::CyclicTy(self_ty),
3516            )
3517        } else {
3518            (obligation.cause.clone(), terr)
3519        };
3520        self.report_and_explain_type_error(
3521            TypeTrace::trait_refs(&cause, expected_trait_ref, found_trait_ref),
3522            obligation.param_env,
3523            terr,
3524        )
3525    }
3526
3527    fn report_signature_mismatch_error(
3528        &self,
3529        obligation: &PredicateObligation<'tcx>,
3530        span: Span,
3531        found_trait_ref: ty::TraitRef<'tcx>,
3532        expected_trait_ref: ty::TraitRef<'tcx>,
3533    ) -> Result<Diag<'a>, ErrorGuaranteed> {
3534        let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
3535        let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
3536
3537        expected_trait_ref.self_ty().error_reported()?;
3538        let found_trait_ty = found_trait_ref.self_ty();
3539
3540        let found_did = match *found_trait_ty.kind() {
3541            ty::Closure(did, _) | ty::FnDef(did, _) | ty::Coroutine(did, ..) => Some(did),
3542            _ => None,
3543        };
3544
3545        let found_node = found_did.and_then(|did| self.tcx.hir_get_if_local(did));
3546        let found_span = found_did.and_then(|did| self.tcx.hir_span_if_local(did));
3547
3548        if !self.reported_signature_mismatch.borrow_mut().insert((span, found_span)) {
3549            // We check closures twice, with obligations flowing in different directions,
3550            // but we want to complain about them only once.
3551            return Err(self.dcx().span_delayed_bug(span, "already_reported"));
3552        }
3553
3554        let mut not_tupled = false;
3555
3556        let found = match found_trait_ref.args.type_at(1).kind() {
3557            ty::Tuple(tys) => ::alloc::vec::from_elem(ArgKind::empty(), tys.len())vec![ArgKind::empty(); tys.len()],
3558            _ => {
3559                not_tupled = true;
3560                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ArgKind::empty()]))vec![ArgKind::empty()]
3561            }
3562        };
3563
3564        let expected_ty = expected_trait_ref.args.type_at(1);
3565        let expected = match expected_ty.kind() {
3566            ty::Tuple(tys) => {
3567                tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
3568            }
3569            _ => {
3570                not_tupled = true;
3571                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ArgKind::Arg("_".to_owned(), expected_ty.to_string())]))vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())]
3572            }
3573        };
3574
3575        // If this is a `Fn` family trait and either the expected or found
3576        // is not tupled, then fall back to just a regular mismatch error.
3577        // This shouldn't be common unless manually implementing one of the
3578        // traits manually, but don't make it more confusing when it does
3579        // happen.
3580        if !self.tcx.is_lang_item(expected_trait_ref.def_id, LangItem::Coroutine) && not_tupled {
3581            return Ok(self.report_and_explain_type_error(
3582                TypeTrace::trait_refs(&obligation.cause, expected_trait_ref, found_trait_ref),
3583                obligation.param_env,
3584                ty::error::TypeError::Mismatch,
3585            ));
3586        }
3587        if found.len() != expected.len() {
3588            let (closure_span, closure_arg_span, found) = found_did
3589                .and_then(|did| {
3590                    let node = self.tcx.hir_get_if_local(did)?;
3591                    let (found_span, closure_arg_span, found) = self.get_fn_like_arguments(node)?;
3592                    Some((Some(found_span), closure_arg_span, found))
3593                })
3594                .unwrap_or((found_span, None, found));
3595
3596            // If the coroutine take a single () as its argument,
3597            // the trait argument would found the coroutine take 0 arguments,
3598            // but get_fn_like_arguments would give 1 argument.
3599            // This would result in "Expected to take 1 argument, but it takes 1 argument".
3600            // Check again to avoid this.
3601            if found.len() != expected.len() {
3602                return Ok(self.report_arg_count_mismatch(
3603                    span,
3604                    closure_span,
3605                    expected,
3606                    found,
3607                    found_trait_ty.is_closure(),
3608                    closure_arg_span,
3609                ));
3610            }
3611        }
3612        Ok(self.report_closure_arg_mismatch(
3613            span,
3614            found_span,
3615            found_trait_ref,
3616            expected_trait_ref,
3617            obligation.cause.code(),
3618            found_node,
3619            obligation.param_env,
3620        ))
3621    }
3622
3623    /// Given some node representing a fn-like thing in the HIR map,
3624    /// returns a span and `ArgKind` information that describes the
3625    /// arguments it expects. This can be supplied to
3626    /// `report_arg_count_mismatch`.
3627    pub fn get_fn_like_arguments(
3628        &self,
3629        node: Node<'_>,
3630    ) -> Option<(Span, Option<Span>, Vec<ArgKind>)> {
3631        let sm = self.tcx.sess.source_map();
3632        Some(match node {
3633            Node::Expr(&hir::Expr {
3634                kind: hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, fn_arg_span, .. }),
3635                ..
3636            }) => (
3637                fn_decl_span,
3638                fn_arg_span,
3639                self.tcx
3640                    .hir_body(body)
3641                    .params
3642                    .iter()
3643                    .map(|arg| {
3644                        if let hir::Pat { kind: hir::PatKind::Tuple(args, _), span, .. } = *arg.pat
3645                        {
3646                            Some(ArgKind::Tuple(
3647                                Some(span),
3648                                args.iter()
3649                                    .map(|pat| {
3650                                        sm.span_to_snippet(pat.span)
3651                                            .ok()
3652                                            .map(|snippet| (snippet, "_".to_owned()))
3653                                    })
3654                                    .collect::<Option<Vec<_>>>()?,
3655                            ))
3656                        } else {
3657                            let name = sm.span_to_snippet(arg.pat.span).ok()?;
3658                            Some(ArgKind::Arg(name, "_".to_owned()))
3659                        }
3660                    })
3661                    .collect::<Option<Vec<ArgKind>>>()?,
3662            ),
3663            Node::Item(&hir::Item { kind: hir::ItemKind::Fn { ref sig, .. }, .. })
3664            | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(ref sig, _), .. })
3665            | Node::TraitItem(&hir::TraitItem {
3666                kind: hir::TraitItemKind::Fn(ref sig, _), ..
3667            })
3668            | Node::ForeignItem(&hir::ForeignItem {
3669                kind: hir::ForeignItemKind::Fn(ref sig, _, _),
3670                ..
3671            }) => (
3672                sig.span,
3673                None,
3674                sig.decl
3675                    .inputs
3676                    .iter()
3677                    .map(|arg| match arg.kind {
3678                        hir::TyKind::Tup(tys) => ArgKind::Tuple(
3679                            Some(arg.span),
3680                            ::alloc::vec::from_elem(("_".to_owned(), "_".to_owned()), tys.len())vec![("_".to_owned(), "_".to_owned()); tys.len()],
3681                        ),
3682                        _ => ArgKind::empty(),
3683                    })
3684                    .collect::<Vec<ArgKind>>(),
3685            ),
3686            Node::Ctor(variant_data) => {
3687                let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| self.tcx.hir_span(id));
3688                (span, None, ::alloc::vec::from_elem(ArgKind::empty(), variant_data.fields().len())vec![ArgKind::empty(); variant_data.fields().len()])
3689            }
3690            _ => {
    ::core::panicking::panic_fmt(format_args!("non-FnLike node found: {0:?}",
            node));
}panic!("non-FnLike node found: {node:?}"),
3691        })
3692    }
3693
3694    /// Reports an error when the number of arguments needed by a
3695    /// trait match doesn't match the number that the expression
3696    /// provides.
3697    pub fn report_arg_count_mismatch(
3698        &self,
3699        span: Span,
3700        found_span: Option<Span>,
3701        expected_args: Vec<ArgKind>,
3702        found_args: Vec<ArgKind>,
3703        is_closure: bool,
3704        closure_arg_span: Option<Span>,
3705    ) -> Diag<'a> {
3706        let kind = if is_closure { "closure" } else { "function" };
3707
3708        let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
3709            let arg_length = arguments.len();
3710            let distinct = #[allow(non_exhaustive_omitted_patterns)] match other {
    &[ArgKind::Tuple(..)] => true,
    _ => false,
}matches!(other, &[ArgKind::Tuple(..)]);
3711            match (arg_length, arguments.get(0)) {
3712                (1, Some(ArgKind::Tuple(_, fields))) => {
3713                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a single {0}-tuple as argument",
                fields.len()))
    })format!("a single {}-tuple as argument", fields.len())
3714                }
3715                _ => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}argument{2}", arg_length,
                if distinct && arg_length > 1 { "distinct " } else { "" },
                if arg_length == 1 { "" } else { "s" }))
    })format!(
3716                    "{} {}argument{}",
3717                    arg_length,
3718                    if distinct && arg_length > 1 { "distinct " } else { "" },
3719                    pluralize!(arg_length)
3720                ),
3721            }
3722        };
3723
3724        let expected_str = args_str(&expected_args, &found_args);
3725        let found_str = args_str(&found_args, &expected_args);
3726
3727        let mut err = {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} is expected to take {1}, but it takes {2}",
                            kind, expected_str, found_str))
                })).with_code(E0593)
}struct_span_code_err!(
3728            self.dcx(),
3729            span,
3730            E0593,
3731            "{} is expected to take {}, but it takes {}",
3732            kind,
3733            expected_str,
3734            found_str,
3735        );
3736
3737        err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0} that takes {1}", kind,
                expected_str))
    })format!("expected {kind} that takes {expected_str}"));
3738
3739        if let Some(found_span) = found_span {
3740            err.span_label(found_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("takes {0}", found_str))
    })format!("takes {found_str}"));
3741
3742            // Suggest to take and ignore the arguments with expected_args_length `_`s if
3743            // found arguments is empty (assume the user just wants to ignore args in this case).
3744            // For example, if `expected_args_length` is 2, suggest `|_, _|`.
3745            if found_args.is_empty() && is_closure {
3746                let underscores = ::alloc::vec::from_elem("_", expected_args.len())vec!["_"; expected_args.len()].join(", ");
3747                err.span_suggestion_verbose(
3748                    closure_arg_span.unwrap_or(found_span),
3749                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider changing the closure to take and ignore the expected argument{0}",
                if expected_args.len() == 1 { "" } else { "s" }))
    })format!(
3750                        "consider changing the closure to take and ignore the expected argument{}",
3751                        pluralize!(expected_args.len())
3752                    ),
3753                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("|{0}|", underscores))
    })format!("|{underscores}|"),
3754                    Applicability::MachineApplicable,
3755                );
3756            }
3757
3758            if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
3759                if fields.len() == expected_args.len() {
3760                    let sugg = fields
3761                        .iter()
3762                        .map(|(name, _)| name.to_owned())
3763                        .collect::<Vec<String>>()
3764                        .join(", ");
3765                    err.span_suggestion_verbose(
3766                        found_span,
3767                        "change the closure to take multiple arguments instead of a single tuple",
3768                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("|{0}|", sugg))
    })format!("|{sugg}|"),
3769                        Applicability::MachineApplicable,
3770                    );
3771                }
3772            }
3773            if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..]
3774                && fields.len() == found_args.len()
3775                && is_closure
3776            {
3777                let sugg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("|({0}){1}|",
                found_args.iter().map(|arg|
                                match arg {
                                    ArgKind::Arg(name, _) => name.to_owned(),
                                    _ => "_".to_owned(),
                                }).collect::<Vec<String>>().join(", "),
                if found_args.iter().any(|arg|
                            match arg { ArgKind::Arg(_, ty) => ty != "_", _ => false, })
                    {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(": ({0})",
                                    fields.iter().map(|(_, ty)|
                                                    ty.to_owned()).collect::<Vec<String>>().join(", ")))
                        })
                } else { String::new() }))
    })format!(
3778                    "|({}){}|",
3779                    found_args
3780                        .iter()
3781                        .map(|arg| match arg {
3782                            ArgKind::Arg(name, _) => name.to_owned(),
3783                            _ => "_".to_owned(),
3784                        })
3785                        .collect::<Vec<String>>()
3786                        .join(", "),
3787                    // add type annotations if available
3788                    if found_args.iter().any(|arg| match arg {
3789                        ArgKind::Arg(_, ty) => ty != "_",
3790                        _ => false,
3791                    }) {
3792                        format!(
3793                            ": ({})",
3794                            fields
3795                                .iter()
3796                                .map(|(_, ty)| ty.to_owned())
3797                                .collect::<Vec<String>>()
3798                                .join(", ")
3799                        )
3800                    } else {
3801                        String::new()
3802                    },
3803                );
3804                err.span_suggestion_verbose(
3805                    found_span,
3806                    "change the closure to accept a tuple instead of individual arguments",
3807                    sugg,
3808                    Applicability::MachineApplicable,
3809                );
3810            }
3811        }
3812
3813        err
3814    }
3815
3816    /// Checks if the type implements one of `Fn`, `FnMut`, or `FnOnce`
3817    /// in that order, and returns the generic type corresponding to the
3818    /// argument of that trait (corresponding to the closure arguments).
3819    pub fn type_implements_fn_trait(
3820        &self,
3821        param_env: ty::ParamEnv<'tcx>,
3822        ty: ty::Binder<'tcx, Ty<'tcx>>,
3823        polarity: ty::PredicatePolarity,
3824    ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> {
3825        self.commit_if_ok(|_| {
3826            for trait_def_id in [
3827                self.tcx.lang_items().fn_trait(),
3828                self.tcx.lang_items().fn_mut_trait(),
3829                self.tcx.lang_items().fn_once_trait(),
3830            ] {
3831                let Some(trait_def_id) = trait_def_id else { continue };
3832                // Make a fresh inference variable so we can determine what the generic parameters
3833                // of the trait are.
3834                let var = self.next_ty_var(DUMMY_SP);
3835                // FIXME(const_trait_impl)
3836                let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, [ty.skip_binder(), var]);
3837                let obligation = Obligation::new(
3838                    self.tcx,
3839                    ObligationCause::dummy(),
3840                    param_env,
3841                    ty.rebind(ty::TraitPredicate { trait_ref, polarity }),
3842                );
3843                let ocx = ObligationCtxt::new(self);
3844                ocx.register_obligation(obligation);
3845                if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
3846                    return Ok((
3847                        self.tcx
3848                            .fn_trait_kind_from_def_id(trait_def_id)
3849                            .expect("expected to map DefId to ClosureKind"),
3850                        ty.rebind(self.resolve_vars_if_possible(var)),
3851                    ));
3852                }
3853            }
3854
3855            Err(())
3856        })
3857    }
3858
3859    fn report_not_const_evaluatable_error(
3860        &self,
3861        obligation: &PredicateObligation<'tcx>,
3862        span: Span,
3863    ) -> Result<Diag<'a>, ErrorGuaranteed> {
3864        if !self.tcx.features().generic_const_exprs()
3865            && !self.tcx.features().min_generic_const_args()
3866        {
3867            let guar = self
3868                .dcx()
3869                .struct_span_err(span, "constant expression depends on a generic parameter")
3870                // FIXME(const_generics): we should suggest to the user how they can resolve this
3871                // issue. However, this is currently not actually possible
3872                // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
3873                //
3874                // Note that with `feature(generic_const_exprs)` this case should not
3875                // be reachable.
3876                .with_note("this may fail depending on what value the parameter takes")
3877                .emit();
3878            return Err(guar);
3879        }
3880
3881        match obligation.predicate.kind().skip_binder() {
3882            ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => match ct.kind() {
3883                ty::ConstKind::Alias(_, alias_const) => {
3884                    let mut err =
3885                        self.dcx().struct_span_err(span, "unconstrained generic constant");
3886
3887                    let const_span = alias_const.kind.def_span(self.tcx);
3888                    let const_ty = alias_const.type_of(self.tcx).skip_norm_wip();
3889
3890                    let msg = "try adding a `where` bound";
3891                    if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(const_span) {
3892                        let code = if const_ty == self.tcx.types.usize {
3893                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("[(); {0}]:", snippet))
    })format!("[(); {snippet}]:")
3894                        } else if let ty::AliasConstKind::Anon { def_id } = alias_const.kind
3895                            && let Some(local_def_id) = def_id.as_local()
3896                            && let Some(local_body) = self.tcx.hir_maybe_body_owned_by(local_def_id)
3897                            && expr_needs_parens(local_body.value)
3898                        {
3899                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("[(); ({0}) as usize]:", snippet))
    })format!("[(); ({snippet}) as usize]:")
3900                        } else {
3901                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("[(); {0} as usize]:", snippet))
    })format!("[(); {snippet} as usize]:")
3902                        };
3903
3904                        let suggestion_def_id = if let ObligationCauseCode::CompareImplItem {
3905                            trait_item_def_id,
3906                            ..
3907                        } = obligation.cause.code()
3908                        {
3909                            trait_item_def_id.as_local()
3910                        } else {
3911                            Some(obligation.cause.body_def_id)
3912                        };
3913
3914                        if let Some(suggestion_def_id) = suggestion_def_id
3915                            && let Some(generics) = self.tcx.hir_get_generics(suggestion_def_id)
3916                        {
3917                            err.span_suggestion_verbose(
3918                                generics.tail_span_for_predicate_suggestion(),
3919                                msg,
3920                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}",
                generics.add_where_or_trailing_comma(), code))
    })format!("{} {code}", generics.add_where_or_trailing_comma()),
3921                                Applicability::MaybeIncorrect,
3922                            );
3923                        } else {
3924                            err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: where {1}", msg, code))
    })format!("{msg}: where {code}"));
3925                        };
3926                    } else {
3927                        err.help(msg);
3928                    }
3929                    Ok(err)
3930                }
3931                ty::ConstKind::Expr(_) => {
3932                    let err = self
3933                        .dcx()
3934                        .struct_span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unconstrained generic constant `{0}`",
                ct))
    })format!("unconstrained generic constant `{ct}`"));
3935                    Ok(err)
3936                }
3937                _ => {
3938                    ::rustc_middle::util::bug::bug_fmt(format_args!("const evaluatable failed for non-alias const `{0:?}`",
        ct));bug!("const evaluatable failed for non-alias const `{ct:?}`");
3939                }
3940            },
3941            _ => {
3942                ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("unexpected non-ConstEvaluatable predicate, this should not be reachable"))span_bug!(
3943                    span,
3944                    "unexpected non-ConstEvaluatable predicate, this should not be reachable"
3945                )
3946            }
3947        }
3948    }
3949}