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