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