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 middle::def_id::DefId;
15 use middle::subst::{self, Substs};
17 use middle::ty::{self, AdtDef, TypeFlags, Ty, TyS};
18 use middle::ty::{RegionEscape, ToPredicate};
19 use util::common::ErrorReported;
21 use collections::enum_set::{self, EnumSet, CLike};
26 use syntax::ast::{Name, NodeId};
30 use self::FnOutput::*;
32 use self::TypeVariants::*;
34 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
35 pub struct TypeAndMut<'tcx> {
37 pub mutbl: hir::Mutability,
40 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
41 RustcEncodable, RustcDecodable, Copy)]
42 /// A "free" region `fr` can be interpreted as "some region
43 /// at least as big as the scope `fr.scope`".
44 pub struct FreeRegion {
45 pub scope: region::CodeExtent,
46 pub bound_region: BoundRegion
49 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
50 RustcEncodable, RustcDecodable, Copy)]
51 pub enum BoundRegion {
52 /// An anonymous region parameter for a given fn (&T)
55 /// Named region parameters for functions (a in &'a T)
57 /// The def-id is needed to distinguish free regions in
58 /// the event of shadowing.
61 /// Fresh bound identifiers created during GLB computations.
64 // Anonymous region for the implicit env pointer parameter
69 // NB: If you change this, you'll probably want to change the corresponding
70 // AST structure in libsyntax/ast.rs as well.
71 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
72 pub enum TypeVariants<'tcx> {
73 /// The primitive boolean type. Written as `bool`.
76 /// The primitive character type; holds a Unicode scalar value
77 /// (a non-surrogate code point). Written as `char`.
80 /// A primitive signed integer type. For example, `i32`.
83 /// A primitive unsigned integer type. For example, `u32`.
86 /// A primitive floating-point type. For example, `f64`.
87 TyFloat(hir::FloatTy),
89 /// An enumerated type, defined with `enum`.
91 /// Substs here, possibly against intuition, *may* contain `TyParam`s.
92 /// That is, even after substitution it is possible that there are type
93 /// variables. This happens when the `TyEnum` corresponds to an enum
94 /// definition and not a concrete use of it. To get the correct `TyEnum`
95 /// from the tcx, use the `NodeId` from the `hir::Ty` and look it up in
96 /// the `ast_ty_to_ty_cache`. This is probably true for `TyStruct` as
98 TyEnum(AdtDef<'tcx>, &'tcx Substs<'tcx>),
100 /// A structure type, defined with `struct`.
102 /// See warning about substitutions for enumerated types.
103 TyStruct(AdtDef<'tcx>, &'tcx Substs<'tcx>),
105 /// `Box<T>`; this is nominally a struct in the documentation, but is
106 /// special-cased internally. For example, it is possible to implicitly
107 /// move the contents of a box out of that box, and methods of any type
108 /// can have type `Box<Self>`.
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>, usize),
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(&'tcx Region, TypeAndMut<'tcx>),
127 /// If the def-id is Some(_), then this is the type of a specific
128 /// fn item. Otherwise, if None(_), it a fn pointer type.
130 /// FIXME: Conflating function pointers and the type of a
131 /// function is probably a terrible idea; a function pointer is a
132 /// value with a specific type, but a function can be polymorphic
133 /// or dynamically dispatched.
134 TyBareFn(Option<DefId>, &'tcx BareFnTy<'tcx>),
136 /// A trait, defined with `trait`.
137 TyTrait(Box<TraitTy<'tcx>>),
139 /// The anonymous type of a closure. Used to represent the type of
141 TyClosure(DefId, Box<ClosureSubsts<'tcx>>),
143 /// A tuple type. For example, `(i32, bool)`.
144 TyTuple(Vec<Ty<'tcx>>),
146 /// The projection of an associated type. For example,
147 /// `<T as Trait<..>>::N`.
148 TyProjection(ProjectionTy<'tcx>),
150 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
153 /// A type variable used during type-checking.
156 /// A placeholder for a type which could not be computed; this is
157 /// propagated to avoid useless error messages.
161 /// A closure can be modeled as a struct that looks like:
163 /// struct Closure<'l0...'li, T0...Tj, U0...Uk> {
169 /// where 'l0...'li and T0...Tj are the lifetime and type parameters
170 /// in scope on the function that defined the closure, and U0...Uk are
171 /// type parameters representing the types of its upvars (borrowed, if
174 /// So, for example, given this function:
176 /// fn foo<'a, T>(data: &'a mut T) {
177 /// do(|| data.count += 1)
180 /// the type of the closure would be something like:
182 /// struct Closure<'a, T, U0> {
186 /// Note that the type of the upvar is not specified in the struct.
187 /// You may wonder how the impl would then be able to use the upvar,
188 /// if it doesn't know it's type? The answer is that the impl is
189 /// (conceptually) not fully generic over Closure but rather tied to
190 /// instances with the expected upvar types:
192 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
196 /// You can see that the *impl* fully specified the type of the upvar
197 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
198 /// (Here, I am assuming that `data` is mut-borrowed.)
200 /// Now, the last question you may ask is: Why include the upvar types
201 /// as extra type parameters? The reason for this design is that the
202 /// upvar types can reference lifetimes that are internal to the
203 /// creating function. In my example above, for example, the lifetime
204 /// `'b` represents the extent of the closure itself; this is some
205 /// subset of `foo`, probably just the extent of the call to the to
206 /// `do()`. If we just had the lifetime/type parameters from the
207 /// enclosing function, we couldn't name this lifetime `'b`. Note that
208 /// there can also be lifetimes in the types of the upvars themselves,
209 /// if one of them happens to be a reference to something that the
210 /// creating fn owns.
212 /// OK, you say, so why not create a more minimal set of parameters
213 /// that just includes the extra lifetime parameters? The answer is
214 /// primarily that it would be hard --- we don't know at the time when
215 /// we create the closure type what the full types of the upvars are,
216 /// nor do we know which are borrowed and which are not. In this
217 /// design, we can just supply a fresh type parameter and figure that
220 /// All right, you say, but why include the type parameters from the
221 /// original function then? The answer is that trans may need them
222 /// when monomorphizing, and they may not appear in the upvars. A
223 /// closure could capture no variables but still make use of some
224 /// in-scope type parameter with a bound (e.g., if our example above
225 /// had an extra `U: Default`, and the closure called `U::default()`).
227 /// There is another reason. This design (implicitly) prohibits
228 /// closures from capturing themselves (except via a trait
229 /// object). This simplifies closure inference considerably, since it
230 /// means that when we infer the kind of a closure or its upvars, we
231 /// don't have to handle cycles where the decisions we make for
232 /// closure C wind up influencing the decisions we ought to make for
233 /// closure C (which would then require fixed point iteration to
234 /// handle). Plus it fixes an ICE. :P
235 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
236 pub struct ClosureSubsts<'tcx> {
237 /// Lifetime and type parameters from the enclosing function.
238 /// These are separated out because trans wants to pass them around
239 /// when monomorphizing.
240 pub func_substs: &'tcx Substs<'tcx>,
242 /// The types of the upvars. The list parallels the freevars and
243 /// `upvar_borrows` lists. These are kept distinct so that we can
244 /// easily index into them.
245 pub upvar_tys: Vec<Ty<'tcx>>
248 #[derive(Clone, PartialEq, Eq, Hash)]
249 pub struct TraitTy<'tcx> {
250 pub principal: ty::PolyTraitRef<'tcx>,
251 pub bounds: ExistentialBounds<'tcx>,
254 impl<'tcx> TraitTy<'tcx> {
255 pub fn principal_def_id(&self) -> DefId {
256 self.principal.0.def_id
259 /// Object types don't have a self-type specified. Therefore, when
260 /// we convert the principal trait-ref into a normal trait-ref,
261 /// you must give *some* self-type. A common choice is `mk_err()`
262 /// or some skolemized type.
263 pub fn principal_trait_ref_with_self_ty(&self,
264 tcx: &ty::ctxt<'tcx>,
266 -> ty::PolyTraitRef<'tcx>
268 // otherwise the escaping regions would be captured by the binder
269 assert!(!self_ty.has_escaping_regions());
271 ty::Binder(TraitRef {
272 def_id: self.principal.0.def_id,
273 substs: tcx.mk_substs(self.principal.0.substs.with_self_ty(self_ty)),
277 pub fn projection_bounds_with_self_ty(&self,
278 tcx: &ty::ctxt<'tcx>,
280 -> Vec<ty::PolyProjectionPredicate<'tcx>>
282 // otherwise the escaping regions would be captured by the binders
283 assert!(!self_ty.has_escaping_regions());
285 self.bounds.projection_bounds.iter()
286 .map(|in_poly_projection_predicate| {
287 let in_projection_ty = &in_poly_projection_predicate.0.projection_ty;
288 let substs = tcx.mk_substs(in_projection_ty.trait_ref.substs.with_self_ty(self_ty));
289 let trait_ref = ty::TraitRef::new(in_projection_ty.trait_ref.def_id,
291 let projection_ty = ty::ProjectionTy {
292 trait_ref: trait_ref,
293 item_name: in_projection_ty.item_name
295 ty::Binder(ty::ProjectionPredicate {
296 projection_ty: projection_ty,
297 ty: in_poly_projection_predicate.0.ty
304 /// A complete reference to a trait. These take numerous guises in syntax,
305 /// but perhaps the most recognizable form is in a where clause:
309 /// This would be represented by a trait-reference where the def-id is the
310 /// def-id for the trait `Foo` and the substs defines `T` as parameter 0 in the
311 /// `SelfSpace` and `U` as parameter 0 in the `TypeSpace`.
313 /// Trait references also appear in object types like `Foo<U>`, but in
314 /// that case the `Self` parameter is absent from the substitutions.
316 /// Note that a `TraitRef` introduces a level of region binding, to
317 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
318 /// U>` or higher-ranked object types.
319 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
320 pub struct TraitRef<'tcx> {
322 pub substs: &'tcx Substs<'tcx>,
325 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
327 impl<'tcx> PolyTraitRef<'tcx> {
328 pub fn self_ty(&self) -> Ty<'tcx> {
332 pub fn def_id(&self) -> DefId {
336 pub fn substs(&self) -> &'tcx Substs<'tcx> {
337 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
341 pub fn input_types(&self) -> &[Ty<'tcx>] {
342 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
346 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
347 // Note that we preserve binding levels
348 Binder(ty::TraitPredicate { trait_ref: self.0.clone() })
352 /// Binder is a binder for higher-ranked lifetimes. It is part of the
353 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
354 /// (which would be represented by the type `PolyTraitRef ==
355 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
356 /// erase, or otherwise "discharge" these bound regions, we change the
357 /// type from `Binder<T>` to just `T` (see
358 /// e.g. `liberate_late_bound_regions`).
359 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
360 pub struct Binder<T>(pub T);
363 /// Skips the binder and returns the "bound" value. This is a
364 /// risky thing to do because it's easy to get confused about
365 /// debruijn indices and the like. It is usually better to
366 /// discharge the binder using `no_late_bound_regions` or
367 /// `replace_late_bound_regions` or something like
368 /// that. `skip_binder` is only valid when you are either
369 /// extracting data that has nothing to do with bound regions, you
370 /// are doing some sort of test that does not involve bound
371 /// regions, or you are being very careful about your depth
374 /// Some examples where `skip_binder` is reasonable:
375 /// - extracting the def-id from a PolyTraitRef;
376 /// - comparing the self type of a PolyTraitRef to see if it is equal to
377 /// a type parameter `X`, since the type `X` does not reference any regions
378 pub fn skip_binder(&self) -> &T {
382 pub fn as_ref(&self) -> Binder<&T> {
386 pub fn map_bound_ref<F,U>(&self, f: F) -> Binder<U>
387 where F: FnOnce(&T) -> U
389 self.as_ref().map_bound(f)
392 pub fn map_bound<F,U>(self, f: F) -> Binder<U>
393 where F: FnOnce(T) -> U
395 ty::Binder(f(self.0))
399 impl fmt::Debug for TypeFlags {
400 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
401 write!(f, "{}", self.bits)
405 /// Represents the projection of an associated type. In explicit UFCS
406 /// form this would be written `<T as Trait<..>>::N`.
407 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
408 pub struct ProjectionTy<'tcx> {
409 /// The trait reference `T as Trait<..>`.
410 pub trait_ref: ty::TraitRef<'tcx>,
412 /// The name `N` of the associated type.
416 impl<'tcx> ProjectionTy<'tcx> {
417 pub fn sort_key(&self) -> (DefId, Name) {
418 (self.trait_ref.def_id, self.item_name)
422 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
423 pub struct BareFnTy<'tcx> {
424 pub unsafety: hir::Unsafety,
426 pub sig: PolyFnSig<'tcx>,
429 #[derive(Clone, PartialEq, Eq, Hash)]
430 pub struct ClosureTy<'tcx> {
431 pub unsafety: hir::Unsafety,
433 pub sig: PolyFnSig<'tcx>,
436 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
437 pub enum FnOutput<'tcx> {
438 FnConverging(Ty<'tcx>),
442 impl<'tcx> FnOutput<'tcx> {
443 pub fn diverges(&self) -> bool {
447 pub fn unwrap(self) -> Ty<'tcx> {
449 ty::FnConverging(t) => t,
450 ty::FnDiverging => unreachable!()
454 pub fn unwrap_or(self, def: Ty<'tcx>) -> Ty<'tcx> {
456 ty::FnConverging(t) => t,
457 ty::FnDiverging => def
462 pub type PolyFnOutput<'tcx> = Binder<FnOutput<'tcx>>;
464 impl<'tcx> PolyFnOutput<'tcx> {
465 pub fn diverges(&self) -> bool {
470 /// Signature of a function type, which I have arbitrarily
471 /// decided to use to refer to the input/output types.
473 /// - `inputs` is the list of arguments and their modes.
474 /// - `output` is the return type.
475 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
476 #[derive(Clone, PartialEq, Eq, Hash)]
477 pub struct FnSig<'tcx> {
478 pub inputs: Vec<Ty<'tcx>>,
479 pub output: FnOutput<'tcx>,
483 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
485 impl<'tcx> PolyFnSig<'tcx> {
486 pub fn inputs(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
487 self.map_bound_ref(|fn_sig| fn_sig.inputs.clone())
489 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
490 self.map_bound_ref(|fn_sig| fn_sig.inputs[index])
492 pub fn output(&self) -> ty::Binder<FnOutput<'tcx>> {
493 self.map_bound_ref(|fn_sig| fn_sig.output.clone())
495 pub fn variadic(&self) -> bool {
496 self.skip_binder().variadic
500 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
502 pub space: subst::ParamSpace,
507 /// A [De Bruijn index][dbi] is a standard means of representing
508 /// regions (and perhaps later types) in a higher-ranked setting. In
509 /// particular, imagine a type like this:
511 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
514 /// | +------------+ 1 | |
516 /// +--------------------------------+ 2 |
518 /// +------------------------------------------+ 1
520 /// In this type, there are two binders (the outer fn and the inner
521 /// fn). We need to be able to determine, for any given region, which
522 /// fn type it is bound by, the inner or the outer one. There are
523 /// various ways you can do this, but a De Bruijn index is one of the
524 /// more convenient and has some nice properties. The basic idea is to
525 /// count the number of binders, inside out. Some examples should help
526 /// clarify what I mean.
528 /// Let's start with the reference type `&'b isize` that is the first
529 /// argument to the inner function. This region `'b` is assigned a De
530 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
531 /// fn). The region `'a` that appears in the second argument type (`&'a
532 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
533 /// second-innermost binder". (These indices are written on the arrays
536 /// What is interesting is that De Bruijn index attached to a particular
537 /// variable will vary depending on where it appears. For example,
538 /// the final type `&'a char` also refers to the region `'a` declared on
539 /// the outermost fn. But this time, this reference is not nested within
540 /// any other binders (i.e., it is not an argument to the inner fn, but
541 /// rather the outer one). Therefore, in this case, it is assigned a
542 /// De Bruijn index of 1, because the innermost binder in that location
545 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
546 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
547 pub struct DebruijnIndex {
548 // We maintain the invariant that this is never 0. So 1 indicates
549 // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
553 /// Representation of regions.
555 /// Unlike types, most region variants are "fictitious", not concrete,
556 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
557 /// ones representing concrete regions.
561 /// These are regions that are stored behind a binder and must be substituted
562 /// with some concrete region before being used. There are 2 kind of
563 /// bound regions: early-bound, which are bound in a TypeScheme/TraitDef,
564 /// and are substituted by a Substs, and late-bound, which are part of
565 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
566 /// the likes of `liberate_late_bound_regions`. The distinction exists
567 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
569 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
570 /// outside their binder, e.g. in types passed to type inference, and
571 /// should first be substituted (by skolemized regions, free regions,
572 /// or region variables).
574 /// ## Skolemized and Free Regions
576 /// One often wants to work with bound regions without knowing their precise
577 /// identity. For example, when checking a function, the lifetime of a borrow
578 /// can end up being assigned to some region parameter. In these cases,
579 /// it must be ensured that bounds on the region can't be accidentally
580 /// assumed without being checked.
582 /// The process of doing that is called "skolemization". The bound regions
583 /// are replaced by skolemized markers, which don't satisfy any relation
584 /// not explicity provided.
586 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
587 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
588 /// to be used. These also support explicit bounds: both the internally-stored
589 /// *scope*, which the region is assumed to outlive, as well as other
590 /// relations stored in the `FreeRegionMap`. Note that these relations
591 /// aren't checked when you `make_subregion` (or `mk_eqty`), only by
592 /// `resolve_regions_and_report_errors`.
594 /// When working with higher-ranked types, some region relations aren't
595 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
596 /// `ReSkolemized` is designed for this purpose. In these contexts,
597 /// there's also the risk that some inference variable laying around will
598 /// get unified with your skolemized region: if you want to check whether
599 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
600 /// with a skolemized region `'%a`, the variable `'_` would just be
601 /// instantiated to the skolemized region `'%a`, which is wrong because
602 /// the inference variable is supposed to satisfy the relation
603 /// *for every value of the skolemized region*. To ensure that doesn't
604 /// happen, you can use `leak_check`. This is more clearly explained
605 /// by infer/higher_ranked/README.md.
607 /// [1] http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
608 /// [2] http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
609 #[derive(Clone, PartialEq, Eq, Hash, Copy)]
611 // Region bound in a type or fn declaration which will be
612 // substituted 'early' -- that is, at the same time when type
613 // parameters are substituted.
614 ReEarlyBound(EarlyBoundRegion),
616 // Region bound in a function scope, which will be substituted when the
617 // function is called.
618 ReLateBound(DebruijnIndex, BoundRegion),
620 /// When checking a function body, the types of all arguments and so forth
621 /// that refer to bound region parameters are modified to refer to free
622 /// region parameters.
625 /// A concrete region naming some statically determined extent
626 /// (e.g. an expression or sequence of statements) within the
627 /// current function.
628 ReScope(region::CodeExtent),
630 /// Static data that has an "infinite" lifetime. Top in the region lattice.
633 /// A region variable. Should not exist after typeck.
636 /// A skolemized region - basically the higher-ranked version of ReFree.
637 /// Should not exist after typeck.
638 ReSkolemized(SkolemizedRegionVid, BoundRegion),
640 /// Empty lifetime is for data that is never accessed.
641 /// Bottom in the region lattice. We treat ReEmpty somewhat
642 /// specially; at least right now, we do not generate instances of
643 /// it during the GLB computations, but rather
644 /// generate an error instead. This is to improve error messages.
645 /// The only way to get an instance of ReEmpty is to have a region
646 /// variable with no constraints.
650 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
651 pub struct EarlyBoundRegion {
652 pub param_id: NodeId,
653 pub space: subst::ParamSpace,
658 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
663 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
668 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
669 pub struct FloatVid {
673 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
674 pub struct RegionVid {
678 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
679 pub struct SkolemizedRegionVid {
683 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
689 /// A `FreshTy` is one that is generated as a replacement for an
690 /// unbound type variable. This is convenient for caching etc. See
691 /// `middle::infer::freshen` for more details.
697 /// Bounds suitable for an existentially quantified type parameter
698 /// such as those that appear in object types or closure types.
699 #[derive(PartialEq, Eq, Hash, Clone)]
700 pub struct ExistentialBounds<'tcx> {
701 pub region_bound: ty::Region,
702 pub builtin_bounds: BuiltinBounds,
703 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
706 impl<'tcx> ExistentialBounds<'tcx> {
707 pub fn new(region_bound: ty::Region,
708 builtin_bounds: BuiltinBounds,
709 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>)
711 let mut projection_bounds = projection_bounds;
712 projection_bounds.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()));
714 region_bound: region_bound,
715 builtin_bounds: builtin_bounds,
716 projection_bounds: projection_bounds
721 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
722 pub struct BuiltinBounds(EnumSet<BuiltinBound>);
725 pub fn empty() -> BuiltinBounds {
726 BuiltinBounds(EnumSet::new())
729 pub fn iter(&self) -> enum_set::Iter<BuiltinBound> {
733 pub fn to_predicates<'tcx>(&self,
734 tcx: &ty::ctxt<'tcx>,
735 self_ty: Ty<'tcx>) -> Vec<ty::Predicate<'tcx>> {
736 self.iter().filter_map(|builtin_bound|
737 match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, self_ty) {
738 Ok(trait_ref) => Some(trait_ref.to_predicate()),
739 Err(ErrorReported) => { None }
745 impl ops::Deref for BuiltinBounds {
746 type Target = EnumSet<BuiltinBound>;
747 fn deref(&self) -> &Self::Target { &self.0 }
750 impl ops::DerefMut for BuiltinBounds {
751 fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
754 impl<'a> IntoIterator for &'a BuiltinBounds {
755 type Item = BuiltinBound;
756 type IntoIter = enum_set::Iter<BuiltinBound>;
757 fn into_iter(self) -> Self::IntoIter {
762 #[derive(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
765 pub enum BuiltinBound {
772 impl CLike for BuiltinBound {
773 fn to_usize(&self) -> usize {
776 fn from_usize(v: usize) -> BuiltinBound {
777 unsafe { mem::transmute(v) }
781 impl<'tcx> ty::ctxt<'tcx> {
782 pub fn try_add_builtin_trait(&self,
784 builtin_bounds: &mut EnumSet<BuiltinBound>)
787 //! Checks whether `trait_ref` refers to one of the builtin
788 //! traits, like `Send`, and adds the corresponding
789 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
790 //! is a builtin trait.
792 match self.lang_items.to_builtin_kind(trait_def_id) {
793 Some(bound) => { builtin_bounds.insert(bound); true }
800 pub fn new(depth: u32) -> DebruijnIndex {
802 DebruijnIndex { depth: depth }
805 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
806 DebruijnIndex { depth: self.depth + amount }
812 pub fn is_bound(&self) -> bool {
814 ty::ReEarlyBound(..) => true,
815 ty::ReLateBound(..) => true,
820 pub fn needs_infer(&self) -> bool {
822 ty::ReVar(..) | ty::ReSkolemized(..) => true,
827 pub fn escapes_depth(&self, depth: u32) -> bool {
829 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
834 /// Returns the depth of `self` from the (1-based) binding level `depth`
835 pub fn from_depth(&self, depth: u32) -> Region {
837 ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
838 depth: debruijn.depth - (depth - 1)
846 impl<'tcx> TyS<'tcx> {
847 pub fn is_nil(&self) -> bool {
849 TyTuple(ref tys) => tys.is_empty(),
854 pub fn is_empty(&self, _cx: &ty::ctxt) -> bool {
855 // FIXME(#24885): be smarter here
857 TyEnum(def, _) | TyStruct(def, _) => def.is_empty(),
862 pub fn is_ty_var(&self) -> bool {
864 TyInfer(TyVar(_)) => true,
869 pub fn is_bool(&self) -> bool { self.sty == TyBool }
871 pub fn is_self(&self) -> bool {
873 TyParam(ref p) => p.space == subst::SelfSpace,
878 fn is_slice(&self) -> bool {
880 TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
881 TySlice(_) | TyStr => true,
888 pub fn is_structural(&self) -> bool {
890 TyStruct(..) | TyTuple(_) | TyEnum(..) |
891 TyArray(..) | TyClosure(..) => true,
892 _ => self.is_slice() | self.is_trait()
897 pub fn is_simd(&self) -> bool {
899 TyStruct(def, _) => def.is_simd(),
904 pub fn sequence_element_type(&self, cx: &ty::ctxt<'tcx>) -> Ty<'tcx> {
906 TyArray(ty, _) | TySlice(ty) => ty,
907 TyStr => cx.mk_mach_uint(hir::TyU8),
908 _ => cx.sess.bug(&format!("sequence_element_type called on non-sequence value: {}",
913 pub fn simd_type(&self, cx: &ty::ctxt<'tcx>) -> Ty<'tcx> {
915 TyStruct(def, substs) => {
916 def.struct_variant().fields[0].ty(cx, substs)
918 _ => panic!("simd_type called on invalid type")
922 pub fn simd_size(&self, _cx: &ty::ctxt) -> usize {
924 TyStruct(def, _) => def.struct_variant().fields.len(),
925 _ => panic!("simd_size called on invalid type")
929 pub fn is_region_ptr(&self) -> bool {
936 pub fn is_unsafe_ptr(&self) -> bool {
938 TyRawPtr(_) => return true,
943 pub fn is_unique(&self) -> bool {
951 A scalar type is one that denotes an atomic datum, with no sub-components.
952 (A TyRawPtr is scalar because it represents a non-managed pointer, so its
953 contents are abstract to rustc.)
955 pub fn is_scalar(&self) -> bool {
957 TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
958 TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
959 TyBareFn(..) | TyRawPtr(_) => true,
964 /// Returns true if this type is a floating point type and false otherwise.
965 pub fn is_floating_point(&self) -> bool {
968 TyInfer(FloatVar(_)) => true,
973 pub fn is_trait(&self) -> bool {
980 pub fn is_integral(&self) -> bool {
982 TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
987 pub fn is_fresh(&self) -> bool {
989 TyInfer(FreshTy(_)) => true,
990 TyInfer(FreshIntTy(_)) => true,
991 TyInfer(FreshFloatTy(_)) => true,
996 pub fn is_uint(&self) -> bool {
998 TyInfer(IntVar(_)) | TyUint(hir::TyUs) => true,
1003 pub fn is_char(&self) -> bool {
1010 pub fn is_bare_fn(&self) -> bool {
1012 TyBareFn(..) => true,
1017 pub fn is_bare_fn_item(&self) -> bool {
1019 TyBareFn(Some(_), _) => true,
1024 pub fn is_fp(&self) -> bool {
1026 TyInfer(FloatVar(_)) | TyFloat(_) => true,
1031 pub fn is_numeric(&self) -> bool {
1032 self.is_integral() || self.is_fp()
1035 pub fn is_signed(&self) -> bool {
1042 pub fn is_machine(&self) -> bool {
1044 TyInt(hir::TyIs) | TyUint(hir::TyUs) => false,
1045 TyInt(..) | TyUint(..) | TyFloat(..) => true,
1050 // Returns the type and mutability of *ty.
1052 // The parameter `explicit` indicates if this is an *explicit* dereference.
1053 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1054 pub fn builtin_deref(&self, explicit: bool, pref: ty::LvaluePreference)
1055 -> Option<TypeAndMut<'tcx>>
1061 mutbl: if pref == ty::PreferMutLvalue {
1068 TyRef(_, mt) => Some(mt),
1069 TyRawPtr(mt) if explicit => Some(mt),
1074 // Returns the type of ty[i]
1075 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1077 TyArray(ty, _) | TySlice(ty) => Some(ty),
1082 pub fn fn_sig(&self) -> &'tcx PolyFnSig<'tcx> {
1084 TyBareFn(_, ref f) => &f.sig,
1085 _ => panic!("Ty::fn_sig() called on non-fn type: {:?}", self)
1089 /// Returns the ABI of the given function.
1090 pub fn fn_abi(&self) -> abi::Abi {
1092 TyBareFn(_, ref f) => f.abi,
1093 _ => panic!("Ty::fn_abi() called on non-fn type"),
1097 // Type accessors for substructures of types
1098 pub fn fn_args(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
1099 self.fn_sig().inputs()
1102 pub fn fn_ret(&self) -> Binder<FnOutput<'tcx>> {
1103 self.fn_sig().output()
1106 pub fn is_fn(&self) -> bool {
1108 TyBareFn(..) => true,
1113 pub fn ty_to_def_id(&self) -> Option<DefId> {
1115 TyTrait(ref tt) => Some(tt.principal_def_id()),
1117 TyEnum(def, _) => Some(def.did),
1118 TyClosure(id, _) => Some(id),
1123 pub fn ty_adt_def(&self) -> Option<AdtDef<'tcx>> {
1125 TyStruct(adt, _) | TyEnum(adt, _) => Some(adt),