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