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::attrs::AttributeKind;
10use rustc_hir::def::{DefKind, Res};
11use rustc_hir::intravisit::VisitorExt;
12use rustc_hir::{self as hir, AmbigArg, GenericParamKind, ImplItemKind, find_attr, intravisit};
13use rustc_infer::infer::{self, BoundRegionConversionTime, InferCtxt, TyCtxtInferExt};
14use rustc_infer::traits::util;
15use rustc_middle::ty::error::{ExpectedFound, TypeError};
16use rustc_middle::ty::{
17 self, BottomUpFolder, GenericArgs, GenericParamDefKind, Generics, Ty, TyCtxt, TypeFoldable,
18 TypeFolder, TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
19 Upcast,
20};
21use rustc_middle::{bug, span_bug};
22use rustc_span::{DUMMY_SP, Span};
23use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
24use rustc_trait_selection::infer::InferCtxtExt;
25use rustc_trait_selection::regions::InferCtxtRegionExt;
26use rustc_trait_selection::traits::{
27 self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
28};
29use tracing::{debug, instrument};
30
31use super::potentially_plural_count;
32use crate::errors::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture};
33
34pub(super) mod refine;
35
36pub(super) fn compare_impl_item(
38 tcx: TyCtxt<'_>,
39 impl_item_def_id: LocalDefId,
40) -> Result<(), ErrorGuaranteed> {
41 let impl_item = tcx.associated_item(impl_item_def_id);
42 let trait_item = tcx.associated_item(impl_item.expect_trait_impl()?);
43 let impl_trait_ref = tcx.impl_trait_ref(impl_item.container_id(tcx)).instantiate_identity();
44 debug!(?impl_trait_ref);
45
46 match impl_item.kind {
47 ty::AssocKind::Fn { .. } => compare_impl_method(tcx, impl_item, trait_item, impl_trait_ref),
48 ty::AssocKind::Type { .. } => compare_impl_ty(tcx, impl_item, trait_item, impl_trait_ref),
49 ty::AssocKind::Const { .. } => {
50 compare_impl_const(tcx, impl_item, trait_item, impl_trait_ref)
51 }
52 }
53}
54
55#[instrument(level = "debug", skip(tcx))]
64fn compare_impl_method<'tcx>(
65 tcx: TyCtxt<'tcx>,
66 impl_m: ty::AssocItem,
67 trait_m: ty::AssocItem,
68 impl_trait_ref: ty::TraitRef<'tcx>,
69) -> Result<(), ErrorGuaranteed> {
70 check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, false)?;
71 compare_method_predicate_entailment(tcx, impl_m, trait_m, impl_trait_ref)?;
72 Ok(())
73}
74
75fn check_method_is_structurally_compatible<'tcx>(
79 tcx: TyCtxt<'tcx>,
80 impl_m: ty::AssocItem,
81 trait_m: ty::AssocItem,
82 impl_trait_ref: ty::TraitRef<'tcx>,
83 delay: bool,
84) -> Result<(), ErrorGuaranteed> {
85 compare_self_type(tcx, impl_m, trait_m, impl_trait_ref, delay)?;
86 compare_number_of_generics(tcx, impl_m, trait_m, delay)?;
87 compare_generic_param_kinds(tcx, impl_m, trait_m, delay)?;
88 compare_number_of_method_arguments(tcx, impl_m, trait_m, delay)?;
89 compare_synthetic_generics(tcx, impl_m, trait_m, delay)?;
90 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, delay)?;
91 Ok(())
92}
93
94#[instrument(level = "debug", skip(tcx, impl_trait_ref))]
173fn compare_method_predicate_entailment<'tcx>(
174 tcx: TyCtxt<'tcx>,
175 impl_m: ty::AssocItem,
176 trait_m: ty::AssocItem,
177 impl_trait_ref: ty::TraitRef<'tcx>,
178) -> Result<(), ErrorGuaranteed> {
179 let impl_m_def_id = impl_m.def_id.expect_local();
185 let impl_m_span = tcx.def_span(impl_m_def_id);
186 let cause = ObligationCause::new(
187 impl_m_span,
188 impl_m_def_id,
189 ObligationCauseCode::CompareImplItem {
190 impl_item_def_id: impl_m_def_id,
191 trait_item_def_id: trait_m.def_id,
192 kind: impl_m.kind,
193 },
194 );
195
196 let impl_def_id = impl_m.container_id(tcx);
198 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
199 tcx,
200 impl_m.container_id(tcx),
201 impl_trait_ref.args,
202 );
203 debug!(?trait_to_impl_args);
204
205 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
206 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
207
208 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
216 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
217 hybrid_preds.extend(
218 trait_m_predicates.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate),
219 );
220
221 let is_conditionally_const = tcx.is_conditionally_const(impl_def_id);
222 if is_conditionally_const {
223 hybrid_preds.extend(
226 tcx.const_conditions(impl_def_id)
227 .instantiate_identity(tcx)
228 .into_iter()
229 .chain(
230 tcx.const_conditions(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args),
231 )
232 .map(|(trait_ref, _)| {
233 trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
234 }),
235 );
236 }
237
238 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
239 let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
240 let param_env = if tcx.next_trait_solver_globally() {
256 traits::deeply_normalize_param_env_ignoring_regions(tcx, param_env, normalize_cause)
257 } else {
258 traits::normalize_param_env_or_error(tcx, param_env, normalize_cause)
259 };
260 debug!(caller_bounds=?param_env.caller_bounds());
261
262 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
263 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
264
265 let impl_m_own_bounds = impl_m_predicates.instantiate_own_identity();
270 for (predicate, span) in impl_m_own_bounds {
271 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
272 let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
273
274 let cause = ObligationCause::new(
275 span,
276 impl_m_def_id,
277 ObligationCauseCode::CompareImplItem {
278 impl_item_def_id: impl_m_def_id,
279 trait_item_def_id: trait_m.def_id,
280 kind: impl_m.kind,
281 },
282 );
283 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
284 }
285
286 if is_conditionally_const {
293 for (const_condition, span) in
294 tcx.const_conditions(impl_m.def_id).instantiate_own_identity()
295 {
296 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
297 let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
298
299 let cause = ObligationCause::new(
300 span,
301 impl_m_def_id,
302 ObligationCauseCode::CompareImplItem {
303 impl_item_def_id: impl_m_def_id,
304 trait_item_def_id: trait_m.def_id,
305 kind: impl_m.kind,
306 },
307 );
308 ocx.register_obligation(traits::Obligation::new(
309 tcx,
310 cause,
311 param_env,
312 const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
313 ));
314 }
315 }
316
317 let mut wf_tys = FxIndexSet::default();
326
327 let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars(
328 impl_m_span,
329 BoundRegionConversionTime::HigherRankedType,
330 tcx.fn_sig(impl_m.def_id).instantiate_identity(),
331 );
332
333 let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id);
334 let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig);
335 debug!(?impl_sig);
336
337 let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args);
338 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
339
340 wf_tys.extend(trait_sig.inputs_and_output.iter());
344 let trait_sig = ocx.normalize(&norm_cause, param_env, trait_sig);
345 wf_tys.extend(trait_sig.inputs_and_output.iter());
348 debug!(?trait_sig);
349
350 let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
358
359 if let Err(terr) = result {
360 debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
361
362 let emitted = report_trait_method_mismatch(
363 infcx,
364 cause,
365 param_env,
366 terr,
367 (trait_m, trait_sig),
368 (impl_m, impl_sig),
369 impl_trait_ref,
370 );
371 return Err(emitted);
372 }
373
374 if !(impl_sig, trait_sig).references_error() {
375 for ty in unnormalized_impl_sig.inputs_and_output {
376 ocx.register_obligation(traits::Obligation::new(
377 infcx.tcx,
378 cause.clone(),
379 param_env,
380 ty::ClauseKind::WellFormed(ty.into()),
381 ));
382 }
383 }
384
385 let errors = ocx.evaluate_obligations_error_on_ambiguity();
388 if !errors.is_empty() {
389 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
390 return Err(reported);
391 }
392
393 let errors = infcx.resolve_regions(impl_m_def_id, param_env, wf_tys);
396 if !errors.is_empty() {
397 return Err(infcx
398 .tainted_by_errors()
399 .unwrap_or_else(|| infcx.err_ctxt().report_region_errors(impl_m_def_id, &errors)));
400 }
401
402 Ok(())
403}
404
405struct RemapLateParam<'tcx> {
406 tcx: TyCtxt<'tcx>,
407 mapping: FxIndexMap<ty::LateParamRegionKind, ty::LateParamRegionKind>,
408}
409
410impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateParam<'tcx> {
411 fn cx(&self) -> TyCtxt<'tcx> {
412 self.tcx
413 }
414
415 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
416 if let ty::ReLateParam(fr) = r.kind() {
417 ty::Region::new_late_param(
418 self.tcx,
419 fr.scope,
420 self.mapping.get(&fr.kind).copied().unwrap_or(fr.kind),
421 )
422 } else {
423 r
424 }
425 }
426}
427
428#[instrument(skip(tcx), level = "debug", ret)]
460pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
461 tcx: TyCtxt<'tcx>,
462 impl_m_def_id: LocalDefId,
463) -> Result<&'tcx DefIdMap<ty::EarlyBinder<'tcx, Ty<'tcx>>>, ErrorGuaranteed> {
464 let impl_m = tcx.associated_item(impl_m_def_id.to_def_id());
465 let trait_m = tcx.associated_item(impl_m.expect_trait_impl()?);
466 let impl_trait_ref =
467 tcx.impl_trait_ref(tcx.parent(impl_m_def_id.to_def_id())).instantiate_identity();
468 check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?;
471
472 let impl_m_hir_id = tcx.local_def_id_to_hir_id(impl_m_def_id);
473 let return_span = tcx.hir_fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
474 let cause = ObligationCause::new(
475 return_span,
476 impl_m_def_id,
477 ObligationCauseCode::CompareImplItem {
478 impl_item_def_id: impl_m_def_id,
479 trait_item_def_id: trait_m.def_id,
480 kind: impl_m.kind,
481 },
482 );
483
484 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
486 tcx,
487 impl_m.container_id(tcx),
488 impl_trait_ref.args,
489 );
490
491 let hybrid_preds = tcx
492 .predicates_of(impl_m.container_id(tcx))
493 .instantiate_identity(tcx)
494 .into_iter()
495 .chain(tcx.predicates_of(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args))
496 .map(|(clause, _)| clause);
497 let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
498 let param_env = traits::normalize_param_env_or_error(
499 tcx,
500 param_env,
501 ObligationCause::misc(tcx.def_span(impl_m_def_id), impl_m_def_id),
502 );
503
504 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
505 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
506
507 let impl_m_own_bounds = tcx.predicates_of(impl_m_def_id).instantiate_own_identity();
514 for (predicate, span) in impl_m_own_bounds {
515 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
516 let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
517
518 let cause = ObligationCause::new(
519 span,
520 impl_m_def_id,
521 ObligationCauseCode::CompareImplItem {
522 impl_item_def_id: impl_m_def_id,
523 trait_item_def_id: trait_m.def_id,
524 kind: impl_m.kind,
525 },
526 );
527 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
528 }
529
530 let misc_cause = ObligationCause::misc(return_span, impl_m_def_id);
532 let impl_sig = ocx.normalize(
533 &misc_cause,
534 param_env,
535 infcx.instantiate_binder_with_fresh_vars(
536 return_span,
537 BoundRegionConversionTime::HigherRankedType,
538 tcx.fn_sig(impl_m.def_id).instantiate_identity(),
539 ),
540 );
541 impl_sig.error_reported()?;
542 let impl_return_ty = impl_sig.output();
543
544 let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_def_id);
549 let unnormalized_trait_sig = tcx
550 .liberate_late_bound_regions(
551 impl_m.def_id,
552 tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args),
553 )
554 .fold_with(&mut collector);
555
556 let trait_sig = ocx.normalize(&misc_cause, param_env, unnormalized_trait_sig);
557 trait_sig.error_reported()?;
558 let trait_return_ty = trait_sig.output();
559
560 let universe = infcx.create_next_universe();
580 let mut idx = ty::BoundVar::ZERO;
581 let mapping: FxIndexMap<_, _> = collector
582 .types
583 .iter()
584 .map(|(_, &(ty, _))| {
585 assert!(
586 infcx.resolve_vars_if_possible(ty) == ty && ty.is_ty_var(),
587 "{ty:?} should not have been constrained via normalization",
588 ty = infcx.resolve_vars_if_possible(ty)
589 );
590 idx += 1;
591 (
592 ty,
593 Ty::new_placeholder(
594 tcx,
595 ty::Placeholder::new(
596 universe,
597 ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
598 ),
599 ),
600 )
601 })
602 .collect();
603 let mut type_mapper = BottomUpFolder {
604 tcx,
605 ty_op: |ty| *mapping.get(&ty).unwrap_or(&ty),
606 lt_op: |lt| lt,
607 ct_op: |ct| ct,
608 };
609 let wf_tys = FxIndexSet::from_iter(
610 unnormalized_trait_sig
611 .inputs_and_output
612 .iter()
613 .chain(trait_sig.inputs_and_output.iter())
614 .map(|ty| ty.fold_with(&mut type_mapper)),
615 );
616
617 match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
618 Ok(()) => {}
619 Err(terr) => {
620 let mut diag = struct_span_code_err!(
621 tcx.dcx(),
622 cause.span,
623 E0053,
624 "method `{}` has an incompatible return type for trait",
625 trait_m.name()
626 );
627 infcx.err_ctxt().note_type_err(
628 &mut diag,
629 &cause,
630 tcx.hir_get_if_local(impl_m.def_id)
631 .and_then(|node| node.fn_decl())
632 .map(|decl| (decl.output.span(), Cow::from("return type in trait"), false)),
633 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
634 expected: trait_return_ty.into(),
635 found: impl_return_ty.into(),
636 }))),
637 terr,
638 false,
639 None,
640 );
641 return Err(diag.emit());
642 }
643 }
644
645 debug!(?trait_sig, ?impl_sig, "equating function signatures");
646
647 match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
652 Ok(()) => {}
653 Err(terr) => {
654 let emitted = report_trait_method_mismatch(
659 infcx,
660 cause,
661 param_env,
662 terr,
663 (trait_m, trait_sig),
664 (impl_m, impl_sig),
665 impl_trait_ref,
666 );
667 return Err(emitted);
668 }
669 }
670
671 if !unnormalized_trait_sig.output().references_error() && collector.types.is_empty() {
672 tcx.dcx().delayed_bug(
673 "expect >0 RPITITs in call to `collect_return_position_impl_trait_in_trait_tys`",
674 );
675 }
676
677 let collected_types = collector.types;
682 for (_, &(ty, _)) in &collected_types {
683 ocx.register_obligation(traits::Obligation::new(
684 tcx,
685 misc_cause.clone(),
686 param_env,
687 ty::ClauseKind::WellFormed(ty.into()),
688 ));
689 }
690
691 let errors = ocx.evaluate_obligations_error_on_ambiguity();
694 if !errors.is_empty() {
695 if let Err(guar) = try_report_async_mismatch(tcx, infcx, &errors, trait_m, impl_m, impl_sig)
696 {
697 return Err(guar);
698 }
699
700 let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
701 return Err(guar);
702 }
703
704 ocx.resolve_regions_and_report_errors(impl_m_def_id, param_env, wf_tys)?;
707
708 let mut remapped_types = DefIdMap::default();
709 for (def_id, (ty, args)) in collected_types {
710 match infcx.fully_resolve(ty) {
711 Ok(ty) => {
712 let id_args = GenericArgs::identity_for_item(tcx, def_id);
716 debug!(?id_args, ?args);
717 let map: FxIndexMap<_, _> = std::iter::zip(args, id_args)
718 .skip(tcx.generics_of(trait_m.def_id).count())
719 .filter_map(|(a, b)| Some((a.as_region()?, b.as_region()?)))
720 .collect();
721 debug!(?map);
722
723 let num_trait_args = impl_trait_ref.args.len();
744 let num_impl_args = tcx.generics_of(impl_m.container_id(tcx)).own_params.len();
745 let ty = match ty.try_fold_with(&mut RemapHiddenTyRegions {
746 tcx,
747 map,
748 num_trait_args,
749 num_impl_args,
750 def_id,
751 impl_m_def_id: impl_m.def_id,
752 ty,
753 return_span,
754 }) {
755 Ok(ty) => ty,
756 Err(guar) => Ty::new_error(tcx, guar),
757 };
758 remapped_types.insert(def_id, ty::EarlyBinder::bind(ty));
759 }
760 Err(err) => {
761 tcx.dcx()
766 .span_bug(return_span, format!("could not fully resolve: {ty} => {err:?}"));
767 }
768 }
769 }
770
771 for assoc_item in tcx.associated_types_for_impl_traits_in_associated_fn(trait_m.def_id) {
777 if !remapped_types.contains_key(assoc_item) {
778 remapped_types.insert(
779 *assoc_item,
780 ty::EarlyBinder::bind(Ty::new_error_with_message(
781 tcx,
782 return_span,
783 "missing synthetic item for RPITIT",
784 )),
785 );
786 }
787 }
788
789 Ok(&*tcx.arena.alloc(remapped_types))
790}
791
792struct ImplTraitInTraitCollector<'a, 'tcx, E> {
793 ocx: &'a ObligationCtxt<'a, 'tcx, E>,
794 types: FxIndexMap<DefId, (Ty<'tcx>, ty::GenericArgsRef<'tcx>)>,
795 span: Span,
796 param_env: ty::ParamEnv<'tcx>,
797 body_id: LocalDefId,
798}
799
800impl<'a, 'tcx, E> ImplTraitInTraitCollector<'a, 'tcx, E>
801where
802 E: 'tcx,
803{
804 fn new(
805 ocx: &'a ObligationCtxt<'a, 'tcx, E>,
806 span: Span,
807 param_env: ty::ParamEnv<'tcx>,
808 body_id: LocalDefId,
809 ) -> Self {
810 ImplTraitInTraitCollector { ocx, types: FxIndexMap::default(), span, param_env, body_id }
811 }
812}
813
814impl<'tcx, E> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx, E>
815where
816 E: 'tcx,
817{
818 fn cx(&self) -> TyCtxt<'tcx> {
819 self.ocx.infcx.tcx
820 }
821
822 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
823 if let ty::Alias(ty::Projection, proj) = ty.kind()
824 && self.cx().is_impl_trait_in_trait(proj.def_id)
825 {
826 if let Some((ty, _)) = self.types.get(&proj.def_id) {
827 return *ty;
828 }
829 if proj.args.has_escaping_bound_vars() {
831 bug!("FIXME(RPITIT): error here");
832 }
833 let infer_ty = self.ocx.infcx.next_ty_var(self.span);
835 self.types.insert(proj.def_id, (infer_ty, proj.args));
836 for (pred, pred_span) in self
838 .cx()
839 .explicit_item_bounds(proj.def_id)
840 .iter_instantiated_copied(self.cx(), proj.args)
841 {
842 let pred = pred.fold_with(self);
843 let pred = self.ocx.normalize(
844 &ObligationCause::misc(self.span, self.body_id),
845 self.param_env,
846 pred,
847 );
848
849 self.ocx.register_obligation(traits::Obligation::new(
850 self.cx(),
851 ObligationCause::new(
852 self.span,
853 self.body_id,
854 ObligationCauseCode::WhereClause(proj.def_id, pred_span),
855 ),
856 self.param_env,
857 pred,
858 ));
859 }
860 infer_ty
861 } else {
862 ty.super_fold_with(self)
863 }
864 }
865}
866
867struct RemapHiddenTyRegions<'tcx> {
868 tcx: TyCtxt<'tcx>,
869 map: FxIndexMap<ty::Region<'tcx>, ty::Region<'tcx>>,
872 num_trait_args: usize,
873 num_impl_args: usize,
874 def_id: DefId,
876 impl_m_def_id: DefId,
878 ty: Ty<'tcx>,
880 return_span: Span,
882}
883
884impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> {
885 type Error = ErrorGuaranteed;
886
887 fn cx(&self) -> TyCtxt<'tcx> {
888 self.tcx
889 }
890
891 fn try_fold_region(
892 &mut self,
893 region: ty::Region<'tcx>,
894 ) -> Result<ty::Region<'tcx>, Self::Error> {
895 match region.kind() {
896 ty::ReBound(..) | ty::ReStatic | ty::ReError(_) => return Ok(region),
898 ty::ReLateParam(_) => {}
900 ty::ReEarlyParam(ebr) => {
903 if ebr.index as usize >= self.num_impl_args {
904 } else {
906 return Ok(region);
907 }
908 }
909 ty::ReVar(_) | ty::RePlaceholder(_) | ty::ReErased => unreachable!(
910 "should not have leaked vars or placeholders into hidden type of RPITIT"
911 ),
912 }
913
914 let e = if let Some(id_region) = self.map.get(®ion) {
915 if let ty::ReEarlyParam(e) = id_region.kind() {
916 e
917 } else {
918 bug!(
919 "expected to map region {region} to early-bound identity region, but got {id_region}"
920 );
921 }
922 } else {
923 let guar = match region.opt_param_def_id(self.tcx, self.impl_m_def_id) {
924 Some(def_id) => {
925 let return_span = if let ty::Alias(ty::Opaque, opaque_ty) = self.ty.kind() {
926 self.tcx.def_span(opaque_ty.def_id)
927 } else {
928 self.return_span
929 };
930 self.tcx
931 .dcx()
932 .struct_span_err(
933 return_span,
934 "return type captures more lifetimes than trait definition",
935 )
936 .with_span_label(self.tcx.def_span(def_id), "this lifetime was captured")
937 .with_span_note(
938 self.tcx.def_span(self.def_id),
939 "hidden type must only reference lifetimes captured by this impl trait",
940 )
941 .with_note(format!("hidden type inferred to be `{}`", self.ty))
942 .emit()
943 }
944 None => {
945 self.tcx.dcx().bug("should've been able to remap region");
950 }
951 };
952 return Err(guar);
953 };
954
955 Ok(ty::Region::new_early_param(
956 self.tcx,
957 ty::EarlyParamRegion {
958 name: e.name,
959 index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32,
960 },
961 ))
962 }
963}
964
965fn get_self_string<'tcx, P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> String
968where
969 P: Fn(Ty<'tcx>) -> bool,
970{
971 if is_self_ty(self_arg_ty) {
972 "self".to_owned()
973 } else if let ty::Ref(_, ty, mutbl) = self_arg_ty.kind()
974 && is_self_ty(*ty)
975 {
976 match mutbl {
977 hir::Mutability::Not => "&self".to_owned(),
978 hir::Mutability::Mut => "&mut self".to_owned(),
979 }
980 } else {
981 format!("self: {self_arg_ty}")
982 }
983}
984
985fn report_trait_method_mismatch<'tcx>(
986 infcx: &InferCtxt<'tcx>,
987 mut cause: ObligationCause<'tcx>,
988 param_env: ty::ParamEnv<'tcx>,
989 terr: TypeError<'tcx>,
990 (trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>),
991 (impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>),
992 impl_trait_ref: ty::TraitRef<'tcx>,
993) -> ErrorGuaranteed {
994 let tcx = infcx.tcx;
995 let (impl_err_span, trait_err_span) =
996 extract_spans_for_error_reporting(infcx, terr, &cause, impl_m, trait_m);
997
998 let mut diag = struct_span_code_err!(
999 tcx.dcx(),
1000 impl_err_span,
1001 E0053,
1002 "method `{}` has an incompatible type for trait",
1003 trait_m.name()
1004 );
1005 match &terr {
1006 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
1007 if trait_m.is_method() =>
1008 {
1009 let ty = trait_sig.inputs()[0];
1010 let sugg = get_self_string(ty, |ty| ty == impl_trait_ref.self_ty());
1011
1012 let (sig, body) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1016 let span = tcx
1017 .hir_body_param_idents(body)
1018 .zip(sig.decl.inputs.iter())
1019 .map(|(param_ident, ty)| {
1020 if let Some(param_ident) = param_ident {
1021 param_ident.span.to(ty.span)
1022 } else {
1023 ty.span
1024 }
1025 })
1026 .next()
1027 .unwrap_or(impl_err_span);
1028
1029 diag.span_suggestion_verbose(
1030 span,
1031 "change the self-receiver type to match the trait",
1032 sugg,
1033 Applicability::MachineApplicable,
1034 );
1035 }
1036 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
1037 if trait_sig.inputs().len() == *i {
1038 if let ImplItemKind::Fn(sig, _) =
1041 &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).kind
1042 && !sig.header.asyncness.is_async()
1043 {
1044 let msg = "change the output type to match the trait";
1045 let ap = Applicability::MachineApplicable;
1046 match sig.decl.output {
1047 hir::FnRetTy::DefaultReturn(sp) => {
1048 let sugg = format!(" -> {}", trait_sig.output());
1049 diag.span_suggestion_verbose(sp, msg, sugg, ap);
1050 }
1051 hir::FnRetTy::Return(hir_ty) => {
1052 let sugg = trait_sig.output();
1053 diag.span_suggestion_verbose(hir_ty.span, msg, sugg, ap);
1054 }
1055 };
1056 };
1057 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
1058 diag.span_suggestion_verbose(
1059 impl_err_span,
1060 "change the parameter type to match the trait",
1061 trait_ty,
1062 Applicability::MachineApplicable,
1063 );
1064 }
1065 }
1066 _ => {}
1067 }
1068
1069 cause.span = impl_err_span;
1070 infcx.err_ctxt().note_type_err(
1071 &mut diag,
1072 &cause,
1073 trait_err_span.map(|sp| (sp, Cow::from("type in trait"), false)),
1074 Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound {
1075 expected: ty::Binder::dummy(trait_sig),
1076 found: ty::Binder::dummy(impl_sig),
1077 }))),
1078 terr,
1079 false,
1080 None,
1081 );
1082
1083 diag.emit()
1084}
1085
1086fn check_region_bounds_on_impl_item<'tcx>(
1087 tcx: TyCtxt<'tcx>,
1088 impl_m: ty::AssocItem,
1089 trait_m: ty::AssocItem,
1090 delay: bool,
1091) -> Result<(), ErrorGuaranteed> {
1092 let impl_generics = tcx.generics_of(impl_m.def_id);
1093 let impl_params = impl_generics.own_counts().lifetimes;
1094
1095 let trait_generics = tcx.generics_of(trait_m.def_id);
1096 let trait_params = trait_generics.own_counts().lifetimes;
1097
1098 let Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span }) =
1099 check_number_of_early_bound_regions(
1100 tcx,
1101 impl_m.def_id.expect_local(),
1102 trait_m.def_id,
1103 impl_generics,
1104 impl_params,
1105 trait_generics,
1106 trait_params,
1107 )
1108 else {
1109 return Ok(());
1110 };
1111
1112 if !delay && let Some(guar) = check_region_late_boundedness(tcx, impl_m, trait_m) {
1113 return Err(guar);
1114 }
1115
1116 let reported = tcx
1117 .dcx()
1118 .create_err(LifetimesOrBoundsMismatchOnTrait {
1119 span,
1120 item_kind: impl_m.descr(),
1121 ident: impl_m.ident(tcx),
1122 generics_span,
1123 bounds_span,
1124 where_span,
1125 })
1126 .emit_unless_delay(delay);
1127
1128 Err(reported)
1129}
1130
1131pub(super) struct CheckNumberOfEarlyBoundRegionsError {
1132 pub(super) span: Span,
1133 pub(super) generics_span: Span,
1134 pub(super) bounds_span: Vec<Span>,
1135 pub(super) where_span: Option<Span>,
1136}
1137
1138pub(super) fn check_number_of_early_bound_regions<'tcx>(
1139 tcx: TyCtxt<'tcx>,
1140 impl_def_id: LocalDefId,
1141 trait_def_id: DefId,
1142 impl_generics: &Generics,
1143 impl_params: usize,
1144 trait_generics: &Generics,
1145 trait_params: usize,
1146) -> Result<(), CheckNumberOfEarlyBoundRegionsError> {
1147 debug!(?trait_generics, ?impl_generics);
1148
1149 if trait_params == impl_params {
1159 return Ok(());
1160 }
1161
1162 let span = tcx
1163 .hir_get_generics(impl_def_id)
1164 .expect("expected impl item to have generics or else we can't compare them")
1165 .span;
1166
1167 let mut generics_span = tcx.def_span(trait_def_id);
1168 let mut bounds_span = vec![];
1169 let mut where_span = None;
1170
1171 if let Some(trait_node) = tcx.hir_get_if_local(trait_def_id)
1172 && let Some(trait_generics) = trait_node.generics()
1173 {
1174 generics_span = trait_generics.span;
1175 for p in trait_generics.predicates {
1178 match p.kind {
1179 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1180 bounds,
1181 ..
1182 })
1183 | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1184 bounds,
1185 ..
1186 }) => {
1187 for b in *bounds {
1188 if let hir::GenericBound::Outlives(lt) = b {
1189 bounds_span.push(lt.ident.span);
1190 }
1191 }
1192 }
1193 _ => {}
1194 }
1195 }
1196 if let Some(impl_node) = tcx.hir_get_if_local(impl_def_id.into())
1197 && let Some(impl_generics) = impl_node.generics()
1198 {
1199 let mut impl_bounds = 0;
1200 for p in impl_generics.predicates {
1201 match p.kind {
1202 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1203 bounds,
1204 ..
1205 })
1206 | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1207 bounds,
1208 ..
1209 }) => {
1210 for b in *bounds {
1211 if let hir::GenericBound::Outlives(_) = b {
1212 impl_bounds += 1;
1213 }
1214 }
1215 }
1216 _ => {}
1217 }
1218 }
1219 if impl_bounds == bounds_span.len() {
1220 bounds_span = vec![];
1221 } else if impl_generics.has_where_clause_predicates {
1222 where_span = Some(impl_generics.where_clause_span);
1223 }
1224 }
1225 }
1226
1227 Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span })
1228}
1229
1230#[allow(unused)]
1231enum LateEarlyMismatch<'tcx> {
1232 EarlyInImpl(DefId, DefId, ty::Region<'tcx>),
1233 LateInImpl(DefId, DefId, ty::Region<'tcx>),
1234}
1235
1236fn check_region_late_boundedness<'tcx>(
1237 tcx: TyCtxt<'tcx>,
1238 impl_m: ty::AssocItem,
1239 trait_m: ty::AssocItem,
1240) -> Option<ErrorGuaranteed> {
1241 if !impl_m.is_fn() {
1242 return None;
1243 }
1244
1245 let (infcx, param_env) = tcx
1246 .infer_ctxt()
1247 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, impl_m.def_id));
1248
1249 let impl_m_args = infcx.fresh_args_for_item(DUMMY_SP, impl_m.def_id);
1250 let impl_m_sig = tcx.fn_sig(impl_m.def_id).instantiate(tcx, impl_m_args);
1251 let impl_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, impl_m_sig);
1252
1253 let trait_m_args = infcx.fresh_args_for_item(DUMMY_SP, trait_m.def_id);
1254 let trait_m_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_args);
1255 let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_m_sig);
1256
1257 let ocx = ObligationCtxt::new(&infcx);
1258
1259 let Ok(()) = ocx.eq(
1264 &ObligationCause::dummy(),
1265 param_env,
1266 ty::Binder::dummy(trait_m_sig),
1267 ty::Binder::dummy(impl_m_sig),
1268 ) else {
1269 return None;
1270 };
1271
1272 let errors = ocx.try_evaluate_obligations();
1273 if !errors.is_empty() {
1274 return None;
1275 }
1276
1277 let mut mismatched = vec![];
1278
1279 let impl_generics = tcx.generics_of(impl_m.def_id);
1280 for (id_arg, arg) in
1281 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, impl_m.def_id), impl_m_args)
1282 {
1283 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1284 && let ty::ReVar(vid) = r.kind()
1285 && let r = infcx
1286 .inner
1287 .borrow_mut()
1288 .unwrap_region_constraints()
1289 .opportunistic_resolve_var(tcx, vid)
1290 && let ty::ReLateParam(ty::LateParamRegion {
1291 kind: ty::LateParamRegionKind::Named(trait_param_def_id),
1292 ..
1293 }) = r.kind()
1294 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1295 {
1296 mismatched.push(LateEarlyMismatch::EarlyInImpl(
1297 impl_generics.region_param(ebr, tcx).def_id,
1298 trait_param_def_id,
1299 id_arg.expect_region(),
1300 ));
1301 }
1302 }
1303
1304 let trait_generics = tcx.generics_of(trait_m.def_id);
1305 for (id_arg, arg) in
1306 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, trait_m.def_id), trait_m_args)
1307 {
1308 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1309 && let ty::ReVar(vid) = r.kind()
1310 && let r = infcx
1311 .inner
1312 .borrow_mut()
1313 .unwrap_region_constraints()
1314 .opportunistic_resolve_var(tcx, vid)
1315 && let ty::ReLateParam(ty::LateParamRegion {
1316 kind: ty::LateParamRegionKind::Named(impl_param_def_id),
1317 ..
1318 }) = r.kind()
1319 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1320 {
1321 mismatched.push(LateEarlyMismatch::LateInImpl(
1322 impl_param_def_id,
1323 trait_generics.region_param(ebr, tcx).def_id,
1324 id_arg.expect_region(),
1325 ));
1326 }
1327 }
1328
1329 if mismatched.is_empty() {
1330 return None;
1331 }
1332
1333 let spans: Vec<_> = mismatched
1334 .iter()
1335 .map(|param| {
1336 let (LateEarlyMismatch::EarlyInImpl(impl_param_def_id, ..)
1337 | LateEarlyMismatch::LateInImpl(impl_param_def_id, ..)) = param;
1338 tcx.def_span(impl_param_def_id)
1339 })
1340 .collect();
1341
1342 let mut diag = tcx
1343 .dcx()
1344 .struct_span_err(spans, "lifetime parameters do not match the trait definition")
1345 .with_note("lifetime parameters differ in whether they are early- or late-bound")
1346 .with_code(E0195);
1347 for mismatch in mismatched {
1348 match mismatch {
1349 LateEarlyMismatch::EarlyInImpl(
1350 impl_param_def_id,
1351 trait_param_def_id,
1352 early_bound_region,
1353 ) => {
1354 let mut multispan = MultiSpan::from_spans(vec![
1355 tcx.def_span(impl_param_def_id),
1356 tcx.def_span(trait_param_def_id),
1357 ]);
1358 multispan
1359 .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1360 multispan
1361 .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1362 multispan.push_span_label(
1363 tcx.def_span(impl_param_def_id),
1364 format!("`{}` is early-bound", tcx.item_name(impl_param_def_id)),
1365 );
1366 multispan.push_span_label(
1367 tcx.def_span(trait_param_def_id),
1368 format!("`{}` is late-bound", tcx.item_name(trait_param_def_id)),
1369 );
1370 if let Some(span) =
1371 find_region_in_predicates(tcx, impl_m.def_id, early_bound_region)
1372 {
1373 multispan.push_span_label(
1374 span,
1375 format!(
1376 "this lifetime bound makes `{}` early-bound",
1377 tcx.item_name(impl_param_def_id)
1378 ),
1379 );
1380 }
1381 diag.span_note(
1382 multispan,
1383 format!(
1384 "`{}` differs between the trait and impl",
1385 tcx.item_name(impl_param_def_id)
1386 ),
1387 );
1388 }
1389 LateEarlyMismatch::LateInImpl(
1390 impl_param_def_id,
1391 trait_param_def_id,
1392 early_bound_region,
1393 ) => {
1394 let mut multispan = MultiSpan::from_spans(vec![
1395 tcx.def_span(impl_param_def_id),
1396 tcx.def_span(trait_param_def_id),
1397 ]);
1398 multispan
1399 .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1400 multispan
1401 .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1402 multispan.push_span_label(
1403 tcx.def_span(impl_param_def_id),
1404 format!("`{}` is late-bound", tcx.item_name(impl_param_def_id)),
1405 );
1406 multispan.push_span_label(
1407 tcx.def_span(trait_param_def_id),
1408 format!("`{}` is early-bound", tcx.item_name(trait_param_def_id)),
1409 );
1410 if let Some(span) =
1411 find_region_in_predicates(tcx, trait_m.def_id, early_bound_region)
1412 {
1413 multispan.push_span_label(
1414 span,
1415 format!(
1416 "this lifetime bound makes `{}` early-bound",
1417 tcx.item_name(trait_param_def_id)
1418 ),
1419 );
1420 }
1421 diag.span_note(
1422 multispan,
1423 format!(
1424 "`{}` differs between the trait and impl",
1425 tcx.item_name(impl_param_def_id)
1426 ),
1427 );
1428 }
1429 }
1430 }
1431
1432 Some(diag.emit())
1433}
1434
1435fn find_region_in_predicates<'tcx>(
1436 tcx: TyCtxt<'tcx>,
1437 def_id: DefId,
1438 early_bound_region: ty::Region<'tcx>,
1439) -> Option<Span> {
1440 for (pred, span) in tcx.explicit_predicates_of(def_id).instantiate_identity(tcx) {
1441 if pred.visit_with(&mut FindRegion(early_bound_region)).is_break() {
1442 return Some(span);
1443 }
1444 }
1445
1446 struct FindRegion<'tcx>(ty::Region<'tcx>);
1447 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindRegion<'tcx> {
1448 type Result = ControlFlow<()>;
1449 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
1450 if r == self.0 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
1451 }
1452 }
1453
1454 None
1455}
1456
1457#[instrument(level = "debug", skip(infcx))]
1458fn extract_spans_for_error_reporting<'tcx>(
1459 infcx: &infer::InferCtxt<'tcx>,
1460 terr: TypeError<'_>,
1461 cause: &ObligationCause<'tcx>,
1462 impl_m: ty::AssocItem,
1463 trait_m: ty::AssocItem,
1464) -> (Span, Option<Span>) {
1465 let tcx = infcx.tcx;
1466 let mut impl_args = {
1467 let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1468 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1469 };
1470
1471 let trait_args = trait_m.def_id.as_local().map(|def_id| {
1472 let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
1473 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1474 });
1475
1476 match terr {
1477 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1478 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1479 }
1480 _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
1481 }
1482}
1483
1484fn compare_self_type<'tcx>(
1485 tcx: TyCtxt<'tcx>,
1486 impl_m: ty::AssocItem,
1487 trait_m: ty::AssocItem,
1488 impl_trait_ref: ty::TraitRef<'tcx>,
1489 delay: bool,
1490) -> Result<(), ErrorGuaranteed> {
1491 let self_string = |method: ty::AssocItem| {
1500 let untransformed_self_ty = match method.container {
1501 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1502 impl_trait_ref.self_ty()
1503 }
1504 ty::AssocContainer::Trait => tcx.types.self_param,
1505 };
1506 let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().input(0);
1507 let (infcx, param_env) = tcx
1508 .infer_ctxt()
1509 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
1510 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1511 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1512 get_self_string(self_arg_ty, can_eq_self)
1513 };
1514
1515 match (trait_m.is_method(), impl_m.is_method()) {
1516 (false, false) | (true, true) => {}
1517
1518 (false, true) => {
1519 let self_descr = self_string(impl_m);
1520 let impl_m_span = tcx.def_span(impl_m.def_id);
1521 let mut err = struct_span_code_err!(
1522 tcx.dcx(),
1523 impl_m_span,
1524 E0185,
1525 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1526 trait_m.name(),
1527 self_descr
1528 );
1529 err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
1530 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1531 err.span_label(span, format!("trait method declared without `{self_descr}`"));
1532 } else {
1533 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1534 }
1535 return Err(err.emit_unless_delay(delay));
1536 }
1537
1538 (true, false) => {
1539 let self_descr = self_string(trait_m);
1540 let impl_m_span = tcx.def_span(impl_m.def_id);
1541 let mut err = struct_span_code_err!(
1542 tcx.dcx(),
1543 impl_m_span,
1544 E0186,
1545 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1546 trait_m.name(),
1547 self_descr
1548 );
1549 err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
1550 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1551 err.span_label(span, format!("`{self_descr}` used in trait"));
1552 } else {
1553 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1554 }
1555
1556 return Err(err.emit_unless_delay(delay));
1557 }
1558 }
1559
1560 Ok(())
1561}
1562
1563fn compare_number_of_generics<'tcx>(
1585 tcx: TyCtxt<'tcx>,
1586 impl_: ty::AssocItem,
1587 trait_: ty::AssocItem,
1588 delay: bool,
1589) -> Result<(), ErrorGuaranteed> {
1590 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1591 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1592
1593 if (trait_own_counts.types + trait_own_counts.consts)
1597 == (impl_own_counts.types + impl_own_counts.consts)
1598 {
1599 return Ok(());
1600 }
1601
1602 if trait_.is_impl_trait_in_trait() {
1607 tcx.dcx()
1610 .bug("errors comparing numbers of generics of trait/impl functions were not emitted");
1611 }
1612
1613 let matchings = [
1614 ("type", trait_own_counts.types, impl_own_counts.types),
1615 ("const", trait_own_counts.consts, impl_own_counts.consts),
1616 ];
1617
1618 let item_kind = impl_.descr();
1619
1620 let mut err_occurred = None;
1621 for (kind, trait_count, impl_count) in matchings {
1622 if impl_count != trait_count {
1623 let arg_spans = |item: &ty::AssocItem, generics: &hir::Generics<'_>| {
1624 let mut spans = generics
1625 .params
1626 .iter()
1627 .filter(|p| match p.kind {
1628 hir::GenericParamKind::Lifetime {
1629 kind: hir::LifetimeParamKind::Elided(_),
1630 } => {
1631 !item.is_fn()
1634 }
1635 _ => true,
1636 })
1637 .map(|p| p.span)
1638 .collect::<Vec<Span>>();
1639 if spans.is_empty() {
1640 spans = vec![generics.span]
1641 }
1642 spans
1643 };
1644 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1645 let trait_item = tcx.hir_expect_trait_item(def_id);
1646 let arg_spans: Vec<Span> = arg_spans(&trait_, trait_item.generics);
1647 let impl_trait_spans: Vec<Span> = trait_item
1648 .generics
1649 .params
1650 .iter()
1651 .filter_map(|p| match p.kind {
1652 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1653 _ => None,
1654 })
1655 .collect();
1656 (Some(arg_spans), impl_trait_spans)
1657 } else {
1658 let trait_span = tcx.hir_span_if_local(trait_.def_id);
1659 (trait_span.map(|s| vec![s]), vec![])
1660 };
1661
1662 let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
1663 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1664 .generics
1665 .params
1666 .iter()
1667 .filter_map(|p| match p.kind {
1668 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1669 _ => None,
1670 })
1671 .collect();
1672 let spans = arg_spans(&impl_, impl_item.generics);
1673 let span = spans.first().copied();
1674
1675 let mut err = tcx.dcx().struct_span_err(
1676 spans,
1677 format!(
1678 "{} `{}` has {} {kind} parameter{} but its trait \
1679 declaration has {} {kind} parameter{}",
1680 item_kind,
1681 trait_.name(),
1682 impl_count,
1683 pluralize!(impl_count),
1684 trait_count,
1685 pluralize!(trait_count),
1686 kind = kind,
1687 ),
1688 );
1689 err.code(E0049);
1690
1691 let msg =
1692 format!("expected {trait_count} {kind} parameter{}", pluralize!(trait_count),);
1693 if let Some(spans) = trait_spans {
1694 let mut spans = spans.iter();
1695 if let Some(span) = spans.next() {
1696 err.span_label(*span, msg);
1697 }
1698 for span in spans {
1699 err.span_label(*span, "");
1700 }
1701 } else {
1702 err.span_label(tcx.def_span(trait_.def_id), msg);
1703 }
1704
1705 if let Some(span) = span {
1706 err.span_label(
1707 span,
1708 format!("found {} {} parameter{}", impl_count, kind, pluralize!(impl_count),),
1709 );
1710 }
1711
1712 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1713 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1714 }
1715
1716 let reported = err.emit_unless_delay(delay);
1717 err_occurred = Some(reported);
1718 }
1719 }
1720
1721 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1722}
1723
1724fn compare_number_of_method_arguments<'tcx>(
1725 tcx: TyCtxt<'tcx>,
1726 impl_m: ty::AssocItem,
1727 trait_m: ty::AssocItem,
1728 delay: bool,
1729) -> Result<(), ErrorGuaranteed> {
1730 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1731 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1732 let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1733 let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1734
1735 if trait_number_args != impl_number_args {
1736 let trait_span = trait_m
1737 .def_id
1738 .as_local()
1739 .and_then(|def_id| {
1740 let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
1741 let pos = trait_number_args.saturating_sub(1);
1742 trait_m_sig.decl.inputs.get(pos).map(|arg| {
1743 if pos == 0 {
1744 arg.span
1745 } else {
1746 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1747 }
1748 })
1749 })
1750 .or_else(|| tcx.hir_span_if_local(trait_m.def_id));
1751
1752 let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1753 let pos = impl_number_args.saturating_sub(1);
1754 let impl_span = impl_m_sig
1755 .decl
1756 .inputs
1757 .get(pos)
1758 .map(|arg| {
1759 if pos == 0 {
1760 arg.span
1761 } else {
1762 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1763 }
1764 })
1765 .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1766
1767 let mut err = struct_span_code_err!(
1768 tcx.dcx(),
1769 impl_span,
1770 E0050,
1771 "method `{}` has {} but the declaration in trait `{}` has {}",
1772 trait_m.name(),
1773 potentially_plural_count(impl_number_args, "parameter"),
1774 tcx.def_path_str(trait_m.def_id),
1775 trait_number_args
1776 );
1777
1778 if let Some(trait_span) = trait_span {
1779 err.span_label(
1780 trait_span,
1781 format!(
1782 "trait requires {}",
1783 potentially_plural_count(trait_number_args, "parameter")
1784 ),
1785 );
1786 } else {
1787 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1788 }
1789
1790 err.span_label(
1791 impl_span,
1792 format!(
1793 "expected {}, found {}",
1794 potentially_plural_count(trait_number_args, "parameter"),
1795 impl_number_args
1796 ),
1797 );
1798
1799 return Err(err.emit_unless_delay(delay));
1800 }
1801
1802 Ok(())
1803}
1804
1805fn compare_synthetic_generics<'tcx>(
1806 tcx: TyCtxt<'tcx>,
1807 impl_m: ty::AssocItem,
1808 trait_m: ty::AssocItem,
1809 delay: bool,
1810) -> Result<(), ErrorGuaranteed> {
1811 let mut error_found = None;
1817 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1818 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1819 let impl_m_type_params =
1820 impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
1821 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1822 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1823 });
1824 let trait_m_type_params =
1825 trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
1826 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1827 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1828 });
1829 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1830 iter::zip(impl_m_type_params, trait_m_type_params)
1831 {
1832 if impl_synthetic != trait_synthetic {
1833 let impl_def_id = impl_def_id.expect_local();
1834 let impl_span = tcx.def_span(impl_def_id);
1835 let trait_span = tcx.def_span(trait_def_id);
1836 let mut err = struct_span_code_err!(
1837 tcx.dcx(),
1838 impl_span,
1839 E0643,
1840 "method `{}` has incompatible signature for trait",
1841 trait_m.name()
1842 );
1843 err.span_label(trait_span, "declaration in trait here");
1844 if impl_synthetic {
1845 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1848 let _: Option<_> = try {
1849 let new_name = tcx.opt_item_name(trait_def_id)?;
1853 let trait_m = trait_m.def_id.as_local()?;
1854 let trait_m = tcx.hir_expect_trait_item(trait_m);
1855
1856 let impl_m = impl_m.def_id.as_local()?;
1857 let impl_m = tcx.hir_expect_impl_item(impl_m);
1858
1859 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1862 let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
1864 let new_generics =
1866 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1867
1868 err.multipart_suggestion(
1869 "try changing the `impl Trait` argument to a generic parameter",
1870 vec![
1871 (impl_span, new_name.to_string()),
1873 (generics_span, new_generics),
1877 ],
1878 Applicability::MaybeIncorrect,
1879 );
1880 };
1881 } else {
1882 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1885 let _: Option<_> = try {
1886 let impl_m = impl_m.def_id.as_local()?;
1887 let impl_m = tcx.hir_expect_impl_item(impl_m);
1888 let (sig, _) = impl_m.expect_fn();
1889 let input_tys = sig.decl.inputs;
1890
1891 struct Visitor(hir::def_id::LocalDefId);
1892 impl<'v> intravisit::Visitor<'v> for Visitor {
1893 type Result = ControlFlow<Span>;
1894 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
1895 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
1896 && let Res::Def(DefKind::TyParam, def_id) = path.res
1897 && def_id == self.0.to_def_id()
1898 {
1899 ControlFlow::Break(ty.span)
1900 } else {
1901 intravisit::walk_ty(self, ty)
1902 }
1903 }
1904 }
1905
1906 let span = input_tys
1907 .iter()
1908 .find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
1909
1910 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
1911 let bounds = bounds.first()?.span().to(bounds.last()?.span());
1912 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1913
1914 err.multipart_suggestion(
1915 "try removing the generic parameter and using `impl Trait` instead",
1916 vec![
1917 (impl_m.generics.span, String::new()),
1919 (span, format!("impl {bounds}")),
1921 ],
1922 Applicability::MaybeIncorrect,
1923 );
1924 };
1925 }
1926 error_found = Some(err.emit_unless_delay(delay));
1927 }
1928 }
1929 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1930}
1931
1932fn compare_generic_param_kinds<'tcx>(
1958 tcx: TyCtxt<'tcx>,
1959 impl_item: ty::AssocItem,
1960 trait_item: ty::AssocItem,
1961 delay: bool,
1962) -> Result<(), ErrorGuaranteed> {
1963 assert_eq!(impl_item.as_tag(), trait_item.as_tag());
1964
1965 let ty_const_params_of = |def_id| {
1966 tcx.generics_of(def_id).own_params.iter().filter(|param| {
1967 matches!(
1968 param.kind,
1969 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1970 )
1971 })
1972 };
1973
1974 for (param_impl, param_trait) in
1975 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1976 {
1977 use GenericParamDefKind::*;
1978 if match (¶m_impl.kind, ¶m_trait.kind) {
1979 (Const { .. }, Const { .. })
1980 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1981 {
1982 true
1983 }
1984 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1985 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1988 (Lifetime { .. }, _) | (_, Lifetime { .. }) => {
1989 bug!("lifetime params are expected to be filtered by `ty_const_params_of`")
1990 }
1991 } {
1992 let param_impl_span = tcx.def_span(param_impl.def_id);
1993 let param_trait_span = tcx.def_span(param_trait.def_id);
1994
1995 let mut err = struct_span_code_err!(
1996 tcx.dcx(),
1997 param_impl_span,
1998 E0053,
1999 "{} `{}` has an incompatible generic parameter for trait `{}`",
2000 impl_item.descr(),
2001 trait_item.name(),
2002 &tcx.def_path_str(tcx.parent(trait_item.def_id))
2003 );
2004
2005 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
2006 Const { .. } => {
2007 format!(
2008 "{} const parameter of type `{}`",
2009 prefix,
2010 tcx.type_of(param.def_id).instantiate_identity()
2011 )
2012 }
2013 Type { .. } => format!("{prefix} type parameter"),
2014 Lifetime { .. } => span_bug!(
2015 tcx.def_span(param.def_id),
2016 "lifetime params are expected to be filtered by `ty_const_params_of`"
2017 ),
2018 };
2019
2020 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
2021 err.span_label(trait_header_span, "");
2022 err.span_label(param_trait_span, make_param_message("expected", param_trait));
2023
2024 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
2025 err.span_label(impl_header_span, "");
2026 err.span_label(param_impl_span, make_param_message("found", param_impl));
2027
2028 let reported = err.emit_unless_delay(delay);
2029 return Err(reported);
2030 }
2031 }
2032
2033 Ok(())
2034}
2035
2036fn compare_impl_const<'tcx>(
2037 tcx: TyCtxt<'tcx>,
2038 impl_const_item: ty::AssocItem,
2039 trait_const_item: ty::AssocItem,
2040 impl_trait_ref: ty::TraitRef<'tcx>,
2041) -> Result<(), ErrorGuaranteed> {
2042 compare_type_const(tcx, impl_const_item, trait_const_item)?;
2043 compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
2044 compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
2045 check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
2046 compare_const_predicate_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
2047}
2048
2049fn compare_type_const<'tcx>(
2050 tcx: TyCtxt<'tcx>,
2051 impl_const_item: ty::AssocItem,
2052 trait_const_item: ty::AssocItem,
2053) -> Result<(), ErrorGuaranteed> {
2054 let impl_is_type_const =
2055 find_attr!(tcx.get_all_attrs(impl_const_item.def_id), AttributeKind::TypeConst(_));
2056 let trait_type_const_span = find_attr!(
2057 tcx.get_all_attrs(trait_const_item.def_id),
2058 AttributeKind::TypeConst(sp) => *sp
2059 );
2060
2061 if let Some(trait_type_const_span) = trait_type_const_span
2062 && !impl_is_type_const
2063 {
2064 return Err(tcx
2065 .dcx()
2066 .struct_span_err(
2067 tcx.def_span(impl_const_item.def_id),
2068 "implementation of `#[type_const]` const must be marked with `#[type_const]`",
2069 )
2070 .with_span_note(
2071 MultiSpan::from_spans(vec![
2072 tcx.def_span(trait_const_item.def_id),
2073 trait_type_const_span,
2074 ]),
2075 "trait declaration of const is marked with `#[type_const]`",
2076 )
2077 .emit());
2078 }
2079 Ok(())
2080}
2081
2082#[instrument(level = "debug", skip(tcx))]
2086fn compare_const_predicate_entailment<'tcx>(
2087 tcx: TyCtxt<'tcx>,
2088 impl_ct: ty::AssocItem,
2089 trait_ct: ty::AssocItem,
2090 impl_trait_ref: ty::TraitRef<'tcx>,
2091) -> Result<(), ErrorGuaranteed> {
2092 let impl_ct_def_id = impl_ct.def_id.expect_local();
2093 let impl_ct_span = tcx.def_span(impl_ct_def_id);
2094
2095 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto(
2101 tcx,
2102 impl_ct.container_id(tcx),
2103 impl_trait_ref.args,
2104 );
2105
2106 let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
2109
2110 let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
2111 let code = ObligationCauseCode::CompareImplItem {
2112 impl_item_def_id: impl_ct_def_id,
2113 trait_item_def_id: trait_ct.def_id,
2114 kind: impl_ct.kind,
2115 };
2116 let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());
2117
2118 let impl_ct_predicates = tcx.predicates_of(impl_ct.def_id);
2119 let trait_ct_predicates = tcx.predicates_of(trait_ct.def_id);
2120
2121 let impl_predicates = tcx.predicates_of(impl_ct_predicates.parent.unwrap());
2124 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2125 hybrid_preds.extend(
2126 trait_ct_predicates
2127 .instantiate_own(tcx, trait_to_impl_args)
2128 .map(|(predicate, _)| predicate),
2129 );
2130
2131 let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
2132 let param_env = traits::normalize_param_env_or_error(
2133 tcx,
2134 param_env,
2135 ObligationCause::misc(impl_ct_span, impl_ct_def_id),
2136 );
2137
2138 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2139 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2140
2141 let impl_ct_own_bounds = impl_ct_predicates.instantiate_own_identity();
2142 for (predicate, span) in impl_ct_own_bounds {
2143 let cause = ObligationCause::misc(span, impl_ct_def_id);
2144 let predicate = ocx.normalize(&cause, param_env, predicate);
2145
2146 let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
2147 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2148 }
2149
2150 let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
2152 debug!(?impl_ty);
2153
2154 let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
2155 debug!(?trait_ty);
2156
2157 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
2158
2159 if let Err(terr) = err {
2160 debug!(?impl_ty, ?trait_ty);
2161
2162 let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
2164 cause.span = ty.span;
2165
2166 let mut diag = struct_span_code_err!(
2167 tcx.dcx(),
2168 cause.span,
2169 E0326,
2170 "implemented const `{}` has an incompatible type for trait",
2171 trait_ct.name()
2172 );
2173
2174 let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
2175 let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
2177 ty.span
2178 });
2179
2180 infcx.err_ctxt().note_type_err(
2181 &mut diag,
2182 &cause,
2183 trait_c_span.map(|span| (span, Cow::from("type in trait"), false)),
2184 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2185 expected: trait_ty.into(),
2186 found: impl_ty.into(),
2187 }))),
2188 terr,
2189 false,
2190 None,
2191 );
2192 return Err(diag.emit());
2193 };
2194
2195 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2198 if !errors.is_empty() {
2199 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2200 }
2201
2202 ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env, [])
2203}
2204
2205#[instrument(level = "debug", skip(tcx))]
2206fn compare_impl_ty<'tcx>(
2207 tcx: TyCtxt<'tcx>,
2208 impl_ty: ty::AssocItem,
2209 trait_ty: ty::AssocItem,
2210 impl_trait_ref: ty::TraitRef<'tcx>,
2211) -> Result<(), ErrorGuaranteed> {
2212 compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2213 compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2214 check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2215 compare_type_predicate_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2216 check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2217}
2218
2219#[instrument(level = "debug", skip(tcx))]
2222fn compare_type_predicate_entailment<'tcx>(
2223 tcx: TyCtxt<'tcx>,
2224 impl_ty: ty::AssocItem,
2225 trait_ty: ty::AssocItem,
2226 impl_trait_ref: ty::TraitRef<'tcx>,
2227) -> Result<(), ErrorGuaranteed> {
2228 let impl_def_id = impl_ty.container_id(tcx);
2229 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2230 tcx,
2231 impl_def_id,
2232 impl_trait_ref.args,
2233 );
2234
2235 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
2236 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
2237
2238 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own_identity();
2239 if impl_ty_own_bounds.len() == 0 {
2241 return Ok(());
2243 }
2244
2245 let impl_ty_def_id = impl_ty.def_id.expect_local();
2249 debug!(?trait_to_impl_args);
2250
2251 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
2254 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2255 hybrid_preds.extend(
2256 trait_ty_predicates
2257 .instantiate_own(tcx, trait_to_impl_args)
2258 .map(|(predicate, _)| predicate),
2259 );
2260 debug!(?hybrid_preds);
2261
2262 let impl_ty_span = tcx.def_span(impl_ty_def_id);
2263 let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2264
2265 let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2266 if is_conditionally_const {
2267 hybrid_preds.extend(
2270 tcx.const_conditions(impl_ty_predicates.parent.unwrap())
2271 .instantiate_identity(tcx)
2272 .into_iter()
2273 .chain(
2274 tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2275 )
2276 .map(|(trait_ref, _)| {
2277 trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2278 }),
2279 );
2280 }
2281
2282 let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
2283 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2284 debug!(caller_bounds=?param_env.caller_bounds());
2285
2286 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2287 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2288
2289 for (predicate, span) in impl_ty_own_bounds {
2290 let cause = ObligationCause::misc(span, impl_ty_def_id);
2291 let predicate = ocx.normalize(&cause, param_env, predicate);
2292
2293 let cause = ObligationCause::new(
2294 span,
2295 impl_ty_def_id,
2296 ObligationCauseCode::CompareImplItem {
2297 impl_item_def_id: impl_ty.def_id.expect_local(),
2298 trait_item_def_id: trait_ty.def_id,
2299 kind: impl_ty.kind,
2300 },
2301 );
2302 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2303 }
2304
2305 if is_conditionally_const {
2306 let impl_ty_own_const_conditions =
2308 tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2309 for (const_condition, span) in impl_ty_own_const_conditions {
2310 let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2311 let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2312
2313 let cause = ObligationCause::new(
2314 span,
2315 impl_ty_def_id,
2316 ObligationCauseCode::CompareImplItem {
2317 impl_item_def_id: impl_ty_def_id,
2318 trait_item_def_id: trait_ty.def_id,
2319 kind: impl_ty.kind,
2320 },
2321 );
2322 ocx.register_obligation(traits::Obligation::new(
2323 tcx,
2324 cause,
2325 param_env,
2326 const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2327 ));
2328 }
2329 }
2330
2331 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2334 if !errors.is_empty() {
2335 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2336 return Err(reported);
2337 }
2338
2339 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2342}
2343
2344#[instrument(level = "debug", skip(tcx))]
2358pub(super) fn check_type_bounds<'tcx>(
2359 tcx: TyCtxt<'tcx>,
2360 trait_ty: ty::AssocItem,
2361 impl_ty: ty::AssocItem,
2362 impl_trait_ref: ty::TraitRef<'tcx>,
2363) -> Result<(), ErrorGuaranteed> {
2364 tcx.ensure_ok().coherent_trait(impl_trait_ref.def_id)?;
2367
2368 let param_env = tcx.param_env(impl_ty.def_id);
2369 debug!(?param_env);
2370
2371 let container_id = impl_ty.container_id(tcx);
2372 let impl_ty_def_id = impl_ty.def_id.expect_local();
2373 let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2374 let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2375
2376 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2377 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2378
2379 let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2383 tcx.def_span(impl_ty_def_id)
2384 } else {
2385 match tcx.hir_node_by_def_id(impl_ty_def_id) {
2386 hir::Node::TraitItem(hir::TraitItem {
2387 kind: hir::TraitItemKind::Type(_, Some(ty)),
2388 ..
2389 }) => ty.span,
2390 hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2391 item => span_bug!(
2392 tcx.def_span(impl_ty_def_id),
2393 "cannot call `check_type_bounds` on item: {item:?}",
2394 ),
2395 }
2396 };
2397 let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2398
2399 let normalize_cause = ObligationCause::new(
2400 impl_ty_span,
2401 impl_ty_def_id,
2402 ObligationCauseCode::CheckAssociatedTypeBounds {
2403 impl_item_def_id: impl_ty.def_id.expect_local(),
2404 trait_item_def_id: trait_ty.def_id,
2405 },
2406 );
2407 let mk_cause = |span: Span| {
2408 let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2409 ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2410 };
2411
2412 let mut obligations: Vec<_> = util::elaborate(
2413 tcx,
2414 tcx.explicit_item_bounds(trait_ty.def_id).iter_instantiated_copied(tcx, rebased_args).map(
2415 |(concrete_ty_bound, span)| {
2416 debug!(?concrete_ty_bound);
2417 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2418 },
2419 ),
2420 )
2421 .collect();
2422
2423 if tcx.is_conditionally_const(impl_ty_def_id) {
2425 obligations.extend(util::elaborate(
2426 tcx,
2427 tcx.explicit_implied_const_bounds(trait_ty.def_id)
2428 .iter_instantiated_copied(tcx, rebased_args)
2429 .map(|(c, span)| {
2430 traits::Obligation::new(
2431 tcx,
2432 mk_cause(span),
2433 param_env,
2434 c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2435 )
2436 }),
2437 ));
2438 }
2439 debug!(item_bounds=?obligations);
2440
2441 let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2446 for obligation in &mut obligations {
2447 match ocx.deeply_normalize(&normalize_cause, normalize_param_env, obligation.predicate) {
2448 Ok(pred) => obligation.predicate = pred,
2449 Err(e) => {
2450 return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2451 }
2452 }
2453 }
2454
2455 ocx.register_obligations(obligations);
2458 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2459 if !errors.is_empty() {
2460 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2461 return Err(reported);
2462 }
2463
2464 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2467}
2468
2469fn param_env_with_gat_bounds<'tcx>(
2517 tcx: TyCtxt<'tcx>,
2518 impl_ty: ty::AssocItem,
2519 impl_trait_ref: ty::TraitRef<'tcx>,
2520) -> ty::ParamEnv<'tcx> {
2521 let param_env = tcx.param_env(impl_ty.def_id);
2522 let container_id = impl_ty.container_id(tcx);
2523 let mut predicates = param_env.caller_bounds().to_vec();
2524
2525 let impl_tys_to_install = match impl_ty.kind {
2530 ty::AssocKind::Type {
2531 data:
2532 ty::AssocTypeData::Rpitit(
2533 ty::ImplTraitInTraitData::Impl { fn_def_id }
2534 | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2535 ),
2536 } => tcx
2537 .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2538 .iter()
2539 .map(|def_id| tcx.associated_item(*def_id))
2540 .collect(),
2541 _ => vec![impl_ty],
2542 };
2543
2544 for impl_ty in impl_tys_to_install {
2545 let trait_ty = match impl_ty.container {
2546 ty::AssocContainer::InherentImpl => bug!(),
2547 ty::AssocContainer::Trait => impl_ty,
2548 ty::AssocContainer::TraitImpl(Err(_)) => continue,
2549 ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2550 tcx.associated_item(trait_item_def_id)
2551 }
2552 };
2553
2554 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
2555 smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2556 let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2558 .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2559 GenericParamDefKind::Type { .. } => {
2560 let kind = ty::BoundTyKind::Param(param.def_id);
2561 let bound_var = ty::BoundVariableKind::Ty(kind);
2562 bound_vars.push(bound_var);
2563 Ty::new_bound(
2564 tcx,
2565 ty::INNERMOST,
2566 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2567 )
2568 .into()
2569 }
2570 GenericParamDefKind::Lifetime => {
2571 let kind = ty::BoundRegionKind::Named(param.def_id);
2572 let bound_var = ty::BoundVariableKind::Region(kind);
2573 bound_vars.push(bound_var);
2574 ty::Region::new_bound(
2575 tcx,
2576 ty::INNERMOST,
2577 ty::BoundRegion {
2578 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2579 kind,
2580 },
2581 )
2582 .into()
2583 }
2584 GenericParamDefKind::Const { .. } => {
2585 let bound_var = ty::BoundVariableKind::Const;
2586 bound_vars.push(bound_var);
2587 ty::Const::new_bound(
2588 tcx,
2589 ty::INNERMOST,
2590 ty::BoundConst { var: ty::BoundVar::from_usize(bound_vars.len() - 1) },
2591 )
2592 .into()
2593 }
2594 });
2595 let normalize_impl_ty =
2605 tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args);
2606 let rebased_args =
2607 normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2608 let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2609
2610 match normalize_impl_ty.kind() {
2611 ty::Alias(ty::Projection, proj)
2612 if proj.def_id == trait_ty.def_id && proj.args == rebased_args =>
2613 {
2614 }
2620 _ => predicates.push(
2621 ty::Binder::bind_with_vars(
2622 ty::ProjectionPredicate {
2623 projection_term: ty::AliasTerm::new_from_args(
2624 tcx,
2625 trait_ty.def_id,
2626 rebased_args,
2627 ),
2628 term: normalize_impl_ty.into(),
2629 },
2630 bound_vars,
2631 )
2632 .upcast(tcx),
2633 ),
2634 };
2635 }
2636
2637 ty::ParamEnv::new(tcx.mk_clauses(&predicates))
2638}
2639
2640fn try_report_async_mismatch<'tcx>(
2643 tcx: TyCtxt<'tcx>,
2644 infcx: &InferCtxt<'tcx>,
2645 errors: &[FulfillmentError<'tcx>],
2646 trait_m: ty::AssocItem,
2647 impl_m: ty::AssocItem,
2648 impl_sig: ty::FnSig<'tcx>,
2649) -> Result<(), ErrorGuaranteed> {
2650 if !tcx.asyncness(trait_m.def_id).is_async() {
2651 return Ok(());
2652 }
2653
2654 let ty::Alias(ty::Projection, ty::AliasTy { def_id: async_future_def_id, .. }) =
2655 *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2656 else {
2657 bug!("expected `async fn` to return an RPITIT");
2658 };
2659
2660 for error in errors {
2661 if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2662 && def_id == async_future_def_id
2663 && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2664 && let Some(proj) = proj.no_bound_vars()
2665 && infcx.can_eq(
2666 error.root_obligation.param_env,
2667 proj.term.expect_type(),
2668 impl_sig.output(),
2669 )
2670 {
2671 return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2674 span: tcx.def_span(impl_m.def_id),
2675 method_name: tcx.item_ident(impl_m.def_id),
2676 trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2677 }));
2678 }
2679 }
2680
2681 Ok(())
2682}