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