Skip to main content

rustc_trait_selection/error_reporting/traits/
fulfillment_errors.rs

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