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