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