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};
5 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, ErrorGuaranteed};
7 use rustc_hir::def::{DefKind, Res};
8 use rustc_hir::intravisit;
9 use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
10 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
11 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
12 use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
13 use rustc_infer::traits::util;
14 use rustc_middle::ty::error::{ExpectedFound, TypeError};
15 use rustc_middle::ty::util::ExplicitSelf;
16 use rustc_middle::ty::{
17 self, DefIdTree, InternalSubsts, Ty, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
19 use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt};
21 use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt;
22 use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _;
23 use rustc_trait_selection::traits::{
24 self, ObligationCause, ObligationCauseCode, ObligationCtxt, Reveal,
28 /// Checks that a method from an impl conforms to the signature of
29 /// the same method as declared in the trait.
33 /// - `impl_m`: type of the method we are checking
34 /// - `impl_m_span`: span to use for reporting errors
35 /// - `trait_m`: the method in the trait
36 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
37 pub(super) fn compare_impl_method<'tcx>(
39 impl_m: &ty::AssocItem,
40 trait_m: &ty::AssocItem,
41 impl_trait_ref: ty::TraitRef<'tcx>,
42 trait_item_span: Option<Span>,
44 debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
46 let impl_m_span = tcx.def_span(impl_m.def_id);
48 if let Err(_) = compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref) {
52 if let Err(_) = compare_number_of_generics(tcx, impl_m, trait_m, trait_item_span, false) {
56 if let Err(_) = compare_generic_param_kinds(tcx, impl_m, trait_m, false) {
61 compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
66 if let Err(_) = compare_synthetic_generics(tcx, impl_m, trait_m) {
70 if let Err(_) = compare_asyncness(tcx, impl_m, impl_m_span, trait_m, trait_item_span) {
74 if let Err(_) = compare_predicate_entailment(
80 CheckImpliedWfMode::Check,
86 /// This function is best explained by example. Consider a trait:
88 /// trait Trait<'t, T> {
90 /// fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
95 /// impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
97 /// fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo;
100 /// We wish to decide if those two method types are compatible.
101 /// For this we have to show that, assuming the bounds of the impl hold, the
102 /// bounds of `trait_m` imply the bounds of `impl_m`.
104 /// We start out with `trait_to_impl_substs`, that maps the trait
105 /// type parameters to impl type parameters. This is taken from the
106 /// impl trait reference:
108 /// trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
110 /// We create a mapping `dummy_substs` that maps from the impl type
111 /// parameters to fresh types and regions. For type parameters,
112 /// this is the identity transform, but we could as well use any
113 /// placeholder types. For regions, we convert from bound to free
114 /// regions (Note: but only early-bound regions, i.e., those
115 /// declared on the impl or used in type parameter bounds).
117 /// impl_to_placeholder_substs = {'i => 'i0, U => U0, N => N0 }
119 /// Now we can apply `placeholder_substs` to the type of the impl method
120 /// to yield a new function type in terms of our fresh, placeholder
123 /// <'b> fn(t: &'i0 U0, m: &'b) -> Foo
125 /// We now want to extract and substitute the type of the *trait*
126 /// method and compare it. To do so, we must create a compound
127 /// substitution by combining `trait_to_impl_substs` and
128 /// `impl_to_placeholder_substs`, and also adding a mapping for the method
129 /// type parameters. We extend the mapping to also include
130 /// the method parameters.
132 /// trait_to_placeholder_substs = { T => &'i0 U0, Self => Foo, M => N0 }
134 /// Applying this to the trait method type yields:
136 /// <'a> fn(t: &'i0 U0, m: &'a) -> Foo
138 /// This type is also the same but the name of the bound region (`'a`
139 /// vs `'b`). However, the normal subtyping rules on fn types handle
140 /// this kind of equivalency just fine.
142 /// We now use these substitutions to ensure that all declared bounds are
143 /// satisfied by the implementation's method.
145 /// We do this by creating a parameter environment which contains a
146 /// substitution corresponding to `impl_to_placeholder_substs`. We then build
147 /// `trait_to_placeholder_substs` and use it to convert the predicates contained
148 /// in the `trait_m` generics to the placeholder form.
150 /// Finally we register each of these predicates as an obligation and check that
152 #[instrument(level = "debug", skip(tcx, impl_m_span, impl_trait_ref))]
153 fn compare_predicate_entailment<'tcx>(
155 impl_m: &ty::AssocItem,
157 trait_m: &ty::AssocItem,
158 impl_trait_ref: ty::TraitRef<'tcx>,
159 check_implied_wf: CheckImpliedWfMode,
160 ) -> Result<(), ErrorGuaranteed> {
161 let trait_to_impl_substs = impl_trait_ref.substs;
163 // This node-id should be used for the `body_id` field on each
164 // `ObligationCause` (and the `FnCtxt`).
166 // FIXME(@lcnr): remove that after removing `cause.body_id` from
168 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
169 let cause = ObligationCause::new(
172 ObligationCauseCode::CompareImplItemObligation {
173 impl_item_def_id: impl_m.def_id.expect_local(),
174 trait_item_def_id: trait_m.def_id,
179 // Create mapping from impl to placeholder.
180 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
182 // Create mapping from trait to placeholder.
183 let trait_to_placeholder_substs =
184 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
185 debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_substs);
187 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
188 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
190 // Check region bounds.
191 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, false)?;
193 // Create obligations for each predicate declared by the impl
194 // definition in the context of the trait's parameter
195 // environment. We can't just use `impl_env.caller_bounds`,
196 // however, because we want to replace all late-bound regions with
198 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
199 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
201 debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
203 // This is the only tricky bit of the new way we check implementation methods
204 // We need to build a set of predicates where only the method-level bounds
205 // are from the trait and we assume all other bounds from the implementation
206 // to be previously satisfied.
208 // We then register the obligations from the impl_m and check to see
209 // if all constraints hold.
212 .extend(trait_m_predicates.instantiate_own(tcx, trait_to_placeholder_substs).predicates);
214 // Construct trait parameter environment and then shift it into the placeholder viewpoint.
215 // The key step here is to update the caller_bounds's predicates to be
216 // the new hybrid bounds we computed.
217 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
218 let param_env = ty::ParamEnv::new(
219 tcx.intern_predicates(&hybrid_preds.predicates),
221 hir::Constness::NotConst,
223 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
225 let infcx = &tcx.infer_ctxt().build();
226 let ocx = ObligationCtxt::new(infcx);
228 debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
230 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
231 for (predicate, span) in iter::zip(impl_m_own_bounds.predicates, impl_m_own_bounds.spans) {
232 let normalize_cause = traits::ObligationCause::misc(span, impl_m_hir_id);
233 let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
235 let cause = ObligationCause::new(
238 ObligationCauseCode::CompareImplItemObligation {
239 impl_item_def_id: impl_m.def_id.expect_local(),
240 trait_item_def_id: trait_m.def_id,
244 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
247 // We now need to check that the signature of the impl method is
248 // compatible with that of the trait method. We do this by
249 // checking that `impl_fty <: trait_fty`.
251 // FIXME. Unfortunately, this doesn't quite work right now because
252 // associated type normalization is not integrated into subtype
253 // checks. For the comparison to be valid, we need to
254 // normalize the associated types in the impl/trait methods
255 // first. However, because function types bind regions, just
256 // calling `normalize_associated_types_in` would have no effect on
257 // any associated types appearing in the fn arguments or return
260 // Compute placeholder form of impl and trait method tys.
263 let mut wf_tys = FxIndexSet::default();
265 let unnormalized_impl_sig = infcx.replace_bound_vars_with_fresh_vars(
267 infer::HigherRankedType,
268 tcx.fn_sig(impl_m.def_id),
270 let unnormalized_impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(unnormalized_impl_sig));
272 let norm_cause = ObligationCause::misc(impl_m_span, impl_m_hir_id);
273 let impl_fty = ocx.normalize(&norm_cause, param_env, unnormalized_impl_fty);
274 debug!("compare_impl_method: impl_fty={:?}", impl_fty);
276 let trait_sig = tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs);
277 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
279 // Next, add all inputs and output as well-formed tys. Importantly,
280 // we have to do this before normalization, since the normalized ty may
281 // not contain the input parameters. See issue #87748.
282 wf_tys.extend(trait_sig.inputs_and_output.iter());
283 let trait_sig = ocx.normalize(&norm_cause, param_env, trait_sig);
284 // We also have to add the normalized trait signature
285 // as we don't normalize during implied bounds computation.
286 wf_tys.extend(trait_sig.inputs_and_output.iter());
287 let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
289 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
291 // FIXME: We'd want to keep more accurate spans than "the method signature" when
292 // processing the comparison between the trait and impl fn, but we sadly lose them
293 // and point at the whole signature when a trait bound or specific input or output
294 // type would be more appropriate. In other places we have a `Vec<Span>`
295 // corresponding to their `Vec<Predicate>`, but we don't have that here.
296 // Fixing this would improve the output of test `issue-83765.rs`.
297 let result = ocx.sup(&cause, param_env, trait_fty, impl_fty);
299 if let Err(terr) = result {
300 debug!(?terr, "sub_types failed: impl ty {:?}, trait ty {:?}", impl_fty, trait_fty);
302 let emitted = report_trait_method_mismatch(
306 (trait_m, trait_fty),
314 if check_implied_wf == CheckImpliedWfMode::Check {
315 // We need to check that the impl's args are well-formed given
316 // the hybrid param-env (impl + trait method where-clauses).
317 ocx.register_obligation(traits::Obligation::new(
319 ObligationCause::dummy(),
321 ty::Binder::dummy(ty::PredicateKind::WellFormed(unnormalized_impl_fty.into())),
324 let emit_implied_wf_lint = || {
325 infcx.tcx.struct_span_lint_hir(
326 rustc_session::lint::builtin::IMPLIED_BOUNDS_ENTAILMENT,
328 infcx.tcx.def_span(impl_m.def_id),
329 "impl method assumes more implied bounds than the corresponding trait method",
334 // Check that all obligations are satisfied by the implementation's
336 let errors = ocx.select_all_or_error();
337 if !errors.is_empty() {
338 match check_implied_wf {
339 CheckImpliedWfMode::Check => {
340 return compare_predicate_entailment(
346 CheckImpliedWfMode::Skip,
349 // If the skip-mode was successful, emit a lint.
350 emit_implied_wf_lint();
353 CheckImpliedWfMode::Skip => {
354 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
355 return Err(reported);
360 // Finally, resolve all regions. This catches wily misuses of
361 // lifetime parameters.
362 let outlives_env = OutlivesEnvironment::with_bounds(
365 infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys.clone()),
367 infcx.process_registered_region_obligations(
368 outlives_env.region_bound_pairs(),
369 outlives_env.param_env,
371 let errors = infcx.resolve_regions(&outlives_env);
372 if !errors.is_empty() {
373 // FIXME(compiler-errors): This can be simplified when IMPLIED_BOUNDS_ENTAILMENT
374 // becomes a hard error (i.e. ideally we'd just call `resolve_regions_and_report_errors`
375 match check_implied_wf {
376 CheckImpliedWfMode::Check => {
377 return compare_predicate_entailment(
383 CheckImpliedWfMode::Skip,
386 // If the skip-mode was successful, emit a lint.
387 emit_implied_wf_lint();
390 CheckImpliedWfMode::Skip => {
391 if infcx.tainted_by_errors().is_none() {
392 infcx.err_ctxt().report_region_errors(impl_m.def_id.expect_local(), &errors);
396 .delay_span_bug(rustc_span::DUMMY_SP, "error should have been emitted"));
404 #[derive(Debug, PartialEq, Eq)]
405 enum CheckImpliedWfMode {
406 /// Checks implied well-formedness of the impl method. If it fails, we will
407 /// re-check with `Skip`, and emit a lint if it succeeds.
409 /// Skips checking implied well-formedness of the impl method, but will emit
410 /// a lint if the `compare_predicate_entailment` succeeded. This means that
411 /// the reason that we had failed earlier during `Check` was due to the impl
412 /// having stronger requirements than the trait.
416 fn compare_asyncness<'tcx>(
418 impl_m: &ty::AssocItem,
420 trait_m: &ty::AssocItem,
421 trait_item_span: Option<Span>,
422 ) -> Result<(), ErrorGuaranteed> {
423 if tcx.asyncness(trait_m.def_id) == hir::IsAsync::Async {
424 match tcx.fn_sig(impl_m.def_id).skip_binder().output().kind() {
425 ty::Alias(ty::Opaque, ..) => {
426 // allow both `async fn foo()` and `fn foo() -> impl Future`
428 ty::Error(rustc_errors::ErrorGuaranteed { .. }) => {
429 // We don't know if it's ok, but at least it's already an error.
432 return Err(tcx.sess.emit_err(crate::errors::AsyncTraitImplShouldBeAsync {
434 method_name: trait_m.name,
444 #[instrument(skip(tcx), level = "debug", ret)]
445 pub(super) fn collect_trait_impl_trait_tys<'tcx>(
448 ) -> Result<&'tcx FxHashMap<DefId, Ty<'tcx>>, ErrorGuaranteed> {
449 let impl_m = tcx.opt_associated_item(def_id).unwrap();
450 let trait_m = tcx.opt_associated_item(impl_m.trait_item_def_id.unwrap()).unwrap();
451 let impl_trait_ref = tcx.impl_trait_ref(impl_m.impl_container(tcx).unwrap()).unwrap();
452 let param_env = tcx.param_env(def_id);
454 // First, check a few of the same thing as `compare_impl_method`, just so we don't ICE during substitutions later.
455 compare_number_of_generics(tcx, impl_m, trait_m, tcx.hir().span_if_local(impl_m.def_id), true)?;
456 compare_generic_param_kinds(tcx, impl_m, trait_m, true)?;
457 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, true)?;
459 let trait_to_impl_substs = impl_trait_ref.substs;
461 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
462 let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
463 let cause = ObligationCause::new(
466 ObligationCauseCode::CompareImplItemObligation {
467 impl_item_def_id: impl_m.def_id.expect_local(),
468 trait_item_def_id: trait_m.def_id,
473 // Create mapping from impl to placeholder.
474 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
476 // Create mapping from trait to placeholder.
477 let trait_to_placeholder_substs =
478 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
480 let infcx = &tcx.infer_ctxt().build();
481 let ocx = ObligationCtxt::new(infcx);
483 // Normalize the impl signature with fresh variables for lifetime inference.
484 let norm_cause = ObligationCause::misc(return_span, impl_m_hir_id);
485 let impl_sig = ocx.normalize(
488 infcx.replace_bound_vars_with_fresh_vars(
490 infer::HigherRankedType,
491 tcx.fn_sig(impl_m.def_id),
494 impl_sig.error_reported()?;
495 let impl_return_ty = impl_sig.output();
497 // Normalize the trait signature with liberated bound vars, passing it through
498 // the ImplTraitInTraitCollector, which gathers all of the RPITITs and replaces
499 // them with inference variables.
500 // We will use these inference variables to collect the hidden types of RPITITs.
501 let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_hir_id);
502 let unnormalized_trait_sig = tcx
503 .liberate_late_bound_regions(
505 tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs),
507 .fold_with(&mut collector);
508 let trait_sig = ocx.normalize(&norm_cause, param_env, unnormalized_trait_sig);
509 trait_sig.error_reported()?;
510 let trait_return_ty = trait_sig.output();
512 let wf_tys = FxIndexSet::from_iter(
513 unnormalized_trait_sig.inputs_and_output.iter().chain(trait_sig.inputs_and_output.iter()),
516 match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
519 let mut diag = struct_span_err!(
523 "method `{}` has an incompatible return type for trait",
527 infcx.err_ctxt().note_type_err(
530 hir.get_if_local(impl_m.def_id)
531 .and_then(|node| node.fn_decl())
532 .map(|decl| (decl.output.span(), "return type in trait".to_owned())),
533 Some(infer::ValuePairs::Terms(ExpectedFound {
534 expected: trait_return_ty.into(),
535 found: impl_return_ty.into(),
541 return Err(diag.emit());
545 debug!(?trait_sig, ?impl_sig, "equating function signatures");
547 let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
548 let impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(impl_sig));
550 // Unify the whole function signature. We need to do this to fully infer
551 // the lifetimes of the return type, but do this after unifying just the
552 // return types, since we want to avoid duplicating errors from
553 // `compare_predicate_entailment`.
554 match ocx.eq(&cause, param_env, trait_fty, impl_fty) {
557 // This function gets called during `compare_predicate_entailment` when normalizing a
558 // signature that contains RPITIT. When the method signatures don't match, we have to
559 // emit an error now because `compare_predicate_entailment` will not report the error
560 // when normalization fails.
561 let emitted = report_trait_method_mismatch(
565 (trait_m, trait_fty),
574 // Check that all obligations are satisfied by the implementation's
576 let errors = ocx.select_all_or_error();
577 if !errors.is_empty() {
578 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
579 return Err(reported);
582 // Finally, resolve all regions. This catches wily misuses of
583 // lifetime parameters.
584 let outlives_environment = OutlivesEnvironment::with_bounds(
587 infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys),
589 infcx.check_region_obligations_and_report_errors(
590 impl_m.def_id.expect_local(),
591 &outlives_environment,
594 let mut collected_tys = FxHashMap::default();
595 for (def_id, (ty, substs)) in collector.types {
596 match infcx.fully_resolve(ty) {
598 // `ty` contains free regions that we created earlier while liberating the
599 // trait fn signature. However, projection normalization expects `ty` to
600 // contains `def_id`'s early-bound regions.
601 let id_substs = InternalSubsts::identity_for_item(tcx, def_id);
602 debug!(?id_substs, ?substs);
603 let map: FxHashMap<ty::GenericArg<'tcx>, ty::GenericArg<'tcx>> =
604 std::iter::zip(substs, id_substs).collect();
607 // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound
608 // region substs that are synthesized during AST lowering. These are substs
609 // that are appended to the parent substs (trait and trait method). However,
610 // we're trying to infer the unsubstituted type value of the RPITIT inside
611 // the *impl*, so we can later use the impl's method substs to normalize
612 // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`).
614 // Due to the design of RPITITs, during AST lowering, we have no idea that
615 // an impl method corresponds to a trait method with RPITITs in it. Therefore,
616 // we don't have a list of early-bound region substs for the RPITIT in the impl.
617 // Since early region parameters are index-based, we can't just rebase these
618 // (trait method) early-bound region substs onto the impl, and there's no
619 // guarantee that the indices from the trait substs and impl substs line up.
620 // So to fix this, we subtract the number of trait substs and add the number of
621 // impl substs to *renumber* these early-bound regions to their corresponding
622 // indices in the impl's substitutions list.
624 // Also, we only need to account for a difference in trait and impl substs,
625 // since we previously enforce that the trait method and impl method have the
627 let num_trait_substs = trait_to_impl_substs.len();
628 let num_impl_substs = tcx.generics_of(impl_m.container_id(tcx)).params.len();
629 let ty = tcx.fold_regions(ty, |region, _| {
630 match region.kind() {
631 // Remap all free regions, which correspond to late-bound regions in the function.
633 // Remap early-bound regions as long as they don't come from the `impl` itself.
634 ty::ReEarlyBound(ebr) if tcx.parent(ebr.def_id) != impl_m.container_id(tcx) => {}
637 let Some(ty::ReEarlyBound(e)) = map.get(®ion.into()).map(|r| r.expect_region().kind())
643 "expected ReFree to map to ReEarlyBound"
645 return tcx.lifetimes.re_static;
647 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
650 index: (e.index as usize - num_trait_substs + num_impl_substs) as u32,
654 collected_tys.insert(def_id, ty);
657 let reported = tcx.sess.delay_span_bug(
659 format!("could not fully resolve: {ty} => {err:?}"),
661 collected_tys.insert(def_id, tcx.ty_error_with_guaranteed(reported));
666 Ok(&*tcx.arena.alloc(collected_tys))
669 struct ImplTraitInTraitCollector<'a, 'tcx> {
670 ocx: &'a ObligationCtxt<'a, 'tcx>,
671 types: FxHashMap<DefId, (Ty<'tcx>, ty::SubstsRef<'tcx>)>,
673 param_env: ty::ParamEnv<'tcx>,
677 impl<'a, 'tcx> ImplTraitInTraitCollector<'a, 'tcx> {
679 ocx: &'a ObligationCtxt<'a, 'tcx>,
681 param_env: ty::ParamEnv<'tcx>,
684 ImplTraitInTraitCollector { ocx, types: FxHashMap::default(), span, param_env, body_id }
688 impl<'tcx> TypeFolder<'tcx> for ImplTraitInTraitCollector<'_, 'tcx> {
689 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
693 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
694 if let ty::Alias(ty::Projection, proj) = ty.kind()
695 && self.tcx().def_kind(proj.def_id) == DefKind::ImplTraitPlaceholder
697 if let Some((ty, _)) = self.types.get(&proj.def_id) {
700 //FIXME(RPITIT): Deny nested RPITIT in substs too
701 if proj.substs.has_escaping_bound_vars() {
702 bug!("FIXME(RPITIT): error here");
704 // Replace with infer var
705 let infer_ty = self.ocx.infcx.next_ty_var(TypeVariableOrigin {
707 kind: TypeVariableOriginKind::MiscVariable,
709 self.types.insert(proj.def_id, (infer_ty, proj.substs));
710 // Recurse into bounds
711 for (pred, pred_span) in self.tcx().bound_explicit_item_bounds(proj.def_id).subst_iter_copied(self.tcx(), proj.substs) {
712 let pred = pred.fold_with(self);
713 let pred = self.ocx.normalize(
714 &ObligationCause::misc(self.span, self.body_id),
719 self.ocx.register_obligation(traits::Obligation::new(
721 ObligationCause::new(
724 ObligationCauseCode::BindingObligation(proj.def_id, pred_span),
732 ty.super_fold_with(self)
737 fn report_trait_method_mismatch<'tcx>(
738 infcx: &InferCtxt<'tcx>,
739 mut cause: ObligationCause<'tcx>,
740 terr: TypeError<'tcx>,
741 (trait_m, trait_fty): (&ty::AssocItem, Ty<'tcx>),
742 (impl_m, impl_fty): (&ty::AssocItem, Ty<'tcx>),
743 trait_sig: ty::FnSig<'tcx>,
744 impl_trait_ref: ty::TraitRef<'tcx>,
745 ) -> ErrorGuaranteed {
747 let (impl_err_span, trait_err_span) =
748 extract_spans_for_error_reporting(&infcx, terr, &cause, impl_m, trait_m);
750 let mut diag = struct_span_err!(
754 "method `{}` has an incompatible type for trait",
758 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
759 if trait_m.fn_has_self_parameter =>
761 let ty = trait_sig.inputs()[0];
762 let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty()) {
763 ExplicitSelf::ByValue => "self".to_owned(),
764 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
765 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
766 _ => format!("self: {ty}"),
769 // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
770 // span points only at the type `Box<Self`>, but we want to cover the whole
771 // argument pattern and type.
772 let span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
773 ImplItemKind::Fn(ref sig, body) => tcx
775 .body_param_names(body)
776 .zip(sig.decl.inputs.iter())
777 .map(|(param, ty)| param.span.to(ty.span))
779 .unwrap_or(impl_err_span),
780 _ => bug!("{:?} is not a method", impl_m),
783 diag.span_suggestion(
785 "change the self-receiver type to match the trait",
787 Applicability::MachineApplicable,
790 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
791 if trait_sig.inputs().len() == *i {
792 // Suggestion to change output type. We do not suggest in `async` functions
793 // to avoid complex logic or incorrect output.
794 match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
795 ImplItemKind::Fn(ref sig, _) if !sig.header.asyncness.is_async() => {
796 let msg = "change the output type to match the trait";
797 let ap = Applicability::MachineApplicable;
798 match sig.decl.output {
799 hir::FnRetTy::DefaultReturn(sp) => {
800 let sugg = format!("-> {} ", trait_sig.output());
801 diag.span_suggestion_verbose(sp, msg, sugg, ap);
803 hir::FnRetTy::Return(hir_ty) => {
804 let sugg = trait_sig.output();
805 diag.span_suggestion(hir_ty.span, msg, sugg, ap);
811 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
812 diag.span_suggestion(
814 "change the parameter type to match the trait",
816 Applicability::MachineApplicable,
823 cause.span = impl_err_span;
824 infcx.err_ctxt().note_type_err(
827 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
828 Some(infer::ValuePairs::Terms(ExpectedFound {
829 expected: trait_fty.into(),
830 found: impl_fty.into(),
840 fn check_region_bounds_on_impl_item<'tcx>(
842 impl_m: &ty::AssocItem,
843 trait_m: &ty::AssocItem,
845 ) -> Result<(), ErrorGuaranteed> {
846 let impl_generics = tcx.generics_of(impl_m.def_id);
847 let impl_params = impl_generics.own_counts().lifetimes;
849 let trait_generics = tcx.generics_of(trait_m.def_id);
850 let trait_params = trait_generics.own_counts().lifetimes;
853 "check_region_bounds_on_impl_item: \
854 trait_generics={:?} \
856 trait_generics, impl_generics
859 // Must have same number of early-bound lifetime parameters.
860 // Unfortunately, if the user screws up the bounds, then this
861 // will change classification between early and late. E.g.,
862 // if in trait we have `<'a,'b:'a>`, and in impl we just have
863 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
864 // in trait but 0 in the impl. But if we report "expected 2
865 // but found 0" it's confusing, because it looks like there
866 // are zero. Since I don't quite know how to phrase things at
867 // the moment, give a kind of vague error message.
868 if trait_params != impl_params {
871 .get_generics(impl_m.def_id.expect_local())
872 .expect("expected impl item to have generics or else we can't compare them")
875 let mut generics_span = None;
876 let mut bounds_span = vec![];
877 let mut where_span = None;
878 if let Some(trait_node) = tcx.hir().get_if_local(trait_m.def_id)
879 && let Some(trait_generics) = trait_node.generics()
881 generics_span = Some(trait_generics.span);
882 // FIXME: we could potentially look at the impl's bounds to not point at bounds that
883 // *are* present in the impl.
884 for p in trait_generics.predicates {
885 if let hir::WherePredicate::BoundPredicate(pred) = p {
886 for b in pred.bounds {
887 if let hir::GenericBound::Outlives(lt) = b {
888 bounds_span.push(lt.ident.span);
893 if let Some(impl_node) = tcx.hir().get_if_local(impl_m.def_id)
894 && let Some(impl_generics) = impl_node.generics()
896 let mut impl_bounds = 0;
897 for p in impl_generics.predicates {
898 if let hir::WherePredicate::BoundPredicate(pred) = p {
899 for b in pred.bounds {
900 if let hir::GenericBound::Outlives(_) = b {
906 if impl_bounds == bounds_span.len() {
907 bounds_span = vec![];
908 } else if impl_generics.has_where_clause_predicates {
909 where_span = Some(impl_generics.where_clause_span);
915 .create_err(LifetimesOrBoundsMismatchOnTrait {
917 item_kind: assoc_item_kind_str(impl_m),
918 ident: impl_m.ident(tcx),
924 return Err(reported);
930 #[instrument(level = "debug", skip(infcx))]
931 fn extract_spans_for_error_reporting<'tcx>(
932 infcx: &infer::InferCtxt<'tcx>,
934 cause: &ObligationCause<'tcx>,
935 impl_m: &ty::AssocItem,
936 trait_m: &ty::AssocItem,
937 ) -> (Span, Option<Span>) {
939 let mut impl_args = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
940 ImplItemKind::Fn(ref sig, _) => {
941 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
943 _ => bug!("{:?} is not a method", impl_m),
946 trait_m.def_id.as_local().map(|def_id| match tcx.hir().expect_trait_item(def_id).kind {
947 TraitItemKind::Fn(ref sig, _) => {
948 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
950 _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
954 TypeError::ArgumentMutability(i) => {
955 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
957 TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
958 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
960 _ => (cause.span(), tcx.hir().span_if_local(trait_m.def_id)),
964 fn compare_self_type<'tcx>(
966 impl_m: &ty::AssocItem,
968 trait_m: &ty::AssocItem,
969 impl_trait_ref: ty::TraitRef<'tcx>,
970 ) -> Result<(), ErrorGuaranteed> {
971 // Try to give more informative error messages about self typing
972 // mismatches. Note that any mismatch will also be detected
973 // below, where we construct a canonical function type that
974 // includes the self parameter as a normal parameter. It's just
975 // that the error messages you get out of this code are a bit more
976 // inscrutable, particularly for cases where one method has no
979 let self_string = |method: &ty::AssocItem| {
980 let untransformed_self_ty = match method.container {
981 ty::ImplContainer => impl_trait_ref.self_ty(),
982 ty::TraitContainer => tcx.types.self_param,
984 let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
985 let param_env = ty::ParamEnv::reveal_all();
987 let infcx = tcx.infer_ctxt().build();
988 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
989 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
990 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
991 ExplicitSelf::ByValue => "self".to_owned(),
992 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
993 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
994 _ => format!("self: {self_arg_ty}"),
998 match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
999 (false, false) | (true, true) => {}
1002 let self_descr = self_string(impl_m);
1003 let mut err = struct_span_err!(
1007 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1011 err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
1012 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1013 err.span_label(span, format!("trait method declared without `{self_descr}`"));
1015 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1017 let reported = err.emit();
1018 return Err(reported);
1022 let self_descr = self_string(trait_m);
1023 let mut err = struct_span_err!(
1027 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1031 err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
1032 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1033 err.span_label(span, format!("`{self_descr}` used in trait"));
1035 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1037 let reported = err.emit();
1038 return Err(reported);
1045 /// Checks that the number of generics on a given assoc item in a trait impl is the same
1046 /// as the number of generics on the respective assoc item in the trait definition.
1048 /// For example this code emits the errors in the following code:
1055 /// impl Trait for () {
1058 /// type Assoc = u32;
1063 /// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
1064 /// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
1065 /// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
1066 fn compare_number_of_generics<'tcx>(
1068 impl_: &ty::AssocItem,
1069 trait_: &ty::AssocItem,
1070 trait_span: Option<Span>,
1072 ) -> Result<(), ErrorGuaranteed> {
1073 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1074 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1076 // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
1077 // in `compare_generic_param_kinds` which will give a nicer error message than something like:
1078 // "expected 1 type parameter, found 0 type parameters"
1079 if (trait_own_counts.types + trait_own_counts.consts)
1080 == (impl_own_counts.types + impl_own_counts.consts)
1086 ("type", trait_own_counts.types, impl_own_counts.types),
1087 ("const", trait_own_counts.consts, impl_own_counts.consts),
1090 let item_kind = assoc_item_kind_str(impl_);
1092 let mut err_occurred = None;
1093 for (kind, trait_count, impl_count) in matchings {
1094 if impl_count != trait_count {
1095 let arg_spans = |kind: ty::AssocKind, generics: &hir::Generics<'_>| {
1096 let mut spans = generics
1099 .filter(|p| match p.kind {
1100 hir::GenericParamKind::Lifetime {
1101 kind: hir::LifetimeParamKind::Elided,
1103 // A fn can have an arbitrary number of extra elided lifetimes for the
1105 !matches!(kind, ty::AssocKind::Fn)
1110 .collect::<Vec<Span>>();
1111 if spans.is_empty() {
1112 spans = vec![generics.span]
1116 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1117 let trait_item = tcx.hir().expect_trait_item(def_id);
1118 let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
1119 let impl_trait_spans: Vec<Span> = trait_item
1123 .filter_map(|p| match p.kind {
1124 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1128 (Some(arg_spans), impl_trait_spans)
1130 (trait_span.map(|s| vec![s]), vec![])
1133 let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
1134 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1138 .filter_map(|p| match p.kind {
1139 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1143 let spans = arg_spans(impl_.kind, impl_item.generics);
1144 let span = spans.first().copied();
1146 let mut err = tcx.sess.struct_span_err_with_code(
1149 "{} `{}` has {} {kind} parameter{} but its trait \
1150 declaration has {} {kind} parameter{}",
1154 pluralize!(impl_count),
1156 pluralize!(trait_count),
1159 DiagnosticId::Error("E0049".into()),
1162 let mut suffix = None;
1164 if let Some(spans) = trait_spans {
1165 let mut spans = spans.iter();
1166 if let Some(span) = spans.next() {
1170 "expected {} {} parameter{}",
1173 pluralize!(trait_count),
1178 err.span_label(*span, "");
1181 suffix = Some(format!(", expected {trait_count}"));
1184 if let Some(span) = span {
1188 "found {} {} parameter{}{}",
1191 pluralize!(impl_count),
1192 suffix.unwrap_or_else(String::new),
1197 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1198 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1201 let reported = err.emit_unless(delay);
1202 err_occurred = Some(reported);
1206 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1209 fn compare_number_of_method_arguments<'tcx>(
1211 impl_m: &ty::AssocItem,
1213 trait_m: &ty::AssocItem,
1214 trait_item_span: Option<Span>,
1215 ) -> Result<(), ErrorGuaranteed> {
1216 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1217 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1218 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
1219 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
1220 if trait_number_args != impl_number_args {
1221 let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
1222 match tcx.hir().expect_trait_item(def_id).kind {
1223 TraitItemKind::Fn(ref trait_m_sig, _) => {
1224 let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
1225 if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
1229 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1235 _ => bug!("{:?} is not a method", impl_m),
1240 let impl_span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
1241 ImplItemKind::Fn(ref impl_m_sig, _) => {
1242 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
1243 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
1247 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1253 _ => bug!("{:?} is not a method", impl_m),
1255 let mut err = struct_span_err!(
1259 "method `{}` has {} but the declaration in trait `{}` has {}",
1261 potentially_plural_count(impl_number_args, "parameter"),
1262 tcx.def_path_str(trait_m.def_id),
1265 if let Some(trait_span) = trait_span {
1269 "trait requires {}",
1270 potentially_plural_count(trait_number_args, "parameter")
1274 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1279 "expected {}, found {}",
1280 potentially_plural_count(trait_number_args, "parameter"),
1284 let reported = err.emit();
1285 return Err(reported);
1291 fn compare_synthetic_generics<'tcx>(
1293 impl_m: &ty::AssocItem,
1294 trait_m: &ty::AssocItem,
1295 ) -> Result<(), ErrorGuaranteed> {
1296 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1297 // 1. Better messages for the span labels
1298 // 2. Explanation as to what is going on
1299 // If we get here, we already have the same number of generics, so the zip will
1301 let mut error_found = None;
1302 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1303 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1304 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
1305 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1306 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1308 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
1309 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1310 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1312 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1313 iter::zip(impl_m_type_params, trait_m_type_params)
1315 if impl_synthetic != trait_synthetic {
1316 let impl_def_id = impl_def_id.expect_local();
1317 let impl_span = tcx.def_span(impl_def_id);
1318 let trait_span = tcx.def_span(trait_def_id);
1319 let mut err = struct_span_err!(
1323 "method `{}` has incompatible signature for trait",
1326 err.span_label(trait_span, "declaration in trait here");
1327 match (impl_synthetic, trait_synthetic) {
1328 // The case where the impl method uses `impl Trait` but the trait method uses
1329 // explicit generics
1331 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1333 // try taking the name from the trait impl
1334 // FIXME: this is obviously suboptimal since the name can already be used
1335 // as another generic argument
1336 let new_name = tcx.opt_item_name(trait_def_id)?;
1337 let trait_m = trait_m.def_id.as_local()?;
1338 let trait_m = tcx.hir().expect_trait_item(trait_m);
1340 let impl_m = impl_m.def_id.as_local()?;
1341 let impl_m = tcx.hir().expect_impl_item(impl_m);
1343 // in case there are no generics, take the spot between the function name
1344 // and the opening paren of the argument list
1345 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1346 // in case there are generics, just replace them
1348 impl_m.generics.span.substitute_dummy(new_generics_span);
1349 // replace with the generics from the trait
1351 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1353 err.multipart_suggestion(
1354 "try changing the `impl Trait` argument to a generic parameter",
1356 // replace `impl Trait` with `T`
1357 (impl_span, new_name.to_string()),
1358 // replace impl method generics with trait method generics
1359 // This isn't quite right, as users might have changed the names
1360 // of the generics, but it works for the common case
1361 (generics_span, new_generics),
1363 Applicability::MaybeIncorrect,
1368 // The case where the trait method uses `impl Trait`, but the impl method uses
1369 // explicit generics.
1371 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1373 let impl_m = impl_m.def_id.as_local()?;
1374 let impl_m = tcx.hir().expect_impl_item(impl_m);
1375 let input_tys = match impl_m.kind {
1376 hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
1377 _ => unreachable!(),
1379 struct Visitor(Option<Span>, hir::def_id::LocalDefId);
1380 impl<'v> intravisit::Visitor<'v> for Visitor {
1381 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
1382 intravisit::walk_ty(self, ty);
1383 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
1385 && let Res::Def(DefKind::TyParam, def_id) = path.res
1386 && def_id == self.1.to_def_id()
1388 self.0 = Some(ty.span);
1392 let mut visitor = Visitor(None, impl_def_id);
1393 for ty in input_tys {
1394 intravisit::Visitor::visit_ty(&mut visitor, ty);
1396 let span = visitor.0?;
1398 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
1399 let bounds = bounds.first()?.span().to(bounds.last()?.span());
1400 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1402 err.multipart_suggestion(
1403 "try removing the generic parameter and using `impl Trait` instead",
1405 // delete generic parameters
1406 (impl_m.generics.span, String::new()),
1407 // replace param usage with `impl Trait`
1408 (span, format!("impl {bounds}")),
1410 Applicability::MaybeIncorrect,
1415 _ => unreachable!(),
1417 let reported = err.emit();
1418 error_found = Some(reported);
1421 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1424 /// Checks that all parameters in the generics of a given assoc item in a trait impl have
1425 /// the same kind as the respective generic parameter in the trait def.
1427 /// For example all 4 errors in the following code are emitted here:
1430 /// fn foo<const N: u8>();
1431 /// type bar<const N: u8>;
1432 /// fn baz<const N: u32>();
1436 /// impl Foo for () {
1437 /// fn foo<const N: u64>() {}
1439 /// type bar<const N: u64> {}
1443 /// type blah<const N: i64> = u32;
1448 /// This function does not handle lifetime parameters
1449 fn compare_generic_param_kinds<'tcx>(
1451 impl_item: &ty::AssocItem,
1452 trait_item: &ty::AssocItem,
1454 ) -> Result<(), ErrorGuaranteed> {
1455 assert_eq!(impl_item.kind, trait_item.kind);
1457 let ty_const_params_of = |def_id| {
1458 tcx.generics_of(def_id).params.iter().filter(|param| {
1461 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1466 for (param_impl, param_trait) in
1467 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1469 use GenericParamDefKind::*;
1470 if match (¶m_impl.kind, ¶m_trait.kind) {
1471 (Const { .. }, Const { .. })
1472 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1476 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1477 // this is exhaustive so that anyone adding new generic param kinds knows
1478 // to make sure this error is reported for them.
1479 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1480 (Lifetime { .. }, _) | (_, Lifetime { .. }) => unreachable!(),
1482 let param_impl_span = tcx.def_span(param_impl.def_id);
1483 let param_trait_span = tcx.def_span(param_trait.def_id);
1485 let mut err = struct_span_err!(
1489 "{} `{}` has an incompatible generic parameter for trait `{}`",
1490 assoc_item_kind_str(&impl_item),
1492 &tcx.def_path_str(tcx.parent(trait_item.def_id))
1495 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1497 format!("{} const parameter of type `{}`", prefix, tcx.type_of(param.def_id))
1499 Type { .. } => format!("{} type parameter", prefix),
1500 Lifetime { .. } => unreachable!(),
1503 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1504 err.span_label(trait_header_span, "");
1505 err.span_label(param_trait_span, make_param_message("expected", param_trait));
1507 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1508 err.span_label(impl_header_span, "");
1509 err.span_label(param_impl_span, make_param_message("found", param_impl));
1511 let reported = err.emit_unless(delay);
1512 return Err(reported);
1519 /// Use `tcx.compare_impl_const` instead
1520 pub(super) fn compare_impl_const_raw(
1522 (impl_const_item_def, trait_const_item_def): (LocalDefId, DefId),
1523 ) -> Result<(), ErrorGuaranteed> {
1524 let impl_const_item = tcx.associated_item(impl_const_item_def);
1525 let trait_const_item = tcx.associated_item(trait_const_item_def);
1526 let impl_trait_ref = tcx.impl_trait_ref(impl_const_item.container_id(tcx)).unwrap();
1527 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
1529 let impl_c_span = tcx.def_span(impl_const_item_def.to_def_id());
1531 let infcx = tcx.infer_ctxt().build();
1532 let param_env = tcx.param_env(impl_const_item_def.to_def_id());
1533 let ocx = ObligationCtxt::new(&infcx);
1535 // The below is for the most part highly similar to the procedure
1536 // for methods above. It is simpler in many respects, especially
1537 // because we shouldn't really have to deal with lifetimes or
1538 // predicates. In fact some of this should probably be put into
1539 // shared functions because of DRY violations...
1540 let trait_to_impl_substs = impl_trait_ref.substs;
1542 // Create a parameter environment that represents the implementation's
1544 let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_const_item_def);
1546 // Compute placeholder form of impl and trait const tys.
1547 let impl_ty = tcx.type_of(impl_const_item_def.to_def_id());
1548 let trait_ty = tcx.bound_type_of(trait_const_item_def).subst(tcx, trait_to_impl_substs);
1549 let mut cause = ObligationCause::new(
1552 ObligationCauseCode::CompareImplItemObligation {
1553 impl_item_def_id: impl_const_item_def,
1554 trait_item_def_id: trait_const_item_def,
1555 kind: impl_const_item.kind,
1559 // There is no "body" here, so just pass dummy id.
1560 let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
1562 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1564 let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
1566 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1568 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
1570 if let Err(terr) = err {
1572 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1576 // Locate the Span containing just the type of the offending impl
1577 match tcx.hir().expect_impl_item(impl_const_item_def).kind {
1578 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
1579 _ => bug!("{:?} is not a impl const", impl_const_item),
1582 let mut diag = struct_span_err!(
1586 "implemented const `{}` has an incompatible type for trait",
1587 trait_const_item.name
1590 let trait_c_span = trait_const_item_def.as_local().map(|trait_c_def_id| {
1591 // Add a label to the Span containing just the type of the const
1592 match tcx.hir().expect_trait_item(trait_c_def_id).kind {
1593 TraitItemKind::Const(ref ty, _) => ty.span,
1594 _ => bug!("{:?} is not a trait const", trait_const_item),
1598 infcx.err_ctxt().note_type_err(
1601 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1602 Some(infer::ValuePairs::Terms(ExpectedFound {
1603 expected: trait_ty.into(),
1604 found: impl_ty.into(),
1610 return Err(diag.emit());
1613 // Check that all obligations are satisfied by the implementation's
1615 let errors = ocx.select_all_or_error();
1616 if !errors.is_empty() {
1617 return Err(infcx.err_ctxt().report_fulfillment_errors(&errors, None));
1620 let outlives_environment = OutlivesEnvironment::new(param_env);
1621 infcx.check_region_obligations_and_report_errors(impl_const_item_def, &outlives_environment)?;
1626 pub(super) fn compare_impl_ty<'tcx>(
1628 impl_ty: &ty::AssocItem,
1630 trait_ty: &ty::AssocItem,
1631 impl_trait_ref: ty::TraitRef<'tcx>,
1632 trait_item_span: Option<Span>,
1634 debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1636 let _: Result<(), ErrorGuaranteed> = (|| {
1637 compare_number_of_generics(tcx, impl_ty, trait_ty, trait_item_span, false)?;
1639 compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
1641 let sp = tcx.def_span(impl_ty.def_id);
1642 compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;
1644 check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1648 /// The equivalent of [compare_predicate_entailment], but for associated types
1649 /// instead of associated functions.
1650 fn compare_type_predicate_entailment<'tcx>(
1652 impl_ty: &ty::AssocItem,
1654 trait_ty: &ty::AssocItem,
1655 impl_trait_ref: ty::TraitRef<'tcx>,
1656 ) -> Result<(), ErrorGuaranteed> {
1657 let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1658 let trait_to_impl_substs =
1659 impl_substs.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.substs);
1661 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1662 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1664 check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
1666 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1668 if impl_ty_own_bounds.is_empty() {
1669 // Nothing to check.
1673 // This `HirId` should be used for the `body_id` field on each
1674 // `ObligationCause` (and the `FnCtxt`). This is what
1675 // `regionck_item` expects.
1676 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1677 debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1679 // The predicates declared by the impl definition, the trait and the
1680 // associated type in the trait are assumed.
1681 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1682 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1685 .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1687 debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1689 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1690 let param_env = ty::ParamEnv::new(
1691 tcx.intern_predicates(&hybrid_preds.predicates),
1693 hir::Constness::NotConst,
1695 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
1696 let infcx = tcx.infer_ctxt().build();
1697 let ocx = ObligationCtxt::new(&infcx);
1699 debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1701 assert_eq!(impl_ty_own_bounds.predicates.len(), impl_ty_own_bounds.spans.len());
1702 for (span, predicate) in std::iter::zip(impl_ty_own_bounds.spans, impl_ty_own_bounds.predicates)
1704 let cause = ObligationCause::misc(span, impl_ty_hir_id);
1705 let predicate = ocx.normalize(&cause, param_env, predicate);
1707 let cause = ObligationCause::new(
1710 ObligationCauseCode::CompareImplItemObligation {
1711 impl_item_def_id: impl_ty.def_id.expect_local(),
1712 trait_item_def_id: trait_ty.def_id,
1716 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
1719 // Check that all obligations are satisfied by the implementation's
1721 let errors = ocx.select_all_or_error();
1722 if !errors.is_empty() {
1723 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
1724 return Err(reported);
1727 // Finally, resolve all regions. This catches wily misuses of
1728 // lifetime parameters.
1729 let outlives_environment = OutlivesEnvironment::new(param_env);
1730 infcx.check_region_obligations_and_report_errors(
1731 impl_ty.def_id.expect_local(),
1732 &outlives_environment,
1738 /// Validate that `ProjectionCandidate`s created for this associated type will
1743 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1745 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1746 /// impl is well-formed we have to prove `S: Copy`.
1748 /// For default associated types the normalization is not possible (the value
1749 /// from the impl could be overridden). We also can't normalize generic
1750 /// associated types (yet) because they contain bound parameters.
1751 #[instrument(level = "debug", skip(tcx))]
1752 pub(super) fn check_type_bounds<'tcx>(
1754 trait_ty: &ty::AssocItem,
1755 impl_ty: &ty::AssocItem,
1757 impl_trait_ref: ty::TraitRef<'tcx>,
1758 ) -> Result<(), ErrorGuaranteed> {
1761 // impl<A, B> Foo<u32> for (A, B) {
1765 // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1766 // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1767 // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1768 // the *trait* with the generic associated type parameters (as bound vars).
1770 // A note regarding the use of bound vars here:
1771 // Imagine as an example
1774 // type Member<C: Eq>;
1777 // impl Family for VecFamily {
1778 // type Member<C: Eq> = i32;
1781 // Here, we would generate
1783 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1785 // when we really would like to generate
1787 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1789 // But, this is probably fine, because although the first clause can be used with types C that
1790 // do not implement Eq, for it to cause some kind of problem, there would have to be a
1791 // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1792 // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1793 // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1794 // the trait (notably, that X: Eq and T: Family).
1795 let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1796 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1797 if let Some(def_id) = defs.parent {
1798 let parent_defs = tcx.generics_of(def_id);
1799 InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1800 tcx.mk_param_from_def(param)
1803 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1804 smallvec::SmallVec::with_capacity(defs.count());
1805 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1806 GenericParamDefKind::Type { .. } => {
1807 let kind = ty::BoundTyKind::Param(param.name);
1808 let bound_var = ty::BoundVariableKind::Ty(kind);
1809 bound_vars.push(bound_var);
1810 tcx.mk_ty(ty::Bound(
1812 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1816 GenericParamDefKind::Lifetime => {
1817 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1818 let bound_var = ty::BoundVariableKind::Region(kind);
1819 bound_vars.push(bound_var);
1820 tcx.mk_region(ty::ReLateBound(
1822 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1826 GenericParamDefKind::Const { .. } => {
1827 let bound_var = ty::BoundVariableKind::Const;
1828 bound_vars.push(bound_var);
1830 ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(bound_vars.len() - 1)),
1831 tcx.type_of(param.def_id),
1836 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
1837 let impl_ty_substs = tcx.intern_substs(&substs);
1838 let container_id = impl_ty.container_id(tcx);
1840 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
1841 let impl_ty_value = tcx.type_of(impl_ty.def_id);
1843 let param_env = tcx.param_env(impl_ty.def_id);
1845 // When checking something like
1847 // trait X { type Y: PartialEq<<Self as X>::Y> }
1848 // impl X for T { default type Y = S; }
1850 // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
1851 // we want <T as X>::Y to normalize to S. This is valid because we are
1852 // checking the default value specifically here. Add this equality to the
1853 // ParamEnv for normalization specifically.
1854 let normalize_param_env = {
1855 let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
1856 match impl_ty_value.kind() {
1857 ty::Alias(ty::Projection, proj)
1858 if proj.def_id == trait_ty.def_id && proj.substs == rebased_substs =>
1860 // Don't include this predicate if the projected type is
1861 // exactly the same as the projection. This can occur in
1862 // (somewhat dubious) code like this:
1864 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
1866 _ => predicates.push(
1867 ty::Binder::bind_with_vars(
1868 ty::ProjectionPredicate {
1869 projection_ty: tcx.mk_alias_ty(trait_ty.def_id, rebased_substs),
1870 term: impl_ty_value.into(),
1878 tcx.intern_predicates(&predicates),
1880 param_env.constness(),
1883 debug!(?normalize_param_env);
1885 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1886 let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1887 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
1889 let infcx = tcx.infer_ctxt().build();
1890 let ocx = ObligationCtxt::new(&infcx);
1892 let assumed_wf_types =
1893 ocx.assumed_wf_types(param_env, impl_ty_span, impl_ty.def_id.expect_local());
1895 let normalize_cause = ObligationCause::new(
1898 ObligationCauseCode::CheckAssociatedTypeBounds {
1899 impl_item_def_id: impl_ty.def_id.expect_local(),
1900 trait_item_def_id: trait_ty.def_id,
1903 let mk_cause = |span: Span| {
1904 let code = if span.is_dummy() {
1905 traits::ItemObligation(trait_ty.def_id)
1907 traits::BindingObligation(trait_ty.def_id, span)
1909 ObligationCause::new(impl_ty_span, impl_ty_hir_id, code)
1912 let obligations = tcx
1913 .bound_explicit_item_bounds(trait_ty.def_id)
1914 .subst_iter_copied(tcx, rebased_substs)
1915 .map(|(concrete_ty_bound, span)| {
1916 debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
1917 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
1920 debug!("check_type_bounds: item_bounds={:?}", obligations);
1922 for mut obligation in util::elaborate_obligations(tcx, obligations) {
1923 let normalized_predicate =
1924 ocx.normalize(&normalize_cause, normalize_param_env, obligation.predicate);
1925 debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
1926 obligation.predicate = normalized_predicate;
1928 ocx.register_obligation(obligation);
1930 // Check that all obligations are satisfied by the implementation's
1932 let errors = ocx.select_all_or_error();
1933 if !errors.is_empty() {
1934 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
1935 return Err(reported);
1938 // Finally, resolve all regions. This catches wily misuses of
1939 // lifetime parameters.
1940 let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_hir_id, assumed_wf_types);
1941 let outlives_environment =
1942 OutlivesEnvironment::with_bounds(param_env, Some(&infcx), implied_bounds);
1944 infcx.check_region_obligations_and_report_errors(
1945 impl_ty.def_id.expect_local(),
1946 &outlives_environment,
1949 let constraints = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
1950 for (key, value) in constraints {
1953 .report_mismatched_types(
1954 &ObligationCause::misc(
1955 value.hidden_type.span,
1956 tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local()),
1958 tcx.mk_opaque(key.def_id.to_def_id(), key.substs),
1959 value.hidden_type.ty,
1960 TypeError::Mismatch,
1968 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
1969 match impl_item.kind {
1970 ty::AssocKind::Const => "const",
1971 ty::AssocKind::Fn => "method",
1972 ty::AssocKind::Type => "type",