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