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