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 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
395 infcx.report_fulfillment_errors(errors, None, false);
396 return Err(ErrorReported);
399 // Finally, resolve all regions. This catches wily misuses of
400 // lifetime parameters.
401 let fcx = FnCtxt::new(&inh, param_env, impl_m_hir_id);
402 fcx.regionck_item(impl_m_hir_id, impl_m_span, wf_tys);
408 fn check_region_bounds_on_impl_item<'tcx>(
411 impl_m: &ty::AssocItem,
412 trait_m: &ty::AssocItem,
413 trait_generics: &ty::Generics,
414 impl_generics: &ty::Generics,
415 ) -> Result<(), ErrorReported> {
416 let trait_params = trait_generics.own_counts().lifetimes;
417 let impl_params = impl_generics.own_counts().lifetimes;
420 "check_region_bounds_on_impl_item: \
421 trait_generics={:?} \
423 trait_generics, impl_generics
426 // Must have same number of early-bound lifetime parameters.
427 // Unfortunately, if the user screws up the bounds, then this
428 // will change classification between early and late. E.g.,
429 // if in trait we have `<'a,'b:'a>`, and in impl we just have
430 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
431 // in trait but 0 in the impl. But if we report "expected 2
432 // but found 0" it's confusing, because it looks like there
433 // are zero. Since I don't quite know how to phrase things at
434 // the moment, give a kind of vague error message.
435 if trait_params != impl_params {
436 let item_kind = assoc_item_kind_str(impl_m);
437 let def_span = tcx.sess.source_map().guess_head_span(span);
438 let span = tcx.hir().get_generics(impl_m.def_id).map_or(def_span, |g| g.span);
439 let generics_span = tcx.hir().span_if_local(trait_m.def_id).map(|sp| {
440 let def_sp = tcx.sess.source_map().guess_head_span(sp);
441 tcx.hir().get_generics(trait_m.def_id).map_or(def_sp, |g| g.span)
444 tcx.sess.emit_err(LifetimesOrBoundsMismatchOnTrait {
450 return Err(ErrorReported);
456 fn extract_spans_for_error_reporting<'a, 'tcx>(
457 infcx: &infer::InferCtxt<'a, 'tcx>,
458 terr: &TypeError<'_>,
459 cause: &ObligationCause<'tcx>,
460 impl_m: &ty::AssocItem,
461 trait_m: &ty::AssocItem,
462 ) -> (Span, Option<Span>) {
464 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
465 let mut impl_args = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
466 ImplItemKind::Fn(ref sig, _) => {
467 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
469 _ => bug!("{:?} is not a method", impl_m),
471 let trait_args = trait_m.def_id.as_local().map(|def_id| {
472 let trait_m_hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
473 match tcx.hir().expect_trait_item(trait_m_hir_id).kind {
474 TraitItemKind::Fn(ref sig, _) => {
475 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
477 _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
482 TypeError::ArgumentMutability(i) => {
483 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
485 TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
486 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
488 _ => (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)),
492 fn compare_self_type<'tcx>(
494 impl_m: &ty::AssocItem,
496 trait_m: &ty::AssocItem,
497 impl_trait_ref: ty::TraitRef<'tcx>,
498 ) -> Result<(), ErrorReported> {
499 // Try to give more informative error messages about self typing
500 // mismatches. Note that any mismatch will also be detected
501 // below, where we construct a canonical function type that
502 // includes the self parameter as a normal parameter. It's just
503 // that the error messages you get out of this code are a bit more
504 // inscrutable, particularly for cases where one method has no
507 let self_string = |method: &ty::AssocItem| {
508 let untransformed_self_ty = match method.container {
509 ty::ImplContainer(_) => impl_trait_ref.self_ty(),
510 ty::TraitContainer(_) => tcx.types.self_param,
512 let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
513 let param_env = ty::ParamEnv::reveal_all();
515 tcx.infer_ctxt().enter(|infcx| {
516 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
517 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
518 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
519 ExplicitSelf::ByValue => "self".to_owned(),
520 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
521 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
522 _ => format!("self: {}", self_arg_ty),
527 match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
528 (false, false) | (true, true) => {}
531 let self_descr = self_string(impl_m);
532 let mut err = struct_span_err!(
536 "method `{}` has a `{}` declaration in the impl, but not in the trait",
540 err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
541 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
542 err.span_label(span, format!("trait method declared without `{}`", self_descr));
544 err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
547 return Err(ErrorReported);
551 let self_descr = self_string(trait_m);
552 let mut err = struct_span_err!(
556 "method `{}` has a `{}` declaration in the trait, but not in the impl",
560 err.span_label(impl_m_span, format!("expected `{}` in impl", self_descr));
561 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
562 err.span_label(span, format!("`{}` used in trait", self_descr));
564 err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
567 return Err(ErrorReported);
574 fn compare_number_of_generics<'tcx>(
576 impl_: &ty::AssocItem,
578 trait_: &ty::AssocItem,
579 trait_span: Option<Span>,
580 ) -> Result<(), ErrorReported> {
581 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
582 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
585 ("type", trait_own_counts.types, impl_own_counts.types),
586 ("const", trait_own_counts.consts, impl_own_counts.consts),
589 let item_kind = assoc_item_kind_str(impl_);
591 let mut err_occurred = false;
592 for (kind, trait_count, impl_count) in matchings {
593 if impl_count != trait_count {
596 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
597 let trait_hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
598 let trait_item = tcx.hir().expect_trait_item(trait_hir_id);
599 if trait_item.generics.params.is_empty() {
600 (Some(vec![trait_item.generics.span]), vec![])
602 let arg_spans: Vec<Span> =
603 trait_item.generics.params.iter().map(|p| p.span).collect();
604 let impl_trait_spans: Vec<Span> = trait_item
608 .filter_map(|p| match p.kind {
609 GenericParamKind::Type {
610 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
616 (Some(arg_spans), impl_trait_spans)
619 (trait_span.map(|s| vec![s]), vec![])
622 let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_.def_id.expect_local());
623 let impl_item = tcx.hir().expect_impl_item(impl_hir_id);
624 let impl_item_impl_trait_spans: Vec<Span> = impl_item
628 .filter_map(|p| match p.kind {
629 GenericParamKind::Type {
630 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
636 let spans = impl_item.generics.spans();
637 let span = spans.primary_span();
639 let mut err = tcx.sess.struct_span_err_with_code(
642 "{} `{}` has {} {kind} parameter{} but its trait \
643 declaration has {} {kind} parameter{}",
647 pluralize!(impl_count),
649 pluralize!(trait_count),
652 DiagnosticId::Error("E0049".into()),
655 let mut suffix = None;
657 if let Some(spans) = trait_spans {
658 let mut spans = spans.iter();
659 if let Some(span) = spans.next() {
663 "expected {} {} parameter{}",
666 pluralize!(trait_count),
671 err.span_label(*span, "");
674 suffix = Some(format!(", expected {}", trait_count));
677 if let Some(span) = span {
681 "found {} {} parameter{}{}",
684 pluralize!(impl_count),
685 suffix.unwrap_or_else(String::new),
690 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
691 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
698 if err_occurred { Err(ErrorReported) } else { Ok(()) }
701 fn compare_number_of_method_arguments<'tcx>(
703 impl_m: &ty::AssocItem,
705 trait_m: &ty::AssocItem,
706 trait_item_span: Option<Span>,
707 ) -> Result<(), ErrorReported> {
708 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
709 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
710 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
711 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
712 if trait_number_args != impl_number_args {
713 let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
714 let trait_id = tcx.hir().local_def_id_to_hir_id(def_id);
715 match tcx.hir().expect_trait_item(trait_id).kind {
716 TraitItemKind::Fn(ref trait_m_sig, _) => {
717 let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
718 if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
722 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
728 _ => bug!("{:?} is not a method", impl_m),
733 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
734 let impl_span = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
735 ImplItemKind::Fn(ref impl_m_sig, _) => {
736 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
737 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
741 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
747 _ => bug!("{:?} is not a method", impl_m),
749 let mut err = struct_span_err!(
753 "method `{}` has {} but the declaration in \
756 potentially_plural_count(impl_number_args, "parameter"),
757 tcx.def_path_str(trait_m.def_id),
760 if let Some(trait_span) = trait_span {
765 potentially_plural_count(trait_number_args, "parameter")
769 err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
774 "expected {}, found {}",
775 potentially_plural_count(trait_number_args, "parameter"),
780 return Err(ErrorReported);
786 fn compare_synthetic_generics<'tcx>(
788 impl_m: &ty::AssocItem,
789 trait_m: &ty::AssocItem,
790 ) -> Result<(), ErrorReported> {
791 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
792 // 1. Better messages for the span labels
793 // 2. Explanation as to what is going on
794 // If we get here, we already have the same number of generics, so the zip will
796 let mut error_found = false;
797 let impl_m_generics = tcx.generics_of(impl_m.def_id);
798 let trait_m_generics = tcx.generics_of(trait_m.def_id);
799 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
800 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
801 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
803 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
804 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
805 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
807 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
808 iter::zip(impl_m_type_params, trait_m_type_params)
810 if impl_synthetic != trait_synthetic {
811 let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_def_id.expect_local());
812 let impl_span = tcx.hir().span(impl_hir_id);
813 let trait_span = tcx.def_span(trait_def_id);
814 let mut err = struct_span_err!(
818 "method `{}` has incompatible signature for trait",
821 err.span_label(trait_span, "declaration in trait here");
822 match (impl_synthetic, trait_synthetic) {
823 // The case where the impl method uses `impl Trait` but the trait method uses
825 (Some(hir::SyntheticTyParamKind::ImplTrait), None) => {
826 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
828 // try taking the name from the trait impl
829 // FIXME: this is obviously suboptimal since the name can already be used
830 // as another generic argument
831 let new_name = tcx.sess.source_map().span_to_snippet(trait_span).ok()?;
832 let trait_m = trait_m.def_id.as_local()?;
833 let trait_m = tcx.hir().trait_item(hir::TraitItemId { def_id: trait_m });
835 let impl_m = impl_m.def_id.as_local()?;
836 let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
838 // in case there are no generics, take the spot between the function name
839 // and the opening paren of the argument list
840 let new_generics_span =
841 tcx.sess.source_map().generate_fn_name_span(impl_span)?.shrink_to_hi();
842 // in case there are generics, just replace them
844 impl_m.generics.span.substitute_dummy(new_generics_span);
845 // replace with the generics from the trait
847 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
849 err.multipart_suggestion(
850 "try changing the `impl Trait` argument to a generic parameter",
852 // replace `impl Trait` with `T`
853 (impl_span, new_name),
854 // replace impl method generics with trait method generics
855 // This isn't quite right, as users might have changed the names
856 // of the generics, but it works for the common case
857 (generics_span, new_generics),
859 Applicability::MaybeIncorrect,
864 // The case where the trait method uses `impl Trait`, but the impl method uses
865 // explicit generics.
866 (None, Some(hir::SyntheticTyParamKind::ImplTrait)) => {
867 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
869 let impl_m = impl_m.def_id.as_local()?;
870 let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
871 let input_tys = match impl_m.kind {
872 hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
875 struct Visitor(Option<Span>, hir::def_id::DefId);
876 impl<'v> intravisit::Visitor<'v> for Visitor {
877 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
878 intravisit::walk_ty(self, ty);
879 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
882 if let Res::Def(DefKind::TyParam, def_id) = path.res {
883 if def_id == self.1 {
884 self.0 = Some(ty.span);
889 type Map = intravisit::ErasedMap<'v>;
892 ) -> intravisit::NestedVisitorMap<Self::Map>
894 intravisit::NestedVisitorMap::None
897 let mut visitor = Visitor(None, impl_def_id);
898 for ty in input_tys {
899 intravisit::Visitor::visit_ty(&mut visitor, ty);
901 let span = visitor.0?;
904 impl_m.generics.params.iter().find_map(|param| match param.kind {
905 GenericParamKind::Lifetime { .. } => None,
906 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
907 if param.hir_id == impl_hir_id {
914 let bounds = bounds.first()?.span().to(bounds.last()?.span());
915 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
917 err.multipart_suggestion(
918 "try removing the generic parameter and using `impl Trait` instead",
920 // delete generic parameters
921 (impl_m.generics.span, String::new()),
922 // replace param usage with `impl Trait`
923 (span, format!("impl {}", bounds)),
925 Applicability::MaybeIncorrect,
936 if error_found { Err(ErrorReported) } else { Ok(()) }
939 fn compare_const_param_types<'tcx>(
941 impl_m: &ty::AssocItem,
942 trait_m: &ty::AssocItem,
943 trait_item_span: Option<Span>,
944 ) -> Result<(), ErrorReported> {
945 let const_params_of = |def_id| {
946 tcx.generics_of(def_id).params.iter().filter_map(|param| match param.kind {
947 GenericParamDefKind::Const { .. } => Some(param.def_id),
951 let const_params_impl = const_params_of(impl_m.def_id);
952 let const_params_trait = const_params_of(trait_m.def_id);
954 for (const_param_impl, const_param_trait) in iter::zip(const_params_impl, const_params_trait) {
955 let impl_ty = tcx.type_of(const_param_impl);
956 let trait_ty = tcx.type_of(const_param_trait);
957 if impl_ty != trait_ty {
958 let (impl_span, impl_ident) = match tcx.hir().get_if_local(const_param_impl) {
959 Some(hir::Node::GenericParam(hir::GenericParam { span, name, .. })) => (
962 hir::ParamName::Plain(ident) => Some(ident),
967 "expected GenericParam, found {:?}",
968 other.map_or_else(|| "nothing".to_string(), |n| format!("{:?}", n))
971 let trait_span = match tcx.hir().get_if_local(const_param_trait) {
972 Some(hir::Node::GenericParam(hir::GenericParam { span, .. })) => Some(span),
975 let mut err = struct_span_err!(
979 "method `{}` has an incompatible const parameter type for trait",
983 trait_span.map_or_else(|| trait_item_span.unwrap_or(*impl_span), |span| *span),
985 "the const parameter{} has type `{}`, but the declaration \
986 in trait `{}` has type `{}`",
987 &impl_ident.map_or_else(|| "".to_string(), |ident| format!(" `{}`", ident)),
989 tcx.def_path_str(trait_m.def_id),
994 return Err(ErrorReported);
1001 crate fn compare_const_impl<'tcx>(
1003 impl_c: &ty::AssocItem,
1005 trait_c: &ty::AssocItem,
1006 impl_trait_ref: ty::TraitRef<'tcx>,
1008 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
1010 tcx.infer_ctxt().enter(|infcx| {
1011 let param_env = tcx.param_env(impl_c.def_id);
1012 let inh = Inherited::new(infcx, impl_c.def_id.expect_local());
1013 let infcx = &inh.infcx;
1015 // The below is for the most part highly similar to the procedure
1016 // for methods above. It is simpler in many respects, especially
1017 // because we shouldn't really have to deal with lifetimes or
1018 // predicates. In fact some of this should probably be put into
1019 // shared functions because of DRY violations...
1020 let trait_to_impl_substs = impl_trait_ref.substs;
1022 // Create a parameter environment that represents the implementation's
1024 let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_c.def_id.expect_local());
1026 // Compute placeholder form of impl and trait const tys.
1027 let impl_ty = tcx.type_of(impl_c.def_id);
1028 let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
1029 let mut cause = ObligationCause::new(
1032 ObligationCauseCode::CompareImplConstObligation,
1035 // There is no "body" here, so just pass dummy id.
1037 inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, impl_ty);
1039 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1042 inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, trait_ty);
1044 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1047 .at(&cause, param_env)
1048 .sup(trait_ty, impl_ty)
1049 .map(|ok| inh.register_infer_ok_obligations(ok));
1051 if let Err(terr) = err {
1053 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1057 // Locate the Span containing just the type of the offending impl
1058 match tcx.hir().expect_impl_item(impl_c_hir_id).kind {
1059 ImplItemKind::Const(ref ty, _) => cause.make_mut().span = ty.span,
1060 _ => bug!("{:?} is not a impl const", impl_c),
1063 let mut diag = struct_span_err!(
1067 "implemented const `{}` has an incompatible type for trait",
1071 let trait_c_hir_id =
1072 trait_c.def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id));
1073 let trait_c_span = trait_c_hir_id.map(|trait_c_hir_id| {
1074 // Add a label to the Span containing just the type of the const
1075 match tcx.hir().expect_trait_item(trait_c_hir_id).kind {
1076 TraitItemKind::Const(ref ty, _) => ty.span,
1077 _ => bug!("{:?} is not a trait const", trait_c),
1081 infcx.note_type_err(
1084 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1085 Some(infer::ValuePairs::Types(ExpectedFound {
1094 // Check that all obligations are satisfied by the implementation's
1096 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
1097 infcx.report_fulfillment_errors(errors, None, false);
1101 let fcx = FnCtxt::new(&inh, param_env, impl_c_hir_id);
1102 fcx.regionck_item(impl_c_hir_id, impl_c_span, FxHashSet::default());
1106 crate fn compare_ty_impl<'tcx>(
1108 impl_ty: &ty::AssocItem,
1110 trait_ty: &ty::AssocItem,
1111 impl_trait_ref: ty::TraitRef<'tcx>,
1112 trait_item_span: Option<Span>,
1114 debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1116 let _: Result<(), ErrorReported> = (|| {
1117 compare_number_of_generics(tcx, impl_ty, impl_ty_span, trait_ty, trait_item_span)?;
1119 compare_type_predicate_entailment(tcx, impl_ty, impl_ty_span, trait_ty, impl_trait_ref)?;
1121 check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1125 /// The equivalent of [compare_predicate_entailment], but for associated types
1126 /// instead of associated functions.
1127 fn compare_type_predicate_entailment<'tcx>(
1129 impl_ty: &ty::AssocItem,
1131 trait_ty: &ty::AssocItem,
1132 impl_trait_ref: ty::TraitRef<'tcx>,
1133 ) -> Result<(), ErrorReported> {
1134 let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1135 let trait_to_impl_substs =
1136 impl_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1138 let impl_ty_generics = tcx.generics_of(impl_ty.def_id);
1139 let trait_ty_generics = tcx.generics_of(trait_ty.def_id);
1140 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1141 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1143 check_region_bounds_on_impl_item(
1152 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1154 if impl_ty_own_bounds.is_empty() {
1155 // Nothing to check.
1159 // This `HirId` should be used for the `body_id` field on each
1160 // `ObligationCause` (and the `FnCtxt`). This is what
1161 // `regionck_item` expects.
1162 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1163 let cause = ObligationCause::new(
1166 ObligationCauseCode::CompareImplTypeObligation {
1167 item_name: impl_ty.ident.name,
1168 impl_item_def_id: impl_ty.def_id,
1169 trait_item_def_id: trait_ty.def_id,
1173 debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1175 // The predicates declared by the impl definition, the trait and the
1176 // associated type in the trait are assumed.
1177 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1178 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1181 .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1183 debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1185 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1187 ty::ParamEnv::new(tcx.intern_predicates(&hybrid_preds.predicates), Reveal::UserFacing);
1188 let param_env = traits::normalize_param_env_or_error(
1192 normalize_cause.clone(),
1194 tcx.infer_ctxt().enter(|infcx| {
1195 let inh = Inherited::new(infcx, impl_ty.def_id.expect_local());
1196 let infcx = &inh.infcx;
1198 debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1200 let mut selcx = traits::SelectionContext::new(&infcx);
1202 for predicate in impl_ty_own_bounds.predicates {
1203 let traits::Normalized { value: predicate, obligations } =
1204 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), predicate);
1206 inh.register_predicates(obligations);
1207 inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
1210 // Check that all obligations are satisfied by the implementation's
1212 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
1213 infcx.report_fulfillment_errors(errors, None, false);
1214 return Err(ErrorReported);
1217 // Finally, resolve all regions. This catches wily misuses of
1218 // lifetime parameters.
1219 let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
1220 fcx.regionck_item(impl_ty_hir_id, impl_ty_span, FxHashSet::default());
1226 /// Validate that `ProjectionCandidate`s created for this associated type will
1231 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1233 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1234 /// impl is well-formed we have to prove `S: Copy`.
1236 /// For default associated types the normalization is not possible (the value
1237 /// from the impl could be overridden). We also can't normalize generic
1238 /// associated types (yet) because they contain bound parameters.
1239 #[tracing::instrument(level = "debug", skip(tcx))]
1240 pub fn check_type_bounds<'tcx>(
1242 trait_ty: &ty::AssocItem,
1243 impl_ty: &ty::AssocItem,
1245 impl_trait_ref: ty::TraitRef<'tcx>,
1246 ) -> Result<(), ErrorReported> {
1249 // impl<A, B> Foo<u32> for (A, B) {
1253 // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1254 // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1255 // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1256 // the *trait* with the generic associated type parameters (as bound vars).
1258 // A note regarding the use of bound vars here:
1259 // Imagine as an example
1262 // type Member<C: Eq>;
1265 // impl Family for VecFamily {
1266 // type Member<C: Eq> = i32;
1269 // Here, we would generate
1271 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1273 // when we really would like to generate
1275 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1277 // But, this is probably fine, because although the first clause can be used with types C that
1278 // do not implement Eq, for it to cause some kind of problem, there would have to be a
1279 // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1280 // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1281 // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1282 // the trait (notably, that X: Eq and T: Family).
1283 let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1284 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1285 if let Some(def_id) = defs.parent {
1286 let parent_defs = tcx.generics_of(def_id);
1287 InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1288 tcx.mk_param_from_def(param)
1291 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1292 smallvec::SmallVec::with_capacity(defs.count());
1293 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1294 GenericParamDefKind::Type { .. } => {
1295 let kind = ty::BoundTyKind::Param(param.name);
1296 let bound_var = ty::BoundVariableKind::Ty(kind);
1297 bound_vars.push(bound_var);
1298 tcx.mk_ty(ty::Bound(
1300 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1304 GenericParamDefKind::Lifetime => {
1305 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1306 let bound_var = ty::BoundVariableKind::Region(kind);
1307 bound_vars.push(bound_var);
1308 tcx.mk_region(ty::ReLateBound(
1310 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1314 GenericParamDefKind::Const { .. } => {
1315 let bound_var = ty::BoundVariableKind::Const;
1316 bound_vars.push(bound_var);
1317 tcx.mk_const(ty::Const {
1318 ty: tcx.type_of(param.def_id),
1319 val: ty::ConstKind::Bound(
1321 ty::BoundVar::from_usize(bound_vars.len() - 1),
1327 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
1328 let impl_ty_substs = tcx.intern_substs(&substs);
1330 let rebased_substs =
1331 impl_ty_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1332 let impl_ty_value = tcx.type_of(impl_ty.def_id);
1334 let param_env = tcx.param_env(impl_ty.def_id);
1336 // When checking something like
1338 // trait X { type Y: PartialEq<<Self as X>::Y> }
1339 // impl X for T { default type Y = S; }
1341 // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
1342 // we want <T as X>::Y to normalize to S. This is valid because we are
1343 // checking the default value specifically here. Add this equality to the
1344 // ParamEnv for normalization specifically.
1345 let normalize_param_env = {
1346 let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
1347 match impl_ty_value.kind() {
1348 ty::Projection(proj)
1349 if proj.item_def_id == trait_ty.def_id && proj.substs == rebased_substs =>
1351 // Don't include this predicate if the projected type is
1352 // exactly the same as the projection. This can occur in
1353 // (somewhat dubious) code like this:
1355 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
1357 _ => predicates.push(
1358 ty::Binder::bind_with_vars(
1359 ty::ProjectionPredicate {
1360 projection_ty: ty::ProjectionTy {
1361 item_def_id: trait_ty.def_id,
1362 substs: rebased_substs,
1371 ty::ParamEnv::new(tcx.intern_predicates(&predicates), Reveal::UserFacing)
1373 debug!(?normalize_param_env);
1375 let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1376 let rebased_substs =
1377 impl_ty_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1379 tcx.infer_ctxt().enter(move |infcx| {
1380 let constness = impl_ty
1383 .map(|did| tcx.impl_constness(did))
1384 .unwrap_or(hir::Constness::NotConst);
1386 let inh = Inherited::with_constness(infcx, impl_ty.def_id.expect_local(), constness);
1387 let infcx = &inh.infcx;
1388 let mut selcx = traits::SelectionContext::new(&infcx);
1390 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1391 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1392 let mk_cause = |span| {
1393 ObligationCause::new(
1396 ObligationCauseCode::BindingObligation(trait_ty.def_id, span),
1400 let obligations = tcx
1401 .explicit_item_bounds(trait_ty.def_id)
1403 .map(|&(bound, span)| {
1405 let concrete_ty_bound = bound.subst(tcx, rebased_substs);
1406 debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
1408 traits::Obligation::new(mk_cause(span), param_env, concrete_ty_bound)
1411 debug!("check_type_bounds: item_bounds={:?}", obligations);
1413 for mut obligation in util::elaborate_obligations(tcx, obligations) {
1414 let traits::Normalized { value: normalized_predicate, obligations } = traits::normalize(
1416 normalize_param_env,
1417 normalize_cause.clone(),
1418 obligation.predicate,
1420 debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
1421 obligation.predicate = normalized_predicate;
1423 inh.register_predicates(obligations);
1424 inh.register_predicate(obligation);
1427 // Check that all obligations are satisfied by the implementation's
1429 if let Err(ref errors) =
1430 inh.fulfillment_cx.borrow_mut().select_all_with_constness_or_error(&infcx, constness)
1432 infcx.report_fulfillment_errors(errors, None, false);
1433 return Err(ErrorReported);
1436 // Finally, resolve all regions. This catches wily misuses of
1437 // lifetime parameters.
1438 let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
1439 let implied_bounds = match impl_ty.container {
1440 ty::TraitContainer(_) => FxHashSet::default(),
1441 ty::ImplContainer(def_id) => fcx.impl_implied_bounds(def_id, impl_ty_span),
1443 fcx.regionck_item(impl_ty_hir_id, impl_ty_span, implied_bounds);
1449 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
1450 match impl_item.kind {
1451 ty::AssocKind::Const => "const",
1452 ty::AssocKind::Fn => "method",
1453 ty::AssocKind::Type => "type",