2 use crate::ty::subst::{Subst, SubstsRef};
3 use crate::ty::EarlyBinder;
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_hir::def_id::DefId;
7 use rustc_span::symbol::Symbol;
10 use super::{EarlyBoundRegion, InstantiatedPredicates, ParamConst, ParamTy, Predicate, TyCtxt};
12 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
13 pub enum GenericParamDefKind {
15 Type { has_default: bool, synthetic: bool },
16 Const { has_default: bool },
19 impl GenericParamDefKind {
20 pub fn descr(&self) -> &'static str {
22 GenericParamDefKind::Lifetime => "lifetime",
23 GenericParamDefKind::Type { .. } => "type",
24 GenericParamDefKind::Const { .. } => "constant",
27 pub fn to_ord(&self) -> ast::ParamKindOrd {
29 GenericParamDefKind::Lifetime => ast::ParamKindOrd::Lifetime,
30 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
31 ast::ParamKindOrd::TypeOrConst
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(tcx.bound_type_of(self.def_id).map_bound(|t| t.into()))
90 GenericParamDefKind::Const { has_default } if has_default => {
91 Some(tcx.bound_const_param_default(self.def_id).map_bound(|c| c.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 {
125 /// Looks through the generics and all parents to find the index of the
126 /// given param def-id. This is in comparison to the `param_def_id_to_index`
127 /// struct member, which only stores information about this item's own
129 pub fn param_def_id_to_index(&self, tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<u32> {
130 if let Some(idx) = self.param_def_id_to_index.get(&def_id) {
132 } else if let Some(parent) = self.parent {
133 let parent = tcx.generics_of(parent);
134 parent.param_def_id_to_index(tcx, def_id)
141 pub fn count(&self) -> usize {
142 self.parent_count + self.params.len()
145 pub fn own_counts(&self) -> GenericParamCount {
146 // We could cache this as a property of `GenericParamCount`, but
147 // the aim is to refactor this away entirely eventually and the
148 // presence of this method will be a constant reminder.
149 let mut own_counts = GenericParamCount::default();
151 for param in &self.params {
153 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
154 GenericParamDefKind::Type { .. } => own_counts.types += 1,
155 GenericParamDefKind::Const { .. } => own_counts.consts += 1,
162 pub fn own_defaults(&self) -> GenericParamCount {
163 let mut own_defaults = GenericParamCount::default();
165 for param in &self.params {
167 GenericParamDefKind::Lifetime => (),
168 GenericParamDefKind::Type { has_default, .. } => {
169 own_defaults.types += has_default as usize;
171 GenericParamDefKind::Const { has_default } => {
172 own_defaults.consts += has_default as usize;
180 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
181 if self.own_requires_monomorphization() {
185 if let Some(parent_def_id) = self.parent {
186 let parent = tcx.generics_of(parent_def_id);
187 parent.requires_monomorphization(tcx)
193 pub fn own_requires_monomorphization(&self) -> bool {
194 for param in &self.params {
196 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
199 GenericParamDefKind::Lifetime => {}
205 /// Returns the `GenericParamDef` with the given index.
206 pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
207 if let Some(index) = param_index.checked_sub(self.parent_count) {
210 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
211 .param_at(param_index, tcx)
215 /// Returns the `GenericParamDef` associated with this `EarlyBoundRegion`.
218 param: &EarlyBoundRegion,
220 ) -> &'tcx GenericParamDef {
221 let param = self.param_at(param.index as usize, tcx);
223 GenericParamDefKind::Lifetime => param,
224 _ => bug!("expected lifetime parameter, but found another generic parameter"),
228 /// Returns the `GenericParamDef` associated with this `ParamTy`.
229 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
230 let param = self.param_at(param.index as usize, tcx);
232 GenericParamDefKind::Type { .. } => param,
233 _ => bug!("expected type parameter, but found another generic parameter"),
237 /// Returns the `GenericParamDef` associated with this `ParamConst`.
238 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
239 let param = self.param_at(param.index as usize, tcx);
241 GenericParamDefKind::Const { .. } => param,
242 _ => bug!("expected const parameter, but found another generic parameter"),
246 /// Returns `true` if `params` has `impl Trait`.
247 pub fn has_impl_trait(&'tcx self) -> bool {
248 self.params.iter().any(|param| {
249 matches!(param.kind, ty::GenericParamDefKind::Type { synthetic: true, .. })
253 /// Returns the substs corresponding to the generic parameters
254 /// of this item, excluding `Self`.
256 /// **This should only be used for diagnostics purposes.**
257 pub fn own_substs_no_defaults(
260 substs: &'tcx [ty::GenericArg<'tcx>],
261 ) -> &'tcx [ty::GenericArg<'tcx>] {
262 let mut own_params = self.parent_count..self.count();
263 if self.has_self && self.parent.is_none() {
264 own_params.start = 1;
267 // Filter the default arguments.
269 // This currently uses structural equality instead
270 // of semantic equivalence. While not ideal, that's
271 // good enough for now as this should only be used
272 // for diagnostics anyways.
273 own_params.end -= self
277 .take_while(|param| {
278 param.default_value(tcx).map_or(false, |default| {
279 default.subst(tcx, substs) == substs[param.index as usize]
287 /// Returns the substs corresponding to the generic parameters of this item, excluding `Self`.
289 /// **This should only be used for diagnostics purposes.**
292 substs: &'tcx [ty::GenericArg<'tcx>],
293 ) -> &'tcx [ty::GenericArg<'tcx>] {
294 let own = &substs[self.parent_count..][..self.params.len()];
295 if self.has_self && self.parent.is_none() { &own[1..] } else { &own }
299 /// Bounds on generics.
300 #[derive(Copy, Clone, Default, Debug, TyEncodable, TyDecodable, HashStable)]
301 pub struct GenericPredicates<'tcx> {
302 pub parent: Option<DefId>,
303 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
306 impl<'tcx> GenericPredicates<'tcx> {
310 substs: SubstsRef<'tcx>,
311 ) -> InstantiatedPredicates<'tcx> {
312 let mut instantiated = InstantiatedPredicates::empty();
313 self.instantiate_into(tcx, &mut instantiated, substs);
317 pub fn instantiate_own(
320 substs: SubstsRef<'tcx>,
321 ) -> InstantiatedPredicates<'tcx> {
322 InstantiatedPredicates {
326 .map(|(p, _)| EarlyBinder(*p).subst(tcx, substs))
328 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
332 #[instrument(level = "debug", skip(self, tcx))]
336 instantiated: &mut InstantiatedPredicates<'tcx>,
337 substs: SubstsRef<'tcx>,
339 if let Some(def_id) = self.parent {
340 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
344 .extend(self.predicates.iter().map(|(p, _)| EarlyBinder(*p).subst(tcx, substs)));
345 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
348 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
349 let mut instantiated = InstantiatedPredicates::empty();
350 self.instantiate_identity_into(tcx, &mut instantiated);
354 fn instantiate_identity_into(
357 instantiated: &mut InstantiatedPredicates<'tcx>,
359 if let Some(def_id) = self.parent {
360 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
362 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
363 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));