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