]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/inhabitedness/mod.rs
Rollup merge of #62096 - spastorino:impl-place-from, r=oli-obk,Centril
[rust.git] / src / librustc / ty / inhabitedness / mod.rs
1 use crate::ty::context::TyCtxt;
2 use crate::ty::{AdtDef, VariantDef, FieldDef, Ty, TyS};
3 use crate::ty::{DefId, SubstsRef};
4 use crate::ty::{AdtKind, Visibility};
5 use crate::ty::TyKind::*;
6
7 pub use self::def_id_forest::DefIdForest;
8
9 mod def_id_forest;
10
11 // The methods in this module calculate DefIdForests of modules in which a
12 // AdtDef/VariantDef/FieldDef is visibly uninhabited.
13 //
14 // # Example
15 // ```rust
16 // enum Void {}
17 // mod a {
18 //     pub mod b {
19 //         pub struct SecretlyUninhabited {
20 //             _priv: !,
21 //         }
22 //     }
23 // }
24 //
25 // mod c {
26 //     pub struct AlsoSecretlyUninhabited {
27 //         _priv: Void,
28 //     }
29 //     mod d {
30 //     }
31 // }
32 //
33 // struct Foo {
34 //     x: a::b::SecretlyUninhabited,
35 //     y: c::AlsoSecretlyUninhabited,
36 // }
37 // ```
38 // In this code, the type Foo will only be visibly uninhabited inside the
39 // modules b, c and d. Calling uninhabited_from on Foo or its AdtDef will
40 // return the forest of modules {b, c->d} (represented in a DefIdForest by the
41 // set {b, c})
42 //
43 // We need this information for pattern-matching on Foo or types that contain
44 // Foo.
45 //
46 // # Example
47 // ```rust
48 // let foo_result: Result<T, Foo> = ... ;
49 // let Ok(t) = foo_result;
50 // ```
51 // This code should only compile in modules where the uninhabitedness of Foo is
52 // visible.
53
54 impl<'tcx> TyCtxt<'tcx> {
55     /// Checks whether a type is visibly uninhabited from a particular module.
56     /// # Example
57     /// ```rust
58     /// enum Void {}
59     /// mod a {
60     ///     pub mod b {
61     ///         pub struct SecretlyUninhabited {
62     ///             _priv: !,
63     ///         }
64     ///     }
65     /// }
66     ///
67     /// mod c {
68     ///     pub struct AlsoSecretlyUninhabited {
69     ///         _priv: Void,
70     ///     }
71     ///     mod d {
72     ///     }
73     /// }
74     ///
75     /// struct Foo {
76     ///     x: a::b::SecretlyUninhabited,
77     ///     y: c::AlsoSecretlyUninhabited,
78     /// }
79     /// ```
80     /// In this code, the type `Foo` will only be visibly uninhabited inside the
81     /// modules b, c and d. This effects pattern-matching on `Foo` or types that
82     /// contain `Foo`.
83     ///
84     /// # Example
85     /// ```rust
86     /// let foo_result: Result<T, Foo> = ... ;
87     /// let Ok(t) = foo_result;
88     /// ```
89     /// This code should only compile in modules where the uninhabitedness of Foo is
90     /// visible.
91     pub fn is_ty_uninhabited_from(self, module: DefId, ty: Ty<'tcx>) -> bool {
92         // To check whether this type is uninhabited at all (not just from the
93         // given node) you could check whether the forest is empty.
94         // ```
95         // forest.is_empty()
96         // ```
97         self.ty_inhabitedness_forest(ty).contains(self, module)
98     }
99
100     pub fn is_ty_uninhabited_from_any_module(self, ty: Ty<'tcx>) -> bool {
101         !self.ty_inhabitedness_forest(ty).is_empty()
102     }
103
104     fn ty_inhabitedness_forest(self, ty: Ty<'tcx>) -> DefIdForest {
105         ty.uninhabited_from(self)
106     }
107 }
108
109 impl<'tcx> AdtDef {
110     /// Calculate the forest of DefIds from which this adt is visibly uninhabited.
111     fn uninhabited_from(&self, tcx: TyCtxt<'tcx>, substs: SubstsRef<'tcx>) -> DefIdForest {
112         // Non-exhaustive ADTs from other crates are always considered inhabited.
113         if self.is_variant_list_non_exhaustive() && !self.did.is_local() {
114             DefIdForest::empty()
115         } else {
116             DefIdForest::intersection(tcx, self.variants.iter().map(|v| {
117                 v.uninhabited_from(tcx, substs, self.adt_kind())
118             }))
119         }
120     }
121 }
122
123 impl<'tcx> VariantDef {
124     /// Calculate the forest of DefIds from which this variant is visibly uninhabited.
125     pub fn uninhabited_from(
126         &self,
127         tcx: TyCtxt<'tcx>,
128         substs: SubstsRef<'tcx>,
129         adt_kind: AdtKind,
130     ) -> DefIdForest {
131         let is_enum = match adt_kind {
132             // For now, `union`s are never considered uninhabited.
133             // The precise semantics of inhabitedness with respect to unions is currently undecided.
134             AdtKind::Union => return DefIdForest::empty(),
135             AdtKind::Enum => true,
136             AdtKind::Struct => false,
137         };
138         // Non-exhaustive variants from other crates are always considered inhabited.
139         if self.is_field_list_non_exhaustive() && !self.def_id.is_local() {
140             DefIdForest::empty()
141         } else {
142             DefIdForest::union(tcx, self.fields.iter().map(|f| {
143                 f.uninhabited_from(tcx, substs, is_enum)
144             }))
145         }
146     }
147 }
148
149 impl<'tcx> FieldDef {
150     /// Calculate the forest of DefIds from which this field is visibly uninhabited.
151     fn uninhabited_from(
152         &self,
153         tcx: TyCtxt<'tcx>,
154         substs: SubstsRef<'tcx>,
155         is_enum: bool,
156     ) -> DefIdForest {
157         let data_uninhabitedness = move || {
158             self.ty(tcx, substs).uninhabited_from(tcx)
159         };
160         // FIXME(canndrew): Currently enum fields are (incorrectly) stored with
161         // Visibility::Invisible so we need to override self.vis if we're
162         // dealing with an enum.
163         if is_enum {
164             data_uninhabitedness()
165         } else {
166             match self.vis {
167                 Visibility::Invisible => DefIdForest::empty(),
168                 Visibility::Restricted(from) => {
169                     let forest = DefIdForest::from_id(from);
170                     let iter = Some(forest).into_iter().chain(Some(data_uninhabitedness()));
171                     DefIdForest::intersection(tcx, iter)
172                 },
173                 Visibility::Public => data_uninhabitedness(),
174             }
175         }
176     }
177 }
178
179 impl<'tcx> TyS<'tcx> {
180     /// Calculate the forest of DefIds from which this type is visibly uninhabited.
181     fn uninhabited_from(&self, tcx: TyCtxt<'tcx>) -> DefIdForest {
182         match self.sty {
183             Adt(def, substs) => def.uninhabited_from(tcx, substs),
184
185             Never => DefIdForest::full(tcx),
186
187             Tuple(ref tys) => {
188                 DefIdForest::union(tcx, tys.iter().map(|ty| {
189                     ty.expect_ty().uninhabited_from(tcx)
190                 }))
191             }
192
193             Array(ty, len) => match len.assert_usize(tcx) {
194                 // If the array is definitely non-empty, it's uninhabited if
195                 // the type of its elements is uninhabited.
196                 Some(n) if n != 0 => ty.uninhabited_from(tcx),
197                 _ => DefIdForest::empty()
198             },
199
200             // References to uninitialised memory is valid for any type, including
201             // uninhabited types, in unsafe code, so we treat all references as
202             // inhabited.
203             // The precise semantics of inhabitedness with respect to references is currently
204             // undecided.
205             Ref(..) => DefIdForest::empty(),
206
207             _ => DefIdForest::empty(),
208         }
209     }
210 }