Skip to main content

rustc_trait_selection/error_reporting/traits/
fulfillment_errors.rs

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