]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/sty.rs
Updating the instructions for when a tool breaks to use the new toolstate feature
[rust.git] / src / librustc / ty / sty.rs
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.
4 //
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.
10
11 //! This module contains TypeVariants and its major components
12
13 use hir::def_id::DefId;
14
15 use middle::const_val::ConstVal;
16 use middle::region;
17 use ty::subst::{Substs, Subst};
18 use ty::{self, AdtDef, TypeFlags, Ty, TyCtxt, TypeFoldable};
19 use ty::{Slice, TyS};
20 use ty::subst::Kind;
21
22 use std::iter;
23 use std::cmp::Ordering;
24 use syntax::abi;
25 use syntax::ast::{self, Name};
26 use syntax::symbol::keywords;
27 use util::nodemap::FxHashMap;
28
29 use serialize;
30
31 use hir;
32
33 use self::InferTy::*;
34 use self::TypeVariants::*;
35
36 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
37 pub struct TypeAndMut<'tcx> {
38     pub ty: Ty<'tcx>,
39     pub mutbl: hir::Mutability,
40 }
41
42 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
43          RustcEncodable, RustcDecodable, Copy)]
44 /// A "free" region `fr` can be interpreted as "some region
45 /// at least as big as the scope `fr.scope`".
46 pub struct FreeRegion {
47     pub scope: DefId,
48     pub bound_region: BoundRegion,
49 }
50
51 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
52          RustcEncodable, RustcDecodable, Copy)]
53 pub enum BoundRegion {
54     /// An anonymous region parameter for a given fn (&T)
55     BrAnon(u32),
56
57     /// Named region parameters for functions (a in &'a T)
58     ///
59     /// The def-id is needed to distinguish free regions in
60     /// the event of shadowing.
61     BrNamed(DefId, Name),
62
63     /// Fresh bound identifiers created during GLB computations.
64     BrFresh(u32),
65
66     /// Anonymous region for the implicit env pointer parameter
67     /// to a closure
68     BrEnv,
69 }
70
71 impl BoundRegion {
72     pub fn is_named(&self) -> bool {
73         match *self {
74             BoundRegion::BrNamed(..) => true,
75             _ => false,
76         }
77     }
78 }
79
80 /// NB: If you change this, you'll probably want to change the corresponding
81 /// AST structure in libsyntax/ast.rs as well.
82 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
83 pub enum TypeVariants<'tcx> {
84     /// The primitive boolean type. Written as `bool`.
85     TyBool,
86
87     /// The primitive character type; holds a Unicode scalar value
88     /// (a non-surrogate code point).  Written as `char`.
89     TyChar,
90
91     /// A primitive signed integer type. For example, `i32`.
92     TyInt(ast::IntTy),
93
94     /// A primitive unsigned integer type. For example, `u32`.
95     TyUint(ast::UintTy),
96
97     /// A primitive floating-point type. For example, `f64`.
98     TyFloat(ast::FloatTy),
99
100     /// Structures, enumerations and unions.
101     ///
102     /// Substs here, possibly against intuition, *may* contain `TyParam`s.
103     /// That is, even after substitution it is possible that there are type
104     /// variables. This happens when the `TyAdt` corresponds to an ADT
105     /// definition and not a concrete use of it.
106     TyAdt(&'tcx AdtDef, &'tcx Substs<'tcx>),
107
108     /// The pointee of a string slice. Written as `str`.
109     TyStr,
110
111     /// An array with the given length. Written as `[T; n]`.
112     TyArray(Ty<'tcx>, &'tcx ty::Const<'tcx>),
113
114     /// The pointee of an array slice.  Written as `[T]`.
115     TySlice(Ty<'tcx>),
116
117     /// A raw pointer. Written as `*mut T` or `*const T`
118     TyRawPtr(TypeAndMut<'tcx>),
119
120     /// A reference; a pointer with an associated lifetime. Written as
121     /// `&'a mut T` or `&'a T`.
122     TyRef(Region<'tcx>, TypeAndMut<'tcx>),
123
124     /// The anonymous type of a function declaration/definition. Each
125     /// function has a unique type.
126     TyFnDef(DefId, &'tcx Substs<'tcx>),
127
128     /// A pointer to a function.  Written as `fn() -> i32`.
129     TyFnPtr(PolyFnSig<'tcx>),
130
131     /// A trait, defined with `trait`.
132     TyDynamic(Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
133
134     /// The anonymous type of a closure. Used to represent the type of
135     /// `|a| a`.
136     TyClosure(DefId, ClosureSubsts<'tcx>),
137
138     /// The anonymous type of a generator. Used to represent the type of
139     /// `|a| yield a`.
140     TyGenerator(DefId, ClosureSubsts<'tcx>, GeneratorInterior<'tcx>),
141
142     /// The never type `!`
143     TyNever,
144
145     /// A tuple type.  For example, `(i32, bool)`.
146     /// The bool indicates whether this is a unit tuple and was created by
147     /// defaulting a diverging type variable with feature(never_type) disabled.
148     /// It's only purpose is for raising future-compatibility warnings for when
149     /// diverging type variables start defaulting to ! instead of ().
150     TyTuple(&'tcx Slice<Ty<'tcx>>, bool),
151
152     /// The projection of an associated type.  For example,
153     /// `<T as Trait<..>>::N`.
154     TyProjection(ProjectionTy<'tcx>),
155
156     /// Anonymized (`impl Trait`) type found in a return type.
157     /// The DefId comes from the `impl Trait` ast::Ty node, and the
158     /// substitutions are for the generics of the function in question.
159     /// After typeck, the concrete type can be found in the `types` map.
160     TyAnon(DefId, &'tcx Substs<'tcx>),
161
162     /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
163     TyParam(ParamTy),
164
165     /// A type variable used during type-checking.
166     TyInfer(InferTy),
167
168     /// A placeholder for a type which could not be computed; this is
169     /// propagated to avoid useless error messages.
170     TyError,
171 }
172
173 /// A closure can be modeled as a struct that looks like:
174 ///
175 ///     struct Closure<'l0...'li, T0...Tj, U0...Uk> {
176 ///         upvar0: U0,
177 ///         ...
178 ///         upvark: Uk
179 ///     }
180 ///
181 /// where 'l0...'li and T0...Tj are the lifetime and type parameters
182 /// in scope on the function that defined the closure, and U0...Uk are
183 /// type parameters representing the types of its upvars (borrowed, if
184 /// appropriate).
185 ///
186 /// So, for example, given this function:
187 ///
188 ///     fn foo<'a, T>(data: &'a mut T) {
189 ///          do(|| data.count += 1)
190 ///     }
191 ///
192 /// the type of the closure would be something like:
193 ///
194 ///     struct Closure<'a, T, U0> {
195 ///         data: U0
196 ///     }
197 ///
198 /// Note that the type of the upvar is not specified in the struct.
199 /// You may wonder how the impl would then be able to use the upvar,
200 /// if it doesn't know it's type? The answer is that the impl is
201 /// (conceptually) not fully generic over Closure but rather tied to
202 /// instances with the expected upvar types:
203 ///
204 ///     impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
205 ///         ...
206 ///     }
207 ///
208 /// You can see that the *impl* fully specified the type of the upvar
209 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
210 /// (Here, I am assuming that `data` is mut-borrowed.)
211 ///
212 /// Now, the last question you may ask is: Why include the upvar types
213 /// as extra type parameters? The reason for this design is that the
214 /// upvar types can reference lifetimes that are internal to the
215 /// creating function. In my example above, for example, the lifetime
216 /// `'b` represents the scope of the closure itself; this is some
217 /// subset of `foo`, probably just the scope of the call to the to
218 /// `do()`. If we just had the lifetime/type parameters from the
219 /// enclosing function, we couldn't name this lifetime `'b`. Note that
220 /// there can also be lifetimes in the types of the upvars themselves,
221 /// if one of them happens to be a reference to something that the
222 /// creating fn owns.
223 ///
224 /// OK, you say, so why not create a more minimal set of parameters
225 /// that just includes the extra lifetime parameters? The answer is
226 /// primarily that it would be hard --- we don't know at the time when
227 /// we create the closure type what the full types of the upvars are,
228 /// nor do we know which are borrowed and which are not. In this
229 /// design, we can just supply a fresh type parameter and figure that
230 /// out later.
231 ///
232 /// All right, you say, but why include the type parameters from the
233 /// original function then? The answer is that trans may need them
234 /// when monomorphizing, and they may not appear in the upvars.  A
235 /// closure could capture no variables but still make use of some
236 /// in-scope type parameter with a bound (e.g., if our example above
237 /// had an extra `U: Default`, and the closure called `U::default()`).
238 ///
239 /// There is another reason. This design (implicitly) prohibits
240 /// closures from capturing themselves (except via a trait
241 /// object). This simplifies closure inference considerably, since it
242 /// means that when we infer the kind of a closure or its upvars, we
243 /// don't have to handle cycles where the decisions we make for
244 /// closure C wind up influencing the decisions we ought to make for
245 /// closure C (which would then require fixed point iteration to
246 /// handle). Plus it fixes an ICE. :P
247 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
248 pub struct ClosureSubsts<'tcx> {
249     /// Lifetime and type parameters from the enclosing function,
250     /// concatenated with the types of the upvars.
251     ///
252     /// These are separated out because trans wants to pass them around
253     /// when monomorphizing.
254     pub substs: &'tcx Substs<'tcx>,
255 }
256
257 impl<'a, 'gcx, 'acx, 'tcx> ClosureSubsts<'tcx> {
258     #[inline]
259     pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'acx>) ->
260         impl Iterator<Item=Ty<'tcx>> + 'tcx
261     {
262         let generics = tcx.generics_of(def_id);
263         self.substs[self.substs.len()-generics.own_count()..].iter().map(
264             |t| t.as_type().expect("unexpected region in upvars"))
265     }
266 }
267
268 impl<'a, 'gcx, 'tcx> ClosureSubsts<'tcx> {
269     /// This returns the types of the MIR locals which had to be stored across suspension points.
270     /// It is calculated in rustc_mir::transform::generator::StateTransform.
271     /// All the types here must be in the tuple in GeneratorInterior.
272     pub fn state_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
273         impl Iterator<Item=Ty<'tcx>> + 'a
274     {
275         let state = tcx.generator_layout(def_id).fields.iter();
276         state.map(move |d| d.ty.subst(tcx, self.substs))
277     }
278
279     /// This is the types of all the fields stored in a generator.
280     /// It includes the upvars, state types and the state discriminant which is u32.
281     pub fn field_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
282         impl Iterator<Item=Ty<'tcx>> + 'a
283     {
284         let upvars = self.upvar_tys(def_id, tcx);
285         let state = self.state_tys(def_id, tcx);
286         upvars.chain(iter::once(tcx.types.u32)).chain(state)
287     }
288 }
289
290 /// This describes the types that can be contained in a generator.
291 /// It will be a type variable initially and unified in the last stages of typeck of a body.
292 /// It contains a tuple of all the types that could end up on a generator frame.
293 /// The state transformation MIR pass may only produce layouts which mention types in this tuple.
294 /// Upvars are not counted here.
295 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
296 pub struct GeneratorInterior<'tcx> {
297     pub witness: Ty<'tcx>,
298 }
299
300 impl<'tcx> GeneratorInterior<'tcx> {
301     pub fn new(witness: Ty<'tcx>) -> GeneratorInterior<'tcx> {
302         GeneratorInterior { witness }
303     }
304
305     pub fn as_slice(&self) -> &'tcx Slice<Ty<'tcx>> {
306         match self.witness.sty {
307             ty::TyTuple(s, _) => s,
308             _ => bug!(),
309         }
310     }
311 }
312
313 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
314 pub enum ExistentialPredicate<'tcx> {
315     /// e.g. Iterator
316     Trait(ExistentialTraitRef<'tcx>),
317     /// e.g. Iterator::Item = T
318     Projection(ExistentialProjection<'tcx>),
319     /// e.g. Send
320     AutoTrait(DefId),
321 }
322
323 impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
324     pub fn cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
325         use self::ExistentialPredicate::*;
326         match (*self, *other) {
327             (Trait(_), Trait(_)) => Ordering::Equal,
328             (Projection(ref a), Projection(ref b)) =>
329                 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
330             (AutoTrait(ref a), AutoTrait(ref b)) =>
331                 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
332             (Trait(_), _) => Ordering::Less,
333             (Projection(_), Trait(_)) => Ordering::Greater,
334             (Projection(_), _) => Ordering::Less,
335             (AutoTrait(_), _) => Ordering::Greater,
336         }
337     }
338
339 }
340
341 impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
342     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
343         -> ty::Predicate<'tcx> {
344         use ty::ToPredicate;
345         match *self.skip_binder() {
346             ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
347             ExistentialPredicate::Projection(p) =>
348                 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
349             ExistentialPredicate::AutoTrait(did) => {
350                 let trait_ref = Binder(ty::TraitRef {
351                     def_id: did,
352                     substs: tcx.mk_substs_trait(self_ty, &[]),
353                 });
354                 trait_ref.to_predicate()
355             }
356         }
357     }
358 }
359
360 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<ExistentialPredicate<'tcx>> {}
361
362 impl<'tcx> Slice<ExistentialPredicate<'tcx>> {
363     pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
364         match self.get(0) {
365             Some(&ExistentialPredicate::Trait(tr)) => Some(tr),
366             _ => None,
367         }
368     }
369
370     #[inline]
371     pub fn projection_bounds<'a>(&'a self) ->
372         impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
373         self.iter().filter_map(|predicate| {
374             match *predicate {
375                 ExistentialPredicate::Projection(p) => Some(p),
376                 _ => None,
377             }
378         })
379     }
380
381     #[inline]
382     pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
383         self.iter().filter_map(|predicate| {
384             match *predicate {
385                 ExistentialPredicate::AutoTrait(d) => Some(d),
386                 _ => None
387             }
388         })
389     }
390 }
391
392 impl<'tcx> Binder<&'tcx Slice<ExistentialPredicate<'tcx>>> {
393     pub fn principal(&self) -> Option<PolyExistentialTraitRef<'tcx>> {
394         self.skip_binder().principal().map(Binder)
395     }
396
397     #[inline]
398     pub fn projection_bounds<'a>(&'a self) ->
399         impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
400         self.skip_binder().projection_bounds().map(Binder)
401     }
402
403     #[inline]
404     pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
405         self.skip_binder().auto_traits()
406     }
407
408     pub fn iter<'a>(&'a self)
409         -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
410         self.skip_binder().iter().cloned().map(Binder)
411     }
412 }
413
414 /// A complete reference to a trait. These take numerous guises in syntax,
415 /// but perhaps the most recognizable form is in a where clause:
416 ///
417 ///     T : Foo<U>
418 ///
419 /// This would be represented by a trait-reference where the def-id is the
420 /// def-id for the trait `Foo` and the substs define `T` as parameter 0,
421 /// and `U` as parameter 1.
422 ///
423 /// Trait references also appear in object types like `Foo<U>`, but in
424 /// that case the `Self` parameter is absent from the substitutions.
425 ///
426 /// Note that a `TraitRef` introduces a level of region binding, to
427 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
428 /// U>` or higher-ranked object types.
429 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
430 pub struct TraitRef<'tcx> {
431     pub def_id: DefId,
432     pub substs: &'tcx Substs<'tcx>,
433 }
434
435 impl<'tcx> TraitRef<'tcx> {
436     pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
437         TraitRef { def_id: def_id, substs: substs }
438     }
439
440     pub fn self_ty(&self) -> Ty<'tcx> {
441         self.substs.type_at(0)
442     }
443
444     pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
445         // Select only the "input types" from a trait-reference. For
446         // now this is all the types that appear in the
447         // trait-reference, but it should eventually exclude
448         // associated types.
449         self.substs.types()
450     }
451 }
452
453 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
454
455 impl<'tcx> PolyTraitRef<'tcx> {
456     pub fn self_ty(&self) -> Ty<'tcx> {
457         self.0.self_ty()
458     }
459
460     pub fn def_id(&self) -> DefId {
461         self.0.def_id
462     }
463
464     pub fn substs(&self) -> &'tcx Substs<'tcx> {
465         // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
466         self.0.substs
467     }
468
469     pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
470         // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
471         self.0.input_types()
472     }
473
474     pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
475         // Note that we preserve binding levels
476         Binder(ty::TraitPredicate { trait_ref: self.0.clone() })
477     }
478 }
479
480 /// An existential reference to a trait, where `Self` is erased.
481 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
482 ///
483 ///     exists T. T: Trait<'a, 'b, X, Y>
484 ///
485 /// The substitutions don't include the erased `Self`, only trait
486 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
487 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
488 pub struct ExistentialTraitRef<'tcx> {
489     pub def_id: DefId,
490     pub substs: &'tcx Substs<'tcx>,
491 }
492
493 impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
494     pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
495         // Select only the "input types" from a trait-reference. For
496         // now this is all the types that appear in the
497         // trait-reference, but it should eventually exclude
498         // associated types.
499         self.substs.types()
500     }
501
502     /// Object types don't have a self-type specified. Therefore, when
503     /// we convert the principal trait-ref into a normal trait-ref,
504     /// you must give *some* self-type. A common choice is `mk_err()`
505     /// or some skolemized type.
506     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
507         -> ty::TraitRef<'tcx>  {
508         // otherwise the escaping regions would be captured by the binder
509         assert!(!self_ty.has_escaping_regions());
510
511         ty::TraitRef {
512             def_id: self.def_id,
513             substs: tcx.mk_substs(
514                 iter::once(Kind::from(self_ty)).chain(self.substs.iter().cloned()))
515         }
516     }
517 }
518
519 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
520
521 impl<'tcx> PolyExistentialTraitRef<'tcx> {
522     pub fn def_id(&self) -> DefId {
523         self.0.def_id
524     }
525
526     pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
527         // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
528         self.0.input_types()
529     }
530 }
531
532 /// Binder is a binder for higher-ranked lifetimes. It is part of the
533 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
534 /// (which would be represented by the type `PolyTraitRef ==
535 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
536 /// erase, or otherwise "discharge" these bound regions, we change the
537 /// type from `Binder<T>` to just `T` (see
538 /// e.g. `liberate_late_bound_regions`).
539 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
540 pub struct Binder<T>(pub T);
541
542 impl<T> Binder<T> {
543     /// Skips the binder and returns the "bound" value. This is a
544     /// risky thing to do because it's easy to get confused about
545     /// debruijn indices and the like. It is usually better to
546     /// discharge the binder using `no_late_bound_regions` or
547     /// `replace_late_bound_regions` or something like
548     /// that. `skip_binder` is only valid when you are either
549     /// extracting data that has nothing to do with bound regions, you
550     /// are doing some sort of test that does not involve bound
551     /// regions, or you are being very careful about your depth
552     /// accounting.
553     ///
554     /// Some examples where `skip_binder` is reasonable:
555     /// - extracting the def-id from a PolyTraitRef;
556     /// - comparing the self type of a PolyTraitRef to see if it is equal to
557     ///   a type parameter `X`, since the type `X`  does not reference any regions
558     pub fn skip_binder(&self) -> &T {
559         &self.0
560     }
561
562     pub fn as_ref(&self) -> Binder<&T> {
563         ty::Binder(&self.0)
564     }
565
566     pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
567         where F: FnOnce(&T) -> U
568     {
569         self.as_ref().map_bound(f)
570     }
571
572     pub fn map_bound<F, U>(self, f: F) -> Binder<U>
573         where F: FnOnce(T) -> U
574     {
575         ty::Binder(f(self.0))
576     }
577 }
578
579 /// Represents the projection of an associated type. In explicit UFCS
580 /// form this would be written `<T as Trait<..>>::N`.
581 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
582 pub struct ProjectionTy<'tcx> {
583     /// The parameters of the associated item.
584     pub substs: &'tcx Substs<'tcx>,
585
586     /// The DefId of the TraitItem for the associated type N.
587     ///
588     /// Note that this is not the DefId of the TraitRef containing this
589     /// associated type, which is in tcx.associated_item(item_def_id).container.
590     pub item_def_id: DefId,
591 }
592
593 impl<'a, 'tcx> ProjectionTy<'tcx> {
594     /// Construct a ProjectionTy by searching the trait from trait_ref for the
595     /// associated item named item_name.
596     pub fn from_ref_and_name(
597         tcx: TyCtxt, trait_ref: ty::TraitRef<'tcx>, item_name: Name
598     ) -> ProjectionTy<'tcx> {
599         let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
600             item.kind == ty::AssociatedKind::Type &&
601             tcx.hygienic_eq(item_name, item.name, trait_ref.def_id)
602         }).unwrap().def_id;
603
604         ProjectionTy {
605             substs: trait_ref.substs,
606             item_def_id,
607         }
608     }
609
610     /// Extracts the underlying trait reference from this projection.
611     /// For example, if this is a projection of `<T as Iterator>::Item`,
612     /// then this function would return a `T: Iterator` trait reference.
613     pub fn trait_ref(&self, tcx: TyCtxt) -> ty::TraitRef<'tcx> {
614         let def_id = tcx.associated_item(self.item_def_id).container.id();
615         ty::TraitRef {
616             def_id,
617             substs: self.substs,
618         }
619     }
620
621     pub fn self_ty(&self) -> Ty<'tcx> {
622         self.substs.type_at(0)
623     }
624 }
625
626 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
627 pub struct GenSig<'tcx> {
628     pub yield_ty: Ty<'tcx>,
629     pub return_ty: Ty<'tcx>,
630 }
631
632 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
633
634 impl<'tcx> PolyGenSig<'tcx> {
635     pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
636         self.map_bound_ref(|sig| sig.yield_ty)
637     }
638     pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
639         self.map_bound_ref(|sig| sig.return_ty)
640     }
641 }
642
643 /// Signature of a function type, which I have arbitrarily
644 /// decided to use to refer to the input/output types.
645 ///
646 /// - `inputs` is the list of arguments and their modes.
647 /// - `output` is the return type.
648 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
649 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
650 pub struct FnSig<'tcx> {
651     pub inputs_and_output: &'tcx Slice<Ty<'tcx>>,
652     pub variadic: bool,
653     pub unsafety: hir::Unsafety,
654     pub abi: abi::Abi,
655 }
656
657 impl<'tcx> FnSig<'tcx> {
658     pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
659         &self.inputs_and_output[..self.inputs_and_output.len() - 1]
660     }
661
662     pub fn output(&self) -> Ty<'tcx> {
663         self.inputs_and_output[self.inputs_and_output.len() - 1]
664     }
665 }
666
667 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
668
669 impl<'tcx> PolyFnSig<'tcx> {
670     pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
671         Binder(self.skip_binder().inputs())
672     }
673     pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
674         self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
675     }
676     pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
677         self.map_bound_ref(|fn_sig| fn_sig.output().clone())
678     }
679     pub fn variadic(&self) -> bool {
680         self.skip_binder().variadic
681     }
682     pub fn unsafety(&self) -> hir::Unsafety {
683         self.skip_binder().unsafety
684     }
685     pub fn abi(&self) -> abi::Abi {
686         self.skip_binder().abi
687     }
688 }
689
690 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
691 pub struct ParamTy {
692     pub idx: u32,
693     pub name: Name,
694 }
695
696 impl<'a, 'gcx, 'tcx> ParamTy {
697     pub fn new(index: u32, name: Name) -> ParamTy {
698         ParamTy { idx: index, name: name }
699     }
700
701     pub fn for_self() -> ParamTy {
702         ParamTy::new(0, keywords::SelfType.name())
703     }
704
705     pub fn for_def(def: &ty::TypeParameterDef) -> ParamTy {
706         ParamTy::new(def.index, def.name)
707     }
708
709     pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
710         tcx.mk_param(self.idx, self.name)
711     }
712
713     pub fn is_self(&self) -> bool {
714         if self.name == keywords::SelfType.name() {
715             assert_eq!(self.idx, 0);
716             true
717         } else {
718             false
719         }
720     }
721 }
722
723 /// A [De Bruijn index][dbi] is a standard means of representing
724 /// regions (and perhaps later types) in a higher-ranked setting. In
725 /// particular, imagine a type like this:
726 ///
727 ///     for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
728 ///     ^          ^            |        |         |
729 ///     |          |            |        |         |
730 ///     |          +------------+ 1      |         |
731 ///     |                                |         |
732 ///     +--------------------------------+ 2       |
733 ///     |                                          |
734 ///     +------------------------------------------+ 1
735 ///
736 /// In this type, there are two binders (the outer fn and the inner
737 /// fn). We need to be able to determine, for any given region, which
738 /// fn type it is bound by, the inner or the outer one. There are
739 /// various ways you can do this, but a De Bruijn index is one of the
740 /// more convenient and has some nice properties. The basic idea is to
741 /// count the number of binders, inside out. Some examples should help
742 /// clarify what I mean.
743 ///
744 /// Let's start with the reference type `&'b isize` that is the first
745 /// argument to the inner function. This region `'b` is assigned a De
746 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
747 /// fn). The region `'a` that appears in the second argument type (`&'a
748 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
749 /// second-innermost binder". (These indices are written on the arrays
750 /// in the diagram).
751 ///
752 /// What is interesting is that De Bruijn index attached to a particular
753 /// variable will vary depending on where it appears. For example,
754 /// the final type `&'a char` also refers to the region `'a` declared on
755 /// the outermost fn. But this time, this reference is not nested within
756 /// any other binders (i.e., it is not an argument to the inner fn, but
757 /// rather the outer one). Therefore, in this case, it is assigned a
758 /// De Bruijn index of 1, because the innermost binder in that location
759 /// is the outer fn.
760 ///
761 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
762 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
763 pub struct DebruijnIndex {
764     /// We maintain the invariant that this is never 0. So 1 indicates
765     /// the innermost binder. To ensure this, create with `DebruijnIndex::new`.
766     pub depth: u32,
767 }
768
769 pub type Region<'tcx> = &'tcx RegionKind;
770
771 /// Representation of regions.
772 ///
773 /// Unlike types, most region variants are "fictitious", not concrete,
774 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
775 /// ones representing concrete regions.
776 ///
777 /// ## Bound Regions
778 ///
779 /// These are regions that are stored behind a binder and must be substituted
780 /// with some concrete region before being used. There are 2 kind of
781 /// bound regions: early-bound, which are bound in an item's Generics,
782 /// and are substituted by a Substs,  and late-bound, which are part of
783 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
784 /// the likes of `liberate_late_bound_regions`. The distinction exists
785 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
786 ///
787 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
788 /// outside their binder, e.g. in types passed to type inference, and
789 /// should first be substituted (by skolemized regions, free regions,
790 /// or region variables).
791 ///
792 /// ## Skolemized and Free Regions
793 ///
794 /// One often wants to work with bound regions without knowing their precise
795 /// identity. For example, when checking a function, the lifetime of a borrow
796 /// can end up being assigned to some region parameter. In these cases,
797 /// it must be ensured that bounds on the region can't be accidentally
798 /// assumed without being checked.
799 ///
800 /// The process of doing that is called "skolemization". The bound regions
801 /// are replaced by skolemized markers, which don't satisfy any relation
802 /// not explicitly provided.
803 ///
804 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
805 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
806 /// to be used. These also support explicit bounds: both the internally-stored
807 /// *scope*, which the region is assumed to outlive, as well as other
808 /// relations stored in the `FreeRegionMap`. Note that these relations
809 /// aren't checked when you `make_subregion` (or `eq_types`), only by
810 /// `resolve_regions_and_report_errors`.
811 ///
812 /// When working with higher-ranked types, some region relations aren't
813 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
814 /// `ReSkolemized` is designed for this purpose. In these contexts,
815 /// there's also the risk that some inference variable laying around will
816 /// get unified with your skolemized region: if you want to check whether
817 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
818 /// with a skolemized region `'%a`, the variable `'_` would just be
819 /// instantiated to the skolemized region `'%a`, which is wrong because
820 /// the inference variable is supposed to satisfy the relation
821 /// *for every value of the skolemized region*. To ensure that doesn't
822 /// happen, you can use `leak_check`. This is more clearly explained
823 /// by infer/higher_ranked/README.md.
824 ///
825 /// [1] http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
826 /// [2] http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
827 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable)]
828 pub enum RegionKind {
829     // Region bound in a type or fn declaration which will be
830     // substituted 'early' -- that is, at the same time when type
831     // parameters are substituted.
832     ReEarlyBound(EarlyBoundRegion),
833
834     // Region bound in a function scope, which will be substituted when the
835     // function is called.
836     ReLateBound(DebruijnIndex, BoundRegion),
837
838     /// When checking a function body, the types of all arguments and so forth
839     /// that refer to bound region parameters are modified to refer to free
840     /// region parameters.
841     ReFree(FreeRegion),
842
843     /// A concrete region naming some statically determined scope
844     /// (e.g. an expression or sequence of statements) within the
845     /// current function.
846     ReScope(region::Scope),
847
848     /// Static data that has an "infinite" lifetime. Top in the region lattice.
849     ReStatic,
850
851     /// A region variable.  Should not exist after typeck.
852     ReVar(RegionVid),
853
854     /// A skolemized region - basically the higher-ranked version of ReFree.
855     /// Should not exist after typeck.
856     ReSkolemized(SkolemizedRegionVid, BoundRegion),
857
858     /// Empty lifetime is for data that is never accessed.
859     /// Bottom in the region lattice. We treat ReEmpty somewhat
860     /// specially; at least right now, we do not generate instances of
861     /// it during the GLB computations, but rather
862     /// generate an error instead. This is to improve error messages.
863     /// The only way to get an instance of ReEmpty is to have a region
864     /// variable with no constraints.
865     ReEmpty,
866
867     /// Erased region, used by trait selection, in MIR and during trans.
868     ReErased,
869 }
870
871 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
872
873 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
874 pub struct EarlyBoundRegion {
875     pub def_id: DefId,
876     pub index: u32,
877     pub name: Name,
878 }
879
880 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
881 pub struct TyVid {
882     pub index: u32,
883 }
884
885 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
886 pub struct IntVid {
887     pub index: u32,
888 }
889
890 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
891 pub struct FloatVid {
892     pub index: u32,
893 }
894
895 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
896 pub struct RegionVid {
897     pub index: u32,
898 }
899
900 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
901 pub struct SkolemizedRegionVid {
902     pub index: u32,
903 }
904
905 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
906 pub enum InferTy {
907     TyVar(TyVid),
908     IntVar(IntVid),
909     FloatVar(FloatVid),
910
911     /// A `FreshTy` is one that is generated as a replacement for an
912     /// unbound type variable. This is convenient for caching etc. See
913     /// `infer::freshen` for more details.
914     FreshTy(u32),
915     FreshIntTy(u32),
916     FreshFloatTy(u32),
917 }
918
919 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
920 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
921 pub struct ExistentialProjection<'tcx> {
922     pub item_def_id: DefId,
923     pub substs: &'tcx Substs<'tcx>,
924     pub ty: Ty<'tcx>,
925 }
926
927 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
928
929 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
930     /// Extracts the underlying existential trait reference from this projection.
931     /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
932     /// then this function would return a `exists T. T: Iterator` existential trait
933     /// reference.
934     pub fn trait_ref(&self, tcx: TyCtxt) -> ty::ExistentialTraitRef<'tcx> {
935         let def_id = tcx.associated_item(self.item_def_id).container.id();
936         ty::ExistentialTraitRef{
937             def_id,
938             substs: self.substs,
939         }
940     }
941
942     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
943                         self_ty: Ty<'tcx>)
944                         -> ty::ProjectionPredicate<'tcx>
945     {
946         // otherwise the escaping regions would be captured by the binders
947         assert!(!self_ty.has_escaping_regions());
948
949         ty::ProjectionPredicate {
950             projection_ty: ty::ProjectionTy {
951                 item_def_id: self.item_def_id,
952                 substs: tcx.mk_substs(
953                 iter::once(Kind::from(self_ty)).chain(self.substs.iter().cloned())),
954             },
955             ty: self.ty,
956         }
957     }
958 }
959
960 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
961     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
962         -> ty::PolyProjectionPredicate<'tcx> {
963         self.map_bound(|p| p.with_self_ty(tcx, self_ty))
964     }
965 }
966
967 impl DebruijnIndex {
968     pub fn new(depth: u32) -> DebruijnIndex {
969         assert!(depth > 0);
970         DebruijnIndex { depth: depth }
971     }
972
973     pub fn shifted(&self, amount: u32) -> DebruijnIndex {
974         DebruijnIndex { depth: self.depth + amount }
975     }
976 }
977
978 /// Region utilities
979 impl RegionKind {
980     pub fn is_late_bound(&self) -> bool {
981         match *self {
982             ty::ReLateBound(..) => true,
983             _ => false,
984         }
985     }
986
987     pub fn needs_infer(&self) -> bool {
988         match *self {
989             ty::ReVar(..) | ty::ReSkolemized(..) => true,
990             _ => false
991         }
992     }
993
994     pub fn escapes_depth(&self, depth: u32) -> bool {
995         match *self {
996             ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
997             _ => false,
998         }
999     }
1000
1001     /// Returns the depth of `self` from the (1-based) binding level `depth`
1002     pub fn from_depth(&self, depth: u32) -> RegionKind {
1003         match *self {
1004             ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
1005                 depth: debruijn.depth - (depth - 1)
1006             }, r),
1007             r => r
1008         }
1009     }
1010
1011     pub fn type_flags(&self) -> TypeFlags {
1012         let mut flags = TypeFlags::empty();
1013
1014         match *self {
1015             ty::ReVar(..) => {
1016                 flags = flags | TypeFlags::HAS_RE_INFER;
1017                 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1018             }
1019             ty::ReSkolemized(..) => {
1020                 flags = flags | TypeFlags::HAS_RE_INFER;
1021                 flags = flags | TypeFlags::HAS_RE_SKOL;
1022                 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1023             }
1024             ty::ReLateBound(..) => { }
1025             ty::ReEarlyBound(..) => { flags = flags | TypeFlags::HAS_RE_EARLY_BOUND; }
1026             ty::ReStatic | ty::ReErased => { }
1027             _ => { flags = flags | TypeFlags::HAS_FREE_REGIONS; }
1028         }
1029
1030         match *self {
1031             ty::ReStatic | ty::ReEmpty | ty::ReErased => (),
1032             _ => flags = flags | TypeFlags::HAS_LOCAL_NAMES,
1033         }
1034
1035         debug!("type_flags({:?}) = {:?}", self, flags);
1036
1037         flags
1038     }
1039 }
1040
1041 /// Type utilities
1042 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
1043     pub fn as_opt_param_ty(&self) -> Option<ty::ParamTy> {
1044         match self.sty {
1045             ty::TyParam(ref d) => Some(d.clone()),
1046             _ => None,
1047         }
1048     }
1049
1050     pub fn is_nil(&self) -> bool {
1051         match self.sty {
1052             TyTuple(ref tys, _) => tys.is_empty(),
1053             _ => false,
1054         }
1055     }
1056
1057     pub fn is_never(&self) -> bool {
1058         match self.sty {
1059             TyNever => true,
1060             _ => false,
1061         }
1062     }
1063
1064     /// Test whether this is a `()` which was produced by defaulting a
1065     /// diverging type variable with feature(never_type) disabled.
1066     pub fn is_defaulted_unit(&self) -> bool {
1067         match self.sty {
1068             TyTuple(_, true) => true,
1069             _ => false,
1070         }
1071     }
1072
1073     /// Checks whether a type is visibly uninhabited from a particular module.
1074     /// # Example
1075     /// ```rust
1076     /// enum Void {}
1077     /// mod a {
1078     ///     pub mod b {
1079     ///         pub struct SecretlyUninhabited {
1080     ///             _priv: !,
1081     ///         }
1082     ///     }
1083     /// }
1084     ///
1085     /// mod c {
1086     ///     pub struct AlsoSecretlyUninhabited {
1087     ///         _priv: Void,
1088     ///     }
1089     ///     mod d {
1090     ///     }
1091     /// }
1092     ///
1093     /// struct Foo {
1094     ///     x: a::b::SecretlyUninhabited,
1095     ///     y: c::AlsoSecretlyUninhabited,
1096     /// }
1097     /// ```
1098     /// In this code, the type `Foo` will only be visibly uninhabited inside the
1099     /// modules b, c and d. This effects pattern-matching on `Foo` or types that
1100     /// contain `Foo`.
1101     ///
1102     /// # Example
1103     /// ```rust
1104     /// let foo_result: Result<T, Foo> = ... ;
1105     /// let Ok(t) = foo_result;
1106     /// ```
1107     /// This code should only compile in modules where the uninhabitedness of Foo is
1108     /// visible.
1109     pub fn is_uninhabited_from(&self, module: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1110         let mut visited = FxHashMap::default();
1111         let forest = self.uninhabited_from(&mut visited, tcx);
1112
1113         // To check whether this type is uninhabited at all (not just from the
1114         // given node) you could check whether the forest is empty.
1115         // ```
1116         // forest.is_empty()
1117         // ```
1118         forest.contains(tcx, module)
1119     }
1120
1121     pub fn is_primitive(&self) -> bool {
1122         match self.sty {
1123             TyBool | TyChar | TyInt(_) | TyUint(_) | TyFloat(_) => true,
1124             _ => false,
1125         }
1126     }
1127
1128     pub fn is_ty_var(&self) -> bool {
1129         match self.sty {
1130             TyInfer(TyVar(_)) => true,
1131             _ => false,
1132         }
1133     }
1134
1135     pub fn is_phantom_data(&self) -> bool {
1136         if let TyAdt(def, _) = self.sty {
1137             def.is_phantom_data()
1138         } else {
1139             false
1140         }
1141     }
1142
1143     pub fn is_bool(&self) -> bool { self.sty == TyBool }
1144
1145     pub fn is_param(&self, index: u32) -> bool {
1146         match self.sty {
1147             ty::TyParam(ref data) => data.idx == index,
1148             _ => false,
1149         }
1150     }
1151
1152     pub fn is_self(&self) -> bool {
1153         match self.sty {
1154             TyParam(ref p) => p.is_self(),
1155             _ => false,
1156         }
1157     }
1158
1159     pub fn is_slice(&self) -> bool {
1160         match self.sty {
1161             TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
1162                 TySlice(_) | TyStr => true,
1163                 _ => false,
1164             },
1165             _ => false
1166         }
1167     }
1168
1169     pub fn is_structural(&self) -> bool {
1170         match self.sty {
1171             TyAdt(..) | TyTuple(..) | TyArray(..) | TyClosure(..) => true,
1172             _ => self.is_slice() | self.is_trait(),
1173         }
1174     }
1175
1176     #[inline]
1177     pub fn is_simd(&self) -> bool {
1178         match self.sty {
1179             TyAdt(def, _) => def.repr.simd(),
1180             _ => false,
1181         }
1182     }
1183
1184     pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1185         match self.sty {
1186             TyArray(ty, _) | TySlice(ty) => ty,
1187             TyStr => tcx.mk_mach_uint(ast::UintTy::U8),
1188             _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1189         }
1190     }
1191
1192     pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1193         match self.sty {
1194             TyAdt(def, substs) => {
1195                 def.struct_variant().fields[0].ty(tcx, substs)
1196             }
1197             _ => bug!("simd_type called on invalid type")
1198         }
1199     }
1200
1201     pub fn simd_size(&self, _cx: TyCtxt) -> usize {
1202         match self.sty {
1203             TyAdt(def, _) => def.struct_variant().fields.len(),
1204             _ => bug!("simd_size called on invalid type")
1205         }
1206     }
1207
1208     pub fn is_region_ptr(&self) -> bool {
1209         match self.sty {
1210             TyRef(..) => true,
1211             _ => false,
1212         }
1213     }
1214
1215     pub fn is_mutable_pointer(&self) -> bool {
1216         match self.sty {
1217             TyRawPtr(tnm) | TyRef(_, tnm) => if let hir::Mutability::MutMutable = tnm.mutbl {
1218                 true
1219             } else {
1220                 false
1221             },
1222             _ => false
1223         }
1224     }
1225
1226     pub fn is_unsafe_ptr(&self) -> bool {
1227         match self.sty {
1228             TyRawPtr(_) => return true,
1229             _ => return false,
1230         }
1231     }
1232
1233     pub fn is_box(&self) -> bool {
1234         match self.sty {
1235             TyAdt(def, _) => def.is_box(),
1236             _ => false,
1237         }
1238     }
1239
1240     /// panics if called on any type other than `Box<T>`
1241     pub fn boxed_ty(&self) -> Ty<'tcx> {
1242         match self.sty {
1243             TyAdt(def, substs) if def.is_box() => substs.type_at(0),
1244             _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1245         }
1246     }
1247
1248     /// A scalar type is one that denotes an atomic datum, with no sub-components.
1249     /// (A TyRawPtr is scalar because it represents a non-managed pointer, so its
1250     /// contents are abstract to rustc.)
1251     pub fn is_scalar(&self) -> bool {
1252         match self.sty {
1253             TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
1254             TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
1255             TyFnDef(..) | TyFnPtr(_) | TyRawPtr(_) => true,
1256             _ => false
1257         }
1258     }
1259
1260     /// Returns true if this type is a floating point type and false otherwise.
1261     pub fn is_floating_point(&self) -> bool {
1262         match self.sty {
1263             TyFloat(_) |
1264             TyInfer(FloatVar(_)) => true,
1265             _ => false,
1266         }
1267     }
1268
1269     pub fn is_trait(&self) -> bool {
1270         match self.sty {
1271             TyDynamic(..) => true,
1272             _ => false,
1273         }
1274     }
1275
1276     pub fn is_closure(&self) -> bool {
1277         match self.sty {
1278             TyClosure(..) => true,
1279             _ => false,
1280         }
1281     }
1282
1283     pub fn is_integral(&self) -> bool {
1284         match self.sty {
1285             TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
1286             _ => false
1287         }
1288     }
1289
1290     pub fn is_fresh(&self) -> bool {
1291         match self.sty {
1292             TyInfer(FreshTy(_)) => true,
1293             TyInfer(FreshIntTy(_)) => true,
1294             TyInfer(FreshFloatTy(_)) => true,
1295             _ => false,
1296         }
1297     }
1298
1299     pub fn is_uint(&self) -> bool {
1300         match self.sty {
1301             TyInfer(IntVar(_)) | TyUint(ast::UintTy::Us) => true,
1302             _ => false
1303         }
1304     }
1305
1306     pub fn is_char(&self) -> bool {
1307         match self.sty {
1308             TyChar => true,
1309             _ => false,
1310         }
1311     }
1312
1313     pub fn is_fp(&self) -> bool {
1314         match self.sty {
1315             TyInfer(FloatVar(_)) | TyFloat(_) => true,
1316             _ => false
1317         }
1318     }
1319
1320     pub fn is_numeric(&self) -> bool {
1321         self.is_integral() || self.is_fp()
1322     }
1323
1324     pub fn is_signed(&self) -> bool {
1325         match self.sty {
1326             TyInt(_) => true,
1327             _ => false,
1328         }
1329     }
1330
1331     pub fn is_machine(&self) -> bool {
1332         match self.sty {
1333             TyInt(ast::IntTy::Is) | TyUint(ast::UintTy::Us) => false,
1334             TyInt(..) | TyUint(..) | TyFloat(..) => true,
1335             _ => false,
1336         }
1337     }
1338
1339     pub fn has_concrete_skeleton(&self) -> bool {
1340         match self.sty {
1341             TyParam(_) | TyInfer(_) | TyError => false,
1342             _ => true,
1343         }
1344     }
1345
1346     /// Returns the type and mutability of *ty.
1347     ///
1348     /// The parameter `explicit` indicates if this is an *explicit* dereference.
1349     /// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1350     pub fn builtin_deref(&self, explicit: bool, pref: ty::LvaluePreference)
1351         -> Option<TypeAndMut<'tcx>>
1352     {
1353         match self.sty {
1354             TyAdt(def, _) if def.is_box() => {
1355                 Some(TypeAndMut {
1356                     ty: self.boxed_ty(),
1357                     mutbl: if pref == ty::PreferMutLvalue {
1358                         hir::MutMutable
1359                     } else {
1360                         hir::MutImmutable
1361                     },
1362                 })
1363             },
1364             TyRef(_, mt) => Some(mt),
1365             TyRawPtr(mt) if explicit => Some(mt),
1366             _ => None,
1367         }
1368     }
1369
1370     /// Returns the type of ty[i]
1371     pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1372         match self.sty {
1373             TyArray(ty, _) | TySlice(ty) => Some(ty),
1374             _ => None,
1375         }
1376     }
1377
1378     pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1379         match self.sty {
1380             TyFnDef(def_id, substs) => {
1381                 tcx.fn_sig(def_id).subst(tcx, substs)
1382             }
1383             TyFnPtr(f) => f,
1384             _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1385         }
1386     }
1387
1388     pub fn is_fn(&self) -> bool {
1389         match self.sty {
1390             TyFnDef(..) | TyFnPtr(_) => true,
1391             _ => false,
1392         }
1393     }
1394
1395     pub fn ty_to_def_id(&self) -> Option<DefId> {
1396         match self.sty {
1397             TyDynamic(ref tt, ..) => tt.principal().map(|p| p.def_id()),
1398             TyAdt(def, _) => Some(def.did),
1399             TyClosure(id, _) => Some(id),
1400             _ => None,
1401         }
1402     }
1403
1404     pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1405         match self.sty {
1406             TyAdt(adt, _) => Some(adt),
1407             _ => None,
1408         }
1409     }
1410
1411     /// Returns the regions directly referenced from this type (but
1412     /// not types reachable from this type via `walk_tys`). This
1413     /// ignores late-bound regions binders.
1414     pub fn regions(&self) -> Vec<ty::Region<'tcx>> {
1415         match self.sty {
1416             TyRef(region, _) => {
1417                 vec![region]
1418             }
1419             TyDynamic(ref obj, region) => {
1420                 let mut v = vec![region];
1421                 if let Some(p) = obj.principal() {
1422                     v.extend(p.skip_binder().substs.regions());
1423                 }
1424                 v
1425             }
1426             TyAdt(_, substs) | TyAnon(_, substs) => {
1427                 substs.regions().collect()
1428             }
1429             TyClosure(_, ref substs) | TyGenerator(_, ref substs, _) => {
1430                 substs.substs.regions().collect()
1431             }
1432             TyProjection(ref data) => {
1433                 data.substs.regions().collect()
1434             }
1435             TyFnDef(..) |
1436             TyFnPtr(_) |
1437             TyBool |
1438             TyChar |
1439             TyInt(_) |
1440             TyUint(_) |
1441             TyFloat(_) |
1442             TyStr |
1443             TyArray(..) |
1444             TySlice(_) |
1445             TyRawPtr(_) |
1446             TyNever |
1447             TyTuple(..) |
1448             TyParam(_) |
1449             TyInfer(_) |
1450             TyError => {
1451                 vec![]
1452             }
1453         }
1454     }
1455 }
1456
1457 /// Typed constant value.
1458 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Eq, PartialEq)]
1459 pub struct Const<'tcx> {
1460     pub ty: Ty<'tcx>,
1461
1462     // FIXME(eddyb) Replace this with a miri value.
1463     pub val: ConstVal<'tcx>,
1464 }
1465
1466 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}