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