sty.rs 69.6 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

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 129
    /// The anonymous type of a function declaration/definition. Each
    /// function has a unique type.
V
varkor 已提交
130
    FnDef(DefId, &'tcx Substs<'tcx>),
131 132

    /// A pointer to a function.  Written as `fn() -> i32`.
V
varkor 已提交
133
    FnPtr(PolyFnSig<'tcx>),
134 135

    /// A trait, defined with `trait`.
V
varkor 已提交
136
    Dynamic(Binder<&'tcx List<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
137 138 139

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

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

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

A
Andrew Cann 已提交
150
    /// The never type `!`
V
varkor 已提交
151
    Never,
152

153
    /// A tuple type.  For example, `(i32, bool)`.
V
varkor 已提交
154
    Tuple(&'tcx List<Ty<'tcx>>),
155 156 157

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

160 161 162 163 164
    /// 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>),

165
    /// Opaque (`impl Trait`) type found in a return type.
166
    /// The `DefId` comes either from
O
Oliver Schneider 已提交
167 168 169
    /// * the `impl Trait` ast::Ty node,
    /// * or the `existential type` declaration
    /// The substitutions are for the generics of the function in question.
170
    /// After typeck, the concrete type can be found in the `types` map.
171
    Opaque(DefId, &'tcx Substs<'tcx>),
172

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

176
    /// A type variable used during type checking.
V
varkor 已提交
177
    Infer(InferTy),
178 179 180

    /// A placeholder for a type which could not be computed; this is
    /// propagated to avoid useless error messages.
V
varkor 已提交
181
    Error,
182 183 184 185
}

/// A closure can be modeled as a struct that looks like:
///
186
///     struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
187 188 189 190 191
///         upvar0: U0,
///         ...
///         upvark: Uk
///     }
///
192 193 194 195 196 197 198
/// 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.
199 200 201 202
/// - 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.
203 204 205
/// - 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`).
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
///
/// 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
237 238
/// `'b` represents the scope of the closure itself; this is some
/// subset of `foo`, probably just the scope of the call to the to
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
/// `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 已提交
254
/// original function then? The answer is that codegen may need them
255 256 257 258 259 260 261 262 263 264 265 266 267
/// 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
268 269 270 271 272 273 274 275 276 277 278
///
/// ## 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
279
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
280
pub struct ClosureSubsts<'tcx> {
281 282 283
    /// Lifetime and type parameters from the enclosing function,
    /// concatenated with the types of the upvars.
    ///
I
Irina Popa 已提交
284
    /// These are separated out because codegen wants to pass them around
285
    /// when monomorphizing.
286 287
    pub substs: &'tcx Substs<'tcx>,
}
288

289 290 291 292
/// 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>,
293
    closure_sig_ty: Ty<'tcx>,
294 295 296 297 298 299 300 301 302
    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 已提交
303
        let parent_len = generics.parent_count;
304
        SplitClosureSubsts {
V
varkor 已提交
305 306
            closure_kind_ty: self.substs.type_at(parent_len),
            closure_sig_ty: self.substs.type_at(parent_len + 1),
307
            upvar_kinds: &self.substs[parent_len + 2..],
308 309 310
        }
    }

311
    #[inline]
312
    pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
313 314
        impl Iterator<Item=Ty<'tcx>> + 'tcx
    {
315
        let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
V
varkor 已提交
316 317 318 319 320 321 322
        upvar_kinds.iter().map(|t| {
            if let UnpackedKind::Type(ty) = t.unpack() {
                ty
            } else {
                bug!("upvar should be type")
            }
        })
323 324
    }

325
    /// Returns the closure kind for this closure; may return a type
326 327
    /// variable during inference. To get the closure kind during
    /// inference, use `infcx.closure_kind(def_id, substs)`.
328 329 330
    pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
        self.split(def_id, tcx).closure_kind_ty
    }
331 332

    /// Returns the type representing the closure signature for this
333 334 335
    /// closure; may contain type variables during inference. To get
    /// the closure signature during inference, use
    /// `infcx.fn_sig(def_id)`.
336 337 338
    pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
        self.split(def_id, tcx).closure_sig_ty
    }
339

340
    /// Returns the closure kind for this closure; only usable outside
341 342
    /// of an inference context, because in that context we know that
    /// there are no type variables.
343 344
    ///
    /// If you have an inference context, use `infcx.closure_kind()`.
345
    pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::ClosureKind {
346
        self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
347
    }
348 349 350 351

    /// 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.
352 353
    ///
    /// If you have an inference context, use `infcx.closure_sig()`.
354 355
    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 已提交
356
            ty::FnPtr(sig) => sig,
357 358 359
            ref t => bug!("closure_sig_ty is not a fn-ptr: {:?}", t),
        }
    }
360 361
}

362
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
363 364 365 366 367 368 369 370 371 372 373 374 375 376
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 已提交
377
        let parent_len = generics.parent_count;
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 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
        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 已提交
440 441 442
    /// 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.
443 444 445 446 447
    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 已提交
448
        let state = tcx.generator_layout(def_id).fields.iter();
J
John Kåre Alsaker 已提交
449
        state.map(move |d| d.ty.subst(tcx, self.substs))
J
John Kåre Alsaker 已提交
450 451
    }

452 453 454 455 456 457 458 459 460
    /// 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 已提交
461 462
    /// 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 已提交
463
    pub fn field_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
464
        impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a
J
John Kåre Alsaker 已提交
465
    {
466
        self.pre_transforms_tys(def_id, tcx).chain(self.state_tys(def_id, tcx))
J
John Kåre Alsaker 已提交
467 468 469
    }
}

470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
#[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 已提交
493 494
}

495
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, RustcEncodable, RustcDecodable)]
496
pub enum ExistentialPredicate<'tcx> {
497
    /// e.g. Iterator
498
    Trait(ExistentialTraitRef<'tcx>),
499
    /// e.g. Iterator::Item = T
500
    Projection(ExistentialProjection<'tcx>),
501
    /// e.g. Send
502
    AutoTrait(DefId),
503 504
}

505
impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
506 507 508
    /// 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 {
509 510 511
        use self::ExistentialPredicate::*;
        match (*self, *other) {
            (Trait(_), Trait(_)) => Ordering::Equal,
512 513
            (Projection(ref a), Projection(ref b)) =>
                tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
514
            (AutoTrait(ref a), AutoTrait(ref b)) =>
515
                tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
            (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 已提交
544
impl<'tcx> serialize::UseSpecializedDecodable for &'tcx List<ExistentialPredicate<'tcx>> {}
545

V
varkor 已提交
546
impl<'tcx> List<ExistentialPredicate<'tcx>> {
547 548 549
    pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
        match self.get(0) {
            Some(&ExistentialPredicate::Trait(tr)) => Some(tr),
T
Tshepang Lekhonkhobe 已提交
550
            _ => None,
551 552 553
        }
    }

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    #[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 已提交
576
impl<'tcx> Binder<&'tcx List<ExistentialPredicate<'tcx>>> {
577
    pub fn principal(&self) -> Option<PolyExistentialTraitRef<'tcx>> {
578
        self.skip_binder().principal().map(Binder::bind)
579 580 581 582 583
    }

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

587
    #[inline]
588
    pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
589 590 591 592 593
        self.skip_binder().auto_traits()
    }

    pub fn iter<'a>(&'a self)
        -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
594
        self.skip_binder().iter().cloned().map(Binder::bind)
595
    }
596 597
}

598 599 600 601 602 603
/// 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
604 605
/// def-id for the trait `Foo` and the substs define `T` as parameter 0,
/// and `U` as parameter 1.
606 607 608 609 610 611 612
///
/// 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.
613
#[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
614 615 616 617 618
pub struct TraitRef<'tcx> {
    pub def_id: DefId,
    pub substs: &'tcx Substs<'tcx>,
}

619 620 621 622 623
impl<'tcx> TraitRef<'tcx> {
    pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
        TraitRef { def_id: def_id, substs: substs }
    }

624 625 626 627 628 629 630 631 632
    /// 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),
        }
    }

633 634 635 636 637 638 639 640 641 642 643
    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()
    }
644 645 646 647 648 649 650 651 652 653 654 655

    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()])
        }
    }
656 657
}

658 659 660 661
pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;

impl<'tcx> PolyTraitRef<'tcx> {
    pub fn self_ty(&self) -> Ty<'tcx> {
662
        self.skip_binder().self_ty()
663 664 665
    }

    pub fn def_id(&self) -> DefId {
666
        self.skip_binder().def_id
667 668 669 670
    }

    pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
        // Note that we preserve binding levels
671
        Binder(ty::TraitPredicate { trait_ref: self.skip_binder().clone() })
672 673 674
    }
}

675 676 677 678 679 680 681
/// 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).
682
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
683 684 685 686 687
pub struct ExistentialTraitRef<'tcx> {
    pub def_id: DefId,
    pub substs: &'tcx Substs<'tcx>,
}

688 689
impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
    pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
690 691 692 693
        // 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.
694
        self.substs.types()
695
    }
696

697 698 699 700 701 702 703 704 705 706 707 708
    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..])
        }
    }

709 710 711 712 713 714 715
    /// 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()`
    /// or some skolemized type.
    pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
        -> ty::TraitRef<'tcx>  {
        // otherwise the escaping regions would be captured by the binder
716
        // debug_assert!(!self_ty.has_escaping_regions());
717 718 719

        ty::TraitRef {
            def_id: self.def_id,
720
            substs: tcx.mk_substs_trait(self_ty, self.substs)
721 722
        }
    }
723 724 725 726
}

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

727
impl<'tcx> PolyExistentialTraitRef<'tcx> {
728
    pub fn def_id(&self) -> DefId {
729
        self.skip_binder().def_id
730
    }
731 732 733 734 735 736 737 738 739 740

    /// 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()`
    /// or some skolemized type.
    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))
    }
741 742
}

743 744 745 746 747 748 749
/// 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 ==
/// Binder<TraitRef>`). Note that when we skolemize, instantiate,
/// erase, or otherwise "discharge" these bound regions, we change the
/// type from `Binder<T>` to just `T` (see
/// e.g. `liberate_late_bound_regions`).
750
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
751
pub struct Binder<T>(T);
752 753

impl<T> Binder<T> {
754 755 756 757
    /// 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.
758
    pub fn dummy<'tcx>(value: T) -> Binder<T>
759 760
        where T: TypeFoldable<'tcx>
    {
761
        debug_assert!(!value.has_escaping_regions());
762 763 764
        Binder(value)
    }

765 766 767 768 769 770
    /// Wraps `value` in a binder, binding late-bound regions (if any).
    pub fn bind<'tcx>(value: T) -> Binder<T>
    {
        Binder(value)
    }

771 772 773 774 775 776 777 778 779 780 781 782
    /// 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:
783
    ///
784 785 786 787 788 789 790 791
    /// - 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> {
792
        Binder(&self.0)
793 794
    }

T
Tshepang Lekhonkhobe 已提交
795
    pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
796 797 798 799 800
        where F: FnOnce(&T) -> U
    {
        self.as_ref().map_bound(f)
    }

T
Tshepang Lekhonkhobe 已提交
801
    pub fn map_bound<F, U>(self, f: F) -> Binder<U>
802 803
        where F: FnOnce(T) -> U
    {
804
        Binder(f(self.0))
805
    }
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825

    /// 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>
    {
        if self.skip_binder().has_escaping_regions() {
            None
        } else {
            Some(self.skip_binder().clone())
        }
    }
826 827 828 829 830 831 832 833 834 835 836

    /// 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
    {
837
        Binder(f(self.0, u.0))
838 839 840 841 842 843 844 845 846 847 848 849
    }

    /// 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);
850
        (Binder(u), Binder(v))
851
    }
852 853 854 855
}

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

861 862 863 864 865 866 867 868 869 870 871
    /// 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(
872
        tcx: TyCtxt<'_, '_, '_>, trait_ref: ty::TraitRef<'tcx>, item_name: Ident
873
    ) -> ProjectionTy<'tcx> {
874 875
        let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
            item.kind == ty::AssociatedKind::Type &&
876
            tcx.hygienic_eq(item_name, item.ident, trait_ref.def_id)
877
        }).unwrap().def_id;
878 879

        ProjectionTy {
880
            substs: trait_ref.substs,
881
            item_def_id,
882 883 884
        }
    }

885 886 887
    /// 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.
888
    pub fn trait_ref(&self, tcx: TyCtxt<'_, '_, '_>) -> ty::TraitRef<'tcx> {
889 890
        let def_id = tcx.associated_item(self.item_def_id).container.id();
        ty::TraitRef {
891
            def_id,
892 893 894 895 896 897
            substs: self.substs,
        }
    }

    pub fn self_ty(&self) -> Ty<'tcx> {
        self.substs.type_at(0)
898
    }
899
}
900

J
John Kåre Alsaker 已提交
901 902
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
pub struct GenSig<'tcx> {
J
John Kåre Alsaker 已提交
903
    pub yield_ty: Ty<'tcx>,
J
John Kåre Alsaker 已提交
904 905 906 907 908 909
    pub return_ty: Ty<'tcx>,
}

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

impl<'tcx> PolyGenSig<'tcx> {
J
John Kåre Alsaker 已提交
910 911
    pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
        self.map_bound_ref(|sig| sig.yield_ty)
J
John Kåre Alsaker 已提交
912 913 914 915 916
    }
    pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
        self.map_bound_ref(|sig| sig.return_ty)
    }
}
917

918 919 920 921 922 923
/// 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)
924
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
925
pub struct FnSig<'tcx> {
V
varkor 已提交
926
    pub inputs_and_output: &'tcx List<Ty<'tcx>>,
927 928 929
    pub variadic: bool,
    pub unsafety: hir::Unsafety,
    pub abi: abi::Abi,
930 931 932
}

impl<'tcx> FnSig<'tcx> {
933
    pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
934
        &self.inputs_and_output[..self.inputs_and_output.len() - 1]
935 936 937
    }

    pub fn output(&self) -> Ty<'tcx> {
938
        self.inputs_and_output[self.inputs_and_output.len() - 1]
939
    }
940 941 942 943 944
}

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

impl<'tcx> PolyFnSig<'tcx> {
945
    pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
946
        self.map_bound_ref(|fn_sig| fn_sig.inputs())
947 948
    }
    pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
949
        self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
950
    }
V
varkor 已提交
951
    pub fn inputs_and_output(&self) -> ty::Binder<&'tcx List<Ty<'tcx>>> {
952 953
        self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
    }
954
    pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
955
        self.map_bound_ref(|fn_sig| fn_sig.output().clone())
956 957 958 959
    }
    pub fn variadic(&self) -> bool {
        self.skip_binder().variadic
    }
960 961 962 963 964 965
    pub fn unsafety(&self) -> hir::Unsafety {
        self.skip_binder().unsafety
    }
    pub fn abi(&self) -> abi::Abi {
        self.skip_binder().abi
    }
966 967
}

968
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
969 970
pub struct ParamTy {
    pub idx: u32,
971
    pub name: InternedString,
972 973
}

974
impl<'a, 'gcx, 'tcx> ParamTy {
975
    pub fn new(index: u32, name: InternedString) -> ParamTy {
976
        ParamTy { idx: index, name: name }
977 978 979
    }

    pub fn for_self() -> ParamTy {
980
        ParamTy::new(0, keywords::SelfType.name().as_interned_str())
981 982
    }

983
    pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
984
        ParamTy::new(def.index, def.name)
985 986
    }

987
    pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
988
        tcx.mk_ty_param(self.idx, self.name)
989 990 991
    }

    pub fn is_self(&self) -> bool {
J
Josh Stone 已提交
992 993 994 995
        // 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`.
        if self.name == keywords::SelfType.name().as_str() && self.idx == 0 {
996 997 998 999
            true
        } else {
            false
        }
1000 1001 1002
    }
}

1003 1004 1005 1006 1007 1008 1009
/// 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 已提交
1010
///     |          +------------+ 0      |         |
1011
///     |                                |         |
N
Niko Matsakis 已提交
1012
///     +--------------------------------+ 1       |
1013
///     |                                          |
N
Niko Matsakis 已提交
1014
///     +------------------------------------------+ 0
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
///
/// 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 已提交
1026
/// Bruijn index of 0, meaning "the innermost binder" (in this case, a
1027
/// fn). The region `'a` that appears in the second argument type (`&'a
N
Niko Matsakis 已提交
1028
/// isize`) would then be assigned a De Bruijn index of 1, meaning "the
1029 1030 1031 1032 1033 1034 1035 1036 1037
/// 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 已提交
1038
/// De Bruijn index of 0, because the innermost binder in that location
1039 1040 1041
/// is the outer fn.
///
/// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1042 1043
newtype_index! {
    pub struct DebruijnIndex {
1044
        DEBUG_FORMAT = "DebruijnIndex({})",
1045
        const INNERMOST = 0,
1046 1047
    }
}
1048

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

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
/// 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
1061
/// bound regions: early-bound, which are bound in an item's Generics,
1062 1063 1064 1065 1066
/// 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 已提交
1067
/// Unlike Param-s, bound regions are not supposed to exist "in the wild"
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
/// outside their binder, e.g. in types passed to type inference, and
/// should first be substituted (by skolemized regions, free regions,
/// or region variables).
///
/// ## Skolemized and Free Regions
///
/// 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.
///
/// The process of doing that is called "skolemization". The bound regions
/// are replaced by skolemized markers, which don't satisfy any relation
F
Fourchaux 已提交
1082
/// not explicitly provided.
1083 1084 1085 1086 1087 1088
///
/// There are 2 kinds of skolemized regions in rustc: `ReFree` and
/// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
/// 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
1089
/// aren't checked when you `make_subregion` (or `eq_types`), only by
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
/// `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`.
/// `ReSkolemized` is designed for this purpose. In these contexts,
/// there's also the risk that some inference variable laying around will
/// get unified with your skolemized region: if you want to check whether
/// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
/// with a skolemized region `'%a`, the variable `'_` would just be
/// instantiated to the skolemized region `'%a`, which is wrong because
/// the inference variable is supposed to satisfy the relation
/// *for every value of the skolemized region*. To ensure that doesn't
/// happen, you can use `leak_check`. This is more clearly explained
1103
/// by the [rustc guide].
1104
///
1105 1106
/// [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 已提交
1107
/// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/traits/hrtb.html
C
Cengiz Can 已提交
1108
#[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1109
pub enum RegionKind {
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    // 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.
1122
    ReFree(FreeRegion),
1123

1124
    /// A concrete region naming some statically determined scope
1125 1126
    /// (e.g. an expression or sequence of statements) within the
    /// current function.
1127
    ReScope(region::Scope),
1128 1129 1130 1131 1132 1133 1134 1135 1136

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

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

    /// A skolemized region - basically the higher-ranked version of ReFree.
    /// Should not exist after typeck.
1137
    ReSkolemized(ty::UniverseIndex, BoundRegion),
1138 1139 1140 1141 1142 1143 1144 1145 1146

    /// 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,
1147

I
Irina Popa 已提交
1148
    /// Erased region, used by trait selection, in MIR and during codegen.
1149
    ReErased,
1150 1151 1152 1153 1154 1155

    /// 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),
1156 1157 1158

    /// Canonicalized region, used only when preparing a trait query.
    ReCanonical(CanonicalVar),
1159 1160
}

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

C
Cengiz Can 已提交
1163
#[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1164
pub struct EarlyBoundRegion {
1165
    pub def_id: DefId,
1166
    pub index: u32,
1167
    pub name: InternedString,
1168 1169
}

1170
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1171
pub struct TyVid {
N
Niko Matsakis 已提交
1172
    pub index: u32,
1173 1174
}

1175
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1176
pub struct IntVid {
T
Tshepang Lekhonkhobe 已提交
1177
    pub index: u32,
1178 1179
}

1180
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1181
pub struct FloatVid {
T
Tshepang Lekhonkhobe 已提交
1182
    pub index: u32,
1183 1184
}

1185 1186
newtype_index! {
    pub struct RegionVid {
1187
        DEBUG_FORMAT = custom,
1188 1189
    }
}
1190

1191 1192 1193 1194 1195 1196
impl Atom for RegionVid {
    fn index(self) -> usize {
        Idx::index(self)
    }
}

1197
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1198 1199 1200 1201 1202 1203 1204
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
1205
    /// `infer::freshen` for more details.
1206 1207
    FreshTy(u32),
    FreshIntTy(u32),
T
Tshepang Lekhonkhobe 已提交
1208
    FreshFloatTy(u32),
1209 1210 1211

    /// Canonicalized type variable, used only when preparing a trait query.
    CanonicalTy(CanonicalVar),
1212 1213
}

1214 1215 1216
newtype_index! {
    pub struct CanonicalVar { .. }
}
1217

1218
/// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1219
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1220
pub struct ExistentialProjection<'tcx> {
1221 1222
    pub item_def_id: DefId,
    pub substs: &'tcx Substs<'tcx>,
T
Tshepang Lekhonkhobe 已提交
1223
    pub ty: Ty<'tcx>,
1224 1225
}

1226 1227
pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;

1228
impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
1229 1230 1231 1232
    /// 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.
1233
    pub fn trait_ref(&self, tcx: TyCtxt<'_, '_, '_>) -> ty::ExistentialTraitRef<'tcx> {
1234 1235
        let def_id = tcx.associated_item(self.item_def_id).container.id();
        ty::ExistentialTraitRef{
1236
            def_id,
1237 1238
            substs: self.substs,
        }
1239 1240 1241 1242
    }

    pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
                        self_ty: Ty<'tcx>)
1243
                        -> ty::ProjectionPredicate<'tcx>
1244 1245
    {
        // otherwise the escaping regions would be captured by the binders
1246
        debug_assert!(!self_ty.has_escaping_regions());
1247

1248
        ty::ProjectionPredicate {
1249 1250
            projection_ty: ty::ProjectionTy {
                item_def_id: self.item_def_id,
1251
                substs: tcx.mk_substs_trait(self_ty, self.substs),
1252
            },
T
Tshepang Lekhonkhobe 已提交
1253
            ty: self.ty,
1254
        }
1255 1256 1257
    }
}

1258 1259 1260 1261
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))
1262
    }
1263 1264 1265 1266

    pub fn item_def_id(&self) -> DefId {
        return self.skip_binder().item_def_id;
    }
1267 1268 1269
}

impl DebruijnIndex {
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
    /// 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]
1281
    pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
1282
        DebruijnIndex::from_u32(self.as_u32() + amount)
1283
    }
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293

    /// 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]
1294
    pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
1295
        DebruijnIndex::from_u32(self.as_u32() - amount)
1296 1297 1298 1299 1300 1301
    }

    /// Update in place by shifting out from `amount` binders.
    pub fn shift_out(&mut self, amount: u32) {
        *self = self.shifted_out(amount);
    }
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323

    /// 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 {
1324
        self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
1325
    }
1326 1327
}

1328
impl_stable_hash_for!(struct DebruijnIndex { private });
1329

1330
/// Region utilities
1331
impl RegionKind {
D
David Wood 已提交
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
    /// 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,
            RegionKind::ReSkolemized(_, br) => br.is_named(),
            RegionKind::ReEmpty => false,
            RegionKind::ReErased => false,
            RegionKind::ReClosureBound(..) => false,
            RegionKind::ReCanonical(..) => false,
        }
    }

1349
    pub fn is_late_bound(&self) -> bool {
1350 1351
        match *self {
            ty::ReLateBound(..) => true,
T
Tshepang Lekhonkhobe 已提交
1352
            _ => false,
1353 1354 1355
        }
    }

1356
    pub fn bound_at_or_above_binder(&self, index: DebruijnIndex) -> bool {
1357
        match *self {
1358
            ty::ReLateBound(debruijn, _) => debruijn >= index,
1359 1360 1361 1362
            _ => false,
        }
    }

1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
    /// 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 {
1384
        match *self {
1385 1386 1387 1388
            ty::ReLateBound(debruijn, r) => ty::ReLateBound(
                debruijn.shifted_out_to_binder(to_binder),
                r,
            ),
1389 1390 1391
            r => r
        }
    }
1392

1393 1394 1395 1396 1397 1398 1399 1400
    pub fn keep_in_local_tcx(&self) -> bool {
        if let ty::ReVar(..) = self {
            true
        } else {
            false
        }
    }

1401 1402 1403
    pub fn type_flags(&self) -> TypeFlags {
        let mut flags = TypeFlags::empty();

1404 1405 1406 1407
        if self.keep_in_local_tcx() {
            flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
        }

1408 1409
        match *self {
            ty::ReVar(..) => {
1410
                flags = flags | TypeFlags::HAS_FREE_REGIONS;
1411 1412 1413
                flags = flags | TypeFlags::HAS_RE_INFER;
            }
            ty::ReSkolemized(..) => {
1414
                flags = flags | TypeFlags::HAS_FREE_REGIONS;
1415 1416
                flags = flags | TypeFlags::HAS_RE_SKOL;
            }
1417 1418 1419
            ty::ReLateBound(..) => {
                flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
            }
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
            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 => {
            }
1432 1433 1434 1435
            ty::ReCanonical(..) => {
                flags = flags | TypeFlags::HAS_FREE_REGIONS;
                flags = flags | TypeFlags::HAS_CANONICAL_VARS;
            }
1436 1437 1438
            ty::ReClosureBound(..) => {
                flags = flags | TypeFlags::HAS_FREE_REGIONS;
            }
1439 1440 1441
        }

        match *self {
1442 1443
            ty::ReStatic | ty::ReEmpty | ty::ReErased | ty::ReLateBound(..) => (),
            _ => flags = flags | TypeFlags::HAS_FREE_LOCAL_NAMES,
1444 1445 1446 1447 1448 1449
        }

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

        flags
    }
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478

    /// 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),
        }
    }
1479 1480
}

1481
/// Type utilities
1482
impl<'a, 'gcx, 'tcx> TyS<'tcx> {
K
kenta7777 已提交
1483
    pub fn is_unit(&self) -> bool {
1484
        match self.sty {
V
varkor 已提交
1485
            Tuple(ref tys) => tys.is_empty(),
T
Tshepang Lekhonkhobe 已提交
1486
            _ => false,
1487 1488 1489
        }
    }

A
Andrew Cann 已提交
1490 1491
    pub fn is_never(&self) -> bool {
        match self.sty {
V
varkor 已提交
1492
            Never => true,
A
Andrew Cann 已提交
1493 1494 1495 1496
            _ => false,
        }
    }

1497 1498
    pub fn is_primitive(&self) -> bool {
        match self.sty {
1499
            Bool | Char | Int(_) | Uint(_) | Float(_) => true,
1500 1501 1502 1503
            _ => false,
        }
    }

1504 1505
    pub fn is_ty_var(&self) -> bool {
        match self.sty {
V
varkor 已提交
1506
            Infer(TyVar(_)) => true,
T
Tshepang Lekhonkhobe 已提交
1507
            _ => false,
1508 1509 1510
        }
    }

L
leonardo.yvens 已提交
1511 1512
    pub fn is_ty_infer(&self) -> bool {
        match self.sty {
V
varkor 已提交
1513
            Infer(_) => true,
L
leonardo.yvens 已提交
1514 1515 1516 1517
            _ => false,
        }
    }

1518
    pub fn is_phantom_data(&self) -> bool {
V
varkor 已提交
1519
        if let Adt(def, _) = self.sty {
1520 1521 1522 1523 1524 1525
            def.is_phantom_data()
        } else {
            false
        }
    }

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

1528
    pub fn is_param(&self, index: u32) -> bool {
1529
        match self.sty {
V
varkor 已提交
1530
            ty::Param(ref data) => data.idx == index,
1531 1532 1533 1534
            _ => false,
        }
    }

1535 1536
    pub fn is_self(&self) -> bool {
        match self.sty {
V
varkor 已提交
1537
            Param(ref p) => p.is_self(),
T
Tshepang Lekhonkhobe 已提交
1538
            _ => false,
1539 1540 1541
        }
    }

1542
    pub fn is_slice(&self) -> bool {
1543
        match self.sty {
V
varkor 已提交
1544
            RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => match ty.sty {
1545
                Slice(_) | Str => true,
1546 1547 1548 1549 1550 1551 1552 1553 1554
                _ => false,
            },
            _ => false
        }
    }

    #[inline]
    pub fn is_simd(&self) -> bool {
        match self.sty {
V
varkor 已提交
1555
            Adt(def, _) => def.repr.simd(),
T
Tshepang Lekhonkhobe 已提交
1556
            _ => false,
1557 1558 1559
        }
    }

1560
    pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1561
        match self.sty {
V
varkor 已提交
1562
            Array(ty, _) | Slice(ty) => ty,
1563
            Str => tcx.mk_mach_uint(ast::UintTy::U8),
1564
            _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1565 1566 1567
        }
    }

1568
    pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1569
        match self.sty {
V
varkor 已提交
1570
            Adt(def, substs) => {
1571
                def.non_enum_variant().fields[0].ty(tcx, substs)
1572
            }
1573
            _ => bug!("simd_type called on invalid type")
1574 1575 1576
        }
    }

1577
    pub fn simd_size(&self, _cx: TyCtxt<'_, '_, '_>) -> usize {
1578
        match self.sty {
V
varkor 已提交
1579
            Adt(def, _) => def.non_enum_variant().fields.len(),
1580
            _ => bug!("simd_size called on invalid type")
1581 1582 1583 1584 1585
        }
    }

    pub fn is_region_ptr(&self) -> bool {
        match self.sty {
V
varkor 已提交
1586
            Ref(..) => true,
T
Tshepang Lekhonkhobe 已提交
1587
            _ => false,
1588 1589 1590
        }
    }

1591 1592
    pub fn is_mutable_pointer(&self) -> bool {
        match self.sty {
V
varkor 已提交
1593 1594
            RawPtr(TypeAndMut { mutbl: hir::Mutability::MutMutable, .. }) |
            Ref(_, _, hir::Mutability::MutMutable) => true,
1595 1596 1597 1598
            _ => false
        }
    }

1599 1600
    pub fn is_unsafe_ptr(&self) -> bool {
        match self.sty {
V
varkor 已提交
1601
            RawPtr(_) => return true,
T
Tshepang Lekhonkhobe 已提交
1602
            _ => return false,
1603 1604 1605
        }
    }

1606
    pub fn is_box(&self) -> bool {
1607
        match self.sty {
V
varkor 已提交
1608
            Adt(def, _) => def.is_box(),
1609 1610 1611 1612
            _ => false,
        }
    }

1613
    /// panics if called on any type other than `Box<T>`
1614 1615
    pub fn boxed_ty(&self) -> Ty<'tcx> {
        match self.sty {
V
varkor 已提交
1616
            Adt(def, substs) if def.is_box() => substs.type_at(0),
1617
            _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1618 1619 1620
        }
    }

1621
    /// A scalar type is one that denotes an atomic datum, with no sub-components.
V
varkor 已提交
1622
    /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1623
    /// contents are abstract to rustc.)
1624 1625
    pub fn is_scalar(&self) -> bool {
        match self.sty {
1626
            Bool | Char | Int(_) | Float(_) | Uint(_) |
V
varkor 已提交
1627 1628
            Infer(IntVar(_)) | Infer(FloatVar(_)) |
            FnDef(..) | FnPtr(_) | RawPtr(_) => true,
1629 1630 1631 1632 1633 1634 1635
            _ => false
        }
    }

    /// Returns true if this type is a floating point type and false otherwise.
    pub fn is_floating_point(&self) -> bool {
        match self.sty {
1636
            Float(_) |
V
varkor 已提交
1637
            Infer(FloatVar(_)) => true,
1638 1639 1640 1641 1642 1643
            _ => false,
        }
    }

    pub fn is_trait(&self) -> bool {
        match self.sty {
V
varkor 已提交
1644
            Dynamic(..) => true,
T
Tshepang Lekhonkhobe 已提交
1645
            _ => false,
1646 1647 1648
        }
    }

1649 1650
    pub fn is_enum(&self) -> bool {
        match self.sty {
V
varkor 已提交
1651
            Adt(adt_def, _) => {
1652 1653 1654 1655 1656 1657
                adt_def.is_enum()
            }
            _ => false,
        }
    }

1658 1659
    pub fn is_closure(&self) -> bool {
        match self.sty {
V
varkor 已提交
1660
            Closure(..) => true,
1661 1662 1663 1664
            _ => false,
        }
    }

1665 1666
    pub fn is_generator(&self) -> bool {
        match self.sty {
V
varkor 已提交
1667
            Generator(..) => true,
1668 1669 1670 1671
            _ => false,
        }
    }

1672 1673
    pub fn is_integral(&self) -> bool {
        match self.sty {
1674
            Infer(IntVar(_)) | Int(_) | Uint(_) => true,
1675 1676 1677 1678
            _ => false
        }
    }

1679 1680
    pub fn is_fresh_ty(&self) -> bool {
        match self.sty {
V
varkor 已提交
1681
            Infer(FreshTy(_)) => true,
1682 1683 1684 1685
            _ => false,
        }
    }

1686 1687
    pub fn is_fresh(&self) -> bool {
        match self.sty {
V
varkor 已提交
1688 1689 1690
            Infer(FreshTy(_)) => true,
            Infer(FreshIntTy(_)) => true,
            Infer(FreshFloatTy(_)) => true,
T
Tshepang Lekhonkhobe 已提交
1691
            _ => false,
1692 1693 1694 1695 1696
        }
    }

    pub fn is_char(&self) -> bool {
        match self.sty {
1697
            Char => true,
T
Tshepang Lekhonkhobe 已提交
1698
            _ => false,
1699 1700 1701 1702 1703
        }
    }

    pub fn is_fp(&self) -> bool {
        match self.sty {
1704
            Infer(FloatVar(_)) | Float(_) => true,
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
            _ => false
        }
    }

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

    pub fn is_signed(&self) -> bool {
        match self.sty {
1715
            Int(_) => true,
T
Tshepang Lekhonkhobe 已提交
1716
            _ => false,
1717 1718 1719 1720 1721
        }
    }

    pub fn is_machine(&self) -> bool {
        match self.sty {
1722 1723
            Int(ast::IntTy::Isize) | Uint(ast::UintTy::Usize) => false,
            Int(..) | Uint(..) | Float(..) => true,
T
Tshepang Lekhonkhobe 已提交
1724
            _ => false,
1725 1726 1727
        }
    }

1728 1729
    pub fn has_concrete_skeleton(&self) -> bool {
        match self.sty {
V
varkor 已提交
1730
            Param(_) | Infer(_) | Error => false,
1731 1732 1733 1734
            _ => true,
        }
    }

1735 1736 1737 1738
    /// 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.
1739
    pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1740
        match self.sty {
V
varkor 已提交
1741
            Adt(def, _) if def.is_box() => {
1742
                Some(TypeAndMut {
1743
                    ty: self.boxed_ty(),
1744
                    mutbl: hir::MutImmutable,
1745 1746
                })
            },
V
varkor 已提交
1747 1748
            Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl }),
            RawPtr(mt) if explicit => Some(mt),
T
Tshepang Lekhonkhobe 已提交
1749
            _ => None,
1750 1751 1752
        }
    }

1753
    /// Returns the type of `ty[i]`.
1754 1755
    pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
        match self.sty {
V
varkor 已提交
1756
            Array(ty, _) | Slice(ty) => Some(ty),
T
Tshepang Lekhonkhobe 已提交
1757
            _ => None,
1758 1759 1760
        }
    }

1761
    pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1762
        match self.sty {
V
varkor 已提交
1763
            FnDef(def_id, substs) => {
1764 1765
                tcx.fn_sig(def_id).subst(tcx, substs)
            }
V
varkor 已提交
1766
            FnPtr(f) => f,
1767
            _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1768 1769 1770 1771 1772
        }
    }

    pub fn is_fn(&self) -> bool {
        match self.sty {
V
varkor 已提交
1773
            FnDef(..) | FnPtr(_) => true,
T
Tshepang Lekhonkhobe 已提交
1774
            _ => false,
1775 1776 1777
        }
    }

1778 1779
    pub fn is_impl_trait(&self) -> bool {
        match self.sty {
1780
            Opaque(..) => true,
1781 1782 1783 1784
            _ => false,
        }
    }

1785
    pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1786
        match self.sty {
V
varkor 已提交
1787
            Adt(adt, _) => Some(adt),
T
Tshepang Lekhonkhobe 已提交
1788
            _ => None,
1789 1790
        }
    }
1791 1792 1793 1794

    /// 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 已提交
1795
    pub fn regions(&self) -> Vec<ty::Region<'tcx>> {
1796
        match self.sty {
V
varkor 已提交
1797
            Ref(region, _, _) => {
1798
                vec![region]
1799
            }
V
varkor 已提交
1800
            Dynamic(ref obj, region) => {
1801 1802 1803 1804
                let mut v = vec![region];
                if let Some(p) = obj.principal() {
                    v.extend(p.skip_binder().substs.regions());
                }
1805 1806
                v
            }
1807
            Adt(_, substs) | Opaque(_, substs) => {
1808
                substs.regions().collect()
1809
            }
V
varkor 已提交
1810 1811
            Closure(_, ClosureSubsts { ref substs }) |
            Generator(_, GeneratorSubsts { ref substs }, _) => {
1812
                substs.regions().collect()
1813
            }
1814
            Projection(ref data) | UnnormalizedProjection(ref data) => {
1815
                data.substs.regions().collect()
1816
            }
V
varkor 已提交
1817 1818 1819
            FnDef(..) |
            FnPtr(_) |
            GeneratorWitness(..) |
1820 1821 1822 1823 1824 1825
            Bool |
            Char |
            Int(_) |
            Uint(_) |
            Float(_) |
            Str |
V
varkor 已提交
1826 1827 1828 1829 1830
            Array(..) |
            Slice(_) |
            RawPtr(_) |
            Never |
            Tuple(..) |
V
varkor 已提交
1831 1832
            Foreign(..) |
            Param(_) |
V
varkor 已提交
1833 1834
            Infer(_) |
            Error => {
1835 1836 1837 1838
                vec![]
            }
        }
    }
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849

    /// 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é 已提交
1850 1851
    /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
    /// is complete, that type variable will be unified.
1852 1853
    pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
        match self.sty {
1854
            Int(int_ty) => match int_ty {
1855 1856 1857 1858 1859 1860
                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 已提交
1861
            Infer(_) => None,
1862

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

1865 1866 1867
            _ => bug!("cannot convert type `{:?}` to a closure kind", self),
        }
    }
1868 1869 1870 1871 1872 1873 1874

    /// 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 已提交
1875
            ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) |
1876
            ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
V
varkor 已提交
1877
            ty::FnDef(..) | ty::FnPtr(_) | ty::RawPtr(..) |
1878
            ty::Char | ty::Ref(..) | ty::Generator(..) |
V
varkor 已提交
1879 1880
            ty::GeneratorWitness(..) | ty::Array(..) | ty::Closure(..) |
            ty::Never | ty::Error =>
1881 1882
                true,

1883
            ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) =>
1884 1885
                false,

V
varkor 已提交
1886
            ty::Tuple(tys) =>
1887 1888
                tys.iter().all(|ty| ty.is_trivially_sized(tcx)),

V
varkor 已提交
1889
            ty::Adt(def, _substs) =>
1890 1891
                def.sized_constraint(tcx).is_empty(),

1892
            ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
1893

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

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

V
varkor 已提交
1898 1899 1900 1901
            ty::Infer(ty::CanonicalTy(_)) |
            ty::Infer(ty::FreshTy(_)) |
            ty::Infer(ty::FreshIntTy(_)) |
            ty::Infer(ty::FreshFloatTy(_)) =>
1902 1903 1904
                bug!("is_trivially_sized applied to unexpected type: {:?}", self),
        }
    }
1905
}
1906 1907

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

1912
    pub val: ConstValue<'tcx>,
1913 1914
}

1915 1916 1917 1918 1919 1920 1921 1922
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 {
1923
            val: ConstValue::Unevaluated(def_id, substs),
1924 1925 1926 1927 1928
            ty,
        })
    }

    #[inline]
1929
    pub fn from_const_value(
1930
        tcx: TyCtxt<'_, '_, 'tcx>,
1931
        val: ConstValue<'tcx>,
1932 1933 1934 1935 1936 1937 1938 1939 1940
        ty: Ty<'tcx>,
    ) -> &'tcx Self {
        tcx.mk_const(Const {
            val,
            ty,
        })
    }

    #[inline]
O
Oliver Schneider 已提交
1941
    pub fn from_scalar(
1942
        tcx: TyCtxt<'_, '_, 'tcx>,
O
Oliver Schneider 已提交
1943
        val: Scalar,
1944 1945
        ty: Ty<'tcx>,
    ) -> &'tcx Self {
1946
        Self::from_const_value(tcx, ConstValue::Scalar(val), ty)
1947 1948 1949 1950 1951
    }

    #[inline]
    pub fn from_bits(
        tcx: TyCtxt<'_, '_, 'tcx>,
1952
        bits: u128,
O
Oliver Schneider 已提交
1953
        ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
1954
    ) -> &'tcx Self {
1955 1956
        let ty = tcx.lift_to_global(&ty).unwrap();
        let size = tcx.layout_of(ty).unwrap_or_else(|e| {
O
Oliver Schneider 已提交
1957
            panic!("could not compute layout for {:?}: {:?}", ty, e)
1958
        }).size;
1959 1960
        let shift = 128 - size.bits();
        let truncated = (bits << shift) >> shift;
1961
        assert_eq!(truncated, bits, "from_bits called with untruncated value");
1962
        Self::from_scalar(tcx, Scalar::Bits { bits, size: size.bytes() as u8 }, ty.value)
1963 1964 1965 1966
    }

    #[inline]
    pub fn zero_sized(tcx: TyCtxt<'_, '_, 'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
1967
        Self::from_scalar(tcx, Scalar::Bits { bits: 0, size: 0 }, ty)
1968 1969 1970 1971
    }

    #[inline]
    pub fn from_bool(tcx: TyCtxt<'_, '_, 'tcx>, v: bool) -> &'tcx Self {
O
Oliver Schneider 已提交
1972
        Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
1973 1974 1975 1976
    }

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

    #[inline]
O
Oliver Schneider 已提交
1981 1982 1983 1984 1985 1986
    pub fn to_bits(
        &self,
        tcx: TyCtxt<'_, '_, 'tcx>,
        ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
    ) -> Option<u128> {
        if self.ty != ty.value {
1987 1988
            return None;
        }
1989 1990
        let ty = tcx.lift_to_global(&ty).unwrap();
        let size = tcx.layout_of(ty).ok()?.size;
R
Ralf Jung 已提交
1991
        self.val.try_to_bits(size)
1992 1993 1994
    }

    #[inline]
1995
    pub fn to_ptr(&self) -> Option<Pointer> {
R
Ralf Jung 已提交
1996
        self.val.try_to_ptr()
1997 1998
    }

1999
    #[inline]
O
Oliver Schneider 已提交
2000 2001 2002 2003 2004 2005
    pub fn assert_bits(
        &self,
        tcx: TyCtxt<'_, '_, '_>,
        ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
    ) -> Option<u128> {
        assert_eq!(self.ty, ty.value);
2006 2007
        let ty = tcx.lift_to_global(&ty).unwrap();
        let size = tcx.layout_of(ty).ok()?.size;
R
Ralf Jung 已提交
2008
        self.val.try_to_bits(size)
2009 2010 2011 2012
    }

    #[inline]
    pub fn assert_bool(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<bool> {
O
Oliver Schneider 已提交
2013
        self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.bool)).and_then(|v| match v {
2014 2015 2016 2017 2018 2019 2020 2021
            0 => Some(false),
            1 => Some(true),
            _ => None,
        })
    }

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

    #[inline]
O
Oliver Schneider 已提交
2026 2027 2028 2029 2030
    pub fn unwrap_bits(
        &self,
        tcx: TyCtxt<'_, '_, '_>,
        ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
    ) -> u128 {
2031
        match self.assert_bits(tcx, ty) {
2032
            Some(val) => val,
O
Oliver Schneider 已提交
2033
            None => bug!("expected bits of {}, got {:#?}", ty.value, self),
2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
        }
    }

    #[inline]
    pub fn unwrap_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> u64 {
        match self.assert_usize(tcx) {
            Some(val) => val,
            None => bug!("expected constant usize, got {:#?}", self),
        }
    }
}

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