]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/generics.rs
Rollup merge of #95632 - evanrichter:master, r=joshtriplett
[rust.git] / compiler / rustc_middle / src / ty / generics.rs
1 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
2 use crate::ty;
3 use crate::ty::subst::{Subst, SubstsRef};
4 use crate::ty::EarlyBinder;
5 use rustc_ast as ast;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_hir::def_id::DefId;
8 use rustc_span::symbol::Symbol;
9 use rustc_span::Span;
10
11 use super::{EarlyBoundRegion, InstantiatedPredicates, ParamConst, ParamTy, Predicate, TyCtxt};
12
13 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
14 pub enum GenericParamDefKind {
15     Lifetime,
16     Type { has_default: bool, object_lifetime_default: ObjectLifetimeDefault, synthetic: bool },
17     Const { has_default: bool },
18 }
19
20 impl GenericParamDefKind {
21     pub fn descr(&self) -> &'static str {
22         match self {
23             GenericParamDefKind::Lifetime => "lifetime",
24             GenericParamDefKind::Type { .. } => "type",
25             GenericParamDefKind::Const { .. } => "constant",
26         }
27     }
28     pub fn to_ord(&self) -> ast::ParamKindOrd {
29         match self {
30             GenericParamDefKind::Lifetime => ast::ParamKindOrd::Lifetime,
31             GenericParamDefKind::Type { .. } => ast::ParamKindOrd::Type,
32             GenericParamDefKind::Const { .. } => ast::ParamKindOrd::Const,
33         }
34     }
35
36     pub fn is_ty_or_const(&self) -> bool {
37         match self {
38             GenericParamDefKind::Lifetime => false,
39             GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => true,
40         }
41     }
42 }
43
44 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
45 pub struct GenericParamDef {
46     pub name: Symbol,
47     pub def_id: DefId,
48     pub index: u32,
49
50     /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
51     /// on generic parameter `'a`/`T`, asserts data behind the parameter
52     /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
53     pub pure_wrt_drop: bool,
54
55     pub kind: GenericParamDefKind,
56 }
57
58 impl GenericParamDef {
59     pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
60         if let GenericParamDefKind::Lifetime = self.kind {
61             ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
62         } else {
63             bug!("cannot convert a non-lifetime parameter def to an early bound region")
64         }
65     }
66
67     pub fn has_default(&self) -> bool {
68         match self.kind {
69             GenericParamDefKind::Type { has_default, .. }
70             | GenericParamDefKind::Const { has_default } => has_default,
71             GenericParamDefKind::Lifetime => false,
72         }
73     }
74
75     pub fn default_value<'tcx>(
76         &self,
77         tcx: TyCtxt<'tcx>,
78     ) -> Option<EarlyBinder<ty::GenericArg<'tcx>>> {
79         match self.kind {
80             GenericParamDefKind::Type { has_default, .. } if has_default => {
81                 Some(EarlyBinder(tcx.type_of(self.def_id).into()))
82             }
83             GenericParamDefKind::Const { has_default } if has_default => {
84                 Some(EarlyBinder(tcx.const_param_default(self.def_id).into()))
85             }
86             _ => None,
87         }
88     }
89 }
90
91 #[derive(Default)]
92 pub struct GenericParamCount {
93     pub lifetimes: usize,
94     pub types: usize,
95     pub consts: usize,
96 }
97
98 /// Information about the formal type/lifetime parameters associated
99 /// with an item or method. Analogous to `hir::Generics`.
100 ///
101 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
102 /// `Self` (optionally), `Lifetime` params..., `Type` params...
103 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
104 pub struct Generics {
105     pub parent: Option<DefId>,
106     pub parent_count: usize,
107     pub params: Vec<GenericParamDef>,
108
109     /// Reverse map to the `index` field of each `GenericParamDef`.
110     #[stable_hasher(ignore)]
111     pub param_def_id_to_index: FxHashMap<DefId, u32>,
112
113     pub has_self: bool,
114     pub has_late_bound_regions: Option<Span>,
115 }
116
117 impl<'tcx> Generics {
118     #[inline]
119     pub fn count(&self) -> usize {
120         self.parent_count + self.params.len()
121     }
122
123     pub fn own_counts(&self) -> GenericParamCount {
124         // We could cache this as a property of `GenericParamCount`, but
125         // the aim is to refactor this away entirely eventually and the
126         // presence of this method will be a constant reminder.
127         let mut own_counts = GenericParamCount::default();
128
129         for param in &self.params {
130             match param.kind {
131                 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
132                 GenericParamDefKind::Type { .. } => own_counts.types += 1,
133                 GenericParamDefKind::Const { .. } => own_counts.consts += 1,
134             }
135         }
136
137         own_counts
138     }
139
140     pub fn own_defaults(&self) -> GenericParamCount {
141         let mut own_defaults = GenericParamCount::default();
142
143         for param in &self.params {
144             match param.kind {
145                 GenericParamDefKind::Lifetime => (),
146                 GenericParamDefKind::Type { has_default, .. } => {
147                     own_defaults.types += has_default as usize;
148                 }
149                 GenericParamDefKind::Const { has_default } => {
150                     own_defaults.consts += has_default as usize;
151                 }
152             }
153         }
154
155         own_defaults
156     }
157
158     pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
159         if self.own_requires_monomorphization() {
160             return true;
161         }
162
163         if let Some(parent_def_id) = self.parent {
164             let parent = tcx.generics_of(parent_def_id);
165             parent.requires_monomorphization(tcx)
166         } else {
167             false
168         }
169     }
170
171     pub fn own_requires_monomorphization(&self) -> bool {
172         for param in &self.params {
173             match param.kind {
174                 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
175                     return true;
176                 }
177                 GenericParamDefKind::Lifetime => {}
178             }
179         }
180         false
181     }
182
183     /// Returns the `GenericParamDef` with the given index.
184     pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
185         if let Some(index) = param_index.checked_sub(self.parent_count) {
186             &self.params[index]
187         } else {
188             tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
189                 .param_at(param_index, tcx)
190         }
191     }
192
193     /// Returns the `GenericParamDef` associated with this `EarlyBoundRegion`.
194     pub fn region_param(
195         &'tcx self,
196         param: &EarlyBoundRegion,
197         tcx: TyCtxt<'tcx>,
198     ) -> &'tcx GenericParamDef {
199         let param = self.param_at(param.index as usize, tcx);
200         match param.kind {
201             GenericParamDefKind::Lifetime => param,
202             _ => bug!("expected lifetime parameter, but found another generic parameter"),
203         }
204     }
205
206     /// Returns the `GenericParamDef` associated with this `ParamTy`.
207     pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
208         let param = self.param_at(param.index as usize, tcx);
209         match param.kind {
210             GenericParamDefKind::Type { .. } => param,
211             _ => bug!("expected type parameter, but found another generic parameter"),
212         }
213     }
214
215     /// Returns the `GenericParamDef` associated with this `ParamConst`.
216     pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
217         let param = self.param_at(param.index as usize, tcx);
218         match param.kind {
219             GenericParamDefKind::Const { .. } => param,
220             _ => bug!("expected const parameter, but found another generic parameter"),
221         }
222     }
223
224     /// Returns `true` if `params` has `impl Trait`.
225     pub fn has_impl_trait(&'tcx self) -> bool {
226         self.params.iter().any(|param| {
227             matches!(param.kind, ty::GenericParamDefKind::Type { synthetic: true, .. })
228         })
229     }
230
231     /// Returns the substs corresponding to the generic parameters of this item, excluding `Self`.
232     pub fn own_substs(&'tcx self, substs: SubstsRef<'tcx>) -> &'tcx [ty::GenericArg<'tcx>] {
233         let own = &substs[self.parent_count..][..self.params.len()];
234         if self.has_self && self.parent.is_none() { &own[1..] } else { &own }
235     }
236 }
237
238 /// Bounds on generics.
239 #[derive(Copy, Clone, Default, Debug, TyEncodable, TyDecodable, HashStable)]
240 pub struct GenericPredicates<'tcx> {
241     pub parent: Option<DefId>,
242     pub predicates: &'tcx [(Predicate<'tcx>, Span)],
243 }
244
245 impl<'tcx> GenericPredicates<'tcx> {
246     pub fn instantiate(
247         &self,
248         tcx: TyCtxt<'tcx>,
249         substs: SubstsRef<'tcx>,
250     ) -> InstantiatedPredicates<'tcx> {
251         let mut instantiated = InstantiatedPredicates::empty();
252         self.instantiate_into(tcx, &mut instantiated, substs);
253         instantiated
254     }
255
256     pub fn instantiate_own(
257         &self,
258         tcx: TyCtxt<'tcx>,
259         substs: SubstsRef<'tcx>,
260     ) -> InstantiatedPredicates<'tcx> {
261         InstantiatedPredicates {
262             predicates: self
263                 .predicates
264                 .iter()
265                 .map(|(p, _)| EarlyBinder(*p).subst(tcx, substs))
266                 .collect(),
267             spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
268         }
269     }
270
271     fn instantiate_into(
272         &self,
273         tcx: TyCtxt<'tcx>,
274         instantiated: &mut InstantiatedPredicates<'tcx>,
275         substs: SubstsRef<'tcx>,
276     ) {
277         if let Some(def_id) = self.parent {
278             tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
279         }
280         instantiated
281             .predicates
282             .extend(self.predicates.iter().map(|(p, _)| EarlyBinder(*p).subst(tcx, substs)));
283         instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
284     }
285
286     pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
287         let mut instantiated = InstantiatedPredicates::empty();
288         self.instantiate_identity_into(tcx, &mut instantiated);
289         instantiated
290     }
291
292     fn instantiate_identity_into(
293         &self,
294         tcx: TyCtxt<'tcx>,
295         instantiated: &mut InstantiatedPredicates<'tcx>,
296     ) {
297         if let Some(def_id) = self.parent {
298             tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
299         }
300         instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
301         instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
302     }
303 }