1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This module contains TypeVariants and its major components
13 use hir::def_id::DefId;
15 use mir::interpret::ConstValue;
17 use polonius_engine::Atom;
18 use rustc_data_structures::indexed_vec::Idx;
19 use ty::subst::{Substs, Subst, Kind, UnpackedKind};
20 use ty::{self, AdtDef, TypeFlags, Ty, TyCtxt, TypeFoldable};
21 use ty::{Slice, TyS, ParamEnvAnd, ParamEnv};
22 use util::captures::Captures;
23 use mir::interpret::{Scalar, Pointer, Value};
26 use std::cmp::Ordering;
27 use rustc_target::spec::abi;
28 use syntax::ast::{self, Ident};
29 use syntax::symbol::{keywords, InternedString};
36 use self::TypeVariants::*;
38 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
39 pub struct TypeAndMut<'tcx> {
41 pub mutbl: hir::Mutability,
44 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
45 RustcEncodable, RustcDecodable, Copy)]
46 /// A "free" region `fr` can be interpreted as "some region
47 /// at least as big as the scope `fr.scope`".
48 pub struct FreeRegion {
50 pub bound_region: BoundRegion,
53 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
54 RustcEncodable, RustcDecodable, Copy)]
55 pub enum BoundRegion {
56 /// An anonymous region parameter for a given fn (&T)
59 /// Named region parameters for functions (a in &'a T)
61 /// The def-id is needed to distinguish free regions in
62 /// the event of shadowing.
63 BrNamed(DefId, InternedString),
65 /// Fresh bound identifiers created during GLB computations.
68 /// Anonymous region for the implicit env pointer parameter
74 pub fn is_named(&self) -> bool {
76 BoundRegion::BrNamed(..) => true,
82 /// NB: If you change this, you'll probably want to change the corresponding
83 /// AST structure in libsyntax/ast.rs as well.
84 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
85 pub enum TypeVariants<'tcx> {
86 /// The primitive boolean type. Written as `bool`.
89 /// The primitive character type; holds a Unicode scalar value
90 /// (a non-surrogate code point). Written as `char`.
93 /// A primitive signed integer type. For example, `i32`.
96 /// A primitive unsigned integer type. For example, `u32`.
99 /// A primitive floating-point type. For example, `f64`.
100 TyFloat(ast::FloatTy),
102 /// Structures, enumerations and unions.
104 /// Substs here, possibly against intuition, *may* contain `TyParam`s.
105 /// That is, even after substitution it is possible that there are type
106 /// variables. This happens when the `TyAdt` corresponds to an ADT
107 /// definition and not a concrete use of it.
108 TyAdt(&'tcx AdtDef, &'tcx Substs<'tcx>),
112 /// The pointee of a string slice. Written as `str`.
115 /// An array with the given length. Written as `[T; n]`.
116 TyArray(Ty<'tcx>, &'tcx ty::Const<'tcx>),
118 /// The pointee of an array slice. Written as `[T]`.
121 /// A raw pointer. Written as `*mut T` or `*const T`
122 TyRawPtr(TypeAndMut<'tcx>),
124 /// A reference; a pointer with an associated lifetime. Written as
125 /// `&'a mut T` or `&'a T`.
126 TyRef(Region<'tcx>, Ty<'tcx>, hir::Mutability),
128 /// The anonymous type of a function declaration/definition. Each
129 /// function has a unique type.
130 TyFnDef(DefId, &'tcx Substs<'tcx>),
132 /// A pointer to a function. Written as `fn() -> i32`.
133 TyFnPtr(PolyFnSig<'tcx>),
135 /// A trait, defined with `trait`.
136 TyDynamic(Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
138 /// The anonymous type of a closure. Used to represent the type of
140 TyClosure(DefId, ClosureSubsts<'tcx>),
142 /// The anonymous type of a generator. Used to represent the type of
144 TyGenerator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
146 /// A type representin the types stored inside a generator.
147 /// This should only appear in GeneratorInteriors.
148 TyGeneratorWitness(Binder<&'tcx Slice<Ty<'tcx>>>),
150 /// The never type `!`
153 /// A tuple type. For example, `(i32, bool)`.
154 TyTuple(&'tcx Slice<Ty<'tcx>>),
156 /// The projection of an associated type. For example,
157 /// `<T as Trait<..>>::N`.
158 TyProjection(ProjectionTy<'tcx>),
160 /// Anonymized (`impl Trait`) type found in a return type.
161 /// The DefId comes from the `impl Trait` ast::Ty node, and the
162 /// substitutions are for the generics of the function in question.
163 /// After typeck, the concrete type can be found in the `types` map.
164 TyAnon(DefId, &'tcx Substs<'tcx>),
166 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
169 /// A type variable used during type-checking.
172 /// A placeholder for a type which could not be computed; this is
173 /// propagated to avoid useless error messages.
177 /// A closure can be modeled as a struct that looks like:
179 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
187 /// - 'l0...'li and T0...Tj are the lifetime and type parameters
188 /// in scope on the function that defined the closure,
189 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
190 /// is rather hackily encoded via a scalar type. See
191 /// `TyS::to_opt_closure_kind` for details.
192 /// - CS represents the *closure signature*, representing as a `fn()`
193 /// type. For example, `fn(u32, u32) -> u32` would mean that the closure
194 /// implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
196 /// - U0...Uk are type parameters representing the types of its upvars
197 /// (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
198 /// and the up-var has the type `Foo`, then `Ui = &Foo`).
200 /// So, for example, given this function:
202 /// fn foo<'a, T>(data: &'a mut T) {
203 /// do(|| data.count += 1)
206 /// the type of the closure would be something like:
208 /// struct Closure<'a, T, U0> {
212 /// Note that the type of the upvar is not specified in the struct.
213 /// You may wonder how the impl would then be able to use the upvar,
214 /// if it doesn't know it's type? The answer is that the impl is
215 /// (conceptually) not fully generic over Closure but rather tied to
216 /// instances with the expected upvar types:
218 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
222 /// You can see that the *impl* fully specified the type of the upvar
223 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
224 /// (Here, I am assuming that `data` is mut-borrowed.)
226 /// Now, the last question you may ask is: Why include the upvar types
227 /// as extra type parameters? The reason for this design is that the
228 /// upvar types can reference lifetimes that are internal to the
229 /// creating function. In my example above, for example, the lifetime
230 /// `'b` represents the scope of the closure itself; this is some
231 /// subset of `foo`, probably just the scope of the call to the to
232 /// `do()`. If we just had the lifetime/type parameters from the
233 /// enclosing function, we couldn't name this lifetime `'b`. Note that
234 /// there can also be lifetimes in the types of the upvars themselves,
235 /// if one of them happens to be a reference to something that the
236 /// creating fn owns.
238 /// OK, you say, so why not create a more minimal set of parameters
239 /// that just includes the extra lifetime parameters? The answer is
240 /// primarily that it would be hard --- we don't know at the time when
241 /// we create the closure type what the full types of the upvars are,
242 /// nor do we know which are borrowed and which are not. In this
243 /// design, we can just supply a fresh type parameter and figure that
246 /// All right, you say, but why include the type parameters from the
247 /// original function then? The answer is that codegen may need them
248 /// when monomorphizing, and they may not appear in the upvars. A
249 /// closure could capture no variables but still make use of some
250 /// in-scope type parameter with a bound (e.g., if our example above
251 /// had an extra `U: Default`, and the closure called `U::default()`).
253 /// There is another reason. This design (implicitly) prohibits
254 /// closures from capturing themselves (except via a trait
255 /// object). This simplifies closure inference considerably, since it
256 /// means that when we infer the kind of a closure or its upvars, we
257 /// don't have to handle cycles where the decisions we make for
258 /// closure C wind up influencing the decisions we ought to make for
259 /// closure C (which would then require fixed point iteration to
260 /// handle). Plus it fixes an ICE. :P
264 /// Perhaps surprisingly, `ClosureSubsts` are also used for
265 /// generators. In that case, what is written above is only half-true
266 /// -- the set of type parameters is similar, but the role of CK and
267 /// CS are different. CK represents the "yield type" and CS
268 /// represents the "return type" of the generator.
270 /// It'd be nice to split this struct into ClosureSubsts and
271 /// GeneratorSubsts, I believe. -nmatsakis
272 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
273 pub struct ClosureSubsts<'tcx> {
274 /// Lifetime and type parameters from the enclosing function,
275 /// concatenated with the types of the upvars.
277 /// These are separated out because codegen wants to pass them around
278 /// when monomorphizing.
279 pub substs: &'tcx Substs<'tcx>,
282 /// Struct returned by `split()`. Note that these are subslices of the
283 /// parent slice and not canonical substs themselves.
284 struct SplitClosureSubsts<'tcx> {
285 closure_kind_ty: Ty<'tcx>,
286 closure_sig_ty: Ty<'tcx>,
287 upvar_kinds: &'tcx [Kind<'tcx>],
290 impl<'tcx> ClosureSubsts<'tcx> {
291 /// Divides the closure substs into their respective
292 /// components. Single source of truth with respect to the
294 fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitClosureSubsts<'tcx> {
295 let generics = tcx.generics_of(def_id);
296 let parent_len = generics.parent_count;
298 closure_kind_ty: self.substs.type_at(parent_len),
299 closure_sig_ty: self.substs.type_at(parent_len + 1),
300 upvar_kinds: &self.substs[parent_len + 2..],
305 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
306 impl Iterator<Item=Ty<'tcx>> + 'tcx
308 let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
309 upvar_kinds.iter().map(|t| {
310 if let UnpackedKind::Type(ty) = t.unpack() {
313 bug!("upvar should be type")
318 /// Returns the closure kind for this closure; may return a type
319 /// variable during inference. To get the closure kind during
320 /// inference, use `infcx.closure_kind(def_id, substs)`.
321 pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
322 self.split(def_id, tcx).closure_kind_ty
325 /// Returns the type representing the closure signature for this
326 /// closure; may contain type variables during inference. To get
327 /// the closure signature during inference, use
328 /// `infcx.fn_sig(def_id)`.
329 pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
330 self.split(def_id, tcx).closure_sig_ty
333 /// Returns the closure kind for this closure; only usable outside
334 /// of an inference context, because in that context we know that
335 /// there are no type variables.
337 /// If you have an inference context, use `infcx.closure_kind()`.
338 pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::ClosureKind {
339 self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
342 /// Extracts the signature from the closure; only usable outside
343 /// of an inference context, because in that context we know that
344 /// there are no type variables.
346 /// If you have an inference context, use `infcx.closure_sig()`.
347 pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::PolyFnSig<'tcx> {
348 match self.closure_sig_ty(def_id, tcx).sty {
349 ty::TyFnPtr(sig) => sig,
350 ref t => bug!("closure_sig_ty is not a fn-ptr: {:?}", t),
355 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
356 pub struct GeneratorSubsts<'tcx> {
357 pub substs: &'tcx Substs<'tcx>,
360 struct SplitGeneratorSubsts<'tcx> {
364 upvar_kinds: &'tcx [Kind<'tcx>],
367 impl<'tcx> GeneratorSubsts<'tcx> {
368 fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitGeneratorSubsts<'tcx> {
369 let generics = tcx.generics_of(def_id);
370 let parent_len = generics.parent_count;
371 SplitGeneratorSubsts {
372 yield_ty: self.substs.type_at(parent_len),
373 return_ty: self.substs.type_at(parent_len + 1),
374 witness: self.substs.type_at(parent_len + 2),
375 upvar_kinds: &self.substs[parent_len + 3..],
379 /// This describes the types that can be contained in a generator.
380 /// It will be a type variable initially and unified in the last stages of typeck of a body.
381 /// It contains a tuple of all the types that could end up on a generator frame.
382 /// The state transformation MIR pass may only produce layouts which mention types
383 /// in this tuple. Upvars are not counted here.
384 pub fn witness(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
385 self.split(def_id, tcx).witness
389 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
390 impl Iterator<Item=Ty<'tcx>> + 'tcx
392 let SplitGeneratorSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
393 upvar_kinds.iter().map(|t| {
394 if let UnpackedKind::Type(ty) = t.unpack() {
397 bug!("upvar should be type")
402 /// Returns the type representing the yield type of the generator.
403 pub fn yield_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
404 self.split(def_id, tcx).yield_ty
407 /// Returns the type representing the return type of the generator.
408 pub fn return_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
409 self.split(def_id, tcx).return_ty
412 /// Return the "generator signature", which consists of its yield
413 /// and return types.
415 /// NB. Some bits of the code prefers to see this wrapped in a
416 /// binder, but it never contains bound regions. Probably this
417 /// function should be removed.
418 pub fn poly_sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> PolyGenSig<'tcx> {
419 ty::Binder::dummy(self.sig(def_id, tcx))
422 /// Return the "generator signature", which consists of its yield
423 /// and return types.
424 pub fn sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> GenSig<'tcx> {
426 yield_ty: self.yield_ty(def_id, tcx),
427 return_ty: self.return_ty(def_id, tcx),
432 impl<'a, 'gcx, 'tcx> GeneratorSubsts<'tcx> {
433 /// This returns the types of the MIR locals which had to be stored across suspension points.
434 /// It is calculated in rustc_mir::transform::generator::StateTransform.
435 /// All the types here must be in the tuple in GeneratorInterior.
439 tcx: TyCtxt<'a, 'gcx, 'tcx>,
440 ) -> impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a {
441 let state = tcx.generator_layout(def_id).fields.iter();
442 state.map(move |d| d.ty.subst(tcx, self.substs))
445 /// This is the types of the fields of a generate which
446 /// is available before the generator transformation.
447 /// It includes the upvars and the state discriminant which is u32.
448 pub fn pre_transforms_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
449 impl Iterator<Item=Ty<'tcx>> + 'a
451 self.upvar_tys(def_id, tcx).chain(iter::once(tcx.types.u32))
454 /// This is the types of all the fields stored in a generator.
455 /// It includes the upvars, state types and the state discriminant which is u32.
456 pub fn field_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
457 impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a
459 self.pre_transforms_tys(def_id, tcx).chain(self.state_tys(def_id, tcx))
463 #[derive(Debug, Copy, Clone)]
464 pub enum UpvarSubsts<'tcx> {
465 Closure(ClosureSubsts<'tcx>),
466 Generator(GeneratorSubsts<'tcx>),
469 impl<'tcx> UpvarSubsts<'tcx> {
471 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
472 impl Iterator<Item=Ty<'tcx>> + 'tcx
474 let upvar_kinds = match self {
475 UpvarSubsts::Closure(substs) => substs.split(def_id, tcx).upvar_kinds,
476 UpvarSubsts::Generator(substs) => substs.split(def_id, tcx).upvar_kinds,
478 upvar_kinds.iter().map(|t| {
479 if let UnpackedKind::Type(ty) = t.unpack() {
482 bug!("upvar should be type")
488 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, RustcEncodable, RustcDecodable)]
489 pub enum ExistentialPredicate<'tcx> {
491 Trait(ExistentialTraitRef<'tcx>),
492 /// e.g. Iterator::Item = T
493 Projection(ExistentialProjection<'tcx>),
498 impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
499 /// Compares via an ordering that will not change if modules are reordered or other changes are
500 /// made to the tree. In particular, this ordering is preserved across incremental compilations.
501 pub fn stable_cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
502 use self::ExistentialPredicate::*;
503 match (*self, *other) {
504 (Trait(_), Trait(_)) => Ordering::Equal,
505 (Projection(ref a), Projection(ref b)) =>
506 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
507 (AutoTrait(ref a), AutoTrait(ref b)) =>
508 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
509 (Trait(_), _) => Ordering::Less,
510 (Projection(_), Trait(_)) => Ordering::Greater,
511 (Projection(_), _) => Ordering::Less,
512 (AutoTrait(_), _) => Ordering::Greater,
518 impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
519 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
520 -> ty::Predicate<'tcx> {
522 match *self.skip_binder() {
523 ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
524 ExistentialPredicate::Projection(p) =>
525 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
526 ExistentialPredicate::AutoTrait(did) => {
527 let trait_ref = Binder(ty::TraitRef {
529 substs: tcx.mk_substs_trait(self_ty, &[]),
531 trait_ref.to_predicate()
537 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<ExistentialPredicate<'tcx>> {}
539 impl<'tcx> Slice<ExistentialPredicate<'tcx>> {
540 pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
542 Some(&ExistentialPredicate::Trait(tr)) => Some(tr),
548 pub fn projection_bounds<'a>(&'a self) ->
549 impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
550 self.iter().filter_map(|predicate| {
552 ExistentialPredicate::Projection(p) => Some(p),
559 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
560 self.iter().filter_map(|predicate| {
562 ExistentialPredicate::AutoTrait(d) => Some(d),
569 impl<'tcx> Binder<&'tcx Slice<ExistentialPredicate<'tcx>>> {
570 pub fn principal(&self) -> Option<PolyExistentialTraitRef<'tcx>> {
571 self.skip_binder().principal().map(Binder::bind)
575 pub fn projection_bounds<'a>(&'a self) ->
576 impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
577 self.skip_binder().projection_bounds().map(Binder::bind)
581 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
582 self.skip_binder().auto_traits()
585 pub fn iter<'a>(&'a self)
586 -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
587 self.skip_binder().iter().cloned().map(Binder::bind)
591 /// A complete reference to a trait. These take numerous guises in syntax,
592 /// but perhaps the most recognizable form is in a where clause:
596 /// This would be represented by a trait-reference where the def-id is the
597 /// def-id for the trait `Foo` and the substs define `T` as parameter 0,
598 /// and `U` as parameter 1.
600 /// Trait references also appear in object types like `Foo<U>`, but in
601 /// that case the `Self` parameter is absent from the substitutions.
603 /// Note that a `TraitRef` introduces a level of region binding, to
604 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
605 /// U>` or higher-ranked object types.
606 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
607 pub struct TraitRef<'tcx> {
609 pub substs: &'tcx Substs<'tcx>,
612 impl<'tcx> TraitRef<'tcx> {
613 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
614 TraitRef { def_id: def_id, substs: substs }
617 pub fn self_ty(&self) -> Ty<'tcx> {
618 self.substs.type_at(0)
621 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
622 // Select only the "input types" from a trait-reference. For
623 // now this is all the types that appear in the
624 // trait-reference, but it should eventually exclude
629 pub fn from_method(tcx: TyCtxt<'_, '_, 'tcx>,
631 substs: &Substs<'tcx>)
632 -> ty::TraitRef<'tcx> {
633 let defs = tcx.generics_of(trait_id);
637 substs: tcx.intern_substs(&substs[..defs.params.len()])
642 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
644 impl<'tcx> PolyTraitRef<'tcx> {
645 pub fn self_ty(&self) -> Ty<'tcx> {
646 self.skip_binder().self_ty()
649 pub fn def_id(&self) -> DefId {
650 self.skip_binder().def_id
653 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
654 // Note that we preserve binding levels
655 Binder(ty::TraitPredicate { trait_ref: self.skip_binder().clone() })
659 /// An existential reference to a trait, where `Self` is erased.
660 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
662 /// exists T. T: Trait<'a, 'b, X, Y>
664 /// The substitutions don't include the erased `Self`, only trait
665 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
666 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
667 pub struct ExistentialTraitRef<'tcx> {
669 pub substs: &'tcx Substs<'tcx>,
672 impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
673 pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
674 // Select only the "input types" from a trait-reference. For
675 // now this is all the types that appear in the
676 // trait-reference, but it should eventually exclude
681 pub fn erase_self_ty(tcx: TyCtxt<'a, 'gcx, 'tcx>,
682 trait_ref: ty::TraitRef<'tcx>)
683 -> ty::ExistentialTraitRef<'tcx> {
684 // Assert there is a Self.
685 trait_ref.substs.type_at(0);
687 ty::ExistentialTraitRef {
688 def_id: trait_ref.def_id,
689 substs: tcx.intern_substs(&trait_ref.substs[1..])
693 /// Object types don't have a self-type specified. Therefore, when
694 /// we convert the principal trait-ref into a normal trait-ref,
695 /// you must give *some* self-type. A common choice is `mk_err()`
696 /// or some skolemized type.
697 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
698 -> ty::TraitRef<'tcx> {
699 // otherwise the escaping regions would be captured by the binder
700 assert!(!self_ty.has_escaping_regions());
704 substs: tcx.mk_substs_trait(self_ty, self.substs)
709 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
711 impl<'tcx> PolyExistentialTraitRef<'tcx> {
712 pub fn def_id(&self) -> DefId {
713 self.skip_binder().def_id
716 /// Object types don't have a self-type specified. Therefore, when
717 /// we convert the principal trait-ref into a normal trait-ref,
718 /// you must give *some* self-type. A common choice is `mk_err()`
719 /// or some skolemized type.
720 pub fn with_self_ty(&self, tcx: TyCtxt<'_, '_, 'tcx>,
722 -> ty::PolyTraitRef<'tcx> {
723 self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty))
727 /// Binder is a binder for higher-ranked lifetimes. It is part of the
728 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
729 /// (which would be represented by the type `PolyTraitRef ==
730 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
731 /// erase, or otherwise "discharge" these bound regions, we change the
732 /// type from `Binder<T>` to just `T` (see
733 /// e.g. `liberate_late_bound_regions`).
734 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
735 pub struct Binder<T>(T);
738 /// Wraps `value` in a binder, asserting that `value` does not
739 /// contain any bound regions that would be bound by the
740 /// binder. This is commonly used to 'inject' a value T into a
741 /// different binding level.
742 pub fn dummy<'tcx>(value: T) -> Binder<T>
743 where T: TypeFoldable<'tcx>
745 assert!(!value.has_escaping_regions());
749 /// Wraps `value` in a binder, binding late-bound regions (if any).
750 pub fn bind<'tcx>(value: T) -> Binder<T>
755 /// Skips the binder and returns the "bound" value. This is a
756 /// risky thing to do because it's easy to get confused about
757 /// debruijn indices and the like. It is usually better to
758 /// discharge the binder using `no_late_bound_regions` or
759 /// `replace_late_bound_regions` or something like
760 /// that. `skip_binder` is only valid when you are either
761 /// extracting data that has nothing to do with bound regions, you
762 /// are doing some sort of test that does not involve bound
763 /// regions, or you are being very careful about your depth
766 /// Some examples where `skip_binder` is reasonable:
768 /// - extracting the def-id from a PolyTraitRef;
769 /// - comparing the self type of a PolyTraitRef to see if it is equal to
770 /// a type parameter `X`, since the type `X` does not reference any regions
771 pub fn skip_binder(&self) -> &T {
775 pub fn as_ref(&self) -> Binder<&T> {
779 pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
780 where F: FnOnce(&T) -> U
782 self.as_ref().map_bound(f)
785 pub fn map_bound<F, U>(self, f: F) -> Binder<U>
786 where F: FnOnce(T) -> U
791 /// Unwraps and returns the value within, but only if it contains
792 /// no bound regions at all. (In other words, if this binder --
793 /// and indeed any enclosing binder -- doesn't bind anything at
794 /// all.) Otherwise, returns `None`.
796 /// (One could imagine having a method that just unwraps a single
797 /// binder, but permits late-bound regions bound by enclosing
798 /// binders, but that would require adjusting the debruijn
799 /// indices, and given the shallow binding structure we often use,
800 /// would not be that useful.)
801 pub fn no_late_bound_regions<'tcx>(self) -> Option<T>
802 where T : TypeFoldable<'tcx>
804 if self.skip_binder().has_escaping_regions() {
807 Some(self.skip_binder().clone())
811 /// Given two things that have the same binder level,
812 /// and an operation that wraps on their contents, execute the operation
813 /// and then wrap its result.
815 /// `f` should consider bound regions at depth 1 to be free, and
816 /// anything it produces with bound regions at depth 1 will be
817 /// bound in the resulting return value.
818 pub fn fuse<U,F,R>(self, u: Binder<U>, f: F) -> Binder<R>
819 where F: FnOnce(T, U) -> R
821 Binder(f(self.0, u.0))
824 /// Split the contents into two things that share the same binder
825 /// level as the original, returning two distinct binders.
827 /// `f` should consider bound regions at depth 1 to be free, and
828 /// anything it produces with bound regions at depth 1 will be
829 /// bound in the resulting return values.
830 pub fn split<U,V,F>(self, f: F) -> (Binder<U>, Binder<V>)
831 where F: FnOnce(T) -> (U, V)
833 let (u, v) = f(self.0);
834 (Binder(u), Binder(v))
838 /// Represents the projection of an associated type. In explicit UFCS
839 /// form this would be written `<T as Trait<..>>::N`.
840 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
841 pub struct ProjectionTy<'tcx> {
842 /// The parameters of the associated item.
843 pub substs: &'tcx Substs<'tcx>,
845 /// The DefId of the TraitItem for the associated type N.
847 /// Note that this is not the DefId of the TraitRef containing this
848 /// associated type, which is in tcx.associated_item(item_def_id).container.
849 pub item_def_id: DefId,
852 impl<'a, 'tcx> ProjectionTy<'tcx> {
853 /// Construct a ProjectionTy by searching the trait from trait_ref for the
854 /// associated item named item_name.
855 pub fn from_ref_and_name(
856 tcx: TyCtxt, trait_ref: ty::TraitRef<'tcx>, item_name: Ident
857 ) -> ProjectionTy<'tcx> {
858 let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
859 item.kind == ty::AssociatedKind::Type &&
860 tcx.hygienic_eq(item_name, item.ident, trait_ref.def_id)
864 substs: trait_ref.substs,
869 /// Extracts the underlying trait reference from this projection.
870 /// For example, if this is a projection of `<T as Iterator>::Item`,
871 /// then this function would return a `T: Iterator` trait reference.
872 pub fn trait_ref(&self, tcx: TyCtxt) -> ty::TraitRef<'tcx> {
873 let def_id = tcx.associated_item(self.item_def_id).container.id();
880 pub fn self_ty(&self) -> Ty<'tcx> {
881 self.substs.type_at(0)
885 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
886 pub struct GenSig<'tcx> {
887 pub yield_ty: Ty<'tcx>,
888 pub return_ty: Ty<'tcx>,
891 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
893 impl<'tcx> PolyGenSig<'tcx> {
894 pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
895 self.map_bound_ref(|sig| sig.yield_ty)
897 pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
898 self.map_bound_ref(|sig| sig.return_ty)
902 /// Signature of a function type, which I have arbitrarily
903 /// decided to use to refer to the input/output types.
905 /// - `inputs` is the list of arguments and their modes.
906 /// - `output` is the return type.
907 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
908 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
909 pub struct FnSig<'tcx> {
910 pub inputs_and_output: &'tcx Slice<Ty<'tcx>>,
912 pub unsafety: hir::Unsafety,
916 impl<'tcx> FnSig<'tcx> {
917 pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
918 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
921 pub fn output(&self) -> Ty<'tcx> {
922 self.inputs_and_output[self.inputs_and_output.len() - 1]
926 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
928 impl<'tcx> PolyFnSig<'tcx> {
929 pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
930 self.map_bound_ref(|fn_sig| fn_sig.inputs())
932 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
933 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
935 pub fn inputs_and_output(&self) -> ty::Binder<&'tcx Slice<Ty<'tcx>>> {
936 self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
938 pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
939 self.map_bound_ref(|fn_sig| fn_sig.output().clone())
941 pub fn variadic(&self) -> bool {
942 self.skip_binder().variadic
944 pub fn unsafety(&self) -> hir::Unsafety {
945 self.skip_binder().unsafety
947 pub fn abi(&self) -> abi::Abi {
948 self.skip_binder().abi
952 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
955 pub name: InternedString,
958 impl<'a, 'gcx, 'tcx> ParamTy {
959 pub fn new(index: u32, name: InternedString) -> ParamTy {
960 ParamTy { idx: index, name: name }
963 pub fn for_self() -> ParamTy {
964 ParamTy::new(0, keywords::SelfType.name().as_interned_str())
967 pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
968 ParamTy::new(def.index, def.name)
971 pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
972 tcx.mk_ty_param(self.idx, self.name)
975 pub fn is_self(&self) -> bool {
976 // FIXME(#50125): Ignoring `Self` with `idx != 0` might lead to weird behavior elsewhere,
977 // but this should only be possible when using `-Z continue-parse-after-error` like
978 // `compile-fail/issue-36638.rs`.
979 if self.name == keywords::SelfType.name().as_str() && self.idx == 0 {
987 /// A [De Bruijn index][dbi] is a standard means of representing
988 /// regions (and perhaps later types) in a higher-ranked setting. In
989 /// particular, imagine a type like this:
991 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
994 /// | +------------+ 0 | |
996 /// +--------------------------------+ 1 |
998 /// +------------------------------------------+ 0
1000 /// In this type, there are two binders (the outer fn and the inner
1001 /// fn). We need to be able to determine, for any given region, which
1002 /// fn type it is bound by, the inner or the outer one. There are
1003 /// various ways you can do this, but a De Bruijn index is one of the
1004 /// more convenient and has some nice properties. The basic idea is to
1005 /// count the number of binders, inside out. Some examples should help
1006 /// clarify what I mean.
1008 /// Let's start with the reference type `&'b isize` that is the first
1009 /// argument to the inner function. This region `'b` is assigned a De
1010 /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
1011 /// fn). The region `'a` that appears in the second argument type (`&'a
1012 /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
1013 /// second-innermost binder". (These indices are written on the arrays
1014 /// in the diagram).
1016 /// What is interesting is that De Bruijn index attached to a particular
1017 /// variable will vary depending on where it appears. For example,
1018 /// the final type `&'a char` also refers to the region `'a` declared on
1019 /// the outermost fn. But this time, this reference is not nested within
1020 /// any other binders (i.e., it is not an argument to the inner fn, but
1021 /// rather the outer one). Therefore, in this case, it is assigned a
1022 /// De Bruijn index of 0, because the innermost binder in that location
1023 /// is the outer fn.
1025 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1026 newtype_index!(DebruijnIndex
1028 DEBUG_FORMAT = "DebruijnIndex({})",
1029 const INNERMOST = 0,
1032 pub type Region<'tcx> = &'tcx RegionKind;
1034 /// Representation of regions.
1036 /// Unlike types, most region variants are "fictitious", not concrete,
1037 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1038 /// ones representing concrete regions.
1040 /// ## Bound Regions
1042 /// These are regions that are stored behind a binder and must be substituted
1043 /// with some concrete region before being used. There are 2 kind of
1044 /// bound regions: early-bound, which are bound in an item's Generics,
1045 /// and are substituted by a Substs, and late-bound, which are part of
1046 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
1047 /// the likes of `liberate_late_bound_regions`. The distinction exists
1048 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1050 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
1051 /// outside their binder, e.g. in types passed to type inference, and
1052 /// should first be substituted (by skolemized regions, free regions,
1053 /// or region variables).
1055 /// ## Skolemized and Free Regions
1057 /// One often wants to work with bound regions without knowing their precise
1058 /// identity. For example, when checking a function, the lifetime of a borrow
1059 /// can end up being assigned to some region parameter. In these cases,
1060 /// it must be ensured that bounds on the region can't be accidentally
1061 /// assumed without being checked.
1063 /// The process of doing that is called "skolemization". The bound regions
1064 /// are replaced by skolemized markers, which don't satisfy any relation
1065 /// not explicitly provided.
1067 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
1068 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
1069 /// to be used. These also support explicit bounds: both the internally-stored
1070 /// *scope*, which the region is assumed to outlive, as well as other
1071 /// relations stored in the `FreeRegionMap`. Note that these relations
1072 /// aren't checked when you `make_subregion` (or `eq_types`), only by
1073 /// `resolve_regions_and_report_errors`.
1075 /// When working with higher-ranked types, some region relations aren't
1076 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1077 /// `ReSkolemized` is designed for this purpose. In these contexts,
1078 /// there's also the risk that some inference variable laying around will
1079 /// get unified with your skolemized region: if you want to check whether
1080 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1081 /// with a skolemized region `'%a`, the variable `'_` would just be
1082 /// instantiated to the skolemized region `'%a`, which is wrong because
1083 /// the inference variable is supposed to satisfy the relation
1084 /// *for every value of the skolemized region*. To ensure that doesn't
1085 /// happen, you can use `leak_check`. This is more clearly explained
1086 /// by the [rustc guide].
1088 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1089 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1090 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/traits/hrtb.html
1091 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1092 pub enum RegionKind {
1093 // Region bound in a type or fn declaration which will be
1094 // substituted 'early' -- that is, at the same time when type
1095 // parameters are substituted.
1096 ReEarlyBound(EarlyBoundRegion),
1098 // Region bound in a function scope, which will be substituted when the
1099 // function is called.
1100 ReLateBound(DebruijnIndex, BoundRegion),
1102 /// When checking a function body, the types of all arguments and so forth
1103 /// that refer to bound region parameters are modified to refer to free
1104 /// region parameters.
1107 /// A concrete region naming some statically determined scope
1108 /// (e.g. an expression or sequence of statements) within the
1109 /// current function.
1110 ReScope(region::Scope),
1112 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1115 /// A region variable. Should not exist after typeck.
1118 /// A skolemized region - basically the higher-ranked version of ReFree.
1119 /// Should not exist after typeck.
1120 ReSkolemized(ty::UniverseIndex, BoundRegion),
1122 /// Empty lifetime is for data that is never accessed.
1123 /// Bottom in the region lattice. We treat ReEmpty somewhat
1124 /// specially; at least right now, we do not generate instances of
1125 /// it during the GLB computations, but rather
1126 /// generate an error instead. This is to improve error messages.
1127 /// The only way to get an instance of ReEmpty is to have a region
1128 /// variable with no constraints.
1131 /// Erased region, used by trait selection, in MIR and during codegen.
1134 /// These are regions bound in the "defining type" for a
1135 /// closure. They are used ONLY as part of the
1136 /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1137 /// See `ClosureRegionRequirements` for more details.
1138 ReClosureBound(RegionVid),
1140 /// Canonicalized region, used only when preparing a trait query.
1141 ReCanonical(CanonicalVar),
1144 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
1146 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1147 pub struct EarlyBoundRegion {
1150 pub name: InternedString,
1153 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1158 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1163 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1164 pub struct FloatVid {
1168 newtype_index!(RegionVid
1171 DEBUG_FORMAT = custom,
1174 impl Atom for RegionVid {
1175 fn index(self) -> usize {
1180 impl From<usize> for RegionVid {
1181 fn from(i: usize) -> RegionVid {
1186 impl From<RegionVid> for usize {
1187 fn from(vid: RegionVid) -> usize {
1192 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1198 /// A `FreshTy` is one that is generated as a replacement for an
1199 /// unbound type variable. This is convenient for caching etc. See
1200 /// `infer::freshen` for more details.
1205 /// Canonicalized type variable, used only when preparing a trait query.
1206 CanonicalTy(CanonicalVar),
1209 newtype_index!(CanonicalVar);
1211 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1212 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1213 pub struct ExistentialProjection<'tcx> {
1214 pub item_def_id: DefId,
1215 pub substs: &'tcx Substs<'tcx>,
1219 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1221 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
1222 /// Extracts the underlying existential trait reference from this projection.
1223 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1224 /// then this function would return a `exists T. T: Iterator` existential trait
1226 pub fn trait_ref(&self, tcx: TyCtxt) -> ty::ExistentialTraitRef<'tcx> {
1227 let def_id = tcx.associated_item(self.item_def_id).container.id();
1228 ty::ExistentialTraitRef{
1230 substs: self.substs,
1234 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1236 -> ty::ProjectionPredicate<'tcx>
1238 // otherwise the escaping regions would be captured by the binders
1239 assert!(!self_ty.has_escaping_regions());
1241 ty::ProjectionPredicate {
1242 projection_ty: ty::ProjectionTy {
1243 item_def_id: self.item_def_id,
1244 substs: tcx.mk_substs_trait(self_ty, self.substs),
1251 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
1252 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
1253 -> ty::PolyProjectionPredicate<'tcx> {
1254 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1257 pub fn item_def_id(&self) -> DefId {
1258 return self.skip_binder().item_def_id;
1262 impl DebruijnIndex {
1263 /// Returns the resulting index when this value is moved into
1264 /// `amount` number of new binders. So e.g. if you had
1266 /// for<'a> fn(&'a x)
1268 /// and you wanted to change to
1270 /// for<'a> fn(for<'b> fn(&'a x))
1272 /// you would need to shift the index for `'a` into 1 new binder.
1274 pub const fn shifted_in(self, amount: u32) -> DebruijnIndex {
1275 DebruijnIndex(self.0 + amount)
1278 /// Update this index in place by shifting it "in" through
1279 /// `amount` number of binders.
1280 pub fn shift_in(&mut self, amount: u32) {
1281 *self = self.shifted_in(amount);
1284 /// Returns the resulting index when this value is moved out from
1285 /// `amount` number of new binders.
1287 pub const fn shifted_out(self, amount: u32) -> DebruijnIndex {
1288 DebruijnIndex(self.0 - amount)
1291 /// Update in place by shifting out from `amount` binders.
1292 pub fn shift_out(&mut self, amount: u32) {
1293 *self = self.shifted_out(amount);
1296 /// Adjusts any Debruijn Indices so as to make `to_binder` the
1297 /// innermost binder. That is, if we have something bound at `to_binder`,
1298 /// it will now be bound at INNERMOST. This is an appropriate thing to do
1299 /// when moving a region out from inside binders:
1302 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
1303 /// // Binder: D3 D2 D1 ^^
1306 /// Here, the region `'a` would have the debruijn index D3,
1307 /// because it is the bound 3 binders out. However, if we wanted
1308 /// to refer to that region `'a` in the second argument (the `_`),
1309 /// those two binders would not be in scope. In that case, we
1310 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1311 /// debruijn index of `'a` to D1 (the innermost binder).
1313 /// If we invoke `shift_out_to_binder` and the region is in fact
1314 /// bound by one of the binders we are shifting out of, that is an
1315 /// error (and should fail an assertion failure).
1316 pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
1317 self.shifted_out((to_binder.0 - INNERMOST.0) as u32)
1321 impl_stable_hash_for!(tuple_struct DebruijnIndex { index });
1323 /// Region utilities
1325 pub fn is_late_bound(&self) -> bool {
1327 ty::ReLateBound(..) => true,
1332 pub fn bound_at_or_above_binder(&self, index: DebruijnIndex) -> bool {
1334 ty::ReLateBound(debruijn, _) => debruijn >= index,
1339 /// Adjusts any Debruijn Indices so as to make `to_binder` the
1340 /// innermost binder. That is, if we have something bound at `to_binder`,
1341 /// it will now be bound at INNERMOST. This is an appropriate thing to do
1342 /// when moving a region out from inside binders:
1345 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
1346 /// // Binder: D3 D2 D1 ^^
1349 /// Here, the region `'a` would have the debruijn index D3,
1350 /// because it is the bound 3 binders out. However, if we wanted
1351 /// to refer to that region `'a` in the second argument (the `_`),
1352 /// those two binders would not be in scope. In that case, we
1353 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1354 /// debruijn index of `'a` to D1 (the innermost binder).
1356 /// If we invoke `shift_out_to_binder` and the region is in fact
1357 /// bound by one of the binders we are shifting out of, that is an
1358 /// error (and should fail an assertion failure).
1359 pub fn shifted_out_to_binder(&self, to_binder: ty::DebruijnIndex) -> RegionKind {
1361 ty::ReLateBound(debruijn, r) => ty::ReLateBound(
1362 debruijn.shifted_out_to_binder(to_binder),
1369 pub fn keep_in_local_tcx(&self) -> bool {
1370 if let ty::ReVar(..) = self {
1377 pub fn type_flags(&self) -> TypeFlags {
1378 let mut flags = TypeFlags::empty();
1380 if self.keep_in_local_tcx() {
1381 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1386 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1387 flags = flags | TypeFlags::HAS_RE_INFER;
1389 ty::ReSkolemized(..) => {
1390 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1391 flags = flags | TypeFlags::HAS_RE_SKOL;
1393 ty::ReLateBound(..) => {
1394 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1396 ty::ReEarlyBound(..) => {
1397 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1398 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1403 ty::ReScope { .. } => {
1404 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1408 ty::ReCanonical(..) => {
1409 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1410 flags = flags | TypeFlags::HAS_CANONICAL_VARS;
1412 ty::ReClosureBound(..) => {
1413 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1418 ty::ReStatic | ty::ReEmpty | ty::ReErased | ty::ReLateBound(..) => (),
1419 _ => flags = flags | TypeFlags::HAS_FREE_LOCAL_NAMES,
1422 debug!("type_flags({:?}) = {:?}", self, flags);
1427 /// Given an early-bound or free region, returns the def-id where it was bound.
1428 /// For example, consider the regions in this snippet of code:
1432 /// ^^ -- early bound, declared on an impl
1434 /// fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1435 /// ^^ ^^ ^ anonymous, late-bound
1436 /// | early-bound, appears in where-clauses
1437 /// late-bound, appears only in fn args
1442 /// Here, `free_region_binding_scope('a)` would return the def-id
1443 /// of the impl, and for all the other highlighted regions, it
1444 /// would return the def-id of the function. In other cases (not shown), this
1445 /// function might return the def-id of a closure.
1446 pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_, '_, '_>) -> DefId {
1448 ty::ReEarlyBound(br) => {
1449 tcx.parent_def_id(br.def_id).unwrap()
1451 ty::ReFree(fr) => fr.scope,
1452 _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1458 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
1459 pub fn is_nil(&self) -> bool {
1461 TyTuple(ref tys) => tys.is_empty(),
1466 pub fn is_never(&self) -> bool {
1473 pub fn is_primitive(&self) -> bool {
1475 TyBool | TyChar | TyInt(_) | TyUint(_) | TyFloat(_) => true,
1480 pub fn is_ty_var(&self) -> bool {
1482 TyInfer(TyVar(_)) => true,
1487 pub fn is_ty_infer(&self) -> bool {
1494 pub fn is_phantom_data(&self) -> bool {
1495 if let TyAdt(def, _) = self.sty {
1496 def.is_phantom_data()
1502 pub fn is_bool(&self) -> bool { self.sty == TyBool }
1504 pub fn is_param(&self, index: u32) -> bool {
1506 ty::TyParam(ref data) => data.idx == index,
1511 pub fn is_self(&self) -> bool {
1513 TyParam(ref p) => p.is_self(),
1518 pub fn is_slice(&self) -> bool {
1520 TyRawPtr(TypeAndMut { ty, .. }) | TyRef(_, ty, _) => match ty.sty {
1521 TySlice(_) | TyStr => true,
1529 pub fn is_simd(&self) -> bool {
1531 TyAdt(def, _) => def.repr.simd(),
1536 pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1538 TyArray(ty, _) | TySlice(ty) => ty,
1539 TyStr => tcx.mk_mach_uint(ast::UintTy::U8),
1540 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1544 pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1546 TyAdt(def, substs) => {
1547 def.non_enum_variant().fields[0].ty(tcx, substs)
1549 _ => bug!("simd_type called on invalid type")
1553 pub fn simd_size(&self, _cx: TyCtxt) -> usize {
1555 TyAdt(def, _) => def.non_enum_variant().fields.len(),
1556 _ => bug!("simd_size called on invalid type")
1560 pub fn is_region_ptr(&self) -> bool {
1567 pub fn is_mutable_pointer(&self) -> bool {
1569 TyRawPtr(TypeAndMut { mutbl: hir::Mutability::MutMutable, .. }) |
1570 TyRef(_, _, hir::Mutability::MutMutable) => true,
1575 pub fn is_unsafe_ptr(&self) -> bool {
1577 TyRawPtr(_) => return true,
1582 pub fn is_box(&self) -> bool {
1584 TyAdt(def, _) => def.is_box(),
1589 /// panics if called on any type other than `Box<T>`
1590 pub fn boxed_ty(&self) -> Ty<'tcx> {
1592 TyAdt(def, substs) if def.is_box() => substs.type_at(0),
1593 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1597 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1598 /// (A TyRawPtr is scalar because it represents a non-managed pointer, so its
1599 /// contents are abstract to rustc.)
1600 pub fn is_scalar(&self) -> bool {
1602 TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
1603 TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
1604 TyFnDef(..) | TyFnPtr(_) | TyRawPtr(_) => true,
1609 /// Returns true if this type is a floating point type and false otherwise.
1610 pub fn is_floating_point(&self) -> bool {
1613 TyInfer(FloatVar(_)) => true,
1618 pub fn is_trait(&self) -> bool {
1620 TyDynamic(..) => true,
1625 pub fn is_enum(&self) -> bool {
1627 TyAdt(adt_def, _) => {
1634 pub fn is_closure(&self) -> bool {
1636 TyClosure(..) => true,
1641 pub fn is_generator(&self) -> bool {
1643 TyGenerator(..) => true,
1648 pub fn is_integral(&self) -> bool {
1650 TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
1655 pub fn is_fresh_ty(&self) -> bool {
1657 TyInfer(FreshTy(_)) => true,
1662 pub fn is_fresh(&self) -> bool {
1664 TyInfer(FreshTy(_)) => true,
1665 TyInfer(FreshIntTy(_)) => true,
1666 TyInfer(FreshFloatTy(_)) => true,
1671 pub fn is_char(&self) -> bool {
1678 pub fn is_fp(&self) -> bool {
1680 TyInfer(FloatVar(_)) | TyFloat(_) => true,
1685 pub fn is_numeric(&self) -> bool {
1686 self.is_integral() || self.is_fp()
1689 pub fn is_signed(&self) -> bool {
1696 pub fn is_machine(&self) -> bool {
1698 TyInt(ast::IntTy::Isize) | TyUint(ast::UintTy::Usize) => false,
1699 TyInt(..) | TyUint(..) | TyFloat(..) => true,
1704 pub fn has_concrete_skeleton(&self) -> bool {
1706 TyParam(_) | TyInfer(_) | TyError => false,
1711 /// Returns the type and mutability of *ty.
1713 /// The parameter `explicit` indicates if this is an *explicit* dereference.
1714 /// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1715 pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1717 TyAdt(def, _) if def.is_box() => {
1719 ty: self.boxed_ty(),
1720 mutbl: hir::MutImmutable,
1723 TyRef(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl }),
1724 TyRawPtr(mt) if explicit => Some(mt),
1729 /// Returns the type of `ty[i]`.
1730 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1732 TyArray(ty, _) | TySlice(ty) => Some(ty),
1737 pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1739 TyFnDef(def_id, substs) => {
1740 tcx.fn_sig(def_id).subst(tcx, substs)
1743 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1747 pub fn is_fn(&self) -> bool {
1749 TyFnDef(..) | TyFnPtr(_) => true,
1754 pub fn is_impl_trait(&self) -> bool {
1761 pub fn ty_to_def_id(&self) -> Option<DefId> {
1763 TyDynamic(ref tt, ..) => tt.principal().map(|p| p.def_id()),
1764 TyAdt(def, _) => Some(def.did),
1765 TyForeign(did) => Some(did),
1766 TyClosure(id, _) => Some(id),
1767 TyFnDef(id, _) => Some(id),
1772 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1774 TyAdt(adt, _) => Some(adt),
1779 /// Returns the regions directly referenced from this type (but
1780 /// not types reachable from this type via `walk_tys`). This
1781 /// ignores late-bound regions binders.
1782 pub fn regions(&self) -> Vec<ty::Region<'tcx>> {
1784 TyRef(region, _, _) => {
1787 TyDynamic(ref obj, region) => {
1788 let mut v = vec![region];
1789 if let Some(p) = obj.principal() {
1790 v.extend(p.skip_binder().substs.regions());
1794 TyAdt(_, substs) | TyAnon(_, substs) => {
1795 substs.regions().collect()
1797 TyClosure(_, ClosureSubsts { ref substs }) |
1798 TyGenerator(_, GeneratorSubsts { ref substs }, _) => {
1799 substs.regions().collect()
1801 TyProjection(ref data) => {
1802 data.substs.regions().collect()
1806 TyGeneratorWitness(..) |
1827 /// When we create a closure, we record its kind (i.e., what trait
1828 /// it implements) into its `ClosureSubsts` using a type
1829 /// parameter. This is kind of a phantom type, except that the
1830 /// most convenient thing for us to are the integral types. This
1831 /// function converts such a special type into the closure
1832 /// kind. To go the other way, use
1833 /// `tcx.closure_kind_ty(closure_kind)`.
1835 /// Note that during type checking, we use an inference variable
1836 /// to represent the closure kind, because it has not yet been
1837 /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
1838 /// is complete, that type variable will be unified.
1839 pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
1841 TyInt(int_ty) => match int_ty {
1842 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
1843 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1844 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1845 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1850 TyError => Some(ty::ClosureKind::Fn),
1852 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1857 /// Typed constant value.
1858 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Eq, PartialEq, Ord, PartialOrd)]
1859 pub struct Const<'tcx> {
1862 pub val: ConstValue<'tcx>,
1865 impl<'tcx> Const<'tcx> {
1867 tcx: TyCtxt<'_, '_, 'tcx>,
1869 substs: &'tcx Substs<'tcx>,
1872 tcx.mk_const(Const {
1873 val: ConstValue::Unevaluated(def_id, substs),
1879 pub fn from_const_value(
1880 tcx: TyCtxt<'_, '_, 'tcx>,
1881 val: ConstValue<'tcx>,
1884 tcx.mk_const(Const {
1891 pub fn from_byval_value(
1892 tcx: TyCtxt<'_, '_, 'tcx>,
1896 Self::from_const_value(tcx, ConstValue::from_byval_value(val), ty)
1901 tcx: TyCtxt<'_, '_, 'tcx>,
1905 Self::from_const_value(tcx, ConstValue::from_scalar(val), ty)
1910 tcx: TyCtxt<'_, '_, 'tcx>,
1912 ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
1914 let ty = tcx.lift_to_global(&ty).unwrap();
1915 let size = tcx.layout_of(ty).unwrap_or_else(|e| {
1916 panic!("could not compute layout for {:?}: {:?}", ty, e)
1918 let shift = 128 - size.bits();
1919 let truncated = (bits << shift) >> shift;
1920 assert_eq!(truncated, bits, "from_bits called with untruncated value");
1921 Self::from_scalar(tcx, Scalar::Bits { bits, defined: size.bits() as u8 }, ty.value)
1925 pub fn zero_sized(tcx: TyCtxt<'_, '_, 'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
1926 Self::from_scalar(tcx, Scalar::undef(), ty)
1930 pub fn from_bool(tcx: TyCtxt<'_, '_, 'tcx>, v: bool) -> &'tcx Self {
1931 Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
1935 pub fn from_usize(tcx: TyCtxt<'_, '_, 'tcx>, n: u64) -> &'tcx Self {
1936 Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize))
1942 tcx: TyCtxt<'_, '_, 'tcx>,
1943 ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
1945 if self.ty != ty.value {
1948 let ty = tcx.lift_to_global(&ty).unwrap();
1949 let size = tcx.layout_of(ty).ok()?.size;
1950 self.val.to_bits(size)
1954 pub fn to_ptr(&self) -> Option<Pointer> {
1959 pub fn to_byval_value(&self) -> Option<Value> {
1960 self.val.to_byval_value()
1964 pub fn to_scalar(&self) -> Option<Scalar> {
1965 self.val.to_scalar()
1971 tcx: TyCtxt<'_, '_, '_>,
1972 ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
1974 assert_eq!(self.ty, ty.value);
1975 let ty = tcx.lift_to_global(&ty).unwrap();
1976 let size = tcx.layout_of(ty).ok()?.size;
1977 self.val.to_bits(size)
1981 pub fn assert_bool(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<bool> {
1982 self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.bool)).and_then(|v| match v {
1990 pub fn assert_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<u64> {
1991 self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.usize)).map(|v| v as u64)
1997 tcx: TyCtxt<'_, '_, '_>,
1998 ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2000 match self.assert_bits(tcx, ty) {
2002 None => bug!("expected bits of {}, got {:#?}", ty.value, self),
2007 pub fn unwrap_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> u64 {
2008 match self.assert_usize(tcx) {
2010 None => bug!("expected constant usize, got {:#?}", self),
2015 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}