1 use crate::errors::LifetimesOrBoundsMismatchOnTrait;
2 use rustc_data_structures::stable_set::FxHashSet;
3 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, ErrorReported};
5 use rustc_hir::def::{DefKind, Res};
6 use rustc_hir::intravisit;
7 use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
8 use rustc_infer::infer::{self, InferOk, TyCtxtInferExt};
9 use rustc_infer::traits::util;
11 use rustc_middle::ty::error::{ExpectedFound, TypeError};
12 use rustc_middle::ty::subst::{InternalSubsts, Subst};
13 use rustc_middle::ty::util::ExplicitSelf;
14 use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt};
16 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
17 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
20 use super::{potentially_plural_count, FnCtxt, Inherited};
22 /// Checks that a method from an impl conforms to the signature of
23 /// the same method as declared in the trait.
27 /// - `impl_m`: type of the method we are checking
28 /// - `impl_m_span`: span to use for reporting errors
29 /// - `trait_m`: the method in the trait
30 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
32 crate fn compare_impl_method<'tcx>(
34 impl_m: &ty::AssocItem,
36 trait_m: &ty::AssocItem,
37 impl_trait_ref: ty::TraitRef<'tcx>,
38 trait_item_span: Option<Span>,
40 debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
42 let impl_m_span = tcx.sess.source_map().guess_head_span(impl_m_span);
44 if let Err(ErrorReported) = compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
49 if let Err(ErrorReported) =
50 compare_number_of_generics(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
55 if let Err(ErrorReported) =
56 compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
61 if let Err(ErrorReported) = compare_synthetic_generics(tcx, impl_m, trait_m) {
65 if let Err(ErrorReported) =
66 compare_predicate_entailment(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
71 if let Err(ErrorReported) = compare_const_param_types(tcx, impl_m, trait_m, trait_item_span) {
76 fn compare_predicate_entailment<'tcx>(
78 impl_m: &ty::AssocItem,
80 trait_m: &ty::AssocItem,
81 impl_trait_ref: ty::TraitRef<'tcx>,
82 ) -> Result<(), ErrorReported> {
83 let trait_to_impl_substs = impl_trait_ref.substs;
85 // This node-id should be used for the `body_id` field on each
86 // `ObligationCause` (and the `FnCtxt`). This is what
87 // `regionck_item` expects.
88 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
90 // We sometimes modify the span further down.
91 let mut cause = ObligationCause::new(
94 ObligationCauseCode::CompareImplMethodObligation {
95 item_name: impl_m.ident.name,
96 impl_item_def_id: impl_m.def_id,
97 trait_item_def_id: trait_m.def_id,
101 // This code is best explained by example. Consider a trait:
103 // trait Trait<'t, T> {
104 // fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
109 // impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
110 // fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo;
113 // We wish to decide if those two method types are compatible.
115 // We start out with trait_to_impl_substs, that maps the trait
116 // type parameters to impl type parameters. This is taken from the
117 // impl trait reference:
119 // trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
121 // We create a mapping `dummy_substs` that maps from the impl type
122 // parameters to fresh types and regions. For type parameters,
123 // this is the identity transform, but we could as well use any
124 // placeholder types. For regions, we convert from bound to free
125 // regions (Note: but only early-bound regions, i.e., those
126 // declared on the impl or used in type parameter bounds).
128 // impl_to_placeholder_substs = {'i => 'i0, U => U0, N => N0 }
130 // Now we can apply placeholder_substs to the type of the impl method
131 // to yield a new function type in terms of our fresh, placeholder
134 // <'b> fn(t: &'i0 U0, m: &'b) -> Foo
136 // We now want to extract and substitute the type of the *trait*
137 // method and compare it. To do so, we must create a compound
138 // substitution by combining trait_to_impl_substs and
139 // impl_to_placeholder_substs, and also adding a mapping for the method
140 // type parameters. We extend the mapping to also include
141 // the method parameters.
143 // trait_to_placeholder_substs = { T => &'i0 U0, Self => Foo, M => N0 }
145 // Applying this to the trait method type yields:
147 // <'a> fn(t: &'i0 U0, m: &'a) -> Foo
149 // This type is also the same but the name of the bound region ('a
150 // vs 'b). However, the normal subtyping rules on fn types handle
151 // this kind of equivalency just fine.
153 // We now use these substitutions to ensure that all declared bounds are
154 // satisfied by the implementation's method.
156 // We do this by creating a parameter environment which contains a
157 // substitution corresponding to impl_to_placeholder_substs. We then build
158 // trait_to_placeholder_substs and use it to convert the predicates contained
159 // in the trait_m.generics to the placeholder form.
161 // Finally we register each of these predicates as an obligation in
162 // a fresh FulfillmentCtxt, and invoke select_all_or_error.
164 // Create mapping from impl to placeholder.
165 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
167 // Create mapping from trait to placeholder.
168 let trait_to_placeholder_substs =
169 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container.id(), trait_to_impl_substs);
170 debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_substs);
172 let impl_m_generics = tcx.generics_of(impl_m.def_id);
173 let trait_m_generics = tcx.generics_of(trait_m.def_id);
174 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
175 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
177 // Check region bounds.
178 check_region_bounds_on_impl_item(
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);
213 ty::ParamEnv::new(tcx.intern_predicates(&hybrid_preds.predicates), Reveal::UserFacing);
214 let param_env = traits::normalize_param_env_or_error(
218 normalize_cause.clone(),
221 tcx.infer_ctxt().enter(|infcx| {
222 let inh = Inherited::new(infcx, impl_m.def_id.expect_local());
223 let infcx = &inh.infcx;
225 debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
227 let mut selcx = traits::SelectionContext::new(&infcx);
229 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
230 for predicate in impl_m_own_bounds.predicates {
231 let traits::Normalized { value: predicate, obligations } =
232 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), predicate);
234 inh.register_predicates(obligations);
235 inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
238 // We now need to check that the signature of the impl method is
239 // compatible with that of the trait method. We do this by
240 // checking that `impl_fty <: trait_fty`.
242 // FIXME. Unfortunately, this doesn't quite work right now because
243 // associated type normalization is not integrated into subtype
244 // checks. For the comparison to be valid, we need to
245 // normalize the associated types in the impl/trait methods
246 // first. However, because function types bind regions, just
247 // calling `normalize_associated_types_in` would have no effect on
248 // any associated types appearing in the fn arguments or return
251 // Compute placeholder form of impl and trait method tys.
254 let mut wf_tys = FxHashSet::default();
256 let (impl_sig, _) = infcx.replace_bound_vars_with_fresh_vars(
258 infer::HigherRankedType,
259 tcx.fn_sig(impl_m.def_id),
262 inh.normalize_associated_types_in(impl_m_span, impl_m_hir_id, param_env, impl_sig);
263 let impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(impl_sig));
264 debug!("compare_impl_method: impl_fty={:?}", impl_fty);
266 // First liberate late bound regions and subst placeholders
267 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, tcx.fn_sig(trait_m.def_id));
268 let trait_sig = trait_sig.subst(tcx, trait_to_placeholder_substs);
269 // Next, add all inputs and output as well-formed tys. Importantly,
270 // we have to do this before normalization, since the normalized ty may
271 // not contain the input parameters. See issue #87748.
272 wf_tys.extend(trait_sig.inputs_and_output.iter());
274 inh.normalize_associated_types_in(impl_m_span, impl_m_hir_id, param_env, trait_sig);
275 // Also add the resulting inputs and output as well-formed.
276 // This probably isn't strictly necessary.
277 wf_tys.extend(trait_sig.inputs_and_output.iter());
278 let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
280 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
282 let sub_result = infcx.at(&cause, param_env).sup(trait_fty, impl_fty).map(
283 |InferOk { obligations, .. }| {
284 inh.register_predicates(obligations);
288 if let Err(terr) = sub_result {
289 debug!("sub_types failed: impl ty {:?}, trait ty {:?}", impl_fty, trait_fty);
291 let (impl_err_span, trait_err_span) =
292 extract_spans_for_error_reporting(&infcx, &terr, &cause, impl_m, trait_m);
294 cause.make_mut().span = impl_err_span;
296 let mut diag = struct_span_err!(
300 "method `{}` has an incompatible type for trait",
304 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
305 if trait_m.fn_has_self_parameter =>
307 let ty = trait_sig.inputs()[0];
308 let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty())
310 ExplicitSelf::ByValue => "self".to_owned(),
311 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
312 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => {
313 "&mut self".to_owned()
315 _ => format!("self: {}", ty),
318 // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
319 // span points only at the type `Box<Self`>, but we want to cover the whole
320 // argument pattern and type.
322 tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
323 let span = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
324 ImplItemKind::Fn(ref sig, body) => tcx
326 .body_param_names(body)
327 .zip(sig.decl.inputs.iter())
328 .map(|(param, ty)| param.span.to(ty.span))
330 .unwrap_or(impl_err_span),
331 _ => bug!("{:?} is not a method", impl_m),
334 diag.span_suggestion(
336 "change the self-receiver type to match the trait",
338 Applicability::MachineApplicable,
341 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
342 if trait_sig.inputs().len() == *i {
343 // Suggestion to change output type. We do not suggest in `async` functions
344 // to avoid complex logic or incorrect output.
346 tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
347 match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
348 ImplItemKind::Fn(ref sig, _)
349 if sig.header.asyncness == hir::IsAsync::NotAsync =>
351 let msg = "change the output type to match the trait";
352 let ap = Applicability::MachineApplicable;
353 match sig.decl.output {
354 hir::FnRetTy::DefaultReturn(sp) => {
355 let sugg = format!("-> {} ", trait_sig.output());
356 diag.span_suggestion_verbose(sp, msg, sugg, ap);
358 hir::FnRetTy::Return(hir_ty) => {
359 let sugg = trait_sig.output().to_string();
360 diag.span_suggestion(hir_ty.span, msg, sugg, ap);
366 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
367 diag.span_suggestion(
369 "change the parameter type to match the trait",
370 trait_ty.to_string(),
371 Applicability::MachineApplicable,
381 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
382 Some(infer::ValuePairs::Types(ExpectedFound {
389 return Err(ErrorReported);
392 // Check that all obligations are satisfied by the implementation's
394 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
395 if !errors.is_empty() {
396 infcx.report_fulfillment_errors(&errors, None, false);
397 return Err(ErrorReported);
400 // Finally, resolve all regions. This catches wily misuses of
401 // lifetime parameters.
402 let fcx = FnCtxt::new(&inh, param_env, impl_m_hir_id);
403 fcx.regionck_item(impl_m_hir_id, impl_m_span, wf_tys);
409 fn check_region_bounds_on_impl_item<'tcx>(
412 impl_m: &ty::AssocItem,
413 trait_m: &ty::AssocItem,
414 trait_generics: &ty::Generics,
415 impl_generics: &ty::Generics,
416 ) -> Result<(), ErrorReported> {
417 let trait_params = trait_generics.own_counts().lifetimes;
418 let impl_params = impl_generics.own_counts().lifetimes;
421 "check_region_bounds_on_impl_item: \
422 trait_generics={:?} \
424 trait_generics, impl_generics
427 // Must have same number of early-bound lifetime parameters.
428 // Unfortunately, if the user screws up the bounds, then this
429 // will change classification between early and late. E.g.,
430 // if in trait we have `<'a,'b:'a>`, and in impl we just have
431 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
432 // in trait but 0 in the impl. But if we report "expected 2
433 // but found 0" it's confusing, because it looks like there
434 // are zero. Since I don't quite know how to phrase things at
435 // the moment, give a kind of vague error message.
436 if trait_params != impl_params {
437 let item_kind = assoc_item_kind_str(impl_m);
438 let def_span = tcx.sess.source_map().guess_head_span(span);
439 let span = tcx.hir().get_generics(impl_m.def_id).map_or(def_span, |g| g.span);
440 let generics_span = tcx.hir().span_if_local(trait_m.def_id).map(|sp| {
441 let def_sp = tcx.sess.source_map().guess_head_span(sp);
442 tcx.hir().get_generics(trait_m.def_id).map_or(def_sp, |g| g.span)
445 tcx.sess.emit_err(LifetimesOrBoundsMismatchOnTrait {
451 return Err(ErrorReported);
457 #[instrument(level = "debug", skip(infcx))]
458 fn extract_spans_for_error_reporting<'a, 'tcx>(
459 infcx: &infer::InferCtxt<'a, 'tcx>,
460 terr: &TypeError<'_>,
461 cause: &ObligationCause<'tcx>,
462 impl_m: &ty::AssocItem,
463 trait_m: &ty::AssocItem,
464 ) -> (Span, Option<Span>) {
466 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
467 let mut impl_args = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
468 ImplItemKind::Fn(ref sig, _) => {
469 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
471 _ => bug!("{:?} is not a method", impl_m),
473 let trait_args = trait_m.def_id.as_local().map(|def_id| {
474 let trait_m_hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
475 match tcx.hir().expect_trait_item(trait_m_hir_id).kind {
476 TraitItemKind::Fn(ref sig, _) => {
477 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
479 _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
484 TypeError::ArgumentMutability(i) => {
485 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
487 TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
488 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
490 _ => (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)),
494 fn compare_self_type<'tcx>(
496 impl_m: &ty::AssocItem,
498 trait_m: &ty::AssocItem,
499 impl_trait_ref: ty::TraitRef<'tcx>,
500 ) -> Result<(), ErrorReported> {
501 // Try to give more informative error messages about self typing
502 // mismatches. Note that any mismatch will also be detected
503 // below, where we construct a canonical function type that
504 // includes the self parameter as a normal parameter. It's just
505 // that the error messages you get out of this code are a bit more
506 // inscrutable, particularly for cases where one method has no
509 let self_string = |method: &ty::AssocItem| {
510 let untransformed_self_ty = match method.container {
511 ty::ImplContainer(_) => impl_trait_ref.self_ty(),
512 ty::TraitContainer(_) => tcx.types.self_param,
514 let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
515 let param_env = ty::ParamEnv::reveal_all();
517 tcx.infer_ctxt().enter(|infcx| {
518 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
519 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
520 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
521 ExplicitSelf::ByValue => "self".to_owned(),
522 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
523 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
524 _ => format!("self: {}", self_arg_ty),
529 match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
530 (false, false) | (true, true) => {}
533 let self_descr = self_string(impl_m);
534 let mut err = struct_span_err!(
538 "method `{}` has a `{}` declaration in the impl, but not in the trait",
542 err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
543 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
544 err.span_label(span, format!("trait method declared without `{}`", self_descr));
546 err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
549 return Err(ErrorReported);
553 let self_descr = self_string(trait_m);
554 let mut err = struct_span_err!(
558 "method `{}` has a `{}` declaration in the trait, but not in the impl",
562 err.span_label(impl_m_span, format!("expected `{}` in impl", self_descr));
563 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
564 err.span_label(span, format!("`{}` used in trait", self_descr));
566 err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
569 return Err(ErrorReported);
576 fn compare_number_of_generics<'tcx>(
578 impl_: &ty::AssocItem,
580 trait_: &ty::AssocItem,
581 trait_span: Option<Span>,
582 ) -> Result<(), ErrorReported> {
583 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
584 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
587 ("type", trait_own_counts.types, impl_own_counts.types),
588 ("const", trait_own_counts.consts, impl_own_counts.consts),
591 let item_kind = assoc_item_kind_str(impl_);
593 let mut err_occurred = false;
594 for (kind, trait_count, impl_count) in matchings {
595 if impl_count != trait_count {
598 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
599 let trait_hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
600 let trait_item = tcx.hir().expect_trait_item(trait_hir_id);
601 if trait_item.generics.params.is_empty() {
602 (Some(vec![trait_item.generics.span]), vec![])
604 let arg_spans: Vec<Span> =
605 trait_item.generics.params.iter().map(|p| p.span).collect();
606 let impl_trait_spans: Vec<Span> = trait_item
610 .filter_map(|p| match p.kind {
611 GenericParamKind::Type {
612 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
618 (Some(arg_spans), impl_trait_spans)
621 (trait_span.map(|s| vec![s]), vec![])
624 let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_.def_id.expect_local());
625 let impl_item = tcx.hir().expect_impl_item(impl_hir_id);
626 let impl_item_impl_trait_spans: Vec<Span> = impl_item
630 .filter_map(|p| match p.kind {
631 GenericParamKind::Type {
632 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
638 let spans = impl_item.generics.spans();
639 let span = spans.primary_span();
641 let mut err = tcx.sess.struct_span_err_with_code(
644 "{} `{}` has {} {kind} parameter{} but its trait \
645 declaration has {} {kind} parameter{}",
649 pluralize!(impl_count),
651 pluralize!(trait_count),
654 DiagnosticId::Error("E0049".into()),
657 let mut suffix = None;
659 if let Some(spans) = trait_spans {
660 let mut spans = spans.iter();
661 if let Some(span) = spans.next() {
665 "expected {} {} parameter{}",
668 pluralize!(trait_count),
673 err.span_label(*span, "");
676 suffix = Some(format!(", expected {}", trait_count));
679 if let Some(span) = span {
683 "found {} {} parameter{}{}",
686 pluralize!(impl_count),
687 suffix.unwrap_or_else(String::new),
692 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
693 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
700 if err_occurred { Err(ErrorReported) } else { Ok(()) }
703 fn compare_number_of_method_arguments<'tcx>(
705 impl_m: &ty::AssocItem,
707 trait_m: &ty::AssocItem,
708 trait_item_span: Option<Span>,
709 ) -> Result<(), ErrorReported> {
710 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
711 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
712 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
713 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
714 if trait_number_args != impl_number_args {
715 let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
716 let trait_id = tcx.hir().local_def_id_to_hir_id(def_id);
717 match tcx.hir().expect_trait_item(trait_id).kind {
718 TraitItemKind::Fn(ref trait_m_sig, _) => {
719 let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
720 if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
724 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
730 _ => bug!("{:?} is not a method", impl_m),
735 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
736 let impl_span = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
737 ImplItemKind::Fn(ref impl_m_sig, _) => {
738 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
739 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
743 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
749 _ => bug!("{:?} is not a method", impl_m),
751 let mut err = struct_span_err!(
755 "method `{}` has {} but the declaration in \
758 potentially_plural_count(impl_number_args, "parameter"),
759 tcx.def_path_str(trait_m.def_id),
762 if let Some(trait_span) = trait_span {
767 potentially_plural_count(trait_number_args, "parameter")
771 err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
776 "expected {}, found {}",
777 potentially_plural_count(trait_number_args, "parameter"),
782 return Err(ErrorReported);
788 fn compare_synthetic_generics<'tcx>(
790 impl_m: &ty::AssocItem,
791 trait_m: &ty::AssocItem,
792 ) -> Result<(), ErrorReported> {
793 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
794 // 1. Better messages for the span labels
795 // 2. Explanation as to what is going on
796 // If we get here, we already have the same number of generics, so the zip will
798 let mut error_found = false;
799 let impl_m_generics = tcx.generics_of(impl_m.def_id);
800 let trait_m_generics = tcx.generics_of(trait_m.def_id);
801 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
802 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
803 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
805 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
806 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
807 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
809 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
810 iter::zip(impl_m_type_params, trait_m_type_params)
812 if impl_synthetic != trait_synthetic {
813 let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_def_id.expect_local());
814 let impl_span = tcx.hir().span(impl_hir_id);
815 let trait_span = tcx.def_span(trait_def_id);
816 let mut err = struct_span_err!(
820 "method `{}` has incompatible signature for trait",
823 err.span_label(trait_span, "declaration in trait here");
824 match (impl_synthetic, trait_synthetic) {
825 // The case where the impl method uses `impl Trait` but the trait method uses
827 (Some(hir::SyntheticTyParamKind::ImplTrait), None) => {
828 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
830 // try taking the name from the trait impl
831 // FIXME: this is obviously suboptimal since the name can already be used
832 // as another generic argument
833 let new_name = tcx.sess.source_map().span_to_snippet(trait_span).ok()?;
834 let trait_m = trait_m.def_id.as_local()?;
835 let trait_m = tcx.hir().trait_item(hir::TraitItemId { def_id: trait_m });
837 let impl_m = impl_m.def_id.as_local()?;
838 let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
840 // in case there are no generics, take the spot between the function name
841 // and the opening paren of the argument list
842 let new_generics_span =
843 tcx.sess.source_map().generate_fn_name_span(impl_span)?.shrink_to_hi();
844 // in case there are generics, just replace them
846 impl_m.generics.span.substitute_dummy(new_generics_span);
847 // replace with the generics from the trait
849 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
851 err.multipart_suggestion(
852 "try changing the `impl Trait` argument to a generic parameter",
854 // replace `impl Trait` with `T`
855 (impl_span, new_name),
856 // replace impl method generics with trait method generics
857 // This isn't quite right, as users might have changed the names
858 // of the generics, but it works for the common case
859 (generics_span, new_generics),
861 Applicability::MaybeIncorrect,
866 // The case where the trait method uses `impl Trait`, but the impl method uses
867 // explicit generics.
868 (None, Some(hir::SyntheticTyParamKind::ImplTrait)) => {
869 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
871 let impl_m = impl_m.def_id.as_local()?;
872 let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
873 let input_tys = match impl_m.kind {
874 hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
877 struct Visitor(Option<Span>, hir::def_id::DefId);
878 impl<'v> intravisit::Visitor<'v> for Visitor {
879 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
880 intravisit::walk_ty(self, ty);
881 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
884 if let Res::Def(DefKind::TyParam, def_id) = path.res {
885 if def_id == self.1 {
886 self.0 = Some(ty.span);
891 type Map = intravisit::ErasedMap<'v>;
894 ) -> intravisit::NestedVisitorMap<Self::Map>
896 intravisit::NestedVisitorMap::None
899 let mut visitor = Visitor(None, impl_def_id);
900 for ty in input_tys {
901 intravisit::Visitor::visit_ty(&mut visitor, ty);
903 let span = visitor.0?;
906 impl_m.generics.params.iter().find_map(|param| match param.kind {
907 GenericParamKind::Lifetime { .. } => None,
908 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
909 if param.hir_id == impl_hir_id {
916 let bounds = bounds.first()?.span().to(bounds.last()?.span());
917 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
919 err.multipart_suggestion(
920 "try removing the generic parameter and using `impl Trait` instead",
922 // delete generic parameters
923 (impl_m.generics.span, String::new()),
924 // replace param usage with `impl Trait`
925 (span, format!("impl {}", bounds)),
927 Applicability::MaybeIncorrect,
938 if error_found { Err(ErrorReported) } else { Ok(()) }
941 fn compare_const_param_types<'tcx>(
943 impl_m: &ty::AssocItem,
944 trait_m: &ty::AssocItem,
945 trait_item_span: Option<Span>,
946 ) -> Result<(), ErrorReported> {
947 let const_params_of = |def_id| {
948 tcx.generics_of(def_id).params.iter().filter_map(|param| match param.kind {
949 GenericParamDefKind::Const { .. } => Some(param.def_id),
953 let const_params_impl = const_params_of(impl_m.def_id);
954 let const_params_trait = const_params_of(trait_m.def_id);
956 for (const_param_impl, const_param_trait) in iter::zip(const_params_impl, const_params_trait) {
957 let impl_ty = tcx.type_of(const_param_impl);
958 let trait_ty = tcx.type_of(const_param_trait);
959 if impl_ty != trait_ty {
960 let (impl_span, impl_ident) = match tcx.hir().get_if_local(const_param_impl) {
961 Some(hir::Node::GenericParam(hir::GenericParam { span, name, .. })) => (
964 hir::ParamName::Plain(ident) => Some(ident),
969 "expected GenericParam, found {:?}",
970 other.map_or_else(|| "nothing".to_string(), |n| format!("{:?}", n))
973 let trait_span = match tcx.hir().get_if_local(const_param_trait) {
974 Some(hir::Node::GenericParam(hir::GenericParam { span, .. })) => Some(span),
977 let mut err = struct_span_err!(
981 "method `{}` has an incompatible const parameter type for trait",
985 trait_span.map_or_else(|| trait_item_span.unwrap_or(*impl_span), |span| *span),
987 "the const parameter{} has type `{}`, but the declaration \
988 in trait `{}` has type `{}`",
989 &impl_ident.map_or_else(|| "".to_string(), |ident| format!(" `{}`", ident)),
991 tcx.def_path_str(trait_m.def_id),
996 return Err(ErrorReported);
1003 crate fn compare_const_impl<'tcx>(
1005 impl_c: &ty::AssocItem,
1007 trait_c: &ty::AssocItem,
1008 impl_trait_ref: ty::TraitRef<'tcx>,
1010 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
1012 tcx.infer_ctxt().enter(|infcx| {
1013 let param_env = tcx.param_env(impl_c.def_id);
1014 let inh = Inherited::new(infcx, impl_c.def_id.expect_local());
1015 let infcx = &inh.infcx;
1017 // The below is for the most part highly similar to the procedure
1018 // for methods above. It is simpler in many respects, especially
1019 // because we shouldn't really have to deal with lifetimes or
1020 // predicates. In fact some of this should probably be put into
1021 // shared functions because of DRY violations...
1022 let trait_to_impl_substs = impl_trait_ref.substs;
1024 // Create a parameter environment that represents the implementation's
1026 let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_c.def_id.expect_local());
1028 // Compute placeholder form of impl and trait const tys.
1029 let impl_ty = tcx.type_of(impl_c.def_id);
1030 let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
1031 let mut cause = ObligationCause::new(
1034 ObligationCauseCode::CompareImplConstObligation,
1037 // There is no "body" here, so just pass dummy id.
1039 inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, impl_ty);
1041 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1044 inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, trait_ty);
1046 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1049 .at(&cause, param_env)
1050 .sup(trait_ty, impl_ty)
1051 .map(|ok| inh.register_infer_ok_obligations(ok));
1053 if let Err(terr) = err {
1055 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1059 // Locate the Span containing just the type of the offending impl
1060 match tcx.hir().expect_impl_item(impl_c_hir_id).kind {
1061 ImplItemKind::Const(ref ty, _) => cause.make_mut().span = ty.span,
1062 _ => bug!("{:?} is not a impl const", impl_c),
1065 let mut diag = struct_span_err!(
1069 "implemented const `{}` has an incompatible type for trait",
1073 let trait_c_hir_id =
1074 trait_c.def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id));
1075 let trait_c_span = trait_c_hir_id.map(|trait_c_hir_id| {
1076 // Add a label to the Span containing just the type of the const
1077 match tcx.hir().expect_trait_item(trait_c_hir_id).kind {
1078 TraitItemKind::Const(ref ty, _) => ty.span,
1079 _ => bug!("{:?} is not a trait const", trait_c),
1083 infcx.note_type_err(
1086 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1087 Some(infer::ValuePairs::Types(ExpectedFound {
1096 // Check that all obligations are satisfied by the implementation's
1098 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
1099 if !errors.is_empty() {
1100 infcx.report_fulfillment_errors(&errors, None, false);
1104 let fcx = FnCtxt::new(&inh, param_env, impl_c_hir_id);
1105 fcx.regionck_item(impl_c_hir_id, impl_c_span, FxHashSet::default());
1109 crate fn compare_ty_impl<'tcx>(
1111 impl_ty: &ty::AssocItem,
1113 trait_ty: &ty::AssocItem,
1114 impl_trait_ref: ty::TraitRef<'tcx>,
1115 trait_item_span: Option<Span>,
1117 debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1119 let _: Result<(), ErrorReported> = (|| {
1120 compare_number_of_generics(tcx, impl_ty, impl_ty_span, trait_ty, trait_item_span)?;
1122 compare_type_predicate_entailment(tcx, impl_ty, impl_ty_span, trait_ty, impl_trait_ref)?;
1124 check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1128 /// The equivalent of [compare_predicate_entailment], but for associated types
1129 /// instead of associated functions.
1130 fn compare_type_predicate_entailment<'tcx>(
1132 impl_ty: &ty::AssocItem,
1134 trait_ty: &ty::AssocItem,
1135 impl_trait_ref: ty::TraitRef<'tcx>,
1136 ) -> Result<(), ErrorReported> {
1137 let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1138 let trait_to_impl_substs =
1139 impl_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1141 let impl_ty_generics = tcx.generics_of(impl_ty.def_id);
1142 let trait_ty_generics = tcx.generics_of(trait_ty.def_id);
1143 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1144 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1146 check_region_bounds_on_impl_item(
1155 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1157 if impl_ty_own_bounds.is_empty() {
1158 // Nothing to check.
1162 // This `HirId` should be used for the `body_id` field on each
1163 // `ObligationCause` (and the `FnCtxt`). This is what
1164 // `regionck_item` expects.
1165 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1166 let cause = ObligationCause::new(
1169 ObligationCauseCode::CompareImplTypeObligation {
1170 item_name: impl_ty.ident.name,
1171 impl_item_def_id: impl_ty.def_id,
1172 trait_item_def_id: trait_ty.def_id,
1176 debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1178 // The predicates declared by the impl definition, the trait and the
1179 // associated type in the trait are assumed.
1180 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1181 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1184 .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1186 debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1188 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1190 ty::ParamEnv::new(tcx.intern_predicates(&hybrid_preds.predicates), Reveal::UserFacing);
1191 let param_env = traits::normalize_param_env_or_error(
1195 normalize_cause.clone(),
1197 tcx.infer_ctxt().enter(|infcx| {
1198 let inh = Inherited::new(infcx, impl_ty.def_id.expect_local());
1199 let infcx = &inh.infcx;
1201 debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1203 let mut selcx = traits::SelectionContext::new(&infcx);
1205 for predicate in impl_ty_own_bounds.predicates {
1206 let traits::Normalized { value: predicate, obligations } =
1207 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), predicate);
1209 inh.register_predicates(obligations);
1210 inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
1213 // Check that all obligations are satisfied by the implementation's
1215 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
1216 if !errors.is_empty() {
1217 infcx.report_fulfillment_errors(&errors, None, false);
1218 return Err(ErrorReported);
1221 // Finally, resolve all regions. This catches wily misuses of
1222 // lifetime parameters.
1223 let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
1224 fcx.regionck_item(impl_ty_hir_id, impl_ty_span, FxHashSet::default());
1230 /// Validate that `ProjectionCandidate`s created for this associated type will
1235 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1237 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1238 /// impl is well-formed we have to prove `S: Copy`.
1240 /// For default associated types the normalization is not possible (the value
1241 /// from the impl could be overridden). We also can't normalize generic
1242 /// associated types (yet) because they contain bound parameters.
1243 #[tracing::instrument(level = "debug", skip(tcx))]
1244 pub fn check_type_bounds<'tcx>(
1246 trait_ty: &ty::AssocItem,
1247 impl_ty: &ty::AssocItem,
1249 impl_trait_ref: ty::TraitRef<'tcx>,
1250 ) -> Result<(), ErrorReported> {
1253 // impl<A, B> Foo<u32> for (A, B) {
1257 // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1258 // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1259 // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1260 // the *trait* with the generic associated type parameters (as bound vars).
1262 // A note regarding the use of bound vars here:
1263 // Imagine as an example
1266 // type Member<C: Eq>;
1269 // impl Family for VecFamily {
1270 // type Member<C: Eq> = i32;
1273 // Here, we would generate
1275 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1277 // when we really would like to generate
1279 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1281 // But, this is probably fine, because although the first clause can be used with types C that
1282 // do not implement Eq, for it to cause some kind of problem, there would have to be a
1283 // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1284 // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1285 // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1286 // the trait (notably, that X: Eq and T: Family).
1287 let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1288 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1289 if let Some(def_id) = defs.parent {
1290 let parent_defs = tcx.generics_of(def_id);
1291 InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1292 tcx.mk_param_from_def(param)
1295 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1296 smallvec::SmallVec::with_capacity(defs.count());
1297 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1298 GenericParamDefKind::Type { .. } => {
1299 let kind = ty::BoundTyKind::Param(param.name);
1300 let bound_var = ty::BoundVariableKind::Ty(kind);
1301 bound_vars.push(bound_var);
1302 tcx.mk_ty(ty::Bound(
1304 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1308 GenericParamDefKind::Lifetime => {
1309 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1310 let bound_var = ty::BoundVariableKind::Region(kind);
1311 bound_vars.push(bound_var);
1312 tcx.mk_region(ty::ReLateBound(
1314 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1318 GenericParamDefKind::Const { .. } => {
1319 let bound_var = ty::BoundVariableKind::Const;
1320 bound_vars.push(bound_var);
1321 tcx.mk_const(ty::Const {
1322 ty: tcx.type_of(param.def_id),
1323 val: ty::ConstKind::Bound(
1325 ty::BoundVar::from_usize(bound_vars.len() - 1),
1331 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
1332 let impl_ty_substs = tcx.intern_substs(&substs);
1334 let rebased_substs =
1335 impl_ty_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1336 let impl_ty_value = tcx.type_of(impl_ty.def_id);
1338 let param_env = tcx.param_env(impl_ty.def_id);
1340 // When checking something like
1342 // trait X { type Y: PartialEq<<Self as X>::Y> }
1343 // impl X for T { default type Y = S; }
1345 // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
1346 // we want <T as X>::Y to normalize to S. This is valid because we are
1347 // checking the default value specifically here. Add this equality to the
1348 // ParamEnv for normalization specifically.
1349 let normalize_param_env = {
1350 let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
1351 match impl_ty_value.kind() {
1352 ty::Projection(proj)
1353 if proj.item_def_id == trait_ty.def_id && proj.substs == rebased_substs =>
1355 // Don't include this predicate if the projected type is
1356 // exactly the same as the projection. This can occur in
1357 // (somewhat dubious) code like this:
1359 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
1361 _ => predicates.push(
1362 ty::Binder::bind_with_vars(
1363 ty::ProjectionPredicate {
1364 projection_ty: ty::ProjectionTy {
1365 item_def_id: trait_ty.def_id,
1366 substs: rebased_substs,
1375 ty::ParamEnv::new(tcx.intern_predicates(&predicates), Reveal::UserFacing)
1377 debug!(?normalize_param_env);
1379 let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1380 let rebased_substs =
1381 impl_ty_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1383 tcx.infer_ctxt().enter(move |infcx| {
1384 let constness = impl_ty
1387 .map(|did| tcx.impl_constness(did))
1388 .unwrap_or(hir::Constness::NotConst);
1390 let inh = Inherited::with_constness(infcx, impl_ty.def_id.expect_local(), constness);
1391 let infcx = &inh.infcx;
1392 let mut selcx = traits::SelectionContext::new(&infcx);
1394 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1395 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1396 let mk_cause = |span| {
1397 ObligationCause::new(
1400 ObligationCauseCode::BindingObligation(trait_ty.def_id, span),
1404 let obligations = tcx
1405 .explicit_item_bounds(trait_ty.def_id)
1407 .map(|&(bound, span)| {
1409 let concrete_ty_bound = bound.subst(tcx, rebased_substs);
1410 debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
1412 traits::Obligation::new(mk_cause(span), param_env, concrete_ty_bound)
1415 debug!("check_type_bounds: item_bounds={:?}", obligations);
1417 for mut obligation in util::elaborate_obligations(tcx, obligations) {
1418 let traits::Normalized { value: normalized_predicate, obligations } = traits::normalize(
1420 normalize_param_env,
1421 normalize_cause.clone(),
1422 obligation.predicate,
1424 debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
1425 obligation.predicate = normalized_predicate;
1427 inh.register_predicates(obligations);
1428 inh.register_predicate(obligation);
1431 // Check that all obligations are satisfied by the implementation's
1434 inh.fulfillment_cx.borrow_mut().select_all_with_constness_or_error(&infcx, constness);
1435 if !errors.is_empty() {
1436 infcx.report_fulfillment_errors(&errors, None, false);
1437 return Err(ErrorReported);
1440 // Finally, resolve all regions. This catches wily misuses of
1441 // lifetime parameters.
1442 let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
1443 let implied_bounds = match impl_ty.container {
1444 ty::TraitContainer(_) => FxHashSet::default(),
1445 ty::ImplContainer(def_id) => fcx.impl_implied_bounds(def_id, impl_ty_span),
1447 fcx.regionck_item(impl_ty_hir_id, impl_ty_span, implied_bounds);
1453 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
1454 match impl_item.kind {
1455 ty::AssocKind::Const => "const",
1456 ty::AssocKind::Fn => "method",
1457 ty::AssocKind::Type => "type",