rustc_trait_selection/error_reporting/traits/
fulfillment_errors.rs

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