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