2 use crate::ty::{EarlyBinder, SubstsRef};
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_hir::def_id::DefId;
6 use rustc_span::symbol::Symbol;
9 use super::{EarlyBoundRegion, InstantiatedPredicates, ParamConst, ParamTy, Predicate, TyCtxt};
11 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
12 pub enum GenericParamDefKind {
14 Type { has_default: bool, synthetic: bool },
15 Const { has_default: bool },
18 impl GenericParamDefKind {
19 pub fn descr(&self) -> &'static str {
21 GenericParamDefKind::Lifetime => "lifetime",
22 GenericParamDefKind::Type { .. } => "type",
23 GenericParamDefKind::Const { .. } => "constant",
26 pub fn to_ord(&self) -> ast::ParamKindOrd {
28 GenericParamDefKind::Lifetime => ast::ParamKindOrd::Lifetime,
29 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
30 ast::ParamKindOrd::TypeOrConst
35 pub fn is_ty_or_const(&self) -> bool {
37 GenericParamDefKind::Lifetime => false,
38 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => true,
42 pub fn is_synthetic(&self) -> bool {
44 GenericParamDefKind::Type { synthetic, .. } => *synthetic,
50 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
51 pub struct GenericParamDef {
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,
61 pub kind: GenericParamDefKind,
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 }
69 bug!("cannot convert a non-lifetime parameter def to an early bound region")
73 pub fn has_default(&self) -> bool {
75 GenericParamDefKind::Type { has_default, .. }
76 | GenericParamDefKind::Const { has_default } => has_default,
77 GenericParamDefKind::Lifetime => false,
81 pub fn default_value<'tcx>(
84 ) -> Option<EarlyBinder<ty::GenericArg<'tcx>>> {
86 GenericParamDefKind::Type { has_default, .. } if has_default => {
87 Some(tcx.bound_type_of(self.def_id).map_bound(|t| t.into()))
89 GenericParamDefKind::Const { has_default } if has_default => {
90 Some(tcx.bound_const_param_default(self.def_id).map_bound(|c| c.into()))
98 pub struct GenericParamCount {
104 /// Information about the formal type/lifetime parameters associated
105 /// with an item or method. Analogous to `hir::Generics`.
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>,
115 /// Reverse map to the `index` field of each `GenericParamDef`.
116 #[stable_hasher(ignore)]
117 pub param_def_id_to_index: FxHashMap<DefId, u32>,
120 pub has_late_bound_regions: Option<Span>,
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
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) {
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)
140 pub fn count(&self) -> usize {
141 self.parent_count + self.params.len()
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();
150 for param in &self.params {
152 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
153 GenericParamDefKind::Type { .. } => own_counts.types += 1,
154 GenericParamDefKind::Const { .. } => own_counts.consts += 1,
161 pub fn own_defaults(&self) -> GenericParamCount {
162 let mut own_defaults = GenericParamCount::default();
164 for param in &self.params {
166 GenericParamDefKind::Lifetime => (),
167 GenericParamDefKind::Type { has_default, .. } => {
168 own_defaults.types += has_default as usize;
170 GenericParamDefKind::Const { has_default } => {
171 own_defaults.consts += has_default as usize;
179 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
180 if self.own_requires_monomorphization() {
184 if let Some(parent_def_id) = self.parent {
185 let parent = tcx.generics_of(parent_def_id);
186 parent.requires_monomorphization(tcx)
192 pub fn own_requires_monomorphization(&self) -> bool {
193 for param in &self.params {
195 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
198 GenericParamDefKind::Lifetime => {}
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) {
209 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
210 .param_at(param_index, tcx)
214 /// Returns the `GenericParamDef` associated with this `EarlyBoundRegion`.
217 param: &EarlyBoundRegion,
219 ) -> &'tcx GenericParamDef {
220 let param = self.param_at(param.index as usize, tcx);
222 GenericParamDefKind::Lifetime => param,
223 _ => bug!("expected lifetime parameter, but found another generic parameter"),
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);
231 GenericParamDefKind::Type { .. } => param,
232 _ => bug!("expected type parameter, but found another generic parameter"),
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);
240 GenericParamDefKind::Const { .. } => param,
241 _ => bug!("expected const parameter, but found another generic parameter"),
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, .. })
252 /// Returns the substs corresponding to the generic parameters
253 /// of this item, excluding `Self`.
255 /// **This should only be used for diagnostics purposes.**
256 pub fn own_substs_no_defaults(
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;
266 // Filter the default arguments.
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
276 .take_while(|param| {
277 param.default_value(tcx).map_or(false, |default| {
278 default.subst(tcx, substs) == substs[param.index as usize]
286 /// Returns the substs corresponding to the generic parameters of this item, excluding `Self`.
288 /// **This should only be used for diagnostics purposes.**
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 }
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)],
305 impl<'tcx> GenericPredicates<'tcx> {
309 substs: SubstsRef<'tcx>,
310 ) -> InstantiatedPredicates<'tcx> {
311 let mut instantiated = InstantiatedPredicates::empty();
312 self.instantiate_into(tcx, &mut instantiated, substs);
316 pub fn instantiate_own(
319 substs: SubstsRef<'tcx>,
320 ) -> InstantiatedPredicates<'tcx> {
321 InstantiatedPredicates {
325 .map(|(p, _)| EarlyBinder(*p).subst(tcx, substs))
327 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
331 #[instrument(level = "debug", skip(self, tcx))]
335 instantiated: &mut InstantiatedPredicates<'tcx>,
336 substs: SubstsRef<'tcx>,
338 if let Some(def_id) = self.parent {
339 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
343 .extend(self.predicates.iter().map(|(p, _)| EarlyBinder(*p).subst(tcx, substs)));
344 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
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);
353 fn instantiate_identity_into(
356 instantiated: &mut InstantiatedPredicates<'tcx>,
358 if let Some(def_id) = self.parent {
359 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
361 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
362 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));