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_middle::{bug, span_bug};
37use rustc_span::def_id::CrateNum;
38use rustc_span::{BytePos, DUMMY_SP, STDLIB_STABLE_CRATES, Span, Symbol, sym};
39use tracing::{debug, instrument};
40
41use super::suggestions::get_explanation_based_on_obligation;
42use super::{ArgKind, CandidateSimilarity, GetSafeTransmuteErrorAndReason, ImplCandidate};
43use crate::diagnostics::{
44    ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch, CoroClosureNotFn,
45};
46use crate::error_reporting::TypeErrCtxt;
47use crate::error_reporting::infer::TyCategory;
48use crate::error_reporting::traits::report_dyn_incompatibility;
49use crate::infer::{self, InferCtxt, InferCtxtExt as _};
50use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
51use crate::traits::{
52    MismatchedProjectionTypes, NormalizeExt, Obligation, ObligationCause, ObligationCauseCode,
53    ObligationCtxt, PredicateObligation, SelectionContext, SelectionError, elaborate,
54    specialization_graph,
55};
56
57impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
58    /// The `root_obligation` parameter should be the `root_obligation` field
59    /// from a `FulfillmentError`. If no `FulfillmentError` is available,
60    /// then it should be the same as `obligation`.
61    pub fn report_selection_error(
62        &self,
63        mut obligation: PredicateObligation<'tcx>,
64        root_obligation: &PredicateObligation<'tcx>,
65        error: &SelectionError<'tcx>,
66    ) -> ErrorGuaranteed {
67        let tcx = self.tcx;
68        let mut span = obligation.cause.span;
69        let mut long_ty_file = None;
70
71        let mut err = match *error {
72            SelectionError::Unimplemented => {
73                // If this obligation was generated as a result of well-formedness checking, see if we
74                // can get a better error message by performing HIR-based well-formedness checking.
75                if let ObligationCauseCode::WellFormed(Some(wf_loc)) =
76                    root_obligation.cause.code().peel_derives()
77                    && !obligation.predicate.has_non_region_infer()
78                {
79                    if let Some(cause) = self.tcx.diagnostic_hir_wf_check((
80                        tcx.erase_and_anonymize_regions(obligation.predicate),
81                        *wf_loc,
82                    )) {
83                        obligation.cause = cause.clone();
84                        span = obligation.cause.span;
85                    }
86                }
87
88                if let ObligationCauseCode::CompareImplItem {
89                    impl_item_def_id,
90                    trait_item_def_id,
91                    kind: _,
92                } = *obligation.cause.code()
93                {
94                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs:94",
                        "rustc_trait_selection::error_reporting::traits::fulfillment_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(94u32),
                        ::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");
95                    return self
96                        .report_extra_impl_obligation(
97                            span,
98                            impl_item_def_id,
99                            trait_item_def_id,
100                            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", obligation.predicate))
    })format!("`{}`", obligation.predicate),
101                        )
102                        .emit();
103                }
104
105                // Report a const-param specific error
106                if let ObligationCauseCode::ConstParam(ty) = *obligation.cause.code().peel_derives()
107                {
108                    return self.report_const_param_not_wf(ty, &obligation).emit();
109                }
110
111                let bound_predicate = obligation.predicate.kind();
112                match bound_predicate.skip_binder() {
113                    ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_predicate)) => {
114                        let leaf_trait_predicate = self.deeply_resolve_ignoring_regions(
115                            bound_predicate.rebind(trait_predicate),
116                        );
117
118                        // Let's use the root obligation as the main message, when we care about the
119                        // most general case ("X doesn't implement Pattern<'_>") over the case that
120                        // happened to fail ("char doesn't implement Fn(&mut char)").
121                        //
122                        // We rely on a few heuristics to identify cases where this root
123                        // obligation is more important than the leaf obligation:
124                        let (main_trait_predicate, main_obligation) =
125                            if let ty::PredicateKind::Clause(
126                            ty::ClauseKind::Trait(root_pred)
127                        ) = root_obligation.predicate.kind().skip_binder()
128                            && !leaf_trait_predicate.self_ty().skip_binder().has_escaping_bound_vars()
129                            && !root_pred.self_ty().has_escaping_bound_vars()
130                            // The type of the leaf predicate is (roughly) the same as the type
131                            // from the root predicate, as a proxy for "we care about the root"
132                            // FIXME: this doesn't account for trivial derefs, but works as a first
133                            // approximation.
134                            && (
135                                // `T: Trait` && `&&T: OtherTrait`, we want `OtherTrait`
136                                self.can_eq(
137                                    obligation.param_env,
138                                    leaf_trait_predicate.self_ty().skip_binder(),
139                                    root_pred.self_ty().peel_refs(),
140                                )
141                                // `&str: Iterator` && `&str: IntoIterator`, we want `IntoIterator`
142                                || self.can_eq(
143                                    obligation.param_env,
144                                    leaf_trait_predicate.self_ty().skip_binder(),
145                                    root_pred.self_ty(),
146                                )
147                            )
148                            // The leaf trait and the root trait are different, so as to avoid
149                            // talking about `&mut T: Trait` and instead remain talking about
150                            // `T: Trait` instead
151                            && leaf_trait_predicate.def_id() != root_pred.def_id()
152                            // The root trait is not `Unsize`, as to avoid talking about it in
153                            // `tests/ui/coercion/coerce-issue-49593-box-never.rs`.
154                            && !self.tcx.is_lang_item(root_pred.def_id(), LangItem::Unsize)
155                            {
156                                (
157                                    self.deeply_resolve_ignoring_regions(
158                                        root_obligation.predicate.kind().rebind(root_pred),
159                                    ),
160                                    root_obligation,
161                                )
162                            } else {
163                                (leaf_trait_predicate, &obligation)
164                            };
165
166                        if let Some(guar) = self
167                            .emit_specialized_closure_kind_error(&obligation, leaf_trait_predicate)
168                        {
169                            return guar;
170                        }
171
172                        if let Err(guar) = leaf_trait_predicate.error_reported() {
173                            return guar;
174                        }
175                        // Silence redundant errors on binding access that are already
176                        // reported on the binding definition (#56607).
177                        if let Err(guar) = self.fn_arg_obligation(&obligation) {
178                            return guar;
179                        }
180                        let (post_message, pre_message, type_def) = self
181                            .get_parent_trait_ref(obligation.cause.code())
182                            .map(|(t, s)| {
183                                let t = self.tcx.short_string(t, &mut long_ty_file);
184                                (
185                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" in `{0}`", t))
    })format!(" in `{t}`"),
186                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("within `{0}`, ", t))
    })format!("within `{t}`, "),
187                                    s.map(|s| (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("within this `{0}`", t))
    })format!("within this `{t}`"), s)),
188                                )
189                            })
190                            .unwrap_or_default();
191
192                        let CustomDiagnostic { message, label, notes, parent_label } = self
193                            .on_unimplemented_note(
194                                main_trait_predicate,
195                                main_obligation,
196                                &mut long_ty_file,
197                            );
198
199                        let have_alt_message = message.is_some() || label.is_some();
200
201                        let message = message.unwrap_or_else(|| {
202                            self.get_standard_error_message(
203                                main_trait_predicate,
204                                None,
205                                post_message,
206                                &mut long_ty_file,
207                            )
208                        });
209                        let is_try_conversion =
210                            self.is_try_conversion(span, main_trait_predicate.def_id());
211                        let is_question_mark = #[allow(non_exhaustive_omitted_patterns)] match root_obligation.cause.code().peel_derives()
    {
    ObligationCauseCode::QuestionMark => true,
    _ => false,
}matches!(
212                            root_obligation.cause.code().peel_derives(),
213                            ObligationCauseCode::QuestionMark,
214                        ) && !(self
215                            .tcx
216                            .is_diagnostic_item(sym::FromResidual, main_trait_predicate.def_id())
217                            || self.tcx.is_lang_item(main_trait_predicate.def_id(), LangItem::Try));
218                        let is_unsize =
219                            self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Unsize);
220                        let question_mark_message = "the question mark operation (`?`) implicitly \
221                                                     performs a conversion on the error value \
222                                                     using the `From` trait";
223                        let (message, notes) = if is_try_conversion {
224                            let ty = self.tcx.short_string(
225                                main_trait_predicate.skip_binder().self_ty(),
226                                &mut long_ty_file,
227                            );
228                            // We have a `-> Result<_, E1>` and `gives_E2()?`.
229                            (
230                                ::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}`"),
231                                ::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()],
232                            )
233                        } else if is_question_mark {
234                            let main_trait_predicate =
235                                self.tcx.short_string(main_trait_predicate, &mut long_ty_file);
236                            // Similar to the case above, but in this case the conversion is for a
237                            // trait object: `-> Result<_, Box<dyn Error>` and `gives_E()?` when
238                            // `E: Error` isn't met.
239                            (
240                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`?` couldn\'t convert the error: `{0}` is not satisfied",
                main_trait_predicate))
    })format!(
241                                    "`?` couldn't convert the error: `{main_trait_predicate}` is \
242                                     not satisfied",
243                                ),
244                                ::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()],
245                            )
246                        } else {
247                            (message, notes)
248                        };
249
250                        let (err_msg, safe_transmute_explanation) = if self
251                            .tcx
252                            .is_lang_item(main_trait_predicate.def_id(), LangItem::TransmuteTrait)
253                        {
254                            // Recompute the safe transmute reason and use that for the error reporting
255                            let (report_obligation, report_pred) = self
256                                .select_transmute_obligation_for_reporting(
257                                    &obligation,
258                                    main_trait_predicate,
259                                    root_obligation,
260                                );
261
262                            match self.get_safe_transmute_error_and_reason(
263                                report_obligation,
264                                report_pred,
265                                span,
266                            ) {
267                                GetSafeTransmuteErrorAndReason::Silent => {
268                                    return self
269                                        .dcx()
270                                        .span_delayed_bug(span, "silent safe transmute error");
271                                }
272                                GetSafeTransmuteErrorAndReason::Default => (message, None),
273                                GetSafeTransmuteErrorAndReason::Error {
274                                    err_msg,
275                                    safe_transmute_explanation,
276                                } => (err_msg, safe_transmute_explanation),
277                            }
278                        } else {
279                            (message, None)
280                        };
281
282                        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);
283
284                        let trait_def_id = main_trait_predicate.def_id();
285                        let leaf_trait_def_id = leaf_trait_predicate.def_id();
286                        if (self.tcx.is_diagnostic_item(sym::From, trait_def_id)
287                            || self.tcx.is_diagnostic_item(sym::TryFrom, trait_def_id))
288                            && (self.tcx.is_diagnostic_item(sym::From, leaf_trait_def_id)
289                                || self.tcx.is_diagnostic_item(sym::TryFrom, leaf_trait_def_id))
290                            && let Some(trait_ref) =
291                                leaf_trait_predicate.no_bound_vars().map(|pred| pred.trait_ref)
292                            && let Some(found_ty) =
293                                trait_ref.args.get(1).and_then(|arg| arg.as_type())
294                            && let Some(ty) =
295                                main_trait_predicate.no_bound_vars().map(|pred| pred.self_ty())
296                            && let Some(cast_ty) =
297                                self.find_explicit_cast_type(obligation.param_env, found_ty, ty)
298                        {
299                            let found_ty_str = self.tcx.short_string(found_ty, &mut long_ty_file);
300                            let cast_ty_str = self.tcx.short_string(cast_ty, &mut long_ty_file);
301
302                            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!(
303                                "consider casting the `{found_ty_str}` value to `{cast_ty_str}`",
304                            ));
305                        }
306
307                        *err.long_ty_path() = long_ty_file;
308
309                        let mut suggested = false;
310                        let mut noted_missing_impl = false;
311                        if is_try_conversion || is_question_mark {
312                            (suggested, noted_missing_impl) = self.try_conversion_context(
313                                &obligation,
314                                main_trait_predicate,
315                                &mut err,
316                            );
317                        }
318
319                        suggested |= self.detect_negative_literal(
320                            &obligation,
321                            main_trait_predicate,
322                            &mut err,
323                        );
324
325                        if let Some(ret_span) = self.return_type_span(&obligation) {
326                            if is_try_conversion {
327                                let ty = self.tcx.short_string(
328                                    main_trait_predicate.skip_binder().self_ty(),
329                                    err.long_ty_path(),
330                                );
331                                err.span_label(
332                                    ret_span,
333                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}` because of this",
                ty))
    })format!("expected `{ty}` because of this"),
334                                );
335                            } else if is_question_mark {
336                                let main_trait_predicate =
337                                    self.tcx.short_string(main_trait_predicate, err.long_ty_path());
338                                err.span_label(
339                                    ret_span,
340                                    ::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"),
341                                );
342                            }
343                        }
344
345                        if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Tuple) {
346                            self.add_tuple_trait_message(
347                                obligation.cause.code().peel_derives(),
348                                &mut err,
349                            );
350                        }
351
352                        let explanation = get_explanation_based_on_obligation(
353                            self.tcx,
354                            &obligation,
355                            leaf_trait_predicate,
356                            pre_message,
357                            err.long_ty_path(),
358                        );
359
360                        self.check_for_binding_assigned_block_without_tail_expression(
361                            &obligation,
362                            &mut err,
363                            leaf_trait_predicate,
364                        );
365                        self.suggest_add_result_as_return_type(
366                            &obligation,
367                            &mut err,
368                            leaf_trait_predicate,
369                        );
370
371                        if self.suggest_add_reference_to_arg(
372                            &obligation,
373                            &mut err,
374                            leaf_trait_predicate,
375                            have_alt_message,
376                        ) {
377                            self.note_obligation_cause(&mut err, &obligation);
378                            return err.emit();
379                        }
380
381                        let ty_span = match leaf_trait_predicate.self_ty().skip_binder().kind() {
382                            ty::Adt(def, _)
383                                if def.did().is_local()
384                                    && !self
385                                        .can_suggest_derive(&obligation, leaf_trait_predicate) =>
386                            {
387                                self.tcx.def_span(def.did())
388                            }
389                            _ => DUMMY_SP,
390                        };
391                        if let Some(s) = label {
392                            // If it has a custom `#[rustc_on_unimplemented]`
393                            // error message, let's display it as the label!
394                            err.span_label(span, s);
395                            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(_))
396                                // When the self type is a type param We don't need to "the trait
397                                // `std::marker::Sized` is not implemented for `T`" as we will point
398                                // at the type param with a label to suggest constraining it.
399                                && !self.tcx.is_diagnostic_item(sym::FromResidual, leaf_trait_predicate.def_id())
400                            // Don't say "the trait `FromResidual<Option<!>>` is
401                            // not implemented for `Result<T, E>`".
402                            {
403                                // We do this just so that the JSON output's `help` position is the
404                                // right one and not `file.rs:1:1`. The render is the same.
405                                if ty_span == DUMMY_SP {
406                                    err.help(explanation);
407                                } else {
408                                    err.span_help(ty_span, explanation);
409                                }
410                            }
411                        } else if let Some(custom_explanation) = safe_transmute_explanation {
412                            err.span_label(span, custom_explanation);
413                        } else if (explanation.len() > self.tcx.sess.diagnostic_width()
414                            || ty_span != DUMMY_SP)
415                            && !noted_missing_impl
416                        {
417                            // Really long types don't look good as span labels, instead move it
418                            // to a `help`.
419                            err.span_label(span, "unsatisfied trait bound");
420
421                            // We do this just so that the JSON output's `help` position is the
422                            // right one and not `file.rs:1:1`. The render is the same.
423                            if ty_span == DUMMY_SP {
424                                err.help(explanation);
425                            } else {
426                                err.span_help(ty_span, explanation);
427                            }
428                        } else {
429                            err.span_label(span, explanation);
430                        }
431
432                        if let ObligationCauseCode::Coercion { source, target } =
433                            *obligation.cause.code().peel_derives()
434                        {
435                            if self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Sized)
436                            {
437                                self.suggest_borrowing_for_object_cast(
438                                    &mut err,
439                                    root_obligation,
440                                    source,
441                                    target,
442                                );
443                            }
444                        }
445
446                        if let Some((msg, span)) = type_def {
447                            err.span_label(span, msg);
448                        }
449                        // `#[rustc_on_unimplemented]` notes for derivable traits (e.g. `Debug`'s
450                        // "add `#[derive(Debug)]` to `X` or manually `impl Debug for X`") duplicate
451                        // the `consider annotating X with #[derive(..)]` suggestion that
452                        // `suggest_derive` emits below, so skip them when that suggestion will be
453                        // shown. We keep the note otherwise (e.g. when a field isn't `Debug`, so
454                        // the derive can't be suggested) to avoid leaving the diagnostic without
455                        // actionable guidance.
456                        let derive_suggestion_will_be_shown = main_trait_predicate
457                            == leaf_trait_predicate
458                            && self.can_suggest_derive(&obligation, leaf_trait_predicate);
459                        if !derive_suggestion_will_be_shown {
460                            for note in notes {
461                                // If it has a custom `#[rustc_on_unimplemented]` note, let's display
462                                // it.
463                                err.note(note);
464                            }
465                        }
466                        if let Some(s) = parent_label {
467                            let body = obligation.cause.body_def_id;
468                            err.span_label(tcx.def_span(body), s);
469                        }
470
471                        self.suggest_floating_point_literal(
472                            &obligation,
473                            &mut err,
474                            leaf_trait_predicate,
475                        );
476                        self.suggest_dereferencing_index(
477                            &obligation,
478                            &mut err,
479                            leaf_trait_predicate,
480                        );
481                        suggested |=
482                            self.suggest_dereferences(&obligation, &mut err, leaf_trait_predicate)
483                                || self.suggest_remove_reference(
484                                    &obligation,
485                                    &mut err,
486                                    leaf_trait_predicate,
487                                );
488
489                        suggested |=
490                            self.suggest_fn_call(&obligation, &mut err, leaf_trait_predicate);
491                        suggested |= self.suggest_cast_to_fn_pointer(
492                            &obligation,
493                            &mut err,
494                            leaf_trait_predicate,
495                            main_trait_predicate,
496                            span,
497                        );
498
499                        suggested |= self.suggest_semicolon_removal(
500                            &obligation,
501                            &mut err,
502                            span,
503                            leaf_trait_predicate,
504                        );
505                        self.note_different_trait_with_same_name(
506                            &mut err,
507                            &obligation,
508                            leaf_trait_predicate,
509                        );
510                        self.note_adt_version_mismatch(&mut err, leaf_trait_predicate);
511                        self.suggest_remove_await(&obligation, &mut err);
512                        self.suggest_derive(&obligation, &mut err, leaf_trait_predicate);
513
514                        if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Try) {
515                            self.suggest_await_before_try(
516                                &mut err,
517                                &obligation,
518                                leaf_trait_predicate,
519                                span,
520                            );
521                        }
522
523                        if self.suggest_add_clone_to_arg(
524                            &obligation,
525                            &mut err,
526                            leaf_trait_predicate,
527                        ) {
528                            return err.emit();
529                        }
530
531                        if self.suggest_impl_trait(&mut err, &obligation, leaf_trait_predicate) {
532                            return err.emit();
533                        }
534
535                        if is_unsize {
536                            // If the obligation failed due to a missing implementation of the
537                            // `Unsize` trait, give a pointer to why that might be the case
538                            err.note(
539                                "all implementations of `Unsize` are provided \
540                                automatically by the compiler, see \
541                                <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
542                                for more information",
543                            );
544                        }
545
546                        let is_fn_trait = tcx.is_fn_trait(leaf_trait_predicate.def_id());
547                        let is_target_feature_fn = if let ty::FnDef(def_id, _) =
548                            *leaf_trait_predicate.skip_binder().self_ty().kind()
549                        {
550                            !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
551                        } else {
552                            false
553                        };
554                        if is_fn_trait && is_target_feature_fn {
555                            err.note(
556                                "`#[target_feature(..)]` functions do not implement the `Fn` traits",
557                            );
558                            err.note(
559                                "try casting the function to a `fn` pointer or wrapping it in a closure",
560                            );
561                        }
562
563                        self.note_field_shadowed_by_private_candidate_in_cause(
564                            &mut err,
565                            &obligation.cause,
566                            obligation.param_env,
567                        );
568                        self.try_to_add_help_message(
569                            &root_obligation,
570                            &obligation,
571                            leaf_trait_predicate,
572                            &mut err,
573                            span,
574                            is_fn_trait,
575                            suggested,
576                        );
577
578                        // Changing mutability doesn't make a difference to whether we have
579                        // an `Unsize` impl (Fixes ICE in #71036)
580                        if !is_unsize {
581                            self.suggest_change_mut(&obligation, &mut err, leaf_trait_predicate);
582                        }
583
584                        // If this error is due to `!: Trait` not implemented but `(): Trait` is
585                        // implemented, and fallback has occurred, then it could be due to a
586                        // variable that used to fallback to `()` now falling back to `!`. Issue a
587                        // note informing about the change in behaviour.
588                        if leaf_trait_predicate.skip_binder().self_ty().is_never()
589                            && self.diverging_fallback_has_occurred
590                        {
591                            let predicate = leaf_trait_predicate.map_bound(|trait_pred| {
592                                trait_pred.with_replaced_self_ty(self.tcx, tcx.types.unit)
593                            });
594                            let unit_obligation = obligation.with(tcx, predicate);
595                            if self.predicate_may_hold(&unit_obligation) {
596                                err.note(
597                                    "this error might have been caused by changes to \
598                                    Rust's type-inference algorithm (see issue #148922 \
599                                    <https://github.com/rust-lang/rust/issues/148922> \
600                                    for more information)",
601                                );
602                                err.help(
603                                    "you might have intended to use the type `()` here instead",
604                                );
605                            }
606                        }
607
608                        self.explain_hrtb_projection(
609                            &mut err,
610                            leaf_trait_predicate,
611                            obligation.param_env,
612                            &obligation.cause,
613                        );
614                        self.suggest_desugaring_async_fn_in_trait(&mut err, main_trait_predicate);
615
616                        // Return early if the trait is Debug or Display and the invocation
617                        // originates within a standard library macro, because the output
618                        // is otherwise overwhelming and unhelpful (see #85844 for an
619                        // example).
620
621                        let in_std_macro =
622                            match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
623                                Some(macro_def_id) => {
624                                    let crate_name = tcx.crate_name(macro_def_id.krate);
625                                    STDLIB_STABLE_CRATES.contains(&crate_name)
626                                }
627                                None => false,
628                            };
629
630                        if in_std_macro
631                            && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.get_diagnostic_name(leaf_trait_predicate.def_id())
    {
    Some(sym::Debug | sym::Display) => true,
    _ => false,
}matches!(
632                                self.tcx.get_diagnostic_name(leaf_trait_predicate.def_id()),
633                                Some(sym::Debug | sym::Display)
634                            )
635                        {
636                            return err.emit();
637                        }
638
639                        err
640                    }
641
642                    ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(clause)) => self
643                        .report_host_effect_error(
644                            bound_predicate.rebind(clause),
645                            &obligation,
646                            span,
647                        ),
648
649                    ty::PredicateKind::Subtype(predicate) => {
650                        // Errors for Subtype predicates show up as
651                        // `FulfillmentErrorCode::SubtypeError`,
652                        // not selection error.
653                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("subtype requirement gave wrong error: `{0:?}`", predicate))span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
654                    }
655
656                    ty::PredicateKind::Coerce(predicate) => {
657                        // Errors for Coerce predicates show up as
658                        // `FulfillmentErrorCode::SubtypeError`,
659                        // not selection error.
660                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("coerce requirement gave wrong error: `{0:?}`", predicate))span_bug!(span, "coerce requirement gave wrong error: `{:?}`", predicate)
661                    }
662
663                    ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(..))
664                        if self.next_trait_solver() =>
665                    {
666                        // We normalize `TypeOutlives` in the next solver, which is fallible
667                        return self.dcx().span_delayed_bug(
668                            span,
669                            "type outlives claues errored outside borrowck without any other error",
670                        );
671                    }
672                    ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(..))
673                    | ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(..)) => {
674                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("outlives clauses should not error outside borrowck. obligation: `{0:?}`",
        obligation))span_bug!(
675                            span,
676                            "outlives clauses should not error outside borrowck. obligation: `{:?}`",
677                            obligation
678                        )
679                    }
680
681                    ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) => {
682                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("projection clauses should be implied from elsewhere. obligation: `{0:?}`",
        obligation))span_bug!(
683                            span,
684                            "projection clauses should be implied from elsewhere. obligation: `{:?}`",
685                            obligation
686                        )
687                    }
688
689                    ty::PredicateKind::DynCompatible(trait_def_id) => {
690                        let violations = self.tcx.dyn_compatibility_violations(trait_def_id);
691                        let mut err = report_dyn_incompatibility(
692                            self.tcx,
693                            span,
694                            None,
695                            trait_def_id,
696                            violations,
697                        );
698                        if let hir::Node::Item(item) =
699                            self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
700                            && let hir::ItemKind::Impl(impl_) = item.kind
701                            && let None = impl_.of_trait
702                            && let hir::TyKind::TraitObject(_, tagged_ptr) = impl_.self_ty.kind
703                            && let TraitObjectSyntax::None = tagged_ptr.tag()
704                            && impl_.self_ty.span.edition().at_least_rust_2021()
705                        {
706                            // Silence the dyn-compatibility error in favor of the missing dyn on
707                            // self type error. #131051.
708                            err.downgrade_to_delayed_bug();
709                        }
710                        err
711                    }
712
713                    ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(ty)) => {
714                        let ty = self.deeply_resolve_ignoring_regions(ty);
715                        if self.next_trait_solver() {
716                            if let Err(guar) = ty.error_reported() {
717                                return guar;
718                            }
719
720                            // FIXME: we'll need a better message which takes into account
721                            // which bounds actually failed to hold.
722                            self.dcx().struct_span_err(
723                                span,
724                                ::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"),
725                            )
726                        } else {
727                            // WF predicates cannot themselves make
728                            // errors. They can only block due to
729                            // ambiguity; otherwise, they always
730                            // degenerate into other obligations
731                            // (which may fail).
732                            ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("WF predicate not satisfied for {0:?}", ty));span_bug!(span, "WF predicate not satisfied for {:?}", ty);
733                        }
734                    }
735
736                    // Errors for `ConstEvaluatable`, `ConstEquate` predicates show up as
737                    // `SelectionError::ConstEvalFailure`, not `Unimplemented`.
738                    // Ambiguous predicates should never error.
739                    // We never return `Err` when proving `UnstableFeature` goal.
740                    ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
741                    | ty::PredicateKind::ConstEquate { .. }
742                    | ty::PredicateKind::Ambiguous
743                    | ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature { .. })
744                    | ty::PredicateKind::NormalizesTo { .. }
745                    | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType { .. }) => {
746                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("Unexpected `Predicate` for `SelectionError`: `{0:?}`",
        obligation))span_bug!(
747                            span,
748                            "Unexpected `Predicate` for `SelectionError`: `{:?}`",
749                            obligation
750                        )
751                    }
752                }
753            }
754
755            SelectionError::SignatureMismatch(SignatureMismatchData {
756                found_trait_ref,
757                expected_trait_ref,
758                terr: terr @ TypeError::CyclicTy(_),
759            }) => self.report_cyclic_signature_error(
760                &obligation,
761                found_trait_ref,
762                expected_trait_ref,
763                terr,
764            ),
765            SelectionError::SignatureMismatch(SignatureMismatchData {
766                found_trait_ref,
767                expected_trait_ref,
768                terr: _,
769            }) => {
770                match self.report_signature_mismatch_error(
771                    &obligation,
772                    span,
773                    found_trait_ref,
774                    expected_trait_ref,
775                ) {
776                    Ok(err) => err,
777                    Err(guar) => return guar,
778                }
779            }
780
781            SelectionError::TraitDynIncompatible(did) => {
782                let violations = self.tcx.dyn_compatibility_violations(did);
783                report_dyn_incompatibility(self.tcx, span, None, did, violations)
784            }
785
786            SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsInfer) => {
787                ::rustc_middle::util::bug::bug_fmt(format_args!("MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"))bug!(
788                    "MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"
789                )
790            }
791            SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsParam) => {
792                match self.report_not_const_evaluatable_error(&obligation, span) {
793                    Ok(err) => err,
794                    Err(guar) => return guar,
795                }
796            }
797
798            // Already reported in the query.
799            SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(guar))
800            | SelectionError::Overflow(OverflowError::Error(guar)) => {
801                self.set_tainted_by_errors(guar);
802                return guar;
803            }
804
805            SelectionError::Overflow(_) => {
806                ::rustc_middle::util::bug::bug_fmt(format_args!("overflow should be handled before the `report_selection_error` path"));bug!("overflow should be handled before the `report_selection_error` path");
807            }
808
809            SelectionError::ConstArgHasWrongType { ct, ct_ty, expected_ty } => {
810                let expected_ty_str = self.tcx.short_string(expected_ty, &mut long_ty_file);
811                let ct_str = self.tcx.short_string(ct, &mut long_ty_file);
812                let mut diag = self.dcx().struct_span_err(
813                    span,
814                    ::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}`"),
815                );
816                diag.long_ty_path = long_ty_file;
817
818                self.note_type_err(
819                    &mut diag,
820                    &obligation.cause,
821                    None,
822                    None,
823                    TypeError::Sorts(ty::error::ExpectedFound::new(expected_ty, ct_ty)),
824                    false,
825                    None,
826                );
827                diag
828            }
829        };
830
831        self.note_obligation_cause(&mut err, &obligation);
832        err.emit()
833    }
834}
835
836impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
837    pub(super) fn apply_do_not_recommend(
838        &self,
839        obligation: &mut PredicateObligation<'tcx>,
840        root_obligation: &PredicateObligation<'tcx>,
841    ) -> bool {
842        let mut base_cause = obligation.cause.code().clone();
843        let mut applied_do_not_recommend = false;
844        loop {
845            if let ObligationCauseCode::ImplDerived(ref c) = base_cause {
846                if self.tcx.do_not_recommend_impl(c.impl_or_alias_def_id) {
847                    let code = (*c.derived.parent_code).clone();
848                    // Keep more precise spans that still point within the parent obligation,
849                    // but do not let hidden impl details move the span outside of it.
850                    if code == *root_obligation.cause.code()
851                        && root_obligation.cause.span.eq_ctxt(obligation.cause.span)
852                        && !root_obligation.cause.span.contains(obligation.cause.span)
853                    {
854                        obligation.cause.span = root_obligation.cause.span;
855                    }
856                    obligation.cause.map_code(|_| code);
857                    obligation.predicate = c.derived.parent_trait_pred.upcast(self.tcx);
858                    applied_do_not_recommend = true;
859                }
860            }
861            if let Some(parent_cause) = base_cause.parent() {
862                base_cause = parent_cause.clone();
863            } else {
864                break;
865            }
866        }
867
868        applied_do_not_recommend
869    }
870
871    fn report_host_effect_error(
872        &self,
873        clause: ty::Binder<'tcx, ty::HostEffectClause<'tcx>>,
874        main_obligation: &PredicateObligation<'tcx>,
875        span: Span,
876    ) -> Diag<'a> {
877        // FIXME(const_trait_impl): We should recompute the clause with `[const]`
878        // if it's `const`, and if it holds, explain that this bound only
879        // *conditionally* holds.
880        let trait_ref = clause.map_bound(|clause| ty::TraitClause {
881            trait_ref: clause.trait_ref,
882            polarity: ty::ClausePolarity::Positive,
883        });
884        let mut file = None;
885
886        let err_msg = self.get_standard_error_message(
887            trait_ref,
888            Some(clause.constness()),
889            String::new(),
890            &mut file,
891        );
892        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);
893        *diag.long_ty_path() = file;
894        let obligation = Obligation::new(
895            self.tcx,
896            ObligationCause::dummy(),
897            main_obligation.param_env,
898            trait_ref,
899        );
900        if !self.predicate_may_hold(&obligation) {
901            diag.downgrade_to_delayed_bug();
902        }
903
904        if let Ok(Some(ImplSource::UserDefined(impl_data))) =
905            SelectionContext::new(self).poly_select(&obligation.with(self.tcx, trait_ref))
906        {
907            let impl_did = impl_data.impl_def_id;
908            let trait_did = trait_ref.def_id();
909            let impl_span = self.tcx.def_span(impl_did);
910            let trait_name = self.tcx.item_name(trait_did);
911
912            if self.tcx.is_const_trait(trait_did) && !self.tcx.is_const_trait_impl(impl_did) {
913                if !impl_did.is_local() {
914                    diag.span_note(
915                        impl_span,
916                        ::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`"),
917                    );
918                }
919
920                if let Some(command) =
921                    {
    {
        '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())
922                        .flatten()
923                {
924                    let (_, mut format_args) = self.on_unimplemented_components(
925                        trait_ref,
926                        main_obligation,
927                        diag.long_ty_path(),
928                        false,
929                    );
930                    if let ty::Adt(def, args) = trait_ref.self_ty().skip_binder().kind() {
931                        for param in self.tcx.generics_of(def.did()).own_params.iter() {
932                            match param.kind {
933                                GenericParamDefKind::Type { .. }
934                                | GenericParamDefKind::Const { .. } => {
935                                    format_args
936                                        .generic_args
937                                        .push((param.name, args[param.index as usize].to_string()));
938                                }
939                                _ => continue,
940                            }
941                        }
942                    }
943                    let CustomDiagnostic { message, label, notes, parent_label: _ } =
944                        command.eval(None, &format_args);
945
946                    if let Some(message) = message {
947                        diag.primary_message(message);
948                    }
949                    if let Some(label) = label {
950                        diag.span_label(span, label);
951                    }
952                    for note in notes {
953                        diag.note(note);
954                    }
955                } else if let Some(impl_did) = impl_did.as_local()
956                    && let item = self.tcx.hir_expect_item(impl_did)
957                    && let hir::ItemKind::Impl(impl_) = item.kind
958                    && impl_.of_trait.is_some()
959                {
960                    // trait is const, impl is local and not const
961                    diag.span_suggestion_verbose(
962                        item.span.shrink_to_lo(),
963                        ::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`"),
964                        "const ".to_string(),
965                        Applicability::MaybeIncorrect,
966                    );
967                }
968            }
969        } else if let ty::Param(param) = trait_ref.self_ty().skip_binder().kind()
970            && let Some(generics) =
971                self.tcx.hir_node_by_def_id(main_obligation.cause.body_def_id).generics()
972        {
973            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!(
974                "[const] {}",
975                trait_ref.map_bound(|tr| tr.trait_ref).print_trait_sugared(),
976            ));
977            ty::suggest_constraining_type_param(
978                self.tcx,
979                generics,
980                &mut diag,
981                param.name.as_str(),
982                &constraint,
983                Some(trait_ref.def_id()),
984                None,
985            );
986        }
987        diag
988    }
989
990    fn emit_specialized_closure_kind_error(
991        &self,
992        obligation: &PredicateObligation<'tcx>,
993        mut trait_pred: ty::PolyTraitClause<'tcx>,
994    ) -> Option<ErrorGuaranteed> {
995        // If we end up on an `AsyncFnKindHelper` goal, try to unwrap the parent
996        // `AsyncFn*` goal.
997        if self.tcx.is_lang_item(trait_pred.def_id(), LangItem::AsyncFnKindHelper) {
998            let mut code = obligation.cause.code();
999            // Unwrap a `FunctionArg` cause, which has been refined from a derived obligation.
1000            if let ObligationCauseCode::FunctionArg { parent_code, .. } = code {
1001                code = &**parent_code;
1002            }
1003            // If we have a derived obligation, then the parent will be a `AsyncFn*` goal.
1004            if let Some((_, Some(parent))) = code.parent_with_predicate() {
1005                trait_pred = parent;
1006            }
1007        }
1008
1009        let original_self_ty = trait_pred.self_ty().skip_binder();
1010        let peeled_self_ty = original_self_ty.peel_refs();
1011
1012        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(..))
1013            && #[allow(non_exhaustive_omitted_patterns)] match peeled_self_ty.kind() {
    ty::Closure(..) => true,
    _ => false,
}matches!(peeled_self_ty.kind(), ty::Closure(..));
1014
1015        let self_ty = if is_ref_to_closure { peeled_self_ty } else { original_self_ty };
1016
1017        let (expected_kind, is_async) =
1018            if let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) {
1019                (expected_kind, false)
1020            } else if let Some(expected_kind) =
1021                self.tcx.async_fn_trait_kind_from_def_id(trait_pred.def_id())
1022            {
1023                (expected_kind, true)
1024            } else {
1025                return None;
1026            };
1027        let trait_prefix = if is_async { "Async" } else { "" };
1028
1029        let (closure_def_id, found_args, has_self_borrows) = match *self_ty.kind() {
1030            ty::Closure(def_id, args) => {
1031                (def_id, args.as_closure().sig().map_bound(|sig| sig.inputs()[0]), false)
1032            }
1033            ty::CoroutineClosure(def_id, args) => (
1034                def_id,
1035                args.as_coroutine_closure()
1036                    .coroutine_closure_sig()
1037                    .map_bound(|sig| sig.tupled_inputs_ty),
1038                !args.as_coroutine_closure().tupled_upvars_ty().is_ty_var()
1039                    && args.as_coroutine_closure().has_self_borrows(),
1040            ),
1041            _ => return None,
1042        };
1043
1044        let expected_args = trait_pred.map_bound(|trait_pred| trait_pred.trait_ref.args.type_at(1));
1045
1046        // Verify that the arguments are compatible. If the signature is
1047        // mismatched, then we have a totally different error to report.
1048        if self.enter_forall(found_args, |found_args| {
1049            self.enter_forall(expected_args, |expected_args| {
1050                !self.can_eq(obligation.param_env, expected_args, found_args)
1051            })
1052        }) {
1053            return None;
1054        }
1055
1056        let mut found_kind = self.closure_kind(self_ty);
1057        let mut kind_origin = None;
1058
1059        if found_kind.is_none()
1060            && is_ref_to_closure
1061            && !is_async
1062            && let Some(local_def_id) = closure_def_id.as_local()
1063            && let Some((inferred_kind, origin)) = (self.infer_closure_kind)(local_def_id)
1064        {
1065            found_kind = Some(inferred_kind);
1066            kind_origin = origin;
1067        }
1068
1069        if let Some(found_kind) = found_kind
1070            && !found_kind.extends(expected_kind)
1071        {
1072            let mut err = self.report_closure_error(
1073                &obligation,
1074                closure_def_id,
1075                found_kind,
1076                expected_kind,
1077                trait_prefix,
1078                kind_origin,
1079            );
1080            self.suggest_change_mut_ref_for_closure(&mut err, &obligation);
1081            self.note_obligation_cause(&mut err, &obligation);
1082            return Some(err.emit());
1083        }
1084
1085        // If the closure has captures, then perhaps the reason that the trait
1086        // is unimplemented is because async closures don't implement `Fn`/`FnMut`
1087        // if they have captures.
1088        if has_self_borrows && expected_kind != ty::ClosureKind::FnOnce {
1089            let coro_kind = match self
1090                .tcx
1091                .coroutine_kind(self.tcx.coroutine_for_closure(closure_def_id))
1092                .unwrap()
1093            {
1094                rustc_hir::CoroutineKind::Desugared(desugaring, _) => desugaring.to_string(),
1095                coro => coro.to_string(),
1096            };
1097            let mut err = self.dcx().create_err(CoroClosureNotFn {
1098                span: self.tcx.def_span(closure_def_id),
1099                kind: expected_kind.as_str(),
1100                coro_kind,
1101            });
1102            self.note_obligation_cause(&mut err, &obligation);
1103            return Some(err.emit());
1104        }
1105
1106        None
1107    }
1108
1109    fn fn_arg_obligation(
1110        &self,
1111        obligation: &PredicateObligation<'tcx>,
1112    ) -> Result<(), ErrorGuaranteed> {
1113        if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1114            && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
1115            && let arg = arg.peel_borrows()
1116            && let hir::ExprKind::Path(hir::QPath::Resolved(
1117                None,
1118                hir::Path { res: hir::def::Res::Local(hir_id), .. },
1119            )) = arg.kind
1120            && let Node::Pat(pat) = self.tcx.hir_node(*hir_id)
1121            && let Some((preds, guar)) = self.reported_trait_errors.borrow().get(&pat.span)
1122            && preds.contains(&obligation.as_goal())
1123        {
1124            return Err(*guar);
1125        }
1126        Ok(())
1127    }
1128
1129    fn detect_negative_literal(
1130        &self,
1131        obligation: &PredicateObligation<'tcx>,
1132        trait_pred: ty::PolyTraitClause<'tcx>,
1133        err: &mut Diag<'_>,
1134    ) -> bool {
1135        if let ObligationCauseCode::UnOp { hir_id, .. } = obligation.cause.code()
1136            && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1137            && let hir::ExprKind::Unary(hir::UnOp::Neg, inner) = expr.kind
1138            && let hir::ExprKind::Lit(lit) = inner.kind
1139            && let LitKind::Int(_, LitIntType::Unsuffixed) = lit.node
1140        {
1141            err.span_suggestion_verbose(
1142                lit.span.shrink_to_hi(),
1143                "consider specifying an integer type that can be negative",
1144                match trait_pred.skip_binder().self_ty().kind() {
1145                    ty::Uint(ty::UintTy::Usize) => "isize",
1146                    ty::Uint(ty::UintTy::U8) => "i8",
1147                    ty::Uint(ty::UintTy::U16) => "i16",
1148                    ty::Uint(ty::UintTy::U32) => "i32",
1149                    ty::Uint(ty::UintTy::U64) => "i64",
1150                    ty::Uint(ty::UintTy::U128) => "i128",
1151                    _ => "i64",
1152                }
1153                .to_string(),
1154                Applicability::MaybeIncorrect,
1155            );
1156            return true;
1157        }
1158        false
1159    }
1160
1161    /// When the `E` of the resulting `Result<T, E>` in an expression `foo().bar().baz()?`,
1162    /// identify those method chain sub-expressions that could or could not have been annotated
1163    /// with `?`.
1164    fn try_conversion_context(
1165        &self,
1166        obligation: &PredicateObligation<'tcx>,
1167        trait_pred: ty::PolyTraitClause<'tcx>,
1168        err: &mut Diag<'_>,
1169    ) -> (bool, bool) {
1170        let span = obligation.cause.span;
1171        /// Look for the (direct) sub-expr of `?`, and return it if it's a `.` method call.
1172        struct FindMethodSubexprOfTry {
1173            search_span: Span,
1174        }
1175        impl<'v> Visitor<'v> for FindMethodSubexprOfTry {
1176            type Result = ControlFlow<&'v hir::Expr<'v>>;
1177            fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
1178                if let hir::ExprKind::Match(expr, _arms, hir::MatchSource::TryDesugar(_)) = ex.kind
1179                    && ex.span.with_lo(ex.span.hi() - BytePos(1)).source_equal(self.search_span)
1180                    && let hir::ExprKind::Call(_, [expr, ..]) = expr.kind
1181                {
1182                    ControlFlow::Break(expr)
1183                } else {
1184                    hir::intravisit::walk_expr(self, ex)
1185                }
1186            }
1187        }
1188        let hir_id = self.tcx.local_def_id_to_hir_id(obligation.cause.body_def_id);
1189        let Some(body_id) = self.tcx.hir_node(hir_id).body_id() else { return (false, false) };
1190        let ControlFlow::Break(expr) =
1191            (FindMethodSubexprOfTry { search_span: span }).visit_body(self.tcx.hir_body(body_id))
1192        else {
1193            return (false, false);
1194        };
1195        let Some(typeck) = &self.typeck_results else {
1196            return (false, false);
1197        };
1198        let ObligationCauseCode::QuestionMark = obligation.cause.code().peel_derives() else {
1199            return (false, false);
1200        };
1201        let self_ty = trait_pred.skip_binder().self_ty();
1202        let found_ty = trait_pred.skip_binder().trait_ref.args.get(1).and_then(|a| a.as_type());
1203        let noted_missing_impl =
1204            self.note_missing_impl_for_question_mark(err, self_ty, found_ty, trait_pred);
1205
1206        let mut prev_ty = self.deeply_resolve_ignoring_regions(
1207            typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1208        );
1209
1210        // We always look at the `E` type, because that's the only one affected by `?`. If the
1211        // incorrect `Result<T, E>` is because of the `T`, we'll get an E0308 on the whole
1212        // expression, after the `?` has "unwrapped" the `T`.
1213        let get_e_type = |prev_ty: Ty<'tcx>| -> Option<Ty<'tcx>> {
1214            let ty::Adt(def, args) = prev_ty.kind() else {
1215                return None;
1216            };
1217            let Some(arg) = args.get(1) else {
1218                return None;
1219            };
1220            if !self.tcx.is_diagnostic_item(sym::Result, def.did()) {
1221                return None;
1222            }
1223            arg.as_type()
1224        };
1225
1226        let mut suggested = false;
1227        let mut chain = ::alloc::vec::Vec::new()vec![];
1228
1229        // The following logic is similar to `point_at_chain`, but that's focused on associated types
1230        let mut expr = expr;
1231        while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
1232            // Point at every method call in the chain with the `Result` type.
1233            // let foo = bar.iter().map(mapper)?;
1234            //               ------ -----------
1235            expr = rcvr_expr;
1236            chain.push((span, prev_ty));
1237
1238            let next_ty = self.deeply_resolve_ignoring_regions(
1239                typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1240            );
1241
1242            let is_diagnostic_item = |symbol: Symbol, ty: Ty<'tcx>| {
1243                let ty::Adt(def, _) = ty.kind() else {
1244                    return false;
1245                };
1246                self.tcx.is_diagnostic_item(symbol, def.did())
1247            };
1248            // For each method in the chain, see if this is `Result::map_err` or
1249            // `Option::ok_or_else` and if it is, see if the closure passed to it has an incorrect
1250            // trailing `;`.
1251            if let Some(ty) = get_e_type(prev_ty)
1252                && let Some(found_ty) = found_ty
1253                // Ideally we would instead use `FnCtxt::lookup_method_for_diagnostic` for 100%
1254                // accurate check, but we are in the wrong stage to do that and looking for
1255                // `Result::map_err` by checking the Self type and the path segment is enough.
1256                // sym::ok_or_else
1257                && (
1258                    ( // Result::map_err
1259                        path_segment.ident.name == sym::map_err
1260                            && is_diagnostic_item(sym::Result, next_ty)
1261                    ) || ( // Option::ok_or_else
1262                        path_segment.ident.name == sym::ok_or_else
1263                            && is_diagnostic_item(sym::Option, next_ty)
1264                    )
1265                )
1266                // Found `Result<_, ()>?`
1267                && let ty::Tuple(tys) = found_ty.kind()
1268                && tys.is_empty()
1269                // The current method call returns `Result<_, ()>`
1270                && self.can_eq(obligation.param_env, ty, found_ty)
1271                // There's a single argument in the method call and it is a closure
1272                && let [arg] = args
1273                && let hir::ExprKind::Closure(closure) = arg.kind
1274                // The closure has a block for its body with no tail expression
1275                && let body = self.tcx.hir_body(closure.body)
1276                && let hir::ExprKind::Block(block, _) = body.value.kind
1277                && let None = block.expr
1278                // The last statement is of a type that can be converted to the return error type
1279                && let [.., stmt] = block.stmts
1280                && let hir::StmtKind::Semi(expr) = stmt.kind
1281                && let expr_ty = self.deeply_resolve_ignoring_regions(
1282                    typeck.expr_ty_adjusted_opt(expr)
1283                        .unwrap_or(Ty::new_misc_error(self.tcx)),
1284                )
1285                && self
1286                    .infcx
1287                    .type_implements_trait(
1288                        self.tcx.get_diagnostic_item(sym::From).unwrap(),
1289                        [self_ty, expr_ty],
1290                        obligation.param_env,
1291                    )
1292                    .must_apply_modulo_regions()
1293            {
1294                suggested = true;
1295                err.span_suggestion_short(
1296                    stmt.span.with_lo(expr.span.hi()),
1297                    "remove this semicolon",
1298                    String::new(),
1299                    Applicability::MachineApplicable,
1300                );
1301            }
1302
1303            prev_ty = next_ty;
1304
1305            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1306                && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
1307                && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
1308            {
1309                let parent = self.tcx.parent_hir_node(binding.hir_id);
1310                // We've reached the root of the method call chain...
1311                if let hir::Node::LetStmt(local) = parent
1312                    && let Some(binding_expr) = local.init
1313                {
1314                    // ...and it is a binding. Get the binding creation and continue the chain.
1315                    expr = binding_expr;
1316                }
1317                if let hir::Node::Param(_param) = parent {
1318                    // ...and it is an fn argument.
1319                    break;
1320                }
1321            }
1322        }
1323        // `expr` is now the "root" expression of the method call chain, which can be any
1324        // expression kind, like a method call or a path. If this expression is `Result<T, E>` as
1325        // well, then we also point at it.
1326        prev_ty = self.deeply_resolve_ignoring_regions(
1327            typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1328        );
1329        chain.push((expr.span, prev_ty));
1330
1331        let mut prev = None;
1332        let mut iter = chain.into_iter().rev().peekable();
1333        while let Some((span, err_ty)) = iter.next() {
1334            let is_last = iter.peek().is_none();
1335            let err_ty = get_e_type(err_ty);
1336            let err_ty = match (err_ty, prev) {
1337                (Some(err_ty), Some(prev)) if !self.can_eq(obligation.param_env, err_ty, prev) => {
1338                    err_ty
1339                }
1340                (Some(err_ty), None) => err_ty,
1341                _ => {
1342                    prev = err_ty;
1343                    continue;
1344                }
1345            };
1346
1347            let implements_from = self
1348                .infcx
1349                .type_implements_trait(
1350                    self.tcx.get_diagnostic_item(sym::From).unwrap(),
1351                    [self_ty, err_ty],
1352                    obligation.param_env,
1353                )
1354                .must_apply_modulo_regions();
1355
1356            let err_ty_str = self.tcx.short_string(err_ty, err.long_ty_path());
1357            let label = if !implements_from && is_last {
1358                ::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!(
1359                    "this can't be annotated with `?` because it has type `Result<_, {err_ty_str}>`"
1360                )
1361            } else {
1362                ::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}>`")
1363            };
1364
1365            if !suggested || !implements_from {
1366                err.span_label(span, label);
1367            }
1368            prev = Some(err_ty);
1369        }
1370        (suggested, noted_missing_impl)
1371    }
1372
1373    fn note_missing_impl_for_question_mark(
1374        &self,
1375        err: &mut Diag<'_>,
1376        self_ty: Ty<'_>,
1377        found_ty: Option<Ty<'_>>,
1378        trait_pred: ty::PolyTraitClause<'tcx>,
1379    ) -> bool {
1380        match (self_ty.kind(), found_ty) {
1381            (ty::Adt(def, _), Some(ty))
1382                if let ty::Adt(found, _) = ty.kind()
1383                    && def.did().is_local()
1384                    && found.did().is_local() =>
1385            {
1386                err.span_note(
1387                    self.tcx.def_span(def.did()),
1388                    ::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}>`"),
1389                );
1390            }
1391            (ty::Adt(def, _), None) if def.did().is_local() => {
1392                let trait_path = self.tcx.short_string(
1393                    trait_pred.skip_binder().trait_ref.print_only_trait_path(),
1394                    err.long_ty_path(),
1395                );
1396                err.span_note(
1397                    self.tcx.def_span(def.did()),
1398                    ::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}`"),
1399                );
1400            }
1401            (ty::Adt(def, _), Some(ty)) if def.did().is_local() => {
1402                err.span_note(
1403                    self.tcx.def_span(def.did()),
1404                    ::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}>`"),
1405                );
1406            }
1407            (_, Some(ty))
1408                if let ty::Adt(def, _) = ty.kind()
1409                    && def.did().is_local() =>
1410            {
1411                err.span_note(
1412                    self.tcx.def_span(def.did()),
1413                    ::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}>`"),
1414                );
1415            }
1416            _ => return false,
1417        }
1418        true
1419    }
1420
1421    fn report_const_param_not_wf(
1422        &self,
1423        ty: Ty<'tcx>,
1424        obligation: &PredicateObligation<'tcx>,
1425    ) -> Diag<'a> {
1426        let def_id = obligation.cause.body_def_id;
1427        let span = self.tcx.ty_span(def_id);
1428
1429        let mut file = None;
1430        let ty_str = self.tcx.short_string(ty, &mut file);
1431        let mut diag = match ty.kind() {
1432            ty::Float(_) => {
1433                {
    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!(
1434                    self.dcx(),
1435                    span,
1436                    E0741,
1437                    "`{ty_str}` is forbidden as the type of a const generic parameter",
1438                )
1439            }
1440            ty::FnPtr(..) => {
1441                {
    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!(
1442                    self.dcx(),
1443                    span,
1444                    E0741,
1445                    "using function pointers as const generic parameters is forbidden",
1446                )
1447            }
1448            ty::RawPtr(_, _) => {
1449                {
    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!(
1450                    self.dcx(),
1451                    span,
1452                    E0741,
1453                    "using raw pointers as const generic parameters is forbidden",
1454                )
1455            }
1456            ty::Adt(def, _) => {
1457                // We should probably see if we're *allowed* to derive `ConstParamTy` on the type...
1458                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!(
1459                    self.dcx(),
1460                    span,
1461                    E0741,
1462                    "`{ty_str}` must implement `ConstParamTy` to be used as the type of a const generic parameter",
1463                );
1464                // Only suggest derive if this isn't a derived obligation,
1465                // and the struct is local.
1466                if let Some(span) = self.tcx.hir_span_if_local(def.did())
1467                    && obligation.cause.code().parent().is_none()
1468                {
1469                    if ty.is_structural_eq_shallow(self.tcx) {
1470                        diag.span_suggestion(
1471                            span.shrink_to_lo(),
1472                            ::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()),
1473                            "#[derive(ConstParamTy)]\n",
1474                            Applicability::MachineApplicable,
1475                        );
1476                    } else {
1477                        // FIXME(adt_const_params): We should check there's not already an
1478                        // overlapping `Eq`/`PartialEq` impl.
1479                        diag.span_suggestion(
1480                            span.shrink_to_lo(),
1481                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {0}",
                def.descr()))
    })format!(
1482                                "add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {}",
1483                                def.descr()
1484                            ),
1485                            "#[derive(ConstParamTy, PartialEq, Eq)]\n",
1486                            Applicability::MachineApplicable,
1487                        );
1488                    }
1489                }
1490                diag
1491            }
1492            _ => {
1493                {
    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!(
1494                    self.dcx(),
1495                    span,
1496                    E0741,
1497                    "`{ty_str}` can't be used as a const parameter type",
1498                )
1499            }
1500        };
1501        diag.long_ty_path = file;
1502
1503        let mut code = obligation.cause.code();
1504        let mut pred = obligation.predicate.as_trait_clause();
1505        while let Some((next_code, next_pred)) = code.parent_with_predicate() {
1506            if let Some(pred) = pred {
1507                self.enter_forall(pred, |pred| {
1508                    let ty = self.tcx.short_string(pred.self_ty(), diag.long_ty_path());
1509                    let trait_path = self
1510                        .tcx
1511                        .short_string(pred.print_modifiers_and_trait_path(), diag.long_ty_path());
1512                    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"));
1513                })
1514            }
1515            code = next_code;
1516            pred = next_pred;
1517        }
1518
1519        diag
1520    }
1521}
1522
1523impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
1524    fn can_match_trait(
1525        &self,
1526        param_env: ty::ParamEnv<'tcx>,
1527        goal: ty::TraitClause<'tcx>,
1528        assumption: ty::PolyTraitClause<'tcx>,
1529    ) -> bool {
1530        // Fast path
1531        if goal.polarity != assumption.polarity() {
1532            return false;
1533        }
1534
1535        let trait_assumption = self.instantiate_binder_with_fresh_vars(
1536            DUMMY_SP,
1537            infer::BoundRegionConversionTime::HigherRankedType,
1538            assumption,
1539        );
1540
1541        self.can_eq(param_env, goal.trait_ref, trait_assumption.trait_ref)
1542    }
1543
1544    fn can_match_host_effect(
1545        &self,
1546        param_env: ty::ParamEnv<'tcx>,
1547        goal: ty::HostEffectClause<'tcx>,
1548        assumption: ty::Binder<'tcx, ty::HostEffectClause<'tcx>>,
1549    ) -> bool {
1550        let assumption = self.instantiate_binder_with_fresh_vars(
1551            DUMMY_SP,
1552            infer::BoundRegionConversionTime::HigherRankedType,
1553            assumption,
1554        );
1555
1556        assumption.constness.satisfies(goal.constness)
1557            && self.can_eq(param_env, goal.trait_ref, assumption.trait_ref)
1558    }
1559
1560    fn as_host_effect_clause(
1561        predicate: ty::Predicate<'tcx>,
1562    ) -> Option<ty::Binder<'tcx, ty::HostEffectClause<'tcx>>> {
1563        predicate.as_clause().and_then(|clause| match clause.kind().skip_binder() {
1564            ty::ClauseKind::HostEffect(host_clause) => Some(clause.kind().rebind(host_clause)),
1565            _ => None,
1566        })
1567    }
1568
1569    fn can_match_projection(
1570        &self,
1571        param_env: ty::ParamEnv<'tcx>,
1572        goal: ty::ProjectionClause<'tcx>,
1573        assumption: ty::PolyProjectionClause<'tcx>,
1574    ) -> bool {
1575        let assumption = self.instantiate_binder_with_fresh_vars(
1576            DUMMY_SP,
1577            infer::BoundRegionConversionTime::HigherRankedType,
1578            assumption,
1579        );
1580
1581        self.can_eq(param_env, goal.projection_term, assumption.projection_term)
1582            && self.can_eq(param_env, goal.term, assumption.term)
1583    }
1584
1585    // returns if `cond` not occurring implies that `error` does not occur - i.e., that
1586    // `error` occurring implies that `cond` occurs.
1587    {}
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/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
                                ::tracing_core::__macro_support::Option::Some(1587u32),
                                ::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/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs:1587",
                        "rustc_trait_selection::error_reporting::traits::fulfillment_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1587u32),
                        ::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)]
1588    pub(super) fn error_implies(
1589        &self,
1590        cond: Goal<'tcx, ty::Predicate<'tcx>>,
1591        error: Goal<'tcx, ty::Predicate<'tcx>>,
1592    ) -> bool {
1593        if cond == error {
1594            return true;
1595        }
1596
1597        // FIXME: We could be smarter about this, i.e. if cond's param-env is a
1598        // subset of error's param-env. This only matters when binders will carry
1599        // predicates though, and obviously only matters for error reporting.
1600        if cond.param_env != error.param_env {
1601            return false;
1602        }
1603        let param_env = error.param_env;
1604
1605        if let Some(error) = error.predicate.as_trait_clause() {
1606            self.enter_forall(error, |error| {
1607                elaborate(self.tcx, std::iter::once(cond.predicate))
1608                    .filter_map(|implied| implied.as_trait_clause())
1609                    .any(|implied| self.can_match_trait(param_env, error, implied))
1610            })
1611        } else if let Some(error) = Self::as_host_effect_clause(error.predicate) {
1612            self.enter_forall(error, |error| {
1613                elaborate(self.tcx, std::iter::once(cond.predicate))
1614                    .filter_map(Self::as_host_effect_clause)
1615                    .any(|implied| self.can_match_host_effect(param_env, error, implied))
1616            })
1617        } else if let Some(error) = error.predicate.as_projection_clause() {
1618            self.enter_forall(error, |error| {
1619                elaborate(self.tcx, std::iter::once(cond.predicate))
1620                    .filter_map(|implied| implied.as_projection_clause())
1621                    .any(|implied| self.can_match_projection(param_env, error, implied))
1622            })
1623        } else {
1624            false
1625        }
1626    }
1627
1628    /// Whether `error`, a projection goal, only failed because the trait goal it rests on
1629    /// did: `<T as Trait>::Assoc == U` cannot hold when `T: Trait` doesn't, so an error on
1630    /// the latter says everything the former would.
1631    pub(super) fn trait_error_implies_projection_error(
1632        &self,
1633        cond: Goal<'tcx, ty::Predicate<'tcx>>,
1634        error: Goal<'tcx, ty::Predicate<'tcx>>,
1635    ) -> bool {
1636        if cond.param_env != error.param_env {
1637            return false;
1638        }
1639        let Some(error) = error.predicate.as_projection_clause() else {
1640            return false;
1641        };
1642
1643        self.enter_forall(error, |error| {
1644            if !error.projection_term.kind.is_trait_projection() {
1645                return false;
1646            }
1647            let trait_pred = ty::TraitClause {
1648                trait_ref: error.projection_term.trait_ref(self.tcx),
1649                polarity: ty::ClausePolarity::Positive,
1650            };
1651            // Elaborating is what pairs a failing `C: FnMut(..)` with the
1652            // `<C as FnOnce<..>>::Output` projection resting on it. A supertrait can hold
1653            // while `cond` fails though, so the projection is only covered if its own trait
1654            // goal is unproven too, otherwise it failed for its own reasons.
1655            elaborate(self.tcx, std::iter::once(cond.predicate))
1656                .filter_map(|implied| implied.as_trait_clause())
1657                .any(|implied| self.can_match_trait(cond.param_env, trait_pred, implied))
1658                && !self.predicate_must_hold_modulo_regions(&Obligation::new(
1659                    self.tcx,
1660                    ObligationCause::dummy(),
1661                    cond.param_env,
1662                    trait_pred,
1663                ))
1664        })
1665    }
1666
1667    {}
#[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/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1667u32),
                                    ::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)]
1668    pub(super) fn report_projection_error(
1669        &self,
1670        obligation: &PredicateObligation<'tcx>,
1671        error: &MismatchedProjectionTypes<'tcx>,
1672    ) -> ErrorGuaranteed {
1673        let predicate = self.deeply_resolve_ignoring_regions(obligation.predicate);
1674
1675        if let Err(e) = predicate.error_reported() {
1676            return e;
1677        }
1678
1679        self.probe(|_| {
1680            // try to find the mismatched types to report the error with.
1681            //
1682            // this can fail if the problem was higher-ranked, in which
1683            // cause I have no idea for a good error message.
1684            let bound_predicate = predicate.kind();
1685            let (values, err) = match bound_predicate.skip_binder() {
1686                ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
1687                    let ocx = ObligationCtxt::new(self);
1688
1689                    let data = self.instantiate_binder_with_fresh_vars(
1690                        obligation.cause.span,
1691                        infer::BoundRegionConversionTime::HigherRankedType,
1692                        bound_predicate.rebind(data),
1693                    );
1694                    let unnormalized_term = data.projection_term.to_term(self.tcx, ty::IsRigid::No);
1695                    let normalized_term = ocx.normalize(
1696                        &obligation.cause,
1697                        obligation.param_env,
1698                        Unnormalized::new_wip(unnormalized_term),
1699                    );
1700
1701                    // constrain inference variables a bit more to nested obligations from normalize so
1702                    // we can have more helpful errors.
1703                    //
1704                    // we intentionally drop errors from normalization here,
1705                    // since the normalization is just done to improve the error message.
1706                    let _ = ocx.try_evaluate_obligations();
1707
1708                    if let Err(new_err) =
1709                        ocx.eq(&obligation.cause, obligation.param_env, data.term, normalized_term)
1710                    {
1711                        (
1712                            Some((
1713                                data.projection_term,
1714                                self.deeply_resolve_ignoring_regions(normalized_term),
1715                                data.term,
1716                            )),
1717                            new_err,
1718                        )
1719                    } else {
1720                        (None, error.err)
1721                    }
1722                }
1723                _ => (None, error.err),
1724            };
1725
1726            let mut file = None;
1727            let (msg, mut span, mut closure_span) = values
1728                .and_then(|(predicate, normalized_term, expected_term)| {
1729                    self.maybe_detailed_projection_msg(
1730                        obligation.cause.span,
1731                        predicate,
1732                        normalized_term,
1733                        expected_term,
1734                        &mut file,
1735                    )
1736                })
1737                .unwrap_or_else(|| {
1738                    (
1739                        with_forced_trimmed_paths!(format!(
1740                            "type mismatch resolving `{}`",
1741                            self.tcx.short_string(
1742                                self.deeply_resolve_ignoring_regions(predicate),
1743                                &mut file
1744                            ),
1745                        )),
1746                        obligation.cause.span,
1747                        None,
1748                    )
1749                });
1750
1751            // When the obligation comes from a closure arg and the projection isn't FnOnceOutput
1752            // (which maybe_detailed_projection_msg handles via self_ty), point at the closure's
1753            // return expression and label the closure declaration.
1754            if closure_span.is_none()
1755                && let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1756                && let Node::Expr(arg_expr) = self.tcx.hir_node(*arg_hir_id)
1757                && let hir::ExprKind::Closure(closure) = arg_expr.kind
1758                && closure.kind == hir::ClosureKind::Closure
1759            {
1760                let body = self.tcx.hir_body(closure.body);
1761                let ret_span = match body.value.kind {
1762                    hir::ExprKind::Block(hir::Block { expr: Some(expr), .. }, _) => expr.span,
1763                    hir::ExprKind::Block(hir::Block { expr: None, stmts: [.., last], .. }, _) => {
1764                        last.span
1765                    }
1766                    _ => body.value.span,
1767                };
1768                if !closure.fn_decl_span.overlaps(ret_span) {
1769                    closure_span = Some(closure.fn_decl_span);
1770                    span = ret_span;
1771                }
1772            }
1773
1774            let mut diag = struct_span_code_err!(self.dcx(), span, E0271, "{msg}");
1775            *diag.long_ty_path() = file;
1776            let mut mention_bounds = true;
1777            if let Some(span) = closure_span {
1778                if let Some((_, _, expected_ty)) = values
1779                    && let Some(expected_ty) = expected_ty.as_type()
1780                    && let ty::Closure(def_id, _) = expected_ty.kind()
1781                    && self.tcx.def_span(*def_id).overlaps(span)
1782                    && let ObligationCauseCode::FunctionArg { parent_code, arg_hir_id, .. } =
1783                        obligation.cause.code()
1784                    && let ObligationCauseCode::WhereClauseInExpr(def_id, span, _, _)
1785                    | ObligationCauseCode::WhereClause(def_id, span) = &**parent_code
1786                {
1787                    // We have a trait bound for a closure to return itself, like
1788                    // `T: FnOnce() -> T`. This is nonsensical, but as far as the type system is
1789                    // concerned, valid. This is quite an edge case, but lets produce a reasonable
1790                    // diagnostic even in the face of an unreasonable user :)
1791                    let mut multispan: MultiSpan = (*span).into();
1792                    multispan.push_span_label(*span, "this requires the closure to return itself");
1793                    if let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) {
1794                        multispan
1795                            .push_span_label(arg.span, "this closure would have to return itself");
1796                    }
1797                    let in_the_item = match self.tcx.opt_item_name(*def_id) {
1798                        Some(name) => format!("in `{name}`"),
1799                        None => String::new(),
1800                    };
1801                    diag.span_note(
1802                        multispan,
1803                        format!(
1804                            "a bound {in_the_item} requires that a closure return itself, which is \
1805                             not possible",
1806                        ),
1807                    );
1808                    mention_bounds = false;
1809                } else {
1810                    // Mark the closure decl so that it is seen even if we are pointing at the
1811                    // return type or expression.
1812                    //
1813                    // error[E0271]: expected `{closure@foo.rs:41:16}` to be a closure that returns
1814                    //               `Unit3`, but it returns `Unit4`
1815                    //   --> $DIR/foo.rs:43:17
1816                    //    |
1817                    // LL |     let v = Unit2.m(
1818                    //    |                   - required by a bound introduced by this call
1819                    // ...
1820                    // LL |             f: |x| {
1821                    //    |                --- /* this span */
1822                    // LL |                 drop(x);
1823                    // LL |                 Unit4
1824                    //    |                 ^^^^^ expected `Unit3`, found `Unit4`
1825                    //    |
1826                    diag.span_label(span, "this closure");
1827                    if !span.overlaps(obligation.cause.span) {
1828                        // Point at the binding corresponding to the closure where it is used.
1829                        diag.span_label(obligation.cause.span, "closure used here");
1830                    }
1831                }
1832            }
1833
1834            let secondary_span = self.probe(|_| {
1835                let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
1836                    predicate.kind().skip_binder()
1837                else {
1838                    return None;
1839                };
1840                if !proj.projection_term.kind.is_trait_projection() {
1841                    return None;
1842                }
1843
1844                let trait_ref = self.enter_forall_and_leak_universe(
1845                    predicate.kind().rebind(proj.projection_term.trait_ref(self.tcx)),
1846                );
1847                let Ok(Some(ImplSource::UserDefined(impl_data))) =
1848                    SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref))
1849                else {
1850                    return None;
1851                };
1852
1853                let Ok(node) =
1854                    specialization_graph::assoc_def(self.tcx, impl_data.impl_def_id, proj.def_id())
1855                else {
1856                    return None;
1857                };
1858
1859                if !node.is_final() {
1860                    return None;
1861                }
1862
1863                match self.tcx.hir_get_if_local(node.item.def_id) {
1864                    Some(
1865                        hir::Node::TraitItem(hir::TraitItem {
1866                            kind: hir::TraitItemKind::Type(_, Some(ty)),
1867                            ..
1868                        })
1869                        | hir::Node::ImplItem(hir::ImplItem {
1870                            kind: hir::ImplItemKind::Type(ty),
1871                            ..
1872                        }),
1873                    ) => Some((
1874                        ty.span,
1875                        with_forced_trimmed_paths!(Cow::from(format!(
1876                            "type mismatch resolving `{}`",
1877                            self.tcx.short_string(
1878                                self.deeply_resolve_ignoring_regions(predicate),
1879                                diag.long_ty_path()
1880                            ),
1881                        ))),
1882                        true,
1883                    )),
1884                    _ => None,
1885                }
1886            });
1887
1888            self.note_type_err(
1889                &mut diag,
1890                &obligation.cause,
1891                secondary_span,
1892                values.map(|(_, normalized_ty, expected_ty)| {
1893                    obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(
1894                        expected_ty,
1895                        normalized_ty,
1896                    )))
1897                }),
1898                err,
1899                false,
1900                Some(span),
1901            );
1902            if mention_bounds {
1903                self.note_obligation_cause(&mut diag, obligation);
1904            }
1905            diag.emit()
1906        })
1907    }
1908
1909    fn maybe_detailed_projection_msg(
1910        &self,
1911        mut span: Span,
1912        projection_term: ty::AliasTerm<'tcx>,
1913        normalized_ty: ty::Term<'tcx>,
1914        expected_ty: ty::Term<'tcx>,
1915        long_ty_path: &mut Option<PathBuf>,
1916    ) -> Option<(String, Span, Option<Span>)> {
1917        if !projection_term.kind.is_trait_projection() {
1918            return None;
1919        }
1920
1921        let projection_def_id = projection_term.expect_projection_def_id();
1922        let trait_def_id = projection_term.trait_def_id(self.tcx);
1923        let self_ty = projection_term.self_ty();
1924
1925        {
    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! {
1926            if self.tcx.is_lang_item(projection_def_id, LangItem::FnOnceOutput) {
1927                let (span, closure_span) = if let ty::Closure(def_id, _) = *self_ty.kind() {
1928                    let def_span = self.tcx.def_span(def_id);
1929                    if let Some(local_def_id) = def_id.as_local()
1930                        && let node = self.tcx.hir_node_by_def_id(local_def_id)
1931                        && let Some(fn_decl) = node.fn_decl()
1932                        && let Some(id) = node.body_id()
1933                    {
1934                        span = match fn_decl.output {
1935                            hir::FnRetTy::Return(ty) => ty.span,
1936                            hir::FnRetTy::DefaultReturn(_) => {
1937                                let body = self.tcx.hir_body(id);
1938                                match body.value.kind {
1939                                    hir::ExprKind::Block(
1940                                        hir::Block { expr: Some(expr), .. },
1941                                        _,
1942                                    ) => expr.span,
1943                                    hir::ExprKind::Block(
1944                                        hir::Block {
1945                                            expr: None, stmts: [.., last], ..
1946                                        },
1947                                        _,
1948                                    ) => last.span,
1949                                    _ => body.value.span,
1950                                }
1951                            }
1952                        };
1953                    }
1954                    (span, Some(def_span))
1955                } else {
1956                    (span, None)
1957                };
1958                let item = match self_ty.kind() {
1959                    ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
1960                    _ => self.tcx.short_string(self_ty, long_ty_path),
1961                };
1962                let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1963                let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1964                Some((format!(
1965                    "expected `{item}` to return `{expected_ty}`, but it returns `{normalized_ty}`",
1966                ), span, closure_span))
1967            } else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
1968                let self_ty = self.tcx.short_string(self_ty, long_ty_path);
1969                let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1970                let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1971                Some((format!(
1972                    "expected `{self_ty}` to be a future that resolves to `{expected_ty}`, but it \
1973                     resolves to `{normalized_ty}`"
1974                ), span, None))
1975            } else if Some(trait_def_id) == self.tcx.get_diagnostic_item(sym::Iterator) {
1976                let self_ty = self.tcx.short_string(self_ty, long_ty_path);
1977                let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1978                let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1979                Some((format!(
1980                    "expected `{self_ty}` to be an iterator that yields `{expected_ty}`, but it \
1981                     yields `{normalized_ty}`"
1982                ), span, None))
1983            } else {
1984                None
1985            }
1986        }
1987    }
1988
1989    pub fn fuzzy_match_tys(
1990        &self,
1991        mut a: Ty<'tcx>,
1992        mut b: Ty<'tcx>,
1993        ignoring_lifetimes: bool,
1994    ) -> Option<CandidateSimilarity> {
1995        /// returns the fuzzy category of a given type, or None
1996        /// if the type can be equated to any type.
1997        fn type_category(tcx: TyCtxt<'_>, t: Ty<'_>) -> Option<u32> {
1998            match t.kind() {
1999                ty::Bool => Some(0),
2000                ty::Char => Some(1),
2001                ty::Str => Some(2),
2002                ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => Some(2),
2003                ty::Int(..)
2004                | ty::Uint(..)
2005                | ty::Float(..)
2006                | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) => Some(4),
2007                ty::Ref(..) | ty::RawPtr(..) => Some(5),
2008                ty::Array(..) | ty::Slice(..) => Some(6),
2009                ty::FnDef(..) | ty::FnPtr(..) => Some(7),
2010                ty::Dynamic(..) => Some(8),
2011                ty::Closure(..) => Some(9),
2012                ty::Tuple(..) => Some(10),
2013                ty::Param(..) => Some(11),
2014                ty::Alias(_, ty::AliasTy { kind: ty::Projection { .. }, .. }) => Some(12),
2015                ty::Alias(_, ty::AliasTy { kind: ty::Inherent { .. }, .. }) => Some(13),
2016                ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => Some(14),
2017                ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) => Some(15),
2018                ty::Never => Some(16),
2019                ty::Adt(..) => Some(17),
2020                ty::Coroutine(..) => Some(18),
2021                ty::Foreign(..) => Some(19),
2022                ty::CoroutineWitness(..) => Some(20),
2023                ty::CoroutineClosure(..) => Some(21),
2024                ty::Pat(..) => Some(22),
2025                ty::UnsafeBinder(..) => Some(23),
2026                ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
2027            }
2028        }
2029
2030        let strip_references = |mut t: Ty<'tcx>| -> Ty<'tcx> {
2031            loop {
2032                match t.kind() {
2033                    ty::Ref(_, inner, _) | ty::RawPtr(inner, _) => t = *inner,
2034                    _ => break t,
2035                }
2036            }
2037        };
2038
2039        if !ignoring_lifetimes {
2040            a = strip_references(a);
2041            b = strip_references(b);
2042        }
2043
2044        let cat_a = type_category(self.tcx, a)?;
2045        let cat_b = type_category(self.tcx, b)?;
2046        if a == b {
2047            Some(CandidateSimilarity::Exact { ignoring_lifetimes })
2048        } else if cat_a == cat_b {
2049            match (a.kind(), b.kind()) {
2050                (ty::Adt(def_a, _), ty::Adt(def_b, _)) => def_a == def_b,
2051                (ty::Foreign(def_a), ty::Foreign(def_b)) => def_a == def_b,
2052                // Matching on references results in a lot of unhelpful
2053                // suggestions, so let's just not do that for now.
2054                //
2055                // We still upgrade successful matches to `ignoring_lifetimes: true`
2056                // to prioritize that impl.
2057                (ty::Ref(..) | ty::RawPtr(..), ty::Ref(..) | ty::RawPtr(..)) => {
2058                    self.fuzzy_match_tys(a, b, true).is_some()
2059                }
2060                _ => true,
2061            }
2062            .then_some(CandidateSimilarity::Fuzzy { ignoring_lifetimes })
2063        } else if ignoring_lifetimes {
2064            None
2065        } else {
2066            self.fuzzy_match_tys(a, b, true)
2067        }
2068    }
2069
2070    pub(super) fn describe_closure(&self, kind: hir::ClosureKind) -> &'static str {
2071        match kind {
2072            hir::ClosureKind::Closure => "a closure",
2073            hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => "a coroutine",
2074            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2075                hir::CoroutineDesugaring::Async,
2076                hir::CoroutineSource::Block,
2077            )) => "an async block",
2078            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2079                hir::CoroutineDesugaring::Async,
2080                hir::CoroutineSource::Fn,
2081            )) => "an async function",
2082            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2083                hir::CoroutineDesugaring::Async,
2084                hir::CoroutineSource::Closure,
2085            ))
2086            | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
2087                "an async closure"
2088            }
2089            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2090                hir::CoroutineDesugaring::AsyncGen,
2091                hir::CoroutineSource::Block,
2092            )) => "an async gen block",
2093            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2094                hir::CoroutineDesugaring::AsyncGen,
2095                hir::CoroutineSource::Fn,
2096            )) => "an async gen function",
2097            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2098                hir::CoroutineDesugaring::AsyncGen,
2099                hir::CoroutineSource::Closure,
2100            ))
2101            | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
2102                "an async gen closure"
2103            }
2104            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2105                hir::CoroutineDesugaring::Gen,
2106                hir::CoroutineSource::Block,
2107            )) => "a gen block",
2108            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2109                hir::CoroutineDesugaring::Gen,
2110                hir::CoroutineSource::Fn,
2111            )) => "a gen function",
2112            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2113                hir::CoroutineDesugaring::Gen,
2114                hir::CoroutineSource::Closure,
2115            ))
2116            | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => "a gen closure",
2117        }
2118    }
2119
2120    pub(super) fn find_similar_impl_candidates(
2121        &self,
2122        trait_pred: ty::PolyTraitClause<'tcx>,
2123    ) -> Vec<ImplCandidate<'tcx>> {
2124        let mut candidates: Vec<_> = self
2125            .tcx
2126            .all_impls(trait_pred.def_id())
2127            .filter_map(|def_id| {
2128                let imp = self.tcx.impl_trait_header(def_id);
2129                if imp.polarity != ty::ImplPolarity::Positive
2130                    || !self.tcx.is_user_visible_dep(def_id.krate)
2131                {
2132                    return None;
2133                }
2134                let imp = imp.trait_ref.skip_binder();
2135
2136                self.fuzzy_match_tys(trait_pred.skip_binder().self_ty(), imp.self_ty(), false).map(
2137                    |similarity| ImplCandidate { trait_ref: imp, similarity, impl_def_id: def_id },
2138                )
2139            })
2140            .collect();
2141        if candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
    CandidateSimilarity::Exact { .. } => true,
    _ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. })) {
2142            // If any of the candidates is a perfect match, we don't want to show all of them.
2143            // This is particularly relevant for the case of numeric types (as they all have the
2144            // same category).
2145            candidates.retain(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
    CandidateSimilarity::Exact { .. } => true,
    _ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. }));
2146        }
2147        candidates
2148    }
2149
2150    pub(super) fn report_similar_impl_candidates(
2151        &self,
2152        impl_candidates: &[ImplCandidate<'tcx>],
2153        obligation: &PredicateObligation<'tcx>,
2154        trait_pred: ty::PolyTraitClause<'tcx>,
2155        body_def_id: LocalDefId,
2156        err: &mut Diag<'_>,
2157        other: bool,
2158        param_env: ty::ParamEnv<'tcx>,
2159    ) -> bool {
2160        let parent_map = self.tcx.visible_parent_map(());
2161        let alternative_candidates = |def_id: DefId| {
2162            let mut impl_candidates: Vec<_> = self
2163                .tcx
2164                .all_impls(def_id)
2165                // ignore `do_not_recommend` items
2166                .filter(|def_id| !self.tcx.do_not_recommend_impl(*def_id))
2167                // Ignore automatically derived impls and `!Trait` impls.
2168                .map(|def_id| (self.tcx.impl_trait_header(def_id), def_id))
2169                .filter_map(|(header, def_id)| {
2170                    (header.polarity == ty::ImplPolarity::Positive
2171                        || self.tcx.is_automatically_derived(def_id))
2172                    .then(|| (header.trait_ref.instantiate_identity().skip_norm_wip(), def_id))
2173                })
2174                .filter(|(trait_ref, _)| {
2175                    let self_ty = trait_ref.self_ty();
2176                    // Avoid mentioning type parameters.
2177                    if let ty::Param(_) = self_ty.kind() {
2178                        false
2179                    }
2180                    // Avoid mentioning types that are private to another crate
2181                    else if let ty::Adt(def, _) = self_ty.peel_refs().kind() {
2182                        // FIXME(compiler-errors): This could be generalized, both to
2183                        // be more granular, and probably look past other `#[fundamental]`
2184                        // types, too.
2185                        let mut did = def.did();
2186                        if self.tcx.visibility(did).is_accessible_from(body_def_id, self.tcx) {
2187                            // don't suggest foreign `#[doc(hidden)]` types
2188                            if !did.is_local() {
2189                                let mut previously_seen_dids: FxHashSet<DefId> = Default::default();
2190                                previously_seen_dids.insert(did);
2191                                while let Some(&parent) = parent_map.get(&did)
2192                                    && let hash_set::Entry::Vacant(v) =
2193                                        previously_seen_dids.entry(parent)
2194                                {
2195                                    if self.tcx.is_doc_hidden(did) {
2196                                        return false;
2197                                    }
2198                                    v.insert();
2199                                    did = parent;
2200                                }
2201                            }
2202                            true
2203                        } else {
2204                            false
2205                        }
2206                    } else {
2207                        true
2208                    }
2209                })
2210                .collect();
2211
2212            impl_candidates.sort_by_key(|(tr, _)| tr.to_string());
2213            impl_candidates.dedup();
2214            impl_candidates
2215        };
2216
2217        if let [single] = &impl_candidates {
2218            let self_ty = trait_pred.skip_binder().self_ty();
2219            if !self_ty.has_escaping_bound_vars() {
2220                let self_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
2221                if let ty::Ref(_, inner_ty, _) = self_ty.kind()
2222                    && self.can_eq(param_env, single.trait_ref.self_ty(), *inner_ty)
2223                    && !self.where_clause_expr_matches_failed_self_ty(obligation, self_ty)
2224                {
2225                    // Avoid pointing at a nearby impl like `String: Borrow<str>` when the
2226                    // failing obligation comes from something nested inside an enclosing call
2227                    // expression such as `foo(&[String::from("a")])`.
2228                    return true;
2229                }
2230            }
2231
2232            // If we have a single implementation, try to unify it with the trait ref
2233            // that failed. This should uncover a better hint for what *is* implemented.
2234            if self.probe(|_| {
2235                let ocx = ObligationCtxt::new(self);
2236
2237                self.enter_forall(trait_pred, |obligation_trait_ref| {
2238                    let impl_args = self.fresh_args_for_item(DUMMY_SP, single.impl_def_id);
2239                    let impl_trait_ref = ocx.normalize(
2240                        &ObligationCause::dummy(),
2241                        param_env,
2242                        ty::EarlyBinder::bind(self.tcx, single.trait_ref)
2243                            .instantiate(self.tcx, impl_args),
2244                    );
2245
2246                    ocx.register_obligations(
2247                        self.tcx
2248                            .clauses_of(single.impl_def_id)
2249                            .instantiate(self.tcx, impl_args)
2250                            .into_iter()
2251                            .map(|(clause, _)| {
2252                                Obligation::new(
2253                                    self.tcx,
2254                                    ObligationCause::dummy(),
2255                                    param_env,
2256                                    clause.skip_norm_wip(),
2257                                )
2258                            }),
2259                    );
2260                    if !ocx.try_evaluate_obligations().no_errors() {
2261                        return false;
2262                    }
2263
2264                    let mut terrs = ::alloc::vec::Vec::new()vec![];
2265                    for (obligation_arg, impl_arg) in
2266                        std::iter::zip(obligation_trait_ref.trait_ref.args, impl_trait_ref.args)
2267                    {
2268                        if (obligation_arg, impl_arg).references_error() {
2269                            return false;
2270                        }
2271                        if let Err(terr) =
2272                            ocx.eq(&ObligationCause::dummy(), param_env, impl_arg, obligation_arg)
2273                        {
2274                            terrs.push(terr);
2275                        }
2276                        if !ocx.try_evaluate_obligations().no_errors() {
2277                            return false;
2278                        }
2279                    }
2280
2281                    // Literally nothing unified, just give up.
2282                    if terrs.len() == impl_trait_ref.args.len() {
2283                        return false;
2284                    }
2285
2286                    let impl_trait_ref = self.deeply_resolve_ignoring_regions(impl_trait_ref);
2287                    if impl_trait_ref.references_error() {
2288                        return false;
2289                    }
2290
2291                    if let [child, ..] = &err.children[..]
2292                        && child.level == Sublevel::Help
2293                        && let Some(line) = child.messages.get(0)
2294                        && let Some(line) = line.0.as_str()
2295                        && line.starts_with("the trait")
2296                        && line.contains("is not implemented for")
2297                    {
2298                        // HACK(estebank): we remove the pre-existing
2299                        // "the trait `X` is not implemented for" note, which only happens if there
2300                        // was a custom label. We do this because we want that note to always be the
2301                        // first, and making this logic run earlier will get tricky. For now, we
2302                        // instead keep the logic the same and modify the already constructed error
2303                        // to avoid the wording duplication.
2304                        err.children.remove(0);
2305                    }
2306
2307                    let traits = self.cmp_traits(
2308                        obligation_trait_ref.def_id(),
2309                        &obligation_trait_ref.trait_ref.args[1..],
2310                        impl_trait_ref.def_id,
2311                        &impl_trait_ref.args[1..],
2312                    );
2313                    let traits_content = (traits.0.content(), traits.1.content());
2314                    let types = self.cmp(obligation_trait_ref.self_ty(), impl_trait_ref.self_ty());
2315                    let types_content = (types.0.content(), types.1.content());
2316                    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 `")];
2317                    if traits_content.0 == traits_content.1 {
2318                        msg.push(StringPart::normal(
2319                            impl_trait_ref.print_trait_sugared().to_string(),
2320                        ));
2321                    } else {
2322                        msg.extend(traits.0.0);
2323                    }
2324                    msg.extend([
2325                        StringPart::normal("` "),
2326                        StringPart::highlighted("is not"),
2327                        StringPart::normal(" implemented for `"),
2328                    ]);
2329                    if types_content.0 == types_content.1 {
2330                        let ty = self
2331                            .tcx
2332                            .short_string(obligation_trait_ref.self_ty(), err.long_ty_path());
2333                        msg.push(StringPart::normal(ty));
2334                    } else {
2335                        msg.extend(types.0.0);
2336                    }
2337                    msg.push(StringPart::normal("`"));
2338                    if types_content.0 == types_content.1 {
2339                        msg.push(StringPart::normal("\nbut trait `"));
2340                        msg.extend(traits.1.0);
2341                        msg.extend([
2342                            StringPart::normal("` "),
2343                            StringPart::highlighted("is"),
2344                            StringPart::normal(" implemented for it"),
2345                        ]);
2346                    } else if traits_content.0 == traits_content.1 {
2347                        msg.extend([
2348                            StringPart::normal("\nbut it "),
2349                            StringPart::highlighted("is"),
2350                            StringPart::normal(" implemented for `"),
2351                        ]);
2352                        msg.extend(types.1.0);
2353                        msg.push(StringPart::normal("`"));
2354                    } else {
2355                        msg.push(StringPart::normal("\nbut trait `"));
2356                        msg.extend(traits.1.0);
2357                        msg.extend([
2358                            StringPart::normal("` "),
2359                            StringPart::highlighted("is"),
2360                            StringPart::normal(" implemented for `"),
2361                        ]);
2362                        msg.extend(types.1.0);
2363                        msg.push(StringPart::normal("`"));
2364                    }
2365                    err.highlighted_span_help(self.tcx.def_span(single.impl_def_id), msg);
2366
2367                    if let [TypeError::Sorts(exp_found)] = &terrs[..] {
2368                        let exp_found = self.deeply_resolve_ignoring_regions(*exp_found);
2369                        let expected =
2370                            self.tcx.short_string(exp_found.expected, err.long_ty_path());
2371                        let found = self.tcx.short_string(exp_found.found, err.long_ty_path());
2372                        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![
2373                            StringPart::normal("for that trait implementation, "),
2374                            StringPart::normal("expected `"),
2375                            StringPart::highlighted(expected),
2376                            StringPart::normal("`, found `"),
2377                            StringPart::highlighted(found),
2378                            StringPart::normal("`"),
2379                        ]);
2380                        self.suggest_function_pointers_impl(None, &exp_found, err);
2381                    }
2382
2383                    if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2384                        && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2385                        && !crates.is_empty()
2386                    {
2387                        self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2388                        err.help("you can use `cargo tree` to explore your dependency tree");
2389                    }
2390                    true
2391                })
2392            }) {
2393                return true;
2394            }
2395        }
2396
2397        let other = if other { "other " } else { "" };
2398        let report = |mut candidates: Vec<(TraitRef<'tcx>, DefId)>, err: &mut Diag<'_>| {
2399            candidates.retain(|(tr, _)| !tr.references_error());
2400            if candidates.is_empty() {
2401                return false;
2402            }
2403            let mut specific_candidates = candidates.clone();
2404            specific_candidates.retain(|(tr, _)| {
2405                tr.with_replaced_self_ty(self.tcx, trait_pred.skip_binder().self_ty())
2406                    == trait_pred.skip_binder().trait_ref
2407            });
2408            if !specific_candidates.is_empty() {
2409                // We have found a subset of impls that fully satisfy the expected trait, only
2410                // mention those types.
2411                candidates = specific_candidates;
2412            }
2413            if let &[(cand, def_id)] = &candidates[..] {
2414                if self.tcx.is_diagnostic_item(sym::FromResidual, cand.def_id)
2415                    && !self.tcx.features().enabled(sym::try_trait_v2)
2416                {
2417                    return false;
2418                }
2419                let mut multi_span = MultiSpan::from_span(self.tcx.def_span(def_id));
2420                let (desc, mention_castable) =
2421                    match (cand.self_ty().kind(), trait_pred.self_ty().skip_binder().kind()) {
2422                        (ty::FnPtr(..), ty::FnDef(..)) => {
2423                            (" implemented for fn pointer `", ", cast using `as`")
2424                        }
2425                        (ty::FnPtr(..), _) => (" implemented for fn pointer `", ""),
2426                        _ => {
2427                            let evaluate_obligations = || {
2428                                let ocx = ObligationCtxt::new_with_diagnostics(self);
2429                                self.enter_forall(trait_pred, |obligation_trait_ref| {
2430                                    let impl_args = self.fresh_args_for_item(DUMMY_SP, def_id);
2431                                    let impl_trait_ref = ocx.normalize(
2432                                        &ObligationCause::dummy(),
2433                                        param_env,
2434                                        ty::EarlyBinder::bind(self.tcx, cand)
2435                                            .instantiate(self.tcx, impl_args),
2436                                    );
2437                                    if ocx
2438                                        .eq(
2439                                            &ObligationCause::dummy(),
2440                                            param_env,
2441                                            obligation_trait_ref.trait_ref,
2442                                            impl_trait_ref,
2443                                        )
2444                                        .is_err()
2445                                    {
2446                                        return TraitErrors::NoErrors;
2447                                    }
2448                                    ocx.register_obligations(
2449                                        self.tcx
2450                                            .clauses_of(def_id)
2451                                            .instantiate(self.tcx, impl_args)
2452                                            .into_iter()
2453                                            .map(|(clause, span)| {
2454                                                Obligation::new(
2455                                                    self.tcx,
2456                                                    ObligationCause::dummy_with_span(span),
2457                                                    param_env,
2458                                                    clause.skip_normalization(),
2459                                                )
2460                                            }),
2461                                    );
2462                                    ocx.try_evaluate_obligations()
2463                                })
2464                            };
2465                            let failing_obligations =
2466                                if !self.tcx.clauses_of(def_id).clauses.is_empty() {
2467                                    self.probe(|_| evaluate_obligations())
2468                                } else {
2469                                    TraitErrors::NoErrors
2470                                };
2471
2472                            if failing_obligations.no_errors() {
2473                                (" implemented for `", "")
2474                            } else {
2475                                for error in failing_obligations {
2476                                    multi_span.push_span_label(
2477                                        error.root_obligation.cause.span,
2478                                        ::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!(
2479                                            "unsatisfied requirement introduced here: `{}`",
2480                                            self.tcx.short_string(
2481                                                error.root_obligation.predicate,
2482                                                err.long_ty_path()
2483                                            ),
2484                                        ),
2485                                    );
2486                                }
2487
2488                                (" conditionally implemented for `", "")
2489                            }
2490                        }
2491                    };
2492                let trait_ = self.tcx.short_string(cand.print_trait_sugared(), err.long_ty_path());
2493                let self_ty = self.tcx.short_string(cand.self_ty(), err.long_ty_path());
2494                err.highlighted_span_help(
2495                    multi_span,
2496                    ::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![
2497                        StringPart::normal(format!("the trait `{trait_}` ")),
2498                        StringPart::highlighted("is"),
2499                        StringPart::normal(desc),
2500                        StringPart::highlighted(self_ty),
2501                        StringPart::normal("`"),
2502                        StringPart::normal(mention_castable),
2503                    ],
2504                );
2505                return true;
2506            }
2507            let trait_ref = TraitRef::identity(self.tcx, candidates[0].0.def_id);
2508            // Check if the trait is the same in all cases. If so, we'll only show the type.
2509            let mut traits: Vec<_> =
2510                candidates.iter().map(|(c, _)| c.print_only_trait_path().to_string()).collect();
2511            traits.sort();
2512            traits.dedup();
2513            // FIXME: this could use a better heuristic, like just checking
2514            // that args[1..] is the same.
2515            let all_traits_equal = traits.len() == 1;
2516            let mut types: Vec<_> =
2517                candidates.iter().map(|(c, _)| c.self_ty().to_string()).collect();
2518            types.sort();
2519            types.dedup();
2520            let all_types_equal = types.len() == 1;
2521
2522            let end = if candidates.len() <= 9 || self.tcx.sess.opts.verbose {
2523                candidates.len()
2524            } else {
2525                8
2526            };
2527            if candidates.len() < 5 {
2528                let spans: Vec<_> =
2529                    candidates.iter().map(|&(_, def_id)| self.tcx.def_span(def_id)).collect();
2530                let mut span: MultiSpan = spans.into();
2531                for (c, def_id) in &candidates {
2532                    let msg = if all_traits_equal {
2533                        ::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()))
2534                    } else if all_types_equal {
2535                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`",
                self.tcx.short_string(c.print_only_trait_path(),
                    err.long_ty_path())))
    })format!(
2536                            "`{}`",
2537                            self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path())
2538                        )
2539                    } else {
2540                        ::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!(
2541                            "`{}` implements `{}`",
2542                            self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2543                            self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path()),
2544                        )
2545                    };
2546                    span.push_span_label(self.tcx.def_span(*def_id), msg);
2547                }
2548                let msg = if all_types_equal {
2549                    ::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!(
2550                        "`{}` implements trait `{}`",
2551                        self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2552                        self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2553                    )
2554                } else {
2555                    ::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!(
2556                        "the following {other}types implement trait `{}`",
2557                        self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2558                    )
2559                };
2560                err.span_help(span, msg);
2561            } else {
2562                // When more than 5 tuples implement the same trait, the output might be very verbose
2563                // Instead of displaying each of these, we sort the candidates by arity in ascending
2564                // order, then we compute the min and the max arity, ensuring that the arities are
2565                // consecutive (by step of one). If these conditions are met, then the output is shown
2566                // as a range of tuples [tuple_min_arity:tuple_max_arity]
2567                let mut tuple_min_arity = usize::MAX;
2568                let mut tuple_max_arity = 0_usize;
2569                let mut last_arity = None;
2570                let mut all_types_tuples_cont_arity = true;
2571                candidates.sort_by(|(c1, _), (c2, _)| {
2572                    if let ty::Tuple(tys1) = c1.self_ty().kind()
2573                        && let ty::Tuple(tys2) = c2.self_ty().kind()
2574                    {
2575                        tys1.len().cmp(&tys2.len())
2576                    } else {
2577                        std::cmp::Ordering::Equal
2578                    }
2579                });
2580                let candidate_names: Vec<String> = candidates
2581                    .iter()
2582                    .map(|(c, _)| {
2583                        if all_traits_equal {
2584                            if all_types_tuples_cont_arity
2585                                && let ty::Tuple(tys) = c.self_ty().kind()
2586                                && last_arity.map_or(1, |a: usize| a.abs_diff(tys.len())) == 1
2587                            {
2588                                last_arity = Some(tys.len());
2589                                if tys.len() > tuple_max_arity {
2590                                    tuple_max_arity = tys.len();
2591                                }
2592                                if tys.len() < tuple_min_arity {
2593                                    tuple_min_arity = tys.len();
2594                                }
2595                            } else {
2596                                all_types_tuples_cont_arity = false;
2597                            }
2598                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n  {0}",
                self.tcx.short_string(c.self_ty(), err.long_ty_path())))
    })format!(
2599                                "\n  {}",
2600                                self.tcx.short_string(c.self_ty(), err.long_ty_path())
2601                            )
2602                        } else if all_types_equal {
2603                            ::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!(
2604                                "\n  {}",
2605                                self.tcx
2606                                    .short_string(c.print_only_trait_path(), err.long_ty_path())
2607                            )
2608                        } else {
2609                            ::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!(
2610                                "\n  `{}` implements `{}`",
2611                                self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2612                                self.tcx
2613                                    .short_string(c.print_only_trait_path(), err.long_ty_path()),
2614                            )
2615                        }
2616                    })
2617                    .collect();
2618
2619                let details = if all_traits_equal && all_types_tuples_cont_arity {
2620                    if tuple_min_arity == 0 {
2621                        ::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}")
2622                    } else {
2623                        ::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!(
2624                            "for tuples of arity {tuple_min_arity} up to and including {tuple_max_arity}"
2625                        )
2626                    }
2627                } else {
2628                    String::new()
2629                };
2630                let (candidate_names, end) = if all_traits_equal && all_types_tuples_cont_arity {
2631                    (
2632                        ::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![
2633                            // (T₁, T₂, …, Tₙ)
2634                            format!("\n  (T\u{2081}, T\u{2082}, …, T\u{2099}) {details}"),
2635                        ],
2636                        1,
2637                    )
2638                } else {
2639                    (candidate_names, end)
2640                };
2641                let msg = if all_types_equal {
2642                    ::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!(
2643                        "`{}` implements trait `{}`",
2644                        self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2645                        self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2646                    )
2647                } else {
2648                    ::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!(
2649                        "the following {other}types implement trait `{}`",
2650                        self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2651                    )
2652                };
2653
2654                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!(
2655                    "{msg}:{}{}",
2656                    candidate_names[..end].join(""),
2657                    if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
2658                        format!("\nand {} others", candidates.len() - 8)
2659                    } else {
2660                        String::new()
2661                    }
2662                ));
2663            }
2664
2665            if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2666                && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2667                && !crates.is_empty()
2668            {
2669                self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2670                err.help("you can use `cargo tree` to explore your dependency tree");
2671            }
2672            true
2673        };
2674
2675        // we filter before checking if `impl_candidates` is empty
2676        // to get the fallback solution if we filtered out any impls
2677        let impl_candidates = impl_candidates
2678            .into_iter()
2679            .cloned()
2680            .filter(|cand| !self.tcx.do_not_recommend_impl(cand.impl_def_id))
2681            .collect::<Vec<_>>();
2682
2683        let def_id = trait_pred.def_id();
2684        if impl_candidates.is_empty() {
2685            if self.tcx.trait_is_auto(def_id)
2686                || self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2687                || self.tcx.get_diagnostic_name(def_id).is_some()
2688            {
2689                // Mentioning implementers of `Copy`, `Debug` and friends is not useful.
2690                return false;
2691            }
2692            return report(alternative_candidates(def_id), err);
2693        }
2694
2695        // Sort impl candidates so that ordering is consistent for UI tests.
2696        // because the ordering of `impl_candidates` may not be deterministic:
2697        // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
2698        //
2699        // Prefer more similar candidates first, then sort lexicographically
2700        // by their normalized string representation.
2701        let mut impl_candidates: Vec<_> = impl_candidates
2702            .iter()
2703            .cloned()
2704            .filter(|cand| !cand.trait_ref.references_error())
2705            .map(|mut cand| {
2706                // Normalize the trait ref in its *own* param-env so
2707                // that consts are folded and any trivial projections
2708                // are normalized.
2709                cand.trait_ref = self
2710                    .tcx
2711                    .try_normalize_erasing_regions(
2712                        ty::TypingEnv::non_body_analysis(self.tcx, cand.impl_def_id),
2713                        Unnormalized::new_wip(cand.trait_ref),
2714                    )
2715                    .unwrap_or(cand.trait_ref);
2716                cand
2717            })
2718            .collect();
2719        impl_candidates.sort_by_key(|cand| {
2720            // When suggesting array types, sort them by the length of the array, not lexicographically (#135098)
2721            let len = if let GenericArgKind::Type(ty) = cand.trait_ref.args[0].kind()
2722                && let ty::Array(_, len) = ty.kind()
2723            {
2724                // Deprioritize suggestions for parameterized arrays.
2725                len.try_to_target_usize(self.tcx).unwrap_or(u64::MAX)
2726            } else {
2727                0
2728            };
2729
2730            (cand.similarity, len, cand.trait_ref.to_string())
2731        });
2732        let mut impl_candidates: Vec<_> =
2733            impl_candidates.into_iter().map(|cand| (cand.trait_ref, cand.impl_def_id)).collect();
2734        impl_candidates.dedup();
2735
2736        report(impl_candidates, err)
2737    }
2738
2739    fn report_similar_impl_candidates_for_root_obligation(
2740        &self,
2741        obligation: &PredicateObligation<'tcx>,
2742        trait_predicate: ty::Binder<'tcx, ty::TraitClause<'tcx>>,
2743        body_def_id: LocalDefId,
2744        err: &mut Diag<'_>,
2745    ) {
2746        // This is *almost* equivalent to
2747        // `obligation.cause.code().peel_derives()`, but it gives us the
2748        // trait predicate for that corresponding root obligation. This
2749        // lets us get a derived obligation from a type parameter, like
2750        // when calling `string.strip_suffix(p)` where `p` is *not* an
2751        // implementer of `Pattern<'_>`.
2752        let mut code = obligation.cause.code();
2753        let mut trait_pred = trait_predicate;
2754        let mut peeled = false;
2755        while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
2756            code = parent_code;
2757            if let Some(parent_trait_pred) = parent_trait_pred {
2758                trait_pred = parent_trait_pred;
2759                peeled = true;
2760            }
2761        }
2762        let def_id = trait_pred.def_id();
2763        // Mention *all* the `impl`s for the *top most* obligation, the
2764        // user might have meant to use one of them, if any found. We skip
2765        // auto-traits or fundamental traits that might not be exactly what
2766        // the user might expect to be presented with. Instead this is
2767        // useful for less general traits.
2768        if peeled && !self.tcx.trait_is_auto(def_id) && self.tcx.as_lang_item(def_id).is_none() {
2769            let impl_candidates = self.find_similar_impl_candidates(trait_pred);
2770            self.report_similar_impl_candidates(
2771                &impl_candidates,
2772                obligation,
2773                trait_pred,
2774                body_def_id,
2775                err,
2776                true,
2777                obligation.param_env,
2778            );
2779        }
2780    }
2781
2782    /// Gets the parent trait chain start
2783    fn get_parent_trait_ref(
2784        &self,
2785        code: &ObligationCauseCode<'tcx>,
2786    ) -> Option<(Ty<'tcx>, Option<Span>)> {
2787        match code {
2788            ObligationCauseCode::BuiltinDerived(data) => {
2789                let parent_trait_ref = self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
2790                match self.get_parent_trait_ref(&data.parent_code) {
2791                    Some(t) => Some(t),
2792                    None => {
2793                        let ty = parent_trait_ref.skip_binder().self_ty();
2794                        let span = TyCategory::from_ty(self.tcx, ty)
2795                            .map(|(_, def_id)| self.tcx.def_span(def_id));
2796                        Some((ty, span))
2797                    }
2798                }
2799            }
2800            ObligationCauseCode::FunctionArg { parent_code, .. } => {
2801                self.get_parent_trait_ref(parent_code)
2802            }
2803            _ => None,
2804        }
2805    }
2806
2807    fn check_same_trait_different_version(
2808        &self,
2809        err: &mut Diag<'_>,
2810        trait_pred: ty::PolyTraitClause<'tcx>,
2811    ) -> bool {
2812        let get_trait_impls = |trait_def_id| {
2813            let mut trait_impls = ::alloc::vec::Vec::new()vec![];
2814            self.tcx.for_each_relevant_impl(
2815                trait_def_id,
2816                trait_pred.skip_binder().self_ty(),
2817                |impl_def_id| {
2818                    let impl_trait_header = self.tcx.impl_trait_header(impl_def_id);
2819                    trait_impls
2820                        .push(self.tcx.def_span(impl_trait_header.trait_ref.skip_binder().def_id));
2821                },
2822            );
2823            trait_impls
2824        };
2825        self.check_same_definition_different_crate(
2826            err,
2827            trait_pred.def_id(),
2828            self.tcx.visible_traits(),
2829            get_trait_impls,
2830            "trait",
2831        )
2832    }
2833
2834    pub fn note_two_crate_versions(
2835        &self,
2836        krate: CrateNum,
2837        sp: impl Into<MultiSpan>,
2838        err: &mut Diag<'_>,
2839    ) {
2840        let crate_name = self.tcx.crate_name(krate);
2841        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!(
2842            "there are multiple different versions of crate `{crate_name}` in the dependency graph"
2843        );
2844        err.span_note(sp, crate_msg);
2845    }
2846
2847    fn note_adt_version_mismatch(&self, err: &mut Diag<'_>, trait_pred: ty::PolyTraitClause<'tcx>) {
2848        let ty::Adt(impl_self_def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2849        else {
2850            return;
2851        };
2852
2853        let impl_self_did = impl_self_def.did();
2854
2855        // We only want to warn about different versions of a dependency.
2856        // If no dependency is involved, bail.
2857        if impl_self_did.krate == LOCAL_CRATE {
2858            return;
2859        }
2860
2861        let impl_self_path = self.comparable_path(impl_self_did);
2862        let impl_self_crate_name = self.tcx.crate_name(impl_self_did.krate);
2863        let similar_items: UnordSet<_> = self
2864            .tcx
2865            .visible_parent_map(())
2866            .items()
2867            .filter_map(|(&item, _)| {
2868                // If we found ourselves, ignore.
2869                if impl_self_did == item {
2870                    return None;
2871                }
2872                // We only want to warn about different versions of a dependency.
2873                // Ignore items from our own crate.
2874                if item.krate == LOCAL_CRATE {
2875                    return None;
2876                }
2877                // We want to warn about different versions of a dependency.
2878                // So make sure the crate names are the same.
2879                if impl_self_crate_name != self.tcx.crate_name(item.krate) {
2880                    return None;
2881                }
2882                // Filter out e.g. constructors that often have the same path
2883                // str as the relevant ADT.
2884                if !self.tcx.def_kind(item).is_adt() {
2885                    return None;
2886                }
2887                let path = self.comparable_path(item);
2888                // We don't know if our item or the one we found is the re-exported one.
2889                // Check both cases.
2890                let is_similar = path.ends_with(&impl_self_path) || impl_self_path.ends_with(&path);
2891                is_similar.then_some((item, path))
2892            })
2893            .collect();
2894
2895        let mut similar_items =
2896            similar_items.into_items().into_sorted_stable_ord_by_key(|(_, path)| path);
2897        similar_items.dedup();
2898
2899        for (similar_item, _) in similar_items {
2900            err.span_help(self.tcx.def_span(similar_item), "item with same name found");
2901            self.note_two_crate_versions(similar_item.krate, MultiSpan::new(), err);
2902        }
2903    }
2904
2905    fn check_same_name_different_path(
2906        &self,
2907        err: &mut Diag<'_>,
2908        obligation: &PredicateObligation<'tcx>,
2909        trait_pred: ty::PolyTraitClause<'tcx>,
2910    ) -> bool {
2911        let mut suggested = false;
2912        let trait_def_id = trait_pred.def_id();
2913        let trait_has_same_params = |other_trait_def_id: DefId| -> bool {
2914            let trait_generics = self.tcx.generics_of(trait_def_id);
2915            let other_trait_generics = self.tcx.generics_of(other_trait_def_id);
2916
2917            if trait_generics.count() != other_trait_generics.count() {
2918                return false;
2919            }
2920            trait_generics.own_params.iter().zip(other_trait_generics.own_params.iter()).all(
2921                |(a, b)| match (&a.kind, &b.kind) {
2922                    (ty::GenericParamDefKind::Lifetime, ty::GenericParamDefKind::Lifetime)
2923                    | (
2924                        ty::GenericParamDefKind::Type { .. },
2925                        ty::GenericParamDefKind::Type { .. },
2926                    )
2927                    | (
2928                        ty::GenericParamDefKind::Const { .. },
2929                        ty::GenericParamDefKind::Const { .. },
2930                    ) => true,
2931                    _ => false,
2932                },
2933            )
2934        };
2935        let trait_name = self.tcx.item_name(trait_def_id);
2936        if let Some(other_trait_def_id) = self.tcx.all_traits_including_private().find(|&def_id| {
2937            trait_def_id != def_id
2938                && trait_name == self.tcx.item_name(def_id)
2939                && trait_has_same_params(def_id)
2940                // `PointeeSized` is removed during lowering.
2941                && !self.tcx.is_lang_item(def_id, LangItem::PointeeSized)
2942                && self.predicate_must_hold_modulo_regions(&Obligation::new(
2943                    self.tcx,
2944                    obligation.cause.clone(),
2945                    obligation.param_env,
2946                    trait_pred.map_bound(|tr| ty::TraitClause {
2947                        trait_ref: ty::TraitRef::new(self.tcx, def_id, tr.trait_ref.args),
2948                        ..tr
2949                    }),
2950                ))
2951        }) {
2952            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!(
2953                "`{}` implements similarly named trait `{}`, but not `{}`",
2954                trait_pred.self_ty(),
2955                self.tcx.def_path_str(other_trait_def_id),
2956                trait_pred.print_modifiers_and_trait_path()
2957            ));
2958            suggested = true;
2959        }
2960        suggested
2961    }
2962
2963    /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
2964    /// with the same path as `trait_ref`, a help message about a multiple different
2965    /// versions of the same crate is added to `err`. Otherwise if it implements another
2966    /// trait with the same name, a note message about a similarly named trait is added to `err`.
2967    pub fn note_different_trait_with_same_name(
2968        &self,
2969        err: &mut Diag<'_>,
2970        obligation: &PredicateObligation<'tcx>,
2971        trait_pred: ty::PolyTraitClause<'tcx>,
2972    ) -> bool {
2973        if self.check_same_trait_different_version(err, trait_pred) {
2974            return true;
2975        }
2976        self.check_same_name_different_path(err, obligation, trait_pred)
2977    }
2978
2979    /// Add a `::` prefix when comparing paths so that paths with just one item
2980    /// like "Foo" does not equal the end of "OtherFoo".
2981    fn comparable_path(&self, did: DefId) -> String {
2982        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("::{0}",
                self.tcx.def_path_str(did)))
    })format!("::{}", self.tcx.def_path_str(did))
2983    }
2984
2985    /// Creates a `PredicateObligation` with `new_self_ty` replacing the existing type in the
2986    /// `trait_ref`.
2987    ///
2988    /// For this to work, `new_self_ty` must have no escaping bound variables.
2989    pub(super) fn mk_trait_obligation_with_new_self_ty(
2990        &self,
2991        param_env: ty::ParamEnv<'tcx>,
2992        trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitClause<'tcx>, Ty<'tcx>)>,
2993    ) -> PredicateObligation<'tcx> {
2994        let trait_pred = trait_ref_and_ty
2995            .map_bound(|(tr, new_self_ty)| tr.with_replaced_self_ty(self.tcx, new_self_ty));
2996
2997        Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred)
2998    }
2999
3000    /// Returns `true` if the trait predicate may apply for *some* assignment
3001    /// to the type parameters.
3002    fn predicate_can_apply(
3003        &self,
3004        param_env: ty::ParamEnv<'tcx>,
3005        pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + TypeFoldable<TyCtxt<'tcx>>,
3006    ) -> bool {
3007        struct ParamToVarFolder<'a, 'tcx> {
3008            infcx: &'a InferCtxt<'tcx>,
3009            var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
3010        }
3011
3012        impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ParamToVarFolder<'a, 'tcx> {
3013            fn cx(&self) -> TyCtxt<'tcx> {
3014                self.infcx.tcx
3015            }
3016
3017            // FIXME: why don't we also instantiate const and region params with infer vars
3018            // here? Because diagnostics isn't soundness critical and no one bothers to be
3019            // pedantic yet.
3020            fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
3021                match ty.kind() {
3022                    ty::Param(_) => {
3023                        let infcx = self.infcx;
3024                        *self.var_map.entry(ty).or_insert_with(|| infcx.next_ty_var(DUMMY_SP))
3025                    }
3026                    // FIXME(#155345): This should automatically
3027                    // handled by type folders instead of needing to do it
3028                    // manually here.
3029                    &ty::Alias(is_rigid, alias)
3030                        if is_rigid == ty::IsRigid::Yes
3031                            && ty.has_type_flags(ty::TypeFlags::HAS_TY_PARAM) =>
3032                    {
3033                        let alias = alias.fold_with(self);
3034                        Ty::new_alias(self.cx(), ty::IsRigid::No, alias)
3035                    }
3036                    _ => ty.super_fold_with(self),
3037                }
3038            }
3039        }
3040
3041        self.probe(|_| {
3042            let cleaned_pred =
3043                pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
3044
3045            let InferOk { value: cleaned_pred, .. } = self
3046                .infcx
3047                .at(&ObligationCause::dummy(), param_env)
3048                .normalize(Unnormalized::new_wip(cleaned_pred));
3049
3050            let obligation =
3051                Obligation::new(self.tcx, ObligationCause::dummy(), param_env, cleaned_pred);
3052
3053            self.predicate_may_hold(&obligation)
3054        })
3055    }
3056
3057    fn suggest_change_mut_ref_for_closure(
3058        &self,
3059        err: &mut Diag<'_>,
3060        obligation: &PredicateObligation<'tcx>,
3061    ) {
3062        if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
3063            && let (_, Some(root_trait_pred)) =
3064                obligation.cause.code().peel_derives_with_predicate()
3065            && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
3066            && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, _) = arg.kind
3067        {
3068            let mut obligation = obligation.clone();
3069            // Error reporting may narrow the cause span to the borrow's operand.
3070            // Use the whole argument so `suggest_change_mut` can replace the shared borrow.
3071            obligation.cause.span = arg.span;
3072            self.suggest_change_mut(&obligation, err, root_trait_pred);
3073        }
3074    }
3075
3076    pub fn note_obligation_cause(
3077        &self,
3078        err: &mut Diag<'_>,
3079        obligation: &PredicateObligation<'tcx>,
3080    ) {
3081        // First, attempt to add note to this error with an async-await-specific
3082        // message, and fall back to regular note otherwise.
3083        if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
3084            self.note_obligation_cause_code(
3085                obligation.cause.body_def_id,
3086                err,
3087                obligation.predicate,
3088                obligation.param_env,
3089                obligation.cause.code(),
3090                &mut ::alloc::vec::Vec::new()vec![],
3091                &mut Default::default(),
3092            );
3093            self.suggest_swapping_lhs_and_rhs(
3094                err,
3095                obligation.predicate,
3096                obligation.param_env,
3097                obligation.cause.code(),
3098            );
3099            self.suggest_borrow_for_unsized_closure_return(
3100                obligation.cause.body_def_id,
3101                err,
3102                obligation.predicate,
3103            );
3104            self.suggest_unsized_bound_if_applicable(err, obligation);
3105            if let Some(span) = err.span.primary_span()
3106                && let Some(mut diag) =
3107                    self.dcx().steal_non_err(span, StashKey::AssociatedTypeSuggestion)
3108                && let Suggestions::Enabled(ref mut s1) = err.suggestions
3109                && let Suggestions::Enabled(ref mut s2) = diag.suggestions
3110            {
3111                s1.append(s2);
3112                diag.cancel()
3113            }
3114        }
3115    }
3116
3117    pub(super) fn is_recursive_obligation(
3118        &self,
3119        obligated_types: &mut Vec<Ty<'tcx>>,
3120        cause_code: &ObligationCauseCode<'tcx>,
3121    ) -> bool {
3122        if let ObligationCauseCode::BuiltinDerived(data) = cause_code {
3123            let parent_trait_ref = self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
3124            let self_ty = parent_trait_ref.skip_binder().self_ty();
3125            if obligated_types.iter().any(|ot| ot == &self_ty) {
3126                return true;
3127            }
3128            if let ty::Adt(def, args) = self_ty.kind()
3129                && let [arg] = &args[..]
3130                && let ty::GenericArgKind::Type(ty) = arg.kind()
3131                && let ty::Adt(inner_def, _) = ty.kind()
3132                && inner_def == def
3133            {
3134                return true;
3135            }
3136        }
3137        false
3138    }
3139
3140    fn get_standard_error_message(
3141        &self,
3142        trait_predicate: ty::PolyTraitClause<'tcx>,
3143        predicate_constness: Option<ty::BoundConstness>,
3144        post_message: String,
3145        long_ty_path: &mut Option<PathBuf>,
3146    ) -> String {
3147        ::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!(
3148            "the trait bound `{}` is not satisfied{post_message}",
3149            self.tcx.short_string(
3150                trait_predicate.print_with_bound_constness(predicate_constness),
3151                long_ty_path,
3152            ),
3153        )
3154    }
3155
3156    fn select_transmute_obligation_for_reporting(
3157        &self,
3158        obligation: &PredicateObligation<'tcx>,
3159        trait_predicate: ty::PolyTraitClause<'tcx>,
3160        root_obligation: &PredicateObligation<'tcx>,
3161    ) -> (PredicateObligation<'tcx>, ty::PolyTraitClause<'tcx>) {
3162        if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
3163            return (obligation.clone(), trait_predicate);
3164        }
3165
3166        let ocx = ObligationCtxt::new(self);
3167        let normalized_predicate = self.tcx.erase_and_anonymize_regions(
3168            self.tcx.instantiate_bound_regions_with_erased(trait_predicate),
3169        );
3170        let trait_ref = normalized_predicate.trait_ref;
3171
3172        let assume = ocx.normalize(
3173            &obligation.cause,
3174            obligation.param_env,
3175            Unnormalized::new_wip(trait_ref.args.const_at(2)),
3176        );
3177
3178        let Some(assume) = rustc_transmute::Assume::from_const(self.tcx, assume) else {
3179            return (obligation.clone(), trait_predicate);
3180        };
3181
3182        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!(
3183            rustc_transmute::TransmuteTypeEnv::new(self.tcx).is_transmutable(
3184                trait_ref.args.type_at(1),
3185                trait_ref.args.type_at(0),
3186                assume,
3187            ),
3188            rustc_transmute::Answer::Yes,
3189        );
3190
3191        // If the normalized check unexpectedly passes, fall back to root obligation for reporting.
3192        if is_normalized_yes
3193            && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3194                root_obligation.predicate.kind().skip_binder()
3195            && root_pred.def_id() == trait_predicate.def_id()
3196        {
3197            return (root_obligation.clone(), root_obligation.predicate.kind().rebind(root_pred));
3198        }
3199
3200        (obligation.clone(), trait_predicate)
3201    }
3202
3203    fn get_safe_transmute_error_and_reason(
3204        &self,
3205        obligation: PredicateObligation<'tcx>,
3206        trait_pred: ty::PolyTraitClause<'tcx>,
3207        span: Span,
3208    ) -> GetSafeTransmuteErrorAndReason {
3209        use rustc_transmute::Answer;
3210        self.probe(|_| {
3211            // We don't assemble a transmutability candidate for types that are generic
3212            // and we should have ambiguity for types that still have non-region infer.
3213            if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
3214                return GetSafeTransmuteErrorAndReason::Default;
3215            }
3216
3217            // Erase regions because layout code doesn't particularly care about regions.
3218            let trait_pred = self.tcx.erase_and_anonymize_regions(
3219                self.tcx.instantiate_bound_regions_with_erased(trait_pred),
3220            );
3221
3222            let ocx = ObligationCtxt::new(self);
3223            let assume = ocx.normalize(
3224                &obligation.cause,
3225                obligation.param_env,
3226                Unnormalized::new_wip(trait_pred.trait_ref.args.const_at(2)),
3227            );
3228
3229            let Some(assume) = rustc_transmute::Assume::from_const(self.infcx.tcx, assume) else {
3230                self.dcx().span_delayed_bug(
3231                    span,
3232                    "Unable to construct rustc_transmute::Assume where it was previously possible",
3233                );
3234                return GetSafeTransmuteErrorAndReason::Silent;
3235            };
3236
3237            let dst = trait_pred.trait_ref.args.type_at(0);
3238            let src = trait_pred.trait_ref.args.type_at(1);
3239            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}`");
3240
3241            match rustc_transmute::TransmuteTypeEnv::new(self.infcx.tcx)
3242                .is_transmutable(src, dst, assume)
3243            {
3244                Answer::No(reason) => {
3245                    let safe_transmute_explanation = match reason {
3246                        rustc_transmute::Reason::SrcIsNotYetSupported => {
3247                            ::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")
3248                        }
3249                        rustc_transmute::Reason::DstIsNotYetSupported => {
3250                            ::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")
3251                        }
3252                        rustc_transmute::Reason::DstIsBitIncompatible => {
3253                            ::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!(
3254                                "at least one value of `{src}` isn't a bit-valid value of `{dst}`"
3255                            )
3256                        }
3257                        rustc_transmute::Reason::DstUninhabited => {
3258                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is uninhabited", dst))
    })format!("`{dst}` is uninhabited")
3259                        }
3260                        rustc_transmute::Reason::DstMayHaveSafetyInvariants => {
3261                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` may carry safety invariants",
                dst))
    })format!("`{dst}` may carry safety invariants")
3262                        }
3263                        rustc_transmute::Reason::DstIsTooBig => {
3264                            ::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}`")
3265                        }
3266                        rustc_transmute::Reason::DstRefIsTooBig {
3267                            src,
3268                            src_size,
3269                            dst,
3270                            dst_size,
3271                        } => {
3272                            ::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!(
3273                                "the size of `{src}` ({src_size} bytes) \
3274                        is smaller than that of `{dst}` ({dst_size} bytes)"
3275                            )
3276                        }
3277                        rustc_transmute::Reason::SrcSizeOverflow => {
3278                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
                src))
    })format!(
3279                                "values of the type `{src}` are too big for the target architecture"
3280                            )
3281                        }
3282                        rustc_transmute::Reason::DstSizeOverflow => {
3283                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
                dst))
    })format!(
3284                                "values of the type `{dst}` are too big for the target architecture"
3285                            )
3286                        }
3287                        rustc_transmute::Reason::DstHasStricterAlignment {
3288                            src_min_align,
3289                            dst_min_align,
3290                        } => {
3291                            ::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!(
3292                                "the minimum alignment of `{src}` ({src_min_align}) should be \
3293                                 greater than that of `{dst}` ({dst_min_align})"
3294                            )
3295                        }
3296                        rustc_transmute::Reason::DstIsMoreUnique => {
3297                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is a shared reference, but `{1}` is a unique reference",
                src, dst))
    })format!(
3298                                "`{src}` is a shared reference, but `{dst}` is a unique reference"
3299                            )
3300                        }
3301                        // Already reported by rustc
3302                        rustc_transmute::Reason::TypeError => {
3303                            return GetSafeTransmuteErrorAndReason::Silent;
3304                        }
3305                        rustc_transmute::Reason::SrcLayoutUnknown => {
3306                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` has an unknown layout", src))
    })format!("`{src}` has an unknown layout")
3307                        }
3308                        rustc_transmute::Reason::DstLayoutUnknown => {
3309                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` has an unknown layout", dst))
    })format!("`{dst}` has an unknown layout")
3310                        }
3311                    };
3312                    GetSafeTransmuteErrorAndReason::Error {
3313                        err_msg,
3314                        safe_transmute_explanation: Some(safe_transmute_explanation),
3315                    }
3316                }
3317                // Should never get a Yes at this point! We already ran it before, and did not get a Yes.
3318                Answer::Yes => ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("Inconsistent rustc_transmute::is_transmutable(...) result, got Yes"))span_bug!(
3319                    span,
3320                    "Inconsistent rustc_transmute::is_transmutable(...) result, got Yes",
3321                ),
3322                // Reached when a different obligation (namely `Freeze`) causes the
3323                // transmutability analysis to fail. In this case, silence the
3324                // transmutability error message in favor of that more specific
3325                // error.
3326                Answer::If(_) => GetSafeTransmuteErrorAndReason::Error {
3327                    err_msg,
3328                    safe_transmute_explanation: None,
3329                },
3330            }
3331        })
3332    }
3333
3334    /// If `found_ty` is a reference that can be explicitly cast to another reference type for which
3335    /// a `From` / `TryFrom` impl exists for `self_ty`, return that type.
3336    fn find_explicit_cast_type(
3337        &self,
3338        param_env: ty::ParamEnv<'tcx>,
3339        found_ty: Ty<'tcx>,
3340        self_ty: Ty<'tcx>,
3341    ) -> Option<Ty<'tcx>> {
3342        let ty::Ref(region, inner_ty, mutbl) = *found_ty.kind() else {
3343            return None;
3344        };
3345
3346        let mut derefs = (self.autoderef_steps)(inner_ty).into_iter();
3347        derefs.next(); // skip the first one, which is inner_ty itself
3348        let deref_target = derefs.into_iter().next()?.0;
3349
3350        let cast_ty = Ty::new_ref(self.tcx, region, deref_target, mutbl);
3351
3352        let Some(from_def_id) = self.tcx.get_diagnostic_item(sym::From) else {
3353            return None;
3354        };
3355        let Some(try_from_def_id) = self.tcx.get_diagnostic_item(sym::TryFrom) else {
3356            return None;
3357        };
3358
3359        if self.has_impl_for_type(
3360            param_env,
3361            ty::TraitRef::new(
3362                self.tcx,
3363                from_def_id,
3364                self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3365            ),
3366        ) {
3367            Some(cast_ty)
3368        } else if self.has_impl_for_type(
3369            param_env,
3370            ty::TraitRef::new(
3371                self.tcx,
3372                try_from_def_id,
3373                self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3374            ),
3375        ) {
3376            Some(cast_ty)
3377        } else {
3378            None
3379        }
3380    }
3381
3382    fn has_impl_for_type(
3383        &self,
3384        param_env: ty::ParamEnv<'tcx>,
3385        trait_ref: ty::TraitRef<'tcx>,
3386    ) -> bool {
3387        let obligation = Obligation::new(
3388            self.tcx,
3389            ObligationCause::dummy(),
3390            param_env,
3391            ty::TraitClause { trait_ref, polarity: ty::ClausePolarity::Positive },
3392        );
3393
3394        self.predicate_must_hold_modulo_regions(&obligation)
3395    }
3396
3397    fn add_tuple_trait_message(
3398        &self,
3399        obligation_cause_code: &ObligationCauseCode<'tcx>,
3400        err: &mut Diag<'_>,
3401    ) {
3402        match obligation_cause_code {
3403            ObligationCauseCode::RustCall => {
3404                err.primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
3405            }
3406            ObligationCauseCode::WhereClause(def_id, _) if self.tcx.is_fn_trait(*def_id) => {
3407                err.code(E0059);
3408                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!(
3409                    "type parameter to bare `{}` trait must be a tuple",
3410                    self.tcx.def_path_str(*def_id)
3411                ));
3412            }
3413            _ => {}
3414        }
3415    }
3416
3417    fn try_to_add_help_message(
3418        &self,
3419        root_obligation: &PredicateObligation<'tcx>,
3420        obligation: &PredicateObligation<'tcx>,
3421        trait_predicate: ty::PolyTraitClause<'tcx>,
3422        err: &mut Diag<'_>,
3423        span: Span,
3424        is_fn_trait: bool,
3425        suggested: bool,
3426    ) {
3427        let body_def_id = obligation.cause.body_def_id;
3428        let span = if let ObligationCauseCode::BinOp { rhs_span, .. } = obligation.cause.code() {
3429            *rhs_span
3430        } else {
3431            span
3432        };
3433
3434        // Try to report a help message
3435        let trait_def_id = trait_predicate.def_id();
3436        if is_fn_trait
3437            && let Ok((implemented_kind, params)) = self.type_implements_fn_trait(
3438                obligation.param_env,
3439                trait_predicate.self_ty(),
3440                trait_predicate.skip_binder().polarity,
3441            )
3442        {
3443            self.add_help_message_for_fn_trait(trait_predicate, err, implemented_kind, params);
3444        } else if !trait_predicate.has_non_region_infer()
3445            && self.predicate_can_apply(obligation.param_env, trait_predicate)
3446        {
3447            // If a where-clause may be useful, remind the
3448            // user that they can add it.
3449            //
3450            // don't display an on-unimplemented note, as
3451            // these notes will often be of the form
3452            //     "the type `T` can't be frobnicated"
3453            // which is somewhat confusing.
3454            self.suggest_restricting_param_bound(
3455                err,
3456                trait_predicate,
3457                None,
3458                obligation.cause.body_def_id,
3459            );
3460        } else if trait_def_id.is_local()
3461            && self.tcx.trait_impls_of(trait_def_id).is_empty()
3462            && !self.tcx.trait_is_auto(trait_def_id)
3463            && !self.tcx.trait_is_alias(trait_def_id)
3464            && trait_predicate.polarity() == ty::ClausePolarity::Positive
3465        {
3466            err.span_help(
3467                self.tcx.def_span(trait_def_id),
3468                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"),
3469            );
3470        } else if !suggested && trait_predicate.polarity() == ty::ClausePolarity::Positive {
3471            // Can't show anything else useful, try to find similar impls.
3472            let impl_candidates = self.find_similar_impl_candidates(trait_predicate);
3473            if !self.report_similar_impl_candidates(
3474                &impl_candidates,
3475                obligation,
3476                trait_predicate,
3477                body_def_id,
3478                err,
3479                true,
3480                obligation.param_env,
3481            ) {
3482                self.report_similar_impl_candidates_for_root_obligation(
3483                    obligation,
3484                    trait_predicate,
3485                    body_def_id,
3486                    err,
3487                );
3488            }
3489
3490            self.suggest_convert_to_slice(
3491                err,
3492                obligation,
3493                trait_predicate,
3494                impl_candidates.as_slice(),
3495                span,
3496            );
3497
3498            self.suggest_tuple_wrapping(err, root_obligation, obligation);
3499        }
3500        self.suggest_shadowed_inherent_method(err, obligation, trait_predicate);
3501    }
3502
3503    fn add_help_message_for_fn_trait(
3504        &self,
3505        trait_pred: ty::PolyTraitClause<'tcx>,
3506        err: &mut Diag<'_>,
3507        implemented_kind: ty::ClosureKind,
3508        params: ty::Binder<'tcx, Ty<'tcx>>,
3509    ) {
3510        // If the type implements `Fn`, `FnMut`, or `FnOnce`, suppress the following
3511        // suggestion to add trait bounds for the type, since we only typically implement
3512        // these traits once.
3513
3514        // Note if the `FnMut` or `FnOnce` is less general than the trait we're trying
3515        // to implement.
3516        let selected_kind = self
3517            .tcx
3518            .fn_trait_kind_from_def_id(trait_pred.def_id())
3519            .expect("expected to map DefId to ClosureKind");
3520        if !implemented_kind.extends(selected_kind) {
3521            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!(
3522                "`{}` implements `{}`, but it must implement `{}`, which is more general",
3523                trait_pred.skip_binder().self_ty(),
3524                implemented_kind,
3525                selected_kind
3526            ));
3527        }
3528
3529        // Note any argument mismatches
3530        let ty::Tuple(given) = *params.skip_binder().kind() else {
3531            return;
3532        };
3533
3534        let expected_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
3535        let ty::Tuple(expected) = *expected_ty.kind() else {
3536            return;
3537        };
3538
3539        if expected.len() != given.len() {
3540            // Note number of types that were expected and given
3541            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!(
3542                "expected a closure taking {} argument{}, but one taking {} argument{} was given",
3543                given.len(),
3544                pluralize!(given.len()),
3545                expected.len(),
3546                pluralize!(expected.len()),
3547            ));
3548            return;
3549        }
3550
3551        let given_ty = Ty::new_fn_ptr(
3552            self.tcx,
3553            params.rebind(self.tcx.mk_fn_sig_safe_rust_abi(given, self.tcx.types.unit)),
3554        );
3555        let expected_ty = Ty::new_fn_ptr(
3556            self.tcx,
3557            trait_pred.rebind(self.tcx.mk_fn_sig_safe_rust_abi(expected, self.tcx.types.unit)),
3558        );
3559
3560        if !self.same_type_modulo_infer(given_ty, expected_ty) {
3561            // Print type mismatch
3562            let (expected_args, given_args) = self.cmp(expected_ty, given_ty);
3563            err.note_expected_found(
3564                "a closure with signature",
3565                expected_args,
3566                "a closure with signature",
3567                given_args,
3568            );
3569        }
3570    }
3571
3572    fn report_closure_error(
3573        &self,
3574        obligation: &PredicateObligation<'tcx>,
3575        closure_def_id: DefId,
3576        found_kind: ty::ClosureKind,
3577        kind: ty::ClosureKind,
3578        trait_prefix: &'static str,
3579        kind_origin: Option<(Span, rustc_middle::hir::place::Place<'tcx>)>,
3580    ) -> Diag<'a> {
3581        let closure_span = self.tcx.def_span(closure_def_id);
3582
3583        let mut err = ClosureKindMismatch {
3584            closure_span,
3585            expected: kind,
3586            found: found_kind,
3587            cause_span: obligation.cause.span,
3588            trait_prefix,
3589            fn_once_label: None,
3590            fn_mut_label: None,
3591        };
3592
3593        // Additional context information explaining why the closure only implements
3594        // a particular trait.
3595        let origin = kind_origin.or_else(|| {
3596            let typeck_results = self.typeck_results.as_ref()?;
3597            let local_def_id = closure_def_id.as_local()?;
3598            let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id);
3599            typeck_results.closure_kind_origins().get(hir_id).cloned()
3600        });
3601
3602        match (found_kind, origin) {
3603            (ty::ClosureKind::FnOnce, Some((span, place))) => {
3604                err.fn_once_label = Some(ClosureFnOnceLabel {
3605                    span,
3606                    place: ty::place_to_string_for_capture(self.tcx, &place),
3607                    trait_prefix,
3608                })
3609            }
3610            (ty::ClosureKind::FnMut, Some((span, place))) => {
3611                err.fn_mut_label = Some(ClosureFnMutLabel {
3612                    span,
3613                    place: ty::place_to_string_for_capture(self.tcx, &place),
3614                    trait_prefix,
3615                })
3616            }
3617            _ => {}
3618        }
3619        self.dcx().create_err(err)
3620    }
3621
3622    fn report_cyclic_signature_error(
3623        &self,
3624        obligation: &PredicateObligation<'tcx>,
3625        found_trait_ref: ty::TraitRef<'tcx>,
3626        expected_trait_ref: ty::TraitRef<'tcx>,
3627        terr: TypeError<'tcx>,
3628    ) -> Diag<'a> {
3629        let self_ty = found_trait_ref.self_ty();
3630        let (cause, terr) = if let ty::Closure(def_id, _) = *self_ty.kind() {
3631            (
3632                ObligationCause::dummy_with_span(self.tcx.def_span(def_id)),
3633                TypeError::CyclicTy(self_ty),
3634            )
3635        } else {
3636            (obligation.cause.clone(), terr)
3637        };
3638        self.report_and_explain_type_error(
3639            TypeTrace::trait_refs(&cause, expected_trait_ref, found_trait_ref),
3640            obligation.param_env,
3641            terr,
3642        )
3643    }
3644
3645    fn report_signature_mismatch_error(
3646        &self,
3647        obligation: &PredicateObligation<'tcx>,
3648        span: Span,
3649        found_trait_ref: ty::TraitRef<'tcx>,
3650        expected_trait_ref: ty::TraitRef<'tcx>,
3651    ) -> Result<Diag<'a>, ErrorGuaranteed> {
3652        let found_trait_ref = self.deeply_resolve_ignoring_regions(found_trait_ref);
3653        let expected_trait_ref = self.deeply_resolve_ignoring_regions(expected_trait_ref);
3654
3655        expected_trait_ref.self_ty().error_reported()?;
3656        let found_trait_ty = found_trait_ref.self_ty();
3657
3658        let found_did = match *found_trait_ty.kind() {
3659            ty::Closure(did, _) | ty::FnDef(did, _) | ty::Coroutine(did, ..) => Some(did),
3660            _ => None,
3661        };
3662
3663        let found_node = found_did.and_then(|did| self.tcx.hir_get_if_local(did));
3664        let found_span = found_did.and_then(|did| self.tcx.hir_span_if_local(did));
3665
3666        if !self.reported_signature_mismatch.borrow_mut().insert((span, found_span)) {
3667            // We check closures twice, with obligations flowing in different directions,
3668            // but we want to complain about them only once.
3669            return Err(self.dcx().span_delayed_bug(span, "already_reported"));
3670        }
3671
3672        let mut not_tupled = false;
3673
3674        let found = match found_trait_ref.args.type_at(1).kind() {
3675            ty::Tuple(tys) => ::alloc::vec::from_elem(ArgKind::empty(), tys.len())vec![ArgKind::empty(); tys.len()],
3676            _ => {
3677                not_tupled = true;
3678                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ArgKind::empty()]))vec![ArgKind::empty()]
3679            }
3680        };
3681
3682        let expected_ty = expected_trait_ref.args.type_at(1);
3683        let expected = match expected_ty.kind() {
3684            ty::Tuple(tys) => {
3685                tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
3686            }
3687            _ => {
3688                not_tupled = true;
3689                ::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())]
3690            }
3691        };
3692
3693        // If this is a `Fn` family trait and either the expected or found
3694        // is not tupled, then fall back to just a regular mismatch error.
3695        // This shouldn't be common unless manually implementing one of the
3696        // traits manually, but don't make it more confusing when it does
3697        // happen.
3698        if !self.tcx.is_lang_item(expected_trait_ref.def_id, LangItem::Coroutine) && not_tupled {
3699            return Ok(self.report_and_explain_type_error(
3700                TypeTrace::trait_refs(&obligation.cause, expected_trait_ref, found_trait_ref),
3701                obligation.param_env,
3702                ty::error::TypeError::Mismatch,
3703            ));
3704        }
3705        if found.len() != expected.len() {
3706            let (closure_span, closure_arg_span, found) = found_did
3707                .and_then(|did| {
3708                    let node = self.tcx.hir_get_if_local(did)?;
3709                    let (found_span, closure_arg_span, found) = self.get_fn_like_arguments(node)?;
3710                    Some((Some(found_span), closure_arg_span, found))
3711                })
3712                .unwrap_or((found_span, None, found));
3713
3714            // If the coroutine take a single () as its argument,
3715            // the trait argument would found the coroutine take 0 arguments,
3716            // but get_fn_like_arguments would give 1 argument.
3717            // This would result in "Expected to take 1 argument, but it takes 1 argument".
3718            // Check again to avoid this.
3719            if found.len() != expected.len() {
3720                return Ok(self.report_arg_count_mismatch(
3721                    span,
3722                    closure_span,
3723                    expected,
3724                    found,
3725                    found_trait_ty.is_closure(),
3726                    closure_arg_span,
3727                ));
3728            }
3729        }
3730        Ok(self.report_closure_arg_mismatch(
3731            span,
3732            found_span,
3733            found_trait_ref,
3734            expected_trait_ref,
3735            obligation.cause.code(),
3736            found_node,
3737            obligation.param_env,
3738        ))
3739    }
3740
3741    /// Given some node representing a fn-like thing in the HIR map,
3742    /// returns a span and `ArgKind` information that describes the
3743    /// arguments it expects. This can be supplied to
3744    /// `report_arg_count_mismatch`.
3745    pub fn get_fn_like_arguments(
3746        &self,
3747        node: Node<'_>,
3748    ) -> Option<(Span, Option<Span>, Vec<ArgKind>)> {
3749        let sm = self.tcx.sess.source_map();
3750        Some(match node {
3751            Node::Expr(&hir::Expr {
3752                kind: hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, fn_arg_span, .. }),
3753                ..
3754            }) => (
3755                fn_decl_span,
3756                fn_arg_span,
3757                self.tcx
3758                    .hir_body(body)
3759                    .params
3760                    .iter()
3761                    .map(|arg| {
3762                        if let hir::Pat { kind: hir::PatKind::Tuple(args, _), span, .. } = *arg.pat
3763                        {
3764                            Some(ArgKind::Tuple(
3765                                Some(span),
3766                                args.iter()
3767                                    .map(|pat| {
3768                                        sm.span_to_snippet(pat.span)
3769                                            .ok()
3770                                            .map(|snippet| (snippet, "_".to_owned()))
3771                                    })
3772                                    .collect::<Option<Vec<_>>>()?,
3773                            ))
3774                        } else {
3775                            let name = sm.span_to_snippet(arg.pat.span).ok()?;
3776                            Some(ArgKind::Arg(name, "_".to_owned()))
3777                        }
3778                    })
3779                    .collect::<Option<Vec<ArgKind>>>()?,
3780            ),
3781            Node::Item(&hir::Item { kind: hir::ItemKind::Fn { ref sig, .. }, .. })
3782            | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(ref sig, _), .. })
3783            | Node::TraitItem(&hir::TraitItem {
3784                kind: hir::TraitItemKind::Fn(ref sig, _), ..
3785            })
3786            | Node::ForeignItem(&hir::ForeignItem {
3787                kind: hir::ForeignItemKind::Fn(ref sig, _, _),
3788                ..
3789            }) => (
3790                sig.span,
3791                None,
3792                sig.decl
3793                    .inputs
3794                    .iter()
3795                    .map(|arg| match arg.kind {
3796                        hir::TyKind::Tup(tys) => ArgKind::Tuple(
3797                            Some(arg.span),
3798                            ::alloc::vec::from_elem(("_".to_owned(), "_".to_owned()), tys.len())vec![("_".to_owned(), "_".to_owned()); tys.len()],
3799                        ),
3800                        _ => ArgKind::empty(),
3801                    })
3802                    .collect::<Vec<ArgKind>>(),
3803            ),
3804            Node::Ctor(variant_data) => {
3805                let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| self.tcx.hir_span(id));
3806                (span, None, ::alloc::vec::from_elem(ArgKind::empty(), variant_data.fields().len())vec![ArgKind::empty(); variant_data.fields().len()])
3807            }
3808            _ => {
    ::core::panicking::panic_fmt(format_args!("non-FnLike node found: {0:?}",
            node));
}panic!("non-FnLike node found: {node:?}"),
3809        })
3810    }
3811
3812    /// Reports an error when the number of arguments needed by a
3813    /// trait match doesn't match the number that the expression
3814    /// provides.
3815    pub fn report_arg_count_mismatch(
3816        &self,
3817        span: Span,
3818        found_span: Option<Span>,
3819        expected_args: Vec<ArgKind>,
3820        found_args: Vec<ArgKind>,
3821        is_closure: bool,
3822        closure_arg_span: Option<Span>,
3823    ) -> Diag<'a> {
3824        let kind = if is_closure { "closure" } else { "function" };
3825
3826        let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
3827            let arg_length = arguments.len();
3828            let distinct = #[allow(non_exhaustive_omitted_patterns)] match other {
    &[ArgKind::Tuple(..)] => true,
    _ => false,
}matches!(other, &[ArgKind::Tuple(..)]);
3829            match (arg_length, arguments.get(0)) {
3830                (1, Some(ArgKind::Tuple(_, fields))) => {
3831                    ::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())
3832                }
3833                _ => ::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!(
3834                    "{} {}argument{}",
3835                    arg_length,
3836                    if distinct && arg_length > 1 { "distinct " } else { "" },
3837                    pluralize!(arg_length)
3838                ),
3839            }
3840        };
3841
3842        let expected_str = args_str(&expected_args, &found_args);
3843        let found_str = args_str(&found_args, &expected_args);
3844
3845        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!(
3846            self.dcx(),
3847            span,
3848            E0593,
3849            "{} is expected to take {}, but it takes {}",
3850            kind,
3851            expected_str,
3852            found_str,
3853        );
3854
3855        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}"));
3856
3857        if let Some(found_span) = found_span {
3858            err.span_label(found_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("takes {0}", found_str))
    })format!("takes {found_str}"));
3859
3860            // Suggest to take and ignore the arguments with expected_args_length `_`s if
3861            // found arguments is empty (assume the user just wants to ignore args in this case).
3862            // For example, if `expected_args_length` is 2, suggest `|_, _|`.
3863            if found_args.is_empty() && is_closure {
3864                let underscores = ::alloc::vec::from_elem("_", expected_args.len())vec!["_"; expected_args.len()].join(", ");
3865                err.span_suggestion_verbose(
3866                    closure_arg_span.unwrap_or(found_span),
3867                    ::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!(
3868                        "consider changing the closure to take and ignore the expected argument{}",
3869                        pluralize!(expected_args.len())
3870                    ),
3871                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("|{0}|", underscores))
    })format!("|{underscores}|"),
3872                    Applicability::MachineApplicable,
3873                );
3874            }
3875
3876            if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
3877                if fields.len() == expected_args.len() {
3878                    let sugg = fields
3879                        .iter()
3880                        .map(|(name, _)| name.to_owned())
3881                        .collect::<Vec<String>>()
3882                        .join(", ");
3883                    err.span_suggestion_verbose(
3884                        found_span,
3885                        "change the closure to take multiple arguments instead of a single tuple",
3886                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("|{0}|", sugg))
    })format!("|{sugg}|"),
3887                        Applicability::MachineApplicable,
3888                    );
3889                }
3890            }
3891            if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..]
3892                && fields.len() == found_args.len()
3893                && is_closure
3894            {
3895                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!(
3896                    "|({}){}|",
3897                    found_args
3898                        .iter()
3899                        .map(|arg| match arg {
3900                            ArgKind::Arg(name, _) => name.to_owned(),
3901                            _ => "_".to_owned(),
3902                        })
3903                        .collect::<Vec<String>>()
3904                        .join(", "),
3905                    // add type annotations if available
3906                    if found_args.iter().any(|arg| match arg {
3907                        ArgKind::Arg(_, ty) => ty != "_",
3908                        _ => false,
3909                    }) {
3910                        format!(
3911                            ": ({})",
3912                            fields
3913                                .iter()
3914                                .map(|(_, ty)| ty.to_owned())
3915                                .collect::<Vec<String>>()
3916                                .join(", ")
3917                        )
3918                    } else {
3919                        String::new()
3920                    },
3921                );
3922                err.span_suggestion_verbose(
3923                    found_span,
3924                    "change the closure to accept a tuple instead of individual arguments",
3925                    sugg,
3926                    Applicability::MachineApplicable,
3927                );
3928            }
3929        }
3930
3931        err
3932    }
3933
3934    /// Checks if the type implements one of `Fn`, `FnMut`, or `FnOnce`
3935    /// in that order, and returns the generic type corresponding to the
3936    /// argument of that trait (corresponding to the closure arguments).
3937    pub fn type_implements_fn_trait(
3938        &self,
3939        param_env: ty::ParamEnv<'tcx>,
3940        ty: ty::Binder<'tcx, Ty<'tcx>>,
3941        polarity: ty::ClausePolarity,
3942    ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> {
3943        self.commit_if_ok(|_| {
3944            for trait_def_id in [
3945                self.tcx.lang_items().fn_trait(),
3946                self.tcx.lang_items().fn_mut_trait(),
3947                self.tcx.lang_items().fn_once_trait(),
3948            ] {
3949                let Some(trait_def_id) = trait_def_id else { continue };
3950                // Make a fresh inference variable so we can determine what the generic parameters
3951                // of the trait are.
3952                let var = self.next_ty_var(DUMMY_SP);
3953                // FIXME(const_trait_impl)
3954                let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, [ty.skip_binder(), var]);
3955                let obligation = Obligation::new(
3956                    self.tcx,
3957                    ObligationCause::dummy(),
3958                    param_env,
3959                    ty.rebind(ty::TraitClause { trait_ref, polarity }),
3960                );
3961                let ocx = ObligationCtxt::new(self);
3962                ocx.register_obligation(obligation);
3963                if ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
3964                    return Ok((
3965                        self.tcx
3966                            .fn_trait_kind_from_def_id(trait_def_id)
3967                            .expect("expected to map DefId to ClosureKind"),
3968                        ty.rebind(self.deeply_resolve_ignoring_regions(var)),
3969                    ));
3970                }
3971            }
3972
3973            Err(())
3974        })
3975    }
3976
3977    fn report_not_const_evaluatable_error(
3978        &self,
3979        obligation: &PredicateObligation<'tcx>,
3980        span: Span,
3981    ) -> Result<Diag<'a>, ErrorGuaranteed> {
3982        if !self.tcx.features().generic_const_exprs()
3983            && !self.tcx.features().min_generic_const_args()
3984        {
3985            let guar = self
3986                .dcx()
3987                .struct_span_err(span, "constant expression depends on a generic parameter")
3988                // FIXME(const_generics): we should suggest to the user how they can resolve this
3989                // issue. However, this is currently not actually possible
3990                // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
3991                //
3992                // Note that with `feature(generic_const_exprs)` this case should not
3993                // be reachable.
3994                .with_note("this may fail depending on what value the parameter takes")
3995                .emit();
3996            return Err(guar);
3997        }
3998
3999        match obligation.predicate.kind().skip_binder() {
4000            ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => match ct.kind() {
4001                ty::ConstKind::Alias(_, alias_const) => {
4002                    let mut err =
4003                        self.dcx().struct_span_err(span, "unconstrained generic constant");
4004
4005                    let const_span = alias_const.kind.def_span(self.tcx);
4006                    let const_ty = alias_const.type_of(self.tcx).skip_norm_wip();
4007
4008                    let msg = "try adding a `where` bound";
4009                    if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(const_span) {
4010                        let code = if const_ty == self.tcx.types.usize {
4011                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("[(); {0}]:", snippet))
    })format!("[(); {snippet}]:")
4012                        } else if let ty::AliasConstKind::Anon { def_id } = alias_const.kind
4013                            && let Some(local_def_id) = def_id.as_local()
4014                            && let Some(local_body) = self.tcx.hir_maybe_body_owned_by(local_def_id)
4015                            && expr_needs_parens(local_body.value)
4016                        {
4017                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("[(); ({0}) as usize]:", snippet))
    })format!("[(); ({snippet}) as usize]:")
4018                        } else {
4019                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("[(); {0} as usize]:", snippet))
    })format!("[(); {snippet} as usize]:")
4020                        };
4021
4022                        let suggestion_def_id = if let ObligationCauseCode::CompareImplItem {
4023                            trait_item_def_id,
4024                            ..
4025                        } = obligation.cause.code()
4026                        {
4027                            trait_item_def_id.as_local()
4028                        } else {
4029                            Some(obligation.cause.body_def_id)
4030                        };
4031
4032                        if let Some(suggestion_def_id) = suggestion_def_id
4033                            && let Some(generics) = self.tcx.hir_get_generics(suggestion_def_id)
4034                        {
4035                            err.span_suggestion_verbose(
4036                                generics.tail_span_for_predicate_suggestion(),
4037                                msg,
4038                                ::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()),
4039                                Applicability::MaybeIncorrect,
4040                            );
4041                        } else {
4042                            err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: where {1}", msg, code))
    })format!("{msg}: where {code}"));
4043                        };
4044                    } else {
4045                        err.help(msg);
4046                    }
4047                    Ok(err)
4048                }
4049                ty::ConstKind::Expr(_) => {
4050                    let err = self
4051                        .dcx()
4052                        .struct_span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unconstrained generic constant `{0}`",
                ct))
    })format!("unconstrained generic constant `{ct}`"));
4053                    Ok(err)
4054                }
4055                _ => {
4056                    ::rustc_middle::util::bug::bug_fmt(format_args!("const evaluatable failed for non-alias const `{0:?}`",
        ct));bug!("const evaluatable failed for non-alias const `{ct:?}`");
4057                }
4058            },
4059            _ => {
4060                ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("unexpected non-ConstEvaluatable predicate, this should not be reachable"))span_bug!(
4061                    span,
4062                    "unexpected non-ConstEvaluatable predicate, this should not be reachable"
4063                )
4064            }
4065        }
4066    }
4067}