1 use super::potentially_plural_count;
2 use crate::check::regionck::OutlivesEnvironmentExt;
3 use crate::check::wfcheck;
4 use crate::errors::LifetimesOrBoundsMismatchOnTrait;
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, ErrorGuaranteed};
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::intravisit;
10 use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
11 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
12 use rustc_infer::infer::{self, TyCtxtInferExt};
13 use rustc_infer::traits::util;
14 use rustc_middle::ty::error::{ExpectedFound, TypeError};
15 use rustc_middle::ty::subst::{InternalSubsts, Subst};
16 use rustc_middle::ty::util::ExplicitSelf;
17 use rustc_middle::ty::{self, DefIdTree};
18 use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt};
20 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
21 use rustc_trait_selection::traits::{
22 self, ObligationCause, ObligationCauseCode, ObligationCtxt, Reveal,
26 /// Checks that a method from an impl conforms to the signature of
27 /// the same method as declared in the trait.
31 /// - `impl_m`: type of the method we are checking
32 /// - `impl_m_span`: span to use for reporting errors
33 /// - `trait_m`: the method in the trait
34 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
35 pub(crate) fn compare_impl_method<'tcx>(
37 impl_m: &ty::AssocItem,
38 trait_m: &ty::AssocItem,
39 impl_trait_ref: ty::TraitRef<'tcx>,
40 trait_item_span: Option<Span>,
42 debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
44 let impl_m_span = tcx.def_span(impl_m.def_id);
46 if let Err(_) = compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref) {
50 if let Err(_) = compare_number_of_generics(tcx, impl_m, impl_m_span, trait_m, trait_item_span) {
54 if let Err(_) = compare_generic_param_kinds(tcx, impl_m, trait_m) {
59 compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
64 if let Err(_) = compare_synthetic_generics(tcx, impl_m, trait_m) {
68 if let Err(_) = compare_predicate_entailment(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
74 fn compare_predicate_entailment<'tcx>(
76 impl_m: &ty::AssocItem,
78 trait_m: &ty::AssocItem,
79 impl_trait_ref: ty::TraitRef<'tcx>,
80 ) -> Result<(), ErrorGuaranteed> {
81 let trait_to_impl_substs = impl_trait_ref.substs;
83 // This node-id should be used for the `body_id` field on each
84 // `ObligationCause` (and the `FnCtxt`).
86 // FIXME(@lcnr): remove that after removing `cause.body_id` from
88 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
89 // We sometimes modify the span further down.
90 let mut cause = ObligationCause::new(
93 ObligationCauseCode::CompareImplItemObligation {
94 impl_item_def_id: impl_m.def_id.expect_local(),
95 trait_item_def_id: trait_m.def_id,
100 // This code is best explained by example. Consider a trait:
102 // trait Trait<'t, T> {
103 // fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
108 // impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
109 // fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo;
112 // We wish to decide if those two method types are compatible.
114 // We start out with trait_to_impl_substs, that maps the trait
115 // type parameters to impl type parameters. This is taken from the
116 // impl trait reference:
118 // trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
120 // We create a mapping `dummy_substs` that maps from the impl type
121 // parameters to fresh types and regions. For type parameters,
122 // this is the identity transform, but we could as well use any
123 // placeholder types. For regions, we convert from bound to free
124 // regions (Note: but only early-bound regions, i.e., those
125 // declared on the impl or used in type parameter bounds).
127 // impl_to_placeholder_substs = {'i => 'i0, U => U0, N => N0 }
129 // Now we can apply placeholder_substs to the type of the impl method
130 // to yield a new function type in terms of our fresh, placeholder
133 // <'b> fn(t: &'i0 U0, m: &'b) -> Foo
135 // We now want to extract and substitute the type of the *trait*
136 // method and compare it. To do so, we must create a compound
137 // substitution by combining trait_to_impl_substs and
138 // impl_to_placeholder_substs, and also adding a mapping for the method
139 // type parameters. We extend the mapping to also include
140 // the method parameters.
142 // trait_to_placeholder_substs = { T => &'i0 U0, Self => Foo, M => N0 }
144 // Applying this to the trait method type yields:
146 // <'a> fn(t: &'i0 U0, m: &'a) -> Foo
148 // This type is also the same but the name of the bound region ('a
149 // vs 'b). However, the normal subtyping rules on fn types handle
150 // this kind of equivalency just fine.
152 // We now use these substitutions to ensure that all declared bounds are
153 // satisfied by the implementation's method.
155 // We do this by creating a parameter environment which contains a
156 // substitution corresponding to impl_to_placeholder_substs. We then build
157 // trait_to_placeholder_substs and use it to convert the predicates contained
158 // in the trait_m.generics to the placeholder form.
160 // Finally we register each of these predicates as an obligation in
161 // a fresh FulfillmentCtxt, and invoke select_all_or_error.
163 // Create mapping from impl to placeholder.
164 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
166 // Create mapping from trait to placeholder.
167 let trait_to_placeholder_substs =
168 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
169 debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_substs);
171 let impl_m_generics = tcx.generics_of(impl_m.def_id);
172 let trait_m_generics = tcx.generics_of(trait_m.def_id);
173 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
174 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
176 // Check region bounds.
177 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, &trait_m_generics, &impl_m_generics)?;
179 // Create obligations for each predicate declared by the impl
180 // definition in the context of the trait's parameter
181 // environment. We can't just use `impl_env.caller_bounds`,
182 // however, because we want to replace all late-bound regions with
184 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
185 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
187 debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
189 // This is the only tricky bit of the new way we check implementation methods
190 // We need to build a set of predicates where only the method-level bounds
191 // are from the trait and we assume all other bounds from the implementation
192 // to be previously satisfied.
194 // We then register the obligations from the impl_m and check to see
195 // if all constraints hold.
198 .extend(trait_m_predicates.instantiate_own(tcx, trait_to_placeholder_substs).predicates);
200 // Construct trait parameter environment and then shift it into the placeholder viewpoint.
201 // The key step here is to update the caller_bounds's predicates to be
202 // the new hybrid bounds we computed.
203 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
204 let param_env = ty::ParamEnv::new(
205 tcx.intern_predicates(&hybrid_preds.predicates),
207 hir::Constness::NotConst,
209 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
211 tcx.infer_ctxt().enter(|ref infcx| {
212 let ocx = ObligationCtxt::new(infcx);
214 debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
216 let mut selcx = traits::SelectionContext::new(&infcx);
217 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
218 for (predicate, span) in iter::zip(impl_m_own_bounds.predicates, impl_m_own_bounds.spans) {
219 let normalize_cause = traits::ObligationCause::misc(span, impl_m_hir_id);
220 let traits::Normalized { value: predicate, obligations } =
221 traits::normalize(&mut selcx, param_env, normalize_cause, predicate);
223 ocx.register_obligations(obligations);
224 let cause = ObligationCause::new(
227 ObligationCauseCode::CompareImplItemObligation {
228 impl_item_def_id: impl_m.def_id.expect_local(),
229 trait_item_def_id: trait_m.def_id,
233 ocx.register_obligation(traits::Obligation::new(cause, param_env, predicate));
236 // We now need to check that the signature of the impl method is
237 // compatible with that of the trait method. We do this by
238 // checking that `impl_fty <: trait_fty`.
240 // FIXME. Unfortunately, this doesn't quite work right now because
241 // associated type normalization is not integrated into subtype
242 // checks. For the comparison to be valid, we need to
243 // normalize the associated types in the impl/trait methods
244 // first. However, because function types bind regions, just
245 // calling `normalize_associated_types_in` would have no effect on
246 // any associated types appearing in the fn arguments or return
249 // Compute placeholder form of impl and trait method tys.
252 let mut wf_tys = FxHashSet::default();
254 let impl_sig = infcx.replace_bound_vars_with_fresh_vars(
256 infer::HigherRankedType,
257 tcx.fn_sig(impl_m.def_id),
260 let norm_cause = ObligationCause::misc(impl_m_span, impl_m_hir_id);
261 let impl_sig = ocx.normalize(norm_cause.clone(), param_env, impl_sig);
262 let impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(impl_sig));
263 debug!("compare_impl_method: impl_fty={:?}", impl_fty);
265 let trait_sig = tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs);
266 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
267 let trait_sig = ocx.normalize(norm_cause, param_env, trait_sig);
268 // Add the resulting inputs and output as well-formed.
269 wf_tys.extend(trait_sig.inputs_and_output.iter());
270 let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
272 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
274 // FIXME: We'd want to keep more accurate spans than "the method signature" when
275 // processing the comparison between the trait and impl fn, but we sadly lose them
276 // and point at the whole signature when a trait bound or specific input or output
277 // type would be more appropriate. In other places we have a `Vec<Span>`
278 // corresponding to their `Vec<Predicate>`, but we don't have that here.
279 // Fixing this would improve the output of test `issue-83765.rs`.
280 let sub_result = infcx
281 .at(&cause, param_env)
282 .sup(trait_fty, impl_fty)
283 .map(|infer_ok| ocx.register_infer_ok_obligations(infer_ok));
285 if let Err(terr) = sub_result {
286 debug!("sub_types failed: impl ty {:?}, trait ty {:?}", impl_fty, trait_fty);
288 let (impl_err_span, trait_err_span) =
289 extract_spans_for_error_reporting(&infcx, &terr, &cause, impl_m, trait_m);
291 cause.span = impl_err_span;
293 let mut diag = struct_span_err!(
297 "method `{}` has an incompatible type for trait",
301 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
302 if trait_m.fn_has_self_parameter =>
304 let ty = trait_sig.inputs()[0];
305 let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty())
307 ExplicitSelf::ByValue => "self".to_owned(),
308 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
309 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => {
310 "&mut self".to_owned()
312 _ => format!("self: {ty}"),
315 // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
316 // span points only at the type `Box<Self`>, but we want to cover the whole
317 // argument pattern and type.
318 let span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
319 ImplItemKind::Fn(ref sig, body) => tcx
321 .body_param_names(body)
322 .zip(sig.decl.inputs.iter())
323 .map(|(param, ty)| param.span.to(ty.span))
325 .unwrap_or(impl_err_span),
326 _ => bug!("{:?} is not a method", impl_m),
329 diag.span_suggestion(
331 "change the self-receiver type to match the trait",
333 Applicability::MachineApplicable,
336 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
337 if trait_sig.inputs().len() == *i {
338 // Suggestion to change output type. We do not suggest in `async` functions
339 // to avoid complex logic or incorrect output.
340 match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
341 ImplItemKind::Fn(ref sig, _)
342 if sig.header.asyncness == hir::IsAsync::NotAsync =>
344 let msg = "change the output type to match the trait";
345 let ap = Applicability::MachineApplicable;
346 match sig.decl.output {
347 hir::FnRetTy::DefaultReturn(sp) => {
348 let sugg = format!("-> {} ", trait_sig.output());
349 diag.span_suggestion_verbose(sp, msg, sugg, ap);
351 hir::FnRetTy::Return(hir_ty) => {
352 let sugg = trait_sig.output();
353 diag.span_suggestion(hir_ty.span, msg, sugg, ap);
359 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
360 diag.span_suggestion(
362 "change the parameter type to match the trait",
364 Applicability::MachineApplicable,
374 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
375 Some(infer::ValuePairs::Terms(ExpectedFound {
376 expected: trait_fty.into(),
377 found: impl_fty.into(),
384 return Err(diag.emit());
387 // Check that all obligations are satisfied by the implementation's
389 let errors = ocx.select_all_or_error();
390 if !errors.is_empty() {
391 let reported = infcx.report_fulfillment_errors(&errors, None, false);
392 return Err(reported);
395 // Finally, resolve all regions. This catches wily misuses of
396 // lifetime parameters.
397 let mut outlives_environment = OutlivesEnvironment::new(param_env);
398 outlives_environment.add_implied_bounds(infcx, wf_tys, impl_m_hir_id);
399 infcx.check_region_obligations_and_report_errors(
400 impl_m.def_id.expect_local(),
401 &outlives_environment,
408 fn check_region_bounds_on_impl_item<'tcx>(
410 impl_m: &ty::AssocItem,
411 trait_m: &ty::AssocItem,
412 trait_generics: &ty::Generics,
413 impl_generics: &ty::Generics,
414 ) -> Result<(), ErrorGuaranteed> {
415 let trait_params = trait_generics.own_counts().lifetimes;
416 let impl_params = impl_generics.own_counts().lifetimes;
419 "check_region_bounds_on_impl_item: \
420 trait_generics={:?} \
422 trait_generics, impl_generics
425 // Must have same number of early-bound lifetime parameters.
426 // Unfortunately, if the user screws up the bounds, then this
427 // will change classification between early and late. E.g.,
428 // if in trait we have `<'a,'b:'a>`, and in impl we just have
429 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
430 // in trait but 0 in the impl. But if we report "expected 2
431 // but found 0" it's confusing, because it looks like there
432 // are zero. Since I don't quite know how to phrase things at
433 // the moment, give a kind of vague error message.
434 if trait_params != impl_params {
437 .get_generics(impl_m.def_id.expect_local())
438 .expect("expected impl item to have generics or else we can't compare them")
440 let generics_span = if let Some(local_def_id) = trait_m.def_id.as_local() {
443 .get_generics(local_def_id)
444 .expect("expected trait item to have generics or else we can't compare them")
451 let reported = tcx.sess.emit_err(LifetimesOrBoundsMismatchOnTrait {
453 item_kind: assoc_item_kind_str(impl_m),
454 ident: impl_m.ident(tcx),
457 return Err(reported);
463 #[instrument(level = "debug", skip(infcx))]
464 fn extract_spans_for_error_reporting<'a, 'tcx>(
465 infcx: &infer::InferCtxt<'a, 'tcx>,
466 terr: &TypeError<'_>,
467 cause: &ObligationCause<'tcx>,
468 impl_m: &ty::AssocItem,
469 trait_m: &ty::AssocItem,
470 ) -> (Span, Option<Span>) {
472 let mut impl_args = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
473 ImplItemKind::Fn(ref sig, _) => {
474 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
476 _ => bug!("{:?} is not a method", impl_m),
479 trait_m.def_id.as_local().map(|def_id| match tcx.hir().expect_trait_item(def_id).kind {
480 TraitItemKind::Fn(ref sig, _) => {
481 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
483 _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
487 TypeError::ArgumentMutability(i) => {
488 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
490 TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
491 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
493 _ => (cause.span(), tcx.hir().span_if_local(trait_m.def_id)),
497 fn compare_self_type<'tcx>(
499 impl_m: &ty::AssocItem,
501 trait_m: &ty::AssocItem,
502 impl_trait_ref: ty::TraitRef<'tcx>,
503 ) -> Result<(), ErrorGuaranteed> {
504 // Try to give more informative error messages about self typing
505 // mismatches. Note that any mismatch will also be detected
506 // below, where we construct a canonical function type that
507 // includes the self parameter as a normal parameter. It's just
508 // that the error messages you get out of this code are a bit more
509 // inscrutable, particularly for cases where one method has no
512 let self_string = |method: &ty::AssocItem| {
513 let untransformed_self_ty = match method.container {
514 ty::ImplContainer => impl_trait_ref.self_ty(),
515 ty::TraitContainer => tcx.types.self_param,
517 let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
518 let param_env = ty::ParamEnv::reveal_all();
520 tcx.infer_ctxt().enter(|infcx| {
521 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
522 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
523 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
524 ExplicitSelf::ByValue => "self".to_owned(),
525 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
526 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
527 _ => format!("self: {self_arg_ty}"),
532 match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
533 (false, false) | (true, true) => {}
536 let self_descr = self_string(impl_m);
537 let mut err = struct_span_err!(
541 "method `{}` has a `{}` declaration in the impl, but not in the trait",
545 err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
546 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
547 err.span_label(span, format!("trait method declared without `{self_descr}`"));
549 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
551 let reported = err.emit();
552 return Err(reported);
556 let self_descr = self_string(trait_m);
557 let mut err = struct_span_err!(
561 "method `{}` has a `{}` declaration in the trait, but not in the impl",
565 err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
566 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
567 err.span_label(span, format!("`{self_descr}` used in trait"));
569 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
571 let reported = err.emit();
572 return Err(reported);
579 /// Checks that the number of generics on a given assoc item in a trait impl is the same
580 /// as the number of generics on the respective assoc item in the trait definition.
582 /// For example this code emits the errors in the following code:
589 /// impl Trait for () {
592 /// type Assoc = u32;
597 /// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
598 /// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
599 /// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
600 fn compare_number_of_generics<'tcx>(
602 impl_: &ty::AssocItem,
604 trait_: &ty::AssocItem,
605 trait_span: Option<Span>,
606 ) -> Result<(), ErrorGuaranteed> {
607 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
608 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
610 // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
611 // in `compare_generic_param_kinds` which will give a nicer error message than something like:
612 // "expected 1 type parameter, found 0 type parameters"
613 if (trait_own_counts.types + trait_own_counts.consts)
614 == (impl_own_counts.types + impl_own_counts.consts)
620 ("type", trait_own_counts.types, impl_own_counts.types),
621 ("const", trait_own_counts.consts, impl_own_counts.consts),
624 let item_kind = assoc_item_kind_str(impl_);
626 let mut err_occurred = None;
627 for (kind, trait_count, impl_count) in matchings {
628 if impl_count != trait_count {
629 let arg_spans = |kind: ty::AssocKind, generics: &hir::Generics<'_>| {
630 let mut spans = generics
633 .filter(|p| match p.kind {
634 hir::GenericParamKind::Lifetime {
635 kind: hir::LifetimeParamKind::Elided,
637 // A fn can have an arbitrary number of extra elided lifetimes for the
639 !matches!(kind, ty::AssocKind::Fn)
644 .collect::<Vec<Span>>();
645 if spans.is_empty() {
646 spans = vec![generics.span]
650 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
651 let trait_item = tcx.hir().expect_trait_item(def_id);
652 let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
653 let impl_trait_spans: Vec<Span> = trait_item
657 .filter_map(|p| match p.kind {
658 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
662 (Some(arg_spans), impl_trait_spans)
664 (trait_span.map(|s| vec![s]), vec![])
667 let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
668 let impl_item_impl_trait_spans: Vec<Span> = impl_item
672 .filter_map(|p| match p.kind {
673 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
677 let spans = arg_spans(impl_.kind, impl_item.generics);
678 let span = spans.first().copied();
680 let mut err = tcx.sess.struct_span_err_with_code(
683 "{} `{}` has {} {kind} parameter{} but its trait \
684 declaration has {} {kind} parameter{}",
688 pluralize!(impl_count),
690 pluralize!(trait_count),
693 DiagnosticId::Error("E0049".into()),
696 let mut suffix = None;
698 if let Some(spans) = trait_spans {
699 let mut spans = spans.iter();
700 if let Some(span) = spans.next() {
704 "expected {} {} parameter{}",
707 pluralize!(trait_count),
712 err.span_label(*span, "");
715 suffix = Some(format!(", expected {trait_count}"));
718 if let Some(span) = span {
722 "found {} {} parameter{}{}",
725 pluralize!(impl_count),
726 suffix.unwrap_or_else(String::new),
731 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
732 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
735 let reported = err.emit();
736 err_occurred = Some(reported);
740 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
743 fn compare_number_of_method_arguments<'tcx>(
745 impl_m: &ty::AssocItem,
747 trait_m: &ty::AssocItem,
748 trait_item_span: Option<Span>,
749 ) -> Result<(), ErrorGuaranteed> {
750 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
751 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
752 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
753 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
754 if trait_number_args != impl_number_args {
755 let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
756 match tcx.hir().expect_trait_item(def_id).kind {
757 TraitItemKind::Fn(ref trait_m_sig, _) => {
758 let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
759 if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
763 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
769 _ => bug!("{:?} is not a method", impl_m),
774 let impl_span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
775 ImplItemKind::Fn(ref impl_m_sig, _) => {
776 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
777 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
781 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
787 _ => bug!("{:?} is not a method", impl_m),
789 let mut err = struct_span_err!(
793 "method `{}` has {} but the declaration in trait `{}` has {}",
795 potentially_plural_count(impl_number_args, "parameter"),
796 tcx.def_path_str(trait_m.def_id),
799 if let Some(trait_span) = trait_span {
804 potentially_plural_count(trait_number_args, "parameter")
808 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
813 "expected {}, found {}",
814 potentially_plural_count(trait_number_args, "parameter"),
818 let reported = err.emit();
819 return Err(reported);
825 fn compare_synthetic_generics<'tcx>(
827 impl_m: &ty::AssocItem,
828 trait_m: &ty::AssocItem,
829 ) -> Result<(), ErrorGuaranteed> {
830 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
831 // 1. Better messages for the span labels
832 // 2. Explanation as to what is going on
833 // If we get here, we already have the same number of generics, so the zip will
835 let mut error_found = None;
836 let impl_m_generics = tcx.generics_of(impl_m.def_id);
837 let trait_m_generics = tcx.generics_of(trait_m.def_id);
838 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
839 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
840 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
842 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
843 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
844 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
846 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
847 iter::zip(impl_m_type_params, trait_m_type_params)
849 if impl_synthetic != trait_synthetic {
850 let impl_def_id = impl_def_id.expect_local();
851 let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_def_id);
852 let impl_span = tcx.hir().span(impl_hir_id);
853 let trait_span = tcx.def_span(trait_def_id);
854 let mut err = struct_span_err!(
858 "method `{}` has incompatible signature for trait",
861 err.span_label(trait_span, "declaration in trait here");
862 match (impl_synthetic, trait_synthetic) {
863 // The case where the impl method uses `impl Trait` but the trait method uses
866 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
868 // try taking the name from the trait impl
869 // FIXME: this is obviously suboptimal since the name can already be used
870 // as another generic argument
871 let new_name = tcx.sess.source_map().span_to_snippet(trait_span).ok()?;
872 let trait_m = trait_m.def_id.as_local()?;
873 let trait_m = tcx.hir().trait_item(hir::TraitItemId { def_id: trait_m });
875 let impl_m = impl_m.def_id.as_local()?;
876 let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
878 // in case there are no generics, take the spot between the function name
879 // and the opening paren of the argument list
880 let new_generics_span =
881 tcx.sess.source_map().generate_fn_name_span(impl_span)?.shrink_to_hi();
882 // in case there are generics, just replace them
884 impl_m.generics.span.substitute_dummy(new_generics_span);
885 // replace with the generics from the trait
887 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
889 err.multipart_suggestion(
890 "try changing the `impl Trait` argument to a generic parameter",
892 // replace `impl Trait` with `T`
893 (impl_span, new_name),
894 // replace impl method generics with trait method generics
895 // This isn't quite right, as users might have changed the names
896 // of the generics, but it works for the common case
897 (generics_span, new_generics),
899 Applicability::MaybeIncorrect,
904 // The case where the trait method uses `impl Trait`, but the impl method uses
905 // explicit generics.
907 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
909 let impl_m = impl_m.def_id.as_local()?;
910 let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
911 let input_tys = match impl_m.kind {
912 hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
915 struct Visitor(Option<Span>, hir::def_id::LocalDefId);
916 impl<'v> intravisit::Visitor<'v> for Visitor {
917 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
918 intravisit::walk_ty(self, ty);
919 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
921 && let Res::Def(DefKind::TyParam, def_id) = path.res
922 && def_id == self.1.to_def_id()
924 self.0 = Some(ty.span);
928 let mut visitor = Visitor(None, impl_def_id);
929 for ty in input_tys {
930 intravisit::Visitor::visit_ty(&mut visitor, ty);
932 let span = visitor.0?;
934 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
935 let bounds = bounds.first()?.span().to(bounds.last()?.span());
936 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
938 err.multipart_suggestion(
939 "try removing the generic parameter and using `impl Trait` instead",
941 // delete generic parameters
942 (impl_m.generics.span, String::new()),
943 // replace param usage with `impl Trait`
944 (span, format!("impl {bounds}")),
946 Applicability::MaybeIncorrect,
953 let reported = err.emit();
954 error_found = Some(reported);
957 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
960 /// Checks that all parameters in the generics of a given assoc item in a trait impl have
961 /// the same kind as the respective generic parameter in the trait def.
963 /// For example all 4 errors in the following code are emitted here:
966 /// fn foo<const N: u8>();
967 /// type bar<const N: u8>;
968 /// fn baz<const N: u32>();
972 /// impl Foo for () {
973 /// fn foo<const N: u64>() {}
975 /// type bar<const N: u64> {}
979 /// type blah<const N: i64> = u32;
984 /// This function does not handle lifetime parameters
985 fn compare_generic_param_kinds<'tcx>(
987 impl_item: &ty::AssocItem,
988 trait_item: &ty::AssocItem,
989 ) -> Result<(), ErrorGuaranteed> {
990 assert_eq!(impl_item.kind, trait_item.kind);
992 let ty_const_params_of = |def_id| {
993 tcx.generics_of(def_id).params.iter().filter(|param| {
996 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1001 for (param_impl, param_trait) in
1002 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1004 use GenericParamDefKind::*;
1005 if match (¶m_impl.kind, ¶m_trait.kind) {
1006 (Const { .. }, Const { .. })
1007 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1011 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1012 // this is exhaustive so that anyone adding new generic param kinds knows
1013 // to make sure this error is reported for them.
1014 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1015 (Lifetime { .. }, _) | (_, Lifetime { .. }) => unreachable!(),
1017 let param_impl_span = tcx.def_span(param_impl.def_id);
1018 let param_trait_span = tcx.def_span(param_trait.def_id);
1020 let mut err = struct_span_err!(
1024 "{} `{}` has an incompatible generic parameter for trait `{}`",
1025 assoc_item_kind_str(&impl_item),
1027 &tcx.def_path_str(tcx.parent(trait_item.def_id))
1030 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1032 format!("{} const parameter of type `{}`", prefix, tcx.type_of(param.def_id))
1034 Type { .. } => format!("{} type parameter", prefix),
1035 Lifetime { .. } => unreachable!(),
1038 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1039 err.span_label(trait_header_span, "");
1040 err.span_label(param_trait_span, make_param_message("expected", param_trait));
1042 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1043 err.span_label(impl_header_span, "");
1044 err.span_label(param_impl_span, make_param_message("found", param_impl));
1046 let reported = err.emit();
1047 return Err(reported);
1054 pub(crate) fn compare_const_impl<'tcx>(
1056 impl_c: &ty::AssocItem,
1058 trait_c: &ty::AssocItem,
1059 impl_trait_ref: ty::TraitRef<'tcx>,
1061 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
1063 tcx.infer_ctxt().enter(|infcx| {
1064 let param_env = tcx.param_env(impl_c.def_id);
1065 let ocx = ObligationCtxt::new(&infcx);
1067 // The below is for the most part highly similar to the procedure
1068 // for methods above. It is simpler in many respects, especially
1069 // because we shouldn't really have to deal with lifetimes or
1070 // predicates. In fact some of this should probably be put into
1071 // shared functions because of DRY violations...
1072 let trait_to_impl_substs = impl_trait_ref.substs;
1074 // Create a parameter environment that represents the implementation's
1076 let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_c.def_id.expect_local());
1078 // Compute placeholder form of impl and trait const tys.
1079 let impl_ty = tcx.type_of(impl_c.def_id);
1080 let trait_ty = tcx.bound_type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
1081 let mut cause = ObligationCause::new(
1084 ObligationCauseCode::CompareImplItemObligation {
1085 impl_item_def_id: impl_c.def_id.expect_local(),
1086 trait_item_def_id: trait_c.def_id,
1091 // There is no "body" here, so just pass dummy id.
1092 let impl_ty = ocx.normalize(cause.clone(), param_env, impl_ty);
1094 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1096 let trait_ty = ocx.normalize(cause.clone(), param_env, trait_ty);
1098 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1101 .at(&cause, param_env)
1102 .sup(trait_ty, impl_ty)
1103 .map(|ok| ocx.register_infer_ok_obligations(ok));
1105 if let Err(terr) = err {
1107 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1111 // Locate the Span containing just the type of the offending impl
1112 match tcx.hir().expect_impl_item(impl_c.def_id.expect_local()).kind {
1113 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
1114 _ => bug!("{:?} is not a impl const", impl_c),
1117 let mut diag = struct_span_err!(
1121 "implemented const `{}` has an incompatible type for trait",
1125 let trait_c_span = trait_c.def_id.as_local().map(|trait_c_def_id| {
1126 // Add a label to the Span containing just the type of the const
1127 match tcx.hir().expect_trait_item(trait_c_def_id).kind {
1128 TraitItemKind::Const(ref ty, _) => ty.span,
1129 _ => bug!("{:?} is not a trait const", trait_c),
1133 infcx.note_type_err(
1136 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1137 Some(infer::ValuePairs::Terms(ExpectedFound {
1138 expected: trait_ty.into(),
1139 found: impl_ty.into(),
1148 // Check that all obligations are satisfied by the implementation's
1150 let errors = ocx.select_all_or_error();
1151 if !errors.is_empty() {
1152 infcx.report_fulfillment_errors(&errors, None, false);
1156 let outlives_environment = OutlivesEnvironment::new(param_env);
1157 infcx.check_region_obligations_and_report_errors(
1158 impl_c.def_id.expect_local(),
1159 &outlives_environment,
1164 pub(crate) fn compare_ty_impl<'tcx>(
1166 impl_ty: &ty::AssocItem,
1168 trait_ty: &ty::AssocItem,
1169 impl_trait_ref: ty::TraitRef<'tcx>,
1170 trait_item_span: Option<Span>,
1172 debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1174 let _: Result<(), ErrorGuaranteed> = (|| {
1175 compare_number_of_generics(tcx, impl_ty, impl_ty_span, trait_ty, trait_item_span)?;
1177 compare_generic_param_kinds(tcx, impl_ty, trait_ty)?;
1179 let sp = tcx.def_span(impl_ty.def_id);
1180 compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;
1182 check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1186 /// The equivalent of [compare_predicate_entailment], but for associated types
1187 /// instead of associated functions.
1188 fn compare_type_predicate_entailment<'tcx>(
1190 impl_ty: &ty::AssocItem,
1192 trait_ty: &ty::AssocItem,
1193 impl_trait_ref: ty::TraitRef<'tcx>,
1194 ) -> Result<(), ErrorGuaranteed> {
1195 let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1196 let trait_to_impl_substs =
1197 impl_substs.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.substs);
1199 let impl_ty_generics = tcx.generics_of(impl_ty.def_id);
1200 let trait_ty_generics = tcx.generics_of(trait_ty.def_id);
1201 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1202 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1204 check_region_bounds_on_impl_item(
1212 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1214 if impl_ty_own_bounds.is_empty() {
1215 // Nothing to check.
1219 // This `HirId` should be used for the `body_id` field on each
1220 // `ObligationCause` (and the `FnCtxt`). This is what
1221 // `regionck_item` expects.
1222 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1223 debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1225 // The predicates declared by the impl definition, the trait and the
1226 // associated type in the trait are assumed.
1227 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1228 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1231 .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1233 debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1235 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1236 let param_env = ty::ParamEnv::new(
1237 tcx.intern_predicates(&hybrid_preds.predicates),
1239 hir::Constness::NotConst,
1241 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
1242 tcx.infer_ctxt().enter(|infcx| {
1243 let ocx = ObligationCtxt::new(&infcx);
1245 debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1247 let mut selcx = traits::SelectionContext::new(&infcx);
1249 assert_eq!(impl_ty_own_bounds.predicates.len(), impl_ty_own_bounds.spans.len());
1250 for (span, predicate) in
1251 std::iter::zip(impl_ty_own_bounds.spans, impl_ty_own_bounds.predicates)
1253 let cause = ObligationCause::misc(span, impl_ty_hir_id);
1254 let traits::Normalized { value: predicate, obligations } =
1255 traits::normalize(&mut selcx, param_env, cause, predicate);
1257 let cause = ObligationCause::new(
1260 ObligationCauseCode::CompareImplItemObligation {
1261 impl_item_def_id: impl_ty.def_id.expect_local(),
1262 trait_item_def_id: trait_ty.def_id,
1266 ocx.register_obligations(obligations);
1267 ocx.register_obligation(traits::Obligation::new(cause, param_env, predicate));
1270 // Check that all obligations are satisfied by the implementation's
1272 let errors = ocx.select_all_or_error();
1273 if !errors.is_empty() {
1274 let reported = infcx.report_fulfillment_errors(&errors, None, false);
1275 return Err(reported);
1278 // Finally, resolve all regions. This catches wily misuses of
1279 // lifetime parameters.
1280 let outlives_environment = OutlivesEnvironment::new(param_env);
1281 infcx.check_region_obligations_and_report_errors(
1282 impl_ty.def_id.expect_local(),
1283 &outlives_environment,
1290 /// Validate that `ProjectionCandidate`s created for this associated type will
1295 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1297 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1298 /// impl is well-formed we have to prove `S: Copy`.
1300 /// For default associated types the normalization is not possible (the value
1301 /// from the impl could be overridden). We also can't normalize generic
1302 /// associated types (yet) because they contain bound parameters.
1303 #[tracing::instrument(level = "debug", skip(tcx))]
1304 pub fn check_type_bounds<'tcx>(
1306 trait_ty: &ty::AssocItem,
1307 impl_ty: &ty::AssocItem,
1309 impl_trait_ref: ty::TraitRef<'tcx>,
1310 ) -> Result<(), ErrorGuaranteed> {
1313 // impl<A, B> Foo<u32> for (A, B) {
1317 // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1318 // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1319 // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1320 // the *trait* with the generic associated type parameters (as bound vars).
1322 // A note regarding the use of bound vars here:
1323 // Imagine as an example
1326 // type Member<C: Eq>;
1329 // impl Family for VecFamily {
1330 // type Member<C: Eq> = i32;
1333 // Here, we would generate
1335 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1337 // when we really would like to generate
1339 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1341 // But, this is probably fine, because although the first clause can be used with types C that
1342 // do not implement Eq, for it to cause some kind of problem, there would have to be a
1343 // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1344 // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1345 // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1346 // the trait (notably, that X: Eq and T: Family).
1347 let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1348 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1349 if let Some(def_id) = defs.parent {
1350 let parent_defs = tcx.generics_of(def_id);
1351 InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1352 tcx.mk_param_from_def(param)
1355 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1356 smallvec::SmallVec::with_capacity(defs.count());
1357 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1358 GenericParamDefKind::Type { .. } => {
1359 let kind = ty::BoundTyKind::Param(param.name);
1360 let bound_var = ty::BoundVariableKind::Ty(kind);
1361 bound_vars.push(bound_var);
1362 tcx.mk_ty(ty::Bound(
1364 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1368 GenericParamDefKind::Lifetime => {
1369 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1370 let bound_var = ty::BoundVariableKind::Region(kind);
1371 bound_vars.push(bound_var);
1372 tcx.mk_region(ty::ReLateBound(
1374 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1378 GenericParamDefKind::Const { .. } => {
1379 let bound_var = ty::BoundVariableKind::Const;
1380 bound_vars.push(bound_var);
1381 tcx.mk_const(ty::ConstS {
1382 ty: tcx.type_of(param.def_id),
1383 kind: ty::ConstKind::Bound(
1385 ty::BoundVar::from_usize(bound_vars.len() - 1),
1391 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
1392 let impl_ty_substs = tcx.intern_substs(&substs);
1393 let container_id = impl_ty.container_id(tcx);
1395 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
1396 let impl_ty_value = tcx.type_of(impl_ty.def_id);
1398 let param_env = tcx.param_env(impl_ty.def_id);
1400 // When checking something like
1402 // trait X { type Y: PartialEq<<Self as X>::Y> }
1403 // impl X for T { default type Y = S; }
1405 // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
1406 // we want <T as X>::Y to normalize to S. This is valid because we are
1407 // checking the default value specifically here. Add this equality to the
1408 // ParamEnv for normalization specifically.
1409 let normalize_param_env = {
1410 let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
1411 match impl_ty_value.kind() {
1412 ty::Projection(proj)
1413 if proj.item_def_id == trait_ty.def_id && proj.substs == rebased_substs =>
1415 // Don't include this predicate if the projected type is
1416 // exactly the same as the projection. This can occur in
1417 // (somewhat dubious) code like this:
1419 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
1421 _ => predicates.push(
1422 ty::Binder::bind_with_vars(
1423 ty::ProjectionPredicate {
1424 projection_ty: ty::ProjectionTy {
1425 item_def_id: trait_ty.def_id,
1426 substs: rebased_substs,
1428 term: impl_ty_value.into(),
1436 tcx.intern_predicates(&predicates),
1438 param_env.constness(),
1441 debug!(?normalize_param_env);
1443 let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1444 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
1446 tcx.infer_ctxt().enter(move |infcx| {
1447 let ocx = ObligationCtxt::new(&infcx);
1449 let mut selcx = traits::SelectionContext::new(&infcx);
1450 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1451 let normalize_cause = ObligationCause::new(
1454 ObligationCauseCode::CheckAssociatedTypeBounds {
1455 impl_item_def_id: impl_ty.def_id.expect_local(),
1456 trait_item_def_id: trait_ty.def_id,
1459 let mk_cause = |span: Span| {
1460 let code = if span.is_dummy() {
1461 traits::MiscObligation
1463 traits::BindingObligation(trait_ty.def_id, span)
1465 ObligationCause::new(impl_ty_span, impl_ty_hir_id, code)
1468 let obligations = tcx
1469 .bound_explicit_item_bounds(trait_ty.def_id)
1471 .map(|e| e.map_bound(|e| *e).transpose_tuple2())
1472 .map(|(bound, span)| {
1474 // this is where opaque type is found
1475 let concrete_ty_bound = bound.subst(tcx, rebased_substs);
1476 debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
1478 traits::Obligation::new(mk_cause(span.0), param_env, concrete_ty_bound)
1481 debug!("check_type_bounds: item_bounds={:?}", obligations);
1483 for mut obligation in util::elaborate_obligations(tcx, obligations) {
1484 let traits::Normalized { value: normalized_predicate, obligations } = traits::normalize(
1486 normalize_param_env,
1487 normalize_cause.clone(),
1488 obligation.predicate,
1490 debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
1491 obligation.predicate = normalized_predicate;
1493 ocx.register_obligations(obligations);
1494 ocx.register_obligation(obligation);
1496 // Check that all obligations are satisfied by the implementation's
1498 let errors = ocx.select_all_or_error();
1499 if !errors.is_empty() {
1500 let reported = infcx.report_fulfillment_errors(&errors, None, false);
1501 return Err(reported);
1504 // Finally, resolve all regions. This catches wily misuses of
1505 // lifetime parameters.
1506 let implied_bounds = match impl_ty.container {
1507 ty::TraitContainer => FxHashSet::default(),
1508 ty::ImplContainer => wfcheck::impl_implied_bounds(
1511 container_id.expect_local(),
1515 let mut outlives_environment = OutlivesEnvironment::new(param_env);
1516 outlives_environment.add_implied_bounds(&infcx, implied_bounds, impl_ty_hir_id);
1517 infcx.check_region_obligations_and_report_errors(
1518 impl_ty.def_id.expect_local(),
1519 &outlives_environment,
1522 let constraints = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
1523 for (key, value) in constraints {
1525 .report_mismatched_types(
1526 &ObligationCause::misc(
1527 value.hidden_type.span,
1528 tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local()),
1530 tcx.mk_opaque(key.def_id.to_def_id(), key.substs),
1531 value.hidden_type.ty,
1532 TypeError::Mismatch,
1541 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
1542 match impl_item.kind {
1543 ty::AssocKind::Const => "const",
1544 ty::AssocKind::Fn => "method",
1545 ty::AssocKind::Type => "type",