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