]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/coherence.rs
refactor a bit
[rust.git] / src / librustc / traits / coherence.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 //! See `README.md` for high-level documentation
12
13 use hir::def_id::{DefId, LOCAL_CRATE};
14 use syntax_pos::DUMMY_SP;
15 use traits::{self, Normalized, SelectionContext, Obligation, ObligationCause, Reveal};
16 use traits::select::IntercrateAmbiguityCause;
17 use ty::{self, Ty, TyCtxt};
18 use ty::subst::Subst;
19
20 use infer::{InferCtxt, InferOk};
21
22 #[derive(Copy, Clone, Debug)]
23 /// Whether we do the orphan check relative to this crate or
24 /// to some remote crate.
25 enum InCrate {
26     Local,
27     Remote
28 }
29
30 #[derive(Debug, Copy, Clone)]
31 pub enum Conflict {
32     Upstream,
33     Downstream { used_to_be_broken: bool }
34 }
35
36 pub struct OverlapResult<'tcx> {
37     pub impl_header: ty::ImplHeader<'tcx>,
38     pub intercrate_ambiguity_causes: Vec<IntercrateAmbiguityCause>,
39 }
40
41 /// If there are types that satisfy both impls, returns a suitably-freshened
42 /// `ImplHeader` with those types substituted
43 pub fn overlapping_impls<'cx, 'gcx, 'tcx>(infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
44                                           impl1_def_id: DefId,
45                                           impl2_def_id: DefId)
46                                           -> Option<OverlapResult<'tcx>>
47 {
48     debug!("impl_can_satisfy(\
49            impl1_def_id={:?}, \
50            impl2_def_id={:?})",
51            impl1_def_id,
52            impl2_def_id);
53
54     let selcx = &mut SelectionContext::intercrate(infcx);
55     overlap(selcx, impl1_def_id, impl2_def_id)
56 }
57
58 fn with_fresh_ty_vars<'cx, 'gcx, 'tcx>(selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
59                                        param_env: ty::ParamEnv<'tcx>,
60                                        impl_def_id: DefId)
61                                        -> ty::ImplHeader<'tcx>
62 {
63     let tcx = selcx.tcx();
64     let impl_substs = selcx.infcx().fresh_substs_for_item(DUMMY_SP, impl_def_id);
65
66     let header = ty::ImplHeader {
67         impl_def_id,
68         self_ty: tcx.type_of(impl_def_id),
69         trait_ref: tcx.impl_trait_ref(impl_def_id),
70         predicates: tcx.predicates_of(impl_def_id).predicates
71     }.subst(tcx, impl_substs);
72
73     let Normalized { value: mut header, obligations } =
74         traits::normalize(selcx, param_env, ObligationCause::dummy(), &header);
75
76     header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
77     header
78 }
79
80 /// Can both impl `a` and impl `b` be satisfied by a common type (including
81 /// `where` clauses)? If so, returns an `ImplHeader` that unifies the two impls.
82 fn overlap<'cx, 'gcx, 'tcx>(selcx: &mut SelectionContext<'cx, 'gcx, 'tcx>,
83                             a_def_id: DefId,
84                             b_def_id: DefId)
85                             -> Option<OverlapResult<'tcx>>
86 {
87     debug!("overlap(a_def_id={:?}, b_def_id={:?})",
88            a_def_id,
89            b_def_id);
90
91     // For the purposes of this check, we don't bring any skolemized
92     // types into scope; instead, we replace the generic types with
93     // fresh type variables, and hence we do our evaluations in an
94     // empty environment.
95     let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
96
97     let a_impl_header = with_fresh_ty_vars(selcx, param_env, a_def_id);
98     let b_impl_header = with_fresh_ty_vars(selcx, param_env, b_def_id);
99
100     debug!("overlap: a_impl_header={:?}", a_impl_header);
101     debug!("overlap: b_impl_header={:?}", b_impl_header);
102
103     // Do `a` and `b` unify? If not, no overlap.
104     let obligations = match selcx.infcx().at(&ObligationCause::dummy(), param_env)
105                                          .eq_impl_headers(&a_impl_header, &b_impl_header) {
106         Ok(InferOk { obligations, value: () }) => {
107             obligations
108         }
109         Err(_) => return None
110     };
111
112     debug!("overlap: unification check succeeded");
113
114     // Are any of the obligations unsatisfiable? If so, no overlap.
115     let infcx = selcx.infcx();
116     let opt_failing_obligation =
117         a_impl_header.predicates
118                      .iter()
119                      .chain(&b_impl_header.predicates)
120                      .map(|p| infcx.resolve_type_vars_if_possible(p))
121                      .map(|p| Obligation { cause: ObligationCause::dummy(),
122                                            param_env,
123                                            recursion_depth: 0,
124                                            predicate: p })
125                      .chain(obligations)
126                      .find(|o| !selcx.evaluate_obligation(o));
127
128     if let Some(failing_obligation) = opt_failing_obligation {
129         debug!("overlap: obligation unsatisfiable {:?}", failing_obligation);
130         return None
131     }
132
133     Some(OverlapResult {
134         impl_header: selcx.infcx().resolve_type_vars_if_possible(&a_impl_header),
135         intercrate_ambiguity_causes: selcx.intercrate_ambiguity_causes().to_vec(),
136     })
137 }
138
139 pub fn trait_ref_is_knowable<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
140                                              trait_ref: ty::TraitRef<'tcx>)
141                                              -> Option<Conflict>
142 {
143     debug!("trait_ref_is_knowable(trait_ref={:?})", trait_ref);
144     if orphan_check_trait_ref(tcx, trait_ref, InCrate::Remote).is_ok() {
145         // A downstream or cousin crate is allowed to implement some
146         // substitution of this trait-ref.
147
148         // A trait can be implementable for a trait ref by both the current
149         // crate and crates downstream of it. Older versions of rustc
150         // were not aware of this, causing incoherence (issue #43355).
151         let used_to_be_broken =
152             orphan_check_trait_ref(tcx, trait_ref, InCrate::Local).is_ok();
153         if used_to_be_broken {
154             debug!("trait_ref_is_knowable({:?}) - USED TO BE BROKEN", trait_ref);
155         }
156         return Some(Conflict::Downstream { used_to_be_broken });
157     }
158
159     if trait_ref_is_local_or_fundamental(tcx, trait_ref) {
160         // This is a local or fundamental trait, so future-compatibility
161         // is no concern. We know that downstream/cousin crates are not
162         // allowed to implement a substitution of this trait ref, which
163         // means impls could only come from dependencies of this crate,
164         // which we already know about.
165         return None;
166     }
167
168     // This is a remote non-fundamental trait, so if another crate
169     // can be the "final owner" of a substitution of this trait-ref,
170     // they are allowed to implement it future-compatibly.
171     //
172     // However, if we are a final owner, then nobody else can be,
173     // and if we are an intermediate owner, then we don't care
174     // about future-compatibility, which means that we're OK if
175     // we are an owner.
176     if orphan_check_trait_ref(tcx, trait_ref, InCrate::Local).is_ok() {
177         debug!("trait_ref_is_knowable: orphan check passed");
178         return None;
179     } else {
180         debug!("trait_ref_is_knowable: nonlocal, nonfundamental, unowned");
181         return Some(Conflict::Upstream);
182     }
183 }
184
185 pub fn trait_ref_is_local_or_fundamental<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
186                                                          trait_ref: ty::TraitRef<'tcx>)
187                                                          -> bool {
188     trait_ref.def_id.krate == LOCAL_CRATE || tcx.has_attr(trait_ref.def_id, "fundamental")
189 }
190
191 pub enum OrphanCheckErr<'tcx> {
192     NoLocalInputType,
193     UncoveredTy(Ty<'tcx>),
194 }
195
196 /// Checks the coherence orphan rules. `impl_def_id` should be the
197 /// def-id of a trait impl. To pass, either the trait must be local, or else
198 /// two conditions must be satisfied:
199 ///
200 /// 1. All type parameters in `Self` must be "covered" by some local type constructor.
201 /// 2. Some local type must appear in `Self`.
202 pub fn orphan_check<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
203                                     impl_def_id: DefId)
204                                     -> Result<(), OrphanCheckErr<'tcx>>
205 {
206     debug!("orphan_check({:?})", impl_def_id);
207
208     // We only except this routine to be invoked on implementations
209     // of a trait, not inherent implementations.
210     let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
211     debug!("orphan_check: trait_ref={:?}", trait_ref);
212
213     // If the *trait* is local to the crate, ok.
214     if trait_ref.def_id.is_local() {
215         debug!("trait {:?} is local to current crate",
216                trait_ref.def_id);
217         return Ok(());
218     }
219
220     orphan_check_trait_ref(tcx, trait_ref, InCrate::Local)
221 }
222
223 fn orphan_check_trait_ref<'tcx>(tcx: TyCtxt,
224                                 trait_ref: ty::TraitRef<'tcx>,
225                                 in_crate: InCrate)
226                                 -> Result<(), OrphanCheckErr<'tcx>>
227 {
228     debug!("orphan_check_trait_ref(trait_ref={:?}, in_crate={:?})",
229            trait_ref, in_crate);
230
231     // First, create an ordered iterator over all the type parameters to the trait, with the self
232     // type appearing first.
233     // Find the first input type that either references a type parameter OR
234     // some local type.
235     for input_ty in trait_ref.input_types() {
236         if ty_is_local(tcx, input_ty, in_crate) {
237             debug!("orphan_check_trait_ref: ty_is_local `{:?}`", input_ty);
238
239             // First local input type. Check that there are no
240             // uncovered type parameters.
241             let uncovered_tys = uncovered_tys(tcx, input_ty, in_crate);
242             for uncovered_ty in uncovered_tys {
243                 if let Some(param) = uncovered_ty.walk()
244                     .find(|t| is_possibly_remote_type(t, in_crate))
245                 {
246                     debug!("orphan_check_trait_ref: uncovered type `{:?}`", param);
247                     return Err(OrphanCheckErr::UncoveredTy(param));
248                 }
249             }
250
251             // OK, found local type, all prior types upheld invariant.
252             return Ok(());
253         }
254
255         // Otherwise, enforce invariant that there are no type
256         // parameters reachable.
257         if let Some(param) = input_ty.walk()
258             .find(|t| is_possibly_remote_type(t, in_crate))
259         {
260             debug!("orphan_check_trait_ref: uncovered type `{:?}`", param);
261             return Err(OrphanCheckErr::UncoveredTy(param));
262         }
263     }
264
265     // If we exit above loop, never found a local type.
266     debug!("orphan_check_trait_ref: no local type");
267     return Err(OrphanCheckErr::NoLocalInputType);
268 }
269
270 fn uncovered_tys<'tcx>(tcx: TyCtxt, ty: Ty<'tcx>, in_crate: InCrate)
271                        -> Vec<Ty<'tcx>> {
272     if ty_is_local_constructor(ty, in_crate) {
273         vec![]
274     } else if fundamental_ty(tcx, ty) {
275         ty.walk_shallow()
276           .flat_map(|t| uncovered_tys(tcx, t, in_crate))
277           .collect()
278     } else {
279         vec![ty]
280     }
281 }
282
283 fn is_possibly_remote_type(ty: Ty, _in_crate: InCrate) -> bool {
284     match ty.sty {
285         ty::TyProjection(..) | ty::TyParam(..) => true,
286         _ => false,
287     }
288 }
289
290 fn ty_is_local(tcx: TyCtxt, ty: Ty, in_crate: InCrate) -> bool {
291     ty_is_local_constructor(ty, in_crate) ||
292         fundamental_ty(tcx, ty) && ty.walk_shallow().any(|t| ty_is_local(tcx, t, in_crate))
293 }
294
295 fn fundamental_ty(tcx: TyCtxt, ty: Ty) -> bool {
296     match ty.sty {
297         ty::TyRef(..) => true,
298         ty::TyAdt(def, _) => def.is_fundamental(),
299         ty::TyDynamic(ref data, ..) => {
300             data.principal().map_or(false, |p| tcx.has_attr(p.def_id(), "fundamental"))
301         }
302         _ => false
303     }
304 }
305
306 fn def_id_is_local(def_id: DefId, in_crate: InCrate) -> bool {
307     match in_crate {
308         // The type is local to *this* crate - it will not be
309         // local in any other crate.
310         InCrate::Remote => false,
311         InCrate::Local => def_id.is_local()
312     }
313 }
314
315 fn ty_is_local_constructor(ty: Ty, in_crate: InCrate) -> bool {
316     debug!("ty_is_local_constructor({:?})", ty);
317
318     match ty.sty {
319         ty::TyBool |
320         ty::TyChar |
321         ty::TyInt(..) |
322         ty::TyUint(..) |
323         ty::TyFloat(..) |
324         ty::TyStr |
325         ty::TyFnDef(..) |
326         ty::TyFnPtr(_) |
327         ty::TyArray(..) |
328         ty::TySlice(..) |
329         ty::TyRawPtr(..) |
330         ty::TyRef(..) |
331         ty::TyNever |
332         ty::TyTuple(..) |
333         ty::TyParam(..) |
334         ty::TyProjection(..) => {
335             false
336         }
337
338         ty::TyInfer(..) => match in_crate {
339             InCrate::Local => false,
340             // The inference variable might be unified with a local
341             // type in that remote crate.
342             InCrate::Remote => true,
343         },
344
345         ty::TyAdt(def, _) => def_id_is_local(def.did, in_crate),
346         ty::TyForeign(did) => def_id_is_local(did, in_crate),
347
348         ty::TyDynamic(ref tt, ..) => {
349             tt.principal().map_or(false, |p| {
350                 def_id_is_local(p.def_id(), in_crate)
351             })
352         }
353
354         ty::TyError => {
355             true
356         }
357
358         ty::TyClosure(..) | ty::TyGenerator(..) | ty::TyAnon(..) => {
359             bug!("ty_is_local invoked on unexpected type: {:?}", ty)
360         }
361     }
362 }