1 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
3 use crate::ty::subst::{Subst, SubstsRef};
4 use crate::ty::EarlyBinder;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_hir::def_id::DefId;
8 use rustc_span::symbol::Symbol;
11 use super::{EarlyBoundRegion, InstantiatedPredicates, ParamConst, ParamTy, Predicate, TyCtxt};
13 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
14 pub enum GenericParamDefKind {
16 Type { has_default: bool, object_lifetime_default: ObjectLifetimeDefault, synthetic: bool },
17 Const { has_default: bool },
20 impl GenericParamDefKind {
21 pub fn descr(&self) -> &'static str {
23 GenericParamDefKind::Lifetime => "lifetime",
24 GenericParamDefKind::Type { .. } => "type",
25 GenericParamDefKind::Const { .. } => "constant",
28 pub fn to_ord(&self) -> ast::ParamKindOrd {
30 GenericParamDefKind::Lifetime => ast::ParamKindOrd::Lifetime,
31 GenericParamDefKind::Type { .. } => ast::ParamKindOrd::Type,
32 GenericParamDefKind::Const { .. } => ast::ParamKindOrd::Const,
36 pub fn is_ty_or_const(&self) -> bool {
38 GenericParamDefKind::Lifetime => false,
39 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => true,
43 pub fn is_synthetic(&self) -> bool {
45 GenericParamDefKind::Type { synthetic, .. } => *synthetic,
51 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
52 pub struct GenericParamDef {
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,
62 pub kind: GenericParamDefKind,
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 }
70 bug!("cannot convert a non-lifetime parameter def to an early bound region")
74 pub fn has_default(&self) -> bool {
76 GenericParamDefKind::Type { has_default, .. }
77 | GenericParamDefKind::Const { has_default } => has_default,
78 GenericParamDefKind::Lifetime => false,
82 pub fn default_value<'tcx>(
85 ) -> Option<EarlyBinder<ty::GenericArg<'tcx>>> {
87 GenericParamDefKind::Type { has_default, .. } if has_default => {
88 Some(EarlyBinder(tcx.type_of(self.def_id).into()))
90 GenericParamDefKind::Const { has_default } if has_default => {
91 Some(EarlyBinder(tcx.const_param_default(self.def_id).into()))
99 pub struct GenericParamCount {
100 pub lifetimes: usize,
105 /// Information about the formal type/lifetime parameters associated
106 /// with an item or method. Analogous to `hir::Generics`.
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>,
116 /// Reverse map to the `index` field of each `GenericParamDef`.
117 #[stable_hasher(ignore)]
118 pub param_def_id_to_index: FxHashMap<DefId, u32>,
121 pub has_late_bound_regions: Option<Span>,
124 impl<'tcx> Generics {
126 pub fn count(&self) -> usize {
127 self.parent_count + self.params.len()
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();
136 for param in &self.params {
138 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
139 GenericParamDefKind::Type { .. } => own_counts.types += 1,
140 GenericParamDefKind::Const { .. } => own_counts.consts += 1,
147 pub fn own_defaults(&self) -> GenericParamCount {
148 let mut own_defaults = GenericParamCount::default();
150 for param in &self.params {
152 GenericParamDefKind::Lifetime => (),
153 GenericParamDefKind::Type { has_default, .. } => {
154 own_defaults.types += has_default as usize;
156 GenericParamDefKind::Const { has_default } => {
157 own_defaults.consts += has_default as usize;
165 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
166 if self.own_requires_monomorphization() {
170 if let Some(parent_def_id) = self.parent {
171 let parent = tcx.generics_of(parent_def_id);
172 parent.requires_monomorphization(tcx)
178 pub fn own_requires_monomorphization(&self) -> bool {
179 for param in &self.params {
181 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
184 GenericParamDefKind::Lifetime => {}
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) {
195 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
196 .param_at(param_index, tcx)
200 /// Returns the `GenericParamDef` associated with this `EarlyBoundRegion`.
203 param: &EarlyBoundRegion,
205 ) -> &'tcx GenericParamDef {
206 let param = self.param_at(param.index as usize, tcx);
208 GenericParamDefKind::Lifetime => param,
209 _ => bug!("expected lifetime parameter, but found another generic parameter"),
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);
217 GenericParamDefKind::Type { .. } => param,
218 _ => bug!("expected type parameter, but found another generic parameter"),
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);
226 GenericParamDefKind::Const { .. } => param,
227 _ => bug!("expected const parameter, but found another generic parameter"),
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, .. })
238 /// Returns the substs corresponding to the generic parameters
239 /// of this item, excluding `Self`.
241 /// **This should only be used for diagnostics purposes.**
242 pub fn own_substs_no_defaults(
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;
252 // Filter the default arguments.
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
262 .take_while(|param| {
263 param.default_value(tcx).map_or(false, |default| {
264 default.subst(tcx, substs) == substs[param.index as usize]
272 /// Returns the substs corresponding to the generic parameters of this item, excluding `Self`.
274 /// **This should only be used for diagnostics purposes.**
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 }
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)],
291 impl<'tcx> GenericPredicates<'tcx> {
295 substs: SubstsRef<'tcx>,
296 ) -> InstantiatedPredicates<'tcx> {
297 let mut instantiated = InstantiatedPredicates::empty();
298 self.instantiate_into(tcx, &mut instantiated, substs);
302 pub fn instantiate_own(
305 substs: SubstsRef<'tcx>,
306 ) -> InstantiatedPredicates<'tcx> {
307 InstantiatedPredicates {
311 .map(|(p, _)| EarlyBinder(*p).subst(tcx, substs))
313 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
320 instantiated: &mut InstantiatedPredicates<'tcx>,
321 substs: SubstsRef<'tcx>,
323 if let Some(def_id) = self.parent {
324 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
328 .extend(self.predicates.iter().map(|(p, _)| EarlyBinder(*p).subst(tcx, substs)));
329 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
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);
338 fn instantiate_identity_into(
341 instantiated: &mut InstantiatedPredicates<'tcx>,
343 if let Some(def_id) = self.parent {
344 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
346 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
347 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));