mod.rs 108.0 KB
Newer Older
1
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// 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.

S
Steven Fackler 已提交
11 12 13 14 15 16 17
pub use self::ImplOrTraitItemId::*;
pub use self::Variance::*;
pub use self::DtorKind::*;
pub use self::ImplOrTraitItemContainer::*;
pub use self::BorrowKind::*;
pub use self::ImplOrTraitItem::*;
pub use self::IntVarValue::*;
18
pub use self::LvaluePreference::*;
19
pub use self::fold::TypeFoldable;
S
Steven Fackler 已提交
20

21
use dep_graph::{self, DepNode};
22
use hir::map as ast_map;
23
use middle;
S
Seo Sanghyeon 已提交
24
use middle::cstore::{self, LOCAL_CRATE};
25
use hir::def::{Def, PathResolution, ExportMap};
26
use hir::def_id::DefId;
27
use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
28
use middle::region::{CodeExtent, ROOT_CODE_EXTENT};
29 30
use traits;
use ty;
31
use ty::subst::{Subst, Substs};
32
use ty::walk::TypeWalker;
33
use util::common::MemoizationMap;
34
use util::nodemap::NodeSet;
35
use util::nodemap::FnvHashMap;
36

37
use serialize::{Encodable, Encoder, Decodable, Decoder};
S
Seo Sanghyeon 已提交
38
use std::borrow::Cow;
39
use std::cell::Cell;
40
use std::hash::{Hash, Hasher};
41
use std::iter;
H
Huon Wilson 已提交
42
use std::rc::Rc;
43
use std::slice;
44
use std::vec::IntoIter;
45
use syntax::ast::{self, CrateNum, Name, NodeId};
46
use syntax::attr;
47
use syntax::parse::token::InternedString;
48
use syntax_pos::{DUMMY_SP, Span};
49

50
use rustc_const_math::ConstInt;
O
Oliver Schneider 已提交
51

52 53 54
use hir;
use hir::{ItemImpl, ItemTrait, PatKind};
use hir::intravisit::Visitor;
55

56
pub use self::sty::{Binder, DebruijnIndex};
57
pub use self::sty::{BuiltinBound, BuiltinBounds};
58
pub use self::sty::{BareFnTy, FnSig, PolyFnSig};
59
pub use self::sty::{ClosureTy, InferTy, ParamTy, ProjectionTy, TraitObject};
60 61
pub use self::sty::{ClosureSubsts, TypeAndMut};
pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
62 63
pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
64
pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
65
pub use self::sty::Issue32330;
66 67 68 69 70 71 72 73 74 75 76 77
pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid, SkolemizedRegionVid};
pub use self::sty::BoundRegion::*;
pub use self::sty::InferTy::*;
pub use self::sty::Region::*;
pub use self::sty::TypeVariants::*;

pub use self::sty::BuiltinBound::Send as BoundSend;
pub use self::sty::BuiltinBound::Sized as BoundSized;
pub use self::sty::BuiltinBound::Copy as BoundCopy;
pub use self::sty::BuiltinBound::Sync as BoundSync;

pub use self::contents::TypeContents;
78
pub use self::context::{TyCtxt, tls};
79 80
pub use self::context::{CtxtArenas, Lift, Tables};

81 82
pub use self::trait_def::{TraitDef, TraitFlags};

83
pub mod adjustment;
84
pub mod cast;
85
pub mod error;
86 87
pub mod fast_reject;
pub mod fold;
88
pub mod item_path;
89
pub mod layout;
90
pub mod _match;
91
pub mod maps;
92 93
pub mod outlives;
pub mod relate;
94
pub mod subst;
95
pub mod trait_def;
96 97
pub mod walk;
pub mod wf;
98
pub mod util;
99

100 101 102 103 104 105 106
mod contents;
mod context;
mod flags;
mod ivar;
mod structural_impls;
mod sty;

O
Oliver Schneider 已提交
107
pub type Disr = ConstInt;
108

109
// Data types
110

111 112
/// The complete set of all analyses described in this module. This is
/// produced by the driver and fed to trans and later passes.
J
Jeffrey Seyfried 已提交
113
#[derive(Clone)]
114
pub struct CrateAnalysis<'a> {
115
    pub export_map: ExportMap,
116
    pub access_levels: middle::privacy::AccessLevels,
117
    pub reachable: NodeSet,
118
    pub name: &'a str,
119
    pub glob_map: Option<hir::GlobMap>,
120 121
}

122 123 124
#[derive(Copy, Clone)]
pub enum DtorKind {
    NoDtor,
125
    TraitDtor
126 127 128 129 130
}

impl DtorKind {
    pub fn is_present(&self) -> bool {
        match *self {
131
            TraitDtor => true,
132 133 134 135 136
            _ => false
        }
    }
}

137
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
138
pub enum ImplOrTraitItemContainer {
N
Niko Matsakis 已提交
139 140
    TraitContainer(DefId),
    ImplContainer(DefId),
141 142
}

143
impl ImplOrTraitItemContainer {
N
Niko Matsakis 已提交
144
    pub fn id(&self) -> DefId {
145 146 147 148 149 150 151
        match *self {
            TraitContainer(id) => id,
            ImplContainer(id) => id,
        }
    }
}

A
Aaron Turon 已提交
152 153 154 155 156 157 158 159 160 161 162
/// The "header" of an impl is everything outside the body: a Self type, a trait
/// ref (in the case of a trait impl), and a set of predicates (from the
/// bounds/where clauses).
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct ImplHeader<'tcx> {
    pub impl_def_id: DefId,
    pub self_ty: Ty<'tcx>,
    pub trait_ref: Option<TraitRef<'tcx>>,
    pub predicates: Vec<Predicate<'tcx>>,
}

163 164
impl<'a, 'gcx, 'tcx> ImplHeader<'tcx> {
    pub fn with_fresh_ty_vars(selcx: &mut traits::SelectionContext<'a, 'gcx, 'tcx>,
165 166
                              impl_def_id: DefId)
                              -> ImplHeader<'tcx>
A
Aaron Turon 已提交
167 168
    {
        let tcx = selcx.tcx();
169
        let impl_substs = selcx.infcx().fresh_substs_for_item(DUMMY_SP, impl_def_id);
A
Aaron Turon 已提交
170 171 172

        let header = ImplHeader {
            impl_def_id: impl_def_id,
173
            self_ty: tcx.lookup_item_type(impl_def_id).ty,
A
Aaron Turon 已提交
174
            trait_ref: tcx.impl_trait_ref(impl_def_id),
175
            predicates: tcx.lookup_predicates(impl_def_id).predicates
176
        }.subst(tcx, impl_substs);
A
Aaron Turon 已提交
177

178 179
        let traits::Normalized { value: mut header, obligations } =
            traits::normalize(selcx, traits::ObligationCause::dummy(), &header);
A
Aaron Turon 已提交
180 181 182 183 184 185

        header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
        header
    }
}

186
#[derive(Clone)]
187
pub enum ImplOrTraitItem<'tcx> {
188
    ConstTraitItem(Rc<AssociatedConst<'tcx>>),
189
    MethodTraitItem(Rc<Method<'tcx>>),
190
    TypeTraitItem(Rc<AssociatedType<'tcx>>),
191 192
}

193
impl<'tcx> ImplOrTraitItem<'tcx> {
194 195
    fn id(&self) -> ImplOrTraitItemId {
        match *self {
196 197 198
            ConstTraitItem(ref associated_const) => {
                ConstTraitItemId(associated_const.def_id)
            }
199
            MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
200 201 202
            TypeTraitItem(ref associated_type) => {
                TypeTraitItemId(associated_type.def_id)
            }
203 204 205
        }
    }

206 207 208 209 210 211 212 213
    pub fn def(&self) -> Def {
        match *self {
            ConstTraitItem(ref associated_const) => Def::AssociatedConst(associated_const.def_id),
            MethodTraitItem(ref method) => Def::Method(method.def_id),
            TypeTraitItem(ref ty) => Def::AssociatedTy(ty.container.id(), ty.def_id),
        }
    }

N
Niko Matsakis 已提交
214
    pub fn def_id(&self) -> DefId {
215
        match *self {
216
            ConstTraitItem(ref associated_const) => associated_const.def_id,
217
            MethodTraitItem(ref method) => method.def_id,
218
            TypeTraitItem(ref associated_type) => associated_type.def_id,
219 220 221
        }
    }

222
    pub fn name(&self) -> Name {
223
        match *self {
224
            ConstTraitItem(ref associated_const) => associated_const.name,
225 226
            MethodTraitItem(ref method) => method.name,
            TypeTraitItem(ref associated_type) => associated_type.name,
227 228 229
        }
    }

230
    pub fn vis(&self) -> Visibility {
231 232 233 234 235 236 237
        match *self {
            ConstTraitItem(ref associated_const) => associated_const.vis,
            MethodTraitItem(ref method) => method.vis,
            TypeTraitItem(ref associated_type) => associated_type.vis,
        }
    }

238 239
    pub fn container(&self) -> ImplOrTraitItemContainer {
        match *self {
240
            ConstTraitItem(ref associated_const) => associated_const.container,
241
            MethodTraitItem(ref method) => method.container,
242
            TypeTraitItem(ref associated_type) => associated_type.container,
243 244
        }
    }
245

246
    pub fn as_opt_method(&self) -> Option<Rc<Method<'tcx>>> {
247 248
        match *self {
            MethodTraitItem(ref m) => Some((*m).clone()),
249
            _ => None,
250 251
        }
    }
252 253
}

J
Jorge Aparicio 已提交
254
#[derive(Clone, Copy, Debug)]
255
pub enum ImplOrTraitItemId {
N
Niko Matsakis 已提交
256 257 258
    ConstTraitItemId(DefId),
    MethodTraitItemId(DefId),
    TypeTraitItemId(DefId),
259 260 261
}

impl ImplOrTraitItemId {
N
Niko Matsakis 已提交
262
    pub fn def_id(&self) -> DefId {
263
        match *self {
264
            ConstTraitItemId(def_id) => def_id,
265
            MethodTraitItemId(def_id) => def_id,
266
            TypeTraitItemId(def_id) => def_id,
267 268 269 270
        }
    }
}

271 272 273 274 275 276 277 278 279 280
#[derive(Clone, Debug, PartialEq, Eq, Copy)]
pub enum Visibility {
    /// Visible everywhere (including in other crates).
    Public,
    /// Visible only in the given crate-local module.
    Restricted(NodeId),
    /// Not visible anywhere in the local crate. This is the visibility of private external items.
    PrivateExternal,
}

281 282 283 284 285 286 287
pub trait NodeIdTree {
    fn is_descendant_of(&self, node: NodeId, ancestor: NodeId) -> bool;
}

impl<'a> NodeIdTree for ast_map::Map<'a> {
    fn is_descendant_of(&self, node: NodeId, ancestor: NodeId) -> bool {
        let mut node_ancestor = node;
J
Jeffrey Seyfried 已提交
288
        while node_ancestor != ancestor {
289
            let node_ancestor_parent = self.get_module_parent(node_ancestor);
J
Jeffrey Seyfried 已提交
290 291 292
            if node_ancestor_parent == node_ancestor {
                return false;
            }
293 294
            node_ancestor = node_ancestor_parent;
        }
J
Jeffrey Seyfried 已提交
295
        true
296 297 298
    }
}

299
impl Visibility {
300
    pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
301 302
        match *visibility {
            hir::Public => Visibility::Public,
303
            hir::Visibility::Crate => Visibility::Restricted(ast::CRATE_NODE_ID),
304
            hir::Visibility::Restricted { id, .. } => match tcx.expect_def(id) {
305 306
                // If there is no resolution, `resolve` will have already reported an error, so
                // assume that the visibility is public to avoid reporting more privacy errors.
307 308
                Def::Err => Visibility::Public,
                def => Visibility::Restricted(tcx.map.as_local_node_id(def.def_id()).unwrap()),
309
            },
310 311 312
            hir::Inherited => Visibility::Restricted(tcx.map.get_module_parent(id)),
        }
    }
313 314

    /// Returns true if an item with this visibility is accessible from the given block.
315
    pub fn is_accessible_from<T: NodeIdTree>(self, block: NodeId, tree: &T) -> bool {
316 317 318 319 320 321 322 323 324
        let restriction = match self {
            // Public items are visible everywhere.
            Visibility::Public => return true,
            // Private items from other crates are visible nowhere.
            Visibility::PrivateExternal => return false,
            // Restricted items are visible in an arbitrary local module.
            Visibility::Restricted(module) => module,
        };

325
        tree.is_descendant_of(block, restriction)
326
    }
327 328

    /// Returns true if this visibility is at least as accessible as the given visibility
329
    pub fn is_at_least<T: NodeIdTree>(self, vis: Visibility, tree: &T) -> bool {
330 331 332 333 334 335
        let vis_restriction = match vis {
            Visibility::Public => return self == Visibility::Public,
            Visibility::PrivateExternal => return true,
            Visibility::Restricted(module) => module,
        };

336
        self.is_accessible_from(vis_restriction, tree)
337
    }
338 339
}

J
Jorge Aparicio 已提交
340
#[derive(Clone, Debug)]
341
pub struct Method<'tcx> {
342
    pub name: Name,
343
    pub generics: &'tcx Generics<'tcx>,
344
    pub predicates: GenericPredicates<'tcx>,
345
    pub fty: &'tcx BareFnTy<'tcx>,
346
    pub explicit_self: ExplicitSelfCategory<'tcx>,
347
    pub vis: Visibility,
348
    pub defaultness: hir::Defaultness,
N
Niko Matsakis 已提交
349
    pub def_id: DefId,
350
    pub container: ImplOrTraitItemContainer,
351
}
352

353
impl<'tcx> Method<'tcx> {
354
    pub fn new(name: Name,
355
               generics: &'tcx ty::Generics<'tcx>,
356
               predicates: GenericPredicates<'tcx>,
357
               fty: &'tcx BareFnTy<'tcx>,
358
               explicit_self: ExplicitSelfCategory<'tcx>,
359
               vis: Visibility,
360
               defaultness: hir::Defaultness,
N
Niko Matsakis 已提交
361
               def_id: DefId,
362
               container: ImplOrTraitItemContainer)
363
               -> Method<'tcx> {
364
        Method {
365
            name: name,
366
            generics: generics,
367
            predicates: predicates,
368 369 370
            fty: fty,
            explicit_self: explicit_self,
            vis: vis,
371
            defaultness: defaultness,
372
            def_id: def_id,
373
            container: container,
374 375
        }
    }
376

N
Niko Matsakis 已提交
377
    pub fn container_id(&self) -> DefId {
378 379 380 381 382
        match self.container {
            TraitContainer(id) => id,
            ImplContainer(id) => id,
        }
    }
383 384
}

385 386 387 388 389 390 391 392 393 394 395 396 397 398
impl<'tcx> PartialEq for Method<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.def_id == other.def_id }
}

impl<'tcx> Eq for Method<'tcx> {}

impl<'tcx> Hash for Method<'tcx> {
    #[inline]
    fn hash<H: Hasher>(&self, s: &mut H) {
        self.def_id.hash(s)
    }
}

399 400
#[derive(Clone, Copy, Debug)]
pub struct AssociatedConst<'tcx> {
401
    pub name: Name,
402
    pub ty: Ty<'tcx>,
403
    pub vis: Visibility,
404
    pub defaultness: hir::Defaultness,
N
Niko Matsakis 已提交
405
    pub def_id: DefId,
406
    pub container: ImplOrTraitItemContainer,
407
    pub has_value: bool
408 409
}

J
Jorge Aparicio 已提交
410
#[derive(Clone, Copy, Debug)]
411
pub struct AssociatedType<'tcx> {
412
    pub name: Name,
413
    pub ty: Option<Ty<'tcx>>,
414
    pub vis: Visibility,
415
    pub defaultness: hir::Defaultness,
N
Niko Matsakis 已提交
416
    pub def_id: DefId,
417 418 419
    pub container: ImplOrTraitItemContainer,
}

420
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
421
pub enum Variance {
422 423 424 425
    Covariant,      // T<A> <: T<B> iff A <: B -- e.g., function return type
    Invariant,      // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
    Contravariant,  // T<A> <: T<B> iff B <: A -- e.g., function param type
    Bivariant,      // T<A> <: T<B>            -- e.g., unused type parameter
426
}
427

428
#[derive(Clone, Copy, Debug)]
429
pub struct MethodCallee<'tcx> {
430
    /// Impl method ID, for inherent methods, or trait method ID, otherwise.
N
Niko Matsakis 已提交
431
    pub def_id: DefId,
432
    pub ty: Ty<'tcx>,
433
    pub substs: &'tcx Substs<'tcx>
434 435 436 437 438 439 440 441 442 443 444 445 446 447
}

/// With method calls, we store some extra information in
/// side tables (i.e method_map). We use
/// MethodCall as a key to index into these tables instead of
/// just directly using the expression's NodeId. The reason
/// for this being that we may apply adjustments (coercions)
/// with the resulting expression also needing to use the
/// side tables. The problem with this is that we don't
/// assign a separate NodeId to this new expression
/// and so it would clash with the base expression if both
/// needed to add to the side tables. Thus to disambiguate
/// we also keep track of whether there's an adjustment in
/// our key.
J
Jorge Aparicio 已提交
448
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
449
pub struct MethodCall {
450
    pub expr_id: NodeId,
451
    pub autoderef: u32
452 453 454
}

impl MethodCall {
455
    pub fn expr(id: NodeId) -> MethodCall {
456 457
        MethodCall {
            expr_id: id,
458
            autoderef: 0
459 460 461
        }
    }

462
    pub fn autoderef(expr_id: NodeId, autoderef: u32) -> MethodCall {
463 464
        MethodCall {
            expr_id: expr_id,
465
            autoderef: 1 + autoderef
466 467 468 469 470 471
        }
    }
}

// maps from an expression id that corresponds to a method call to the details
// of the method to be invoked
472
pub type MethodMap<'tcx> = FnvHashMap<MethodCall, MethodCallee<'tcx>>;
473

474 475 476
// Contains information needed to resolve types and (in the future) look up
// the types of AST nodes.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
477
pub struct CReaderCacheKey {
478 479 480 481
    pub cnum: CrateNum,
    pub pos: usize,
}

482 483 484 485 486 487 488 489 490
/// Describes the fragment-state associated with a NodeId.
///
/// Currently only unfragmented paths have entries in the table,
/// but longer-term this enum is expected to expand to also
/// include data for fragmented paths.
#[derive(Copy, Clone, Debug)]
pub enum FragmentInfo {
    Moved { var: NodeId, move_expr: NodeId },
    Assigned { var: NodeId, assign_expr: NodeId, assignee_id: NodeId },
491
}
492

493 494 495 496
// Flags that we track on types. These flags are propagated upwards
// through the type during type construction, so that we can quickly
// check whether the type has various kinds of types in it without
// recursing over the type itself.
497 498
bitflags! {
    flags TypeFlags: u32 {
499 500 501 502
        const HAS_PARAMS         = 1 << 0,
        const HAS_SELF           = 1 << 1,
        const HAS_TY_INFER       = 1 << 2,
        const HAS_RE_INFER       = 1 << 3,
N
Niko Matsakis 已提交
503 504 505 506 507 508
        const HAS_RE_SKOL        = 1 << 4,
        const HAS_RE_EARLY_BOUND = 1 << 5,
        const HAS_FREE_REGIONS   = 1 << 6,
        const HAS_TY_ERR         = 1 << 7,
        const HAS_PROJECTION     = 1 << 8,
        const HAS_TY_CLOSURE     = 1 << 9,
509 510 511

        // true if there are "names" of types and regions and so forth
        // that are local to a particular fn
N
Niko Matsakis 已提交
512
        const HAS_LOCAL_NAMES    = 1 << 10,
513

514 515
        // Present if the type belongs in a local type context.
        // Only set for TyInfer other than Fresh.
516
        const KEEP_IN_LOCAL_TCX  = 1 << 11,
517

518 519 520
        const NEEDS_SUBST        = TypeFlags::HAS_PARAMS.bits |
                                   TypeFlags::HAS_SELF.bits |
                                   TypeFlags::HAS_RE_EARLY_BOUND.bits,
521 522

        // Flags representing the nominal content of a type,
523 524
        // computed by FlagsComputation. If you add a new nominal
        // flag, it should be added here too.
525 526 527 528
        const NOMINAL_FLAGS     = TypeFlags::HAS_PARAMS.bits |
                                  TypeFlags::HAS_SELF.bits |
                                  TypeFlags::HAS_TY_INFER.bits |
                                  TypeFlags::HAS_RE_INFER.bits |
529 530
                                  TypeFlags::HAS_RE_EARLY_BOUND.bits |
                                  TypeFlags::HAS_FREE_REGIONS.bits |
531
                                  TypeFlags::HAS_TY_ERR.bits |
532
                                  TypeFlags::HAS_PROJECTION.bits |
533
                                  TypeFlags::HAS_TY_CLOSURE.bits |
534 535
                                  TypeFlags::HAS_LOCAL_NAMES.bits |
                                  TypeFlags::KEEP_IN_LOCAL_TCX.bits,
536 537 538 539 540 541

        // Caches for type_is_sized, type_moves_by_default
        const SIZEDNESS_CACHED  = 1 << 16,
        const IS_SIZED          = 1 << 17,
        const MOVENESS_CACHED   = 1 << 18,
        const MOVES_BY_DEFAULT  = 1 << 19,
542
    }
543 544
}

545
pub struct TyS<'tcx> {
546
    pub sty: TypeVariants<'tcx>,
547
    pub flags: Cell<TypeFlags>,
548 549

    // the maximal depth of any bound regions appearing in this type.
550
    region_depth: u32,
551 552
}

553
impl<'tcx> PartialEq for TyS<'tcx> {
554
    #[inline]
555 556 557 558 559
    fn eq(&self, other: &TyS<'tcx>) -> bool {
        // (self as *const _) == (other as *const _)
        (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
    }
}
560
impl<'tcx> Eq for TyS<'tcx> {}
561

A
Alex Crichton 已提交
562 563
impl<'tcx> Hash for TyS<'tcx> {
    fn hash<H: Hasher>(&self, s: &mut H) {
N
Nick Cameron 已提交
564
        (self as *const TyS).hash(s)
A
Alex Crichton 已提交
565 566
    }
}
567

568
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
569

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
impl<'tcx> Encodable for Ty<'tcx> {
    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        cstore::tls::with_encoding_context(s, |ecx, rbml_w| {
            ecx.encode_ty(rbml_w, *self);
            Ok(())
        })
    }
}

impl<'tcx> Decodable for Ty<'tcx> {
    fn decode<D: Decoder>(d: &mut D) -> Result<Ty<'tcx>, D::Error> {
        cstore::tls::with_decoding_context(d, |dcx, rbml_r| {
            Ok(dcx.decode_ty(rbml_r))
        })
    }
}


S
Steve Klabnik 已提交
588 589 590
/// Upvars do not get their own node-id. Instead, we use the pair of
/// the original var id (that is, the root variable that is referenced
/// by the upvar) and the id of the closure expression.
591
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
592
pub struct UpvarId {
593 594
    pub var_id: NodeId,
    pub closure_expr_id: NodeId,
595 596
}

J
Jorge Aparicio 已提交
597
#[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
598 599 600 601 602 603 604 605 606
pub enum BorrowKind {
    /// Data must be immutable and is aliasable.
    ImmBorrow,

    /// Data must be immutable but not aliasable.  This kind of borrow
    /// cannot currently be expressed by the user and is used only in
    /// implicit closure bindings. It is needed when you the closure
    /// is borrowing or mutating a mutable referent, e.g.:
    ///
607
    ///    let x: &mut isize = ...;
608 609 610 611 612
    ///    let y = || *x += 5;
    ///
    /// If we were to try to translate this closure into a more explicit
    /// form, we'd encounter an error with the code as written:
    ///
613 614
    ///    struct Env { x: & &mut isize }
    ///    let x: &mut isize = ...;
615 616 617 618 619 620 621
    ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
    ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
    ///
    /// This is then illegal because you cannot mutate a `&mut` found
    /// in an aliasable location. To solve, you'd have to translate with
    /// an `&mut` borrow:
    ///
622 623
    ///    struct Env { x: & &mut isize }
    ///    let x: &mut isize = ...;
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
    ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
    ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
    ///
    /// Now the assignment to `**env.x` is legal, but creating a
    /// mutable pointer to `x` is not because `x` is not mutable. We
    /// could fix this by declaring `x` as `let mut x`. This is ok in
    /// user code, if awkward, but extra weird for closures, since the
    /// borrow is hidden.
    ///
    /// So we introduce a "unique imm" borrow -- the referent is
    /// immutable, but not aliasable. This solves the problem. For
    /// simplicity, we don't give users the way to express this
    /// borrow, it's just used when translating closures.
    UniqueImmBorrow,

    /// Data is mutable and not aliasable.
    MutBorrow
}

643 644
/// Information describing the capture of an upvar. This is computed
/// during `typeck`, specifically by `regionck`.
645
#[derive(PartialEq, Clone, Debug, Copy)]
646
pub enum UpvarCapture<'tcx> {
647 648 649 650 651 652
    /// Upvar is captured by value. This is always true when the
    /// closure is labeled `move`, but can also be true in other cases
    /// depending on inference.
    ByValue,

    /// Upvar is captured by reference.
653
    ByRef(UpvarBorrow<'tcx>),
654 655
}

656
#[derive(PartialEq, Clone, Copy)]
657
pub struct UpvarBorrow<'tcx> {
658 659 660
    /// The kind of borrow: by-ref upvars have access to shared
    /// immutable borrows, which are not part of the normal language
    /// syntax.
661
    pub kind: BorrowKind,
662 663

    /// Region of the resulting reference.
664
    pub region: &'tcx ty::Region,
665 666
}

667
pub type UpvarCaptureMap<'tcx> = FnvHashMap<UpvarId, UpvarCapture<'tcx>>;
668

669 670
#[derive(Copy, Clone)]
pub struct ClosureUpvar<'tcx> {
671
    pub def: Def,
672 673 674 675
    pub span: Span,
    pub ty: Ty<'tcx>,
}

676
#[derive(Clone, Copy, PartialEq)]
677
pub enum IntVarValue {
678 679
    IntType(ast::IntTy),
    UintType(ast::UintTy),
680 681
}

682 683 684 685 686
/// Default region to use for the bound of objects that are
/// supplied as the value for this type parameter. This is derived
/// from `T:'a` annotations appearing in the type definition.  If
/// this is `None`, then the default is inherited from the
/// surrounding context. See RFC #599 for details.
687
#[derive(Copy, Clone)]
688
pub enum ObjectLifetimeDefault<'tcx> {
689 690 691 692
    /// Require an explicit annotation. Occurs when multiple
    /// `T:'a` constraints are found.
    Ambiguous,

693 694 695
    /// Use the base default, typically 'static, but in a fn body it is a fresh variable
    BaseDefault,

696
    /// Use the given region as the default.
697
    Specific(&'tcx Region),
698 699
}

700
#[derive(Clone)]
701
pub struct TypeParameterDef<'tcx> {
702
    pub name: Name,
N
Niko Matsakis 已提交
703
    pub def_id: DefId,
704
    pub index: u32,
J
Jared Roesch 已提交
705
    pub default_def_id: DefId, // for use in error reporing about defaults
706
    pub default: Option<Ty<'tcx>>,
707
    pub object_lifetime_default: ObjectLifetimeDefault<'tcx>,
708 709
}

710
#[derive(Clone)]
711
pub struct RegionParameterDef<'tcx> {
712
    pub name: Name,
N
Niko Matsakis 已提交
713
    pub def_id: DefId,
714
    pub index: u32,
715
    pub bounds: Vec<&'tcx ty::Region>,
716 717
}

718
impl<'tcx> RegionParameterDef<'tcx> {
719
    pub fn to_early_bound_region(&self) -> ty::Region {
720 721 722 723
        ty::ReEarlyBound(ty::EarlyBoundRegion {
            index: self.index,
            name: self.name,
        })
724
    }
725
    pub fn to_bound_region(&self) -> ty::BoundRegion {
726 727
        // this is an early bound region, so unaffected by #32330
        ty::BoundRegion::BrNamed(self.def_id, self.name, Issue32330::WontChange)
728
    }
729 730 731
}

/// Information about the formal type/lifetime parameters associated
732
/// with an item or method. Analogous to hir::Generics.
J
Jorge Aparicio 已提交
733
#[derive(Clone, Debug)]
734
pub struct Generics<'tcx> {
735 736 737
    pub parent: Option<DefId>,
    pub parent_regions: u32,
    pub parent_types: u32,
738
    pub regions: Vec<RegionParameterDef<'tcx>>,
739
    pub types: Vec<TypeParameterDef<'tcx>>,
740
    pub has_self: bool,
741 742
}

743 744 745 746 747 748 749 750 751 752 753 754 755 756
impl<'tcx> Generics<'tcx> {
    pub fn parent_count(&self) -> usize {
        self.parent_regions as usize + self.parent_types as usize
    }

    pub fn own_count(&self) -> usize {
        self.regions.len() + self.types.len()
    }

    pub fn count(&self) -> usize {
        self.parent_count() + self.own_count()
    }
}

757
/// Bounds on generics.
758
#[derive(Clone)]
759
pub struct GenericPredicates<'tcx> {
760
    pub parent: Option<DefId>,
761
    pub predicates: Vec<Predicate<'tcx>>,
762 763
}

764 765
impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
    pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
766
                       -> InstantiatedPredicates<'tcx> {
767 768 769 770 771 772
        let mut instantiated = InstantiatedPredicates::empty();
        self.instantiate_into(tcx, &mut instantiated, substs);
        instantiated
    }
    pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
                           -> InstantiatedPredicates<'tcx> {
773
        InstantiatedPredicates {
774 775 776 777 778 779 780 781 782
            predicates: self.predicates.subst(tcx, substs)
        }
    }

    fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
                        instantiated: &mut InstantiatedPredicates<'tcx>,
                        substs: &Substs<'tcx>) {
        if let Some(def_id) = self.parent {
            tcx.lookup_predicates(def_id).instantiate_into(tcx, instantiated, substs);
783
        }
784
        instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
785
    }
786

787
    pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
788 789 790
                                  poly_trait_ref: &ty::PolyTraitRef<'tcx>)
                                  -> InstantiatedPredicates<'tcx>
    {
791
        assert_eq!(self.parent, None);
792
        InstantiatedPredicates {
793
            predicates: self.predicates.iter().map(|pred| {
794
                pred.subst_supertrait(tcx, poly_trait_ref)
795
            }).collect()
796 797
        }
    }
798 799
}

800
#[derive(Clone, PartialEq, Eq, Hash)]
801
pub enum Predicate<'tcx> {
N
Niko Matsakis 已提交
802 803
    /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
    /// the `Self` type of the trait reference and `A`, `B`, and `C`
804
    /// would be the type parameters.
805
    Trait(PolyTraitPredicate<'tcx>),
806

N
Niko Matsakis 已提交
807
    /// where `T1 == T2`.
808
    Equate(PolyEquatePredicate<'tcx>),
809 810

    /// where 'a : 'b
811
    RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
812 813

    /// where T : 'a
814
    TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
815

N
Niko Matsakis 已提交
816 817
    /// where <T as TraitRef>::Name == X, approximately.
    /// See `ProjectionPredicate` struct for details.
818
    Projection(PolyProjectionPredicate<'tcx>),
819 820 821 822 823

    /// no syntax: T WF
    WellFormed(Ty<'tcx>),

    /// trait must be object-safe
N
Niko Matsakis 已提交
824
    ObjectSafe(DefId),
825

826 827 828
    /// No direct syntax. May be thought of as `where T : FnFoo<...>`
    /// for some substitutions `...` and T being a closure type.
    /// Satisfied (or refuted) once we know the closure's kind.
829
    ClosureKind(DefId, ClosureKind),
830 831
}

832
impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
833
    /// Performs a substitution suitable for going from a
834 835 836 837
    /// poly-trait-ref to supertraits that must hold if that
    /// poly-trait-ref holds. This is slightly different from a normal
    /// substitution in terms of what happens with bound regions.  See
    /// lengthy comment below for details.
838
    pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
                            trait_ref: &ty::PolyTraitRef<'tcx>)
                            -> ty::Predicate<'tcx>
    {
        // The interaction between HRTB and supertraits is not entirely
        // obvious. Let me walk you (and myself) through an example.
        //
        // Let's start with an easy case. Consider two traits:
        //
        //     trait Foo<'a> : Bar<'a,'a> { }
        //     trait Bar<'b,'c> { }
        //
        // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
        // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
        // knew that `Foo<'x>` (for any 'x) then we also know that
        // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
        // normal substitution.
        //
        // In terms of why this is sound, the idea is that whenever there
        // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
        // holds.  So if there is an impl of `T:Foo<'a>` that applies to
        // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
        // `'a`.
        //
        // Another example to be careful of is this:
        //
        //     trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
        //     trait Bar1<'b,'c> { }
        //
        // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
        // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
        // reason is similar to the previous example: any impl of
        // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`.  So
        // basically we would want to collapse the bound lifetimes from
        // the input (`trait_ref`) and the supertraits.
        //
        // To achieve this in practice is fairly straightforward. Let's
        // consider the more complicated scenario:
        //
        // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
        //   has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
        //   where both `'x` and `'b` would have a DB index of 1.
        //   The substitution from the input trait-ref is therefore going to be
        //   `'a => 'x` (where `'x` has a DB index of 1).
        // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
        //   early-bound parameter and `'b' is a late-bound parameter with a
        //   DB index of 1.
        // - If we replace `'a` with `'x` from the input, it too will have
        //   a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
        //   just as we wanted.
        //
        // There is only one catch. If we just apply the substitution `'a
        // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
        // adjust the DB index because we substituting into a binder (it
        // tries to be so smart...) resulting in `for<'x> for<'b>
        // Bar1<'x,'b>` (we have no syntax for this, so use your
        // imagination). Basically the 'x will have DB index of 2 and 'b
        // will have DB index of 1. Not quite what we want. So we apply
        // the substitution to the *contents* of the trait reference,
        // rather than the trait reference itself (put another way, the
        // substitution code expects equal binding levels in the values
        // from the substitution and the value being substituted into, and
        // this trick achieves that).

        let substs = &trait_ref.0.substs;
        match *self {
            Predicate::Trait(ty::Binder(ref data)) =>
                Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
            Predicate::Equate(ty::Binder(ref data)) =>
                Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
            Predicate::RegionOutlives(ty::Binder(ref data)) =>
                Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
            Predicate::TypeOutlives(ty::Binder(ref data)) =>
                Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
            Predicate::Projection(ty::Binder(ref data)) =>
                Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
914 915 916 917
            Predicate::WellFormed(data) =>
                Predicate::WellFormed(data.subst(tcx, substs)),
            Predicate::ObjectSafe(trait_def_id) =>
                Predicate::ObjectSafe(trait_def_id),
918 919
            Predicate::ClosureKind(closure_def_id, kind) =>
                Predicate::ClosureKind(closure_def_id, kind),
920 921 922 923
        }
    }
}

924
#[derive(Clone, PartialEq, Eq, Hash)]
925
pub struct TraitPredicate<'tcx> {
926
    pub trait_ref: TraitRef<'tcx>
927 928 929 930
}
pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;

impl<'tcx> TraitPredicate<'tcx> {
N
Niko Matsakis 已提交
931
    pub fn def_id(&self) -> DefId {
932 933 934
        self.trait_ref.def_id
    }

935
    /// Creates the dep-node for selecting/evaluating this trait reference.
936
    fn dep_node(&self) -> DepNode<DefId> {
937 938 939 940 941 942 943
        // Ideally, the dep-node would just have all the input types
        // in it.  But they are limited to including def-ids. So as an
        // approximation we include the def-ids for all nominal types
        // found somewhere. This means that we will e.g. conflate the
        // dep-nodes for `u32: SomeTrait` and `u64: SomeTrait`, but we
        // would have distinct dep-nodes for `Vec<u32>: SomeTrait`,
        // `Rc<u32>: SomeTrait`, and `(Vec<u32>, Rc<u32>): SomeTrait`.
N
Niko Matsakis 已提交
944
        // Note that it's always sound to conflate dep-nodes, it just
945 946 947 948 949 950
        // leads to more recompilation.
        let def_ids: Vec<_> =
            self.input_types()
                .flat_map(|t| t.walk())
                .filter_map(|t| match t.sty {
                    ty::TyStruct(adt_def, _) |
951
                    ty::TyUnion(adt_def, _) |
952 953 954 955 956
                    ty::TyEnum(adt_def, _) =>
                        Some(adt_def.did),
                    _ =>
                        None
                })
957
                .chain(iter::once(self.def_id()))
958
                .collect();
959
        DepNode::TraitSelect(def_ids)
960 961
    }

962
    pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
963
        self.trait_ref.input_types()
964 965 966 967 968 969 970 971
    }

    pub fn self_ty(&self) -> Ty<'tcx> {
        self.trait_ref.self_ty()
    }
}

impl<'tcx> PolyTraitPredicate<'tcx> {
N
Niko Matsakis 已提交
972
    pub fn def_id(&self) -> DefId {
973
        // ok to skip binder since trait def-id does not care about regions
974 975
        self.0.def_id()
    }
976

977
    pub fn dep_node(&self) -> DepNode<DefId> {
978 979 980
        // ok to skip binder since depnode does not care about regions
        self.0.dep_node()
    }
981 982
}

J
Jorge Aparicio 已提交
983
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
984 985 986
pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;

J
Jorge Aparicio 已提交
987
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
988 989
pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
990 991 992
pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<&'tcx ty::Region,
                                                                   &'tcx ty::Region>;
pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, &'tcx ty::Region>;
993

994 995 996 997 998 999 1000 1001 1002 1003
/// This kind of predicate has no *direct* correspondent in the
/// syntax, but it roughly corresponds to the syntactic forms:
///
/// 1. `T : TraitRef<..., Item=Type>`
/// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
///
/// In particular, form #1 is "desugared" to the combination of a
/// normal trait predicate (`T : TraitRef<...>`) and one of these
/// predicates. Form #2 is a broader form in that it also permits
/// equality between arbitrary types. Processing an instance of Form
F
Flavio Percoco 已提交
1004
/// #2 eventually yields one of these `ProjectionPredicate`
1005
/// instances to normalize the LHS.
1006
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
1007 1008 1009 1010 1011 1012 1013
pub struct ProjectionPredicate<'tcx> {
    pub projection_ty: ProjectionTy<'tcx>,
    pub ty: Ty<'tcx>,
}

pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;

1014
impl<'tcx> PolyProjectionPredicate<'tcx> {
1015
    pub fn item_name(&self) -> Name {
1016 1017 1018
        self.0.projection_ty.item_name // safe to skip the binder to access a name
    }

1019
    pub fn sort_key(&self) -> (DefId, Name) {
1020 1021 1022 1023
        self.0.projection_ty.sort_key()
    }
}

1024 1025 1026 1027
pub trait ToPolyTraitRef<'tcx> {
    fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
}

1028
impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1029 1030 1031 1032 1033 1034 1035 1036
    fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
        assert!(!self.has_escaping_regions());
        ty::Binder(self.clone())
    }
}

impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
    fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1037
        self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
    }
}

impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
    fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
        // Note: unlike with TraitRef::to_poly_trait_ref(),
        // self.0.trait_ref is permitted to have escaping regions.
        // This is because here `self` has a `Binder` and so does our
        // return value, so we are preserving the number of binding
        // levels.
1048
        ty::Binder(self.0.projection_ty.trait_ref)
1049 1050 1051
    }
}

1052 1053
pub trait ToPredicate<'tcx> {
    fn to_predicate(&self) -> Predicate<'tcx>;
1054 1055
}

1056 1057
impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
    fn to_predicate(&self) -> Predicate<'tcx> {
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
        // we're about to add a binder, so let's check that we don't
        // accidentally capture anything, or else that might be some
        // weird debruijn accounting.
        assert!(!self.has_escaping_regions());

        ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
            trait_ref: self.clone()
        }))
    }
}

1069 1070
impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
    fn to_predicate(&self) -> Predicate<'tcx> {
1071
        ty::Predicate::Trait(self.to_poly_trait_predicate())
1072 1073 1074
    }
}

1075 1076
impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
    fn to_predicate(&self) -> Predicate<'tcx> {
1077 1078 1079 1080
        Predicate::Equate(self.clone())
    }
}

1081
impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1082
    fn to_predicate(&self) -> Predicate<'tcx> {
1083 1084 1085 1086
        Predicate::RegionOutlives(self.clone())
    }
}

1087 1088
impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
    fn to_predicate(&self) -> Predicate<'tcx> {
1089 1090
        Predicate::TypeOutlives(self.clone())
    }
1091 1092
}

1093 1094
impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
    fn to_predicate(&self) -> Predicate<'tcx> {
1095 1096 1097 1098
        Predicate::Projection(self.clone())
    }
}

1099
impl<'tcx> Predicate<'tcx> {
1100 1101 1102 1103 1104 1105
    /// Iterates over the types in this predicate. Note that in all
    /// cases this is skipping over a binder, so late-bound regions
    /// with depth 0 are bound by the predicate.
    pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
        let vec: Vec<_> = match *self {
            ty::Predicate::Trait(ref data) => {
1106
                data.skip_binder().input_types().collect()
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
            }
            ty::Predicate::Equate(ty::Binder(ref data)) => {
                vec![data.0, data.1]
            }
            ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
                vec![data.0]
            }
            ty::Predicate::RegionOutlives(..) => {
                vec![]
            }
            ty::Predicate::Projection(ref data) => {
1118
                let trait_inputs = data.0.projection_ty.trait_ref.input_types();
1119
                trait_inputs.chain(Some(data.0.ty)).collect()
1120
            }
1121 1122 1123 1124 1125 1126
            ty::Predicate::WellFormed(data) => {
                vec![data]
            }
            ty::Predicate::ObjectSafe(_trait_def_id) => {
                vec![]
            }
1127 1128 1129
            ty::Predicate::ClosureKind(_closure_def_id, _kind) => {
                vec![]
            }
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
        };

        // The only reason to collect into a vector here is that I was
        // too lazy to make the full (somewhat complicated) iterator
        // type that would be needed here. But I wanted this fn to
        // return an iterator conceptually, rather than a `Vec`, so as
        // to be closer to `Ty::walk`.
        vec.into_iter()
    }

1140
    pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1141 1142
        match *self {
            Predicate::Trait(ref t) => {
1143
                Some(t.to_poly_trait_ref())
1144
            }
1145
            Predicate::Projection(..) |
1146 1147
            Predicate::Equate(..) |
            Predicate::RegionOutlives(..) |
1148 1149
            Predicate::WellFormed(..) |
            Predicate::ObjectSafe(..) |
1150
            Predicate::ClosureKind(..) |
1151 1152 1153
            Predicate::TypeOutlives(..) => {
                None
            }
1154 1155 1156 1157
        }
    }
}

S
Steve Klabnik 已提交
1158 1159
/// Represents the bounds declared on a particular set of type
/// parameters.  Should eventually be generalized into a flag list of
1160 1161 1162 1163 1164
/// where clauses.  You can obtain a `InstantiatedPredicates` list from a
/// `GenericPredicates` by using the `instantiate` method. Note that this method
/// reflects an important semantic invariant of `InstantiatedPredicates`: while
/// the `GenericPredicates` are expressed in terms of the bound type
/// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
S
Steve Klabnik 已提交
1165 1166 1167 1168 1169 1170 1171 1172
/// represented a set of bounds for some particular instantiation,
/// meaning that the generic parameters have been substituted with
/// their values.
///
/// Example:
///
///     struct Foo<T,U:Bar<T>> { ... }
///
1173
/// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
J
Jorge Aparicio 已提交
1174
/// `[[], [U:Bar<T>]]`.  Now if there were some particular reference
1175 1176
/// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
/// [usize:Bar<isize>]]`.
1177
#[derive(Clone)]
1178
pub struct InstantiatedPredicates<'tcx> {
1179
    pub predicates: Vec<Predicate<'tcx>>,
1180 1181
}

1182 1183
impl<'tcx> InstantiatedPredicates<'tcx> {
    pub fn empty() -> InstantiatedPredicates<'tcx> {
1184
        InstantiatedPredicates { predicates: vec![] }
1185 1186
    }

1187 1188
    pub fn is_empty(&self) -> bool {
        self.predicates.is_empty()
1189
    }
1190 1191
}

1192
impl<'tcx> TraitRef<'tcx> {
N
Niko Matsakis 已提交
1193
    pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
1194 1195 1196
        TraitRef { def_id: def_id, substs: substs }
    }

1197
    pub fn self_ty(&self) -> Ty<'tcx> {
1198
        self.substs.type_at(0)
1199
    }
N
Niko Matsakis 已提交
1200

1201
    pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
N
Niko Matsakis 已提交
1202 1203 1204 1205
        // 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.
1206
        self.substs.types()
N
Niko Matsakis 已提交
1207
    }
1208 1209
}

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
/// When type checking, we use the `ParameterEnvironment` to track
/// details about the type/lifetime parameters that are in scope.
/// It primarily stores the bounds information.
///
/// Note: This information might seem to be redundant with the data in
/// `tcx.ty_param_defs`, but it is not. That table contains the
/// parameter definitions from an "outside" perspective, but this
/// struct will contain the bounds for a parameter as seen from inside
/// the function body. Currently the only real distinction is that
/// bound lifetime parameters are replaced with free ones, but in the
/// future I hope to refine the representation of types so as to make
/// more distinctions clearer.
1222
#[derive(Clone)]
1223
pub struct ParameterEnvironment<'tcx> {
1224
    /// See `construct_free_substs` for details.
1225
    pub free_substs: &'tcx Substs<'tcx>,
1226

1227 1228 1229 1230
    /// Each type parameter has an implicit region bound that
    /// indicates it must outlive at least the function body (the user
    /// may specify stronger requirements). This field indicates the
    /// region of the callee.
1231
    pub implicit_region_bound: &'tcx ty::Region,
1232 1233 1234

    /// Obligations that the caller must satisfy. This is basically
    /// the set of bounds on the in-scope type parameters, translated
1235
    /// into Obligations, and elaborated and normalized.
1236
    pub caller_bounds: Vec<ty::Predicate<'tcx>>,
1237

1238 1239 1240 1241 1242 1243 1244
    /// Scope that is attached to free regions for this scope. This
    /// is usually the id of the fn body, but for more abstract scopes
    /// like structs we often use the node-id of the struct.
    ///
    /// FIXME(#3696). It would be nice to refactor so that free
    /// regions don't have this implicit scope and instead introduce
    /// relationships in the environment.
1245
    pub free_id_outlive: CodeExtent,
1246 1247
}

1248
impl<'a, 'tcx> ParameterEnvironment<'tcx> {
1249 1250
    pub fn with_caller_bounds(&self,
                              caller_bounds: Vec<ty::Predicate<'tcx>>)
1251
                              -> ParameterEnvironment<'tcx>
1252 1253
    {
        ParameterEnvironment {
1254
            free_substs: self.free_substs,
1255 1256
            implicit_region_bound: self.implicit_region_bound,
            caller_bounds: caller_bounds,
1257
            free_id_outlive: self.free_id_outlive,
1258 1259 1260
        }
    }

1261
    /// Construct a parameter environment given an item, impl item, or trait item
1262 1263
    pub fn for_item(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: NodeId)
                    -> ParameterEnvironment<'tcx> {
1264
        match tcx.map.find(id) {
1265
            Some(ast_map::NodeImplItem(ref impl_item)) => {
1266
                match impl_item.node {
1267
                    hir::ImplItemKind::Type(_) | hir::ImplItemKind::Const(_, _) => {
1268 1269
                        // associated types don't have their own entry (for some reason),
                        // so for now just grab environment for the impl
1270 1271 1272
                        let impl_id = tcx.map.get_parent(id);
                        let impl_def_id = tcx.map.local_def_id(impl_id);
                        tcx.construct_parameter_environment(impl_item.span,
1273
                                                            impl_def_id,
1274
                                                            tcx.region_maps.item_extent(id))
1275
                    }
1276
                    hir::ImplItemKind::Method(_, ref body) => {
1277 1278
                        let method_def_id = tcx.map.local_def_id(id);
                        match tcx.impl_or_trait_item(method_def_id) {
1279
                            MethodTraitItem(ref method_ty) => {
1280
                                tcx.construct_parameter_environment(
1281
                                    impl_item.span,
1282
                                    method_ty.def_id,
1283
                                    tcx.region_maps.call_site_extent(id, body.id))
1284
                            }
1285
                            _ => {
1286 1287
                                bug!("ParameterEnvironment::for_item(): \
                                      got non-method item from impl method?!")
1288
                            }
1289 1290 1291 1292
                        }
                    }
                }
            }
1293 1294
            Some(ast_map::NodeTraitItem(trait_item)) => {
                match trait_item.node {
1295
                    hir::TypeTraitItem(..) | hir::ConstTraitItem(..) => {
1296 1297
                        // associated types don't have their own entry (for some reason),
                        // so for now just grab environment for the trait
1298 1299 1300
                        let trait_id = tcx.map.get_parent(id);
                        let trait_def_id = tcx.map.local_def_id(trait_id);
                        tcx.construct_parameter_environment(trait_item.span,
1301
                                                            trait_def_id,
1302
                                                            tcx.region_maps.item_extent(id))
1303
                    }
1304
                    hir::MethodTraitItem(_, ref body) => {
1305 1306 1307
                        // Use call-site for extent (unless this is a
                        // trait method with no default; then fallback
                        // to the method id).
1308 1309
                        let method_def_id = tcx.map.local_def_id(id);
                        match tcx.impl_or_trait_item(method_def_id) {
1310
                            MethodTraitItem(ref method_ty) => {
1311 1312
                                let extent = if let Some(ref body) = *body {
                                    // default impl: use call_site extent as free_id_outlive bound.
1313
                                    tcx.region_maps.call_site_extent(id, body.id)
1314 1315
                                } else {
                                    // no default impl: use item extent as free_id_outlive bound.
1316
                                    tcx.region_maps.item_extent(id)
1317
                                };
1318
                                tcx.construct_parameter_environment(
1319
                                    trait_item.span,
1320
                                    method_ty.def_id,
1321
                                    extent)
1322
                            }
1323
                            _ => {
1324 1325 1326
                                bug!("ParameterEnvironment::for_item(): \
                                      got non-method item from provided \
                                      method?!")
1327
                            }
1328 1329 1330 1331 1332 1333
                        }
                    }
                }
            }
            Some(ast_map::NodeItem(item)) => {
                match item.node {
1334
                    hir::ItemFn(_, _, _, _, _, ref body) => {
1335
                        // We assume this is a function.
1336 1337 1338 1339
                        let fn_def_id = tcx.map.local_def_id(id);

                        tcx.construct_parameter_environment(
                            item.span,
1340
                            fn_def_id,
1341
                            tcx.region_maps.call_site_extent(id, body.id))
1342
                    }
1343 1344
                    hir::ItemEnum(..) |
                    hir::ItemStruct(..) |
1345
                    hir::ItemUnion(..) |
1346
                    hir::ItemTy(..) |
1347 1348 1349
                    hir::ItemImpl(..) |
                    hir::ItemConst(..) |
                    hir::ItemStatic(..) => {
1350 1351
                        let def_id = tcx.map.local_def_id(id);
                        tcx.construct_parameter_environment(item.span,
1352
                                                            def_id,
1353
                                                            tcx.region_maps.item_extent(id))
1354
                    }
1355
                    hir::ItemTrait(..) => {
1356 1357
                        let def_id = tcx.map.local_def_id(id);
                        tcx.construct_parameter_environment(item.span,
1358
                                                            def_id,
1359
                                                            tcx.region_maps.item_extent(id))
1360
                    }
1361
                    _ => {
1362 1363 1364 1365
                        span_bug!(item.span,
                                  "ParameterEnvironment::for_item():
                                   can't create a parameter \
                                   environment for this kind of item")
1366 1367 1368
                    }
                }
            }
1369
            Some(ast_map::NodeExpr(expr)) => {
N
Niko Matsakis 已提交
1370
                // This is a convenience to allow closures to work.
1371 1372 1373 1374 1375
                if let hir::ExprClosure(..) = expr.node {
                    ParameterEnvironment::for_item(tcx, tcx.map.get_parent(id))
                } else {
                    tcx.empty_parameter_environment()
                }
N
Niko Matsakis 已提交
1376
            }
1377
            Some(ast_map::NodeForeignItem(item)) => {
1378 1379
                let def_id = tcx.map.local_def_id(id);
                tcx.construct_parameter_environment(item.span,
1380
                                                    def_id,
1381
                                                    ROOT_CODE_EXTENT)
1382
            }
1383
            _ => {
1384 1385
                bug!("ParameterEnvironment::from_item(): \
                      `{}` is not an item",
1386
                     tcx.map.node_to_string(id))
1387 1388 1389 1390 1391
            }
        }
    }
}

1392 1393 1394 1395 1396 1397
/// A "type scheme", in ML terminology, is a type combined with some
/// set of generic types that the type is, well, generic over. In Rust
/// terms, it is the "type" of a fn item or struct -- this type will
/// include various generic parameters that must be substituted when
/// the item/struct is referenced. That is called converting the type
/// scheme to a monotype.
1398
///
1399 1400 1401
/// - `generics`: the set of type parameters and their bounds
/// - `ty`: the base types, which may reference the parameters defined
///   in `generics`
N
Niko Matsakis 已提交
1402 1403 1404 1405 1406 1407
///
/// Note that TypeSchemes are also sometimes called "polytypes" (and
/// in fact this struct used to carry that name, so you may find some
/// stray references in a comment or something). We try to reserve the
/// "poly" prefix to refer to higher-ranked things, as in
/// `PolyTraitRef`.
1408 1409 1410
///
/// Note that each item also comes with predicates, see
/// `lookup_predicates`.
J
Jorge Aparicio 已提交
1411
#[derive(Clone, Debug)]
1412
pub struct TypeScheme<'tcx> {
1413
    pub generics: &'tcx Generics<'tcx>,
1414
    pub ty: Ty<'tcx>,
1415
}
1416

1417
bitflags! {
A
Ariel Ben-Yehuda 已提交
1418
    flags AdtFlags: u32 {
1419
        const NO_ADT_FLAGS        = 0,
A
Ariel Ben-Yehuda 已提交
1420 1421 1422 1423 1424 1425
        const IS_ENUM             = 1 << 0,
        const IS_DTORCK           = 1 << 1, // is this a dtorck type?
        const IS_DTORCK_VALID     = 1 << 2,
        const IS_PHANTOM_DATA     = 1 << 3,
        const IS_SIMD             = 1 << 4,
        const IS_FUNDAMENTAL      = 1 << 5,
V
Vadim Petrochenkov 已提交
1426
        const IS_UNION            = 1 << 7,
1427 1428 1429
    }
}

A
Ariel Ben-Yehuda 已提交
1430 1431 1432
pub type AdtDef<'tcx> = &'tcx AdtDefData<'tcx, 'static>;
pub type VariantDef<'tcx> = &'tcx VariantDefData<'tcx, 'static>;
pub type FieldDef<'tcx> = &'tcx FieldDefData<'tcx, 'static>;
1433

A
Ariel Ben-Yehuda 已提交
1434 1435 1436 1437 1438 1439
// See comment on AdtDefData for explanation
pub type AdtDefMaster<'tcx> = &'tcx AdtDefData<'tcx, 'tcx>;
pub type VariantDefMaster<'tcx> = &'tcx VariantDefData<'tcx, 'tcx>;
pub type FieldDefMaster<'tcx> = &'tcx FieldDefData<'tcx, 'tcx>;

pub struct VariantDefData<'tcx, 'container: 'tcx> {
1440 1441
    /// The variant's DefId. If this is a tuple-like struct,
    /// this is the DefId of the struct's ctor.
1442 1443 1444
    pub did: DefId,
    pub name: Name, // struct's name if this is a struct
    pub disr_val: Disr,
1445
    pub fields: Vec<FieldDefData<'tcx, 'container>>,
1446
    pub kind: VariantKind,
1447 1448
}

A
Ariel Ben-Yehuda 已提交
1449
pub struct FieldDefData<'tcx, 'container: 'tcx> {
A
Ariel Ben-Yehuda 已提交
1450 1451
    /// The field's DefId. NOTE: the fields of tuple-like enum variants
    /// are not real items, and don't have entries in tcache etc.
1452
    pub did: DefId,
1453
    pub name: Name,
1454
    pub vis: Visibility,
A
Ariel Ben-Yehuda 已提交
1455
    /// TyIVar is used here to allow for variance (see the doc at
A
Ariel Ben-Yehuda 已提交
1456
    /// AdtDefData).
1457 1458
    ///
    /// Note: direct accesses to `ty` must also add dep edges.
1459
    ty: ivar::TyIVar<'tcx, 'container>
1460 1461
}

A
Ariel Ben-Yehuda 已提交
1462 1463 1464 1465 1466 1467 1468 1469 1470
/// The definition of an abstract data type - a struct or enum.
///
/// These are all interned (by intern_adt_def) into the adt_defs
/// table.
///
/// Because of the possibility of nested tcx-s, this type
/// needs 2 lifetimes: the traditional variant lifetime ('tcx)
/// bounding the lifetime of the inner types is of course necessary.
/// However, it is not sufficient - types from a child tcx must
A
Ariel Ben-Yehuda 已提交
1471
/// not be leaked into the master tcx by being stored in an AdtDefData.
A
Ariel Ben-Yehuda 已提交
1472 1473 1474 1475
///
/// The 'container lifetime ensures that by outliving the container
/// tcx and preventing shorter-lived types from being inserted. When
/// write access is not needed, the 'container lifetime can be
A
Ariel Ben-Yehuda 已提交
1476 1477
/// erased to 'static, which can be done by the AdtDef wrapper.
pub struct AdtDefData<'tcx, 'container: 'tcx> {
1478
    pub did: DefId,
A
Ariel Ben-Yehuda 已提交
1479
    pub variants: Vec<VariantDefData<'tcx, 'container>>,
1480
    destructor: Cell<Option<DefId>>,
A
Ariel Ben-Yehuda 已提交
1481
    flags: Cell<AdtFlags>,
1482
    sized_constraint: ivar::TyIVar<'tcx, 'container>,
1483 1484
}

A
Ariel Ben-Yehuda 已提交
1485 1486
impl<'tcx, 'container> PartialEq for AdtDefData<'tcx, 'container> {
    // AdtDefData are always interned and this is part of TyS equality
1487 1488 1489 1490
    #[inline]
    fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
}

A
Ariel Ben-Yehuda 已提交
1491
impl<'tcx, 'container> Eq for AdtDefData<'tcx, 'container> {}
1492

A
Ariel Ben-Yehuda 已提交
1493
impl<'tcx, 'container> Hash for AdtDefData<'tcx, 'container> {
1494 1495
    #[inline]
    fn hash<H: Hasher>(&self, s: &mut H) {
A
Ariel Ben-Yehuda 已提交
1496
        (self as *const AdtDefData).hash(s)
1497 1498 1499
    }
}

1500 1501 1502 1503 1504 1505 1506 1507
impl<'tcx> Encodable for AdtDef<'tcx> {
    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        self.did.encode(s)
    }
}

impl<'tcx> Decodable for AdtDef<'tcx> {
    fn decode<D: Decoder>(d: &mut D) -> Result<AdtDef<'tcx>, D::Error> {
J
Jorge Aparicio 已提交
1508
        let def_id: DefId = Decodable::decode(d)?;
1509 1510 1511 1512 1513 1514 1515 1516

        cstore::tls::with_decoding_context(d, |dcx, _| {
            let def_id = dcx.translate_def_id(def_id);
            Ok(dcx.tcx().lookup_adt_def(def_id))
        })
    }
}

1517 1518

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1519
pub enum AdtKind { Struct, Union, Enum }
1520

1521
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1522
pub enum VariantKind { Struct, Tuple, Unit }
1523

1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
impl VariantKind {
    pub fn from_variant_data(vdata: &hir::VariantData) -> Self {
        match *vdata {
            hir::VariantData::Struct(..) => VariantKind::Struct,
            hir::VariantData::Tuple(..) => VariantKind::Tuple,
            hir::VariantData::Unit(..) => VariantKind::Unit,
        }
    }
}

1534 1535
impl<'a, 'gcx, 'tcx, 'container> AdtDefData<'gcx, 'container> {
    fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1536
           did: DefId,
A
Ariel Ben-Yehuda 已提交
1537
           kind: AdtKind,
1538
           variants: Vec<VariantDefData<'gcx, 'container>>) -> Self {
A
Ariel Ben-Yehuda 已提交
1539
        let mut flags = AdtFlags::NO_ADT_FLAGS;
A
Ariel Ben-Yehuda 已提交
1540
        let attrs = tcx.get_attrs(did);
1541
        if attr::contains_name(&attrs, "fundamental") {
A
Ariel Ben-Yehuda 已提交
1542
            flags = flags | AdtFlags::IS_FUNDAMENTAL;
1543
        }
1544
        if tcx.lookup_simd(did) {
A
Ariel Ben-Yehuda 已提交
1545
            flags = flags | AdtFlags::IS_SIMD;
A
Ariel Ben-Yehuda 已提交
1546
        }
1547
        if Some(did) == tcx.lang_items.phantom_data() {
A
Ariel Ben-Yehuda 已提交
1548
            flags = flags | AdtFlags::IS_PHANTOM_DATA;
1549
        }
1550 1551 1552 1553
        match kind {
            AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
            AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
            AdtKind::Struct => {}
1554
        }
A
Ariel Ben-Yehuda 已提交
1555
        AdtDefData {
1556
            did: did,
1557
            variants: variants,
1558
            flags: Cell::new(flags),
1559 1560
            destructor: Cell::new(None),
            sized_constraint: ivar::TyIVar::new(),
1561 1562 1563
        }
    }

1564
    fn calculate_dtorck(&'gcx self, tcx: TyCtxt) {
1565
        if tcx.is_adt_dtorck(self) {
A
Ariel Ben-Yehuda 已提交
1566
            self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK);
1567
        }
A
Ariel Ben-Yehuda 已提交
1568
        self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK_VALID)
1569 1570
    }

A
Ariel Ben-Yehuda 已提交
1571
    /// Returns the kind of the ADT - Struct or Enum.
1572
    #[inline]
A
Ariel Ben-Yehuda 已提交
1573 1574 1575
    pub fn adt_kind(&self) -> AdtKind {
        if self.flags.get().intersects(AdtFlags::IS_ENUM) {
            AdtKind::Enum
1576 1577
        } else if self.flags.get().intersects(AdtFlags::IS_UNION) {
            AdtKind::Union
1578
        } else {
A
Ariel Ben-Yehuda 已提交
1579
            AdtKind::Struct
1580 1581 1582
        }
    }

A
Ariel Ben-Yehuda 已提交
1583 1584 1585
    /// Returns whether this is a dtorck type. If this returns
    /// true, this type being safe for destruction requires it to be
    /// alive; Otherwise, only the contents are required to be.
1586
    #[inline]
1587
    pub fn is_dtorck(&'gcx self, tcx: TyCtxt) -> bool {
A
Ariel Ben-Yehuda 已提交
1588
        if !self.flags.get().intersects(AdtFlags::IS_DTORCK_VALID) {
1589 1590
            self.calculate_dtorck(tcx)
        }
A
Ariel Ben-Yehuda 已提交
1591
        self.flags.get().intersects(AdtFlags::IS_DTORCK)
1592 1593
    }

A
Ariel Ben-Yehuda 已提交
1594 1595
    /// Returns whether this type is #[fundamental] for the purposes
    /// of coherence checking.
1596 1597
    #[inline]
    pub fn is_fundamental(&self) -> bool {
A
Ariel Ben-Yehuda 已提交
1598
        self.flags.get().intersects(AdtFlags::IS_FUNDAMENTAL)
1599 1600
    }

A
Ariel Ben-Yehuda 已提交
1601 1602
    #[inline]
    pub fn is_simd(&self) -> bool {
A
Ariel Ben-Yehuda 已提交
1603
        self.flags.get().intersects(AdtFlags::IS_SIMD)
A
Ariel Ben-Yehuda 已提交
1604 1605
    }

A
Ariel Ben-Yehuda 已提交
1606
    /// Returns true if this is PhantomData<T>.
1607 1608
    #[inline]
    pub fn is_phantom_data(&self) -> bool {
A
Ariel Ben-Yehuda 已提交
1609
        self.flags.get().intersects(AdtFlags::IS_PHANTOM_DATA)
1610 1611
    }

A
Ariel Ben-Yehuda 已提交
1612
    /// Returns whether this type has a destructor.
1613
    pub fn has_dtor(&self) -> bool {
1614
        self.dtor_kind().is_present()
1615 1616
    }

A
Ariel Ben-Yehuda 已提交
1617 1618
    /// Asserts this is a struct and returns the struct's unique
    /// variant.
1619
    pub fn struct_variant(&self) -> &VariantDefData<'gcx, 'container> {
1620 1621
        let adt_kind = self.adt_kind();
        assert!(adt_kind == AdtKind::Struct || adt_kind == AdtKind::Union);
1622
        &self.variants[0]
1623 1624 1625
    }

    #[inline]
1626
    pub fn type_scheme(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeScheme<'gcx> {
1627 1628 1629 1630
        tcx.lookup_item_type(self.did)
    }

    #[inline]
1631
    pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1632 1633
        tcx.lookup_predicates(self.did)
    }
1634

A
Ariel Ben-Yehuda 已提交
1635 1636
    /// Returns an iterator over all fields contained
    /// by this ADT.
1637 1638 1639
    #[inline]
    pub fn all_fields(&self) ->
            iter::FlatMap<
1640 1641 1642 1643
                slice::Iter<VariantDefData<'gcx, 'container>>,
                slice::Iter<FieldDefData<'gcx, 'container>>,
                for<'s> fn(&'s VariantDefData<'gcx, 'container>)
                    -> slice::Iter<'s, FieldDefData<'gcx, 'container>>
1644
            > {
A
Ariel Ben-Yehuda 已提交
1645
        self.variants.iter().flat_map(VariantDefData::fields_iter)
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.variants.is_empty()
    }

    #[inline]
    pub fn is_univariant(&self) -> bool {
        self.variants.len() == 1
    }

    pub fn is_payloadfree(&self) -> bool {
        !self.variants.is_empty() &&
            self.variants.iter().all(|v| v.fields.is_empty())
    }

1663
    pub fn variant_with_id(&self, vid: DefId) -> &VariantDefData<'gcx, 'container> {
1664 1665 1666 1667 1668 1669
        self.variants
            .iter()
            .find(|v| v.did == vid)
            .expect("variant_with_id: unknown variant")
    }

N
Niko Matsakis 已提交
1670 1671 1672 1673 1674 1675 1676
    pub fn variant_index_with_id(&self, vid: DefId) -> usize {
        self.variants
            .iter()
            .position(|v| v.did == vid)
            .expect("variant_index_with_id: unknown variant")
    }

1677
    pub fn variant_of_def(&self, def: Def) -> &VariantDefData<'gcx, 'container> {
1678
        match def {
1679
            Def::Variant(_, vid) => self.variant_with_id(vid),
1680 1681
            Def::Struct(..) | Def::Union(..) |
            Def::TyAlias(..) | Def::AssociatedTy(..) => self.struct_variant(),
1682
            _ => bug!("unexpected def {:?} in variant_of_def", def)
1683 1684
        }
    }
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695

    pub fn destructor(&self) -> Option<DefId> {
        self.destructor.get()
    }

    pub fn set_destructor(&self, dtor: DefId) {
        self.destructor.set(Some(dtor));
    }

    pub fn dtor_kind(&self) -> DtorKind {
        match self.destructor.get() {
1696
            Some(_) => TraitDtor,
1697 1698 1699
            None => NoDtor,
        }
    }
1700
}
1701

1702
impl<'a, 'gcx, 'tcx, 'container> AdtDefData<'tcx, 'container> {
1703 1704
    /// Returns a simpler type such that `Self: Sized` if and only
    /// if that type is Sized, or `TyErr` if this type is recursive.
A
Ariel Ben-Yehuda 已提交
1705
    ///
1706 1707 1708 1709
    /// HACK: instead of returning a list of types, this function can
    /// return a tuple. In that case, the result is Sized only if
    /// all elements of the tuple are Sized.
    ///
A
Ariel Ben-Yehuda 已提交
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
    /// This is generally the `struct_tail` if this is a struct, or a
    /// tuple of them if this is an enum.
    ///
    /// Oddly enough, checking that the sized-constraint is Sized is
    /// actually more expressive than checking all members:
    /// the Sized trait is inductive, so an associated type that references
    /// Self would prevent its containing ADT from being Sized.
    ///
    /// Due to normalization being eager, this applies even if
    /// the associated type is behind a pointer, e.g. issue #31299.
1720
    pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1721
        match self.sized_constraint.get(DepNode::SizedConstraint(self.did)) {
1722
            None => {
1723 1724 1725
                let global_tcx = tcx.global_tcx();
                let this = global_tcx.lookup_adt_def_master(self.did);
                this.calculate_sized_constraint_inner(global_tcx, &mut Vec::new());
1726
                self.sized_constraint(tcx)
1727 1728 1729 1730 1731 1732
            }
            Some(ty) => ty
        }
    }
}

1733
impl<'a, 'tcx> AdtDefData<'tcx, 'tcx> {
A
Ariel Ben-Yehuda 已提交
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
    /// Calculates the Sized-constraint.
    ///
    /// As the Sized-constraint of enums can be a *set* of types,
    /// the Sized-constraint may need to be a set also. Because introducing
    /// a new type of IVar is currently a complex affair, the Sized-constraint
    /// may be a tuple.
    ///
    /// In fact, there are only a few options for the constraint:
    ///     - `bool`, if the type is always Sized
    ///     - an obviously-unsized type
    ///     - a type parameter or projection whose Sizedness can't be known
    ///     - a tuple of type parameters or projections, if there are multiple
    ///       such.
    ///     - a TyError, if a type contained itself. The representability
    ///       check should catch this case.
1749 1750
    fn calculate_sized_constraint_inner(&'tcx self,
                                        tcx: TyCtxt<'a, 'tcx, 'tcx>,
A
Ariel Ben-Yehuda 已提交
1751
                                        stack: &mut Vec<AdtDefMaster<'tcx>>)
1752
    {
1753
        let dep_node = || DepNode::SizedConstraint(self.did);
1754 1755 1756 1757 1758 1759 1760

        // Follow the memoization pattern: push the computation of
        // DepNode::SizedConstraint as our current task.
        let _task = tcx.dep_graph.in_task(dep_node());
        if self.sized_constraint.untracked_get().is_some() {
            //                   ---------------
            // can skip the dep-graph read since we just pushed the task
A
Ariel Ben-Yehuda 已提交
1761 1762 1763 1764 1765 1766 1767 1768 1769
            return;
        }

        if stack.contains(&self) {
            debug!("calculate_sized_constraint: {:?} is recursive", self);
            // This should be reported as an error by `check_representable`.
            //
            // Consider the type as Sized in the meanwhile to avoid
            // further errors.
1770
            self.sized_constraint.fulfill(dep_node(), tcx.types.err);
A
Ariel Ben-Yehuda 已提交
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
            return;
        }

        stack.push(self);

        let tys : Vec<_> =
            self.variants.iter().flat_map(|v| {
                v.fields.last()
            }).flat_map(|f| {
                self.sized_constraint_for_ty(tcx, stack, f.unsubst_ty())
            }).collect();

        let self_ = stack.pop().unwrap();
        assert_eq!(self_, self);

        let ty = match tys.len() {
A
Ariel Ben-Yehuda 已提交
1787
            _ if tys.references_error() => tcx.types.err,
1788 1789 1790
            0 => tcx.types.bool,
            1 => tys[0],
            _ => tcx.mk_tup(tys)
A
Ariel Ben-Yehuda 已提交
1791 1792
        };

1793
        match self.sized_constraint.get(dep_node()) {
A
Ariel Ben-Yehuda 已提交
1794 1795 1796 1797 1798 1799
            Some(old_ty) => {
                debug!("calculate_sized_constraint: {:?} recurred", self);
                assert_eq!(old_ty, tcx.types.err)
            }
            None => {
                debug!("calculate_sized_constraint: {:?} => {:?}", self, ty);
1800
                self.sized_constraint.fulfill(dep_node(), ty)
A
Ariel Ben-Yehuda 已提交
1801
            }
1802 1803
        }
    }
1804

1805 1806
    fn sized_constraint_for_ty(
        &'tcx self,
1807
        tcx: TyCtxt<'a, 'tcx, 'tcx>,
1808 1809
        stack: &mut Vec<AdtDefMaster<'tcx>>,
        ty: Ty<'tcx>
A
Ariel Ben-Yehuda 已提交
1810
    ) -> Vec<Ty<'tcx>> {
1811 1812 1813
        let result = match ty.sty {
            TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
            TyBox(..) | TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
A
Andrew Cann 已提交
1814
            TyArray(..) | TyClosure(..) | TyNever => {
A
Ariel Ben-Yehuda 已提交
1815
                vec![]
1816 1817
            }

A
Ariel Ben-Yehuda 已提交
1818
            TyStr | TyTrait(..) | TySlice(_) | TyError => {
1819
                // these are never sized - return the target type
A
Ariel Ben-Yehuda 已提交
1820
                vec![ty]
1821 1822 1823
            }

            TyTuple(ref tys) => {
1824 1825 1826 1827
                match tys.last() {
                    None => vec![],
                    Some(ty) => self.sized_constraint_for_ty(tcx, stack, ty)
                }
1828 1829
            }

V
Vadim Petrochenkov 已提交
1830
            TyEnum(adt, substs) | TyStruct(adt, substs) | TyUnion(adt, substs) => {
1831 1832 1833 1834 1835 1836 1837 1838 1839
                // recursive case
                let adt = tcx.lookup_adt_def_master(adt.did);
                adt.calculate_sized_constraint_inner(tcx, stack);
                let adt_ty =
                    adt.sized_constraint
                    .unwrap(DepNode::SizedConstraint(adt.did))
                    .subst(tcx, substs);
                debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
                       ty, adt_ty);
A
Ariel Ben-Yehuda 已提交
1840 1841 1842 1843 1844 1845 1846
                if let ty::TyTuple(ref tys) = adt_ty.sty {
                    tys.iter().flat_map(|ty| {
                        self.sized_constraint_for_ty(tcx, stack, ty)
                    }).collect()
                } else {
                    self.sized_constraint_for_ty(tcx, stack, adt_ty)
                }
1847 1848
            }

1849
            TyProjection(..) | TyAnon(..) => {
1850 1851
                // must calculate explicitly.
                // FIXME: consider special-casing always-Sized projections
A
Ariel Ben-Yehuda 已提交
1852
                vec![ty]
1853 1854 1855
            }

            TyParam(..) => {
A
Ariel Ben-Yehuda 已提交
1856 1857 1858 1859
                // perf hack: if there is a `T: Sized` bound, then
                // we know that `T` is Sized and do not need to check
                // it on the impl.

1860 1861
                let sized_trait = match tcx.lang_items.sized_trait() {
                    Some(x) => x,
A
Ariel Ben-Yehuda 已提交
1862
                    _ => return vec![ty]
1863 1864 1865
                };
                let sized_predicate = Binder(TraitRef {
                    def_id: sized_trait,
1866
                    substs: Substs::new_trait(tcx, ty, &[])
1867 1868 1869
                }).to_predicate();
                let predicates = tcx.lookup_predicates(self.did).predicates;
                if predicates.into_iter().any(|p| p == sized_predicate) {
A
Ariel Ben-Yehuda 已提交
1870
                    vec![]
1871
                } else {
A
Ariel Ben-Yehuda 已提交
1872
                    vec![ty]
1873 1874 1875
                }
            }

A
Ariel Ben-Yehuda 已提交
1876
            TyInfer(..) => {
1877 1878 1879 1880 1881 1882 1883
                bug!("unexpected type `{:?}` in sized_constraint_for_ty",
                     ty)
            }
        };
        debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
        result
    }
1884 1885
}

A
Ariel Ben-Yehuda 已提交
1886
impl<'tcx, 'container> VariantDefData<'tcx, 'container> {
1887
    #[inline]
A
Ariel Ben-Yehuda 已提交
1888
    fn fields_iter(&self) -> slice::Iter<FieldDefData<'tcx, 'container>> {
1889 1890 1891 1892
        self.fields.iter()
    }

    #[inline]
A
Ariel Ben-Yehuda 已提交
1893 1894 1895
    pub fn find_field_named(&self,
                            name: ast::Name)
                            -> Option<&FieldDefData<'tcx, 'container>> {
1896 1897 1898
        self.fields.iter().find(|f| f.name == name)
    }

1899 1900 1901 1902 1903 1904 1905
    #[inline]
    pub fn index_of_field_named(&self,
                                name: ast::Name)
                                -> Option<usize> {
        self.fields.iter().position(|f| f.name == name)
    }

1906
    #[inline]
A
Ariel Ben-Yehuda 已提交
1907
    pub fn field_named(&self, name: ast::Name) -> &FieldDefData<'tcx, 'container> {
1908 1909 1910 1911
        self.find_field_named(name).unwrap()
    }
}

1912
impl<'a, 'gcx, 'tcx, 'container> FieldDefData<'tcx, 'container> {
1913 1914
    pub fn new(did: DefId,
               name: Name,
1915
               vis: Visibility) -> Self {
A
Ariel Ben-Yehuda 已提交
1916
        FieldDefData {
1917 1918 1919
            did: did,
            name: name,
            vis: vis,
1920
            ty: ivar::TyIVar::new()
1921 1922 1923
        }
    }

1924
    pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1925 1926 1927 1928
        self.unsubst_ty().subst(tcx, subst)
    }

    pub fn unsubst_ty(&self) -> Ty<'tcx> {
1929
        self.ty.unwrap(DepNode::FieldTy(self.did))
1930 1931
    }

A
Ariel Ben-Yehuda 已提交
1932
    pub fn fulfill_ty(&self, ty: Ty<'container>) {
1933
        self.ty.fulfill(DepNode::FieldTy(self.did), ty);
1934
    }
1935 1936
}

1937 1938
/// Records the substitutions used to translate the polytype for an
/// item into the monotype of an item reference.
1939
#[derive(Clone)]
1940
pub struct ItemSubsts<'tcx> {
1941
    pub substs: &'tcx Substs<'tcx>,
1942 1943
}

1944
#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1945
pub enum ClosureKind {
1946 1947 1948
    // Warning: Ordering is significant here! The ordering is chosen
    // because the trait Fn is a subtrait of FnMut and so in turn, and
    // hence we order it so that Fn < FnMut < FnOnce.
1949 1950 1951
    Fn,
    FnMut,
    FnOnce,
1952 1953
}

1954 1955
impl<'a, 'tcx> ClosureKind {
    pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
1956
        let result = match *self {
1957
            ClosureKind::Fn => tcx.lang_items.require(FnTraitLangItem),
1958
            ClosureKind::FnMut => {
1959
                tcx.lang_items.require(FnMutTraitLangItem)
1960
            }
1961
            ClosureKind::FnOnce => {
1962
                tcx.lang_items.require(FnOnceTraitLangItem)
1963 1964 1965 1966
            }
        };
        match result {
            Ok(trait_did) => trait_did,
1967
            Err(err) => tcx.sess.fatal(&err[..]),
1968 1969
        }
    }
1970 1971 1972 1973 1974

    /// True if this a type that impls this closure kind
    /// must also implement `other`.
    pub fn extends(self, other: ty::ClosureKind) -> bool {
        match (self, other) {
1975 1976 1977 1978 1979 1980
            (ClosureKind::Fn, ClosureKind::Fn) => true,
            (ClosureKind::Fn, ClosureKind::FnMut) => true,
            (ClosureKind::Fn, ClosureKind::FnOnce) => true,
            (ClosureKind::FnMut, ClosureKind::FnMut) => true,
            (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
            (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
1981 1982 1983
            _ => false,
        }
    }
1984 1985
}

1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
impl<'tcx> TyS<'tcx> {
    /// Iterator that walks `self` and any types reachable from
    /// `self`, in depth-first order. Note that just walks the types
    /// that appear in `self`, it does not descend into the fields of
    /// structs or variants. For example:
    ///
    /// ```notrust
    /// isize => { isize }
    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
    /// [isize] => { [isize], isize }
    /// ```
    pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
        TypeWalker::new(self)
1999 2000
    }

2001 2002 2003 2004 2005
    /// Iterator that walks the immediate children of `self`.  Hence
    /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
    /// (but not `i32`, like `walk`).
    pub fn walk_shallow(&'tcx self) -> IntoIter<Ty<'tcx>> {
        walk::walk_shallow(self)
2006 2007
    }

2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
    /// Walks `ty` and any types appearing within `ty`, invoking the
    /// callback `f` on each type. If the callback returns false, then the
    /// children of the current type are ignored.
    ///
    /// Note: prefer `ty.walk()` where possible.
    pub fn maybe_walk<F>(&'tcx self, mut f: F)
        where F : FnMut(Ty<'tcx>) -> bool
    {
        let mut walker = self.walk();
        while let Some(ty) = walker.next() {
            if !f(ty) {
                walker.skip_current_subtree();
            }
        }
2022
    }
2023
}
2024

2025 2026 2027
impl<'tcx> ItemSubsts<'tcx> {
    pub fn is_noop(&self) -> bool {
        self.substs.is_noop()
A
Alex Crichton 已提交
2028
    }
2029
}
2030

2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum LvaluePreference {
    PreferMutLvalue,
    NoPreference
}

impl LvaluePreference {
    pub fn from_mutbl(m: hir::Mutability) -> Self {
        match m {
            hir::MutMutable => PreferMutLvalue,
            hir::MutImmutable => NoPreference,
        }
    }
}

2046
/// Helper for looking things up in the various maps that are populated during
2047
/// typeck::collect (e.g., `tcx.impl_or_trait_items`, `tcx.tcache`, etc).  All of
2048 2049 2050
/// these share the pattern that if the id is local, it should have been loaded
/// into the map by the `typeck::collect` phase.  If the def-id is external,
/// then we have to go consult the crate loading code (and cache the result for
S
Steve Klabnik 已提交
2051
/// the future).
2052
fn lookup_locally_or_in_crate_store<M, F>(descr: &str,
N
Niko Matsakis 已提交
2053
                                          def_id: DefId,
2054 2055 2056 2057 2058
                                          map: &M,
                                          load_external: F)
                                          -> M::Value where
    M: MemoizationMap<Key=DefId>,
    F: FnOnce() -> M::Value,
J
Jorge Aparicio 已提交
2059
{
2060 2061
    map.memoize(def_id, || {
        if def_id.is_local() {
2062
            bug!("No def'n found for {:?} in tcx.{}", def_id, descr);
2063 2064 2065
        }
        load_external()
    })
2066 2067
}

2068
impl BorrowKind {
2069
    pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2070
        match m {
2071 2072
            hir::MutMutable => MutBorrow,
            hir::MutImmutable => ImmBorrow,
2073 2074
        }
    }
2075

2076 2077 2078 2079
    /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
    /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
    /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
    /// question.
2080
    pub fn to_mutbl_lossy(self) -> hir::Mutability {
2081
        match self {
2082 2083
            MutBorrow => hir::MutMutable,
            ImmBorrow => hir::MutImmutable,
2084 2085 2086 2087

            // We have no type corresponding to a unique imm borrow, so
            // use `&mut`. It gives all the capabilities of an `&uniq`
            // and hence is a safe "over approximation".
2088
            UniqueImmBorrow => hir::MutMutable,
2089
        }
2090
    }
2091

2092 2093 2094 2095 2096 2097
    pub fn to_user_str(&self) -> &'static str {
        match *self {
            MutBorrow => "mutable",
            ImmBorrow => "immutable",
            UniqueImmBorrow => "uniquely immutable",
        }
2098 2099 2100
    }
}

2101 2102
impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
    pub fn node_id_to_type(self, id: NodeId) -> Ty<'gcx> {
2103 2104
        match self.node_id_to_type_opt(id) {
           Some(ty) => ty,
2105 2106
           None => bug!("node_id_to_type: no type for node `{}`",
                        self.map.node_to_string(id))
2107 2108
        }
    }
2109

2110
    pub fn node_id_to_type_opt(self, id: NodeId) -> Option<Ty<'gcx>> {
2111
        self.tables.borrow().node_types.get(&id).cloned()
2112
    }
2113

2114
    pub fn node_id_item_substs(self, id: NodeId) -> ItemSubsts<'gcx> {
2115
        match self.tables.borrow().item_substs.get(&id) {
2116
            None => ItemSubsts {
2117
                substs: Substs::empty(self.global_tcx())
2118
            },
2119 2120 2121
            Some(ts) => ts.clone(),
        }
    }
2122

2123 2124
    // Returns the type of a pattern as a monotype. Like @expr_ty, this function
    // doesn't provide type parameter substitutions.
2125
    pub fn pat_ty(self, pat: &hir::Pat) -> Ty<'gcx> {
2126 2127
        self.node_id_to_type(pat.id)
    }
2128
    pub fn pat_ty_opt(self, pat: &hir::Pat) -> Option<Ty<'gcx>> {
2129 2130
        self.node_id_to_type_opt(pat.id)
    }
2131

2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
    // Returns the type of an expression as a monotype.
    //
    // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression.  That is, in
    // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
    // auto-ref.  The type returned by this function does not consider such
    // adjustments.  See `expr_ty_adjusted()` instead.
    //
    // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
    // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
    // instead of "fn(ty) -> T with T = isize".
2142
    pub fn expr_ty(self, expr: &hir::Expr) -> Ty<'gcx> {
2143
        self.node_id_to_type(expr.id)
2144
    }
2145

2146
    pub fn expr_ty_opt(self, expr: &hir::Expr) -> Option<Ty<'gcx>> {
2147
        self.node_id_to_type_opt(expr.id)
2148
    }
2149

2150 2151 2152 2153 2154 2155 2156 2157 2158
    /// Returns the type of `expr`, considering any `AutoAdjustment`
    /// entry recorded for that expression.
    ///
    /// It would almost certainly be better to store the adjusted ty in with
    /// the `AutoAdjustment`, but I opted not to do this because it would
    /// require serializing and deserializing the type and, although that's not
    /// hard to do, I just hate that code so much I didn't want to touch it
    /// unless it was to fix it properly, which seemed a distraction from the
    /// thread at hand! -nmatsakis
2159
    pub fn expr_ty_adjusted(self, expr: &hir::Expr) -> Ty<'gcx> {
2160
        self.expr_ty(expr)
2161
            .adjust(self.global_tcx(), expr.span, expr.id,
2162
                    self.tables.borrow().adjustments.get(&expr.id),
2163
                    |method_call| {
2164
            self.tables.borrow().method_map.get(&method_call).map(|method| method.ty)
2165 2166
        })
    }
2167

2168 2169
    pub fn expr_ty_adjusted_opt(self, expr: &hir::Expr) -> Option<Ty<'gcx>> {
        self.expr_ty_opt(expr).map(|t| t.adjust(self.global_tcx(),
2170 2171 2172 2173 2174 2175 2176 2177
                                                expr.span,
                                                expr.id,
                                                self.tables.borrow().adjustments.get(&expr.id),
                                                |method_call| {
            self.tables.borrow().method_map.get(&method_call).map(|method| method.ty)
        }))
    }

2178
    pub fn expr_span(self, id: NodeId) -> Span {
2179 2180 2181 2182 2183
        match self.map.find(id) {
            Some(ast_map::NodeExpr(e)) => {
                e.span
            }
            Some(f) => {
2184
                bug!("Node id {} is not an expr: {:?}", id, f);
2185 2186
            }
            None => {
2187
                bug!("Node id {} is not present in the node map", id);
2188
            }
2189
        }
2190 2191
    }

2192
    pub fn local_var_name_str(self, id: NodeId) -> InternedString {
2193 2194 2195
        match self.map.find(id) {
            Some(ast_map::NodeLocal(pat)) => {
                match pat.node {
2196
                    PatKind::Binding(_, ref path1, _) => path1.node.as_str(),
2197
                    _ => {
2198
                        bug!("Variable id {} maps to {:?}, not local", id, pat);
2199
                    },
2200
                }
2201
            },
2202
            r => bug!("Variable id {} maps to {:?}, not local", id, r),
2203
        }
2204 2205
    }

2206
    pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
2207
         match expr.node {
2208
            hir::ExprPath(..) => {
2209 2210 2211 2212 2213 2214
                // This function can be used during type checking when not all paths are
                // fully resolved. Partially resolved paths in expressions can only legally
                // refer to associated items which are always rvalues.
                match self.expect_resolution(expr.id).base_def {
                    Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
                    _ => false,
2215 2216
                }
            }
2217

2218 2219 2220 2221
            hir::ExprType(ref e, _) => {
                self.expr_is_lval(e)
            }

2222 2223 2224 2225
            hir::ExprUnary(hir::UnDeref, _) |
            hir::ExprField(..) |
            hir::ExprTupField(..) |
            hir::ExprIndex(..) => {
2226 2227 2228
                true
            }

2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
            hir::ExprCall(..) |
            hir::ExprMethodCall(..) |
            hir::ExprStruct(..) |
            hir::ExprTup(..) |
            hir::ExprIf(..) |
            hir::ExprMatch(..) |
            hir::ExprClosure(..) |
            hir::ExprBlock(..) |
            hir::ExprRepeat(..) |
            hir::ExprVec(..) |
            hir::ExprBreak(..) |
            hir::ExprAgain(..) |
            hir::ExprRet(..) |
            hir::ExprWhile(..) |
            hir::ExprLoop(..) |
            hir::ExprAssign(..) |
            hir::ExprInlineAsm(..) |
            hir::ExprAssignOp(..) |
            hir::ExprLit(_) |
            hir::ExprUnary(..) |
2249 2250 2251 2252 2253
            hir::ExprBox(..) |
            hir::ExprAddrOf(..) |
            hir::ExprBinary(..) |
            hir::ExprCast(..) => {
                false
2254
            }
2255 2256 2257
        }
    }

2258
    pub fn provided_trait_methods(self, id: DefId) -> Vec<Rc<Method<'gcx>>> {
2259 2260
        if let Some(id) = self.map.as_local_node_id(id) {
            if let ItemTrait(_, _, _, ref ms) = self.map.expect_item(id).node {
2261
                ms.iter().filter_map(|ti| {
2262
                    if let hir::MethodTraitItem(_, Some(_)) = ti.node {
2263
                        match self.impl_or_trait_item(self.map.local_def_id(ti.id)) {
2264 2265
                            MethodTraitItem(m) => Some(m),
                            _ => {
2266 2267 2268
                                bug!("provided_trait_methods(): \
                                      non-method item found from \
                                      looking up provided method?!")
2269 2270 2271 2272 2273 2274 2275
                            }
                        }
                    } else {
                        None
                    }
                }).collect()
            } else {
2276
                bug!("provided_trait_methods: `{:?}` is not a trait", id)
2277 2278
            }
        } else {
2279
            self.sess.cstore.provided_trait_methods(self.global_tcx(), id)
2280 2281 2282
        }
    }

2283
    pub fn associated_consts(self, id: DefId) -> Vec<Rc<AssociatedConst<'gcx>>> {
2284 2285
        if let Some(id) = self.map.as_local_node_id(id) {
            match self.map.expect_item(id).node {
2286 2287
                ItemTrait(_, _, _, ref tis) => {
                    tis.iter().filter_map(|ti| {
2288
                        if let hir::ConstTraitItem(_, _) = ti.node {
2289
                            match self.impl_or_trait_item(self.map.local_def_id(ti.id)) {
2290 2291
                                ConstTraitItem(ac) => Some(ac),
                                _ => {
2292 2293 2294
                                    bug!("associated_consts(): \
                                          non-const item found from \
                                          looking up a constant?!")
2295 2296 2297 2298 2299 2300 2301 2302 2303
                                }
                            }
                        } else {
                            None
                        }
                    }).collect()
                }
                ItemImpl(_, _, _, _, _, ref iis) => {
                    iis.iter().filter_map(|ii| {
2304
                        if let hir::ImplItemKind::Const(_, _) = ii.node {
2305
                            match self.impl_or_trait_item(self.map.local_def_id(ii.id)) {
2306 2307
                                ConstTraitItem(ac) => Some(ac),
                                _ => {
2308 2309 2310
                                    bug!("associated_consts(): \
                                          non-const item found from \
                                          looking up a constant?!")
2311 2312 2313 2314 2315 2316 2317 2318
                                }
                            }
                        } else {
                            None
                        }
                    }).collect()
                }
                _ => {
2319
                    bug!("associated_consts: `{:?}` is not a trait or impl", id)
2320 2321 2322
                }
            }
        } else {
2323
            self.sess.cstore.associated_consts(self.global_tcx(), id)
2324 2325 2326
        }
    }

2327
    pub fn trait_impl_polarity(self, id: DefId) -> Option<hir::ImplPolarity> {
2328 2329
        if let Some(id) = self.map.as_local_node_id(id) {
            match self.map.find(id) {
2330 2331
                Some(ast_map::NodeItem(item)) => {
                    match item.node {
2332
                        hir::ItemImpl(_, polarity, _, _, _, _) => Some(polarity),
2333 2334 2335 2336 2337 2338
                        _ => None
                    }
                }
                _ => None
            }
        } else {
2339
            self.sess.cstore.impl_polarity(id)
2340
        }
2341
    }
2342

2343
    pub fn custom_coerce_unsized_kind(self, did: DefId) -> adjustment::CustomCoerceUnsized {
2344
        self.custom_coerce_unsized_kinds.memoize(did, || {
N
Niko Matsakis 已提交
2345
            let (kind, src) = if did.krate != LOCAL_CRATE {
2346
                (self.sess.cstore.custom_coerce_unsized_kind(did), "external")
2347 2348 2349
            } else {
                (None, "local")
            };
2350

2351 2352 2353
            match kind {
                Some(kind) => kind,
                None => {
2354 2355 2356
                    bug!("custom_coerce_unsized_kind: \
                          {} impl `{}` is missing its kind",
                          src, self.item_path_str(did));
2357 2358 2359 2360 2361
                }
            }
        })
    }

2362
    pub fn impl_or_trait_item(self, id: DefId) -> ImplOrTraitItem<'gcx> {
2363 2364
        lookup_locally_or_in_crate_store(
            "impl_or_trait_items", id, &self.impl_or_trait_items,
2365
            || self.sess.cstore.impl_or_trait_item(self.global_tcx(), id)
2366
                   .expect("missing ImplOrTraitItem in metadata"))
2367 2368
    }

2369
    pub fn trait_item_def_ids(self, id: DefId) -> Rc<Vec<ImplOrTraitItemId>> {
2370 2371
        lookup_locally_or_in_crate_store(
            "trait_item_def_ids", id, &self.trait_item_def_ids,
2372
            || Rc::new(self.sess.cstore.trait_item_def_ids(id)))
2373 2374 2375 2376
    }

    /// Returns the trait-ref corresponding to a given impl, or None if it is
    /// an inherent impl.
2377
    pub fn impl_trait_ref(self, id: DefId) -> Option<TraitRef<'gcx>> {
2378 2379
        lookup_locally_or_in_crate_store(
            "impl_trait_refs", id, &self.impl_trait_refs,
2380
            || self.sess.cstore.impl_trait_ref(self.global_tcx(), id))
2381 2382 2383
    }

    /// Returns whether this DefId refers to an impl
2384
    pub fn is_impl(self, id: DefId) -> bool {
2385
        if let Some(id) = self.map.as_local_node_id(id) {
2386
            if let Some(ast_map::NodeItem(
2387
                &hir::Item { node: hir::ItemImpl(..), .. })) = self.map.find(id) {
2388 2389 2390 2391 2392
                true
            } else {
                false
            }
        } else {
2393
            self.sess.cstore.is_impl(id)
2394 2395 2396
        }
    }

2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410
    /// Returns a path resolution for node id if it exists, panics otherwise.
    pub fn expect_resolution(self, id: NodeId) -> PathResolution {
        *self.def_map.borrow().get(&id).expect("no def-map entry for node id")
    }

    /// Returns a fully resolved definition for node id if it exists, panics otherwise.
    pub fn expect_def(self, id: NodeId) -> Def {
        self.expect_resolution(id).full_def()
    }

    /// Returns a fully resolved definition for node id if it exists, or none if no
    /// definition exists, panics on partial resolutions to catch errors.
    pub fn expect_def_or_none(self, id: NodeId) -> Option<Def> {
        self.def_map.borrow().get(&id).map(|resolution| resolution.full_def())
2411
    }
2412

2413 2414 2415 2416 2417 2418 2419
    // Returns `ty::VariantDef` if `def` refers to a struct,
    // or variant or their constructors, panics otherwise.
    pub fn expect_variant_def(self, def: Def) -> VariantDef<'tcx> {
        match def {
            Def::Variant(enum_did, did) => {
                self.lookup_adt_def(enum_did).variant_with_id(did)
            }
2420
            Def::Struct(did) | Def::Union(did) => {
2421 2422 2423 2424 2425 2426
                self.lookup_adt_def(did).struct_variant()
            }
            _ => bug!("expect_variant_def used with unexpected def {:?}", def)
        }
    }

2427
    pub fn def_key(self, id: DefId) -> ast_map::DefKey {
2428 2429 2430 2431 2432
        if id.is_local() {
            self.map.def_key(id)
        } else {
            self.sess.cstore.def_key(id)
        }
2433 2434
    }

2435 2436 2437
    /// Returns the `DefPath` of an item. Note that if `id` is not
    /// local to this crate -- or is inlined into this crate -- the
    /// result will be a non-local `DefPath`.
2438
    pub fn def_path(self, id: DefId) -> ast_map::DefPath {
2439 2440 2441
        if id.is_local() {
            self.map.def_path(id)
        } else {
2442
            self.sess.cstore.relative_def_path(id)
2443 2444 2445
        }
    }

2446
    pub fn item_name(self, id: DefId) -> ast::Name {
2447
        if let Some(id) = self.map.as_local_node_id(id) {
2448
            self.map.name(id)
2449
        } else {
2450
            self.sess.cstore.item_name(id)
2451 2452 2453
        }
    }

2454
    // Register a given item type
2455 2456 2457
    pub fn register_item_type(self, did: DefId, scheme: TypeScheme<'gcx>) {
        self.tcache.borrow_mut().insert(did, scheme.ty);
        self.generics.borrow_mut().insert(did, scheme.generics);
2458
    }
2459

2460 2461
    // If the given item is in an external crate, looks up its type and adds it to
    // the type cache. Returns the type parameters and type.
2462
    pub fn lookup_item_type(self, did: DefId) -> TypeScheme<'gcx> {
2463
        let ty = lookup_locally_or_in_crate_store(
2464
            "tcache", did, &self.tcache,
2465 2466 2467 2468 2469 2470
            || self.sess.cstore.item_type(self.global_tcx(), did));

        TypeScheme {
            ty: ty,
            generics: self.lookup_generics(did)
        }
2471
    }
T
Tim Chevalier 已提交
2472

A
Ariel Ben-Yehuda 已提交
2473
    pub fn opt_lookup_item_type(self, did: DefId) -> Option<TypeScheme<'gcx>> {
2474 2475
        if did.krate != LOCAL_CRATE {
            return Some(self.lookup_item_type(did));
A
Ariel Ben-Yehuda 已提交
2476 2477
        }

2478 2479 2480 2481 2482
        if let Some(ty) = self.tcache.borrow().get(&did).cloned() {
            Some(TypeScheme {
                ty: ty,
                generics: self.lookup_generics(did)
            })
A
Ariel Ben-Yehuda 已提交
2483
        } else {
2484
            None
A
Ariel Ben-Yehuda 已提交
2485 2486 2487
        }
    }

2488
    /// Given the did of a trait, returns its canonical trait ref.
2489
    pub fn lookup_trait_def(self, did: DefId) -> &'gcx TraitDef<'gcx> {
2490 2491
        lookup_locally_or_in_crate_store(
            "trait_defs", did, &self.trait_defs,
2492
            || self.alloc_trait_def(self.sess.cstore.trait_def(self.global_tcx(), did))
2493 2494
        )
    }
2495

A
Ariel Ben-Yehuda 已提交
2496 2497 2498
    /// Given the did of an ADT, return a master reference to its
    /// definition. Unless you are planning on fulfilling the ADT's fields,
    /// use lookup_adt_def instead.
2499
    pub fn lookup_adt_def_master(self, did: DefId) -> AdtDefMaster<'gcx> {
2500 2501
        lookup_locally_or_in_crate_store(
            "adt_defs", did, &self.adt_defs,
2502
            || self.sess.cstore.adt_def(self.global_tcx(), did)
2503 2504 2505
        )
    }

A
Ariel Ben-Yehuda 已提交
2506
    /// Given the did of an ADT, return a reference to its definition.
2507
    pub fn lookup_adt_def(self, did: DefId) -> AdtDef<'gcx> {
A
Ariel Ben-Yehuda 已提交
2508
        // when reverse-variance goes away, a transmute::<AdtDefMaster,AdtDef>
C
Carlos E. Garcia 已提交
2509
        // would be needed here.
A
Ariel Ben-Yehuda 已提交
2510 2511 2512
        self.lookup_adt_def_master(did)
    }

2513 2514 2515 2516 2517 2518 2519
    /// Given the did of an item, returns its generics.
    pub fn lookup_generics(self, did: DefId) -> &'gcx Generics<'gcx> {
        lookup_locally_or_in_crate_store(
            "generics", did, &self.generics,
            || self.sess.cstore.item_generics(self.global_tcx(), did))
    }

2520
    /// Given the did of an item, returns its full set of predicates.
2521
    pub fn lookup_predicates(self, did: DefId) -> GenericPredicates<'gcx> {
2522 2523
        lookup_locally_or_in_crate_store(
            "predicates", did, &self.predicates,
2524
            || self.sess.cstore.item_predicates(self.global_tcx(), did))
2525
    }
2526

2527
    /// Given the did of a trait, returns its superpredicates.
2528
    pub fn lookup_super_predicates(self, did: DefId) -> GenericPredicates<'gcx> {
2529 2530
        lookup_locally_or_in_crate_store(
            "super_predicates", did, &self.super_predicates,
2531
            || self.sess.cstore.item_super_predicates(self.global_tcx(), did))
2532
    }
2533

2534 2535 2536 2537 2538 2539
    /// If `type_needs_drop` returns true, then `ty` is definitely
    /// non-copy and *might* have a destructor attached; if it returns
    /// false, then `ty` definitely has no destructor (i.e. no drop glue).
    ///
    /// (Note that this implies that if `ty` has a destructor attached,
    /// then `type_needs_drop` will definitely return `true` for `ty`.)
2540
    pub fn type_needs_drop_given_env(self,
2541 2542
                                     ty: Ty<'gcx>,
                                     param_env: &ty::ParameterEnvironment<'gcx>) -> bool {
2543 2544 2545 2546
        // Issue #22536: We first query type_moves_by_default.  It sees a
        // normalized version of the type, and therefore will definitely
        // know whether the type implements Copy (and thus needs no
        // cleanup/drop/zeroing) ...
2547 2548
        let tcx = self.global_tcx();
        let implements_copy = !ty.moves_by_default(tcx, param_env, DUMMY_SP);
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562

        if implements_copy { return false; }

        // ... (issue #22536 continued) but as an optimization, still use
        // prior logic of asking if the `needs_drop` bit is set; we need
        // not zero non-Copy types if they have no destructor.

        // FIXME(#22815): Note that calling `ty::type_contents` is a
        // conservative heuristic; it may report that `needs_drop` is set
        // when actual type does not actually have a destructor associated
        // with it. But since `ty` absolutely did not have the `Copy`
        // bound attached (see above), it is sound to treat it as having a
        // destructor (e.g. zero its memory on move).

2563
        let contents = ty.type_contents(tcx);
2564
        debug!("type_needs_drop ty={:?} contents={:?}", ty, contents);
2565
        contents.needs_drop(tcx)
2566 2567
    }

2568
    /// Get the attributes of a definition.
2569
    pub fn get_attrs(self, did: DefId) -> Cow<'gcx, [ast::Attribute]> {
2570 2571
        if let Some(id) = self.map.as_local_node_id(did) {
            Cow::Borrowed(self.map.attrs(id))
2572
        } else {
2573
            Cow::Owned(self.sess.cstore.item_attrs(did))
2574
        }
2575 2576
    }

2577
    /// Determine whether an item is annotated with an attribute
2578
    pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2579 2580
        self.get_attrs(did).iter().any(|item| item.check_name(attr))
    }
2581

2582
    /// Determine whether an item is annotated with `#[repr(packed)]`
2583
    pub fn lookup_packed(self, did: DefId) -> bool {
2584 2585
        self.lookup_repr_hints(did).contains(&attr::ReprPacked)
    }
2586

2587
    /// Determine whether an item is annotated with `#[simd]`
2588
    pub fn lookup_simd(self, did: DefId) -> bool {
2589
        self.has_attr(did, "simd")
2590
            || self.lookup_repr_hints(did).contains(&attr::ReprSimd)
2591
    }
S
Seo Sanghyeon 已提交
2592

2593
    pub fn item_variances(self, item_id: DefId) -> Rc<Vec<ty::Variance>> {
2594 2595
        lookup_locally_or_in_crate_store(
            "item_variance_map", item_id, &self.item_variance_map,
2596
            || Rc::new(self.sess.cstore.item_variances(item_id)))
2597
    }
2598

2599
    pub fn trait_has_default_impl(self, trait_def_id: DefId) -> bool {
2600
        self.populate_implementations_for_trait_if_necessary(trait_def_id);
2601

2602 2603
        let def = self.lookup_trait_def(trait_def_id);
        def.flags.get().intersects(TraitFlags::HAS_DEFAULT_IMPL)
2604
    }
2605

2606
    /// Records a trait-to-implementation mapping.
2607
    pub fn record_trait_has_default_impl(self, trait_def_id: DefId) {
2608 2609
        let def = self.lookup_trait_def(trait_def_id);
        def.flags.set(def.flags.get() | TraitFlags::HAS_DEFAULT_IMPL)
2610 2611
    }

2612
    /// Load primitive inherent implementations if necessary
2613
    pub fn populate_implementations_for_primitive_if_necessary(self,
N
Niko Matsakis 已提交
2614
                                                               primitive_def_id: DefId) {
2615
        if primitive_def_id.is_local() {
2616 2617
            return
        }
2618

2619 2620 2621 2622
        // The primitive is not local, hence we are reading this out
        // of metadata.
        let _ignore = self.dep_graph.in_ignore();

2623 2624 2625
        if self.populated_external_primitive_impls.borrow().contains(&primitive_def_id) {
            return
        }
2626

2627 2628
        debug!("populate_implementations_for_primitive_if_necessary: searching for {:?}",
               primitive_def_id);
2629

2630
        let impl_items = self.sess.cstore.impl_items(primitive_def_id);
2631

2632 2633 2634
        // Store the implementation info.
        self.impl_items.borrow_mut().insert(primitive_def_id, impl_items);
        self.populated_external_primitive_impls.borrow_mut().insert(primitive_def_id);
2635 2636
    }

2637 2638
    /// Populates the type context with all the inherent implementations for
    /// the given type if necessary.
2639
    pub fn populate_inherent_implementations_for_type_if_necessary(self,
N
Niko Matsakis 已提交
2640
                                                                   type_id: DefId) {
2641
        if type_id.is_local() {
2642 2643 2644
            return
        }

2645 2646 2647 2648
        // The type is not local, hence we are reading this out of
        // metadata and don't need to track edges.
        let _ignore = self.dep_graph.in_ignore();

2649 2650 2651
        if self.populated_external_types.borrow().contains(&type_id) {
            return
        }
2652

2653 2654
        debug!("populate_inherent_implementations_for_type_if_necessary: searching for {:?}",
               type_id);
2655

2656 2657
        let inherent_impls = self.sess.cstore.inherent_implementations_for_type(type_id);
        for &impl_def_id in &inherent_impls {
2658
            // Store the implementation info.
2659
            let impl_items = self.sess.cstore.impl_items(impl_def_id);
2660
            self.impl_items.borrow_mut().insert(impl_def_id, impl_items);
2661
        }
2662

2663 2664
        self.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
        self.populated_external_types.borrow_mut().insert(type_id);
2665
    }
2666

2667 2668
    /// Populates the type context with all the implementations for the given
    /// trait if necessary.
2669
    pub fn populate_implementations_for_trait_if_necessary(self, trait_id: DefId) {
2670
        if trait_id.is_local() {
2671 2672
            return
        }
2673

2674 2675 2676 2677
        // The type is not local, hence we are reading this out of
        // metadata and don't need to track edges.
        let _ignore = self.dep_graph.in_ignore();

2678 2679 2680 2681
        let def = self.lookup_trait_def(trait_id);
        if def.flags.get().intersects(TraitFlags::IMPLS_VALID) {
            return;
        }
2682

2683
        debug!("populate_implementations_for_trait_if_necessary: searching for {:?}", def);
2684

2685
        if self.sess.cstore.is_defaulted_trait(trait_id) {
2686 2687 2688
            self.record_trait_has_default_impl(trait_id);
        }

2689 2690
        for impl_def_id in self.sess.cstore.implementations_of_trait(trait_id) {
            let impl_items = self.sess.cstore.impl_items(impl_def_id);
2691
            let trait_ref = self.impl_trait_ref(impl_def_id).unwrap();
2692

2693
            // Record the trait->implementation mapping.
2694 2695 2696 2697 2698
            if let Some(parent) = self.sess.cstore.impl_parent(impl_def_id) {
                def.record_remote_impl(self, impl_def_id, trait_ref, parent);
            } else {
                def.record_remote_impl(self, impl_def_id, trait_ref, trait_id);
            }
2699

2700 2701 2702 2703
            // For any methods that use a default implementation, add them to
            // the map. This is a bit unfortunate.
            for impl_item_def_id in &impl_items {
                let method_def_id = impl_item_def_id.def_id();
2704 2705 2706
                // load impl items eagerly for convenience
                // FIXME: we may want to load these lazily
                self.impl_or_trait_item(method_def_id);
2707 2708
            }

2709 2710
            // Store the implementation info.
            self.impl_items.borrow_mut().insert(impl_def_id, impl_items);
2711
        }
2712

2713 2714
        def.flags.set(def.flags.get() | TraitFlags::IMPLS_VALID);
    }
2715

2716
    pub fn closure_kind(self, def_id: DefId) -> ty::ClosureKind {
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
        // If this is a local def-id, it should be inserted into the
        // tables by typeck; else, it will be retreived from
        // the external crate metadata.
        if let Some(&kind) = self.tables.borrow().closure_kinds.get(&def_id) {
            return kind;
        }

        let kind = self.sess.cstore.closure_kind(def_id);
        self.tables.borrow_mut().closure_kinds.insert(def_id, kind);
        kind
2727 2728
    }

2729
    pub fn closure_type(self,
2730
                        def_id: DefId,
2731 2732
                        substs: ClosureSubsts<'tcx>)
                        -> ty::ClosureTy<'tcx>
2733
    {
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743
        // If this is a local def-id, it should be inserted into the
        // tables by typeck; else, it will be retreived from
        // the external crate metadata.
        if let Some(ty) = self.tables.borrow().closure_tys.get(&def_id) {
            return ty.subst(self, substs.func_substs);
        }

        let ty = self.sess.cstore.closure_ty(self.global_tcx(), def_id);
        self.tables.borrow_mut().closure_tys.insert(def_id, ty.clone());
        ty.subst(self, substs.func_substs)
2744 2745
    }

2746 2747
    /// Given the def_id of an impl, return the def_id of the trait it implements.
    /// If it implements no trait, return `None`.
2748
    pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2749
        self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2750
    }
2751 2752 2753

    /// If the given def ID describes a method belonging to an impl, return the
    /// ID of the impl that the method belongs to. Otherwise, return `None`.
2754
    pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2755
        if def_id.krate != LOCAL_CRATE {
2756 2757
            return self.sess.cstore.impl_or_trait_item(self.global_tcx(), def_id)
                       .and_then(|item| {
2758 2759 2760 2761 2762
                match item.container() {
                    TraitContainer(_) => None,
                    ImplContainer(def_id) => Some(def_id),
                }
            });
2763
        }
2764 2765 2766 2767 2768 2769
        match self.impl_or_trait_items.borrow().get(&def_id).cloned() {
            Some(trait_item) => {
                match trait_item.container() {
                    TraitContainer(_) => None,
                    ImplContainer(def_id) => Some(def_id),
                }
2770
            }
2771
            None => None
2772 2773 2774
        }
    }

2775 2776 2777
    /// If the given def ID describes an item belonging to a trait,
    /// return the ID of the trait that the trait item belongs to.
    /// Otherwise, return `None`.
2778
    pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
2779
        if def_id.krate != LOCAL_CRATE {
2780
            return self.sess.cstore.trait_of_item(def_id);
2781
        }
2782
        match self.impl_or_trait_items.borrow().get(&def_id) {
2783 2784 2785
            Some(impl_or_trait_item) => {
                match impl_or_trait_item.container() {
                    TraitContainer(def_id) => Some(def_id),
2786
                    ImplContainer(_) => None
2787
                }
A
Alex Crichton 已提交
2788
            }
2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
            None => None
        }
    }

    /// If the given def ID describes an item belonging to a trait, (either a
    /// default method or an implementation of a trait method), return the ID of
    /// the method inside trait definition (this means that if the given def ID
    /// is already that of the original trait method, then the return value is
    /// the same).
    /// Otherwise, return `None`.
2799
    pub fn trait_item_of_item(self, def_id: DefId) -> Option<ImplOrTraitItemId> {
2800
        let impl_or_trait_item = match self.impl_or_trait_items.borrow().get(&def_id) {
2801 2802
            Some(m) => m.clone(),
            None => return None,
2803
        };
2804 2805 2806 2807 2808 2809 2810 2811 2812
        match impl_or_trait_item.container() {
            TraitContainer(_) => Some(impl_or_trait_item.id()),
            ImplContainer(def_id) => {
                self.trait_id_of_impl(def_id).and_then(|trait_did| {
                    let name = impl_or_trait_item.name();
                    self.trait_items(trait_did).iter()
                        .find(|item| item.name() == name)
                        .map(|item| item.id())
                })
2813 2814 2815 2816 2817 2818
            }
        }
    }

    /// Construct a parameter environment suitable for static contexts or other contexts where there
    /// are no free type/lifetime parameters in scope.
2819
    pub fn empty_parameter_environment(self) -> ParameterEnvironment<'tcx> {
2820 2821 2822 2823

        // for an empty parameter environment, there ARE no free
        // regions, so it shouldn't matter what we use for the free id
        let free_id_outlive = self.region_maps.node_extent(ast::DUMMY_NODE_ID);
2824
        ty::ParameterEnvironment {
2825
            free_substs: Substs::empty(self),
2826
            caller_bounds: Vec::new(),
2827
            implicit_region_bound: self.mk_region(ty::ReEmpty),
2828 2829
            free_id_outlive: free_id_outlive
        }
2830 2831 2832 2833 2834 2835 2836
    }

    /// Constructs and returns a substitution that can be applied to move from
    /// the "outer" view of a type or method to the "inner" view.
    /// In general, this means converting from bound parameters to
    /// free parameters. Since we currently represent bound/free type
    /// parameters in the same way, this only has an effect on regions.
2837 2838 2839 2840 2841 2842
    pub fn construct_free_substs(self, def_id: DefId,
                                 free_id_outlive: CodeExtent)
                                 -> &'gcx Substs<'gcx> {

        let substs = Substs::for_item(self.global_tcx(), def_id, |def, _| {
            // map bound 'a => free 'a
2843 2844 2845 2846
            self.global_tcx().mk_region(ReFree(FreeRegion {
                scope: free_id_outlive,
                bound_region: def.to_bound_region()
            }))
2847 2848
        }, |def, _| {
            // map T => T
2849 2850
            self.global_tcx().mk_param_from_def(def)
        });
2851

2852 2853
        debug!("construct_parameter_environment: {:?}", substs);
        substs
2854
    }
2855

2856 2857 2858
    /// See `ParameterEnvironment` struct def'n for details.
    /// If you were using `free_id: NodeId`, you might try `self.region_maps.item_extent(free_id)`
    /// for the `free_id_outlive` parameter. (But note that that is not always quite right.)
2859 2860
    pub fn construct_parameter_environment(self,
                                           span: Span,
2861
                                           def_id: DefId,
2862
                                           free_id_outlive: CodeExtent)
2863
                                           -> ParameterEnvironment<'gcx>
2864 2865 2866 2867
    {
        //
        // Construct the free substs.
        //
2868

2869
        let free_substs = self.construct_free_substs(def_id, free_id_outlive);
2870

2871 2872 2873
        //
        // Compute the bounds on Self and the type parameters.
        //
2874

2875
        let tcx = self.global_tcx();
2876 2877
        let generic_predicates = tcx.lookup_predicates(def_id);
        let bounds = generic_predicates.instantiate(tcx, free_substs);
2878
        let bounds = tcx.liberate_late_bound_regions(free_id_outlive, &ty::Binder(bounds));
2879
        let predicates = bounds.predicates;
2880

2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
        // Finally, we have to normalize the bounds in the environment, in
        // case they contain any associated type projections. This process
        // can yield errors if the put in illegal associated types, like
        // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
        // report these errors right here; this doesn't actually feel
        // right to me, because constructing the environment feels like a
        // kind of a "idempotent" action, but I'm not sure where would be
        // a better place. In practice, we construct environments for
        // every fn once during type checking, and we'll abort if there
        // are any errors at that point, so after type checking you can be
        // sure that this will succeed without errors anyway.
        //
2893

2894
        let unnormalized_env = ty::ParameterEnvironment {
2895
            free_substs: free_substs,
2896
            implicit_region_bound: tcx.mk_region(ty::ReScope(free_id_outlive)),
2897
            caller_bounds: predicates,
2898
            free_id_outlive: free_id_outlive,
2899
        };
2900

2901
        let cause = traits::ObligationCause::misc(span, free_id_outlive.node_id(&self.region_maps));
2902
        traits::normalize_param_env_or_error(tcx, unnormalized_env, cause)
2903
    }
2904

2905 2906 2907 2908
    pub fn node_scope_region(self, id: NodeId) -> &'tcx Region {
        self.mk_region(ty::ReScope(self.region_maps.node_extent(id)))
    }

2909
    pub fn is_method_call(self, expr_id: NodeId) -> bool {
2910
        self.tables.borrow().method_map.contains_key(&MethodCall::expr(expr_id))
2911
    }
2912

2913
    pub fn is_overloaded_autoderef(self, expr_id: NodeId, autoderefs: u32) -> bool {
2914 2915 2916 2917
        self.tables.borrow().method_map.contains_key(&MethodCall::autoderef(expr_id,
                                                                            autoderefs))
    }

2918
    pub fn upvar_capture(self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
2919
        Some(self.tables.borrow().upvar_capture_map.get(&upvar_id).unwrap().clone())
2920
    }
2921

2922
    pub fn visit_all_items_in_krate<V,F>(self,
2923 2924
                                         dep_node_fn: F,
                                         visitor: &mut V)
2925
        where F: FnMut(DefId) -> DepNode<DefId>, V: Visitor<'gcx>
2926
    {
2927
        dep_graph::visit_all_items_in_krate(self.global_tcx(), dep_node_fn, visitor);
2928
    }
2929

2930 2931
    /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
    /// with the name of the crate containing the impl.
2932
    pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, InternedString> {
2933 2934 2935 2936
        if impl_did.is_local() {
            let node_id = self.map.as_local_node_id(impl_did).unwrap();
            Ok(self.map.span(node_id))
        } else {
2937
            Err(self.sess.cstore.crate_name(impl_did.krate))
2938 2939
        }
    }
2940
}
2941

2942
/// The category of explicit self.
J
Jorge Aparicio 已提交
2943
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
2944
pub enum ExplicitSelfCategory<'tcx> {
2945 2946
    Static,
    ByValue,
2947
    ByReference(&'tcx Region, hir::Mutability),
2948
    ByBox,
2949 2950
}

2951
impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2952
    pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2953
        F: FnOnce(&[hir::Freevar]) -> T,
2954 2955 2956 2957 2958 2959
    {
        match self.freevars.borrow().get(&fid) {
            None => f(&[]),
            Some(d) => f(&d[..])
        }
    }
2960
}