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