Skip to main content

rustc_trait_selection/error_reporting/traits/
fulfillment_errors.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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