sty.rs 70.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

V
varkor 已提交
11
//! This module contains TyKind and its major components
12

13
use hir::def_id::DefId;
14
use infer::canonical::Canonical;
15
use mir::interpret::ConstValue;
16
use middle::region;
17
use polonius_engine::Atom;
18
use rustc_data_structures::indexed_vec::Idx;
V
varkor 已提交
19
use ty::subst::{Substs, Subst, Kind, UnpackedKind};
20
use ty::{self, AdtDef, TypeFlags, Ty, TyCtxt, TypeFoldable};
V
varkor 已提交
21
use ty::{List, TyS, ParamEnvAnd, ParamEnv};
22
use util::captures::Captures;
R
Ralf Jung 已提交
23
use mir::interpret::{Scalar, Pointer};
24

25 26
use std::iter;
use std::cmp::Ordering;
27
use rustc_target::spec::abi;
28
use syntax::ast::{self, Ident};
29
use syntax::symbol::{keywords, InternedString};
30

31
use serialize;
32

33
use hir;
34 35

use self::InferTy::*;
V
varkor 已提交
36
use self::TyKind::*;
37

38
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
39 40 41 42 43 44 45 46 47
pub struct TypeAndMut<'tcx> {
    pub ty: Ty<'tcx>,
    pub mutbl: hir::Mutability,
}

#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
         RustcEncodable, RustcDecodable, Copy)]
/// A "free" region `fr` can be interpreted as "some region
/// at least as big as the scope `fr.scope`".
48 49
pub struct FreeRegion {
    pub scope: DefId,
T
Tshepang Lekhonkhobe 已提交
50
    pub bound_region: BoundRegion,
51 52 53 54 55 56 57 58 59 60 61 62
}

#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
         RustcEncodable, RustcDecodable, Copy)]
pub enum BoundRegion {
    /// An anonymous region parameter for a given fn (&T)
    BrAnon(u32),

    /// Named region parameters for functions (a in &'a T)
    ///
    /// The def-id is needed to distinguish free regions in
    /// the event of shadowing.
63
    BrNamed(DefId, InternedString),
64 65 66 67

    /// Fresh bound identifiers created during GLB computations.
    BrFresh(u32),

68 69
    /// Anonymous region for the implicit env pointer parameter
    /// to a closure
T
Tshepang Lekhonkhobe 已提交
70
    BrEnv,
71 72
}

73 74 75 76 77 78 79 80 81
impl BoundRegion {
    pub fn is_named(&self) -> bool {
        match *self {
            BoundRegion::BrNamed(..) => true,
            _ => false,
        }
    }
}

82 83
/// N.B., If you change this, you'll probably want to change the corresponding
/// AST structure in `libsyntax/ast.rs` as well.
84
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
V
varkor 已提交
85
pub enum TyKind<'tcx> {
86
    /// The primitive boolean type. Written as `bool`.
87
    Bool,
88 89 90

    /// The primitive character type; holds a Unicode scalar value
    /// (a non-surrogate code point).  Written as `char`.
91
    Char,
92 93

    /// A primitive signed integer type. For example, `i32`.
94
    Int(ast::IntTy),
95 96

    /// A primitive unsigned integer type. For example, `u32`.
97
    Uint(ast::UintTy),
98 99

    /// A primitive floating-point type. For example, `f64`.
100
    Float(ast::FloatTy),
101

102
    /// Structures, enumerations and unions.
103
    ///
V
varkor 已提交
104
    /// Substs here, possibly against intuition, *may* contain `Param`s.
105
    /// That is, even after substitution it is possible that there are type
V
varkor 已提交
106
    /// variables. This happens when the `Adt` corresponds to an ADT
107
    /// definition and not a concrete use of it.
V
varkor 已提交
108
    Adt(&'tcx AdtDef, &'tcx Substs<'tcx>),
V
Vadim Petrochenkov 已提交
109

V
varkor 已提交
110
    Foreign(DefId),
P
Paul Lietar 已提交
111

112
    /// The pointee of a string slice. Written as `str`.
113
    Str,
114 115

    /// An array with the given length. Written as `[T; n]`.
V
varkor 已提交
116
    Array(Ty<'tcx>, &'tcx ty::Const<'tcx>),
117 118

    /// The pointee of an array slice.  Written as `[T]`.
V
varkor 已提交
119
    Slice(Ty<'tcx>),
120 121

    /// A raw pointer. Written as `*mut T` or `*const T`
V
varkor 已提交
122
    RawPtr(TypeAndMut<'tcx>),
123 124

    /// A reference; a pointer with an associated lifetime. Written as
125
    /// `&'a mut T` or `&'a T`.
V
varkor 已提交
126
    Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability),
127

128
    /// The anonymous type of a function declaration/definition. Each
129 130
    /// function has a unique type, which is output (for a function
    /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`.
131
    ///
132
    /// For example the type of `bar` here:
133 134 135
    ///
    /// ```rust
    /// fn foo() -> i32 { 1 }
136
    /// let bar = foo; // bar: fn() -> i32 {foo}
137
    /// ```
V
varkor 已提交
138
    FnDef(DefId, &'tcx Substs<'tcx>),
139 140

    /// A pointer to a function.  Written as `fn() -> i32`.
141
    ///
142
    /// For example the type of `bar` here:
143 144 145
    ///
    /// ```rust
    /// fn foo() -> i32 { 1 }
146
    /// let bar: fn() -> i32 = foo;
147
    /// ```
V
varkor 已提交
148
    FnPtr(PolyFnSig<'tcx>),
149 150

    /// A trait, defined with `trait`.
V
varkor 已提交
151
    Dynamic(Binder<&'tcx List<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
152 153 154

    /// The anonymous type of a closure. Used to represent the type of
    /// `|a| a`.
V
varkor 已提交
155
    Closure(DefId, ClosureSubsts<'tcx>),
156

J
John Kåre Alsaker 已提交
157 158
    /// The anonymous type of a generator. Used to represent the type of
    /// `|a| yield a`.
V
varkor 已提交
159
    Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
J
John Kåre Alsaker 已提交
160

161 162
    /// A type representin the types stored inside a generator.
    /// This should only appear in GeneratorInteriors.
V
varkor 已提交
163
    GeneratorWitness(Binder<&'tcx List<Ty<'tcx>>>),
164

A
Andrew Cann 已提交
165
    /// The never type `!`
V
varkor 已提交
166
    Never,
167

168
    /// A tuple type.  For example, `(i32, bool)`.
V
varkor 已提交
169
    Tuple(&'tcx List<Ty<'tcx>>),
170 171 172

    /// The projection of an associated type.  For example,
    /// `<T as Trait<..>>::N`.
V
varkor 已提交
173
    Projection(ProjectionTy<'tcx>),
174

175 176 177 178 179
    /// A placeholder type used when we do not have enough information
    /// to normalize the projection of an associated type to an
    /// existing concrete type. Currently only used with chalk-engine.
    UnnormalizedProjection(ProjectionTy<'tcx>),

180
    /// Opaque (`impl Trait`) type found in a return type.
181
    /// The `DefId` comes either from
O
Oliver Schneider 已提交
182 183 184
    /// * the `impl Trait` ast::Ty node,
    /// * or the `existential type` declaration
    /// The substitutions are for the generics of the function in question.
185
    /// After typeck, the concrete type can be found in the `types` map.
186
    Opaque(DefId, &'tcx Substs<'tcx>),
187

188
    /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
V
varkor 已提交
189
    Param(ParamTy),
190

S
scalexm 已提交
191 192 193
    /// Bound type variable, used only when preparing a trait query.
    Bound(BoundTy),

194
    /// A type variable used during type checking.
V
varkor 已提交
195
    Infer(InferTy),
196 197 198

    /// A placeholder for a type which could not be computed; this is
    /// propagated to avoid useless error messages.
V
varkor 已提交
199
    Error,
200 201 202 203
}

/// A closure can be modeled as a struct that looks like:
///
204
///     struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
205 206 207 208 209
///         upvar0: U0,
///         ...
///         upvark: Uk
///     }
///
210 211 212 213 214 215 216
/// where:
///
/// - 'l0...'li and T0...Tj are the lifetime and type parameters
///   in scope on the function that defined the closure,
/// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
///   is rather hackily encoded via a scalar type. See
///   `TyS::to_opt_closure_kind` for details.
217 218 219 220
/// - CS represents the *closure signature*, representing as a `fn()`
///   type. For example, `fn(u32, u32) -> u32` would mean that the closure
///   implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
///   specified above.
221 222 223
/// - U0...Uk are type parameters representing the types of its upvars
///   (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
///    and the up-var has the type `Foo`, then `Ui = &Foo`).
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
///
/// So, for example, given this function:
///
///     fn foo<'a, T>(data: &'a mut T) {
///          do(|| data.count += 1)
///     }
///
/// the type of the closure would be something like:
///
///     struct Closure<'a, T, U0> {
///         data: U0
///     }
///
/// Note that the type of the upvar is not specified in the struct.
/// You may wonder how the impl would then be able to use the upvar,
/// if it doesn't know it's type? The answer is that the impl is
/// (conceptually) not fully generic over Closure but rather tied to
/// instances with the expected upvar types:
///
///     impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
///         ...
///     }
///
/// You can see that the *impl* fully specified the type of the upvar
/// and thus knows full well that `data` has type `&'b mut &'a mut T`.
/// (Here, I am assuming that `data` is mut-borrowed.)
///
/// Now, the last question you may ask is: Why include the upvar types
/// as extra type parameters? The reason for this design is that the
/// upvar types can reference lifetimes that are internal to the
/// creating function. In my example above, for example, the lifetime
255 256
/// `'b` represents the scope of the closure itself; this is some
/// subset of `foo`, probably just the scope of the call to the to
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
/// `do()`. If we just had the lifetime/type parameters from the
/// enclosing function, we couldn't name this lifetime `'b`. Note that
/// there can also be lifetimes in the types of the upvars themselves,
/// if one of them happens to be a reference to something that the
/// creating fn owns.
///
/// OK, you say, so why not create a more minimal set of parameters
/// that just includes the extra lifetime parameters? The answer is
/// primarily that it would be hard --- we don't know at the time when
/// we create the closure type what the full types of the upvars are,
/// nor do we know which are borrowed and which are not. In this
/// design, we can just supply a fresh type parameter and figure that
/// out later.
///
/// All right, you say, but why include the type parameters from the
I
Irina Popa 已提交
272
/// original function then? The answer is that codegen may need them
273 274 275 276 277 278 279 280 281 282 283 284 285
/// when monomorphizing, and they may not appear in the upvars.  A
/// closure could capture no variables but still make use of some
/// in-scope type parameter with a bound (e.g., if our example above
/// had an extra `U: Default`, and the closure called `U::default()`).
///
/// There is another reason. This design (implicitly) prohibits
/// closures from capturing themselves (except via a trait
/// object). This simplifies closure inference considerably, since it
/// means that when we infer the kind of a closure or its upvars, we
/// don't have to handle cycles where the decisions we make for
/// closure C wind up influencing the decisions we ought to make for
/// closure C (which would then require fixed point iteration to
/// handle). Plus it fixes an ICE. :P
286 287 288 289 290 291 292 293 294 295 296
///
/// ## Generators
///
/// Perhaps surprisingly, `ClosureSubsts` are also used for
/// generators.  In that case, what is written above is only half-true
/// -- the set of type parameters is similar, but the role of CK and
/// CS are different.  CK represents the "yield type" and CS
/// represents the "return type" of the generator.
///
/// It'd be nice to split this struct into ClosureSubsts and
/// GeneratorSubsts, I believe. -nmatsakis
297
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
298
pub struct ClosureSubsts<'tcx> {
299 300 301
    /// Lifetime and type parameters from the enclosing function,
    /// concatenated with the types of the upvars.
    ///
I
Irina Popa 已提交
302
    /// These are separated out because codegen wants to pass them around
303
    /// when monomorphizing.
304 305
    pub substs: &'tcx Substs<'tcx>,
}
306

307 308 309 310
/// Struct returned by `split()`. Note that these are subslices of the
/// parent slice and not canonical substs themselves.
struct SplitClosureSubsts<'tcx> {
    closure_kind_ty: Ty<'tcx>,
311
    closure_sig_ty: Ty<'tcx>,
312 313 314 315 316 317 318 319 320
    upvar_kinds: &'tcx [Kind<'tcx>],
}

impl<'tcx> ClosureSubsts<'tcx> {
    /// Divides the closure substs into their respective
    /// components. Single source of truth with respect to the
    /// ordering.
    fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitClosureSubsts<'tcx> {
        let generics = tcx.generics_of(def_id);
V
varkor 已提交
321
        let parent_len = generics.parent_count;
322
        SplitClosureSubsts {
V
varkor 已提交
323 324
            closure_kind_ty: self.substs.type_at(parent_len),
            closure_sig_ty: self.substs.type_at(parent_len + 1),
325
            upvar_kinds: &self.substs[parent_len + 2..],
326 327 328
        }
    }

329
    #[inline]
330
    pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
331 332
        impl Iterator<Item=Ty<'tcx>> + 'tcx
    {
333
        let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
V
varkor 已提交
334 335 336 337 338 339 340
        upvar_kinds.iter().map(|t| {
            if let UnpackedKind::Type(ty) = t.unpack() {
                ty
            } else {
                bug!("upvar should be type")
            }
        })
341 342
    }

343
    /// Returns the closure kind for this closure; may return a type
344 345
    /// variable during inference. To get the closure kind during
    /// inference, use `infcx.closure_kind(def_id, substs)`.
346 347 348
    pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
        self.split(def_id, tcx).closure_kind_ty
    }
349 350

    /// Returns the type representing the closure signature for this
351 352 353
    /// closure; may contain type variables during inference. To get
    /// the closure signature during inference, use
    /// `infcx.fn_sig(def_id)`.
354 355 356
    pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
        self.split(def_id, tcx).closure_sig_ty
    }
357

358
    /// Returns the closure kind for this closure; only usable outside
359 360
    /// of an inference context, because in that context we know that
    /// there are no type variables.
361 362
    ///
    /// If you have an inference context, use `infcx.closure_kind()`.
363
    pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::ClosureKind {
364
        self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
365
    }
366 367 368 369

    /// Extracts the signature from the closure; only usable outside
    /// of an inference context, because in that context we know that
    /// there are no type variables.
370 371
    ///
    /// If you have an inference context, use `infcx.closure_sig()`.
372 373
    pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::PolyFnSig<'tcx> {
        match self.closure_sig_ty(def_id, tcx).sty {
V
varkor 已提交
374
            ty::FnPtr(sig) => sig,
375 376 377
            ref t => bug!("closure_sig_ty is not a fn-ptr: {:?}", t),
        }
    }
378 379
}

380
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
381 382 383 384 385 386 387 388 389 390 391 392 393 394
pub struct GeneratorSubsts<'tcx> {
    pub substs: &'tcx Substs<'tcx>,
}

struct SplitGeneratorSubsts<'tcx> {
    yield_ty: Ty<'tcx>,
    return_ty: Ty<'tcx>,
    witness: Ty<'tcx>,
    upvar_kinds: &'tcx [Kind<'tcx>],
}

impl<'tcx> GeneratorSubsts<'tcx> {
    fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitGeneratorSubsts<'tcx> {
        let generics = tcx.generics_of(def_id);
V
varkor 已提交
395
        let parent_len = generics.parent_count;
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
        SplitGeneratorSubsts {
            yield_ty: self.substs.type_at(parent_len),
            return_ty: self.substs.type_at(parent_len + 1),
            witness: self.substs.type_at(parent_len + 2),
            upvar_kinds: &self.substs[parent_len + 3..],
        }
    }

    /// This describes the types that can be contained in a generator.
    /// It will be a type variable initially and unified in the last stages of typeck of a body.
    /// It contains a tuple of all the types that could end up on a generator frame.
    /// The state transformation MIR pass may only produce layouts which mention types
    /// in this tuple. Upvars are not counted here.
    pub fn witness(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
        self.split(def_id, tcx).witness
    }

    #[inline]
    pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
        impl Iterator<Item=Ty<'tcx>> + 'tcx
    {
        let SplitGeneratorSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
        upvar_kinds.iter().map(|t| {
            if let UnpackedKind::Type(ty) = t.unpack() {
                ty
            } else {
                bug!("upvar should be type")
            }
        })
    }

    /// Returns the type representing the yield type of the generator.
    pub fn yield_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
        self.split(def_id, tcx).yield_ty
    }

    /// Returns the type representing the return type of the generator.
    pub fn return_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
        self.split(def_id, tcx).return_ty
    }

    /// Return the "generator signature", which consists of its yield
    /// and return types.
    ///
    /// NB. Some bits of the code prefers to see this wrapped in a
    /// binder, but it never contains bound regions. Probably this
    /// function should be removed.
    pub fn poly_sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> PolyGenSig<'tcx> {
        ty::Binder::dummy(self.sig(def_id, tcx))
    }

    /// Return the "generator signature", which consists of its yield
    /// and return types.
    pub fn sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> GenSig<'tcx> {
        ty::GenSig {
            yield_ty: self.yield_ty(def_id, tcx),
            return_ty: self.return_ty(def_id, tcx),
        }
    }
}

impl<'a, 'gcx, 'tcx> GeneratorSubsts<'tcx> {
J
John Kåre Alsaker 已提交
458 459 460
    /// This returns the types of the MIR locals which had to be stored across suspension points.
    /// It is calculated in rustc_mir::transform::generator::StateTransform.
    /// All the types here must be in the tuple in GeneratorInterior.
461 462 463 464 465
    pub fn state_tys(
        self,
        def_id: DefId,
        tcx: TyCtxt<'a, 'gcx, 'tcx>,
    ) -> impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a {
J
John Kåre Alsaker 已提交
466
        let state = tcx.generator_layout(def_id).fields.iter();
J
John Kåre Alsaker 已提交
467
        state.map(move |d| d.ty.subst(tcx, self.substs))
J
John Kåre Alsaker 已提交
468 469
    }

470 471 472 473 474 475 476 477 478
    /// This is the types of the fields of a generate which
    /// is available before the generator transformation.
    /// It includes the upvars and the state discriminant which is u32.
    pub fn pre_transforms_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
        impl Iterator<Item=Ty<'tcx>> + 'a
    {
        self.upvar_tys(def_id, tcx).chain(iter::once(tcx.types.u32))
    }

J
John Kåre Alsaker 已提交
479 480
    /// This is the types of all the fields stored in a generator.
    /// It includes the upvars, state types and the state discriminant which is u32.
J
John Kåre Alsaker 已提交
481
    pub fn field_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
482
        impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a
J
John Kåre Alsaker 已提交
483
    {
484
        self.pre_transforms_tys(def_id, tcx).chain(self.state_tys(def_id, tcx))
J
John Kåre Alsaker 已提交
485 486 487
    }
}

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
#[derive(Debug, Copy, Clone)]
pub enum UpvarSubsts<'tcx> {
    Closure(ClosureSubsts<'tcx>),
    Generator(GeneratorSubsts<'tcx>),
}

impl<'tcx> UpvarSubsts<'tcx> {
    #[inline]
    pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
        impl Iterator<Item=Ty<'tcx>> + 'tcx
    {
        let upvar_kinds = match self {
            UpvarSubsts::Closure(substs) => substs.split(def_id, tcx).upvar_kinds,
            UpvarSubsts::Generator(substs) => substs.split(def_id, tcx).upvar_kinds,
        };
        upvar_kinds.iter().map(|t| {
            if let UnpackedKind::Type(ty) = t.unpack() {
                ty
            } else {
                bug!("upvar should be type")
            }
        })
    }
J
John Kåre Alsaker 已提交
511 512
}

513
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, RustcEncodable, RustcDecodable)]
514
pub enum ExistentialPredicate<'tcx> {
515
    /// e.g. Iterator
516
    Trait(ExistentialTraitRef<'tcx>),
517
    /// e.g. Iterator::Item = T
518
    Projection(ExistentialProjection<'tcx>),
519
    /// e.g. Send
520
    AutoTrait(DefId),
521 522
}

523
impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
524 525 526
    /// Compares via an ordering that will not change if modules are reordered or other changes are
    /// made to the tree. In particular, this ordering is preserved across incremental compilations.
    pub fn stable_cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
527 528 529
        use self::ExistentialPredicate::*;
        match (*self, *other) {
            (Trait(_), Trait(_)) => Ordering::Equal,
530 531
            (Projection(ref a), Projection(ref b)) =>
                tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
532
            (AutoTrait(ref a), AutoTrait(ref b)) =>
533
                tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
            (Trait(_), _) => Ordering::Less,
            (Projection(_), Trait(_)) => Ordering::Greater,
            (Projection(_), _) => Ordering::Less,
            (AutoTrait(_), _) => Ordering::Greater,
        }
    }

}

impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
    pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
        -> ty::Predicate<'tcx> {
        use ty::ToPredicate;
        match *self.skip_binder() {
            ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
            ExistentialPredicate::Projection(p) =>
                ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
            ExistentialPredicate::AutoTrait(did) => {
                let trait_ref = Binder(ty::TraitRef {
                    def_id: did,
                    substs: tcx.mk_substs_trait(self_ty, &[]),
                });
                trait_ref.to_predicate()
            }
        }
    }
}

V
varkor 已提交
562
impl<'tcx> serialize::UseSpecializedDecodable for &'tcx List<ExistentialPredicate<'tcx>> {}
563

V
varkor 已提交
564
impl<'tcx> List<ExistentialPredicate<'tcx>> {
565 566 567 568
    pub fn principal(&self) -> ExistentialTraitRef<'tcx> {
        match self[0] {
            ExistentialPredicate::Trait(tr) => tr,
            other => bug!("first predicate is {:?}", other),
569 570 571
        }
    }

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    #[inline]
    pub fn projection_bounds<'a>(&'a self) ->
        impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
        self.iter().filter_map(|predicate| {
            match *predicate {
                ExistentialPredicate::Projection(p) => Some(p),
                _ => None,
            }
        })
    }

    #[inline]
    pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
        self.iter().filter_map(|predicate| {
            match *predicate {
                ExistentialPredicate::AutoTrait(d) => Some(d),
                _ => None
            }
        })
    }
}

V
varkor 已提交
594
impl<'tcx> Binder<&'tcx List<ExistentialPredicate<'tcx>>> {
595 596
    pub fn principal(&self) -> PolyExistentialTraitRef<'tcx> {
        Binder::bind(self.skip_binder().principal())
597 598 599 600 601
    }

    #[inline]
    pub fn projection_bounds<'a>(&'a self) ->
        impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
602
        self.skip_binder().projection_bounds().map(Binder::bind)
603
    }
604

605
    #[inline]
606
    pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
607 608 609 610 611
        self.skip_binder().auto_traits()
    }

    pub fn iter<'a>(&'a self)
        -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
612
        self.skip_binder().iter().cloned().map(Binder::bind)
613
    }
614 615
}

616 617 618 619 620 621
/// A complete reference to a trait. These take numerous guises in syntax,
/// but perhaps the most recognizable form is in a where clause:
///
///     T : Foo<U>
///
/// This would be represented by a trait-reference where the def-id is the
622 623
/// def-id for the trait `Foo` and the substs define `T` as parameter 0,
/// and `U` as parameter 1.
624 625 626 627 628 629 630
///
/// Trait references also appear in object types like `Foo<U>`, but in
/// that case the `Self` parameter is absent from the substitutions.
///
/// Note that a `TraitRef` introduces a level of region binding, to
/// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
/// U>` or higher-ranked object types.
631
#[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
632 633 634 635 636
pub struct TraitRef<'tcx> {
    pub def_id: DefId,
    pub substs: &'tcx Substs<'tcx>,
}

637 638 639 640 641
impl<'tcx> TraitRef<'tcx> {
    pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
        TraitRef { def_id: def_id, substs: substs }
    }

642 643 644 645 646 647 648 649 650
    /// Returns a TraitRef of the form `P0: Foo<P1..Pn>` where `Pi`
    /// are the parameters defined on trait.
    pub fn identity<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, def_id: DefId) -> TraitRef<'tcx> {
        TraitRef {
            def_id,
            substs: Substs::identity_for_item(tcx, def_id),
        }
    }

651 652 653 654 655 656 657 658 659 660 661
    pub fn self_ty(&self) -> Ty<'tcx> {
        self.substs.type_at(0)
    }

    pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
        // Select only the "input types" from a trait-reference. For
        // now this is all the types that appear in the
        // trait-reference, but it should eventually exclude
        // associated types.
        self.substs.types()
    }
662 663 664 665 666 667 668 669 670 671 672 673

    pub fn from_method(tcx: TyCtxt<'_, '_, 'tcx>,
                       trait_id: DefId,
                       substs: &Substs<'tcx>)
                       -> ty::TraitRef<'tcx> {
        let defs = tcx.generics_of(trait_id);

        ty::TraitRef {
            def_id: trait_id,
            substs: tcx.intern_substs(&substs[..defs.params.len()])
        }
    }
674 675
}

676 677 678 679
pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;

impl<'tcx> PolyTraitRef<'tcx> {
    pub fn self_ty(&self) -> Ty<'tcx> {
680
        self.skip_binder().self_ty()
681 682 683
    }

    pub fn def_id(&self) -> DefId {
684
        self.skip_binder().def_id
685 686 687 688
    }

    pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
        // Note that we preserve binding levels
689
        Binder(ty::TraitPredicate { trait_ref: self.skip_binder().clone() })
690 691 692
    }
}

693 694 695 696 697 698 699
/// An existential reference to a trait, where `Self` is erased.
/// For example, the trait object `Trait<'a, 'b, X, Y>` is:
///
///     exists T. T: Trait<'a, 'b, X, Y>
///
/// The substitutions don't include the erased `Self`, only trait
/// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
700
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
701 702 703 704 705
pub struct ExistentialTraitRef<'tcx> {
    pub def_id: DefId,
    pub substs: &'tcx Substs<'tcx>,
}

706 707
impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
    pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
708 709 710 711
        // Select only the "input types" from a trait-reference. For
        // now this is all the types that appear in the
        // trait-reference, but it should eventually exclude
        // associated types.
712
        self.substs.types()
713
    }
714

715 716 717 718 719 720 721 722 723 724 725 726
    pub fn erase_self_ty(tcx: TyCtxt<'a, 'gcx, 'tcx>,
                         trait_ref: ty::TraitRef<'tcx>)
                         -> ty::ExistentialTraitRef<'tcx> {
        // Assert there is a Self.
        trait_ref.substs.type_at(0);

        ty::ExistentialTraitRef {
            def_id: trait_ref.def_id,
            substs: tcx.intern_substs(&trait_ref.substs[1..])
        }
    }

727 728 729
    /// Object types don't have a self-type specified. Therefore, when
    /// we convert the principal trait-ref into a normal trait-ref,
    /// you must give *some* self-type. A common choice is `mk_err()`
N
Niko Matsakis 已提交
730
    /// or some placeholder type.
731 732
    pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
        -> ty::TraitRef<'tcx>  {
733 734
        // otherwise the escaping vars would be captured by the binder
        // debug_assert!(!self_ty.has_escaping_bound_vars());
735 736 737

        ty::TraitRef {
            def_id: self.def_id,
738
            substs: tcx.mk_substs_trait(self_ty, self.substs)
739 740
        }
    }
741 742 743 744
}

pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;

745
impl<'tcx> PolyExistentialTraitRef<'tcx> {
746
    pub fn def_id(&self) -> DefId {
747
        self.skip_binder().def_id
748
    }
749 750 751 752

    /// Object types don't have a self-type specified. Therefore, when
    /// we convert the principal trait-ref into a normal trait-ref,
    /// you must give *some* self-type. A common choice is `mk_err()`
N
Niko Matsakis 已提交
753
    /// or some placeholder type.
754 755 756 757 758
    pub fn with_self_ty(&self, tcx: TyCtxt<'_, '_, 'tcx>,
                        self_ty: Ty<'tcx>)
                        -> ty::PolyTraitRef<'tcx>  {
        self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty))
    }
759 760
}

761 762 763
/// Binder is a binder for higher-ranked lifetimes. It is part of the
/// compiler's representation for things like `for<'a> Fn(&'a isize)`
/// (which would be represented by the type `PolyTraitRef ==
764
/// Binder<TraitRef>`). Note that when we instantiate,
765 766 767
/// erase, or otherwise "discharge" these bound regions, we change the
/// type from `Binder<T>` to just `T` (see
/// e.g. `liberate_late_bound_regions`).
768
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
769
pub struct Binder<T>(T);
770 771

impl<T> Binder<T> {
772 773 774 775
    /// Wraps `value` in a binder, asserting that `value` does not
    /// contain any bound regions that would be bound by the
    /// binder. This is commonly used to 'inject' a value T into a
    /// different binding level.
776
    pub fn dummy<'tcx>(value: T) -> Binder<T>
777 778
        where T: TypeFoldable<'tcx>
    {
779
        debug_assert!(!value.has_escaping_bound_vars());
780 781 782
        Binder(value)
    }

783 784 785 786 787 788
    /// Wraps `value` in a binder, binding late-bound regions (if any).
    pub fn bind<'tcx>(value: T) -> Binder<T>
    {
        Binder(value)
    }

789 790 791 792 793 794 795 796 797 798 799 800
    /// Skips the binder and returns the "bound" value. This is a
    /// risky thing to do because it's easy to get confused about
    /// debruijn indices and the like. It is usually better to
    /// discharge the binder using `no_late_bound_regions` or
    /// `replace_late_bound_regions` or something like
    /// that. `skip_binder` is only valid when you are either
    /// extracting data that has nothing to do with bound regions, you
    /// are doing some sort of test that does not involve bound
    /// regions, or you are being very careful about your depth
    /// accounting.
    ///
    /// Some examples where `skip_binder` is reasonable:
801
    ///
802 803 804 805 806 807 808 809
    /// - extracting the def-id from a PolyTraitRef;
    /// - comparing the self type of a PolyTraitRef to see if it is equal to
    ///   a type parameter `X`, since the type `X`  does not reference any regions
    pub fn skip_binder(&self) -> &T {
        &self.0
    }

    pub fn as_ref(&self) -> Binder<&T> {
810
        Binder(&self.0)
811 812
    }

T
Tshepang Lekhonkhobe 已提交
813
    pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
814 815 816 817 818
        where F: FnOnce(&T) -> U
    {
        self.as_ref().map_bound(f)
    }

T
Tshepang Lekhonkhobe 已提交
819
    pub fn map_bound<F, U>(self, f: F) -> Binder<U>
820 821
        where F: FnOnce(T) -> U
    {
822
        Binder(f(self.0))
823
    }
824 825 826 827 828 829 830 831 832 833 834 835 836 837

    /// Unwraps and returns the value within, but only if it contains
    /// no bound regions at all. (In other words, if this binder --
    /// and indeed any enclosing binder -- doesn't bind anything at
    /// all.) Otherwise, returns `None`.
    ///
    /// (One could imagine having a method that just unwraps a single
    /// binder, but permits late-bound regions bound by enclosing
    /// binders, but that would require adjusting the debruijn
    /// indices, and given the shallow binding structure we often use,
    /// would not be that useful.)
    pub fn no_late_bound_regions<'tcx>(self) -> Option<T>
        where T : TypeFoldable<'tcx>
    {
838
        if self.skip_binder().has_escaping_bound_vars() {
839 840 841 842 843
            None
        } else {
            Some(self.skip_binder().clone())
        }
    }
844 845 846 847 848 849 850 851 852 853 854

    /// Given two things that have the same binder level,
    /// and an operation that wraps on their contents, execute the operation
    /// and then wrap its result.
    ///
    /// `f` should consider bound regions at depth 1 to be free, and
    /// anything it produces with bound regions at depth 1 will be
    /// bound in the resulting return value.
    pub fn fuse<U,F,R>(self, u: Binder<U>, f: F) -> Binder<R>
        where F: FnOnce(T, U) -> R
    {
855
        Binder(f(self.0, u.0))
856 857 858 859 860 861 862 863 864 865 866 867
    }

    /// Split the contents into two things that share the same binder
    /// level as the original, returning two distinct binders.
    ///
    /// `f` should consider bound regions at depth 1 to be free, and
    /// anything it produces with bound regions at depth 1 will be
    /// bound in the resulting return values.
    pub fn split<U,V,F>(self, f: F) -> (Binder<U>, Binder<V>)
        where F: FnOnce(T) -> (U, V)
    {
        let (u, v) = f(self.0);
868
        (Binder(u), Binder(v))
869
    }
870 871 872 873
}

/// Represents the projection of an associated type. In explicit UFCS
/// form this would be written `<T as Trait<..>>::N`.
874
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
875
pub struct ProjectionTy<'tcx> {
876 877
    /// The parameters of the associated item.
    pub substs: &'tcx Substs<'tcx>,
878

879 880 881 882 883 884 885 886 887 888 889
    /// The DefId of the TraitItem for the associated type N.
    ///
    /// Note that this is not the DefId of the TraitRef containing this
    /// associated type, which is in tcx.associated_item(item_def_id).container.
    pub item_def_id: DefId,
}

impl<'a, 'tcx> ProjectionTy<'tcx> {
    /// Construct a ProjectionTy by searching the trait from trait_ref for the
    /// associated item named item_name.
    pub fn from_ref_and_name(
890
        tcx: TyCtxt<'_, '_, '_>, trait_ref: ty::TraitRef<'tcx>, item_name: Ident
891
    ) -> ProjectionTy<'tcx> {
892 893
        let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
            item.kind == ty::AssociatedKind::Type &&
894
            tcx.hygienic_eq(item_name, item.ident, trait_ref.def_id)
895
        }).unwrap().def_id;
896 897

        ProjectionTy {
898
            substs: trait_ref.substs,
899
            item_def_id,
900 901 902
        }
    }

903 904 905
    /// Extracts the underlying trait reference from this projection.
    /// For example, if this is a projection of `<T as Iterator>::Item`,
    /// then this function would return a `T: Iterator` trait reference.
906
    pub fn trait_ref(&self, tcx: TyCtxt<'_, '_, '_>) -> ty::TraitRef<'tcx> {
907 908
        let def_id = tcx.associated_item(self.item_def_id).container.id();
        ty::TraitRef {
909
            def_id,
910 911 912 913 914 915
            substs: self.substs,
        }
    }

    pub fn self_ty(&self) -> Ty<'tcx> {
        self.substs.type_at(0)
916
    }
917
}
918

J
John Kåre Alsaker 已提交
919 920
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
pub struct GenSig<'tcx> {
J
John Kåre Alsaker 已提交
921
    pub yield_ty: Ty<'tcx>,
J
John Kåre Alsaker 已提交
922 923 924 925 926 927
    pub return_ty: Ty<'tcx>,
}

pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;

impl<'tcx> PolyGenSig<'tcx> {
J
John Kåre Alsaker 已提交
928 929
    pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
        self.map_bound_ref(|sig| sig.yield_ty)
J
John Kåre Alsaker 已提交
930 931 932 933 934
    }
    pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
        self.map_bound_ref(|sig| sig.return_ty)
    }
}
935

936 937 938 939 940 941
/// Signature of a function type, which I have arbitrarily
/// decided to use to refer to the input/output types.
///
/// - `inputs` is the list of arguments and their modes.
/// - `output` is the return type.
/// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
942
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
943
pub struct FnSig<'tcx> {
V
varkor 已提交
944
    pub inputs_and_output: &'tcx List<Ty<'tcx>>,
945 946 947
    pub variadic: bool,
    pub unsafety: hir::Unsafety,
    pub abi: abi::Abi,
948 949 950
}

impl<'tcx> FnSig<'tcx> {
951
    pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
952
        &self.inputs_and_output[..self.inputs_and_output.len() - 1]
953 954 955
    }

    pub fn output(&self) -> Ty<'tcx> {
956
        self.inputs_and_output[self.inputs_and_output.len() - 1]
957
    }
958 959 960 961 962
}

pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;

impl<'tcx> PolyFnSig<'tcx> {
963
    pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
964
        self.map_bound_ref(|fn_sig| fn_sig.inputs())
965 966
    }
    pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
967
        self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
968
    }
V
varkor 已提交
969
    pub fn inputs_and_output(&self) -> ty::Binder<&'tcx List<Ty<'tcx>>> {
970 971
        self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
    }
972
    pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
S
Shotaro Yamada 已提交
973
        self.map_bound_ref(|fn_sig| fn_sig.output())
974 975 976 977
    }
    pub fn variadic(&self) -> bool {
        self.skip_binder().variadic
    }
978 979 980 981 982 983
    pub fn unsafety(&self) -> hir::Unsafety {
        self.skip_binder().unsafety
    }
    pub fn abi(&self) -> abi::Abi {
        self.skip_binder().abi
    }
984 985
}

986 987 988
pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<FnSig<'tcx>>>;


989
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
990 991
pub struct ParamTy {
    pub idx: u32,
992
    pub name: InternedString,
993 994
}

995
impl<'a, 'gcx, 'tcx> ParamTy {
996
    pub fn new(index: u32, name: InternedString) -> ParamTy {
997
        ParamTy { idx: index, name: name }
998 999 1000
    }

    pub fn for_self() -> ParamTy {
1001
        ParamTy::new(0, keywords::SelfType.name().as_interned_str())
1002 1003
    }

1004
    pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1005
        ParamTy::new(def.index, def.name)
1006 1007
    }

1008
    pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1009
        tcx.mk_ty_param(self.idx, self.name)
1010 1011 1012
    }

    pub fn is_self(&self) -> bool {
J
Josh Stone 已提交
1013 1014 1015
        // FIXME(#50125): Ignoring `Self` with `idx != 0` might lead to weird behavior elsewhere,
        // but this should only be possible when using `-Z continue-parse-after-error` like
        // `compile-fail/issue-36638.rs`.
L
ljedrz 已提交
1016
        self.name == keywords::SelfType.name().as_str() && self.idx == 0
1017 1018 1019
    }
}

1020 1021 1022 1023 1024 1025 1026
/// A [De Bruijn index][dbi] is a standard means of representing
/// regions (and perhaps later types) in a higher-ranked setting. In
/// particular, imagine a type like this:
///
///     for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
///     ^          ^            |        |         |
///     |          |            |        |         |
N
Niko Matsakis 已提交
1027
///     |          +------------+ 0      |         |
1028
///     |                                |         |
N
Niko Matsakis 已提交
1029
///     +--------------------------------+ 1       |
1030
///     |                                          |
N
Niko Matsakis 已提交
1031
///     +------------------------------------------+ 0
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
///
/// In this type, there are two binders (the outer fn and the inner
/// fn). We need to be able to determine, for any given region, which
/// fn type it is bound by, the inner or the outer one. There are
/// various ways you can do this, but a De Bruijn index is one of the
/// more convenient and has some nice properties. The basic idea is to
/// count the number of binders, inside out. Some examples should help
/// clarify what I mean.
///
/// Let's start with the reference type `&'b isize` that is the first
/// argument to the inner function. This region `'b` is assigned a De
N
Niko Matsakis 已提交
1043
/// Bruijn index of 0, meaning "the innermost binder" (in this case, a
1044
/// fn). The region `'a` that appears in the second argument type (`&'a
N
Niko Matsakis 已提交
1045
/// isize`) would then be assigned a De Bruijn index of 1, meaning "the
1046 1047 1048 1049 1050 1051 1052 1053 1054
/// second-innermost binder". (These indices are written on the arrays
/// in the diagram).
///
/// What is interesting is that De Bruijn index attached to a particular
/// variable will vary depending on where it appears. For example,
/// the final type `&'a char` also refers to the region `'a` declared on
/// the outermost fn. But this time, this reference is not nested within
/// any other binders (i.e., it is not an argument to the inner fn, but
/// rather the outer one). Therefore, in this case, it is assigned a
N
Niko Matsakis 已提交
1055
/// De Bruijn index of 0, because the innermost binder in that location
1056 1057 1058
/// is the outer fn.
///
/// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1059 1060
newtype_index! {
    pub struct DebruijnIndex {
1061
        DEBUG_FORMAT = "DebruijnIndex({})",
1062
        const INNERMOST = 0,
1063 1064
    }
}
1065

1066
pub type Region<'tcx> = &'tcx RegionKind;
N
Niko Matsakis 已提交
1067

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
/// Representation of regions.
///
/// Unlike types, most region variants are "fictitious", not concrete,
/// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
/// ones representing concrete regions.
///
/// ## Bound Regions
///
/// These are regions that are stored behind a binder and must be substituted
/// with some concrete region before being used. There are 2 kind of
1078
/// bound regions: early-bound, which are bound in an item's Generics,
1079 1080 1081 1082 1083
/// and are substituted by a Substs,  and late-bound, which are part of
/// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
/// the likes of `liberate_late_bound_regions`. The distinction exists
/// because higher-ranked lifetimes aren't supported in all places. See [1][2].
///
V
varkor 已提交
1084
/// Unlike Param-s, bound regions are not supposed to exist "in the wild"
1085
/// outside their binder, e.g. in types passed to type inference, and
N
Niko Matsakis 已提交
1086
/// should first be substituted (by placeholder regions, free regions,
1087 1088
/// or region variables).
///
N
Niko Matsakis 已提交
1089
/// ## Placeholder and Free Regions
1090 1091 1092 1093 1094 1095 1096
///
/// One often wants to work with bound regions without knowing their precise
/// identity. For example, when checking a function, the lifetime of a borrow
/// can end up being assigned to some region parameter. In these cases,
/// it must be ensured that bounds on the region can't be accidentally
/// assumed without being checked.
///
1097 1098
/// To do this, we replace the bound regions with placeholder markers,
/// which don't satisfy any relation not explicitly provided.
1099
///
N
Niko Matsakis 已提交
1100 1101
/// There are 2 kinds of placeholder regions in rustc: `ReFree` and
/// `RePlaceholder`. When checking an item's body, `ReFree` is supposed
1102 1103 1104
/// to be used. These also support explicit bounds: both the internally-stored
/// *scope*, which the region is assumed to outlive, as well as other
/// relations stored in the `FreeRegionMap`. Note that these relations
1105
/// aren't checked when you `make_subregion` (or `eq_types`), only by
1106 1107 1108 1109
/// `resolve_regions_and_report_errors`.
///
/// When working with higher-ranked types, some region relations aren't
/// yet known, so you can't just call `resolve_regions_and_report_errors`.
N
Niko Matsakis 已提交
1110
/// `RePlaceholder` is designed for this purpose. In these contexts,
1111
/// there's also the risk that some inference variable laying around will
N
Niko Matsakis 已提交
1112
/// get unified with your placeholder region: if you want to check whether
1113
/// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
N
Niko Matsakis 已提交
1114 1115
/// with a placeholder region `'%a`, the variable `'_` would just be
/// instantiated to the placeholder region `'%a`, which is wrong because
1116
/// the inference variable is supposed to satisfy the relation
N
Niko Matsakis 已提交
1117
/// *for every value of the placeholder region*. To ensure that doesn't
1118
/// happen, you can use `leak_check`. This is more clearly explained
1119
/// by the [rustc guide].
1120
///
1121 1122
/// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
/// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
A
Alex Kitchens 已提交
1123
/// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/traits/hrtb.html
C
Cengiz Can 已提交
1124
#[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1125
pub enum RegionKind {
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    // Region bound in a type or fn declaration which will be
    // substituted 'early' -- that is, at the same time when type
    // parameters are substituted.
    ReEarlyBound(EarlyBoundRegion),

    // Region bound in a function scope, which will be substituted when the
    // function is called.
    ReLateBound(DebruijnIndex, BoundRegion),

    /// When checking a function body, the types of all arguments and so forth
    /// that refer to bound region parameters are modified to refer to free
    /// region parameters.
1138
    ReFree(FreeRegion),
1139

1140
    /// A concrete region naming some statically determined scope
1141 1142
    /// (e.g. an expression or sequence of statements) within the
    /// current function.
1143
    ReScope(region::Scope),
1144 1145 1146 1147 1148 1149 1150

    /// Static data that has an "infinite" lifetime. Top in the region lattice.
    ReStatic,

    /// A region variable.  Should not exist after typeck.
    ReVar(RegionVid),

N
Niko Matsakis 已提交
1151
    /// A placeholder region - basically the higher-ranked version of ReFree.
1152
    /// Should not exist after typeck.
1153
    RePlaceholder(ty::Placeholder),
1154 1155 1156 1157 1158 1159 1160 1161 1162

    /// Empty lifetime is for data that is never accessed.
    /// Bottom in the region lattice. We treat ReEmpty somewhat
    /// specially; at least right now, we do not generate instances of
    /// it during the GLB computations, but rather
    /// generate an error instead. This is to improve error messages.
    /// The only way to get an instance of ReEmpty is to have a region
    /// variable with no constraints.
    ReEmpty,
1163

I
Irina Popa 已提交
1164
    /// Erased region, used by trait selection, in MIR and during codegen.
1165
    ReErased,
1166 1167 1168 1169 1170 1171

    /// These are regions bound in the "defining type" for a
    /// closure. They are used ONLY as part of the
    /// `ClosureRegionRequirements` that are produced by MIR borrowck.
    /// See `ClosureRegionRequirements` for more details.
    ReClosureBound(RegionVid),
1172 1173

    /// Canonicalized region, used only when preparing a trait query.
S
scalexm 已提交
1174
    ReCanonical(BoundVar),
1175 1176
}

N
Niko Matsakis 已提交
1177
impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
1178

C
Cengiz Can 已提交
1179
#[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1180
pub struct EarlyBoundRegion {
1181
    pub def_id: DefId,
1182
    pub index: u32,
1183
    pub name: InternedString,
1184 1185
}

1186
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1187
pub struct TyVid {
N
Niko Matsakis 已提交
1188
    pub index: u32,
1189 1190
}

1191
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1192
pub struct IntVid {
T
Tshepang Lekhonkhobe 已提交
1193
    pub index: u32,
1194 1195
}

1196
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1197
pub struct FloatVid {
T
Tshepang Lekhonkhobe 已提交
1198
    pub index: u32,
1199 1200
}

1201 1202
newtype_index! {
    pub struct RegionVid {
1203
        DEBUG_FORMAT = custom,
1204 1205
    }
}
1206

1207 1208 1209 1210 1211 1212
impl Atom for RegionVid {
    fn index(self) -> usize {
        Idx::index(self)
    }
}

1213
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1214 1215 1216 1217 1218 1219 1220
pub enum InferTy {
    TyVar(TyVid),
    IntVar(IntVid),
    FloatVar(FloatVid),

    /// A `FreshTy` is one that is generated as a replacement for an
    /// unbound type variable. This is convenient for caching etc. See
1221
    /// `infer::freshen` for more details.
1222 1223
    FreshTy(u32),
    FreshIntTy(u32),
T
Tshepang Lekhonkhobe 已提交
1224
    FreshFloatTy(u32),
1225 1226
}

1227
newtype_index! {
S
scalexm 已提交
1228
    pub struct BoundVar { .. }
1229
}
1230

1231 1232 1233
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
pub struct BoundTy {
    pub level: DebruijnIndex,
S
scalexm 已提交
1234
    pub var: BoundVar,
S
scalexm 已提交
1235
    pub kind: BoundTyKind,
1236 1237
}

S
scalexm 已提交
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
pub enum BoundTyKind {
    Anon,
    Param(InternedString),
}

impl_stable_hash_for!(struct BoundTy { level, var, kind });
impl_stable_hash_for!(enum self::BoundTyKind { Anon, Param(a) });

impl BoundTy {
S
scalexm 已提交
1248
    pub fn new(level: DebruijnIndex, var: BoundVar) -> Self {
S
scalexm 已提交
1249 1250 1251 1252 1253 1254 1255
        BoundTy {
            level,
            var,
            kind: BoundTyKind::Anon,
        }
    }
}
1256

1257
/// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1258
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1259
pub struct ExistentialProjection<'tcx> {
1260 1261
    pub item_def_id: DefId,
    pub substs: &'tcx Substs<'tcx>,
T
Tshepang Lekhonkhobe 已提交
1262
    pub ty: Ty<'tcx>,
1263 1264
}

1265 1266
pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;

1267
impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
1268 1269 1270 1271
    /// Extracts the underlying existential trait reference from this projection.
    /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
    /// then this function would return a `exists T. T: Iterator` existential trait
    /// reference.
1272
    pub fn trait_ref(&self, tcx: TyCtxt<'_, '_, '_>) -> ty::ExistentialTraitRef<'tcx> {
1273 1274
        let def_id = tcx.associated_item(self.item_def_id).container.id();
        ty::ExistentialTraitRef{
1275
            def_id,
1276 1277
            substs: self.substs,
        }
1278 1279 1280 1281
    }

    pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
                        self_ty: Ty<'tcx>)
1282
                        -> ty::ProjectionPredicate<'tcx>
1283 1284
    {
        // otherwise the escaping regions would be captured by the binders
1285
        debug_assert!(!self_ty.has_escaping_bound_vars());
1286

1287
        ty::ProjectionPredicate {
1288 1289
            projection_ty: ty::ProjectionTy {
                item_def_id: self.item_def_id,
1290
                substs: tcx.mk_substs_trait(self_ty, self.substs),
1291
            },
T
Tshepang Lekhonkhobe 已提交
1292
            ty: self.ty,
1293
        }
1294 1295 1296
    }
}

1297 1298 1299 1300
impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
    pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
        -> ty::PolyProjectionPredicate<'tcx> {
        self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1301
    }
1302 1303 1304 1305

    pub fn item_def_id(&self) -> DefId {
        return self.skip_binder().item_def_id;
    }
1306 1307 1308
}

impl DebruijnIndex {
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
    /// Returns the resulting index when this value is moved into
    /// `amount` number of new binders. So e.g. if you had
    ///
    ///    for<'a> fn(&'a x)
    ///
    /// and you wanted to change to
    ///
    ///    for<'a> fn(for<'b> fn(&'a x))
    ///
    /// you would need to shift the index for `'a` into 1 new binder.
    #[must_use]
1320
    pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
1321
        DebruijnIndex::from_u32(self.as_u32() + amount)
1322
    }
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332

    /// Update this index in place by shifting it "in" through
    /// `amount` number of binders.
    pub fn shift_in(&mut self, amount: u32) {
        *self = self.shifted_in(amount);
    }

    /// Returns the resulting index when this value is moved out from
    /// `amount` number of new binders.
    #[must_use]
1333
    pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
1334
        DebruijnIndex::from_u32(self.as_u32() - amount)
1335 1336 1337 1338 1339 1340
    }

    /// Update in place by shifting out from `amount` binders.
    pub fn shift_out(&mut self, amount: u32) {
        *self = self.shifted_out(amount);
    }
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362

    /// Adjusts any Debruijn Indices so as to make `to_binder` the
    /// innermost binder. That is, if we have something bound at `to_binder`,
    /// it will now be bound at INNERMOST. This is an appropriate thing to do
    /// when moving a region out from inside binders:
    ///
    /// ```
    ///             for<'a>   fn(for<'b>   for<'c>   fn(&'a u32), _)
    /// // Binder:  D3           D2        D1            ^^
    /// ```
    ///
    /// Here, the region `'a` would have the debruijn index D3,
    /// because it is the bound 3 binders out. However, if we wanted
    /// to refer to that region `'a` in the second argument (the `_`),
    /// those two binders would not be in scope. In that case, we
    /// might invoke `shift_out_to_binder(D3)`. This would adjust the
    /// debruijn index of `'a` to D1 (the innermost binder).
    ///
    /// If we invoke `shift_out_to_binder` and the region is in fact
    /// bound by one of the binders we are shifting out of, that is an
    /// error (and should fail an assertion failure).
    pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
1363
        self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
1364
    }
1365 1366
}

1367
impl_stable_hash_for!(struct DebruijnIndex { private });
1368

1369
/// Region utilities
1370
impl RegionKind {
D
David Wood 已提交
1371 1372 1373 1374 1375 1376 1377 1378 1379
    /// Is this region named by the user?
    pub fn has_name(&self) -> bool {
        match *self {
            RegionKind::ReEarlyBound(ebr) => ebr.has_name(),
            RegionKind::ReLateBound(_, br) => br.is_named(),
            RegionKind::ReFree(fr) => fr.bound_region.is_named(),
            RegionKind::ReScope(..) => false,
            RegionKind::ReStatic => true,
            RegionKind::ReVar(..) => false,
1380
            RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(),
D
David Wood 已提交
1381 1382 1383 1384 1385 1386 1387
            RegionKind::ReEmpty => false,
            RegionKind::ReErased => false,
            RegionKind::ReClosureBound(..) => false,
            RegionKind::ReCanonical(..) => false,
        }
    }

1388
    pub fn is_late_bound(&self) -> bool {
1389 1390
        match *self {
            ty::ReLateBound(..) => true,
T
Tshepang Lekhonkhobe 已提交
1391
            _ => false,
1392 1393 1394
        }
    }

1395
    pub fn bound_at_or_above_binder(&self, index: DebruijnIndex) -> bool {
1396
        match *self {
1397
            ty::ReLateBound(debruijn, _) => debruijn >= index,
1398 1399 1400 1401
            _ => false,
        }
    }

1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
    /// Adjusts any Debruijn Indices so as to make `to_binder` the
    /// innermost binder. That is, if we have something bound at `to_binder`,
    /// it will now be bound at INNERMOST. This is an appropriate thing to do
    /// when moving a region out from inside binders:
    ///
    /// ```
    ///             for<'a>   fn(for<'b>   for<'c>   fn(&'a u32), _)
    /// // Binder:  D3           D2        D1            ^^
    /// ```
    ///
    /// Here, the region `'a` would have the debruijn index D3,
    /// because it is the bound 3 binders out. However, if we wanted
    /// to refer to that region `'a` in the second argument (the `_`),
    /// those two binders would not be in scope. In that case, we
    /// might invoke `shift_out_to_binder(D3)`. This would adjust the
    /// debruijn index of `'a` to D1 (the innermost binder).
    ///
    /// If we invoke `shift_out_to_binder` and the region is in fact
    /// bound by one of the binders we are shifting out of, that is an
    /// error (and should fail an assertion failure).
    pub fn shifted_out_to_binder(&self, to_binder: ty::DebruijnIndex) -> RegionKind {
1423
        match *self {
1424 1425 1426 1427
            ty::ReLateBound(debruijn, r) => ty::ReLateBound(
                debruijn.shifted_out_to_binder(to_binder),
                r,
            ),
1428 1429 1430
            r => r
        }
    }
1431

1432 1433 1434 1435 1436 1437 1438 1439
    pub fn keep_in_local_tcx(&self) -> bool {
        if let ty::ReVar(..) = self {
            true
        } else {
            false
        }
    }

1440 1441 1442
    pub fn type_flags(&self) -> TypeFlags {
        let mut flags = TypeFlags::empty();

1443 1444 1445 1446
        if self.keep_in_local_tcx() {
            flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
        }

1447 1448
        match *self {
            ty::ReVar(..) => {
1449
                flags = flags | TypeFlags::HAS_FREE_REGIONS;
1450 1451
                flags = flags | TypeFlags::HAS_RE_INFER;
            }
N
Niko Matsakis 已提交
1452
            ty::RePlaceholder(..) => {
1453
                flags = flags | TypeFlags::HAS_FREE_REGIONS;
1454 1455
                flags = flags | TypeFlags::HAS_RE_SKOL;
            }
1456 1457 1458
            ty::ReLateBound(..) => {
                flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
            }
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
            ty::ReEarlyBound(..) => {
                flags = flags | TypeFlags::HAS_FREE_REGIONS;
                flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
            }
            ty::ReEmpty |
            ty::ReStatic |
            ty::ReFree { .. } |
            ty::ReScope { .. } => {
                flags = flags | TypeFlags::HAS_FREE_REGIONS;
            }
            ty::ReErased => {
            }
1471 1472 1473 1474
            ty::ReCanonical(..) => {
                flags = flags | TypeFlags::HAS_FREE_REGIONS;
                flags = flags | TypeFlags::HAS_CANONICAL_VARS;
            }
1475 1476 1477
            ty::ReClosureBound(..) => {
                flags = flags | TypeFlags::HAS_FREE_REGIONS;
            }
1478 1479 1480
        }

        match *self {
1481 1482
            ty::ReStatic | ty::ReEmpty | ty::ReErased | ty::ReLateBound(..) => (),
            _ => flags = flags | TypeFlags::HAS_FREE_LOCAL_NAMES,
1483 1484 1485 1486 1487 1488
        }

        debug!("type_flags({:?}) = {:?}", self, flags);

        flags
    }
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517

    /// Given an early-bound or free region, returns the def-id where it was bound.
    /// For example, consider the regions in this snippet of code:
    ///
    /// ```
    /// impl<'a> Foo {
    ///      ^^ -- early bound, declared on an impl
    ///
    ///     fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
    ///            ^^  ^^     ^ anonymous, late-bound
    ///            |   early-bound, appears in where-clauses
    ///            late-bound, appears only in fn args
    ///     {..}
    /// }
    /// ```
    ///
    /// Here, `free_region_binding_scope('a)` would return the def-id
    /// of the impl, and for all the other highlighted regions, it
    /// would return the def-id of the function. In other cases (not shown), this
    /// function might return the def-id of a closure.
    pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_, '_, '_>) -> DefId {
        match self {
            ty::ReEarlyBound(br) => {
                tcx.parent_def_id(br.def_id).unwrap()
            }
            ty::ReFree(fr) => fr.scope,
            _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
        }
    }
1518 1519
}

1520
/// Type utilities
1521
impl<'a, 'gcx, 'tcx> TyS<'tcx> {
K
kenta7777 已提交
1522
    pub fn is_unit(&self) -> bool {
1523
        match self.sty {
V
varkor 已提交
1524
            Tuple(ref tys) => tys.is_empty(),
T
Tshepang Lekhonkhobe 已提交
1525
            _ => false,
1526 1527 1528
        }
    }

A
Andrew Cann 已提交
1529 1530
    pub fn is_never(&self) -> bool {
        match self.sty {
V
varkor 已提交
1531
            Never => true,
A
Andrew Cann 已提交
1532 1533 1534 1535
            _ => false,
        }
    }

1536 1537
    pub fn is_primitive(&self) -> bool {
        match self.sty {
1538
            Bool | Char | Int(_) | Uint(_) | Float(_) => true,
1539 1540 1541 1542
            _ => false,
        }
    }

1543 1544
    pub fn is_ty_var(&self) -> bool {
        match self.sty {
V
varkor 已提交
1545
            Infer(TyVar(_)) => true,
T
Tshepang Lekhonkhobe 已提交
1546
            _ => false,
1547 1548 1549
        }
    }

L
leonardo.yvens 已提交
1550 1551
    pub fn is_ty_infer(&self) -> bool {
        match self.sty {
V
varkor 已提交
1552
            Infer(_) => true,
L
leonardo.yvens 已提交
1553 1554 1555 1556
            _ => false,
        }
    }

1557
    pub fn is_phantom_data(&self) -> bool {
V
varkor 已提交
1558
        if let Adt(def, _) = self.sty {
1559 1560 1561 1562 1563 1564
            def.is_phantom_data()
        } else {
            false
        }
    }

1565
    pub fn is_bool(&self) -> bool { self.sty == Bool }
1566

1567
    pub fn is_param(&self, index: u32) -> bool {
1568
        match self.sty {
V
varkor 已提交
1569
            ty::Param(ref data) => data.idx == index,
1570 1571 1572 1573
            _ => false,
        }
    }

1574 1575
    pub fn is_self(&self) -> bool {
        match self.sty {
V
varkor 已提交
1576
            Param(ref p) => p.is_self(),
T
Tshepang Lekhonkhobe 已提交
1577
            _ => false,
1578 1579 1580
        }
    }

1581
    pub fn is_slice(&self) -> bool {
1582
        match self.sty {
V
varkor 已提交
1583
            RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => match ty.sty {
1584
                Slice(_) | Str => true,
1585 1586 1587 1588 1589 1590 1591 1592 1593
                _ => false,
            },
            _ => false
        }
    }

    #[inline]
    pub fn is_simd(&self) -> bool {
        match self.sty {
V
varkor 已提交
1594
            Adt(def, _) => def.repr.simd(),
T
Tshepang Lekhonkhobe 已提交
1595
            _ => false,
1596 1597 1598
        }
    }

1599
    pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1600
        match self.sty {
V
varkor 已提交
1601
            Array(ty, _) | Slice(ty) => ty,
1602
            Str => tcx.mk_mach_uint(ast::UintTy::U8),
1603
            _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1604 1605 1606
        }
    }

1607
    pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1608
        match self.sty {
V
varkor 已提交
1609
            Adt(def, substs) => {
1610
                def.non_enum_variant().fields[0].ty(tcx, substs)
1611
            }
1612
            _ => bug!("simd_type called on invalid type")
1613 1614 1615
        }
    }

1616
    pub fn simd_size(&self, _cx: TyCtxt<'_, '_, '_>) -> usize {
1617
        match self.sty {
V
varkor 已提交
1618
            Adt(def, _) => def.non_enum_variant().fields.len(),
1619
            _ => bug!("simd_size called on invalid type")
1620 1621 1622 1623 1624
        }
    }

    pub fn is_region_ptr(&self) -> bool {
        match self.sty {
V
varkor 已提交
1625
            Ref(..) => true,
T
Tshepang Lekhonkhobe 已提交
1626
            _ => false,
1627 1628 1629
        }
    }

1630 1631
    pub fn is_mutable_pointer(&self) -> bool {
        match self.sty {
V
varkor 已提交
1632 1633
            RawPtr(TypeAndMut { mutbl: hir::Mutability::MutMutable, .. }) |
            Ref(_, _, hir::Mutability::MutMutable) => true,
1634 1635 1636 1637
            _ => false
        }
    }

1638 1639
    pub fn is_unsafe_ptr(&self) -> bool {
        match self.sty {
V
varkor 已提交
1640
            RawPtr(_) => return true,
T
Tshepang Lekhonkhobe 已提交
1641
            _ => return false,
1642 1643 1644
        }
    }

1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
    /// Returns `true` if this type is an `Arc<T>`.
    pub fn is_arc(&self) -> bool {
        match self.sty {
            Adt(def, _) => def.is_arc(),
            _ => false,
        }
    }

    /// Returns `true` if this type is an `Rc<T>`.
    pub fn is_rc(&self) -> bool {
        match self.sty {
            Adt(def, _) => def.is_rc(),
            _ => false,
        }
    }

1661
    pub fn is_box(&self) -> bool {
1662
        match self.sty {
V
varkor 已提交
1663
            Adt(def, _) => def.is_box(),
1664 1665 1666 1667
            _ => false,
        }
    }

1668
    /// panics if called on any type other than `Box<T>`
1669 1670
    pub fn boxed_ty(&self) -> Ty<'tcx> {
        match self.sty {
V
varkor 已提交
1671
            Adt(def, substs) if def.is_box() => substs.type_at(0),
1672
            _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1673 1674 1675
        }
    }

1676
    /// A scalar type is one that denotes an atomic datum, with no sub-components.
V
varkor 已提交
1677
    /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1678
    /// contents are abstract to rustc.)
1679 1680
    pub fn is_scalar(&self) -> bool {
        match self.sty {
1681
            Bool | Char | Int(_) | Float(_) | Uint(_) |
V
varkor 已提交
1682 1683
            Infer(IntVar(_)) | Infer(FloatVar(_)) |
            FnDef(..) | FnPtr(_) | RawPtr(_) => true,
1684 1685 1686 1687 1688 1689 1690
            _ => false
        }
    }

    /// Returns true if this type is a floating point type and false otherwise.
    pub fn is_floating_point(&self) -> bool {
        match self.sty {
1691
            Float(_) |
V
varkor 已提交
1692
            Infer(FloatVar(_)) => true,
1693 1694 1695 1696 1697 1698
            _ => false,
        }
    }

    pub fn is_trait(&self) -> bool {
        match self.sty {
V
varkor 已提交
1699
            Dynamic(..) => true,
T
Tshepang Lekhonkhobe 已提交
1700
            _ => false,
1701 1702 1703
        }
    }

1704 1705
    pub fn is_enum(&self) -> bool {
        match self.sty {
V
varkor 已提交
1706
            Adt(adt_def, _) => {
1707 1708 1709 1710 1711 1712
                adt_def.is_enum()
            }
            _ => false,
        }
    }

1713 1714
    pub fn is_closure(&self) -> bool {
        match self.sty {
V
varkor 已提交
1715
            Closure(..) => true,
1716 1717 1718 1719
            _ => false,
        }
    }

1720 1721
    pub fn is_generator(&self) -> bool {
        match self.sty {
V
varkor 已提交
1722
            Generator(..) => true,
1723 1724 1725 1726
            _ => false,
        }
    }

1727 1728
    pub fn is_integral(&self) -> bool {
        match self.sty {
1729
            Infer(IntVar(_)) | Int(_) | Uint(_) => true,
1730 1731 1732 1733
            _ => false
        }
    }

1734 1735
    pub fn is_fresh_ty(&self) -> bool {
        match self.sty {
V
varkor 已提交
1736
            Infer(FreshTy(_)) => true,
1737 1738 1739 1740
            _ => false,
        }
    }

1741 1742
    pub fn is_fresh(&self) -> bool {
        match self.sty {
V
varkor 已提交
1743 1744 1745
            Infer(FreshTy(_)) => true,
            Infer(FreshIntTy(_)) => true,
            Infer(FreshFloatTy(_)) => true,
T
Tshepang Lekhonkhobe 已提交
1746
            _ => false,
1747 1748 1749 1750 1751
        }
    }

    pub fn is_char(&self) -> bool {
        match self.sty {
1752
            Char => true,
T
Tshepang Lekhonkhobe 已提交
1753
            _ => false,
1754 1755 1756 1757 1758
        }
    }

    pub fn is_fp(&self) -> bool {
        match self.sty {
1759
            Infer(FloatVar(_)) | Float(_) => true,
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
            _ => false
        }
    }

    pub fn is_numeric(&self) -> bool {
        self.is_integral() || self.is_fp()
    }

    pub fn is_signed(&self) -> bool {
        match self.sty {
1770
            Int(_) => true,
T
Tshepang Lekhonkhobe 已提交
1771
            _ => false,
1772 1773 1774 1775 1776
        }
    }

    pub fn is_machine(&self) -> bool {
        match self.sty {
1777 1778
            Int(ast::IntTy::Isize) | Uint(ast::UintTy::Usize) => false,
            Int(..) | Uint(..) | Float(..) => true,
T
Tshepang Lekhonkhobe 已提交
1779
            _ => false,
1780 1781 1782
        }
    }

1783 1784
    pub fn has_concrete_skeleton(&self) -> bool {
        match self.sty {
V
varkor 已提交
1785
            Param(_) | Infer(_) | Error => false,
1786 1787 1788 1789
            _ => true,
        }
    }

1790 1791 1792 1793
    /// Returns the type and mutability of *ty.
    ///
    /// The parameter `explicit` indicates if this is an *explicit* dereference.
    /// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1794
    pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1795
        match self.sty {
V
varkor 已提交
1796
            Adt(def, _) if def.is_box() => {
1797
                Some(TypeAndMut {
1798
                    ty: self.boxed_ty(),
1799
                    mutbl: hir::MutImmutable,
1800 1801
                })
            },
V
varkor 已提交
1802 1803
            Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl }),
            RawPtr(mt) if explicit => Some(mt),
T
Tshepang Lekhonkhobe 已提交
1804
            _ => None,
1805 1806 1807
        }
    }

1808
    /// Returns the type of `ty[i]`.
1809 1810
    pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
        match self.sty {
V
varkor 已提交
1811
            Array(ty, _) | Slice(ty) => Some(ty),
T
Tshepang Lekhonkhobe 已提交
1812
            _ => None,
1813 1814 1815
        }
    }

1816
    pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1817
        match self.sty {
V
varkor 已提交
1818
            FnDef(def_id, substs) => {
1819 1820
                tcx.fn_sig(def_id).subst(tcx, substs)
            }
V
varkor 已提交
1821
            FnPtr(f) => f,
1822
            _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1823 1824 1825 1826 1827
        }
    }

    pub fn is_fn(&self) -> bool {
        match self.sty {
V
varkor 已提交
1828
            FnDef(..) | FnPtr(_) => true,
T
Tshepang Lekhonkhobe 已提交
1829
            _ => false,
1830 1831 1832
        }
    }

1833 1834
    pub fn is_impl_trait(&self) -> bool {
        match self.sty {
1835
            Opaque(..) => true,
1836 1837 1838 1839
            _ => false,
        }
    }

1840
    pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1841
        match self.sty {
V
varkor 已提交
1842
            Adt(adt, _) => Some(adt),
T
Tshepang Lekhonkhobe 已提交
1843
            _ => None,
1844 1845
        }
    }
1846 1847 1848 1849

    /// Returns the regions directly referenced from this type (but
    /// not types reachable from this type via `walk_tys`). This
    /// ignores late-bound regions binders.
N
Niko Matsakis 已提交
1850
    pub fn regions(&self) -> Vec<ty::Region<'tcx>> {
1851
        match self.sty {
V
varkor 已提交
1852
            Ref(region, _, _) => {
1853
                vec![region]
1854
            }
V
varkor 已提交
1855
            Dynamic(ref obj, region) => {
1856
                let mut v = vec![region];
1857
                v.extend(obj.principal().skip_binder().substs.regions());
1858 1859
                v
            }
1860
            Adt(_, substs) | Opaque(_, substs) => {
1861
                substs.regions().collect()
1862
            }
V
varkor 已提交
1863 1864
            Closure(_, ClosureSubsts { ref substs }) |
            Generator(_, GeneratorSubsts { ref substs }, _) => {
1865
                substs.regions().collect()
1866
            }
1867
            Projection(ref data) | UnnormalizedProjection(ref data) => {
1868
                data.substs.regions().collect()
1869
            }
V
varkor 已提交
1870 1871 1872
            FnDef(..) |
            FnPtr(_) |
            GeneratorWitness(..) |
1873 1874 1875 1876 1877 1878
            Bool |
            Char |
            Int(_) |
            Uint(_) |
            Float(_) |
            Str |
V
varkor 已提交
1879 1880 1881 1882 1883
            Array(..) |
            Slice(_) |
            RawPtr(_) |
            Never |
            Tuple(..) |
V
varkor 已提交
1884 1885
            Foreign(..) |
            Param(_) |
S
scalexm 已提交
1886
            Bound(..) |
V
varkor 已提交
1887 1888
            Infer(_) |
            Error => {
1889 1890 1891 1892
                vec![]
            }
        }
    }
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903

    /// When we create a closure, we record its kind (i.e., what trait
    /// it implements) into its `ClosureSubsts` using a type
    /// parameter. This is kind of a phantom type, except that the
    /// most convenient thing for us to are the integral types. This
    /// function converts such a special type into the closure
    /// kind. To go the other way, use
    /// `tcx.closure_kind_ty(closure_kind)`.
    ///
    /// Note that during type checking, we use an inference variable
    /// to represent the closure kind, because it has not yet been
M
Malo Jaffré 已提交
1904 1905
    /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
    /// is complete, that type variable will be unified.
1906 1907
    pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
        match self.sty {
1908
            Int(int_ty) => match int_ty {
1909 1910 1911 1912 1913 1914
                ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
                ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
                ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
                _ => bug!("cannot convert type `{:?}` to a closure kind", self),
            },

V
varkor 已提交
1915
            Infer(_) => None,
1916

V
varkor 已提交
1917
            Error => Some(ty::ClosureKind::Fn),
1918

1919 1920 1921
            _ => bug!("cannot convert type `{:?}` to a closure kind", self),
        }
    }
1922 1923 1924 1925 1926 1927 1928

    /// Fast path helper for testing if a type is `Sized`.
    ///
    /// Returning true means the type is known to be sized. Returning
    /// `false` means nothing -- could be sized, might not be.
    pub fn is_trivially_sized(&self, tcx: TyCtxt<'_, '_, 'tcx>) -> bool {
        match self.sty {
V
varkor 已提交
1929
            ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) |
1930
            ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
V
varkor 已提交
1931
            ty::FnDef(..) | ty::FnPtr(_) | ty::RawPtr(..) |
1932
            ty::Char | ty::Ref(..) | ty::Generator(..) |
V
varkor 已提交
1933 1934
            ty::GeneratorWitness(..) | ty::Array(..) | ty::Closure(..) |
            ty::Never | ty::Error =>
1935 1936
                true,

1937
            ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) =>
1938 1939
                false,

V
varkor 已提交
1940
            ty::Tuple(tys) =>
1941 1942
                tys.iter().all(|ty| ty.is_trivially_sized(tcx)),

V
varkor 已提交
1943
            ty::Adt(def, _substs) =>
1944 1945
                def.sized_constraint(tcx).is_empty(),

1946
            ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
1947

1948 1949
            ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),

V
varkor 已提交
1950
            ty::Infer(ty::TyVar(_)) => false,
1951

S
scalexm 已提交
1952
            ty::Bound(_) |
V
varkor 已提交
1953 1954 1955
            ty::Infer(ty::FreshTy(_)) |
            ty::Infer(ty::FreshIntTy(_)) |
            ty::Infer(ty::FreshFloatTy(_)) =>
1956 1957 1958
                bug!("is_trivially_sized applied to unexpected type: {:?}", self),
        }
    }
1959
}
1960 1961

/// Typed constant value.
1962
#[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Eq, PartialEq, Ord, PartialOrd)]
1963 1964 1965
pub struct Const<'tcx> {
    pub ty: Ty<'tcx>,

1966
    pub val: ConstValue<'tcx>,
1967 1968
}

1969 1970 1971 1972 1973 1974 1975 1976
impl<'tcx> Const<'tcx> {
    pub fn unevaluated(
        tcx: TyCtxt<'_, '_, 'tcx>,
        def_id: DefId,
        substs: &'tcx Substs<'tcx>,
        ty: Ty<'tcx>,
    ) -> &'tcx Self {
        tcx.mk_const(Const {
1977
            val: ConstValue::Unevaluated(def_id, substs),
1978 1979 1980 1981 1982
            ty,
        })
    }

    #[inline]
1983
    pub fn from_const_value(
1984
        tcx: TyCtxt<'_, '_, 'tcx>,
1985
        val: ConstValue<'tcx>,
1986 1987 1988 1989 1990 1991 1992 1993 1994
        ty: Ty<'tcx>,
    ) -> &'tcx Self {
        tcx.mk_const(Const {
            val,
            ty,
        })
    }

    #[inline]
O
Oliver Schneider 已提交
1995
    pub fn from_scalar(
1996
        tcx: TyCtxt<'_, '_, 'tcx>,
O
Oliver Schneider 已提交
1997
        val: Scalar,
1998 1999
        ty: Ty<'tcx>,
    ) -> &'tcx Self {
2000
        Self::from_const_value(tcx, ConstValue::Scalar(val), ty)
2001 2002 2003 2004 2005
    }

    #[inline]
    pub fn from_bits(
        tcx: TyCtxt<'_, '_, 'tcx>,
2006
        bits: u128,
O
Oliver Schneider 已提交
2007
        ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2008
    ) -> &'tcx Self {
2009 2010
        let ty = tcx.lift_to_global(&ty).unwrap();
        let size = tcx.layout_of(ty).unwrap_or_else(|e| {
O
Oliver Schneider 已提交
2011
            panic!("could not compute layout for {:?}: {:?}", ty, e)
2012
        }).size;
2013 2014
        let shift = 128 - size.bits();
        let truncated = (bits << shift) >> shift;
2015
        assert_eq!(truncated, bits, "from_bits called with untruncated value");
2016
        Self::from_scalar(tcx, Scalar::Bits { bits, size: size.bytes() as u8 }, ty.value)
2017 2018 2019 2020
    }

    #[inline]
    pub fn zero_sized(tcx: TyCtxt<'_, '_, 'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
2021
        Self::from_scalar(tcx, Scalar::Bits { bits: 0, size: 0 }, ty)
2022 2023 2024 2025
    }

    #[inline]
    pub fn from_bool(tcx: TyCtxt<'_, '_, 'tcx>, v: bool) -> &'tcx Self {
O
Oliver Schneider 已提交
2026
        Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
2027 2028 2029 2030
    }

    #[inline]
    pub fn from_usize(tcx: TyCtxt<'_, '_, 'tcx>, n: u64) -> &'tcx Self {
O
Oliver Schneider 已提交
2031
        Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize))
2032 2033 2034
    }

    #[inline]
O
Oliver Schneider 已提交
2035 2036 2037 2038 2039 2040
    pub fn to_bits(
        &self,
        tcx: TyCtxt<'_, '_, 'tcx>,
        ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
    ) -> Option<u128> {
        if self.ty != ty.value {
2041 2042
            return None;
        }
2043 2044
        let ty = tcx.lift_to_global(&ty).unwrap();
        let size = tcx.layout_of(ty).ok()?.size;
R
Ralf Jung 已提交
2045
        self.val.try_to_bits(size)
2046 2047 2048
    }

    #[inline]
2049
    pub fn to_ptr(&self) -> Option<Pointer> {
R
Ralf Jung 已提交
2050
        self.val.try_to_ptr()
2051 2052
    }

2053
    #[inline]
O
Oliver Schneider 已提交
2054 2055 2056 2057 2058 2059
    pub fn assert_bits(
        &self,
        tcx: TyCtxt<'_, '_, '_>,
        ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
    ) -> Option<u128> {
        assert_eq!(self.ty, ty.value);
2060 2061
        let ty = tcx.lift_to_global(&ty).unwrap();
        let size = tcx.layout_of(ty).ok()?.size;
R
Ralf Jung 已提交
2062
        self.val.try_to_bits(size)
2063 2064 2065 2066
    }

    #[inline]
    pub fn assert_bool(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<bool> {
O
Oliver Schneider 已提交
2067
        self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.bool)).and_then(|v| match v {
2068 2069 2070 2071 2072 2073 2074 2075
            0 => Some(false),
            1 => Some(true),
            _ => None,
        })
    }

    #[inline]
    pub fn assert_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<u64> {
O
Oliver Schneider 已提交
2076
        self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.usize)).map(|v| v as u64)
2077 2078 2079
    }

    #[inline]
O
Oliver Schneider 已提交
2080 2081 2082 2083 2084
    pub fn unwrap_bits(
        &self,
        tcx: TyCtxt<'_, '_, '_>,
        ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
    ) -> u128 {
L
ljedrz 已提交
2085 2086
        self.assert_bits(tcx, ty).unwrap_or_else(||
            bug!("expected bits of {}, got {:#?}", ty.value, self))
2087 2088 2089 2090
    }

    #[inline]
    pub fn unwrap_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> u64 {
L
ljedrz 已提交
2091 2092
        self.assert_usize(tcx).unwrap_or_else(||
            bug!("expected constant usize, got {:#?}", self))
2093 2094 2095
    }
}

2096
impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}