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