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

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