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