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 middle::const_val::ConstVal;
17 use rustc_data_structures::indexed_vec::Idx;
18 use ty::subst::{Substs, Subst, Kind, UnpackedKind};
19 use ty::{self, AdtDef, TypeFlags, Ty, TyCtxt, TypeFoldable};
23 use std::cmp::Ordering;
25 use syntax::ast::{self, Name};
26 use syntax::symbol::keywords;
33 use self::TypeVariants::*;
35 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
36 pub struct TypeAndMut<'tcx> {
38 pub mutbl: hir::Mutability,
41 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
42 RustcEncodable, RustcDecodable, Copy)]
43 /// A "free" region `fr` can be interpreted as "some region
44 /// at least as big as the scope `fr.scope`".
45 pub struct FreeRegion {
47 pub bound_region: BoundRegion,
50 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
51 RustcEncodable, RustcDecodable, Copy)]
52 pub enum BoundRegion {
53 /// An anonymous region parameter for a given fn (&T)
56 /// Named region parameters for functions (a in &'a T)
58 /// The def-id is needed to distinguish free regions in
59 /// the event of shadowing.
62 /// Fresh bound identifiers created during GLB computations.
65 /// Anonymous region for the implicit env pointer parameter
71 pub fn is_named(&self) -> bool {
73 BoundRegion::BrNamed(..) => true,
79 /// NB: If you change this, you'll probably want to change the corresponding
80 /// AST structure in libsyntax/ast.rs as well.
81 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
82 pub enum TypeVariants<'tcx> {
83 /// The primitive boolean type. Written as `bool`.
86 /// The primitive character type; holds a Unicode scalar value
87 /// (a non-surrogate code point). Written as `char`.
90 /// A primitive signed integer type. For example, `i32`.
93 /// A primitive unsigned integer type. For example, `u32`.
96 /// A primitive floating-point type. For example, `f64`.
97 TyFloat(ast::FloatTy),
99 /// Structures, enumerations and unions.
101 /// Substs here, possibly against intuition, *may* contain `TyParam`s.
102 /// That is, even after substitution it is possible that there are type
103 /// variables. This happens when the `TyAdt` corresponds to an ADT
104 /// definition and not a concrete use of it.
105 TyAdt(&'tcx AdtDef, &'tcx Substs<'tcx>),
109 /// The pointee of a string slice. Written as `str`.
112 /// An array with the given length. Written as `[T; n]`.
113 TyArray(Ty<'tcx>, &'tcx ty::Const<'tcx>),
115 /// The pointee of an array slice. Written as `[T]`.
118 /// A raw pointer. Written as `*mut T` or `*const T`
119 TyRawPtr(TypeAndMut<'tcx>),
121 /// A reference; a pointer with an associated lifetime. Written as
122 /// `&'a mut T` or `&'a T`.
123 TyRef(Region<'tcx>, TypeAndMut<'tcx>),
125 /// The anonymous type of a function declaration/definition. Each
126 /// function has a unique type.
127 TyFnDef(DefId, &'tcx Substs<'tcx>),
129 /// A pointer to a function. Written as `fn() -> i32`.
130 TyFnPtr(PolyFnSig<'tcx>),
132 /// A trait, defined with `trait`.
133 TyDynamic(Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
135 /// The anonymous type of a closure. Used to represent the type of
137 TyClosure(DefId, ClosureSubsts<'tcx>),
139 /// The anonymous type of a generator. Used to represent the type of
141 TyGenerator(DefId, ClosureSubsts<'tcx>, GeneratorInterior<'tcx>),
143 /// A type representin the types stored inside a generator.
144 /// This should only appear in GeneratorInteriors.
145 TyGeneratorWitness(Binder<&'tcx Slice<Ty<'tcx>>>),
147 /// The never type `!`
150 /// A tuple type. For example, `(i32, bool)`.
151 TyTuple(&'tcx Slice<Ty<'tcx>>),
153 /// The projection of an associated type. For example,
154 /// `<T as Trait<..>>::N`.
155 TyProjection(ProjectionTy<'tcx>),
157 /// Anonymized (`impl Trait`) type found in a return type.
158 /// The DefId comes from the `impl Trait` ast::Ty node, and the
159 /// substitutions are for the generics of the function in question.
160 /// After typeck, the concrete type can be found in the `types` map.
161 TyAnon(DefId, &'tcx Substs<'tcx>),
163 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
166 /// A type variable used during type-checking.
169 /// A placeholder for a type which could not be computed; this is
170 /// propagated to avoid useless error messages.
174 /// A closure can be modeled as a struct that looks like:
176 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
184 /// - 'l0...'li and T0...Tj are the lifetime and type parameters
185 /// in scope on the function that defined the closure,
186 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
187 /// is rather hackily encoded via a scalar type. See
188 /// `TyS::to_opt_closure_kind` for details.
189 /// - CS represents the *closure signature*, representing as a `fn()`
190 /// type. For example, `fn(u32, u32) -> u32` would mean that the closure
191 /// implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
193 /// - U0...Uk are type parameters representing the types of its upvars
194 /// (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
195 /// and the up-var has the type `Foo`, then `Ui = &Foo`).
197 /// So, for example, given this function:
199 /// fn foo<'a, T>(data: &'a mut T) {
200 /// do(|| data.count += 1)
203 /// the type of the closure would be something like:
205 /// struct Closure<'a, T, U0> {
209 /// Note that the type of the upvar is not specified in the struct.
210 /// You may wonder how the impl would then be able to use the upvar,
211 /// if it doesn't know it's type? The answer is that the impl is
212 /// (conceptually) not fully generic over Closure but rather tied to
213 /// instances with the expected upvar types:
215 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
219 /// You can see that the *impl* fully specified the type of the upvar
220 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
221 /// (Here, I am assuming that `data` is mut-borrowed.)
223 /// Now, the last question you may ask is: Why include the upvar types
224 /// as extra type parameters? The reason for this design is that the
225 /// upvar types can reference lifetimes that are internal to the
226 /// creating function. In my example above, for example, the lifetime
227 /// `'b` represents the scope of the closure itself; this is some
228 /// subset of `foo`, probably just the scope of the call to the to
229 /// `do()`. If we just had the lifetime/type parameters from the
230 /// enclosing function, we couldn't name this lifetime `'b`. Note that
231 /// there can also be lifetimes in the types of the upvars themselves,
232 /// if one of them happens to be a reference to something that the
233 /// creating fn owns.
235 /// OK, you say, so why not create a more minimal set of parameters
236 /// that just includes the extra lifetime parameters? The answer is
237 /// primarily that it would be hard --- we don't know at the time when
238 /// we create the closure type what the full types of the upvars are,
239 /// nor do we know which are borrowed and which are not. In this
240 /// design, we can just supply a fresh type parameter and figure that
243 /// All right, you say, but why include the type parameters from the
244 /// original function then? The answer is that trans may need them
245 /// when monomorphizing, and they may not appear in the upvars. A
246 /// closure could capture no variables but still make use of some
247 /// in-scope type parameter with a bound (e.g., if our example above
248 /// had an extra `U: Default`, and the closure called `U::default()`).
250 /// There is another reason. This design (implicitly) prohibits
251 /// closures from capturing themselves (except via a trait
252 /// object). This simplifies closure inference considerably, since it
253 /// means that when we infer the kind of a closure or its upvars, we
254 /// don't have to handle cycles where the decisions we make for
255 /// closure C wind up influencing the decisions we ought to make for
256 /// closure C (which would then require fixed point iteration to
257 /// handle). Plus it fixes an ICE. :P
261 /// Perhaps surprisingly, `ClosureSubsts` are also used for
262 /// generators. In that case, what is written above is only half-true
263 /// -- the set of type parameters is similar, but the role of CK and
264 /// CS are different. CK represents the "yield type" and CS
265 /// represents the "return type" of the generator.
267 /// It'd be nice to split this struct into ClosureSubsts and
268 /// GeneratorSubsts, I believe. -nmatsakis
269 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
270 pub struct ClosureSubsts<'tcx> {
271 /// Lifetime and type parameters from the enclosing function,
272 /// concatenated with the types of the upvars.
274 /// These are separated out because trans wants to pass them around
275 /// when monomorphizing.
276 pub substs: &'tcx Substs<'tcx>,
279 /// Struct returned by `split()`. Note that these are subslices of the
280 /// parent slice and not canonical substs themselves.
281 struct SplitClosureSubsts<'tcx> {
282 closure_kind_ty: Ty<'tcx>,
283 closure_sig_ty: Ty<'tcx>,
284 upvar_kinds: &'tcx [Kind<'tcx>],
287 impl<'tcx> ClosureSubsts<'tcx> {
288 /// Divides the closure substs into their respective
289 /// components. Single source of truth with respect to the
291 fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitClosureSubsts<'tcx> {
292 let generics = tcx.generics_of(def_id);
293 let parent_len = generics.parent_count();
295 closure_kind_ty: self.substs.type_at(parent_len),
296 closure_sig_ty: self.substs.type_at(parent_len + 1),
297 upvar_kinds: &self.substs[parent_len + 2..],
302 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
303 impl Iterator<Item=Ty<'tcx>> + 'tcx
305 let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
306 upvar_kinds.iter().map(|t| {
307 if let UnpackedKind::Type(ty) = t.unpack() {
310 bug!("upvar should be type")
315 /// Returns the closure kind for this closure; may return a type
316 /// variable during inference. To get the closure kind during
317 /// inference, use `infcx.closure_kind(def_id, substs)`.
318 pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
319 self.split(def_id, tcx).closure_kind_ty
322 /// Returns the type representing the closure signature for this
323 /// closure; may contain type variables during inference. To get
324 /// the closure signature during inference, use
325 /// `infcx.fn_sig(def_id)`.
326 pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
327 self.split(def_id, tcx).closure_sig_ty
330 /// Returns the type representing the yield type of the generator.
331 pub fn generator_yield_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
332 self.closure_kind_ty(def_id, tcx)
335 /// Returns the type representing the return type of the generator.
336 pub fn generator_return_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
337 self.closure_sig_ty(def_id, tcx)
340 /// Return the "generator signature", which consists of its yield
341 /// and return types.
343 /// NB. Some bits of the code prefers to see this wrapped in a
344 /// binder, but it never contains bound regions. Probably this
345 /// function should be removed.
346 pub fn generator_poly_sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> PolyGenSig<'tcx> {
347 ty::Binder(self.generator_sig(def_id, tcx))
350 /// Return the "generator signature", which consists of its yield
351 /// and return types.
352 pub fn generator_sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> GenSig<'tcx> {
354 yield_ty: self.generator_yield_ty(def_id, tcx),
355 return_ty: self.generator_return_ty(def_id, tcx),
360 impl<'tcx> ClosureSubsts<'tcx> {
361 /// Returns the closure kind for this closure; only usable outside
362 /// of an inference context, because in that context we know that
363 /// there are no type variables.
365 /// If you have an inference context, use `infcx.closure_kind()`.
366 pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::ClosureKind {
367 self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
370 /// Extracts the signature from the closure; only usable outside
371 /// of an inference context, because in that context we know that
372 /// there are no type variables.
374 /// If you have an inference context, use `infcx.closure_sig()`.
375 pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::PolyFnSig<'tcx> {
376 match self.closure_sig_ty(def_id, tcx).sty {
377 ty::TyFnPtr(sig) => sig,
378 ref t => bug!("closure_sig_ty is not a fn-ptr: {:?}", t),
383 impl<'a, 'gcx, 'tcx> ClosureSubsts<'tcx> {
384 /// This returns the types of the MIR locals which had to be stored across suspension points.
385 /// It is calculated in rustc_mir::transform::generator::StateTransform.
386 /// All the types here must be in the tuple in GeneratorInterior.
387 pub fn state_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
388 impl Iterator<Item=Ty<'tcx>> + 'a
390 let state = tcx.generator_layout(def_id).fields.iter();
391 state.map(move |d| d.ty.subst(tcx, self.substs))
394 /// This is the types of the fields of a generate which
395 /// is available before the generator transformation.
396 /// It includes the upvars and the state discriminant which is u32.
397 pub fn pre_transforms_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
398 impl Iterator<Item=Ty<'tcx>> + 'a
400 self.upvar_tys(def_id, tcx).chain(iter::once(tcx.types.u32))
403 /// This is the types of all the fields stored in a generator.
404 /// It includes the upvars, state types and the state discriminant which is u32.
405 pub fn field_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
406 impl Iterator<Item=Ty<'tcx>> + 'a
408 self.pre_transforms_tys(def_id, tcx).chain(self.state_tys(def_id, tcx))
412 /// This describes the types that can be contained in a generator.
413 /// It will be a type variable initially and unified in the last stages of typeck of a body.
414 /// It contains a tuple of all the types that could end up on a generator frame.
415 /// The state transformation MIR pass may only produce layouts which mention types in this tuple.
416 /// Upvars are not counted here.
417 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
418 pub struct GeneratorInterior<'tcx> {
419 pub witness: Ty<'tcx>,
423 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
424 pub enum ExistentialPredicate<'tcx> {
426 Trait(ExistentialTraitRef<'tcx>),
427 /// e.g. Iterator::Item = T
428 Projection(ExistentialProjection<'tcx>),
433 impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
434 pub fn cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
435 use self::ExistentialPredicate::*;
436 match (*self, *other) {
437 (Trait(_), Trait(_)) => Ordering::Equal,
438 (Projection(ref a), Projection(ref b)) =>
439 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
440 (AutoTrait(ref a), AutoTrait(ref b)) =>
441 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
442 (Trait(_), _) => Ordering::Less,
443 (Projection(_), Trait(_)) => Ordering::Greater,
444 (Projection(_), _) => Ordering::Less,
445 (AutoTrait(_), _) => Ordering::Greater,
451 impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
452 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
453 -> ty::Predicate<'tcx> {
455 match *self.skip_binder() {
456 ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
457 ExistentialPredicate::Projection(p) =>
458 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
459 ExistentialPredicate::AutoTrait(did) => {
460 let trait_ref = Binder(ty::TraitRef {
462 substs: tcx.mk_substs_trait(self_ty, &[]),
464 trait_ref.to_predicate()
470 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<ExistentialPredicate<'tcx>> {}
472 impl<'tcx> Slice<ExistentialPredicate<'tcx>> {
473 pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
475 Some(&ExistentialPredicate::Trait(tr)) => Some(tr),
481 pub fn projection_bounds<'a>(&'a self) ->
482 impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
483 self.iter().filter_map(|predicate| {
485 ExistentialPredicate::Projection(p) => Some(p),
492 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
493 self.iter().filter_map(|predicate| {
495 ExistentialPredicate::AutoTrait(d) => Some(d),
502 impl<'tcx> Binder<&'tcx Slice<ExistentialPredicate<'tcx>>> {
503 pub fn principal(&self) -> Option<PolyExistentialTraitRef<'tcx>> {
504 self.skip_binder().principal().map(Binder)
508 pub fn projection_bounds<'a>(&'a self) ->
509 impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
510 self.skip_binder().projection_bounds().map(Binder)
514 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
515 self.skip_binder().auto_traits()
518 pub fn iter<'a>(&'a self)
519 -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
520 self.skip_binder().iter().cloned().map(Binder)
524 /// A complete reference to a trait. These take numerous guises in syntax,
525 /// but perhaps the most recognizable form is in a where clause:
529 /// This would be represented by a trait-reference where the def-id is the
530 /// def-id for the trait `Foo` and the substs define `T` as parameter 0,
531 /// and `U` as parameter 1.
533 /// Trait references also appear in object types like `Foo<U>`, but in
534 /// that case the `Self` parameter is absent from the substitutions.
536 /// Note that a `TraitRef` introduces a level of region binding, to
537 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
538 /// U>` or higher-ranked object types.
539 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
540 pub struct TraitRef<'tcx> {
542 pub substs: &'tcx Substs<'tcx>,
545 impl<'tcx> TraitRef<'tcx> {
546 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
547 TraitRef { def_id: def_id, substs: substs }
550 pub fn self_ty(&self) -> Ty<'tcx> {
551 self.substs.type_at(0)
554 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
555 // Select only the "input types" from a trait-reference. For
556 // now this is all the types that appear in the
557 // trait-reference, but it should eventually exclude
563 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
565 impl<'tcx> PolyTraitRef<'tcx> {
566 pub fn self_ty(&self) -> Ty<'tcx> {
570 pub fn def_id(&self) -> DefId {
574 pub fn substs(&self) -> &'tcx Substs<'tcx> {
575 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
579 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
580 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
584 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
585 // Note that we preserve binding levels
586 Binder(ty::TraitPredicate { trait_ref: self.0.clone() })
590 /// An existential reference to a trait, where `Self` is erased.
591 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
593 /// exists T. T: Trait<'a, 'b, X, Y>
595 /// The substitutions don't include the erased `Self`, only trait
596 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
597 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
598 pub struct ExistentialTraitRef<'tcx> {
600 pub substs: &'tcx Substs<'tcx>,
603 impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
604 pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
605 // Select only the "input types" from a trait-reference. For
606 // now this is all the types that appear in the
607 // trait-reference, but it should eventually exclude
612 /// Object types don't have a self-type specified. Therefore, when
613 /// we convert the principal trait-ref into a normal trait-ref,
614 /// you must give *some* self-type. A common choice is `mk_err()`
615 /// or some skolemized type.
616 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
617 -> ty::TraitRef<'tcx> {
618 // otherwise the escaping regions would be captured by the binder
619 assert!(!self_ty.has_escaping_regions());
623 substs: tcx.mk_substs(
624 iter::once(self_ty.into()).chain(self.substs.iter().cloned()))
629 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
631 impl<'tcx> PolyExistentialTraitRef<'tcx> {
632 pub fn def_id(&self) -> DefId {
636 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
637 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
642 /// Binder is a binder for higher-ranked lifetimes. It is part of the
643 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
644 /// (which would be represented by the type `PolyTraitRef ==
645 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
646 /// erase, or otherwise "discharge" these bound regions, we change the
647 /// type from `Binder<T>` to just `T` (see
648 /// e.g. `liberate_late_bound_regions`).
649 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
650 pub struct Binder<T>(pub T);
653 /// Wraps `value` in a binder, asserting that `value` does not
654 /// contain any bound regions that would be bound by the
655 /// binder. This is commonly used to 'inject' a value T into a
656 /// different binding level.
657 pub fn dummy<'tcx>(value: T) -> Binder<T>
658 where T: TypeFoldable<'tcx>
660 assert!(!value.has_escaping_regions());
664 /// Skips the binder and returns the "bound" value. This is a
665 /// risky thing to do because it's easy to get confused about
666 /// debruijn indices and the like. It is usually better to
667 /// discharge the binder using `no_late_bound_regions` or
668 /// `replace_late_bound_regions` or something like
669 /// that. `skip_binder` is only valid when you are either
670 /// extracting data that has nothing to do with bound regions, you
671 /// are doing some sort of test that does not involve bound
672 /// regions, or you are being very careful about your depth
675 /// Some examples where `skip_binder` is reasonable:
677 /// - extracting the def-id from a PolyTraitRef;
678 /// - comparing the self type of a PolyTraitRef to see if it is equal to
679 /// a type parameter `X`, since the type `X` does not reference any regions
680 pub fn skip_binder(&self) -> &T {
684 pub fn as_ref(&self) -> Binder<&T> {
688 pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
689 where F: FnOnce(&T) -> U
691 self.as_ref().map_bound(f)
694 pub fn map_bound<F, U>(self, f: F) -> Binder<U>
695 where F: FnOnce(T) -> U
697 ty::Binder(f(self.0))
700 /// Unwraps and returns the value within, but only if it contains
701 /// no bound regions at all. (In other words, if this binder --
702 /// and indeed any enclosing binder -- doesn't bind anything at
703 /// all.) Otherwise, returns `None`.
705 /// (One could imagine having a method that just unwraps a single
706 /// binder, but permits late-bound regions bound by enclosing
707 /// binders, but that would require adjusting the debruijn
708 /// indices, and given the shallow binding structure we often use,
709 /// would not be that useful.)
710 pub fn no_late_bound_regions<'tcx>(self) -> Option<T>
711 where T : TypeFoldable<'tcx>
713 if self.skip_binder().has_escaping_regions() {
716 Some(self.skip_binder().clone())
720 /// Given two things that have the same binder level,
721 /// and an operation that wraps on their contents, execute the operation
722 /// and then wrap its result.
724 /// `f` should consider bound regions at depth 1 to be free, and
725 /// anything it produces with bound regions at depth 1 will be
726 /// bound in the resulting return value.
727 pub fn fuse<U,F,R>(self, u: Binder<U>, f: F) -> Binder<R>
728 where F: FnOnce(T, U) -> R
730 ty::Binder(f(self.0, u.0))
733 /// Split the contents into two things that share the same binder
734 /// level as the original, returning two distinct binders.
736 /// `f` should consider bound regions at depth 1 to be free, and
737 /// anything it produces with bound regions at depth 1 will be
738 /// bound in the resulting return values.
739 pub fn split<U,V,F>(self, f: F) -> (Binder<U>, Binder<V>)
740 where F: FnOnce(T) -> (U, V)
742 let (u, v) = f(self.0);
743 (ty::Binder(u), ty::Binder(v))
747 /// Represents the projection of an associated type. In explicit UFCS
748 /// form this would be written `<T as Trait<..>>::N`.
749 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
750 pub struct ProjectionTy<'tcx> {
751 /// The parameters of the associated item.
752 pub substs: &'tcx Substs<'tcx>,
754 /// The DefId of the TraitItem for the associated type N.
756 /// Note that this is not the DefId of the TraitRef containing this
757 /// associated type, which is in tcx.associated_item(item_def_id).container.
758 pub item_def_id: DefId,
761 impl<'a, 'tcx> ProjectionTy<'tcx> {
762 /// Construct a ProjectionTy by searching the trait from trait_ref for the
763 /// associated item named item_name.
764 pub fn from_ref_and_name(
765 tcx: TyCtxt, trait_ref: ty::TraitRef<'tcx>, item_name: Name
766 ) -> ProjectionTy<'tcx> {
767 let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
768 item.kind == ty::AssociatedKind::Type &&
769 tcx.hygienic_eq(item_name, item.name, trait_ref.def_id)
773 substs: trait_ref.substs,
778 /// Extracts the underlying trait reference from this projection.
779 /// For example, if this is a projection of `<T as Iterator>::Item`,
780 /// then this function would return a `T: Iterator` trait reference.
781 pub fn trait_ref(&self, tcx: TyCtxt) -> ty::TraitRef<'tcx> {
782 let def_id = tcx.associated_item(self.item_def_id).container.id();
789 pub fn self_ty(&self) -> Ty<'tcx> {
790 self.substs.type_at(0)
794 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
795 pub struct GenSig<'tcx> {
796 pub yield_ty: Ty<'tcx>,
797 pub return_ty: Ty<'tcx>,
800 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
802 impl<'tcx> PolyGenSig<'tcx> {
803 pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
804 self.map_bound_ref(|sig| sig.yield_ty)
806 pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
807 self.map_bound_ref(|sig| sig.return_ty)
811 /// Signature of a function type, which I have arbitrarily
812 /// decided to use to refer to the input/output types.
814 /// - `inputs` is the list of arguments and their modes.
815 /// - `output` is the return type.
816 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
817 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
818 pub struct FnSig<'tcx> {
819 pub inputs_and_output: &'tcx Slice<Ty<'tcx>>,
821 pub unsafety: hir::Unsafety,
825 impl<'tcx> FnSig<'tcx> {
826 pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
827 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
830 pub fn output(&self) -> Ty<'tcx> {
831 self.inputs_and_output[self.inputs_and_output.len() - 1]
835 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
837 impl<'tcx> PolyFnSig<'tcx> {
838 pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
839 Binder(self.skip_binder().inputs())
841 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
842 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
844 pub fn inputs_and_output(&self) -> ty::Binder<&'tcx Slice<Ty<'tcx>>> {
845 self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
847 pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
848 self.map_bound_ref(|fn_sig| fn_sig.output().clone())
850 pub fn variadic(&self) -> bool {
851 self.skip_binder().variadic
853 pub fn unsafety(&self) -> hir::Unsafety {
854 self.skip_binder().unsafety
856 pub fn abi(&self) -> abi::Abi {
857 self.skip_binder().abi
861 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
867 impl<'a, 'gcx, 'tcx> ParamTy {
868 pub fn new(index: u32, name: Name) -> ParamTy {
869 ParamTy { idx: index, name: name }
872 pub fn for_self() -> ParamTy {
873 ParamTy::new(0, keywords::SelfType.name())
876 pub fn for_def(def: &ty::TypeParameterDef) -> ParamTy {
877 ParamTy::new(def.index, def.name)
880 pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
881 tcx.mk_param(self.idx, self.name)
884 pub fn is_self(&self) -> bool {
885 if self.name == keywords::SelfType.name() {
886 assert_eq!(self.idx, 0);
894 /// A [De Bruijn index][dbi] is a standard means of representing
895 /// regions (and perhaps later types) in a higher-ranked setting. In
896 /// particular, imagine a type like this:
898 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
901 /// | +------------+ 1 | |
903 /// +--------------------------------+ 2 |
905 /// +------------------------------------------+ 1
907 /// In this type, there are two binders (the outer fn and the inner
908 /// fn). We need to be able to determine, for any given region, which
909 /// fn type it is bound by, the inner or the outer one. There are
910 /// various ways you can do this, but a De Bruijn index is one of the
911 /// more convenient and has some nice properties. The basic idea is to
912 /// count the number of binders, inside out. Some examples should help
913 /// clarify what I mean.
915 /// Let's start with the reference type `&'b isize` that is the first
916 /// argument to the inner function. This region `'b` is assigned a De
917 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
918 /// fn). The region `'a` that appears in the second argument type (`&'a
919 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
920 /// second-innermost binder". (These indices are written on the arrays
923 /// What is interesting is that De Bruijn index attached to a particular
924 /// variable will vary depending on where it appears. For example,
925 /// the final type `&'a char` also refers to the region `'a` declared on
926 /// the outermost fn. But this time, this reference is not nested within
927 /// any other binders (i.e., it is not an argument to the inner fn, but
928 /// rather the outer one). Therefore, in this case, it is assigned a
929 /// De Bruijn index of 1, because the innermost binder in that location
932 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
933 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy, PartialOrd, Ord)]
934 pub struct DebruijnIndex {
935 /// We maintain the invariant that this is never 0. So 1 indicates
936 /// the innermost binder. To ensure this, create with `DebruijnIndex::new`.
940 pub type Region<'tcx> = &'tcx RegionKind;
942 /// Representation of regions.
944 /// Unlike types, most region variants are "fictitious", not concrete,
945 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
946 /// ones representing concrete regions.
950 /// These are regions that are stored behind a binder and must be substituted
951 /// with some concrete region before being used. There are 2 kind of
952 /// bound regions: early-bound, which are bound in an item's Generics,
953 /// and are substituted by a Substs, and late-bound, which are part of
954 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
955 /// the likes of `liberate_late_bound_regions`. The distinction exists
956 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
958 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
959 /// outside their binder, e.g. in types passed to type inference, and
960 /// should first be substituted (by skolemized regions, free regions,
961 /// or region variables).
963 /// ## Skolemized and Free Regions
965 /// One often wants to work with bound regions without knowing their precise
966 /// identity. For example, when checking a function, the lifetime of a borrow
967 /// can end up being assigned to some region parameter. In these cases,
968 /// it must be ensured that bounds on the region can't be accidentally
969 /// assumed without being checked.
971 /// The process of doing that is called "skolemization". The bound regions
972 /// are replaced by skolemized markers, which don't satisfy any relation
973 /// not explicitly provided.
975 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
976 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
977 /// to be used. These also support explicit bounds: both the internally-stored
978 /// *scope*, which the region is assumed to outlive, as well as other
979 /// relations stored in the `FreeRegionMap`. Note that these relations
980 /// aren't checked when you `make_subregion` (or `eq_types`), only by
981 /// `resolve_regions_and_report_errors`.
983 /// When working with higher-ranked types, some region relations aren't
984 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
985 /// `ReSkolemized` is designed for this purpose. In these contexts,
986 /// there's also the risk that some inference variable laying around will
987 /// get unified with your skolemized region: if you want to check whether
988 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
989 /// with a skolemized region `'%a`, the variable `'_` would just be
990 /// instantiated to the skolemized region `'%a`, which is wrong because
991 /// the inference variable is supposed to satisfy the relation
992 /// *for every value of the skolemized region*. To ensure that doesn't
993 /// happen, you can use `leak_check`. This is more clearly explained
994 /// by the [rustc guide].
996 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
997 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
998 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/trait-hrtb.html
999 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1000 pub enum RegionKind {
1001 // Region bound in a type or fn declaration which will be
1002 // substituted 'early' -- that is, at the same time when type
1003 // parameters are substituted.
1004 ReEarlyBound(EarlyBoundRegion),
1006 // Region bound in a function scope, which will be substituted when the
1007 // function is called.
1008 ReLateBound(DebruijnIndex, BoundRegion),
1010 /// When checking a function body, the types of all arguments and so forth
1011 /// that refer to bound region parameters are modified to refer to free
1012 /// region parameters.
1015 /// A concrete region naming some statically determined scope
1016 /// (e.g. an expression or sequence of statements) within the
1017 /// current function.
1018 ReScope(region::Scope),
1020 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1023 /// A region variable. Should not exist after typeck.
1026 /// A skolemized region - basically the higher-ranked version of ReFree.
1027 /// Should not exist after typeck.
1028 ReSkolemized(ty::UniverseIndex, BoundRegion),
1030 /// Empty lifetime is for data that is never accessed.
1031 /// Bottom in the region lattice. We treat ReEmpty somewhat
1032 /// specially; at least right now, we do not generate instances of
1033 /// it during the GLB computations, but rather
1034 /// generate an error instead. This is to improve error messages.
1035 /// The only way to get an instance of ReEmpty is to have a region
1036 /// variable with no constraints.
1039 /// Erased region, used by trait selection, in MIR and during trans.
1042 /// These are regions bound in the "defining type" for a
1043 /// closure. They are used ONLY as part of the
1044 /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1045 /// See `ClosureRegionRequirements` for more details.
1046 ReClosureBound(RegionVid),
1048 /// Canonicalized region, used only when preparing a trait query.
1049 ReCanonical(CanonicalVar),
1052 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
1054 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1055 pub struct EarlyBoundRegion {
1061 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1066 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1071 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1072 pub struct FloatVid {
1076 newtype_index!(RegionVid
1079 DEBUG_FORMAT = custom,
1082 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1088 /// A `FreshTy` is one that is generated as a replacement for an
1089 /// unbound type variable. This is convenient for caching etc. See
1090 /// `infer::freshen` for more details.
1095 /// Canonicalized type variable, used only when preparing a trait query.
1096 CanonicalTy(CanonicalVar),
1099 newtype_index!(CanonicalVar);
1101 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1102 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1103 pub struct ExistentialProjection<'tcx> {
1104 pub item_def_id: DefId,
1105 pub substs: &'tcx Substs<'tcx>,
1109 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1111 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
1112 /// Extracts the underlying existential trait reference from this projection.
1113 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1114 /// then this function would return a `exists T. T: Iterator` existential trait
1116 pub fn trait_ref(&self, tcx: TyCtxt) -> ty::ExistentialTraitRef<'tcx> {
1117 let def_id = tcx.associated_item(self.item_def_id).container.id();
1118 ty::ExistentialTraitRef{
1120 substs: self.substs,
1124 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1126 -> ty::ProjectionPredicate<'tcx>
1128 // otherwise the escaping regions would be captured by the binders
1129 assert!(!self_ty.has_escaping_regions());
1131 ty::ProjectionPredicate {
1132 projection_ty: ty::ProjectionTy {
1133 item_def_id: self.item_def_id,
1134 substs: tcx.mk_substs(
1135 iter::once(self_ty.into()).chain(self.substs.iter().cloned())),
1142 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
1143 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
1144 -> ty::PolyProjectionPredicate<'tcx> {
1145 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1149 impl DebruijnIndex {
1150 pub fn new(depth: u32) -> DebruijnIndex {
1152 DebruijnIndex { depth: depth }
1155 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
1156 DebruijnIndex { depth: self.depth + amount }
1160 /// Region utilities
1162 pub fn is_late_bound(&self) -> bool {
1164 ty::ReLateBound(..) => true,
1169 pub fn needs_infer(&self) -> bool {
1171 ty::ReVar(..) | ty::ReSkolemized(..) => true,
1176 pub fn escapes_depth(&self, depth: u32) -> bool {
1178 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1183 /// Returns the depth of `self` from the (1-based) binding level `depth`
1184 pub fn from_depth(&self, depth: u32) -> RegionKind {
1186 ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
1187 depth: debruijn.depth - (depth - 1)
1193 pub fn type_flags(&self) -> TypeFlags {
1194 let mut flags = TypeFlags::empty();
1198 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1199 flags = flags | TypeFlags::HAS_RE_INFER;
1200 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1202 ty::ReSkolemized(..) => {
1203 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1204 flags = flags | TypeFlags::HAS_RE_INFER;
1205 flags = flags | TypeFlags::HAS_RE_SKOL;
1206 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1208 ty::ReLateBound(..) => { }
1209 ty::ReEarlyBound(..) => {
1210 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1211 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1216 ty::ReScope { .. } => {
1217 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1221 ty::ReCanonical(..) => {
1222 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1223 flags = flags | TypeFlags::HAS_CANONICAL_VARS;
1225 ty::ReClosureBound(..) => {
1226 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1231 ty::ReStatic | ty::ReEmpty | ty::ReErased => (),
1232 _ => flags = flags | TypeFlags::HAS_LOCAL_NAMES,
1235 debug!("type_flags({:?}) = {:?}", self, flags);
1240 /// Given an early-bound or free region, returns the def-id where it was bound.
1241 /// For example, consider the regions in this snippet of code:
1245 /// ^^ -- early bound, declared on an impl
1247 /// fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1248 /// ^^ ^^ ^ anonymous, late-bound
1249 /// | early-bound, appears in where-clauses
1250 /// late-bound, appears only in fn args
1255 /// Here, `free_region_binding_scope('a)` would return the def-id
1256 /// of the impl, and for all the other highlighted regions, it
1257 /// would return the def-id of the function. In other cases (not shown), this
1258 /// function might return the def-id of a closure.
1259 pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_, '_, '_>) -> DefId {
1261 ty::ReEarlyBound(br) => {
1262 tcx.parent_def_id(br.def_id).unwrap()
1264 ty::ReFree(fr) => fr.scope,
1265 _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1271 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
1272 pub fn is_nil(&self) -> bool {
1274 TyTuple(ref tys) => tys.is_empty(),
1279 pub fn is_never(&self) -> bool {
1286 pub fn is_primitive(&self) -> bool {
1288 TyBool | TyChar | TyInt(_) | TyUint(_) | TyFloat(_) => true,
1293 pub fn is_ty_var(&self) -> bool {
1295 TyInfer(TyVar(_)) => true,
1300 pub fn is_ty_infer(&self) -> bool {
1307 pub fn is_phantom_data(&self) -> bool {
1308 if let TyAdt(def, _) = self.sty {
1309 def.is_phantom_data()
1315 pub fn is_bool(&self) -> bool { self.sty == TyBool }
1317 pub fn is_param(&self, index: u32) -> bool {
1319 ty::TyParam(ref data) => data.idx == index,
1324 pub fn is_self(&self) -> bool {
1326 TyParam(ref p) => p.is_self(),
1331 pub fn is_slice(&self) -> bool {
1333 TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
1334 TySlice(_) | TyStr => true,
1342 pub fn is_simd(&self) -> bool {
1344 TyAdt(def, _) => def.repr.simd(),
1349 pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1351 TyArray(ty, _) | TySlice(ty) => ty,
1352 TyStr => tcx.mk_mach_uint(ast::UintTy::U8),
1353 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1357 pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1359 TyAdt(def, substs) => {
1360 def.non_enum_variant().fields[0].ty(tcx, substs)
1362 _ => bug!("simd_type called on invalid type")
1366 pub fn simd_size(&self, _cx: TyCtxt) -> usize {
1368 TyAdt(def, _) => def.non_enum_variant().fields.len(),
1369 _ => bug!("simd_size called on invalid type")
1373 pub fn is_region_ptr(&self) -> bool {
1380 pub fn is_mutable_pointer(&self) -> bool {
1382 TyRawPtr(tnm) | TyRef(_, tnm) => if let hir::Mutability::MutMutable = tnm.mutbl {
1391 pub fn is_unsafe_ptr(&self) -> bool {
1393 TyRawPtr(_) => return true,
1398 pub fn is_box(&self) -> bool {
1400 TyAdt(def, _) => def.is_box(),
1405 /// panics if called on any type other than `Box<T>`
1406 pub fn boxed_ty(&self) -> Ty<'tcx> {
1408 TyAdt(def, substs) if def.is_box() => substs.type_at(0),
1409 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1413 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1414 /// (A TyRawPtr is scalar because it represents a non-managed pointer, so its
1415 /// contents are abstract to rustc.)
1416 pub fn is_scalar(&self) -> bool {
1418 TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
1419 TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
1420 TyFnDef(..) | TyFnPtr(_) | TyRawPtr(_) => true,
1425 /// Returns true if this type is a floating point type and false otherwise.
1426 pub fn is_floating_point(&self) -> bool {
1429 TyInfer(FloatVar(_)) => true,
1434 pub fn is_trait(&self) -> bool {
1436 TyDynamic(..) => true,
1441 pub fn is_enum(&self) -> bool {
1443 TyAdt(adt_def, _) => {
1450 pub fn is_closure(&self) -> bool {
1452 TyClosure(..) => true,
1457 pub fn is_generator(&self) -> bool {
1459 TyGenerator(..) => true,
1464 pub fn is_integral(&self) -> bool {
1466 TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
1471 pub fn is_fresh_ty(&self) -> bool {
1473 TyInfer(FreshTy(_)) => true,
1478 pub fn is_fresh(&self) -> bool {
1480 TyInfer(FreshTy(_)) => true,
1481 TyInfer(FreshIntTy(_)) => true,
1482 TyInfer(FreshFloatTy(_)) => true,
1487 pub fn is_char(&self) -> bool {
1494 pub fn is_fp(&self) -> bool {
1496 TyInfer(FloatVar(_)) | TyFloat(_) => true,
1501 pub fn is_numeric(&self) -> bool {
1502 self.is_integral() || self.is_fp()
1505 pub fn is_signed(&self) -> bool {
1512 pub fn is_machine(&self) -> bool {
1514 TyInt(ast::IntTy::Isize) | TyUint(ast::UintTy::Usize) => false,
1515 TyInt(..) | TyUint(..) | TyFloat(..) => true,
1520 pub fn has_concrete_skeleton(&self) -> bool {
1522 TyParam(_) | TyInfer(_) | TyError => false,
1527 /// Returns the type and mutability of *ty.
1529 /// The parameter `explicit` indicates if this is an *explicit* dereference.
1530 /// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1531 pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1533 TyAdt(def, _) if def.is_box() => {
1535 ty: self.boxed_ty(),
1536 mutbl: hir::MutImmutable,
1539 TyRef(_, mt) => Some(mt),
1540 TyRawPtr(mt) if explicit => Some(mt),
1545 /// Returns the type of ty[i]
1546 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1548 TyArray(ty, _) | TySlice(ty) => Some(ty),
1553 pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1555 TyFnDef(def_id, substs) => {
1556 tcx.fn_sig(def_id).subst(tcx, substs)
1559 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1563 pub fn is_fn(&self) -> bool {
1565 TyFnDef(..) | TyFnPtr(_) => true,
1570 pub fn ty_to_def_id(&self) -> Option<DefId> {
1572 TyDynamic(ref tt, ..) => tt.principal().map(|p| p.def_id()),
1573 TyAdt(def, _) => Some(def.did),
1574 TyForeign(did) => Some(did),
1575 TyClosure(id, _) => Some(id),
1576 TyFnDef(id, _) => Some(id),
1581 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1583 TyAdt(adt, _) => Some(adt),
1588 /// Returns the regions directly referenced from this type (but
1589 /// not types reachable from this type via `walk_tys`). This
1590 /// ignores late-bound regions binders.
1591 pub fn regions(&self) -> Vec<ty::Region<'tcx>> {
1593 TyRef(region, _) => {
1596 TyDynamic(ref obj, region) => {
1597 let mut v = vec![region];
1598 if let Some(p) = obj.principal() {
1599 v.extend(p.skip_binder().substs.regions());
1603 TyAdt(_, substs) | TyAnon(_, substs) => {
1604 substs.regions().collect()
1606 TyClosure(_, ref substs) | TyGenerator(_, ref substs, _) => {
1607 substs.substs.regions().collect()
1609 TyProjection(ref data) => {
1610 data.substs.regions().collect()
1614 TyGeneratorWitness(..) |
1635 /// When we create a closure, we record its kind (i.e., what trait
1636 /// it implements) into its `ClosureSubsts` using a type
1637 /// parameter. This is kind of a phantom type, except that the
1638 /// most convenient thing for us to are the integral types. This
1639 /// function converts such a special type into the closure
1640 /// kind. To go the other way, use
1641 /// `tcx.closure_kind_ty(closure_kind)`.
1643 /// Note that during type checking, we use an inference variable
1644 /// to represent the closure kind, because it has not yet been
1645 /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
1646 /// is complete, that type variable will be unified.
1647 pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
1649 TyInt(int_ty) => match int_ty {
1650 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
1651 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1652 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1653 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1658 TyError => Some(ty::ClosureKind::Fn),
1660 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1665 /// Typed constant value.
1666 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Eq, PartialEq)]
1667 pub struct Const<'tcx> {
1670 // FIXME(eddyb) Replace this with a miri value.
1671 pub val: ConstVal<'tcx>,
1674 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}