1use core::ops::ControlFlow;
2use std::borrow::Cow;
3use std::iter;
4
5use hir::def_id::{DefId, DefIdMap, LocalDefId};
6use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
7use rustc_errors::codes::*;
8use rustc_errors::{Applicability, ErrorGuaranteed, pluralize, struct_span_code_err};
9use rustc_hir::def::{DefKind, Res};
10use rustc_hir::intravisit::VisitorExt;
11use rustc_hir::{self as hir, AmbigArg, GenericParamKind, ImplItemKind, intravisit};
12use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
13use rustc_infer::traits::util;
14use rustc_middle::ty::error::{ExpectedFound, TypeError};
15use rustc_middle::ty::util::ExplicitSelf;
16use rustc_middle::ty::{
17 self, BottomUpFolder, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFoldable, TypeFolder,
18 TypeSuperFoldable, TypeVisitableExt, TypingMode, Upcast,
19};
20use rustc_middle::{bug, span_bug};
21use rustc_span::Span;
22use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
23use rustc_trait_selection::infer::InferCtxtExt;
24use rustc_trait_selection::regions::InferCtxtRegionExt;
25use rustc_trait_selection::traits::{
26 self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
27};
28use tracing::{debug, instrument};
29
30use super::potentially_plural_count;
31use crate::errors::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture};
32
33pub(super) mod refine;
34
35pub(super) fn compare_impl_item(
37 tcx: TyCtxt<'_>,
38 impl_item_def_id: LocalDefId,
39) -> Result<(), ErrorGuaranteed> {
40 let impl_item = tcx.associated_item(impl_item_def_id);
41 let trait_item = tcx.associated_item(impl_item.trait_item_def_id.unwrap());
42 let impl_trait_ref =
43 tcx.impl_trait_ref(impl_item.container_id(tcx)).unwrap().instantiate_identity();
44 debug!(?impl_trait_ref);
45
46 match impl_item.kind {
47 ty::AssocKind::Fn => compare_impl_method(tcx, impl_item, trait_item, impl_trait_ref),
48 ty::AssocKind::Type => compare_impl_ty(tcx, impl_item, trait_item, impl_trait_ref),
49 ty::AssocKind::Const => compare_impl_const(tcx, impl_item, trait_item, impl_trait_ref),
50 }
51}
52
53#[instrument(level = "debug", skip(tcx))]
62fn compare_impl_method<'tcx>(
63 tcx: TyCtxt<'tcx>,
64 impl_m: ty::AssocItem,
65 trait_m: ty::AssocItem,
66 impl_trait_ref: ty::TraitRef<'tcx>,
67) -> Result<(), ErrorGuaranteed> {
68 check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, false)?;
69 compare_method_predicate_entailment(tcx, impl_m, trait_m, impl_trait_ref)?;
70 Ok(())
71}
72
73fn check_method_is_structurally_compatible<'tcx>(
77 tcx: TyCtxt<'tcx>,
78 impl_m: ty::AssocItem,
79 trait_m: ty::AssocItem,
80 impl_trait_ref: ty::TraitRef<'tcx>,
81 delay: bool,
82) -> Result<(), ErrorGuaranteed> {
83 compare_self_type(tcx, impl_m, trait_m, impl_trait_ref, delay)?;
84 compare_number_of_generics(tcx, impl_m, trait_m, delay)?;
85 compare_generic_param_kinds(tcx, impl_m, trait_m, delay)?;
86 compare_number_of_method_arguments(tcx, impl_m, trait_m, delay)?;
87 compare_synthetic_generics(tcx, impl_m, trait_m, delay)?;
88 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, delay)?;
89 Ok(())
90}
91
92#[instrument(level = "debug", skip(tcx, impl_trait_ref))]
171fn compare_method_predicate_entailment<'tcx>(
172 tcx: TyCtxt<'tcx>,
173 impl_m: ty::AssocItem,
174 trait_m: ty::AssocItem,
175 impl_trait_ref: ty::TraitRef<'tcx>,
176) -> Result<(), ErrorGuaranteed> {
177 let impl_m_def_id = impl_m.def_id.expect_local();
183 let impl_m_span = tcx.def_span(impl_m_def_id);
184 let cause = ObligationCause::new(
185 impl_m_span,
186 impl_m_def_id,
187 ObligationCauseCode::CompareImplItem {
188 impl_item_def_id: impl_m_def_id,
189 trait_item_def_id: trait_m.def_id,
190 kind: impl_m.kind,
191 },
192 );
193
194 let impl_def_id = impl_m.container_id(tcx);
196 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
197 tcx,
198 impl_m.container_id(tcx),
199 impl_trait_ref.args,
200 );
201 debug!(?trait_to_impl_args);
202
203 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
204 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
205
206 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
214 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
215 hybrid_preds.extend(
216 trait_m_predicates.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate),
217 );
218
219 let is_conditionally_const = tcx.is_conditionally_const(impl_def_id);
220 if is_conditionally_const {
221 hybrid_preds.extend(
224 tcx.const_conditions(impl_def_id)
225 .instantiate_identity(tcx)
226 .into_iter()
227 .chain(
228 tcx.const_conditions(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args),
229 )
230 .map(|(trait_ref, _)| {
231 trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
232 }),
233 );
234 }
235
236 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
237 let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
238 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
239 debug!(caller_bounds=?param_env.caller_bounds());
240
241 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
242 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
243
244 let impl_m_own_bounds = impl_m_predicates.instantiate_own_identity();
249 for (predicate, span) in impl_m_own_bounds {
250 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
251 let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
252
253 let cause = ObligationCause::new(
254 span,
255 impl_m_def_id,
256 ObligationCauseCode::CompareImplItem {
257 impl_item_def_id: impl_m_def_id,
258 trait_item_def_id: trait_m.def_id,
259 kind: impl_m.kind,
260 },
261 );
262 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
263 }
264
265 if is_conditionally_const {
272 for (const_condition, span) in
273 tcx.const_conditions(impl_m.def_id).instantiate_own_identity()
274 {
275 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
276 let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
277
278 let cause = ObligationCause::new(
279 span,
280 impl_m_def_id,
281 ObligationCauseCode::CompareImplItem {
282 impl_item_def_id: impl_m_def_id,
283 trait_item_def_id: trait_m.def_id,
284 kind: impl_m.kind,
285 },
286 );
287 ocx.register_obligation(traits::Obligation::new(
288 tcx,
289 cause,
290 param_env,
291 const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
292 ));
293 }
294 }
295
296 let mut wf_tys = FxIndexSet::default();
310
311 let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars(
312 impl_m_span,
313 infer::HigherRankedType,
314 tcx.fn_sig(impl_m.def_id).instantiate_identity(),
315 );
316
317 let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id);
318 let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig);
319 debug!(?impl_sig);
320
321 let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args);
322 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
323
324 wf_tys.extend(trait_sig.inputs_and_output.iter());
328 let trait_sig = ocx.normalize(&norm_cause, param_env, trait_sig);
329 wf_tys.extend(trait_sig.inputs_and_output.iter());
332 debug!(?trait_sig);
333
334 let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
341
342 if let Err(terr) = result {
343 debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
344
345 let emitted = report_trait_method_mismatch(
346 infcx,
347 cause,
348 param_env,
349 terr,
350 (trait_m, trait_sig),
351 (impl_m, impl_sig),
352 impl_trait_ref,
353 );
354 return Err(emitted);
355 }
356
357 if !(impl_sig, trait_sig).references_error() {
358 let errors = ocx.select_where_possible();
362 if !errors.is_empty() {
363 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
364 return Err(reported);
365 }
366
367 let mut wf_args: smallvec::SmallVec<[_; 4]> =
377 unnormalized_impl_sig.inputs_and_output.iter().map(|ty| ty.into()).collect();
378 let mut wf_args_seen: FxHashSet<_> = wf_args.iter().copied().collect();
381 while let Some(arg) = wf_args.pop() {
382 let Some(obligations) = rustc_trait_selection::traits::wf::obligations(
383 infcx,
384 param_env,
385 impl_m_def_id,
386 0,
387 arg,
388 impl_m_span,
389 ) else {
390 continue;
391 };
392 for obligation in obligations {
393 debug!(?obligation);
394 match obligation.predicate.kind().skip_binder() {
395 ty::PredicateKind::Clause(
400 ty::ClauseKind::RegionOutlives(..)
401 | ty::ClauseKind::TypeOutlives(..)
402 | ty::ClauseKind::Projection(..),
403 ) => ocx.register_obligation(obligation),
404 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
405 if wf_args_seen.insert(arg) {
406 wf_args.push(arg)
407 }
408 }
409 _ => {}
410 }
411 }
412 }
413 }
414
415 let errors = ocx.select_all_or_error();
418 if !errors.is_empty() {
419 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
420 return Err(reported);
421 }
422
423 let errors = infcx.resolve_regions(impl_m_def_id, param_env, wf_tys);
426 if !errors.is_empty() {
427 return Err(infcx
428 .tainted_by_errors()
429 .unwrap_or_else(|| infcx.err_ctxt().report_region_errors(impl_m_def_id, &errors)));
430 }
431
432 Ok(())
433}
434
435struct RemapLateParam<'tcx> {
436 tcx: TyCtxt<'tcx>,
437 mapping: FxIndexMap<ty::LateParamRegionKind, ty::LateParamRegionKind>,
438}
439
440impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateParam<'tcx> {
441 fn cx(&self) -> TyCtxt<'tcx> {
442 self.tcx
443 }
444
445 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
446 if let ty::ReLateParam(fr) = *r {
447 ty::Region::new_late_param(
448 self.tcx,
449 fr.scope,
450 self.mapping.get(&fr.kind).copied().unwrap_or(fr.kind),
451 )
452 } else {
453 r
454 }
455 }
456}
457
458#[instrument(skip(tcx), level = "debug", ret)]
490pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
491 tcx: TyCtxt<'tcx>,
492 impl_m_def_id: LocalDefId,
493) -> Result<&'tcx DefIdMap<ty::EarlyBinder<'tcx, Ty<'tcx>>>, ErrorGuaranteed> {
494 let impl_m = tcx.opt_associated_item(impl_m_def_id.to_def_id()).unwrap();
495 let trait_m = tcx.opt_associated_item(impl_m.trait_item_def_id.unwrap()).unwrap();
496 let impl_trait_ref =
497 tcx.impl_trait_ref(impl_m.impl_container(tcx).unwrap()).unwrap().instantiate_identity();
498 check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?;
501
502 let impl_m_hir_id = tcx.local_def_id_to_hir_id(impl_m_def_id);
503 let return_span = tcx.hir_fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
504 let cause = ObligationCause::new(
505 return_span,
506 impl_m_def_id,
507 ObligationCauseCode::CompareImplItem {
508 impl_item_def_id: impl_m_def_id,
509 trait_item_def_id: trait_m.def_id,
510 kind: impl_m.kind,
511 },
512 );
513
514 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
516 tcx,
517 impl_m.container_id(tcx),
518 impl_trait_ref.args,
519 );
520
521 let hybrid_preds = tcx
522 .predicates_of(impl_m.container_id(tcx))
523 .instantiate_identity(tcx)
524 .into_iter()
525 .chain(tcx.predicates_of(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args))
526 .map(|(clause, _)| clause);
527 let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
528 let param_env = traits::normalize_param_env_or_error(
529 tcx,
530 param_env,
531 ObligationCause::misc(tcx.def_span(impl_m_def_id), impl_m_def_id),
532 );
533
534 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
535 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
536
537 let impl_m_own_bounds = tcx.predicates_of(impl_m_def_id).instantiate_own_identity();
544 for (predicate, span) in impl_m_own_bounds {
545 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
546 let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
547
548 let cause = ObligationCause::new(
549 span,
550 impl_m_def_id,
551 ObligationCauseCode::CompareImplItem {
552 impl_item_def_id: impl_m_def_id,
553 trait_item_def_id: trait_m.def_id,
554 kind: impl_m.kind,
555 },
556 );
557 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
558 }
559
560 let misc_cause = ObligationCause::misc(return_span, impl_m_def_id);
562 let impl_sig = ocx.normalize(
563 &misc_cause,
564 param_env,
565 infcx.instantiate_binder_with_fresh_vars(
566 return_span,
567 infer::HigherRankedType,
568 tcx.fn_sig(impl_m.def_id).instantiate_identity(),
569 ),
570 );
571 impl_sig.error_reported()?;
572 let impl_return_ty = impl_sig.output();
573
574 let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_def_id);
579 let unnormalized_trait_sig = tcx
580 .liberate_late_bound_regions(
581 impl_m.def_id,
582 tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args),
583 )
584 .fold_with(&mut collector);
585
586 let trait_sig = ocx.normalize(&misc_cause, param_env, unnormalized_trait_sig);
587 trait_sig.error_reported()?;
588 let trait_return_ty = trait_sig.output();
589
590 let universe = infcx.create_next_universe();
610 let mut idx = 0;
611 let mapping: FxIndexMap<_, _> = collector
612 .types
613 .iter()
614 .map(|(_, &(ty, _))| {
615 assert!(
616 infcx.resolve_vars_if_possible(ty) == ty && ty.is_ty_var(),
617 "{ty:?} should not have been constrained via normalization",
618 ty = infcx.resolve_vars_if_possible(ty)
619 );
620 idx += 1;
621 (
622 ty,
623 Ty::new_placeholder(
624 tcx,
625 ty::Placeholder {
626 universe,
627 bound: ty::BoundTy {
628 var: ty::BoundVar::from_usize(idx),
629 kind: ty::BoundTyKind::Anon,
630 },
631 },
632 ),
633 )
634 })
635 .collect();
636 let mut type_mapper = BottomUpFolder {
637 tcx,
638 ty_op: |ty| *mapping.get(&ty).unwrap_or(&ty),
639 lt_op: |lt| lt,
640 ct_op: |ct| ct,
641 };
642 let wf_tys = FxIndexSet::from_iter(
643 unnormalized_trait_sig
644 .inputs_and_output
645 .iter()
646 .chain(trait_sig.inputs_and_output.iter())
647 .map(|ty| ty.fold_with(&mut type_mapper)),
648 );
649
650 match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
651 Ok(()) => {}
652 Err(terr) => {
653 let mut diag = struct_span_code_err!(
654 tcx.dcx(),
655 cause.span,
656 E0053,
657 "method `{}` has an incompatible return type for trait",
658 trait_m.name
659 );
660 infcx.err_ctxt().note_type_err(
661 &mut diag,
662 &cause,
663 tcx.hir_get_if_local(impl_m.def_id)
664 .and_then(|node| node.fn_decl())
665 .map(|decl| (decl.output.span(), Cow::from("return type in trait"), false)),
666 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
667 expected: trait_return_ty.into(),
668 found: impl_return_ty.into(),
669 }))),
670 terr,
671 false,
672 None,
673 );
674 return Err(diag.emit());
675 }
676 }
677
678 debug!(?trait_sig, ?impl_sig, "equating function signatures");
679
680 match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
685 Ok(()) => {}
686 Err(terr) => {
687 let emitted = report_trait_method_mismatch(
692 infcx,
693 cause,
694 param_env,
695 terr,
696 (trait_m, trait_sig),
697 (impl_m, impl_sig),
698 impl_trait_ref,
699 );
700 return Err(emitted);
701 }
702 }
703
704 if !unnormalized_trait_sig.output().references_error() && collector.types.is_empty() {
705 tcx.dcx().delayed_bug(
706 "expect >0 RPITITs in call to `collect_return_position_impl_trait_in_trait_tys`",
707 );
708 }
709
710 let collected_types = collector.types;
715 for (_, &(ty, _)) in &collected_types {
716 ocx.register_obligation(traits::Obligation::new(
717 tcx,
718 misc_cause.clone(),
719 param_env,
720 ty::ClauseKind::WellFormed(ty.into()),
721 ));
722 }
723
724 let errors = ocx.select_all_or_error();
727 if !errors.is_empty() {
728 if let Err(guar) = try_report_async_mismatch(tcx, infcx, &errors, trait_m, impl_m, impl_sig)
729 {
730 return Err(guar);
731 }
732
733 let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
734 return Err(guar);
735 }
736
737 ocx.resolve_regions_and_report_errors(impl_m_def_id, param_env, wf_tys)?;
740
741 let mut remapped_types = DefIdMap::default();
742 for (def_id, (ty, args)) in collected_types {
743 match infcx.fully_resolve(ty) {
744 Ok(ty) => {
745 let id_args = GenericArgs::identity_for_item(tcx, def_id);
749 debug!(?id_args, ?args);
750 let map: FxIndexMap<_, _> = std::iter::zip(args, id_args)
751 .skip(tcx.generics_of(trait_m.def_id).count())
752 .filter_map(|(a, b)| Some((a.as_region()?, b.as_region()?)))
753 .collect();
754 debug!(?map);
755
756 let num_trait_args = impl_trait_ref.args.len();
777 let num_impl_args = tcx.generics_of(impl_m.container_id(tcx)).own_params.len();
778 let ty = match ty.try_fold_with(&mut RemapHiddenTyRegions {
779 tcx,
780 map,
781 num_trait_args,
782 num_impl_args,
783 def_id,
784 impl_m_def_id: impl_m.def_id,
785 ty,
786 return_span,
787 }) {
788 Ok(ty) => ty,
789 Err(guar) => Ty::new_error(tcx, guar),
790 };
791 remapped_types.insert(def_id, ty::EarlyBinder::bind(ty));
792 }
793 Err(err) => {
794 tcx.dcx()
799 .span_bug(return_span, format!("could not fully resolve: {ty} => {err:?}"));
800 }
801 }
802 }
803
804 for assoc_item in tcx.associated_types_for_impl_traits_in_associated_fn(trait_m.def_id) {
810 if !remapped_types.contains_key(assoc_item) {
811 remapped_types.insert(
812 *assoc_item,
813 ty::EarlyBinder::bind(Ty::new_error_with_message(
814 tcx,
815 return_span,
816 "missing synthetic item for RPITIT",
817 )),
818 );
819 }
820 }
821
822 Ok(&*tcx.arena.alloc(remapped_types))
823}
824
825struct ImplTraitInTraitCollector<'a, 'tcx, E> {
826 ocx: &'a ObligationCtxt<'a, 'tcx, E>,
827 types: FxIndexMap<DefId, (Ty<'tcx>, ty::GenericArgsRef<'tcx>)>,
828 span: Span,
829 param_env: ty::ParamEnv<'tcx>,
830 body_id: LocalDefId,
831}
832
833impl<'a, 'tcx, E> ImplTraitInTraitCollector<'a, 'tcx, E>
834where
835 E: 'tcx,
836{
837 fn new(
838 ocx: &'a ObligationCtxt<'a, 'tcx, E>,
839 span: Span,
840 param_env: ty::ParamEnv<'tcx>,
841 body_id: LocalDefId,
842 ) -> Self {
843 ImplTraitInTraitCollector { ocx, types: FxIndexMap::default(), span, param_env, body_id }
844 }
845}
846
847impl<'tcx, E> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx, E>
848where
849 E: 'tcx,
850{
851 fn cx(&self) -> TyCtxt<'tcx> {
852 self.ocx.infcx.tcx
853 }
854
855 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
856 if let ty::Alias(ty::Projection, proj) = ty.kind()
857 && self.cx().is_impl_trait_in_trait(proj.def_id)
858 {
859 if let Some((ty, _)) = self.types.get(&proj.def_id) {
860 return *ty;
861 }
862 if proj.args.has_escaping_bound_vars() {
864 bug!("FIXME(RPITIT): error here");
865 }
866 let infer_ty = self.ocx.infcx.next_ty_var(self.span);
868 self.types.insert(proj.def_id, (infer_ty, proj.args));
869 for (pred, pred_span) in self
871 .cx()
872 .explicit_item_bounds(proj.def_id)
873 .iter_instantiated_copied(self.cx(), proj.args)
874 {
875 let pred = pred.fold_with(self);
876 let pred = self.ocx.normalize(
877 &ObligationCause::misc(self.span, self.body_id),
878 self.param_env,
879 pred,
880 );
881
882 self.ocx.register_obligation(traits::Obligation::new(
883 self.cx(),
884 ObligationCause::new(
885 self.span,
886 self.body_id,
887 ObligationCauseCode::WhereClause(proj.def_id, pred_span),
888 ),
889 self.param_env,
890 pred,
891 ));
892 }
893 infer_ty
894 } else {
895 ty.super_fold_with(self)
896 }
897 }
898}
899
900struct RemapHiddenTyRegions<'tcx> {
901 tcx: TyCtxt<'tcx>,
902 map: FxIndexMap<ty::Region<'tcx>, ty::Region<'tcx>>,
905 num_trait_args: usize,
906 num_impl_args: usize,
907 def_id: DefId,
909 impl_m_def_id: DefId,
911 ty: Ty<'tcx>,
913 return_span: Span,
915}
916
917impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> {
918 type Error = ErrorGuaranteed;
919
920 fn cx(&self) -> TyCtxt<'tcx> {
921 self.tcx
922 }
923
924 fn try_fold_region(
925 &mut self,
926 region: ty::Region<'tcx>,
927 ) -> Result<ty::Region<'tcx>, Self::Error> {
928 match region.kind() {
929 ty::ReBound(..) | ty::ReStatic | ty::ReError(_) => return Ok(region),
931 ty::ReLateParam(_) => {}
933 ty::ReEarlyParam(ebr) => {
936 if ebr.index as usize >= self.num_impl_args {
937 } else {
939 return Ok(region);
940 }
941 }
942 ty::ReVar(_) | ty::RePlaceholder(_) | ty::ReErased => unreachable!(
943 "should not have leaked vars or placeholders into hidden type of RPITIT"
944 ),
945 }
946
947 let e = if let Some(id_region) = self.map.get(®ion) {
948 if let ty::ReEarlyParam(e) = id_region.kind() {
949 e
950 } else {
951 bug!(
952 "expected to map region {region} to early-bound identity region, but got {id_region}"
953 );
954 }
955 } else {
956 let guar = match region.opt_param_def_id(self.tcx, self.impl_m_def_id) {
957 Some(def_id) => {
958 let return_span = if let ty::Alias(ty::Opaque, opaque_ty) = self.ty.kind() {
959 self.tcx.def_span(opaque_ty.def_id)
960 } else {
961 self.return_span
962 };
963 self.tcx
964 .dcx()
965 .struct_span_err(
966 return_span,
967 "return type captures more lifetimes than trait definition",
968 )
969 .with_span_label(self.tcx.def_span(def_id), "this lifetime was captured")
970 .with_span_note(
971 self.tcx.def_span(self.def_id),
972 "hidden type must only reference lifetimes captured by this impl trait",
973 )
974 .with_note(format!("hidden type inferred to be `{}`", self.ty))
975 .emit()
976 }
977 None => {
978 self.tcx.dcx().bug("should've been able to remap region");
983 }
984 };
985 return Err(guar);
986 };
987
988 Ok(ty::Region::new_early_param(
989 self.tcx,
990 ty::EarlyParamRegion {
991 name: e.name,
992 index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32,
993 },
994 ))
995 }
996}
997
998fn report_trait_method_mismatch<'tcx>(
999 infcx: &InferCtxt<'tcx>,
1000 mut cause: ObligationCause<'tcx>,
1001 param_env: ty::ParamEnv<'tcx>,
1002 terr: TypeError<'tcx>,
1003 (trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>),
1004 (impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>),
1005 impl_trait_ref: ty::TraitRef<'tcx>,
1006) -> ErrorGuaranteed {
1007 let tcx = infcx.tcx;
1008 let (impl_err_span, trait_err_span) =
1009 extract_spans_for_error_reporting(infcx, terr, &cause, impl_m, trait_m);
1010
1011 let mut diag = struct_span_code_err!(
1012 tcx.dcx(),
1013 impl_err_span,
1014 E0053,
1015 "method `{}` has an incompatible type for trait",
1016 trait_m.name
1017 );
1018 match &terr {
1019 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
1020 if trait_m.fn_has_self_parameter =>
1021 {
1022 let ty = trait_sig.inputs()[0];
1023 let sugg = match ExplicitSelf::determine(ty, |ty| ty == impl_trait_ref.self_ty()) {
1024 ExplicitSelf::ByValue => "self".to_owned(),
1025 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
1026 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
1027 _ => format!("self: {ty}"),
1028 };
1029
1030 let (sig, body) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1034 let span = tcx
1035 .hir_body_param_names(body)
1036 .zip(sig.decl.inputs.iter())
1037 .map(|(param_name, ty)| {
1038 if let Some(param_name) = param_name {
1039 param_name.span.to(ty.span)
1040 } else {
1041 ty.span
1042 }
1043 })
1044 .next()
1045 .unwrap_or(impl_err_span);
1046
1047 diag.span_suggestion_verbose(
1048 span,
1049 "change the self-receiver type to match the trait",
1050 sugg,
1051 Applicability::MachineApplicable,
1052 );
1053 }
1054 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
1055 if trait_sig.inputs().len() == *i {
1056 if let ImplItemKind::Fn(sig, _) =
1059 &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).kind
1060 && !sig.header.asyncness.is_async()
1061 {
1062 let msg = "change the output type to match the trait";
1063 let ap = Applicability::MachineApplicable;
1064 match sig.decl.output {
1065 hir::FnRetTy::DefaultReturn(sp) => {
1066 let sugg = format!(" -> {}", trait_sig.output());
1067 diag.span_suggestion_verbose(sp, msg, sugg, ap);
1068 }
1069 hir::FnRetTy::Return(hir_ty) => {
1070 let sugg = trait_sig.output();
1071 diag.span_suggestion_verbose(hir_ty.span, msg, sugg, ap);
1072 }
1073 };
1074 };
1075 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
1076 diag.span_suggestion_verbose(
1077 impl_err_span,
1078 "change the parameter type to match the trait",
1079 trait_ty,
1080 Applicability::MachineApplicable,
1081 );
1082 }
1083 }
1084 _ => {}
1085 }
1086
1087 cause.span = impl_err_span;
1088 infcx.err_ctxt().note_type_err(
1089 &mut diag,
1090 &cause,
1091 trait_err_span.map(|sp| (sp, Cow::from("type in trait"), false)),
1092 Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound {
1093 expected: ty::Binder::dummy(trait_sig),
1094 found: ty::Binder::dummy(impl_sig),
1095 }))),
1096 terr,
1097 false,
1098 None,
1099 );
1100
1101 diag.emit()
1102}
1103
1104fn check_region_bounds_on_impl_item<'tcx>(
1105 tcx: TyCtxt<'tcx>,
1106 impl_m: ty::AssocItem,
1107 trait_m: ty::AssocItem,
1108 delay: bool,
1109) -> Result<(), ErrorGuaranteed> {
1110 let impl_generics = tcx.generics_of(impl_m.def_id);
1111 let impl_params = impl_generics.own_counts().lifetimes;
1112
1113 let trait_generics = tcx.generics_of(trait_m.def_id);
1114 let trait_params = trait_generics.own_counts().lifetimes;
1115
1116 debug!(?trait_generics, ?impl_generics);
1117
1118 if trait_params != impl_params {
1128 let span = tcx
1129 .hir_get_generics(impl_m.def_id.expect_local())
1130 .expect("expected impl item to have generics or else we can't compare them")
1131 .span;
1132
1133 let mut generics_span = None;
1134 let mut bounds_span = vec![];
1135 let mut where_span = None;
1136 if let Some(trait_node) = tcx.hir_get_if_local(trait_m.def_id)
1137 && let Some(trait_generics) = trait_node.generics()
1138 {
1139 generics_span = Some(trait_generics.span);
1140 for p in trait_generics.predicates {
1143 if let hir::WherePredicateKind::BoundPredicate(pred) = p.kind {
1144 for b in pred.bounds {
1145 if let hir::GenericBound::Outlives(lt) = b {
1146 bounds_span.push(lt.ident.span);
1147 }
1148 }
1149 }
1150 }
1151 if let Some(impl_node) = tcx.hir_get_if_local(impl_m.def_id)
1152 && let Some(impl_generics) = impl_node.generics()
1153 {
1154 let mut impl_bounds = 0;
1155 for p in impl_generics.predicates {
1156 if let hir::WherePredicateKind::BoundPredicate(pred) = p.kind {
1157 for b in pred.bounds {
1158 if let hir::GenericBound::Outlives(_) = b {
1159 impl_bounds += 1;
1160 }
1161 }
1162 }
1163 }
1164 if impl_bounds == bounds_span.len() {
1165 bounds_span = vec![];
1166 } else if impl_generics.has_where_clause_predicates {
1167 where_span = Some(impl_generics.where_clause_span);
1168 }
1169 }
1170 }
1171 let reported = tcx
1172 .dcx()
1173 .create_err(LifetimesOrBoundsMismatchOnTrait {
1174 span,
1175 item_kind: impl_m.descr(),
1176 ident: impl_m.ident(tcx),
1177 generics_span,
1178 bounds_span,
1179 where_span,
1180 })
1181 .emit_unless(delay);
1182 return Err(reported);
1183 }
1184
1185 Ok(())
1186}
1187
1188#[instrument(level = "debug", skip(infcx))]
1189fn extract_spans_for_error_reporting<'tcx>(
1190 infcx: &infer::InferCtxt<'tcx>,
1191 terr: TypeError<'_>,
1192 cause: &ObligationCause<'tcx>,
1193 impl_m: ty::AssocItem,
1194 trait_m: ty::AssocItem,
1195) -> (Span, Option<Span>) {
1196 let tcx = infcx.tcx;
1197 let mut impl_args = {
1198 let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1199 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1200 };
1201
1202 let trait_args = trait_m.def_id.as_local().map(|def_id| {
1203 let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
1204 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1205 });
1206
1207 match terr {
1208 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1209 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1210 }
1211 _ => (cause.span, tcx.hir().span_if_local(trait_m.def_id)),
1212 }
1213}
1214
1215fn compare_self_type<'tcx>(
1216 tcx: TyCtxt<'tcx>,
1217 impl_m: ty::AssocItem,
1218 trait_m: ty::AssocItem,
1219 impl_trait_ref: ty::TraitRef<'tcx>,
1220 delay: bool,
1221) -> Result<(), ErrorGuaranteed> {
1222 let self_string = |method: ty::AssocItem| {
1231 let untransformed_self_ty = match method.container {
1232 ty::AssocItemContainer::Impl => impl_trait_ref.self_ty(),
1233 ty::AssocItemContainer::Trait => tcx.types.self_param,
1234 };
1235 let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().input(0);
1236 let (infcx, param_env) = tcx
1237 .infer_ctxt()
1238 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
1239 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1240 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1241 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
1242 ExplicitSelf::ByValue => "self".to_owned(),
1243 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
1244 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
1245 _ => format!("self: {self_arg_ty}"),
1246 }
1247 };
1248
1249 match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
1250 (false, false) | (true, true) => {}
1251
1252 (false, true) => {
1253 let self_descr = self_string(impl_m);
1254 let impl_m_span = tcx.def_span(impl_m.def_id);
1255 let mut err = struct_span_code_err!(
1256 tcx.dcx(),
1257 impl_m_span,
1258 E0185,
1259 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1260 trait_m.name,
1261 self_descr
1262 );
1263 err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
1264 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1265 err.span_label(span, format!("trait method declared without `{self_descr}`"));
1266 } else {
1267 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1268 }
1269 return Err(err.emit_unless(delay));
1270 }
1271
1272 (true, false) => {
1273 let self_descr = self_string(trait_m);
1274 let impl_m_span = tcx.def_span(impl_m.def_id);
1275 let mut err = struct_span_code_err!(
1276 tcx.dcx(),
1277 impl_m_span,
1278 E0186,
1279 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1280 trait_m.name,
1281 self_descr
1282 );
1283 err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
1284 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1285 err.span_label(span, format!("`{self_descr}` used in trait"));
1286 } else {
1287 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1288 }
1289
1290 return Err(err.emit_unless(delay));
1291 }
1292 }
1293
1294 Ok(())
1295}
1296
1297fn compare_number_of_generics<'tcx>(
1319 tcx: TyCtxt<'tcx>,
1320 impl_: ty::AssocItem,
1321 trait_: ty::AssocItem,
1322 delay: bool,
1323) -> Result<(), ErrorGuaranteed> {
1324 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1325 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1326
1327 if (trait_own_counts.types + trait_own_counts.consts)
1331 == (impl_own_counts.types + impl_own_counts.consts)
1332 {
1333 return Ok(());
1334 }
1335
1336 if trait_.is_impl_trait_in_trait() {
1341 tcx.dcx()
1344 .bug("errors comparing numbers of generics of trait/impl functions were not emitted");
1345 }
1346
1347 let matchings = [
1348 ("type", trait_own_counts.types, impl_own_counts.types),
1349 ("const", trait_own_counts.consts, impl_own_counts.consts),
1350 ];
1351
1352 let item_kind = impl_.descr();
1353
1354 let mut err_occurred = None;
1355 for (kind, trait_count, impl_count) in matchings {
1356 if impl_count != trait_count {
1357 let arg_spans = |kind: ty::AssocKind, generics: &hir::Generics<'_>| {
1358 let mut spans = generics
1359 .params
1360 .iter()
1361 .filter(|p| match p.kind {
1362 hir::GenericParamKind::Lifetime {
1363 kind: hir::LifetimeParamKind::Elided(_),
1364 } => {
1365 !matches!(kind, ty::AssocKind::Fn)
1368 }
1369 _ => true,
1370 })
1371 .map(|p| p.span)
1372 .collect::<Vec<Span>>();
1373 if spans.is_empty() {
1374 spans = vec![generics.span]
1375 }
1376 spans
1377 };
1378 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1379 let trait_item = tcx.hir_expect_trait_item(def_id);
1380 let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
1381 let impl_trait_spans: Vec<Span> = trait_item
1382 .generics
1383 .params
1384 .iter()
1385 .filter_map(|p| match p.kind {
1386 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1387 _ => None,
1388 })
1389 .collect();
1390 (Some(arg_spans), impl_trait_spans)
1391 } else {
1392 let trait_span = tcx.hir().span_if_local(trait_.def_id);
1393 (trait_span.map(|s| vec![s]), vec![])
1394 };
1395
1396 let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
1397 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1398 .generics
1399 .params
1400 .iter()
1401 .filter_map(|p| match p.kind {
1402 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1403 _ => None,
1404 })
1405 .collect();
1406 let spans = arg_spans(impl_.kind, impl_item.generics);
1407 let span = spans.first().copied();
1408
1409 let mut err = tcx.dcx().struct_span_err(
1410 spans,
1411 format!(
1412 "{} `{}` has {} {kind} parameter{} but its trait \
1413 declaration has {} {kind} parameter{}",
1414 item_kind,
1415 trait_.name,
1416 impl_count,
1417 pluralize!(impl_count),
1418 trait_count,
1419 pluralize!(trait_count),
1420 kind = kind,
1421 ),
1422 );
1423 err.code(E0049);
1424
1425 let msg =
1426 format!("expected {trait_count} {kind} parameter{}", pluralize!(trait_count),);
1427 if let Some(spans) = trait_spans {
1428 let mut spans = spans.iter();
1429 if let Some(span) = spans.next() {
1430 err.span_label(*span, msg);
1431 }
1432 for span in spans {
1433 err.span_label(*span, "");
1434 }
1435 } else {
1436 err.span_label(tcx.def_span(trait_.def_id), msg);
1437 }
1438
1439 if let Some(span) = span {
1440 err.span_label(
1441 span,
1442 format!("found {} {} parameter{}", impl_count, kind, pluralize!(impl_count),),
1443 );
1444 }
1445
1446 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1447 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1448 }
1449
1450 let reported = err.emit_unless(delay);
1451 err_occurred = Some(reported);
1452 }
1453 }
1454
1455 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1456}
1457
1458fn compare_number_of_method_arguments<'tcx>(
1459 tcx: TyCtxt<'tcx>,
1460 impl_m: ty::AssocItem,
1461 trait_m: ty::AssocItem,
1462 delay: bool,
1463) -> Result<(), ErrorGuaranteed> {
1464 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1465 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1466 let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1467 let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1468
1469 if trait_number_args != impl_number_args {
1470 let trait_span = trait_m
1471 .def_id
1472 .as_local()
1473 .and_then(|def_id| {
1474 let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
1475 let pos = trait_number_args.saturating_sub(1);
1476 trait_m_sig.decl.inputs.get(pos).map(|arg| {
1477 if pos == 0 {
1478 arg.span
1479 } else {
1480 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1481 }
1482 })
1483 })
1484 .or_else(|| tcx.hir().span_if_local(trait_m.def_id));
1485
1486 let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1487 let pos = impl_number_args.saturating_sub(1);
1488 let impl_span = impl_m_sig
1489 .decl
1490 .inputs
1491 .get(pos)
1492 .map(|arg| {
1493 if pos == 0 {
1494 arg.span
1495 } else {
1496 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1497 }
1498 })
1499 .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1500
1501 let mut err = struct_span_code_err!(
1502 tcx.dcx(),
1503 impl_span,
1504 E0050,
1505 "method `{}` has {} but the declaration in trait `{}` has {}",
1506 trait_m.name,
1507 potentially_plural_count(impl_number_args, "parameter"),
1508 tcx.def_path_str(trait_m.def_id),
1509 trait_number_args
1510 );
1511
1512 if let Some(trait_span) = trait_span {
1513 err.span_label(
1514 trait_span,
1515 format!(
1516 "trait requires {}",
1517 potentially_plural_count(trait_number_args, "parameter")
1518 ),
1519 );
1520 } else {
1521 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1522 }
1523
1524 err.span_label(
1525 impl_span,
1526 format!(
1527 "expected {}, found {}",
1528 potentially_plural_count(trait_number_args, "parameter"),
1529 impl_number_args
1530 ),
1531 );
1532
1533 return Err(err.emit_unless(delay));
1534 }
1535
1536 Ok(())
1537}
1538
1539fn compare_synthetic_generics<'tcx>(
1540 tcx: TyCtxt<'tcx>,
1541 impl_m: ty::AssocItem,
1542 trait_m: ty::AssocItem,
1543 delay: bool,
1544) -> Result<(), ErrorGuaranteed> {
1545 let mut error_found = None;
1551 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1552 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1553 let impl_m_type_params =
1554 impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
1555 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1556 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1557 });
1558 let trait_m_type_params =
1559 trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
1560 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1561 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1562 });
1563 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1564 iter::zip(impl_m_type_params, trait_m_type_params)
1565 {
1566 if impl_synthetic != trait_synthetic {
1567 let impl_def_id = impl_def_id.expect_local();
1568 let impl_span = tcx.def_span(impl_def_id);
1569 let trait_span = tcx.def_span(trait_def_id);
1570 let mut err = struct_span_code_err!(
1571 tcx.dcx(),
1572 impl_span,
1573 E0643,
1574 "method `{}` has incompatible signature for trait",
1575 trait_m.name
1576 );
1577 err.span_label(trait_span, "declaration in trait here");
1578 if impl_synthetic {
1579 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1582 let _: Option<_> = try {
1583 let new_name = tcx.opt_item_name(trait_def_id)?;
1587 let trait_m = trait_m.def_id.as_local()?;
1588 let trait_m = tcx.hir_expect_trait_item(trait_m);
1589
1590 let impl_m = impl_m.def_id.as_local()?;
1591 let impl_m = tcx.hir_expect_impl_item(impl_m);
1592
1593 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1596 let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
1598 let new_generics =
1600 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1601
1602 err.multipart_suggestion(
1603 "try changing the `impl Trait` argument to a generic parameter",
1604 vec![
1605 (impl_span, new_name.to_string()),
1607 (generics_span, new_generics),
1611 ],
1612 Applicability::MaybeIncorrect,
1613 );
1614 };
1615 } else {
1616 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1619 let _: Option<_> = try {
1620 let impl_m = impl_m.def_id.as_local()?;
1621 let impl_m = tcx.hir_expect_impl_item(impl_m);
1622 let (sig, _) = impl_m.expect_fn();
1623 let input_tys = sig.decl.inputs;
1624
1625 struct Visitor(hir::def_id::LocalDefId);
1626 impl<'v> intravisit::Visitor<'v> for Visitor {
1627 type Result = ControlFlow<Span>;
1628 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
1629 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
1630 && let Res::Def(DefKind::TyParam, def_id) = path.res
1631 && def_id == self.0.to_def_id()
1632 {
1633 ControlFlow::Break(ty.span)
1634 } else {
1635 intravisit::walk_ty(self, ty)
1636 }
1637 }
1638 }
1639
1640 let span = input_tys
1641 .iter()
1642 .find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
1643
1644 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
1645 let bounds = bounds.first()?.span().to(bounds.last()?.span());
1646 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1647
1648 err.multipart_suggestion(
1649 "try removing the generic parameter and using `impl Trait` instead",
1650 vec![
1651 (impl_m.generics.span, String::new()),
1653 (span, format!("impl {bounds}")),
1655 ],
1656 Applicability::MaybeIncorrect,
1657 );
1658 };
1659 }
1660 error_found = Some(err.emit_unless(delay));
1661 }
1662 }
1663 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1664}
1665
1666fn compare_generic_param_kinds<'tcx>(
1692 tcx: TyCtxt<'tcx>,
1693 impl_item: ty::AssocItem,
1694 trait_item: ty::AssocItem,
1695 delay: bool,
1696) -> Result<(), ErrorGuaranteed> {
1697 assert_eq!(impl_item.kind, trait_item.kind);
1698
1699 let ty_const_params_of = |def_id| {
1700 tcx.generics_of(def_id).own_params.iter().filter(|param| {
1701 matches!(
1702 param.kind,
1703 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1704 )
1705 })
1706 };
1707
1708 for (param_impl, param_trait) in
1709 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1710 {
1711 use GenericParamDefKind::*;
1712 if match (¶m_impl.kind, ¶m_trait.kind) {
1713 (Const { .. }, Const { .. })
1714 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1715 {
1716 true
1717 }
1718 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1719 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1722 (Lifetime { .. }, _) | (_, Lifetime { .. }) => {
1723 bug!("lifetime params are expected to be filtered by `ty_const_params_of`")
1724 }
1725 } {
1726 let param_impl_span = tcx.def_span(param_impl.def_id);
1727 let param_trait_span = tcx.def_span(param_trait.def_id);
1728
1729 let mut err = struct_span_code_err!(
1730 tcx.dcx(),
1731 param_impl_span,
1732 E0053,
1733 "{} `{}` has an incompatible generic parameter for trait `{}`",
1734 impl_item.descr(),
1735 trait_item.name,
1736 &tcx.def_path_str(tcx.parent(trait_item.def_id))
1737 );
1738
1739 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1740 Const { .. } => {
1741 format!(
1742 "{} const parameter of type `{}`",
1743 prefix,
1744 tcx.type_of(param.def_id).instantiate_identity()
1745 )
1746 }
1747 Type { .. } => format!("{prefix} type parameter"),
1748 Lifetime { .. } => span_bug!(
1749 tcx.def_span(param.def_id),
1750 "lifetime params are expected to be filtered by `ty_const_params_of`"
1751 ),
1752 };
1753
1754 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1755 err.span_label(trait_header_span, "");
1756 err.span_label(param_trait_span, make_param_message("expected", param_trait));
1757
1758 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1759 err.span_label(impl_header_span, "");
1760 err.span_label(param_impl_span, make_param_message("found", param_impl));
1761
1762 let reported = err.emit_unless(delay);
1763 return Err(reported);
1764 }
1765 }
1766
1767 Ok(())
1768}
1769
1770fn compare_impl_const<'tcx>(
1771 tcx: TyCtxt<'tcx>,
1772 impl_const_item: ty::AssocItem,
1773 trait_const_item: ty::AssocItem,
1774 impl_trait_ref: ty::TraitRef<'tcx>,
1775) -> Result<(), ErrorGuaranteed> {
1776 compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
1777 compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
1778 check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
1779 compare_const_predicate_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
1780}
1781
1782#[instrument(level = "debug", skip(tcx))]
1786fn compare_const_predicate_entailment<'tcx>(
1787 tcx: TyCtxt<'tcx>,
1788 impl_ct: ty::AssocItem,
1789 trait_ct: ty::AssocItem,
1790 impl_trait_ref: ty::TraitRef<'tcx>,
1791) -> Result<(), ErrorGuaranteed> {
1792 let impl_ct_def_id = impl_ct.def_id.expect_local();
1793 let impl_ct_span = tcx.def_span(impl_ct_def_id);
1794
1795 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto(
1801 tcx,
1802 impl_ct.container_id(tcx),
1803 impl_trait_ref.args,
1804 );
1805
1806 let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
1809
1810 let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
1811 let code = ObligationCauseCode::CompareImplItem {
1812 impl_item_def_id: impl_ct_def_id,
1813 trait_item_def_id: trait_ct.def_id,
1814 kind: impl_ct.kind,
1815 };
1816 let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());
1817
1818 let impl_ct_predicates = tcx.predicates_of(impl_ct.def_id);
1819 let trait_ct_predicates = tcx.predicates_of(trait_ct.def_id);
1820
1821 let impl_predicates = tcx.predicates_of(impl_ct_predicates.parent.unwrap());
1824 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
1825 hybrid_preds.extend(
1826 trait_ct_predicates
1827 .instantiate_own(tcx, trait_to_impl_args)
1828 .map(|(predicate, _)| predicate),
1829 );
1830
1831 let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
1832 let param_env = traits::normalize_param_env_or_error(
1833 tcx,
1834 param_env,
1835 ObligationCause::misc(impl_ct_span, impl_ct_def_id),
1836 );
1837
1838 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1839 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1840
1841 let impl_ct_own_bounds = impl_ct_predicates.instantiate_own_identity();
1842 for (predicate, span) in impl_ct_own_bounds {
1843 let cause = ObligationCause::misc(span, impl_ct_def_id);
1844 let predicate = ocx.normalize(&cause, param_env, predicate);
1845
1846 let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
1847 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
1848 }
1849
1850 let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
1852 debug!(?impl_ty);
1853
1854 let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
1855 debug!(?trait_ty);
1856
1857 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
1858
1859 if let Err(terr) = err {
1860 debug!(?impl_ty, ?trait_ty);
1861
1862 let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
1864 cause.span = ty.span;
1865
1866 let mut diag = struct_span_code_err!(
1867 tcx.dcx(),
1868 cause.span,
1869 E0326,
1870 "implemented const `{}` has an incompatible type for trait",
1871 trait_ct.name
1872 );
1873
1874 let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
1875 let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
1877 ty.span
1878 });
1879
1880 infcx.err_ctxt().note_type_err(
1881 &mut diag,
1882 &cause,
1883 trait_c_span.map(|span| (span, Cow::from("type in trait"), false)),
1884 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
1885 expected: trait_ty.into(),
1886 found: impl_ty.into(),
1887 }))),
1888 terr,
1889 false,
1890 None,
1891 );
1892 return Err(diag.emit());
1893 };
1894
1895 let errors = ocx.select_all_or_error();
1898 if !errors.is_empty() {
1899 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
1900 }
1901
1902 ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env, [])
1903}
1904
1905#[instrument(level = "debug", skip(tcx))]
1906fn compare_impl_ty<'tcx>(
1907 tcx: TyCtxt<'tcx>,
1908 impl_ty: ty::AssocItem,
1909 trait_ty: ty::AssocItem,
1910 impl_trait_ref: ty::TraitRef<'tcx>,
1911) -> Result<(), ErrorGuaranteed> {
1912 compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
1913 compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
1914 check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
1915 compare_type_predicate_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
1916 check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
1917}
1918
1919#[instrument(level = "debug", skip(tcx))]
1922fn compare_type_predicate_entailment<'tcx>(
1923 tcx: TyCtxt<'tcx>,
1924 impl_ty: ty::AssocItem,
1925 trait_ty: ty::AssocItem,
1926 impl_trait_ref: ty::TraitRef<'tcx>,
1927) -> Result<(), ErrorGuaranteed> {
1928 let impl_def_id = impl_ty.container_id(tcx);
1929 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
1930 tcx,
1931 impl_def_id,
1932 impl_trait_ref.args,
1933 );
1934
1935 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1936 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1937
1938 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own_identity();
1939 if impl_ty_own_bounds.len() == 0 {
1941 return Ok(());
1943 }
1944
1945 let impl_ty_def_id = impl_ty.def_id.expect_local();
1949 debug!(?trait_to_impl_args);
1950
1951 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1954 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
1955 hybrid_preds.extend(
1956 trait_ty_predicates
1957 .instantiate_own(tcx, trait_to_impl_args)
1958 .map(|(predicate, _)| predicate),
1959 );
1960 debug!(?hybrid_preds);
1961
1962 let impl_ty_span = tcx.def_span(impl_ty_def_id);
1963 let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
1964
1965 let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
1966 if is_conditionally_const {
1967 hybrid_preds.extend(
1970 tcx.const_conditions(impl_ty_predicates.parent.unwrap())
1971 .instantiate_identity(tcx)
1972 .into_iter()
1973 .chain(
1974 tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
1975 )
1976 .map(|(trait_ref, _)| {
1977 trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
1978 }),
1979 );
1980 }
1981
1982 let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
1983 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
1984 debug!(caller_bounds=?param_env.caller_bounds());
1985
1986 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1987 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1988
1989 for (predicate, span) in impl_ty_own_bounds {
1990 let cause = ObligationCause::misc(span, impl_ty_def_id);
1991 let predicate = ocx.normalize(&cause, param_env, predicate);
1992
1993 let cause = ObligationCause::new(
1994 span,
1995 impl_ty_def_id,
1996 ObligationCauseCode::CompareImplItem {
1997 impl_item_def_id: impl_ty.def_id.expect_local(),
1998 trait_item_def_id: trait_ty.def_id,
1999 kind: impl_ty.kind,
2000 },
2001 );
2002 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2003 }
2004
2005 if is_conditionally_const {
2006 let impl_ty_own_const_conditions =
2008 tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2009 for (const_condition, span) in impl_ty_own_const_conditions {
2010 let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2011 let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2012
2013 let cause = ObligationCause::new(
2014 span,
2015 impl_ty_def_id,
2016 ObligationCauseCode::CompareImplItem {
2017 impl_item_def_id: impl_ty_def_id,
2018 trait_item_def_id: trait_ty.def_id,
2019 kind: impl_ty.kind,
2020 },
2021 );
2022 ocx.register_obligation(traits::Obligation::new(
2023 tcx,
2024 cause,
2025 param_env,
2026 const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2027 ));
2028 }
2029 }
2030
2031 let errors = ocx.select_all_or_error();
2034 if !errors.is_empty() {
2035 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2036 return Err(reported);
2037 }
2038
2039 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2042}
2043
2044#[instrument(level = "debug", skip(tcx))]
2058pub(super) fn check_type_bounds<'tcx>(
2059 tcx: TyCtxt<'tcx>,
2060 trait_ty: ty::AssocItem,
2061 impl_ty: ty::AssocItem,
2062 impl_trait_ref: ty::TraitRef<'tcx>,
2063) -> Result<(), ErrorGuaranteed> {
2064 tcx.ensure_ok().coherent_trait(impl_trait_ref.def_id)?;
2067
2068 let param_env = tcx.param_env(impl_ty.def_id);
2069 debug!(?param_env);
2070
2071 let container_id = impl_ty.container_id(tcx);
2072 let impl_ty_def_id = impl_ty.def_id.expect_local();
2073 let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2074 let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2075
2076 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2077 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2078
2079 let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2083 tcx.def_span(impl_ty_def_id)
2084 } else {
2085 match tcx.hir_node_by_def_id(impl_ty_def_id) {
2086 hir::Node::TraitItem(hir::TraitItem {
2087 kind: hir::TraitItemKind::Type(_, Some(ty)),
2088 ..
2089 }) => ty.span,
2090 hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2091 item => span_bug!(
2092 tcx.def_span(impl_ty_def_id),
2093 "cannot call `check_type_bounds` on item: {item:?}",
2094 ),
2095 }
2096 };
2097 let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2098
2099 let normalize_cause = ObligationCause::new(
2100 impl_ty_span,
2101 impl_ty_def_id,
2102 ObligationCauseCode::CheckAssociatedTypeBounds {
2103 impl_item_def_id: impl_ty.def_id.expect_local(),
2104 trait_item_def_id: trait_ty.def_id,
2105 },
2106 );
2107 let mk_cause = |span: Span| {
2108 let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2109 ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2110 };
2111
2112 let mut obligations: Vec<_> = util::elaborate(
2113 tcx,
2114 tcx.explicit_item_bounds(trait_ty.def_id).iter_instantiated_copied(tcx, rebased_args).map(
2115 |(concrete_ty_bound, span)| {
2116 debug!(?concrete_ty_bound);
2117 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2118 },
2119 ),
2120 )
2121 .collect();
2122
2123 if tcx.is_conditionally_const(impl_ty_def_id) {
2125 obligations.extend(util::elaborate(
2126 tcx,
2127 tcx.explicit_implied_const_bounds(trait_ty.def_id)
2128 .iter_instantiated_copied(tcx, rebased_args)
2129 .map(|(c, span)| {
2130 traits::Obligation::new(
2131 tcx,
2132 mk_cause(span),
2133 param_env,
2134 c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2135 )
2136 }),
2137 ));
2138 }
2139 debug!(item_bounds=?obligations);
2140
2141 let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2146 for obligation in &mut obligations {
2147 match ocx.deeply_normalize(&normalize_cause, normalize_param_env, obligation.predicate) {
2148 Ok(pred) => obligation.predicate = pred,
2149 Err(e) => {
2150 return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2151 }
2152 }
2153 }
2154
2155 ocx.register_obligations(obligations);
2158 let errors = ocx.select_all_or_error();
2159 if !errors.is_empty() {
2160 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2161 return Err(reported);
2162 }
2163
2164 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2167}
2168
2169fn param_env_with_gat_bounds<'tcx>(
2217 tcx: TyCtxt<'tcx>,
2218 impl_ty: ty::AssocItem,
2219 impl_trait_ref: ty::TraitRef<'tcx>,
2220) -> ty::ParamEnv<'tcx> {
2221 let param_env = tcx.param_env(impl_ty.def_id);
2222 let container_id = impl_ty.container_id(tcx);
2223 let mut predicates = param_env.caller_bounds().to_vec();
2224
2225 let impl_tys_to_install = match impl_ty.opt_rpitit_info {
2230 None => vec![impl_ty],
2231 Some(
2232 ty::ImplTraitInTraitData::Impl { fn_def_id }
2233 | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2234 ) => tcx
2235 .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2236 .iter()
2237 .map(|def_id| tcx.associated_item(*def_id))
2238 .collect(),
2239 };
2240
2241 for impl_ty in impl_tys_to_install {
2242 let trait_ty = match impl_ty.container {
2243 ty::AssocItemContainer::Trait => impl_ty,
2244 ty::AssocItemContainer::Impl => tcx.associated_item(impl_ty.trait_item_def_id.unwrap()),
2245 };
2246
2247 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
2248 smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2249 let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2251 .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2252 GenericParamDefKind::Type { .. } => {
2253 let kind = ty::BoundTyKind::Param(param.def_id, param.name);
2254 let bound_var = ty::BoundVariableKind::Ty(kind);
2255 bound_vars.push(bound_var);
2256 Ty::new_bound(
2257 tcx,
2258 ty::INNERMOST,
2259 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2260 )
2261 .into()
2262 }
2263 GenericParamDefKind::Lifetime => {
2264 let kind = ty::BoundRegionKind::Named(param.def_id, param.name);
2265 let bound_var = ty::BoundVariableKind::Region(kind);
2266 bound_vars.push(bound_var);
2267 ty::Region::new_bound(
2268 tcx,
2269 ty::INNERMOST,
2270 ty::BoundRegion {
2271 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2272 kind,
2273 },
2274 )
2275 .into()
2276 }
2277 GenericParamDefKind::Const { .. } => {
2278 let bound_var = ty::BoundVariableKind::Const;
2279 bound_vars.push(bound_var);
2280 ty::Const::new_bound(
2281 tcx,
2282 ty::INNERMOST,
2283 ty::BoundVar::from_usize(bound_vars.len() - 1),
2284 )
2285 .into()
2286 }
2287 });
2288 let normalize_impl_ty =
2298 tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args);
2299 let rebased_args =
2300 normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2301 let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2302
2303 match normalize_impl_ty.kind() {
2304 ty::Alias(ty::Projection, proj)
2305 if proj.def_id == trait_ty.def_id && proj.args == rebased_args =>
2306 {
2307 }
2313 _ => predicates.push(
2314 ty::Binder::bind_with_vars(
2315 ty::ProjectionPredicate {
2316 projection_term: ty::AliasTerm::new_from_args(
2317 tcx,
2318 trait_ty.def_id,
2319 rebased_args,
2320 ),
2321 term: normalize_impl_ty.into(),
2322 },
2323 bound_vars,
2324 )
2325 .upcast(tcx),
2326 ),
2327 };
2328 }
2329
2330 ty::ParamEnv::new(tcx.mk_clauses(&predicates))
2331}
2332
2333fn try_report_async_mismatch<'tcx>(
2336 tcx: TyCtxt<'tcx>,
2337 infcx: &InferCtxt<'tcx>,
2338 errors: &[FulfillmentError<'tcx>],
2339 trait_m: ty::AssocItem,
2340 impl_m: ty::AssocItem,
2341 impl_sig: ty::FnSig<'tcx>,
2342) -> Result<(), ErrorGuaranteed> {
2343 if !tcx.asyncness(trait_m.def_id).is_async() {
2344 return Ok(());
2345 }
2346
2347 let ty::Alias(ty::Projection, ty::AliasTy { def_id: async_future_def_id, .. }) =
2348 *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2349 else {
2350 bug!("expected `async fn` to return an RPITIT");
2351 };
2352
2353 for error in errors {
2354 if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2355 && def_id == async_future_def_id
2356 && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2357 && let Some(proj) = proj.no_bound_vars()
2358 && infcx.can_eq(
2359 error.root_obligation.param_env,
2360 proj.term.expect_type(),
2361 impl_sig.output(),
2362 )
2363 {
2364 return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2367 span: tcx.def_span(impl_m.def_id),
2368 method_name: tcx.item_ident(impl_m.def_id),
2369 trait_item_span: tcx.hir().span_if_local(trait_m.def_id),
2370 }));
2371 }
2372 }
2373
2374 Ok(())
2375}