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