rustc_trait_selection/error_reporting/traits/
fulfillment_errors.rs

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