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