4 use crate::ty::codec::{TyDecoder, TyEncoder};
5 use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable};
6 use crate::ty::sty::{ClosureSubsts, GeneratorSubsts, InlineConstSubsts};
7 use crate::ty::visit::{TypeVisitable, TypeVisitor};
8 use crate::ty::{self, Lift, List, ParamConst, Ty, TyCtxt};
10 use rustc_data_structures::intern::{Interned, WithStableHash};
11 use rustc_hir::def_id::DefId;
12 use rustc_macros::HashStable;
13 use rustc_serialize::{self, Decodable, Encodable};
14 use smallvec::SmallVec;
17 use std::cmp::Ordering;
19 use std::marker::PhantomData;
21 use std::num::NonZeroUsize;
22 use std::ops::ControlFlow;
25 /// An entity in the Rust type system, which can be one of
26 /// several kinds (types, lifetimes, and consts).
27 /// To reduce memory usage, a `GenericArg` is an interned pointer,
28 /// with the lowest 2 bits being reserved for a tag to
29 /// indicate the type (`Ty`, `Region`, or `Const`) it points to.
31 /// Note: the `PartialEq`, `Eq` and `Hash` derives are only valid because `Ty`,
32 /// `Region` and `Const` are all interned.
33 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
34 pub struct GenericArg<'tcx> {
36 marker: PhantomData<(Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>)>,
39 const TAG_MASK: usize = 0b11;
40 const TYPE_TAG: usize = 0b00;
41 const REGION_TAG: usize = 0b01;
42 const CONST_TAG: usize = 0b10;
44 #[derive(Debug, TyEncodable, TyDecodable, PartialEq, Eq, PartialOrd, Ord)]
45 pub enum GenericArgKind<'tcx> {
46 Lifetime(ty::Region<'tcx>),
48 Const(ty::Const<'tcx>),
51 /// This function goes from `&'a [Ty<'tcx>]` to `&'a [GenericArg<'tcx>]`
53 /// This is sound as, for types, `GenericArg` is just
54 /// `NonZeroUsize::new_unchecked(ty as *const _ as usize)` as
55 /// long as we use `0` for the `TYPE_TAG`.
56 pub fn ty_slice_as_generic_args<'a, 'tcx>(ts: &'a [Ty<'tcx>]) -> &'a [GenericArg<'tcx>] {
57 assert_eq!(TYPE_TAG, 0);
58 // SAFETY: the whole slice is valid and immutable.
59 // `Ty` and `GenericArg` is explained above.
60 unsafe { slice::from_raw_parts(ts.as_ptr().cast(), ts.len()) }
63 impl<'tcx> List<Ty<'tcx>> {
64 /// Allows to freely switch between `List<Ty<'tcx>>` and `List<GenericArg<'tcx>>`.
66 /// As lists are interned, `List<Ty<'tcx>>` and `List<GenericArg<'tcx>>` have
67 /// be interned together, see `intern_type_list` for more details.
69 pub fn as_substs(&'tcx self) -> SubstsRef<'tcx> {
70 assert_eq!(TYPE_TAG, 0);
71 // SAFETY: `List<T>` is `#[repr(C)]`. `Ty` and `GenericArg` is explained above.
72 unsafe { &*(self as *const List<Ty<'tcx>> as *const List<GenericArg<'tcx>>) }
76 impl<'tcx> GenericArgKind<'tcx> {
78 fn pack(self) -> GenericArg<'tcx> {
79 let (tag, ptr) = match self {
80 GenericArgKind::Lifetime(lt) => {
81 // Ensure we can use the tag bits.
82 assert_eq!(mem::align_of_val(&*lt.0.0) & TAG_MASK, 0);
83 (REGION_TAG, lt.0.0 as *const ty::RegionKind<'tcx> as usize)
85 GenericArgKind::Type(ty) => {
86 // Ensure we can use the tag bits.
87 assert_eq!(mem::align_of_val(&*ty.0.0) & TAG_MASK, 0);
88 (TYPE_TAG, ty.0.0 as *const WithStableHash<ty::TyS<'tcx>> as usize)
90 GenericArgKind::Const(ct) => {
91 // Ensure we can use the tag bits.
92 assert_eq!(mem::align_of_val(&*ct.0.0) & TAG_MASK, 0);
93 (CONST_TAG, ct.0.0 as *const ty::ConstS<'tcx> as usize)
97 GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData }
101 impl<'tcx> fmt::Debug for GenericArg<'tcx> {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 match self.unpack() {
104 GenericArgKind::Lifetime(lt) => lt.fmt(f),
105 GenericArgKind::Type(ty) => ty.fmt(f),
106 GenericArgKind::Const(ct) => ct.fmt(f),
111 impl<'tcx> Ord for GenericArg<'tcx> {
112 fn cmp(&self, other: &GenericArg<'tcx>) -> Ordering {
113 self.unpack().cmp(&other.unpack())
117 impl<'tcx> PartialOrd for GenericArg<'tcx> {
118 fn partial_cmp(&self, other: &GenericArg<'tcx>) -> Option<Ordering> {
119 Some(self.cmp(&other))
123 impl<'tcx> From<ty::Region<'tcx>> for GenericArg<'tcx> {
125 fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> {
126 GenericArgKind::Lifetime(r).pack()
130 impl<'tcx> From<Ty<'tcx>> for GenericArg<'tcx> {
132 fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> {
133 GenericArgKind::Type(ty).pack()
137 impl<'tcx> From<ty::Const<'tcx>> for GenericArg<'tcx> {
139 fn from(c: ty::Const<'tcx>) -> GenericArg<'tcx> {
140 GenericArgKind::Const(c).pack()
144 impl<'tcx> GenericArg<'tcx> {
146 pub fn unpack(self) -> GenericArgKind<'tcx> {
147 let ptr = self.ptr.get();
148 // SAFETY: use of `Interned::new_unchecked` here is ok because these
149 // pointers were originally created from `Interned` types in `pack()`,
150 // and this is just going in the other direction.
152 match ptr & TAG_MASK {
153 REGION_TAG => GenericArgKind::Lifetime(ty::Region(Interned::new_unchecked(
154 &*((ptr & !TAG_MASK) as *const ty::RegionKind<'tcx>),
156 TYPE_TAG => GenericArgKind::Type(Ty(Interned::new_unchecked(
157 &*((ptr & !TAG_MASK) as *const WithStableHash<ty::TyS<'tcx>>),
159 CONST_TAG => GenericArgKind::Const(ty::Const(Interned::new_unchecked(
160 &*((ptr & !TAG_MASK) as *const ty::ConstS<'tcx>),
162 _ => intrinsics::unreachable(),
167 /// Unpack the `GenericArg` as a region when it is known certainly to be a region.
168 pub fn expect_region(self) -> ty::Region<'tcx> {
169 match self.unpack() {
170 GenericArgKind::Lifetime(lt) => lt,
171 _ => bug!("expected a region, but found another kind"),
175 /// Unpack the `GenericArg` as a type when it is known certainly to be a type.
176 /// This is true in cases where `Substs` is used in places where the kinds are known
177 /// to be limited (e.g. in tuples, where the only parameters are type parameters).
178 pub fn expect_ty(self) -> Ty<'tcx> {
179 match self.unpack() {
180 GenericArgKind::Type(ty) => ty,
181 _ => bug!("expected a type, but found another kind"),
185 /// Unpack the `GenericArg` as a const when it is known certainly to be a const.
186 pub fn expect_const(self) -> ty::Const<'tcx> {
187 match self.unpack() {
188 GenericArgKind::Const(c) => c,
189 _ => bug!("expected a const, but found another kind"),
194 impl<'a, 'tcx> Lift<'tcx> for GenericArg<'a> {
195 type Lifted = GenericArg<'tcx>;
197 fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
198 match self.unpack() {
199 GenericArgKind::Lifetime(lt) => tcx.lift(lt).map(|lt| lt.into()),
200 GenericArgKind::Type(ty) => tcx.lift(ty).map(|ty| ty.into()),
201 GenericArgKind::Const(ct) => tcx.lift(ct).map(|ct| ct.into()),
206 impl<'tcx> TypeFoldable<'tcx> for GenericArg<'tcx> {
207 fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
208 match self.unpack() {
209 GenericArgKind::Lifetime(lt) => lt.try_fold_with(folder).map(Into::into),
210 GenericArgKind::Type(ty) => ty.try_fold_with(folder).map(Into::into),
211 GenericArgKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
216 impl<'tcx> TypeVisitable<'tcx> for GenericArg<'tcx> {
217 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
218 match self.unpack() {
219 GenericArgKind::Lifetime(lt) => lt.visit_with(visitor),
220 GenericArgKind::Type(ty) => ty.visit_with(visitor),
221 GenericArgKind::Const(ct) => ct.visit_with(visitor),
226 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for GenericArg<'tcx> {
227 fn encode(&self, e: &mut E) {
228 self.unpack().encode(e)
232 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for GenericArg<'tcx> {
233 fn decode(d: &mut D) -> GenericArg<'tcx> {
234 GenericArgKind::decode(d).pack()
238 /// A substitution mapping generic parameters to new values.
239 pub type InternalSubsts<'tcx> = List<GenericArg<'tcx>>;
241 pub type SubstsRef<'tcx> = &'tcx InternalSubsts<'tcx>;
243 impl<'tcx> InternalSubsts<'tcx> {
244 /// Checks whether all elements of this list are types, if so, transmute.
245 pub fn try_as_type_list(&'tcx self) -> Option<&'tcx List<Ty<'tcx>>> {
246 if self.iter().all(|arg| matches!(arg.unpack(), GenericArgKind::Type(_))) {
247 assert_eq!(TYPE_TAG, 0);
248 // SAFETY: All elements are types, see `List<Ty<'tcx>>::as_substs`.
249 Some(unsafe { &*(self as *const List<GenericArg<'tcx>> as *const List<Ty<'tcx>>) })
255 /// Interpret these substitutions as the substitutions of a closure type.
256 /// Closure substitutions have a particular structure controlled by the
257 /// compiler that encodes information like the signature and closure kind;
258 /// see `ty::ClosureSubsts` struct for more comments.
259 pub fn as_closure(&'tcx self) -> ClosureSubsts<'tcx> {
260 ClosureSubsts { substs: self }
263 /// Interpret these substitutions as the substitutions of a generator type.
264 /// Generator substitutions have a particular structure controlled by the
265 /// compiler that encodes information like the signature and generator kind;
266 /// see `ty::GeneratorSubsts` struct for more comments.
267 pub fn as_generator(&'tcx self) -> GeneratorSubsts<'tcx> {
268 GeneratorSubsts { substs: self }
271 /// Interpret these substitutions as the substitutions of an inline const.
272 /// Inline const substitutions have a particular structure controlled by the
273 /// compiler that encodes information like the inferred type;
274 /// see `ty::InlineConstSubsts` struct for more comments.
275 pub fn as_inline_const(&'tcx self) -> InlineConstSubsts<'tcx> {
276 InlineConstSubsts { substs: self }
279 /// Creates an `InternalSubsts` that maps each generic parameter to itself.
280 pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> {
281 Self::for_item(tcx, def_id, |param, _| tcx.mk_param_from_def(param))
284 /// Creates an `InternalSubsts` for generic parameter definitions,
285 /// by calling closures to obtain each kind.
286 /// The closures get to observe the `InternalSubsts` as they're
287 /// being built, which can be used to correctly
288 /// substitute defaults of generic parameters.
289 pub fn for_item<F>(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx>
291 F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
293 let defs = tcx.generics_of(def_id);
294 let count = defs.count();
295 let mut substs = SmallVec::with_capacity(count);
296 Self::fill_item(&mut substs, tcx, defs, &mut mk_kind);
297 tcx.intern_substs(&substs)
300 pub fn extend_to<F>(&self, tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx>
302 F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
304 Self::for_item(tcx, def_id, |param, substs| {
305 self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, substs))
310 substs: &mut SmallVec<[GenericArg<'tcx>; 8]>,
315 F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
317 if let Some(def_id) = defs.parent {
318 let parent_defs = tcx.generics_of(def_id);
319 Self::fill_item(substs, tcx, parent_defs, mk_kind);
321 Self::fill_single(substs, defs, mk_kind)
324 pub fn fill_single<F>(
325 substs: &mut SmallVec<[GenericArg<'tcx>; 8]>,
329 F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
331 substs.reserve(defs.params.len());
332 for param in &defs.params {
333 let kind = mk_kind(param, substs);
334 assert_eq!(param.index as usize, substs.len());
340 pub fn types(&'tcx self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'tcx {
342 .filter_map(|k| if let GenericArgKind::Type(ty) = k.unpack() { Some(ty) } else { None })
346 pub fn regions(&'tcx self) -> impl DoubleEndedIterator<Item = ty::Region<'tcx>> + 'tcx {
347 self.iter().filter_map(|k| {
348 if let GenericArgKind::Lifetime(lt) = k.unpack() { Some(lt) } else { None }
353 pub fn consts(&'tcx self) -> impl DoubleEndedIterator<Item = ty::Const<'tcx>> + 'tcx {
354 self.iter().filter_map(|k| {
355 if let GenericArgKind::Const(ct) = k.unpack() { Some(ct) } else { None }
360 pub fn non_erasable_generics(
362 ) -> impl DoubleEndedIterator<Item = GenericArgKind<'tcx>> + 'tcx {
363 self.iter().filter_map(|k| match k.unpack() {
364 GenericArgKind::Lifetime(_) => None,
365 generic => Some(generic),
370 pub fn type_at(&self, i: usize) -> Ty<'tcx> {
371 if let GenericArgKind::Type(ty) = self[i].unpack() {
374 bug!("expected type for param #{} in {:?}", i, self);
379 pub fn region_at(&self, i: usize) -> ty::Region<'tcx> {
380 if let GenericArgKind::Lifetime(lt) = self[i].unpack() {
383 bug!("expected region for param #{} in {:?}", i, self);
388 pub fn const_at(&self, i: usize) -> ty::Const<'tcx> {
389 if let GenericArgKind::Const(ct) = self[i].unpack() {
392 bug!("expected const for param #{} in {:?}", i, self);
397 pub fn type_for_def(&self, def: &ty::GenericParamDef) -> GenericArg<'tcx> {
398 self.type_at(def.index as usize).into()
401 /// Transform from substitutions for a child of `source_ancestor`
402 /// (e.g., a trait or impl) to substitutions for the same child
403 /// in a different item, with `target_substs` as the base for
404 /// the target impl/trait, with the source child-specific
405 /// parameters (e.g., method parameters) on top of that base.
407 /// For example given:
410 /// trait X<S> { fn f<T>(); }
411 /// impl<U> X<U> for U { fn f<V>() {} }
414 /// * If `self` is `[Self, S, T]`: the identity substs of `f` in the trait.
415 /// * If `source_ancestor` is the def_id of the trait.
416 /// * If `target_substs` is `[U]`, the substs for the impl.
417 /// * Then we will return `[U, T]`, the subst for `f` in the impl that
418 /// are needed for it to match the trait.
422 source_ancestor: DefId,
423 target_substs: SubstsRef<'tcx>,
424 ) -> SubstsRef<'tcx> {
425 let defs = tcx.generics_of(source_ancestor);
426 tcx.mk_substs(target_substs.iter().chain(self.iter().skip(defs.params.len())))
429 pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> {
430 tcx.mk_substs(self.iter().take(generics.count()))
434 impl<'tcx> TypeFoldable<'tcx> for SubstsRef<'tcx> {
435 fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
436 // This code is hot enough that it's worth specializing for the most
437 // common length lists, to avoid the overhead of `SmallVec` creation.
438 // The match arms are in order of frequency. The 1, 2, and 0 cases are
439 // typically hit in 90--99.99% of cases. When folding doesn't change
440 // the substs, it's faster to reuse the existing substs rather than
441 // calling `intern_substs`.
444 let param0 = self[0].try_fold_with(folder)?;
445 if param0 == self[0] { Ok(self) } else { Ok(folder.tcx().intern_substs(&[param0])) }
448 let param0 = self[0].try_fold_with(folder)?;
449 let param1 = self[1].try_fold_with(folder)?;
450 if param0 == self[0] && param1 == self[1] {
453 Ok(folder.tcx().intern_substs(&[param0, param1]))
457 _ => ty::util::fold_list(self, folder, |tcx, v| tcx.intern_substs(v)),
462 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<Ty<'tcx>> {
463 fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
464 // This code is fairly hot, though not as hot as `SubstsRef`.
466 // When compiling stage 2, I get the following results:
469 // --- | --------- | -----
470 // 2 | 15083590 | 48.1
471 // 3 | 7540067 | 24.0
472 // 1 | 5300377 | 16.9
476 // I've tried it with some private repositories and got
477 // close to the same result, with 4 and 0 swapping places
481 let param0 = self[0].try_fold_with(folder)?;
482 let param1 = self[1].try_fold_with(folder)?;
483 if param0 == self[0] && param1 == self[1] {
486 Ok(folder.tcx().intern_type_list(&[param0, param1]))
489 _ => ty::util::fold_list(self, folder, |tcx, v| tcx.intern_type_list(v)),
494 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for &'tcx ty::List<T> {
496 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
497 self.iter().try_for_each(|t| t.visit_with(visitor))
501 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
502 #[derive(Encodable, Decodable, HashStable)]
503 pub struct EarlyBinder<T>(pub T);
505 /// For early binders, you should first call `subst` before using any visitors.
506 impl<'tcx, T> !TypeFoldable<'tcx> for ty::EarlyBinder<T> {}
507 impl<'tcx, T> !TypeVisitable<'tcx> for ty::EarlyBinder<T> {}
509 impl<T> EarlyBinder<T> {
510 pub fn as_ref(&self) -> EarlyBinder<&T> {
514 pub fn map_bound_ref<F, U>(&self, f: F) -> EarlyBinder<U>
518 self.as_ref().map_bound(f)
521 pub fn map_bound<F, U>(self, f: F) -> EarlyBinder<U>
525 let value = f(self.0);
529 pub fn try_map_bound<F, U, E>(self, f: F) -> Result<EarlyBinder<U>, E>
531 F: FnOnce(T) -> Result<U, E>,
533 let value = f(self.0)?;
534 Ok(EarlyBinder(value))
537 pub fn rebind<U>(&self, value: U) -> EarlyBinder<U> {
542 impl<T> EarlyBinder<Option<T>> {
543 pub fn transpose(self) -> Option<EarlyBinder<T>> {
544 self.0.map(|v| EarlyBinder(v))
548 impl<T, U> EarlyBinder<(T, U)> {
549 pub fn transpose_tuple2(self) -> (EarlyBinder<T>, EarlyBinder<U>) {
550 (EarlyBinder(self.0.0), EarlyBinder(self.0.1))
554 pub struct EarlyBinderIter<T> {
558 impl<T: IntoIterator> EarlyBinder<T> {
559 pub fn transpose_iter(self) -> EarlyBinderIter<T::IntoIter> {
560 EarlyBinderIter { t: self.0.into_iter() }
564 impl<T: Iterator> Iterator for EarlyBinderIter<T> {
565 type Item = EarlyBinder<T::Item>;
567 fn next(&mut self) -> Option<Self::Item> {
568 self.t.next().map(|i| EarlyBinder(i))
572 impl<'tcx, T: TypeFoldable<'tcx>> ty::EarlyBinder<T> {
573 pub fn subst(self, tcx: TyCtxt<'tcx>, substs: &[GenericArg<'tcx>]) -> T {
574 let mut folder = SubstFolder { tcx, substs, binders_passed: 0 };
575 self.0.fold_with(&mut folder)
579 ///////////////////////////////////////////////////////////////////////////
580 // The actual substitution engine itself is a type folder.
582 struct SubstFolder<'a, 'tcx> {
584 substs: &'a [GenericArg<'tcx>],
586 /// Number of region binders we have passed through while doing the substitution
590 impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> {
592 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
596 fn fold_binder<T: TypeFoldable<'tcx>>(
598 t: ty::Binder<'tcx, T>,
599 ) -> ty::Binder<'tcx, T> {
600 self.binders_passed += 1;
601 let t = t.super_fold_with(self);
602 self.binders_passed -= 1;
606 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
609 fn region_param_out_of_range(data: ty::EarlyBoundRegion) -> ! {
611 "Region parameter out of range when substituting in region {} (index={})",
617 // Note: This routine only handles regions that are bound on
618 // type declarations and other outer declarations, not those
619 // bound in *fn types*. Region substitution of the bound
620 // regions that appear in a function signature is done using
621 // the specialized routine `ty::replace_late_regions()`.
623 ty::ReEarlyBound(data) => {
624 let rk = self.substs.get(data.index as usize).map(|k| k.unpack());
626 Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt),
627 _ => region_param_out_of_range(data),
634 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
635 if !t.needs_subst() {
640 ty::Param(p) => self.ty_for_param(p, t),
641 _ => t.super_fold_with(self),
645 fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
646 if let ty::ConstKind::Param(p) = c.kind() {
647 self.const_for_param(p, c)
649 c.super_fold_with(self)
654 fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx> {
655 c.super_fold_with(self)
659 impl<'a, 'tcx> SubstFolder<'a, 'tcx> {
660 fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> {
661 // Look up the type in the substitutions. It really should be in there.
662 let opt_ty = self.substs.get(p.index as usize).map(|k| k.unpack());
663 let ty = match opt_ty {
664 Some(GenericArgKind::Type(ty)) => ty,
665 Some(kind) => self.type_param_expected(p, source_ty, kind),
666 None => self.type_param_out_of_range(p, source_ty),
669 self.shift_vars_through_binders(ty)
674 fn type_param_expected(&self, p: ty::ParamTy, ty: Ty<'tcx>, kind: GenericArgKind<'tcx>) -> ! {
676 "expected type for `{:?}` ({:?}/{}) but found {:?} when substituting, substs={:?}",
687 fn type_param_out_of_range(&self, p: ty::ParamTy, ty: Ty<'tcx>) -> ! {
689 "type parameter `{:?}` ({:?}/{}) out of range when substituting, substs={:?}",
697 fn const_for_param(&self, p: ParamConst, source_ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
698 // Look up the const in the substitutions. It really should be in there.
699 let opt_ct = self.substs.get(p.index as usize).map(|k| k.unpack());
700 let ct = match opt_ct {
701 Some(GenericArgKind::Const(ct)) => ct,
702 Some(kind) => self.const_param_expected(p, source_ct, kind),
703 None => self.const_param_out_of_range(p, source_ct),
706 self.shift_vars_through_binders(ct)
711 fn const_param_expected(
715 kind: GenericArgKind<'tcx>,
718 "expected const for `{:?}` ({:?}/{}) but found {:?} when substituting substs={:?}",
729 fn const_param_out_of_range(&self, p: ty::ParamConst, ct: ty::Const<'tcx>) -> ! {
731 "const parameter `{:?}` ({:?}/{}) out of range when substituting substs={:?}",
739 /// It is sometimes necessary to adjust the De Bruijn indices during substitution. This occurs
740 /// when we are substituting a type with escaping bound vars into a context where we have
741 /// passed through binders. That's quite a mouthful. Let's see an example:
744 /// type Func<A> = fn(A);
745 /// type MetaFunc = for<'a> fn(Func<&'a i32>);
748 /// The type `MetaFunc`, when fully expanded, will be
749 /// ```ignore (illustrative)
750 /// for<'a> fn(fn(&'a i32))
753 /// // | | DebruijnIndex of 2
756 /// Here the `'a` lifetime is bound in the outer function, but appears as an argument of the
757 /// inner one. Therefore, that appearance will have a DebruijnIndex of 2, because we must skip
758 /// over the inner binder (remember that we count De Bruijn indices from 1). However, in the
759 /// definition of `MetaFunc`, the binder is not visible, so the type `&'a i32` will have a
760 /// De Bruijn index of 1. It's only during the substitution that we can see we must increase the
761 /// depth by 1 to account for the binder that we passed through.
763 /// As a second example, consider this twist:
766 /// type FuncTuple<A> = (A,fn(A));
767 /// type MetaFuncTuple = for<'a> fn(FuncTuple<&'a i32>);
770 /// Here the final type will be:
771 /// ```ignore (illustrative)
772 /// for<'a> fn((&'a i32, fn(&'a i32)))
775 /// // DebruijnIndex of 1 |
776 /// // DebruijnIndex of 2
778 /// As indicated in the diagram, here the same type `&'a i32` is substituted once, but in the
779 /// first case we do not increase the De Bruijn index and in the second case we do. The reason
780 /// is that only in the second case have we passed through a fn binder.
781 fn shift_vars_through_binders<T: TypeFoldable<'tcx>>(&self, val: T) -> T {
783 "shift_vars(val={:?}, binders_passed={:?}, has_escaping_bound_vars={:?})",
786 val.has_escaping_bound_vars()
789 if self.binders_passed == 0 || !val.has_escaping_bound_vars() {
793 let result = ty::fold::shift_vars(TypeFolder::tcx(self), val, self.binders_passed);
794 debug!("shift_vars: shifted result = {:?}", result);
799 fn shift_region_through_binders(&self, region: ty::Region<'tcx>) -> ty::Region<'tcx> {
800 if self.binders_passed == 0 || !region.has_escaping_bound_vars() {
803 ty::fold::shift_region(self.tcx, region, self.binders_passed)
807 /// Stores the user-given substs to reach some fully qualified path
808 /// (e.g., `<T>::Item` or `<T as Trait>::Item`).
809 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
810 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
811 pub struct UserSubsts<'tcx> {
812 /// The substitutions for the item as given by the user.
813 pub substs: SubstsRef<'tcx>,
815 /// The self type, in the case of a `<T>::Item` path (when applied
816 /// to an inherent impl). See `UserSelfTy` below.
817 pub user_self_ty: Option<UserSelfTy<'tcx>>,
820 /// Specifies the user-given self type. In the case of a path that
821 /// refers to a member in an inherent impl, this self type is
822 /// sometimes needed to constrain the type parameters on the impl. For
823 /// example, in this code:
825 /// ```ignore (illustrative)
826 /// struct Foo<T> { }
827 /// impl<A> Foo<A> { fn method() { } }
830 /// when you then have a path like `<Foo<&'static u32>>::method`,
831 /// this struct would carry the `DefId` of the impl along with the
832 /// self type `Foo<u32>`. Then we can instantiate the parameters of
833 /// the impl (with the substs from `UserSubsts`) and apply those to
834 /// the self type, giving `Foo<?A>`. Finally, we unify that with
835 /// the self type here, which contains `?A` to be `&'static u32`
836 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
837 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
838 pub struct UserSelfTy<'tcx> {
839 pub impl_def_id: DefId,
840 pub self_ty: Ty<'tcx>,