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;
22 use mir::interpret::{Allocation, PrimVal, MemoryPointer, Value, ConstValue};
25 use std::cmp::Ordering;
26 use rustc_target::spec::abi;
27 use syntax::ast::{self, Name};
28 use syntax::symbol::{keywords, InternedString};
35 use self::TypeVariants::*;
37 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
38 pub struct TypeAndMut<'tcx> {
40 pub mutbl: hir::Mutability,
43 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
44 RustcEncodable, RustcDecodable, Copy)]
45 /// A "free" region `fr` can be interpreted as "some region
46 /// at least as big as the scope `fr.scope`".
47 pub struct FreeRegion {
49 pub bound_region: BoundRegion,
52 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
53 RustcEncodable, RustcDecodable, Copy)]
54 pub enum BoundRegion {
55 /// An anonymous region parameter for a given fn (&T)
58 /// Named region parameters for functions (a in &'a T)
60 /// The def-id is needed to distinguish free regions in
61 /// the event of shadowing.
62 BrNamed(DefId, InternedString),
64 /// Fresh bound identifiers created during GLB computations.
67 /// Anonymous region for the implicit env pointer parameter
73 pub fn is_named(&self) -> bool {
75 BoundRegion::BrNamed(..) => true,
81 /// NB: If you change this, you'll probably want to change the corresponding
82 /// AST structure in libsyntax/ast.rs as well.
83 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
84 pub enum TypeVariants<'tcx> {
85 /// The primitive boolean type. Written as `bool`.
88 /// The primitive character type; holds a Unicode scalar value
89 /// (a non-surrogate code point). Written as `char`.
92 /// A primitive signed integer type. For example, `i32`.
95 /// A primitive unsigned integer type. For example, `u32`.
98 /// A primitive floating-point type. For example, `f64`.
99 TyFloat(ast::FloatTy),
101 /// Structures, enumerations and unions.
103 /// Substs here, possibly against intuition, *may* contain `TyParam`s.
104 /// That is, even after substitution it is possible that there are type
105 /// variables. This happens when the `TyAdt` corresponds to an ADT
106 /// definition and not a concrete use of it.
107 TyAdt(&'tcx AdtDef, &'tcx Substs<'tcx>),
111 /// The pointee of a string slice. Written as `str`.
114 /// An array with the given length. Written as `[T; n]`.
115 TyArray(Ty<'tcx>, &'tcx ty::Const<'tcx>),
117 /// The pointee of an array slice. Written as `[T]`.
120 /// A raw pointer. Written as `*mut T` or `*const T`
121 TyRawPtr(TypeAndMut<'tcx>),
123 /// A reference; a pointer with an associated lifetime. Written as
124 /// `&'a mut T` or `&'a T`.
125 TyRef(Region<'tcx>, Ty<'tcx>, hir::Mutability),
127 /// The anonymous type of a function declaration/definition. Each
128 /// function has a unique type.
129 TyFnDef(DefId, &'tcx Substs<'tcx>),
131 /// A pointer to a function. Written as `fn() -> i32`.
132 TyFnPtr(PolyFnSig<'tcx>),
134 /// A trait, defined with `trait`.
135 TyDynamic(Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
137 /// The anonymous type of a closure. Used to represent the type of
139 TyClosure(DefId, ClosureSubsts<'tcx>),
141 /// The anonymous type of a generator. Used to represent the type of
143 TyGenerator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
145 /// A type representin the types stored inside a generator.
146 /// This should only appear in GeneratorInteriors.
147 TyGeneratorWitness(Binder<&'tcx Slice<Ty<'tcx>>>),
149 /// The never type `!`
152 /// A tuple type. For example, `(i32, bool)`.
153 TyTuple(&'tcx Slice<Ty<'tcx>>),
155 /// The projection of an associated type. For example,
156 /// `<T as Trait<..>>::N`.
157 TyProjection(ProjectionTy<'tcx>),
159 /// Anonymized (`impl Trait`) type found in a return type.
160 /// The DefId comes from the `impl Trait` ast::Ty node, and the
161 /// substitutions are for the generics of the function in question.
162 /// After typeck, the concrete type can be found in the `types` map.
163 TyAnon(DefId, &'tcx Substs<'tcx>),
165 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
168 /// A type variable used during type-checking.
171 /// A placeholder for a type which could not be computed; this is
172 /// propagated to avoid useless error messages.
176 /// A closure can be modeled as a struct that looks like:
178 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
186 /// - 'l0...'li and T0...Tj are the lifetime and type parameters
187 /// in scope on the function that defined the closure,
188 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
189 /// is rather hackily encoded via a scalar type. See
190 /// `TyS::to_opt_closure_kind` for details.
191 /// - CS represents the *closure signature*, representing as a `fn()`
192 /// type. For example, `fn(u32, u32) -> u32` would mean that the closure
193 /// implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
195 /// - U0...Uk are type parameters representing the types of its upvars
196 /// (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
197 /// and the up-var has the type `Foo`, then `Ui = &Foo`).
199 /// So, for example, given this function:
201 /// fn foo<'a, T>(data: &'a mut T) {
202 /// do(|| data.count += 1)
205 /// the type of the closure would be something like:
207 /// struct Closure<'a, T, U0> {
211 /// Note that the type of the upvar is not specified in the struct.
212 /// You may wonder how the impl would then be able to use the upvar,
213 /// if it doesn't know it's type? The answer is that the impl is
214 /// (conceptually) not fully generic over Closure but rather tied to
215 /// instances with the expected upvar types:
217 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
221 /// You can see that the *impl* fully specified the type of the upvar
222 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
223 /// (Here, I am assuming that `data` is mut-borrowed.)
225 /// Now, the last question you may ask is: Why include the upvar types
226 /// as extra type parameters? The reason for this design is that the
227 /// upvar types can reference lifetimes that are internal to the
228 /// creating function. In my example above, for example, the lifetime
229 /// `'b` represents the scope of the closure itself; this is some
230 /// subset of `foo`, probably just the scope of the call to the to
231 /// `do()`. If we just had the lifetime/type parameters from the
232 /// enclosing function, we couldn't name this lifetime `'b`. Note that
233 /// there can also be lifetimes in the types of the upvars themselves,
234 /// if one of them happens to be a reference to something that the
235 /// creating fn owns.
237 /// OK, you say, so why not create a more minimal set of parameters
238 /// that just includes the extra lifetime parameters? The answer is
239 /// primarily that it would be hard --- we don't know at the time when
240 /// we create the closure type what the full types of the upvars are,
241 /// nor do we know which are borrowed and which are not. In this
242 /// design, we can just supply a fresh type parameter and figure that
245 /// All right, you say, but why include the type parameters from the
246 /// original function then? The answer is that trans may need them
247 /// when monomorphizing, and they may not appear in the upvars. A
248 /// closure could capture no variables but still make use of some
249 /// in-scope type parameter with a bound (e.g., if our example above
250 /// had an extra `U: Default`, and the closure called `U::default()`).
252 /// There is another reason. This design (implicitly) prohibits
253 /// closures from capturing themselves (except via a trait
254 /// object). This simplifies closure inference considerably, since it
255 /// means that when we infer the kind of a closure or its upvars, we
256 /// don't have to handle cycles where the decisions we make for
257 /// closure C wind up influencing the decisions we ought to make for
258 /// closure C (which would then require fixed point iteration to
259 /// handle). Plus it fixes an ICE. :P
263 /// Perhaps surprisingly, `ClosureSubsts` are also used for
264 /// generators. In that case, what is written above is only half-true
265 /// -- the set of type parameters is similar, but the role of CK and
266 /// CS are different. CK represents the "yield type" and CS
267 /// represents the "return type" of the generator.
269 /// It'd be nice to split this struct into ClosureSubsts and
270 /// GeneratorSubsts, I believe. -nmatsakis
271 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
272 pub struct ClosureSubsts<'tcx> {
273 /// Lifetime and type parameters from the enclosing function,
274 /// concatenated with the types of the upvars.
276 /// These are separated out because trans wants to pass them around
277 /// when monomorphizing.
278 pub substs: &'tcx Substs<'tcx>,
281 /// Struct returned by `split()`. Note that these are subslices of the
282 /// parent slice and not canonical substs themselves.
283 struct SplitClosureSubsts<'tcx> {
284 closure_kind_ty: Ty<'tcx>,
285 closure_sig_ty: Ty<'tcx>,
286 upvar_kinds: &'tcx [Kind<'tcx>],
289 impl<'tcx> ClosureSubsts<'tcx> {
290 /// Divides the closure substs into their respective
291 /// components. Single source of truth with respect to the
293 fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitClosureSubsts<'tcx> {
294 let generics = tcx.generics_of(def_id);
295 let parent_len = generics.parent_count();
297 closure_kind_ty: self.substs.type_at(parent_len),
298 closure_sig_ty: self.substs.type_at(parent_len + 1),
299 upvar_kinds: &self.substs[parent_len + 2..],
304 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
305 impl Iterator<Item=Ty<'tcx>> + 'tcx
307 let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
308 upvar_kinds.iter().map(|t| {
309 if let UnpackedKind::Type(ty) = t.unpack() {
312 bug!("upvar should be type")
317 /// Returns the closure kind for this closure; may return a type
318 /// variable during inference. To get the closure kind during
319 /// inference, use `infcx.closure_kind(def_id, substs)`.
320 pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
321 self.split(def_id, tcx).closure_kind_ty
324 /// Returns the type representing the closure signature for this
325 /// closure; may contain type variables during inference. To get
326 /// the closure signature during inference, use
327 /// `infcx.fn_sig(def_id)`.
328 pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
329 self.split(def_id, tcx).closure_sig_ty
332 /// Returns the closure kind for this closure; only usable outside
333 /// of an inference context, because in that context we know that
334 /// there are no type variables.
336 /// If you have an inference context, use `infcx.closure_kind()`.
337 pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::ClosureKind {
338 self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
341 /// Extracts the signature from the closure; only usable outside
342 /// of an inference context, because in that context we know that
343 /// there are no type variables.
345 /// If you have an inference context, use `infcx.closure_sig()`.
346 pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::PolyFnSig<'tcx> {
347 match self.closure_sig_ty(def_id, tcx).sty {
348 ty::TyFnPtr(sig) => sig,
349 ref t => bug!("closure_sig_ty is not a fn-ptr: {:?}", t),
354 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
355 pub struct GeneratorSubsts<'tcx> {
356 pub substs: &'tcx Substs<'tcx>,
359 struct SplitGeneratorSubsts<'tcx> {
363 upvar_kinds: &'tcx [Kind<'tcx>],
366 impl<'tcx> GeneratorSubsts<'tcx> {
367 fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitGeneratorSubsts<'tcx> {
368 let generics = tcx.generics_of(def_id);
369 let parent_len = generics.parent_count();
370 SplitGeneratorSubsts {
371 yield_ty: self.substs.type_at(parent_len),
372 return_ty: self.substs.type_at(parent_len + 1),
373 witness: self.substs.type_at(parent_len + 2),
374 upvar_kinds: &self.substs[parent_len + 3..],
378 /// This describes the types that can be contained in a generator.
379 /// It will be a type variable initially and unified in the last stages of typeck of a body.
380 /// It contains a tuple of all the types that could end up on a generator frame.
381 /// The state transformation MIR pass may only produce layouts which mention types
382 /// in this tuple. Upvars are not counted here.
383 pub fn witness(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
384 self.split(def_id, tcx).witness
388 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
389 impl Iterator<Item=Ty<'tcx>> + 'tcx
391 let SplitGeneratorSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
392 upvar_kinds.iter().map(|t| {
393 if let UnpackedKind::Type(ty) = t.unpack() {
396 bug!("upvar should be type")
401 /// Returns the type representing the yield type of the generator.
402 pub fn yield_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
403 self.split(def_id, tcx).yield_ty
406 /// Returns the type representing the return type of the generator.
407 pub fn return_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
408 self.split(def_id, tcx).return_ty
411 /// Return the "generator signature", which consists of its yield
412 /// and return types.
414 /// NB. Some bits of the code prefers to see this wrapped in a
415 /// binder, but it never contains bound regions. Probably this
416 /// function should be removed.
417 pub fn poly_sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> PolyGenSig<'tcx> {
418 ty::Binder::dummy(self.sig(def_id, tcx))
421 /// Return the "generator signature", which consists of its yield
422 /// and return types.
423 pub fn sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> GenSig<'tcx> {
425 yield_ty: self.yield_ty(def_id, tcx),
426 return_ty: self.return_ty(def_id, tcx),
431 impl<'a, 'gcx, 'tcx> GeneratorSubsts<'tcx> {
432 /// This returns the types of the MIR locals which had to be stored across suspension points.
433 /// It is calculated in rustc_mir::transform::generator::StateTransform.
434 /// All the types here must be in the tuple in GeneratorInterior.
438 tcx: TyCtxt<'a, 'gcx, 'tcx>,
439 ) -> impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a {
440 let state = tcx.generator_layout(def_id).fields.iter();
441 state.map(move |d| d.ty.subst(tcx, self.substs))
444 /// This is the types of the fields of a generate which
445 /// is available before the generator transformation.
446 /// It includes the upvars and the state discriminant which is u32.
447 pub fn pre_transforms_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
448 impl Iterator<Item=Ty<'tcx>> + 'a
450 self.upvar_tys(def_id, tcx).chain(iter::once(tcx.types.u32))
453 /// This is the types of all the fields stored in a generator.
454 /// It includes the upvars, state types and the state discriminant which is u32.
455 pub fn field_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
456 impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a
458 self.pre_transforms_tys(def_id, tcx).chain(self.state_tys(def_id, tcx))
462 #[derive(Debug, Copy, Clone)]
463 pub enum UpvarSubsts<'tcx> {
464 Closure(ClosureSubsts<'tcx>),
465 Generator(GeneratorSubsts<'tcx>),
468 impl<'tcx> UpvarSubsts<'tcx> {
470 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
471 impl Iterator<Item=Ty<'tcx>> + 'tcx
473 let upvar_kinds = match self {
474 UpvarSubsts::Closure(substs) => substs.split(def_id, tcx).upvar_kinds,
475 UpvarSubsts::Generator(substs) => substs.split(def_id, tcx).upvar_kinds,
477 upvar_kinds.iter().map(|t| {
478 if let UnpackedKind::Type(ty) = t.unpack() {
481 bug!("upvar should be type")
487 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
488 pub enum ExistentialPredicate<'tcx> {
490 Trait(ExistentialTraitRef<'tcx>),
491 /// e.g. Iterator::Item = T
492 Projection(ExistentialProjection<'tcx>),
497 impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
498 pub fn cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
499 use self::ExistentialPredicate::*;
500 match (*self, *other) {
501 (Trait(_), Trait(_)) => Ordering::Equal,
502 (Projection(ref a), Projection(ref b)) =>
503 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
504 (AutoTrait(ref a), AutoTrait(ref b)) =>
505 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
506 (Trait(_), _) => Ordering::Less,
507 (Projection(_), Trait(_)) => Ordering::Greater,
508 (Projection(_), _) => Ordering::Less,
509 (AutoTrait(_), _) => Ordering::Greater,
515 impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
516 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
517 -> ty::Predicate<'tcx> {
519 match *self.skip_binder() {
520 ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
521 ExistentialPredicate::Projection(p) =>
522 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
523 ExistentialPredicate::AutoTrait(did) => {
524 let trait_ref = Binder(ty::TraitRef {
526 substs: tcx.mk_substs_trait(self_ty, &[]),
528 trait_ref.to_predicate()
534 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<ExistentialPredicate<'tcx>> {}
536 impl<'tcx> Slice<ExistentialPredicate<'tcx>> {
537 pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
539 Some(&ExistentialPredicate::Trait(tr)) => Some(tr),
545 pub fn projection_bounds<'a>(&'a self) ->
546 impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
547 self.iter().filter_map(|predicate| {
549 ExistentialPredicate::Projection(p) => Some(p),
556 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
557 self.iter().filter_map(|predicate| {
559 ExistentialPredicate::AutoTrait(d) => Some(d),
566 impl<'tcx> Binder<&'tcx Slice<ExistentialPredicate<'tcx>>> {
567 pub fn principal(&self) -> Option<PolyExistentialTraitRef<'tcx>> {
568 self.skip_binder().principal().map(Binder::bind)
572 pub fn projection_bounds<'a>(&'a self) ->
573 impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
574 self.skip_binder().projection_bounds().map(Binder::bind)
578 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
579 self.skip_binder().auto_traits()
582 pub fn iter<'a>(&'a self)
583 -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
584 self.skip_binder().iter().cloned().map(Binder::bind)
588 /// A complete reference to a trait. These take numerous guises in syntax,
589 /// but perhaps the most recognizable form is in a where clause:
593 /// This would be represented by a trait-reference where the def-id is the
594 /// def-id for the trait `Foo` and the substs define `T` as parameter 0,
595 /// and `U` as parameter 1.
597 /// Trait references also appear in object types like `Foo<U>`, but in
598 /// that case the `Self` parameter is absent from the substitutions.
600 /// Note that a `TraitRef` introduces a level of region binding, to
601 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
602 /// U>` or higher-ranked object types.
603 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
604 pub struct TraitRef<'tcx> {
606 pub substs: &'tcx Substs<'tcx>,
609 impl<'tcx> TraitRef<'tcx> {
610 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
611 TraitRef { def_id: def_id, substs: substs }
614 pub fn self_ty(&self) -> Ty<'tcx> {
615 self.substs.type_at(0)
618 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
619 // Select only the "input types" from a trait-reference. For
620 // now this is all the types that appear in the
621 // trait-reference, but it should eventually exclude
627 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
629 impl<'tcx> PolyTraitRef<'tcx> {
630 pub fn self_ty(&self) -> Ty<'tcx> {
631 self.skip_binder().self_ty()
634 pub fn def_id(&self) -> DefId {
635 self.skip_binder().def_id
638 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
639 // Note that we preserve binding levels
640 Binder(ty::TraitPredicate { trait_ref: self.skip_binder().clone() })
644 /// An existential reference to a trait, where `Self` is erased.
645 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
647 /// exists T. T: Trait<'a, 'b, X, Y>
649 /// The substitutions don't include the erased `Self`, only trait
650 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
651 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
652 pub struct ExistentialTraitRef<'tcx> {
654 pub substs: &'tcx Substs<'tcx>,
657 impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
658 pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
659 // Select only the "input types" from a trait-reference. For
660 // now this is all the types that appear in the
661 // trait-reference, but it should eventually exclude
666 /// Object types don't have a self-type specified. Therefore, when
667 /// we convert the principal trait-ref into a normal trait-ref,
668 /// you must give *some* self-type. A common choice is `mk_err()`
669 /// or some skolemized type.
670 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
671 -> ty::TraitRef<'tcx> {
672 // otherwise the escaping regions would be captured by the binder
673 assert!(!self_ty.has_escaping_regions());
677 substs: tcx.mk_substs(
678 iter::once(self_ty.into()).chain(self.substs.iter().cloned()))
683 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
685 impl<'tcx> PolyExistentialTraitRef<'tcx> {
686 pub fn def_id(&self) -> DefId {
687 self.skip_binder().def_id
691 /// Binder is a binder for higher-ranked lifetimes. It is part of the
692 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
693 /// (which would be represented by the type `PolyTraitRef ==
694 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
695 /// erase, or otherwise "discharge" these bound regions, we change the
696 /// type from `Binder<T>` to just `T` (see
697 /// e.g. `liberate_late_bound_regions`).
698 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
699 pub struct Binder<T>(T);
702 /// Wraps `value` in a binder, asserting that `value` does not
703 /// contain any bound regions that would be bound by the
704 /// binder. This is commonly used to 'inject' a value T into a
705 /// different binding level.
706 pub fn dummy<'tcx>(value: T) -> Binder<T>
707 where T: TypeFoldable<'tcx>
709 assert!(!value.has_escaping_regions());
713 /// Wraps `value` in a binder, binding late-bound regions (if any).
714 pub fn bind<'tcx>(value: T) -> Binder<T>
719 /// Skips the binder and returns the "bound" value. This is a
720 /// risky thing to do because it's easy to get confused about
721 /// debruijn indices and the like. It is usually better to
722 /// discharge the binder using `no_late_bound_regions` or
723 /// `replace_late_bound_regions` or something like
724 /// that. `skip_binder` is only valid when you are either
725 /// extracting data that has nothing to do with bound regions, you
726 /// are doing some sort of test that does not involve bound
727 /// regions, or you are being very careful about your depth
730 /// Some examples where `skip_binder` is reasonable:
732 /// - extracting the def-id from a PolyTraitRef;
733 /// - comparing the self type of a PolyTraitRef to see if it is equal to
734 /// a type parameter `X`, since the type `X` does not reference any regions
735 pub fn skip_binder(&self) -> &T {
739 pub fn as_ref(&self) -> Binder<&T> {
743 pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
744 where F: FnOnce(&T) -> U
746 self.as_ref().map_bound(f)
749 pub fn map_bound<F, U>(self, f: F) -> Binder<U>
750 where F: FnOnce(T) -> U
755 /// Unwraps and returns the value within, but only if it contains
756 /// no bound regions at all. (In other words, if this binder --
757 /// and indeed any enclosing binder -- doesn't bind anything at
758 /// all.) Otherwise, returns `None`.
760 /// (One could imagine having a method that just unwraps a single
761 /// binder, but permits late-bound regions bound by enclosing
762 /// binders, but that would require adjusting the debruijn
763 /// indices, and given the shallow binding structure we often use,
764 /// would not be that useful.)
765 pub fn no_late_bound_regions<'tcx>(self) -> Option<T>
766 where T : TypeFoldable<'tcx>
768 if self.skip_binder().has_escaping_regions() {
771 Some(self.skip_binder().clone())
775 /// Given two things that have the same binder level,
776 /// and an operation that wraps on their contents, execute the operation
777 /// and then wrap its result.
779 /// `f` should consider bound regions at depth 1 to be free, and
780 /// anything it produces with bound regions at depth 1 will be
781 /// bound in the resulting return value.
782 pub fn fuse<U,F,R>(self, u: Binder<U>, f: F) -> Binder<R>
783 where F: FnOnce(T, U) -> R
785 Binder(f(self.0, u.0))
788 /// Split the contents into two things that share the same binder
789 /// level as the original, returning two distinct binders.
791 /// `f` should consider bound regions at depth 1 to be free, and
792 /// anything it produces with bound regions at depth 1 will be
793 /// bound in the resulting return values.
794 pub fn split<U,V,F>(self, f: F) -> (Binder<U>, Binder<V>)
795 where F: FnOnce(T) -> (U, V)
797 let (u, v) = f(self.0);
798 (Binder(u), Binder(v))
802 /// Represents the projection of an associated type. In explicit UFCS
803 /// form this would be written `<T as Trait<..>>::N`.
804 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
805 pub struct ProjectionTy<'tcx> {
806 /// The parameters of the associated item.
807 pub substs: &'tcx Substs<'tcx>,
809 /// The DefId of the TraitItem for the associated type N.
811 /// Note that this is not the DefId of the TraitRef containing this
812 /// associated type, which is in tcx.associated_item(item_def_id).container.
813 pub item_def_id: DefId,
816 impl<'a, 'tcx> ProjectionTy<'tcx> {
817 /// Construct a ProjectionTy by searching the trait from trait_ref for the
818 /// associated item named item_name.
819 pub fn from_ref_and_name(
820 tcx: TyCtxt, trait_ref: ty::TraitRef<'tcx>, item_name: Name
821 ) -> ProjectionTy<'tcx> {
822 let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
823 item.kind == ty::AssociatedKind::Type &&
824 tcx.hygienic_eq(item_name, item.name, trait_ref.def_id)
828 substs: trait_ref.substs,
833 /// Extracts the underlying trait reference from this projection.
834 /// For example, if this is a projection of `<T as Iterator>::Item`,
835 /// then this function would return a `T: Iterator` trait reference.
836 pub fn trait_ref(&self, tcx: TyCtxt) -> ty::TraitRef<'tcx> {
837 let def_id = tcx.associated_item(self.item_def_id).container.id();
844 pub fn self_ty(&self) -> Ty<'tcx> {
845 self.substs.type_at(0)
849 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
850 pub struct GenSig<'tcx> {
851 pub yield_ty: Ty<'tcx>,
852 pub return_ty: Ty<'tcx>,
855 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
857 impl<'tcx> PolyGenSig<'tcx> {
858 pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
859 self.map_bound_ref(|sig| sig.yield_ty)
861 pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
862 self.map_bound_ref(|sig| sig.return_ty)
866 /// Signature of a function type, which I have arbitrarily
867 /// decided to use to refer to the input/output types.
869 /// - `inputs` is the list of arguments and their modes.
870 /// - `output` is the return type.
871 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
872 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
873 pub struct FnSig<'tcx> {
874 pub inputs_and_output: &'tcx Slice<Ty<'tcx>>,
876 pub unsafety: hir::Unsafety,
880 impl<'tcx> FnSig<'tcx> {
881 pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
882 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
885 pub fn output(&self) -> Ty<'tcx> {
886 self.inputs_and_output[self.inputs_and_output.len() - 1]
890 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
892 impl<'tcx> PolyFnSig<'tcx> {
893 pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
894 self.map_bound_ref(|fn_sig| fn_sig.inputs())
896 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
897 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
899 pub fn inputs_and_output(&self) -> ty::Binder<&'tcx Slice<Ty<'tcx>>> {
900 self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
902 pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
903 self.map_bound_ref(|fn_sig| fn_sig.output().clone())
905 pub fn variadic(&self) -> bool {
906 self.skip_binder().variadic
908 pub fn unsafety(&self) -> hir::Unsafety {
909 self.skip_binder().unsafety
911 pub fn abi(&self) -> abi::Abi {
912 self.skip_binder().abi
916 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
919 pub name: InternedString,
922 impl<'a, 'gcx, 'tcx> ParamTy {
923 pub fn new(index: u32, name: InternedString) -> ParamTy {
924 ParamTy { idx: index, name: name }
927 pub fn for_self() -> ParamTy {
928 ParamTy::new(0, keywords::SelfType.name().as_interned_str())
931 pub fn for_def(def: &ty::TypeParameterDef) -> ParamTy {
932 ParamTy::new(def.index, def.name)
935 pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
936 tcx.mk_param(self.idx, self.name)
939 pub fn is_self(&self) -> bool {
940 // FIXME(#50125): Ignoring `Self` with `idx != 0` might lead to weird behavior elsewhere,
941 // but this should only be possible when using `-Z continue-parse-after-error` like
942 // `compile-fail/issue-36638.rs`.
943 if self.name == keywords::SelfType.name().as_str() && self.idx == 0 {
951 /// A [De Bruijn index][dbi] is a standard means of representing
952 /// regions (and perhaps later types) in a higher-ranked setting. In
953 /// particular, imagine a type like this:
955 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
958 /// | +------------+ 1 | |
960 /// +--------------------------------+ 2 |
962 /// +------------------------------------------+ 1
964 /// In this type, there are two binders (the outer fn and the inner
965 /// fn). We need to be able to determine, for any given region, which
966 /// fn type it is bound by, the inner or the outer one. There are
967 /// various ways you can do this, but a De Bruijn index is one of the
968 /// more convenient and has some nice properties. The basic idea is to
969 /// count the number of binders, inside out. Some examples should help
970 /// clarify what I mean.
972 /// Let's start with the reference type `&'b isize` that is the first
973 /// argument to the inner function. This region `'b` is assigned a De
974 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
975 /// fn). The region `'a` that appears in the second argument type (`&'a
976 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
977 /// second-innermost binder". (These indices are written on the arrays
980 /// What is interesting is that De Bruijn index attached to a particular
981 /// variable will vary depending on where it appears. For example,
982 /// the final type `&'a char` also refers to the region `'a` declared on
983 /// the outermost fn. But this time, this reference is not nested within
984 /// any other binders (i.e., it is not an argument to the inner fn, but
985 /// rather the outer one). Therefore, in this case, it is assigned a
986 /// De Bruijn index of 1, because the innermost binder in that location
989 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
990 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy, PartialOrd, Ord)]
991 pub struct DebruijnIndex {
992 /// We maintain the invariant that this is never 0. So 1 indicates
993 /// the innermost binder. To ensure this, create with `DebruijnIndex::new`.
997 pub type Region<'tcx> = &'tcx RegionKind;
999 /// Representation of regions.
1001 /// Unlike types, most region variants are "fictitious", not concrete,
1002 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1003 /// ones representing concrete regions.
1005 /// ## Bound Regions
1007 /// These are regions that are stored behind a binder and must be substituted
1008 /// with some concrete region before being used. There are 2 kind of
1009 /// bound regions: early-bound, which are bound in an item's Generics,
1010 /// and are substituted by a Substs, and late-bound, which are part of
1011 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
1012 /// the likes of `liberate_late_bound_regions`. The distinction exists
1013 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1015 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
1016 /// outside their binder, e.g. in types passed to type inference, and
1017 /// should first be substituted (by skolemized regions, free regions,
1018 /// or region variables).
1020 /// ## Skolemized and Free Regions
1022 /// One often wants to work with bound regions without knowing their precise
1023 /// identity. For example, when checking a function, the lifetime of a borrow
1024 /// can end up being assigned to some region parameter. In these cases,
1025 /// it must be ensured that bounds on the region can't be accidentally
1026 /// assumed without being checked.
1028 /// The process of doing that is called "skolemization". The bound regions
1029 /// are replaced by skolemized markers, which don't satisfy any relation
1030 /// not explicitly provided.
1032 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
1033 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
1034 /// to be used. These also support explicit bounds: both the internally-stored
1035 /// *scope*, which the region is assumed to outlive, as well as other
1036 /// relations stored in the `FreeRegionMap`. Note that these relations
1037 /// aren't checked when you `make_subregion` (or `eq_types`), only by
1038 /// `resolve_regions_and_report_errors`.
1040 /// When working with higher-ranked types, some region relations aren't
1041 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1042 /// `ReSkolemized` is designed for this purpose. In these contexts,
1043 /// there's also the risk that some inference variable laying around will
1044 /// get unified with your skolemized region: if you want to check whether
1045 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1046 /// with a skolemized region `'%a`, the variable `'_` would just be
1047 /// instantiated to the skolemized region `'%a`, which is wrong because
1048 /// the inference variable is supposed to satisfy the relation
1049 /// *for every value of the skolemized region*. To ensure that doesn't
1050 /// happen, you can use `leak_check`. This is more clearly explained
1051 /// by the [rustc guide].
1053 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1054 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1055 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/trait-hrtb.html
1056 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1057 pub enum RegionKind {
1058 // Region bound in a type or fn declaration which will be
1059 // substituted 'early' -- that is, at the same time when type
1060 // parameters are substituted.
1061 ReEarlyBound(EarlyBoundRegion),
1063 // Region bound in a function scope, which will be substituted when the
1064 // function is called.
1065 ReLateBound(DebruijnIndex, BoundRegion),
1067 /// When checking a function body, the types of all arguments and so forth
1068 /// that refer to bound region parameters are modified to refer to free
1069 /// region parameters.
1072 /// A concrete region naming some statically determined scope
1073 /// (e.g. an expression or sequence of statements) within the
1074 /// current function.
1075 ReScope(region::Scope),
1077 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1080 /// A region variable. Should not exist after typeck.
1083 /// A skolemized region - basically the higher-ranked version of ReFree.
1084 /// Should not exist after typeck.
1085 ReSkolemized(ty::UniverseIndex, BoundRegion),
1087 /// Empty lifetime is for data that is never accessed.
1088 /// Bottom in the region lattice. We treat ReEmpty somewhat
1089 /// specially; at least right now, we do not generate instances of
1090 /// it during the GLB computations, but rather
1091 /// generate an error instead. This is to improve error messages.
1092 /// The only way to get an instance of ReEmpty is to have a region
1093 /// variable with no constraints.
1096 /// Erased region, used by trait selection, in MIR and during trans.
1099 /// These are regions bound in the "defining type" for a
1100 /// closure. They are used ONLY as part of the
1101 /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1102 /// See `ClosureRegionRequirements` for more details.
1103 ReClosureBound(RegionVid),
1105 /// Canonicalized region, used only when preparing a trait query.
1106 ReCanonical(CanonicalVar),
1109 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
1111 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1112 pub struct EarlyBoundRegion {
1115 pub name: InternedString,
1118 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1123 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1128 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1129 pub struct FloatVid {
1133 newtype_index!(RegionVid
1136 DEBUG_FORMAT = custom,
1139 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1145 /// A `FreshTy` is one that is generated as a replacement for an
1146 /// unbound type variable. This is convenient for caching etc. See
1147 /// `infer::freshen` for more details.
1152 /// Canonicalized type variable, used only when preparing a trait query.
1153 CanonicalTy(CanonicalVar),
1156 newtype_index!(CanonicalVar);
1158 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1159 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1160 pub struct ExistentialProjection<'tcx> {
1161 pub item_def_id: DefId,
1162 pub substs: &'tcx Substs<'tcx>,
1166 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1168 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
1169 /// Extracts the underlying existential trait reference from this projection.
1170 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1171 /// then this function would return a `exists T. T: Iterator` existential trait
1173 pub fn trait_ref(&self, tcx: TyCtxt) -> ty::ExistentialTraitRef<'tcx> {
1174 let def_id = tcx.associated_item(self.item_def_id).container.id();
1175 ty::ExistentialTraitRef{
1177 substs: self.substs,
1181 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1183 -> ty::ProjectionPredicate<'tcx>
1185 // otherwise the escaping regions would be captured by the binders
1186 assert!(!self_ty.has_escaping_regions());
1188 ty::ProjectionPredicate {
1189 projection_ty: ty::ProjectionTy {
1190 item_def_id: self.item_def_id,
1191 substs: tcx.mk_substs(
1192 iter::once(self_ty.into()).chain(self.substs.iter().cloned())),
1199 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
1200 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
1201 -> ty::PolyProjectionPredicate<'tcx> {
1202 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1205 pub fn item_def_id(&self) -> DefId {
1206 return self.skip_binder().item_def_id;
1210 impl DebruijnIndex {
1211 pub fn new(depth: u32) -> DebruijnIndex {
1213 DebruijnIndex { depth: depth }
1216 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
1217 DebruijnIndex { depth: self.depth + amount }
1221 /// Region utilities
1223 pub fn is_late_bound(&self) -> bool {
1225 ty::ReLateBound(..) => true,
1230 pub fn escapes_depth(&self, depth: u32) -> bool {
1232 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1237 /// Returns the depth of `self` from the (1-based) binding level `depth`
1238 pub fn from_depth(&self, depth: u32) -> RegionKind {
1240 ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
1241 depth: debruijn.depth - (depth - 1)
1247 pub fn keep_in_local_tcx(&self) -> bool {
1248 if let ty::ReVar(..) = self {
1255 pub fn type_flags(&self) -> TypeFlags {
1256 let mut flags = TypeFlags::empty();
1258 if self.keep_in_local_tcx() {
1259 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1264 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1265 flags = flags | TypeFlags::HAS_RE_INFER;
1267 ty::ReSkolemized(..) => {
1268 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1269 flags = flags | TypeFlags::HAS_RE_SKOL;
1271 ty::ReLateBound(..) => { }
1272 ty::ReEarlyBound(..) => {
1273 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1274 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1279 ty::ReScope { .. } => {
1280 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1284 ty::ReCanonical(..) => {
1285 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1286 flags = flags | TypeFlags::HAS_CANONICAL_VARS;
1288 ty::ReClosureBound(..) => {
1289 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1294 ty::ReStatic | ty::ReEmpty | ty::ReErased => (),
1295 _ => flags = flags | TypeFlags::HAS_LOCAL_NAMES,
1298 debug!("type_flags({:?}) = {:?}", self, flags);
1303 /// Given an early-bound or free region, returns the def-id where it was bound.
1304 /// For example, consider the regions in this snippet of code:
1308 /// ^^ -- early bound, declared on an impl
1310 /// fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1311 /// ^^ ^^ ^ anonymous, late-bound
1312 /// | early-bound, appears in where-clauses
1313 /// late-bound, appears only in fn args
1318 /// Here, `free_region_binding_scope('a)` would return the def-id
1319 /// of the impl, and for all the other highlighted regions, it
1320 /// would return the def-id of the function. In other cases (not shown), this
1321 /// function might return the def-id of a closure.
1322 pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_, '_, '_>) -> DefId {
1324 ty::ReEarlyBound(br) => {
1325 tcx.parent_def_id(br.def_id).unwrap()
1327 ty::ReFree(fr) => fr.scope,
1328 _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1334 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
1335 pub fn is_nil(&self) -> bool {
1337 TyTuple(ref tys) => tys.is_empty(),
1342 pub fn is_never(&self) -> bool {
1349 pub fn is_primitive(&self) -> bool {
1351 TyBool | TyChar | TyInt(_) | TyUint(_) | TyFloat(_) => true,
1356 pub fn is_ty_var(&self) -> bool {
1358 TyInfer(TyVar(_)) => true,
1363 pub fn is_ty_infer(&self) -> bool {
1370 pub fn is_phantom_data(&self) -> bool {
1371 if let TyAdt(def, _) = self.sty {
1372 def.is_phantom_data()
1378 pub fn is_bool(&self) -> bool { self.sty == TyBool }
1380 pub fn is_param(&self, index: u32) -> bool {
1382 ty::TyParam(ref data) => data.idx == index,
1387 pub fn is_self(&self) -> bool {
1389 TyParam(ref p) => p.is_self(),
1394 pub fn is_slice(&self) -> bool {
1396 TyRawPtr(TypeAndMut { ty, .. }) | TyRef(_, ty, _) => match ty.sty {
1397 TySlice(_) | TyStr => true,
1405 pub fn is_simd(&self) -> bool {
1407 TyAdt(def, _) => def.repr.simd(),
1412 pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1414 TyArray(ty, _) | TySlice(ty) => ty,
1415 TyStr => tcx.mk_mach_uint(ast::UintTy::U8),
1416 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1420 pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1422 TyAdt(def, substs) => {
1423 def.non_enum_variant().fields[0].ty(tcx, substs)
1425 _ => bug!("simd_type called on invalid type")
1429 pub fn simd_size(&self, _cx: TyCtxt) -> usize {
1431 TyAdt(def, _) => def.non_enum_variant().fields.len(),
1432 _ => bug!("simd_size called on invalid type")
1436 pub fn is_region_ptr(&self) -> bool {
1443 pub fn is_mutable_pointer(&self) -> bool {
1445 TyRawPtr(TypeAndMut { mutbl: hir::Mutability::MutMutable, .. }) |
1446 TyRef(_, _, hir::Mutability::MutMutable) => true,
1451 pub fn is_unsafe_ptr(&self) -> bool {
1453 TyRawPtr(_) => return true,
1458 pub fn is_box(&self) -> bool {
1460 TyAdt(def, _) => def.is_box(),
1465 /// panics if called on any type other than `Box<T>`
1466 pub fn boxed_ty(&self) -> Ty<'tcx> {
1468 TyAdt(def, substs) if def.is_box() => substs.type_at(0),
1469 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1473 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1474 /// (A TyRawPtr is scalar because it represents a non-managed pointer, so its
1475 /// contents are abstract to rustc.)
1476 pub fn is_scalar(&self) -> bool {
1478 TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
1479 TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
1480 TyFnDef(..) | TyFnPtr(_) | TyRawPtr(_) => true,
1485 /// Returns true if this type is a floating point type and false otherwise.
1486 pub fn is_floating_point(&self) -> bool {
1489 TyInfer(FloatVar(_)) => true,
1494 pub fn is_trait(&self) -> bool {
1496 TyDynamic(..) => true,
1501 pub fn is_enum(&self) -> bool {
1503 TyAdt(adt_def, _) => {
1510 pub fn is_closure(&self) -> bool {
1512 TyClosure(..) => true,
1517 pub fn is_generator(&self) -> bool {
1519 TyGenerator(..) => true,
1524 pub fn is_integral(&self) -> bool {
1526 TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
1531 pub fn is_fresh_ty(&self) -> bool {
1533 TyInfer(FreshTy(_)) => true,
1538 pub fn is_fresh(&self) -> bool {
1540 TyInfer(FreshTy(_)) => true,
1541 TyInfer(FreshIntTy(_)) => true,
1542 TyInfer(FreshFloatTy(_)) => true,
1547 pub fn is_char(&self) -> bool {
1554 pub fn is_fp(&self) -> bool {
1556 TyInfer(FloatVar(_)) | TyFloat(_) => true,
1561 pub fn is_numeric(&self) -> bool {
1562 self.is_integral() || self.is_fp()
1565 pub fn is_signed(&self) -> bool {
1572 pub fn is_machine(&self) -> bool {
1574 TyInt(ast::IntTy::Isize) | TyUint(ast::UintTy::Usize) => false,
1575 TyInt(..) | TyUint(..) | TyFloat(..) => true,
1580 pub fn has_concrete_skeleton(&self) -> bool {
1582 TyParam(_) | TyInfer(_) | TyError => false,
1587 /// Returns the type and mutability of *ty.
1589 /// The parameter `explicit` indicates if this is an *explicit* dereference.
1590 /// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1591 pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1593 TyAdt(def, _) if def.is_box() => {
1595 ty: self.boxed_ty(),
1596 mutbl: hir::MutImmutable,
1599 TyRef(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl }),
1600 TyRawPtr(mt) if explicit => Some(mt),
1605 /// Returns the type of `ty[i]`.
1606 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1608 TyArray(ty, _) | TySlice(ty) => Some(ty),
1613 pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1615 TyFnDef(def_id, substs) => {
1616 tcx.fn_sig(def_id).subst(tcx, substs)
1619 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1623 pub fn is_fn(&self) -> bool {
1625 TyFnDef(..) | TyFnPtr(_) => true,
1630 pub fn ty_to_def_id(&self) -> Option<DefId> {
1632 TyDynamic(ref tt, ..) => tt.principal().map(|p| p.def_id()),
1633 TyAdt(def, _) => Some(def.did),
1634 TyForeign(did) => Some(did),
1635 TyClosure(id, _) => Some(id),
1636 TyFnDef(id, _) => Some(id),
1641 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1643 TyAdt(adt, _) => Some(adt),
1648 /// Returns the regions directly referenced from this type (but
1649 /// not types reachable from this type via `walk_tys`). This
1650 /// ignores late-bound regions binders.
1651 pub fn regions(&self) -> Vec<ty::Region<'tcx>> {
1653 TyRef(region, _, _) => {
1656 TyDynamic(ref obj, region) => {
1657 let mut v = vec![region];
1658 if let Some(p) = obj.principal() {
1659 v.extend(p.skip_binder().substs.regions());
1663 TyAdt(_, substs) | TyAnon(_, substs) => {
1664 substs.regions().collect()
1666 TyClosure(_, ClosureSubsts { ref substs }) |
1667 TyGenerator(_, GeneratorSubsts { ref substs }, _) => {
1668 substs.regions().collect()
1670 TyProjection(ref data) => {
1671 data.substs.regions().collect()
1675 TyGeneratorWitness(..) |
1696 /// When we create a closure, we record its kind (i.e., what trait
1697 /// it implements) into its `ClosureSubsts` using a type
1698 /// parameter. This is kind of a phantom type, except that the
1699 /// most convenient thing for us to are the integral types. This
1700 /// function converts such a special type into the closure
1701 /// kind. To go the other way, use
1702 /// `tcx.closure_kind_ty(closure_kind)`.
1704 /// Note that during type checking, we use an inference variable
1705 /// to represent the closure kind, because it has not yet been
1706 /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
1707 /// is complete, that type variable will be unified.
1708 pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
1710 TyInt(int_ty) => match int_ty {
1711 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
1712 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1713 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1714 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1719 TyError => Some(ty::ClosureKind::Fn),
1721 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1726 /// Typed constant value.
1727 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Eq, PartialEq)]
1728 pub struct Const<'tcx> {
1731 pub val: ConstVal<'tcx>,
1734 impl<'tcx> Const<'tcx> {
1736 tcx: TyCtxt<'_, '_, 'tcx>,
1738 substs: &'tcx Substs<'tcx>,
1741 tcx.mk_const(Const {
1742 val: ConstVal::Unevaluated(def_id, substs),
1748 pub fn from_const_val(
1749 tcx: TyCtxt<'_, '_, 'tcx>,
1750 val: ConstVal<'tcx>,
1753 tcx.mk_const(Const {
1760 pub fn from_const_value(
1761 tcx: TyCtxt<'_, '_, 'tcx>,
1762 val: ConstValue<'tcx>,
1765 Self::from_const_val(tcx, ConstVal::Value(val), ty)
1770 tcx: TyCtxt<'_, '_, 'tcx>,
1771 alloc: &'tcx Allocation,
1774 Self::from_const_value(tcx, ConstValue::ByRef(alloc), ty)
1778 pub fn from_byval_value(
1779 tcx: TyCtxt<'_, '_, 'tcx>,
1783 Self::from_const_value(tcx, ConstValue::from_byval_value(val), ty)
1787 pub fn from_primval(
1788 tcx: TyCtxt<'_, '_, 'tcx>,
1792 Self::from_const_value(tcx, ConstValue::from_primval(val), ty)
1797 tcx: TyCtxt<'_, '_, 'tcx>,
1801 Self::from_primval(tcx, PrimVal::Bytes(val), ty)
1805 pub fn zero_sized(tcx: TyCtxt<'_, '_, 'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
1806 Self::from_primval(tcx, PrimVal::Undef, ty)
1810 pub fn from_bool(tcx: TyCtxt<'_, '_, 'tcx>, v: bool) -> &'tcx Self {
1811 Self::from_bits(tcx, v as u128, tcx.types.bool)
1815 pub fn from_usize(tcx: TyCtxt<'_, '_, 'tcx>, n: u64) -> &'tcx Self {
1816 Self::from_bits(tcx, n as u128, tcx.types.usize)
1820 pub fn to_bits(&self, ty: Ty<'_>) -> Option<u128> {
1825 ConstVal::Value(val) => val.to_bits(),
1831 pub fn to_ptr(&self) -> Option<MemoryPointer> {
1833 ConstVal::Value(val) => val.to_ptr(),
1839 pub fn to_primval(&self) -> Option<PrimVal> {
1841 ConstVal::Value(val) => val.to_primval(),
1847 pub fn assert_bits(&self, ty: Ty<'_>) -> Option<u128> {
1848 assert_eq!(self.ty, ty);
1850 ConstVal::Value(val) => val.to_bits(),
1856 pub fn assert_bool(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<bool> {
1857 self.assert_bits(tcx.types.bool).and_then(|v| match v {
1865 pub fn assert_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<u64> {
1866 self.assert_bits(tcx.types.usize).map(|v| v as u64)
1870 pub fn unwrap_bits(&self, ty: Ty<'_>) -> u128 {
1871 match self.assert_bits(ty) {
1873 None => bug!("expected bits of {}, got {:#?}", ty, self),
1878 pub fn unwrap_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> u64 {
1879 match self.assert_usize(tcx) {
1881 None => bug!("expected constant usize, got {:#?}", self),
1886 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}