rustc_trait_selection/error_reporting/traits/
fulfillment_errors.rs

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