]> git.proxmox.com Git - rustc.git/blob - src/librustc_typeck/check/compare_method.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / librustc_typeck / check / compare_method.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use middle::free_region::FreeRegionMap;
12 use rustc::infer::{self, InferOk, TypeOrigin};
13 use rustc::ty::{self, TyCtxt};
14 use rustc::traits::{self, ProjectionMode};
15 use rustc::ty::subst::{self, Subst, Substs, VecPerParamSpace};
16
17 use syntax::ast;
18 use syntax::codemap::Span;
19
20 use super::assoc;
21
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 ///
27 /// - impl_m: type of the method we are checking
28 /// - impl_m_span: span to use for reporting errors
29 /// - impl_m_body_id: id of the method body
30 /// - trait_m: the method in the trait
31 /// - impl_trait_ref: the TraitRef corresponding to the trait implementation
32
33 pub fn compare_impl_method<'tcx>(tcx: &TyCtxt<'tcx>,
34 impl_m: &ty::Method<'tcx>,
35 impl_m_span: Span,
36 impl_m_body_id: ast::NodeId,
37 trait_m: &ty::Method<'tcx>,
38 impl_trait_ref: &ty::TraitRef<'tcx>) {
39 debug!("compare_impl_method(impl_trait_ref={:?})",
40 impl_trait_ref);
41
42 debug!("compare_impl_method: impl_trait_ref (liberated) = {:?}",
43 impl_trait_ref);
44
45 let mut infcx = infer::new_infer_ctxt(tcx, &tcx.tables, None, ProjectionMode::AnyFinal);
46 let mut fulfillment_cx = traits::FulfillmentContext::new();
47
48 let trait_to_impl_substs = &impl_trait_ref.substs;
49
50 // Try to give more informative error messages about self typing
51 // mismatches. Note that any mismatch will also be detected
52 // below, where we construct a canonical function type that
53 // includes the self parameter as a normal parameter. It's just
54 // that the error messages you get out of this code are a bit more
55 // inscrutable, particularly for cases where one method has no
56 // self.
57 match (&trait_m.explicit_self, &impl_m.explicit_self) {
58 (&ty::ExplicitSelfCategory::Static,
59 &ty::ExplicitSelfCategory::Static) => {}
60 (&ty::ExplicitSelfCategory::Static, _) => {
61 span_err!(tcx.sess, impl_m_span, E0185,
62 "method `{}` has a `{}` declaration in the impl, \
63 but not in the trait",
64 trait_m.name,
65 impl_m.explicit_self);
66 return;
67 }
68 (_, &ty::ExplicitSelfCategory::Static) => {
69 span_err!(tcx.sess, impl_m_span, E0186,
70 "method `{}` has a `{}` declaration in the trait, \
71 but not in the impl",
72 trait_m.name,
73 trait_m.explicit_self);
74 return;
75 }
76 _ => {
77 // Let the type checker catch other errors below
78 }
79 }
80
81 let num_impl_m_type_params = impl_m.generics.types.len(subst::FnSpace);
82 let num_trait_m_type_params = trait_m.generics.types.len(subst::FnSpace);
83 if num_impl_m_type_params != num_trait_m_type_params {
84 span_err!(tcx.sess, impl_m_span, E0049,
85 "method `{}` has {} type parameter{} \
86 but its trait declaration has {} type parameter{}",
87 trait_m.name,
88 num_impl_m_type_params,
89 if num_impl_m_type_params == 1 {""} else {"s"},
90 num_trait_m_type_params,
91 if num_trait_m_type_params == 1 {""} else {"s"});
92 return;
93 }
94
95 if impl_m.fty.sig.0.inputs.len() != trait_m.fty.sig.0.inputs.len() {
96 span_err!(tcx.sess, impl_m_span, E0050,
97 "method `{}` has {} parameter{} \
98 but the declaration in trait `{}` has {}",
99 trait_m.name,
100 impl_m.fty.sig.0.inputs.len(),
101 if impl_m.fty.sig.0.inputs.len() == 1 {""} else {"s"},
102 tcx.item_path_str(trait_m.def_id),
103 trait_m.fty.sig.0.inputs.len());
104 return;
105 }
106
107 // This code is best explained by example. Consider a trait:
108 //
109 // trait Trait<'t,T> {
110 // fn method<'a,M>(t: &'t T, m: &'a M) -> Self;
111 // }
112 //
113 // And an impl:
114 //
115 // impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
116 // fn method<'b,N>(t: &'j &'i U, m: &'b N) -> Foo;
117 // }
118 //
119 // We wish to decide if those two method types are compatible.
120 //
121 // We start out with trait_to_impl_substs, that maps the trait
122 // type parameters to impl type parameters. This is taken from the
123 // impl trait reference:
124 //
125 // trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
126 //
127 // We create a mapping `dummy_substs` that maps from the impl type
128 // parameters to fresh types and regions. For type parameters,
129 // this is the identity transform, but we could as well use any
130 // skolemized types. For regions, we convert from bound to free
131 // regions (Note: but only early-bound regions, i.e., those
132 // declared on the impl or used in type parameter bounds).
133 //
134 // impl_to_skol_substs = {'i => 'i0, U => U0, N => N0 }
135 //
136 // Now we can apply skol_substs to the type of the impl method
137 // to yield a new function type in terms of our fresh, skolemized
138 // types:
139 //
140 // <'b> fn(t: &'i0 U0, m: &'b) -> Foo
141 //
142 // We now want to extract and substitute the type of the *trait*
143 // method and compare it. To do so, we must create a compound
144 // substitution by combining trait_to_impl_substs and
145 // impl_to_skol_substs, and also adding a mapping for the method
146 // type parameters. We extend the mapping to also include
147 // the method parameters.
148 //
149 // trait_to_skol_substs = { T => &'i0 U0, Self => Foo, M => N0 }
150 //
151 // Applying this to the trait method type yields:
152 //
153 // <'a> fn(t: &'i0 U0, m: &'a) -> Foo
154 //
155 // This type is also the same but the name of the bound region ('a
156 // vs 'b). However, the normal subtyping rules on fn types handle
157 // this kind of equivalency just fine.
158 //
159 // We now use these substitutions to ensure that all declared bounds are
160 // satisfied by the implementation's method.
161 //
162 // We do this by creating a parameter environment which contains a
163 // substitution corresponding to impl_to_skol_substs. We then build
164 // trait_to_skol_substs and use it to convert the predicates contained
165 // in the trait_m.generics to the skolemized form.
166 //
167 // Finally we register each of these predicates as an obligation in
168 // a fresh FulfillmentCtxt, and invoke select_all_or_error.
169
170 // Create a parameter environment that represents the implementation's
171 // method.
172 let impl_m_node_id = tcx.map.as_local_node_id(impl_m.def_id).unwrap();
173 let impl_param_env = ty::ParameterEnvironment::for_item(tcx, impl_m_node_id);
174
175 // Create mapping from impl to skolemized.
176 let impl_to_skol_substs = &impl_param_env.free_substs;
177
178 // Create mapping from trait to skolemized.
179 let trait_to_skol_substs =
180 trait_to_impl_substs
181 .subst(tcx, impl_to_skol_substs)
182 .with_method(impl_to_skol_substs.types.get_slice(subst::FnSpace).to_vec(),
183 impl_to_skol_substs.regions.get_slice(subst::FnSpace).to_vec());
184 debug!("compare_impl_method: trait_to_skol_substs={:?}",
185 trait_to_skol_substs);
186
187 // Check region bounds. FIXME(@jroesch) refactor this away when removing
188 // ParamBounds.
189 if !check_region_bounds_on_impl_method(tcx,
190 impl_m_span,
191 impl_m,
192 &trait_m.generics,
193 &impl_m.generics,
194 &trait_to_skol_substs,
195 impl_to_skol_substs) {
196 return;
197 }
198
199 // Create obligations for each predicate declared by the impl
200 // definition in the context of the trait's parameter
201 // environment. We can't just use `impl_env.caller_bounds`,
202 // however, because we want to replace all late-bound regions with
203 // region variables.
204 let impl_bounds =
205 impl_m.predicates.instantiate(tcx, impl_to_skol_substs);
206
207 let (impl_bounds, _) =
208 infcx.replace_late_bound_regions_with_fresh_var(
209 impl_m_span,
210 infer::HigherRankedType,
211 &ty::Binder(impl_bounds));
212 debug!("compare_impl_method: impl_bounds={:?}",
213 impl_bounds);
214
215 // Normalize the associated types in the trait_bounds.
216 let trait_bounds = trait_m.predicates.instantiate(tcx, &trait_to_skol_substs);
217
218 // Obtain the predicate split predicate sets for each.
219 let trait_pred = trait_bounds.predicates.split();
220 let impl_pred = impl_bounds.predicates.split();
221
222 // This is the only tricky bit of the new way we check implementation methods
223 // We need to build a set of predicates where only the FnSpace bounds
224 // are from the trait and we assume all other bounds from the implementation
225 // to be previously satisfied.
226 //
227 // We then register the obligations from the impl_m and check to see
228 // if all constraints hold.
229 let hybrid_preds = VecPerParamSpace::new(
230 impl_pred.types,
231 impl_pred.selfs,
232 trait_pred.fns
233 );
234
235 // Construct trait parameter environment and then shift it into the skolemized viewpoint.
236 // The key step here is to update the caller_bounds's predicates to be
237 // the new hybrid bounds we computed.
238 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_body_id);
239 let trait_param_env = impl_param_env.with_caller_bounds(hybrid_preds.into_vec());
240 let trait_param_env = traits::normalize_param_env_or_error(trait_param_env,
241 normalize_cause.clone());
242 // FIXME(@jroesch) this seems ugly, but is a temporary change
243 infcx.parameter_environment = trait_param_env;
244
245 debug!("compare_impl_method: trait_bounds={:?}",
246 infcx.parameter_environment.caller_bounds);
247
248 let mut selcx = traits::SelectionContext::new(&infcx);
249
250 for predicate in impl_pred.fns {
251 let traits::Normalized { value: predicate, .. } =
252 traits::normalize(&mut selcx, normalize_cause.clone(), &predicate);
253
254 let cause = traits::ObligationCause {
255 span: impl_m_span,
256 body_id: impl_m_body_id,
257 code: traits::ObligationCauseCode::CompareImplMethodObligation
258 };
259
260 fulfillment_cx.register_predicate_obligation(
261 &infcx,
262 traits::Obligation::new(cause, predicate));
263 }
264
265 // We now need to check that the signature of the impl method is
266 // compatible with that of the trait method. We do this by
267 // checking that `impl_fty <: trait_fty`.
268 //
269 // FIXME. Unfortunately, this doesn't quite work right now because
270 // associated type normalization is not integrated into subtype
271 // checks. For the comparison to be valid, we need to
272 // normalize the associated types in the impl/trait methods
273 // first. However, because function types bind regions, just
274 // calling `normalize_associated_types_in` would have no effect on
275 // any associated types appearing in the fn arguments or return
276 // type.
277
278 // Compute skolemized form of impl and trait method tys.
279 let impl_fty = tcx.mk_fn_ptr(impl_m.fty.clone());
280 let impl_fty = impl_fty.subst(tcx, impl_to_skol_substs);
281 let trait_fty = tcx.mk_fn_ptr(trait_m.fty.clone());
282 let trait_fty = trait_fty.subst(tcx, &trait_to_skol_substs);
283
284 let err = infcx.commit_if_ok(|snapshot| {
285 let origin = TypeOrigin::MethodCompatCheck(impl_m_span);
286
287 let (impl_sig, _) =
288 infcx.replace_late_bound_regions_with_fresh_var(impl_m_span,
289 infer::HigherRankedType,
290 &impl_m.fty.sig);
291 let impl_sig =
292 impl_sig.subst(tcx, impl_to_skol_substs);
293 let impl_sig =
294 assoc::normalize_associated_types_in(&infcx,
295 &mut fulfillment_cx,
296 impl_m_span,
297 impl_m_body_id,
298 &impl_sig);
299 let impl_fty = tcx.mk_fn_ptr(ty::BareFnTy {
300 unsafety: impl_m.fty.unsafety,
301 abi: impl_m.fty.abi,
302 sig: ty::Binder(impl_sig)
303 });
304 debug!("compare_impl_method: impl_fty={:?}",
305 impl_fty);
306
307 let (trait_sig, skol_map) =
308 infcx.skolemize_late_bound_regions(&trait_m.fty.sig, snapshot);
309 let trait_sig =
310 trait_sig.subst(tcx, &trait_to_skol_substs);
311 let trait_sig =
312 assoc::normalize_associated_types_in(&infcx,
313 &mut fulfillment_cx,
314 impl_m_span,
315 impl_m_body_id,
316 &trait_sig);
317 let trait_fty = tcx.mk_fn_ptr(ty::BareFnTy {
318 unsafety: trait_m.fty.unsafety,
319 abi: trait_m.fty.abi,
320 sig: ty::Binder(trait_sig)
321 });
322
323 debug!("compare_impl_method: trait_fty={:?}",
324 trait_fty);
325
326 infer::mk_subty(&infcx, false, origin, impl_fty, trait_fty)?;
327
328 infcx.leak_check(&skol_map, snapshot)
329 });
330
331 match err {
332 Ok(()) => { }
333 Err(terr) => {
334 debug!("checking trait method for compatibility: impl ty {:?}, trait ty {:?}",
335 impl_fty,
336 trait_fty);
337 span_err!(tcx.sess, impl_m_span, E0053,
338 "method `{}` has an incompatible type for trait: {}",
339 trait_m.name,
340 terr);
341 return;
342 }
343 }
344
345 // Check that all obligations are satisfied by the implementation's
346 // version.
347 match fulfillment_cx.select_all_or_error(&infcx) {
348 Err(ref errors) => { traits::report_fulfillment_errors(&infcx, errors) }
349 Ok(_) => {}
350 }
351
352 // Finally, resolve all regions. This catches wily misuses of
353 // lifetime parameters. We have to build up a plausible lifetime
354 // environment based on what we find in the trait. We could also
355 // include the obligations derived from the method argument types,
356 // but I don't think it's necessary -- after all, those are still
357 // in effect when type-checking the body, and all the
358 // where-clauses in the header etc should be implied by the trait
359 // anyway, so it shouldn't be needed there either. Anyway, we can
360 // always add more relations later (it's backwards compat).
361 let mut free_regions = FreeRegionMap::new();
362 free_regions.relate_free_regions_from_predicates(tcx,
363 &infcx.parameter_environment.caller_bounds);
364
365 infcx.resolve_regions_and_report_errors(&free_regions, impl_m_body_id);
366
367 fn check_region_bounds_on_impl_method<'tcx>(tcx: &TyCtxt<'tcx>,
368 span: Span,
369 impl_m: &ty::Method<'tcx>,
370 trait_generics: &ty::Generics<'tcx>,
371 impl_generics: &ty::Generics<'tcx>,
372 trait_to_skol_substs: &Substs<'tcx>,
373 impl_to_skol_substs: &Substs<'tcx>)
374 -> bool
375 {
376
377 let trait_params = trait_generics.regions.get_slice(subst::FnSpace);
378 let impl_params = impl_generics.regions.get_slice(subst::FnSpace);
379
380 debug!("check_region_bounds_on_impl_method: \
381 trait_generics={:?} \
382 impl_generics={:?} \
383 trait_to_skol_substs={:?} \
384 impl_to_skol_substs={:?}",
385 trait_generics,
386 impl_generics,
387 trait_to_skol_substs,
388 impl_to_skol_substs);
389
390 // Must have same number of early-bound lifetime parameters.
391 // Unfortunately, if the user screws up the bounds, then this
392 // will change classification between early and late. E.g.,
393 // if in trait we have `<'a,'b:'a>`, and in impl we just have
394 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
395 // in trait but 0 in the impl. But if we report "expected 2
396 // but found 0" it's confusing, because it looks like there
397 // are zero. Since I don't quite know how to phrase things at
398 // the moment, give a kind of vague error message.
399 if trait_params.len() != impl_params.len() {
400 span_err!(tcx.sess, span, E0195,
401 "lifetime parameters or bounds on method `{}` do \
402 not match the trait declaration",
403 impl_m.name);
404 return false;
405 }
406
407 return true;
408 }
409 }
410
411 pub fn compare_const_impl<'tcx>(tcx: &TyCtxt<'tcx>,
412 impl_c: &ty::AssociatedConst<'tcx>,
413 impl_c_span: Span,
414 trait_c: &ty::AssociatedConst<'tcx>,
415 impl_trait_ref: &ty::TraitRef<'tcx>) {
416 debug!("compare_const_impl(impl_trait_ref={:?})",
417 impl_trait_ref);
418
419 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, None, ProjectionMode::AnyFinal);
420 let mut fulfillment_cx = traits::FulfillmentContext::new();
421
422 // The below is for the most part highly similar to the procedure
423 // for methods above. It is simpler in many respects, especially
424 // because we shouldn't really have to deal with lifetimes or
425 // predicates. In fact some of this should probably be put into
426 // shared functions because of DRY violations...
427 let trait_to_impl_substs = &impl_trait_ref.substs;
428
429 // Create a parameter environment that represents the implementation's
430 // method.
431 let impl_c_node_id = tcx.map.as_local_node_id(impl_c.def_id).unwrap();
432 let impl_param_env = ty::ParameterEnvironment::for_item(tcx, impl_c_node_id);
433
434 // Create mapping from impl to skolemized.
435 let impl_to_skol_substs = &impl_param_env.free_substs;
436
437 // Create mapping from trait to skolemized.
438 let trait_to_skol_substs =
439 trait_to_impl_substs
440 .subst(tcx, impl_to_skol_substs)
441 .with_method(impl_to_skol_substs.types.get_slice(subst::FnSpace).to_vec(),
442 impl_to_skol_substs.regions.get_slice(subst::FnSpace).to_vec());
443 debug!("compare_const_impl: trait_to_skol_substs={:?}",
444 trait_to_skol_substs);
445
446 // Compute skolemized form of impl and trait const tys.
447 let impl_ty = impl_c.ty.subst(tcx, impl_to_skol_substs);
448 let trait_ty = trait_c.ty.subst(tcx, &trait_to_skol_substs);
449
450 let err = infcx.commit_if_ok(|_| {
451 let origin = TypeOrigin::Misc(impl_c_span);
452
453 // There is no "body" here, so just pass dummy id.
454 let impl_ty =
455 assoc::normalize_associated_types_in(&infcx,
456 &mut fulfillment_cx,
457 impl_c_span,
458 0,
459 &impl_ty);
460
461 debug!("compare_const_impl: impl_ty={:?}",
462 impl_ty);
463
464 let trait_ty =
465 assoc::normalize_associated_types_in(&infcx,
466 &mut fulfillment_cx,
467 impl_c_span,
468 0,
469 &trait_ty);
470
471 debug!("compare_const_impl: trait_ty={:?}",
472 trait_ty);
473
474 infer::mk_subty(&infcx, false, origin, impl_ty, trait_ty)
475 });
476
477 match err {
478 Ok(InferOk { obligations, .. }) => {
479 // FIXME(#32730) propagate obligations
480 assert!(obligations.is_empty())
481 }
482 Err(terr) => {
483 debug!("checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
484 impl_ty,
485 trait_ty);
486 span_err!(tcx.sess, impl_c_span, E0326,
487 "implemented const `{}` has an incompatible type for \
488 trait: {}",
489 trait_c.name,
490 terr);
491 return;
492 }
493 }
494 }