]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_middle/src/ty/generic_args.rs
New upstream version 1.74.1+dfsg1
[rustc.git] / compiler / rustc_middle / src / ty / generic_args.rs
CommitLineData
add651ee 1// Generic arguments.
970d7e83 2
3dfed10e 3use crate::ty::codec::{TyDecoder, TyEncoder};
064997fb 4use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable};
add651ee 5use crate::ty::sty::{ClosureArgs, GeneratorArgs, InlineConstArgs};
9ffffee4 6use crate::ty::visit::{TypeVisitable, TypeVisitableExt, TypeVisitor};
923072b8 7use crate::ty::{self, Lift, List, ParamConst, Ty, TyCtxt};
970d7e83 8
487cf647 9use rustc_data_structures::intern::Interned;
9c376795 10use rustc_errors::{DiagnosticArgValue, IntoDiagnosticArg};
dfeec247 11use rustc_hir::def_id::DefId;
532ac7d7 12use rustc_macros::HashStable;
3dfed10e 13use rustc_serialize::{self, Decodable, Encodable};
fe692bf9 14use rustc_span::sym;
487cf647 15use rustc_type_ir::WithCachedTypeInfo;
dfeec247 16use smallvec::SmallVec;
1a4d82fc 17
0531ce1d 18use core::intrinsics;
532ac7d7 19use std::cmp::Ordering;
9e0c209e
SL
20use std::marker::PhantomData;
21use std::mem;
0531ce1d 22use std::num::NonZeroUsize;
487cf647 23use std::ops::{ControlFlow, Deref};
9e0c209e 24
a1dfa0c6 25/// An entity in the Rust type system, which can be one of
532ac7d7 26/// several kinds (types, lifetimes, and consts).
94222f64 27/// To reduce memory usage, a `GenericArg` is an interned pointer,
9e0c209e 28/// with the lowest 2 bits being reserved for a tag to
532ac7d7 29/// indicate the type (`Ty`, `Region`, or `Const`) it points to.
5099ac24
FG
30///
31/// Note: the `PartialEq`, `Eq` and `Hash` derives are only valid because `Ty`,
32/// `Region` and `Const` are all interned.
0531ce1d 33#[derive(Copy, Clone, PartialEq, Eq, Hash)]
e74abb32 34pub struct GenericArg<'tcx> {
0531ce1d 35 ptr: NonZeroUsize,
5099ac24 36 marker: PhantomData<(Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>)>,
970d7e83
LB
37}
38
9c376795
FG
39impl<'tcx> IntoDiagnosticArg for GenericArg<'tcx> {
40 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
41 self.to_string().into_diagnostic_arg()
42 }
43}
44
9e0c209e
SL
45const TAG_MASK: usize = 0b11;
46const TYPE_TAG: usize = 0b00;
47const REGION_TAG: usize = 0b01;
532ac7d7 48const CONST_TAG: usize = 0b10;
9e0c209e 49
49aad941 50#[derive(Debug, TyEncodable, TyDecodable, PartialEq, Eq, PartialOrd, Ord, HashStable)]
e74abb32 51pub enum GenericArgKind<'tcx> {
0531ce1d
XL
52 Lifetime(ty::Region<'tcx>),
53 Type(Ty<'tcx>),
5099ac24 54 Const(ty::Const<'tcx>),
0531ce1d
XL
55}
56
e74abb32 57impl<'tcx> GenericArgKind<'tcx> {
5099ac24 58 #[inline]
e74abb32 59 fn pack(self) -> GenericArg<'tcx> {
0531ce1d 60 let (tag, ptr) = match self {
e74abb32 61 GenericArgKind::Lifetime(lt) => {
0531ce1d 62 // Ensure we can use the tag bits.
923072b8
FG
63 assert_eq!(mem::align_of_val(&*lt.0.0) & TAG_MASK, 0);
64 (REGION_TAG, lt.0.0 as *const ty::RegionKind<'tcx> as usize)
0531ce1d 65 }
e74abb32 66 GenericArgKind::Type(ty) => {
0531ce1d 67 // Ensure we can use the tag bits.
923072b8 68 assert_eq!(mem::align_of_val(&*ty.0.0) & TAG_MASK, 0);
487cf647 69 (TYPE_TAG, ty.0.0 as *const WithCachedTypeInfo<ty::TyKind<'tcx>> as usize)
0531ce1d 70 }
e74abb32 71 GenericArgKind::Const(ct) => {
532ac7d7 72 // Ensure we can use the tag bits.
923072b8 73 assert_eq!(mem::align_of_val(&*ct.0.0) & TAG_MASK, 0);
9c376795 74 (CONST_TAG, ct.0.0 as *const ty::ConstData<'tcx> as usize)
532ac7d7 75 }
0531ce1d 76 };
9e0c209e 77
dfeec247 78 GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData }
1a4d82fc 79 }
9cc50fc6
SL
80}
81
e74abb32 82impl<'tcx> Ord for GenericArg<'tcx> {
923072b8 83 fn cmp(&self, other: &GenericArg<'tcx>) -> Ordering {
b7449926 84 self.unpack().cmp(&other.unpack())
94b46f34
XL
85 }
86}
87
e74abb32 88impl<'tcx> PartialOrd for GenericArg<'tcx> {
923072b8 89 fn partial_cmp(&self, other: &GenericArg<'tcx>) -> Option<Ordering> {
94b46f34
XL
90 Some(self.cmp(&other))
91 }
92}
93
e74abb32 94impl<'tcx> From<ty::Region<'tcx>> for GenericArg<'tcx> {
5099ac24 95 #[inline]
e74abb32
XL
96 fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> {
97 GenericArgKind::Lifetime(r).pack()
0531ce1d
XL
98 }
99}
9e0c209e 100
e74abb32 101impl<'tcx> From<Ty<'tcx>> for GenericArg<'tcx> {
5099ac24 102 #[inline]
e74abb32
XL
103 fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> {
104 GenericArgKind::Type(ty).pack()
970d7e83
LB
105 }
106}
107
5099ac24
FG
108impl<'tcx> From<ty::Const<'tcx>> for GenericArg<'tcx> {
109 #[inline]
110 fn from(c: ty::Const<'tcx>) -> GenericArg<'tcx> {
e74abb32 111 GenericArgKind::Const(c).pack()
532ac7d7
XL
112 }
113}
114
487cf647
FG
115impl<'tcx> From<ty::Term<'tcx>> for GenericArg<'tcx> {
116 fn from(value: ty::Term<'tcx>) -> Self {
117 match value.unpack() {
118 ty::TermKind::Ty(t) => t.into(),
119 ty::TermKind::Const(c) => c.into(),
120 }
121 }
122}
123
e74abb32 124impl<'tcx> GenericArg<'tcx> {
9e0c209e 125 #[inline]
e74abb32 126 pub fn unpack(self) -> GenericArgKind<'tcx> {
7cac9316 127 let ptr = self.ptr.get();
5099ac24
FG
128 // SAFETY: use of `Interned::new_unchecked` here is ok because these
129 // pointers were originally created from `Interned` types in `pack()`,
130 // and this is just going in the other direction.
9e0c209e 131 unsafe {
0531ce1d 132 match ptr & TAG_MASK {
5099ac24 133 REGION_TAG => GenericArgKind::Lifetime(ty::Region(Interned::new_unchecked(
923072b8 134 &*((ptr & !TAG_MASK) as *const ty::RegionKind<'tcx>),
5099ac24
FG
135 ))),
136 TYPE_TAG => GenericArgKind::Type(Ty(Interned::new_unchecked(
487cf647 137 &*((ptr & !TAG_MASK) as *const WithCachedTypeInfo<ty::TyKind<'tcx>>),
5099ac24
FG
138 ))),
139 CONST_TAG => GenericArgKind::Const(ty::Const(Interned::new_unchecked(
9c376795 140 &*((ptr & !TAG_MASK) as *const ty::ConstData<'tcx>),
5099ac24 141 ))),
dfeec247 142 _ => intrinsics::unreachable(),
0531ce1d 143 }
1a4d82fc
JJ
144 }
145 }
48663c56 146
49aad941
FG
147 #[inline]
148 pub fn as_type(self) -> Option<Ty<'tcx>> {
064997fb 149 match self.unpack() {
49aad941
FG
150 GenericArgKind::Type(ty) => Some(ty),
151 _ => None,
064997fb
FG
152 }
153 }
154
49aad941
FG
155 #[inline]
156 pub fn as_region(self) -> Option<ty::Region<'tcx>> {
157 match self.unpack() {
158 GenericArgKind::Lifetime(re) => Some(re),
159 _ => None,
160 }
161 }
162
163 #[inline]
164 pub fn as_const(self) -> Option<ty::Const<'tcx>> {
165 match self.unpack() {
166 GenericArgKind::Const(ct) => Some(ct),
167 _ => None,
168 }
169 }
170
171 /// Unpack the `GenericArg` as a region when it is known certainly to be a region.
172 pub fn expect_region(self) -> ty::Region<'tcx> {
173 self.as_region().unwrap_or_else(|| bug!("expected a region, but found another kind"))
174 }
175
e74abb32 176 /// Unpack the `GenericArg` as a type when it is known certainly to be a type.
add651ee 177 /// This is true in cases where `GenericArgs` is used in places where the kinds are known
48663c56
XL
178 /// to be limited (e.g. in tuples, where the only parameters are type parameters).
179 pub fn expect_ty(self) -> Ty<'tcx> {
49aad941 180 self.as_type().unwrap_or_else(|| bug!("expected a type, but found another kind"))
48663c56 181 }
ba9703b0
XL
182
183 /// Unpack the `GenericArg` as a const when it is known certainly to be a const.
5099ac24 184 pub fn expect_const(self) -> ty::Const<'tcx> {
49aad941 185 self.as_const().unwrap_or_else(|| bug!("expected a const, but found another kind"))
ba9703b0 186 }
2b03887a
FG
187
188 pub fn is_non_region_infer(self) -> bool {
189 match self.unpack() {
190 GenericArgKind::Lifetime(_) => false,
9c376795 191 GenericArgKind::Type(ty) => ty.is_ty_or_numeric_infer(),
2b03887a
FG
192 GenericArgKind::Const(ct) => ct.is_ct_infer(),
193 }
194 }
9e0c209e 195}
1a4d82fc 196
e74abb32
XL
197impl<'a, 'tcx> Lift<'tcx> for GenericArg<'a> {
198 type Lifted = GenericArg<'tcx>;
0531ce1d 199
29967ef6 200 fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
0531ce1d 201 match self.unpack() {
29967ef6
XL
202 GenericArgKind::Lifetime(lt) => tcx.lift(lt).map(|lt| lt.into()),
203 GenericArgKind::Type(ty) => tcx.lift(ty).map(|ty| ty.into()),
204 GenericArgKind::Const(ct) => tcx.lift(ct).map(|ct| ct.into()),
abe05a73
XL
205 }
206 }
207}
208
9ffffee4
FG
209impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for GenericArg<'tcx> {
210 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
211 self,
212 folder: &mut F,
213 ) -> Result<Self, F::Error> {
0531ce1d 214 match self.unpack() {
a2a8927a
XL
215 GenericArgKind::Lifetime(lt) => lt.try_fold_with(folder).map(Into::into),
216 GenericArgKind::Type(ty) => ty.try_fold_with(folder).map(Into::into),
217 GenericArgKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
1a4d82fc 218 }
1a4d82fc 219 }
064997fb 220}
1a4d82fc 221
9ffffee4
FG
222impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for GenericArg<'tcx> {
223 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
0531ce1d 224 match self.unpack() {
e74abb32
XL
225 GenericArgKind::Lifetime(lt) => lt.visit_with(visitor),
226 GenericArgKind::Type(ty) => ty.visit_with(visitor),
227 GenericArgKind::Const(ct) => ct.visit_with(visitor),
1a4d82fc
JJ
228 }
229 }
9e0c209e 230}
1a4d82fc 231
923072b8
FG
232impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for GenericArg<'tcx> {
233 fn encode(&self, e: &mut E) {
94b46f34 234 self.unpack().encode(e)
1a4d82fc 235 }
9e0c209e 236}
1a4d82fc 237
923072b8 238impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for GenericArg<'tcx> {
5099ac24
FG
239 fn decode(d: &mut D) -> GenericArg<'tcx> {
240 GenericArgKind::decode(d).pack()
1a4d82fc 241 }
9e0c209e 242}
1a4d82fc 243
add651ee
FG
244/// List of generic arguments that are gonna be used to replace generic parameters.
245pub type GenericArgs<'tcx> = List<GenericArg<'tcx>>;
1a4d82fc 246
add651ee 247pub type GenericArgsRef<'tcx> = &'tcx GenericArgs<'tcx>;
532ac7d7 248
add651ee
FG
249impl<'tcx> GenericArgs<'tcx> {
250 /// Converts generic args to a type list.
49aad941
FG
251 ///
252 /// # Panics
253 ///
254 /// If any of the generic arguments are not types.
255 pub fn into_type_list(&self, tcx: TyCtxt<'tcx>) -> &'tcx List<Ty<'tcx>> {
256 tcx.mk_type_list_from_iter(self.iter().map(|arg| match arg.unpack() {
257 GenericArgKind::Type(ty) => ty,
add651ee 258 _ => bug!("`into_type_list` called on generic arg with non-types"),
49aad941 259 }))
5e7ed085
FG
260 }
261
add651ee
FG
262 /// Interpret these generic args as the args of a closure type.
263 /// Closure args have a particular structure controlled by the
e74abb32 264 /// compiler that encodes information like the signature and closure kind;
add651ee
FG
265 /// see `ty::ClosureArgs` struct for more comments.
266 pub fn as_closure(&'tcx self) -> ClosureArgs<'tcx> {
267 ClosureArgs { args: self }
e74abb32
XL
268 }
269
add651ee
FG
270 /// Interpret these generic args as the args of a generator type.
271 /// Generator args have a particular structure controlled by the
e74abb32 272 /// compiler that encodes information like the signature and generator kind;
add651ee
FG
273 /// see `ty::GeneratorArgs` struct for more comments.
274 pub fn as_generator(&'tcx self) -> GeneratorArgs<'tcx> {
275 GeneratorArgs { args: self }
e74abb32
XL
276 }
277
add651ee
FG
278 /// Interpret these generic args as the args of an inline const.
279 /// Inline const args have a particular structure controlled by the
3c0e092e 280 /// compiler that encodes information like the inferred type;
add651ee
FG
281 /// see `ty::InlineConstArgs` struct for more comments.
282 pub fn as_inline_const(&'tcx self) -> InlineConstArgs<'tcx> {
283 InlineConstArgs { args: self }
3c0e092e
XL
284 }
285
add651ee
FG
286 /// Creates an `GenericArgs` that maps each generic parameter to itself.
287 pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: impl Into<DefId>) -> GenericArgsRef<'tcx> {
353b0b11 288 Self::for_item(tcx, def_id.into(), |param, _| tcx.mk_param_from_def(param))
476ff2be
SL
289 }
290
add651ee 291 /// Creates an `GenericArgs` for generic parameter definitions,
94b46f34 292 /// by calling closures to obtain each kind.
add651ee 293 /// The closures get to observe the `GenericArgs` as they're
9e0c209e 294 /// being built, which can be used to correctly
add651ee
FG
295 /// replace defaults of generic parameters.
296 pub fn for_item<F>(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> GenericArgsRef<'tcx>
dc9dc135 297 where
e74abb32 298 F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
94b46f34 299 {
7cac9316 300 let defs = tcx.generics_of(def_id);
94b46f34 301 let count = defs.count();
add651ee
FG
302 let mut args = SmallVec::with_capacity(count);
303 Self::fill_item(&mut args, tcx, defs, &mut mk_kind);
304 tcx.mk_args(&args)
1a4d82fc
JJ
305 }
306
add651ee
FG
307 pub fn extend_to<F>(
308 &self,
309 tcx: TyCtxt<'tcx>,
310 def_id: DefId,
311 mut mk_kind: F,
312 ) -> GenericArgsRef<'tcx>
dc9dc135 313 where
e74abb32 314 F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
476ff2be 315 {
add651ee
FG
316 Self::for_item(tcx, def_id, |param, args| {
317 self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, args))
94b46f34 318 })
476ff2be
SL
319 }
320
94222f64 321 pub fn fill_item<F>(
add651ee 322 args: &mut SmallVec<[GenericArg<'tcx>; 8]>,
dc9dc135
XL
323 tcx: TyCtxt<'tcx>,
324 defs: &ty::Generics,
325 mk_kind: &mut F,
326 ) where
e74abb32 327 F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
94b46f34 328 {
9e0c209e 329 if let Some(def_id) = defs.parent {
7cac9316 330 let parent_defs = tcx.generics_of(def_id);
add651ee 331 Self::fill_item(args, tcx, parent_defs, mk_kind);
9e0c209e 332 }
add651ee 333 Self::fill_single(args, defs, mk_kind)
94b46f34 334 }
1a4d82fc 335
94222f64 336 pub fn fill_single<F>(
add651ee 337 args: &mut SmallVec<[GenericArg<'tcx>; 8]>,
dfeec247
XL
338 defs: &ty::Generics,
339 mk_kind: &mut F,
340 ) where
341 F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
94b46f34 342 {
add651ee 343 args.reserve(defs.params.len());
94b46f34 344 for param in &defs.params {
add651ee
FG
345 let kind = mk_kind(param, args);
346 assert_eq!(param.index as usize, args.len(), "{args:#?}, {defs:#?}");
347 args.push(kind);
9e0c209e 348 }
1a4d82fc
JJ
349 }
350
add651ee 351 // Extend an `original_args` list to the full number of args expected by `def_id`,
487cf647
FG
352 // filling in the missing parameters with error ty/ct or 'static regions.
353 pub fn extend_with_error(
354 tcx: TyCtxt<'tcx>,
355 def_id: DefId,
add651ee
FG
356 original_args: &[GenericArg<'tcx>],
357 ) -> GenericArgsRef<'tcx> {
358 ty::GenericArgs::for_item(tcx, def_id, |def, args| {
359 if let Some(arg) = original_args.get(def.index as usize) {
360 *arg
487cf647 361 } else {
add651ee 362 def.to_error(tcx, args)
487cf647
FG
363 }
364 })
365 }
366
9e0c209e 367 #[inline]
923072b8 368 pub fn types(&'tcx self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'tcx {
49aad941 369 self.iter().filter_map(|k| k.as_type())
1a4d82fc
JJ
370 }
371
9e0c209e 372 #[inline]
923072b8 373 pub fn regions(&'tcx self) -> impl DoubleEndedIterator<Item = ty::Region<'tcx>> + 'tcx {
49aad941 374 self.iter().filter_map(|k| k.as_region())
970d7e83 375 }
1a4d82fc 376
532ac7d7 377 #[inline]
923072b8 378 pub fn consts(&'tcx self) -> impl DoubleEndedIterator<Item = ty::Const<'tcx>> + 'tcx {
49aad941 379 self.iter().filter_map(|k| k.as_const())
532ac7d7
XL
380 }
381
781aab86 382 /// Returns generic arguments that are not lifetimes or host effect params.
532ac7d7
XL
383 #[inline]
384 pub fn non_erasable_generics(
923072b8 385 &'tcx self,
781aab86
FG
386 tcx: TyCtxt<'tcx>,
387 def_id: DefId,
923072b8 388 ) -> impl DoubleEndedIterator<Item = GenericArgKind<'tcx>> + 'tcx {
781aab86
FG
389 let generics = tcx.generics_of(def_id);
390 self.iter().enumerate().filter_map(|(i, k)| match k.unpack() {
391 _ if Some(i) == generics.host_effect_index => None,
392 ty::GenericArgKind::Lifetime(_) => None,
dfeec247 393 generic => Some(generic),
532ac7d7
XL
394 })
395 }
396
9e0c209e 397 #[inline]
9c376795 398 #[track_caller]
9e0c209e 399 pub fn type_at(&self, i: usize) -> Ty<'tcx> {
49aad941 400 self[i].as_type().unwrap_or_else(|| bug!("expected type for param #{} in {:?}", i, self))
1a4d82fc 401 }
1a4d82fc 402
9e0c209e 403 #[inline]
9c376795 404 #[track_caller]
7cac9316 405 pub fn region_at(&self, i: usize) -> ty::Region<'tcx> {
49aad941
FG
406 self[i]
407 .as_region()
408 .unwrap_or_else(|| bug!("expected region for param #{} in {:?}", i, self))
1a4d82fc
JJ
409 }
410
532ac7d7 411 #[inline]
9c376795 412 #[track_caller]
5099ac24 413 pub fn const_at(&self, i: usize) -> ty::Const<'tcx> {
49aad941 414 self[i].as_const().unwrap_or_else(|| bug!("expected const for param #{} in {:?}", i, self))
532ac7d7
XL
415 }
416
9e0c209e 417 #[inline]
9c376795 418 #[track_caller]
e74abb32 419 pub fn type_for_def(&self, def: &ty::GenericParamDef) -> GenericArg<'tcx> {
94b46f34 420 self.type_at(def.index as usize).into()
9e0c209e
SL
421 }
422
add651ee
FG
423 /// Transform from generic args for a child of `source_ancestor`
424 /// (e.g., a trait or impl) to args for the same child
425 /// in a different item, with `target_args` as the base for
9e0c209e 426 /// the target impl/trait, with the source child-specific
0731742a 427 /// parameters (e.g., method parameters) on top of that base.
f035d41b
XL
428 ///
429 /// For example given:
430 ///
431 /// ```no_run
432 /// trait X<S> { fn f<T>(); }
433 /// impl<U> X<U> for U { fn f<V>() {} }
434 /// ```
435 ///
add651ee 436 /// * If `self` is `[Self, S, T]`: the identity args of `f` in the trait.
f035d41b 437 /// * If `source_ancestor` is the def_id of the trait.
add651ee
FG
438 /// * If `target_args` is `[U]`, the args for the impl.
439 /// * Then we will return `[U, T]`, the arg for `f` in the impl that
f035d41b 440 /// are needed for it to match the trait.
dc9dc135
XL
441 pub fn rebase_onto(
442 &self,
443 tcx: TyCtxt<'tcx>,
444 source_ancestor: DefId,
add651ee
FG
445 target_args: GenericArgsRef<'tcx>,
446 ) -> GenericArgsRef<'tcx> {
7cac9316 447 let defs = tcx.generics_of(source_ancestor);
781aab86 448 tcx.mk_args_from_iter(target_args.iter().chain(self.iter().skip(defs.count())))
970d7e83 449 }
476ff2be 450
add651ee
FG
451 pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> GenericArgsRef<'tcx> {
452 tcx.mk_args_from_iter(self.iter().take(generics.count()))
476ff2be 453 }
fe692bf9
FG
454
455 pub fn host_effect_param(&'tcx self) -> Option<ty::Const<'tcx>> {
456 self.consts().rfind(|x| matches!(x.kind(), ty::ConstKind::Param(p) if p.name == sym::host))
457 }
781aab86
FG
458
459 pub fn print_as_list(&self) -> String {
460 let v = self.iter().map(|arg| arg.to_string()).collect::<Vec<_>>();
461 format!("[{}]", v.join(", "))
462 }
970d7e83
LB
463}
464
add651ee 465impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for GenericArgsRef<'tcx> {
9ffffee4
FG
466 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
467 self,
468 folder: &mut F,
469 ) -> Result<Self, F::Error> {
e74abb32
XL
470 // This code is hot enough that it's worth specializing for the most
471 // common length lists, to avoid the overhead of `SmallVec` creation.
472 // The match arms are in order of frequency. The 1, 2, and 0 cases are
473 // typically hit in 90--99.99% of cases. When folding doesn't change
add651ee
FG
474 // the args, it's faster to reuse the existing args rather than
475 // calling `mk_args`.
e74abb32
XL
476 match self.len() {
477 1 => {
a2a8927a 478 let param0 = self[0].try_fold_with(folder)?;
add651ee 479 if param0 == self[0] { Ok(self) } else { Ok(folder.interner().mk_args(&[param0])) }
e74abb32
XL
480 }
481 2 => {
a2a8927a
XL
482 let param0 = self[0].try_fold_with(folder)?;
483 let param1 = self[1].try_fold_with(folder)?;
e74abb32 484 if param0 == self[0] && param1 == self[1] {
a2a8927a 485 Ok(self)
e74abb32 486 } else {
add651ee 487 Ok(folder.interner().mk_args(&[param0, param1]))
e74abb32
XL
488 }
489 }
a2a8927a 490 0 => Ok(self),
add651ee 491 _ => ty::util::fold_list(self, folder, |tcx, v| tcx.mk_args(v)),
c30ab7b3 492 }
7453a54e 493 }
064997fb 494}
85aaf69f 495
9ffffee4
FG
496impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
497 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
498 self,
499 folder: &mut F,
500 ) -> Result<Self, F::Error> {
add651ee 501 // This code is fairly hot, though not as hot as `GenericArgsRef`.
5e7ed085
FG
502 //
503 // When compiling stage 2, I get the following results:
504 //
505 // len | total | %
506 // --- | --------- | -----
507 // 2 | 15083590 | 48.1
508 // 3 | 7540067 | 24.0
509 // 1 | 5300377 | 16.9
510 // 4 | 1351897 | 4.3
511 // 0 | 1256849 | 4.0
512 //
513 // I've tried it with some private repositories and got
514 // close to the same result, with 4 and 0 swapping places
515 // sometimes.
516 match self.len() {
517 2 => {
518 let param0 = self[0].try_fold_with(folder)?;
519 let param1 = self[1].try_fold_with(folder)?;
520 if param0 == self[0] && param1 == self[1] {
521 Ok(self)
522 } else {
9ffffee4 523 Ok(folder.interner().mk_type_list(&[param0, param1]))
5e7ed085
FG
524 }
525 }
9ffffee4 526 _ => ty::util::fold_list(self, folder, |tcx, v| tcx.mk_type_list(v)),
5e7ed085
FG
527 }
528 }
064997fb 529}
5e7ed085 530
9ffffee4 531impl<'tcx, T: TypeVisitable<TyCtxt<'tcx>>> TypeVisitable<TyCtxt<'tcx>> for &'tcx ty::List<T> {
2b03887a 532 #[inline]
9ffffee4 533 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
5e7ed085
FG
534 self.iter().try_for_each(|t| t.visit_with(visitor))
535 }
536}
537
487cf647 538/// Similar to [`super::Binder`] except that it tracks early bound generics, i.e. `struct Foo<T>(T)`
add651ee
FG
539/// needs `T` instantiated immediately. This type primarily exists to avoid forgetting to call
540/// `instantiate`.
9c376795 541///
add651ee
FG
542/// If you don't have anything to `instantiate`, you may be looking for
543/// [`instantiate_identity`](EarlyBinder::instantiate_identity) or [`skip_binder`](EarlyBinder::skip_binder).
2b03887a
FG
544#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
545#[derive(Encodable, Decodable, HashStable)]
fe692bf9
FG
546pub struct EarlyBinder<T> {
547 value: T,
548}
2b03887a 549
add651ee 550/// For early binders, you should first call `instantiate` before using any visitors.
9ffffee4
FG
551impl<'tcx, T> !TypeFoldable<TyCtxt<'tcx>> for ty::EarlyBinder<T> {}
552impl<'tcx, T> !TypeVisitable<TyCtxt<'tcx>> for ty::EarlyBinder<T> {}
2b03887a
FG
553
554impl<T> EarlyBinder<T> {
fe692bf9
FG
555 pub fn bind(value: T) -> EarlyBinder<T> {
556 EarlyBinder { value }
557 }
558
2b03887a 559 pub fn as_ref(&self) -> EarlyBinder<&T> {
fe692bf9 560 EarlyBinder { value: &self.value }
2b03887a 561 }
1a4d82fc 562
2b03887a
FG
563 pub fn map_bound_ref<F, U>(&self, f: F) -> EarlyBinder<U>
564 where
565 F: FnOnce(&T) -> U,
566 {
567 self.as_ref().map_bound(f)
568 }
569
570 pub fn map_bound<F, U>(self, f: F) -> EarlyBinder<U>
571 where
572 F: FnOnce(T) -> U,
573 {
fe692bf9
FG
574 let value = f(self.value);
575 EarlyBinder { value }
2b03887a
FG
576 }
577
578 pub fn try_map_bound<F, U, E>(self, f: F) -> Result<EarlyBinder<U>, E>
579 where
580 F: FnOnce(T) -> Result<U, E>,
581 {
fe692bf9
FG
582 let value = f(self.value)?;
583 Ok(EarlyBinder { value })
2b03887a
FG
584 }
585
586 pub fn rebind<U>(&self, value: U) -> EarlyBinder<U> {
fe692bf9 587 EarlyBinder { value }
2b03887a 588 }
9c376795
FG
589
590 /// Skips the binder and returns the "bound" value.
591 /// This can be used to extract data that does not depend on generic parameters
592 /// (e.g., getting the `DefId` of the inner value or getting the number of
593 /// arguments of an `FnSig`). Otherwise, consider using
add651ee 594 /// [`instantiate_identity`](EarlyBinder::instantiate_identity).
9c376795 595 ///
fe692bf9
FG
596 /// To skip the binder on `x: &EarlyBinder<T>` to obtain `&T`, leverage
597 /// [`EarlyBinder::as_ref`](EarlyBinder::as_ref): `x.as_ref().skip_binder()`.
598 ///
9c376795
FG
599 /// See also [`Binder::skip_binder`](super::Binder::skip_binder), which is
600 /// the analogous operation on [`super::Binder`].
601 pub fn skip_binder(self) -> T {
fe692bf9 602 self.value
9c376795 603 }
1a4d82fc
JJ
604}
605
2b03887a
FG
606impl<T> EarlyBinder<Option<T>> {
607 pub fn transpose(self) -> Option<EarlyBinder<T>> {
fe692bf9 608 self.value.map(|value| EarlyBinder { value })
2b03887a
FG
609 }
610}
611
612impl<T, U> EarlyBinder<(T, U)> {
613 pub fn transpose_tuple2(self) -> (EarlyBinder<T>, EarlyBinder<U>) {
fe692bf9
FG
614 let EarlyBinder { value: (lhs, rhs) } = self;
615 (EarlyBinder { value: lhs }, EarlyBinder { value: rhs })
2b03887a
FG
616 }
617}
04454e1e 618
487cf647
FG
619impl<'tcx, 's, I: IntoIterator> EarlyBinder<I>
620where
9ffffee4 621 I::Item: TypeFoldable<TyCtxt<'tcx>>,
487cf647 622{
add651ee 623 pub fn iter_instantiated(
2b03887a
FG
624 self,
625 tcx: TyCtxt<'tcx>,
add651ee
FG
626 args: &'s [GenericArg<'tcx>],
627 ) -> IterInstantiated<'s, 'tcx, I> {
628 IterInstantiated { it: self.value.into_iter(), tcx, args }
487cf647 629 }
49aad941 630
add651ee 631 /// Similar to [`instantiate_identity`](EarlyBinder::instantiate_identity),
49aad941 632 /// but on an iterator of `TypeFoldable` values.
add651ee 633 pub fn instantiate_identity_iter(self) -> I::IntoIter {
fe692bf9 634 self.value.into_iter()
49aad941 635 }
487cf647
FG
636}
637
add651ee 638pub struct IterInstantiated<'s, 'tcx, I: IntoIterator> {
487cf647
FG
639 it: I::IntoIter,
640 tcx: TyCtxt<'tcx>,
add651ee 641 args: &'s [GenericArg<'tcx>],
487cf647
FG
642}
643
add651ee 644impl<'tcx, I: IntoIterator> Iterator for IterInstantiated<'_, 'tcx, I>
487cf647 645where
9ffffee4 646 I::Item: TypeFoldable<TyCtxt<'tcx>>,
487cf647
FG
647{
648 type Item = I::Item;
649
650 fn next(&mut self) -> Option<Self::Item> {
add651ee 651 Some(EarlyBinder { value: self.it.next()? }.instantiate(self.tcx, self.args))
487cf647
FG
652 }
653
654 fn size_hint(&self) -> (usize, Option<usize>) {
655 self.it.size_hint()
2b03887a
FG
656 }
657}
658
add651ee 659impl<'tcx, I: IntoIterator> DoubleEndedIterator for IterInstantiated<'_, 'tcx, I>
487cf647
FG
660where
661 I::IntoIter: DoubleEndedIterator,
9ffffee4 662 I::Item: TypeFoldable<TyCtxt<'tcx>>,
487cf647
FG
663{
664 fn next_back(&mut self) -> Option<Self::Item> {
add651ee 665 Some(EarlyBinder { value: self.it.next_back()? }.instantiate(self.tcx, self.args))
487cf647
FG
666 }
667}
668
add651ee 669impl<'tcx, I: IntoIterator> ExactSizeIterator for IterInstantiated<'_, 'tcx, I>
9c376795
FG
670where
671 I::IntoIter: ExactSizeIterator,
9ffffee4 672 I::Item: TypeFoldable<TyCtxt<'tcx>>,
9c376795
FG
673{
674}
675
487cf647
FG
676impl<'tcx, 's, I: IntoIterator> EarlyBinder<I>
677where
678 I::Item: Deref,
9ffffee4 679 <I::Item as Deref>::Target: Copy + TypeFoldable<TyCtxt<'tcx>>,
2b03887a 680{
add651ee 681 pub fn iter_instantiated_copied(
2b03887a
FG
682 self,
683 tcx: TyCtxt<'tcx>,
add651ee
FG
684 args: &'s [GenericArg<'tcx>],
685 ) -> IterInstantiatedCopied<'s, 'tcx, I> {
686 IterInstantiatedCopied { it: self.value.into_iter(), tcx, args }
487cf647 687 }
49aad941 688
add651ee 689 /// Similar to [`instantiate_identity`](EarlyBinder::instantiate_identity),
49aad941 690 /// but on an iterator of values that deref to a `TypeFoldable`.
add651ee
FG
691 pub fn instantiate_identity_iter_copied(
692 self,
693 ) -> impl Iterator<Item = <I::Item as Deref>::Target> {
fe692bf9 694 self.value.into_iter().map(|v| *v)
49aad941 695 }
487cf647
FG
696}
697
add651ee 698pub struct IterInstantiatedCopied<'a, 'tcx, I: IntoIterator> {
487cf647
FG
699 it: I::IntoIter,
700 tcx: TyCtxt<'tcx>,
add651ee 701 args: &'a [GenericArg<'tcx>],
487cf647
FG
702}
703
add651ee 704impl<'tcx, I: IntoIterator> Iterator for IterInstantiatedCopied<'_, 'tcx, I>
487cf647
FG
705where
706 I::Item: Deref,
9ffffee4 707 <I::Item as Deref>::Target: Copy + TypeFoldable<TyCtxt<'tcx>>,
487cf647
FG
708{
709 type Item = <I::Item as Deref>::Target;
710
711 fn next(&mut self) -> Option<Self::Item> {
add651ee 712 self.it.next().map(|value| EarlyBinder { value: *value }.instantiate(self.tcx, self.args))
487cf647
FG
713 }
714
715 fn size_hint(&self) -> (usize, Option<usize>) {
716 self.it.size_hint()
717 }
718}
719
add651ee 720impl<'tcx, I: IntoIterator> DoubleEndedIterator for IterInstantiatedCopied<'_, 'tcx, I>
487cf647
FG
721where
722 I::IntoIter: DoubleEndedIterator,
723 I::Item: Deref,
9ffffee4 724 <I::Item as Deref>::Target: Copy + TypeFoldable<TyCtxt<'tcx>>,
487cf647
FG
725{
726 fn next_back(&mut self) -> Option<Self::Item> {
add651ee
FG
727 self.it
728 .next_back()
729 .map(|value| EarlyBinder { value: *value }.instantiate(self.tcx, self.args))
2b03887a
FG
730 }
731}
732
add651ee 733impl<'tcx, I: IntoIterator> ExactSizeIterator for IterInstantiatedCopied<'_, 'tcx, I>
9c376795
FG
734where
735 I::IntoIter: ExactSizeIterator,
736 I::Item: Deref,
9ffffee4 737 <I::Item as Deref>::Target: Copy + TypeFoldable<TyCtxt<'tcx>>,
9c376795
FG
738{
739}
740
2b03887a
FG
741pub struct EarlyBinderIter<T> {
742 t: T,
743}
744
745impl<T: IntoIterator> EarlyBinder<T> {
746 pub fn transpose_iter(self) -> EarlyBinderIter<T::IntoIter> {
fe692bf9 747 EarlyBinderIter { t: self.value.into_iter() }
2b03887a
FG
748 }
749}
750
751impl<T: Iterator> Iterator for EarlyBinderIter<T> {
752 type Item = EarlyBinder<T::Item>;
753
754 fn next(&mut self) -> Option<Self::Item> {
fe692bf9 755 self.t.next().map(|value| EarlyBinder { value })
2b03887a 756 }
487cf647
FG
757
758 fn size_hint(&self) -> (usize, Option<usize>) {
759 self.t.size_hint()
760 }
2b03887a
FG
761}
762
9ffffee4 763impl<'tcx, T: TypeFoldable<TyCtxt<'tcx>>> ty::EarlyBinder<T> {
add651ee
FG
764 pub fn instantiate(self, tcx: TyCtxt<'tcx>, args: &[GenericArg<'tcx>]) -> T {
765 let mut folder = ArgFolder { tcx, args, binders_passed: 0 };
fe692bf9 766 self.value.fold_with(&mut folder)
1a4d82fc 767 }
9c376795 768
add651ee 769 /// Makes the identity replacement `T0 => T0, ..., TN => TN`.
9c376795
FG
770 /// Conceptually, this converts universally bound variables into placeholders
771 /// when inside of a given item.
772 ///
773 /// For example, consider `for<T> fn foo<T>(){ .. }`:
774 /// - Outside of `foo`, `T` is bound (represented by the presence of `EarlyBinder`).
775 /// - Inside of the body of `foo`, we treat `T` as a placeholder by calling
add651ee
FG
776 /// `instantiate_identity` to discharge the `EarlyBinder`.
777 pub fn instantiate_identity(self) -> T {
fe692bf9 778 self.value
9c376795 779 }
9ffffee4
FG
780
781 /// Returns the inner value, but only if it contains no bound vars.
782 pub fn no_bound_vars(self) -> Option<T> {
fe692bf9 783 if !self.value.has_param() { Some(self.value) } else { None }
9ffffee4 784 }
1a4d82fc
JJ
785}
786
787///////////////////////////////////////////////////////////////////////////
788// The actual substitution engine itself is a type folder.
789
add651ee 790struct ArgFolder<'a, 'tcx> {
dc9dc135 791 tcx: TyCtxt<'tcx>,
add651ee 792 args: &'a [GenericArg<'tcx>],
1a4d82fc 793
48663c56 794 /// Number of region binders we have passed through while doing the substitution
a1dfa0c6 795 binders_passed: u32,
1a4d82fc
JJ
796}
797
add651ee 798impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ArgFolder<'a, 'tcx> {
064997fb 799 #[inline]
9ffffee4 800 fn interner(&self) -> TyCtxt<'tcx> {
dfeec247
XL
801 self.tcx
802 }
1a4d82fc 803
9ffffee4 804 fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>(
cdc7bbd5
XL
805 &mut self,
806 t: ty::Binder<'tcx, T>,
807 ) -> ty::Binder<'tcx, T> {
a1dfa0c6 808 self.binders_passed += 1;
54a0048b 809 let t = t.super_fold_with(self);
a1dfa0c6 810 self.binders_passed -= 1;
54a0048b 811 t
1a4d82fc
JJ
812 }
813
7cac9316 814 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
064997fb
FG
815 #[cold]
816 #[inline(never)]
add651ee 817 fn region_param_out_of_range(data: ty::EarlyBoundRegion, args: &[GenericArg<'_>]) -> ! {
064997fb 818 bug!(
add651ee 819 "Region parameter out of range when substituting in region {} (index={}, args = {:?})",
2b03887a
FG
820 data.name,
821 data.index,
add651ee 822 args,
2b03887a
FG
823 )
824 }
825
826 #[cold]
827 #[inline(never)]
828 fn region_param_invalid(data: ty::EarlyBoundRegion, other: GenericArgKind<'_>) -> ! {
829 bug!(
830 "Unexpected parameter {:?} when substituting in region {} (index={})",
831 other,
064997fb
FG
832 data.name,
833 data.index
834 )
835 }
836
1a4d82fc
JJ
837 // Note: This routine only handles regions that are bound on
838 // type declarations and other outer declarations, not those
839 // bound in *fn types*. Region substitution of the bound
840 // regions that appear in a function signature is done using
841 // the specialized routine `ty::replace_late_regions()`.
9e0c209e 842 match *r {
9346a6ac 843 ty::ReEarlyBound(data) => {
add651ee 844 let rk = self.args.get(data.index as usize).map(|k| k.unpack());
48663c56 845 match rk {
dfeec247 846 Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt),
2b03887a 847 Some(other) => region_param_invalid(data, other),
add651ee 848 None => region_param_out_of_range(data, self.args),
970d7e83
LB
849 }
850 }
49aad941
FG
851 ty::ReLateBound(..)
852 | ty::ReFree(_)
853 | ty::ReStatic
854 | ty::RePlaceholder(_)
855 | ty::ReErased
856 | ty::ReError(_) => r,
857 ty::ReVar(_) => bug!("unexpected region: {r:?}"),
970d7e83
LB
858 }
859 }
1a4d82fc
JJ
860
861 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
49aad941 862 if !t.has_param() {
1a4d82fc
JJ
863 return t;
864 }
865
1b1a35ee 866 match *t.kind() {
dfeec247
XL
867 ty::Param(p) => self.ty_for_param(p, t),
868 _ => t.super_fold_with(self),
1a4d82fc 869 }
1a4d82fc 870 }
532ac7d7 871
5099ac24 872 fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
923072b8 873 if let ty::ConstKind::Param(p) = c.kind() {
532ac7d7
XL
874 self.const_for_param(p, c)
875 } else {
876 c.super_fold_with(self)
877 }
878 }
970d7e83
LB
879}
880
add651ee 881impl<'a, 'tcx> ArgFolder<'a, 'tcx> {
1a4d82fc 882 fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> {
add651ee
FG
883 // Look up the type in the args. It really should be in there.
884 let opt_ty = self.args.get(p.index as usize).map(|k| k.unpack());
1a4d82fc 885 let ty = match opt_ty {
e74abb32 886 Some(GenericArgKind::Type(ty)) => ty,
064997fb
FG
887 Some(kind) => self.type_param_expected(p, source_ty, kind),
888 None => self.type_param_out_of_range(p, source_ty),
1a4d82fc
JJ
889 };
890
a1dfa0c6 891 self.shift_vars_through_binders(ty)
1a4d82fc
JJ
892 }
893
064997fb
FG
894 #[cold]
895 #[inline(never)]
896 fn type_param_expected(&self, p: ty::ParamTy, ty: Ty<'tcx>, kind: GenericArgKind<'tcx>) -> ! {
897 bug!(
add651ee 898 "expected type for `{:?}` ({:?}/{}) but found {:?} when substituting, args={:?}",
064997fb
FG
899 p,
900 ty,
901 p.index,
902 kind,
add651ee 903 self.args,
064997fb
FG
904 )
905 }
906
907 #[cold]
908 #[inline(never)]
909 fn type_param_out_of_range(&self, p: ty::ParamTy, ty: Ty<'tcx>) -> ! {
910 bug!(
add651ee 911 "type parameter `{:?}` ({:?}/{}) out of range when substituting, args={:?}",
064997fb
FG
912 p,
913 ty,
914 p.index,
add651ee 915 self.args,
064997fb
FG
916 )
917 }
918
5099ac24 919 fn const_for_param(&self, p: ParamConst, source_ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
add651ee
FG
920 // Look up the const in the args. It really should be in there.
921 let opt_ct = self.args.get(p.index as usize).map(|k| k.unpack());
48663c56 922 let ct = match opt_ct {
e74abb32 923 Some(GenericArgKind::Const(ct)) => ct,
064997fb
FG
924 Some(kind) => self.const_param_expected(p, source_ct, kind),
925 None => self.const_param_out_of_range(p, source_ct),
532ac7d7
XL
926 };
927
48663c56 928 self.shift_vars_through_binders(ct)
532ac7d7
XL
929 }
930
064997fb
FG
931 #[cold]
932 #[inline(never)]
933 fn const_param_expected(
934 &self,
935 p: ty::ParamConst,
936 ct: ty::Const<'tcx>,
937 kind: GenericArgKind<'tcx>,
938 ) -> ! {
939 bug!(
add651ee 940 "expected const for `{:?}` ({:?}/{}) but found {:?} when substituting args={:?}",
064997fb
FG
941 p,
942 ct,
943 p.index,
944 kind,
add651ee 945 self.args,
064997fb
FG
946 )
947 }
948
949 #[cold]
950 #[inline(never)]
951 fn const_param_out_of_range(&self, p: ty::ParamConst, ct: ty::Const<'tcx>) -> ! {
952 bug!(
add651ee 953 "const parameter `{:?}` ({:?}/{}) out of range when substituting args={:?}",
064997fb
FG
954 p,
955 ct,
956 p.index,
add651ee 957 self.args,
064997fb
FG
958 )
959 }
960
9fa01778 961 /// It is sometimes necessary to adjust the De Bruijn indices during substitution. This occurs
a1dfa0c6
XL
962 /// when we are substituting a type with escaping bound vars into a context where we have
963 /// passed through binders. That's quite a mouthful. Let's see an example:
1a4d82fc
JJ
964 ///
965 /// ```
966 /// type Func<A> = fn(A);
04454e1e 967 /// type MetaFunc = for<'a> fn(Func<&'a i32>);
1a4d82fc
JJ
968 /// ```
969 ///
970 /// The type `MetaFunc`, when fully expanded, will be
04454e1e
FG
971 /// ```ignore (illustrative)
972 /// for<'a> fn(fn(&'a i32))
973 /// // ^~ ^~ ^~~
974 /// // | | |
975 /// // | | DebruijnIndex of 2
976 /// // Binders
977 /// ```
1a4d82fc
JJ
978 /// Here the `'a` lifetime is bound in the outer function, but appears as an argument of the
979 /// inner one. Therefore, that appearance will have a DebruijnIndex of 2, because we must skip
9fa01778 980 /// over the inner binder (remember that we count De Bruijn indices from 1). However, in the
f035d41b 981 /// definition of `MetaFunc`, the binder is not visible, so the type `&'a i32` will have a
9fa01778 982 /// De Bruijn index of 1. It's only during the substitution that we can see we must increase the
1a4d82fc
JJ
983 /// depth by 1 to account for the binder that we passed through.
984 ///
985 /// As a second example, consider this twist:
986 ///
987 /// ```
988 /// type FuncTuple<A> = (A,fn(A));
04454e1e 989 /// type MetaFuncTuple = for<'a> fn(FuncTuple<&'a i32>);
1a4d82fc
JJ
990 /// ```
991 ///
992 /// Here the final type will be:
04454e1e
FG
993 /// ```ignore (illustrative)
994 /// for<'a> fn((&'a i32, fn(&'a i32)))
995 /// // ^~~ ^~~
996 /// // | |
997 /// // DebruijnIndex of 1 |
998 /// // DebruijnIndex of 2
999 /// ```
f035d41b 1000 /// As indicated in the diagram, here the same type `&'a i32` is substituted once, but in the
9fa01778 1001 /// first case we do not increase the De Bruijn index and in the second case we do. The reason
1a4d82fc 1002 /// is that only in the second case have we passed through a fn binder.
9ffffee4 1003 fn shift_vars_through_binders<T: TypeFoldable<TyCtxt<'tcx>>>(&self, val: T) -> T {
dfeec247
XL
1004 debug!(
1005 "shift_vars(val={:?}, binders_passed={:?}, has_escaping_bound_vars={:?})",
1006 val,
1007 self.binders_passed,
1008 val.has_escaping_bound_vars()
1009 );
1a4d82fc 1010
48663c56
XL
1011 if self.binders_passed == 0 || !val.has_escaping_bound_vars() {
1012 return val;
970d7e83 1013 }
1a4d82fc 1014
9ffffee4 1015 let result = ty::fold::shift_vars(TypeFolder::interner(self), val, self.binders_passed);
a1dfa0c6 1016 debug!("shift_vars: shifted result = {:?}", result);
1a4d82fc
JJ
1017
1018 result
1019 }
1020
7cac9316 1021 fn shift_region_through_binders(&self, region: ty::Region<'tcx>) -> ty::Region<'tcx> {
a1dfa0c6 1022 if self.binders_passed == 0 || !region.has_escaping_bound_vars() {
cc61c64b
XL
1023 return region;
1024 }
a1dfa0c6 1025 ty::fold::shift_region(self.tcx, region, self.binders_passed)
9e0c209e
SL
1026 }
1027}
0bf4aa26 1028
add651ee 1029/// Stores the user-given args to reach some fully qualified path
0bf4aa26 1030/// (e.g., `<T>::Item` or `<T as Trait>::Item`).
3dfed10e 1031#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
781aab86 1032#[derive(HashStable, TypeFoldable, TypeVisitable)]
add651ee
FG
1033pub struct UserArgs<'tcx> {
1034 /// The args for the item as given by the user.
1035 pub args: GenericArgsRef<'tcx>,
0bf4aa26 1036
9fa01778 1037 /// The self type, in the case of a `<T>::Item` path (when applied
0bf4aa26
XL
1038 /// to an inherent impl). See `UserSelfTy` below.
1039 pub user_self_ty: Option<UserSelfTy<'tcx>>,
1040}
1041
9fa01778
XL
1042/// Specifies the user-given self type. In the case of a path that
1043/// refers to a member in an inherent impl, this self type is
0bf4aa26
XL
1044/// sometimes needed to constrain the type parameters on the impl. For
1045/// example, in this code:
1046///
04454e1e 1047/// ```ignore (illustrative)
0bf4aa26
XL
1048/// struct Foo<T> { }
1049/// impl<A> Foo<A> { fn method() { } }
1050/// ```
1051///
1052/// when you then have a path like `<Foo<&'static u32>>::method`,
9fa01778
XL
1053/// this struct would carry the `DefId` of the impl along with the
1054/// self type `Foo<u32>`. Then we can instantiate the parameters of
add651ee 1055/// the impl (with the args from `UserArgs`) and apply those to
9fa01778
XL
1056/// the self type, giving `Foo<?A>`. Finally, we unify that with
1057/// the self type here, which contains `?A` to be `&'static u32`
3dfed10e 1058#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
781aab86 1059#[derive(HashStable, TypeFoldable, TypeVisitable)]
0bf4aa26
XL
1060pub struct UserSelfTy<'tcx> {
1061 pub impl_def_id: DefId,
1062 pub self_ty: Ty<'tcx>,
1063}