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}
;
27 use syntax
::parse
::token
::special_idents
;
31 use self::FnOutput
::*;
33 use self::TypeVariants
::*;
35 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
36 pub struct TypeAndMut
<'tcx
> {
38 pub mutbl
: hir
::Mutability
,
41 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
42 RustcEncodable
, RustcDecodable
, Copy
)]
43 /// A "free" region `fr` can be interpreted as "some region
44 /// at least as big as the scope `fr.scope`".
45 pub struct FreeRegion
{
46 pub scope
: region
::CodeExtent
,
47 pub bound_region
: BoundRegion
50 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
51 RustcEncodable
, RustcDecodable
, Copy
)]
52 pub enum BoundRegion
{
53 /// An anonymous region parameter for a given fn (&T)
56 /// Named region parameters for functions (a in &'a T)
58 /// The def-id is needed to distinguish free regions in
59 /// the event of shadowing.
62 /// Fresh bound identifiers created during GLB computations.
65 // Anonymous region for the implicit env pointer parameter
70 // NB: If you change this, you'll probably want to change the corresponding
71 // AST structure in libsyntax/ast.rs as well.
72 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
73 pub enum TypeVariants
<'tcx
> {
74 /// The primitive boolean type. Written as `bool`.
77 /// The primitive character type; holds a Unicode scalar value
78 /// (a non-surrogate code point). Written as `char`.
81 /// A primitive signed integer type. For example, `i32`.
84 /// A primitive unsigned integer type. For example, `u32`.
87 /// A primitive floating-point type. For example, `f64`.
88 TyFloat(hir
::FloatTy
),
90 /// An enumerated type, defined with `enum`.
92 /// Substs here, possibly against intuition, *may* contain `TyParam`s.
93 /// That is, even after substitution it is possible that there are type
94 /// variables. This happens when the `TyEnum` corresponds to an enum
95 /// definition and not a concrete use of it. To get the correct `TyEnum`
96 /// from the tcx, use the `NodeId` from the `hir::Ty` and look it up in
97 /// the `ast_ty_to_ty_cache`. This is probably true for `TyStruct` as
99 TyEnum(AdtDef
<'tcx
>, &'tcx Substs
<'tcx
>),
101 /// A structure type, defined with `struct`.
103 /// See warning about substitutions for enumerated types.
104 TyStruct(AdtDef
<'tcx
>, &'tcx Substs
<'tcx
>),
106 /// `Box<T>`; this is nominally a struct in the documentation, but is
107 /// special-cased internally. For example, it is possible to implicitly
108 /// move the contents of a box out of that box, and methods of any type
109 /// can have type `Box<Self>`.
112 /// The pointee of a string slice. Written as `str`.
115 /// An array with the given length. Written as `[T; n]`.
116 TyArray(Ty
<'tcx
>, usize),
118 /// The pointee of an array slice. Written as `[T]`.
121 /// A raw pointer. Written as `*mut T` or `*const T`
122 TyRawPtr(TypeAndMut
<'tcx
>),
124 /// A reference; a pointer with an associated lifetime. Written as
125 /// `&a mut T` or `&'a T`.
126 TyRef(&'tcx Region
, TypeAndMut
<'tcx
>),
128 /// If the def-id is Some(_), then this is the type of a specific
129 /// fn item. Otherwise, if None(_), it a fn pointer type.
131 /// FIXME: Conflating function pointers and the type of a
132 /// function is probably a terrible idea; a function pointer is a
133 /// value with a specific type, but a function can be polymorphic
134 /// or dynamically dispatched.
135 TyBareFn(Option
<DefId
>, &'tcx BareFnTy
<'tcx
>),
137 /// A trait, defined with `trait`.
138 TyTrait(Box
<TraitTy
<'tcx
>>),
140 /// The anonymous type of a closure. Used to represent the type of
142 TyClosure(DefId
, Box
<ClosureSubsts
<'tcx
>>),
144 /// A tuple type. For example, `(i32, bool)`.
145 TyTuple(Vec
<Ty
<'tcx
>>),
147 /// The projection of an associated type. For example,
148 /// `<T as Trait<..>>::N`.
149 TyProjection(ProjectionTy
<'tcx
>),
151 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
154 /// A type variable used during type-checking.
157 /// A placeholder for a type which could not be computed; this is
158 /// propagated to avoid useless error messages.
162 /// A closure can be modeled as a struct that looks like:
164 /// struct Closure<'l0...'li, T0...Tj, U0...Uk> {
170 /// where 'l0...'li and T0...Tj are the lifetime and type parameters
171 /// in scope on the function that defined the closure, and U0...Uk are
172 /// type parameters representing the types of its upvars (borrowed, if
175 /// So, for example, given this function:
177 /// fn foo<'a, T>(data: &'a mut T) {
178 /// do(|| data.count += 1)
181 /// the type of the closure would be something like:
183 /// struct Closure<'a, T, U0> {
187 /// Note that the type of the upvar is not specified in the struct.
188 /// You may wonder how the impl would then be able to use the upvar,
189 /// if it doesn't know it's type? The answer is that the impl is
190 /// (conceptually) not fully generic over Closure but rather tied to
191 /// instances with the expected upvar types:
193 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
197 /// You can see that the *impl* fully specified the type of the upvar
198 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
199 /// (Here, I am assuming that `data` is mut-borrowed.)
201 /// Now, the last question you may ask is: Why include the upvar types
202 /// as extra type parameters? The reason for this design is that the
203 /// upvar types can reference lifetimes that are internal to the
204 /// creating function. In my example above, for example, the lifetime
205 /// `'b` represents the extent of the closure itself; this is some
206 /// subset of `foo`, probably just the extent of the call to the to
207 /// `do()`. If we just had the lifetime/type parameters from the
208 /// enclosing function, we couldn't name this lifetime `'b`. Note that
209 /// there can also be lifetimes in the types of the upvars themselves,
210 /// if one of them happens to be a reference to something that the
211 /// creating fn owns.
213 /// OK, you say, so why not create a more minimal set of parameters
214 /// that just includes the extra lifetime parameters? The answer is
215 /// primarily that it would be hard --- we don't know at the time when
216 /// we create the closure type what the full types of the upvars are,
217 /// nor do we know which are borrowed and which are not. In this
218 /// design, we can just supply a fresh type parameter and figure that
221 /// All right, you say, but why include the type parameters from the
222 /// original function then? The answer is that trans may need them
223 /// when monomorphizing, and they may not appear in the upvars. A
224 /// closure could capture no variables but still make use of some
225 /// in-scope type parameter with a bound (e.g., if our example above
226 /// had an extra `U: Default`, and the closure called `U::default()`).
228 /// There is another reason. This design (implicitly) prohibits
229 /// closures from capturing themselves (except via a trait
230 /// object). This simplifies closure inference considerably, since it
231 /// means that when we infer the kind of a closure or its upvars, we
232 /// don't have to handle cycles where the decisions we make for
233 /// closure C wind up influencing the decisions we ought to make for
234 /// closure C (which would then require fixed point iteration to
235 /// handle). Plus it fixes an ICE. :P
236 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
237 pub struct ClosureSubsts
<'tcx
> {
238 /// Lifetime and type parameters from the enclosing function.
239 /// These are separated out because trans wants to pass them around
240 /// when monomorphizing.
241 pub func_substs
: &'tcx Substs
<'tcx
>,
243 /// The types of the upvars. The list parallels the freevars and
244 /// `upvar_borrows` lists. These are kept distinct so that we can
245 /// easily index into them.
246 pub upvar_tys
: Vec
<Ty
<'tcx
>>
249 #[derive(Clone, PartialEq, Eq, Hash)]
250 pub struct TraitTy
<'tcx
> {
251 pub principal
: ty
::PolyTraitRef
<'tcx
>,
252 pub bounds
: ExistentialBounds
<'tcx
>,
255 impl<'tcx
> TraitTy
<'tcx
> {
256 pub fn principal_def_id(&self) -> DefId
{
257 self.principal
.0.def_id
260 /// Object types don't have a self-type specified. Therefore, when
261 /// we convert the principal trait-ref into a normal trait-ref,
262 /// you must give *some* self-type. A common choice is `mk_err()`
263 /// or some skolemized type.
264 pub fn principal_trait_ref_with_self_ty(&self,
265 tcx
: &ty
::ctxt
<'tcx
>,
267 -> ty
::PolyTraitRef
<'tcx
>
269 // otherwise the escaping regions would be captured by the binder
270 assert
!(!self_ty
.has_escaping_regions());
272 ty
::Binder(TraitRef
{
273 def_id
: self.principal
.0.def_id
,
274 substs
: tcx
.mk_substs(self.principal
.0.substs
.with_self_ty(self_ty
)),
278 pub fn projection_bounds_with_self_ty(&self,
279 tcx
: &ty
::ctxt
<'tcx
>,
281 -> Vec
<ty
::PolyProjectionPredicate
<'tcx
>>
283 // otherwise the escaping regions would be captured by the binders
284 assert
!(!self_ty
.has_escaping_regions());
286 self.bounds
.projection_bounds
.iter()
287 .map(|in_poly_projection_predicate
| {
288 let in_projection_ty
= &in_poly_projection_predicate
.0.projection_ty
;
289 let substs
= tcx
.mk_substs(in_projection_ty
.trait_ref
.substs
.with_self_ty(self_ty
));
290 let trait_ref
= ty
::TraitRef
::new(in_projection_ty
.trait_ref
.def_id
,
292 let projection_ty
= ty
::ProjectionTy
{
293 trait_ref
: trait_ref
,
294 item_name
: in_projection_ty
.item_name
296 ty
::Binder(ty
::ProjectionPredicate
{
297 projection_ty
: projection_ty
,
298 ty
: in_poly_projection_predicate
.0.ty
305 /// A complete reference to a trait. These take numerous guises in syntax,
306 /// but perhaps the most recognizable form is in a where clause:
310 /// This would be represented by a trait-reference where the def-id is the
311 /// def-id for the trait `Foo` and the substs defines `T` as parameter 0 in the
312 /// `SelfSpace` and `U` as parameter 0 in the `TypeSpace`.
314 /// Trait references also appear in object types like `Foo<U>`, but in
315 /// that case the `Self` parameter is absent from the substitutions.
317 /// Note that a `TraitRef` introduces a level of region binding, to
318 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
319 /// U>` or higher-ranked object types.
320 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
321 pub struct TraitRef
<'tcx
> {
323 pub substs
: &'tcx Substs
<'tcx
>,
326 pub type PolyTraitRef
<'tcx
> = Binder
<TraitRef
<'tcx
>>;
328 impl<'tcx
> PolyTraitRef
<'tcx
> {
329 pub fn self_ty(&self) -> Ty
<'tcx
> {
333 pub fn def_id(&self) -> DefId
{
337 pub fn substs(&self) -> &'tcx Substs
<'tcx
> {
338 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
342 pub fn input_types(&self) -> &[Ty
<'tcx
>] {
343 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
347 pub fn to_poly_trait_predicate(&self) -> ty
::PolyTraitPredicate
<'tcx
> {
348 // Note that we preserve binding levels
349 Binder(ty
::TraitPredicate { trait_ref: self.0.clone() }
)
353 /// Binder is a binder for higher-ranked lifetimes. It is part of the
354 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
355 /// (which would be represented by the type `PolyTraitRef ==
356 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
357 /// erase, or otherwise "discharge" these bound regions, we change the
358 /// type from `Binder<T>` to just `T` (see
359 /// e.g. `liberate_late_bound_regions`).
360 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
361 pub struct Binder
<T
>(pub T
);
364 /// Skips the binder and returns the "bound" value. This is a
365 /// risky thing to do because it's easy to get confused about
366 /// debruijn indices and the like. It is usually better to
367 /// discharge the binder using `no_late_bound_regions` or
368 /// `replace_late_bound_regions` or something like
369 /// that. `skip_binder` is only valid when you are either
370 /// extracting data that has nothing to do with bound regions, you
371 /// are doing some sort of test that does not involve bound
372 /// regions, or you are being very careful about your depth
375 /// Some examples where `skip_binder` is reasonable:
376 /// - extracting the def-id from a PolyTraitRef;
377 /// - comparing the self type of a PolyTraitRef to see if it is equal to
378 /// a type parameter `X`, since the type `X` does not reference any regions
379 pub fn skip_binder(&self) -> &T
{
383 pub fn as_ref(&self) -> Binder
<&T
> {
387 pub fn map_bound_ref
<F
,U
>(&self, f
: F
) -> Binder
<U
>
388 where F
: FnOnce(&T
) -> U
390 self.as_ref().map_bound(f
)
393 pub fn map_bound
<F
,U
>(self, f
: F
) -> Binder
<U
>
394 where F
: FnOnce(T
) -> U
396 ty
::Binder(f(self.0))
400 impl fmt
::Debug
for TypeFlags
{
401 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
402 write
!(f
, "{}", self.bits
)
406 /// Represents the projection of an associated type. In explicit UFCS
407 /// form this would be written `<T as Trait<..>>::N`.
408 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
409 pub struct ProjectionTy
<'tcx
> {
410 /// The trait reference `T as Trait<..>`.
411 pub trait_ref
: ty
::TraitRef
<'tcx
>,
413 /// The name `N` of the associated type.
417 impl<'tcx
> ProjectionTy
<'tcx
> {
418 pub fn sort_key(&self) -> (DefId
, Name
) {
419 (self.trait_ref
.def_id
, self.item_name
)
423 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
424 pub struct BareFnTy
<'tcx
> {
425 pub unsafety
: hir
::Unsafety
,
427 pub sig
: PolyFnSig
<'tcx
>,
430 #[derive(Clone, PartialEq, Eq, Hash)]
431 pub struct ClosureTy
<'tcx
> {
432 pub unsafety
: hir
::Unsafety
,
434 pub sig
: PolyFnSig
<'tcx
>,
437 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
438 pub enum FnOutput
<'tcx
> {
439 FnConverging(Ty
<'tcx
>),
443 impl<'tcx
> FnOutput
<'tcx
> {
444 pub fn diverges(&self) -> bool
{
448 pub fn unwrap(self) -> Ty
<'tcx
> {
450 ty
::FnConverging(t
) => t
,
451 ty
::FnDiverging
=> unreachable
!()
455 pub fn unwrap_or(self, def
: Ty
<'tcx
>) -> Ty
<'tcx
> {
457 ty
::FnConverging(t
) => t
,
458 ty
::FnDiverging
=> def
463 pub type PolyFnOutput
<'tcx
> = Binder
<FnOutput
<'tcx
>>;
465 impl<'tcx
> PolyFnOutput
<'tcx
> {
466 pub fn diverges(&self) -> bool
{
471 /// Signature of a function type, which I have arbitrarily
472 /// decided to use to refer to the input/output types.
474 /// - `inputs` is the list of arguments and their modes.
475 /// - `output` is the return type.
476 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
477 #[derive(Clone, PartialEq, Eq, Hash)]
478 pub struct FnSig
<'tcx
> {
479 pub inputs
: Vec
<Ty
<'tcx
>>,
480 pub output
: FnOutput
<'tcx
>,
484 pub type PolyFnSig
<'tcx
> = Binder
<FnSig
<'tcx
>>;
486 impl<'tcx
> PolyFnSig
<'tcx
> {
487 pub fn inputs(&self) -> ty
::Binder
<Vec
<Ty
<'tcx
>>> {
488 self.map_bound_ref(|fn_sig
| fn_sig
.inputs
.clone())
490 pub fn input(&self, index
: usize) -> ty
::Binder
<Ty
<'tcx
>> {
491 self.map_bound_ref(|fn_sig
| fn_sig
.inputs
[index
])
493 pub fn output(&self) -> ty
::Binder
<FnOutput
<'tcx
>> {
494 self.map_bound_ref(|fn_sig
| fn_sig
.output
.clone())
496 pub fn variadic(&self) -> bool
{
497 self.skip_binder().variadic
501 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
503 pub space
: subst
::ParamSpace
,
509 pub fn new(space
: subst
::ParamSpace
,
513 ParamTy { space: space, idx: index, name: name }
516 pub fn for_self() -> ParamTy
{
517 ParamTy
::new(subst
::SelfSpace
, 0, special_idents
::type_self
.name
)
520 pub fn for_def(def
: &ty
::TypeParameterDef
) -> ParamTy
{
521 ParamTy
::new(def
.space
, def
.index
, def
.name
)
524 pub fn to_ty
<'tcx
>(self, tcx
: &ty
::ctxt
<'tcx
>) -> Ty
<'tcx
> {
525 tcx
.mk_param(self.space
, self.idx
, self.name
)
528 pub fn is_self(&self) -> bool
{
529 self.space
== subst
::SelfSpace
&& self.idx
== 0
533 /// A [De Bruijn index][dbi] is a standard means of representing
534 /// regions (and perhaps later types) in a higher-ranked setting. In
535 /// particular, imagine a type like this:
537 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
540 /// | +------------+ 1 | |
542 /// +--------------------------------+ 2 |
544 /// +------------------------------------------+ 1
546 /// In this type, there are two binders (the outer fn and the inner
547 /// fn). We need to be able to determine, for any given region, which
548 /// fn type it is bound by, the inner or the outer one. There are
549 /// various ways you can do this, but a De Bruijn index is one of the
550 /// more convenient and has some nice properties. The basic idea is to
551 /// count the number of binders, inside out. Some examples should help
552 /// clarify what I mean.
554 /// Let's start with the reference type `&'b isize` that is the first
555 /// argument to the inner function. This region `'b` is assigned a De
556 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
557 /// fn). The region `'a` that appears in the second argument type (`&'a
558 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
559 /// second-innermost binder". (These indices are written on the arrays
562 /// What is interesting is that De Bruijn index attached to a particular
563 /// variable will vary depending on where it appears. For example,
564 /// the final type `&'a char` also refers to the region `'a` declared on
565 /// the outermost fn. But this time, this reference is not nested within
566 /// any other binders (i.e., it is not an argument to the inner fn, but
567 /// rather the outer one). Therefore, in this case, it is assigned a
568 /// De Bruijn index of 1, because the innermost binder in that location
571 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
572 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
573 pub struct DebruijnIndex
{
574 // We maintain the invariant that this is never 0. So 1 indicates
575 // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
579 /// Representation of regions.
581 /// Unlike types, most region variants are "fictitious", not concrete,
582 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
583 /// ones representing concrete regions.
587 /// These are regions that are stored behind a binder and must be substituted
588 /// with some concrete region before being used. There are 2 kind of
589 /// bound regions: early-bound, which are bound in a TypeScheme/TraitDef,
590 /// and are substituted by a Substs, and late-bound, which are part of
591 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
592 /// the likes of `liberate_late_bound_regions`. The distinction exists
593 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
595 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
596 /// outside their binder, e.g. in types passed to type inference, and
597 /// should first be substituted (by skolemized regions, free regions,
598 /// or region variables).
600 /// ## Skolemized and Free Regions
602 /// One often wants to work with bound regions without knowing their precise
603 /// identity. For example, when checking a function, the lifetime of a borrow
604 /// can end up being assigned to some region parameter. In these cases,
605 /// it must be ensured that bounds on the region can't be accidentally
606 /// assumed without being checked.
608 /// The process of doing that is called "skolemization". The bound regions
609 /// are replaced by skolemized markers, which don't satisfy any relation
610 /// not explicity provided.
612 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
613 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
614 /// to be used. These also support explicit bounds: both the internally-stored
615 /// *scope*, which the region is assumed to outlive, as well as other
616 /// relations stored in the `FreeRegionMap`. Note that these relations
617 /// aren't checked when you `make_subregion` (or `mk_eqty`), only by
618 /// `resolve_regions_and_report_errors`.
620 /// When working with higher-ranked types, some region relations aren't
621 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
622 /// `ReSkolemized` is designed for this purpose. In these contexts,
623 /// there's also the risk that some inference variable laying around will
624 /// get unified with your skolemized region: if you want to check whether
625 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
626 /// with a skolemized region `'%a`, the variable `'_` would just be
627 /// instantiated to the skolemized region `'%a`, which is wrong because
628 /// the inference variable is supposed to satisfy the relation
629 /// *for every value of the skolemized region*. To ensure that doesn't
630 /// happen, you can use `leak_check`. This is more clearly explained
631 /// by infer/higher_ranked/README.md.
633 /// [1] http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
634 /// [2] http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
635 #[derive(Clone, PartialEq, Eq, Hash, Copy)]
637 // Region bound in a type or fn declaration which will be
638 // substituted 'early' -- that is, at the same time when type
639 // parameters are substituted.
640 ReEarlyBound(EarlyBoundRegion
),
642 // Region bound in a function scope, which will be substituted when the
643 // function is called.
644 ReLateBound(DebruijnIndex
, BoundRegion
),
646 /// When checking a function body, the types of all arguments and so forth
647 /// that refer to bound region parameters are modified to refer to free
648 /// region parameters.
651 /// A concrete region naming some statically determined extent
652 /// (e.g. an expression or sequence of statements) within the
653 /// current function.
654 ReScope(region
::CodeExtent
),
656 /// Static data that has an "infinite" lifetime. Top in the region lattice.
659 /// A region variable. Should not exist after typeck.
662 /// A skolemized region - basically the higher-ranked version of ReFree.
663 /// Should not exist after typeck.
664 ReSkolemized(SkolemizedRegionVid
, BoundRegion
),
666 /// Empty lifetime is for data that is never accessed.
667 /// Bottom in the region lattice. We treat ReEmpty somewhat
668 /// specially; at least right now, we do not generate instances of
669 /// it during the GLB computations, but rather
670 /// generate an error instead. This is to improve error messages.
671 /// The only way to get an instance of ReEmpty is to have a region
672 /// variable with no constraints.
676 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
677 pub struct EarlyBoundRegion
{
678 pub param_id
: NodeId
,
679 pub space
: subst
::ParamSpace
,
684 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
689 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
694 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
695 pub struct FloatVid
{
699 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
700 pub struct RegionVid
{
704 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
705 pub struct SkolemizedRegionVid
{
709 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
715 /// A `FreshTy` is one that is generated as a replacement for an
716 /// unbound type variable. This is convenient for caching etc. See
717 /// `middle::infer::freshen` for more details.
723 /// Bounds suitable for an existentially quantified type parameter
724 /// such as those that appear in object types or closure types.
725 #[derive(PartialEq, Eq, Hash, Clone)]
726 pub struct ExistentialBounds
<'tcx
> {
727 pub region_bound
: ty
::Region
,
728 pub builtin_bounds
: BuiltinBounds
,
729 pub projection_bounds
: Vec
<ty
::PolyProjectionPredicate
<'tcx
>>,
732 impl<'tcx
> ExistentialBounds
<'tcx
> {
733 pub fn new(region_bound
: ty
::Region
,
734 builtin_bounds
: BuiltinBounds
,
735 projection_bounds
: Vec
<ty
::PolyProjectionPredicate
<'tcx
>>)
737 let mut projection_bounds
= projection_bounds
;
738 projection_bounds
.sort_by(|a
, b
| a
.sort_key().cmp(&b
.sort_key()));
740 region_bound
: region_bound
,
741 builtin_bounds
: builtin_bounds
,
742 projection_bounds
: projection_bounds
747 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
748 pub struct BuiltinBounds(EnumSet
<BuiltinBound
>);
751 pub fn empty() -> BuiltinBounds
{
752 BuiltinBounds(EnumSet
::new())
755 pub fn iter(&self) -> enum_set
::Iter
<BuiltinBound
> {
759 pub fn to_predicates
<'tcx
>(&self,
760 tcx
: &ty
::ctxt
<'tcx
>,
761 self_ty
: Ty
<'tcx
>) -> Vec
<ty
::Predicate
<'tcx
>> {
762 self.iter().filter_map(|builtin_bound
|
763 match traits
::trait_ref_for_builtin_bound(tcx
, builtin_bound
, self_ty
) {
764 Ok(trait_ref
) => Some(trait_ref
.to_predicate()),
765 Err(ErrorReported
) => { None }
771 impl ops
::Deref
for BuiltinBounds
{
772 type Target
= EnumSet
<BuiltinBound
>;
773 fn deref(&self) -> &Self::Target { &self.0 }
776 impl ops
::DerefMut
for BuiltinBounds
{
777 fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
780 impl<'a
> IntoIterator
for &'a BuiltinBounds
{
781 type Item
= BuiltinBound
;
782 type IntoIter
= enum_set
::Iter
<BuiltinBound
>;
783 fn into_iter(self) -> Self::IntoIter
{
788 #[derive(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
791 pub enum BuiltinBound
{
798 impl CLike
for BuiltinBound
{
799 fn to_usize(&self) -> usize {
802 fn from_usize(v
: usize) -> BuiltinBound
{
803 unsafe { mem::transmute(v) }
807 impl<'tcx
> ty
::ctxt
<'tcx
> {
808 pub fn try_add_builtin_trait(&self,
810 builtin_bounds
: &mut EnumSet
<BuiltinBound
>)
813 //! Checks whether `trait_ref` refers to one of the builtin
814 //! traits, like `Send`, and adds the corresponding
815 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
816 //! is a builtin trait.
818 match self.lang_items
.to_builtin_kind(trait_def_id
) {
819 Some(bound
) => { builtin_bounds.insert(bound); true }
826 pub fn new(depth
: u32) -> DebruijnIndex
{
828 DebruijnIndex { depth: depth }
831 pub fn shifted(&self, amount
: u32) -> DebruijnIndex
{
832 DebruijnIndex { depth: self.depth + amount }
838 pub fn is_bound(&self) -> bool
{
840 ty
::ReEarlyBound(..) => true,
841 ty
::ReLateBound(..) => true,
846 pub fn needs_infer(&self) -> bool
{
848 ty
::ReVar(..) | ty
::ReSkolemized(..) => true,
853 pub fn escapes_depth(&self, depth
: u32) -> bool
{
855 ty
::ReLateBound(debruijn
, _
) => debruijn
.depth
> depth
,
860 /// Returns the depth of `self` from the (1-based) binding level `depth`
861 pub fn from_depth(&self, depth
: u32) -> Region
{
863 ty
::ReLateBound(debruijn
, r
) => ty
::ReLateBound(DebruijnIndex
{
864 depth
: debruijn
.depth
- (depth
- 1)
872 impl<'tcx
> TyS
<'tcx
> {
873 pub fn as_opt_param_ty(&self) -> Option
<ty
::ParamTy
> {
875 ty
::TyParam(ref d
) => Some(d
.clone()),
880 pub fn is_nil(&self) -> bool
{
882 TyTuple(ref tys
) => tys
.is_empty(),
887 pub fn is_empty(&self, _cx
: &ty
::ctxt
) -> bool
{
888 // FIXME(#24885): be smarter here
890 TyEnum(def
, _
) | TyStruct(def
, _
) => def
.is_empty(),
895 pub fn is_ty_var(&self) -> bool
{
897 TyInfer(TyVar(_
)) => true,
902 pub fn is_bool(&self) -> bool { self.sty == TyBool }
904 pub fn is_param(&self, space
: subst
::ParamSpace
, index
: u32) -> bool
{
906 ty
::TyParam(ref data
) => data
.space
== space
&& data
.idx
== index
,
911 pub fn is_self(&self) -> bool
{
913 TyParam(ref p
) => p
.space
== subst
::SelfSpace
,
918 fn is_slice(&self) -> bool
{
920 TyRawPtr(mt
) | TyRef(_
, mt
) => match mt
.ty
.sty
{
921 TySlice(_
) | TyStr
=> true,
928 pub fn is_structural(&self) -> bool
{
930 TyStruct(..) | TyTuple(_
) | TyEnum(..) |
931 TyArray(..) | TyClosure(..) => true,
932 _
=> self.is_slice() | self.is_trait()
937 pub fn is_simd(&self) -> bool
{
939 TyStruct(def
, _
) => def
.is_simd(),
944 pub fn sequence_element_type(&self, cx
: &ty
::ctxt
<'tcx
>) -> Ty
<'tcx
> {
946 TyArray(ty
, _
) | TySlice(ty
) => ty
,
947 TyStr
=> cx
.mk_mach_uint(hir
::TyU8
),
948 _
=> cx
.sess
.bug(&format
!("sequence_element_type called on non-sequence value: {}",
953 pub fn simd_type(&self, cx
: &ty
::ctxt
<'tcx
>) -> Ty
<'tcx
> {
955 TyStruct(def
, substs
) => {
956 def
.struct_variant().fields
[0].ty(cx
, substs
)
958 _
=> panic
!("simd_type called on invalid type")
962 pub fn simd_size(&self, _cx
: &ty
::ctxt
) -> usize {
964 TyStruct(def
, _
) => def
.struct_variant().fields
.len(),
965 _
=> panic
!("simd_size called on invalid type")
969 pub fn is_region_ptr(&self) -> bool
{
976 pub fn is_unsafe_ptr(&self) -> bool
{
978 TyRawPtr(_
) => return true,
983 pub fn is_unique(&self) -> bool
{
991 A scalar type is one that denotes an atomic datum, with no sub-components.
992 (A TyRawPtr is scalar because it represents a non-managed pointer, so its
993 contents are abstract to rustc.)
995 pub fn is_scalar(&self) -> bool
{
997 TyBool
| TyChar
| TyInt(_
) | TyFloat(_
) | TyUint(_
) |
998 TyInfer(IntVar(_
)) | TyInfer(FloatVar(_
)) |
999 TyBareFn(..) | TyRawPtr(_
) => true,
1004 /// Returns true if this type is a floating point type and false otherwise.
1005 pub fn is_floating_point(&self) -> bool
{
1008 TyInfer(FloatVar(_
)) => true,
1013 pub fn is_trait(&self) -> bool
{
1015 TyTrait(..) => true,
1020 pub fn is_integral(&self) -> bool
{
1022 TyInfer(IntVar(_
)) | TyInt(_
) | TyUint(_
) => true,
1027 pub fn is_fresh(&self) -> bool
{
1029 TyInfer(FreshTy(_
)) => true,
1030 TyInfer(FreshIntTy(_
)) => true,
1031 TyInfer(FreshFloatTy(_
)) => true,
1036 pub fn is_uint(&self) -> bool
{
1038 TyInfer(IntVar(_
)) | TyUint(hir
::TyUs
) => true,
1043 pub fn is_char(&self) -> bool
{
1050 pub fn is_bare_fn(&self) -> bool
{
1052 TyBareFn(..) => true,
1057 pub fn is_bare_fn_item(&self) -> bool
{
1059 TyBareFn(Some(_
), _
) => true,
1064 pub fn is_fp(&self) -> bool
{
1066 TyInfer(FloatVar(_
)) | TyFloat(_
) => true,
1071 pub fn is_numeric(&self) -> bool
{
1072 self.is_integral() || self.is_fp()
1075 pub fn is_signed(&self) -> bool
{
1082 pub fn is_machine(&self) -> bool
{
1084 TyInt(hir
::TyIs
) | TyUint(hir
::TyUs
) => false,
1085 TyInt(..) | TyUint(..) | TyFloat(..) => true,
1090 // Returns the type and mutability of *ty.
1092 // The parameter `explicit` indicates if this is an *explicit* dereference.
1093 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1094 pub fn builtin_deref(&self, explicit
: bool
, pref
: ty
::LvaluePreference
)
1095 -> Option
<TypeAndMut
<'tcx
>>
1101 mutbl
: if pref
== ty
::PreferMutLvalue
{
1108 TyRef(_
, mt
) => Some(mt
),
1109 TyRawPtr(mt
) if explicit
=> Some(mt
),
1114 // Returns the type of ty[i]
1115 pub fn builtin_index(&self) -> Option
<Ty
<'tcx
>> {
1117 TyArray(ty
, _
) | TySlice(ty
) => Some(ty
),
1122 pub fn fn_sig(&self) -> &'tcx PolyFnSig
<'tcx
> {
1124 TyBareFn(_
, ref f
) => &f
.sig
,
1125 _
=> panic
!("Ty::fn_sig() called on non-fn type: {:?}", self)
1129 /// Returns the ABI of the given function.
1130 pub fn fn_abi(&self) -> abi
::Abi
{
1132 TyBareFn(_
, ref f
) => f
.abi
,
1133 _
=> panic
!("Ty::fn_abi() called on non-fn type"),
1137 // Type accessors for substructures of types
1138 pub fn fn_args(&self) -> ty
::Binder
<Vec
<Ty
<'tcx
>>> {
1139 self.fn_sig().inputs()
1142 pub fn fn_ret(&self) -> Binder
<FnOutput
<'tcx
>> {
1143 self.fn_sig().output()
1146 pub fn is_fn(&self) -> bool
{
1148 TyBareFn(..) => true,
1153 pub fn ty_to_def_id(&self) -> Option
<DefId
> {
1155 TyTrait(ref tt
) => Some(tt
.principal_def_id()),
1157 TyEnum(def
, _
) => Some(def
.did
),
1158 TyClosure(id
, _
) => Some(id
),
1163 pub fn ty_adt_def(&self) -> Option
<AdtDef
<'tcx
>> {
1165 TyStruct(adt
, _
) | TyEnum(adt
, _
) => Some(adt
),
1170 /// Returns the regions directly referenced from this type (but
1171 /// not types reachable from this type via `walk_tys`). This
1172 /// ignores late-bound regions binders.
1173 pub fn regions(&self) -> Vec
<ty
::Region
> {
1175 TyRef(region
, _
) => {
1178 TyTrait(ref obj
) => {
1179 let mut v
= vec
![obj
.bounds
.region_bound
];
1180 v
.push_all(obj
.principal
.skip_binder().substs
.regions().as_slice());
1184 TyStruct(_
, substs
) => {
1185 substs
.regions().as_slice().to_vec()
1187 TyClosure(_
, ref substs
) => {
1188 substs
.func_substs
.regions().as_slice().to_vec()
1190 TyProjection(ref data
) => {
1191 data
.trait_ref
.substs
.regions().as_slice().to_vec()