]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/coherence/mod.rs
Remove unused imports
[rust.git] / src / librustc_typeck / coherence / mod.rs
1 // Copyright 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 // Coherence phase
12 //
13 // The job of the coherence phase of typechecking is to ensure that
14 // each trait has at most one implementation for each type. This is
15 // done by the orphan and overlap modules. Then we build up various
16 // mappings. That mapping code resides here.
17
18
19 use middle::def_id::DefId;
20 use middle::lang_items::UnsizeTraitLangItem;
21 use middle::subst::{self, Subst};
22 use middle::traits;
23 use middle::ty;
24 use middle::ty::RegionEscape;
25 use middle::ty::{ImplOrTraitItemId, ConstTraitItemId};
26 use middle::ty::{MethodTraitItemId, TypeTraitItemId, ParameterEnvironment};
27 use middle::ty::{Ty, TyBool, TyChar, TyEnum, TyError};
28 use middle::ty::{TyParam, TyRawPtr};
29 use middle::ty::{TyRef, TyStruct, TyTrait, TyTuple};
30 use middle::ty::{TyStr, TyArray, TySlice, TyFloat, TyInfer, TyInt};
31 use middle::ty::{TyUint, TyClosure, TyBox, TyBareFn};
32 use middle::ty::TyProjection;
33 use middle::ty::util::CopyImplementationError;
34 use middle::free_region::FreeRegionMap;
35 use CrateCtxt;
36 use middle::infer::{self, InferCtxt, TypeOrigin, new_infer_ctxt};
37 use std::cell::RefCell;
38 use std::rc::Rc;
39 use syntax::codemap::Span;
40 use syntax::parse::token;
41 use util::nodemap::{DefIdMap, FnvHashMap};
42 use rustc::front::map as hir_map;
43 use rustc_front::intravisit;
44 use rustc_front::hir::{Item, ItemImpl,Crate};
45 use rustc_front::hir;
46
47 mod orphan;
48 mod overlap;
49 mod unsafety;
50
51 // Returns the def ID of the base type, if there is one.
52 fn get_base_type_def_id<'a, 'tcx>(inference_context: &InferCtxt<'a, 'tcx>,
53                                   span: Span,
54                                   ty: Ty<'tcx>)
55                                   -> Option<DefId> {
56     match ty.sty {
57         TyEnum(def, _) |
58         TyStruct(def, _) => {
59             Some(def.did)
60         }
61
62         TyTrait(ref t) => {
63             Some(t.principal_def_id())
64         }
65
66         TyBox(_) => {
67             inference_context.tcx.lang_items.owned_box()
68         }
69
70         TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
71         TyStr | TyArray(..) | TySlice(..) | TyBareFn(..) | TyTuple(..) |
72         TyParam(..) | TyError |
73         TyRawPtr(_) | TyRef(_, _) | TyProjection(..) => {
74             None
75         }
76
77         TyInfer(..) | TyClosure(..) => {
78             // `ty` comes from a user declaration so we should only expect types
79             // that the user can type
80             inference_context.tcx.sess.span_bug(
81                 span,
82                 &format!("coherence encountered unexpected type searching for base type: {}",
83                          ty));
84         }
85     }
86 }
87
88 struct CoherenceChecker<'a, 'tcx: 'a> {
89     crate_context: &'a CrateCtxt<'a, 'tcx>,
90     inference_context: InferCtxt<'a, 'tcx>,
91     inherent_impls: RefCell<DefIdMap<Rc<RefCell<Vec<DefId>>>>>,
92 }
93
94 struct CoherenceCheckVisitor<'a, 'tcx: 'a> {
95     cc: &'a CoherenceChecker<'a, 'tcx>
96 }
97
98 impl<'a, 'tcx, 'v> intravisit::Visitor<'v> for CoherenceCheckVisitor<'a, 'tcx> {
99     fn visit_item(&mut self, item: &Item) {
100         if let ItemImpl(..) = item.node {
101             self.cc.check_implementation(item)
102         }
103     }
104 }
105
106 impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> {
107     fn check(&self, krate: &Crate) {
108         // Check implementations and traits. This populates the tables
109         // containing the inherent methods and extension methods. It also
110         // builds up the trait inheritance table.
111         krate.visit_all_items(&mut CoherenceCheckVisitor { cc: self });
112
113         // Copy over the inherent impls we gathered up during the walk into
114         // the tcx.
115         let mut tcx_inherent_impls =
116             self.crate_context.tcx.inherent_impls.borrow_mut();
117         for (k, v) in self.inherent_impls.borrow().iter() {
118             tcx_inherent_impls.insert((*k).clone(),
119                                       Rc::new((*v.borrow()).clone()));
120         }
121
122         // Populate the table of destructors. It might seem a bit strange to
123         // do this here, but it's actually the most convenient place, since
124         // the coherence tables contain the trait -> type mappings.
125         self.populate_destructors();
126
127         // Check to make sure implementations of `Copy` are legal.
128         self.check_implementations_of_copy();
129
130         // Check to make sure implementations of `CoerceUnsized` are legal
131         // and collect the necessary information from them.
132         self.check_implementations_of_coerce_unsized();
133     }
134
135     fn check_implementation(&self, item: &Item) {
136         let tcx = self.crate_context.tcx;
137         let impl_did = tcx.map.local_def_id(item.id);
138         let self_type = tcx.lookup_item_type(impl_did);
139
140         // If there are no traits, then this implementation must have a
141         // base type.
142
143         let impl_items = self.create_impl_from_item(item);
144
145         if let Some(trait_ref) = self.crate_context.tcx.impl_trait_ref(impl_did) {
146             debug!("(checking implementation) adding impl for trait '{:?}', item '{}'",
147                    trait_ref,
148                    item.name);
149
150             enforce_trait_manually_implementable(self.crate_context.tcx,
151                                                  item.span,
152                                                  trait_ref.def_id);
153             self.add_trait_impl(trait_ref, impl_did);
154         } else {
155             // Add the implementation to the mapping from implementation to base
156             // type def ID, if there is a base type for this implementation and
157             // the implementation does not have any associated traits.
158             if let Some(base_type_def_id) = get_base_type_def_id(
159                     &self.inference_context, item.span, self_type.ty) {
160                 self.add_inherent_impl(base_type_def_id, impl_did);
161             }
162         }
163
164         tcx.impl_items.borrow_mut().insert(impl_did, impl_items);
165     }
166
167     fn add_inherent_impl(&self, base_def_id: DefId, impl_def_id: DefId) {
168         match self.inherent_impls.borrow().get(&base_def_id) {
169             Some(implementation_list) => {
170                 implementation_list.borrow_mut().push(impl_def_id);
171                 return;
172             }
173             None => {}
174         }
175
176         self.inherent_impls.borrow_mut().insert(
177             base_def_id,
178             Rc::new(RefCell::new(vec!(impl_def_id))));
179     }
180
181     fn add_trait_impl(&self, impl_trait_ref: ty::TraitRef<'tcx>, impl_def_id: DefId) {
182         debug!("add_trait_impl: impl_trait_ref={:?} impl_def_id={:?}",
183                impl_trait_ref, impl_def_id);
184         let trait_def = self.crate_context.tcx.lookup_trait_def(impl_trait_ref.def_id);
185         trait_def.record_impl(self.crate_context.tcx, impl_def_id, impl_trait_ref);
186     }
187
188     // Converts an implementation in the AST to a vector of items.
189     fn create_impl_from_item(&self, item: &Item) -> Vec<ImplOrTraitItemId> {
190         match item.node {
191             ItemImpl(_, _, _, _, _, ref impl_items) => {
192                 impl_items.iter().map(|impl_item| {
193                     let impl_def_id = self.crate_context.tcx.map.local_def_id(impl_item.id);
194                     match impl_item.node {
195                         hir::ImplItemKind::Const(..) => {
196                             ConstTraitItemId(impl_def_id)
197                         }
198                         hir::ImplItemKind::Method(..) => {
199                             MethodTraitItemId(impl_def_id)
200                         }
201                         hir::ImplItemKind::Type(_) => {
202                             TypeTraitItemId(impl_def_id)
203                         }
204                     }
205                 }).collect()
206             }
207             _ => {
208                 self.crate_context.tcx.sess.span_bug(item.span,
209                                                      "can't convert a non-impl \
210                                                       to an impl");
211             }
212         }
213     }
214
215     //
216     // Destructors
217     //
218
219     fn populate_destructors(&self) {
220         let tcx = self.crate_context.tcx;
221         let drop_trait = match tcx.lang_items.drop_trait() {
222             Some(id) => id, None => { return }
223         };
224         tcx.populate_implementations_for_trait_if_necessary(drop_trait);
225         let drop_trait = tcx.lookup_trait_def(drop_trait);
226
227         let impl_items = tcx.impl_items.borrow();
228
229         drop_trait.for_each_impl(tcx, |impl_did| {
230             let items = impl_items.get(&impl_did).unwrap();
231             if items.is_empty() {
232                 // We'll error out later. For now, just don't ICE.
233                 return;
234             }
235             let method_def_id = items[0];
236
237             let self_type = tcx.lookup_item_type(impl_did);
238             match self_type.ty.sty {
239                 ty::TyEnum(type_def, _) |
240                 ty::TyStruct(type_def, _) => {
241                     type_def.set_destructor(method_def_id.def_id());
242                 }
243                 _ => {
244                     // Destructors only work on nominal types.
245                     if let Some(impl_node_id) = tcx.map.as_local_node_id(impl_did) {
246                         match tcx.map.find(impl_node_id) {
247                             Some(hir_map::NodeItem(item)) => {
248                                 span_err!(tcx.sess, item.span, E0120,
249                                           "the Drop trait may only be implemented on structures");
250                             }
251                             _ => {
252                                 tcx.sess.bug("didn't find impl in ast \
253                                               map");
254                             }
255                         }
256                     } else {
257                         tcx.sess.bug("found external impl of Drop trait on \
258                                       something other than a struct");
259                     }
260                 }
261             }
262         });
263     }
264
265     /// Ensures that implementations of the built-in trait `Copy` are legal.
266     fn check_implementations_of_copy(&self) {
267         let tcx = self.crate_context.tcx;
268         let copy_trait = match tcx.lang_items.copy_trait() {
269             Some(id) => id,
270             None => return,
271         };
272         tcx.populate_implementations_for_trait_if_necessary(copy_trait);
273         let copy_trait = tcx.lookup_trait_def(copy_trait);
274
275         copy_trait.for_each_impl(tcx, |impl_did| {
276             debug!("check_implementations_of_copy: impl_did={:?}",
277                    impl_did);
278
279             let impl_node_id = if let Some(n) = tcx.map.as_local_node_id(impl_did) {
280                 n
281             } else {
282                 debug!("check_implementations_of_copy(): impl not in this \
283                         crate");
284                 return
285             };
286
287             let self_type = tcx.lookup_item_type(impl_did);
288             debug!("check_implementations_of_copy: self_type={:?} (bound)",
289                    self_type);
290
291             let span = tcx.map.span(impl_node_id);
292             let param_env = ParameterEnvironment::for_item(tcx, impl_node_id);
293             let self_type = self_type.ty.subst(tcx, &param_env.free_substs);
294             assert!(!self_type.has_escaping_regions());
295
296             debug!("check_implementations_of_copy: self_type={:?} (free)",
297                    self_type);
298
299             match param_env.can_type_implement_copy(self_type, span) {
300                 Ok(()) => {}
301                 Err(CopyImplementationError::InfrigingField(name)) => {
302                        span_err!(tcx.sess, span, E0204,
303                                  "the trait `Copy` may not be \
304                                           implemented for this type; field \
305                                           `{}` does not implement `Copy`",
306                                          name)
307                 }
308                 Err(CopyImplementationError::InfrigingVariant(name)) => {
309                        span_err!(tcx.sess, span, E0205,
310                                  "the trait `Copy` may not be \
311                                           implemented for this type; variant \
312                                           `{}` does not implement `Copy`",
313                                          name)
314                 }
315                 Err(CopyImplementationError::NotAnAdt) => {
316                        span_err!(tcx.sess, span, E0206,
317                                  "the trait `Copy` may not be implemented \
318                                   for this type; type is not a structure or \
319                                   enumeration")
320                 }
321                 Err(CopyImplementationError::HasDestructor) => {
322                     span_err!(tcx.sess, span, E0184,
323                               "the trait `Copy` may not be implemented for this type; \
324                                the type has a destructor");
325                 }
326             }
327         });
328     }
329
330     /// Process implementations of the built-in trait `CoerceUnsized`.
331     fn check_implementations_of_coerce_unsized(&self) {
332         let tcx = self.crate_context.tcx;
333         let coerce_unsized_trait = match tcx.lang_items.coerce_unsized_trait() {
334             Some(id) => id,
335             None => return,
336         };
337         let unsize_trait = match tcx.lang_items.require(UnsizeTraitLangItem) {
338             Ok(id) => id,
339             Err(err) => {
340                 tcx.sess.fatal(&format!("`CoerceUnsized` implementation {}", err));
341             }
342         };
343
344         let trait_def = tcx.lookup_trait_def(coerce_unsized_trait);
345
346         trait_def.for_each_impl(tcx, |impl_did| {
347             debug!("check_implementations_of_coerce_unsized: impl_did={:?}",
348                    impl_did);
349
350             let impl_node_id = if let Some(n) = tcx.map.as_local_node_id(impl_did) {
351                 n
352             } else {
353                 debug!("check_implementations_of_coerce_unsized(): impl not \
354                         in this crate");
355                 return;
356             };
357
358             let source = tcx.lookup_item_type(impl_did).ty;
359             let trait_ref = self.crate_context.tcx.impl_trait_ref(impl_did).unwrap();
360             let target = *trait_ref.substs.types.get(subst::TypeSpace, 0);
361             debug!("check_implementations_of_coerce_unsized: {:?} -> {:?} (bound)",
362                    source, target);
363
364             let span = tcx.map.span(impl_node_id);
365             let param_env = ParameterEnvironment::for_item(tcx, impl_node_id);
366             let source = source.subst(tcx, &param_env.free_substs);
367             let target = target.subst(tcx, &param_env.free_substs);
368             assert!(!source.has_escaping_regions());
369
370             debug!("check_implementations_of_coerce_unsized: {:?} -> {:?} (free)",
371                    source, target);
372
373             let infcx = new_infer_ctxt(tcx, &tcx.tables, Some(param_env), true);
374
375             let check_mutbl = |mt_a: ty::TypeAndMut<'tcx>, mt_b: ty::TypeAndMut<'tcx>,
376                                mk_ptr: &Fn(Ty<'tcx>) -> Ty<'tcx>| {
377                 if (mt_a.mutbl, mt_b.mutbl) == (hir::MutImmutable, hir::MutMutable) {
378                     infcx.report_mismatched_types(span, mk_ptr(mt_b.ty),
379                                                   target, &ty::error::TypeError::Mutability);
380                 }
381                 (mt_a.ty, mt_b.ty, unsize_trait, None)
382             };
383             let (source, target, trait_def_id, kind) = match (&source.sty, &target.sty) {
384                 (&ty::TyBox(a), &ty::TyBox(b)) => (a, b, unsize_trait, None),
385
386                 (&ty::TyRef(r_a, mt_a), &ty::TyRef(r_b, mt_b)) => {
387                     infer::mk_subr(&infcx, infer::RelateObjectBound(span), *r_b, *r_a);
388                     check_mutbl(mt_a, mt_b, &|ty| tcx.mk_imm_ref(r_b, ty))
389                 }
390
391                 (&ty::TyRef(_, mt_a), &ty::TyRawPtr(mt_b)) |
392                 (&ty::TyRawPtr(mt_a), &ty::TyRawPtr(mt_b)) => {
393                     check_mutbl(mt_a, mt_b, &|ty| tcx.mk_imm_ptr(ty))
394                 }
395
396                 (&ty::TyStruct(def_a, substs_a), &ty::TyStruct(def_b, substs_b)) => {
397                     if def_a != def_b {
398                         let source_path = tcx.item_path_str(def_a.did);
399                         let target_path = tcx.item_path_str(def_b.did);
400                         span_err!(tcx.sess, span, E0377,
401                                   "the trait `CoerceUnsized` may only be implemented \
402                                    for a coercion between structures with the same \
403                                    definition; expected {}, found {}",
404                                   source_path, target_path);
405                         return;
406                     }
407
408                     let origin = TypeOrigin::Misc(span);
409                     let fields = &def_a.struct_variant().fields;
410                     let diff_fields = fields.iter().enumerate().filter_map(|(i, f)| {
411                         let (a, b) = (f.ty(tcx, substs_a), f.ty(tcx, substs_b));
412
413                         if f.unsubst_ty().is_phantom_data() {
414                             // Ignore PhantomData fields
415                             None
416                         } else if infcx.sub_types(false, origin, b, a).is_ok() {
417                             // Ignore fields that aren't significantly changed
418                             None
419                         } else {
420                             // Collect up all fields that were significantly changed
421                             // i.e. those that contain T in coerce_unsized T -> U
422                             Some((i, a, b))
423                         }
424                     }).collect::<Vec<_>>();
425
426                     if diff_fields.is_empty() {
427                         span_err!(tcx.sess, span, E0374,
428                                   "the trait `CoerceUnsized` may only be implemented \
429                                    for a coercion between structures with one field \
430                                    being coerced, none found");
431                         return;
432                     } else if diff_fields.len() > 1 {
433                         span_err!(tcx.sess, span, E0375,
434                                   "the trait `CoerceUnsized` may only be implemented \
435                                    for a coercion between structures with one field \
436                                    being coerced, but {} fields need coercions: {}",
437                                    diff_fields.len(), diff_fields.iter().map(|&(i, a, b)| {
438                                         let name = fields[i].name;
439                                         format!("{} ({} to {})",
440                                                 if name == token::special_names::unnamed_field {
441                                                     i.to_string()
442                                                 } else {
443                                                     name.to_string()
444                                                 }, a, b)
445                                    }).collect::<Vec<_>>().join(", "));
446                         return;
447                     }
448
449                     let (i, a, b) = diff_fields[0];
450                     let kind = ty::adjustment::CustomCoerceUnsized::Struct(i);
451                     (a, b, coerce_unsized_trait, Some(kind))
452                 }
453
454                 _ => {
455                     span_err!(tcx.sess, span, E0376,
456                               "the trait `CoerceUnsized` may only be implemented \
457                                for a coercion between structures");
458                     return;
459                 }
460             };
461
462             let mut fulfill_cx = infcx.fulfillment_cx.borrow_mut();
463
464             // Register an obligation for `A: Trait<B>`.
465             let cause = traits::ObligationCause::misc(span, impl_node_id);
466             let predicate = traits::predicate_for_trait_def(tcx, cause, trait_def_id,
467                                                             0, source, vec![target]);
468             fulfill_cx.register_predicate_obligation(&infcx, predicate);
469
470             // Check that all transitive obligations are satisfied.
471             if let Err(errors) = fulfill_cx.select_all_or_error(&infcx) {
472                 traits::report_fulfillment_errors(&infcx, &errors);
473             }
474
475             // Finally, resolve all regions.
476             let mut free_regions = FreeRegionMap::new();
477             free_regions.relate_free_regions_from_predicates(tcx, &infcx.parameter_environment
478                                                                         .caller_bounds);
479             infcx.resolve_regions_and_report_errors(&free_regions, impl_node_id);
480
481             if let Some(kind) = kind {
482                 tcx.custom_coerce_unsized_kinds.borrow_mut().insert(impl_did, kind);
483             }
484         });
485     }
486 }
487
488 fn enforce_trait_manually_implementable(tcx: &ty::ctxt, sp: Span, trait_def_id: DefId) {
489     if tcx.sess.features.borrow().unboxed_closures {
490         // the feature gate allows all of them
491         return
492     }
493     let did = Some(trait_def_id);
494     let li = &tcx.lang_items;
495
496     let trait_name = if did == li.fn_trait() {
497         "Fn"
498     } else if did == li.fn_mut_trait() {
499         "FnMut"
500     } else if did == li.fn_once_trait() {
501         "FnOnce"
502     } else {
503         return // everything OK
504     };
505     span_err!(tcx.sess, sp, E0183, "manual implementations of `{}` are experimental", trait_name);
506     fileline_help!(tcx.sess, sp,
507                "add `#![feature(unboxed_closures)]` to the crate attributes to enable");
508 }
509
510 pub fn check_coherence(crate_context: &CrateCtxt) {
511     CoherenceChecker {
512         crate_context: crate_context,
513         inference_context: new_infer_ctxt(crate_context.tcx, &crate_context.tcx.tables, None, true),
514         inherent_impls: RefCell::new(FnvHashMap()),
515     }.check(crate_context.tcx.map.krate());
516     unsafety::check(crate_context.tcx);
517     orphan::check(crate_context.tcx);
518     overlap::check(crate_context.tcx);
519 }