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