]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_typeck/src/check/compare_method.rs
New upstream version 1.61.0+dfsg1
[rustc.git] / compiler / rustc_typeck / src / check / compare_method.rs
CommitLineData
1b1a35ee 1use crate::errors::LifetimesOrBoundsMismatchOnTrait;
c295e0f8 2use rustc_data_structures::stable_set::FxHashSet;
ee023bcb 3use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, ErrorGuaranteed};
dfeec247
XL
4use rustc_hir as hir;
5use rustc_hir::def::{DefKind, Res};
6use rustc_hir::intravisit;
7use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
74b04a01 8use rustc_infer::infer::{self, InferOk, TyCtxtInferExt};
29967ef6 9use rustc_infer::traits::util;
f035d41b 10use rustc_middle::ty;
ba9703b0 11use rustc_middle::ty::error::{ExpectedFound, TypeError};
3dfed10e 12use rustc_middle::ty::subst::{InternalSubsts, Subst};
ba9703b0 13use rustc_middle::ty::util::ExplicitSelf;
3dfed10e 14use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt};
dfeec247 15use rustc_span::Span;
ba9703b0
XL
16use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
17use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
cdc7bbd5 18use std::iter;
85aaf69f 19
dfeec247 20use super::{potentially_plural_count, FnCtxt, Inherited};
60c5eb7d 21
85aaf69f
SL
22/// Checks that a method from an impl conforms to the signature of
23/// the same method as declared in the trait.
24///
25/// # Parameters
26///
9fa01778
XL
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
dfeec247 31crate fn compare_impl_method<'tcx>(
dc9dc135
XL
32 tcx: TyCtxt<'tcx>,
33 impl_m: &ty::AssocItem,
34 impl_m_span: Span,
35 trait_m: &ty::AssocItem,
36 impl_trait_ref: ty::TraitRef<'tcx>,
37 trait_item_span: Option<Span>,
38) {
dfeec247 39 debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
85aaf69f 40
ba9703b0 41 let impl_m_span = tcx.sess.source_map().guess_head_span(impl_m_span);
2c00a5a8 42
ee023bcb 43 if let Err(_) = compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref) {
c30ab7b3 44 return;
85aaf69f
SL
45 }
46
ee023bcb 47 if let Err(_) = compare_number_of_generics(tcx, impl_m, impl_m_span, trait_m, trait_item_span) {
c30ab7b3
SL
48 return;
49 }
9e0c209e 50
ee023bcb 51 if let Err(_) =
dfeec247
XL
52 compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
53 {
85aaf69f
SL
54 return;
55 }
56
ee023bcb 57 if let Err(_) = compare_synthetic_generics(tcx, impl_m, trait_m) {
abe05a73
XL
58 return;
59 }
60
ee023bcb 61 if let Err(_) = compare_predicate_entailment(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
dfeec247 62 {
85aaf69f
SL
63 return;
64 }
136023e0 65
ee023bcb 66 if let Err(_) = compare_const_param_types(tcx, impl_m, trait_m, trait_item_span) {
136023e0
XL
67 return;
68 }
c30ab7b3
SL
69}
70
dc9dc135
XL
71fn compare_predicate_entailment<'tcx>(
72 tcx: TyCtxt<'tcx>,
73 impl_m: &ty::AssocItem,
74 impl_m_span: Span,
75 trait_m: &ty::AssocItem,
76 impl_trait_ref: ty::TraitRef<'tcx>,
ee023bcb 77) -> Result<(), ErrorGuaranteed> {
476ff2be
SL
78 let trait_to_impl_substs = impl_trait_ref.substs;
79
7cac9316
XL
80 // This node-id should be used for the `body_id` field on each
81 // `ObligationCause` (and the `FnCtxt`). This is what
82 // `regionck_item` expects.
3dfed10e 83 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
7cac9316 84
f035d41b
XL
85 // We sometimes modify the span further down.
86 let mut cause = ObligationCause::new(
87 impl_m_span,
88 impl_m_hir_id,
89 ObligationCauseCode::CompareImplMethodObligation {
ee023bcb 90 impl_item_def_id: impl_m.def_id.expect_local(),
476ff2be 91 trait_item_def_id: trait_m.def_id,
476ff2be 92 },
f035d41b 93 );
85aaf69f
SL
94
95 // This code is best explained by example. Consider a trait:
96 //
f035d41b
XL
97 // trait Trait<'t, T> {
98 // fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
85aaf69f
SL
99 // }
100 //
101 // And an impl:
102 //
103 // impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
f035d41b 104 // fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo;
85aaf69f
SL
105 // }
106 //
107 // We wish to decide if those two method types are compatible.
108 //
109 // We start out with trait_to_impl_substs, that maps the trait
110 // type parameters to impl type parameters. This is taken from the
111 // impl trait reference:
112 //
113 // trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
114 //
115 // We create a mapping `dummy_substs` that maps from the impl type
116 // parameters to fresh types and regions. For type parameters,
117 // this is the identity transform, but we could as well use any
0bf4aa26 118 // placeholder types. For regions, we convert from bound to free
85aaf69f
SL
119 // regions (Note: but only early-bound regions, i.e., those
120 // declared on the impl or used in type parameter bounds).
121 //
f035d41b 122 // impl_to_placeholder_substs = {'i => 'i0, U => U0, N => N0 }
85aaf69f 123 //
f035d41b 124 // Now we can apply placeholder_substs to the type of the impl method
0bf4aa26 125 // to yield a new function type in terms of our fresh, placeholder
85aaf69f
SL
126 // types:
127 //
128 // <'b> fn(t: &'i0 U0, m: &'b) -> Foo
129 //
130 // We now want to extract and substitute the type of the *trait*
131 // method and compare it. To do so, we must create a compound
132 // substitution by combining trait_to_impl_substs and
f035d41b 133 // impl_to_placeholder_substs, and also adding a mapping for the method
85aaf69f
SL
134 // type parameters. We extend the mapping to also include
135 // the method parameters.
136 //
f035d41b 137 // trait_to_placeholder_substs = { T => &'i0 U0, Self => Foo, M => N0 }
85aaf69f
SL
138 //
139 // Applying this to the trait method type yields:
140 //
141 // <'a> fn(t: &'i0 U0, m: &'a) -> Foo
142 //
143 // This type is also the same but the name of the bound region ('a
144 // vs 'b). However, the normal subtyping rules on fn types handle
145 // this kind of equivalency just fine.
146 //
147 // We now use these substitutions to ensure that all declared bounds are
148 // satisfied by the implementation's method.
149 //
150 // We do this by creating a parameter environment which contains a
f035d41b
XL
151 // substitution corresponding to impl_to_placeholder_substs. We then build
152 // trait_to_placeholder_substs and use it to convert the predicates contained
0bf4aa26 153 // in the trait_m.generics to the placeholder form.
85aaf69f
SL
154 //
155 // Finally we register each of these predicates as an obligation in
156 // a fresh FulfillmentCtxt, and invoke select_all_or_error.
157
0bf4aa26 158 // Create mapping from impl to placeholder.
f035d41b 159 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
85aaf69f 160
0bf4aa26 161 // Create mapping from trait to placeholder.
f035d41b
XL
162 let trait_to_placeholder_substs =
163 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container.id(), trait_to_impl_substs);
164 debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_substs);
85aaf69f 165
7cac9316
XL
166 let impl_m_generics = tcx.generics_of(impl_m.def_id);
167 let trait_m_generics = tcx.generics_of(trait_m.def_id);
168 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
169 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
476ff2be 170
c30ab7b3 171 // Check region bounds.
dfeec247
XL
172 check_region_bounds_on_impl_item(
173 tcx,
174 impl_m_span,
175 impl_m,
176 trait_m,
177 &trait_m_generics,
178 &impl_m_generics,
179 )?;
c30ab7b3
SL
180
181 // Create obligations for each predicate declared by the impl
182 // definition in the context of the trait's parameter
183 // environment. We can't just use `impl_env.caller_bounds`,
184 // however, because we want to replace all late-bound regions with
185 // region variables.
7cac9316
XL
186 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
187 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
c30ab7b3
SL
188
189 debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
190
191 // This is the only tricky bit of the new way we check implementation methods
192 // We need to build a set of predicates where only the method-level bounds
193 // are from the trait and we assume all other bounds from the implementation
194 // to be previously satisfied.
195 //
196 // We then register the obligations from the impl_m and check to see
197 // if all constraints hold.
dfeec247
XL
198 hybrid_preds
199 .predicates
f035d41b 200 .extend(trait_m_predicates.instantiate_own(tcx, trait_to_placeholder_substs).predicates);
c30ab7b3 201
0bf4aa26 202 // Construct trait parameter environment and then shift it into the placeholder viewpoint.
c30ab7b3
SL
203 // The key step here is to update the caller_bounds's predicates to be
204 // the new hybrid bounds we computed.
9fa01778 205 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
a2a8927a
XL
206 let param_env = ty::ParamEnv::new(
207 tcx.intern_predicates(&hybrid_preds.predicates),
208 Reveal::UserFacing,
209 hir::Constness::NotConst,
210 );
3c0e092e
XL
211 let param_env =
212 traits::normalize_param_env_or_error(tcx, impl_m.def_id, param_env, normalize_cause);
7cac9316 213
041b39d2 214 tcx.infer_ctxt().enter(|infcx| {
ba9703b0 215 let inh = Inherited::new(infcx, impl_m.def_id.expect_local());
c30ab7b3 216 let infcx = &inh.infcx;
a7813a04 217
f035d41b 218 debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
a7813a04
XL
219
220 let mut selcx = traits::SelectionContext::new(&infcx);
221
f035d41b 222 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
3c0e092e
XL
223 for (predicate, span) in iter::zip(impl_m_own_bounds.predicates, impl_m_own_bounds.spans) {
224 let normalize_cause = traits::ObligationCause::misc(span, impl_m_hir_id);
cc61c64b 225 let traits::Normalized { value: predicate, obligations } =
3c0e092e 226 traits::normalize(&mut selcx, param_env, normalize_cause, predicate);
a7813a04 227
cc61c64b 228 inh.register_predicates(obligations);
ee023bcb
FG
229 let cause = ObligationCause::new(
230 span,
231 impl_m_hir_id,
232 ObligationCauseCode::CompareImplMethodObligation {
233 impl_item_def_id: impl_m.def_id.expect_local(),
234 trait_item_def_id: trait_m.def_id,
235 },
236 );
3c0e092e 237 inh.register_predicate(traits::Obligation::new(cause, param_env, predicate));
a7813a04 238 }
85aaf69f 239
a7813a04
XL
240 // We now need to check that the signature of the impl method is
241 // compatible with that of the trait method. We do this by
242 // checking that `impl_fty <: trait_fty`.
243 //
244 // FIXME. Unfortunately, this doesn't quite work right now because
245 // associated type normalization is not integrated into subtype
246 // checks. For the comparison to be valid, we need to
247 // normalize the associated types in the impl/trait methods
248 // first. However, because function types bind regions, just
249 // calling `normalize_associated_types_in` would have no effect on
250 // any associated types appearing in the fn arguments or return
251 // type.
252
0bf4aa26 253 // Compute placeholder form of impl and trait method tys.
3157f602 254 let tcx = infcx.tcx;
476ff2be 255
c295e0f8 256 let mut wf_tys = FxHashSet::default();
94222f64 257
a1dfa0c6
XL
258 let (impl_sig, _) = infcx.replace_bound_vars_with_fresh_vars(
259 impl_m_span,
260 infer::HigherRankedType,
fc512014 261 tcx.fn_sig(impl_m.def_id),
a1dfa0c6 262 );
3157f602 263 let impl_sig =
fc512014 264 inh.normalize_associated_types_in(impl_m_span, impl_m_hir_id, param_env, impl_sig);
136023e0 265 let impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(impl_sig));
3157f602
XL
266 debug!("compare_impl_method: impl_fty={:?}", impl_fty);
267
94222f64 268 // First liberate late bound regions and subst placeholders
fc512014 269 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, tcx.fn_sig(trait_m.def_id));
f035d41b 270 let trait_sig = trait_sig.subst(tcx, trait_to_placeholder_substs);
3157f602 271 let trait_sig =
fc512014 272 inh.normalize_associated_types_in(impl_m_span, impl_m_hir_id, param_env, trait_sig);
c295e0f8 273 // Add the resulting inputs and output as well-formed.
94222f64 274 wf_tys.extend(trait_sig.inputs_and_output.iter());
136023e0 275 let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
3157f602
XL
276
277 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
278
dfeec247
XL
279 let sub_result = infcx.at(&cause, param_env).sup(trait_fty, impl_fty).map(
280 |InferOk { obligations, .. }| {
3c0e092e
XL
281 // FIXME: We'd want to keep more accurate spans than "the method signature" when
282 // processing the comparison between the trait and impl fn, but we sadly lose them
283 // and point at the whole signature when a trait bound or specific input or output
284 // type would be more appropriate. In other places we have a `Vec<Span>`
285 // corresponding to their `Vec<Predicate>`, but we don't have that here.
286 // Fixing this would improve the output of test `issue-83765.rs`.
dfeec247
XL
287 inh.register_predicates(obligations);
288 },
289 );
c30ab7b3
SL
290
291 if let Err(terr) = sub_result {
dfeec247
XL
292 debug!("sub_types failed: impl ty {:?}, trait ty {:?}", impl_fty, trait_fty);
293
cdc7bbd5
XL
294 let (impl_err_span, trait_err_span) =
295 extract_spans_for_error_reporting(&infcx, &terr, &cause, impl_m, trait_m);
dfeec247 296
a2a8927a 297 cause.span = impl_err_span;
dfeec247
XL
298
299 let mut diag = struct_span_err!(
300 tcx.sess,
301 cause.span(tcx),
302 E0053,
303 "method `{}` has an incompatible type for trait",
5099ac24 304 trait_m.name
dfeec247 305 );
cdc7bbd5
XL
306 match &terr {
307 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
308 if trait_m.fn_has_self_parameter =>
309 {
310 let ty = trait_sig.inputs()[0];
311 let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty())
dfeec247 312 {
cdc7bbd5
XL
313 ExplicitSelf::ByValue => "self".to_owned(),
314 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
315 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => {
316 "&mut self".to_owned()
317 }
318 _ => format!("self: {}", ty),
319 };
320
321 // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
322 // span points only at the type `Box<Self`>, but we want to cover the whole
323 // argument pattern and type.
a2a8927a 324 let span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
cdc7bbd5
XL
325 ImplItemKind::Fn(ref sig, body) => tcx
326 .hir()
327 .body_param_names(body)
328 .zip(sig.decl.inputs.iter())
329 .map(|(param, ty)| param.span.to(ty.span))
330 .next()
331 .unwrap_or(impl_err_span),
332 _ => bug!("{:?} is not a method", impl_m),
333 };
334
335 diag.span_suggestion(
336 span,
337 "change the self-receiver type to match the trait",
338 sugg,
339 Applicability::MachineApplicable,
340 );
341 }
342 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
343 if trait_sig.inputs().len() == *i {
344 // Suggestion to change output type. We do not suggest in `async` functions
345 // to avoid complex logic or incorrect output.
a2a8927a 346 match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
cdc7bbd5
XL
347 ImplItemKind::Fn(ref sig, _)
348 if sig.header.asyncness == hir::IsAsync::NotAsync =>
349 {
350 let msg = "change the output type to match the trait";
351 let ap = Applicability::MachineApplicable;
352 match sig.decl.output {
353 hir::FnRetTy::DefaultReturn(sp) => {
354 let sugg = format!("-> {} ", trait_sig.output());
355 diag.span_suggestion_verbose(sp, msg, sugg, ap);
356 }
357 hir::FnRetTy::Return(hir_ty) => {
358 let sugg = trait_sig.output().to_string();
359 diag.span_suggestion(hir_ty.span, msg, sugg, ap);
360 }
361 };
362 }
363 _ => {}
364 };
365 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
9fa01778 366 diag.span_suggestion(
8faf50e0 367 impl_err_span,
cdc7bbd5
XL
368 "change the parameter type to match the trait",
369 trait_ty.to_string(),
0bf4aa26 370 Applicability::MachineApplicable,
8faf50e0
XL
371 );
372 }
373 }
cdc7bbd5 374 _ => {}
8faf50e0 375 }
c30ab7b3 376
dfeec247
XL
377 infcx.note_type_err(
378 &mut diag,
379 &cause,
380 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
5099ac24
FG
381 Some(infer::ValuePairs::Terms(ExpectedFound {
382 expected: trait_fty.into(),
383 found: impl_fty.into(),
dfeec247
XL
384 })),
385 &terr,
a2a8927a 386 false,
dfeec247 387 );
ee023bcb
FG
388
389 return Err(diag.emit());
a7813a04 390 }
85aaf69f 391
a7813a04
XL
392 // Check that all obligations are satisfied by the implementation's
393 // version.
3c0e092e
XL
394 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
395 if !errors.is_empty() {
ee023bcb
FG
396 let reported = infcx.report_fulfillment_errors(&errors, None, false);
397 return Err(reported);
85aaf69f 398 }
85aaf69f 399
a7813a04 400 // Finally, resolve all regions. This catches wily misuses of
c30ab7b3 401 // lifetime parameters.
9fa01778 402 let fcx = FnCtxt::new(&inh, param_env, impl_m_hir_id);
c295e0f8 403 fcx.regionck_item(impl_m_hir_id, impl_m_span, wf_tys);
85aaf69f 404
c30ab7b3
SL
405 Ok(())
406 })
407}
408
dfeec247 409fn check_region_bounds_on_impl_item<'tcx>(
dc9dc135
XL
410 tcx: TyCtxt<'tcx>,
411 span: Span,
412 impl_m: &ty::AssocItem,
413 trait_m: &ty::AssocItem,
414 trait_generics: &ty::Generics,
415 impl_generics: &ty::Generics,
ee023bcb 416) -> Result<(), ErrorGuaranteed> {
94b46f34
XL
417 let trait_params = trait_generics.own_counts().lifetimes;
418 let impl_params = impl_generics.own_counts().lifetimes;
c30ab7b3 419
dfeec247
XL
420 debug!(
421 "check_region_bounds_on_impl_item: \
c30ab7b3 422 trait_generics={:?} \
dfeec247
XL
423 impl_generics={:?}",
424 trait_generics, impl_generics
425 );
c30ab7b3
SL
426
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.
94b46f34 436 if trait_params != impl_params {
dfeec247 437 let item_kind = assoc_item_kind_str(impl_m);
ba9703b0 438 let def_span = tcx.sess.source_map().guess_head_span(span);
5099ac24
FG
439 let span = impl_m
440 .def_id
441 .as_local()
442 .and_then(|did| tcx.hir().get_generics(did))
443 .map_or(def_span, |g| g.span);
5869c6ff 444 let generics_span = tcx.hir().span_if_local(trait_m.def_id).map(|sp| {
1b1a35ee 445 let def_sp = tcx.sess.source_map().guess_head_span(sp);
5099ac24
FG
446 trait_m
447 .def_id
448 .as_local()
449 .and_then(|did| tcx.hir().get_generics(did))
450 .map_or(def_sp, |g| g.span)
5869c6ff
XL
451 });
452
ee023bcb 453 let reported = tcx.sess.emit_err(LifetimesOrBoundsMismatchOnTrait {
8faf50e0 454 span,
dfeec247 455 item_kind,
5099ac24 456 ident: impl_m.ident(tcx),
1b1a35ee
XL
457 generics_span,
458 });
ee023bcb 459 return Err(reported);
85aaf69f 460 }
9e0c209e 461
0bf4aa26 462 Ok(())
c30ab7b3 463}
9e0c209e 464
3c0e092e 465#[instrument(level = "debug", skip(infcx))]
dc9dc135
XL
466fn extract_spans_for_error_reporting<'a, 'tcx>(
467 infcx: &infer::InferCtxt<'a, 'tcx>,
dc9dc135
XL
468 terr: &TypeError<'_>,
469 cause: &ObligationCause<'tcx>,
470 impl_m: &ty::AssocItem,
dc9dc135 471 trait_m: &ty::AssocItem,
dc9dc135 472) -> (Span, Option<Span>) {
c30ab7b3 473 let tcx = infcx.tcx;
a2a8927a 474 let mut impl_args = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
cdc7bbd5
XL
475 ImplItemKind::Fn(ref sig, _) => {
476 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
c30ab7b3
SL
477 }
478 _ => bug!("{:?} is not a method", impl_m),
479 };
a2a8927a
XL
480 let trait_args =
481 trait_m.def_id.as_local().map(|def_id| match tcx.hir().expect_trait_item(def_id).kind {
cdc7bbd5
XL
482 TraitItemKind::Fn(ref sig, _) => {
483 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
c30ab7b3 484 }
cdc7bbd5 485 _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
a2a8927a 486 });
9e0c209e 487
cdc7bbd5
XL
488 match *terr {
489 TypeError::ArgumentMutability(i) => {
490 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
491 }
492 TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
493 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
c30ab7b3 494 }
48663c56 495 _ => (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)),
c30ab7b3
SL
496 }
497}
498
dc9dc135
XL
499fn compare_self_type<'tcx>(
500 tcx: TyCtxt<'tcx>,
501 impl_m: &ty::AssocItem,
502 impl_m_span: Span,
503 trait_m: &ty::AssocItem,
504 impl_trait_ref: ty::TraitRef<'tcx>,
ee023bcb 505) -> Result<(), ErrorGuaranteed> {
c30ab7b3
SL
506 // Try to give more informative error messages about self typing
507 // mismatches. Note that any mismatch will also be detected
508 // below, where we construct a canonical function type that
509 // includes the self parameter as a normal parameter. It's just
510 // that the error messages you get out of this code are a bit more
511 // inscrutable, particularly for cases where one method has no
512 // self.
476ff2be 513
dc9dc135 514 let self_string = |method: &ty::AssocItem| {
476ff2be
SL
515 let untransformed_self_ty = match method.container {
516 ty::ImplContainer(_) => impl_trait_ref.self_ty(),
dfeec247 517 ty::TraitContainer(_) => tcx.types.self_param,
476ff2be 518 };
fc512014 519 let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
0531ce1d 520 let param_env = ty::ParamEnv::reveal_all();
abe05a73
XL
521
522 tcx.infer_ctxt().enter(|infcx| {
fc512014 523 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
abe05a73
XL
524 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
525 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
0bf4aa26 526 ExplicitSelf::ByValue => "self".to_owned(),
dfeec247
XL
527 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
528 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
529 _ => format!("self: {}", self_arg_ty),
abe05a73
XL
530 }
531 })
476ff2be
SL
532 };
533
ba9703b0 534 match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
476ff2be
SL
535 (false, false) | (true, true) => {}
536
537 (false, true) => {
538 let self_descr = self_string(impl_m);
dfeec247
XL
539 let mut err = struct_span_err!(
540 tcx.sess,
541 impl_m_span,
542 E0185,
cdc7bbd5 543 "method `{}` has a `{}` declaration in the impl, but not in the trait",
5099ac24 544 trait_m.name,
dfeec247
XL
545 self_descr
546 );
7cac9316 547 err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
0731742a 548 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
2c00a5a8
XL
549 err.span_label(span, format!("trait method declared without `{}`", self_descr));
550 } else {
5099ac24 551 err.note_trait_signature(trait_m.name.to_string(), trait_m.signature(tcx));
c30ab7b3 552 }
ee023bcb
FG
553 let reported = err.emit();
554 return Err(reported);
c30ab7b3 555 }
476ff2be
SL
556
557 (true, false) => {
558 let self_descr = self_string(trait_m);
dfeec247
XL
559 let mut err = struct_span_err!(
560 tcx.sess,
561 impl_m_span,
562 E0186,
cdc7bbd5 563 "method `{}` has a `{}` declaration in the trait, but not in the impl",
5099ac24 564 trait_m.name,
dfeec247
XL
565 self_descr
566 );
2c00a5a8 567 err.span_label(impl_m_span, format!("expected `{}` in impl", self_descr));
0731742a 568 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
7cac9316
XL
569 err.span_label(span, format!("`{}` used in trait", self_descr));
570 } else {
5099ac24 571 err.note_trait_signature(trait_m.name.to_string(), trait_m.signature(tcx));
c30ab7b3 572 }
ee023bcb
FG
573 let reported = err.emit();
574 return Err(reported);
c30ab7b3 575 }
c30ab7b3
SL
576 }
577
578 Ok(())
579}
580
dc9dc135
XL
581fn compare_number_of_generics<'tcx>(
582 tcx: TyCtxt<'tcx>,
583 impl_: &ty::AssocItem,
584 _impl_span: Span,
585 trait_: &ty::AssocItem,
532ac7d7 586 trait_span: Option<Span>,
ee023bcb 587) -> Result<(), ErrorGuaranteed> {
532ac7d7
XL
588 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
589 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
590
591 let matchings = [
592 ("type", trait_own_counts.types, impl_own_counts.types),
593 ("const", trait_own_counts.consts, impl_own_counts.consts),
594 ];
595
dfeec247
XL
596 let item_kind = assoc_item_kind_str(impl_);
597
ee023bcb 598 let mut err_occurred = None;
136023e0 599 for (kind, trait_count, impl_count) in matchings {
532ac7d7 600 if impl_count != trait_count {
f9f354fc 601 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
a2a8927a 602 let trait_item = tcx.hir().expect_trait_item(def_id);
f9f354fc
XL
603 if trait_item.generics.params.is_empty() {
604 (Some(vec![trait_item.generics.span]), vec![])
dc9dc135 605 } else {
f9f354fc
XL
606 let arg_spans: Vec<Span> =
607 trait_item.generics.params.iter().map(|p| p.span).collect();
608 let impl_trait_spans: Vec<Span> = trait_item
609 .generics
610 .params
611 .iter()
612 .filter_map(|p| match p.kind {
3c0e092e 613 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
f9f354fc
XL
614 _ => None,
615 })
616 .collect();
617 (Some(arg_spans), impl_trait_spans)
618 }
619 } else {
620 (trait_span.map(|s| vec![s]), vec![])
621 };
9e0c209e 622
a2a8927a 623 let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
dfeec247
XL
624 let impl_item_impl_trait_spans: Vec<Span> = impl_item
625 .generics
626 .params
627 .iter()
dc9dc135 628 .filter_map(|p| match p.kind {
3c0e092e 629 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
dc9dc135 630 _ => None,
dfeec247
XL
631 })
632 .collect();
dc9dc135
XL
633 let spans = impl_item.generics.spans();
634 let span = spans.primary_span();
635
532ac7d7 636 let mut err = tcx.sess.struct_span_err_with_code(
dc9dc135 637 spans,
532ac7d7 638 &format!(
dfeec247 639 "{} `{}` has {} {kind} parameter{} but its trait \
532ac7d7 640 declaration has {} {kind} parameter{}",
dfeec247 641 item_kind,
5099ac24 642 trait_.name,
532ac7d7 643 impl_count,
60c5eb7d 644 pluralize!(impl_count),
532ac7d7 645 trait_count,
60c5eb7d 646 pluralize!(trait_count),
532ac7d7
XL
647 kind = kind,
648 ),
649 DiagnosticId::Error("E0049".into()),
650 );
c30ab7b3 651
532ac7d7 652 let mut suffix = None;
c30ab7b3 653
dc9dc135
XL
654 if let Some(spans) = trait_spans {
655 let mut spans = spans.iter();
656 if let Some(span) = spans.next() {
dfeec247
XL
657 err.span_label(
658 *span,
659 format!(
660 "expected {} {} parameter{}",
661 trait_count,
662 kind,
663 pluralize!(trait_count),
664 ),
665 );
dc9dc135
XL
666 }
667 for span in spans {
668 err.span_label(*span, "");
669 }
532ac7d7
XL
670 } else {
671 suffix = Some(format!(", expected {}", trait_count));
672 }
c30ab7b3 673
dc9dc135 674 if let Some(span) = span {
dfeec247
XL
675 err.span_label(
676 span,
677 format!(
678 "found {} {} parameter{}{}",
679 impl_count,
680 kind,
681 pluralize!(impl_count),
ba9703b0 682 suffix.unwrap_or_else(String::new),
dfeec247
XL
683 ),
684 );
dc9dc135
XL
685 }
686
687 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
688 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
689 }
c30ab7b3 690
ee023bcb
FG
691 let reported = err.emit();
692 err_occurred = Some(reported);
532ac7d7 693 }
c30ab7b3
SL
694 }
695
ee023bcb 696 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
c30ab7b3
SL
697}
698
dc9dc135
XL
699fn compare_number_of_method_arguments<'tcx>(
700 tcx: TyCtxt<'tcx>,
701 impl_m: &ty::AssocItem,
702 impl_m_span: Span,
703 trait_m: &ty::AssocItem,
704 trait_item_span: Option<Span>,
ee023bcb 705) -> Result<(), ErrorGuaranteed> {
041b39d2
XL
706 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
707 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
8bb4bdeb
XL
708 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
709 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
476ff2be 710 if trait_number_args != impl_number_args {
f9f354fc 711 let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
a2a8927a 712 match tcx.hir().expect_trait_item(def_id).kind {
ba9703b0 713 TraitItemKind::Fn(ref trait_m_sig, _) => {
dfeec247 714 let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
0731742a
XL
715 if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
716 Some(if pos == 0 {
717 arg.span
718 } else {
94222f64 719 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
0731742a 720 })
c30ab7b3
SL
721 } else {
722 trait_item_span
723 }
724 }
725 _ => bug!("{:?} is not a method", impl_m),
726 }
727 } else {
728 trait_item_span
729 };
a2a8927a 730 let impl_span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
ba9703b0 731 ImplItemKind::Fn(ref impl_m_sig, _) => {
dfeec247 732 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
0731742a
XL
733 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
734 if pos == 0 {
735 arg.span
736 } else {
94222f64 737 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
0731742a 738 }
9e0c209e 739 } else {
c30ab7b3 740 impl_m_span
9e0c209e
SL
741 }
742 }
c30ab7b3
SL
743 _ => bug!("{:?} is not a method", impl_m),
744 };
dfeec247
XL
745 let mut err = struct_span_err!(
746 tcx.sess,
747 impl_span,
748 E0050,
a2a8927a 749 "method `{}` has {} but the declaration in trait `{}` has {}",
5099ac24 750 trait_m.name,
dfeec247
XL
751 potentially_plural_count(impl_number_args, "parameter"),
752 tcx.def_path_str(trait_m.def_id),
753 trait_number_args
754 );
c30ab7b3 755 if let Some(trait_span) = trait_span {
dfeec247
XL
756 err.span_label(
757 trait_span,
758 format!(
759 "trait requires {}",
760 potentially_plural_count(trait_number_args, "parameter")
761 ),
762 );
7cac9316 763 } else {
5099ac24 764 err.note_trait_signature(trait_m.name.to_string(), trait_m.signature(tcx));
9e0c209e 765 }
dfeec247
XL
766 err.span_label(
767 impl_span,
768 format!(
769 "expected {}, found {}",
770 potentially_plural_count(trait_number_args, "parameter"),
771 impl_number_args
772 ),
773 );
ee023bcb
FG
774 let reported = err.emit();
775 return Err(reported);
9e0c209e 776 }
c30ab7b3
SL
777
778 Ok(())
85aaf69f 779}
d9579d0f 780
dc9dc135
XL
781fn compare_synthetic_generics<'tcx>(
782 tcx: TyCtxt<'tcx>,
783 impl_m: &ty::AssocItem,
784 trait_m: &ty::AssocItem,
ee023bcb 785) -> Result<(), ErrorGuaranteed> {
abe05a73 786 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
94b46f34 787 // 1. Better messages for the span labels
abe05a73 788 // 2. Explanation as to what is going on
abe05a73
XL
789 // If we get here, we already have the same number of generics, so the zip will
790 // be okay.
ee023bcb 791 let mut error_found = None;
abe05a73
XL
792 let impl_m_generics = tcx.generics_of(impl_m.def_id);
793 let trait_m_generics = tcx.generics_of(trait_m.def_id);
8faf50e0
XL
794 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
795 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
cdc7bbd5 796 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
94b46f34 797 });
dfeec247
XL
798 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
799 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
cdc7bbd5 800 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
94b46f34 801 });
dfeec247 802 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
cdc7bbd5 803 iter::zip(impl_m_type_params, trait_m_type_params)
0bf4aa26 804 {
94b46f34 805 if impl_synthetic != trait_synthetic {
3dfed10e 806 let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_def_id.expect_local());
dc9dc135 807 let impl_span = tcx.hir().span(impl_hir_id);
94b46f34 808 let trait_span = tcx.def_span(trait_def_id);
dfeec247
XL
809 let mut err = struct_span_err!(
810 tcx.sess,
811 impl_span,
812 E0643,
813 "method `{}` has incompatible signature for trait",
5099ac24 814 trait_m.name
dfeec247 815 );
94b46f34
XL
816 err.span_label(trait_span, "declaration in trait here");
817 match (impl_synthetic, trait_synthetic) {
818 // The case where the impl method uses `impl Trait` but the trait method uses
819 // explicit generics
3c0e092e 820 (true, false) => {
94b46f34
XL
821 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
822 (|| {
823 // try taking the name from the trait impl
824 // FIXME: this is obviously suboptimal since the name can already be used
825 // as another generic argument
dfeec247 826 let new_name = tcx.sess.source_map().span_to_snippet(trait_span).ok()?;
6a06907d
XL
827 let trait_m = trait_m.def_id.as_local()?;
828 let trait_m = tcx.hir().trait_item(hir::TraitItemId { def_id: trait_m });
94b46f34 829
6a06907d
XL
830 let impl_m = impl_m.def_id.as_local()?;
831 let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
94b46f34
XL
832
833 // in case there are no generics, take the spot between the function name
834 // and the opening paren of the argument list
dfeec247
XL
835 let new_generics_span =
836 tcx.sess.source_map().generate_fn_name_span(impl_span)?.shrink_to_hi();
94b46f34 837 // in case there are generics, just replace them
dfeec247
XL
838 let generics_span =
839 impl_m.generics.span.substitute_dummy(new_generics_span);
94b46f34 840 // replace with the generics from the trait
dfeec247
XL
841 let new_generics =
842 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
94b46f34 843
9fa01778 844 err.multipart_suggestion(
94b46f34
XL
845 "try changing the `impl Trait` argument to a generic parameter",
846 vec![
847 // replace `impl Trait` with `T`
848 (impl_span, new_name),
849 // replace impl method generics with trait method generics
850 // This isn't quite right, as users might have changed the names
851 // of the generics, but it works for the common case
852 (generics_span, new_generics),
853 ],
0bf4aa26 854 Applicability::MaybeIncorrect,
94b46f34
XL
855 );
856 Some(())
857 })();
dfeec247 858 }
94b46f34
XL
859 // The case where the trait method uses `impl Trait`, but the impl method uses
860 // explicit generics.
3c0e092e 861 (false, true) => {
94b46f34
XL
862 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
863 (|| {
6a06907d
XL
864 let impl_m = impl_m.def_id.as_local()?;
865 let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
e74abb32 866 let input_tys = match impl_m.kind {
ba9703b0 867 hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
94b46f34
XL
868 _ => unreachable!(),
869 };
870 struct Visitor(Option<Span>, hir::def_id::DefId);
dfeec247
XL
871 impl<'v> intravisit::Visitor<'v> for Visitor {
872 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
873 intravisit::walk_ty(self, ty);
874 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
875 ty.kind
0bf4aa26 876 {
48663c56 877 if let Res::Def(DefKind::TyParam, def_id) = path.res {
0bf4aa26
XL
878 if def_id == self.1 {
879 self.0 = Some(ty.span);
94b46f34 880 }
0bf4aa26 881 }
94b46f34
XL
882 }
883 }
94b46f34
XL
884 }
885 let mut visitor = Visitor(None, impl_def_id);
886 for ty in input_tys {
dfeec247 887 intravisit::Visitor::visit_ty(&mut visitor, ty);
94b46f34
XL
888 }
889 let span = visitor.0?;
890
dfeec247
XL
891 let bounds =
892 impl_m.generics.params.iter().find_map(|param| match param.kind {
8faf50e0 893 GenericParamKind::Lifetime { .. } => None,
dfeec247 894 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
9fa01778 895 if param.hir_id == impl_hir_id {
8faf50e0 896 Some(&param.bounds)
94b46f34
XL
897 } else {
898 None
899 }
8faf50e0 900 }
dfeec247 901 })?;
8faf50e0 902 let bounds = bounds.first()?.span().to(bounds.last()?.span());
dfeec247 903 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
94b46f34 904
9fa01778 905 err.multipart_suggestion(
94b46f34
XL
906 "try removing the generic parameter and using `impl Trait` instead",
907 vec![
908 // delete generic parameters
909 (impl_m.generics.span, String::new()),
910 // replace param usage with `impl Trait`
911 (span, format!("impl {}", bounds)),
912 ],
0bf4aa26 913 Applicability::MaybeIncorrect,
94b46f34
XL
914 );
915 Some(())
916 })();
dfeec247 917 }
94b46f34
XL
918 _ => unreachable!(),
919 }
ee023bcb
FG
920 let reported = err.emit();
921 error_found = Some(reported);
abe05a73
XL
922 }
923 }
ee023bcb 924 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
abe05a73
XL
925}
926
136023e0
XL
927fn compare_const_param_types<'tcx>(
928 tcx: TyCtxt<'tcx>,
929 impl_m: &ty::AssocItem,
930 trait_m: &ty::AssocItem,
931 trait_item_span: Option<Span>,
ee023bcb 932) -> Result<(), ErrorGuaranteed> {
136023e0
XL
933 let const_params_of = |def_id| {
934 tcx.generics_of(def_id).params.iter().filter_map(|param| match param.kind {
935 GenericParamDefKind::Const { .. } => Some(param.def_id),
936 _ => None,
937 })
938 };
939 let const_params_impl = const_params_of(impl_m.def_id);
940 let const_params_trait = const_params_of(trait_m.def_id);
941
942 for (const_param_impl, const_param_trait) in iter::zip(const_params_impl, const_params_trait) {
943 let impl_ty = tcx.type_of(const_param_impl);
944 let trait_ty = tcx.type_of(const_param_trait);
945 if impl_ty != trait_ty {
946 let (impl_span, impl_ident) = match tcx.hir().get_if_local(const_param_impl) {
947 Some(hir::Node::GenericParam(hir::GenericParam { span, name, .. })) => (
948 span,
949 match name {
950 hir::ParamName::Plain(ident) => Some(ident),
951 _ => None,
952 },
953 ),
954 other => bug!(
955 "expected GenericParam, found {:?}",
956 other.map_or_else(|| "nothing".to_string(), |n| format!("{:?}", n))
957 ),
958 };
959 let trait_span = match tcx.hir().get_if_local(const_param_trait) {
960 Some(hir::Node::GenericParam(hir::GenericParam { span, .. })) => Some(span),
961 _ => None,
962 };
963 let mut err = struct_span_err!(
964 tcx.sess,
965 *impl_span,
966 E0053,
967 "method `{}` has an incompatible const parameter type for trait",
5099ac24 968 trait_m.name
136023e0
XL
969 );
970 err.span_note(
971 trait_span.map_or_else(|| trait_item_span.unwrap_or(*impl_span), |span| *span),
972 &format!(
973 "the const parameter{} has type `{}`, but the declaration \
974 in trait `{}` has type `{}`",
975 &impl_ident.map_or_else(|| "".to_string(), |ident| format!(" `{}`", ident)),
976 impl_ty,
977 tcx.def_path_str(trait_m.def_id),
978 trait_ty
979 ),
980 );
ee023bcb
FG
981 let reported = err.emit();
982 return Err(reported);
136023e0
XL
983 }
984 }
985
986 Ok(())
987}
988
dfeec247 989crate fn compare_const_impl<'tcx>(
dc9dc135
XL
990 tcx: TyCtxt<'tcx>,
991 impl_c: &ty::AssocItem,
992 impl_c_span: Span,
993 trait_c: &ty::AssocItem,
994 impl_trait_ref: ty::TraitRef<'tcx>,
995) {
c30ab7b3 996 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
d9579d0f 997
041b39d2 998 tcx.infer_ctxt().enter(|infcx| {
532ac7d7 999 let param_env = tcx.param_env(impl_c.def_id);
ba9703b0 1000 let inh = Inherited::new(infcx, impl_c.def_id.expect_local());
cc61c64b 1001 let infcx = &inh.infcx;
a7813a04
XL
1002
1003 // The below is for the most part highly similar to the procedure
1004 // for methods above. It is simpler in many respects, especially
1005 // because we shouldn't really have to deal with lifetimes or
1006 // predicates. In fact some of this should probably be put into
1007 // shared functions because of DRY violations...
476ff2be 1008 let trait_to_impl_substs = impl_trait_ref.substs;
a7813a04
XL
1009
1010 // Create a parameter environment that represents the implementation's
1011 // method.
3dfed10e 1012 let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_c.def_id.expect_local());
a7813a04 1013
0bf4aa26 1014 // Compute placeholder form of impl and trait const tys.
7cac9316
XL
1015 let impl_ty = tcx.type_of(impl_c.def_id);
1016 let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
f035d41b
XL
1017 let mut cause = ObligationCause::new(
1018 impl_c_span,
1019 impl_c_hir_id,
1020 ObligationCauseCode::CompareImplConstObligation,
1021 );
a7813a04 1022
cc61c64b 1023 // There is no "body" here, so just pass dummy id.
dfeec247 1024 let impl_ty =
fc512014 1025 inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, impl_ty);
c30ab7b3 1026
cc61c64b 1027 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
c30ab7b3 1028
dfeec247 1029 let trait_ty =
fc512014 1030 inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, trait_ty);
c30ab7b3 1031
cc61c64b 1032 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
a7813a04 1033
dfeec247
XL
1034 let err = infcx
1035 .at(&cause, param_env)
1036 .sup(trait_ty, impl_ty)
1037 .map(|ok| inh.register_infer_ok_obligations(ok));
d9579d0f 1038
a7813a04 1039 if let Err(terr) = err {
dfeec247
XL
1040 debug!(
1041 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1042 impl_ty, trait_ty
1043 );
5bcae85e
SL
1044
1045 // Locate the Span containing just the type of the offending impl
a2a8927a
XL
1046 match tcx.hir().expect_impl_item(impl_c.def_id.expect_local()).kind {
1047 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
c30ab7b3 1048 _ => bug!("{:?} is not a impl const", impl_c),
5bcae85e
SL
1049 }
1050
dfeec247
XL
1051 let mut diag = struct_span_err!(
1052 tcx.sess,
1053 cause.span,
1054 E0326,
cdc7bbd5 1055 "implemented const `{}` has an incompatible type for trait",
5099ac24 1056 trait_c.name
dfeec247 1057 );
5bcae85e 1058
a2a8927a 1059 let trait_c_span = trait_c.def_id.as_local().map(|trait_c_def_id| {
7cac9316 1060 // Add a label to the Span containing just the type of the const
a2a8927a 1061 match tcx.hir().expect_trait_item(trait_c_def_id).kind {
7cac9316
XL
1062 TraitItemKind::Const(ref ty, _) => ty.span,
1063 _ => bug!("{:?} is not a trait const", trait_c),
1064 }
1065 });
5bcae85e 1066
dfeec247
XL
1067 infcx.note_type_err(
1068 &mut diag,
1069 &cause,
1070 trait_c_span.map(|span| (span, "type in trait".to_owned())),
5099ac24
FG
1071 Some(infer::ValuePairs::Terms(ExpectedFound {
1072 expected: trait_ty.into(),
1073 found: impl_ty.into(),
dfeec247
XL
1074 })),
1075 &terr,
a2a8927a 1076 false,
dfeec247 1077 );
5bcae85e 1078 diag.emit();
d9579d0f 1079 }
cc61c64b 1080
7cac9316
XL
1081 // Check that all obligations are satisfied by the implementation's
1082 // version.
3c0e092e
XL
1083 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
1084 if !errors.is_empty() {
1085 infcx.report_fulfillment_errors(&errors, None, false);
7cac9316
XL
1086 return;
1087 }
1088
9fa01778 1089 let fcx = FnCtxt::new(&inh, param_env, impl_c_hir_id);
c295e0f8 1090 fcx.regionck_item(impl_c_hir_id, impl_c_span, FxHashSet::default());
a7813a04 1091 });
d9579d0f 1092}
dfeec247
XL
1093
1094crate fn compare_ty_impl<'tcx>(
1095 tcx: TyCtxt<'tcx>,
1096 impl_ty: &ty::AssocItem,
1097 impl_ty_span: Span,
1098 trait_ty: &ty::AssocItem,
1099 impl_trait_ref: ty::TraitRef<'tcx>,
1100 trait_item_span: Option<Span>,
1101) {
1102 debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1103
ee023bcb 1104 let _: Result<(), ErrorGuaranteed> = (|| {
dfeec247
XL
1105 compare_number_of_generics(tcx, impl_ty, impl_ty_span, trait_ty, trait_item_span)?;
1106
a2a8927a
XL
1107 let sp = tcx.def_span(impl_ty.def_id);
1108 compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;
f035d41b 1109
29967ef6 1110 check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
dfeec247
XL
1111 })();
1112}
1113
1114/// The equivalent of [compare_predicate_entailment], but for associated types
1115/// instead of associated functions.
f035d41b 1116fn compare_type_predicate_entailment<'tcx>(
dfeec247
XL
1117 tcx: TyCtxt<'tcx>,
1118 impl_ty: &ty::AssocItem,
1119 impl_ty_span: Span,
1120 trait_ty: &ty::AssocItem,
1121 impl_trait_ref: ty::TraitRef<'tcx>,
ee023bcb 1122) -> Result<(), ErrorGuaranteed> {
dfeec247
XL
1123 let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1124 let trait_to_impl_substs =
1125 impl_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1126
1127 let impl_ty_generics = tcx.generics_of(impl_ty.def_id);
1128 let trait_ty_generics = tcx.generics_of(trait_ty.def_id);
1129 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1130 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1131
1132 check_region_bounds_on_impl_item(
1133 tcx,
1134 impl_ty_span,
1135 impl_ty,
1136 trait_ty,
1137 &trait_ty_generics,
1138 &impl_ty_generics,
1139 )?;
1140
1141 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1142
1143 if impl_ty_own_bounds.is_empty() {
1144 // Nothing to check.
1145 return Ok(());
1146 }
1147
1148 // This `HirId` should be used for the `body_id` field on each
1149 // `ObligationCause` (and the `FnCtxt`). This is what
1150 // `regionck_item` expects.
3dfed10e 1151 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
f035d41b
XL
1152 let cause = ObligationCause::new(
1153 impl_ty_span,
1154 impl_ty_hir_id,
1155 ObligationCauseCode::CompareImplTypeObligation {
ee023bcb 1156 impl_item_def_id: impl_ty.def_id.expect_local(),
dfeec247
XL
1157 trait_item_def_id: trait_ty.def_id,
1158 },
f035d41b 1159 );
dfeec247
XL
1160
1161 debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1162
1163 // The predicates declared by the impl definition, the trait and the
1164 // associated type in the trait are assumed.
1165 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1166 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1167 hybrid_preds
1168 .predicates
1169 .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1170
1171 debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1172
1173 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
a2a8927a
XL
1174 let param_env = ty::ParamEnv::new(
1175 tcx.intern_predicates(&hybrid_preds.predicates),
1176 Reveal::UserFacing,
1177 hir::Constness::NotConst,
1178 );
dfeec247
XL
1179 let param_env = traits::normalize_param_env_or_error(
1180 tcx,
1181 impl_ty.def_id,
1182 param_env,
1183 normalize_cause.clone(),
1184 );
1185 tcx.infer_ctxt().enter(|infcx| {
ba9703b0 1186 let inh = Inherited::new(infcx, impl_ty.def_id.expect_local());
dfeec247
XL
1187 let infcx = &inh.infcx;
1188
f035d41b 1189 debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
dfeec247
XL
1190
1191 let mut selcx = traits::SelectionContext::new(&infcx);
1192
1193 for predicate in impl_ty_own_bounds.predicates {
1194 let traits::Normalized { value: predicate, obligations } =
fc512014 1195 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), predicate);
dfeec247
XL
1196
1197 inh.register_predicates(obligations);
1198 inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
1199 }
1200
1201 // Check that all obligations are satisfied by the implementation's
1202 // version.
3c0e092e
XL
1203 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
1204 if !errors.is_empty() {
ee023bcb
FG
1205 let reported = infcx.report_fulfillment_errors(&errors, None, false);
1206 return Err(reported);
dfeec247
XL
1207 }
1208
1209 // Finally, resolve all regions. This catches wily misuses of
1210 // lifetime parameters.
1211 let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
c295e0f8 1212 fcx.regionck_item(impl_ty_hir_id, impl_ty_span, FxHashSet::default());
dfeec247
XL
1213
1214 Ok(())
1215 })
1216}
1217
f035d41b
XL
1218/// Validate that `ProjectionCandidate`s created for this associated type will
1219/// be valid.
1220///
1221/// Usually given
1222///
1223/// trait X { type Y: Copy } impl X for T { type Y = S; }
1224///
1225/// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1226/// impl is well-formed we have to prove `S: Copy`.
1227///
1228/// For default associated types the normalization is not possible (the value
1229/// from the impl could be overridden). We also can't normalize generic
1230/// associated types (yet) because they contain bound parameters.
94222f64 1231#[tracing::instrument(level = "debug", skip(tcx))]
29967ef6 1232pub fn check_type_bounds<'tcx>(
f035d41b
XL
1233 tcx: TyCtxt<'tcx>,
1234 trait_ty: &ty::AssocItem,
1235 impl_ty: &ty::AssocItem,
1236 impl_ty_span: Span,
1237 impl_trait_ref: ty::TraitRef<'tcx>,
ee023bcb 1238) -> Result<(), ErrorGuaranteed> {
f035d41b
XL
1239 // Given
1240 //
1241 // impl<A, B> Foo<u32> for (A, B) {
1242 // type Bar<C> =...
1243 // }
1244 //
94222f64
XL
1245 // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1246 // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1247 // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1248 // the *trait* with the generic associated type parameters (as bound vars).
1249 //
1250 // A note regarding the use of bound vars here:
1251 // Imagine as an example
1252 // ```
1253 // trait Family {
1254 // type Member<C: Eq>;
1255 // }
1256 //
1257 // impl Family for VecFamily {
1258 // type Member<C: Eq> = i32;
1259 // }
1260 // ```
1261 // Here, we would generate
1262 // ```notrust
1263 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1264 // ```
1265 // when we really would like to generate
1266 // ```notrust
1267 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1268 // ```
1269 // But, this is probably fine, because although the first clause can be used with types C that
1270 // do not implement Eq, for it to cause some kind of problem, there would have to be a
1271 // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1272 // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1273 // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1274 // the trait (notably, that X: Eq and T: Family).
1275 let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1276 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1277 if let Some(def_id) = defs.parent {
1278 let parent_defs = tcx.generics_of(def_id);
1279 InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1280 tcx.mk_param_from_def(param)
1281 });
1282 }
1283 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1284 smallvec::SmallVec::with_capacity(defs.count());
1285 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1286 GenericParamDefKind::Type { .. } => {
1287 let kind = ty::BoundTyKind::Param(param.name);
1288 let bound_var = ty::BoundVariableKind::Ty(kind);
1289 bound_vars.push(bound_var);
1290 tcx.mk_ty(ty::Bound(
1291 ty::INNERMOST,
1292 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1293 ))
1294 .into()
1295 }
1296 GenericParamDefKind::Lifetime => {
1297 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1298 let bound_var = ty::BoundVariableKind::Region(kind);
1299 bound_vars.push(bound_var);
1300 tcx.mk_region(ty::ReLateBound(
1301 ty::INNERMOST,
1302 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1303 ))
1304 .into()
1305 }
1306 GenericParamDefKind::Const { .. } => {
1307 let bound_var = ty::BoundVariableKind::Const;
1308 bound_vars.push(bound_var);
5099ac24 1309 tcx.mk_const(ty::ConstS {
94222f64
XL
1310 ty: tcx.type_of(param.def_id),
1311 val: ty::ConstKind::Bound(
1312 ty::INNERMOST,
1313 ty::BoundVar::from_usize(bound_vars.len() - 1),
1314 ),
1315 })
1316 .into()
1317 }
1318 });
1319 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
1320 let impl_ty_substs = tcx.intern_substs(&substs);
1321
f035d41b
XL
1322 let rebased_substs =
1323 impl_ty_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1324 let impl_ty_value = tcx.type_of(impl_ty.def_id);
1325
3dfed10e
XL
1326 let param_env = tcx.param_env(impl_ty.def_id);
1327
1328 // When checking something like
f035d41b 1329 //
3dfed10e
XL
1330 // trait X { type Y: PartialEq<<Self as X>::Y> }
1331 // impl X for T { default type Y = S; }
f035d41b 1332 //
3dfed10e
XL
1333 // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
1334 // we want <T as X>::Y to normalize to S. This is valid because we are
1335 // checking the default value specifically here. Add this equality to the
1336 // ParamEnv for normalization specifically.
1337 let normalize_param_env = {
1338 let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
29967ef6
XL
1339 match impl_ty_value.kind() {
1340 ty::Projection(proj)
1341 if proj.item_def_id == trait_ty.def_id && proj.substs == rebased_substs =>
1342 {
1343 // Don't include this predicate if the projected type is
1344 // exactly the same as the projection. This can occur in
1345 // (somewhat dubious) code like this:
1346 //
1347 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
1348 }
1349 _ => predicates.push(
94222f64
XL
1350 ty::Binder::bind_with_vars(
1351 ty::ProjectionPredicate {
1352 projection_ty: ty::ProjectionTy {
1353 item_def_id: trait_ty.def_id,
1354 substs: rebased_substs,
1355 },
5099ac24 1356 term: impl_ty_value.into(),
29967ef6 1357 },
94222f64
XL
1358 bound_vars,
1359 )
29967ef6
XL
1360 .to_predicate(tcx),
1361 ),
1362 };
a2a8927a
XL
1363 ty::ParamEnv::new(
1364 tcx.intern_predicates(&predicates),
1365 Reveal::UserFacing,
1366 param_env.constness(),
1367 )
f035d41b 1368 };
94222f64
XL
1369 debug!(?normalize_param_env);
1370
1371 let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1372 let rebased_substs =
1373 impl_ty_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
f035d41b
XL
1374
1375 tcx.infer_ctxt().enter(move |infcx| {
a2a8927a 1376 let inh = Inherited::new(infcx, impl_ty.def_id.expect_local());
f035d41b
XL
1377 let infcx = &inh.infcx;
1378 let mut selcx = traits::SelectionContext::new(&infcx);
1379
3dfed10e 1380 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
5099ac24
FG
1381 let normalize_cause = ObligationCause::new(
1382 impl_ty_span,
1383 impl_ty_hir_id,
1384 ObligationCauseCode::CheckAssociatedTypeBounds {
ee023bcb 1385 impl_item_def_id: impl_ty.def_id.expect_local(),
5099ac24
FG
1386 trait_item_def_id: trait_ty.def_id,
1387 },
1388 );
3c0e092e
XL
1389 let mk_cause = |span: Span| {
1390 let code = if span.is_dummy() {
1391 traits::MiscObligation
1392 } else {
1393 traits::BindingObligation(trait_ty.def_id, span)
1394 };
1395 ObligationCause::new(impl_ty_span, impl_ty_hir_id, code)
29967ef6 1396 };
f035d41b 1397
29967ef6
XL
1398 let obligations = tcx
1399 .explicit_item_bounds(trait_ty.def_id)
1400 .iter()
1401 .map(|&(bound, span)| {
94222f64 1402 debug!(?bound);
29967ef6
XL
1403 let concrete_ty_bound = bound.subst(tcx, rebased_substs);
1404 debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
f035d41b 1405
29967ef6
XL
1406 traits::Obligation::new(mk_cause(span), param_env, concrete_ty_bound)
1407 })
1408 .collect();
1409 debug!("check_type_bounds: item_bounds={:?}", obligations);
f035d41b 1410
29967ef6 1411 for mut obligation in util::elaborate_obligations(tcx, obligations) {
f035d41b
XL
1412 let traits::Normalized { value: normalized_predicate, obligations } = traits::normalize(
1413 &mut selcx,
3dfed10e 1414 normalize_param_env,
f035d41b 1415 normalize_cause.clone(),
fc512014 1416 obligation.predicate,
f035d41b 1417 );
f035d41b 1418 debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
29967ef6 1419 obligation.predicate = normalized_predicate;
f035d41b
XL
1420
1421 inh.register_predicates(obligations);
29967ef6 1422 inh.register_predicate(obligation);
f035d41b
XL
1423 }
1424
1425 // Check that all obligations are satisfied by the implementation's
1426 // version.
a2a8927a 1427 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
3c0e092e 1428 if !errors.is_empty() {
ee023bcb
FG
1429 let reported = infcx.report_fulfillment_errors(&errors, None, false);
1430 return Err(reported);
f035d41b
XL
1431 }
1432
1433 // Finally, resolve all regions. This catches wily misuses of
1434 // lifetime parameters.
1435 let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
29967ef6 1436 let implied_bounds = match impl_ty.container {
c295e0f8 1437 ty::TraitContainer(_) => FxHashSet::default(),
29967ef6
XL
1438 ty::ImplContainer(def_id) => fcx.impl_implied_bounds(def_id, impl_ty_span),
1439 };
c295e0f8 1440 fcx.regionck_item(impl_ty_hir_id, impl_ty_span, implied_bounds);
f035d41b
XL
1441
1442 Ok(())
1443 })
1444}
1445
dfeec247
XL
1446fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
1447 match impl_item.kind {
1448 ty::AssocKind::Const => "const",
ba9703b0 1449 ty::AssocKind::Fn => "method",
f035d41b 1450 ty::AssocKind::Type => "type",
dfeec247
XL
1451 }
1452}