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