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_interned_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 // FIXME(#50125): Ignoring `Self` with `idx != 0` might lead to weird behavior elsewhere,
880 // but this should only be possible when using `-Z continue-parse-after-error` like
881 // `compile-fail/issue-36638.rs`.
882 if self.name == keywords::SelfType.name().as_str() && self.idx == 0 {
890 /// A [De Bruijn index][dbi] is a standard means of representing
891 /// regions (and perhaps later types) in a higher-ranked setting. In
892 /// particular, imagine a type like this:
894 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
897 /// | +------------+ 1 | |
899 /// +--------------------------------+ 2 |
901 /// +------------------------------------------+ 1
903 /// In this type, there are two binders (the outer fn and the inner
904 /// fn). We need to be able to determine, for any given region, which
905 /// fn type it is bound by, the inner or the outer one. There are
906 /// various ways you can do this, but a De Bruijn index is one of the
907 /// more convenient and has some nice properties. The basic idea is to
908 /// count the number of binders, inside out. Some examples should help
909 /// clarify what I mean.
911 /// Let's start with the reference type `&'b isize` that is the first
912 /// argument to the inner function. This region `'b` is assigned a De
913 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
914 /// fn). The region `'a` that appears in the second argument type (`&'a
915 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
916 /// second-innermost binder". (These indices are written on the arrays
919 /// What is interesting is that De Bruijn index attached to a particular
920 /// variable will vary depending on where it appears. For example,
921 /// the final type `&'a char` also refers to the region `'a` declared on
922 /// the outermost fn. But this time, this reference is not nested within
923 /// any other binders (i.e., it is not an argument to the inner fn, but
924 /// rather the outer one). Therefore, in this case, it is assigned a
925 /// De Bruijn index of 1, because the innermost binder in that location
928 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
929 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy, PartialOrd, Ord)]
930 pub struct DebruijnIndex {
931 /// We maintain the invariant that this is never 0. So 1 indicates
932 /// the innermost binder. To ensure this, create with `DebruijnIndex::new`.
936 pub type Region<'tcx> = &'tcx RegionKind;
938 /// Representation of regions.
940 /// Unlike types, most region variants are "fictitious", not concrete,
941 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
942 /// ones representing concrete regions.
946 /// These are regions that are stored behind a binder and must be substituted
947 /// with some concrete region before being used. There are 2 kind of
948 /// bound regions: early-bound, which are bound in an item's Generics,
949 /// and are substituted by a Substs, and late-bound, which are part of
950 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
951 /// the likes of `liberate_late_bound_regions`. The distinction exists
952 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
954 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
955 /// outside their binder, e.g. in types passed to type inference, and
956 /// should first be substituted (by skolemized regions, free regions,
957 /// or region variables).
959 /// ## Skolemized and Free Regions
961 /// One often wants to work with bound regions without knowing their precise
962 /// identity. For example, when checking a function, the lifetime of a borrow
963 /// can end up being assigned to some region parameter. In these cases,
964 /// it must be ensured that bounds on the region can't be accidentally
965 /// assumed without being checked.
967 /// The process of doing that is called "skolemization". The bound regions
968 /// are replaced by skolemized markers, which don't satisfy any relation
969 /// not explicitly provided.
971 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
972 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
973 /// to be used. These also support explicit bounds: both the internally-stored
974 /// *scope*, which the region is assumed to outlive, as well as other
975 /// relations stored in the `FreeRegionMap`. Note that these relations
976 /// aren't checked when you `make_subregion` (or `eq_types`), only by
977 /// `resolve_regions_and_report_errors`.
979 /// When working with higher-ranked types, some region relations aren't
980 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
981 /// `ReSkolemized` is designed for this purpose. In these contexts,
982 /// there's also the risk that some inference variable laying around will
983 /// get unified with your skolemized region: if you want to check whether
984 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
985 /// with a skolemized region `'%a`, the variable `'_` would just be
986 /// instantiated to the skolemized region `'%a`, which is wrong because
987 /// the inference variable is supposed to satisfy the relation
988 /// *for every value of the skolemized region*. To ensure that doesn't
989 /// happen, you can use `leak_check`. This is more clearly explained
990 /// by the [rustc guide].
992 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
993 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
994 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/trait-hrtb.html
995 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
996 pub enum RegionKind {
997 // Region bound in a type or fn declaration which will be
998 // substituted 'early' -- that is, at the same time when type
999 // parameters are substituted.
1000 ReEarlyBound(EarlyBoundRegion),
1002 // Region bound in a function scope, which will be substituted when the
1003 // function is called.
1004 ReLateBound(DebruijnIndex, BoundRegion),
1006 /// When checking a function body, the types of all arguments and so forth
1007 /// that refer to bound region parameters are modified to refer to free
1008 /// region parameters.
1011 /// A concrete region naming some statically determined scope
1012 /// (e.g. an expression or sequence of statements) within the
1013 /// current function.
1014 ReScope(region::Scope),
1016 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1019 /// A region variable. Should not exist after typeck.
1022 /// A skolemized region - basically the higher-ranked version of ReFree.
1023 /// Should not exist after typeck.
1024 ReSkolemized(SkolemizedRegionVid, BoundRegion),
1026 /// Empty lifetime is for data that is never accessed.
1027 /// Bottom in the region lattice. We treat ReEmpty somewhat
1028 /// specially; at least right now, we do not generate instances of
1029 /// it during the GLB computations, but rather
1030 /// generate an error instead. This is to improve error messages.
1031 /// The only way to get an instance of ReEmpty is to have a region
1032 /// variable with no constraints.
1035 /// Erased region, used by trait selection, in MIR and during trans.
1038 /// These are regions bound in the "defining type" for a
1039 /// closure. They are used ONLY as part of the
1040 /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1041 /// See `ClosureRegionRequirements` for more details.
1042 ReClosureBound(RegionVid),
1044 /// Canonicalized region, used only when preparing a trait query.
1045 ReCanonical(CanonicalVar),
1048 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
1050 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1051 pub struct EarlyBoundRegion {
1054 pub name: InternedString,
1057 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1062 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1067 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1068 pub struct FloatVid {
1072 newtype_index!(RegionVid
1075 DEBUG_FORMAT = custom,
1078 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1079 pub struct SkolemizedRegionVid {
1083 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1089 /// A `FreshTy` is one that is generated as a replacement for an
1090 /// unbound type variable. This is convenient for caching etc. See
1091 /// `infer::freshen` for more details.
1096 /// Canonicalized type variable, used only when preparing a trait query.
1097 CanonicalTy(CanonicalVar),
1100 newtype_index!(CanonicalVar);
1102 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1103 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1104 pub struct ExistentialProjection<'tcx> {
1105 pub item_def_id: DefId,
1106 pub substs: &'tcx Substs<'tcx>,
1110 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1112 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
1113 /// Extracts the underlying existential trait reference from this projection.
1114 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1115 /// then this function would return a `exists T. T: Iterator` existential trait
1117 pub fn trait_ref(&self, tcx: TyCtxt) -> ty::ExistentialTraitRef<'tcx> {
1118 let def_id = tcx.associated_item(self.item_def_id).container.id();
1119 ty::ExistentialTraitRef{
1121 substs: self.substs,
1125 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1127 -> ty::ProjectionPredicate<'tcx>
1129 // otherwise the escaping regions would be captured by the binders
1130 assert!(!self_ty.has_escaping_regions());
1132 ty::ProjectionPredicate {
1133 projection_ty: ty::ProjectionTy {
1134 item_def_id: self.item_def_id,
1135 substs: tcx.mk_substs(
1136 iter::once(self_ty.into()).chain(self.substs.iter().cloned())),
1143 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
1144 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
1145 -> ty::PolyProjectionPredicate<'tcx> {
1146 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1149 pub fn item_def_id(&self) -> DefId {
1150 return self.skip_binder().item_def_id;
1154 impl DebruijnIndex {
1155 pub fn new(depth: u32) -> DebruijnIndex {
1157 DebruijnIndex { depth: depth }
1160 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
1161 DebruijnIndex { depth: self.depth + amount }
1165 /// Region utilities
1167 pub fn is_late_bound(&self) -> bool {
1169 ty::ReLateBound(..) => true,
1174 pub fn needs_infer(&self) -> bool {
1176 ty::ReVar(..) | ty::ReSkolemized(..) => true,
1181 pub fn escapes_depth(&self, depth: u32) -> bool {
1183 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1188 /// Returns the depth of `self` from the (1-based) binding level `depth`
1189 pub fn from_depth(&self, depth: u32) -> RegionKind {
1191 ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
1192 depth: debruijn.depth - (depth - 1)
1198 pub fn type_flags(&self) -> TypeFlags {
1199 let mut flags = TypeFlags::empty();
1203 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1204 flags = flags | TypeFlags::HAS_RE_INFER;
1205 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1207 ty::ReSkolemized(..) => {
1208 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1209 flags = flags | TypeFlags::HAS_RE_INFER;
1210 flags = flags | TypeFlags::HAS_RE_SKOL;
1211 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1213 ty::ReLateBound(..) => { }
1214 ty::ReEarlyBound(..) => {
1215 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1216 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1221 ty::ReScope { .. } => {
1222 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1226 ty::ReCanonical(..) => {
1227 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1228 flags = flags | TypeFlags::HAS_CANONICAL_VARS;
1230 ty::ReClosureBound(..) => {
1231 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1236 ty::ReStatic | ty::ReEmpty | ty::ReErased => (),
1237 _ => flags = flags | TypeFlags::HAS_LOCAL_NAMES,
1240 debug!("type_flags({:?}) = {:?}", self, flags);
1245 /// Given an early-bound or free region, returns the def-id where it was bound.
1246 /// For example, consider the regions in this snippet of code:
1250 /// ^^ -- early bound, declared on an impl
1252 /// fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1253 /// ^^ ^^ ^ anonymous, late-bound
1254 /// | early-bound, appears in where-clauses
1255 /// late-bound, appears only in fn args
1260 /// Here, `free_region_binding_scope('a)` would return the def-id
1261 /// of the impl, and for all the other highlighted regions, it
1262 /// would return the def-id of the function. In other cases (not shown), this
1263 /// function might return the def-id of a closure.
1264 pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_, '_, '_>) -> DefId {
1266 ty::ReEarlyBound(br) => {
1267 tcx.parent_def_id(br.def_id).unwrap()
1269 ty::ReFree(fr) => fr.scope,
1270 _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1276 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
1277 pub fn is_nil(&self) -> bool {
1279 TyTuple(ref tys) => tys.is_empty(),
1284 pub fn is_never(&self) -> bool {
1291 pub fn is_primitive(&self) -> bool {
1293 TyBool | TyChar | TyInt(_) | TyUint(_) | TyFloat(_) => true,
1298 pub fn is_ty_var(&self) -> bool {
1300 TyInfer(TyVar(_)) => true,
1305 pub fn is_ty_infer(&self) -> bool {
1312 pub fn is_phantom_data(&self) -> bool {
1313 if let TyAdt(def, _) = self.sty {
1314 def.is_phantom_data()
1320 pub fn is_bool(&self) -> bool { self.sty == TyBool }
1322 pub fn is_param(&self, index: u32) -> bool {
1324 ty::TyParam(ref data) => data.idx == index,
1329 pub fn is_self(&self) -> bool {
1331 TyParam(ref p) => p.is_self(),
1336 pub fn is_slice(&self) -> bool {
1338 TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
1339 TySlice(_) | TyStr => true,
1347 pub fn is_simd(&self) -> bool {
1349 TyAdt(def, _) => def.repr.simd(),
1354 pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1356 TyArray(ty, _) | TySlice(ty) => ty,
1357 TyStr => tcx.mk_mach_uint(ast::UintTy::U8),
1358 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1362 pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1364 TyAdt(def, substs) => {
1365 def.non_enum_variant().fields[0].ty(tcx, substs)
1367 _ => bug!("simd_type called on invalid type")
1371 pub fn simd_size(&self, _cx: TyCtxt) -> usize {
1373 TyAdt(def, _) => def.non_enum_variant().fields.len(),
1374 _ => bug!("simd_size called on invalid type")
1378 pub fn is_region_ptr(&self) -> bool {
1385 pub fn is_mutable_pointer(&self) -> bool {
1387 TyRawPtr(tnm) | TyRef(_, tnm) => if let hir::Mutability::MutMutable = tnm.mutbl {
1396 pub fn is_unsafe_ptr(&self) -> bool {
1398 TyRawPtr(_) => return true,
1403 pub fn is_box(&self) -> bool {
1405 TyAdt(def, _) => def.is_box(),
1410 /// panics if called on any type other than `Box<T>`
1411 pub fn boxed_ty(&self) -> Ty<'tcx> {
1413 TyAdt(def, substs) if def.is_box() => substs.type_at(0),
1414 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1418 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1419 /// (A TyRawPtr is scalar because it represents a non-managed pointer, so its
1420 /// contents are abstract to rustc.)
1421 pub fn is_scalar(&self) -> bool {
1423 TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
1424 TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
1425 TyFnDef(..) | TyFnPtr(_) | TyRawPtr(_) => true,
1430 /// Returns true if this type is a floating point type and false otherwise.
1431 pub fn is_floating_point(&self) -> bool {
1434 TyInfer(FloatVar(_)) => true,
1439 pub fn is_trait(&self) -> bool {
1441 TyDynamic(..) => true,
1446 pub fn is_enum(&self) -> bool {
1448 TyAdt(adt_def, _) => {
1455 pub fn is_closure(&self) -> bool {
1457 TyClosure(..) => true,
1462 pub fn is_generator(&self) -> bool {
1464 TyGenerator(..) => true,
1469 pub fn is_integral(&self) -> bool {
1471 TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
1476 pub fn is_fresh_ty(&self) -> bool {
1478 TyInfer(FreshTy(_)) => true,
1483 pub fn is_fresh(&self) -> bool {
1485 TyInfer(FreshTy(_)) => true,
1486 TyInfer(FreshIntTy(_)) => true,
1487 TyInfer(FreshFloatTy(_)) => true,
1492 pub fn is_char(&self) -> bool {
1499 pub fn is_fp(&self) -> bool {
1501 TyInfer(FloatVar(_)) | TyFloat(_) => true,
1506 pub fn is_numeric(&self) -> bool {
1507 self.is_integral() || self.is_fp()
1510 pub fn is_signed(&self) -> bool {
1517 pub fn is_machine(&self) -> bool {
1519 TyInt(ast::IntTy::Isize) | TyUint(ast::UintTy::Usize) => false,
1520 TyInt(..) | TyUint(..) | TyFloat(..) => true,
1525 pub fn has_concrete_skeleton(&self) -> bool {
1527 TyParam(_) | TyInfer(_) | TyError => false,
1532 /// Returns the type and mutability of *ty.
1534 /// The parameter `explicit` indicates if this is an *explicit* dereference.
1535 /// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1536 pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1538 TyAdt(def, _) if def.is_box() => {
1540 ty: self.boxed_ty(),
1541 mutbl: hir::MutImmutable,
1544 TyRef(_, mt) => Some(mt),
1545 TyRawPtr(mt) if explicit => Some(mt),
1550 /// Returns the type of `ty[i]`.
1551 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1553 TyArray(ty, _) | TySlice(ty) => Some(ty),
1558 pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1560 TyFnDef(def_id, substs) => {
1561 tcx.fn_sig(def_id).subst(tcx, substs)
1564 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1568 pub fn is_fn(&self) -> bool {
1570 TyFnDef(..) | TyFnPtr(_) => true,
1575 pub fn ty_to_def_id(&self) -> Option<DefId> {
1577 TyDynamic(ref tt, ..) => tt.principal().map(|p| p.def_id()),
1578 TyAdt(def, _) => Some(def.did),
1579 TyForeign(did) => Some(did),
1580 TyClosure(id, _) => Some(id),
1581 TyFnDef(id, _) => Some(id),
1586 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1588 TyAdt(adt, _) => Some(adt),
1593 /// Returns the regions directly referenced from this type (but
1594 /// not types reachable from this type via `walk_tys`). This
1595 /// ignores late-bound regions binders.
1596 pub fn regions(&self) -> Vec<ty::Region<'tcx>> {
1598 TyRef(region, _) => {
1601 TyDynamic(ref obj, region) => {
1602 let mut v = vec![region];
1603 if let Some(p) = obj.principal() {
1604 v.extend(p.skip_binder().substs.regions());
1608 TyAdt(_, substs) | TyAnon(_, substs) => {
1609 substs.regions().collect()
1611 TyClosure(_, ref substs) | TyGenerator(_, ref substs, _) => {
1612 substs.substs.regions().collect()
1614 TyProjection(ref data) => {
1615 data.substs.regions().collect()
1619 TyGeneratorWitness(..) |
1640 /// When we create a closure, we record its kind (i.e., what trait
1641 /// it implements) into its `ClosureSubsts` using a type
1642 /// parameter. This is kind of a phantom type, except that the
1643 /// most convenient thing for us to are the integral types. This
1644 /// function converts such a special type into the closure
1645 /// kind. To go the other way, use
1646 /// `tcx.closure_kind_ty(closure_kind)`.
1648 /// Note that during type checking, we use an inference variable
1649 /// to represent the closure kind, because it has not yet been
1650 /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
1651 /// is complete, that type variable will be unified.
1652 pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
1654 TyInt(int_ty) => match int_ty {
1655 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
1656 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1657 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1658 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1663 TyError => Some(ty::ClosureKind::Fn),
1665 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1670 /// Typed constant value.
1671 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Eq, PartialEq)]
1672 pub struct Const<'tcx> {
1675 pub val: ConstVal<'tcx>,
1678 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}