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
;
14 use hir
::map
::DefPathHash
;
17 use ty
::subst
::Substs
;
18 use ty
::{self, AdtDef, TypeFlags, Ty, TyCtxt, TypeFoldable}
;
24 use std
::cmp
::Ordering
;
26 use syntax
::ast
::{self, Name}
;
27 use syntax
::symbol
::{keywords, InternedString}
;
28 use util
::nodemap
::FxHashMap
;
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.
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 /// When a region changed from late-bound to early-bound when #32330
82 /// was fixed, its `RegionParameterDef` will have one of these
83 /// structures that we can use to give nicer errors.
84 #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash,
85 RustcEncodable
, RustcDecodable
)]
86 pub struct Issue32330
{
87 /// fn where is region declared
90 /// name of region; duplicates the info in BrNamed but convenient
91 /// to have it here, and this code is only temporary
92 pub region_name
: ast
::Name
,
95 /// NB: If you change this, you'll probably want to change the corresponding
96 /// AST structure in libsyntax/ast.rs as well.
97 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
98 pub enum TypeVariants
<'tcx
> {
99 /// The primitive boolean type. Written as `bool`.
102 /// The primitive character type; holds a Unicode scalar value
103 /// (a non-surrogate code point). Written as `char`.
106 /// A primitive signed integer type. For example, `i32`.
109 /// A primitive unsigned integer type. For example, `u32`.
112 /// A primitive floating-point type. For example, `f64`.
113 TyFloat(ast
::FloatTy
),
115 /// Structures, enumerations and unions.
117 /// Substs here, possibly against intuition, *may* contain `TyParam`s.
118 /// That is, even after substitution it is possible that there are type
119 /// variables. This happens when the `TyAdt` corresponds to an ADT
120 /// definition and not a concrete use of it.
121 TyAdt(&'tcx AdtDef
, &'tcx Substs
<'tcx
>),
123 /// The pointee of a string slice. Written as `str`.
126 /// An array with the given length. Written as `[T; n]`.
127 TyArray(Ty
<'tcx
>, usize),
129 /// The pointee of an array slice. Written as `[T]`.
132 /// A raw pointer. Written as `*mut T` or `*const T`
133 TyRawPtr(TypeAndMut
<'tcx
>),
135 /// A reference; a pointer with an associated lifetime. Written as
136 /// `&'a mut T` or `&'a T`.
137 TyRef(Region
<'tcx
>, TypeAndMut
<'tcx
>),
139 /// The anonymous type of a function declaration/definition. Each
140 /// function has a unique type.
141 TyFnDef(DefId
, &'tcx Substs
<'tcx
>, PolyFnSig
<'tcx
>),
143 /// A pointer to a function. Written as `fn() -> i32`.
144 TyFnPtr(PolyFnSig
<'tcx
>),
146 /// A trait, defined with `trait`.
147 TyDynamic(Binder
<&'tcx Slice
<ExistentialPredicate
<'tcx
>>>, ty
::Region
<'tcx
>),
149 /// The anonymous type of a closure. Used to represent the type of
151 TyClosure(DefId
, ClosureSubsts
<'tcx
>),
153 /// The never type `!`
156 /// A tuple type. For example, `(i32, bool)`.
157 /// The bool indicates whether this is a unit tuple and was created by
158 /// defaulting a diverging type variable with feature(never_type) disabled.
159 /// It's only purpose is for raising future-compatibility warnings for when
160 /// diverging type variables start defaulting to ! instead of ().
161 TyTuple(&'tcx Slice
<Ty
<'tcx
>>, bool
),
163 /// The projection of an associated type. For example,
164 /// `<T as Trait<..>>::N`.
165 TyProjection(ProjectionTy
<'tcx
>),
167 /// Anonymized (`impl Trait`) type found in a return type.
168 /// The DefId comes from the `impl Trait` ast::Ty node, and the
169 /// substitutions are for the generics of the function in question.
170 /// After typeck, the concrete type can be found in the `types` map.
171 TyAnon(DefId
, &'tcx Substs
<'tcx
>),
173 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
176 /// A type variable used during type-checking.
179 /// A placeholder for a type which could not be computed; this is
180 /// propagated to avoid useless error messages.
184 /// A closure can be modeled as a struct that looks like:
186 /// struct Closure<'l0...'li, T0...Tj, U0...Uk> {
192 /// where 'l0...'li and T0...Tj are the lifetime and type parameters
193 /// in scope on the function that defined the closure, and U0...Uk are
194 /// type parameters representing the types of its upvars (borrowed, if
197 /// So, for example, given this function:
199 /// fn foo<'a, T>(data: &'a mut T) {
200 /// do(|| data.count += 1)
203 /// the type of the closure would be something like:
205 /// struct Closure<'a, T, U0> {
209 /// Note that the type of the upvar is not specified in the struct.
210 /// You may wonder how the impl would then be able to use the upvar,
211 /// if it doesn't know it's type? The answer is that the impl is
212 /// (conceptually) not fully generic over Closure but rather tied to
213 /// instances with the expected upvar types:
215 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
219 /// You can see that the *impl* fully specified the type of the upvar
220 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
221 /// (Here, I am assuming that `data` is mut-borrowed.)
223 /// Now, the last question you may ask is: Why include the upvar types
224 /// as extra type parameters? The reason for this design is that the
225 /// upvar types can reference lifetimes that are internal to the
226 /// creating function. In my example above, for example, the lifetime
227 /// `'b` represents the extent of the closure itself; this is some
228 /// subset of `foo`, probably just the extent of the call to the to
229 /// `do()`. If we just had the lifetime/type parameters from the
230 /// enclosing function, we couldn't name this lifetime `'b`. Note that
231 /// there can also be lifetimes in the types of the upvars themselves,
232 /// if one of them happens to be a reference to something that the
233 /// creating fn owns.
235 /// OK, you say, so why not create a more minimal set of parameters
236 /// that just includes the extra lifetime parameters? The answer is
237 /// primarily that it would be hard --- we don't know at the time when
238 /// we create the closure type what the full types of the upvars are,
239 /// nor do we know which are borrowed and which are not. In this
240 /// design, we can just supply a fresh type parameter and figure that
243 /// All right, you say, but why include the type parameters from the
244 /// original function then? The answer is that trans may need them
245 /// when monomorphizing, and they may not appear in the upvars. A
246 /// closure could capture no variables but still make use of some
247 /// in-scope type parameter with a bound (e.g., if our example above
248 /// had an extra `U: Default`, and the closure called `U::default()`).
250 /// There is another reason. This design (implicitly) prohibits
251 /// closures from capturing themselves (except via a trait
252 /// object). This simplifies closure inference considerably, since it
253 /// means that when we infer the kind of a closure or its upvars, we
254 /// don't have to handle cycles where the decisions we make for
255 /// closure C wind up influencing the decisions we ought to make for
256 /// closure C (which would then require fixed point iteration to
257 /// handle). Plus it fixes an ICE. :P
258 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
259 pub struct ClosureSubsts
<'tcx
> {
260 /// Lifetime and type parameters from the enclosing function,
261 /// concatenated with the types of the upvars.
263 /// These are separated out because trans wants to pass them around
264 /// when monomorphizing.
265 pub substs
: &'tcx Substs
<'tcx
>,
268 impl<'a
, 'gcx
, 'acx
, 'tcx
> ClosureSubsts
<'tcx
> {
270 pub fn upvar_tys(self, def_id
: DefId
, tcx
: TyCtxt
<'a
, 'gcx
, 'acx
>) ->
271 impl Iterator
<Item
=Ty
<'tcx
>> + 'tcx
273 let generics
= tcx
.generics_of(def_id
);
274 self.substs
[self.substs
.len()-generics
.own_count()..].iter().map(
275 |t
| t
.as_type().expect("unexpected region in upvars"))
279 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
280 pub enum ExistentialPredicate
<'tcx
> {
282 Trait(ExistentialTraitRef
<'tcx
>),
283 /// e.g. Iterator::Item = T
284 Projection(ExistentialProjection
<'tcx
>),
289 impl<'a
, 'gcx
, 'tcx
> ExistentialPredicate
<'tcx
> {
290 pub fn cmp(&self, tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>, other
: &Self) -> Ordering
{
291 use self::ExistentialPredicate
::*;
292 match (*self, *other
) {
293 (Trait(_
), Trait(_
)) => Ordering
::Equal
,
294 (Projection(ref a
), Projection(ref b
)) => a
.sort_key(tcx
).cmp(&b
.sort_key(tcx
)),
295 (AutoTrait(ref a
), AutoTrait(ref b
)) =>
296 tcx
.trait_def(*a
).def_path_hash
.cmp(&tcx
.trait_def(*b
).def_path_hash
),
297 (Trait(_
), _
) => Ordering
::Less
,
298 (Projection(_
), Trait(_
)) => Ordering
::Greater
,
299 (Projection(_
), _
) => Ordering
::Less
,
300 (AutoTrait(_
), _
) => Ordering
::Greater
,
306 impl<'a
, 'gcx
, 'tcx
> Binder
<ExistentialPredicate
<'tcx
>> {
307 pub fn with_self_ty(&self, tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>, self_ty
: Ty
<'tcx
>)
308 -> ty
::Predicate
<'tcx
> {
310 match *self.skip_binder() {
311 ExistentialPredicate
::Trait(tr
) => Binder(tr
).with_self_ty(tcx
, self_ty
).to_predicate(),
312 ExistentialPredicate
::Projection(p
) =>
313 ty
::Predicate
::Projection(Binder(p
.with_self_ty(tcx
, self_ty
))),
314 ExistentialPredicate
::AutoTrait(did
) => {
315 let trait_ref
= Binder(ty
::TraitRef
{
317 substs
: tcx
.mk_substs_trait(self_ty
, &[]),
319 trait_ref
.to_predicate()
325 impl<'tcx
> serialize
::UseSpecializedDecodable
for &'tcx Slice
<ExistentialPredicate
<'tcx
>> {}
327 impl<'tcx
> Slice
<ExistentialPredicate
<'tcx
>> {
328 pub fn principal(&self) -> Option
<ExistentialTraitRef
<'tcx
>> {
330 Some(&ExistentialPredicate
::Trait(tr
)) => Some(tr
),
336 pub fn projection_bounds
<'a
>(&'a
self) ->
337 impl Iterator
<Item
=ExistentialProjection
<'tcx
>> + 'a
{
338 self.iter().filter_map(|predicate
| {
340 ExistentialPredicate
::Projection(p
) => Some(p
),
347 pub fn auto_traits
<'a
>(&'a
self) -> impl Iterator
<Item
=DefId
> + 'a
{
348 self.iter().filter_map(|predicate
| {
350 ExistentialPredicate
::AutoTrait(d
) => Some(d
),
357 impl<'tcx
> Binder
<&'tcx Slice
<ExistentialPredicate
<'tcx
>>> {
358 pub fn principal(&self) -> Option
<PolyExistentialTraitRef
<'tcx
>> {
359 self.skip_binder().principal().map(Binder
)
363 pub fn projection_bounds
<'a
>(&'a
self) ->
364 impl Iterator
<Item
=PolyExistentialProjection
<'tcx
>> + 'a
{
365 self.skip_binder().projection_bounds().map(Binder
)
369 pub fn auto_traits
<'a
>(&'a
self) -> impl Iterator
<Item
=DefId
> + 'a
{
370 self.skip_binder().auto_traits()
373 pub fn iter
<'a
>(&'a
self)
374 -> impl DoubleEndedIterator
<Item
=Binder
<ExistentialPredicate
<'tcx
>>> + 'tcx
{
375 self.skip_binder().iter().cloned().map(Binder
)
379 /// A complete reference to a trait. These take numerous guises in syntax,
380 /// but perhaps the most recognizable form is in a where clause:
384 /// This would be represented by a trait-reference where the def-id is the
385 /// def-id for the trait `Foo` and the substs define `T` as parameter 0,
386 /// and `U` as parameter 1.
388 /// Trait references also appear in object types like `Foo<U>`, but in
389 /// that case the `Self` parameter is absent from the substitutions.
391 /// Note that a `TraitRef` introduces a level of region binding, to
392 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
393 /// U>` or higher-ranked object types.
394 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
395 pub struct TraitRef
<'tcx
> {
397 pub substs
: &'tcx Substs
<'tcx
>,
400 impl<'tcx
> TraitRef
<'tcx
> {
401 pub fn new(def_id
: DefId
, substs
: &'tcx Substs
<'tcx
>) -> TraitRef
<'tcx
> {
402 TraitRef { def_id: def_id, substs: substs }
405 pub fn self_ty(&self) -> Ty
<'tcx
> {
406 self.substs
.type_at(0)
409 pub fn input_types
<'a
>(&'a
self) -> impl DoubleEndedIterator
<Item
=Ty
<'tcx
>> + 'a
{
410 // Select only the "input types" from a trait-reference. For
411 // now this is all the types that appear in the
412 // trait-reference, but it should eventually exclude
418 pub type PolyTraitRef
<'tcx
> = Binder
<TraitRef
<'tcx
>>;
420 impl<'tcx
> PolyTraitRef
<'tcx
> {
421 pub fn self_ty(&self) -> Ty
<'tcx
> {
425 pub fn def_id(&self) -> DefId
{
429 pub fn substs(&self) -> &'tcx Substs
<'tcx
> {
430 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
434 pub fn input_types
<'a
>(&'a
self) -> impl DoubleEndedIterator
<Item
=Ty
<'tcx
>> + 'a
{
435 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
439 pub fn to_poly_trait_predicate(&self) -> ty
::PolyTraitPredicate
<'tcx
> {
440 // Note that we preserve binding levels
441 Binder(ty
::TraitPredicate { trait_ref: self.0.clone() }
)
445 /// An existential reference to a trait, where `Self` is erased.
446 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
448 /// exists T. T: Trait<'a, 'b, X, Y>
450 /// The substitutions don't include the erased `Self`, only trait
451 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
452 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
453 pub struct ExistentialTraitRef
<'tcx
> {
455 pub substs
: &'tcx Substs
<'tcx
>,
458 impl<'a
, 'gcx
, 'tcx
> ExistentialTraitRef
<'tcx
> {
459 pub fn input_types
<'b
>(&'b
self) -> impl DoubleEndedIterator
<Item
=Ty
<'tcx
>> + 'b
{
460 // Select only the "input types" from a trait-reference. For
461 // now this is all the types that appear in the
462 // trait-reference, but it should eventually exclude
467 /// Object types don't have a self-type specified. Therefore, when
468 /// we convert the principal trait-ref into a normal trait-ref,
469 /// you must give *some* self-type. A common choice is `mk_err()`
470 /// or some skolemized type.
471 pub fn with_self_ty(&self, tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>, self_ty
: Ty
<'tcx
>)
472 -> ty
::TraitRef
<'tcx
> {
473 // otherwise the escaping regions would be captured by the binder
474 assert
!(!self_ty
.has_escaping_regions());
478 substs
: tcx
.mk_substs(
479 iter
::once(Kind
::from(self_ty
)).chain(self.substs
.iter().cloned()))
484 pub type PolyExistentialTraitRef
<'tcx
> = Binder
<ExistentialTraitRef
<'tcx
>>;
486 impl<'tcx
> PolyExistentialTraitRef
<'tcx
> {
487 pub fn def_id(&self) -> DefId
{
491 pub fn input_types
<'a
>(&'a
self) -> impl DoubleEndedIterator
<Item
=Ty
<'tcx
>> + 'a
{
492 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
497 /// Binder is a binder for higher-ranked lifetimes. It is part of the
498 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
499 /// (which would be represented by the type `PolyTraitRef ==
500 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
501 /// erase, or otherwise "discharge" these bound regions, we change the
502 /// type from `Binder<T>` to just `T` (see
503 /// e.g. `liberate_late_bound_regions`).
504 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
505 pub struct Binder
<T
>(pub T
);
508 /// Skips the binder and returns the "bound" value. This is a
509 /// risky thing to do because it's easy to get confused about
510 /// debruijn indices and the like. It is usually better to
511 /// discharge the binder using `no_late_bound_regions` or
512 /// `replace_late_bound_regions` or something like
513 /// that. `skip_binder` is only valid when you are either
514 /// extracting data that has nothing to do with bound regions, you
515 /// are doing some sort of test that does not involve bound
516 /// regions, or you are being very careful about your depth
519 /// Some examples where `skip_binder` is reasonable:
520 /// - extracting the def-id from a PolyTraitRef;
521 /// - comparing the self type of a PolyTraitRef to see if it is equal to
522 /// a type parameter `X`, since the type `X` does not reference any regions
523 pub fn skip_binder(&self) -> &T
{
527 pub fn as_ref(&self) -> Binder
<&T
> {
531 pub fn map_bound_ref
<F
, U
>(&self, f
: F
) -> Binder
<U
>
532 where F
: FnOnce(&T
) -> U
534 self.as_ref().map_bound(f
)
537 pub fn map_bound
<F
, U
>(self, f
: F
) -> Binder
<U
>
538 where F
: FnOnce(T
) -> U
540 ty
::Binder(f(self.0))
544 impl fmt
::Debug
for TypeFlags
{
545 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
546 write
!(f
, "{:x}", self.bits
)
550 /// Represents the projection of an associated type. In explicit UFCS
551 /// form this would be written `<T as Trait<..>>::N`.
552 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
553 pub struct ProjectionTy
<'tcx
> {
554 /// The trait reference `T as Trait<..>`.
555 pub trait_ref
: ty
::TraitRef
<'tcx
>,
557 /// The DefId of the TraitItem for the associated type N.
559 /// Note that this is not the DefId of the TraitRef containing this
560 /// associated type, which is in tcx.associated_item(item_def_id).container.
561 pub item_def_id
: DefId
,
564 impl<'a
, 'tcx
> ProjectionTy
<'tcx
> {
565 /// Construct a ProjectionTy by searching the trait from trait_ref for the
566 /// associated item named item_name.
567 pub fn from_ref_and_name(
568 tcx
: TyCtxt
, trait_ref
: ty
::TraitRef
<'tcx
>, item_name
: Name
569 ) -> ProjectionTy
<'tcx
> {
570 let item_def_id
= tcx
.associated_items(trait_ref
.def_id
).find(
571 |item
| item
.name
== item_name
).unwrap().def_id
;
574 trait_ref
: trait_ref
,
575 item_def_id
: item_def_id
,
579 pub fn item_name(self, tcx
: TyCtxt
) -> Name
{
580 tcx
.associated_item(self.item_def_id
).name
585 /// Signature of a function type, which I have arbitrarily
586 /// decided to use to refer to the input/output types.
588 /// - `inputs` is the list of arguments and their modes.
589 /// - `output` is the return type.
590 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
591 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
592 pub struct FnSig
<'tcx
> {
593 pub inputs_and_output
: &'tcx Slice
<Ty
<'tcx
>>,
595 pub unsafety
: hir
::Unsafety
,
599 impl<'tcx
> FnSig
<'tcx
> {
600 pub fn inputs(&self) -> &'tcx
[Ty
<'tcx
>] {
601 &self.inputs_and_output
[..self.inputs_and_output
.len() - 1]
604 pub fn output(&self) -> Ty
<'tcx
> {
605 self.inputs_and_output
[self.inputs_and_output
.len() - 1]
609 pub type PolyFnSig
<'tcx
> = Binder
<FnSig
<'tcx
>>;
611 impl<'tcx
> PolyFnSig
<'tcx
> {
612 pub fn inputs(&self) -> Binder
<&'tcx
[Ty
<'tcx
>]> {
613 Binder(self.skip_binder().inputs())
615 pub fn input(&self, index
: usize) -> ty
::Binder
<Ty
<'tcx
>> {
616 self.map_bound_ref(|fn_sig
| fn_sig
.inputs()[index
])
618 pub fn output(&self) -> ty
::Binder
<Ty
<'tcx
>> {
619 self.map_bound_ref(|fn_sig
| fn_sig
.output().clone())
621 pub fn variadic(&self) -> bool
{
622 self.skip_binder().variadic
624 pub fn unsafety(&self) -> hir
::Unsafety
{
625 self.skip_binder().unsafety
627 pub fn abi(&self) -> abi
::Abi
{
628 self.skip_binder().abi
632 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
638 impl<'a
, 'gcx
, 'tcx
> ParamTy
{
639 pub fn new(index
: u32, name
: Name
) -> ParamTy
{
640 ParamTy { idx: index, name: name }
643 pub fn for_self() -> ParamTy
{
644 ParamTy
::new(0, keywords
::SelfType
.name())
647 pub fn for_def(def
: &ty
::TypeParameterDef
) -> ParamTy
{
648 ParamTy
::new(def
.index
, def
.name
)
651 pub fn to_ty(self, tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>) -> Ty
<'tcx
> {
652 tcx
.mk_param(self.idx
, self.name
)
655 pub fn is_self(&self) -> bool
{
656 if self.name
== keywords
::SelfType
.name() {
657 assert_eq
!(self.idx
, 0);
665 /// A [De Bruijn index][dbi] is a standard means of representing
666 /// regions (and perhaps later types) in a higher-ranked setting. In
667 /// particular, imagine a type like this:
669 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
672 /// | +------------+ 1 | |
674 /// +--------------------------------+ 2 |
676 /// +------------------------------------------+ 1
678 /// In this type, there are two binders (the outer fn and the inner
679 /// fn). We need to be able to determine, for any given region, which
680 /// fn type it is bound by, the inner or the outer one. There are
681 /// various ways you can do this, but a De Bruijn index is one of the
682 /// more convenient and has some nice properties. The basic idea is to
683 /// count the number of binders, inside out. Some examples should help
684 /// clarify what I mean.
686 /// Let's start with the reference type `&'b isize` that is the first
687 /// argument to the inner function. This region `'b` is assigned a De
688 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
689 /// fn). The region `'a` that appears in the second argument type (`&'a
690 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
691 /// second-innermost binder". (These indices are written on the arrays
694 /// What is interesting is that De Bruijn index attached to a particular
695 /// variable will vary depending on where it appears. For example,
696 /// the final type `&'a char` also refers to the region `'a` declared on
697 /// the outermost fn. But this time, this reference is not nested within
698 /// any other binders (i.e., it is not an argument to the inner fn, but
699 /// rather the outer one). Therefore, in this case, it is assigned a
700 /// De Bruijn index of 1, because the innermost binder in that location
703 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
704 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
705 pub struct DebruijnIndex
{
706 /// We maintain the invariant that this is never 0. So 1 indicates
707 /// the innermost binder. To ensure this, create with `DebruijnIndex::new`.
711 pub type Region
<'tcx
> = &'tcx RegionKind
;
713 /// Representation of regions.
715 /// Unlike types, most region variants are "fictitious", not concrete,
716 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
717 /// ones representing concrete regions.
721 /// These are regions that are stored behind a binder and must be substituted
722 /// with some concrete region before being used. There are 2 kind of
723 /// bound regions: early-bound, which are bound in an item's Generics,
724 /// and are substituted by a Substs, and late-bound, which are part of
725 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
726 /// the likes of `liberate_late_bound_regions`. The distinction exists
727 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
729 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
730 /// outside their binder, e.g. in types passed to type inference, and
731 /// should first be substituted (by skolemized regions, free regions,
732 /// or region variables).
734 /// ## Skolemized and Free Regions
736 /// One often wants to work with bound regions without knowing their precise
737 /// identity. For example, when checking a function, the lifetime of a borrow
738 /// can end up being assigned to some region parameter. In these cases,
739 /// it must be ensured that bounds on the region can't be accidentally
740 /// assumed without being checked.
742 /// The process of doing that is called "skolemization". The bound regions
743 /// are replaced by skolemized markers, which don't satisfy any relation
744 /// not explicity provided.
746 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
747 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
748 /// to be used. These also support explicit bounds: both the internally-stored
749 /// *scope*, which the region is assumed to outlive, as well as other
750 /// relations stored in the `FreeRegionMap`. Note that these relations
751 /// aren't checked when you `make_subregion` (or `eq_types`), only by
752 /// `resolve_regions_and_report_errors`.
754 /// When working with higher-ranked types, some region relations aren't
755 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
756 /// `ReSkolemized` is designed for this purpose. In these contexts,
757 /// there's also the risk that some inference variable laying around will
758 /// get unified with your skolemized region: if you want to check whether
759 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
760 /// with a skolemized region `'%a`, the variable `'_` would just be
761 /// instantiated to the skolemized region `'%a`, which is wrong because
762 /// the inference variable is supposed to satisfy the relation
763 /// *for every value of the skolemized region*. To ensure that doesn't
764 /// happen, you can use `leak_check`. This is more clearly explained
765 /// by infer/higher_ranked/README.md.
767 /// [1] http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
768 /// [2] http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
769 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable)]
770 pub enum RegionKind
{
771 // Region bound in a type or fn declaration which will be
772 // substituted 'early' -- that is, at the same time when type
773 // parameters are substituted.
774 ReEarlyBound(EarlyBoundRegion
),
776 // Region bound in a function scope, which will be substituted when the
777 // function is called.
778 ReLateBound(DebruijnIndex
, BoundRegion
),
780 /// When checking a function body, the types of all arguments and so forth
781 /// that refer to bound region parameters are modified to refer to free
782 /// region parameters.
785 /// A concrete region naming some statically determined extent
786 /// (e.g. an expression or sequence of statements) within the
787 /// current function.
788 ReScope(region
::CodeExtent
),
790 /// Static data that has an "infinite" lifetime. Top in the region lattice.
793 /// A region variable. Should not exist after typeck.
796 /// A skolemized region - basically the higher-ranked version of ReFree.
797 /// Should not exist after typeck.
798 ReSkolemized(SkolemizedRegionVid
, BoundRegion
),
800 /// Empty lifetime is for data that is never accessed.
801 /// Bottom in the region lattice. We treat ReEmpty somewhat
802 /// specially; at least right now, we do not generate instances of
803 /// it during the GLB computations, but rather
804 /// generate an error instead. This is to improve error messages.
805 /// The only way to get an instance of ReEmpty is to have a region
806 /// variable with no constraints.
809 /// Erased region, used by trait selection, in MIR and during trans.
813 impl<'tcx
> serialize
::UseSpecializedDecodable
for Region
<'tcx
> {}
815 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
816 pub struct EarlyBoundRegion
{
822 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
827 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
832 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
833 pub struct FloatVid
{
837 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
838 pub struct RegionVid
{
842 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
843 pub struct SkolemizedRegionVid
{
847 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
853 /// A `FreshTy` is one that is generated as a replacement for an
854 /// unbound type variable. This is convenient for caching etc. See
855 /// `infer::freshen` for more details.
861 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
862 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
863 pub struct ExistentialProjection
<'tcx
> {
864 pub trait_ref
: ExistentialTraitRef
<'tcx
>,
869 pub type PolyExistentialProjection
<'tcx
> = Binder
<ExistentialProjection
<'tcx
>>;
871 impl<'a
, 'tcx
, 'gcx
> ExistentialProjection
<'tcx
> {
872 pub fn item_name(&self) -> Name
{
873 self.item_name
// safe to skip the binder to access a name
876 pub fn sort_key(&self, tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>) -> (DefPathHash
, InternedString
) {
877 // We want something here that is stable across crate boundaries.
878 // The DefId isn't but the `deterministic_hash` of the corresponding
880 let trait_def
= tcx
.trait_def(self.trait_ref
.def_id
);
881 let def_path_hash
= trait_def
.def_path_hash
;
883 // An `ast::Name` is also not stable (it's just an index into an
884 // interning table), so map to the corresponding `InternedString`.
885 let item_name
= self.item_name
.as_str();
886 (def_path_hash
, item_name
)
889 pub fn with_self_ty(&self, tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>,
891 -> ty
::ProjectionPredicate
<'tcx
>
893 // otherwise the escaping regions would be captured by the binders
894 assert
!(!self_ty
.has_escaping_regions());
896 ty
::ProjectionPredicate
{
897 projection_ty
: ty
::ProjectionTy
::from_ref_and_name(
899 self.trait_ref
.with_self_ty(tcx
, self_ty
),
906 impl<'a
, 'tcx
, 'gcx
> PolyExistentialProjection
<'tcx
> {
907 pub fn item_name(&self) -> Name
{
908 self.skip_binder().item_name()
911 pub fn sort_key(&self, tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>) -> (DefPathHash
, InternedString
) {
912 self.skip_binder().sort_key(tcx
)
915 pub fn with_self_ty(&self, tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>, self_ty
: Ty
<'tcx
>)
916 -> ty
::PolyProjectionPredicate
<'tcx
> {
917 self.map_bound(|p
| p
.with_self_ty(tcx
, self_ty
))
922 pub fn new(depth
: u32) -> DebruijnIndex
{
924 DebruijnIndex { depth: depth }
927 pub fn shifted(&self, amount
: u32) -> DebruijnIndex
{
928 DebruijnIndex { depth: self.depth + amount }
934 pub fn is_late_bound(&self) -> bool
{
936 ty
::ReLateBound(..) => true,
941 pub fn needs_infer(&self) -> bool
{
943 ty
::ReVar(..) | ty
::ReSkolemized(..) => true,
948 pub fn escapes_depth(&self, depth
: u32) -> bool
{
950 ty
::ReLateBound(debruijn
, _
) => debruijn
.depth
> depth
,
955 /// Returns the depth of `self` from the (1-based) binding level `depth`
956 pub fn from_depth(&self, depth
: u32) -> RegionKind
{
958 ty
::ReLateBound(debruijn
, r
) => ty
::ReLateBound(DebruijnIndex
{
959 depth
: debruijn
.depth
- (depth
- 1)
965 pub fn type_flags(&self) -> TypeFlags
{
966 let mut flags
= TypeFlags
::empty();
970 flags
= flags
| TypeFlags
::HAS_RE_INFER
;
971 flags
= flags
| TypeFlags
::KEEP_IN_LOCAL_TCX
;
973 ty
::ReSkolemized(..) => {
974 flags
= flags
| TypeFlags
::HAS_RE_INFER
;
975 flags
= flags
| TypeFlags
::HAS_RE_SKOL
;
976 flags
= flags
| TypeFlags
::KEEP_IN_LOCAL_TCX
;
978 ty
::ReLateBound(..) => { }
979 ty
::ReEarlyBound(..) => { flags = flags | TypeFlags::HAS_RE_EARLY_BOUND; }
980 ty
::ReStatic
| ty
::ReErased
=> { }
981 _
=> { flags = flags | TypeFlags::HAS_FREE_REGIONS; }
985 ty
::ReStatic
| ty
::ReEmpty
| ty
::ReErased
=> (),
986 _
=> flags
= flags
| TypeFlags
::HAS_LOCAL_NAMES
,
989 debug
!("type_flags({:?}) = {:?}", self, flags
);
996 impl<'a
, 'gcx
, 'tcx
> TyS
<'tcx
> {
997 pub fn as_opt_param_ty(&self) -> Option
<ty
::ParamTy
> {
999 ty
::TyParam(ref d
) => Some(d
.clone()),
1004 pub fn is_nil(&self) -> bool
{
1006 TyTuple(ref tys
, _
) => tys
.is_empty(),
1011 pub fn is_never(&self) -> bool
{
1018 /// Test whether this is a `()` which was produced by defaulting a
1019 /// diverging type variable with feature(never_type) disabled.
1020 pub fn is_defaulted_unit(&self) -> bool
{
1022 TyTuple(_
, true) => true,
1027 /// Checks whether a type is visibly uninhabited from a particular module.
1033 /// pub struct SecretlyUninhabited {
1040 /// pub struct AlsoSecretlyUninhabited {
1048 /// x: a::b::SecretlyUninhabited,
1049 /// y: c::AlsoSecretlyUninhabited,
1052 /// In this code, the type `Foo` will only be visibly uninhabited inside the
1053 /// modules b, c and d. This effects pattern-matching on `Foo` or types that
1058 /// let foo_result: Result<T, Foo> = ... ;
1059 /// let Ok(t) = foo_result;
1061 /// This code should only compile in modules where the uninhabitedness of Foo is
1063 pub fn is_uninhabited_from(&self, module
: DefId
, tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>) -> bool
{
1064 let mut visited
= FxHashMap
::default();
1065 let forest
= self.uninhabited_from(&mut visited
, tcx
);
1067 // To check whether this type is uninhabited at all (not just from the
1068 // given node) you could check whether the forest is empty.
1070 // forest.is_empty()
1072 forest
.contains(tcx
, module
)
1075 pub fn is_primitive(&self) -> bool
{
1077 TyBool
| TyChar
| TyInt(_
) | TyUint(_
) | TyFloat(_
) => true,
1082 pub fn is_ty_var(&self) -> bool
{
1084 TyInfer(TyVar(_
)) => true,
1089 pub fn is_phantom_data(&self) -> bool
{
1090 if let TyAdt(def
, _
) = self.sty
{
1091 def
.is_phantom_data()
1097 pub fn is_bool(&self) -> bool { self.sty == TyBool }
1099 pub fn is_param(&self, index
: u32) -> bool
{
1101 ty
::TyParam(ref data
) => data
.idx
== index
,
1106 pub fn is_self(&self) -> bool
{
1108 TyParam(ref p
) => p
.is_self(),
1113 pub fn is_slice(&self) -> bool
{
1115 TyRawPtr(mt
) | TyRef(_
, mt
) => match mt
.ty
.sty
{
1116 TySlice(_
) | TyStr
=> true,
1123 pub fn is_structural(&self) -> bool
{
1125 TyAdt(..) | TyTuple(..) | TyArray(..) | TyClosure(..) => true,
1126 _
=> self.is_slice() | self.is_trait(),
1131 pub fn is_simd(&self) -> bool
{
1133 TyAdt(def
, _
) => def
.repr
.simd(),
1138 pub fn sequence_element_type(&self, tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>) -> Ty
<'tcx
> {
1140 TyArray(ty
, _
) | TySlice(ty
) => ty
,
1141 TyStr
=> tcx
.mk_mach_uint(ast
::UintTy
::U8
),
1142 _
=> bug
!("sequence_element_type called on non-sequence value: {}", self),
1146 pub fn simd_type(&self, tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>) -> Ty
<'tcx
> {
1148 TyAdt(def
, substs
) => {
1149 def
.struct_variant().fields
[0].ty(tcx
, substs
)
1151 _
=> bug
!("simd_type called on invalid type")
1155 pub fn simd_size(&self, _cx
: TyCtxt
) -> usize {
1157 TyAdt(def
, _
) => def
.struct_variant().fields
.len(),
1158 _
=> bug
!("simd_size called on invalid type")
1162 pub fn is_region_ptr(&self) -> bool
{
1169 pub fn is_mutable_pointer(&self) -> bool
{
1171 TyRawPtr(tnm
) | TyRef(_
, tnm
) => if let hir
::Mutability
::MutMutable
= tnm
.mutbl
{
1180 pub fn is_unsafe_ptr(&self) -> bool
{
1182 TyRawPtr(_
) => return true,
1187 pub fn is_box(&self) -> bool
{
1189 TyAdt(def
, _
) => def
.is_box(),
1194 /// panics if called on any type other than `Box<T>`
1195 pub fn boxed_ty(&self) -> Ty
<'tcx
> {
1197 TyAdt(def
, substs
) if def
.is_box() => substs
.type_at(0),
1198 _
=> bug
!("`boxed_ty` is called on non-box type {:?}", self),
1202 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1203 /// (A TyRawPtr is scalar because it represents a non-managed pointer, so its
1204 /// contents are abstract to rustc.)
1205 pub fn is_scalar(&self) -> bool
{
1207 TyBool
| TyChar
| TyInt(_
) | TyFloat(_
) | TyUint(_
) |
1208 TyInfer(IntVar(_
)) | TyInfer(FloatVar(_
)) |
1209 TyFnDef(..) | TyFnPtr(_
) | TyRawPtr(_
) => true,
1214 /// Returns true if this type is a floating point type and false otherwise.
1215 pub fn is_floating_point(&self) -> bool
{
1218 TyInfer(FloatVar(_
)) => true,
1223 pub fn is_trait(&self) -> bool
{
1225 TyDynamic(..) => true,
1230 pub fn is_closure(&self) -> bool
{
1232 TyClosure(..) => true,
1237 pub fn is_integral(&self) -> bool
{
1239 TyInfer(IntVar(_
)) | TyInt(_
) | TyUint(_
) => true,
1244 pub fn is_fresh(&self) -> bool
{
1246 TyInfer(FreshTy(_
)) => true,
1247 TyInfer(FreshIntTy(_
)) => true,
1248 TyInfer(FreshFloatTy(_
)) => true,
1253 pub fn is_uint(&self) -> bool
{
1255 TyInfer(IntVar(_
)) | TyUint(ast
::UintTy
::Us
) => true,
1260 pub fn is_char(&self) -> bool
{
1267 pub fn is_fp(&self) -> bool
{
1269 TyInfer(FloatVar(_
)) | TyFloat(_
) => true,
1274 pub fn is_numeric(&self) -> bool
{
1275 self.is_integral() || self.is_fp()
1278 pub fn is_signed(&self) -> bool
{
1285 pub fn is_machine(&self) -> bool
{
1287 TyInt(ast
::IntTy
::Is
) | TyUint(ast
::UintTy
::Us
) => false,
1288 TyInt(..) | TyUint(..) | TyFloat(..) => true,
1293 pub fn has_concrete_skeleton(&self) -> bool
{
1295 TyParam(_
) | TyInfer(_
) | TyError
=> false,
1300 /// Returns the type and mutability of *ty.
1302 /// The parameter `explicit` indicates if this is an *explicit* dereference.
1303 /// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1304 pub fn builtin_deref(&self, explicit
: bool
, pref
: ty
::LvaluePreference
)
1305 -> Option
<TypeAndMut
<'tcx
>>
1308 TyAdt(def
, _
) if def
.is_box() => {
1310 ty
: self.boxed_ty(),
1311 mutbl
: if pref
== ty
::PreferMutLvalue
{
1318 TyRef(_
, mt
) => Some(mt
),
1319 TyRawPtr(mt
) if explicit
=> Some(mt
),
1324 /// Returns the type of ty[i]
1325 pub fn builtin_index(&self) -> Option
<Ty
<'tcx
>> {
1327 TyArray(ty
, _
) | TySlice(ty
) => Some(ty
),
1332 pub fn fn_sig(&self) -> PolyFnSig
<'tcx
> {
1334 TyFnDef(.., f
) | TyFnPtr(f
) => f
,
1335 _
=> bug
!("Ty::fn_sig() called on non-fn type: {:?}", self)
1339 pub fn is_fn(&self) -> bool
{
1341 TyFnDef(..) | TyFnPtr(_
) => true,
1346 pub fn ty_to_def_id(&self) -> Option
<DefId
> {
1348 TyDynamic(ref tt
, ..) => tt
.principal().map(|p
| p
.def_id()),
1349 TyAdt(def
, _
) => Some(def
.did
),
1350 TyClosure(id
, _
) => Some(id
),
1355 pub fn ty_adt_def(&self) -> Option
<&'tcx AdtDef
> {
1357 TyAdt(adt
, _
) => Some(adt
),
1362 /// Returns the regions directly referenced from this type (but
1363 /// not types reachable from this type via `walk_tys`). This
1364 /// ignores late-bound regions binders.
1365 pub fn regions(&self) -> Vec
<ty
::Region
<'tcx
>> {
1367 TyRef(region
, _
) => {
1370 TyDynamic(ref obj
, region
) => {
1371 let mut v
= vec
![region
];
1372 if let Some(p
) = obj
.principal() {
1373 v
.extend(p
.skip_binder().substs
.regions());
1377 TyAdt(_
, substs
) | TyAnon(_
, substs
) => {
1378 substs
.regions().collect()
1380 TyClosure(_
, ref substs
) => {
1381 substs
.substs
.regions().collect()
1383 TyProjection(ref data
) => {
1384 data
.trait_ref
.substs
.regions().collect()