1 use super::potentially_plural_count;
2 use crate::errors::LifetimesOrBoundsMismatchOnTrait;
3 use hir::def_id::{DefId, LocalDefId};
4 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
6 pluralize, struct_span_err, Applicability, DiagnosticId, ErrorGuaranteed, MultiSpan,
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::intravisit;
11 use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
12 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
13 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14 use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
15 use rustc_infer::traits::util;
16 use rustc_middle::ty::error::{ExpectedFound, TypeError};
17 use rustc_middle::ty::util::ExplicitSelf;
18 use rustc_middle::ty::{
19 self, DefIdTree, InternalSubsts, Ty, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
21 use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt};
23 use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt;
24 use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _;
25 use rustc_trait_selection::traits::{
26 self, ObligationCause, ObligationCauseCode, ObligationCtxt, Reveal,
30 /// Checks that a method from an impl conforms to the signature of
31 /// the same method as declared in the trait.
35 /// - `impl_m`: type of the method we are checking
36 /// - `impl_m_span`: span to use for reporting errors
37 /// - `trait_m`: the method in the trait
38 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
39 pub(super) fn compare_impl_method<'tcx>(
41 impl_m: &ty::AssocItem,
42 trait_m: &ty::AssocItem,
43 impl_trait_ref: ty::TraitRef<'tcx>,
44 trait_item_span: Option<Span>,
46 debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
48 let impl_m_span = tcx.def_span(impl_m.def_id);
50 let _: Result<_, ErrorGuaranteed> = try {
51 compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)?;
52 compare_number_of_generics(tcx, impl_m, trait_m, trait_item_span, false)?;
53 compare_generic_param_kinds(tcx, impl_m, trait_m, false)?;
54 compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)?;
55 compare_synthetic_generics(tcx, impl_m, trait_m)?;
56 compare_asyncness(tcx, impl_m, impl_m_span, trait_m, trait_item_span)?;
57 compare_method_predicate_entailment(
63 CheckImpliedWfMode::Check,
68 /// This function is best explained by example. Consider a trait:
70 /// trait Trait<'t, T> {
72 /// fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
77 /// impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
79 /// fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo;
82 /// We wish to decide if those two method types are compatible.
83 /// For this we have to show that, assuming the bounds of the impl hold, the
84 /// bounds of `trait_m` imply the bounds of `impl_m`.
86 /// We start out with `trait_to_impl_substs`, that maps the trait
87 /// type parameters to impl type parameters. This is taken from the
88 /// impl trait reference:
90 /// trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
92 /// We create a mapping `dummy_substs` that maps from the impl type
93 /// parameters to fresh types and regions. For type parameters,
94 /// this is the identity transform, but we could as well use any
95 /// placeholder types. For regions, we convert from bound to free
96 /// regions (Note: but only early-bound regions, i.e., those
97 /// declared on the impl or used in type parameter bounds).
99 /// impl_to_placeholder_substs = {'i => 'i0, U => U0, N => N0 }
101 /// Now we can apply `placeholder_substs` to the type of the impl method
102 /// to yield a new function type in terms of our fresh, placeholder
105 /// <'b> fn(t: &'i0 U0, m: &'b) -> Foo
107 /// We now want to extract and substitute the type of the *trait*
108 /// method and compare it. To do so, we must create a compound
109 /// substitution by combining `trait_to_impl_substs` and
110 /// `impl_to_placeholder_substs`, and also adding a mapping for the method
111 /// type parameters. We extend the mapping to also include
112 /// the method parameters.
114 /// trait_to_placeholder_substs = { T => &'i0 U0, Self => Foo, M => N0 }
116 /// Applying this to the trait method type yields:
118 /// <'a> fn(t: &'i0 U0, m: &'a) -> Foo
120 /// This type is also the same but the name of the bound region (`'a`
121 /// vs `'b`). However, the normal subtyping rules on fn types handle
122 /// this kind of equivalency just fine.
124 /// We now use these substitutions to ensure that all declared bounds are
125 /// satisfied by the implementation's method.
127 /// We do this by creating a parameter environment which contains a
128 /// substitution corresponding to `impl_to_placeholder_substs`. We then build
129 /// `trait_to_placeholder_substs` and use it to convert the predicates contained
130 /// in the `trait_m` generics to the placeholder form.
132 /// Finally we register each of these predicates as an obligation and check that
134 #[instrument(level = "debug", skip(tcx, impl_m_span, impl_trait_ref))]
135 fn compare_method_predicate_entailment<'tcx>(
137 impl_m: &ty::AssocItem,
139 trait_m: &ty::AssocItem,
140 impl_trait_ref: ty::TraitRef<'tcx>,
141 check_implied_wf: CheckImpliedWfMode,
142 ) -> Result<(), ErrorGuaranteed> {
143 let trait_to_impl_substs = impl_trait_ref.substs;
145 // This node-id should be used for the `body_id` field on each
146 // `ObligationCause` (and the `FnCtxt`).
148 // FIXME(@lcnr): remove that after removing `cause.body_id` from
150 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
151 let cause = ObligationCause::new(
154 ObligationCauseCode::CompareImplItemObligation {
155 impl_item_def_id: impl_m.def_id.expect_local(),
156 trait_item_def_id: trait_m.def_id,
161 // Create mapping from impl to placeholder.
162 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
164 // Create mapping from trait to placeholder.
165 let trait_to_placeholder_substs =
166 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
167 debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_substs);
169 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
170 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
172 // Check region bounds.
173 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, false)?;
175 // Create obligations for each predicate declared by the impl
176 // definition in the context of the trait's parameter
177 // environment. We can't just use `impl_env.caller_bounds`,
178 // however, because we want to replace all late-bound regions with
180 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
181 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
183 debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
185 // This is the only tricky bit of the new way we check implementation methods
186 // We need to build a set of predicates where only the method-level bounds
187 // are from the trait and we assume all other bounds from the implementation
188 // to be previously satisfied.
190 // We then register the obligations from the impl_m and check to see
191 // if all constraints hold.
192 hybrid_preds.predicates.extend(
194 .instantiate_own(tcx, trait_to_placeholder_substs)
195 .map(|(predicate, _)| predicate),
198 // Construct trait parameter environment and then shift it into the placeholder viewpoint.
199 // The key step here is to update the caller_bounds's predicates to be
200 // the new hybrid bounds we computed.
201 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
202 let param_env = ty::ParamEnv::new(
203 tcx.intern_predicates(&hybrid_preds.predicates),
205 hir::Constness::NotConst,
207 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
209 let infcx = &tcx.infer_ctxt().build();
210 let ocx = ObligationCtxt::new(infcx);
212 debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
214 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
215 for (predicate, span) in impl_m_own_bounds {
216 let normalize_cause = traits::ObligationCause::misc(span, impl_m_hir_id);
217 let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
219 let cause = ObligationCause::new(
222 ObligationCauseCode::CompareImplItemObligation {
223 impl_item_def_id: impl_m.def_id.expect_local(),
224 trait_item_def_id: trait_m.def_id,
228 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
231 // We now need to check that the signature of the impl method is
232 // compatible with that of the trait method. We do this by
233 // checking that `impl_fty <: trait_fty`.
235 // FIXME. Unfortunately, this doesn't quite work right now because
236 // associated type normalization is not integrated into subtype
237 // checks. For the comparison to be valid, we need to
238 // normalize the associated types in the impl/trait methods
239 // first. However, because function types bind regions, just
240 // calling `normalize_associated_types_in` would have no effect on
241 // any associated types appearing in the fn arguments or return
244 // Compute placeholder form of impl and trait method tys.
247 let mut wf_tys = FxIndexSet::default();
249 let unnormalized_impl_sig = infcx.replace_bound_vars_with_fresh_vars(
251 infer::HigherRankedType,
252 tcx.fn_sig(impl_m.def_id),
254 let unnormalized_impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(unnormalized_impl_sig));
256 let norm_cause = ObligationCause::misc(impl_m_span, impl_m_hir_id);
257 let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig);
258 debug!("compare_impl_method: impl_fty={:?}", impl_sig);
260 let trait_sig = tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs);
261 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
263 // Next, add all inputs and output as well-formed tys. Importantly,
264 // we have to do this before normalization, since the normalized ty may
265 // not contain the input parameters. See issue #87748.
266 wf_tys.extend(trait_sig.inputs_and_output.iter());
267 let trait_sig = ocx.normalize(&norm_cause, param_env, trait_sig);
268 // We also have to add the normalized trait signature
269 // as we don't normalize during implied bounds computation.
270 wf_tys.extend(trait_sig.inputs_and_output.iter());
271 let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
273 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
275 // FIXME: We'd want to keep more accurate spans than "the method signature" when
276 // processing the comparison between the trait and impl fn, but we sadly lose them
277 // and point at the whole signature when a trait bound or specific input or output
278 // type would be more appropriate. In other places we have a `Vec<Span>`
279 // corresponding to their `Vec<Predicate>`, but we don't have that here.
280 // Fixing this would improve the output of test `issue-83765.rs`.
281 let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
283 if let Err(terr) = result {
284 debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
286 let emitted = report_trait_method_mismatch(
290 (trait_m, trait_sig),
297 if check_implied_wf == CheckImpliedWfMode::Check {
298 // We need to check that the impl's args are well-formed given
299 // the hybrid param-env (impl + trait method where-clauses).
300 ocx.register_obligation(traits::Obligation::new(
302 ObligationCause::dummy(),
304 ty::Binder::dummy(ty::PredicateKind::WellFormed(unnormalized_impl_fty.into())),
308 // Check that all obligations are satisfied by the implementation's
310 let errors = ocx.select_all_or_error();
311 if !errors.is_empty() {
312 match check_implied_wf {
313 CheckImpliedWfMode::Check => {
314 return compare_method_predicate_entailment(
320 CheckImpliedWfMode::Skip,
323 // If the skip-mode was successful, emit a lint.
324 emit_implied_wf_lint(infcx.tcx, impl_m, impl_m_hir_id, vec![]);
327 CheckImpliedWfMode::Skip => {
328 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
329 return Err(reported);
334 // Finally, resolve all regions. This catches wily misuses of
335 // lifetime parameters.
336 let outlives_env = OutlivesEnvironment::with_bounds(
339 infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys.clone()),
341 infcx.process_registered_region_obligations(
342 outlives_env.region_bound_pairs(),
343 outlives_env.param_env,
345 let errors = infcx.resolve_regions(&outlives_env);
346 if !errors.is_empty() {
347 // FIXME(compiler-errors): This can be simplified when IMPLIED_BOUNDS_ENTAILMENT
348 // becomes a hard error (i.e. ideally we'd just call `resolve_regions_and_report_errors`
349 match check_implied_wf {
350 CheckImpliedWfMode::Check => {
351 return compare_method_predicate_entailment(
357 CheckImpliedWfMode::Skip,
360 let bad_args = extract_bad_args_for_implies_lint(
363 (trait_m, trait_sig),
364 // Unnormalized impl sig corresponds to the HIR types written
365 (impl_m, unnormalized_impl_sig),
368 // If the skip-mode was successful, emit a lint.
369 emit_implied_wf_lint(tcx, impl_m, impl_m_hir_id, bad_args);
372 CheckImpliedWfMode::Skip => {
373 if infcx.tainted_by_errors().is_none() {
374 infcx.err_ctxt().report_region_errors(impl_m.def_id.expect_local(), &errors);
378 .delay_span_bug(rustc_span::DUMMY_SP, "error should have been emitted"));
386 fn extract_bad_args_for_implies_lint<'tcx>(
388 errors: &[infer::RegionResolutionError<'tcx>],
389 (trait_m, trait_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
390 (impl_m, impl_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
392 ) -> Vec<(Span, Option<String>)> {
393 let mut blame_generics = vec![];
394 for error in errors {
395 // Look for the subregion origin that contains an input/output type
396 let origin = match error {
397 infer::RegionResolutionError::ConcreteFailure(o, ..) => o,
398 infer::RegionResolutionError::GenericBoundFailure(o, ..) => o,
399 infer::RegionResolutionError::SubSupConflict(_, _, o, ..) => o,
400 infer::RegionResolutionError::UpperBoundUniverseConflict(.., o, _) => o,
402 // Extract (possible) input/output types from origin
404 infer::SubregionOrigin::Subtype(trace) => {
405 if let Some((a, b)) = trace.values.ty() {
406 blame_generics.extend([a, b]);
409 infer::SubregionOrigin::RelateParamBound(_, ty, _) => blame_generics.push(*ty),
410 infer::SubregionOrigin::ReferenceOutlivesReferent(ty, _) => blame_generics.push(*ty),
415 let fn_decl = tcx.hir().fn_decl_by_hir_id(hir_id).unwrap();
416 let opt_ret_ty = match fn_decl.output {
417 hir::FnRetTy::DefaultReturn(_) => None,
418 hir::FnRetTy::Return(ty) => Some(ty),
421 // Map late-bound regions from trait to impl, so the names are right.
422 let mapping = std::iter::zip(
423 tcx.fn_sig(trait_m.def_id).bound_vars(),
424 tcx.fn_sig(impl_m.def_id).bound_vars(),
426 .filter_map(|(impl_bv, trait_bv)| {
427 if let ty::BoundVariableKind::Region(impl_bv) = impl_bv
428 && let ty::BoundVariableKind::Region(trait_bv) = trait_bv
430 Some((impl_bv, trait_bv))
437 // For each arg, see if it was in the "blame" of any of the region errors.
438 // If so, then try to produce a suggestion to replace the argument type with
439 // one from the trait.
440 let mut bad_args = vec![];
441 for (idx, (ty, hir_ty)) in
442 std::iter::zip(impl_sig.inputs_and_output, fn_decl.inputs.iter().chain(opt_ret_ty))
445 let expected_ty = trait_sig.inputs_and_output[idx]
446 .fold_with(&mut RemapLateBound { tcx, mapping: &mapping });
447 if blame_generics.iter().any(|blame| ty.contains(*blame)) {
448 let expected_ty_sugg = expected_ty.to_string();
451 // Only suggest something if it actually changed.
452 (expected_ty_sugg != ty.to_string()).then_some(expected_ty_sugg),
460 struct RemapLateBound<'a, 'tcx> {
462 mapping: &'a FxHashMap<ty::BoundRegionKind, ty::BoundRegionKind>,
465 impl<'tcx> TypeFolder<'tcx> for RemapLateBound<'_, 'tcx> {
466 fn tcx(&self) -> TyCtxt<'tcx> {
470 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
471 if let ty::ReFree(fr) = *r {
472 self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
475 .get(&fr.bound_region)
477 .unwrap_or(fr.bound_region),
486 fn emit_implied_wf_lint<'tcx>(
488 impl_m: &ty::AssocItem,
490 bad_args: Vec<(Span, Option<String>)>,
492 let span: MultiSpan = if bad_args.is_empty() {
493 tcx.def_span(impl_m.def_id).into()
495 bad_args.iter().map(|(span, _)| *span).collect::<Vec<_>>().into()
497 tcx.struct_span_lint_hir(
498 rustc_session::lint::builtin::IMPLIED_BOUNDS_ENTAILMENT,
501 "impl method assumes more implied bounds than the corresponding trait method",
503 let bad_args: Vec<_> =
504 bad_args.into_iter().filter_map(|(span, sugg)| Some((span, sugg?))).collect();
505 if !bad_args.is_empty() {
506 lint.multipart_suggestion(
508 "replace {} type{} to make the impl signature compatible",
509 pluralize!("this", bad_args.len()),
510 pluralize!(bad_args.len())
513 Applicability::MaybeIncorrect,
521 #[derive(Debug, PartialEq, Eq)]
522 enum CheckImpliedWfMode {
523 /// Checks implied well-formedness of the impl method. If it fails, we will
524 /// re-check with `Skip`, and emit a lint if it succeeds.
526 /// Skips checking implied well-formedness of the impl method, but will emit
527 /// a lint if the `compare_method_predicate_entailment` succeeded. This means that
528 /// the reason that we had failed earlier during `Check` was due to the impl
529 /// having stronger requirements than the trait.
533 fn compare_asyncness<'tcx>(
535 impl_m: &ty::AssocItem,
537 trait_m: &ty::AssocItem,
538 trait_item_span: Option<Span>,
539 ) -> Result<(), ErrorGuaranteed> {
540 if tcx.asyncness(trait_m.def_id) == hir::IsAsync::Async {
541 match tcx.fn_sig(impl_m.def_id).skip_binder().output().kind() {
542 ty::Alias(ty::Opaque, ..) => {
543 // allow both `async fn foo()` and `fn foo() -> impl Future`
546 // We don't know if it's ok, but at least it's already an error.
549 return Err(tcx.sess.emit_err(crate::errors::AsyncTraitImplShouldBeAsync {
551 method_name: trait_m.name,
561 /// Given a method def-id in an impl, compare the method signature of the impl
562 /// against the trait that it's implementing. In doing so, infer the hidden types
563 /// that this method's signature provides to satisfy each return-position `impl Trait`
564 /// in the trait signature.
566 /// The method is also responsible for making sure that the hidden types for each
567 /// RPITIT actually satisfy the bounds of the `impl Trait`, i.e. that if we infer
568 /// `impl Trait = Foo`, that `Foo: Trait` holds.
570 /// For example, given the sample code:
573 /// #![feature(return_position_impl_trait_in_trait)]
575 /// use std::ops::Deref;
578 /// fn bar() -> impl Deref<Target = impl Sized>;
579 /// // ^- RPITIT #1 ^- RPITIT #2
582 /// impl Foo for () {
583 /// fn bar() -> Box<String> { Box::new(String::new()) }
587 /// The hidden types for the RPITITs in `bar` would be inferred to:
588 /// * `impl Deref` (RPITIT #1) = `Box<String>`
589 /// * `impl Sized` (RPITIT #2) = `String`
591 /// The relationship between these two types is straightforward in this case, but
592 /// may be more tenuously connected via other `impl`s and normalization rules for
593 /// cases of more complicated nested RPITITs.
594 #[instrument(skip(tcx), level = "debug", ret)]
595 pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
598 ) -> Result<&'tcx FxHashMap<DefId, Ty<'tcx>>, ErrorGuaranteed> {
599 let impl_m = tcx.opt_associated_item(def_id).unwrap();
600 let trait_m = tcx.opt_associated_item(impl_m.trait_item_def_id.unwrap()).unwrap();
602 tcx.impl_trait_ref(impl_m.impl_container(tcx).unwrap()).unwrap().subst_identity();
603 let param_env = tcx.param_env(def_id);
605 // First, check a few of the same things as `compare_impl_method`,
606 // just so we don't ICE during substitution later.
607 compare_number_of_generics(tcx, impl_m, trait_m, tcx.hir().span_if_local(impl_m.def_id), true)?;
608 compare_generic_param_kinds(tcx, impl_m, trait_m, true)?;
609 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, true)?;
611 let trait_to_impl_substs = impl_trait_ref.substs;
613 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
614 let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
615 let cause = ObligationCause::new(
618 ObligationCauseCode::CompareImplItemObligation {
619 impl_item_def_id: impl_m.def_id.expect_local(),
620 trait_item_def_id: trait_m.def_id,
625 // Create mapping from impl to placeholder.
626 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
628 // Create mapping from trait to placeholder.
629 let trait_to_placeholder_substs =
630 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
632 let infcx = &tcx.infer_ctxt().build();
633 let ocx = ObligationCtxt::new(infcx);
635 // Normalize the impl signature with fresh variables for lifetime inference.
636 let norm_cause = ObligationCause::misc(return_span, impl_m_hir_id);
637 let impl_sig = ocx.normalize(
640 infcx.replace_bound_vars_with_fresh_vars(
642 infer::HigherRankedType,
643 tcx.fn_sig(impl_m.def_id),
646 impl_sig.error_reported()?;
647 let impl_return_ty = impl_sig.output();
649 // Normalize the trait signature with liberated bound vars, passing it through
650 // the ImplTraitInTraitCollector, which gathers all of the RPITITs and replaces
651 // them with inference variables.
652 // We will use these inference variables to collect the hidden types of RPITITs.
653 let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_hir_id);
654 let unnormalized_trait_sig = tcx
655 .liberate_late_bound_regions(
657 tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs),
659 .fold_with(&mut collector);
660 let trait_sig = ocx.normalize(&norm_cause, param_env, unnormalized_trait_sig);
661 trait_sig.error_reported()?;
662 let trait_return_ty = trait_sig.output();
664 let wf_tys = FxIndexSet::from_iter(
665 unnormalized_trait_sig.inputs_and_output.iter().chain(trait_sig.inputs_and_output.iter()),
668 match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
671 let mut diag = struct_span_err!(
675 "method `{}` has an incompatible return type for trait",
679 infcx.err_ctxt().note_type_err(
682 hir.get_if_local(impl_m.def_id)
683 .and_then(|node| node.fn_decl())
684 .map(|decl| (decl.output.span(), "return type in trait".to_owned())),
685 Some(infer::ValuePairs::Terms(ExpectedFound {
686 expected: trait_return_ty.into(),
687 found: impl_return_ty.into(),
693 return Err(diag.emit());
697 debug!(?trait_sig, ?impl_sig, "equating function signatures");
699 // Unify the whole function signature. We need to do this to fully infer
700 // the lifetimes of the return type, but do this after unifying just the
701 // return types, since we want to avoid duplicating errors from
702 // `compare_method_predicate_entailment`.
703 match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
706 // This function gets called during `compare_method_predicate_entailment` when normalizing a
707 // signature that contains RPITIT. When the method signatures don't match, we have to
708 // emit an error now because `compare_method_predicate_entailment` will not report the error
709 // when normalization fails.
710 let emitted = report_trait_method_mismatch(
714 (trait_m, trait_sig),
722 // Check that all obligations are satisfied by the implementation's
724 let errors = ocx.select_all_or_error();
725 if !errors.is_empty() {
726 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
727 return Err(reported);
730 // Finally, resolve all regions. This catches wily misuses of
731 // lifetime parameters.
732 let outlives_environment = OutlivesEnvironment::with_bounds(
735 infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys),
737 infcx.err_ctxt().check_region_obligations_and_report_errors(
738 impl_m.def_id.expect_local(),
739 &outlives_environment,
742 let mut collected_tys = FxHashMap::default();
743 for (def_id, (ty, substs)) in collector.types {
744 match infcx.fully_resolve(ty) {
746 // `ty` contains free regions that we created earlier while liberating the
747 // trait fn signature. However, projection normalization expects `ty` to
748 // contains `def_id`'s early-bound regions.
749 let id_substs = InternalSubsts::identity_for_item(tcx, def_id);
750 debug!(?id_substs, ?substs);
751 let map: FxHashMap<ty::GenericArg<'tcx>, ty::GenericArg<'tcx>> =
752 std::iter::zip(substs, id_substs).collect();
755 // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound
756 // region substs that are synthesized during AST lowering. These are substs
757 // that are appended to the parent substs (trait and trait method). However,
758 // we're trying to infer the unsubstituted type value of the RPITIT inside
759 // the *impl*, so we can later use the impl's method substs to normalize
760 // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`).
762 // Due to the design of RPITITs, during AST lowering, we have no idea that
763 // an impl method corresponds to a trait method with RPITITs in it. Therefore,
764 // we don't have a list of early-bound region substs for the RPITIT in the impl.
765 // Since early region parameters are index-based, we can't just rebase these
766 // (trait method) early-bound region substs onto the impl, and there's no
767 // guarantee that the indices from the trait substs and impl substs line up.
768 // So to fix this, we subtract the number of trait substs and add the number of
769 // impl substs to *renumber* these early-bound regions to their corresponding
770 // indices in the impl's substitutions list.
772 // Also, we only need to account for a difference in trait and impl substs,
773 // since we previously enforce that the trait method and impl method have the
775 let num_trait_substs = trait_to_impl_substs.len();
776 let num_impl_substs = tcx.generics_of(impl_m.container_id(tcx)).params.len();
777 let ty = tcx.fold_regions(ty, |region, _| {
778 match region.kind() {
779 // Remap all free regions, which correspond to late-bound regions in the function.
781 // Remap early-bound regions as long as they don't come from the `impl` itself.
782 ty::ReEarlyBound(ebr) if tcx.parent(ebr.def_id) != impl_m.container_id(tcx) => {}
785 let Some(ty::ReEarlyBound(e)) = map.get(®ion.into()).map(|r| r.expect_region().kind())
791 "expected ReFree to map to ReEarlyBound"
793 return tcx.lifetimes.re_static;
795 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
798 index: (e.index as usize - num_trait_substs + num_impl_substs) as u32,
802 collected_tys.insert(def_id, ty);
805 let reported = tcx.sess.delay_span_bug(
807 format!("could not fully resolve: {ty} => {err:?}"),
809 collected_tys.insert(def_id, tcx.ty_error_with_guaranteed(reported));
814 Ok(&*tcx.arena.alloc(collected_tys))
817 struct ImplTraitInTraitCollector<'a, 'tcx> {
818 ocx: &'a ObligationCtxt<'a, 'tcx>,
819 types: FxHashMap<DefId, (Ty<'tcx>, ty::SubstsRef<'tcx>)>,
821 param_env: ty::ParamEnv<'tcx>,
825 impl<'a, 'tcx> ImplTraitInTraitCollector<'a, 'tcx> {
827 ocx: &'a ObligationCtxt<'a, 'tcx>,
829 param_env: ty::ParamEnv<'tcx>,
832 ImplTraitInTraitCollector { ocx, types: FxHashMap::default(), span, param_env, body_id }
836 impl<'tcx> TypeFolder<'tcx> for ImplTraitInTraitCollector<'_, 'tcx> {
837 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
841 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
842 if let ty::Alias(ty::Projection, proj) = ty.kind()
843 && self.tcx().def_kind(proj.def_id) == DefKind::ImplTraitPlaceholder
845 if let Some((ty, _)) = self.types.get(&proj.def_id) {
848 //FIXME(RPITIT): Deny nested RPITIT in substs too
849 if proj.substs.has_escaping_bound_vars() {
850 bug!("FIXME(RPITIT): error here");
852 // Replace with infer var
853 let infer_ty = self.ocx.infcx.next_ty_var(TypeVariableOrigin {
855 kind: TypeVariableOriginKind::MiscVariable,
857 self.types.insert(proj.def_id, (infer_ty, proj.substs));
858 // Recurse into bounds
859 for (pred, pred_span) in self.tcx().bound_explicit_item_bounds(proj.def_id).subst_iter_copied(self.tcx(), proj.substs) {
860 let pred = pred.fold_with(self);
861 let pred = self.ocx.normalize(
862 &ObligationCause::misc(self.span, self.body_id),
867 self.ocx.register_obligation(traits::Obligation::new(
869 ObligationCause::new(
872 ObligationCauseCode::BindingObligation(proj.def_id, pred_span),
880 ty.super_fold_with(self)
885 fn report_trait_method_mismatch<'tcx>(
886 infcx: &InferCtxt<'tcx>,
887 mut cause: ObligationCause<'tcx>,
888 terr: TypeError<'tcx>,
889 (trait_m, trait_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
890 (impl_m, impl_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
891 impl_trait_ref: ty::TraitRef<'tcx>,
892 ) -> ErrorGuaranteed {
894 let (impl_err_span, trait_err_span) =
895 extract_spans_for_error_reporting(&infcx, terr, &cause, impl_m, trait_m);
897 let mut diag = struct_span_err!(
901 "method `{}` has an incompatible type for trait",
905 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
906 if trait_m.fn_has_self_parameter =>
908 let ty = trait_sig.inputs()[0];
909 let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty()) {
910 ExplicitSelf::ByValue => "self".to_owned(),
911 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
912 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
913 _ => format!("self: {ty}"),
916 // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
917 // span points only at the type `Box<Self`>, but we want to cover the whole
918 // argument pattern and type.
919 let ImplItemKind::Fn(ref sig, body) = tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind else { bug!("{impl_m:?} is not a method") };
922 .body_param_names(body)
923 .zip(sig.decl.inputs.iter())
924 .map(|(param, ty)| param.span.to(ty.span))
926 .unwrap_or(impl_err_span);
928 diag.span_suggestion(
930 "change the self-receiver type to match the trait",
932 Applicability::MachineApplicable,
935 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
936 if trait_sig.inputs().len() == *i {
937 // Suggestion to change output type. We do not suggest in `async` functions
938 // to avoid complex logic or incorrect output.
939 if let ImplItemKind::Fn(sig, _) = &tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind
940 && !sig.header.asyncness.is_async()
942 let msg = "change the output type to match the trait";
943 let ap = Applicability::MachineApplicable;
944 match sig.decl.output {
945 hir::FnRetTy::DefaultReturn(sp) => {
946 let sugg = format!("-> {} ", trait_sig.output());
947 diag.span_suggestion_verbose(sp, msg, sugg, ap);
949 hir::FnRetTy::Return(hir_ty) => {
950 let sugg = trait_sig.output();
951 diag.span_suggestion(hir_ty.span, msg, sugg, ap);
955 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
956 diag.span_suggestion(
958 "change the parameter type to match the trait",
960 Applicability::MachineApplicable,
967 cause.span = impl_err_span;
968 infcx.err_ctxt().note_type_err(
971 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
972 Some(infer::ValuePairs::Sigs(ExpectedFound { expected: trait_sig, found: impl_sig })),
981 fn check_region_bounds_on_impl_item<'tcx>(
983 impl_m: &ty::AssocItem,
984 trait_m: &ty::AssocItem,
986 ) -> Result<(), ErrorGuaranteed> {
987 let impl_generics = tcx.generics_of(impl_m.def_id);
988 let impl_params = impl_generics.own_counts().lifetimes;
990 let trait_generics = tcx.generics_of(trait_m.def_id);
991 let trait_params = trait_generics.own_counts().lifetimes;
994 "check_region_bounds_on_impl_item: \
995 trait_generics={:?} \
997 trait_generics, impl_generics
1000 // Must have same number of early-bound lifetime parameters.
1001 // Unfortunately, if the user screws up the bounds, then this
1002 // will change classification between early and late. E.g.,
1003 // if in trait we have `<'a,'b:'a>`, and in impl we just have
1004 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
1005 // in trait but 0 in the impl. But if we report "expected 2
1006 // but found 0" it's confusing, because it looks like there
1007 // are zero. Since I don't quite know how to phrase things at
1008 // the moment, give a kind of vague error message.
1009 if trait_params != impl_params {
1012 .get_generics(impl_m.def_id.expect_local())
1013 .expect("expected impl item to have generics or else we can't compare them")
1016 let mut generics_span = None;
1017 let mut bounds_span = vec![];
1018 let mut where_span = None;
1019 if let Some(trait_node) = tcx.hir().get_if_local(trait_m.def_id)
1020 && let Some(trait_generics) = trait_node.generics()
1022 generics_span = Some(trait_generics.span);
1023 // FIXME: we could potentially look at the impl's bounds to not point at bounds that
1024 // *are* present in the impl.
1025 for p in trait_generics.predicates {
1026 if let hir::WherePredicate::BoundPredicate(pred) = p {
1027 for b in pred.bounds {
1028 if let hir::GenericBound::Outlives(lt) = b {
1029 bounds_span.push(lt.ident.span);
1034 if let Some(impl_node) = tcx.hir().get_if_local(impl_m.def_id)
1035 && let Some(impl_generics) = impl_node.generics()
1037 let mut impl_bounds = 0;
1038 for p in impl_generics.predicates {
1039 if let hir::WherePredicate::BoundPredicate(pred) = p {
1040 for b in pred.bounds {
1041 if let hir::GenericBound::Outlives(_) = b {
1047 if impl_bounds == bounds_span.len() {
1048 bounds_span = vec![];
1049 } else if impl_generics.has_where_clause_predicates {
1050 where_span = Some(impl_generics.where_clause_span);
1056 .create_err(LifetimesOrBoundsMismatchOnTrait {
1058 item_kind: assoc_item_kind_str(impl_m),
1059 ident: impl_m.ident(tcx),
1064 .emit_unless(delay);
1065 return Err(reported);
1071 #[instrument(level = "debug", skip(infcx))]
1072 fn extract_spans_for_error_reporting<'tcx>(
1073 infcx: &infer::InferCtxt<'tcx>,
1074 terr: TypeError<'_>,
1075 cause: &ObligationCause<'tcx>,
1076 impl_m: &ty::AssocItem,
1077 trait_m: &ty::AssocItem,
1078 ) -> (Span, Option<Span>) {
1079 let tcx = infcx.tcx;
1080 let mut impl_args = {
1081 let ImplItemKind::Fn(sig, _) = &tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind else { bug!("{:?} is not a method", impl_m) };
1082 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1085 let trait_args = trait_m.def_id.as_local().map(|def_id| {
1086 let TraitItemKind::Fn(sig, _) = &tcx.hir().expect_trait_item(def_id).kind else { bug!("{:?} is not a TraitItemKind::Fn", trait_m) };
1087 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1091 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1092 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1094 _ => (cause.span(), tcx.hir().span_if_local(trait_m.def_id)),
1098 fn compare_self_type<'tcx>(
1100 impl_m: &ty::AssocItem,
1102 trait_m: &ty::AssocItem,
1103 impl_trait_ref: ty::TraitRef<'tcx>,
1104 ) -> Result<(), ErrorGuaranteed> {
1105 // Try to give more informative error messages about self typing
1106 // mismatches. Note that any mismatch will also be detected
1107 // below, where we construct a canonical function type that
1108 // includes the self parameter as a normal parameter. It's just
1109 // that the error messages you get out of this code are a bit more
1110 // inscrutable, particularly for cases where one method has no
1113 let self_string = |method: &ty::AssocItem| {
1114 let untransformed_self_ty = match method.container {
1115 ty::ImplContainer => impl_trait_ref.self_ty(),
1116 ty::TraitContainer => tcx.types.self_param,
1118 let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
1119 let param_env = ty::ParamEnv::reveal_all();
1121 let infcx = tcx.infer_ctxt().build();
1122 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1123 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
1124 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
1125 ExplicitSelf::ByValue => "self".to_owned(),
1126 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
1127 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
1128 _ => format!("self: {self_arg_ty}"),
1132 match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
1133 (false, false) | (true, true) => {}
1136 let self_descr = self_string(impl_m);
1137 let mut err = struct_span_err!(
1141 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1145 err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
1146 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1147 err.span_label(span, format!("trait method declared without `{self_descr}`"));
1149 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1151 return Err(err.emit());
1155 let self_descr = self_string(trait_m);
1156 let mut err = struct_span_err!(
1160 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1164 err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
1165 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1166 err.span_label(span, format!("`{self_descr}` used in trait"));
1168 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1171 return Err(err.emit());
1178 /// Checks that the number of generics on a given assoc item in a trait impl is the same
1179 /// as the number of generics on the respective assoc item in the trait definition.
1181 /// For example this code emits the errors in the following code:
1188 /// impl Trait for () {
1191 /// type Assoc = u32;
1196 /// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
1197 /// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
1198 /// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
1199 fn compare_number_of_generics<'tcx>(
1201 impl_: &ty::AssocItem,
1202 trait_: &ty::AssocItem,
1203 trait_span: Option<Span>,
1205 ) -> Result<(), ErrorGuaranteed> {
1206 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1207 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1209 // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
1210 // in `compare_generic_param_kinds` which will give a nicer error message than something like:
1211 // "expected 1 type parameter, found 0 type parameters"
1212 if (trait_own_counts.types + trait_own_counts.consts)
1213 == (impl_own_counts.types + impl_own_counts.consts)
1219 ("type", trait_own_counts.types, impl_own_counts.types),
1220 ("const", trait_own_counts.consts, impl_own_counts.consts),
1223 let item_kind = assoc_item_kind_str(impl_);
1225 let mut err_occurred = None;
1226 for (kind, trait_count, impl_count) in matchings {
1227 if impl_count != trait_count {
1228 let arg_spans = |kind: ty::AssocKind, generics: &hir::Generics<'_>| {
1229 let mut spans = generics
1232 .filter(|p| match p.kind {
1233 hir::GenericParamKind::Lifetime {
1234 kind: hir::LifetimeParamKind::Elided,
1236 // A fn can have an arbitrary number of extra elided lifetimes for the
1238 !matches!(kind, ty::AssocKind::Fn)
1243 .collect::<Vec<Span>>();
1244 if spans.is_empty() {
1245 spans = vec![generics.span]
1249 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1250 let trait_item = tcx.hir().expect_trait_item(def_id);
1251 let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
1252 let impl_trait_spans: Vec<Span> = trait_item
1256 .filter_map(|p| match p.kind {
1257 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1261 (Some(arg_spans), impl_trait_spans)
1263 (trait_span.map(|s| vec![s]), vec![])
1266 let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
1267 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1271 .filter_map(|p| match p.kind {
1272 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1276 let spans = arg_spans(impl_.kind, impl_item.generics);
1277 let span = spans.first().copied();
1279 let mut err = tcx.sess.struct_span_err_with_code(
1282 "{} `{}` has {} {kind} parameter{} but its trait \
1283 declaration has {} {kind} parameter{}",
1287 pluralize!(impl_count),
1289 pluralize!(trait_count),
1292 DiagnosticId::Error("E0049".into()),
1295 let mut suffix = None;
1297 if let Some(spans) = trait_spans {
1298 let mut spans = spans.iter();
1299 if let Some(span) = spans.next() {
1303 "expected {} {} parameter{}",
1306 pluralize!(trait_count),
1311 err.span_label(*span, "");
1314 suffix = Some(format!(", expected {trait_count}"));
1317 if let Some(span) = span {
1321 "found {} {} parameter{}{}",
1324 pluralize!(impl_count),
1325 suffix.unwrap_or_else(String::new),
1330 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1331 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1334 let reported = err.emit_unless(delay);
1335 err_occurred = Some(reported);
1339 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1342 fn compare_number_of_method_arguments<'tcx>(
1344 impl_m: &ty::AssocItem,
1346 trait_m: &ty::AssocItem,
1347 trait_item_span: Option<Span>,
1348 ) -> Result<(), ErrorGuaranteed> {
1349 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1350 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1351 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
1352 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
1354 if trait_number_args != impl_number_args {
1355 let trait_span = trait_m
1358 .and_then(|def_id| {
1359 let TraitItemKind::Fn(trait_m_sig, _) = &tcx.hir().expect_trait_item(def_id).kind else { bug!("{:?} is not a method", impl_m) };
1360 let pos = trait_number_args.saturating_sub(1);
1361 trait_m_sig.decl.inputs.get(pos).map(|arg| {
1365 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1369 .or(trait_item_span);
1371 let ImplItemKind::Fn(impl_m_sig, _) = &tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind else { bug!("{:?} is not a method", impl_m) };
1372 let pos = impl_number_args.saturating_sub(1);
1373 let impl_span = impl_m_sig
1381 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1384 .unwrap_or(impl_m_span);
1386 let mut err = struct_span_err!(
1390 "method `{}` has {} but the declaration in trait `{}` has {}",
1392 potentially_plural_count(impl_number_args, "parameter"),
1393 tcx.def_path_str(trait_m.def_id),
1397 if let Some(trait_span) = trait_span {
1401 "trait requires {}",
1402 potentially_plural_count(trait_number_args, "parameter")
1406 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1412 "expected {}, found {}",
1413 potentially_plural_count(trait_number_args, "parameter"),
1418 return Err(err.emit());
1424 fn compare_synthetic_generics<'tcx>(
1426 impl_m: &ty::AssocItem,
1427 trait_m: &ty::AssocItem,
1428 ) -> Result<(), ErrorGuaranteed> {
1429 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1430 // 1. Better messages for the span labels
1431 // 2. Explanation as to what is going on
1432 // If we get here, we already have the same number of generics, so the zip will
1434 let mut error_found = None;
1435 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1436 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1437 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
1438 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1439 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1441 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
1442 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1443 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1445 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1446 iter::zip(impl_m_type_params, trait_m_type_params)
1448 if impl_synthetic != trait_synthetic {
1449 let impl_def_id = impl_def_id.expect_local();
1450 let impl_span = tcx.def_span(impl_def_id);
1451 let trait_span = tcx.def_span(trait_def_id);
1452 let mut err = struct_span_err!(
1456 "method `{}` has incompatible signature for trait",
1459 err.span_label(trait_span, "declaration in trait here");
1460 match (impl_synthetic, trait_synthetic) {
1461 // The case where the impl method uses `impl Trait` but the trait method uses
1462 // explicit generics
1464 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1465 let _: Option<_> = try {
1466 // try taking the name from the trait impl
1467 // FIXME: this is obviously suboptimal since the name can already be used
1468 // as another generic argument
1469 let new_name = tcx.opt_item_name(trait_def_id)?;
1470 let trait_m = trait_m.def_id.as_local()?;
1471 let trait_m = tcx.hir().expect_trait_item(trait_m);
1473 let impl_m = impl_m.def_id.as_local()?;
1474 let impl_m = tcx.hir().expect_impl_item(impl_m);
1476 // in case there are no generics, take the spot between the function name
1477 // and the opening paren of the argument list
1478 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1479 // in case there are generics, just replace them
1481 impl_m.generics.span.substitute_dummy(new_generics_span);
1482 // replace with the generics from the trait
1484 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1486 err.multipart_suggestion(
1487 "try changing the `impl Trait` argument to a generic parameter",
1489 // replace `impl Trait` with `T`
1490 (impl_span, new_name.to_string()),
1491 // replace impl method generics with trait method generics
1492 // This isn't quite right, as users might have changed the names
1493 // of the generics, but it works for the common case
1494 (generics_span, new_generics),
1496 Applicability::MaybeIncorrect,
1500 // The case where the trait method uses `impl Trait`, but the impl method uses
1501 // explicit generics.
1503 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1504 let _: Option<_> = try {
1505 let impl_m = impl_m.def_id.as_local()?;
1506 let impl_m = tcx.hir().expect_impl_item(impl_m);
1507 let hir::ImplItemKind::Fn(sig, _) = &impl_m.kind else { unreachable!() };
1508 let input_tys = sig.decl.inputs;
1510 struct Visitor(Option<Span>, hir::def_id::LocalDefId);
1511 impl<'v> intravisit::Visitor<'v> for Visitor {
1512 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
1513 intravisit::walk_ty(self, ty);
1514 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
1515 && let Res::Def(DefKind::TyParam, def_id) = path.res
1516 && def_id == self.1.to_def_id()
1518 self.0 = Some(ty.span);
1523 let mut visitor = Visitor(None, impl_def_id);
1524 for ty in input_tys {
1525 intravisit::Visitor::visit_ty(&mut visitor, ty);
1527 let span = visitor.0?;
1529 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
1530 let bounds = bounds.first()?.span().to(bounds.last()?.span());
1531 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1533 err.multipart_suggestion(
1534 "try removing the generic parameter and using `impl Trait` instead",
1536 // delete generic parameters
1537 (impl_m.generics.span, String::new()),
1538 // replace param usage with `impl Trait`
1539 (span, format!("impl {bounds}")),
1541 Applicability::MaybeIncorrect,
1545 _ => unreachable!(),
1547 error_found = Some(err.emit());
1550 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1553 /// Checks that all parameters in the generics of a given assoc item in a trait impl have
1554 /// the same kind as the respective generic parameter in the trait def.
1556 /// For example all 4 errors in the following code are emitted here:
1559 /// fn foo<const N: u8>();
1560 /// type bar<const N: u8>;
1561 /// fn baz<const N: u32>();
1565 /// impl Foo for () {
1566 /// fn foo<const N: u64>() {}
1568 /// type bar<const N: u64> {}
1572 /// type blah<const N: i64> = u32;
1577 /// This function does not handle lifetime parameters
1578 fn compare_generic_param_kinds<'tcx>(
1580 impl_item: &ty::AssocItem,
1581 trait_item: &ty::AssocItem,
1583 ) -> Result<(), ErrorGuaranteed> {
1584 assert_eq!(impl_item.kind, trait_item.kind);
1586 let ty_const_params_of = |def_id| {
1587 tcx.generics_of(def_id).params.iter().filter(|param| {
1590 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1595 for (param_impl, param_trait) in
1596 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1598 use GenericParamDefKind::*;
1599 if match (¶m_impl.kind, ¶m_trait.kind) {
1600 (Const { .. }, Const { .. })
1601 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1605 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1606 // this is exhaustive so that anyone adding new generic param kinds knows
1607 // to make sure this error is reported for them.
1608 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1609 (Lifetime { .. }, _) | (_, Lifetime { .. }) => unreachable!(),
1611 let param_impl_span = tcx.def_span(param_impl.def_id);
1612 let param_trait_span = tcx.def_span(param_trait.def_id);
1614 let mut err = struct_span_err!(
1618 "{} `{}` has an incompatible generic parameter for trait `{}`",
1619 assoc_item_kind_str(&impl_item),
1621 &tcx.def_path_str(tcx.parent(trait_item.def_id))
1624 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1626 format!("{} const parameter of type `{}`", prefix, tcx.type_of(param.def_id))
1628 Type { .. } => format!("{} type parameter", prefix),
1629 Lifetime { .. } => unreachable!(),
1632 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1633 err.span_label(trait_header_span, "");
1634 err.span_label(param_trait_span, make_param_message("expected", param_trait));
1636 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1637 err.span_label(impl_header_span, "");
1638 err.span_label(param_impl_span, make_param_message("found", param_impl));
1640 let reported = err.emit_unless(delay);
1641 return Err(reported);
1648 /// Use `tcx.compare_impl_const` instead
1649 pub(super) fn compare_impl_const_raw(
1651 (impl_const_item_def, trait_const_item_def): (LocalDefId, DefId),
1652 ) -> Result<(), ErrorGuaranteed> {
1653 let impl_const_item = tcx.associated_item(impl_const_item_def);
1654 let trait_const_item = tcx.associated_item(trait_const_item_def);
1655 let impl_trait_ref =
1656 tcx.impl_trait_ref(impl_const_item.container_id(tcx)).unwrap().subst_identity();
1657 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
1659 let impl_c_span = tcx.def_span(impl_const_item_def.to_def_id());
1661 let infcx = tcx.infer_ctxt().build();
1662 let param_env = tcx.param_env(impl_const_item_def.to_def_id());
1663 let ocx = ObligationCtxt::new(&infcx);
1665 // The below is for the most part highly similar to the procedure
1666 // for methods above. It is simpler in many respects, especially
1667 // because we shouldn't really have to deal with lifetimes or
1668 // predicates. In fact some of this should probably be put into
1669 // shared functions because of DRY violations...
1670 let trait_to_impl_substs = impl_trait_ref.substs;
1672 // Create a parameter environment that represents the implementation's
1674 let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_const_item_def);
1676 // Compute placeholder form of impl and trait const tys.
1677 let impl_ty = tcx.type_of(impl_const_item_def.to_def_id());
1678 let trait_ty = tcx.bound_type_of(trait_const_item_def).subst(tcx, trait_to_impl_substs);
1679 let mut cause = ObligationCause::new(
1682 ObligationCauseCode::CompareImplItemObligation {
1683 impl_item_def_id: impl_const_item_def,
1684 trait_item_def_id: trait_const_item_def,
1685 kind: impl_const_item.kind,
1689 // There is no "body" here, so just pass dummy id.
1690 let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
1692 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1694 let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
1696 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1698 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
1700 if let Err(terr) = err {
1702 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1706 // Locate the Span containing just the type of the offending impl
1707 let ImplItemKind::Const(ty, _) = tcx.hir().expect_impl_item(impl_const_item_def).kind else { bug!("{impl_const_item:?} is not a impl const") };
1708 cause.span = ty.span;
1710 let mut diag = struct_span_err!(
1714 "implemented const `{}` has an incompatible type for trait",
1715 trait_const_item.name
1718 let trait_c_span = trait_const_item_def.as_local().map(|trait_c_def_id| {
1719 // Add a label to the Span containing just the type of the const
1720 let TraitItemKind::Const(ty, _) = tcx.hir().expect_trait_item(trait_c_def_id).kind else { bug!("{trait_const_item:?} is not a trait const") };
1724 infcx.err_ctxt().note_type_err(
1727 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1728 Some(infer::ValuePairs::Terms(ExpectedFound {
1729 expected: trait_ty.into(),
1730 found: impl_ty.into(),
1736 return Err(diag.emit());
1739 // Check that all obligations are satisfied by the implementation's
1741 let errors = ocx.select_all_or_error();
1742 if !errors.is_empty() {
1743 return Err(infcx.err_ctxt().report_fulfillment_errors(&errors, None));
1746 let outlives_environment = OutlivesEnvironment::new(param_env);
1749 .check_region_obligations_and_report_errors(impl_const_item_def, &outlives_environment)?;
1753 pub(super) fn compare_impl_ty<'tcx>(
1755 impl_ty: &ty::AssocItem,
1757 trait_ty: &ty::AssocItem,
1758 impl_trait_ref: ty::TraitRef<'tcx>,
1759 trait_item_span: Option<Span>,
1761 debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1763 let _: Result<(), ErrorGuaranteed> = try {
1764 compare_number_of_generics(tcx, impl_ty, trait_ty, trait_item_span, false)?;
1766 compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
1768 let sp = tcx.def_span(impl_ty.def_id);
1769 compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;
1771 check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)?;
1775 /// The equivalent of [compare_method_predicate_entailment], but for associated types
1776 /// instead of associated functions.
1777 fn compare_type_predicate_entailment<'tcx>(
1779 impl_ty: &ty::AssocItem,
1781 trait_ty: &ty::AssocItem,
1782 impl_trait_ref: ty::TraitRef<'tcx>,
1783 ) -> Result<(), ErrorGuaranteed> {
1784 let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1785 let trait_to_impl_substs =
1786 impl_substs.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.substs);
1788 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1789 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1791 check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
1793 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1794 if impl_ty_own_bounds.len() == 0 {
1795 // Nothing to check.
1799 // This `HirId` should be used for the `body_id` field on each
1800 // `ObligationCause` (and the `FnCtxt`). This is what
1801 // `regionck_item` expects.
1802 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1803 debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1805 // The predicates declared by the impl definition, the trait and the
1806 // associated type in the trait are assumed.
1807 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1808 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1809 hybrid_preds.predicates.extend(
1811 .instantiate_own(tcx, trait_to_impl_substs)
1812 .map(|(predicate, _)| predicate),
1815 debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1817 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1818 let param_env = ty::ParamEnv::new(
1819 tcx.intern_predicates(&hybrid_preds.predicates),
1821 hir::Constness::NotConst,
1823 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
1824 let infcx = tcx.infer_ctxt().build();
1825 let ocx = ObligationCtxt::new(&infcx);
1827 debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1829 for (predicate, span) in impl_ty_own_bounds {
1830 let cause = ObligationCause::misc(span, impl_ty_hir_id);
1831 let predicate = ocx.normalize(&cause, param_env, predicate);
1833 let cause = ObligationCause::new(
1836 ObligationCauseCode::CompareImplItemObligation {
1837 impl_item_def_id: impl_ty.def_id.expect_local(),
1838 trait_item_def_id: trait_ty.def_id,
1842 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
1845 // Check that all obligations are satisfied by the implementation's
1847 let errors = ocx.select_all_or_error();
1848 if !errors.is_empty() {
1849 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
1850 return Err(reported);
1853 // Finally, resolve all regions. This catches wily misuses of
1854 // lifetime parameters.
1855 let outlives_environment = OutlivesEnvironment::new(param_env);
1856 infcx.err_ctxt().check_region_obligations_and_report_errors(
1857 impl_ty.def_id.expect_local(),
1858 &outlives_environment,
1864 /// Validate that `ProjectionCandidate`s created for this associated type will
1869 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1871 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1872 /// impl is well-formed we have to prove `S: Copy`.
1874 /// For default associated types the normalization is not possible (the value
1875 /// from the impl could be overridden). We also can't normalize generic
1876 /// associated types (yet) because they contain bound parameters.
1877 #[instrument(level = "debug", skip(tcx))]
1878 pub(super) fn check_type_bounds<'tcx>(
1880 trait_ty: &ty::AssocItem,
1881 impl_ty: &ty::AssocItem,
1883 impl_trait_ref: ty::TraitRef<'tcx>,
1884 ) -> Result<(), ErrorGuaranteed> {
1887 // impl<A, B> Foo<u32> for (A, B) {
1891 // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1892 // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1893 // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1894 // the *trait* with the generic associated type parameters (as bound vars).
1896 // A note regarding the use of bound vars here:
1897 // Imagine as an example
1900 // type Member<C: Eq>;
1903 // impl Family for VecFamily {
1904 // type Member<C: Eq> = i32;
1907 // Here, we would generate
1909 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1911 // when we really would like to generate
1913 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1915 // But, this is probably fine, because although the first clause can be used with types C that
1916 // do not implement Eq, for it to cause some kind of problem, there would have to be a
1917 // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1918 // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1919 // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1920 // the trait (notably, that X: Eq and T: Family).
1921 let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1922 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1923 if let Some(def_id) = defs.parent {
1924 let parent_defs = tcx.generics_of(def_id);
1925 InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1926 tcx.mk_param_from_def(param)
1929 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1930 smallvec::SmallVec::with_capacity(defs.count());
1931 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1932 GenericParamDefKind::Type { .. } => {
1933 let kind = ty::BoundTyKind::Param(param.name);
1934 let bound_var = ty::BoundVariableKind::Ty(kind);
1935 bound_vars.push(bound_var);
1936 tcx.mk_ty(ty::Bound(
1938 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1942 GenericParamDefKind::Lifetime => {
1943 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1944 let bound_var = ty::BoundVariableKind::Region(kind);
1945 bound_vars.push(bound_var);
1946 tcx.mk_region(ty::ReLateBound(
1948 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1952 GenericParamDefKind::Const { .. } => {
1953 let bound_var = ty::BoundVariableKind::Const;
1954 bound_vars.push(bound_var);
1956 ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(bound_vars.len() - 1)),
1957 tcx.type_of(param.def_id),
1962 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
1963 let impl_ty_substs = tcx.intern_substs(&substs);
1964 let container_id = impl_ty.container_id(tcx);
1966 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
1967 let impl_ty_value = tcx.type_of(impl_ty.def_id);
1969 let param_env = tcx.param_env(impl_ty.def_id);
1971 // When checking something like
1973 // trait X { type Y: PartialEq<<Self as X>::Y> }
1974 // impl X for T { default type Y = S; }
1976 // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
1977 // we want <T as X>::Y to normalize to S. This is valid because we are
1978 // checking the default value specifically here. Add this equality to the
1979 // ParamEnv for normalization specifically.
1980 let normalize_param_env = {
1981 let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
1982 match impl_ty_value.kind() {
1983 ty::Alias(ty::Projection, proj)
1984 if proj.def_id == trait_ty.def_id && proj.substs == rebased_substs =>
1986 // Don't include this predicate if the projected type is
1987 // exactly the same as the projection. This can occur in
1988 // (somewhat dubious) code like this:
1990 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
1992 _ => predicates.push(
1993 ty::Binder::bind_with_vars(
1994 ty::ProjectionPredicate {
1995 projection_ty: tcx.mk_alias_ty(trait_ty.def_id, rebased_substs),
1996 term: impl_ty_value.into(),
2004 tcx.intern_predicates(&predicates),
2006 param_env.constness(),
2009 debug!(?normalize_param_env);
2011 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
2012 let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
2013 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
2015 let infcx = tcx.infer_ctxt().build();
2016 let ocx = ObligationCtxt::new(&infcx);
2018 let assumed_wf_types =
2019 ocx.assumed_wf_types(param_env, impl_ty_span, impl_ty.def_id.expect_local());
2021 let normalize_cause = ObligationCause::new(
2024 ObligationCauseCode::CheckAssociatedTypeBounds {
2025 impl_item_def_id: impl_ty.def_id.expect_local(),
2026 trait_item_def_id: trait_ty.def_id,
2029 let mk_cause = |span: Span| {
2030 let code = if span.is_dummy() {
2031 traits::ItemObligation(trait_ty.def_id)
2033 traits::BindingObligation(trait_ty.def_id, span)
2035 ObligationCause::new(impl_ty_span, impl_ty_hir_id, code)
2038 let obligations = tcx
2039 .bound_explicit_item_bounds(trait_ty.def_id)
2040 .subst_iter_copied(tcx, rebased_substs)
2041 .map(|(concrete_ty_bound, span)| {
2042 debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
2043 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2046 debug!("check_type_bounds: item_bounds={:?}", obligations);
2048 for mut obligation in util::elaborate_obligations(tcx, obligations) {
2049 let normalized_predicate =
2050 ocx.normalize(&normalize_cause, normalize_param_env, obligation.predicate);
2051 debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
2052 obligation.predicate = normalized_predicate;
2054 ocx.register_obligation(obligation);
2056 // Check that all obligations are satisfied by the implementation's
2058 let errors = ocx.select_all_or_error();
2059 if !errors.is_empty() {
2060 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
2061 return Err(reported);
2064 // Finally, resolve all regions. This catches wily misuses of
2065 // lifetime parameters.
2066 let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_hir_id, assumed_wf_types);
2067 let outlives_environment =
2068 OutlivesEnvironment::with_bounds(param_env, Some(&infcx), implied_bounds);
2070 infcx.err_ctxt().check_region_obligations_and_report_errors(
2071 impl_ty.def_id.expect_local(),
2072 &outlives_environment,
2078 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
2079 match impl_item.kind {
2080 ty::AssocKind::Const => "const",
2081 ty::AssocKind::Fn => "method",
2082 ty::AssocKind::Type => "type",