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