Skip to main content

rustc_trait_selection/error_reporting/traits/
fulfillment_errors.rs

1// ignore-tidy-filelength
2use core::ops::ControlFlow;
3use std::borrow::Cow;
4use std::collections::hash_set;
5use std::path::PathBuf;
6
7use rustc_abi::ExternAbi;
8use rustc_ast::ast::LitKind;
9use rustc_ast::{LitIntType, TraitObjectSyntax};
10use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11use rustc_data_structures::unord::UnordSet;
12use rustc_errors::codes::*;
13use rustc_errors::{
14    Applicability, Diag, ErrorGuaranteed, Level, MultiSpan, StashKey, StringPart, Suggestions,
15    pluralize, struct_span_code_err,
16};
17use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
18use rustc_hir::intravisit::Visitor;
19use rustc_hir::{self as hir, LangItem, Node};
20use rustc_infer::infer::{InferOk, TypeTrace};
21use rustc_infer::traits::ImplSource;
22use rustc_infer::traits::solve::Goal;
23use rustc_middle::traits::SignatureMismatchData;
24use rustc_middle::traits::select::OverflowError;
25use rustc_middle::ty::abstract_const::NotConstEvaluatable;
26use rustc_middle::ty::error::{ExpectedFound, TypeError};
27use rustc_middle::ty::print::{
28    PrintPolyTraitPredicateExt, PrintTraitPredicateExt as _, PrintTraitRefExt as _,
29    with_forced_trimmed_paths,
30};
31use rustc_middle::ty::{
32    self, GenericArgKind, TraitRef, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
33    TypeVisitableExt, 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::on_unimplemented::{AppendConstMessage, OnUnimplementedNote};
41use super::suggestions::get_explanation_based_on_obligation;
42use super::{
43    ArgKind, CandidateSimilarity, FindExprBySpan, GetSafeTransmuteErrorAndReason, ImplCandidate,
44};
45use crate::error_reporting::TypeErrCtxt;
46use crate::error_reporting::infer::TyCategory;
47use crate::error_reporting::traits::on_unimplemented::OnUnimplementedDirective;
48use crate::error_reporting::traits::report_dyn_incompatibility;
49use crate::errors::{ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch, CoroClosureNotFn};
50use crate::infer::{self, InferCtxt, InferCtxtExt as _};
51use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
52use crate::traits::{
53    MismatchedProjectionTypes, NormalizeExt, Obligation, ObligationCause, ObligationCauseCode,
54    ObligationCtxt, PredicateObligation, SelectionContext, SelectionError, elaborate,
55    specialization_graph,
56};
57
58impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
59    /// The `root_obligation` parameter should be the `root_obligation` field
60    /// from a `FulfillmentError`. If no `FulfillmentError` is available,
61    /// then it should be the same as `obligation`.
62    pub fn report_selection_error(
63        &self,
64        mut obligation: PredicateObligation<'tcx>,
65        root_obligation: &PredicateObligation<'tcx>,
66        error: &SelectionError<'tcx>,
67    ) -> ErrorGuaranteed {
68        let tcx = self.tcx;
69        let mut span = obligation.cause.span;
70        let mut long_ty_file = None;
71
72        let mut err = match *error {
73            SelectionError::Unimplemented => {
74                // If this obligation was generated as a result of well-formedness checking, see if we
75                // can get a better error message by performing HIR-based well-formedness checking.
76                if let ObligationCauseCode::WellFormed(Some(wf_loc)) =
77                    root_obligation.cause.code().peel_derives()
78                    && !obligation.predicate.has_non_region_infer()
79                {
80                    if let Some(cause) = self
81                        .tcx
82                        .diagnostic_hir_wf_check((tcx.erase_and_anonymize_regions(obligation.predicate), *wf_loc))
83                    {
84                        obligation.cause = cause.clone();
85                        span = obligation.cause.span;
86                    }
87                }
88
89                if let ObligationCauseCode::CompareImplItem {
90                    impl_item_def_id,
91                    trait_item_def_id,
92                    kind: _,
93                } = *obligation.cause.code()
94                {
95                    {
    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:95",
                        "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(95u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::fulfillment_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("ObligationCauseCode::CompareImplItemObligation")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("ObligationCauseCode::CompareImplItemObligation");
96                    return self.report_extra_impl_obligation(
97                        span,
98                        impl_item_def_id,
99                        trait_item_def_id,
100                        &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", obligation.predicate))
    })format!("`{}`", obligation.predicate),
101                    )
102                    .emit()
103                }
104
105                // Report a const-param specific error
106                if let ObligationCauseCode::ConstParam(ty) = *obligation.cause.code().peel_derives()
107                {
108                    return self.report_const_param_not_wf(ty, &obligation).emit();
109                }
110
111                let bound_predicate = obligation.predicate.kind();
112                match bound_predicate.skip_binder() {
113                    ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_predicate)) => {
114                        let leaf_trait_predicate =
115                            self.resolve_vars_if_possible(bound_predicate.rebind(trait_predicate));
116
117                        // Let's use the root obligation as the main message, when we care about the
118                        // most general case ("X doesn't implement Pattern<'_>") over the case that
119                        // happened to fail ("char doesn't implement Fn(&mut char)").
120                        //
121                        // We rely on a few heuristics to identify cases where this root
122                        // obligation is more important than the leaf obligation:
123                        let (main_trait_predicate, main_obligation) = 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.emit_specialized_closure_kind_error(
165                            &obligation,
166                            leaf_trait_predicate,
167                        ) {
168                            return guar;
169                        }
170
171                        if let Err(guar) = leaf_trait_predicate.error_reported()
172                        {
173                            return guar;
174                        }
175                        // Silence redundant errors on binding access that are already
176                        // reported on the binding definition (#56607).
177                        if let Err(guar) = self.fn_arg_obligation(&obligation) {
178                            return guar;
179                        }
180                        let (post_message, pre_message, type_def) = self
181                            .get_parent_trait_ref(obligation.cause.code())
182                            .map(|(t, s)| {
183                                let t = self.tcx.short_string(t, &mut long_ty_file);
184                                (
185                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" in `{0}`", t))
    })format!(" in `{t}`"),
186                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("within `{0}`, ", t))
    })format!("within `{t}`, "),
187                                    s.map(|s| (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("within this `{0}`", t))
    })format!("within this `{t}`"), s)),
188                                )
189                            })
190                            .unwrap_or_default();
191
192                        let OnUnimplementedNote {
193                            message,
194                            label,
195                            notes,
196                            parent_label,
197                            append_const_msg,
198                        } = self.on_unimplemented_note(main_trait_predicate, main_obligation, &mut long_ty_file);
199
200                        let have_alt_message = message.is_some() || label.is_some();
201                        let is_try_conversion = self.is_try_conversion(span, main_trait_predicate.def_id());
202                        let is_question_mark = #[allow(non_exhaustive_omitted_patterns)] match root_obligation.cause.code().peel_derives()
    {
    ObligationCauseCode::QuestionMark => true,
    _ => false,
}matches!(
203                            root_obligation.cause.code().peel_derives(),
204                            ObligationCauseCode::QuestionMark,
205                        ) && !(
206                            self.tcx.is_diagnostic_item(sym::FromResidual, main_trait_predicate.def_id())
207                                || self.tcx.is_lang_item(main_trait_predicate.def_id(), LangItem::Try)
208                        );
209                        let is_unsize =
210                            self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Unsize);
211                        let question_mark_message = "the question mark operation (`?`) implicitly \
212                                                     performs a conversion on the error value \
213                                                     using the `From` trait";
214                        let (message, notes, append_const_msg) = if is_try_conversion {
215                            let ty = self.tcx.short_string(
216                                main_trait_predicate.skip_binder().self_ty(),
217                                &mut long_ty_file,
218                            );
219                            // We have a `-> Result<_, E1>` and `gives_E2()?`.
220                            (
221                                Some(::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}`")),
222                                <[_]>::into_vec(::alloc::boxed::box_new([question_mark_message.to_owned()]))vec![question_mark_message.to_owned()],
223                                Some(AppendConstMessage::Default),
224                            )
225                        } else if is_question_mark {
226                            let main_trait_predicate =
227                                self.tcx.short_string(main_trait_predicate, &mut long_ty_file);
228                            // Similar to the case above, but in this case the conversion is for a
229                            // trait object: `-> Result<_, Box<dyn Error>` and `gives_E()?` when
230                            // `E: Error` isn't met.
231                            (
232                                Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`?` couldn\'t convert the error: `{0}` is not satisfied",
                main_trait_predicate))
    })format!(
233                                    "`?` couldn't convert the error: `{main_trait_predicate}` is \
234                                     not satisfied",
235                                )),
236                                <[_]>::into_vec(::alloc::boxed::box_new([question_mark_message.to_owned()]))vec![question_mark_message.to_owned()],
237                                Some(AppendConstMessage::Default),
238                            )
239                        } else {
240                            (message, notes, append_const_msg)
241                        };
242
243                        let default_err_msg = || self.get_standard_error_message(
244                            main_trait_predicate,
245                            message,
246                            None,
247                            append_const_msg,
248                            post_message,
249                            &mut long_ty_file,
250                        );
251
252                        let (err_msg, safe_transmute_explanation) = if self.tcx.is_lang_item(
253                            main_trait_predicate.def_id(),
254                            LangItem::TransmuteTrait,
255                        ) {
256                            // Recompute the safe transmute reason and use that for the error reporting
257                            match self.get_safe_transmute_error_and_reason(
258                                obligation.clone(),
259                                main_trait_predicate,
260                                span,
261                            ) {
262                                GetSafeTransmuteErrorAndReason::Silent => {
263                                    return self.dcx().span_delayed_bug(
264                                        span, "silent safe transmute error"
265                                    );
266                                }
267                                GetSafeTransmuteErrorAndReason::Default => {
268                                    (default_err_msg(), None)
269                                }
270                                GetSafeTransmuteErrorAndReason::Error {
271                                    err_msg,
272                                    safe_transmute_explanation,
273                                } => (err_msg, safe_transmute_explanation),
274                            }
275                        } else {
276                            (default_err_msg(), None)
277                        };
278
279                        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);
280                        *err.long_ty_path() = long_ty_file;
281
282                        let mut suggested = false;
283                        let mut noted_missing_impl = false;
284                        if is_try_conversion || is_question_mark {
285                            (suggested, noted_missing_impl) = self.try_conversion_context(&obligation, main_trait_predicate, &mut err);
286                        }
287
288                        suggested |= self.detect_negative_literal(
289                            &obligation,
290                            main_trait_predicate,
291                            &mut err,
292                        );
293
294                        if let Some(ret_span) = self.return_type_span(&obligation) {
295                            if is_try_conversion {
296                                let ty = self.tcx.short_string(
297                                    main_trait_predicate.skip_binder().self_ty(),
298                                    err.long_ty_path(),
299                                );
300                                err.span_label(
301                                    ret_span,
302                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}` because of this",
                ty))
    })format!("expected `{ty}` because of this"),
303                                );
304                            } else if is_question_mark {
305                                let main_trait_predicate =
306                                    self.tcx.short_string(main_trait_predicate, err.long_ty_path());
307                                err.span_label(
308                                    ret_span,
309                                    ::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"),
310                                );
311                            }
312                        }
313
314                        if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Tuple) {
315                            self.add_tuple_trait_message(
316                                obligation.cause.code().peel_derives(),
317                                &mut err,
318                            );
319                        }
320
321                        let explanation = get_explanation_based_on_obligation(
322                            self.tcx,
323                            &obligation,
324                            leaf_trait_predicate,
325                            pre_message,
326                            err.long_ty_path(),
327                        );
328
329                        self.check_for_binding_assigned_block_without_tail_expression(
330                            &obligation,
331                            &mut err,
332                            leaf_trait_predicate,
333                        );
334                        self.suggest_add_result_as_return_type(
335                            &obligation,
336                            &mut err,
337                            leaf_trait_predicate,
338                        );
339
340                        if self.suggest_add_reference_to_arg(
341                            &obligation,
342                            &mut err,
343                            leaf_trait_predicate,
344                            have_alt_message,
345                        ) {
346                            self.note_obligation_cause(&mut err, &obligation);
347                            return err.emit();
348                        }
349
350                        let ty_span = match leaf_trait_predicate.self_ty().skip_binder().kind() {
351                            ty::Adt(def, _) if def.did().is_local()
352                                && !self.can_suggest_derive(&obligation, leaf_trait_predicate) => self.tcx.def_span(def.did()),
353                            _ => DUMMY_SP,
354                        };
355                        if let Some(s) = label {
356                            // If it has a custom `#[rustc_on_unimplemented]`
357                            // error message, let's display it as the label!
358                            err.span_label(span, s);
359                            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(_))
360                                // When the self type is a type param We don't need to "the trait
361                                // `std::marker::Sized` is not implemented for `T`" as we will point
362                                // at the type param with a label to suggest constraining it.
363                                && !self.tcx.is_diagnostic_item(sym::FromResidual, leaf_trait_predicate.def_id())
364                                    // Don't say "the trait `FromResidual<Option<Infallible>>` is
365                                    // not implemented for `Result<T, E>`".
366                            {
367                                // We do this just so that the JSON output's `help` position is the
368                                // right one and not `file.rs:1:1`. The render is the same.
369                                if ty_span == DUMMY_SP {
370                                    err.help(explanation);
371                                } else {
372                                    err.span_help(ty_span, explanation);
373                                }
374                            }
375                        } else if let Some(custom_explanation) = safe_transmute_explanation {
376                            err.span_label(span, custom_explanation);
377                        } else if (explanation.len() > self.tcx.sess.diagnostic_width() || ty_span != DUMMY_SP) && !noted_missing_impl {
378                            // Really long types don't look good as span labels, instead move it
379                            // to a `help`.
380                            err.span_label(span, "unsatisfied trait bound");
381
382                            // We do this just so that the JSON output's `help` position is the
383                            // right one and not `file.rs:1:1`. The render is the same.
384                            if ty_span == DUMMY_SP {
385                                err.help(explanation);
386                            } else {
387                                err.span_help(ty_span, explanation);
388                            }
389                        } else {
390                            err.span_label(span, explanation);
391                        }
392
393                        if let ObligationCauseCode::Coercion { source, target } =
394                            *obligation.cause.code().peel_derives()
395                        {
396                            if self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Sized) {
397                                self.suggest_borrowing_for_object_cast(
398                                    &mut err,
399                                    root_obligation,
400                                    source,
401                                    target,
402                                );
403                            }
404                        }
405
406                        if let Some((msg, span)) = type_def {
407                            err.span_label(span, msg);
408                        }
409                        for note in notes {
410                            // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
411                            err.note(note);
412                        }
413                        if let Some(s) = parent_label {
414                            let body = obligation.cause.body_id;
415                            err.span_label(tcx.def_span(body), s);
416                        }
417
418                        self.suggest_floating_point_literal(&obligation, &mut err, leaf_trait_predicate);
419                        self.suggest_dereferencing_index(&obligation, &mut err, leaf_trait_predicate);
420                        suggested |= self.suggest_dereferences(&obligation, &mut err, leaf_trait_predicate);
421                        suggested |= self.suggest_fn_call(&obligation, &mut err, leaf_trait_predicate);
422                        let impl_candidates = self.find_similar_impl_candidates(leaf_trait_predicate);
423                        suggested = if let &[cand] = &impl_candidates[..] {
424                            let cand = cand.trait_ref;
425                            if let (ty::FnPtr(..), ty::FnDef(..)) =
426                                (cand.self_ty().kind(), main_trait_predicate.self_ty().skip_binder().kind())
427                            {
428                                // Wrap method receivers and `&`-references in parens
429                                let suggestion = if self.tcx.sess.source_map().span_look_ahead(span, ".", Some(50)).is_some() {
430                                    <[_]>::into_vec(::alloc::boxed::box_new([(span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("("))
                        })),
                (span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(" as {0})",
                                    cand.self_ty()))
                        }))]))vec![
431                                        (span.shrink_to_lo(), format!("(")),
432                                        (span.shrink_to_hi(), format!(" as {})", cand.self_ty())),
433                                    ]
434                                } else if let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id) {
435                                    let mut expr_finder = FindExprBySpan::new(span, self.tcx);
436                                    expr_finder.visit_expr(body.value);
437                                    if let Some(expr) = expr_finder.result &&
438                                        let hir::ExprKind::AddrOf(_, _, expr) = expr.kind {
439                                        <[_]>::into_vec(::alloc::boxed::box_new([(expr.span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("("))
                        })),
                (expr.span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(" as {0})",
                                    cand.self_ty()))
                        }))]))vec![
440                                            (expr.span.shrink_to_lo(), format!("(")),
441                                            (expr.span.shrink_to_hi(), format!(" as {})", cand.self_ty())),
442                                        ]
443                                    } else {
444                                        <[_]>::into_vec(::alloc::boxed::box_new([(span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(" as {0}",
                                    cand.self_ty()))
                        }))]))vec![(span.shrink_to_hi(), format!(" as {}", cand.self_ty()))]
445                                    }
446                                } else {
447                                    <[_]>::into_vec(::alloc::boxed::box_new([(span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(" as {0}",
                                    cand.self_ty()))
                        }))]))vec![(span.shrink_to_hi(), format!(" as {}", cand.self_ty()))]
448                                };
449                                let trait_ = self.tcx.short_string(cand.print_trait_sugared(), err.long_ty_path());
450                                let ty = self.tcx.short_string(cand.self_ty(), err.long_ty_path());
451                                err.multipart_suggestion(
452                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the trait `{0}` is implemented for fn pointer `{1}`, try casting using `as`",
                trait_, ty))
    })format!(
453                                        "the trait `{trait_}` is implemented for fn pointer \
454                                         `{ty}`, try casting using `as`",
455                                    ),
456                                    suggestion,
457                                    Applicability::MaybeIncorrect,
458                                );
459                                true
460                            } else {
461                                false
462                            }
463                        } else {
464                            false
465                        } || suggested;
466                        suggested |=
467                            self.suggest_remove_reference(&obligation, &mut err, leaf_trait_predicate);
468                        suggested |= self.suggest_semicolon_removal(
469                            &obligation,
470                            &mut err,
471                            span,
472                            leaf_trait_predicate,
473                        );
474                        self.note_different_trait_with_same_name(&mut err, &obligation, leaf_trait_predicate);
475                        self.note_adt_version_mismatch(&mut err, leaf_trait_predicate);
476                        self.suggest_remove_await(&obligation, &mut err);
477                        self.suggest_derive(&obligation, &mut err, leaf_trait_predicate);
478
479                        if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Try) {
480                            self.suggest_await_before_try(
481                                &mut err,
482                                &obligation,
483                                leaf_trait_predicate,
484                                span,
485                            );
486                        }
487
488                        if self.suggest_add_clone_to_arg(&obligation, &mut err, leaf_trait_predicate) {
489                            return err.emit();
490                        }
491
492                        if self.suggest_impl_trait(&mut err, &obligation, leaf_trait_predicate) {
493                            return err.emit();
494                        }
495
496                        if is_unsize {
497                            // If the obligation failed due to a missing implementation of the
498                            // `Unsize` trait, give a pointer to why that might be the case
499                            err.note(
500                                "all implementations of `Unsize` are provided \
501                                automatically by the compiler, see \
502                                <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
503                                for more information",
504                            );
505                        }
506
507                        let is_fn_trait = tcx.is_fn_trait(leaf_trait_predicate.def_id());
508                        let is_target_feature_fn = if let ty::FnDef(def_id, _) =
509                            *leaf_trait_predicate.skip_binder().self_ty().kind()
510                        {
511                            !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
512                        } else {
513                            false
514                        };
515                        if is_fn_trait && is_target_feature_fn {
516                            err.note(
517                                "`#[target_feature]` functions do not implement the `Fn` traits",
518                            );
519                            err.note(
520                                "try casting the function to a `fn` pointer or wrapping it in a closure",
521                            );
522                        }
523
524                        self.try_to_add_help_message(
525                            &root_obligation,
526                            &obligation,
527                            leaf_trait_predicate,
528                            &mut err,
529                            span,
530                            is_fn_trait,
531                            suggested,
532                        );
533
534                        // Changing mutability doesn't make a difference to whether we have
535                        // an `Unsize` impl (Fixes ICE in #71036)
536                        if !is_unsize {
537                            self.suggest_change_mut(&obligation, &mut err, leaf_trait_predicate);
538                        }
539
540                        // If this error is due to `!: Trait` not implemented but `(): Trait` is
541                        // implemented, and fallback has occurred, then it could be due to a
542                        // variable that used to fallback to `()` now falling back to `!`. Issue a
543                        // note informing about the change in behaviour.
544                        if leaf_trait_predicate.skip_binder().self_ty().is_never()
545                            && self.diverging_fallback_has_occurred
546                        {
547                            let predicate = leaf_trait_predicate.map_bound(|trait_pred| {
548                                trait_pred.with_replaced_self_ty(self.tcx, tcx.types.unit)
549                            });
550                            let unit_obligation = obligation.with(tcx, predicate);
551                            if self.predicate_may_hold(&unit_obligation) {
552                                err.note(
553                                    "this error might have been caused by changes to \
554                                    Rust's type-inference algorithm (see issue #148922 \
555                                    <https://github.com/rust-lang/rust/issues/148922> \
556                                    for more information)",
557                                );
558                                err.help("you might have intended to use the type `()` here instead");
559                            }
560                        }
561
562                        self.explain_hrtb_projection(&mut err, leaf_trait_predicate, obligation.param_env, &obligation.cause);
563                        self.suggest_desugaring_async_fn_in_trait(&mut err, main_trait_predicate);
564
565                        // Return early if the trait is Debug or Display and the invocation
566                        // originates within a standard library macro, because the output
567                        // is otherwise overwhelming and unhelpful (see #85844 for an
568                        // example).
569
570                        let in_std_macro =
571                            match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
572                                Some(macro_def_id) => {
573                                    let crate_name = tcx.crate_name(macro_def_id.krate);
574                                    STDLIB_STABLE_CRATES.contains(&crate_name)
575                                }
576                                None => false,
577                            };
578
579                        if in_std_macro
580                            && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.get_diagnostic_name(leaf_trait_predicate.def_id())
    {
    Some(sym::Debug | sym::Display) => true,
    _ => false,
}matches!(
581                                self.tcx.get_diagnostic_name(leaf_trait_predicate.def_id()),
582                                Some(sym::Debug | sym::Display)
583                            )
584                        {
585                            return err.emit();
586                        }
587
588                        err
589                    }
590
591                    ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => {
592                        self.report_host_effect_error(bound_predicate.rebind(predicate), &obligation, span)
593                    }
594
595                    ty::PredicateKind::Subtype(predicate) => {
596                        // Errors for Subtype predicates show up as
597                        // `FulfillmentErrorCode::SubtypeError`,
598                        // not selection error.
599                        ::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)
600                    }
601
602                    ty::PredicateKind::Coerce(predicate) => {
603                        // Errors for Coerce predicates show up as
604                        // `FulfillmentErrorCode::SubtypeError`,
605                        // not selection error.
606                        ::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)
607                    }
608
609                    ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(..))
610                    | ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(..)) => {
611                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("outlives clauses should not error outside borrowck. obligation: `{0:?}`",
        obligation))span_bug!(
612                            span,
613                            "outlives clauses should not error outside borrowck. obligation: `{:?}`",
614                            obligation
615                        )
616                    }
617
618                    ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) => {
619                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("projection clauses should be implied from elsewhere. obligation: `{0:?}`",
        obligation))span_bug!(
620                            span,
621                            "projection clauses should be implied from elsewhere. obligation: `{:?}`",
622                            obligation
623                        )
624                    }
625
626                    ty::PredicateKind::DynCompatible(trait_def_id) => {
627                        let violations = self.tcx.dyn_compatibility_violations(trait_def_id);
628                        let mut err = report_dyn_incompatibility(
629                            self.tcx,
630                            span,
631                            None,
632                            trait_def_id,
633                            violations,
634                        );
635                        if let hir::Node::Item(item) =
636                            self.tcx.hir_node_by_def_id(obligation.cause.body_id)
637                            && let hir::ItemKind::Impl(impl_) = item.kind
638                            && let None = impl_.of_trait
639                            && let hir::TyKind::TraitObject(_, tagged_ptr) = impl_.self_ty.kind
640                            && let TraitObjectSyntax::None = tagged_ptr.tag()
641                            && impl_.self_ty.span.edition().at_least_rust_2021()
642                        {
643                            // Silence the dyn-compatibility error in favor of the missing dyn on
644                            // self type error. #131051.
645                            err.downgrade_to_delayed_bug();
646                        }
647                        err
648                    }
649
650                    ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(ty)) => {
651                        let ty = self.resolve_vars_if_possible(ty);
652                        if self.next_trait_solver() {
653                            if let Err(guar) = ty.error_reported() {
654                                return guar;
655                            }
656
657                            // FIXME: we'll need a better message which takes into account
658                            // which bounds actually failed to hold.
659                            self.dcx().struct_span_err(
660                                span,
661                                ::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"),
662                            )
663                        } else {
664                            // WF predicates cannot themselves make
665                            // errors. They can only block due to
666                            // ambiguity; otherwise, they always
667                            // degenerate into other obligations
668                            // (which may fail).
669                            ::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);
670                        }
671                    }
672
673                    // Errors for `ConstEvaluatable` predicates show up as
674                    // `SelectionError::ConstEvalFailure`,
675                    // not `Unimplemented`.
676                    ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
677                    // Errors for `ConstEquate` predicates show up as
678                    // `SelectionError::ConstEvalFailure`,
679                    // not `Unimplemented`.
680                    | ty::PredicateKind::ConstEquate { .. }
681                    // Ambiguous predicates should never error
682                    | ty::PredicateKind::Ambiguous
683                    // We never return Err when proving UnstableFeature goal.
684                    | ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature { .. })
685                    | ty::PredicateKind::NormalizesTo { .. }
686                    | ty::PredicateKind::AliasRelate { .. }
687                    | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType { .. }) => {
688                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("Unexpected `Predicate` for `SelectionError`: `{0:?}`",
        obligation))span_bug!(
689                            span,
690                            "Unexpected `Predicate` for `SelectionError`: `{:?}`",
691                            obligation
692                        )
693                    }
694                }
695            }
696
697            SelectionError::SignatureMismatch(box SignatureMismatchData {
698                found_trait_ref,
699                expected_trait_ref,
700                terr: terr @ TypeError::CyclicTy(_),
701            }) => self.report_cyclic_signature_error(
702                &obligation,
703                found_trait_ref,
704                expected_trait_ref,
705                terr,
706            ),
707            SelectionError::SignatureMismatch(box SignatureMismatchData {
708                found_trait_ref,
709                expected_trait_ref,
710                terr: _,
711            }) => {
712                match self.report_signature_mismatch_error(
713                    &obligation,
714                    span,
715                    found_trait_ref,
716                    expected_trait_ref,
717                ) {
718                    Ok(err) => err,
719                    Err(guar) => return guar,
720                }
721            }
722
723            SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id) => return self.report_opaque_type_auto_trait_leakage(
724                &obligation,
725                def_id,
726            ),
727
728            SelectionError::TraitDynIncompatible(did) => {
729                let violations = self.tcx.dyn_compatibility_violations(did);
730                report_dyn_incompatibility(self.tcx, span, None, did, violations)
731            }
732
733            SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsInfer) => {
734                ::rustc_middle::util::bug::bug_fmt(format_args!("MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"))bug!(
735                    "MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"
736                )
737            }
738            SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsParam) => {
739                match self.report_not_const_evaluatable_error(&obligation, span) {
740                    Ok(err) => err,
741                    Err(guar) => return guar,
742                }
743            }
744
745            // Already reported in the query.
746            SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(guar)) |
747            // Already reported.
748            SelectionError::Overflow(OverflowError::Error(guar)) => {
749                self.set_tainted_by_errors(guar);
750                return guar
751            },
752
753            SelectionError::Overflow(_) => {
754                ::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");
755            }
756
757            SelectionError::ConstArgHasWrongType { ct, ct_ty, expected_ty } => {
758                let expected_ty_str = self.tcx.short_string(expected_ty, &mut long_ty_file);
759                let ct_str = self.tcx.short_string(ct, &mut long_ty_file);
760                let mut diag = self.dcx().struct_span_err(
761                    span,
762                    ::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}`"),
763                );
764                diag.long_ty_path = long_ty_file;
765
766                self.note_type_err(
767                    &mut diag,
768                    &obligation.cause,
769                    None,
770                    None,
771                    TypeError::Sorts(ty::error::ExpectedFound::new(expected_ty, ct_ty)),
772                    false,
773                    None,
774                );
775                diag
776            }
777        };
778
779        self.note_obligation_cause(&mut err, &obligation);
780        err.emit()
781    }
782}
783
784impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
785    pub(super) fn apply_do_not_recommend(
786        &self,
787        obligation: &mut PredicateObligation<'tcx>,
788    ) -> bool {
789        let mut base_cause = obligation.cause.code().clone();
790        let mut applied_do_not_recommend = false;
791        loop {
792            if let ObligationCauseCode::ImplDerived(ref c) = base_cause {
793                if self.tcx.do_not_recommend_impl(c.impl_or_alias_def_id) {
794                    let code = (*c.derived.parent_code).clone();
795                    obligation.cause.map_code(|_| code);
796                    obligation.predicate = c.derived.parent_trait_pred.upcast(self.tcx);
797                    applied_do_not_recommend = true;
798                }
799            }
800            if let Some(parent_cause) = base_cause.parent() {
801                base_cause = parent_cause.clone();
802            } else {
803                break;
804            }
805        }
806
807        applied_do_not_recommend
808    }
809
810    fn report_host_effect_error(
811        &self,
812        predicate: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
813        main_obligation: &PredicateObligation<'tcx>,
814        span: Span,
815    ) -> Diag<'a> {
816        // FIXME(const_trait_impl): We should recompute the predicate with `[const]`
817        // if it's `const`, and if it holds, explain that this bound only
818        // *conditionally* holds.
819        let trait_ref = predicate.map_bound(|predicate| ty::TraitPredicate {
820            trait_ref: predicate.trait_ref,
821            polarity: ty::PredicatePolarity::Positive,
822        });
823        let mut file = None;
824
825        let err_msg = self.get_standard_error_message(
826            trait_ref,
827            None,
828            Some(predicate.constness()),
829            None,
830            String::new(),
831            &mut file,
832        );
833        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);
834        *diag.long_ty_path() = file;
835        let obligation = Obligation::new(
836            self.tcx,
837            ObligationCause::dummy(),
838            main_obligation.param_env,
839            trait_ref,
840        );
841        if !self.predicate_may_hold(&obligation) {
842            diag.downgrade_to_delayed_bug();
843        }
844
845        if let Ok(Some(ImplSource::UserDefined(impl_data))) =
846            SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref.skip_binder()))
847        {
848            let impl_did = impl_data.impl_def_id;
849            let trait_did = trait_ref.def_id();
850            let impl_span = self.tcx.def_span(impl_did);
851            let trait_name = self.tcx.item_name(trait_did);
852
853            if self.tcx.is_const_trait(trait_did) && !self.tcx.is_const_trait_impl(impl_did) {
854                if let Some(impl_did) = impl_did.as_local()
855                    && let item = self.tcx.hir_expect_item(impl_did)
856                    && let hir::ItemKind::Impl(item) = item.kind
857                    && let Some(of_trait) = item.of_trait
858                {
859                    // trait is const, impl is local and not const
860                    diag.span_suggestion_verbose(
861                        of_trait.trait_ref.path.span.shrink_to_lo(),
862                        ::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`"),
863                        "const ".to_string(),
864                        Applicability::MaybeIncorrect,
865                    );
866                } else {
867                    diag.span_note(
868                        impl_span,
869                        ::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`"),
870                    );
871
872                    let (condition_options, format_args) = self.on_unimplemented_components(
873                        trait_ref,
874                        main_obligation,
875                        diag.long_ty_path(),
876                    );
877
878                    if let Ok(Some(command)) = OnUnimplementedDirective::of_item(self.tcx, impl_did)
879                    {
880                        let note = command.evaluate(
881                            self.tcx,
882                            predicate.skip_binder().trait_ref,
883                            &condition_options,
884                            &format_args,
885                        );
886                        let OnUnimplementedNote {
887                            message,
888                            label,
889                            notes,
890                            parent_label,
891                            append_const_msg: _,
892                        } = note;
893
894                        if let Some(message) = message {
895                            diag.primary_message(message);
896                        }
897                        if let Some(label) = label {
898                            diag.span_label(impl_span, label);
899                        }
900                        for note in notes {
901                            diag.note(note);
902                        }
903                        if let Some(parent_label) = parent_label {
904                            diag.span_label(impl_span, parent_label);
905                        }
906                    }
907                }
908            }
909        }
910        diag
911    }
912
913    fn emit_specialized_closure_kind_error(
914        &self,
915        obligation: &PredicateObligation<'tcx>,
916        mut trait_pred: ty::PolyTraitPredicate<'tcx>,
917    ) -> Option<ErrorGuaranteed> {
918        // If we end up on an `AsyncFnKindHelper` goal, try to unwrap the parent
919        // `AsyncFn*` goal.
920        if self.tcx.is_lang_item(trait_pred.def_id(), LangItem::AsyncFnKindHelper) {
921            let mut code = obligation.cause.code();
922            // Unwrap a `FunctionArg` cause, which has been refined from a derived obligation.
923            if let ObligationCauseCode::FunctionArg { parent_code, .. } = code {
924                code = &**parent_code;
925            }
926            // If we have a derived obligation, then the parent will be a `AsyncFn*` goal.
927            if let Some((_, Some(parent))) = code.parent_with_predicate() {
928                trait_pred = parent;
929            }
930        }
931
932        let self_ty = trait_pred.self_ty().skip_binder();
933
934        let (expected_kind, trait_prefix) =
935            if let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) {
936                (expected_kind, "")
937            } else if let Some(expected_kind) =
938                self.tcx.async_fn_trait_kind_from_def_id(trait_pred.def_id())
939            {
940                (expected_kind, "Async")
941            } else {
942                return None;
943            };
944
945        let (closure_def_id, found_args, has_self_borrows) = match *self_ty.kind() {
946            ty::Closure(def_id, args) => {
947                (def_id, args.as_closure().sig().map_bound(|sig| sig.inputs()[0]), false)
948            }
949            ty::CoroutineClosure(def_id, args) => (
950                def_id,
951                args.as_coroutine_closure()
952                    .coroutine_closure_sig()
953                    .map_bound(|sig| sig.tupled_inputs_ty),
954                !args.as_coroutine_closure().tupled_upvars_ty().is_ty_var()
955                    && args.as_coroutine_closure().has_self_borrows(),
956            ),
957            _ => return None,
958        };
959
960        let expected_args = trait_pred.map_bound(|trait_pred| trait_pred.trait_ref.args.type_at(1));
961
962        // Verify that the arguments are compatible. If the signature is
963        // mismatched, then we have a totally different error to report.
964        if self.enter_forall(found_args, |found_args| {
965            self.enter_forall(expected_args, |expected_args| {
966                !self.can_eq(obligation.param_env, expected_args, found_args)
967            })
968        }) {
969            return None;
970        }
971
972        if let Some(found_kind) = self.closure_kind(self_ty)
973            && !found_kind.extends(expected_kind)
974        {
975            let mut err = self.report_closure_error(
976                &obligation,
977                closure_def_id,
978                found_kind,
979                expected_kind,
980                trait_prefix,
981            );
982            self.note_obligation_cause(&mut err, &obligation);
983            return Some(err.emit());
984        }
985
986        // If the closure has captures, then perhaps the reason that the trait
987        // is unimplemented is because async closures don't implement `Fn`/`FnMut`
988        // if they have captures.
989        if has_self_borrows && expected_kind != ty::ClosureKind::FnOnce {
990            let coro_kind = match self
991                .tcx
992                .coroutine_kind(self.tcx.coroutine_for_closure(closure_def_id))
993                .unwrap()
994            {
995                rustc_hir::CoroutineKind::Desugared(desugaring, _) => desugaring.to_string(),
996                coro => coro.to_string(),
997            };
998            let mut err = self.dcx().create_err(CoroClosureNotFn {
999                span: self.tcx.def_span(closure_def_id),
1000                kind: expected_kind.as_str(),
1001                coro_kind,
1002            });
1003            self.note_obligation_cause(&mut err, &obligation);
1004            return Some(err.emit());
1005        }
1006
1007        None
1008    }
1009
1010    fn fn_arg_obligation(
1011        &self,
1012        obligation: &PredicateObligation<'tcx>,
1013    ) -> Result<(), ErrorGuaranteed> {
1014        if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1015            && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
1016            && let arg = arg.peel_borrows()
1017            && let hir::ExprKind::Path(hir::QPath::Resolved(
1018                None,
1019                hir::Path { res: hir::def::Res::Local(hir_id), .. },
1020            )) = arg.kind
1021            && let Node::Pat(pat) = self.tcx.hir_node(*hir_id)
1022            && let Some((preds, guar)) = self.reported_trait_errors.borrow().get(&pat.span)
1023            && preds.contains(&obligation.as_goal())
1024        {
1025            return Err(*guar);
1026        }
1027        Ok(())
1028    }
1029
1030    fn detect_negative_literal(
1031        &self,
1032        obligation: &PredicateObligation<'tcx>,
1033        trait_pred: ty::PolyTraitPredicate<'tcx>,
1034        err: &mut Diag<'_>,
1035    ) -> bool {
1036        if let ObligationCauseCode::UnOp { hir_id, .. } = obligation.cause.code()
1037            && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1038            && let hir::ExprKind::Unary(hir::UnOp::Neg, inner) = expr.kind
1039            && let hir::ExprKind::Lit(lit) = inner.kind
1040            && let LitKind::Int(_, LitIntType::Unsuffixed) = lit.node
1041        {
1042            err.span_suggestion_verbose(
1043                lit.span.shrink_to_hi(),
1044                "consider specifying an integer type that can be negative",
1045                match trait_pred.skip_binder().self_ty().kind() {
1046                    ty::Uint(ty::UintTy::Usize) => "isize",
1047                    ty::Uint(ty::UintTy::U8) => "i8",
1048                    ty::Uint(ty::UintTy::U16) => "i16",
1049                    ty::Uint(ty::UintTy::U32) => "i32",
1050                    ty::Uint(ty::UintTy::U64) => "i64",
1051                    ty::Uint(ty::UintTy::U128) => "i128",
1052                    _ => "i64",
1053                }
1054                .to_string(),
1055                Applicability::MaybeIncorrect,
1056            );
1057            return true;
1058        }
1059        false
1060    }
1061
1062    /// When the `E` of the resulting `Result<T, E>` in an expression `foo().bar().baz()?`,
1063    /// identify those method chain sub-expressions that could or could not have been annotated
1064    /// with `?`.
1065    fn try_conversion_context(
1066        &self,
1067        obligation: &PredicateObligation<'tcx>,
1068        trait_pred: ty::PolyTraitPredicate<'tcx>,
1069        err: &mut Diag<'_>,
1070    ) -> (bool, bool) {
1071        let span = obligation.cause.span;
1072        /// Look for the (direct) sub-expr of `?`, and return it if it's a `.` method call.
1073        struct FindMethodSubexprOfTry {
1074            search_span: Span,
1075        }
1076        impl<'v> Visitor<'v> for FindMethodSubexprOfTry {
1077            type Result = ControlFlow<&'v hir::Expr<'v>>;
1078            fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
1079                if let hir::ExprKind::Match(expr, _arms, hir::MatchSource::TryDesugar(_)) = ex.kind
1080                    && ex.span.with_lo(ex.span.hi() - BytePos(1)).source_equal(self.search_span)
1081                    && let hir::ExprKind::Call(_, [expr, ..]) = expr.kind
1082                {
1083                    ControlFlow::Break(expr)
1084                } else {
1085                    hir::intravisit::walk_expr(self, ex)
1086                }
1087            }
1088        }
1089        let hir_id = self.tcx.local_def_id_to_hir_id(obligation.cause.body_id);
1090        let Some(body_id) = self.tcx.hir_node(hir_id).body_id() else { return (false, false) };
1091        let ControlFlow::Break(expr) =
1092            (FindMethodSubexprOfTry { search_span: span }).visit_body(self.tcx.hir_body(body_id))
1093        else {
1094            return (false, false);
1095        };
1096        let Some(typeck) = &self.typeck_results else {
1097            return (false, false);
1098        };
1099        let ObligationCauseCode::QuestionMark = obligation.cause.code().peel_derives() else {
1100            return (false, false);
1101        };
1102        let self_ty = trait_pred.skip_binder().self_ty();
1103        let found_ty = trait_pred.skip_binder().trait_ref.args.get(1).and_then(|a| a.as_type());
1104        let noted_missing_impl =
1105            self.note_missing_impl_for_question_mark(err, self_ty, found_ty, trait_pred);
1106
1107        let mut prev_ty = self.resolve_vars_if_possible(
1108            typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1109        );
1110
1111        // We always look at the `E` type, because that's the only one affected by `?`. If the
1112        // incorrect `Result<T, E>` is because of the `T`, we'll get an E0308 on the whole
1113        // expression, after the `?` has "unwrapped" the `T`.
1114        let get_e_type = |prev_ty: Ty<'tcx>| -> Option<Ty<'tcx>> {
1115            let ty::Adt(def, args) = prev_ty.kind() else {
1116                return None;
1117            };
1118            let Some(arg) = args.get(1) else {
1119                return None;
1120            };
1121            if !self.tcx.is_diagnostic_item(sym::Result, def.did()) {
1122                return None;
1123            }
1124            arg.as_type()
1125        };
1126
1127        let mut suggested = false;
1128        let mut chain = ::alloc::vec::Vec::new()vec![];
1129
1130        // The following logic is similar to `point_at_chain`, but that's focused on associated types
1131        let mut expr = expr;
1132        while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
1133            // Point at every method call in the chain with the `Result` type.
1134            // let foo = bar.iter().map(mapper)?;
1135            //               ------ -----------
1136            expr = rcvr_expr;
1137            chain.push((span, prev_ty));
1138
1139            let next_ty = self.resolve_vars_if_possible(
1140                typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1141            );
1142
1143            let is_diagnostic_item = |symbol: Symbol, ty: Ty<'tcx>| {
1144                let ty::Adt(def, _) = ty.kind() else {
1145                    return false;
1146                };
1147                self.tcx.is_diagnostic_item(symbol, def.did())
1148            };
1149            // For each method in the chain, see if this is `Result::map_err` or
1150            // `Option::ok_or_else` and if it is, see if the closure passed to it has an incorrect
1151            // trailing `;`.
1152            if let Some(ty) = get_e_type(prev_ty)
1153                && let Some(found_ty) = found_ty
1154                // Ideally we would instead use `FnCtxt::lookup_method_for_diagnostic` for 100%
1155                // accurate check, but we are in the wrong stage to do that and looking for
1156                // `Result::map_err` by checking the Self type and the path segment is enough.
1157                // sym::ok_or_else
1158                && (
1159                    ( // Result::map_err
1160                        path_segment.ident.name == sym::map_err
1161                            && is_diagnostic_item(sym::Result, next_ty)
1162                    ) || ( // Option::ok_or_else
1163                        path_segment.ident.name == sym::ok_or_else
1164                            && is_diagnostic_item(sym::Option, next_ty)
1165                    )
1166                )
1167                // Found `Result<_, ()>?`
1168                && let ty::Tuple(tys) = found_ty.kind()
1169                && tys.is_empty()
1170                // The current method call returns `Result<_, ()>`
1171                && self.can_eq(obligation.param_env, ty, found_ty)
1172                // There's a single argument in the method call and it is a closure
1173                && let [arg] = args
1174                && let hir::ExprKind::Closure(closure) = arg.kind
1175                // The closure has a block for its body with no tail expression
1176                && let body = self.tcx.hir_body(closure.body)
1177                && let hir::ExprKind::Block(block, _) = body.value.kind
1178                && let None = block.expr
1179                // The last statement is of a type that can be converted to the return error type
1180                && let [.., stmt] = block.stmts
1181                && let hir::StmtKind::Semi(expr) = stmt.kind
1182                && let expr_ty = self.resolve_vars_if_possible(
1183                    typeck.expr_ty_adjusted_opt(expr)
1184                        .unwrap_or(Ty::new_misc_error(self.tcx)),
1185                )
1186                && self
1187                    .infcx
1188                    .type_implements_trait(
1189                        self.tcx.get_diagnostic_item(sym::From).unwrap(),
1190                        [self_ty, expr_ty],
1191                        obligation.param_env,
1192                    )
1193                    .must_apply_modulo_regions()
1194            {
1195                suggested = true;
1196                err.span_suggestion_short(
1197                    stmt.span.with_lo(expr.span.hi()),
1198                    "remove this semicolon",
1199                    String::new(),
1200                    Applicability::MachineApplicable,
1201                );
1202            }
1203
1204            prev_ty = next_ty;
1205
1206            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1207                && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
1208                && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
1209            {
1210                let parent = self.tcx.parent_hir_node(binding.hir_id);
1211                // We've reached the root of the method call chain...
1212                if let hir::Node::LetStmt(local) = parent
1213                    && let Some(binding_expr) = local.init
1214                {
1215                    // ...and it is a binding. Get the binding creation and continue the chain.
1216                    expr = binding_expr;
1217                }
1218                if let hir::Node::Param(_param) = parent {
1219                    // ...and it is an fn argument.
1220                    break;
1221                }
1222            }
1223        }
1224        // `expr` is now the "root" expression of the method call chain, which can be any
1225        // expression kind, like a method call or a path. If this expression is `Result<T, E>` as
1226        // well, then we also point at it.
1227        prev_ty = self.resolve_vars_if_possible(
1228            typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1229        );
1230        chain.push((expr.span, prev_ty));
1231
1232        let mut prev = None;
1233        let mut iter = chain.into_iter().rev().peekable();
1234        while let Some((span, err_ty)) = iter.next() {
1235            let is_last = iter.peek().is_none();
1236            let err_ty = get_e_type(err_ty);
1237            let err_ty = match (err_ty, prev) {
1238                (Some(err_ty), Some(prev)) if !self.can_eq(obligation.param_env, err_ty, prev) => {
1239                    err_ty
1240                }
1241                (Some(err_ty), None) => err_ty,
1242                _ => {
1243                    prev = err_ty;
1244                    continue;
1245                }
1246            };
1247
1248            let implements_from = self
1249                .infcx
1250                .type_implements_trait(
1251                    self.tcx.get_diagnostic_item(sym::From).unwrap(),
1252                    [self_ty, err_ty],
1253                    obligation.param_env,
1254                )
1255                .must_apply_modulo_regions();
1256
1257            let err_ty_str = self.tcx.short_string(err_ty, err.long_ty_path());
1258            let label = if !implements_from && is_last {
1259                ::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!(
1260                    "this can't be annotated with `?` because it has type `Result<_, {err_ty_str}>`"
1261                )
1262            } else {
1263                ::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}>`")
1264            };
1265
1266            if !suggested || !implements_from {
1267                err.span_label(span, label);
1268            }
1269            prev = Some(err_ty);
1270        }
1271        (suggested, noted_missing_impl)
1272    }
1273
1274    fn note_missing_impl_for_question_mark(
1275        &self,
1276        err: &mut Diag<'_>,
1277        self_ty: Ty<'_>,
1278        found_ty: Option<Ty<'_>>,
1279        trait_pred: ty::PolyTraitPredicate<'tcx>,
1280    ) -> bool {
1281        match (self_ty.kind(), found_ty) {
1282            (ty::Adt(def, _), Some(ty))
1283                if let ty::Adt(found, _) = ty.kind()
1284                    && def.did().is_local()
1285                    && found.did().is_local() =>
1286            {
1287                err.span_note(
1288                    self.tcx.def_span(def.did()),
1289                    ::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}>`"),
1290                );
1291            }
1292            (ty::Adt(def, _), None) if def.did().is_local() => {
1293                let trait_path = self.tcx.short_string(
1294                    trait_pred.skip_binder().trait_ref.print_only_trait_path(),
1295                    err.long_ty_path(),
1296                );
1297                err.span_note(
1298                    self.tcx.def_span(def.did()),
1299                    ::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}`"),
1300                );
1301            }
1302            (ty::Adt(def, _), Some(ty)) if def.did().is_local() => {
1303                err.span_note(
1304                    self.tcx.def_span(def.did()),
1305                    ::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}>`"),
1306                );
1307            }
1308            (_, Some(ty))
1309                if let ty::Adt(def, _) = ty.kind()
1310                    && def.did().is_local() =>
1311            {
1312                err.span_note(
1313                    self.tcx.def_span(def.did()),
1314                    ::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}>`"),
1315                );
1316            }
1317            _ => return false,
1318        }
1319        true
1320    }
1321
1322    fn report_const_param_not_wf(
1323        &self,
1324        ty: Ty<'tcx>,
1325        obligation: &PredicateObligation<'tcx>,
1326    ) -> Diag<'a> {
1327        let def_id = obligation.cause.body_id;
1328        let span = self.tcx.ty_span(def_id);
1329
1330        let mut file = None;
1331        let ty_str = self.tcx.short_string(ty, &mut file);
1332        let mut diag = match ty.kind() {
1333            ty::Float(_) => {
1334                {
    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!(
1335                    self.dcx(),
1336                    span,
1337                    E0741,
1338                    "`{ty_str}` is forbidden as the type of a const generic parameter",
1339                )
1340            }
1341            ty::FnPtr(..) => {
1342                {
    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!(
1343                    self.dcx(),
1344                    span,
1345                    E0741,
1346                    "using function pointers as const generic parameters is forbidden",
1347                )
1348            }
1349            ty::RawPtr(_, _) => {
1350                {
    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!(
1351                    self.dcx(),
1352                    span,
1353                    E0741,
1354                    "using raw pointers as const generic parameters is forbidden",
1355                )
1356            }
1357            ty::Adt(def, _) => {
1358                // We should probably see if we're *allowed* to derive `ConstParamTy` on the type...
1359                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!(
1360                    self.dcx(),
1361                    span,
1362                    E0741,
1363                    "`{ty_str}` must implement `ConstParamTy` to be used as the type of a const generic parameter",
1364                );
1365                // Only suggest derive if this isn't a derived obligation,
1366                // and the struct is local.
1367                if let Some(span) = self.tcx.hir_span_if_local(def.did())
1368                    && obligation.cause.code().parent().is_none()
1369                {
1370                    if ty.is_structural_eq_shallow(self.tcx) {
1371                        diag.span_suggestion(
1372                            span.shrink_to_lo(),
1373                            ::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()),
1374                            "#[derive(ConstParamTy)]\n",
1375                            Applicability::MachineApplicable,
1376                        );
1377                    } else {
1378                        // FIXME(adt_const_params): We should check there's not already an
1379                        // overlapping `Eq`/`PartialEq` impl.
1380                        diag.span_suggestion(
1381                            span.shrink_to_lo(),
1382                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {0}",
                def.descr()))
    })format!(
1383                                "add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {}",
1384                                def.descr()
1385                            ),
1386                            "#[derive(ConstParamTy, PartialEq, Eq)]\n",
1387                            Applicability::MachineApplicable,
1388                        );
1389                    }
1390                }
1391                diag
1392            }
1393            _ => {
1394                {
    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!(
1395                    self.dcx(),
1396                    span,
1397                    E0741,
1398                    "`{ty_str}` can't be used as a const parameter type",
1399                )
1400            }
1401        };
1402        diag.long_ty_path = file;
1403
1404        let mut code = obligation.cause.code();
1405        let mut pred = obligation.predicate.as_trait_clause();
1406        while let Some((next_code, next_pred)) = code.parent_with_predicate() {
1407            if let Some(pred) = pred {
1408                self.enter_forall(pred, |pred| {
1409                    let ty = self.tcx.short_string(pred.self_ty(), diag.long_ty_path());
1410                    let trait_path = self
1411                        .tcx
1412                        .short_string(pred.print_modifiers_and_trait_path(), diag.long_ty_path());
1413                    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"));
1414                })
1415            }
1416            code = next_code;
1417            pred = next_pred;
1418        }
1419
1420        diag
1421    }
1422}
1423
1424impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
1425    fn can_match_trait(
1426        &self,
1427        param_env: ty::ParamEnv<'tcx>,
1428        goal: ty::TraitPredicate<'tcx>,
1429        assumption: ty::PolyTraitPredicate<'tcx>,
1430    ) -> bool {
1431        // Fast path
1432        if goal.polarity != assumption.polarity() {
1433            return false;
1434        }
1435
1436        let trait_assumption = self.instantiate_binder_with_fresh_vars(
1437            DUMMY_SP,
1438            infer::BoundRegionConversionTime::HigherRankedType,
1439            assumption,
1440        );
1441
1442        self.can_eq(param_env, goal.trait_ref, trait_assumption.trait_ref)
1443    }
1444
1445    fn can_match_host_effect(
1446        &self,
1447        param_env: ty::ParamEnv<'tcx>,
1448        goal: ty::HostEffectPredicate<'tcx>,
1449        assumption: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
1450    ) -> bool {
1451        let assumption = self.instantiate_binder_with_fresh_vars(
1452            DUMMY_SP,
1453            infer::BoundRegionConversionTime::HigherRankedType,
1454            assumption,
1455        );
1456
1457        assumption.constness.satisfies(goal.constness)
1458            && self.can_eq(param_env, goal.trait_ref, assumption.trait_ref)
1459    }
1460
1461    fn as_host_effect_clause(
1462        predicate: ty::Predicate<'tcx>,
1463    ) -> Option<ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>> {
1464        predicate.as_clause().and_then(|clause| match clause.kind().skip_binder() {
1465            ty::ClauseKind::HostEffect(pred) => Some(clause.kind().rebind(pred)),
1466            _ => None,
1467        })
1468    }
1469
1470    fn can_match_projection(
1471        &self,
1472        param_env: ty::ParamEnv<'tcx>,
1473        goal: ty::ProjectionPredicate<'tcx>,
1474        assumption: ty::PolyProjectionPredicate<'tcx>,
1475    ) -> bool {
1476        let assumption = self.instantiate_binder_with_fresh_vars(
1477            DUMMY_SP,
1478            infer::BoundRegionConversionTime::HigherRankedType,
1479            assumption,
1480        );
1481
1482        self.can_eq(param_env, goal.projection_term, assumption.projection_term)
1483            && self.can_eq(param_env, goal.term, assumption.term)
1484    }
1485
1486    // returns if `cond` not occurring implies that `error` does not occur - i.e., that
1487    // `error` occurring implies that `cond` occurs.
1488    x;#[instrument(level = "debug", skip(self), ret)]
1489    pub(super) fn error_implies(
1490        &self,
1491        cond: Goal<'tcx, ty::Predicate<'tcx>>,
1492        error: Goal<'tcx, ty::Predicate<'tcx>>,
1493    ) -> bool {
1494        if cond == error {
1495            return true;
1496        }
1497
1498        // FIXME: We could be smarter about this, i.e. if cond's param-env is a
1499        // subset of error's param-env. This only matters when binders will carry
1500        // predicates though, and obviously only matters for error reporting.
1501        if cond.param_env != error.param_env {
1502            return false;
1503        }
1504        let param_env = error.param_env;
1505
1506        if let Some(error) = error.predicate.as_trait_clause() {
1507            self.enter_forall(error, |error| {
1508                elaborate(self.tcx, std::iter::once(cond.predicate))
1509                    .filter_map(|implied| implied.as_trait_clause())
1510                    .any(|implied| self.can_match_trait(param_env, error, implied))
1511            })
1512        } else if let Some(error) = Self::as_host_effect_clause(error.predicate) {
1513            self.enter_forall(error, |error| {
1514                elaborate(self.tcx, std::iter::once(cond.predicate))
1515                    .filter_map(Self::as_host_effect_clause)
1516                    .any(|implied| self.can_match_host_effect(param_env, error, implied))
1517            })
1518        } else if let Some(error) = error.predicate.as_projection_clause() {
1519            self.enter_forall(error, |error| {
1520                elaborate(self.tcx, std::iter::once(cond.predicate))
1521                    .filter_map(|implied| implied.as_projection_clause())
1522                    .any(|implied| self.can_match_projection(param_env, error, implied))
1523            })
1524        } else {
1525            false
1526        }
1527    }
1528
1529    #[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(1529u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::fulfillment_errors"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ErrorGuaranteed = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let predicate =
                self.resolve_vars_if_possible(obligation.predicate);
            if let Err(e) = predicate.error_reported() { return e; }
            self.probe(|_|
                    {
                        let bound_predicate = predicate.kind();
                        let (values, err) =
                            match bound_predicate.skip_binder() {
                                ty::PredicateKind::Clause(ty::ClauseKind::Projection(data))
                                    => {
                                    let ocx = ObligationCtxt::new(self);
                                    let data =
                                        self.instantiate_binder_with_fresh_vars(obligation.cause.span,
                                            infer::BoundRegionConversionTime::HigherRankedType,
                                            bound_predicate.rebind(data));
                                    let unnormalized_term =
                                        data.projection_term.to_term(self.tcx);
                                    let normalized_term =
                                        ocx.normalize(&obligation.cause, obligation.param_env,
                                            unnormalized_term);
                                    let _ = ocx.try_evaluate_obligations();
                                    if let Err(new_err) =
                                            ocx.eq(&obligation.cause, obligation.param_env, data.term,
                                                normalized_term) {
                                        (Some((data.projection_term,
                                                    self.resolve_vars_if_possible(normalized_term), data.term)),
                                            new_err)
                                    } else { (None, error.err) }
                                }
                                ty::PredicateKind::AliasRelate(lhs, rhs, _) => {
                                    let derive_better_type_error =
                                        |alias_term: ty::AliasTerm<'tcx>,
                                            expected_term: ty::Term<'tcx>|
                                            {
                                                let ocx = ObligationCtxt::new(self);
                                                let Ok(normalized_term) =
                                                    ocx.structurally_normalize_term(&ObligationCause::dummy(),
                                                        obligation.param_env,
                                                        alias_term.to_term(self.tcx)) else { return None; };
                                                if let Err(terr) =
                                                        ocx.eq(&ObligationCause::dummy(), obligation.param_env,
                                                            expected_term, normalized_term) {
                                                    Some((terr, self.resolve_vars_if_possible(normalized_term)))
                                                } else { None }
                                            };
                                    if let Some(lhs) = lhs.to_alias_term() &&
                                                let ty::AliasTermKind::ProjectionTy |
                                                    ty::AliasTermKind::ProjectionConst = lhs.kind(self.tcx) &&
                                            let Some((better_type_err, expected_term)) =
                                                derive_better_type_error(lhs, rhs) {
                                        (Some((lhs, self.resolve_vars_if_possible(expected_term),
                                                    rhs)), better_type_err)
                                    } else if let Some(rhs) = rhs.to_alias_term() &&
                                                let ty::AliasTermKind::ProjectionTy |
                                                    ty::AliasTermKind::ProjectionConst = rhs.kind(self.tcx) &&
                                            let Some((better_type_err, expected_term)) =
                                                derive_better_type_error(rhs, lhs) {
                                        (Some((rhs, self.resolve_vars_if_possible(expected_term),
                                                    lhs)), better_type_err)
                                    } else { (None, error.err) }
                                }
                                _ => (None, error.err),
                            };
                        let mut file = None;
                        let (msg, span, closure_span) =
                            values.and_then(|(predicate, normalized_term,
                                            expected_term)|
                                        {
                                            self.maybe_detailed_projection_msg(obligation.cause.span,
                                                predicate, normalized_term, expected_term, &mut file)
                                        }).unwrap_or_else(||
                                    {
                                        ({
                                                let _guard = ForceTrimmedGuard::new();
                                                ::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("type mismatch resolving `{0}`",
                                                                self.tcx.short_string(self.resolve_vars_if_possible(predicate),
                                                                    &mut file)))
                                                    })
                                            }, obligation.cause.span, None)
                                    });
                        let mut diag =
                            {
                                self.dcx().struct_span_err(span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("{0}", msg))
                                            })).with_code(E0271)
                            };
                        *diag.long_ty_path() = file;
                        if let Some(span) = closure_span {
                            diag.span_label(span, "this closure");
                            if !span.overlaps(obligation.cause.span) {
                                diag.span_label(obligation.cause.span, "closure used here");
                            }
                        }
                        let secondary_span =
                            self.probe(|_|
                                    {
                                        let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
                                            predicate.kind().skip_binder() else { return None; };
                                        let trait_ref =
                                            self.enter_forall_and_leak_universe(predicate.kind().rebind(proj.projection_term.trait_ref(self.tcx)));
                                        let Ok(Some(ImplSource::UserDefined(impl_data))) =
                                            SelectionContext::new(self).select(&obligation.with(self.tcx,
                                                        trait_ref)) else { return None; };
                                        let Ok(node) =
                                            specialization_graph::assoc_def(self.tcx,
                                                impl_data.impl_def_id, proj.def_id()) else { return None; };
                                        if !node.is_final() { return None; }
                                        match self.tcx.hir_get_if_local(node.item.def_id) {
                                            Some(hir::Node::TraitItem(hir::TraitItem {
                                                kind: hir::TraitItemKind::Type(_, Some(ty)), .. }) |
                                                hir::Node::ImplItem(hir::ImplItem {
                                                kind: hir::ImplItemKind::Type(ty), .. })) =>
                                                Some((ty.span,
                                                        {
                                                            let _guard = ForceTrimmedGuard::new();
                                                            Cow::from(::alloc::__export::must_use({
                                                                        ::alloc::fmt::format(format_args!("type mismatch resolving `{0}`",
                                                                                self.tcx.short_string(self.resolve_vars_if_possible(predicate),
                                                                                    diag.long_ty_path())))
                                                                    }))
                                                        }, true)),
                                            _ => None,
                                        }
                                    });
                        self.note_type_err(&mut diag, &obligation.cause,
                            secondary_span,
                            values.map(|(_, normalized_ty, expected_ty)|
                                    {
                                        obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(expected_ty,
                                                    normalized_ty)))
                                    }), err, false, Some(span));
                        self.note_obligation_cause(&mut diag, obligation);
                        diag.emit()
                    })
        }
    }
}#[instrument(level = "debug", skip_all)]
1530    pub(super) fn report_projection_error(
1531        &self,
1532        obligation: &PredicateObligation<'tcx>,
1533        error: &MismatchedProjectionTypes<'tcx>,
1534    ) -> ErrorGuaranteed {
1535        let predicate = self.resolve_vars_if_possible(obligation.predicate);
1536
1537        if let Err(e) = predicate.error_reported() {
1538            return e;
1539        }
1540
1541        self.probe(|_| {
1542            // try to find the mismatched types to report the error with.
1543            //
1544            // this can fail if the problem was higher-ranked, in which
1545            // cause I have no idea for a good error message.
1546            let bound_predicate = predicate.kind();
1547            let (values, err) = match bound_predicate.skip_binder() {
1548                ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
1549                    let ocx = ObligationCtxt::new(self);
1550
1551                    let data = self.instantiate_binder_with_fresh_vars(
1552                        obligation.cause.span,
1553                        infer::BoundRegionConversionTime::HigherRankedType,
1554                        bound_predicate.rebind(data),
1555                    );
1556                    let unnormalized_term = data.projection_term.to_term(self.tcx);
1557                    // FIXME(-Znext-solver): For diagnostic purposes, it would be nice
1558                    // to deeply normalize this type.
1559                    let normalized_term =
1560                        ocx.normalize(&obligation.cause, obligation.param_env, unnormalized_term);
1561
1562                    // constrain inference variables a bit more to nested obligations from normalize so
1563                    // we can have more helpful errors.
1564                    //
1565                    // we intentionally drop errors from normalization here,
1566                    // since the normalization is just done to improve the error message.
1567                    let _ = ocx.try_evaluate_obligations();
1568
1569                    if let Err(new_err) =
1570                        ocx.eq(&obligation.cause, obligation.param_env, data.term, normalized_term)
1571                    {
1572                        (
1573                            Some((
1574                                data.projection_term,
1575                                self.resolve_vars_if_possible(normalized_term),
1576                                data.term,
1577                            )),
1578                            new_err,
1579                        )
1580                    } else {
1581                        (None, error.err)
1582                    }
1583                }
1584                ty::PredicateKind::AliasRelate(lhs, rhs, _) => {
1585                    let derive_better_type_error =
1586                        |alias_term: ty::AliasTerm<'tcx>, expected_term: ty::Term<'tcx>| {
1587                            let ocx = ObligationCtxt::new(self);
1588
1589                            let Ok(normalized_term) = ocx.structurally_normalize_term(
1590                                &ObligationCause::dummy(),
1591                                obligation.param_env,
1592                                alias_term.to_term(self.tcx),
1593                            ) else {
1594                                return None;
1595                            };
1596
1597                            if let Err(terr) = ocx.eq(
1598                                &ObligationCause::dummy(),
1599                                obligation.param_env,
1600                                expected_term,
1601                                normalized_term,
1602                            ) {
1603                                Some((terr, self.resolve_vars_if_possible(normalized_term)))
1604                            } else {
1605                                None
1606                            }
1607                        };
1608
1609                    if let Some(lhs) = lhs.to_alias_term()
1610                        && let ty::AliasTermKind::ProjectionTy | ty::AliasTermKind::ProjectionConst = lhs.kind(self.tcx)
1611                        && let Some((better_type_err, expected_term)) =
1612                            derive_better_type_error(lhs, rhs)
1613                    {
1614                        (
1615                            Some((lhs, self.resolve_vars_if_possible(expected_term), rhs)),
1616                            better_type_err,
1617                        )
1618                    } else if let Some(rhs) = rhs.to_alias_term()
1619                        && let ty::AliasTermKind::ProjectionTy | ty::AliasTermKind::ProjectionConst = rhs.kind(self.tcx)
1620                        && let Some((better_type_err, expected_term)) =
1621                            derive_better_type_error(rhs, lhs)
1622                    {
1623                        (
1624                            Some((rhs, self.resolve_vars_if_possible(expected_term), lhs)),
1625                            better_type_err,
1626                        )
1627                    } else {
1628                        (None, error.err)
1629                    }
1630                }
1631                _ => (None, error.err),
1632            };
1633
1634            let mut file = None;
1635            let (msg, span, closure_span) = values
1636                .and_then(|(predicate, normalized_term, expected_term)| {
1637                    self.maybe_detailed_projection_msg(
1638                        obligation.cause.span,
1639                        predicate,
1640                        normalized_term,
1641                        expected_term,
1642                        &mut file,
1643                    )
1644                })
1645                .unwrap_or_else(|| {
1646                    (
1647                        with_forced_trimmed_paths!(format!(
1648                            "type mismatch resolving `{}`",
1649                            self.tcx
1650                                .short_string(self.resolve_vars_if_possible(predicate), &mut file),
1651                        )),
1652                        obligation.cause.span,
1653                        None,
1654                    )
1655                });
1656            let mut diag = struct_span_code_err!(self.dcx(), span, E0271, "{msg}");
1657            *diag.long_ty_path() = file;
1658            if let Some(span) = closure_span {
1659                // Mark the closure decl so that it is seen even if we are pointing at the return
1660                // type or expression.
1661                //
1662                // error[E0271]: expected `{closure@foo.rs:41:16}` to be a closure that returns
1663                //               `Unit3`, but it returns `Unit4`
1664                //   --> $DIR/foo.rs:43:17
1665                //    |
1666                // LL |     let v = Unit2.m(
1667                //    |                   - required by a bound introduced by this call
1668                // ...
1669                // LL |             f: |x| {
1670                //    |                --- /* this span */
1671                // LL |                 drop(x);
1672                // LL |                 Unit4
1673                //    |                 ^^^^^ expected `Unit3`, found `Unit4`
1674                //    |
1675                diag.span_label(span, "this closure");
1676                if !span.overlaps(obligation.cause.span) {
1677                    // Point at the binding corresponding to the closure where it is used.
1678                    diag.span_label(obligation.cause.span, "closure used here");
1679                }
1680            }
1681
1682            let secondary_span = self.probe(|_| {
1683                let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
1684                    predicate.kind().skip_binder()
1685                else {
1686                    return None;
1687                };
1688
1689                let trait_ref = self.enter_forall_and_leak_universe(
1690                    predicate.kind().rebind(proj.projection_term.trait_ref(self.tcx)),
1691                );
1692                let Ok(Some(ImplSource::UserDefined(impl_data))) =
1693                    SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref))
1694                else {
1695                    return None;
1696                };
1697
1698                let Ok(node) =
1699                    specialization_graph::assoc_def(self.tcx, impl_data.impl_def_id, proj.def_id())
1700                else {
1701                    return None;
1702                };
1703
1704                if !node.is_final() {
1705                    return None;
1706                }
1707
1708                match self.tcx.hir_get_if_local(node.item.def_id) {
1709                    Some(
1710                        hir::Node::TraitItem(hir::TraitItem {
1711                            kind: hir::TraitItemKind::Type(_, Some(ty)),
1712                            ..
1713                        })
1714                        | hir::Node::ImplItem(hir::ImplItem {
1715                            kind: hir::ImplItemKind::Type(ty),
1716                            ..
1717                        }),
1718                    ) => Some((
1719                        ty.span,
1720                        with_forced_trimmed_paths!(Cow::from(format!(
1721                            "type mismatch resolving `{}`",
1722                            self.tcx.short_string(
1723                                self.resolve_vars_if_possible(predicate),
1724                                diag.long_ty_path()
1725                            ),
1726                        ))),
1727                        true,
1728                    )),
1729                    _ => None,
1730                }
1731            });
1732
1733            self.note_type_err(
1734                &mut diag,
1735                &obligation.cause,
1736                secondary_span,
1737                values.map(|(_, normalized_ty, expected_ty)| {
1738                    obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(
1739                        expected_ty,
1740                        normalized_ty,
1741                    )))
1742                }),
1743                err,
1744                false,
1745                Some(span),
1746            );
1747            self.note_obligation_cause(&mut diag, obligation);
1748            diag.emit()
1749        })
1750    }
1751
1752    fn maybe_detailed_projection_msg(
1753        &self,
1754        mut span: Span,
1755        projection_term: ty::AliasTerm<'tcx>,
1756        normalized_ty: ty::Term<'tcx>,
1757        expected_ty: ty::Term<'tcx>,
1758        long_ty_path: &mut Option<PathBuf>,
1759    ) -> Option<(String, Span, Option<Span>)> {
1760        let trait_def_id = projection_term.trait_def_id(self.tcx);
1761        let self_ty = projection_term.self_ty();
1762
1763        {
    let _guard = ForceTrimmedGuard::new();
    if self.tcx.is_lang_item(projection_term.def_id, LangItem::FnOnceOutput) {
        let (span, closure_span) =
            if let ty::Closure(def_id, _) = self_ty.kind() {
                let def_span = self.tcx.def_span(def_id);
                if let Some(local_def_id) = def_id.as_local() &&
                                let node = self.tcx.hir_node_by_def_id(local_def_id) &&
                            let Some(fn_decl) = node.fn_decl() &&
                        let Some(id) = node.body_id() {
                    span =
                        match fn_decl.output {
                            hir::FnRetTy::Return(ty) => ty.span,
                            hir::FnRetTy::DefaultReturn(_) => {
                                let body = self.tcx.hir_body(id);
                                match body.value.kind {
                                    hir::ExprKind::Block(hir::Block { expr: Some(expr), .. }, _)
                                        => expr.span,
                                    hir::ExprKind::Block(hir::Block {
                                        expr: None, stmts: [.., last], .. }, _) => last.span,
                                    _ => body.value.span,
                                }
                            }
                        };
                }
                (span, Some(def_span))
            } else { (span, None) };
        let item =
            match self_ty.kind() {
                ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
                _ => self.tcx.short_string(self_ty, long_ty_path),
            };
        let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
        let normalized_ty =
            self.tcx.short_string(normalized_ty, long_ty_path);
        Some((::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("expected `{0}` to return `{1}`, but it returns `{2}`",
                                item, expected_ty, normalized_ty))
                    }), span, closure_span))
    } else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
        let self_ty = self.tcx.short_string(self_ty, long_ty_path);
        let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
        let normalized_ty =
            self.tcx.short_string(normalized_ty, long_ty_path);
        Some((::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("expected `{0}` to be a future that resolves to `{1}`, but it resolves to `{2}`",
                                self_ty, expected_ty, normalized_ty))
                    }), span, None))
    } else if Some(trait_def_id) ==
            self.tcx.get_diagnostic_item(sym::Iterator) {
        let self_ty = self.tcx.short_string(self_ty, long_ty_path);
        let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
        let normalized_ty =
            self.tcx.short_string(normalized_ty, long_ty_path);
        Some((::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("expected `{0}` to be an iterator that yields `{1}`, but it yields `{2}`",
                                self_ty, expected_ty, normalized_ty))
                    }), span, None))
    } else { None }
}with_forced_trimmed_paths! {
1764            if self.tcx.is_lang_item(projection_term.def_id, LangItem::FnOnceOutput) {
1765                let (span, closure_span) = if let ty::Closure(def_id, _) = self_ty.kind() {
1766                    let def_span = self.tcx.def_span(def_id);
1767                    if let Some(local_def_id) = def_id.as_local()
1768                        && let node = self.tcx.hir_node_by_def_id(local_def_id)
1769                        && let Some(fn_decl) = node.fn_decl()
1770                        && let Some(id) = node.body_id()
1771                    {
1772                        span = match fn_decl.output {
1773                            hir::FnRetTy::Return(ty) => ty.span,
1774                            hir::FnRetTy::DefaultReturn(_) => {
1775                                let body = self.tcx.hir_body(id);
1776                                match body.value.kind {
1777                                    hir::ExprKind::Block(
1778                                        hir::Block { expr: Some(expr), .. },
1779                                        _,
1780                                    ) => expr.span,
1781                                    hir::ExprKind::Block(
1782                                        hir::Block {
1783                                            expr: None, stmts: [.., last], ..
1784                                        },
1785                                        _,
1786                                    ) => last.span,
1787                                    _ => body.value.span,
1788                                }
1789                            }
1790                        };
1791                    }
1792                    (span, Some(def_span))
1793                } else {
1794                    (span, None)
1795                };
1796                let item = match self_ty.kind() {
1797                    ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
1798                    _ => self.tcx.short_string(self_ty, long_ty_path),
1799                };
1800                let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1801                let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1802                Some((format!(
1803                    "expected `{item}` to return `{expected_ty}`, but it returns `{normalized_ty}`",
1804                ), span, closure_span))
1805            } else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
1806                let self_ty = self.tcx.short_string(self_ty, long_ty_path);
1807                let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1808                let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1809                Some((format!(
1810                    "expected `{self_ty}` to be a future that resolves to `{expected_ty}`, but it \
1811                     resolves to `{normalized_ty}`"
1812                ), span, None))
1813            } else if Some(trait_def_id) == self.tcx.get_diagnostic_item(sym::Iterator) {
1814                let self_ty = self.tcx.short_string(self_ty, long_ty_path);
1815                let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1816                let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1817                Some((format!(
1818                    "expected `{self_ty}` to be an iterator that yields `{expected_ty}`, but it \
1819                     yields `{normalized_ty}`"
1820                ), span, None))
1821            } else {
1822                None
1823            }
1824        }
1825    }
1826
1827    pub fn fuzzy_match_tys(
1828        &self,
1829        mut a: Ty<'tcx>,
1830        mut b: Ty<'tcx>,
1831        ignoring_lifetimes: bool,
1832    ) -> Option<CandidateSimilarity> {
1833        /// returns the fuzzy category of a given type, or None
1834        /// if the type can be equated to any type.
1835        fn type_category(tcx: TyCtxt<'_>, t: Ty<'_>) -> Option<u32> {
1836            match t.kind() {
1837                ty::Bool => Some(0),
1838                ty::Char => Some(1),
1839                ty::Str => Some(2),
1840                ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => Some(2),
1841                ty::Int(..)
1842                | ty::Uint(..)
1843                | ty::Float(..)
1844                | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) => Some(4),
1845                ty::Ref(..) | ty::RawPtr(..) => Some(5),
1846                ty::Array(..) | ty::Slice(..) => Some(6),
1847                ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1848                ty::Dynamic(..) => Some(8),
1849                ty::Closure(..) => Some(9),
1850                ty::Tuple(..) => Some(10),
1851                ty::Param(..) => Some(11),
1852                ty::Alias(ty::Projection, ..) => Some(12),
1853                ty::Alias(ty::Inherent, ..) => Some(13),
1854                ty::Alias(ty::Opaque, ..) => Some(14),
1855                ty::Alias(ty::Free, ..) => Some(15),
1856                ty::Never => Some(16),
1857                ty::Adt(..) => Some(17),
1858                ty::Coroutine(..) => Some(18),
1859                ty::Foreign(..) => Some(19),
1860                ty::CoroutineWitness(..) => Some(20),
1861                ty::CoroutineClosure(..) => Some(21),
1862                ty::Pat(..) => Some(22),
1863                ty::UnsafeBinder(..) => Some(23),
1864                ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1865            }
1866        }
1867
1868        let strip_references = |mut t: Ty<'tcx>| -> Ty<'tcx> {
1869            loop {
1870                match t.kind() {
1871                    ty::Ref(_, inner, _) | ty::RawPtr(inner, _) => t = *inner,
1872                    _ => break t,
1873                }
1874            }
1875        };
1876
1877        if !ignoring_lifetimes {
1878            a = strip_references(a);
1879            b = strip_references(b);
1880        }
1881
1882        let cat_a = type_category(self.tcx, a)?;
1883        let cat_b = type_category(self.tcx, b)?;
1884        if a == b {
1885            Some(CandidateSimilarity::Exact { ignoring_lifetimes })
1886        } else if cat_a == cat_b {
1887            match (a.kind(), b.kind()) {
1888                (ty::Adt(def_a, _), ty::Adt(def_b, _)) => def_a == def_b,
1889                (ty::Foreign(def_a), ty::Foreign(def_b)) => def_a == def_b,
1890                // Matching on references results in a lot of unhelpful
1891                // suggestions, so let's just not do that for now.
1892                //
1893                // We still upgrade successful matches to `ignoring_lifetimes: true`
1894                // to prioritize that impl.
1895                (ty::Ref(..) | ty::RawPtr(..), ty::Ref(..) | ty::RawPtr(..)) => {
1896                    self.fuzzy_match_tys(a, b, true).is_some()
1897                }
1898                _ => true,
1899            }
1900            .then_some(CandidateSimilarity::Fuzzy { ignoring_lifetimes })
1901        } else if ignoring_lifetimes {
1902            None
1903        } else {
1904            self.fuzzy_match_tys(a, b, true)
1905        }
1906    }
1907
1908    pub(super) fn describe_closure(&self, kind: hir::ClosureKind) -> &'static str {
1909        match kind {
1910            hir::ClosureKind::Closure => "a closure",
1911            hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => "a coroutine",
1912            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1913                hir::CoroutineDesugaring::Async,
1914                hir::CoroutineSource::Block,
1915            )) => "an async block",
1916            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1917                hir::CoroutineDesugaring::Async,
1918                hir::CoroutineSource::Fn,
1919            )) => "an async function",
1920            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1921                hir::CoroutineDesugaring::Async,
1922                hir::CoroutineSource::Closure,
1923            ))
1924            | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
1925                "an async closure"
1926            }
1927            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1928                hir::CoroutineDesugaring::AsyncGen,
1929                hir::CoroutineSource::Block,
1930            )) => "an async gen block",
1931            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1932                hir::CoroutineDesugaring::AsyncGen,
1933                hir::CoroutineSource::Fn,
1934            )) => "an async gen function",
1935            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1936                hir::CoroutineDesugaring::AsyncGen,
1937                hir::CoroutineSource::Closure,
1938            ))
1939            | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
1940                "an async gen closure"
1941            }
1942            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1943                hir::CoroutineDesugaring::Gen,
1944                hir::CoroutineSource::Block,
1945            )) => "a gen block",
1946            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1947                hir::CoroutineDesugaring::Gen,
1948                hir::CoroutineSource::Fn,
1949            )) => "a gen function",
1950            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1951                hir::CoroutineDesugaring::Gen,
1952                hir::CoroutineSource::Closure,
1953            ))
1954            | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => "a gen closure",
1955        }
1956    }
1957
1958    pub(super) fn find_similar_impl_candidates(
1959        &self,
1960        trait_pred: ty::PolyTraitPredicate<'tcx>,
1961    ) -> Vec<ImplCandidate<'tcx>> {
1962        let mut candidates: Vec<_> = self
1963            .tcx
1964            .all_impls(trait_pred.def_id())
1965            .filter_map(|def_id| {
1966                let imp = self.tcx.impl_trait_header(def_id);
1967                if imp.polarity != ty::ImplPolarity::Positive
1968                    || !self.tcx.is_user_visible_dep(def_id.krate)
1969                {
1970                    return None;
1971                }
1972                let imp = imp.trait_ref.skip_binder();
1973
1974                self.fuzzy_match_tys(trait_pred.skip_binder().self_ty(), imp.self_ty(), false).map(
1975                    |similarity| ImplCandidate { trait_ref: imp, similarity, impl_def_id: def_id },
1976                )
1977            })
1978            .collect();
1979        if candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
    CandidateSimilarity::Exact { .. } => true,
    _ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. })) {
1980            // If any of the candidates is a perfect match, we don't want to show all of them.
1981            // This is particularly relevant for the case of numeric types (as they all have the
1982            // same category).
1983            candidates.retain(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
    CandidateSimilarity::Exact { .. } => true,
    _ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. }));
1984        }
1985        candidates
1986    }
1987
1988    pub(super) fn report_similar_impl_candidates(
1989        &self,
1990        impl_candidates: &[ImplCandidate<'tcx>],
1991        trait_pred: ty::PolyTraitPredicate<'tcx>,
1992        body_def_id: LocalDefId,
1993        err: &mut Diag<'_>,
1994        other: bool,
1995        param_env: ty::ParamEnv<'tcx>,
1996    ) -> bool {
1997        let parent_map = self.tcx.visible_parent_map(());
1998        let alternative_candidates = |def_id: DefId| {
1999            let mut impl_candidates: Vec<_> = self
2000                .tcx
2001                .all_impls(def_id)
2002                // ignore `do_not_recommend` items
2003                .filter(|def_id| !self.tcx.do_not_recommend_impl(*def_id))
2004                // Ignore automatically derived impls and `!Trait` impls.
2005                .map(|def_id| (self.tcx.impl_trait_header(def_id), def_id))
2006                .filter_map(|(header, def_id)| {
2007                    (header.polarity == ty::ImplPolarity::Positive
2008                        || self.tcx.is_automatically_derived(def_id))
2009                    .then(|| (header.trait_ref.instantiate_identity(), def_id))
2010                })
2011                .filter(|(trait_ref, _)| {
2012                    let self_ty = trait_ref.self_ty();
2013                    // Avoid mentioning type parameters.
2014                    if let ty::Param(_) = self_ty.kind() {
2015                        false
2016                    }
2017                    // Avoid mentioning types that are private to another crate
2018                    else if let ty::Adt(def, _) = self_ty.peel_refs().kind() {
2019                        // FIXME(compiler-errors): This could be generalized, both to
2020                        // be more granular, and probably look past other `#[fundamental]`
2021                        // types, too.
2022                        let mut did = def.did();
2023                        if self.tcx.visibility(did).is_accessible_from(body_def_id, self.tcx) {
2024                            // don't suggest foreign `#[doc(hidden)]` types
2025                            if !did.is_local() {
2026                                let mut previously_seen_dids: FxHashSet<DefId> = Default::default();
2027                                previously_seen_dids.insert(did);
2028                                while let Some(&parent) = parent_map.get(&did)
2029                                    && let hash_set::Entry::Vacant(v) =
2030                                        previously_seen_dids.entry(parent)
2031                                {
2032                                    if self.tcx.is_doc_hidden(did) {
2033                                        return false;
2034                                    }
2035                                    v.insert();
2036                                    did = parent;
2037                                }
2038                            }
2039                            true
2040                        } else {
2041                            false
2042                        }
2043                    } else {
2044                        true
2045                    }
2046                })
2047                .collect();
2048
2049            impl_candidates.sort_by_key(|(tr, _)| tr.to_string());
2050            impl_candidates.dedup();
2051            impl_candidates
2052        };
2053
2054        if let [single] = &impl_candidates {
2055            // If we have a single implementation, try to unify it with the trait ref
2056            // that failed. This should uncover a better hint for what *is* implemented.
2057            if self.probe(|_| {
2058                let ocx = ObligationCtxt::new(self);
2059
2060                self.enter_forall(trait_pred, |obligation_trait_ref| {
2061                    let impl_args = self.fresh_args_for_item(DUMMY_SP, single.impl_def_id);
2062                    let impl_trait_ref = ocx.normalize(
2063                        &ObligationCause::dummy(),
2064                        param_env,
2065                        ty::EarlyBinder::bind(single.trait_ref).instantiate(self.tcx, impl_args),
2066                    );
2067
2068                    ocx.register_obligations(
2069                        self.tcx
2070                            .predicates_of(single.impl_def_id)
2071                            .instantiate(self.tcx, impl_args)
2072                            .into_iter()
2073                            .map(|(clause, _)| {
2074                                Obligation::new(
2075                                    self.tcx,
2076                                    ObligationCause::dummy(),
2077                                    param_env,
2078                                    clause,
2079                                )
2080                            }),
2081                    );
2082                    if !ocx.try_evaluate_obligations().is_empty() {
2083                        return false;
2084                    }
2085
2086                    let mut terrs = ::alloc::vec::Vec::new()vec![];
2087                    for (obligation_arg, impl_arg) in
2088                        std::iter::zip(obligation_trait_ref.trait_ref.args, impl_trait_ref.args)
2089                    {
2090                        if (obligation_arg, impl_arg).references_error() {
2091                            return false;
2092                        }
2093                        if let Err(terr) =
2094                            ocx.eq(&ObligationCause::dummy(), param_env, impl_arg, obligation_arg)
2095                        {
2096                            terrs.push(terr);
2097                        }
2098                        if !ocx.try_evaluate_obligations().is_empty() {
2099                            return false;
2100                        }
2101                    }
2102
2103                    // Literally nothing unified, just give up.
2104                    if terrs.len() == impl_trait_ref.args.len() {
2105                        return false;
2106                    }
2107
2108                    let impl_trait_ref = self.resolve_vars_if_possible(impl_trait_ref);
2109                    if impl_trait_ref.references_error() {
2110                        return false;
2111                    }
2112
2113                    if let [child, ..] = &err.children[..]
2114                        && child.level == Level::Help
2115                        && let Some(line) = child.messages.get(0)
2116                        && let Some(line) = line.0.as_str()
2117                        && line.starts_with("the trait")
2118                        && line.contains("is not implemented for")
2119                    {
2120                        // HACK(estebank): we remove the pre-existing
2121                        // "the trait `X` is not implemented for" note, which only happens if there
2122                        // was a custom label. We do this because we want that note to always be the
2123                        // first, and making this logic run earlier will get tricky. For now, we
2124                        // instead keep the logic the same and modify the already constructed error
2125                        // to avoid the wording duplication.
2126                        err.children.remove(0);
2127                    }
2128
2129                    let traits = self.cmp_traits(
2130                        obligation_trait_ref.def_id(),
2131                        &obligation_trait_ref.trait_ref.args[1..],
2132                        impl_trait_ref.def_id,
2133                        &impl_trait_ref.args[1..],
2134                    );
2135                    let traits_content = (traits.0.content(), traits.1.content());
2136                    let types = self.cmp(obligation_trait_ref.self_ty(), impl_trait_ref.self_ty());
2137                    let types_content = (types.0.content(), types.1.content());
2138                    let mut msg = <[_]>::into_vec(::alloc::boxed::box_new([StringPart::normal("the trait `")]))vec![StringPart::normal("the trait `")];
2139                    if traits_content.0 == traits_content.1 {
2140                        msg.push(StringPart::normal(
2141                            impl_trait_ref.print_trait_sugared().to_string(),
2142                        ));
2143                    } else {
2144                        msg.extend(traits.0.0);
2145                    }
2146                    msg.extend([
2147                        StringPart::normal("` "),
2148                        StringPart::highlighted("is not"),
2149                        StringPart::normal(" implemented for `"),
2150                    ]);
2151                    if types_content.0 == types_content.1 {
2152                        let ty = self
2153                            .tcx
2154                            .short_string(obligation_trait_ref.self_ty(), err.long_ty_path());
2155                        msg.push(StringPart::normal(ty));
2156                    } else {
2157                        msg.extend(types.0.0);
2158                    }
2159                    msg.push(StringPart::normal("`"));
2160                    if types_content.0 == types_content.1 {
2161                        msg.push(StringPart::normal("\nbut trait `"));
2162                        msg.extend(traits.1.0);
2163                        msg.extend([
2164                            StringPart::normal("` "),
2165                            StringPart::highlighted("is"),
2166                            StringPart::normal(" implemented for it"),
2167                        ]);
2168                    } else if traits_content.0 == traits_content.1 {
2169                        msg.extend([
2170                            StringPart::normal("\nbut it "),
2171                            StringPart::highlighted("is"),
2172                            StringPart::normal(" implemented for `"),
2173                        ]);
2174                        msg.extend(types.1.0);
2175                        msg.push(StringPart::normal("`"));
2176                    } else {
2177                        msg.push(StringPart::normal("\nbut trait `"));
2178                        msg.extend(traits.1.0);
2179                        msg.extend([
2180                            StringPart::normal("` "),
2181                            StringPart::highlighted("is"),
2182                            StringPart::normal(" implemented for `"),
2183                        ]);
2184                        msg.extend(types.1.0);
2185                        msg.push(StringPart::normal("`"));
2186                    }
2187                    err.highlighted_span_help(self.tcx.def_span(single.impl_def_id), msg);
2188
2189                    if let [TypeError::Sorts(exp_found)] = &terrs[..] {
2190                        let exp_found = self.resolve_vars_if_possible(*exp_found);
2191                        let expected =
2192                            self.tcx.short_string(exp_found.expected, err.long_ty_path());
2193                        let found = self.tcx.short_string(exp_found.found, err.long_ty_path());
2194                        err.highlighted_help(<[_]>::into_vec(::alloc::boxed::box_new([StringPart::normal("for that trait implementation, "),
                StringPart::normal("expected `"),
                StringPart::highlighted(expected),
                StringPart::normal("`, found `"),
                StringPart::highlighted(found), StringPart::normal("`")]))vec![
2195                            StringPart::normal("for that trait implementation, "),
2196                            StringPart::normal("expected `"),
2197                            StringPart::highlighted(expected),
2198                            StringPart::normal("`, found `"),
2199                            StringPart::highlighted(found),
2200                            StringPart::normal("`"),
2201                        ]);
2202                        self.suggest_function_pointers_impl(None, &exp_found, err);
2203                    }
2204
2205                    if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2206                        && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2207                        && !crates.is_empty()
2208                    {
2209                        self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2210                        err.help("you can use `cargo tree` to explore your dependency tree");
2211                    }
2212                    true
2213                })
2214            }) {
2215                return true;
2216            }
2217        }
2218
2219        let other = if other { "other " } else { "" };
2220        let report = |mut candidates: Vec<(TraitRef<'tcx>, DefId)>, err: &mut Diag<'_>| {
2221            candidates.retain(|(tr, _)| !tr.references_error());
2222            if candidates.is_empty() {
2223                return false;
2224            }
2225            if let &[(cand, def_id)] = &candidates[..] {
2226                if self.tcx.is_diagnostic_item(sym::FromResidual, cand.def_id)
2227                    && !self.tcx.features().enabled(sym::try_trait_v2)
2228                {
2229                    return false;
2230                }
2231                let (desc, mention_castable) =
2232                    match (cand.self_ty().kind(), trait_pred.self_ty().skip_binder().kind()) {
2233                        (ty::FnPtr(..), ty::FnDef(..)) => {
2234                            (" implemented for fn pointer `", ", cast using `as`")
2235                        }
2236                        (ty::FnPtr(..), _) => (" implemented for fn pointer `", ""),
2237                        _ => (" implemented for `", ""),
2238                    };
2239                let trait_ = self.tcx.short_string(cand.print_trait_sugared(), err.long_ty_path());
2240                let self_ty = self.tcx.short_string(cand.self_ty(), err.long_ty_path());
2241                err.highlighted_span_help(
2242                    self.tcx.def_span(def_id),
2243                    <[_]>::into_vec(::alloc::boxed::box_new([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![
2244                        StringPart::normal(format!("the trait `{trait_}` ",)),
2245                        StringPart::highlighted("is"),
2246                        StringPart::normal(desc),
2247                        StringPart::highlighted(self_ty),
2248                        StringPart::normal("`"),
2249                        StringPart::normal(mention_castable),
2250                    ],
2251                );
2252                return true;
2253            }
2254            let trait_ref = TraitRef::identity(self.tcx, candidates[0].0.def_id);
2255            // Check if the trait is the same in all cases. If so, we'll only show the type.
2256            let mut traits: Vec<_> =
2257                candidates.iter().map(|(c, _)| c.print_only_trait_path().to_string()).collect();
2258            traits.sort();
2259            traits.dedup();
2260            // FIXME: this could use a better heuristic, like just checking
2261            // that args[1..] is the same.
2262            let all_traits_equal = traits.len() == 1;
2263
2264            let end = if candidates.len() <= 9 || self.tcx.sess.opts.verbose {
2265                candidates.len()
2266            } else {
2267                8
2268            };
2269            if candidates.len() < 5 {
2270                let spans: Vec<_> =
2271                    candidates.iter().map(|(_, def_id)| self.tcx.def_span(def_id)).collect();
2272                let mut span: MultiSpan = spans.into();
2273                for (c, def_id) in &candidates {
2274                    let msg = if all_traits_equal {
2275                        ::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()))
2276                    } else {
2277                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` implements `{1}`",
                self.tcx.short_string(c.self_ty(), err.long_ty_path()),
                self.tcx.short_string(c.print_only_trait_path(),
                    err.long_ty_path())))
    })format!(
2278                            "`{}` implements `{}`",
2279                            self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2280                            self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path()),
2281                        )
2282                    };
2283                    span.push_span_label(self.tcx.def_span(def_id), msg);
2284                }
2285                err.span_help(
2286                    span,
2287                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the following {1}types implement trait `{0}`",
                trait_ref.print_trait_sugared(), other))
    })format!(
2288                        "the following {other}types implement trait `{}`",
2289                        trait_ref.print_trait_sugared(),
2290                    ),
2291                );
2292            } else {
2293                let candidate_names: Vec<String> = candidates
2294                    .iter()
2295                    .map(|(c, _)| {
2296                        if all_traits_equal {
2297                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n  {0}",
                self.tcx.short_string(c.self_ty(), err.long_ty_path())))
    })format!(
2298                                "\n  {}",
2299                                self.tcx.short_string(c.self_ty(), err.long_ty_path())
2300                            )
2301                        } else {
2302                            ::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!(
2303                                "\n  `{}` implements `{}`",
2304                                self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2305                                self.tcx
2306                                    .short_string(c.print_only_trait_path(), err.long_ty_path()),
2307                            )
2308                        }
2309                    })
2310                    .collect();
2311                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the following {3}types implement trait `{0}`:{1}{2}",
                trait_ref.print_trait_sugared(),
                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() }, other))
    })format!(
2312                    "the following {other}types implement trait `{}`:{}{}",
2313                    trait_ref.print_trait_sugared(),
2314                    candidate_names[..end].join(""),
2315                    if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
2316                        format!("\nand {} others", candidates.len() - 8)
2317                    } else {
2318                        String::new()
2319                    }
2320                ));
2321            }
2322
2323            if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2324                && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2325                && !crates.is_empty()
2326            {
2327                self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2328                err.help("you can use `cargo tree` to explore your dependency tree");
2329            }
2330            true
2331        };
2332
2333        // we filter before checking if `impl_candidates` is empty
2334        // to get the fallback solution if we filtered out any impls
2335        let impl_candidates = impl_candidates
2336            .into_iter()
2337            .cloned()
2338            .filter(|cand| !self.tcx.do_not_recommend_impl(cand.impl_def_id))
2339            .collect::<Vec<_>>();
2340
2341        let def_id = trait_pred.def_id();
2342        if impl_candidates.is_empty() {
2343            if self.tcx.trait_is_auto(def_id)
2344                || self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2345                || self.tcx.get_diagnostic_name(def_id).is_some()
2346            {
2347                // Mentioning implementers of `Copy`, `Debug` and friends is not useful.
2348                return false;
2349            }
2350            return report(alternative_candidates(def_id), err);
2351        }
2352
2353        // Sort impl candidates so that ordering is consistent for UI tests.
2354        // because the ordering of `impl_candidates` may not be deterministic:
2355        // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
2356        //
2357        // Prefer more similar candidates first, then sort lexicographically
2358        // by their normalized string representation.
2359        let mut impl_candidates: Vec<_> = impl_candidates
2360            .iter()
2361            .cloned()
2362            .filter(|cand| !cand.trait_ref.references_error())
2363            .map(|mut cand| {
2364                // Normalize the trait ref in its *own* param-env so
2365                // that consts are folded and any trivial projections
2366                // are normalized.
2367                cand.trait_ref = self
2368                    .tcx
2369                    .try_normalize_erasing_regions(
2370                        ty::TypingEnv::non_body_analysis(self.tcx, cand.impl_def_id),
2371                        cand.trait_ref,
2372                    )
2373                    .unwrap_or(cand.trait_ref);
2374                cand
2375            })
2376            .collect();
2377        impl_candidates.sort_by_key(|cand| {
2378            // When suggesting array types, sort them by the length of the array, not lexicographically (#135098)
2379            let len = if let GenericArgKind::Type(ty) = cand.trait_ref.args[0].kind()
2380                && let ty::Array(_, len) = ty.kind()
2381            {
2382                // Deprioritize suggestions for parameterized arrays.
2383                len.try_to_target_usize(self.tcx).unwrap_or(u64::MAX)
2384            } else {
2385                0
2386            };
2387
2388            (cand.similarity, len, cand.trait_ref.to_string())
2389        });
2390        let mut impl_candidates: Vec<_> =
2391            impl_candidates.into_iter().map(|cand| (cand.trait_ref, cand.impl_def_id)).collect();
2392        impl_candidates.dedup();
2393
2394        report(impl_candidates, err)
2395    }
2396
2397    fn report_similar_impl_candidates_for_root_obligation(
2398        &self,
2399        obligation: &PredicateObligation<'tcx>,
2400        trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2401        body_def_id: LocalDefId,
2402        err: &mut Diag<'_>,
2403    ) {
2404        // This is *almost* equivalent to
2405        // `obligation.cause.code().peel_derives()`, but it gives us the
2406        // trait predicate for that corresponding root obligation. This
2407        // lets us get a derived obligation from a type parameter, like
2408        // when calling `string.strip_suffix(p)` where `p` is *not* an
2409        // implementer of `Pattern<'_>`.
2410        let mut code = obligation.cause.code();
2411        let mut trait_pred = trait_predicate;
2412        let mut peeled = false;
2413        while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
2414            code = parent_code;
2415            if let Some(parent_trait_pred) = parent_trait_pred {
2416                trait_pred = parent_trait_pred;
2417                peeled = true;
2418            }
2419        }
2420        let def_id = trait_pred.def_id();
2421        // Mention *all* the `impl`s for the *top most* obligation, the
2422        // user might have meant to use one of them, if any found. We skip
2423        // auto-traits or fundamental traits that might not be exactly what
2424        // the user might expect to be presented with. Instead this is
2425        // useful for less general traits.
2426        if peeled && !self.tcx.trait_is_auto(def_id) && self.tcx.as_lang_item(def_id).is_none() {
2427            let impl_candidates = self.find_similar_impl_candidates(trait_pred);
2428            self.report_similar_impl_candidates(
2429                &impl_candidates,
2430                trait_pred,
2431                body_def_id,
2432                err,
2433                true,
2434                obligation.param_env,
2435            );
2436        }
2437    }
2438
2439    /// Gets the parent trait chain start
2440    fn get_parent_trait_ref(
2441        &self,
2442        code: &ObligationCauseCode<'tcx>,
2443    ) -> Option<(Ty<'tcx>, Option<Span>)> {
2444        match code {
2445            ObligationCauseCode::BuiltinDerived(data) => {
2446                let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2447                match self.get_parent_trait_ref(&data.parent_code) {
2448                    Some(t) => Some(t),
2449                    None => {
2450                        let ty = parent_trait_ref.skip_binder().self_ty();
2451                        let span = TyCategory::from_ty(self.tcx, ty)
2452                            .map(|(_, def_id)| self.tcx.def_span(def_id));
2453                        Some((ty, span))
2454                    }
2455                }
2456            }
2457            ObligationCauseCode::FunctionArg { parent_code, .. } => {
2458                self.get_parent_trait_ref(parent_code)
2459            }
2460            _ => None,
2461        }
2462    }
2463
2464    fn check_same_trait_different_version(
2465        &self,
2466        err: &mut Diag<'_>,
2467        trait_pred: ty::PolyTraitPredicate<'tcx>,
2468    ) -> bool {
2469        let get_trait_impls = |trait_def_id| {
2470            let mut trait_impls = ::alloc::vec::Vec::new()vec![];
2471            self.tcx.for_each_relevant_impl(
2472                trait_def_id,
2473                trait_pred.skip_binder().self_ty(),
2474                |impl_def_id| {
2475                    let impl_trait_header = self.tcx.impl_trait_header(impl_def_id);
2476                    trait_impls
2477                        .push(self.tcx.def_span(impl_trait_header.trait_ref.skip_binder().def_id));
2478                },
2479            );
2480            trait_impls
2481        };
2482        self.check_same_definition_different_crate(
2483            err,
2484            trait_pred.def_id(),
2485            self.tcx.visible_traits(),
2486            get_trait_impls,
2487            "trait",
2488        )
2489    }
2490
2491    pub fn note_two_crate_versions(
2492        &self,
2493        krate: CrateNum,
2494        sp: impl Into<MultiSpan>,
2495        err: &mut Diag<'_>,
2496    ) {
2497        let crate_name = self.tcx.crate_name(krate);
2498        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!(
2499            "there are multiple different versions of crate `{crate_name}` in the dependency graph"
2500        );
2501        err.span_note(sp, crate_msg);
2502    }
2503
2504    fn note_adt_version_mismatch(
2505        &self,
2506        err: &mut Diag<'_>,
2507        trait_pred: ty::PolyTraitPredicate<'tcx>,
2508    ) {
2509        let ty::Adt(impl_self_def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2510        else {
2511            return;
2512        };
2513
2514        let impl_self_did = impl_self_def.did();
2515
2516        // We only want to warn about different versions of a dependency.
2517        // If no dependency is involved, bail.
2518        if impl_self_did.krate == LOCAL_CRATE {
2519            return;
2520        }
2521
2522        let impl_self_path = self.comparable_path(impl_self_did);
2523        let impl_self_crate_name = self.tcx.crate_name(impl_self_did.krate);
2524        let similar_items: UnordSet<_> = self
2525            .tcx
2526            .visible_parent_map(())
2527            .items()
2528            .filter_map(|(&item, _)| {
2529                // If we found ourselves, ignore.
2530                if impl_self_did == item {
2531                    return None;
2532                }
2533                // We only want to warn about different versions of a dependency.
2534                // Ignore items from our own crate.
2535                if item.krate == LOCAL_CRATE {
2536                    return None;
2537                }
2538                // We want to warn about different versions of a dependency.
2539                // So make sure the crate names are the same.
2540                if impl_self_crate_name != self.tcx.crate_name(item.krate) {
2541                    return None;
2542                }
2543                // Filter out e.g. constructors that often have the same path
2544                // str as the relevant ADT.
2545                if !self.tcx.def_kind(item).is_adt() {
2546                    return None;
2547                }
2548                let path = self.comparable_path(item);
2549                // We don't know if our item or the one we found is the re-exported one.
2550                // Check both cases.
2551                let is_similar = path.ends_with(&impl_self_path) || impl_self_path.ends_with(&path);
2552                is_similar.then_some((item, path))
2553            })
2554            .collect();
2555
2556        let mut similar_items =
2557            similar_items.into_items().into_sorted_stable_ord_by_key(|(_, path)| path);
2558        similar_items.dedup();
2559
2560        for (similar_item, _) in similar_items {
2561            err.span_help(self.tcx.def_span(similar_item), "item with same name found");
2562            self.note_two_crate_versions(similar_item.krate, MultiSpan::new(), err);
2563        }
2564    }
2565
2566    fn check_same_name_different_path(
2567        &self,
2568        err: &mut Diag<'_>,
2569        obligation: &PredicateObligation<'tcx>,
2570        trait_pred: ty::PolyTraitPredicate<'tcx>,
2571    ) -> bool {
2572        let mut suggested = false;
2573        let trait_def_id = trait_pred.def_id();
2574        let trait_has_same_params = |other_trait_def_id: DefId| -> bool {
2575            let trait_generics = self.tcx.generics_of(trait_def_id);
2576            let other_trait_generics = self.tcx.generics_of(other_trait_def_id);
2577
2578            if trait_generics.count() != other_trait_generics.count() {
2579                return false;
2580            }
2581            trait_generics.own_params.iter().zip(other_trait_generics.own_params.iter()).all(
2582                |(a, b)| match (&a.kind, &b.kind) {
2583                    (ty::GenericParamDefKind::Lifetime, ty::GenericParamDefKind::Lifetime)
2584                    | (
2585                        ty::GenericParamDefKind::Type { .. },
2586                        ty::GenericParamDefKind::Type { .. },
2587                    )
2588                    | (
2589                        ty::GenericParamDefKind::Const { .. },
2590                        ty::GenericParamDefKind::Const { .. },
2591                    ) => true,
2592                    _ => false,
2593                },
2594            )
2595        };
2596        let trait_name = self.tcx.item_name(trait_def_id);
2597        if let Some(other_trait_def_id) = self.tcx.all_traits_including_private().find(|def_id| {
2598            trait_def_id != *def_id
2599                && trait_name == self.tcx.item_name(def_id)
2600                && trait_has_same_params(*def_id)
2601                && self.predicate_must_hold_modulo_regions(&Obligation::new(
2602                    self.tcx,
2603                    obligation.cause.clone(),
2604                    obligation.param_env,
2605                    trait_pred.map_bound(|tr| ty::TraitPredicate {
2606                        trait_ref: ty::TraitRef::new(self.tcx, *def_id, tr.trait_ref.args),
2607                        ..tr
2608                    }),
2609                ))
2610        }) {
2611            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!(
2612                "`{}` implements similarly named trait `{}`, but not `{}`",
2613                trait_pred.self_ty(),
2614                self.tcx.def_path_str(other_trait_def_id),
2615                trait_pred.print_modifiers_and_trait_path()
2616            ));
2617            suggested = true;
2618        }
2619        suggested
2620    }
2621
2622    /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
2623    /// with the same path as `trait_ref`, a help message about a multiple different
2624    /// versions of the same crate is added to `err`. Otherwise if it implements another
2625    /// trait with the same name, a note message about a similarly named trait is added to `err`.
2626    pub fn note_different_trait_with_same_name(
2627        &self,
2628        err: &mut Diag<'_>,
2629        obligation: &PredicateObligation<'tcx>,
2630        trait_pred: ty::PolyTraitPredicate<'tcx>,
2631    ) -> bool {
2632        if self.check_same_trait_different_version(err, trait_pred) {
2633            return true;
2634        }
2635        self.check_same_name_different_path(err, obligation, trait_pred)
2636    }
2637
2638    /// Add a `::` prefix when comparing paths so that paths with just one item
2639    /// like "Foo" does not equal the end of "OtherFoo".
2640    fn comparable_path(&self, did: DefId) -> String {
2641        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("::{0}",
                self.tcx.def_path_str(did)))
    })format!("::{}", self.tcx.def_path_str(did))
2642    }
2643
2644    /// Creates a `PredicateObligation` with `new_self_ty` replacing the existing type in the
2645    /// `trait_ref`.
2646    ///
2647    /// For this to work, `new_self_ty` must have no escaping bound variables.
2648    pub(super) fn mk_trait_obligation_with_new_self_ty(
2649        &self,
2650        param_env: ty::ParamEnv<'tcx>,
2651        trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>,
2652    ) -> PredicateObligation<'tcx> {
2653        let trait_pred = trait_ref_and_ty
2654            .map_bound(|(tr, new_self_ty)| tr.with_replaced_self_ty(self.tcx, new_self_ty));
2655
2656        Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred)
2657    }
2658
2659    /// Returns `true` if the trait predicate may apply for *some* assignment
2660    /// to the type parameters.
2661    fn predicate_can_apply(
2662        &self,
2663        param_env: ty::ParamEnv<'tcx>,
2664        pred: ty::PolyTraitPredicate<'tcx>,
2665    ) -> bool {
2666        struct ParamToVarFolder<'a, 'tcx> {
2667            infcx: &'a InferCtxt<'tcx>,
2668            var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2669        }
2670
2671        impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ParamToVarFolder<'a, 'tcx> {
2672            fn cx(&self) -> TyCtxt<'tcx> {
2673                self.infcx.tcx
2674            }
2675
2676            fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2677                if let ty::Param(_) = *ty.kind() {
2678                    let infcx = self.infcx;
2679                    *self.var_map.entry(ty).or_insert_with(|| infcx.next_ty_var(DUMMY_SP))
2680                } else {
2681                    ty.super_fold_with(self)
2682                }
2683            }
2684        }
2685
2686        self.probe(|_| {
2687            let cleaned_pred =
2688                pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2689
2690            let InferOk { value: cleaned_pred, .. } =
2691                self.infcx.at(&ObligationCause::dummy(), param_env).normalize(cleaned_pred);
2692
2693            let obligation =
2694                Obligation::new(self.tcx, ObligationCause::dummy(), param_env, cleaned_pred);
2695
2696            self.predicate_may_hold(&obligation)
2697        })
2698    }
2699
2700    pub fn note_obligation_cause(
2701        &self,
2702        err: &mut Diag<'_>,
2703        obligation: &PredicateObligation<'tcx>,
2704    ) {
2705        // First, attempt to add note to this error with an async-await-specific
2706        // message, and fall back to regular note otherwise.
2707        if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2708            self.note_obligation_cause_code(
2709                obligation.cause.body_id,
2710                err,
2711                obligation.predicate,
2712                obligation.param_env,
2713                obligation.cause.code(),
2714                &mut ::alloc::vec::Vec::new()vec![],
2715                &mut Default::default(),
2716            );
2717            self.suggest_swapping_lhs_and_rhs(
2718                err,
2719                obligation.predicate,
2720                obligation.param_env,
2721                obligation.cause.code(),
2722            );
2723            self.suggest_unsized_bound_if_applicable(err, obligation);
2724            if let Some(span) = err.span.primary_span()
2725                && let Some(mut diag) =
2726                    self.dcx().steal_non_err(span, StashKey::AssociatedTypeSuggestion)
2727                && let Suggestions::Enabled(ref mut s1) = err.suggestions
2728                && let Suggestions::Enabled(ref mut s2) = diag.suggestions
2729            {
2730                s1.append(s2);
2731                diag.cancel()
2732            }
2733        }
2734    }
2735
2736    pub(super) fn is_recursive_obligation(
2737        &self,
2738        obligated_types: &mut Vec<Ty<'tcx>>,
2739        cause_code: &ObligationCauseCode<'tcx>,
2740    ) -> bool {
2741        if let ObligationCauseCode::BuiltinDerived(data) = cause_code {
2742            let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2743            let self_ty = parent_trait_ref.skip_binder().self_ty();
2744            if obligated_types.iter().any(|ot| ot == &self_ty) {
2745                return true;
2746            }
2747            if let ty::Adt(def, args) = self_ty.kind()
2748                && let [arg] = &args[..]
2749                && let ty::GenericArgKind::Type(ty) = arg.kind()
2750                && let ty::Adt(inner_def, _) = ty.kind()
2751                && inner_def == def
2752            {
2753                return true;
2754            }
2755        }
2756        false
2757    }
2758
2759    fn get_standard_error_message(
2760        &self,
2761        trait_predicate: ty::PolyTraitPredicate<'tcx>,
2762        message: Option<String>,
2763        predicate_constness: Option<ty::BoundConstness>,
2764        append_const_msg: Option<AppendConstMessage>,
2765        post_message: String,
2766        long_ty_path: &mut Option<PathBuf>,
2767    ) -> String {
2768        message
2769            .and_then(|cannot_do_this| {
2770                match (predicate_constness, append_const_msg) {
2771                    // do nothing if predicate is not const
2772                    (None, _) => Some(cannot_do_this),
2773                    // suggested using default post message
2774                    (
2775                        Some(ty::BoundConstness::Const | ty::BoundConstness::Maybe),
2776                        Some(AppendConstMessage::Default),
2777                    ) => Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} in const contexts",
                cannot_do_this))
    })format!("{cannot_do_this} in const contexts")),
2778                    // overridden post message
2779                    (
2780                        Some(ty::BoundConstness::Const | ty::BoundConstness::Maybe),
2781                        Some(AppendConstMessage::Custom(custom_msg, _)),
2782                    ) => Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", cannot_do_this,
                custom_msg))
    })format!("{cannot_do_this}{custom_msg}")),
2783                    // fallback to generic message
2784                    (Some(ty::BoundConstness::Const | ty::BoundConstness::Maybe), None) => None,
2785                }
2786            })
2787            .unwrap_or_else(|| {
2788                ::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!(
2789                    "the trait bound `{}` is not satisfied{post_message}",
2790                    self.tcx.short_string(
2791                        trait_predicate.print_with_bound_constness(predicate_constness),
2792                        long_ty_path,
2793                    ),
2794                )
2795            })
2796    }
2797
2798    fn get_safe_transmute_error_and_reason(
2799        &self,
2800        obligation: PredicateObligation<'tcx>,
2801        trait_pred: ty::PolyTraitPredicate<'tcx>,
2802        span: Span,
2803    ) -> GetSafeTransmuteErrorAndReason {
2804        use rustc_transmute::Answer;
2805        self.probe(|_| {
2806            // We don't assemble a transmutability candidate for types that are generic
2807            // and we should have ambiguity for types that still have non-region infer.
2808            if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
2809                return GetSafeTransmuteErrorAndReason::Default;
2810            }
2811
2812            // Erase regions because layout code doesn't particularly care about regions.
2813            let trait_pred = self.tcx.erase_and_anonymize_regions(
2814                self.tcx.instantiate_bound_regions_with_erased(trait_pred),
2815            );
2816
2817            let ocx = ObligationCtxt::new(self);
2818            let Ok(assume) = ocx.structurally_normalize_const(
2819                &obligation.cause,
2820                obligation.param_env,
2821                trait_pred.trait_ref.args.const_at(2),
2822            ) else {
2823                self.dcx().span_delayed_bug(
2824                    span,
2825                    "Unable to construct rustc_transmute::Assume where it was previously possible",
2826                );
2827                return GetSafeTransmuteErrorAndReason::Silent;
2828            };
2829
2830            let Some(assume) = rustc_transmute::Assume::from_const(self.infcx.tcx, assume) else {
2831                self.dcx().span_delayed_bug(
2832                    span,
2833                    "Unable to construct rustc_transmute::Assume where it was previously possible",
2834                );
2835                return GetSafeTransmuteErrorAndReason::Silent;
2836            };
2837
2838            let dst = trait_pred.trait_ref.args.type_at(0);
2839            let src = trait_pred.trait_ref.args.type_at(1);
2840            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}`");
2841
2842            match rustc_transmute::TransmuteTypeEnv::new(self.infcx.tcx)
2843                .is_transmutable(src, dst, assume)
2844            {
2845                Answer::No(reason) => {
2846                    let safe_transmute_explanation = match reason {
2847                        rustc_transmute::Reason::SrcIsNotYetSupported => {
2848                            ::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")
2849                        }
2850                        rustc_transmute::Reason::DstIsNotYetSupported => {
2851                            ::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")
2852                        }
2853                        rustc_transmute::Reason::DstIsBitIncompatible => {
2854                            ::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!(
2855                                "at least one value of `{src}` isn't a bit-valid value of `{dst}`"
2856                            )
2857                        }
2858                        rustc_transmute::Reason::DstUninhabited => {
2859                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is uninhabited", dst))
    })format!("`{dst}` is uninhabited")
2860                        }
2861                        rustc_transmute::Reason::DstMayHaveSafetyInvariants => {
2862                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` may carry safety invariants",
                dst))
    })format!("`{dst}` may carry safety invariants")
2863                        }
2864                        rustc_transmute::Reason::DstIsTooBig => {
2865                            ::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}`")
2866                        }
2867                        rustc_transmute::Reason::DstRefIsTooBig {
2868                            src,
2869                            src_size,
2870                            dst,
2871                            dst_size,
2872                        } => {
2873                            ::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!(
2874                                "the size of `{src}` ({src_size} bytes) \
2875                        is smaller than that of `{dst}` ({dst_size} bytes)"
2876                            )
2877                        }
2878                        rustc_transmute::Reason::SrcSizeOverflow => {
2879                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
                src))
    })format!(
2880                                "values of the type `{src}` are too big for the target architecture"
2881                            )
2882                        }
2883                        rustc_transmute::Reason::DstSizeOverflow => {
2884                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
                dst))
    })format!(
2885                                "values of the type `{dst}` are too big for the target architecture"
2886                            )
2887                        }
2888                        rustc_transmute::Reason::DstHasStricterAlignment {
2889                            src_min_align,
2890                            dst_min_align,
2891                        } => {
2892                            ::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!(
2893                                "the minimum alignment of `{src}` ({src_min_align}) should be \
2894                                 greater than that of `{dst}` ({dst_min_align})"
2895                            )
2896                        }
2897                        rustc_transmute::Reason::DstIsMoreUnique => {
2898                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is a shared reference, but `{1}` is a unique reference",
                src, dst))
    })format!(
2899                                "`{src}` is a shared reference, but `{dst}` is a unique reference"
2900                            )
2901                        }
2902                        // Already reported by rustc
2903                        rustc_transmute::Reason::TypeError => {
2904                            return GetSafeTransmuteErrorAndReason::Silent;
2905                        }
2906                        rustc_transmute::Reason::SrcLayoutUnknown => {
2907                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` has an unknown layout", src))
    })format!("`{src}` has an unknown layout")
2908                        }
2909                        rustc_transmute::Reason::DstLayoutUnknown => {
2910                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` has an unknown layout", dst))
    })format!("`{dst}` has an unknown layout")
2911                        }
2912                    };
2913                    GetSafeTransmuteErrorAndReason::Error {
2914                        err_msg,
2915                        safe_transmute_explanation: Some(safe_transmute_explanation),
2916                    }
2917                }
2918                // Should never get a Yes at this point! We already ran it before, and did not get a Yes.
2919                Answer::Yes => ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("Inconsistent rustc_transmute::is_transmutable(...) result, got Yes"))span_bug!(
2920                    span,
2921                    "Inconsistent rustc_transmute::is_transmutable(...) result, got Yes",
2922                ),
2923                // Reached when a different obligation (namely `Freeze`) causes the
2924                // transmutability analysis to fail. In this case, silence the
2925                // transmutability error message in favor of that more specific
2926                // error.
2927                Answer::If(_) => GetSafeTransmuteErrorAndReason::Error {
2928                    err_msg,
2929                    safe_transmute_explanation: None,
2930                },
2931            }
2932        })
2933    }
2934
2935    fn add_tuple_trait_message(
2936        &self,
2937        obligation_cause_code: &ObligationCauseCode<'tcx>,
2938        err: &mut Diag<'_>,
2939    ) {
2940        match obligation_cause_code {
2941            ObligationCauseCode::RustCall => {
2942                err.primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
2943            }
2944            ObligationCauseCode::WhereClause(def_id, _) if self.tcx.is_fn_trait(*def_id) => {
2945                err.code(E0059);
2946                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!(
2947                    "type parameter to bare `{}` trait must be a tuple",
2948                    self.tcx.def_path_str(*def_id)
2949                ));
2950            }
2951            _ => {}
2952        }
2953    }
2954
2955    fn try_to_add_help_message(
2956        &self,
2957        root_obligation: &PredicateObligation<'tcx>,
2958        obligation: &PredicateObligation<'tcx>,
2959        trait_predicate: ty::PolyTraitPredicate<'tcx>,
2960        err: &mut Diag<'_>,
2961        span: Span,
2962        is_fn_trait: bool,
2963        suggested: bool,
2964    ) {
2965        let body_def_id = obligation.cause.body_id;
2966        let span = if let ObligationCauseCode::BinOp { rhs_span, .. } = obligation.cause.code() {
2967            *rhs_span
2968        } else {
2969            span
2970        };
2971
2972        // Try to report a help message
2973        let trait_def_id = trait_predicate.def_id();
2974        if is_fn_trait
2975            && let Ok((implemented_kind, params)) = self.type_implements_fn_trait(
2976                obligation.param_env,
2977                trait_predicate.self_ty(),
2978                trait_predicate.skip_binder().polarity,
2979            )
2980        {
2981            self.add_help_message_for_fn_trait(trait_predicate, err, implemented_kind, params);
2982        } else if !trait_predicate.has_non_region_infer()
2983            && self.predicate_can_apply(obligation.param_env, trait_predicate)
2984        {
2985            // If a where-clause may be useful, remind the
2986            // user that they can add it.
2987            //
2988            // don't display an on-unimplemented note, as
2989            // these notes will often be of the form
2990            //     "the type `T` can't be frobnicated"
2991            // which is somewhat confusing.
2992            self.suggest_restricting_param_bound(
2993                err,
2994                trait_predicate,
2995                None,
2996                obligation.cause.body_id,
2997            );
2998        } else if trait_def_id.is_local()
2999            && self.tcx.trait_impls_of(trait_def_id).is_empty()
3000            && !self.tcx.trait_is_auto(trait_def_id)
3001            && !self.tcx.trait_is_alias(trait_def_id)
3002            && trait_predicate.polarity() == ty::PredicatePolarity::Positive
3003        {
3004            err.span_help(
3005                self.tcx.def_span(trait_def_id),
3006                crate::fluent_generated::trait_selection_trait_has_no_impls,
3007            );
3008        } else if !suggested && trait_predicate.polarity() == ty::PredicatePolarity::Positive {
3009            // Can't show anything else useful, try to find similar impls.
3010            let impl_candidates = self.find_similar_impl_candidates(trait_predicate);
3011            if !self.report_similar_impl_candidates(
3012                &impl_candidates,
3013                trait_predicate,
3014                body_def_id,
3015                err,
3016                true,
3017                obligation.param_env,
3018            ) {
3019                self.report_similar_impl_candidates_for_root_obligation(
3020                    obligation,
3021                    trait_predicate,
3022                    body_def_id,
3023                    err,
3024                );
3025            }
3026
3027            self.suggest_convert_to_slice(
3028                err,
3029                obligation,
3030                trait_predicate,
3031                impl_candidates.as_slice(),
3032                span,
3033            );
3034
3035            self.suggest_tuple_wrapping(err, root_obligation, obligation);
3036        }
3037    }
3038
3039    fn add_help_message_for_fn_trait(
3040        &self,
3041        trait_pred: ty::PolyTraitPredicate<'tcx>,
3042        err: &mut Diag<'_>,
3043        implemented_kind: ty::ClosureKind,
3044        params: ty::Binder<'tcx, Ty<'tcx>>,
3045    ) {
3046        // If the type implements `Fn`, `FnMut`, or `FnOnce`, suppress the following
3047        // suggestion to add trait bounds for the type, since we only typically implement
3048        // these traits once.
3049
3050        // Note if the `FnMut` or `FnOnce` is less general than the trait we're trying
3051        // to implement.
3052        let selected_kind = self
3053            .tcx
3054            .fn_trait_kind_from_def_id(trait_pred.def_id())
3055            .expect("expected to map DefId to ClosureKind");
3056        if !implemented_kind.extends(selected_kind) {
3057            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!(
3058                "`{}` implements `{}`, but it must implement `{}`, which is more general",
3059                trait_pred.skip_binder().self_ty(),
3060                implemented_kind,
3061                selected_kind
3062            ));
3063        }
3064
3065        // Note any argument mismatches
3066        let ty::Tuple(given) = *params.skip_binder().kind() else {
3067            return;
3068        };
3069
3070        let expected_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
3071        let ty::Tuple(expected) = *expected_ty.kind() else {
3072            return;
3073        };
3074
3075        if expected.len() != given.len() {
3076            // Note number of types that were expected and given
3077            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!(
3078                "expected a closure taking {} argument{}, but one taking {} argument{} was given",
3079                given.len(),
3080                pluralize!(given.len()),
3081                expected.len(),
3082                pluralize!(expected.len()),
3083            ));
3084            return;
3085        }
3086
3087        let given_ty = Ty::new_fn_ptr(
3088            self.tcx,
3089            params.rebind(self.tcx.mk_fn_sig(
3090                given,
3091                self.tcx.types.unit,
3092                false,
3093                hir::Safety::Safe,
3094                ExternAbi::Rust,
3095            )),
3096        );
3097        let expected_ty = Ty::new_fn_ptr(
3098            self.tcx,
3099            trait_pred.rebind(self.tcx.mk_fn_sig(
3100                expected,
3101                self.tcx.types.unit,
3102                false,
3103                hir::Safety::Safe,
3104                ExternAbi::Rust,
3105            )),
3106        );
3107
3108        if !self.same_type_modulo_infer(given_ty, expected_ty) {
3109            // Print type mismatch
3110            let (expected_args, given_args) = self.cmp(expected_ty, given_ty);
3111            err.note_expected_found(
3112                "a closure with signature",
3113                expected_args,
3114                "a closure with signature",
3115                given_args,
3116            );
3117        }
3118    }
3119
3120    fn report_closure_error(
3121        &self,
3122        obligation: &PredicateObligation<'tcx>,
3123        closure_def_id: DefId,
3124        found_kind: ty::ClosureKind,
3125        kind: ty::ClosureKind,
3126        trait_prefix: &'static str,
3127    ) -> Diag<'a> {
3128        let closure_span = self.tcx.def_span(closure_def_id);
3129
3130        let mut err = ClosureKindMismatch {
3131            closure_span,
3132            expected: kind,
3133            found: found_kind,
3134            cause_span: obligation.cause.span,
3135            trait_prefix,
3136            fn_once_label: None,
3137            fn_mut_label: None,
3138        };
3139
3140        // Additional context information explaining why the closure only implements
3141        // a particular trait.
3142        if let Some(typeck_results) = &self.typeck_results {
3143            let hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id.expect_local());
3144            match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
3145                (ty::ClosureKind::FnOnce, Some((span, place))) => {
3146                    err.fn_once_label = Some(ClosureFnOnceLabel {
3147                        span: *span,
3148                        place: ty::place_to_string_for_capture(self.tcx, place),
3149                    })
3150                }
3151                (ty::ClosureKind::FnMut, Some((span, place))) => {
3152                    err.fn_mut_label = Some(ClosureFnMutLabel {
3153                        span: *span,
3154                        place: ty::place_to_string_for_capture(self.tcx, place),
3155                    })
3156                }
3157                _ => {}
3158            }
3159        }
3160
3161        self.dcx().create_err(err)
3162    }
3163
3164    fn report_cyclic_signature_error(
3165        &self,
3166        obligation: &PredicateObligation<'tcx>,
3167        found_trait_ref: ty::TraitRef<'tcx>,
3168        expected_trait_ref: ty::TraitRef<'tcx>,
3169        terr: TypeError<'tcx>,
3170    ) -> Diag<'a> {
3171        let self_ty = found_trait_ref.self_ty();
3172        let (cause, terr) = if let ty::Closure(def_id, _) = self_ty.kind() {
3173            (
3174                ObligationCause::dummy_with_span(self.tcx.def_span(def_id)),
3175                TypeError::CyclicTy(self_ty),
3176            )
3177        } else {
3178            (obligation.cause.clone(), terr)
3179        };
3180        self.report_and_explain_type_error(
3181            TypeTrace::trait_refs(&cause, expected_trait_ref, found_trait_ref),
3182            obligation.param_env,
3183            terr,
3184        )
3185    }
3186
3187    fn report_opaque_type_auto_trait_leakage(
3188        &self,
3189        obligation: &PredicateObligation<'tcx>,
3190        def_id: DefId,
3191    ) -> ErrorGuaranteed {
3192        let name = match self.tcx.local_opaque_ty_origin(def_id.expect_local()) {
3193            hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } => {
3194                "opaque type".to_string()
3195            }
3196            hir::OpaqueTyOrigin::TyAlias { .. } => {
3197                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`",
                self.tcx.def_path_debug_str(def_id)))
    })format!("`{}`", self.tcx.def_path_debug_str(def_id))
3198            }
3199        };
3200        let mut err = self.dcx().struct_span_err(
3201            obligation.cause.span,
3202            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot check whether the hidden type of {0} satisfies auto traits",
                name))
    })format!("cannot check whether the hidden type of {name} satisfies auto traits"),
3203        );
3204
3205        err.note(
3206            "fetching the hidden types of an opaque inside of the defining scope is not supported. \
3207            You can try moving the opaque type and the item that actually registers a hidden type into a new submodule",
3208        );
3209        err.span_note(self.tcx.def_span(def_id), "opaque type is declared here");
3210
3211        self.note_obligation_cause(&mut err, &obligation);
3212        self.dcx().try_steal_replace_and_emit_err(self.tcx.def_span(def_id), StashKey::Cycle, err)
3213    }
3214
3215    fn report_signature_mismatch_error(
3216        &self,
3217        obligation: &PredicateObligation<'tcx>,
3218        span: Span,
3219        found_trait_ref: ty::TraitRef<'tcx>,
3220        expected_trait_ref: ty::TraitRef<'tcx>,
3221    ) -> Result<Diag<'a>, ErrorGuaranteed> {
3222        let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
3223        let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
3224
3225        expected_trait_ref.self_ty().error_reported()?;
3226        let found_trait_ty = found_trait_ref.self_ty();
3227
3228        let found_did = match *found_trait_ty.kind() {
3229            ty::Closure(did, _) | ty::FnDef(did, _) | ty::Coroutine(did, ..) => Some(did),
3230            _ => None,
3231        };
3232
3233        let found_node = found_did.and_then(|did| self.tcx.hir_get_if_local(did));
3234        let found_span = found_did.and_then(|did| self.tcx.hir_span_if_local(did));
3235
3236        if !self.reported_signature_mismatch.borrow_mut().insert((span, found_span)) {
3237            // We check closures twice, with obligations flowing in different directions,
3238            // but we want to complain about them only once.
3239            return Err(self.dcx().span_delayed_bug(span, "already_reported"));
3240        }
3241
3242        let mut not_tupled = false;
3243
3244        let found = match found_trait_ref.args.type_at(1).kind() {
3245            ty::Tuple(tys) => ::alloc::vec::from_elem(ArgKind::empty(), tys.len())vec![ArgKind::empty(); tys.len()],
3246            _ => {
3247                not_tupled = true;
3248                <[_]>::into_vec(::alloc::boxed::box_new([ArgKind::empty()]))vec![ArgKind::empty()]
3249            }
3250        };
3251
3252        let expected_ty = expected_trait_ref.args.type_at(1);
3253        let expected = match expected_ty.kind() {
3254            ty::Tuple(tys) => {
3255                tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
3256            }
3257            _ => {
3258                not_tupled = true;
3259                <[_]>::into_vec(::alloc::boxed::box_new([ArgKind::Arg("_".to_owned(),
                    expected_ty.to_string())]))vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())]
3260            }
3261        };
3262
3263        // If this is a `Fn` family trait and either the expected or found
3264        // is not tupled, then fall back to just a regular mismatch error.
3265        // This shouldn't be common unless manually implementing one of the
3266        // traits manually, but don't make it more confusing when it does
3267        // happen.
3268        if !self.tcx.is_lang_item(expected_trait_ref.def_id, LangItem::Coroutine) && not_tupled {
3269            return Ok(self.report_and_explain_type_error(
3270                TypeTrace::trait_refs(&obligation.cause, expected_trait_ref, found_trait_ref),
3271                obligation.param_env,
3272                ty::error::TypeError::Mismatch,
3273            ));
3274        }
3275        if found.len() != expected.len() {
3276            let (closure_span, closure_arg_span, found) = found_did
3277                .and_then(|did| {
3278                    let node = self.tcx.hir_get_if_local(did)?;
3279                    let (found_span, closure_arg_span, found) = self.get_fn_like_arguments(node)?;
3280                    Some((Some(found_span), closure_arg_span, found))
3281                })
3282                .unwrap_or((found_span, None, found));
3283
3284            // If the coroutine take a single () as its argument,
3285            // the trait argument would found the coroutine take 0 arguments,
3286            // but get_fn_like_arguments would give 1 argument.
3287            // This would result in "Expected to take 1 argument, but it takes 1 argument".
3288            // Check again to avoid this.
3289            if found.len() != expected.len() {
3290                return Ok(self.report_arg_count_mismatch(
3291                    span,
3292                    closure_span,
3293                    expected,
3294                    found,
3295                    found_trait_ty.is_closure(),
3296                    closure_arg_span,
3297                ));
3298            }
3299        }
3300        Ok(self.report_closure_arg_mismatch(
3301            span,
3302            found_span,
3303            found_trait_ref,
3304            expected_trait_ref,
3305            obligation.cause.code(),
3306            found_node,
3307            obligation.param_env,
3308        ))
3309    }
3310
3311    /// Given some node representing a fn-like thing in the HIR map,
3312    /// returns a span and `ArgKind` information that describes the
3313    /// arguments it expects. This can be supplied to
3314    /// `report_arg_count_mismatch`.
3315    pub fn get_fn_like_arguments(
3316        &self,
3317        node: Node<'_>,
3318    ) -> Option<(Span, Option<Span>, Vec<ArgKind>)> {
3319        let sm = self.tcx.sess.source_map();
3320        Some(match node {
3321            Node::Expr(&hir::Expr {
3322                kind: hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, fn_arg_span, .. }),
3323                ..
3324            }) => (
3325                fn_decl_span,
3326                fn_arg_span,
3327                self.tcx
3328                    .hir_body(body)
3329                    .params
3330                    .iter()
3331                    .map(|arg| {
3332                        if let hir::Pat { kind: hir::PatKind::Tuple(args, _), span, .. } = *arg.pat
3333                        {
3334                            Some(ArgKind::Tuple(
3335                                Some(span),
3336                                args.iter()
3337                                    .map(|pat| {
3338                                        sm.span_to_snippet(pat.span)
3339                                            .ok()
3340                                            .map(|snippet| (snippet, "_".to_owned()))
3341                                    })
3342                                    .collect::<Option<Vec<_>>>()?,
3343                            ))
3344                        } else {
3345                            let name = sm.span_to_snippet(arg.pat.span).ok()?;
3346                            Some(ArgKind::Arg(name, "_".to_owned()))
3347                        }
3348                    })
3349                    .collect::<Option<Vec<ArgKind>>>()?,
3350            ),
3351            Node::Item(&hir::Item { kind: hir::ItemKind::Fn { ref sig, .. }, .. })
3352            | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(ref sig, _), .. })
3353            | Node::TraitItem(&hir::TraitItem {
3354                kind: hir::TraitItemKind::Fn(ref sig, _), ..
3355            })
3356            | Node::ForeignItem(&hir::ForeignItem {
3357                kind: hir::ForeignItemKind::Fn(ref sig, _, _),
3358                ..
3359            }) => (
3360                sig.span,
3361                None,
3362                sig.decl
3363                    .inputs
3364                    .iter()
3365                    .map(|arg| match arg.kind {
3366                        hir::TyKind::Tup(tys) => ArgKind::Tuple(
3367                            Some(arg.span),
3368                            ::alloc::vec::from_elem(("_".to_owned(), "_".to_owned()), tys.len())vec![("_".to_owned(), "_".to_owned()); tys.len()],
3369                        ),
3370                        _ => ArgKind::empty(),
3371                    })
3372                    .collect::<Vec<ArgKind>>(),
3373            ),
3374            Node::Ctor(variant_data) => {
3375                let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| self.tcx.hir_span(id));
3376                (span, None, ::alloc::vec::from_elem(ArgKind::empty(), variant_data.fields().len())vec![ArgKind::empty(); variant_data.fields().len()])
3377            }
3378            _ => {
    ::core::panicking::panic_fmt(format_args!("non-FnLike node found: {0:?}",
            node));
}panic!("non-FnLike node found: {node:?}"),
3379        })
3380    }
3381
3382    /// Reports an error when the number of arguments needed by a
3383    /// trait match doesn't match the number that the expression
3384    /// provides.
3385    pub fn report_arg_count_mismatch(
3386        &self,
3387        span: Span,
3388        found_span: Option<Span>,
3389        expected_args: Vec<ArgKind>,
3390        found_args: Vec<ArgKind>,
3391        is_closure: bool,
3392        closure_arg_span: Option<Span>,
3393    ) -> Diag<'a> {
3394        let kind = if is_closure { "closure" } else { "function" };
3395
3396        let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
3397            let arg_length = arguments.len();
3398            let distinct = #[allow(non_exhaustive_omitted_patterns)] match other {
    &[ArgKind::Tuple(..)] => true,
    _ => false,
}matches!(other, &[ArgKind::Tuple(..)]);
3399            match (arg_length, arguments.get(0)) {
3400                (1, Some(ArgKind::Tuple(_, fields))) => {
3401                    ::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())
3402                }
3403                _ => ::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!(
3404                    "{} {}argument{}",
3405                    arg_length,
3406                    if distinct && arg_length > 1 { "distinct " } else { "" },
3407                    pluralize!(arg_length)
3408                ),
3409            }
3410        };
3411
3412        let expected_str = args_str(&expected_args, &found_args);
3413        let found_str = args_str(&found_args, &expected_args);
3414
3415        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!(
3416            self.dcx(),
3417            span,
3418            E0593,
3419            "{} is expected to take {}, but it takes {}",
3420            kind,
3421            expected_str,
3422            found_str,
3423        );
3424
3425        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}"));
3426
3427        if let Some(found_span) = found_span {
3428            err.span_label(found_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("takes {0}", found_str))
    })format!("takes {found_str}"));
3429
3430            // Suggest to take and ignore the arguments with expected_args_length `_`s if
3431            // found arguments is empty (assume the user just wants to ignore args in this case).
3432            // For example, if `expected_args_length` is 2, suggest `|_, _|`.
3433            if found_args.is_empty() && is_closure {
3434                let underscores = ::alloc::vec::from_elem("_", expected_args.len())vec!["_"; expected_args.len()].join(", ");
3435                err.span_suggestion_verbose(
3436                    closure_arg_span.unwrap_or(found_span),
3437                    ::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!(
3438                        "consider changing the closure to take and ignore the expected argument{}",
3439                        pluralize!(expected_args.len())
3440                    ),
3441                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("|{0}|", underscores))
    })format!("|{underscores}|"),
3442                    Applicability::MachineApplicable,
3443                );
3444            }
3445
3446            if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
3447                if fields.len() == expected_args.len() {
3448                    let sugg = fields
3449                        .iter()
3450                        .map(|(name, _)| name.to_owned())
3451                        .collect::<Vec<String>>()
3452                        .join(", ");
3453                    err.span_suggestion_verbose(
3454                        found_span,
3455                        "change the closure to take multiple arguments instead of a single tuple",
3456                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("|{0}|", sugg))
    })format!("|{sugg}|"),
3457                        Applicability::MachineApplicable,
3458                    );
3459                }
3460            }
3461            if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..]
3462                && fields.len() == found_args.len()
3463                && is_closure
3464            {
3465                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!(
3466                    "|({}){}|",
3467                    found_args
3468                        .iter()
3469                        .map(|arg| match arg {
3470                            ArgKind::Arg(name, _) => name.to_owned(),
3471                            _ => "_".to_owned(),
3472                        })
3473                        .collect::<Vec<String>>()
3474                        .join(", "),
3475                    // add type annotations if available
3476                    if found_args.iter().any(|arg| match arg {
3477                        ArgKind::Arg(_, ty) => ty != "_",
3478                        _ => false,
3479                    }) {
3480                        format!(
3481                            ": ({})",
3482                            fields
3483                                .iter()
3484                                .map(|(_, ty)| ty.to_owned())
3485                                .collect::<Vec<String>>()
3486                                .join(", ")
3487                        )
3488                    } else {
3489                        String::new()
3490                    },
3491                );
3492                err.span_suggestion_verbose(
3493                    found_span,
3494                    "change the closure to accept a tuple instead of individual arguments",
3495                    sugg,
3496                    Applicability::MachineApplicable,
3497                );
3498            }
3499        }
3500
3501        err
3502    }
3503
3504    /// Checks if the type implements one of `Fn`, `FnMut`, or `FnOnce`
3505    /// in that order, and returns the generic type corresponding to the
3506    /// argument of that trait (corresponding to the closure arguments).
3507    pub fn type_implements_fn_trait(
3508        &self,
3509        param_env: ty::ParamEnv<'tcx>,
3510        ty: ty::Binder<'tcx, Ty<'tcx>>,
3511        polarity: ty::PredicatePolarity,
3512    ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> {
3513        self.commit_if_ok(|_| {
3514            for trait_def_id in [
3515                self.tcx.lang_items().fn_trait(),
3516                self.tcx.lang_items().fn_mut_trait(),
3517                self.tcx.lang_items().fn_once_trait(),
3518            ] {
3519                let Some(trait_def_id) = trait_def_id else { continue };
3520                // Make a fresh inference variable so we can determine what the generic parameters
3521                // of the trait are.
3522                let var = self.next_ty_var(DUMMY_SP);
3523                // FIXME(const_trait_impl)
3524                let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, [ty.skip_binder(), var]);
3525                let obligation = Obligation::new(
3526                    self.tcx,
3527                    ObligationCause::dummy(),
3528                    param_env,
3529                    ty.rebind(ty::TraitPredicate { trait_ref, polarity }),
3530                );
3531                let ocx = ObligationCtxt::new(self);
3532                ocx.register_obligation(obligation);
3533                if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
3534                    return Ok((
3535                        self.tcx
3536                            .fn_trait_kind_from_def_id(trait_def_id)
3537                            .expect("expected to map DefId to ClosureKind"),
3538                        ty.rebind(self.resolve_vars_if_possible(var)),
3539                    ));
3540                }
3541            }
3542
3543            Err(())
3544        })
3545    }
3546
3547    fn report_not_const_evaluatable_error(
3548        &self,
3549        obligation: &PredicateObligation<'tcx>,
3550        span: Span,
3551    ) -> Result<Diag<'a>, ErrorGuaranteed> {
3552        if !self.tcx.features().generic_const_exprs()
3553            && !self.tcx.features().min_generic_const_args()
3554        {
3555            let guar = self
3556                .dcx()
3557                .struct_span_err(span, "constant expression depends on a generic parameter")
3558                // FIXME(const_generics): we should suggest to the user how they can resolve this
3559                // issue. However, this is currently not actually possible
3560                // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
3561                //
3562                // Note that with `feature(generic_const_exprs)` this case should not
3563                // be reachable.
3564                .with_note("this may fail depending on what value the parameter takes")
3565                .emit();
3566            return Err(guar);
3567        }
3568
3569        match obligation.predicate.kind().skip_binder() {
3570            ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => match ct.kind() {
3571                ty::ConstKind::Unevaluated(uv) => {
3572                    let mut err =
3573                        self.dcx().struct_span_err(span, "unconstrained generic constant");
3574                    let const_span = self.tcx.def_span(uv.def);
3575
3576                    let const_ty = self.tcx.type_of(uv.def).instantiate(self.tcx, uv.args);
3577                    let cast = if const_ty != self.tcx.types.usize { " as usize" } else { "" };
3578                    let msg = "try adding a `where` bound";
3579                    match self.tcx.sess.source_map().span_to_snippet(const_span) {
3580                        Ok(snippet) => {
3581                            let code = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("[(); {0}{1}]:", snippet, cast))
    })format!("[(); {snippet}{cast}]:");
3582                            let def_id = if let ObligationCauseCode::CompareImplItem {
3583                                trait_item_def_id,
3584                                ..
3585                            } = obligation.cause.code()
3586                            {
3587                                trait_item_def_id.as_local()
3588                            } else {
3589                                Some(obligation.cause.body_id)
3590                            };
3591                            if let Some(def_id) = def_id
3592                                && let Some(generics) = self.tcx.hir_get_generics(def_id)
3593                            {
3594                                err.span_suggestion_verbose(
3595                                    generics.tail_span_for_predicate_suggestion(),
3596                                    msg,
3597                                    ::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()),
3598                                    Applicability::MaybeIncorrect,
3599                                );
3600                            } else {
3601                                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: where {1}", msg, code))
    })format!("{msg}: where {code}"));
3602                            };
3603                        }
3604                        _ => {
3605                            err.help(msg);
3606                        }
3607                    };
3608                    Ok(err)
3609                }
3610                ty::ConstKind::Expr(_) => {
3611                    let err = self
3612                        .dcx()
3613                        .struct_span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unconstrained generic constant `{0}`",
                ct))
    })format!("unconstrained generic constant `{ct}`"));
3614                    Ok(err)
3615                }
3616                _ => {
3617                    ::rustc_middle::util::bug::bug_fmt(format_args!("const evaluatable failed for non-unevaluated const `{0:?}`",
        ct));bug!("const evaluatable failed for non-unevaluated const `{ct:?}`");
3618                }
3619            },
3620            _ => {
3621                ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("unexpected non-ConstEvaluatable predicate, this should not be reachable"))span_bug!(
3622                    span,
3623                    "unexpected non-ConstEvaluatable predicate, this should not be reachable"
3624                )
3625            }
3626        }
3627    }
3628}