1use core::ops::ControlFlow;
2use std::borrow::Cow;
3use std::iter;
4
5use hir::def_id::{DefId, DefIdMap, LocalDefId};
6use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
7use rustc_errors::codes::*;
8use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan, 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, BoundRegionConversionTime, InferCtxt, TyCtxtInferExt};
13use rustc_infer::traits::util;
14use rustc_middle::ty::error::{ExpectedFound, TypeError};
15use rustc_middle::ty::{
16 self, BottomUpFolder, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFoldable, TypeFolder,
17 TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Upcast,
18};
19use rustc_middle::{bug, span_bug};
20use rustc_span::{DUMMY_SP, Span};
21use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
22use rustc_trait_selection::infer::InferCtxtExt;
23use rustc_trait_selection::regions::InferCtxtRegionExt;
24use rustc_trait_selection::traits::{
25 self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
26};
27use tracing::{debug, instrument};
28
29use super::potentially_plural_count;
30use crate::errors::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture};
31
32pub(super) mod refine;
33
34pub(super) fn compare_impl_item(
36 tcx: TyCtxt<'_>,
37 impl_item_def_id: LocalDefId,
38) -> Result<(), ErrorGuaranteed> {
39 let impl_item = tcx.associated_item(impl_item_def_id);
40 let trait_item = tcx.associated_item(impl_item.expect_trait_impl()?);
41 let impl_trait_ref =
42 tcx.impl_trait_ref(impl_item.container_id(tcx)).unwrap().instantiate_identity();
43 debug!(?impl_trait_ref);
44
45 match impl_item.kind {
46 ty::AssocKind::Fn { .. } => compare_impl_method(tcx, impl_item, trait_item, impl_trait_ref),
47 ty::AssocKind::Type { .. } => compare_impl_ty(tcx, impl_item, trait_item, impl_trait_ref),
48 ty::AssocKind::Const { .. } => {
49 compare_impl_const(tcx, impl_item, trait_item, impl_trait_ref)
50 }
51 }
52}
53
54#[instrument(level = "debug", skip(tcx))]
63fn compare_impl_method<'tcx>(
64 tcx: TyCtxt<'tcx>,
65 impl_m: ty::AssocItem,
66 trait_m: ty::AssocItem,
67 impl_trait_ref: ty::TraitRef<'tcx>,
68) -> Result<(), ErrorGuaranteed> {
69 check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, false)?;
70 compare_method_predicate_entailment(tcx, impl_m, trait_m, impl_trait_ref)?;
71 Ok(())
72}
73
74fn check_method_is_structurally_compatible<'tcx>(
78 tcx: TyCtxt<'tcx>,
79 impl_m: ty::AssocItem,
80 trait_m: ty::AssocItem,
81 impl_trait_ref: ty::TraitRef<'tcx>,
82 delay: bool,
83) -> Result<(), ErrorGuaranteed> {
84 compare_self_type(tcx, impl_m, trait_m, impl_trait_ref, delay)?;
85 compare_number_of_generics(tcx, impl_m, trait_m, delay)?;
86 compare_generic_param_kinds(tcx, impl_m, trait_m, delay)?;
87 compare_number_of_method_arguments(tcx, impl_m, trait_m, delay)?;
88 compare_synthetic_generics(tcx, impl_m, trait_m, delay)?;
89 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, delay)?;
90 Ok(())
91}
92
93#[instrument(level = "debug", skip(tcx, impl_trait_ref))]
172fn compare_method_predicate_entailment<'tcx>(
173 tcx: TyCtxt<'tcx>,
174 impl_m: ty::AssocItem,
175 trait_m: ty::AssocItem,
176 impl_trait_ref: ty::TraitRef<'tcx>,
177) -> Result<(), ErrorGuaranteed> {
178 let impl_m_def_id = impl_m.def_id.expect_local();
184 let impl_m_span = tcx.def_span(impl_m_def_id);
185 let cause = ObligationCause::new(
186 impl_m_span,
187 impl_m_def_id,
188 ObligationCauseCode::CompareImplItem {
189 impl_item_def_id: impl_m_def_id,
190 trait_item_def_id: trait_m.def_id,
191 kind: impl_m.kind,
192 },
193 );
194
195 let impl_def_id = impl_m.container_id(tcx);
197 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
198 tcx,
199 impl_m.container_id(tcx),
200 impl_trait_ref.args,
201 );
202 debug!(?trait_to_impl_args);
203
204 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
205 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
206
207 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
215 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
216 hybrid_preds.extend(
217 trait_m_predicates.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate),
218 );
219
220 let is_conditionally_const = tcx.is_conditionally_const(impl_def_id);
221 if is_conditionally_const {
222 hybrid_preds.extend(
225 tcx.const_conditions(impl_def_id)
226 .instantiate_identity(tcx)
227 .into_iter()
228 .chain(
229 tcx.const_conditions(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args),
230 )
231 .map(|(trait_ref, _)| {
232 trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
233 }),
234 );
235 }
236
237 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
238 let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
239 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
240 debug!(caller_bounds=?param_env.caller_bounds());
241
242 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
243 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
244
245 let impl_m_own_bounds = impl_m_predicates.instantiate_own_identity();
250 for (predicate, span) in impl_m_own_bounds {
251 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
252 let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
253
254 let cause = ObligationCause::new(
255 span,
256 impl_m_def_id,
257 ObligationCauseCode::CompareImplItem {
258 impl_item_def_id: impl_m_def_id,
259 trait_item_def_id: trait_m.def_id,
260 kind: impl_m.kind,
261 },
262 );
263 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
264 }
265
266 if is_conditionally_const {
273 for (const_condition, span) in
274 tcx.const_conditions(impl_m.def_id).instantiate_own_identity()
275 {
276 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
277 let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
278
279 let cause = ObligationCause::new(
280 span,
281 impl_m_def_id,
282 ObligationCauseCode::CompareImplItem {
283 impl_item_def_id: impl_m_def_id,
284 trait_item_def_id: trait_m.def_id,
285 kind: impl_m.kind,
286 },
287 );
288 ocx.register_obligation(traits::Obligation::new(
289 tcx,
290 cause,
291 param_env,
292 const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
293 ));
294 }
295 }
296
297 let mut wf_tys = FxIndexSet::default();
306
307 let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars(
308 impl_m_span,
309 BoundRegionConversionTime::HigherRankedType,
310 tcx.fn_sig(impl_m.def_id).instantiate_identity(),
311 );
312
313 let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id);
314 let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig);
315 debug!(?impl_sig);
316
317 let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args);
318 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
319
320 wf_tys.extend(trait_sig.inputs_and_output.iter());
324 let trait_sig = ocx.normalize(&norm_cause, param_env, trait_sig);
325 wf_tys.extend(trait_sig.inputs_and_output.iter());
328 debug!(?trait_sig);
329
330 let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
337
338 if let Err(terr) = result {
339 debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
340
341 let emitted = report_trait_method_mismatch(
342 infcx,
343 cause,
344 param_env,
345 terr,
346 (trait_m, trait_sig),
347 (impl_m, impl_sig),
348 impl_trait_ref,
349 );
350 return Err(emitted);
351 }
352
353 if !(impl_sig, trait_sig).references_error() {
354 for ty in unnormalized_impl_sig.inputs_and_output {
355 ocx.register_obligation(traits::Obligation::new(
356 infcx.tcx,
357 cause.clone(),
358 param_env,
359 ty::ClauseKind::WellFormed(ty.into()),
360 ));
361 }
362 }
363
364 let errors = ocx.select_all_or_error();
367 if !errors.is_empty() {
368 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
369 return Err(reported);
370 }
371
372 let errors = infcx.resolve_regions(impl_m_def_id, param_env, wf_tys);
375 if !errors.is_empty() {
376 return Err(infcx
377 .tainted_by_errors()
378 .unwrap_or_else(|| infcx.err_ctxt().report_region_errors(impl_m_def_id, &errors)));
379 }
380
381 Ok(())
382}
383
384struct RemapLateParam<'tcx> {
385 tcx: TyCtxt<'tcx>,
386 mapping: FxIndexMap<ty::LateParamRegionKind, ty::LateParamRegionKind>,
387}
388
389impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateParam<'tcx> {
390 fn cx(&self) -> TyCtxt<'tcx> {
391 self.tcx
392 }
393
394 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
395 if let ty::ReLateParam(fr) = r.kind() {
396 ty::Region::new_late_param(
397 self.tcx,
398 fr.scope,
399 self.mapping.get(&fr.kind).copied().unwrap_or(fr.kind),
400 )
401 } else {
402 r
403 }
404 }
405}
406
407#[instrument(skip(tcx), level = "debug", ret)]
439pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
440 tcx: TyCtxt<'tcx>,
441 impl_m_def_id: LocalDefId,
442) -> Result<&'tcx DefIdMap<ty::EarlyBinder<'tcx, Ty<'tcx>>>, ErrorGuaranteed> {
443 let impl_m = tcx.associated_item(impl_m_def_id.to_def_id());
444 let trait_m = tcx.associated_item(impl_m.expect_trait_impl()?);
445 let impl_trait_ref =
446 tcx.impl_trait_ref(tcx.parent(impl_m_def_id.to_def_id())).unwrap().instantiate_identity();
447 check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?;
450
451 let impl_m_hir_id = tcx.local_def_id_to_hir_id(impl_m_def_id);
452 let return_span = tcx.hir_fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
453 let cause = ObligationCause::new(
454 return_span,
455 impl_m_def_id,
456 ObligationCauseCode::CompareImplItem {
457 impl_item_def_id: impl_m_def_id,
458 trait_item_def_id: trait_m.def_id,
459 kind: impl_m.kind,
460 },
461 );
462
463 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
465 tcx,
466 impl_m.container_id(tcx),
467 impl_trait_ref.args,
468 );
469
470 let hybrid_preds = tcx
471 .predicates_of(impl_m.container_id(tcx))
472 .instantiate_identity(tcx)
473 .into_iter()
474 .chain(tcx.predicates_of(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args))
475 .map(|(clause, _)| clause);
476 let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
477 let param_env = traits::normalize_param_env_or_error(
478 tcx,
479 param_env,
480 ObligationCause::misc(tcx.def_span(impl_m_def_id), impl_m_def_id),
481 );
482
483 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
484 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
485
486 let impl_m_own_bounds = tcx.predicates_of(impl_m_def_id).instantiate_own_identity();
493 for (predicate, span) in impl_m_own_bounds {
494 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
495 let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
496
497 let cause = ObligationCause::new(
498 span,
499 impl_m_def_id,
500 ObligationCauseCode::CompareImplItem {
501 impl_item_def_id: impl_m_def_id,
502 trait_item_def_id: trait_m.def_id,
503 kind: impl_m.kind,
504 },
505 );
506 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
507 }
508
509 let misc_cause = ObligationCause::misc(return_span, impl_m_def_id);
511 let impl_sig = ocx.normalize(
512 &misc_cause,
513 param_env,
514 infcx.instantiate_binder_with_fresh_vars(
515 return_span,
516 BoundRegionConversionTime::HigherRankedType,
517 tcx.fn_sig(impl_m.def_id).instantiate_identity(),
518 ),
519 );
520 impl_sig.error_reported()?;
521 let impl_return_ty = impl_sig.output();
522
523 let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_def_id);
528 let unnormalized_trait_sig = tcx
529 .liberate_late_bound_regions(
530 impl_m.def_id,
531 tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args),
532 )
533 .fold_with(&mut collector);
534
535 let trait_sig = ocx.normalize(&misc_cause, param_env, unnormalized_trait_sig);
536 trait_sig.error_reported()?;
537 let trait_return_ty = trait_sig.output();
538
539 let universe = infcx.create_next_universe();
559 let mut idx = ty::BoundVar::ZERO;
560 let mapping: FxIndexMap<_, _> = collector
561 .types
562 .iter()
563 .map(|(_, &(ty, _))| {
564 assert!(
565 infcx.resolve_vars_if_possible(ty) == ty && ty.is_ty_var(),
566 "{ty:?} should not have been constrained via normalization",
567 ty = infcx.resolve_vars_if_possible(ty)
568 );
569 idx += 1;
570 (
571 ty,
572 Ty::new_placeholder(
573 tcx,
574 ty::Placeholder {
575 universe,
576 bound: ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
577 },
578 ),
579 )
580 })
581 .collect();
582 let mut type_mapper = BottomUpFolder {
583 tcx,
584 ty_op: |ty| *mapping.get(&ty).unwrap_or(&ty),
585 lt_op: |lt| lt,
586 ct_op: |ct| ct,
587 };
588 let wf_tys = FxIndexSet::from_iter(
589 unnormalized_trait_sig
590 .inputs_and_output
591 .iter()
592 .chain(trait_sig.inputs_and_output.iter())
593 .map(|ty| ty.fold_with(&mut type_mapper)),
594 );
595
596 match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
597 Ok(()) => {}
598 Err(terr) => {
599 let mut diag = struct_span_code_err!(
600 tcx.dcx(),
601 cause.span,
602 E0053,
603 "method `{}` has an incompatible return type for trait",
604 trait_m.name()
605 );
606 infcx.err_ctxt().note_type_err(
607 &mut diag,
608 &cause,
609 tcx.hir_get_if_local(impl_m.def_id)
610 .and_then(|node| node.fn_decl())
611 .map(|decl| (decl.output.span(), Cow::from("return type in trait"), false)),
612 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
613 expected: trait_return_ty.into(),
614 found: impl_return_ty.into(),
615 }))),
616 terr,
617 false,
618 None,
619 );
620 return Err(diag.emit());
621 }
622 }
623
624 debug!(?trait_sig, ?impl_sig, "equating function signatures");
625
626 match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
631 Ok(()) => {}
632 Err(terr) => {
633 let emitted = report_trait_method_mismatch(
638 infcx,
639 cause,
640 param_env,
641 terr,
642 (trait_m, trait_sig),
643 (impl_m, impl_sig),
644 impl_trait_ref,
645 );
646 return Err(emitted);
647 }
648 }
649
650 if !unnormalized_trait_sig.output().references_error() && collector.types.is_empty() {
651 tcx.dcx().delayed_bug(
652 "expect >0 RPITITs in call to `collect_return_position_impl_trait_in_trait_tys`",
653 );
654 }
655
656 let collected_types = collector.types;
661 for (_, &(ty, _)) in &collected_types {
662 ocx.register_obligation(traits::Obligation::new(
663 tcx,
664 misc_cause.clone(),
665 param_env,
666 ty::ClauseKind::WellFormed(ty.into()),
667 ));
668 }
669
670 let errors = ocx.select_all_or_error();
673 if !errors.is_empty() {
674 if let Err(guar) = try_report_async_mismatch(tcx, infcx, &errors, trait_m, impl_m, impl_sig)
675 {
676 return Err(guar);
677 }
678
679 let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
680 return Err(guar);
681 }
682
683 ocx.resolve_regions_and_report_errors(impl_m_def_id, param_env, wf_tys)?;
686
687 let mut remapped_types = DefIdMap::default();
688 for (def_id, (ty, args)) in collected_types {
689 match infcx.fully_resolve(ty) {
690 Ok(ty) => {
691 let id_args = GenericArgs::identity_for_item(tcx, def_id);
695 debug!(?id_args, ?args);
696 let map: FxIndexMap<_, _> = std::iter::zip(args, id_args)
697 .skip(tcx.generics_of(trait_m.def_id).count())
698 .filter_map(|(a, b)| Some((a.as_region()?, b.as_region()?)))
699 .collect();
700 debug!(?map);
701
702 let num_trait_args = impl_trait_ref.args.len();
723 let num_impl_args = tcx.generics_of(impl_m.container_id(tcx)).own_params.len();
724 let ty = match ty.try_fold_with(&mut RemapHiddenTyRegions {
725 tcx,
726 map,
727 num_trait_args,
728 num_impl_args,
729 def_id,
730 impl_m_def_id: impl_m.def_id,
731 ty,
732 return_span,
733 }) {
734 Ok(ty) => ty,
735 Err(guar) => Ty::new_error(tcx, guar),
736 };
737 remapped_types.insert(def_id, ty::EarlyBinder::bind(ty));
738 }
739 Err(err) => {
740 tcx.dcx()
745 .span_bug(return_span, format!("could not fully resolve: {ty} => {err:?}"));
746 }
747 }
748 }
749
750 for assoc_item in tcx.associated_types_for_impl_traits_in_associated_fn(trait_m.def_id) {
756 if !remapped_types.contains_key(assoc_item) {
757 remapped_types.insert(
758 *assoc_item,
759 ty::EarlyBinder::bind(Ty::new_error_with_message(
760 tcx,
761 return_span,
762 "missing synthetic item for RPITIT",
763 )),
764 );
765 }
766 }
767
768 Ok(&*tcx.arena.alloc(remapped_types))
769}
770
771struct ImplTraitInTraitCollector<'a, 'tcx, E> {
772 ocx: &'a ObligationCtxt<'a, 'tcx, E>,
773 types: FxIndexMap<DefId, (Ty<'tcx>, ty::GenericArgsRef<'tcx>)>,
774 span: Span,
775 param_env: ty::ParamEnv<'tcx>,
776 body_id: LocalDefId,
777}
778
779impl<'a, 'tcx, E> ImplTraitInTraitCollector<'a, 'tcx, E>
780where
781 E: 'tcx,
782{
783 fn new(
784 ocx: &'a ObligationCtxt<'a, 'tcx, E>,
785 span: Span,
786 param_env: ty::ParamEnv<'tcx>,
787 body_id: LocalDefId,
788 ) -> Self {
789 ImplTraitInTraitCollector { ocx, types: FxIndexMap::default(), span, param_env, body_id }
790 }
791}
792
793impl<'tcx, E> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx, E>
794where
795 E: 'tcx,
796{
797 fn cx(&self) -> TyCtxt<'tcx> {
798 self.ocx.infcx.tcx
799 }
800
801 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
802 if let ty::Alias(ty::Projection, proj) = ty.kind()
803 && self.cx().is_impl_trait_in_trait(proj.def_id)
804 {
805 if let Some((ty, _)) = self.types.get(&proj.def_id) {
806 return *ty;
807 }
808 if proj.args.has_escaping_bound_vars() {
810 bug!("FIXME(RPITIT): error here");
811 }
812 let infer_ty = self.ocx.infcx.next_ty_var(self.span);
814 self.types.insert(proj.def_id, (infer_ty, proj.args));
815 for (pred, pred_span) in self
817 .cx()
818 .explicit_item_bounds(proj.def_id)
819 .iter_instantiated_copied(self.cx(), proj.args)
820 {
821 let pred = pred.fold_with(self);
822 let pred = self.ocx.normalize(
823 &ObligationCause::misc(self.span, self.body_id),
824 self.param_env,
825 pred,
826 );
827
828 self.ocx.register_obligation(traits::Obligation::new(
829 self.cx(),
830 ObligationCause::new(
831 self.span,
832 self.body_id,
833 ObligationCauseCode::WhereClause(proj.def_id, pred_span),
834 ),
835 self.param_env,
836 pred,
837 ));
838 }
839 infer_ty
840 } else {
841 ty.super_fold_with(self)
842 }
843 }
844}
845
846struct RemapHiddenTyRegions<'tcx> {
847 tcx: TyCtxt<'tcx>,
848 map: FxIndexMap<ty::Region<'tcx>, ty::Region<'tcx>>,
851 num_trait_args: usize,
852 num_impl_args: usize,
853 def_id: DefId,
855 impl_m_def_id: DefId,
857 ty: Ty<'tcx>,
859 return_span: Span,
861}
862
863impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> {
864 type Error = ErrorGuaranteed;
865
866 fn cx(&self) -> TyCtxt<'tcx> {
867 self.tcx
868 }
869
870 fn try_fold_region(
871 &mut self,
872 region: ty::Region<'tcx>,
873 ) -> Result<ty::Region<'tcx>, Self::Error> {
874 match region.kind() {
875 ty::ReBound(..) | ty::ReStatic | ty::ReError(_) => return Ok(region),
877 ty::ReLateParam(_) => {}
879 ty::ReEarlyParam(ebr) => {
882 if ebr.index as usize >= self.num_impl_args {
883 } else {
885 return Ok(region);
886 }
887 }
888 ty::ReVar(_) | ty::RePlaceholder(_) | ty::ReErased => unreachable!(
889 "should not have leaked vars or placeholders into hidden type of RPITIT"
890 ),
891 }
892
893 let e = if let Some(id_region) = self.map.get(®ion) {
894 if let ty::ReEarlyParam(e) = id_region.kind() {
895 e
896 } else {
897 bug!(
898 "expected to map region {region} to early-bound identity region, but got {id_region}"
899 );
900 }
901 } else {
902 let guar = match region.opt_param_def_id(self.tcx, self.impl_m_def_id) {
903 Some(def_id) => {
904 let return_span = if let ty::Alias(ty::Opaque, opaque_ty) = self.ty.kind() {
905 self.tcx.def_span(opaque_ty.def_id)
906 } else {
907 self.return_span
908 };
909 self.tcx
910 .dcx()
911 .struct_span_err(
912 return_span,
913 "return type captures more lifetimes than trait definition",
914 )
915 .with_span_label(self.tcx.def_span(def_id), "this lifetime was captured")
916 .with_span_note(
917 self.tcx.def_span(self.def_id),
918 "hidden type must only reference lifetimes captured by this impl trait",
919 )
920 .with_note(format!("hidden type inferred to be `{}`", self.ty))
921 .emit()
922 }
923 None => {
924 self.tcx.dcx().bug("should've been able to remap region");
929 }
930 };
931 return Err(guar);
932 };
933
934 Ok(ty::Region::new_early_param(
935 self.tcx,
936 ty::EarlyParamRegion {
937 name: e.name,
938 index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32,
939 },
940 ))
941 }
942}
943
944fn get_self_string<'tcx, P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> String
947where
948 P: Fn(Ty<'tcx>) -> bool,
949{
950 if is_self_ty(self_arg_ty) {
951 "self".to_owned()
952 } else if let ty::Ref(_, ty, mutbl) = self_arg_ty.kind()
953 && is_self_ty(*ty)
954 {
955 match mutbl {
956 hir::Mutability::Not => "&self".to_owned(),
957 hir::Mutability::Mut => "&mut self".to_owned(),
958 }
959 } else {
960 format!("self: {self_arg_ty}")
961 }
962}
963
964fn report_trait_method_mismatch<'tcx>(
965 infcx: &InferCtxt<'tcx>,
966 mut cause: ObligationCause<'tcx>,
967 param_env: ty::ParamEnv<'tcx>,
968 terr: TypeError<'tcx>,
969 (trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>),
970 (impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>),
971 impl_trait_ref: ty::TraitRef<'tcx>,
972) -> ErrorGuaranteed {
973 let tcx = infcx.tcx;
974 let (impl_err_span, trait_err_span) =
975 extract_spans_for_error_reporting(infcx, terr, &cause, impl_m, trait_m);
976
977 let mut diag = struct_span_code_err!(
978 tcx.dcx(),
979 impl_err_span,
980 E0053,
981 "method `{}` has an incompatible type for trait",
982 trait_m.name()
983 );
984 match &terr {
985 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
986 if trait_m.is_method() =>
987 {
988 let ty = trait_sig.inputs()[0];
989 let sugg = get_self_string(ty, |ty| ty == impl_trait_ref.self_ty());
990
991 let (sig, body) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
995 let span = tcx
996 .hir_body_param_idents(body)
997 .zip(sig.decl.inputs.iter())
998 .map(|(param_ident, ty)| {
999 if let Some(param_ident) = param_ident {
1000 param_ident.span.to(ty.span)
1001 } else {
1002 ty.span
1003 }
1004 })
1005 .next()
1006 .unwrap_or(impl_err_span);
1007
1008 diag.span_suggestion_verbose(
1009 span,
1010 "change the self-receiver type to match the trait",
1011 sugg,
1012 Applicability::MachineApplicable,
1013 );
1014 }
1015 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
1016 if trait_sig.inputs().len() == *i {
1017 if let ImplItemKind::Fn(sig, _) =
1020 &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).kind
1021 && !sig.header.asyncness.is_async()
1022 {
1023 let msg = "change the output type to match the trait";
1024 let ap = Applicability::MachineApplicable;
1025 match sig.decl.output {
1026 hir::FnRetTy::DefaultReturn(sp) => {
1027 let sugg = format!(" -> {}", trait_sig.output());
1028 diag.span_suggestion_verbose(sp, msg, sugg, ap);
1029 }
1030 hir::FnRetTy::Return(hir_ty) => {
1031 let sugg = trait_sig.output();
1032 diag.span_suggestion_verbose(hir_ty.span, msg, sugg, ap);
1033 }
1034 };
1035 };
1036 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
1037 diag.span_suggestion_verbose(
1038 impl_err_span,
1039 "change the parameter type to match the trait",
1040 trait_ty,
1041 Applicability::MachineApplicable,
1042 );
1043 }
1044 }
1045 _ => {}
1046 }
1047
1048 cause.span = impl_err_span;
1049 infcx.err_ctxt().note_type_err(
1050 &mut diag,
1051 &cause,
1052 trait_err_span.map(|sp| (sp, Cow::from("type in trait"), false)),
1053 Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound {
1054 expected: ty::Binder::dummy(trait_sig),
1055 found: ty::Binder::dummy(impl_sig),
1056 }))),
1057 terr,
1058 false,
1059 None,
1060 );
1061
1062 diag.emit()
1063}
1064
1065fn check_region_bounds_on_impl_item<'tcx>(
1066 tcx: TyCtxt<'tcx>,
1067 impl_m: ty::AssocItem,
1068 trait_m: ty::AssocItem,
1069 delay: bool,
1070) -> Result<(), ErrorGuaranteed> {
1071 let impl_generics = tcx.generics_of(impl_m.def_id);
1072 let impl_params = impl_generics.own_counts().lifetimes;
1073
1074 let trait_generics = tcx.generics_of(trait_m.def_id);
1075 let trait_params = trait_generics.own_counts().lifetimes;
1076
1077 debug!(?trait_generics, ?impl_generics);
1078
1079 if trait_params == impl_params {
1089 return Ok(());
1090 }
1091
1092 if !delay && let Some(guar) = check_region_late_boundedness(tcx, impl_m, trait_m) {
1093 return Err(guar);
1094 }
1095
1096 let span = tcx
1097 .hir_get_generics(impl_m.def_id.expect_local())
1098 .expect("expected impl item to have generics or else we can't compare them")
1099 .span;
1100
1101 let mut generics_span = None;
1102 let mut bounds_span = vec![];
1103 let mut where_span = None;
1104
1105 if let Some(trait_node) = tcx.hir_get_if_local(trait_m.def_id)
1106 && let Some(trait_generics) = trait_node.generics()
1107 {
1108 generics_span = Some(trait_generics.span);
1109 for p in trait_generics.predicates {
1112 match p.kind {
1113 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1114 bounds,
1115 ..
1116 })
1117 | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1118 bounds,
1119 ..
1120 }) => {
1121 for b in *bounds {
1122 if let hir::GenericBound::Outlives(lt) = b {
1123 bounds_span.push(lt.ident.span);
1124 }
1125 }
1126 }
1127 _ => {}
1128 }
1129 }
1130 if let Some(impl_node) = tcx.hir_get_if_local(impl_m.def_id)
1131 && let Some(impl_generics) = impl_node.generics()
1132 {
1133 let mut impl_bounds = 0;
1134 for p in impl_generics.predicates {
1135 match p.kind {
1136 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1137 bounds,
1138 ..
1139 })
1140 | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1141 bounds,
1142 ..
1143 }) => {
1144 for b in *bounds {
1145 if let hir::GenericBound::Outlives(_) = b {
1146 impl_bounds += 1;
1147 }
1148 }
1149 }
1150 _ => {}
1151 }
1152 }
1153 if impl_bounds == bounds_span.len() {
1154 bounds_span = vec![];
1155 } else if impl_generics.has_where_clause_predicates {
1156 where_span = Some(impl_generics.where_clause_span);
1157 }
1158 }
1159 }
1160
1161 let reported = tcx
1162 .dcx()
1163 .create_err(LifetimesOrBoundsMismatchOnTrait {
1164 span,
1165 item_kind: impl_m.descr(),
1166 ident: impl_m.ident(tcx),
1167 generics_span,
1168 bounds_span,
1169 where_span,
1170 })
1171 .emit_unless_delay(delay);
1172
1173 Err(reported)
1174}
1175
1176#[allow(unused)]
1177enum LateEarlyMismatch<'tcx> {
1178 EarlyInImpl(DefId, DefId, ty::Region<'tcx>),
1179 LateInImpl(DefId, DefId, ty::Region<'tcx>),
1180}
1181
1182fn check_region_late_boundedness<'tcx>(
1183 tcx: TyCtxt<'tcx>,
1184 impl_m: ty::AssocItem,
1185 trait_m: ty::AssocItem,
1186) -> Option<ErrorGuaranteed> {
1187 if !impl_m.is_fn() {
1188 return None;
1189 }
1190
1191 let (infcx, param_env) = tcx
1192 .infer_ctxt()
1193 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, impl_m.def_id));
1194
1195 let impl_m_args = infcx.fresh_args_for_item(DUMMY_SP, impl_m.def_id);
1196 let impl_m_sig = tcx.fn_sig(impl_m.def_id).instantiate(tcx, impl_m_args);
1197 let impl_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, impl_m_sig);
1198
1199 let trait_m_args = infcx.fresh_args_for_item(DUMMY_SP, trait_m.def_id);
1200 let trait_m_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_args);
1201 let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_m_sig);
1202
1203 let ocx = ObligationCtxt::new(&infcx);
1204
1205 let Ok(()) = ocx.eq(
1210 &ObligationCause::dummy(),
1211 param_env,
1212 ty::Binder::dummy(trait_m_sig),
1213 ty::Binder::dummy(impl_m_sig),
1214 ) else {
1215 return None;
1216 };
1217
1218 let errors = ocx.select_where_possible();
1219 if !errors.is_empty() {
1220 return None;
1221 }
1222
1223 let mut mismatched = vec![];
1224
1225 let impl_generics = tcx.generics_of(impl_m.def_id);
1226 for (id_arg, arg) in
1227 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, impl_m.def_id), impl_m_args)
1228 {
1229 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1230 && let ty::ReVar(vid) = r.kind()
1231 && let r = infcx
1232 .inner
1233 .borrow_mut()
1234 .unwrap_region_constraints()
1235 .opportunistic_resolve_var(tcx, vid)
1236 && let ty::ReLateParam(ty::LateParamRegion {
1237 kind: ty::LateParamRegionKind::Named(trait_param_def_id),
1238 ..
1239 }) = r.kind()
1240 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1241 {
1242 mismatched.push(LateEarlyMismatch::EarlyInImpl(
1243 impl_generics.region_param(ebr, tcx).def_id,
1244 trait_param_def_id,
1245 id_arg.expect_region(),
1246 ));
1247 }
1248 }
1249
1250 let trait_generics = tcx.generics_of(trait_m.def_id);
1251 for (id_arg, arg) in
1252 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, trait_m.def_id), trait_m_args)
1253 {
1254 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1255 && let ty::ReVar(vid) = r.kind()
1256 && let r = infcx
1257 .inner
1258 .borrow_mut()
1259 .unwrap_region_constraints()
1260 .opportunistic_resolve_var(tcx, vid)
1261 && let ty::ReLateParam(ty::LateParamRegion {
1262 kind: ty::LateParamRegionKind::Named(impl_param_def_id),
1263 ..
1264 }) = r.kind()
1265 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1266 {
1267 mismatched.push(LateEarlyMismatch::LateInImpl(
1268 impl_param_def_id,
1269 trait_generics.region_param(ebr, tcx).def_id,
1270 id_arg.expect_region(),
1271 ));
1272 }
1273 }
1274
1275 if mismatched.is_empty() {
1276 return None;
1277 }
1278
1279 let spans: Vec<_> = mismatched
1280 .iter()
1281 .map(|param| {
1282 let (LateEarlyMismatch::EarlyInImpl(impl_param_def_id, ..)
1283 | LateEarlyMismatch::LateInImpl(impl_param_def_id, ..)) = param;
1284 tcx.def_span(impl_param_def_id)
1285 })
1286 .collect();
1287
1288 let mut diag = tcx
1289 .dcx()
1290 .struct_span_err(spans, "lifetime parameters do not match the trait definition")
1291 .with_note("lifetime parameters differ in whether they are early- or late-bound")
1292 .with_code(E0195);
1293 for mismatch in mismatched {
1294 match mismatch {
1295 LateEarlyMismatch::EarlyInImpl(
1296 impl_param_def_id,
1297 trait_param_def_id,
1298 early_bound_region,
1299 ) => {
1300 let mut multispan = MultiSpan::from_spans(vec![
1301 tcx.def_span(impl_param_def_id),
1302 tcx.def_span(trait_param_def_id),
1303 ]);
1304 multispan
1305 .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1306 multispan
1307 .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1308 multispan.push_span_label(
1309 tcx.def_span(impl_param_def_id),
1310 format!("`{}` is early-bound", tcx.item_name(impl_param_def_id)),
1311 );
1312 multispan.push_span_label(
1313 tcx.def_span(trait_param_def_id),
1314 format!("`{}` is late-bound", tcx.item_name(trait_param_def_id)),
1315 );
1316 if let Some(span) =
1317 find_region_in_predicates(tcx, impl_m.def_id, early_bound_region)
1318 {
1319 multispan.push_span_label(
1320 span,
1321 format!(
1322 "this lifetime bound makes `{}` early-bound",
1323 tcx.item_name(impl_param_def_id)
1324 ),
1325 );
1326 }
1327 diag.span_note(
1328 multispan,
1329 format!(
1330 "`{}` differs between the trait and impl",
1331 tcx.item_name(impl_param_def_id)
1332 ),
1333 );
1334 }
1335 LateEarlyMismatch::LateInImpl(
1336 impl_param_def_id,
1337 trait_param_def_id,
1338 early_bound_region,
1339 ) => {
1340 let mut multispan = MultiSpan::from_spans(vec![
1341 tcx.def_span(impl_param_def_id),
1342 tcx.def_span(trait_param_def_id),
1343 ]);
1344 multispan
1345 .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1346 multispan
1347 .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1348 multispan.push_span_label(
1349 tcx.def_span(impl_param_def_id),
1350 format!("`{}` is late-bound", tcx.item_name(impl_param_def_id)),
1351 );
1352 multispan.push_span_label(
1353 tcx.def_span(trait_param_def_id),
1354 format!("`{}` is early-bound", tcx.item_name(trait_param_def_id)),
1355 );
1356 if let Some(span) =
1357 find_region_in_predicates(tcx, trait_m.def_id, early_bound_region)
1358 {
1359 multispan.push_span_label(
1360 span,
1361 format!(
1362 "this lifetime bound makes `{}` early-bound",
1363 tcx.item_name(trait_param_def_id)
1364 ),
1365 );
1366 }
1367 diag.span_note(
1368 multispan,
1369 format!(
1370 "`{}` differs between the trait and impl",
1371 tcx.item_name(impl_param_def_id)
1372 ),
1373 );
1374 }
1375 }
1376 }
1377
1378 Some(diag.emit())
1379}
1380
1381fn find_region_in_predicates<'tcx>(
1382 tcx: TyCtxt<'tcx>,
1383 def_id: DefId,
1384 early_bound_region: ty::Region<'tcx>,
1385) -> Option<Span> {
1386 for (pred, span) in tcx.explicit_predicates_of(def_id).instantiate_identity(tcx) {
1387 if pred.visit_with(&mut FindRegion(early_bound_region)).is_break() {
1388 return Some(span);
1389 }
1390 }
1391
1392 struct FindRegion<'tcx>(ty::Region<'tcx>);
1393 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindRegion<'tcx> {
1394 type Result = ControlFlow<()>;
1395 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
1396 if r == self.0 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
1397 }
1398 }
1399
1400 None
1401}
1402
1403#[instrument(level = "debug", skip(infcx))]
1404fn extract_spans_for_error_reporting<'tcx>(
1405 infcx: &infer::InferCtxt<'tcx>,
1406 terr: TypeError<'_>,
1407 cause: &ObligationCause<'tcx>,
1408 impl_m: ty::AssocItem,
1409 trait_m: ty::AssocItem,
1410) -> (Span, Option<Span>) {
1411 let tcx = infcx.tcx;
1412 let mut impl_args = {
1413 let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1414 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1415 };
1416
1417 let trait_args = trait_m.def_id.as_local().map(|def_id| {
1418 let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
1419 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1420 });
1421
1422 match terr {
1423 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1424 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1425 }
1426 _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
1427 }
1428}
1429
1430fn compare_self_type<'tcx>(
1431 tcx: TyCtxt<'tcx>,
1432 impl_m: ty::AssocItem,
1433 trait_m: ty::AssocItem,
1434 impl_trait_ref: ty::TraitRef<'tcx>,
1435 delay: bool,
1436) -> Result<(), ErrorGuaranteed> {
1437 let self_string = |method: ty::AssocItem| {
1446 let untransformed_self_ty = match method.container {
1447 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1448 impl_trait_ref.self_ty()
1449 }
1450 ty::AssocContainer::Trait => tcx.types.self_param,
1451 };
1452 let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().input(0);
1453 let (infcx, param_env) = tcx
1454 .infer_ctxt()
1455 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
1456 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1457 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1458 get_self_string(self_arg_ty, can_eq_self)
1459 };
1460
1461 match (trait_m.is_method(), impl_m.is_method()) {
1462 (false, false) | (true, true) => {}
1463
1464 (false, true) => {
1465 let self_descr = self_string(impl_m);
1466 let impl_m_span = tcx.def_span(impl_m.def_id);
1467 let mut err = struct_span_code_err!(
1468 tcx.dcx(),
1469 impl_m_span,
1470 E0185,
1471 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1472 trait_m.name(),
1473 self_descr
1474 );
1475 err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
1476 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1477 err.span_label(span, format!("trait method declared without `{self_descr}`"));
1478 } else {
1479 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1480 }
1481 return Err(err.emit_unless_delay(delay));
1482 }
1483
1484 (true, false) => {
1485 let self_descr = self_string(trait_m);
1486 let impl_m_span = tcx.def_span(impl_m.def_id);
1487 let mut err = struct_span_code_err!(
1488 tcx.dcx(),
1489 impl_m_span,
1490 E0186,
1491 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1492 trait_m.name(),
1493 self_descr
1494 );
1495 err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
1496 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1497 err.span_label(span, format!("`{self_descr}` used in trait"));
1498 } else {
1499 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1500 }
1501
1502 return Err(err.emit_unless_delay(delay));
1503 }
1504 }
1505
1506 Ok(())
1507}
1508
1509fn compare_number_of_generics<'tcx>(
1531 tcx: TyCtxt<'tcx>,
1532 impl_: ty::AssocItem,
1533 trait_: ty::AssocItem,
1534 delay: bool,
1535) -> Result<(), ErrorGuaranteed> {
1536 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1537 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1538
1539 if (trait_own_counts.types + trait_own_counts.consts)
1543 == (impl_own_counts.types + impl_own_counts.consts)
1544 {
1545 return Ok(());
1546 }
1547
1548 if trait_.is_impl_trait_in_trait() {
1553 tcx.dcx()
1556 .bug("errors comparing numbers of generics of trait/impl functions were not emitted");
1557 }
1558
1559 let matchings = [
1560 ("type", trait_own_counts.types, impl_own_counts.types),
1561 ("const", trait_own_counts.consts, impl_own_counts.consts),
1562 ];
1563
1564 let item_kind = impl_.descr();
1565
1566 let mut err_occurred = None;
1567 for (kind, trait_count, impl_count) in matchings {
1568 if impl_count != trait_count {
1569 let arg_spans = |item: &ty::AssocItem, generics: &hir::Generics<'_>| {
1570 let mut spans = generics
1571 .params
1572 .iter()
1573 .filter(|p| match p.kind {
1574 hir::GenericParamKind::Lifetime {
1575 kind: hir::LifetimeParamKind::Elided(_),
1576 } => {
1577 !item.is_fn()
1580 }
1581 _ => true,
1582 })
1583 .map(|p| p.span)
1584 .collect::<Vec<Span>>();
1585 if spans.is_empty() {
1586 spans = vec![generics.span]
1587 }
1588 spans
1589 };
1590 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1591 let trait_item = tcx.hir_expect_trait_item(def_id);
1592 let arg_spans: Vec<Span> = arg_spans(&trait_, trait_item.generics);
1593 let impl_trait_spans: Vec<Span> = trait_item
1594 .generics
1595 .params
1596 .iter()
1597 .filter_map(|p| match p.kind {
1598 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1599 _ => None,
1600 })
1601 .collect();
1602 (Some(arg_spans), impl_trait_spans)
1603 } else {
1604 let trait_span = tcx.hir_span_if_local(trait_.def_id);
1605 (trait_span.map(|s| vec![s]), vec![])
1606 };
1607
1608 let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
1609 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1610 .generics
1611 .params
1612 .iter()
1613 .filter_map(|p| match p.kind {
1614 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1615 _ => None,
1616 })
1617 .collect();
1618 let spans = arg_spans(&impl_, impl_item.generics);
1619 let span = spans.first().copied();
1620
1621 let mut err = tcx.dcx().struct_span_err(
1622 spans,
1623 format!(
1624 "{} `{}` has {} {kind} parameter{} but its trait \
1625 declaration has {} {kind} parameter{}",
1626 item_kind,
1627 trait_.name(),
1628 impl_count,
1629 pluralize!(impl_count),
1630 trait_count,
1631 pluralize!(trait_count),
1632 kind = kind,
1633 ),
1634 );
1635 err.code(E0049);
1636
1637 let msg =
1638 format!("expected {trait_count} {kind} parameter{}", pluralize!(trait_count),);
1639 if let Some(spans) = trait_spans {
1640 let mut spans = spans.iter();
1641 if let Some(span) = spans.next() {
1642 err.span_label(*span, msg);
1643 }
1644 for span in spans {
1645 err.span_label(*span, "");
1646 }
1647 } else {
1648 err.span_label(tcx.def_span(trait_.def_id), msg);
1649 }
1650
1651 if let Some(span) = span {
1652 err.span_label(
1653 span,
1654 format!("found {} {} parameter{}", impl_count, kind, pluralize!(impl_count),),
1655 );
1656 }
1657
1658 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1659 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1660 }
1661
1662 let reported = err.emit_unless_delay(delay);
1663 err_occurred = Some(reported);
1664 }
1665 }
1666
1667 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1668}
1669
1670fn compare_number_of_method_arguments<'tcx>(
1671 tcx: TyCtxt<'tcx>,
1672 impl_m: ty::AssocItem,
1673 trait_m: ty::AssocItem,
1674 delay: bool,
1675) -> Result<(), ErrorGuaranteed> {
1676 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1677 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1678 let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1679 let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1680
1681 if trait_number_args != impl_number_args {
1682 let trait_span = trait_m
1683 .def_id
1684 .as_local()
1685 .and_then(|def_id| {
1686 let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
1687 let pos = trait_number_args.saturating_sub(1);
1688 trait_m_sig.decl.inputs.get(pos).map(|arg| {
1689 if pos == 0 {
1690 arg.span
1691 } else {
1692 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1693 }
1694 })
1695 })
1696 .or_else(|| tcx.hir_span_if_local(trait_m.def_id));
1697
1698 let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1699 let pos = impl_number_args.saturating_sub(1);
1700 let impl_span = impl_m_sig
1701 .decl
1702 .inputs
1703 .get(pos)
1704 .map(|arg| {
1705 if pos == 0 {
1706 arg.span
1707 } else {
1708 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1709 }
1710 })
1711 .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1712
1713 let mut err = struct_span_code_err!(
1714 tcx.dcx(),
1715 impl_span,
1716 E0050,
1717 "method `{}` has {} but the declaration in trait `{}` has {}",
1718 trait_m.name(),
1719 potentially_plural_count(impl_number_args, "parameter"),
1720 tcx.def_path_str(trait_m.def_id),
1721 trait_number_args
1722 );
1723
1724 if let Some(trait_span) = trait_span {
1725 err.span_label(
1726 trait_span,
1727 format!(
1728 "trait requires {}",
1729 potentially_plural_count(trait_number_args, "parameter")
1730 ),
1731 );
1732 } else {
1733 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1734 }
1735
1736 err.span_label(
1737 impl_span,
1738 format!(
1739 "expected {}, found {}",
1740 potentially_plural_count(trait_number_args, "parameter"),
1741 impl_number_args
1742 ),
1743 );
1744
1745 return Err(err.emit_unless_delay(delay));
1746 }
1747
1748 Ok(())
1749}
1750
1751fn compare_synthetic_generics<'tcx>(
1752 tcx: TyCtxt<'tcx>,
1753 impl_m: ty::AssocItem,
1754 trait_m: ty::AssocItem,
1755 delay: bool,
1756) -> Result<(), ErrorGuaranteed> {
1757 let mut error_found = None;
1763 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1764 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1765 let impl_m_type_params =
1766 impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
1767 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1768 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1769 });
1770 let trait_m_type_params =
1771 trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
1772 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1773 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1774 });
1775 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1776 iter::zip(impl_m_type_params, trait_m_type_params)
1777 {
1778 if impl_synthetic != trait_synthetic {
1779 let impl_def_id = impl_def_id.expect_local();
1780 let impl_span = tcx.def_span(impl_def_id);
1781 let trait_span = tcx.def_span(trait_def_id);
1782 let mut err = struct_span_code_err!(
1783 tcx.dcx(),
1784 impl_span,
1785 E0643,
1786 "method `{}` has incompatible signature for trait",
1787 trait_m.name()
1788 );
1789 err.span_label(trait_span, "declaration in trait here");
1790 if impl_synthetic {
1791 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1794 let _: Option<_> = try {
1795 let new_name = tcx.opt_item_name(trait_def_id)?;
1799 let trait_m = trait_m.def_id.as_local()?;
1800 let trait_m = tcx.hir_expect_trait_item(trait_m);
1801
1802 let impl_m = impl_m.def_id.as_local()?;
1803 let impl_m = tcx.hir_expect_impl_item(impl_m);
1804
1805 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1808 let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
1810 let new_generics =
1812 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1813
1814 err.multipart_suggestion(
1815 "try changing the `impl Trait` argument to a generic parameter",
1816 vec![
1817 (impl_span, new_name.to_string()),
1819 (generics_span, new_generics),
1823 ],
1824 Applicability::MaybeIncorrect,
1825 );
1826 };
1827 } else {
1828 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1831 let _: Option<_> = try {
1832 let impl_m = impl_m.def_id.as_local()?;
1833 let impl_m = tcx.hir_expect_impl_item(impl_m);
1834 let (sig, _) = impl_m.expect_fn();
1835 let input_tys = sig.decl.inputs;
1836
1837 struct Visitor(hir::def_id::LocalDefId);
1838 impl<'v> intravisit::Visitor<'v> for Visitor {
1839 type Result = ControlFlow<Span>;
1840 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
1841 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
1842 && let Res::Def(DefKind::TyParam, def_id) = path.res
1843 && def_id == self.0.to_def_id()
1844 {
1845 ControlFlow::Break(ty.span)
1846 } else {
1847 intravisit::walk_ty(self, ty)
1848 }
1849 }
1850 }
1851
1852 let span = input_tys
1853 .iter()
1854 .find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
1855
1856 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
1857 let bounds = bounds.first()?.span().to(bounds.last()?.span());
1858 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1859
1860 err.multipart_suggestion(
1861 "try removing the generic parameter and using `impl Trait` instead",
1862 vec![
1863 (impl_m.generics.span, String::new()),
1865 (span, format!("impl {bounds}")),
1867 ],
1868 Applicability::MaybeIncorrect,
1869 );
1870 };
1871 }
1872 error_found = Some(err.emit_unless_delay(delay));
1873 }
1874 }
1875 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1876}
1877
1878fn compare_generic_param_kinds<'tcx>(
1904 tcx: TyCtxt<'tcx>,
1905 impl_item: ty::AssocItem,
1906 trait_item: ty::AssocItem,
1907 delay: bool,
1908) -> Result<(), ErrorGuaranteed> {
1909 assert_eq!(impl_item.as_tag(), trait_item.as_tag());
1910
1911 let ty_const_params_of = |def_id| {
1912 tcx.generics_of(def_id).own_params.iter().filter(|param| {
1913 matches!(
1914 param.kind,
1915 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1916 )
1917 })
1918 };
1919
1920 for (param_impl, param_trait) in
1921 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1922 {
1923 use GenericParamDefKind::*;
1924 if match (¶m_impl.kind, ¶m_trait.kind) {
1925 (Const { .. }, Const { .. })
1926 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1927 {
1928 true
1929 }
1930 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1931 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1934 (Lifetime { .. }, _) | (_, Lifetime { .. }) => {
1935 bug!("lifetime params are expected to be filtered by `ty_const_params_of`")
1936 }
1937 } {
1938 let param_impl_span = tcx.def_span(param_impl.def_id);
1939 let param_trait_span = tcx.def_span(param_trait.def_id);
1940
1941 let mut err = struct_span_code_err!(
1942 tcx.dcx(),
1943 param_impl_span,
1944 E0053,
1945 "{} `{}` has an incompatible generic parameter for trait `{}`",
1946 impl_item.descr(),
1947 trait_item.name(),
1948 &tcx.def_path_str(tcx.parent(trait_item.def_id))
1949 );
1950
1951 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1952 Const { .. } => {
1953 format!(
1954 "{} const parameter of type `{}`",
1955 prefix,
1956 tcx.type_of(param.def_id).instantiate_identity()
1957 )
1958 }
1959 Type { .. } => format!("{prefix} type parameter"),
1960 Lifetime { .. } => span_bug!(
1961 tcx.def_span(param.def_id),
1962 "lifetime params are expected to be filtered by `ty_const_params_of`"
1963 ),
1964 };
1965
1966 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1967 err.span_label(trait_header_span, "");
1968 err.span_label(param_trait_span, make_param_message("expected", param_trait));
1969
1970 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1971 err.span_label(impl_header_span, "");
1972 err.span_label(param_impl_span, make_param_message("found", param_impl));
1973
1974 let reported = err.emit_unless_delay(delay);
1975 return Err(reported);
1976 }
1977 }
1978
1979 Ok(())
1980}
1981
1982fn compare_impl_const<'tcx>(
1983 tcx: TyCtxt<'tcx>,
1984 impl_const_item: ty::AssocItem,
1985 trait_const_item: ty::AssocItem,
1986 impl_trait_ref: ty::TraitRef<'tcx>,
1987) -> Result<(), ErrorGuaranteed> {
1988 compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
1989 compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
1990 check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
1991 compare_const_predicate_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
1992}
1993
1994#[instrument(level = "debug", skip(tcx))]
1998fn compare_const_predicate_entailment<'tcx>(
1999 tcx: TyCtxt<'tcx>,
2000 impl_ct: ty::AssocItem,
2001 trait_ct: ty::AssocItem,
2002 impl_trait_ref: ty::TraitRef<'tcx>,
2003) -> Result<(), ErrorGuaranteed> {
2004 let impl_ct_def_id = impl_ct.def_id.expect_local();
2005 let impl_ct_span = tcx.def_span(impl_ct_def_id);
2006
2007 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto(
2013 tcx,
2014 impl_ct.container_id(tcx),
2015 impl_trait_ref.args,
2016 );
2017
2018 let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
2021
2022 let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
2023 let code = ObligationCauseCode::CompareImplItem {
2024 impl_item_def_id: impl_ct_def_id,
2025 trait_item_def_id: trait_ct.def_id,
2026 kind: impl_ct.kind,
2027 };
2028 let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());
2029
2030 let impl_ct_predicates = tcx.predicates_of(impl_ct.def_id);
2031 let trait_ct_predicates = tcx.predicates_of(trait_ct.def_id);
2032
2033 let impl_predicates = tcx.predicates_of(impl_ct_predicates.parent.unwrap());
2036 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2037 hybrid_preds.extend(
2038 trait_ct_predicates
2039 .instantiate_own(tcx, trait_to_impl_args)
2040 .map(|(predicate, _)| predicate),
2041 );
2042
2043 let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
2044 let param_env = traits::normalize_param_env_or_error(
2045 tcx,
2046 param_env,
2047 ObligationCause::misc(impl_ct_span, impl_ct_def_id),
2048 );
2049
2050 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2051 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2052
2053 let impl_ct_own_bounds = impl_ct_predicates.instantiate_own_identity();
2054 for (predicate, span) in impl_ct_own_bounds {
2055 let cause = ObligationCause::misc(span, impl_ct_def_id);
2056 let predicate = ocx.normalize(&cause, param_env, predicate);
2057
2058 let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
2059 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2060 }
2061
2062 let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
2064 debug!(?impl_ty);
2065
2066 let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
2067 debug!(?trait_ty);
2068
2069 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
2070
2071 if let Err(terr) = err {
2072 debug!(?impl_ty, ?trait_ty);
2073
2074 let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
2076 cause.span = ty.span;
2077
2078 let mut diag = struct_span_code_err!(
2079 tcx.dcx(),
2080 cause.span,
2081 E0326,
2082 "implemented const `{}` has an incompatible type for trait",
2083 trait_ct.name()
2084 );
2085
2086 let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
2087 let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
2089 ty.span
2090 });
2091
2092 infcx.err_ctxt().note_type_err(
2093 &mut diag,
2094 &cause,
2095 trait_c_span.map(|span| (span, Cow::from("type in trait"), false)),
2096 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2097 expected: trait_ty.into(),
2098 found: impl_ty.into(),
2099 }))),
2100 terr,
2101 false,
2102 None,
2103 );
2104 return Err(diag.emit());
2105 };
2106
2107 let errors = ocx.select_all_or_error();
2110 if !errors.is_empty() {
2111 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2112 }
2113
2114 ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env, [])
2115}
2116
2117#[instrument(level = "debug", skip(tcx))]
2118fn compare_impl_ty<'tcx>(
2119 tcx: TyCtxt<'tcx>,
2120 impl_ty: ty::AssocItem,
2121 trait_ty: ty::AssocItem,
2122 impl_trait_ref: ty::TraitRef<'tcx>,
2123) -> Result<(), ErrorGuaranteed> {
2124 compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2125 compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2126 check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2127 compare_type_predicate_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2128 check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2129}
2130
2131#[instrument(level = "debug", skip(tcx))]
2134fn compare_type_predicate_entailment<'tcx>(
2135 tcx: TyCtxt<'tcx>,
2136 impl_ty: ty::AssocItem,
2137 trait_ty: ty::AssocItem,
2138 impl_trait_ref: ty::TraitRef<'tcx>,
2139) -> Result<(), ErrorGuaranteed> {
2140 let impl_def_id = impl_ty.container_id(tcx);
2141 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2142 tcx,
2143 impl_def_id,
2144 impl_trait_ref.args,
2145 );
2146
2147 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
2148 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
2149
2150 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own_identity();
2151 if impl_ty_own_bounds.len() == 0 {
2153 return Ok(());
2155 }
2156
2157 let impl_ty_def_id = impl_ty.def_id.expect_local();
2161 debug!(?trait_to_impl_args);
2162
2163 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
2166 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2167 hybrid_preds.extend(
2168 trait_ty_predicates
2169 .instantiate_own(tcx, trait_to_impl_args)
2170 .map(|(predicate, _)| predicate),
2171 );
2172 debug!(?hybrid_preds);
2173
2174 let impl_ty_span = tcx.def_span(impl_ty_def_id);
2175 let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2176
2177 let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2178 if is_conditionally_const {
2179 hybrid_preds.extend(
2182 tcx.const_conditions(impl_ty_predicates.parent.unwrap())
2183 .instantiate_identity(tcx)
2184 .into_iter()
2185 .chain(
2186 tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2187 )
2188 .map(|(trait_ref, _)| {
2189 trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2190 }),
2191 );
2192 }
2193
2194 let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
2195 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2196 debug!(caller_bounds=?param_env.caller_bounds());
2197
2198 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2199 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2200
2201 for (predicate, span) in impl_ty_own_bounds {
2202 let cause = ObligationCause::misc(span, impl_ty_def_id);
2203 let predicate = ocx.normalize(&cause, param_env, predicate);
2204
2205 let cause = ObligationCause::new(
2206 span,
2207 impl_ty_def_id,
2208 ObligationCauseCode::CompareImplItem {
2209 impl_item_def_id: impl_ty.def_id.expect_local(),
2210 trait_item_def_id: trait_ty.def_id,
2211 kind: impl_ty.kind,
2212 },
2213 );
2214 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2215 }
2216
2217 if is_conditionally_const {
2218 let impl_ty_own_const_conditions =
2220 tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2221 for (const_condition, span) in impl_ty_own_const_conditions {
2222 let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2223 let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2224
2225 let cause = ObligationCause::new(
2226 span,
2227 impl_ty_def_id,
2228 ObligationCauseCode::CompareImplItem {
2229 impl_item_def_id: impl_ty_def_id,
2230 trait_item_def_id: trait_ty.def_id,
2231 kind: impl_ty.kind,
2232 },
2233 );
2234 ocx.register_obligation(traits::Obligation::new(
2235 tcx,
2236 cause,
2237 param_env,
2238 const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2239 ));
2240 }
2241 }
2242
2243 let errors = ocx.select_all_or_error();
2246 if !errors.is_empty() {
2247 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2248 return Err(reported);
2249 }
2250
2251 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2254}
2255
2256#[instrument(level = "debug", skip(tcx))]
2270pub(super) fn check_type_bounds<'tcx>(
2271 tcx: TyCtxt<'tcx>,
2272 trait_ty: ty::AssocItem,
2273 impl_ty: ty::AssocItem,
2274 impl_trait_ref: ty::TraitRef<'tcx>,
2275) -> Result<(), ErrorGuaranteed> {
2276 tcx.ensure_ok().coherent_trait(impl_trait_ref.def_id)?;
2279
2280 let param_env = tcx.param_env(impl_ty.def_id);
2281 debug!(?param_env);
2282
2283 let container_id = impl_ty.container_id(tcx);
2284 let impl_ty_def_id = impl_ty.def_id.expect_local();
2285 let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2286 let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2287
2288 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2289 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2290
2291 let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2295 tcx.def_span(impl_ty_def_id)
2296 } else {
2297 match tcx.hir_node_by_def_id(impl_ty_def_id) {
2298 hir::Node::TraitItem(hir::TraitItem {
2299 kind: hir::TraitItemKind::Type(_, Some(ty)),
2300 ..
2301 }) => ty.span,
2302 hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2303 item => span_bug!(
2304 tcx.def_span(impl_ty_def_id),
2305 "cannot call `check_type_bounds` on item: {item:?}",
2306 ),
2307 }
2308 };
2309 let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2310
2311 let normalize_cause = ObligationCause::new(
2312 impl_ty_span,
2313 impl_ty_def_id,
2314 ObligationCauseCode::CheckAssociatedTypeBounds {
2315 impl_item_def_id: impl_ty.def_id.expect_local(),
2316 trait_item_def_id: trait_ty.def_id,
2317 },
2318 );
2319 let mk_cause = |span: Span| {
2320 let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2321 ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2322 };
2323
2324 let mut obligations: Vec<_> = util::elaborate(
2325 tcx,
2326 tcx.explicit_item_bounds(trait_ty.def_id).iter_instantiated_copied(tcx, rebased_args).map(
2327 |(concrete_ty_bound, span)| {
2328 debug!(?concrete_ty_bound);
2329 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2330 },
2331 ),
2332 )
2333 .collect();
2334
2335 if tcx.is_conditionally_const(impl_ty_def_id) {
2337 obligations.extend(util::elaborate(
2338 tcx,
2339 tcx.explicit_implied_const_bounds(trait_ty.def_id)
2340 .iter_instantiated_copied(tcx, rebased_args)
2341 .map(|(c, span)| {
2342 traits::Obligation::new(
2343 tcx,
2344 mk_cause(span),
2345 param_env,
2346 c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2347 )
2348 }),
2349 ));
2350 }
2351 debug!(item_bounds=?obligations);
2352
2353 let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2358 for obligation in &mut obligations {
2359 match ocx.deeply_normalize(&normalize_cause, normalize_param_env, obligation.predicate) {
2360 Ok(pred) => obligation.predicate = pred,
2361 Err(e) => {
2362 return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2363 }
2364 }
2365 }
2366
2367 ocx.register_obligations(obligations);
2370 let errors = ocx.select_all_or_error();
2371 if !errors.is_empty() {
2372 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2373 return Err(reported);
2374 }
2375
2376 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2379}
2380
2381fn param_env_with_gat_bounds<'tcx>(
2429 tcx: TyCtxt<'tcx>,
2430 impl_ty: ty::AssocItem,
2431 impl_trait_ref: ty::TraitRef<'tcx>,
2432) -> ty::ParamEnv<'tcx> {
2433 let param_env = tcx.param_env(impl_ty.def_id);
2434 let container_id = impl_ty.container_id(tcx);
2435 let mut predicates = param_env.caller_bounds().to_vec();
2436
2437 let impl_tys_to_install = match impl_ty.kind {
2442 ty::AssocKind::Type {
2443 data:
2444 ty::AssocTypeData::Rpitit(
2445 ty::ImplTraitInTraitData::Impl { fn_def_id }
2446 | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2447 ),
2448 } => tcx
2449 .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2450 .iter()
2451 .map(|def_id| tcx.associated_item(*def_id))
2452 .collect(),
2453 _ => vec![impl_ty],
2454 };
2455
2456 for impl_ty in impl_tys_to_install {
2457 let trait_ty = match impl_ty.container {
2458 ty::AssocContainer::InherentImpl => bug!(),
2459 ty::AssocContainer::Trait => impl_ty,
2460 ty::AssocContainer::TraitImpl(Err(_)) => continue,
2461 ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2462 tcx.associated_item(trait_item_def_id)
2463 }
2464 };
2465
2466 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
2467 smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2468 let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2470 .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2471 GenericParamDefKind::Type { .. } => {
2472 let kind = ty::BoundTyKind::Param(param.def_id);
2473 let bound_var = ty::BoundVariableKind::Ty(kind);
2474 bound_vars.push(bound_var);
2475 Ty::new_bound(
2476 tcx,
2477 ty::INNERMOST,
2478 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2479 )
2480 .into()
2481 }
2482 GenericParamDefKind::Lifetime => {
2483 let kind = ty::BoundRegionKind::Named(param.def_id);
2484 let bound_var = ty::BoundVariableKind::Region(kind);
2485 bound_vars.push(bound_var);
2486 ty::Region::new_bound(
2487 tcx,
2488 ty::INNERMOST,
2489 ty::BoundRegion {
2490 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2491 kind,
2492 },
2493 )
2494 .into()
2495 }
2496 GenericParamDefKind::Const { .. } => {
2497 let bound_var = ty::BoundVariableKind::Const;
2498 bound_vars.push(bound_var);
2499 ty::Const::new_bound(
2500 tcx,
2501 ty::INNERMOST,
2502 ty::BoundConst { var: ty::BoundVar::from_usize(bound_vars.len() - 1) },
2503 )
2504 .into()
2505 }
2506 });
2507 let normalize_impl_ty =
2517 tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args);
2518 let rebased_args =
2519 normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2520 let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2521
2522 match normalize_impl_ty.kind() {
2523 ty::Alias(ty::Projection, proj)
2524 if proj.def_id == trait_ty.def_id && proj.args == rebased_args =>
2525 {
2526 }
2532 _ => predicates.push(
2533 ty::Binder::bind_with_vars(
2534 ty::ProjectionPredicate {
2535 projection_term: ty::AliasTerm::new_from_args(
2536 tcx,
2537 trait_ty.def_id,
2538 rebased_args,
2539 ),
2540 term: normalize_impl_ty.into(),
2541 },
2542 bound_vars,
2543 )
2544 .upcast(tcx),
2545 ),
2546 };
2547 }
2548
2549 ty::ParamEnv::new(tcx.mk_clauses(&predicates))
2550}
2551
2552fn try_report_async_mismatch<'tcx>(
2555 tcx: TyCtxt<'tcx>,
2556 infcx: &InferCtxt<'tcx>,
2557 errors: &[FulfillmentError<'tcx>],
2558 trait_m: ty::AssocItem,
2559 impl_m: ty::AssocItem,
2560 impl_sig: ty::FnSig<'tcx>,
2561) -> Result<(), ErrorGuaranteed> {
2562 if !tcx.asyncness(trait_m.def_id).is_async() {
2563 return Ok(());
2564 }
2565
2566 let ty::Alias(ty::Projection, ty::AliasTy { def_id: async_future_def_id, .. }) =
2567 *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2568 else {
2569 bug!("expected `async fn` to return an RPITIT");
2570 };
2571
2572 for error in errors {
2573 if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2574 && def_id == async_future_def_id
2575 && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2576 && let Some(proj) = proj.no_bound_vars()
2577 && infcx.can_eq(
2578 error.root_obligation.param_env,
2579 proj.term.expect_type(),
2580 impl_sig.output(),
2581 )
2582 {
2583 return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2586 span: tcx.def_span(impl_m.def_id),
2587 method_name: tcx.item_ident(impl_m.def_id),
2588 trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2589 }));
2590 }
2591 }
2592
2593 Ok(())
2594}