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