]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/outlives.rs
Rollup merge of #55987 - Thomasdezeeuw:weak-ptr_eq, r=sfackler
[rust.git] / src / librustc / ty / outlives.rs
1 // Copyright 2012 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 // The outlines relation `T: 'a` or `'a: 'b`. This code frequently
12 // refers to rules defined in RFC 1214 (`OutlivesFooBar`), so see that
13 // RFC for reference.
14
15 use smallvec::SmallVec;
16 use ty::{self, Ty, TyCtxt, TypeFoldable};
17
18 #[derive(Debug)]
19 pub enum Component<'tcx> {
20     Region(ty::Region<'tcx>),
21     Param(ty::ParamTy),
22     UnresolvedInferenceVariable(ty::InferTy),
23
24     // Projections like `T::Foo` are tricky because a constraint like
25     // `T::Foo: 'a` can be satisfied in so many ways. There may be a
26     // where-clause that says `T::Foo: 'a`, or the defining trait may
27     // include a bound like `type Foo: 'static`, or -- in the most
28     // conservative way -- we can prove that `T: 'a` (more generally,
29     // that all components in the projection outlive `'a`). This code
30     // is not in a position to judge which is the best technique, so
31     // we just product the projection as a component and leave it to
32     // the consumer to decide (but see `EscapingProjection` below).
33     Projection(ty::ProjectionTy<'tcx>),
34
35     // In the case where a projection has escaping regions -- meaning
36     // regions bound within the type itself -- we always use
37     // the most conservative rule, which requires that all components
38     // outlive the bound. So for example if we had a type like this:
39     //
40     //     for<'a> Trait1<  <T as Trait2<'a,'b>>::Foo  >
41     //                      ~~~~~~~~~~~~~~~~~~~~~~~~~
42     //
43     // then the inner projection (underlined) has an escaping region
44     // `'a`. We consider that outer trait `'c` to meet a bound if `'b`
45     // outlives `'b: 'c`, and we don't consider whether the trait
46     // declares that `Foo: 'static` etc. Therefore, we just return the
47     // free components of such a projection (in this case, `'b`).
48     //
49     // However, in the future, we may want to get smarter, and
50     // actually return a "higher-ranked projection" here. Therefore,
51     // we mark that these components are part of an escaping
52     // projection, so that implied bounds code can avoid relying on
53     // them. This gives us room to improve the regionck reasoning in
54     // the future without breaking backwards compat.
55     EscapingProjection(Vec<Component<'tcx>>),
56 }
57
58 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
59     /// Push onto `out` all the things that must outlive `'a` for the condition
60     /// `ty0: 'a` to hold. Note that `ty0` must be a **fully resolved type**.
61     pub fn push_outlives_components(&self, ty0: Ty<'tcx>,
62                                     out: &mut SmallVec<[Component<'tcx>; 4]>) {
63         self.compute_components(ty0, out);
64         debug!("components({:?}) = {:?}", ty0, out);
65     }
66
67     fn compute_components(&self, ty: Ty<'tcx>, out: &mut SmallVec<[Component<'tcx>; 4]>) {
68         // Descend through the types, looking for the various "base"
69         // components and collecting them into `out`. This is not written
70         // with `collect()` because of the need to sometimes skip subtrees
71         // in the `subtys` iterator (e.g., when encountering a
72         // projection).
73         match ty.sty {
74             ty::Closure(def_id, ref substs) => {
75                 for upvar_ty in substs.upvar_tys(def_id, *self) {
76                     self.compute_components(upvar_ty, out);
77                 }
78             }
79
80             ty::Generator(def_id, ref substs, _) => {
81                 // Same as the closure case
82                 for upvar_ty in substs.upvar_tys(def_id, *self) {
83                     self.compute_components(upvar_ty, out);
84                 }
85
86                 // We ignore regions in the generator interior as we don't
87                 // want these to affect region inference
88             }
89
90             // All regions are bound inside a witness
91             ty::GeneratorWitness(..) => (),
92
93             // OutlivesTypeParameterEnv -- the actual checking that `X:'a`
94             // is implied by the environment is done in regionck.
95             ty::Param(p) => {
96                 out.push(Component::Param(p));
97             }
98
99             // For projections, we prefer to generate an obligation like
100             // `<P0 as Trait<P1...Pn>>::Foo: 'a`, because this gives the
101             // regionck more ways to prove that it holds. However,
102             // regionck is not (at least currently) prepared to deal with
103             // higher-ranked regions that may appear in the
104             // trait-ref. Therefore, if we see any higher-ranke regions,
105             // we simply fallback to the most restrictive rule, which
106             // requires that `Pi: 'a` for all `i`.
107             ty::Projection(ref data) => {
108                 if !data.has_escaping_bound_vars() {
109                     // best case: no escaping regions, so push the
110                     // projection and skip the subtree (thus generating no
111                     // constraints for Pi). This defers the choice between
112                     // the rules OutlivesProjectionEnv,
113                     // OutlivesProjectionTraitDef, and
114                     // OutlivesProjectionComponents to regionck.
115                     out.push(Component::Projection(*data));
116                 } else {
117                     // fallback case: hard code
118                     // OutlivesProjectionComponents.  Continue walking
119                     // through and constrain Pi.
120                     let subcomponents = self.capture_components(ty);
121                     out.push(Component::EscapingProjection(subcomponents));
122                 }
123             }
124
125             ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
126
127             // We assume that inference variables are fully resolved.
128             // So, if we encounter an inference variable, just record
129             // the unresolved variable as a component.
130             ty::Infer(infer_ty) => {
131                 out.push(Component::UnresolvedInferenceVariable(infer_ty));
132             }
133
134             // Most types do not introduce any region binders, nor
135             // involve any other subtle cases, and so the WF relation
136             // simply constraints any regions referenced directly by
137             // the type and then visits the types that are lexically
138             // contained within. (The comments refer to relevant rules
139             // from RFC1214.)
140             ty::Bool |            // OutlivesScalar
141             ty::Char |            // OutlivesScalar
142             ty::Int(..) |         // OutlivesScalar
143             ty::Uint(..) |        // OutlivesScalar
144             ty::Float(..) |       // OutlivesScalar
145             ty::Never |           // ...
146             ty::Adt(..) |         // OutlivesNominalType
147             ty::Opaque(..) |        // OutlivesNominalType (ish)
148             ty::Foreign(..) |     // OutlivesNominalType
149             ty::Str |             // OutlivesScalar (ish)
150             ty::Array(..) |       // ...
151             ty::Slice(..) |       // ...
152             ty::RawPtr(..) |      // ...
153             ty::Ref(..) |         // OutlivesReference
154             ty::Tuple(..) |       // ...
155             ty::FnDef(..) |       // OutlivesFunction (*)
156             ty::FnPtr(_) |        // OutlivesFunction (*)
157             ty::Dynamic(..) |       // OutlivesObject, OutlivesFragment (*)
158             ty::Placeholder(..) |
159             ty::Bound(..) |
160             ty::Error => {
161                 // (*) Bare functions and traits are both binders. In the
162                 // RFC, this means we would add the bound regions to the
163                 // "bound regions list".  In our representation, no such
164                 // list is maintained explicitly, because bound regions
165                 // themselves can be readily identified.
166
167                 push_region_constraints(ty, out);
168                 for subty in ty.walk_shallow() {
169                     self.compute_components(subty, out);
170                 }
171             }
172         }
173     }
174
175     fn capture_components(&self, ty: Ty<'tcx>) -> Vec<Component<'tcx>> {
176         let mut temp = smallvec![];
177         push_region_constraints(ty, &mut temp);
178         for subty in ty.walk_shallow() {
179             self.compute_components(subty, &mut temp);
180         }
181         temp.into_iter().collect()
182     }
183 }
184
185 fn push_region_constraints<'tcx>(ty: Ty<'tcx>, out: &mut SmallVec<[Component<'tcx>; 4]>) {
186     let mut regions = smallvec![];
187     ty.push_regions(&mut regions);
188     out.extend(regions.iter().filter(|&r| !r.is_late_bound()).map(|r| Component::Region(r)));
189 }