Skip to main content

rustc_trait_selection/error_reporting/traits/
fulfillment_errors.rs

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