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, AssocItem, DefIdTree, TraitRef, Ty, TypeFoldable, TypeFolder, TypeSuperFoldable,
20 use rustc_middle::ty::{FnSig, InternalSubsts};
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(crate) 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 if let Err(_) = compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref) {
54 if let Err(_) = compare_number_of_generics(tcx, impl_m, impl_m_span, trait_m, trait_item_span) {
58 if let Err(_) = compare_generic_param_kinds(tcx, impl_m, trait_m) {
63 compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
68 if let Err(_) = compare_synthetic_generics(tcx, impl_m, trait_m) {
72 if let Err(_) = compare_predicate_entailment(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
78 /// This function is best explained by example. Consider a trait:
80 /// trait Trait<'t, T> {
82 /// fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
87 /// impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
89 /// fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo;
92 /// We wish to decide if those two method types are compatible.
93 /// For this we have to show that, assuming the bounds of the impl hold, the
94 /// bounds of `trait_m` imply the bounds of `impl_m`.
96 /// We start out with `trait_to_impl_substs`, that maps the trait
97 /// type parameters to impl type parameters. This is taken from the
98 /// impl trait reference:
100 /// trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
102 /// We create a mapping `dummy_substs` that maps from the impl type
103 /// parameters to fresh types and regions. For type parameters,
104 /// this is the identity transform, but we could as well use any
105 /// placeholder types. For regions, we convert from bound to free
106 /// regions (Note: but only early-bound regions, i.e., those
107 /// declared on the impl or used in type parameter bounds).
109 /// impl_to_placeholder_substs = {'i => 'i0, U => U0, N => N0 }
111 /// Now we can apply `placeholder_substs` to the type of the impl method
112 /// to yield a new function type in terms of our fresh, placeholder
115 /// <'b> fn(t: &'i0 U0, m: &'b) -> Foo
117 /// We now want to extract and substitute the type of the *trait*
118 /// method and compare it. To do so, we must create a compound
119 /// substitution by combining `trait_to_impl_substs` and
120 /// `impl_to_placeholder_substs`, and also adding a mapping for the method
121 /// type parameters. We extend the mapping to also include
122 /// the method parameters.
124 /// trait_to_placeholder_substs = { T => &'i0 U0, Self => Foo, M => N0 }
126 /// Applying this to the trait method type yields:
128 /// <'a> fn(t: &'i0 U0, m: &'a) -> Foo
130 /// This type is also the same but the name of the bound region (`'a`
131 /// vs `'b`). However, the normal subtyping rules on fn types handle
132 /// this kind of equivalency just fine.
134 /// We now use these substitutions to ensure that all declared bounds are
135 /// satisfied by the implementation's method.
137 /// We do this by creating a parameter environment which contains a
138 /// substitution corresponding to `impl_to_placeholder_substs`. We then build
139 /// `trait_to_placeholder_substs` and use it to convert the predicates contained
140 /// in the `trait_m` generics to the placeholder form.
142 /// Finally we register each of these predicates as an obligation and check that
144 #[instrument(level = "debug", skip(tcx, impl_m_span, impl_trait_ref))]
145 fn compare_predicate_entailment<'tcx>(
150 impl_trait_ref: ty::TraitRef<'tcx>,
151 ) -> Result<(), ErrorGuaranteed> {
152 let trait_to_impl_substs = impl_trait_ref.substs;
154 // This node-id should be used for the `body_id` field on each
155 // `ObligationCause` (and the `FnCtxt`).
157 // FIXME(@lcnr): remove that after removing `cause.body_id` from
159 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
160 // We sometimes modify the span further down.
161 let mut cause = ObligationCause::new(
164 ObligationCauseCode::CompareImplItemObligation {
165 impl_item_def_id: impl_m.def_id.expect_local(),
166 trait_item_def_id: trait_m.def_id,
171 // Create mapping from impl to placeholder.
172 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
174 // Create mapping from trait to placeholder.
175 let trait_to_placeholder_substs =
176 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
177 debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_substs);
179 let impl_m_generics = tcx.generics_of(impl_m.def_id);
180 let trait_m_generics = tcx.generics_of(trait_m.def_id);
181 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
182 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
184 // Check region bounds.
185 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, &trait_m_generics, &impl_m_generics)?;
187 // Create obligations for each predicate declared by the impl
188 // definition in the context of the trait's parameter
189 // environment. We can't just use `impl_env.caller_bounds`,
190 // however, because we want to replace all late-bound regions with
192 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
193 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
195 debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
197 // This is the only tricky bit of the new way we check implementation methods
198 // We need to build a set of predicates where only the method-level bounds
199 // are from the trait and we assume all other bounds from the implementation
200 // to be previously satisfied.
202 // We then register the obligations from the impl_m and check to see
203 // if all constraints hold.
206 .extend(trait_m_predicates.instantiate_own(tcx, trait_to_placeholder_substs).predicates);
208 // Construct trait parameter environment and then shift it into the placeholder viewpoint.
209 // The key step here is to update the caller_bounds's predicates to be
210 // the new hybrid bounds we computed.
211 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
212 let param_env = ty::ParamEnv::new(
213 tcx.intern_predicates(&hybrid_preds.predicates),
215 hir::Constness::NotConst,
217 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
219 let infcx = &tcx.infer_ctxt().build();
220 let ocx = ObligationCtxt::new(infcx);
222 debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
224 let mut selcx = traits::SelectionContext::new(&infcx);
225 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
226 for (predicate, span) in iter::zip(impl_m_own_bounds.predicates, impl_m_own_bounds.spans) {
227 let normalize_cause = traits::ObligationCause::misc(span, impl_m_hir_id);
228 let traits::Normalized { value: predicate, obligations } =
229 traits::normalize(&mut selcx, param_env, normalize_cause, predicate);
231 ocx.register_obligations(obligations);
232 let cause = ObligationCause::new(
235 ObligationCauseCode::CompareImplItemObligation {
236 impl_item_def_id: impl_m.def_id.expect_local(),
237 trait_item_def_id: trait_m.def_id,
241 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
244 // We now need to check that the signature of the impl method is
245 // compatible with that of the trait method. We do this by
246 // checking that `impl_fty <: trait_fty`.
248 // FIXME. Unfortunately, this doesn't quite work right now because
249 // associated type normalization is not integrated into subtype
250 // checks. For the comparison to be valid, we need to
251 // normalize the associated types in the impl/trait methods
252 // first. However, because function types bind regions, just
253 // calling `normalize_associated_types_in` would have no effect on
254 // any associated types appearing in the fn arguments or return
257 // Compute placeholder form of impl and trait method tys.
260 let mut wf_tys = FxIndexSet::default();
262 let impl_sig = infcx.replace_bound_vars_with_fresh_vars(
264 infer::HigherRankedType,
265 tcx.fn_sig(impl_m.def_id),
268 let norm_cause = ObligationCause::misc(impl_m_span, impl_m_hir_id);
269 let impl_sig = ocx.normalize(norm_cause.clone(), param_env, impl_sig);
270 let impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(impl_sig));
271 debug!("compare_impl_method: impl_fty={:?}", impl_fty);
273 let trait_sig = tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs);
274 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
276 // Next, add all inputs and output as well-formed tys. Importantly,
277 // we have to do this before normalization, since the normalized ty may
278 // not contain the input parameters. See issue #87748.
279 wf_tys.extend(trait_sig.inputs_and_output.iter());
280 let trait_sig = ocx.normalize(norm_cause, param_env, trait_sig);
281 // We also have to add the normalized trait signature
282 // as we don't normalize during implied bounds computation.
283 wf_tys.extend(trait_sig.inputs_and_output.iter());
284 let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
286 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
288 // FIXME: We'd want to keep more accurate spans than "the method signature" when
289 // processing the comparison between the trait and impl fn, but we sadly lose them
290 // and point at the whole signature when a trait bound or specific input or output
291 // type would be more appropriate. In other places we have a `Vec<Span>`
292 // corresponding to their `Vec<Predicate>`, but we don't have that here.
293 // Fixing this would improve the output of test `issue-83765.rs`.
294 let mut result = ocx.sup(&cause, param_env, trait_fty, impl_fty);
296 // HACK(RPITIT): #101614. When we are trying to infer the hidden types for
297 // RPITITs, we need to equate the output tys instead of just subtyping. If
298 // we just use `sup` above, we'll end up `&'static str <: _#1t`, which causes
299 // us to infer `_#1t = #'_#2r str`, where `'_#2r` is unconstrained, which gets
300 // fixed up to `ReEmpty`, and which is certainly not what we want.
301 if trait_fty.has_infer_types() {
303 result.and_then(|()| ocx.eq(&cause, param_env, trait_sig.output(), impl_sig.output()));
306 if let Err(terr) = result {
307 debug!(?terr, "sub_types failed: impl ty {:?}, trait ty {:?}", impl_fty, trait_fty);
309 let emitted = report_trait_method_mismatch(
314 (trait_m, trait_fty),
322 // Check that all obligations are satisfied by the implementation's
324 let errors = ocx.select_all_or_error();
325 if !errors.is_empty() {
326 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
327 return Err(reported);
330 // Finally, resolve all regions. This catches wily misuses of
331 // lifetime parameters.
332 let outlives_environment = OutlivesEnvironment::with_bounds(
335 infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys),
337 infcx.check_region_obligations_and_report_errors(
338 impl_m.def_id.expect_local(),
339 &outlives_environment,
345 #[instrument(skip(tcx), level = "debug", ret)]
346 pub fn collect_trait_impl_trait_tys<'tcx>(
349 ) -> Result<&'tcx FxHashMap<DefId, Ty<'tcx>>, ErrorGuaranteed> {
350 let impl_m = tcx.opt_associated_item(def_id).unwrap();
351 let trait_m = tcx.opt_associated_item(impl_m.trait_item_def_id.unwrap()).unwrap();
352 let impl_trait_ref = tcx.impl_trait_ref(impl_m.impl_container(tcx).unwrap()).unwrap();
353 let param_env = tcx.param_env(def_id);
355 let trait_to_impl_substs = impl_trait_ref.substs;
357 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
358 let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
359 let mut cause = ObligationCause::new(
362 ObligationCauseCode::CompareImplItemObligation {
363 impl_item_def_id: impl_m.def_id.expect_local(),
364 trait_item_def_id: trait_m.def_id,
369 // Create mapping from impl to placeholder.
370 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
372 // Create mapping from trait to placeholder.
373 let trait_to_placeholder_substs =
374 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
376 let infcx = &tcx.infer_ctxt().build();
377 let ocx = ObligationCtxt::new(infcx);
379 let norm_cause = ObligationCause::misc(return_span, impl_m_hir_id);
380 let impl_sig = ocx.normalize(
383 infcx.replace_bound_vars_with_fresh_vars(
385 infer::HigherRankedType,
386 tcx.fn_sig(impl_m.def_id),
389 let impl_return_ty = impl_sig.output();
391 let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_hir_id);
392 let unnormalized_trait_sig = tcx
393 .liberate_late_bound_regions(
395 tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs),
397 .fold_with(&mut collector);
398 let trait_sig = ocx.normalize(norm_cause.clone(), param_env, unnormalized_trait_sig);
399 let trait_return_ty = trait_sig.output();
401 let wf_tys = FxIndexSet::from_iter(
402 unnormalized_trait_sig.inputs_and_output.iter().chain(trait_sig.inputs_and_output.iter()),
405 match infcx.at(&cause, param_env).eq(trait_return_ty, impl_return_ty) {
406 Ok(infer::InferOk { value: (), obligations }) => {
407 ocx.register_obligations(obligations);
410 let mut diag = struct_span_err!(
414 "method `{}` has an incompatible return type for trait",
418 infcx.err_ctxt().note_type_err(
421 hir.get_if_local(impl_m.def_id)
422 .and_then(|node| node.fn_decl())
423 .map(|decl| (decl.output.span(), "return type in trait".to_owned())),
424 Some(infer::ValuePairs::Terms(ExpectedFound {
425 expected: trait_return_ty.into(),
426 found: impl_return_ty.into(),
432 return Err(diag.emit());
436 debug!(?trait_sig, ?impl_sig, "equating function signatures");
438 let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
439 let impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(impl_sig));
441 // Unify the whole function signature. We need to do this to fully infer
442 // the lifetimes of the return type, but do this after unifying just the
443 // return types, since we want to avoid duplicating errors from
444 // `compare_predicate_entailment`.
445 match infcx.at(&cause, param_env).eq(trait_fty, impl_fty) {
446 Ok(infer::InferOk { value: (), obligations }) => {
447 ocx.register_obligations(obligations);
450 // This function gets called during `compare_predicate_entailment` when normalizing a
451 // signature that contains RPITIT. When the method signatures don't match, we have to
452 // emit an error now because `compare_predicate_entailment` will not report the error
453 // when normalization fails.
454 let emitted = report_trait_method_mismatch(
459 (trait_m, trait_fty),
468 // Check that all obligations are satisfied by the implementation's
470 let errors = ocx.select_all_or_error();
471 if !errors.is_empty() {
472 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
473 return Err(reported);
476 // Finally, resolve all regions. This catches wily misuses of
477 // lifetime parameters.
478 let outlives_environment = OutlivesEnvironment::with_bounds(
481 infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys),
483 infcx.check_region_obligations_and_report_errors(
484 impl_m.def_id.expect_local(),
485 &outlives_environment,
488 let mut collected_tys = FxHashMap::default();
489 for (def_id, (ty, substs)) in collector.types {
490 match infcx.fully_resolve(ty) {
492 // `ty` contains free regions that we created earlier while liberating the
493 // trait fn signature. However, projection normalization expects `ty` to
494 // contains `def_id`'s early-bound regions.
495 let id_substs = InternalSubsts::identity_for_item(tcx, def_id);
496 debug!(?id_substs, ?substs);
497 let map: FxHashMap<ty::GenericArg<'tcx>, ty::GenericArg<'tcx>> =
498 std::iter::zip(substs, id_substs).collect();
501 // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound
502 // region substs that are synthesized during AST lowering. These are substs
503 // that are appended to the parent substs (trait and trait method). However,
504 // we're trying to infer the unsubstituted type value of the RPITIT inside
505 // the *impl*, so we can later use the impl's method substs to normalize
506 // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`).
508 // Due to the design of RPITITs, during AST lowering, we have no idea that
509 // an impl method corresponds to a trait method with RPITITs in it. Therefore,
510 // we don't have a list of early-bound region substs for the RPITIT in the impl.
511 // Since early region parameters are index-based, we can't just rebase these
512 // (trait method) early-bound region substs onto the impl, and there's no
513 // guarantee that the indices from the trait substs and impl substs line up.
514 // So to fix this, we subtract the number of trait substs and add the number of
515 // impl substs to *renumber* these early-bound regions to their corresponding
516 // indices in the impl's substitutions list.
518 // Also, we only need to account for a difference in trait and impl substs,
519 // since we previously enforce that the trait method and impl method have the
521 let num_trait_substs = trait_to_impl_substs.len();
522 let num_impl_substs = tcx.generics_of(impl_m.container_id(tcx)).params.len();
523 let ty = tcx.fold_regions(ty, |region, _| {
524 match region.kind() {
525 // Remap all free regions, which correspond to late-bound regions in the function.
527 // Remap early-bound regions as long as they don't come from the `impl` itself.
528 ty::ReEarlyBound(ebr) if tcx.parent(ebr.def_id) != impl_m.container_id(tcx) => {}
531 let Some(ty::ReEarlyBound(e)) = map.get(®ion.into()).map(|r| r.expect_region().kind())
537 "expected ReFree to map to ReEarlyBound"
539 return tcx.lifetimes.re_static;
541 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
544 index: (e.index as usize - num_trait_substs + num_impl_substs) as u32,
548 collected_tys.insert(def_id, ty);
551 let reported = tcx.sess.delay_span_bug(
553 format!("could not fully resolve: {ty} => {err:?}"),
555 collected_tys.insert(def_id, tcx.ty_error_with_guaranteed(reported));
560 Ok(&*tcx.arena.alloc(collected_tys))
563 struct ImplTraitInTraitCollector<'a, 'tcx> {
564 ocx: &'a ObligationCtxt<'a, 'tcx>,
565 types: FxHashMap<DefId, (Ty<'tcx>, ty::SubstsRef<'tcx>)>,
567 param_env: ty::ParamEnv<'tcx>,
571 impl<'a, 'tcx> ImplTraitInTraitCollector<'a, 'tcx> {
573 ocx: &'a ObligationCtxt<'a, 'tcx>,
575 param_env: ty::ParamEnv<'tcx>,
578 ImplTraitInTraitCollector { ocx, types: FxHashMap::default(), span, param_env, body_id }
582 impl<'tcx> TypeFolder<'tcx> for ImplTraitInTraitCollector<'_, 'tcx> {
583 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
587 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
588 if let ty::Projection(proj) = ty.kind()
589 && self.tcx().def_kind(proj.item_def_id) == DefKind::ImplTraitPlaceholder
591 if let Some((ty, _)) = self.types.get(&proj.item_def_id) {
594 //FIXME(RPITIT): Deny nested RPITIT in substs too
595 if proj.substs.has_escaping_bound_vars() {
596 bug!("FIXME(RPITIT): error here");
598 // Replace with infer var
599 let infer_ty = self.ocx.infcx.next_ty_var(TypeVariableOrigin {
601 kind: TypeVariableOriginKind::MiscVariable,
603 self.types.insert(proj.item_def_id, (infer_ty, proj.substs));
604 // Recurse into bounds
605 for (pred, pred_span) in self.tcx().bound_explicit_item_bounds(proj.item_def_id).subst_iter_copied(self.tcx(), proj.substs) {
606 let pred = pred.fold_with(self);
607 let pred = self.ocx.normalize(
608 ObligationCause::misc(self.span, self.body_id),
613 self.ocx.register_obligation(traits::Obligation::new(
615 ObligationCause::new(
618 ObligationCauseCode::BindingObligation(proj.item_def_id, pred_span),
626 ty.super_fold_with(self)
631 fn report_trait_method_mismatch<'tcx>(
633 cause: &mut ObligationCause<'tcx>,
634 infcx: &InferCtxt<'tcx>,
635 terr: TypeError<'tcx>,
636 (trait_m, trait_fty): (&AssocItem, Ty<'tcx>),
637 (impl_m, impl_fty): (&AssocItem, Ty<'tcx>),
638 trait_sig: &FnSig<'tcx>,
639 impl_trait_ref: &TraitRef<'tcx>,
640 ) -> ErrorGuaranteed {
641 let (impl_err_span, trait_err_span) =
642 extract_spans_for_error_reporting(&infcx, terr, &cause, impl_m, trait_m);
644 cause.span = impl_err_span;
646 let mut diag = struct_span_err!(
650 "method `{}` has an incompatible type for trait",
654 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
655 if trait_m.fn_has_self_parameter =>
657 let ty = trait_sig.inputs()[0];
658 let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty()) {
659 ExplicitSelf::ByValue => "self".to_owned(),
660 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
661 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
662 _ => format!("self: {ty}"),
665 // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
666 // span points only at the type `Box<Self`>, but we want to cover the whole
667 // argument pattern and type.
668 let span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
669 ImplItemKind::Fn(ref sig, body) => tcx
671 .body_param_names(body)
672 .zip(sig.decl.inputs.iter())
673 .map(|(param, ty)| param.span.to(ty.span))
675 .unwrap_or(impl_err_span),
676 _ => bug!("{:?} is not a method", impl_m),
679 diag.span_suggestion(
681 "change the self-receiver type to match the trait",
683 Applicability::MachineApplicable,
686 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
687 if trait_sig.inputs().len() == *i {
688 // Suggestion to change output type. We do not suggest in `async` functions
689 // to avoid complex logic or incorrect output.
690 match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
691 ImplItemKind::Fn(ref sig, _)
692 if sig.header.asyncness == hir::IsAsync::NotAsync =>
694 let msg = "change the output type to match the trait";
695 let ap = Applicability::MachineApplicable;
696 match sig.decl.output {
697 hir::FnRetTy::DefaultReturn(sp) => {
698 let sugg = format!("-> {} ", trait_sig.output());
699 diag.span_suggestion_verbose(sp, msg, sugg, ap);
701 hir::FnRetTy::Return(hir_ty) => {
702 let sugg = trait_sig.output();
703 diag.span_suggestion(hir_ty.span, msg, sugg, ap);
709 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
710 diag.span_suggestion(
712 "change the parameter type to match the trait",
714 Applicability::MachineApplicable,
721 infcx.err_ctxt().note_type_err(
724 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
725 Some(infer::ValuePairs::Terms(ExpectedFound {
726 expected: trait_fty.into(),
727 found: impl_fty.into(),
737 fn check_region_bounds_on_impl_item<'tcx>(
739 impl_m: &ty::AssocItem,
740 trait_m: &ty::AssocItem,
741 trait_generics: &ty::Generics,
742 impl_generics: &ty::Generics,
743 ) -> Result<(), ErrorGuaranteed> {
744 let trait_params = trait_generics.own_counts().lifetimes;
745 let impl_params = impl_generics.own_counts().lifetimes;
748 "check_region_bounds_on_impl_item: \
749 trait_generics={:?} \
751 trait_generics, impl_generics
754 // Must have same number of early-bound lifetime parameters.
755 // Unfortunately, if the user screws up the bounds, then this
756 // will change classification between early and late. E.g.,
757 // if in trait we have `<'a,'b:'a>`, and in impl we just have
758 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
759 // in trait but 0 in the impl. But if we report "expected 2
760 // but found 0" it's confusing, because it looks like there
761 // are zero. Since I don't quite know how to phrase things at
762 // the moment, give a kind of vague error message.
763 if trait_params != impl_params {
766 .get_generics(impl_m.def_id.expect_local())
767 .expect("expected impl item to have generics or else we can't compare them")
769 let generics_span = if let Some(local_def_id) = trait_m.def_id.as_local() {
772 .get_generics(local_def_id)
773 .expect("expected trait item to have generics or else we can't compare them")
780 let reported = tcx.sess.emit_err(LifetimesOrBoundsMismatchOnTrait {
782 item_kind: assoc_item_kind_str(impl_m),
783 ident: impl_m.ident(tcx),
786 return Err(reported);
792 #[instrument(level = "debug", skip(infcx))]
793 fn extract_spans_for_error_reporting<'tcx>(
794 infcx: &infer::InferCtxt<'tcx>,
796 cause: &ObligationCause<'tcx>,
797 impl_m: &ty::AssocItem,
798 trait_m: &ty::AssocItem,
799 ) -> (Span, Option<Span>) {
801 let mut impl_args = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
802 ImplItemKind::Fn(ref sig, _) => {
803 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
805 _ => bug!("{:?} is not a method", impl_m),
808 trait_m.def_id.as_local().map(|def_id| match tcx.hir().expect_trait_item(def_id).kind {
809 TraitItemKind::Fn(ref sig, _) => {
810 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
812 _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
816 TypeError::ArgumentMutability(i) => {
817 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
819 TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
820 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
822 _ => (cause.span(), tcx.hir().span_if_local(trait_m.def_id)),
826 fn compare_self_type<'tcx>(
828 impl_m: &ty::AssocItem,
830 trait_m: &ty::AssocItem,
831 impl_trait_ref: ty::TraitRef<'tcx>,
832 ) -> Result<(), ErrorGuaranteed> {
833 // Try to give more informative error messages about self typing
834 // mismatches. Note that any mismatch will also be detected
835 // below, where we construct a canonical function type that
836 // includes the self parameter as a normal parameter. It's just
837 // that the error messages you get out of this code are a bit more
838 // inscrutable, particularly for cases where one method has no
841 let self_string = |method: &ty::AssocItem| {
842 let untransformed_self_ty = match method.container {
843 ty::ImplContainer => impl_trait_ref.self_ty(),
844 ty::TraitContainer => tcx.types.self_param,
846 let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
847 let param_env = ty::ParamEnv::reveal_all();
849 let infcx = tcx.infer_ctxt().build();
850 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
851 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
852 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
853 ExplicitSelf::ByValue => "self".to_owned(),
854 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
855 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
856 _ => format!("self: {self_arg_ty}"),
860 match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
861 (false, false) | (true, true) => {}
864 let self_descr = self_string(impl_m);
865 let mut err = struct_span_err!(
869 "method `{}` has a `{}` declaration in the impl, but not in the trait",
873 err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
874 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
875 err.span_label(span, format!("trait method declared without `{self_descr}`"));
877 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
879 let reported = err.emit();
880 return Err(reported);
884 let self_descr = self_string(trait_m);
885 let mut err = struct_span_err!(
889 "method `{}` has a `{}` declaration in the trait, but not in the impl",
893 err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
894 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
895 err.span_label(span, format!("`{self_descr}` used in trait"));
897 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
899 let reported = err.emit();
900 return Err(reported);
907 /// Checks that the number of generics on a given assoc item in a trait impl is the same
908 /// as the number of generics on the respective assoc item in the trait definition.
910 /// For example this code emits the errors in the following code:
917 /// impl Trait for () {
920 /// type Assoc = u32;
925 /// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
926 /// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
927 /// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
928 fn compare_number_of_generics<'tcx>(
930 impl_: &ty::AssocItem,
932 trait_: &ty::AssocItem,
933 trait_span: Option<Span>,
934 ) -> Result<(), ErrorGuaranteed> {
935 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
936 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
938 // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
939 // in `compare_generic_param_kinds` which will give a nicer error message than something like:
940 // "expected 1 type parameter, found 0 type parameters"
941 if (trait_own_counts.types + trait_own_counts.consts)
942 == (impl_own_counts.types + impl_own_counts.consts)
948 ("type", trait_own_counts.types, impl_own_counts.types),
949 ("const", trait_own_counts.consts, impl_own_counts.consts),
952 let item_kind = assoc_item_kind_str(impl_);
954 let mut err_occurred = None;
955 for (kind, trait_count, impl_count) in matchings {
956 if impl_count != trait_count {
957 let arg_spans = |kind: ty::AssocKind, generics: &hir::Generics<'_>| {
958 let mut spans = generics
961 .filter(|p| match p.kind {
962 hir::GenericParamKind::Lifetime {
963 kind: hir::LifetimeParamKind::Elided,
965 // A fn can have an arbitrary number of extra elided lifetimes for the
967 !matches!(kind, ty::AssocKind::Fn)
972 .collect::<Vec<Span>>();
973 if spans.is_empty() {
974 spans = vec![generics.span]
978 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
979 let trait_item = tcx.hir().expect_trait_item(def_id);
980 let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
981 let impl_trait_spans: Vec<Span> = trait_item
985 .filter_map(|p| match p.kind {
986 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
990 (Some(arg_spans), impl_trait_spans)
992 (trait_span.map(|s| vec![s]), vec![])
995 let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
996 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1000 .filter_map(|p| match p.kind {
1001 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1005 let spans = arg_spans(impl_.kind, impl_item.generics);
1006 let span = spans.first().copied();
1008 let mut err = tcx.sess.struct_span_err_with_code(
1011 "{} `{}` has {} {kind} parameter{} but its trait \
1012 declaration has {} {kind} parameter{}",
1016 pluralize!(impl_count),
1018 pluralize!(trait_count),
1021 DiagnosticId::Error("E0049".into()),
1024 let mut suffix = None;
1026 if let Some(spans) = trait_spans {
1027 let mut spans = spans.iter();
1028 if let Some(span) = spans.next() {
1032 "expected {} {} parameter{}",
1035 pluralize!(trait_count),
1040 err.span_label(*span, "");
1043 suffix = Some(format!(", expected {trait_count}"));
1046 if let Some(span) = span {
1050 "found {} {} parameter{}{}",
1053 pluralize!(impl_count),
1054 suffix.unwrap_or_else(String::new),
1059 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1060 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1063 let reported = err.emit();
1064 err_occurred = Some(reported);
1068 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1071 fn compare_number_of_method_arguments<'tcx>(
1073 impl_m: &ty::AssocItem,
1075 trait_m: &ty::AssocItem,
1076 trait_item_span: Option<Span>,
1077 ) -> Result<(), ErrorGuaranteed> {
1078 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1079 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1080 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
1081 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
1082 if trait_number_args != impl_number_args {
1083 let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
1084 match tcx.hir().expect_trait_item(def_id).kind {
1085 TraitItemKind::Fn(ref trait_m_sig, _) => {
1086 let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
1087 if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
1091 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1097 _ => bug!("{:?} is not a method", impl_m),
1102 let impl_span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
1103 ImplItemKind::Fn(ref impl_m_sig, _) => {
1104 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
1105 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
1109 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1115 _ => bug!("{:?} is not a method", impl_m),
1117 let mut err = struct_span_err!(
1121 "method `{}` has {} but the declaration in trait `{}` has {}",
1123 potentially_plural_count(impl_number_args, "parameter"),
1124 tcx.def_path_str(trait_m.def_id),
1127 if let Some(trait_span) = trait_span {
1131 "trait requires {}",
1132 potentially_plural_count(trait_number_args, "parameter")
1136 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1141 "expected {}, found {}",
1142 potentially_plural_count(trait_number_args, "parameter"),
1146 let reported = err.emit();
1147 return Err(reported);
1153 fn compare_synthetic_generics<'tcx>(
1155 impl_m: &ty::AssocItem,
1156 trait_m: &ty::AssocItem,
1157 ) -> Result<(), ErrorGuaranteed> {
1158 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1159 // 1. Better messages for the span labels
1160 // 2. Explanation as to what is going on
1161 // If we get here, we already have the same number of generics, so the zip will
1163 let mut error_found = None;
1164 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1165 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1166 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
1167 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1168 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1170 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
1171 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1172 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1174 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1175 iter::zip(impl_m_type_params, trait_m_type_params)
1177 if impl_synthetic != trait_synthetic {
1178 let impl_def_id = impl_def_id.expect_local();
1179 let impl_span = tcx.def_span(impl_def_id);
1180 let trait_span = tcx.def_span(trait_def_id);
1181 let mut err = struct_span_err!(
1185 "method `{}` has incompatible signature for trait",
1188 err.span_label(trait_span, "declaration in trait here");
1189 match (impl_synthetic, trait_synthetic) {
1190 // The case where the impl method uses `impl Trait` but the trait method uses
1191 // explicit generics
1193 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1195 // try taking the name from the trait impl
1196 // FIXME: this is obviously suboptimal since the name can already be used
1197 // as another generic argument
1198 let new_name = tcx.opt_item_name(trait_def_id)?;
1199 let trait_m = trait_m.def_id.as_local()?;
1200 let trait_m = tcx.hir().expect_trait_item(trait_m);
1202 let impl_m = impl_m.def_id.as_local()?;
1203 let impl_m = tcx.hir().expect_impl_item(impl_m);
1205 // in case there are no generics, take the spot between the function name
1206 // and the opening paren of the argument list
1207 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1208 // in case there are generics, just replace them
1210 impl_m.generics.span.substitute_dummy(new_generics_span);
1211 // replace with the generics from the trait
1213 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1215 err.multipart_suggestion(
1216 "try changing the `impl Trait` argument to a generic parameter",
1218 // replace `impl Trait` with `T`
1219 (impl_span, new_name.to_string()),
1220 // replace impl method generics with trait method generics
1221 // This isn't quite right, as users might have changed the names
1222 // of the generics, but it works for the common case
1223 (generics_span, new_generics),
1225 Applicability::MaybeIncorrect,
1230 // The case where the trait method uses `impl Trait`, but the impl method uses
1231 // explicit generics.
1233 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1235 let impl_m = impl_m.def_id.as_local()?;
1236 let impl_m = tcx.hir().expect_impl_item(impl_m);
1237 let input_tys = match impl_m.kind {
1238 hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
1239 _ => unreachable!(),
1241 struct Visitor(Option<Span>, hir::def_id::LocalDefId);
1242 impl<'v> intravisit::Visitor<'v> for Visitor {
1243 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
1244 intravisit::walk_ty(self, ty);
1245 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
1247 && let Res::Def(DefKind::TyParam, def_id) = path.res
1248 && def_id == self.1.to_def_id()
1250 self.0 = Some(ty.span);
1254 let mut visitor = Visitor(None, impl_def_id);
1255 for ty in input_tys {
1256 intravisit::Visitor::visit_ty(&mut visitor, ty);
1258 let span = visitor.0?;
1260 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
1261 let bounds = bounds.first()?.span().to(bounds.last()?.span());
1262 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1264 err.multipart_suggestion(
1265 "try removing the generic parameter and using `impl Trait` instead",
1267 // delete generic parameters
1268 (impl_m.generics.span, String::new()),
1269 // replace param usage with `impl Trait`
1270 (span, format!("impl {bounds}")),
1272 Applicability::MaybeIncorrect,
1277 _ => unreachable!(),
1279 let reported = err.emit();
1280 error_found = Some(reported);
1283 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1286 /// Checks that all parameters in the generics of a given assoc item in a trait impl have
1287 /// the same kind as the respective generic parameter in the trait def.
1289 /// For example all 4 errors in the following code are emitted here:
1292 /// fn foo<const N: u8>();
1293 /// type bar<const N: u8>;
1294 /// fn baz<const N: u32>();
1298 /// impl Foo for () {
1299 /// fn foo<const N: u64>() {}
1301 /// type bar<const N: u64> {}
1305 /// type blah<const N: i64> = u32;
1310 /// This function does not handle lifetime parameters
1311 fn compare_generic_param_kinds<'tcx>(
1313 impl_item: &ty::AssocItem,
1314 trait_item: &ty::AssocItem,
1315 ) -> Result<(), ErrorGuaranteed> {
1316 assert_eq!(impl_item.kind, trait_item.kind);
1318 let ty_const_params_of = |def_id| {
1319 tcx.generics_of(def_id).params.iter().filter(|param| {
1322 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1327 for (param_impl, param_trait) in
1328 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1330 use GenericParamDefKind::*;
1331 if match (¶m_impl.kind, ¶m_trait.kind) {
1332 (Const { .. }, Const { .. })
1333 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1337 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1338 // this is exhaustive so that anyone adding new generic param kinds knows
1339 // to make sure this error is reported for them.
1340 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1341 (Lifetime { .. }, _) | (_, Lifetime { .. }) => unreachable!(),
1343 let param_impl_span = tcx.def_span(param_impl.def_id);
1344 let param_trait_span = tcx.def_span(param_trait.def_id);
1346 let mut err = struct_span_err!(
1350 "{} `{}` has an incompatible generic parameter for trait `{}`",
1351 assoc_item_kind_str(&impl_item),
1353 &tcx.def_path_str(tcx.parent(trait_item.def_id))
1356 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1358 format!("{} const parameter of type `{}`", prefix, tcx.type_of(param.def_id))
1360 Type { .. } => format!("{} type parameter", prefix),
1361 Lifetime { .. } => unreachable!(),
1364 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1365 err.span_label(trait_header_span, "");
1366 err.span_label(param_trait_span, make_param_message("expected", param_trait));
1368 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1369 err.span_label(impl_header_span, "");
1370 err.span_label(param_impl_span, make_param_message("found", param_impl));
1372 let reported = err.emit();
1373 return Err(reported);
1380 /// Use `tcx.compare_assoc_const_impl_item_with_trait_item` instead
1381 pub(crate) fn raw_compare_const_impl<'tcx>(
1383 (impl_const_item_def, trait_const_item_def): (LocalDefId, DefId),
1384 ) -> Result<(), ErrorGuaranteed> {
1385 let impl_const_item = tcx.associated_item(impl_const_item_def);
1386 let trait_const_item = tcx.associated_item(trait_const_item_def);
1387 let impl_trait_ref = tcx.impl_trait_ref(impl_const_item.container_id(tcx)).unwrap();
1388 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
1390 let impl_c_span = tcx.def_span(impl_const_item_def.to_def_id());
1392 let infcx = tcx.infer_ctxt().build();
1393 let param_env = tcx.param_env(impl_const_item_def.to_def_id());
1394 let ocx = ObligationCtxt::new(&infcx);
1396 // The below is for the most part highly similar to the procedure
1397 // for methods above. It is simpler in many respects, especially
1398 // because we shouldn't really have to deal with lifetimes or
1399 // predicates. In fact some of this should probably be put into
1400 // shared functions because of DRY violations...
1401 let trait_to_impl_substs = impl_trait_ref.substs;
1403 // Create a parameter environment that represents the implementation's
1405 let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_const_item_def);
1407 // Compute placeholder form of impl and trait const tys.
1408 let impl_ty = tcx.type_of(impl_const_item_def.to_def_id());
1409 let trait_ty = tcx.bound_type_of(trait_const_item_def).subst(tcx, trait_to_impl_substs);
1410 let mut cause = ObligationCause::new(
1413 ObligationCauseCode::CompareImplItemObligation {
1414 impl_item_def_id: impl_const_item_def,
1415 trait_item_def_id: trait_const_item_def,
1416 kind: impl_const_item.kind,
1420 // There is no "body" here, so just pass dummy id.
1421 let impl_ty = ocx.normalize(cause.clone(), param_env, impl_ty);
1423 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1425 let trait_ty = ocx.normalize(cause.clone(), param_env, trait_ty);
1427 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1429 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
1431 if let Err(terr) = err {
1433 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1437 // Locate the Span containing just the type of the offending impl
1438 match tcx.hir().expect_impl_item(impl_const_item_def).kind {
1439 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
1440 _ => bug!("{:?} is not a impl const", impl_const_item),
1443 let mut diag = struct_span_err!(
1447 "implemented const `{}` has an incompatible type for trait",
1448 trait_const_item.name
1451 let trait_c_span = trait_const_item_def.as_local().map(|trait_c_def_id| {
1452 // Add a label to the Span containing just the type of the const
1453 match tcx.hir().expect_trait_item(trait_c_def_id).kind {
1454 TraitItemKind::Const(ref ty, _) => ty.span,
1455 _ => bug!("{:?} is not a trait const", trait_const_item),
1459 infcx.err_ctxt().note_type_err(
1462 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1463 Some(infer::ValuePairs::Terms(ExpectedFound {
1464 expected: trait_ty.into(),
1465 found: impl_ty.into(),
1471 return Err(diag.emit());
1474 // Check that all obligations are satisfied by the implementation's
1476 let errors = ocx.select_all_or_error();
1477 if !errors.is_empty() {
1478 return Err(infcx.err_ctxt().report_fulfillment_errors(&errors, None));
1481 // FIXME return `ErrorReported` if region obligations error?
1482 let outlives_environment = OutlivesEnvironment::new(param_env);
1483 infcx.check_region_obligations_and_report_errors(impl_const_item_def, &outlives_environment);
1487 pub(crate) fn compare_ty_impl<'tcx>(
1489 impl_ty: &ty::AssocItem,
1491 trait_ty: &ty::AssocItem,
1492 impl_trait_ref: ty::TraitRef<'tcx>,
1493 trait_item_span: Option<Span>,
1495 debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1497 let _: Result<(), ErrorGuaranteed> = (|| {
1498 compare_number_of_generics(tcx, impl_ty, impl_ty_span, trait_ty, trait_item_span)?;
1500 compare_generic_param_kinds(tcx, impl_ty, trait_ty)?;
1502 let sp = tcx.def_span(impl_ty.def_id);
1503 compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;
1505 check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1509 /// The equivalent of [compare_predicate_entailment], but for associated types
1510 /// instead of associated functions.
1511 fn compare_type_predicate_entailment<'tcx>(
1513 impl_ty: &ty::AssocItem,
1515 trait_ty: &ty::AssocItem,
1516 impl_trait_ref: ty::TraitRef<'tcx>,
1517 ) -> Result<(), ErrorGuaranteed> {
1518 let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1519 let trait_to_impl_substs =
1520 impl_substs.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.substs);
1522 let impl_ty_generics = tcx.generics_of(impl_ty.def_id);
1523 let trait_ty_generics = tcx.generics_of(trait_ty.def_id);
1524 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1525 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1527 check_region_bounds_on_impl_item(
1535 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1537 if impl_ty_own_bounds.is_empty() {
1538 // Nothing to check.
1542 // This `HirId` should be used for the `body_id` field on each
1543 // `ObligationCause` (and the `FnCtxt`). This is what
1544 // `regionck_item` expects.
1545 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1546 debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1548 // The predicates declared by the impl definition, the trait and the
1549 // associated type in the trait are assumed.
1550 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1551 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1554 .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1556 debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1558 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1559 let param_env = ty::ParamEnv::new(
1560 tcx.intern_predicates(&hybrid_preds.predicates),
1562 hir::Constness::NotConst,
1564 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
1565 let infcx = tcx.infer_ctxt().build();
1566 let ocx = ObligationCtxt::new(&infcx);
1568 debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1570 let mut selcx = traits::SelectionContext::new(&infcx);
1572 assert_eq!(impl_ty_own_bounds.predicates.len(), impl_ty_own_bounds.spans.len());
1573 for (span, predicate) in std::iter::zip(impl_ty_own_bounds.spans, impl_ty_own_bounds.predicates)
1575 let cause = ObligationCause::misc(span, impl_ty_hir_id);
1576 let traits::Normalized { value: predicate, obligations } =
1577 traits::normalize(&mut selcx, param_env, cause, predicate);
1579 let cause = ObligationCause::new(
1582 ObligationCauseCode::CompareImplItemObligation {
1583 impl_item_def_id: impl_ty.def_id.expect_local(),
1584 trait_item_def_id: trait_ty.def_id,
1588 ocx.register_obligations(obligations);
1589 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
1592 // Check that all obligations are satisfied by the implementation's
1594 let errors = ocx.select_all_or_error();
1595 if !errors.is_empty() {
1596 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
1597 return Err(reported);
1600 // Finally, resolve all regions. This catches wily misuses of
1601 // lifetime parameters.
1602 let outlives_environment = OutlivesEnvironment::new(param_env);
1603 infcx.check_region_obligations_and_report_errors(
1604 impl_ty.def_id.expect_local(),
1605 &outlives_environment,
1611 /// Validate that `ProjectionCandidate`s created for this associated type will
1616 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1618 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1619 /// impl is well-formed we have to prove `S: Copy`.
1621 /// For default associated types the normalization is not possible (the value
1622 /// from the impl could be overridden). We also can't normalize generic
1623 /// associated types (yet) because they contain bound parameters.
1624 #[instrument(level = "debug", skip(tcx))]
1625 pub fn check_type_bounds<'tcx>(
1627 trait_ty: &ty::AssocItem,
1628 impl_ty: &ty::AssocItem,
1630 impl_trait_ref: ty::TraitRef<'tcx>,
1631 ) -> Result<(), ErrorGuaranteed> {
1634 // impl<A, B> Foo<u32> for (A, B) {
1638 // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1639 // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1640 // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1641 // the *trait* with the generic associated type parameters (as bound vars).
1643 // A note regarding the use of bound vars here:
1644 // Imagine as an example
1647 // type Member<C: Eq>;
1650 // impl Family for VecFamily {
1651 // type Member<C: Eq> = i32;
1654 // Here, we would generate
1656 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1658 // when we really would like to generate
1660 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1662 // But, this is probably fine, because although the first clause can be used with types C that
1663 // do not implement Eq, for it to cause some kind of problem, there would have to be a
1664 // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1665 // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1666 // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1667 // the trait (notably, that X: Eq and T: Family).
1668 let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1669 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1670 if let Some(def_id) = defs.parent {
1671 let parent_defs = tcx.generics_of(def_id);
1672 InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1673 tcx.mk_param_from_def(param)
1676 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1677 smallvec::SmallVec::with_capacity(defs.count());
1678 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1679 GenericParamDefKind::Type { .. } => {
1680 let kind = ty::BoundTyKind::Param(param.name);
1681 let bound_var = ty::BoundVariableKind::Ty(kind);
1682 bound_vars.push(bound_var);
1683 tcx.mk_ty(ty::Bound(
1685 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1689 GenericParamDefKind::Lifetime => {
1690 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1691 let bound_var = ty::BoundVariableKind::Region(kind);
1692 bound_vars.push(bound_var);
1693 tcx.mk_region(ty::ReLateBound(
1695 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1699 GenericParamDefKind::Const { .. } => {
1700 let bound_var = ty::BoundVariableKind::Const;
1701 bound_vars.push(bound_var);
1703 ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(bound_vars.len() - 1)),
1704 tcx.type_of(param.def_id),
1709 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
1710 let impl_ty_substs = tcx.intern_substs(&substs);
1711 let container_id = impl_ty.container_id(tcx);
1713 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
1714 let impl_ty_value = tcx.type_of(impl_ty.def_id);
1716 let param_env = tcx.param_env(impl_ty.def_id);
1718 // When checking something like
1720 // trait X { type Y: PartialEq<<Self as X>::Y> }
1721 // impl X for T { default type Y = S; }
1723 // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
1724 // we want <T as X>::Y to normalize to S. This is valid because we are
1725 // checking the default value specifically here. Add this equality to the
1726 // ParamEnv for normalization specifically.
1727 let normalize_param_env = {
1728 let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
1729 match impl_ty_value.kind() {
1730 ty::Projection(proj)
1731 if proj.item_def_id == trait_ty.def_id && proj.substs == rebased_substs =>
1733 // Don't include this predicate if the projected type is
1734 // exactly the same as the projection. This can occur in
1735 // (somewhat dubious) code like this:
1737 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
1739 _ => predicates.push(
1740 ty::Binder::bind_with_vars(
1741 ty::ProjectionPredicate {
1742 projection_ty: ty::ProjectionTy {
1743 item_def_id: trait_ty.def_id,
1744 substs: rebased_substs,
1746 term: impl_ty_value.into(),
1754 tcx.intern_predicates(&predicates),
1756 param_env.constness(),
1759 debug!(?normalize_param_env);
1761 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1762 let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1763 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
1765 let infcx = tcx.infer_ctxt().build();
1766 let ocx = ObligationCtxt::new(&infcx);
1768 let assumed_wf_types =
1769 ocx.assumed_wf_types(param_env, impl_ty_span, impl_ty.def_id.expect_local());
1771 let mut selcx = traits::SelectionContext::new(&infcx);
1772 let normalize_cause = ObligationCause::new(
1775 ObligationCauseCode::CheckAssociatedTypeBounds {
1776 impl_item_def_id: impl_ty.def_id.expect_local(),
1777 trait_item_def_id: trait_ty.def_id,
1780 let mk_cause = |span: Span| {
1781 let code = if span.is_dummy() {
1782 traits::ItemObligation(trait_ty.def_id)
1784 traits::BindingObligation(trait_ty.def_id, span)
1786 ObligationCause::new(impl_ty_span, impl_ty_hir_id, code)
1789 let obligations = tcx
1790 .bound_explicit_item_bounds(trait_ty.def_id)
1791 .subst_iter_copied(tcx, rebased_substs)
1792 .map(|(concrete_ty_bound, span)| {
1793 debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
1794 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
1797 debug!("check_type_bounds: item_bounds={:?}", obligations);
1799 for mut obligation in util::elaborate_obligations(tcx, obligations) {
1800 let traits::Normalized { value: normalized_predicate, obligations } = traits::normalize(
1802 normalize_param_env,
1803 normalize_cause.clone(),
1804 obligation.predicate,
1806 debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
1807 obligation.predicate = normalized_predicate;
1809 ocx.register_obligations(obligations);
1810 ocx.register_obligation(obligation);
1812 // Check that all obligations are satisfied by the implementation's
1814 let errors = ocx.select_all_or_error();
1815 if !errors.is_empty() {
1816 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
1817 return Err(reported);
1820 // Finally, resolve all regions. This catches wily misuses of
1821 // lifetime parameters.
1822 let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_hir_id, assumed_wf_types);
1823 let outlives_environment =
1824 OutlivesEnvironment::with_bounds(param_env, Some(&infcx), implied_bounds);
1826 infcx.check_region_obligations_and_report_errors(
1827 impl_ty.def_id.expect_local(),
1828 &outlives_environment,
1831 let constraints = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
1832 for (key, value) in constraints {
1835 .report_mismatched_types(
1836 &ObligationCause::misc(
1837 value.hidden_type.span,
1838 tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local()),
1840 tcx.mk_opaque(key.def_id.to_def_id(), key.substs),
1841 value.hidden_type.ty,
1842 TypeError::Mismatch,
1850 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
1851 match impl_item.kind {
1852 ty::AssocKind::Const => "const",
1853 ty::AssocKind::Fn => "method",
1854 ty::AssocKind::Type => "type",