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