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