]> git.proxmox.com Git - rustc.git/blob - src/librustc_typeck/check/compare_method.rs
Imported Upstream version 1.0.0-alpha.2
[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::infer;
12 use middle::traits;
13 use middle::ty::{self};
14 use middle::subst::{self, Subst, Substs, VecPerParamSpace};
15 use util::ppaux::{self, Repr};
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.repr(tcx));
42
43 debug!("compare_impl_method: impl_trait_ref (liberated) = {}",
44 impl_trait_ref.repr(tcx));
45
46 let infcx = infer::new_infer_ctxt(tcx);
47 let mut fulfillment_cx = traits::FulfillmentContext::new();
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 token::get_name(trait_m.name),
66 ppaux::explicit_self_category_to_str(
67 &impl_m.explicit_self));
68 return;
69 }
70 (_, &ty::StaticExplicitSelfCategory) => {
71 span_err!(tcx.sess, impl_m_span, E0186,
72 "method `{}` has a `{}` declaration in the trait, \
73 but not in the impl",
74 token::get_name(trait_m.name),
75 ppaux::explicit_self_category_to_str(
76 &trait_m.explicit_self));
77 return;
78 }
79 _ => {
80 // Let the type checker catch other errors below
81 }
82 }
83
84 let num_impl_m_type_params = impl_m.generics.types.len(subst::FnSpace);
85 let num_trait_m_type_params = trait_m.generics.types.len(subst::FnSpace);
86 if num_impl_m_type_params != num_trait_m_type_params {
87 span_err!(tcx.sess, impl_m_span, E0049,
88 "method `{}` has {} type parameter{} \
89 but its trait declaration has {} type parameter{}",
90 token::get_name(trait_m.name),
91 num_impl_m_type_params,
92 if num_impl_m_type_params == 1 {""} else {"s"},
93 num_trait_m_type_params,
94 if num_trait_m_type_params == 1 {""} else {"s"});
95 return;
96 }
97
98 if impl_m.fty.sig.0.inputs.len() != trait_m.fty.sig.0.inputs.len() {
99 span_err!(tcx.sess, impl_m_span, E0050,
100 "method `{}` has {} parameter{} \
101 but the declaration in trait `{}` has {}",
102 token::get_name(trait_m.name),
103 impl_m.fty.sig.0.inputs.len(),
104 if impl_m.fty.sig.0.inputs.len() == 1 {""} else {"s"},
105 ty::item_path_str(tcx, trait_m.def_id),
106 trait_m.fty.sig.0.inputs.len());
107 return;
108 }
109
110 // This code is best explained by example. Consider a trait:
111 //
112 // trait Trait<'t,T> {
113 // fn method<'a,M>(t: &'t T, m: &'a M) -> Self;
114 // }
115 //
116 // And an impl:
117 //
118 // impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
119 // fn method<'b,N>(t: &'j &'i U, m: &'b N) -> Foo;
120 // }
121 //
122 // We wish to decide if those two method types are compatible.
123 //
124 // We start out with trait_to_impl_substs, that maps the trait
125 // type parameters to impl type parameters. This is taken from the
126 // impl trait reference:
127 //
128 // trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
129 //
130 // We create a mapping `dummy_substs` that maps from the impl type
131 // parameters to fresh types and regions. For type parameters,
132 // this is the identity transform, but we could as well use any
133 // skolemized types. For regions, we convert from bound to free
134 // regions (Note: but only early-bound regions, i.e., those
135 // declared on the impl or used in type parameter bounds).
136 //
137 // impl_to_skol_substs = {'i => 'i0, U => U0, N => N0 }
138 //
139 // Now we can apply skol_substs to the type of the impl method
140 // to yield a new function type in terms of our fresh, skolemized
141 // types:
142 //
143 // <'b> fn(t: &'i0 U0, m: &'b) -> Foo
144 //
145 // We now want to extract and substitute the type of the *trait*
146 // method and compare it. To do so, we must create a compound
147 // substitution by combining trait_to_impl_substs and
148 // impl_to_skol_substs, and also adding a mapping for the method
149 // type parameters. We extend the mapping to also include
150 // the method parameters.
151 //
152 // trait_to_skol_substs = { T => &'i0 U0, Self => Foo, M => N0 }
153 //
154 // Applying this to the trait method type yields:
155 //
156 // <'a> fn(t: &'i0 U0, m: &'a) -> Foo
157 //
158 // This type is also the same but the name of the bound region ('a
159 // vs 'b). However, the normal subtyping rules on fn types handle
160 // this kind of equivalency just fine.
161 //
162 // We now use these substitutions to ensure that all declared bounds are
163 // satisfied by the implementation's method.
164 //
165 // We do this by creating a parameter environment which contains a
166 // substitution corresponding to impl_to_skol_substs. We then build
167 // trait_to_skol_substs and use it to convert the predicates contained
168 // in the trait_m.generics to the skolemized form.
169 //
170 // Finally we register each of these predicates as an obligation in
171 // a fresh FulfillmentCtxt, and invoke select_all_or_error.
172
173 // Create a parameter environment that represents the implementation's
174 // method.
175 let impl_param_env =
176 ty::ParameterEnvironment::for_item(tcx, impl_m.def_id.node);
177
178 // Create mapping from impl to skolemized.
179 let impl_to_skol_substs = &impl_param_env.free_substs;
180
181 // Create mapping from trait to skolemized.
182 let trait_to_skol_substs =
183 trait_to_impl_substs
184 .subst(tcx, impl_to_skol_substs)
185 .with_method(impl_to_skol_substs.types.get_slice(subst::FnSpace).to_vec(),
186 impl_to_skol_substs.regions().get_slice(subst::FnSpace).to_vec());
187 debug!("compare_impl_method: trait_to_skol_substs={}",
188 trait_to_skol_substs.repr(tcx));
189
190 // Check region bounds. FIXME(@jroesch) refactor this away when removing
191 // ParamBounds.
192 if !check_region_bounds_on_impl_method(tcx,
193 impl_m_span,
194 impl_m,
195 &trait_m.generics,
196 &impl_m.generics,
197 &trait_to_skol_substs,
198 impl_to_skol_substs) {
199 return;
200 }
201
202 // Create obligations for each predicate declared by the impl
203 // definition in the context of the trait's parameter
204 // environment. We can't just use `impl_env.caller_bounds`,
205 // however, because we want to replace all late-bound regions with
206 // region variables.
207 let impl_bounds =
208 impl_m.predicates.instantiate(tcx, impl_to_skol_substs);
209
210 let (impl_bounds, _) =
211 infcx.replace_late_bound_regions_with_fresh_var(
212 impl_m_span,
213 infer::HigherRankedType,
214 &ty::Binder(impl_bounds));
215 debug!("compare_impl_method: impl_bounds={}",
216 impl_bounds.repr(tcx));
217
218 // Normalize the associated types in the trait_bounds.
219 let trait_bounds = trait_m.predicates.instantiate(tcx, &trait_to_skol_substs);
220
221 // Obtain the predicate split predicate sets for each.
222 let trait_pred = trait_bounds.predicates.split();
223 let impl_pred = impl_bounds.predicates.split();
224
225 // This is the only tricky bit of the new way we check implementation methods
226 // We need to build a set of predicates where only the FnSpace bounds
227 // are from the trait and we assume all other bounds from the implementation
228 // to be previously satisfied.
229 //
230 // We then register the obligations from the impl_m and check to see
231 // if all constraints hold.
232 let hybrid_preds = VecPerParamSpace::new(
233 impl_pred.types,
234 impl_pred.selfs,
235 trait_pred.fns
236 );
237
238 // Construct trait parameter environment and then shift it into the skolemized viewpoint.
239 // The key step here is to update the caller_bounds's predicates to be
240 // the new hybrid bounds we computed.
241 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_body_id);
242 let trait_param_env = impl_param_env.with_caller_bounds(hybrid_preds.into_vec());
243 let trait_param_env = traits::normalize_param_env_or_error(trait_param_env,
244 normalize_cause.clone());
245
246 debug!("compare_impl_method: trait_bounds={}",
247 trait_param_env.caller_bounds.repr(tcx));
248
249 let mut selcx = traits::SelectionContext::new(&infcx, &trait_param_env);
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 = ty::mk_bare_fn(tcx, 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 = ty::mk_bare_fn(tcx, 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.try(|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 &impl_param_env,
297 &mut fulfillment_cx,
298 impl_m_span,
299 impl_m_body_id,
300 &impl_sig);
301 let impl_fty =
302 ty::mk_bare_fn(tcx,
303 None,
304 tcx.mk_bare_fn(ty::BareFnTy { unsafety: impl_m.fty.unsafety,
305 abi: impl_m.fty.abi,
306 sig: ty::Binder(impl_sig) }));
307 debug!("compare_impl_method: impl_fty={}",
308 impl_fty.repr(tcx));
309
310 let (trait_sig, skol_map) =
311 infcx.skolemize_late_bound_regions(&trait_m.fty.sig, snapshot);
312 let trait_sig =
313 trait_sig.subst(tcx, &trait_to_skol_substs);
314 let trait_sig =
315 assoc::normalize_associated_types_in(&infcx,
316 &impl_param_env,
317 &mut fulfillment_cx,
318 impl_m_span,
319 impl_m_body_id,
320 &trait_sig);
321 let trait_fty =
322 ty::mk_bare_fn(tcx,
323 None,
324 tcx.mk_bare_fn(ty::BareFnTy { unsafety: trait_m.fty.unsafety,
325 abi: trait_m.fty.abi,
326 sig: ty::Binder(trait_sig) }));
327
328 debug!("compare_impl_method: trait_fty={}",
329 trait_fty.repr(tcx));
330
331 try!(infer::mk_subty(&infcx, false, origin, impl_fty, trait_fty));
332
333 infcx.leak_check(&skol_map, snapshot)
334 });
335
336 match err {
337 Ok(()) => { }
338 Err(terr) => {
339 debug!("checking trait method for compatibility: impl ty {}, trait ty {}",
340 impl_fty.repr(tcx),
341 trait_fty.repr(tcx));
342 span_err!(tcx.sess, impl_m_span, E0053,
343 "method `{}` has an incompatible type for trait: {}",
344 token::get_name(trait_m.name),
345 ty::type_err_to_str(tcx, &terr));
346 return;
347 }
348 }
349
350 // Check that all obligations are satisfied by the implementation's
351 // version.
352 match fulfillment_cx.select_all_or_error(&infcx, &trait_param_env) {
353 Err(ref errors) => { traits::report_fulfillment_errors(&infcx, errors) }
354 Ok(_) => {}
355 }
356
357 // Finally, resolve all regions. This catches wily misuses of lifetime
358 // parameters.
359 infcx.resolve_regions_and_report_errors(impl_m_body_id);
360
361 fn check_region_bounds_on_impl_method<'tcx>(tcx: &ty::ctxt<'tcx>,
362 span: Span,
363 impl_m: &ty::Method<'tcx>,
364 trait_generics: &ty::Generics<'tcx>,
365 impl_generics: &ty::Generics<'tcx>,
366 trait_to_skol_substs: &Substs<'tcx>,
367 impl_to_skol_substs: &Substs<'tcx>)
368 -> bool
369 {
370
371 let trait_params = trait_generics.regions.get_slice(subst::FnSpace);
372 let impl_params = impl_generics.regions.get_slice(subst::FnSpace);
373
374 debug!("check_region_bounds_on_impl_method: \
375 trait_generics={} \
376 impl_generics={} \
377 trait_to_skol_substs={} \
378 impl_to_skol_substs={}",
379 trait_generics.repr(tcx),
380 impl_generics.repr(tcx),
381 trait_to_skol_substs.repr(tcx),
382 impl_to_skol_substs.repr(tcx));
383
384 // Must have same number of early-bound lifetime parameters.
385 // Unfortunately, if the user screws up the bounds, then this
386 // will change classification between early and late. E.g.,
387 // if in trait we have `<'a,'b:'a>`, and in impl we just have
388 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
389 // in trait but 0 in the impl. But if we report "expected 2
390 // but found 0" it's confusing, because it looks like there
391 // are zero. Since I don't quite know how to phrase things at
392 // the moment, give a kind of vague error message.
393 if trait_params.len() != impl_params.len() {
394 span_err!(tcx.sess, span, E0195,
395 "lifetime parameters or bounds on method `{}` do \
396 not match the trait declaration",
397 token::get_name(impl_m.name));
398 return false;
399 }
400
401 return true;
402 }
403 }