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};
21 use util::captures::Captures;
24 use std::cmp::Ordering;
25 use rustc_target::spec::abi;
26 use syntax::ast::{self, Name};
27 use syntax::symbol::{keywords, InternedString};
34 use self::TypeVariants::*;
36 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
37 pub struct TypeAndMut<'tcx> {
39 pub mutbl: hir::Mutability,
42 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
43 RustcEncodable, RustcDecodable, Copy)]
44 /// A "free" region `fr` can be interpreted as "some region
45 /// at least as big as the scope `fr.scope`".
46 pub struct FreeRegion {
48 pub bound_region: BoundRegion,
51 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
52 RustcEncodable, RustcDecodable, Copy)]
53 pub enum BoundRegion {
54 /// An anonymous region parameter for a given fn (&T)
57 /// Named region parameters for functions (a in &'a T)
59 /// The def-id is needed to distinguish free regions in
60 /// the event of shadowing.
61 BrNamed(DefId, InternedString),
63 /// Fresh bound identifiers created during GLB computations.
66 /// Anonymous region for the implicit env pointer parameter
72 pub fn is_named(&self) -> bool {
74 BoundRegion::BrNamed(..) => true,
80 /// NB: If you change this, you'll probably want to change the corresponding
81 /// AST structure in libsyntax/ast.rs as well.
82 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
83 pub enum TypeVariants<'tcx> {
84 /// The primitive boolean type. Written as `bool`.
87 /// The primitive character type; holds a Unicode scalar value
88 /// (a non-surrogate code point). Written as `char`.
91 /// A primitive signed integer type. For example, `i32`.
94 /// A primitive unsigned integer type. For example, `u32`.
97 /// A primitive floating-point type. For example, `f64`.
98 TyFloat(ast::FloatTy),
100 /// Structures, enumerations and unions.
102 /// Substs here, possibly against intuition, *may* contain `TyParam`s.
103 /// That is, even after substitution it is possible that there are type
104 /// variables. This happens when the `TyAdt` corresponds to an ADT
105 /// definition and not a concrete use of it.
106 TyAdt(&'tcx AdtDef, &'tcx Substs<'tcx>),
110 /// The pointee of a string slice. Written as `str`.
113 /// An array with the given length. Written as `[T; n]`.
114 TyArray(Ty<'tcx>, &'tcx ty::Const<'tcx>),
116 /// The pointee of an array slice. Written as `[T]`.
119 /// A raw pointer. Written as `*mut T` or `*const T`
120 TyRawPtr(TypeAndMut<'tcx>),
122 /// A reference; a pointer with an associated lifetime. Written as
123 /// `&'a mut T` or `&'a T`.
124 TyRef(Region<'tcx>, TypeAndMut<'tcx>),
126 /// The anonymous type of a function declaration/definition. Each
127 /// function has a unique type.
128 TyFnDef(DefId, &'tcx Substs<'tcx>),
130 /// A pointer to a function. Written as `fn() -> i32`.
131 TyFnPtr(PolyFnSig<'tcx>),
133 /// A trait, defined with `trait`.
134 TyDynamic(Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
136 /// The anonymous type of a closure. Used to represent the type of
138 TyClosure(DefId, ClosureSubsts<'tcx>),
140 /// The anonymous type of a generator. Used to represent the type of
142 TyGenerator(DefId, ClosureSubsts<'tcx>, GeneratorInterior<'tcx>),
144 /// A type representin the types stored inside a generator.
145 /// This should only appear in GeneratorInteriors.
146 TyGeneratorWitness(Binder<&'tcx Slice<Ty<'tcx>>>),
148 /// The never type `!`
151 /// A tuple type. For example, `(i32, bool)`.
152 TyTuple(&'tcx Slice<Ty<'tcx>>),
154 /// The projection of an associated type. For example,
155 /// `<T as Trait<..>>::N`.
156 TyProjection(ProjectionTy<'tcx>),
158 /// Anonymized (`impl Trait`) type found in a return type.
159 /// The DefId comes from the `impl Trait` ast::Ty node, and the
160 /// substitutions are for the generics of the function in question.
161 /// After typeck, the concrete type can be found in the `types` map.
162 TyAnon(DefId, &'tcx Substs<'tcx>),
164 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
167 /// A type variable used during type-checking.
170 /// A placeholder for a type which could not be computed; this is
171 /// propagated to avoid useless error messages.
175 /// A closure can be modeled as a struct that looks like:
177 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
185 /// - 'l0...'li and T0...Tj are the lifetime and type parameters
186 /// in scope on the function that defined the closure,
187 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
188 /// is rather hackily encoded via a scalar type. See
189 /// `TyS::to_opt_closure_kind` for details.
190 /// - CS represents the *closure signature*, representing as a `fn()`
191 /// type. For example, `fn(u32, u32) -> u32` would mean that the closure
192 /// implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
194 /// - U0...Uk are type parameters representing the types of its upvars
195 /// (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
196 /// and the up-var has the type `Foo`, then `Ui = &Foo`).
198 /// So, for example, given this function:
200 /// fn foo<'a, T>(data: &'a mut T) {
201 /// do(|| data.count += 1)
204 /// the type of the closure would be something like:
206 /// struct Closure<'a, T, U0> {
210 /// Note that the type of the upvar is not specified in the struct.
211 /// You may wonder how the impl would then be able to use the upvar,
212 /// if it doesn't know it's type? The answer is that the impl is
213 /// (conceptually) not fully generic over Closure but rather tied to
214 /// instances with the expected upvar types:
216 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
220 /// You can see that the *impl* fully specified the type of the upvar
221 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
222 /// (Here, I am assuming that `data` is mut-borrowed.)
224 /// Now, the last question you may ask is: Why include the upvar types
225 /// as extra type parameters? The reason for this design is that the
226 /// upvar types can reference lifetimes that are internal to the
227 /// creating function. In my example above, for example, the lifetime
228 /// `'b` represents the scope of the closure itself; this is some
229 /// subset of `foo`, probably just the scope of the call to the to
230 /// `do()`. If we just had the lifetime/type parameters from the
231 /// enclosing function, we couldn't name this lifetime `'b`. Note that
232 /// there can also be lifetimes in the types of the upvars themselves,
233 /// if one of them happens to be a reference to something that the
234 /// creating fn owns.
236 /// OK, you say, so why not create a more minimal set of parameters
237 /// that just includes the extra lifetime parameters? The answer is
238 /// primarily that it would be hard --- we don't know at the time when
239 /// we create the closure type what the full types of the upvars are,
240 /// nor do we know which are borrowed and which are not. In this
241 /// design, we can just supply a fresh type parameter and figure that
244 /// All right, you say, but why include the type parameters from the
245 /// original function then? The answer is that trans may need them
246 /// when monomorphizing, and they may not appear in the upvars. A
247 /// closure could capture no variables but still make use of some
248 /// in-scope type parameter with a bound (e.g., if our example above
249 /// had an extra `U: Default`, and the closure called `U::default()`).
251 /// There is another reason. This design (implicitly) prohibits
252 /// closures from capturing themselves (except via a trait
253 /// object). This simplifies closure inference considerably, since it
254 /// means that when we infer the kind of a closure or its upvars, we
255 /// don't have to handle cycles where the decisions we make for
256 /// closure C wind up influencing the decisions we ought to make for
257 /// closure C (which would then require fixed point iteration to
258 /// handle). Plus it fixes an ICE. :P
262 /// Perhaps surprisingly, `ClosureSubsts` are also used for
263 /// generators. In that case, what is written above is only half-true
264 /// -- the set of type parameters is similar, but the role of CK and
265 /// CS are different. CK represents the "yield type" and CS
266 /// represents the "return type" of the generator.
268 /// It'd be nice to split this struct into ClosureSubsts and
269 /// GeneratorSubsts, I believe. -nmatsakis
270 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
271 pub struct ClosureSubsts<'tcx> {
272 /// Lifetime and type parameters from the enclosing function,
273 /// concatenated with the types of the upvars.
275 /// These are separated out because trans wants to pass them around
276 /// when monomorphizing.
277 pub substs: &'tcx Substs<'tcx>,
280 /// Struct returned by `split()`. Note that these are subslices of the
281 /// parent slice and not canonical substs themselves.
282 struct SplitClosureSubsts<'tcx> {
283 closure_kind_ty: Ty<'tcx>,
284 closure_sig_ty: Ty<'tcx>,
285 upvar_kinds: &'tcx [Kind<'tcx>],
288 impl<'tcx> ClosureSubsts<'tcx> {
289 /// Divides the closure substs into their respective
290 /// components. Single source of truth with respect to the
292 fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitClosureSubsts<'tcx> {
293 let generics = tcx.generics_of(def_id);
294 let parent_len = generics.parent_count();
296 closure_kind_ty: self.substs.type_at(parent_len),
297 closure_sig_ty: self.substs.type_at(parent_len + 1),
298 upvar_kinds: &self.substs[parent_len + 2..],
303 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
304 impl Iterator<Item=Ty<'tcx>> + 'tcx
306 let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
307 upvar_kinds.iter().map(|t| {
308 if let UnpackedKind::Type(ty) = t.unpack() {
311 bug!("upvar should be type")
316 /// Returns the closure kind for this closure; may return a type
317 /// variable during inference. To get the closure kind during
318 /// inference, use `infcx.closure_kind(def_id, substs)`.
319 pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
320 self.split(def_id, tcx).closure_kind_ty
323 /// Returns the type representing the closure signature for this
324 /// closure; may contain type variables during inference. To get
325 /// the closure signature during inference, use
326 /// `infcx.fn_sig(def_id)`.
327 pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
328 self.split(def_id, tcx).closure_sig_ty
331 /// Returns the type representing the yield type of the generator.
332 pub fn generator_yield_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
333 self.closure_kind_ty(def_id, tcx)
336 /// Returns the type representing the return type of the generator.
337 pub fn generator_return_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
338 self.closure_sig_ty(def_id, tcx)
341 /// Return the "generator signature", which consists of its yield
342 /// and return types.
344 /// NB. Some bits of the code prefers to see this wrapped in a
345 /// binder, but it never contains bound regions. Probably this
346 /// function should be removed.
347 pub fn generator_poly_sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> PolyGenSig<'tcx> {
348 ty::Binder::dummy(self.generator_sig(def_id, tcx))
351 /// Return the "generator signature", which consists of its yield
352 /// and return types.
353 pub fn generator_sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> GenSig<'tcx> {
355 yield_ty: self.generator_yield_ty(def_id, tcx),
356 return_ty: self.generator_return_ty(def_id, tcx),
361 impl<'tcx> ClosureSubsts<'tcx> {
362 /// Returns the closure kind for this closure; only usable outside
363 /// of an inference context, because in that context we know that
364 /// there are no type variables.
366 /// If you have an inference context, use `infcx.closure_kind()`.
367 pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::ClosureKind {
368 self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
371 /// Extracts the signature from the closure; only usable outside
372 /// of an inference context, because in that context we know that
373 /// there are no type variables.
375 /// If you have an inference context, use `infcx.closure_sig()`.
376 pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::PolyFnSig<'tcx> {
377 match self.closure_sig_ty(def_id, tcx).sty {
378 ty::TyFnPtr(sig) => sig,
379 ref t => bug!("closure_sig_ty is not a fn-ptr: {:?}", t),
384 impl<'a, 'gcx, 'tcx> ClosureSubsts<'tcx> {
385 /// This returns the types of the MIR locals which had to be stored across suspension points.
386 /// It is calculated in rustc_mir::transform::generator::StateTransform.
387 /// All the types here must be in the tuple in GeneratorInterior.
391 tcx: TyCtxt<'a, 'gcx, 'tcx>,
392 ) -> impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a {
393 let state = tcx.generator_layout(def_id).fields.iter();
394 state.map(move |d| d.ty.subst(tcx, self.substs))
397 /// This is the types of the fields of a generate which
398 /// is available before the generator transformation.
399 /// It includes the upvars and the state discriminant which is u32.
400 pub fn pre_transforms_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
401 impl Iterator<Item=Ty<'tcx>> + 'a
403 self.upvar_tys(def_id, tcx).chain(iter::once(tcx.types.u32))
406 /// This is the types of all the fields stored in a generator.
407 /// It includes the upvars, state types and the state discriminant which is u32.
408 pub fn field_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
409 impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a
411 self.pre_transforms_tys(def_id, tcx).chain(self.state_tys(def_id, tcx))
415 /// This describes the types that can be contained in a generator.
416 /// It will be a type variable initially and unified in the last stages of typeck of a body.
417 /// It contains a tuple of all the types that could end up on a generator frame.
418 /// The state transformation MIR pass may only produce layouts which mention types in this tuple.
419 /// Upvars are not counted here.
420 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
421 pub struct GeneratorInterior<'tcx> {
422 pub witness: Ty<'tcx>,
426 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
427 pub enum ExistentialPredicate<'tcx> {
429 Trait(ExistentialTraitRef<'tcx>),
430 /// e.g. Iterator::Item = T
431 Projection(ExistentialProjection<'tcx>),
436 impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
437 pub fn cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
438 use self::ExistentialPredicate::*;
439 match (*self, *other) {
440 (Trait(_), Trait(_)) => Ordering::Equal,
441 (Projection(ref a), Projection(ref b)) =>
442 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
443 (AutoTrait(ref a), AutoTrait(ref b)) =>
444 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
445 (Trait(_), _) => Ordering::Less,
446 (Projection(_), Trait(_)) => Ordering::Greater,
447 (Projection(_), _) => Ordering::Less,
448 (AutoTrait(_), _) => Ordering::Greater,
454 impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
455 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
456 -> ty::Predicate<'tcx> {
458 match *self.skip_binder() {
459 ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
460 ExistentialPredicate::Projection(p) =>
461 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
462 ExistentialPredicate::AutoTrait(did) => {
463 let trait_ref = Binder(ty::TraitRef {
465 substs: tcx.mk_substs_trait(self_ty, &[]),
467 trait_ref.to_predicate()
473 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<ExistentialPredicate<'tcx>> {}
475 impl<'tcx> Slice<ExistentialPredicate<'tcx>> {
476 pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
478 Some(&ExistentialPredicate::Trait(tr)) => Some(tr),
484 pub fn projection_bounds<'a>(&'a self) ->
485 impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
486 self.iter().filter_map(|predicate| {
488 ExistentialPredicate::Projection(p) => Some(p),
495 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
496 self.iter().filter_map(|predicate| {
498 ExistentialPredicate::AutoTrait(d) => Some(d),
505 impl<'tcx> Binder<&'tcx Slice<ExistentialPredicate<'tcx>>> {
506 pub fn principal(&self) -> Option<PolyExistentialTraitRef<'tcx>> {
507 self.skip_binder().principal().map(Binder::bind)
511 pub fn projection_bounds<'a>(&'a self) ->
512 impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
513 self.skip_binder().projection_bounds().map(Binder::bind)
517 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
518 self.skip_binder().auto_traits()
521 pub fn iter<'a>(&'a self)
522 -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
523 self.skip_binder().iter().cloned().map(Binder::bind)
527 /// A complete reference to a trait. These take numerous guises in syntax,
528 /// but perhaps the most recognizable form is in a where clause:
532 /// This would be represented by a trait-reference where the def-id is the
533 /// def-id for the trait `Foo` and the substs define `T` as parameter 0,
534 /// and `U` as parameter 1.
536 /// Trait references also appear in object types like `Foo<U>`, but in
537 /// that case the `Self` parameter is absent from the substitutions.
539 /// Note that a `TraitRef` introduces a level of region binding, to
540 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
541 /// U>` or higher-ranked object types.
542 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
543 pub struct TraitRef<'tcx> {
545 pub substs: &'tcx Substs<'tcx>,
548 impl<'tcx> TraitRef<'tcx> {
549 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
550 TraitRef { def_id: def_id, substs: substs }
553 pub fn self_ty(&self) -> Ty<'tcx> {
554 self.substs.type_at(0)
557 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
558 // Select only the "input types" from a trait-reference. For
559 // now this is all the types that appear in the
560 // trait-reference, but it should eventually exclude
566 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
568 impl<'tcx> PolyTraitRef<'tcx> {
569 pub fn self_ty(&self) -> Ty<'tcx> {
570 self.skip_binder().self_ty()
573 pub fn def_id(&self) -> DefId {
574 self.skip_binder().def_id
577 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
578 // Note that we preserve binding levels
579 Binder(ty::TraitPredicate { trait_ref: self.skip_binder().clone() })
583 /// An existential reference to a trait, where `Self` is erased.
584 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
586 /// exists T. T: Trait<'a, 'b, X, Y>
588 /// The substitutions don't include the erased `Self`, only trait
589 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
590 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
591 pub struct ExistentialTraitRef<'tcx> {
593 pub substs: &'tcx Substs<'tcx>,
596 impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
597 pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
598 // Select only the "input types" from a trait-reference. For
599 // now this is all the types that appear in the
600 // trait-reference, but it should eventually exclude
605 /// Object types don't have a self-type specified. Therefore, when
606 /// we convert the principal trait-ref into a normal trait-ref,
607 /// you must give *some* self-type. A common choice is `mk_err()`
608 /// or some skolemized type.
609 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
610 -> ty::TraitRef<'tcx> {
611 // otherwise the escaping regions would be captured by the binder
612 assert!(!self_ty.has_escaping_regions());
616 substs: tcx.mk_substs(
617 iter::once(self_ty.into()).chain(self.substs.iter().cloned()))
622 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
624 impl<'tcx> PolyExistentialTraitRef<'tcx> {
625 pub fn def_id(&self) -> DefId {
626 self.skip_binder().def_id
630 /// Binder is a binder for higher-ranked lifetimes. It is part of the
631 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
632 /// (which would be represented by the type `PolyTraitRef ==
633 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
634 /// erase, or otherwise "discharge" these bound regions, we change the
635 /// type from `Binder<T>` to just `T` (see
636 /// e.g. `liberate_late_bound_regions`).
637 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
638 pub struct Binder<T>(T);
641 /// Wraps `value` in a binder, asserting that `value` does not
642 /// contain any bound regions that would be bound by the
643 /// binder. This is commonly used to 'inject' a value T into a
644 /// different binding level.
645 pub fn dummy<'tcx>(value: T) -> Binder<T>
646 where T: TypeFoldable<'tcx>
648 assert!(!value.has_escaping_regions());
652 /// Wraps `value` in a binder, binding late-bound regions (if any).
653 pub fn bind<'tcx>(value: T) -> Binder<T>
658 /// Skips the binder and returns the "bound" value. This is a
659 /// risky thing to do because it's easy to get confused about
660 /// debruijn indices and the like. It is usually better to
661 /// discharge the binder using `no_late_bound_regions` or
662 /// `replace_late_bound_regions` or something like
663 /// that. `skip_binder` is only valid when you are either
664 /// extracting data that has nothing to do with bound regions, you
665 /// are doing some sort of test that does not involve bound
666 /// regions, or you are being very careful about your depth
669 /// Some examples where `skip_binder` is reasonable:
671 /// - extracting the def-id from a PolyTraitRef;
672 /// - comparing the self type of a PolyTraitRef to see if it is equal to
673 /// a type parameter `X`, since the type `X` does not reference any regions
674 pub fn skip_binder(&self) -> &T {
678 pub fn as_ref(&self) -> Binder<&T> {
682 pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
683 where F: FnOnce(&T) -> U
685 self.as_ref().map_bound(f)
688 pub fn map_bound<F, U>(self, f: F) -> Binder<U>
689 where F: FnOnce(T) -> U
694 /// Unwraps and returns the value within, but only if it contains
695 /// no bound regions at all. (In other words, if this binder --
696 /// and indeed any enclosing binder -- doesn't bind anything at
697 /// all.) Otherwise, returns `None`.
699 /// (One could imagine having a method that just unwraps a single
700 /// binder, but permits late-bound regions bound by enclosing
701 /// binders, but that would require adjusting the debruijn
702 /// indices, and given the shallow binding structure we often use,
703 /// would not be that useful.)
704 pub fn no_late_bound_regions<'tcx>(self) -> Option<T>
705 where T : TypeFoldable<'tcx>
707 if self.skip_binder().has_escaping_regions() {
710 Some(self.skip_binder().clone())
714 /// Given two things that have the same binder level,
715 /// and an operation that wraps on their contents, execute the operation
716 /// and then wrap its result.
718 /// `f` should consider bound regions at depth 1 to be free, and
719 /// anything it produces with bound regions at depth 1 will be
720 /// bound in the resulting return value.
721 pub fn fuse<U,F,R>(self, u: Binder<U>, f: F) -> Binder<R>
722 where F: FnOnce(T, U) -> R
724 Binder(f(self.0, u.0))
727 /// Split the contents into two things that share the same binder
728 /// level as the original, returning two distinct binders.
730 /// `f` should consider bound regions at depth 1 to be free, and
731 /// anything it produces with bound regions at depth 1 will be
732 /// bound in the resulting return values.
733 pub fn split<U,V,F>(self, f: F) -> (Binder<U>, Binder<V>)
734 where F: FnOnce(T) -> (U, V)
736 let (u, v) = f(self.0);
737 (Binder(u), Binder(v))
741 /// Represents the projection of an associated type. In explicit UFCS
742 /// form this would be written `<T as Trait<..>>::N`.
743 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
744 pub struct ProjectionTy<'tcx> {
745 /// The parameters of the associated item.
746 pub substs: &'tcx Substs<'tcx>,
748 /// The DefId of the TraitItem for the associated type N.
750 /// Note that this is not the DefId of the TraitRef containing this
751 /// associated type, which is in tcx.associated_item(item_def_id).container.
752 pub item_def_id: DefId,
755 impl<'a, 'tcx> ProjectionTy<'tcx> {
756 /// Construct a ProjectionTy by searching the trait from trait_ref for the
757 /// associated item named item_name.
758 pub fn from_ref_and_name(
759 tcx: TyCtxt, trait_ref: ty::TraitRef<'tcx>, item_name: Name
760 ) -> ProjectionTy<'tcx> {
761 let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
762 item.kind == ty::AssociatedKind::Type &&
763 tcx.hygienic_eq(item_name, item.name, trait_ref.def_id)
767 substs: trait_ref.substs,
772 /// Extracts the underlying trait reference from this projection.
773 /// For example, if this is a projection of `<T as Iterator>::Item`,
774 /// then this function would return a `T: Iterator` trait reference.
775 pub fn trait_ref(&self, tcx: TyCtxt) -> ty::TraitRef<'tcx> {
776 let def_id = tcx.associated_item(self.item_def_id).container.id();
783 pub fn self_ty(&self) -> Ty<'tcx> {
784 self.substs.type_at(0)
788 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
789 pub struct GenSig<'tcx> {
790 pub yield_ty: Ty<'tcx>,
791 pub return_ty: Ty<'tcx>,
794 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
796 impl<'tcx> PolyGenSig<'tcx> {
797 pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
798 self.map_bound_ref(|sig| sig.yield_ty)
800 pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
801 self.map_bound_ref(|sig| sig.return_ty)
805 /// Signature of a function type, which I have arbitrarily
806 /// decided to use to refer to the input/output types.
808 /// - `inputs` is the list of arguments and their modes.
809 /// - `output` is the return type.
810 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
811 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
812 pub struct FnSig<'tcx> {
813 pub inputs_and_output: &'tcx Slice<Ty<'tcx>>,
815 pub unsafety: hir::Unsafety,
819 impl<'tcx> FnSig<'tcx> {
820 pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
821 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
824 pub fn output(&self) -> Ty<'tcx> {
825 self.inputs_and_output[self.inputs_and_output.len() - 1]
829 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
831 impl<'tcx> PolyFnSig<'tcx> {
832 pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
833 self.map_bound_ref(|fn_sig| fn_sig.inputs())
835 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
836 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
838 pub fn inputs_and_output(&self) -> ty::Binder<&'tcx Slice<Ty<'tcx>>> {
839 self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
841 pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
842 self.map_bound_ref(|fn_sig| fn_sig.output().clone())
844 pub fn variadic(&self) -> bool {
845 self.skip_binder().variadic
847 pub fn unsafety(&self) -> hir::Unsafety {
848 self.skip_binder().unsafety
850 pub fn abi(&self) -> abi::Abi {
851 self.skip_binder().abi
855 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
858 pub name: InternedString,
861 impl<'a, 'gcx, 'tcx> ParamTy {
862 pub fn new(index: u32, name: InternedString) -> ParamTy {
863 ParamTy { idx: index, name: name }
866 pub fn for_self() -> ParamTy {
867 ParamTy::new(0, keywords::SelfType.name().as_str())
870 pub fn for_def(def: &ty::TypeParameterDef) -> ParamTy {
871 ParamTy::new(def.index, def.name)
874 pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
875 tcx.mk_param(self.idx, self.name)
878 pub fn is_self(&self) -> bool {
879 if self.name == keywords::SelfType.name().as_str() {
880 assert_eq!(self.idx, 0);
888 /// A [De Bruijn index][dbi] is a standard means of representing
889 /// regions (and perhaps later types) in a higher-ranked setting. In
890 /// particular, imagine a type like this:
892 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
895 /// | +------------+ 1 | |
897 /// +--------------------------------+ 2 |
899 /// +------------------------------------------+ 1
901 /// In this type, there are two binders (the outer fn and the inner
902 /// fn). We need to be able to determine, for any given region, which
903 /// fn type it is bound by, the inner or the outer one. There are
904 /// various ways you can do this, but a De Bruijn index is one of the
905 /// more convenient and has some nice properties. The basic idea is to
906 /// count the number of binders, inside out. Some examples should help
907 /// clarify what I mean.
909 /// Let's start with the reference type `&'b isize` that is the first
910 /// argument to the inner function. This region `'b` is assigned a De
911 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
912 /// fn). The region `'a` that appears in the second argument type (`&'a
913 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
914 /// second-innermost binder". (These indices are written on the arrays
917 /// What is interesting is that De Bruijn index attached to a particular
918 /// variable will vary depending on where it appears. For example,
919 /// the final type `&'a char` also refers to the region `'a` declared on
920 /// the outermost fn. But this time, this reference is not nested within
921 /// any other binders (i.e., it is not an argument to the inner fn, but
922 /// rather the outer one). Therefore, in this case, it is assigned a
923 /// De Bruijn index of 1, because the innermost binder in that location
926 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
927 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy, PartialOrd, Ord)]
928 pub struct DebruijnIndex {
929 /// We maintain the invariant that this is never 0. So 1 indicates
930 /// the innermost binder. To ensure this, create with `DebruijnIndex::new`.
934 pub type Region<'tcx> = &'tcx RegionKind;
936 /// Representation of regions.
938 /// Unlike types, most region variants are "fictitious", not concrete,
939 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
940 /// ones representing concrete regions.
944 /// These are regions that are stored behind a binder and must be substituted
945 /// with some concrete region before being used. There are 2 kind of
946 /// bound regions: early-bound, which are bound in an item's Generics,
947 /// and are substituted by a Substs, and late-bound, which are part of
948 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
949 /// the likes of `liberate_late_bound_regions`. The distinction exists
950 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
952 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
953 /// outside their binder, e.g. in types passed to type inference, and
954 /// should first be substituted (by skolemized regions, free regions,
955 /// or region variables).
957 /// ## Skolemized and Free Regions
959 /// One often wants to work with bound regions without knowing their precise
960 /// identity. For example, when checking a function, the lifetime of a borrow
961 /// can end up being assigned to some region parameter. In these cases,
962 /// it must be ensured that bounds on the region can't be accidentally
963 /// assumed without being checked.
965 /// The process of doing that is called "skolemization". The bound regions
966 /// are replaced by skolemized markers, which don't satisfy any relation
967 /// not explicitly provided.
969 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
970 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
971 /// to be used. These also support explicit bounds: both the internally-stored
972 /// *scope*, which the region is assumed to outlive, as well as other
973 /// relations stored in the `FreeRegionMap`. Note that these relations
974 /// aren't checked when you `make_subregion` (or `eq_types`), only by
975 /// `resolve_regions_and_report_errors`.
977 /// When working with higher-ranked types, some region relations aren't
978 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
979 /// `ReSkolemized` is designed for this purpose. In these contexts,
980 /// there's also the risk that some inference variable laying around will
981 /// get unified with your skolemized region: if you want to check whether
982 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
983 /// with a skolemized region `'%a`, the variable `'_` would just be
984 /// instantiated to the skolemized region `'%a`, which is wrong because
985 /// the inference variable is supposed to satisfy the relation
986 /// *for every value of the skolemized region*. To ensure that doesn't
987 /// happen, you can use `leak_check`. This is more clearly explained
988 /// by the [rustc guide].
990 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
991 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
992 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/trait-hrtb.html
993 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
994 pub enum RegionKind {
995 // Region bound in a type or fn declaration which will be
996 // substituted 'early' -- that is, at the same time when type
997 // parameters are substituted.
998 ReEarlyBound(EarlyBoundRegion),
1000 // Region bound in a function scope, which will be substituted when the
1001 // function is called.
1002 ReLateBound(DebruijnIndex, BoundRegion),
1004 /// When checking a function body, the types of all arguments and so forth
1005 /// that refer to bound region parameters are modified to refer to free
1006 /// region parameters.
1009 /// A concrete region naming some statically determined scope
1010 /// (e.g. an expression or sequence of statements) within the
1011 /// current function.
1012 ReScope(region::Scope),
1014 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1017 /// A region variable. Should not exist after typeck.
1020 /// A skolemized region - basically the higher-ranked version of ReFree.
1021 /// Should not exist after typeck.
1022 ReSkolemized(SkolemizedRegionVid, BoundRegion),
1024 /// Empty lifetime is for data that is never accessed.
1025 /// Bottom in the region lattice. We treat ReEmpty somewhat
1026 /// specially; at least right now, we do not generate instances of
1027 /// it during the GLB computations, but rather
1028 /// generate an error instead. This is to improve error messages.
1029 /// The only way to get an instance of ReEmpty is to have a region
1030 /// variable with no constraints.
1033 /// Erased region, used by trait selection, in MIR and during trans.
1036 /// These are regions bound in the "defining type" for a
1037 /// closure. They are used ONLY as part of the
1038 /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1039 /// See `ClosureRegionRequirements` for more details.
1040 ReClosureBound(RegionVid),
1042 /// Canonicalized region, used only when preparing a trait query.
1043 ReCanonical(CanonicalVar),
1046 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
1048 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1049 pub struct EarlyBoundRegion {
1052 pub name: InternedString,
1055 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1060 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1065 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1066 pub struct FloatVid {
1070 newtype_index!(RegionVid
1073 DEBUG_FORMAT = custom,
1076 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1077 pub struct SkolemizedRegionVid {
1081 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1087 /// A `FreshTy` is one that is generated as a replacement for an
1088 /// unbound type variable. This is convenient for caching etc. See
1089 /// `infer::freshen` for more details.
1094 /// Canonicalized type variable, used only when preparing a trait query.
1095 CanonicalTy(CanonicalVar),
1098 newtype_index!(CanonicalVar);
1100 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1101 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1102 pub struct ExistentialProjection<'tcx> {
1103 pub item_def_id: DefId,
1104 pub substs: &'tcx Substs<'tcx>,
1108 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1110 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
1111 /// Extracts the underlying existential trait reference from this projection.
1112 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1113 /// then this function would return a `exists T. T: Iterator` existential trait
1115 pub fn trait_ref(&self, tcx: TyCtxt) -> ty::ExistentialTraitRef<'tcx> {
1116 let def_id = tcx.associated_item(self.item_def_id).container.id();
1117 ty::ExistentialTraitRef{
1119 substs: self.substs,
1123 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1125 -> ty::ProjectionPredicate<'tcx>
1127 // otherwise the escaping regions would be captured by the binders
1128 assert!(!self_ty.has_escaping_regions());
1130 ty::ProjectionPredicate {
1131 projection_ty: ty::ProjectionTy {
1132 item_def_id: self.item_def_id,
1133 substs: tcx.mk_substs(
1134 iter::once(self_ty.into()).chain(self.substs.iter().cloned())),
1141 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
1142 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
1143 -> ty::PolyProjectionPredicate<'tcx> {
1144 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1147 pub fn item_def_id(&self) -> DefId {
1148 return self.skip_binder().item_def_id;
1152 impl DebruijnIndex {
1153 pub fn new(depth: u32) -> DebruijnIndex {
1155 DebruijnIndex { depth: depth }
1158 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
1159 DebruijnIndex { depth: self.depth + amount }
1163 /// Region utilities
1165 pub fn is_late_bound(&self) -> bool {
1167 ty::ReLateBound(..) => true,
1172 pub fn needs_infer(&self) -> bool {
1174 ty::ReVar(..) | ty::ReSkolemized(..) => true,
1179 pub fn escapes_depth(&self, depth: u32) -> bool {
1181 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1186 /// Returns the depth of `self` from the (1-based) binding level `depth`
1187 pub fn from_depth(&self, depth: u32) -> RegionKind {
1189 ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
1190 depth: debruijn.depth - (depth - 1)
1196 pub fn type_flags(&self) -> TypeFlags {
1197 let mut flags = TypeFlags::empty();
1201 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1202 flags = flags | TypeFlags::HAS_RE_INFER;
1203 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1205 ty::ReSkolemized(..) => {
1206 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1207 flags = flags | TypeFlags::HAS_RE_INFER;
1208 flags = flags | TypeFlags::HAS_RE_SKOL;
1209 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1211 ty::ReLateBound(..) => { }
1212 ty::ReEarlyBound(..) => {
1213 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1214 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1219 ty::ReScope { .. } => {
1220 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1224 ty::ReCanonical(..) => {
1225 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1226 flags = flags | TypeFlags::HAS_CANONICAL_VARS;
1228 ty::ReClosureBound(..) => {
1229 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1234 ty::ReStatic | ty::ReEmpty | ty::ReErased => (),
1235 _ => flags = flags | TypeFlags::HAS_LOCAL_NAMES,
1238 debug!("type_flags({:?}) = {:?}", self, flags);
1243 /// Given an early-bound or free region, returns the def-id where it was bound.
1244 /// For example, consider the regions in this snippet of code:
1248 /// ^^ -- early bound, declared on an impl
1250 /// fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1251 /// ^^ ^^ ^ anonymous, late-bound
1252 /// | early-bound, appears in where-clauses
1253 /// late-bound, appears only in fn args
1258 /// Here, `free_region_binding_scope('a)` would return the def-id
1259 /// of the impl, and for all the other highlighted regions, it
1260 /// would return the def-id of the function. In other cases (not shown), this
1261 /// function might return the def-id of a closure.
1262 pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_, '_, '_>) -> DefId {
1264 ty::ReEarlyBound(br) => {
1265 tcx.parent_def_id(br.def_id).unwrap()
1267 ty::ReFree(fr) => fr.scope,
1268 _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1274 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
1275 pub fn is_nil(&self) -> bool {
1277 TyTuple(ref tys) => tys.is_empty(),
1282 pub fn is_never(&self) -> bool {
1289 pub fn is_primitive(&self) -> bool {
1291 TyBool | TyChar | TyInt(_) | TyUint(_) | TyFloat(_) => true,
1296 pub fn is_ty_var(&self) -> bool {
1298 TyInfer(TyVar(_)) => true,
1303 pub fn is_ty_infer(&self) -> bool {
1310 pub fn is_phantom_data(&self) -> bool {
1311 if let TyAdt(def, _) = self.sty {
1312 def.is_phantom_data()
1318 pub fn is_bool(&self) -> bool { self.sty == TyBool }
1320 pub fn is_param(&self, index: u32) -> bool {
1322 ty::TyParam(ref data) => data.idx == index,
1327 pub fn is_self(&self) -> bool {
1329 TyParam(ref p) => p.is_self(),
1334 pub fn is_slice(&self) -> bool {
1336 TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
1337 TySlice(_) | TyStr => true,
1345 pub fn is_simd(&self) -> bool {
1347 TyAdt(def, _) => def.repr.simd(),
1352 pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1354 TyArray(ty, _) | TySlice(ty) => ty,
1355 TyStr => tcx.mk_mach_uint(ast::UintTy::U8),
1356 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1360 pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1362 TyAdt(def, substs) => {
1363 def.non_enum_variant().fields[0].ty(tcx, substs)
1365 _ => bug!("simd_type called on invalid type")
1369 pub fn simd_size(&self, _cx: TyCtxt) -> usize {
1371 TyAdt(def, _) => def.non_enum_variant().fields.len(),
1372 _ => bug!("simd_size called on invalid type")
1376 pub fn is_region_ptr(&self) -> bool {
1383 pub fn is_mutable_pointer(&self) -> bool {
1385 TyRawPtr(tnm) | TyRef(_, tnm) => if let hir::Mutability::MutMutable = tnm.mutbl {
1394 pub fn is_unsafe_ptr(&self) -> bool {
1396 TyRawPtr(_) => return true,
1401 pub fn is_box(&self) -> bool {
1403 TyAdt(def, _) => def.is_box(),
1408 /// panics if called on any type other than `Box<T>`
1409 pub fn boxed_ty(&self) -> Ty<'tcx> {
1411 TyAdt(def, substs) if def.is_box() => substs.type_at(0),
1412 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1416 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1417 /// (A TyRawPtr is scalar because it represents a non-managed pointer, so its
1418 /// contents are abstract to rustc.)
1419 pub fn is_scalar(&self) -> bool {
1421 TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
1422 TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
1423 TyFnDef(..) | TyFnPtr(_) | TyRawPtr(_) => true,
1428 /// Returns true if this type is a floating point type and false otherwise.
1429 pub fn is_floating_point(&self) -> bool {
1432 TyInfer(FloatVar(_)) => true,
1437 pub fn is_trait(&self) -> bool {
1439 TyDynamic(..) => true,
1444 pub fn is_enum(&self) -> bool {
1446 TyAdt(adt_def, _) => {
1453 pub fn is_closure(&self) -> bool {
1455 TyClosure(..) => true,
1460 pub fn is_generator(&self) -> bool {
1462 TyGenerator(..) => true,
1467 pub fn is_integral(&self) -> bool {
1469 TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
1474 pub fn is_fresh_ty(&self) -> bool {
1476 TyInfer(FreshTy(_)) => true,
1481 pub fn is_fresh(&self) -> bool {
1483 TyInfer(FreshTy(_)) => true,
1484 TyInfer(FreshIntTy(_)) => true,
1485 TyInfer(FreshFloatTy(_)) => true,
1490 pub fn is_char(&self) -> bool {
1497 pub fn is_fp(&self) -> bool {
1499 TyInfer(FloatVar(_)) | TyFloat(_) => true,
1504 pub fn is_numeric(&self) -> bool {
1505 self.is_integral() || self.is_fp()
1508 pub fn is_signed(&self) -> bool {
1515 pub fn is_machine(&self) -> bool {
1517 TyInt(ast::IntTy::Isize) | TyUint(ast::UintTy::Usize) => false,
1518 TyInt(..) | TyUint(..) | TyFloat(..) => true,
1523 pub fn has_concrete_skeleton(&self) -> bool {
1525 TyParam(_) | TyInfer(_) | TyError => false,
1530 /// Returns the type and mutability of *ty.
1532 /// The parameter `explicit` indicates if this is an *explicit* dereference.
1533 /// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1534 pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1536 TyAdt(def, _) if def.is_box() => {
1538 ty: self.boxed_ty(),
1539 mutbl: hir::MutImmutable,
1542 TyRef(_, mt) => Some(mt),
1543 TyRawPtr(mt) if explicit => Some(mt),
1548 /// Returns the type of `ty[i]`.
1549 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1551 TyArray(ty, _) | TySlice(ty) => Some(ty),
1556 pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1558 TyFnDef(def_id, substs) => {
1559 tcx.fn_sig(def_id).subst(tcx, substs)
1562 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1566 pub fn is_fn(&self) -> bool {
1568 TyFnDef(..) | TyFnPtr(_) => true,
1573 pub fn ty_to_def_id(&self) -> Option<DefId> {
1575 TyDynamic(ref tt, ..) => tt.principal().map(|p| p.def_id()),
1576 TyAdt(def, _) => Some(def.did),
1577 TyForeign(did) => Some(did),
1578 TyClosure(id, _) => Some(id),
1579 TyFnDef(id, _) => Some(id),
1584 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1586 TyAdt(adt, _) => Some(adt),
1591 /// Returns the regions directly referenced from this type (but
1592 /// not types reachable from this type via `walk_tys`). This
1593 /// ignores late-bound regions binders.
1594 pub fn regions(&self) -> Vec<ty::Region<'tcx>> {
1596 TyRef(region, _) => {
1599 TyDynamic(ref obj, region) => {
1600 let mut v = vec![region];
1601 if let Some(p) = obj.principal() {
1602 v.extend(p.skip_binder().substs.regions());
1606 TyAdt(_, substs) | TyAnon(_, substs) => {
1607 substs.regions().collect()
1609 TyClosure(_, ref substs) | TyGenerator(_, ref substs, _) => {
1610 substs.substs.regions().collect()
1612 TyProjection(ref data) => {
1613 data.substs.regions().collect()
1617 TyGeneratorWitness(..) |
1638 /// When we create a closure, we record its kind (i.e., what trait
1639 /// it implements) into its `ClosureSubsts` using a type
1640 /// parameter. This is kind of a phantom type, except that the
1641 /// most convenient thing for us to are the integral types. This
1642 /// function converts such a special type into the closure
1643 /// kind. To go the other way, use
1644 /// `tcx.closure_kind_ty(closure_kind)`.
1646 /// Note that during type checking, we use an inference variable
1647 /// to represent the closure kind, because it has not yet been
1648 /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
1649 /// is complete, that type variable will be unified.
1650 pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
1652 TyInt(int_ty) => match int_ty {
1653 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
1654 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1655 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1656 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1661 TyError => Some(ty::ClosureKind::Fn),
1663 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1668 /// Typed constant value.
1669 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Eq, PartialEq)]
1670 pub struct Const<'tcx> {
1673 pub val: ConstVal<'tcx>,
1676 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}