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