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