rustc_trait_selection/error_reporting/traits/
fulfillment_errors.rs

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