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