]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/mod.rs
Rollup merge of #39604 - est31:i128_tests, r=alexcrichton
[rust.git] / src / librustc / ty / mod.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 pub use self::Variance::*;
12 pub use self::AssociatedItemContainer::*;
13 pub use self::BorrowKind::*;
14 pub use self::IntVarValue::*;
15 pub use self::LvaluePreference::*;
16 pub use self::fold::TypeFoldable;
17
18 use dep_graph::{self, DepNode};
19 use hir::{map as hir_map, FreevarMap, TraitMap};
20 use middle;
21 use hir::def::{Def, CtorKind, ExportMap};
22 use hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
23 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
24 use middle::region::{CodeExtent, ROOT_CODE_EXTENT};
25 use mir::Mir;
26 use traits;
27 use ty;
28 use ty::subst::{Subst, Substs};
29 use ty::walk::TypeWalker;
30 use util::common::MemoizationMap;
31 use util::nodemap::{NodeSet, NodeMap, FxHashMap};
32
33 use serialize::{self, Encodable, Encoder};
34 use std::borrow::Cow;
35 use std::cell::{Cell, RefCell, Ref};
36 use std::hash::{Hash, Hasher};
37 use std::iter;
38 use std::ops::Deref;
39 use std::rc::Rc;
40 use std::slice;
41 use std::vec::IntoIter;
42 use std::mem;
43 use syntax::ast::{self, Name, NodeId};
44 use syntax::attr;
45 use syntax::symbol::{Symbol, InternedString};
46 use syntax_pos::{DUMMY_SP, Span};
47
48 use rustc_const_math::ConstInt;
49 use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
50
51 use hir;
52 use hir::itemlikevisit::ItemLikeVisitor;
53
54 pub use self::sty::{Binder, DebruijnIndex};
55 pub use self::sty::{BareFnTy, FnSig, PolyFnSig};
56 pub use self::sty::{ClosureTy, InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
57 pub use self::sty::{ClosureSubsts, TypeAndMut};
58 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
59 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
60 pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
61 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
62 pub use self::sty::Issue32330;
63 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid, SkolemizedRegionVid};
64 pub use self::sty::BoundRegion::*;
65 pub use self::sty::InferTy::*;
66 pub use self::sty::Region::*;
67 pub use self::sty::TypeVariants::*;
68
69 pub use self::contents::TypeContents;
70 pub use self::context::{TyCtxt, GlobalArenas, tls};
71 pub use self::context::{Lift, TypeckTables};
72
73 pub use self::trait_def::{TraitDef, TraitFlags};
74
75 pub mod adjustment;
76 pub mod cast;
77 pub mod error;
78 pub mod fast_reject;
79 pub mod fold;
80 pub mod inhabitedness;
81 pub mod item_path;
82 pub mod layout;
83 pub mod _match;
84 pub mod maps;
85 pub mod outlives;
86 pub mod relate;
87 pub mod subst;
88 pub mod trait_def;
89 pub mod walk;
90 pub mod wf;
91 pub mod util;
92
93 mod contents;
94 mod context;
95 mod flags;
96 mod structural_impls;
97 mod sty;
98
99 pub type Disr = ConstInt;
100
101 // Data types
102
103 /// The complete set of all analyses described in this module. This is
104 /// produced by the driver and fed to trans and later passes.
105 #[derive(Clone)]
106 pub struct CrateAnalysis<'tcx> {
107     pub export_map: ExportMap,
108     pub access_levels: middle::privacy::AccessLevels,
109     pub reachable: NodeSet,
110     pub name: String,
111     pub glob_map: Option<hir::GlobMap>,
112     pub hir_ty_to_ty: NodeMap<Ty<'tcx>>,
113 }
114
115 #[derive(Clone)]
116 pub struct Resolutions {
117     pub freevars: FreevarMap,
118     pub trait_map: TraitMap,
119     pub maybe_unused_trait_imports: NodeSet,
120 }
121
122 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
123 pub enum AssociatedItemContainer {
124     TraitContainer(DefId),
125     ImplContainer(DefId),
126 }
127
128 impl AssociatedItemContainer {
129     pub fn id(&self) -> DefId {
130         match *self {
131             TraitContainer(id) => id,
132             ImplContainer(id) => id,
133         }
134     }
135 }
136
137 /// The "header" of an impl is everything outside the body: a Self type, a trait
138 /// ref (in the case of a trait impl), and a set of predicates (from the
139 /// bounds/where clauses).
140 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
141 pub struct ImplHeader<'tcx> {
142     pub impl_def_id: DefId,
143     pub self_ty: Ty<'tcx>,
144     pub trait_ref: Option<TraitRef<'tcx>>,
145     pub predicates: Vec<Predicate<'tcx>>,
146 }
147
148 impl<'a, 'gcx, 'tcx> ImplHeader<'tcx> {
149     pub fn with_fresh_ty_vars(selcx: &mut traits::SelectionContext<'a, 'gcx, 'tcx>,
150                               impl_def_id: DefId)
151                               -> ImplHeader<'tcx>
152     {
153         let tcx = selcx.tcx();
154         let impl_substs = selcx.infcx().fresh_substs_for_item(DUMMY_SP, impl_def_id);
155
156         let header = ImplHeader {
157             impl_def_id: impl_def_id,
158             self_ty: tcx.item_type(impl_def_id),
159             trait_ref: tcx.impl_trait_ref(impl_def_id),
160             predicates: tcx.item_predicates(impl_def_id).predicates
161         }.subst(tcx, impl_substs);
162
163         let traits::Normalized { value: mut header, obligations } =
164             traits::normalize(selcx, traits::ObligationCause::dummy(), &header);
165
166         header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
167         header
168     }
169 }
170
171 #[derive(Copy, Clone, Debug)]
172 pub struct AssociatedItem {
173     pub def_id: DefId,
174     pub name: Name,
175     pub kind: AssociatedKind,
176     pub vis: Visibility,
177     pub defaultness: hir::Defaultness,
178     pub container: AssociatedItemContainer,
179
180     /// Whether this is a method with an explicit self
181     /// as its first argument, allowing method calls.
182     pub method_has_self_argument: bool,
183 }
184
185 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
186 pub enum AssociatedKind {
187     Const,
188     Method,
189     Type
190 }
191
192 impl AssociatedItem {
193     pub fn def(&self) -> Def {
194         match self.kind {
195             AssociatedKind::Const => Def::AssociatedConst(self.def_id),
196             AssociatedKind::Method => Def::Method(self.def_id),
197             AssociatedKind::Type => Def::AssociatedTy(self.def_id),
198         }
199     }
200
201     /// Tests whether the associated item admits a non-trivial implementation
202     /// for !
203     pub fn relevant_for_never<'tcx>(&self) -> bool {
204         match self.kind {
205             AssociatedKind::Const => true,
206             AssociatedKind::Type => true,
207             // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
208             AssociatedKind::Method => !self.method_has_self_argument,
209         }
210     }
211 }
212
213 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
214 pub enum Visibility {
215     /// Visible everywhere (including in other crates).
216     Public,
217     /// Visible only in the given crate-local module.
218     Restricted(DefId),
219     /// Not visible anywhere in the local crate. This is the visibility of private external items.
220     Invisible,
221 }
222
223 pub trait DefIdTree: Copy {
224     fn parent(self, id: DefId) -> Option<DefId>;
225
226     fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
227         if descendant.krate != ancestor.krate {
228             return false;
229         }
230
231         while descendant != ancestor {
232             match self.parent(descendant) {
233                 Some(parent) => descendant = parent,
234                 None => return false,
235             }
236         }
237         true
238     }
239 }
240
241 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
242     fn parent(self, id: DefId) -> Option<DefId> {
243         self.def_key(id).parent.map(|index| DefId { index: index, ..id })
244     }
245 }
246
247 impl Visibility {
248     pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
249         match *visibility {
250             hir::Public => Visibility::Public,
251             hir::Visibility::Crate => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
252             hir::Visibility::Restricted { ref path, .. } => match path.def {
253                 // If there is no resolution, `resolve` will have already reported an error, so
254                 // assume that the visibility is public to avoid reporting more privacy errors.
255                 Def::Err => Visibility::Public,
256                 def => Visibility::Restricted(def.def_id()),
257             },
258             hir::Inherited => {
259                 Visibility::Restricted(tcx.hir.local_def_id(tcx.hir.get_module_parent(id)))
260             }
261         }
262     }
263
264     /// Returns true if an item with this visibility is accessible from the given block.
265     pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
266         let restriction = match self {
267             // Public items are visible everywhere.
268             Visibility::Public => return true,
269             // Private items from other crates are visible nowhere.
270             Visibility::Invisible => return false,
271             // Restricted items are visible in an arbitrary local module.
272             Visibility::Restricted(other) if other.krate != module.krate => return false,
273             Visibility::Restricted(module) => module,
274         };
275
276         tree.is_descendant_of(module, restriction)
277     }
278
279     /// Returns true if this visibility is at least as accessible as the given visibility
280     pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
281         let vis_restriction = match vis {
282             Visibility::Public => return self == Visibility::Public,
283             Visibility::Invisible => return true,
284             Visibility::Restricted(module) => module,
285         };
286
287         self.is_accessible_from(vis_restriction, tree)
288     }
289 }
290
291 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
292 pub enum Variance {
293     Covariant,      // T<A> <: T<B> iff A <: B -- e.g., function return type
294     Invariant,      // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
295     Contravariant,  // T<A> <: T<B> iff B <: A -- e.g., function param type
296     Bivariant,      // T<A> <: T<B>            -- e.g., unused type parameter
297 }
298
299 #[derive(Clone, Copy, Debug, RustcDecodable, RustcEncodable)]
300 pub struct MethodCallee<'tcx> {
301     /// Impl method ID, for inherent methods, or trait method ID, otherwise.
302     pub def_id: DefId,
303     pub ty: Ty<'tcx>,
304     pub substs: &'tcx Substs<'tcx>
305 }
306
307 /// With method calls, we store some extra information in
308 /// side tables (i.e method_map). We use
309 /// MethodCall as a key to index into these tables instead of
310 /// just directly using the expression's NodeId. The reason
311 /// for this being that we may apply adjustments (coercions)
312 /// with the resulting expression also needing to use the
313 /// side tables. The problem with this is that we don't
314 /// assign a separate NodeId to this new expression
315 /// and so it would clash with the base expression if both
316 /// needed to add to the side tables. Thus to disambiguate
317 /// we also keep track of whether there's an adjustment in
318 /// our key.
319 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
320 pub struct MethodCall {
321     pub expr_id: NodeId,
322     pub autoderef: u32
323 }
324
325 impl MethodCall {
326     pub fn expr(id: NodeId) -> MethodCall {
327         MethodCall {
328             expr_id: id,
329             autoderef: 0
330         }
331     }
332
333     pub fn autoderef(expr_id: NodeId, autoderef: u32) -> MethodCall {
334         MethodCall {
335             expr_id: expr_id,
336             autoderef: 1 + autoderef
337         }
338     }
339 }
340
341 // maps from an expression id that corresponds to a method call to the details
342 // of the method to be invoked
343 pub type MethodMap<'tcx> = FxHashMap<MethodCall, MethodCallee<'tcx>>;
344
345 // Contains information needed to resolve types and (in the future) look up
346 // the types of AST nodes.
347 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
348 pub struct CReaderCacheKey {
349     pub cnum: CrateNum,
350     pub pos: usize,
351 }
352
353 /// Describes the fragment-state associated with a NodeId.
354 ///
355 /// Currently only unfragmented paths have entries in the table,
356 /// but longer-term this enum is expected to expand to also
357 /// include data for fragmented paths.
358 #[derive(Copy, Clone, Debug)]
359 pub enum FragmentInfo {
360     Moved { var: NodeId, move_expr: NodeId },
361     Assigned { var: NodeId, assign_expr: NodeId, assignee_id: NodeId },
362 }
363
364 // Flags that we track on types. These flags are propagated upwards
365 // through the type during type construction, so that we can quickly
366 // check whether the type has various kinds of types in it without
367 // recursing over the type itself.
368 bitflags! {
369     flags TypeFlags: u32 {
370         const HAS_PARAMS         = 1 << 0,
371         const HAS_SELF           = 1 << 1,
372         const HAS_TY_INFER       = 1 << 2,
373         const HAS_RE_INFER       = 1 << 3,
374         const HAS_RE_SKOL        = 1 << 4,
375         const HAS_RE_EARLY_BOUND = 1 << 5,
376         const HAS_FREE_REGIONS   = 1 << 6,
377         const HAS_TY_ERR         = 1 << 7,
378         const HAS_PROJECTION     = 1 << 8,
379         const HAS_TY_CLOSURE     = 1 << 9,
380
381         // true if there are "names" of types and regions and so forth
382         // that are local to a particular fn
383         const HAS_LOCAL_NAMES    = 1 << 10,
384
385         // Present if the type belongs in a local type context.
386         // Only set for TyInfer other than Fresh.
387         const KEEP_IN_LOCAL_TCX  = 1 << 11,
388
389         // Is there a projection that does not involve a bound region?
390         // Currently we can't normalize projections w/ bound regions.
391         const HAS_NORMALIZABLE_PROJECTION = 1 << 12,
392
393         const NEEDS_SUBST        = TypeFlags::HAS_PARAMS.bits |
394                                    TypeFlags::HAS_SELF.bits |
395                                    TypeFlags::HAS_RE_EARLY_BOUND.bits,
396
397         // Flags representing the nominal content of a type,
398         // computed by FlagsComputation. If you add a new nominal
399         // flag, it should be added here too.
400         const NOMINAL_FLAGS     = TypeFlags::HAS_PARAMS.bits |
401                                   TypeFlags::HAS_SELF.bits |
402                                   TypeFlags::HAS_TY_INFER.bits |
403                                   TypeFlags::HAS_RE_INFER.bits |
404                                   TypeFlags::HAS_RE_SKOL.bits |
405                                   TypeFlags::HAS_RE_EARLY_BOUND.bits |
406                                   TypeFlags::HAS_FREE_REGIONS.bits |
407                                   TypeFlags::HAS_TY_ERR.bits |
408                                   TypeFlags::HAS_PROJECTION.bits |
409                                   TypeFlags::HAS_TY_CLOSURE.bits |
410                                   TypeFlags::HAS_LOCAL_NAMES.bits |
411                                   TypeFlags::KEEP_IN_LOCAL_TCX.bits,
412
413         // Caches for type_is_sized, type_moves_by_default
414         const SIZEDNESS_CACHED  = 1 << 16,
415         const IS_SIZED          = 1 << 17,
416         const MOVENESS_CACHED   = 1 << 18,
417         const MOVES_BY_DEFAULT  = 1 << 19,
418     }
419 }
420
421 pub struct TyS<'tcx> {
422     pub sty: TypeVariants<'tcx>,
423     pub flags: Cell<TypeFlags>,
424
425     // the maximal depth of any bound regions appearing in this type.
426     region_depth: u32,
427 }
428
429 impl<'tcx> PartialEq for TyS<'tcx> {
430     #[inline]
431     fn eq(&self, other: &TyS<'tcx>) -> bool {
432         // (self as *const _) == (other as *const _)
433         (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
434     }
435 }
436 impl<'tcx> Eq for TyS<'tcx> {}
437
438 impl<'tcx> Hash for TyS<'tcx> {
439     fn hash<H: Hasher>(&self, s: &mut H) {
440         (self as *const TyS).hash(s)
441     }
442 }
443
444 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
445
446 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
447 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
448
449 /// A wrapper for slices with the additional invariant
450 /// that the slice is interned and no other slice with
451 /// the same contents can exist in the same context.
452 /// This means we can use pointer + length for both
453 /// equality comparisons and hashing.
454 #[derive(Debug, RustcEncodable)]
455 pub struct Slice<T>([T]);
456
457 impl<T> PartialEq for Slice<T> {
458     #[inline]
459     fn eq(&self, other: &Slice<T>) -> bool {
460         (&self.0 as *const [T]) == (&other.0 as *const [T])
461     }
462 }
463 impl<T> Eq for Slice<T> {}
464
465 impl<T> Hash for Slice<T> {
466     fn hash<H: Hasher>(&self, s: &mut H) {
467         (self.as_ptr(), self.len()).hash(s)
468     }
469 }
470
471 impl<T> Deref for Slice<T> {
472     type Target = [T];
473     fn deref(&self) -> &[T] {
474         &self.0
475     }
476 }
477
478 impl<'a, T> IntoIterator for &'a Slice<T> {
479     type Item = &'a T;
480     type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
481     fn into_iter(self) -> Self::IntoIter {
482         self[..].iter()
483     }
484 }
485
486 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
487
488 impl<T> Slice<T> {
489     pub fn empty<'a>() -> &'a Slice<T> {
490         unsafe {
491             mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
492         }
493     }
494 }
495
496 /// Upvars do not get their own node-id. Instead, we use the pair of
497 /// the original var id (that is, the root variable that is referenced
498 /// by the upvar) and the id of the closure expression.
499 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
500 pub struct UpvarId {
501     pub var_id: NodeId,
502     pub closure_expr_id: NodeId,
503 }
504
505 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
506 pub enum BorrowKind {
507     /// Data must be immutable and is aliasable.
508     ImmBorrow,
509
510     /// Data must be immutable but not aliasable.  This kind of borrow
511     /// cannot currently be expressed by the user and is used only in
512     /// implicit closure bindings. It is needed when the closure
513     /// is borrowing or mutating a mutable referent, e.g.:
514     ///
515     ///    let x: &mut isize = ...;
516     ///    let y = || *x += 5;
517     ///
518     /// If we were to try to translate this closure into a more explicit
519     /// form, we'd encounter an error with the code as written:
520     ///
521     ///    struct Env { x: & &mut isize }
522     ///    let x: &mut isize = ...;
523     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
524     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
525     ///
526     /// This is then illegal because you cannot mutate a `&mut` found
527     /// in an aliasable location. To solve, you'd have to translate with
528     /// an `&mut` borrow:
529     ///
530     ///    struct Env { x: & &mut isize }
531     ///    let x: &mut isize = ...;
532     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
533     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
534     ///
535     /// Now the assignment to `**env.x` is legal, but creating a
536     /// mutable pointer to `x` is not because `x` is not mutable. We
537     /// could fix this by declaring `x` as `let mut x`. This is ok in
538     /// user code, if awkward, but extra weird for closures, since the
539     /// borrow is hidden.
540     ///
541     /// So we introduce a "unique imm" borrow -- the referent is
542     /// immutable, but not aliasable. This solves the problem. For
543     /// simplicity, we don't give users the way to express this
544     /// borrow, it's just used when translating closures.
545     UniqueImmBorrow,
546
547     /// Data is mutable and not aliasable.
548     MutBorrow
549 }
550
551 /// Information describing the capture of an upvar. This is computed
552 /// during `typeck`, specifically by `regionck`.
553 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
554 pub enum UpvarCapture<'tcx> {
555     /// Upvar is captured by value. This is always true when the
556     /// closure is labeled `move`, but can also be true in other cases
557     /// depending on inference.
558     ByValue,
559
560     /// Upvar is captured by reference.
561     ByRef(UpvarBorrow<'tcx>),
562 }
563
564 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
565 pub struct UpvarBorrow<'tcx> {
566     /// The kind of borrow: by-ref upvars have access to shared
567     /// immutable borrows, which are not part of the normal language
568     /// syntax.
569     pub kind: BorrowKind,
570
571     /// Region of the resulting reference.
572     pub region: &'tcx ty::Region,
573 }
574
575 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
576
577 #[derive(Copy, Clone)]
578 pub struct ClosureUpvar<'tcx> {
579     pub def: Def,
580     pub span: Span,
581     pub ty: Ty<'tcx>,
582 }
583
584 #[derive(Clone, Copy, PartialEq)]
585 pub enum IntVarValue {
586     IntType(ast::IntTy),
587     UintType(ast::UintTy),
588 }
589
590 #[derive(Clone, RustcEncodable, RustcDecodable)]
591 pub struct TypeParameterDef<'tcx> {
592     pub name: Name,
593     pub def_id: DefId,
594     pub index: u32,
595     pub default_def_id: DefId, // for use in error reporing about defaults
596     pub default: Option<Ty<'tcx>>,
597
598     /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
599     /// on generic parameter `T`, asserts data behind the parameter
600     /// `T` won't be accessed during the parent type's `Drop` impl.
601     pub pure_wrt_drop: bool,
602 }
603
604 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
605 pub struct RegionParameterDef {
606     pub name: Name,
607     pub def_id: DefId,
608     pub index: u32,
609     pub issue_32330: Option<ty::Issue32330>,
610
611     /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
612     /// on generic parameter `'a`, asserts data of lifetime `'a`
613     /// won't be accessed during the parent type's `Drop` impl.
614     pub pure_wrt_drop: bool,
615 }
616
617 impl RegionParameterDef {
618     pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
619         ty::EarlyBoundRegion {
620             index: self.index,
621             name: self.name,
622         }
623     }
624
625     pub fn to_bound_region(&self) -> ty::BoundRegion {
626         ty::BoundRegion::BrNamed(self.def_id, self.name)
627     }
628 }
629
630 /// Information about the formal type/lifetime parameters associated
631 /// with an item or method. Analogous to hir::Generics.
632 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
633 pub struct Generics<'tcx> {
634     pub parent: Option<DefId>,
635     pub parent_regions: u32,
636     pub parent_types: u32,
637     pub regions: Vec<RegionParameterDef>,
638     pub types: Vec<TypeParameterDef<'tcx>>,
639     pub has_self: bool,
640 }
641
642 impl<'tcx> Generics<'tcx> {
643     pub fn parent_count(&self) -> usize {
644         self.parent_regions as usize + self.parent_types as usize
645     }
646
647     pub fn own_count(&self) -> usize {
648         self.regions.len() + self.types.len()
649     }
650
651     pub fn count(&self) -> usize {
652         self.parent_count() + self.own_count()
653     }
654
655     pub fn region_param(&self, param: &EarlyBoundRegion) -> &RegionParameterDef {
656         &self.regions[param.index as usize - self.has_self as usize]
657     }
658
659     pub fn type_param(&self, param: &ParamTy) -> &TypeParameterDef<'tcx> {
660         &self.types[param.idx as usize - self.has_self as usize - self.regions.len()]
661     }
662 }
663
664 /// Bounds on generics.
665 #[derive(Clone)]
666 pub struct GenericPredicates<'tcx> {
667     pub parent: Option<DefId>,
668     pub predicates: Vec<Predicate<'tcx>>,
669 }
670
671 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
672 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
673
674 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
675     pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
676                        -> InstantiatedPredicates<'tcx> {
677         let mut instantiated = InstantiatedPredicates::empty();
678         self.instantiate_into(tcx, &mut instantiated, substs);
679         instantiated
680     }
681     pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
682                            -> InstantiatedPredicates<'tcx> {
683         InstantiatedPredicates {
684             predicates: self.predicates.subst(tcx, substs)
685         }
686     }
687
688     fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
689                         instantiated: &mut InstantiatedPredicates<'tcx>,
690                         substs: &Substs<'tcx>) {
691         if let Some(def_id) = self.parent {
692             tcx.item_predicates(def_id).instantiate_into(tcx, instantiated, substs);
693         }
694         instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
695     }
696
697     pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
698                                   poly_trait_ref: &ty::PolyTraitRef<'tcx>)
699                                   -> InstantiatedPredicates<'tcx>
700     {
701         assert_eq!(self.parent, None);
702         InstantiatedPredicates {
703             predicates: self.predicates.iter().map(|pred| {
704                 pred.subst_supertrait(tcx, poly_trait_ref)
705             }).collect()
706         }
707     }
708 }
709
710 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
711 pub enum Predicate<'tcx> {
712     /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
713     /// the `Self` type of the trait reference and `A`, `B`, and `C`
714     /// would be the type parameters.
715     Trait(PolyTraitPredicate<'tcx>),
716
717     /// where `T1 == T2`.
718     Equate(PolyEquatePredicate<'tcx>),
719
720     /// where 'a : 'b
721     RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
722
723     /// where T : 'a
724     TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
725
726     /// where <T as TraitRef>::Name == X, approximately.
727     /// See `ProjectionPredicate` struct for details.
728     Projection(PolyProjectionPredicate<'tcx>),
729
730     /// no syntax: T WF
731     WellFormed(Ty<'tcx>),
732
733     /// trait must be object-safe
734     ObjectSafe(DefId),
735
736     /// No direct syntax. May be thought of as `where T : FnFoo<...>`
737     /// for some substitutions `...` and T being a closure type.
738     /// Satisfied (or refuted) once we know the closure's kind.
739     ClosureKind(DefId, ClosureKind),
740 }
741
742 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
743     /// Performs a substitution suitable for going from a
744     /// poly-trait-ref to supertraits that must hold if that
745     /// poly-trait-ref holds. This is slightly different from a normal
746     /// substitution in terms of what happens with bound regions.  See
747     /// lengthy comment below for details.
748     pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
749                             trait_ref: &ty::PolyTraitRef<'tcx>)
750                             -> ty::Predicate<'tcx>
751     {
752         // The interaction between HRTB and supertraits is not entirely
753         // obvious. Let me walk you (and myself) through an example.
754         //
755         // Let's start with an easy case. Consider two traits:
756         //
757         //     trait Foo<'a> : Bar<'a,'a> { }
758         //     trait Bar<'b,'c> { }
759         //
760         // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
761         // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
762         // knew that `Foo<'x>` (for any 'x) then we also know that
763         // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
764         // normal substitution.
765         //
766         // In terms of why this is sound, the idea is that whenever there
767         // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
768         // holds.  So if there is an impl of `T:Foo<'a>` that applies to
769         // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
770         // `'a`.
771         //
772         // Another example to be careful of is this:
773         //
774         //     trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
775         //     trait Bar1<'b,'c> { }
776         //
777         // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
778         // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
779         // reason is similar to the previous example: any impl of
780         // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`.  So
781         // basically we would want to collapse the bound lifetimes from
782         // the input (`trait_ref`) and the supertraits.
783         //
784         // To achieve this in practice is fairly straightforward. Let's
785         // consider the more complicated scenario:
786         //
787         // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
788         //   has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
789         //   where both `'x` and `'b` would have a DB index of 1.
790         //   The substitution from the input trait-ref is therefore going to be
791         //   `'a => 'x` (where `'x` has a DB index of 1).
792         // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
793         //   early-bound parameter and `'b' is a late-bound parameter with a
794         //   DB index of 1.
795         // - If we replace `'a` with `'x` from the input, it too will have
796         //   a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
797         //   just as we wanted.
798         //
799         // There is only one catch. If we just apply the substitution `'a
800         // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
801         // adjust the DB index because we substituting into a binder (it
802         // tries to be so smart...) resulting in `for<'x> for<'b>
803         // Bar1<'x,'b>` (we have no syntax for this, so use your
804         // imagination). Basically the 'x will have DB index of 2 and 'b
805         // will have DB index of 1. Not quite what we want. So we apply
806         // the substitution to the *contents* of the trait reference,
807         // rather than the trait reference itself (put another way, the
808         // substitution code expects equal binding levels in the values
809         // from the substitution and the value being substituted into, and
810         // this trick achieves that).
811
812         let substs = &trait_ref.0.substs;
813         match *self {
814             Predicate::Trait(ty::Binder(ref data)) =>
815                 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
816             Predicate::Equate(ty::Binder(ref data)) =>
817                 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
818             Predicate::RegionOutlives(ty::Binder(ref data)) =>
819                 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
820             Predicate::TypeOutlives(ty::Binder(ref data)) =>
821                 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
822             Predicate::Projection(ty::Binder(ref data)) =>
823                 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
824             Predicate::WellFormed(data) =>
825                 Predicate::WellFormed(data.subst(tcx, substs)),
826             Predicate::ObjectSafe(trait_def_id) =>
827                 Predicate::ObjectSafe(trait_def_id),
828             Predicate::ClosureKind(closure_def_id, kind) =>
829                 Predicate::ClosureKind(closure_def_id, kind),
830         }
831     }
832 }
833
834 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
835 pub struct TraitPredicate<'tcx> {
836     pub trait_ref: TraitRef<'tcx>
837 }
838 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
839
840 impl<'tcx> TraitPredicate<'tcx> {
841     pub fn def_id(&self) -> DefId {
842         self.trait_ref.def_id
843     }
844
845     /// Creates the dep-node for selecting/evaluating this trait reference.
846     fn dep_node(&self) -> DepNode<DefId> {
847         // Ideally, the dep-node would just have all the input types
848         // in it.  But they are limited to including def-ids. So as an
849         // approximation we include the def-ids for all nominal types
850         // found somewhere. This means that we will e.g. conflate the
851         // dep-nodes for `u32: SomeTrait` and `u64: SomeTrait`, but we
852         // would have distinct dep-nodes for `Vec<u32>: SomeTrait`,
853         // `Rc<u32>: SomeTrait`, and `(Vec<u32>, Rc<u32>): SomeTrait`.
854         // Note that it's always sound to conflate dep-nodes, it just
855         // leads to more recompilation.
856         let def_ids: Vec<_> =
857             self.input_types()
858                 .flat_map(|t| t.walk())
859                 .filter_map(|t| match t.sty {
860                     ty::TyAdt(adt_def, _) =>
861                         Some(adt_def.did),
862                     _ =>
863                         None
864                 })
865                 .chain(iter::once(self.def_id()))
866                 .collect();
867         DepNode::TraitSelect(def_ids)
868     }
869
870     pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
871         self.trait_ref.input_types()
872     }
873
874     pub fn self_ty(&self) -> Ty<'tcx> {
875         self.trait_ref.self_ty()
876     }
877 }
878
879 impl<'tcx> PolyTraitPredicate<'tcx> {
880     pub fn def_id(&self) -> DefId {
881         // ok to skip binder since trait def-id does not care about regions
882         self.0.def_id()
883     }
884
885     pub fn dep_node(&self) -> DepNode<DefId> {
886         // ok to skip binder since depnode does not care about regions
887         self.0.dep_node()
888     }
889 }
890
891 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
892 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
893 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
894
895 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
896 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
897 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
898 pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<&'tcx ty::Region,
899                                                                    &'tcx ty::Region>;
900 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, &'tcx ty::Region>;
901
902 /// This kind of predicate has no *direct* correspondent in the
903 /// syntax, but it roughly corresponds to the syntactic forms:
904 ///
905 /// 1. `T : TraitRef<..., Item=Type>`
906 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
907 ///
908 /// In particular, form #1 is "desugared" to the combination of a
909 /// normal trait predicate (`T : TraitRef<...>`) and one of these
910 /// predicates. Form #2 is a broader form in that it also permits
911 /// equality between arbitrary types. Processing an instance of Form
912 /// #2 eventually yields one of these `ProjectionPredicate`
913 /// instances to normalize the LHS.
914 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
915 pub struct ProjectionPredicate<'tcx> {
916     pub projection_ty: ProjectionTy<'tcx>,
917     pub ty: Ty<'tcx>,
918 }
919
920 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
921
922 impl<'tcx> PolyProjectionPredicate<'tcx> {
923     pub fn item_name(&self) -> Name {
924         self.0.projection_ty.item_name // safe to skip the binder to access a name
925     }
926 }
927
928 pub trait ToPolyTraitRef<'tcx> {
929     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
930 }
931
932 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
933     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
934         assert!(!self.has_escaping_regions());
935         ty::Binder(self.clone())
936     }
937 }
938
939 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
940     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
941         self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
942     }
943 }
944
945 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
946     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
947         // Note: unlike with TraitRef::to_poly_trait_ref(),
948         // self.0.trait_ref is permitted to have escaping regions.
949         // This is because here `self` has a `Binder` and so does our
950         // return value, so we are preserving the number of binding
951         // levels.
952         ty::Binder(self.0.projection_ty.trait_ref)
953     }
954 }
955
956 pub trait ToPredicate<'tcx> {
957     fn to_predicate(&self) -> Predicate<'tcx>;
958 }
959
960 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
961     fn to_predicate(&self) -> Predicate<'tcx> {
962         // we're about to add a binder, so let's check that we don't
963         // accidentally capture anything, or else that might be some
964         // weird debruijn accounting.
965         assert!(!self.has_escaping_regions());
966
967         ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
968             trait_ref: self.clone()
969         }))
970     }
971 }
972
973 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
974     fn to_predicate(&self) -> Predicate<'tcx> {
975         ty::Predicate::Trait(self.to_poly_trait_predicate())
976     }
977 }
978
979 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
980     fn to_predicate(&self) -> Predicate<'tcx> {
981         Predicate::Equate(self.clone())
982     }
983 }
984
985 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
986     fn to_predicate(&self) -> Predicate<'tcx> {
987         Predicate::RegionOutlives(self.clone())
988     }
989 }
990
991 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
992     fn to_predicate(&self) -> Predicate<'tcx> {
993         Predicate::TypeOutlives(self.clone())
994     }
995 }
996
997 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
998     fn to_predicate(&self) -> Predicate<'tcx> {
999         Predicate::Projection(self.clone())
1000     }
1001 }
1002
1003 impl<'tcx> Predicate<'tcx> {
1004     /// Iterates over the types in this predicate. Note that in all
1005     /// cases this is skipping over a binder, so late-bound regions
1006     /// with depth 0 are bound by the predicate.
1007     pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1008         let vec: Vec<_> = match *self {
1009             ty::Predicate::Trait(ref data) => {
1010                 data.skip_binder().input_types().collect()
1011             }
1012             ty::Predicate::Equate(ty::Binder(ref data)) => {
1013                 vec![data.0, data.1]
1014             }
1015             ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1016                 vec![data.0]
1017             }
1018             ty::Predicate::RegionOutlives(..) => {
1019                 vec![]
1020             }
1021             ty::Predicate::Projection(ref data) => {
1022                 let trait_inputs = data.0.projection_ty.trait_ref.input_types();
1023                 trait_inputs.chain(Some(data.0.ty)).collect()
1024             }
1025             ty::Predicate::WellFormed(data) => {
1026                 vec![data]
1027             }
1028             ty::Predicate::ObjectSafe(_trait_def_id) => {
1029                 vec![]
1030             }
1031             ty::Predicate::ClosureKind(_closure_def_id, _kind) => {
1032                 vec![]
1033             }
1034         };
1035
1036         // The only reason to collect into a vector here is that I was
1037         // too lazy to make the full (somewhat complicated) iterator
1038         // type that would be needed here. But I wanted this fn to
1039         // return an iterator conceptually, rather than a `Vec`, so as
1040         // to be closer to `Ty::walk`.
1041         vec.into_iter()
1042     }
1043
1044     pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1045         match *self {
1046             Predicate::Trait(ref t) => {
1047                 Some(t.to_poly_trait_ref())
1048             }
1049             Predicate::Projection(..) |
1050             Predicate::Equate(..) |
1051             Predicate::RegionOutlives(..) |
1052             Predicate::WellFormed(..) |
1053             Predicate::ObjectSafe(..) |
1054             Predicate::ClosureKind(..) |
1055             Predicate::TypeOutlives(..) => {
1056                 None
1057             }
1058         }
1059     }
1060 }
1061
1062 /// Represents the bounds declared on a particular set of type
1063 /// parameters.  Should eventually be generalized into a flag list of
1064 /// where clauses.  You can obtain a `InstantiatedPredicates` list from a
1065 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1066 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1067 /// the `GenericPredicates` are expressed in terms of the bound type
1068 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1069 /// represented a set of bounds for some particular instantiation,
1070 /// meaning that the generic parameters have been substituted with
1071 /// their values.
1072 ///
1073 /// Example:
1074 ///
1075 ///     struct Foo<T,U:Bar<T>> { ... }
1076 ///
1077 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1078 /// `[[], [U:Bar<T>]]`.  Now if there were some particular reference
1079 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1080 /// [usize:Bar<isize>]]`.
1081 #[derive(Clone)]
1082 pub struct InstantiatedPredicates<'tcx> {
1083     pub predicates: Vec<Predicate<'tcx>>,
1084 }
1085
1086 impl<'tcx> InstantiatedPredicates<'tcx> {
1087     pub fn empty() -> InstantiatedPredicates<'tcx> {
1088         InstantiatedPredicates { predicates: vec![] }
1089     }
1090
1091     pub fn is_empty(&self) -> bool {
1092         self.predicates.is_empty()
1093     }
1094 }
1095
1096 impl<'tcx> TraitRef<'tcx> {
1097     pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
1098         TraitRef { def_id: def_id, substs: substs }
1099     }
1100
1101     pub fn self_ty(&self) -> Ty<'tcx> {
1102         self.substs.type_at(0)
1103     }
1104
1105     pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
1106         // Select only the "input types" from a trait-reference. For
1107         // now this is all the types that appear in the
1108         // trait-reference, but it should eventually exclude
1109         // associated types.
1110         self.substs.types()
1111     }
1112 }
1113
1114 /// When type checking, we use the `ParameterEnvironment` to track
1115 /// details about the type/lifetime parameters that are in scope.
1116 /// It primarily stores the bounds information.
1117 ///
1118 /// Note: This information might seem to be redundant with the data in
1119 /// `tcx.ty_param_defs`, but it is not. That table contains the
1120 /// parameter definitions from an "outside" perspective, but this
1121 /// struct will contain the bounds for a parameter as seen from inside
1122 /// the function body. Currently the only real distinction is that
1123 /// bound lifetime parameters are replaced with free ones, but in the
1124 /// future I hope to refine the representation of types so as to make
1125 /// more distinctions clearer.
1126 #[derive(Clone)]
1127 pub struct ParameterEnvironment<'tcx> {
1128     /// See `construct_free_substs` for details.
1129     pub free_substs: &'tcx Substs<'tcx>,
1130
1131     /// Each type parameter has an implicit region bound that
1132     /// indicates it must outlive at least the function body (the user
1133     /// may specify stronger requirements). This field indicates the
1134     /// region of the callee.
1135     pub implicit_region_bound: &'tcx ty::Region,
1136
1137     /// Obligations that the caller must satisfy. This is basically
1138     /// the set of bounds on the in-scope type parameters, translated
1139     /// into Obligations, and elaborated and normalized.
1140     pub caller_bounds: Vec<ty::Predicate<'tcx>>,
1141
1142     /// Scope that is attached to free regions for this scope. This
1143     /// is usually the id of the fn body, but for more abstract scopes
1144     /// like structs we often use the node-id of the struct.
1145     ///
1146     /// FIXME(#3696). It would be nice to refactor so that free
1147     /// regions don't have this implicit scope and instead introduce
1148     /// relationships in the environment.
1149     pub free_id_outlive: CodeExtent,
1150
1151     /// A cache for `moves_by_default`.
1152     pub is_copy_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
1153
1154     /// A cache for `type_is_sized`
1155     pub is_sized_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
1156 }
1157
1158 impl<'a, 'tcx> ParameterEnvironment<'tcx> {
1159     pub fn with_caller_bounds(&self,
1160                               caller_bounds: Vec<ty::Predicate<'tcx>>)
1161                               -> ParameterEnvironment<'tcx>
1162     {
1163         ParameterEnvironment {
1164             free_substs: self.free_substs,
1165             implicit_region_bound: self.implicit_region_bound,
1166             caller_bounds: caller_bounds,
1167             free_id_outlive: self.free_id_outlive,
1168             is_copy_cache: RefCell::new(FxHashMap()),
1169             is_sized_cache: RefCell::new(FxHashMap()),
1170         }
1171     }
1172
1173     /// Construct a parameter environment given an item, impl item, or trait item
1174     pub fn for_item(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: NodeId)
1175                     -> ParameterEnvironment<'tcx> {
1176         match tcx.hir.find(id) {
1177             Some(hir_map::NodeImplItem(ref impl_item)) => {
1178                 match impl_item.node {
1179                     hir::ImplItemKind::Type(_) | hir::ImplItemKind::Const(..) => {
1180                         // associated types don't have their own entry (for some reason),
1181                         // so for now just grab environment for the impl
1182                         let impl_id = tcx.hir.get_parent(id);
1183                         let impl_def_id = tcx.hir.local_def_id(impl_id);
1184                         tcx.construct_parameter_environment(impl_item.span,
1185                                                             impl_def_id,
1186                                                             tcx.region_maps.item_extent(id))
1187                     }
1188                     hir::ImplItemKind::Method(_, ref body) => {
1189                         tcx.construct_parameter_environment(
1190                             impl_item.span,
1191                             tcx.hir.local_def_id(id),
1192                             tcx.region_maps.call_site_extent(id, body.node_id))
1193                     }
1194                 }
1195             }
1196             Some(hir_map::NodeTraitItem(trait_item)) => {
1197                 match trait_item.node {
1198                     hir::TraitItemKind::Type(..) | hir::TraitItemKind::Const(..) => {
1199                         // associated types don't have their own entry (for some reason),
1200                         // so for now just grab environment for the trait
1201                         let trait_id = tcx.hir.get_parent(id);
1202                         let trait_def_id = tcx.hir.local_def_id(trait_id);
1203                         tcx.construct_parameter_environment(trait_item.span,
1204                                                             trait_def_id,
1205                                                             tcx.region_maps.item_extent(id))
1206                     }
1207                     hir::TraitItemKind::Method(_, ref body) => {
1208                         // Use call-site for extent (unless this is a
1209                         // trait method with no default; then fallback
1210                         // to the method id).
1211                         let extent = if let hir::TraitMethod::Provided(body_id) = *body {
1212                             // default impl: use call_site extent as free_id_outlive bound.
1213                             tcx.region_maps.call_site_extent(id, body_id.node_id)
1214                         } else {
1215                             // no default impl: use item extent as free_id_outlive bound.
1216                             tcx.region_maps.item_extent(id)
1217                         };
1218                         tcx.construct_parameter_environment(
1219                             trait_item.span,
1220                             tcx.hir.local_def_id(id),
1221                             extent)
1222                     }
1223                 }
1224             }
1225             Some(hir_map::NodeItem(item)) => {
1226                 match item.node {
1227                     hir::ItemFn(.., body_id) => {
1228                         // We assume this is a function.
1229                         let fn_def_id = tcx.hir.local_def_id(id);
1230
1231                         tcx.construct_parameter_environment(
1232                             item.span,
1233                             fn_def_id,
1234                             tcx.region_maps.call_site_extent(id, body_id.node_id))
1235                     }
1236                     hir::ItemEnum(..) |
1237                     hir::ItemStruct(..) |
1238                     hir::ItemUnion(..) |
1239                     hir::ItemTy(..) |
1240                     hir::ItemImpl(..) |
1241                     hir::ItemConst(..) |
1242                     hir::ItemStatic(..) => {
1243                         let def_id = tcx.hir.local_def_id(id);
1244                         tcx.construct_parameter_environment(item.span,
1245                                                             def_id,
1246                                                             tcx.region_maps.item_extent(id))
1247                     }
1248                     hir::ItemTrait(..) => {
1249                         let def_id = tcx.hir.local_def_id(id);
1250                         tcx.construct_parameter_environment(item.span,
1251                                                             def_id,
1252                                                             tcx.region_maps.item_extent(id))
1253                     }
1254                     _ => {
1255                         span_bug!(item.span,
1256                                   "ParameterEnvironment::for_item():
1257                                    can't create a parameter \
1258                                    environment for this kind of item")
1259                     }
1260                 }
1261             }
1262             Some(hir_map::NodeExpr(expr)) => {
1263                 // This is a convenience to allow closures to work.
1264                 if let hir::ExprClosure(.., body, _) = expr.node {
1265                     let def_id = tcx.hir.local_def_id(id);
1266                     let base_def_id = tcx.closure_base_def_id(def_id);
1267                     tcx.construct_parameter_environment(
1268                         expr.span,
1269                         base_def_id,
1270                         tcx.region_maps.call_site_extent(id, body.node_id))
1271                 } else {
1272                     tcx.empty_parameter_environment()
1273                 }
1274             }
1275             Some(hir_map::NodeForeignItem(item)) => {
1276                 let def_id = tcx.hir.local_def_id(id);
1277                 tcx.construct_parameter_environment(item.span,
1278                                                     def_id,
1279                                                     ROOT_CODE_EXTENT)
1280             }
1281             _ => {
1282                 bug!("ParameterEnvironment::from_item(): \
1283                       `{}` is not an item",
1284                      tcx.hir.node_to_string(id))
1285             }
1286         }
1287     }
1288 }
1289
1290 bitflags! {
1291     flags AdtFlags: u32 {
1292         const NO_ADT_FLAGS        = 0,
1293         const IS_ENUM             = 1 << 0,
1294         const IS_DTORCK           = 1 << 1, // is this a dtorck type?
1295         const IS_DTORCK_VALID     = 1 << 2,
1296         const IS_PHANTOM_DATA     = 1 << 3,
1297         const IS_SIMD             = 1 << 4,
1298         const IS_FUNDAMENTAL      = 1 << 5,
1299         const IS_UNION            = 1 << 6,
1300         const IS_BOX              = 1 << 7,
1301     }
1302 }
1303
1304 #[derive(Debug)]
1305 pub struct VariantDef {
1306     /// The variant's DefId. If this is a tuple-like struct,
1307     /// this is the DefId of the struct's ctor.
1308     pub did: DefId,
1309     pub name: Name, // struct's name if this is a struct
1310     pub disr_val: Disr,
1311     pub fields: Vec<FieldDef>,
1312     pub ctor_kind: CtorKind,
1313 }
1314
1315 #[derive(Debug)]
1316 pub struct FieldDef {
1317     pub did: DefId,
1318     pub name: Name,
1319     pub vis: Visibility,
1320 }
1321
1322 /// The definition of an abstract data type - a struct or enum.
1323 ///
1324 /// These are all interned (by intern_adt_def) into the adt_defs
1325 /// table.
1326 pub struct AdtDef {
1327     pub did: DefId,
1328     pub variants: Vec<VariantDef>,
1329     destructor: Cell<Option<DefId>>,
1330     flags: Cell<AdtFlags>,
1331     pub repr: ReprOptions,
1332 }
1333
1334 impl PartialEq for AdtDef {
1335     // AdtDef are always interned and this is part of TyS equality
1336     #[inline]
1337     fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1338 }
1339
1340 impl Eq for AdtDef {}
1341
1342 impl Hash for AdtDef {
1343     #[inline]
1344     fn hash<H: Hasher>(&self, s: &mut H) {
1345         (self as *const AdtDef).hash(s)
1346     }
1347 }
1348
1349 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1350     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1351         self.did.encode(s)
1352     }
1353 }
1354
1355 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1356
1357 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1358 pub enum AdtKind { Struct, Union, Enum }
1359
1360 /// Represents the repr options provided by the user,
1361 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1362 pub struct ReprOptions {
1363     pub c: bool,
1364     pub packed: bool,
1365     pub simd: bool,
1366     pub int: Option<attr::IntType>,
1367 }
1368
1369 impl ReprOptions {
1370     pub fn new<'a, 'gcx, 'tcx>(tcx: &TyCtxt<'a, 'gcx, 'tcx>, did: DefId) -> ReprOptions {
1371         let mut ret = ReprOptions::default();
1372         let attrs = tcx.lookup_repr_hints(did);
1373         for r in attrs.iter() {
1374             match *r {
1375                 attr::ReprExtern => ret.c = true,
1376                 attr::ReprPacked => ret.packed = true,
1377                 attr::ReprSimd => ret.simd = true,
1378                 attr::ReprInt(i) => ret.int = Some(i),
1379                 attr::ReprAny => (),
1380             }
1381         }
1382         ret
1383     }
1384 }
1385
1386 impl<'a, 'gcx, 'tcx> AdtDef {
1387     fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1388            did: DefId,
1389            kind: AdtKind,
1390            variants: Vec<VariantDef>,
1391            repr: ReprOptions) -> Self {
1392         let mut flags = AdtFlags::NO_ADT_FLAGS;
1393         let attrs = tcx.get_attrs(did);
1394         if attr::contains_name(&attrs, "fundamental") {
1395             flags = flags | AdtFlags::IS_FUNDAMENTAL;
1396         }
1397         if tcx.lookup_simd(did) {
1398             flags = flags | AdtFlags::IS_SIMD;
1399         }
1400         if Some(did) == tcx.lang_items.phantom_data() {
1401             flags = flags | AdtFlags::IS_PHANTOM_DATA;
1402         }
1403         if Some(did) == tcx.lang_items.owned_box() {
1404             flags = flags | AdtFlags::IS_BOX;
1405         }
1406         match kind {
1407             AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1408             AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1409             AdtKind::Struct => {}
1410         }
1411         AdtDef {
1412             did: did,
1413             variants: variants,
1414             flags: Cell::new(flags),
1415             destructor: Cell::new(None),
1416             repr: repr,
1417         }
1418     }
1419
1420     fn calculate_dtorck(&'gcx self, tcx: TyCtxt) {
1421         if tcx.is_adt_dtorck(self) {
1422             self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK);
1423         }
1424         self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK_VALID)
1425     }
1426
1427     #[inline]
1428     pub fn is_struct(&self) -> bool {
1429         !self.is_union() && !self.is_enum()
1430     }
1431
1432     #[inline]
1433     pub fn is_union(&self) -> bool {
1434         self.flags.get().intersects(AdtFlags::IS_UNION)
1435     }
1436
1437     #[inline]
1438     pub fn is_enum(&self) -> bool {
1439         self.flags.get().intersects(AdtFlags::IS_ENUM)
1440     }
1441
1442     /// Returns the kind of the ADT - Struct or Enum.
1443     #[inline]
1444     pub fn adt_kind(&self) -> AdtKind {
1445         if self.is_enum() {
1446             AdtKind::Enum
1447         } else if self.is_union() {
1448             AdtKind::Union
1449         } else {
1450             AdtKind::Struct
1451         }
1452     }
1453
1454     pub fn descr(&self) -> &'static str {
1455         match self.adt_kind() {
1456             AdtKind::Struct => "struct",
1457             AdtKind::Union => "union",
1458             AdtKind::Enum => "enum",
1459         }
1460     }
1461
1462     pub fn variant_descr(&self) -> &'static str {
1463         match self.adt_kind() {
1464             AdtKind::Struct => "struct",
1465             AdtKind::Union => "union",
1466             AdtKind::Enum => "variant",
1467         }
1468     }
1469
1470     /// Returns whether this is a dtorck type. If this returns
1471     /// true, this type being safe for destruction requires it to be
1472     /// alive; Otherwise, only the contents are required to be.
1473     #[inline]
1474     pub fn is_dtorck(&'gcx self, tcx: TyCtxt) -> bool {
1475         if !self.flags.get().intersects(AdtFlags::IS_DTORCK_VALID) {
1476             self.calculate_dtorck(tcx)
1477         }
1478         self.flags.get().intersects(AdtFlags::IS_DTORCK)
1479     }
1480
1481     /// Returns whether this type is #[fundamental] for the purposes
1482     /// of coherence checking.
1483     #[inline]
1484     pub fn is_fundamental(&self) -> bool {
1485         self.flags.get().intersects(AdtFlags::IS_FUNDAMENTAL)
1486     }
1487
1488     #[inline]
1489     pub fn is_simd(&self) -> bool {
1490         self.flags.get().intersects(AdtFlags::IS_SIMD)
1491     }
1492
1493     /// Returns true if this is PhantomData<T>.
1494     #[inline]
1495     pub fn is_phantom_data(&self) -> bool {
1496         self.flags.get().intersects(AdtFlags::IS_PHANTOM_DATA)
1497     }
1498
1499     /// Returns true if this is Box<T>.
1500     #[inline]
1501     pub fn is_box(&self) -> bool {
1502         self.flags.get().intersects(AdtFlags::IS_BOX)
1503     }
1504
1505     /// Returns whether this type has a destructor.
1506     pub fn has_dtor(&self) -> bool {
1507         self.destructor.get().is_some()
1508     }
1509
1510     /// Asserts this is a struct and returns the struct's unique
1511     /// variant.
1512     pub fn struct_variant(&self) -> &VariantDef {
1513         assert!(!self.is_enum());
1514         &self.variants[0]
1515     }
1516
1517     #[inline]
1518     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1519         tcx.item_predicates(self.did)
1520     }
1521
1522     /// Returns an iterator over all fields contained
1523     /// by this ADT.
1524     #[inline]
1525     pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1526         self.variants.iter().flat_map(|v| v.fields.iter())
1527     }
1528
1529     #[inline]
1530     pub fn is_univariant(&self) -> bool {
1531         self.variants.len() == 1
1532     }
1533
1534     pub fn is_payloadfree(&self) -> bool {
1535         !self.variants.is_empty() &&
1536             self.variants.iter().all(|v| v.fields.is_empty())
1537     }
1538
1539     pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1540         self.variants
1541             .iter()
1542             .find(|v| v.did == vid)
1543             .expect("variant_with_id: unknown variant")
1544     }
1545
1546     pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1547         self.variants
1548             .iter()
1549             .position(|v| v.did == vid)
1550             .expect("variant_index_with_id: unknown variant")
1551     }
1552
1553     pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1554         match def {
1555             Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1556             Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1557             Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.struct_variant(),
1558             _ => bug!("unexpected def {:?} in variant_of_def", def)
1559         }
1560     }
1561
1562     pub fn destructor(&self) -> Option<DefId> {
1563         self.destructor.get()
1564     }
1565
1566     pub fn set_destructor(&self, dtor: DefId) {
1567         self.destructor.set(Some(dtor));
1568     }
1569
1570     /// Returns a simpler type such that `Self: Sized` if and only
1571     /// if that type is Sized, or `TyErr` if this type is recursive.
1572     ///
1573     /// HACK: instead of returning a list of types, this function can
1574     /// return a tuple. In that case, the result is Sized only if
1575     /// all elements of the tuple are Sized.
1576     ///
1577     /// This is generally the `struct_tail` if this is a struct, or a
1578     /// tuple of them if this is an enum.
1579     ///
1580     /// Oddly enough, checking that the sized-constraint is Sized is
1581     /// actually more expressive than checking all members:
1582     /// the Sized trait is inductive, so an associated type that references
1583     /// Self would prevent its containing ADT from being Sized.
1584     ///
1585     /// Due to normalization being eager, this applies even if
1586     /// the associated type is behind a pointer, e.g. issue #31299.
1587     pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1588         self.calculate_sized_constraint_inner(tcx.global_tcx(), &mut Vec::new())
1589     }
1590
1591     /// Calculates the Sized-constraint.
1592     ///
1593     /// As the Sized-constraint of enums can be a *set* of types,
1594     /// the Sized-constraint may need to be a set also. Because introducing
1595     /// a new type of IVar is currently a complex affair, the Sized-constraint
1596     /// may be a tuple.
1597     ///
1598     /// In fact, there are only a few options for the constraint:
1599     ///     - `bool`, if the type is always Sized
1600     ///     - an obviously-unsized type
1601     ///     - a type parameter or projection whose Sizedness can't be known
1602     ///     - a tuple of type parameters or projections, if there are multiple
1603     ///       such.
1604     ///     - a TyError, if a type contained itself. The representability
1605     ///       check should catch this case.
1606     fn calculate_sized_constraint_inner(&self,
1607                                         tcx: TyCtxt<'a, 'tcx, 'tcx>,
1608                                         stack: &mut Vec<DefId>)
1609                                         -> Ty<'tcx>
1610     {
1611         if let Some(ty) = tcx.adt_sized_constraint.borrow().get(&self.did) {
1612             return ty;
1613         }
1614
1615         // Follow the memoization pattern: push the computation of
1616         // DepNode::SizedConstraint as our current task.
1617         let _task = tcx.dep_graph.in_task(DepNode::SizedConstraint(self.did));
1618
1619         if stack.contains(&self.did) {
1620             debug!("calculate_sized_constraint: {:?} is recursive", self);
1621             // This should be reported as an error by `check_representable`.
1622             //
1623             // Consider the type as Sized in the meanwhile to avoid
1624             // further errors.
1625             tcx.adt_sized_constraint.borrow_mut().insert(self.did, tcx.types.err);
1626             return tcx.types.err;
1627         }
1628
1629         stack.push(self.did);
1630
1631         let tys : Vec<_> =
1632             self.variants.iter().flat_map(|v| {
1633                 v.fields.last()
1634             }).flat_map(|f| {
1635                 let ty = tcx.item_type(f.did);
1636                 self.sized_constraint_for_ty(tcx, stack, ty)
1637             }).collect();
1638
1639         let self_ = stack.pop().unwrap();
1640         assert_eq!(self_, self.did);
1641
1642         let ty = match tys.len() {
1643             _ if tys.references_error() => tcx.types.err,
1644             0 => tcx.types.bool,
1645             1 => tys[0],
1646             _ => tcx.intern_tup(&tys[..], false)
1647         };
1648
1649         let old = tcx.adt_sized_constraint.borrow().get(&self.did).cloned();
1650         match old {
1651             Some(old_ty) => {
1652                 debug!("calculate_sized_constraint: {:?} recurred", self);
1653                 assert_eq!(old_ty, tcx.types.err);
1654                 old_ty
1655             }
1656             None => {
1657                 debug!("calculate_sized_constraint: {:?} => {:?}", self, ty);
1658                 tcx.adt_sized_constraint.borrow_mut().insert(self.did, ty);
1659                 ty
1660             }
1661         }
1662     }
1663
1664     fn sized_constraint_for_ty(&self,
1665                                tcx: TyCtxt<'a, 'tcx, 'tcx>,
1666                                stack: &mut Vec<DefId>,
1667                                ty: Ty<'tcx>)
1668                                -> Vec<Ty<'tcx>> {
1669         let result = match ty.sty {
1670             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
1671             TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
1672             TyArray(..) | TyClosure(..) | TyNever => {
1673                 vec![]
1674             }
1675
1676             TyStr | TyDynamic(..) | TySlice(_) | TyError => {
1677                 // these are never sized - return the target type
1678                 vec![ty]
1679             }
1680
1681             TyTuple(ref tys, _) => {
1682                 match tys.last() {
1683                     None => vec![],
1684                     Some(ty) => self.sized_constraint_for_ty(tcx, stack, ty)
1685                 }
1686             }
1687
1688             TyAdt(adt, substs) => {
1689                 // recursive case
1690                 let adt_ty =
1691                     adt.calculate_sized_constraint_inner(tcx, stack)
1692                        .subst(tcx, substs);
1693                 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
1694                        ty, adt_ty);
1695                 if let ty::TyTuple(ref tys, _) = adt_ty.sty {
1696                     tys.iter().flat_map(|ty| {
1697                         self.sized_constraint_for_ty(tcx, stack, ty)
1698                     }).collect()
1699                 } else {
1700                     self.sized_constraint_for_ty(tcx, stack, adt_ty)
1701                 }
1702             }
1703
1704             TyProjection(..) | TyAnon(..) => {
1705                 // must calculate explicitly.
1706                 // FIXME: consider special-casing always-Sized projections
1707                 vec![ty]
1708             }
1709
1710             TyParam(..) => {
1711                 // perf hack: if there is a `T: Sized` bound, then
1712                 // we know that `T` is Sized and do not need to check
1713                 // it on the impl.
1714
1715                 let sized_trait = match tcx.lang_items.sized_trait() {
1716                     Some(x) => x,
1717                     _ => return vec![ty]
1718                 };
1719                 let sized_predicate = Binder(TraitRef {
1720                     def_id: sized_trait,
1721                     substs: tcx.mk_substs_trait(ty, &[])
1722                 }).to_predicate();
1723                 let predicates = tcx.item_predicates(self.did).predicates;
1724                 if predicates.into_iter().any(|p| p == sized_predicate) {
1725                     vec![]
1726                 } else {
1727                     vec![ty]
1728                 }
1729             }
1730
1731             TyInfer(..) => {
1732                 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
1733                      ty)
1734             }
1735         };
1736         debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
1737         result
1738     }
1739 }
1740
1741 impl<'a, 'gcx, 'tcx> VariantDef {
1742     #[inline]
1743     pub fn find_field_named(&self,
1744                             name: ast::Name)
1745                             -> Option<&FieldDef> {
1746         self.fields.iter().find(|f| f.name == name)
1747     }
1748
1749     #[inline]
1750     pub fn index_of_field_named(&self,
1751                                 name: ast::Name)
1752                                 -> Option<usize> {
1753         self.fields.iter().position(|f| f.name == name)
1754     }
1755
1756     #[inline]
1757     pub fn field_named(&self, name: ast::Name) -> &FieldDef {
1758         self.find_field_named(name).unwrap()
1759     }
1760 }
1761
1762 impl<'a, 'gcx, 'tcx> FieldDef {
1763     pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1764         tcx.item_type(self.did).subst(tcx, subst)
1765     }
1766 }
1767
1768 /// Records the substitutions used to translate the polytype for an
1769 /// item into the monotype of an item reference.
1770 #[derive(Clone, RustcEncodable, RustcDecodable)]
1771 pub struct ItemSubsts<'tcx> {
1772     pub substs: &'tcx Substs<'tcx>,
1773 }
1774
1775 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1776 pub enum ClosureKind {
1777     // Warning: Ordering is significant here! The ordering is chosen
1778     // because the trait Fn is a subtrait of FnMut and so in turn, and
1779     // hence we order it so that Fn < FnMut < FnOnce.
1780     Fn,
1781     FnMut,
1782     FnOnce,
1783 }
1784
1785 impl<'a, 'tcx> ClosureKind {
1786     pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
1787         match *self {
1788             ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
1789             ClosureKind::FnMut => {
1790                 tcx.require_lang_item(FnMutTraitLangItem)
1791             }
1792             ClosureKind::FnOnce => {
1793                 tcx.require_lang_item(FnOnceTraitLangItem)
1794             }
1795         }
1796     }
1797
1798     /// True if this a type that impls this closure kind
1799     /// must also implement `other`.
1800     pub fn extends(self, other: ty::ClosureKind) -> bool {
1801         match (self, other) {
1802             (ClosureKind::Fn, ClosureKind::Fn) => true,
1803             (ClosureKind::Fn, ClosureKind::FnMut) => true,
1804             (ClosureKind::Fn, ClosureKind::FnOnce) => true,
1805             (ClosureKind::FnMut, ClosureKind::FnMut) => true,
1806             (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
1807             (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
1808             _ => false,
1809         }
1810     }
1811 }
1812
1813 impl<'tcx> TyS<'tcx> {
1814     /// Iterator that walks `self` and any types reachable from
1815     /// `self`, in depth-first order. Note that just walks the types
1816     /// that appear in `self`, it does not descend into the fields of
1817     /// structs or variants. For example:
1818     ///
1819     /// ```notrust
1820     /// isize => { isize }
1821     /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
1822     /// [isize] => { [isize], isize }
1823     /// ```
1824     pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
1825         TypeWalker::new(self)
1826     }
1827
1828     /// Iterator that walks the immediate children of `self`.  Hence
1829     /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
1830     /// (but not `i32`, like `walk`).
1831     pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
1832         walk::walk_shallow(self)
1833     }
1834
1835     /// Walks `ty` and any types appearing within `ty`, invoking the
1836     /// callback `f` on each type. If the callback returns false, then the
1837     /// children of the current type are ignored.
1838     ///
1839     /// Note: prefer `ty.walk()` where possible.
1840     pub fn maybe_walk<F>(&'tcx self, mut f: F)
1841         where F : FnMut(Ty<'tcx>) -> bool
1842     {
1843         let mut walker = self.walk();
1844         while let Some(ty) = walker.next() {
1845             if !f(ty) {
1846                 walker.skip_current_subtree();
1847             }
1848         }
1849     }
1850 }
1851
1852 impl<'tcx> ItemSubsts<'tcx> {
1853     pub fn is_noop(&self) -> bool {
1854         self.substs.is_noop()
1855     }
1856 }
1857
1858 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1859 pub enum LvaluePreference {
1860     PreferMutLvalue,
1861     NoPreference
1862 }
1863
1864 impl LvaluePreference {
1865     pub fn from_mutbl(m: hir::Mutability) -> Self {
1866         match m {
1867             hir::MutMutable => PreferMutLvalue,
1868             hir::MutImmutable => NoPreference,
1869         }
1870     }
1871 }
1872
1873 /// Helper for looking things up in the various maps that are populated during
1874 /// typeck::collect (e.g., `tcx.associated_items`, `tcx.types`, etc).  All of
1875 /// these share the pattern that if the id is local, it should have been loaded
1876 /// into the map by the `typeck::collect` phase.  If the def-id is external,
1877 /// then we have to go consult the crate loading code (and cache the result for
1878 /// the future).
1879 fn lookup_locally_or_in_crate_store<M, F>(descr: &str,
1880                                           def_id: DefId,
1881                                           map: &M,
1882                                           load_external: F)
1883                                           -> M::Value where
1884     M: MemoizationMap<Key=DefId>,
1885     F: FnOnce() -> M::Value,
1886 {
1887     map.memoize(def_id, || {
1888         if def_id.is_local() {
1889             bug!("No def'n found for {:?} in tcx.{}", def_id, descr);
1890         }
1891         load_external()
1892     })
1893 }
1894
1895 impl BorrowKind {
1896     pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
1897         match m {
1898             hir::MutMutable => MutBorrow,
1899             hir::MutImmutable => ImmBorrow,
1900         }
1901     }
1902
1903     /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
1904     /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
1905     /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
1906     /// question.
1907     pub fn to_mutbl_lossy(self) -> hir::Mutability {
1908         match self {
1909             MutBorrow => hir::MutMutable,
1910             ImmBorrow => hir::MutImmutable,
1911
1912             // We have no type corresponding to a unique imm borrow, so
1913             // use `&mut`. It gives all the capabilities of an `&uniq`
1914             // and hence is a safe "over approximation".
1915             UniqueImmBorrow => hir::MutMutable,
1916         }
1917     }
1918
1919     pub fn to_user_str(&self) -> &'static str {
1920         match *self {
1921             MutBorrow => "mutable",
1922             ImmBorrow => "immutable",
1923             UniqueImmBorrow => "uniquely immutable",
1924         }
1925     }
1926 }
1927
1928 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1929     pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
1930         self.item_tables(self.hir.body_owner_def_id(body))
1931     }
1932
1933     pub fn item_tables(self, def_id: DefId) -> &'gcx TypeckTables<'gcx> {
1934         self.tables.memoize(def_id, || {
1935             if def_id.is_local() {
1936                 // Closures' tables come from their outermost function,
1937                 // as they are part of the same "inference environment".
1938                 let outer_def_id = self.closure_base_def_id(def_id);
1939                 if outer_def_id != def_id {
1940                     return self.item_tables(outer_def_id);
1941                 }
1942
1943                 bug!("No def'n found for {:?} in tcx.tables", def_id);
1944             }
1945
1946             // Cross-crate side-tables only exist alongside serialized HIR.
1947             self.sess.cstore.maybe_get_item_body(self.global_tcx(), def_id).map(|_| {
1948                 self.tables.borrow()[&def_id]
1949             }).unwrap_or_else(|| {
1950                 bug!("tcx.item_tables({:?}): missing from metadata", def_id)
1951             })
1952         })
1953     }
1954
1955     pub fn expr_span(self, id: NodeId) -> Span {
1956         match self.hir.find(id) {
1957             Some(hir_map::NodeExpr(e)) => {
1958                 e.span
1959             }
1960             Some(f) => {
1961                 bug!("Node id {} is not an expr: {:?}", id, f);
1962             }
1963             None => {
1964                 bug!("Node id {} is not present in the node map", id);
1965             }
1966         }
1967     }
1968
1969     pub fn local_var_name_str(self, id: NodeId) -> InternedString {
1970         match self.hir.find(id) {
1971             Some(hir_map::NodeLocal(pat)) => {
1972                 match pat.node {
1973                     hir::PatKind::Binding(_, _, ref path1, _) => path1.node.as_str(),
1974                     _ => {
1975                         bug!("Variable id {} maps to {:?}, not local", id, pat);
1976                     },
1977                 }
1978             },
1979             r => bug!("Variable id {} maps to {:?}, not local", id, r),
1980         }
1981     }
1982
1983     pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
1984          match expr.node {
1985             hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
1986                 match path.def {
1987                     Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
1988                     _ => false,
1989                 }
1990             }
1991
1992             hir::ExprType(ref e, _) => {
1993                 self.expr_is_lval(e)
1994             }
1995
1996             hir::ExprUnary(hir::UnDeref, _) |
1997             hir::ExprField(..) |
1998             hir::ExprTupField(..) |
1999             hir::ExprIndex(..) => {
2000                 true
2001             }
2002
2003             // Partially qualified paths in expressions can only legally
2004             // refer to associated items which are always rvalues.
2005             hir::ExprPath(hir::QPath::TypeRelative(..)) |
2006
2007             hir::ExprCall(..) |
2008             hir::ExprMethodCall(..) |
2009             hir::ExprStruct(..) |
2010             hir::ExprTup(..) |
2011             hir::ExprIf(..) |
2012             hir::ExprMatch(..) |
2013             hir::ExprClosure(..) |
2014             hir::ExprBlock(..) |
2015             hir::ExprRepeat(..) |
2016             hir::ExprArray(..) |
2017             hir::ExprBreak(..) |
2018             hir::ExprAgain(..) |
2019             hir::ExprRet(..) |
2020             hir::ExprWhile(..) |
2021             hir::ExprLoop(..) |
2022             hir::ExprAssign(..) |
2023             hir::ExprInlineAsm(..) |
2024             hir::ExprAssignOp(..) |
2025             hir::ExprLit(_) |
2026             hir::ExprUnary(..) |
2027             hir::ExprBox(..) |
2028             hir::ExprAddrOf(..) |
2029             hir::ExprBinary(..) |
2030             hir::ExprCast(..) => {
2031                 false
2032             }
2033         }
2034     }
2035
2036     pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2037         self.associated_items(id)
2038             .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2039             .collect()
2040     }
2041
2042     pub fn trait_impl_polarity(self, id: DefId) -> hir::ImplPolarity {
2043         if let Some(id) = self.hir.as_local_node_id(id) {
2044             match self.hir.expect_item(id).node {
2045                 hir::ItemImpl(_, polarity, ..) => polarity,
2046                 ref item => bug!("trait_impl_polarity: {:?} not an impl", item)
2047             }
2048         } else {
2049             self.sess.cstore.impl_polarity(id)
2050         }
2051     }
2052
2053     pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2054         self.associated_items(did).any(|item| {
2055             item.relevant_for_never()
2056         })
2057     }
2058
2059     pub fn custom_coerce_unsized_kind(self, did: DefId) -> adjustment::CustomCoerceUnsized {
2060         self.custom_coerce_unsized_kinds.memoize(did, || {
2061             let (kind, src) = if did.krate != LOCAL_CRATE {
2062                 (self.sess.cstore.custom_coerce_unsized_kind(did), "external")
2063             } else {
2064                 (None, "local")
2065             };
2066
2067             match kind {
2068                 Some(kind) => kind,
2069                 None => {
2070                     bug!("custom_coerce_unsized_kind: \
2071                           {} impl `{}` is missing its kind",
2072                           src, self.item_path_str(did));
2073                 }
2074             }
2075         })
2076     }
2077
2078     pub fn associated_item(self, def_id: DefId) -> AssociatedItem {
2079         self.associated_items.memoize(def_id, || {
2080             if !def_id.is_local() {
2081                 return self.sess.cstore.associated_item(def_id)
2082                            .expect("missing AssociatedItem in metadata");
2083             }
2084
2085             // When the user asks for a given associated item, we
2086             // always go ahead and convert all the associated items in
2087             // the container. Note that we are also careful only to
2088             // ever register a read on the *container* of the assoc
2089             // item, not the assoc item itself. This prevents changes
2090             // in the details of an item (for example, the type to
2091             // which an associated type is bound) from contaminating
2092             // those tasks that just need to scan the names of items
2093             // and so forth.
2094
2095             let id = self.hir.as_local_node_id(def_id).unwrap();
2096             let parent_id = self.hir.get_parent(id);
2097             let parent_def_id = self.hir.local_def_id(parent_id);
2098             let parent_item = self.hir.expect_item(parent_id);
2099             match parent_item.node {
2100                 hir::ItemImpl(.., ref impl_trait_ref, _, ref impl_item_refs) => {
2101                     for impl_item_ref in impl_item_refs {
2102                         let assoc_item =
2103                             self.associated_item_from_impl_item_ref(parent_def_id,
2104                                                                     impl_trait_ref.is_some(),
2105                                                                     impl_item_ref);
2106                         self.associated_items.borrow_mut().insert(assoc_item.def_id, assoc_item);
2107                     }
2108                 }
2109
2110                 hir::ItemTrait(.., ref trait_item_refs) => {
2111                     for trait_item_ref in trait_item_refs {
2112                         let assoc_item =
2113                             self.associated_item_from_trait_item_ref(parent_def_id, trait_item_ref);
2114                         self.associated_items.borrow_mut().insert(assoc_item.def_id, assoc_item);
2115                     }
2116                 }
2117
2118                 ref r => {
2119                     panic!("unexpected container of associated items: {:?}", r)
2120                 }
2121             }
2122
2123             // memoize wants us to return something, so return
2124             // the one we generated for this def-id
2125             *self.associated_items.borrow().get(&def_id).unwrap()
2126         })
2127     }
2128
2129     fn associated_item_from_trait_item_ref(self,
2130                                            parent_def_id: DefId,
2131                                            trait_item_ref: &hir::TraitItemRef)
2132                                            -> AssociatedItem {
2133         let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2134         let (kind, has_self) = match trait_item_ref.kind {
2135             hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2136             hir::AssociatedItemKind::Method { has_self } => {
2137                 (ty::AssociatedKind::Method, has_self)
2138             }
2139             hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2140         };
2141
2142         AssociatedItem {
2143             name: trait_item_ref.name,
2144             kind: kind,
2145             vis: Visibility::from_hir(&hir::Inherited, trait_item_ref.id.node_id, self),
2146             defaultness: trait_item_ref.defaultness,
2147             def_id: def_id,
2148             container: TraitContainer(parent_def_id),
2149             method_has_self_argument: has_self
2150         }
2151     }
2152
2153     fn associated_item_from_impl_item_ref(self,
2154                                           parent_def_id: DefId,
2155                                           from_trait_impl: bool,
2156                                           impl_item_ref: &hir::ImplItemRef)
2157                                           -> AssociatedItem {
2158         let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2159         let (kind, has_self) = match impl_item_ref.kind {
2160             hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2161             hir::AssociatedItemKind::Method { has_self } => {
2162                 (ty::AssociatedKind::Method, has_self)
2163             }
2164             hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2165         };
2166
2167         // Trait impl items are always public.
2168         let public = hir::Public;
2169         let vis = if from_trait_impl { &public } else { &impl_item_ref.vis };
2170
2171         ty::AssociatedItem {
2172             name: impl_item_ref.name,
2173             kind: kind,
2174             vis: ty::Visibility::from_hir(vis, impl_item_ref.id.node_id, self),
2175             defaultness: impl_item_ref.defaultness,
2176             def_id: def_id,
2177             container: ImplContainer(parent_def_id),
2178             method_has_self_argument: has_self
2179         }
2180     }
2181
2182     pub fn associated_item_def_ids(self, def_id: DefId) -> Rc<Vec<DefId>> {
2183         self.associated_item_def_ids.memoize(def_id, || {
2184             if !def_id.is_local() {
2185                 return Rc::new(self.sess.cstore.associated_item_def_ids(def_id));
2186             }
2187
2188             let id = self.hir.as_local_node_id(def_id).unwrap();
2189             let item = self.hir.expect_item(id);
2190             let vec: Vec<_> = match item.node {
2191                 hir::ItemTrait(.., ref trait_item_refs) => {
2192                     trait_item_refs.iter()
2193                                    .map(|trait_item_ref| trait_item_ref.id)
2194                                    .map(|id| self.hir.local_def_id(id.node_id))
2195                                    .collect()
2196                 }
2197                 hir::ItemImpl(.., ref impl_item_refs) => {
2198                     impl_item_refs.iter()
2199                                   .map(|impl_item_ref| impl_item_ref.id)
2200                                   .map(|id| self.hir.local_def_id(id.node_id))
2201                                   .collect()
2202                 }
2203                 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2204             };
2205             Rc::new(vec)
2206         })
2207     }
2208
2209     #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2210     pub fn associated_items(self, def_id: DefId)
2211                             -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2212         let def_ids = self.associated_item_def_ids(def_id);
2213         (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2214     }
2215
2216     /// Returns the trait-ref corresponding to a given impl, or None if it is
2217     /// an inherent impl.
2218     pub fn impl_trait_ref(self, id: DefId) -> Option<TraitRef<'gcx>> {
2219         lookup_locally_or_in_crate_store(
2220             "impl_trait_refs", id, &self.impl_trait_refs,
2221             || self.sess.cstore.impl_trait_ref(self.global_tcx(), id))
2222     }
2223
2224     // Returns `ty::VariantDef` if `def` refers to a struct,
2225     // or variant or their constructors, panics otherwise.
2226     pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2227         match def {
2228             Def::Variant(did) | Def::VariantCtor(did, ..) => {
2229                 let enum_did = self.parent_def_id(did).unwrap();
2230                 self.lookup_adt_def(enum_did).variant_with_id(did)
2231             }
2232             Def::Struct(did) | Def::Union(did) => {
2233                 self.lookup_adt_def(did).struct_variant()
2234             }
2235             Def::StructCtor(ctor_did, ..) => {
2236                 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2237                 self.lookup_adt_def(did).struct_variant()
2238             }
2239             _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2240         }
2241     }
2242
2243     pub fn def_key(self, id: DefId) -> hir_map::DefKey {
2244         if id.is_local() {
2245             self.hir.def_key(id)
2246         } else {
2247             self.sess.cstore.def_key(id)
2248         }
2249     }
2250
2251     /// Convert a `DefId` into its fully expanded `DefPath` (every
2252     /// `DefId` is really just an interned def-path).
2253     ///
2254     /// Note that if `id` is not local to this crate, the result will
2255     //  be a non-local `DefPath`.
2256     pub fn def_path(self, id: DefId) -> hir_map::DefPath {
2257         if id.is_local() {
2258             self.hir.def_path(id)
2259         } else {
2260             self.sess.cstore.def_path(id)
2261         }
2262     }
2263
2264     pub fn def_span(self, def_id: DefId) -> Span {
2265         if let Some(id) = self.hir.as_local_node_id(def_id) {
2266             self.hir.span(id)
2267         } else {
2268             self.sess.cstore.def_span(&self.sess, def_id)
2269         }
2270     }
2271
2272     pub fn vis_is_accessible_from(self, vis: Visibility, block: NodeId) -> bool {
2273         vis.is_accessible_from(self.hir.local_def_id(self.hir.get_module_parent(block)), self)
2274     }
2275
2276     pub fn item_name(self, id: DefId) -> ast::Name {
2277         if let Some(id) = self.hir.as_local_node_id(id) {
2278             self.hir.name(id)
2279         } else if id.index == CRATE_DEF_INDEX {
2280             self.sess.cstore.original_crate_name(id.krate)
2281         } else {
2282             let def_key = self.sess.cstore.def_key(id);
2283             // The name of a StructCtor is that of its struct parent.
2284             if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2285                 self.item_name(DefId {
2286                     krate: id.krate,
2287                     index: def_key.parent.unwrap()
2288                 })
2289             } else {
2290                 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2291                     bug!("item_name: no name for {:?}", self.def_path(id));
2292                 })
2293             }
2294         }
2295     }
2296
2297     // If the given item is in an external crate, looks up its type and adds it to
2298     // the type cache. Returns the type parameters and type.
2299     pub fn item_type(self, did: DefId) -> Ty<'gcx> {
2300         lookup_locally_or_in_crate_store(
2301             "item_types", did, &self.item_types,
2302             || self.sess.cstore.item_type(self.global_tcx(), did))
2303     }
2304
2305     /// Given the did of a trait, returns its canonical trait ref.
2306     pub fn lookup_trait_def(self, did: DefId) -> &'gcx TraitDef {
2307         lookup_locally_or_in_crate_store(
2308             "trait_defs", did, &self.trait_defs,
2309             || self.alloc_trait_def(self.sess.cstore.trait_def(self.global_tcx(), did))
2310         )
2311     }
2312
2313     /// Given the did of an ADT, return a reference to its definition.
2314     pub fn lookup_adt_def(self, did: DefId) -> &'gcx AdtDef {
2315         lookup_locally_or_in_crate_store(
2316             "adt_defs", did, &self.adt_defs,
2317             || self.sess.cstore.adt_def(self.global_tcx(), did))
2318     }
2319
2320     /// Given the did of an item, returns its generics.
2321     pub fn item_generics(self, did: DefId) -> &'gcx Generics<'gcx> {
2322         lookup_locally_or_in_crate_store(
2323             "generics", did, &self.generics,
2324             || self.alloc_generics(self.sess.cstore.item_generics(self.global_tcx(), did)))
2325     }
2326
2327     /// Given the did of an item, returns its full set of predicates.
2328     pub fn item_predicates(self, did: DefId) -> GenericPredicates<'gcx> {
2329         lookup_locally_or_in_crate_store(
2330             "predicates", did, &self.predicates,
2331             || self.sess.cstore.item_predicates(self.global_tcx(), did))
2332     }
2333
2334     /// Given the did of a trait, returns its superpredicates.
2335     pub fn item_super_predicates(self, did: DefId) -> GenericPredicates<'gcx> {
2336         lookup_locally_or_in_crate_store(
2337             "super_predicates", did, &self.super_predicates,
2338             || self.sess.cstore.item_super_predicates(self.global_tcx(), did))
2339     }
2340
2341     /// Given the did of an item, returns its MIR, borrowed immutably.
2342     pub fn item_mir(self, did: DefId) -> Ref<'gcx, Mir<'gcx>> {
2343         lookup_locally_or_in_crate_store("mir_map", did, &self.mir_map, || {
2344             let mir = self.sess.cstore.get_item_mir(self.global_tcx(), did);
2345             let mir = self.alloc_mir(mir);
2346
2347             // Perma-borrow MIR from extern crates to prevent mutation.
2348             mem::forget(mir.borrow());
2349
2350             mir
2351         }).borrow()
2352     }
2353
2354     /// If `type_needs_drop` returns true, then `ty` is definitely
2355     /// non-copy and *might* have a destructor attached; if it returns
2356     /// false, then `ty` definitely has no destructor (i.e. no drop glue).
2357     ///
2358     /// (Note that this implies that if `ty` has a destructor attached,
2359     /// then `type_needs_drop` will definitely return `true` for `ty`.)
2360     pub fn type_needs_drop_given_env(self,
2361                                      ty: Ty<'gcx>,
2362                                      param_env: &ty::ParameterEnvironment<'gcx>) -> bool {
2363         // Issue #22536: We first query type_moves_by_default.  It sees a
2364         // normalized version of the type, and therefore will definitely
2365         // know whether the type implements Copy (and thus needs no
2366         // cleanup/drop/zeroing) ...
2367         let tcx = self.global_tcx();
2368         let implements_copy = !ty.moves_by_default(tcx, param_env, DUMMY_SP);
2369
2370         if implements_copy { return false; }
2371
2372         // ... (issue #22536 continued) but as an optimization, still use
2373         // prior logic of asking if the `needs_drop` bit is set; we need
2374         // not zero non-Copy types if they have no destructor.
2375
2376         // FIXME(#22815): Note that calling `ty::type_contents` is a
2377         // conservative heuristic; it may report that `needs_drop` is set
2378         // when actual type does not actually have a destructor associated
2379         // with it. But since `ty` absolutely did not have the `Copy`
2380         // bound attached (see above), it is sound to treat it as having a
2381         // destructor (e.g. zero its memory on move).
2382
2383         let contents = ty.type_contents(tcx);
2384         debug!("type_needs_drop ty={:?} contents={:?}", ty, contents);
2385         contents.needs_drop(tcx)
2386     }
2387
2388     /// Get the attributes of a definition.
2389     pub fn get_attrs(self, did: DefId) -> Cow<'gcx, [ast::Attribute]> {
2390         if let Some(id) = self.hir.as_local_node_id(did) {
2391             Cow::Borrowed(self.hir.attrs(id))
2392         } else {
2393             Cow::Owned(self.sess.cstore.item_attrs(did))
2394         }
2395     }
2396
2397     /// Determine whether an item is annotated with an attribute
2398     pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2399         self.get_attrs(did).iter().any(|item| item.check_name(attr))
2400     }
2401
2402     /// Determine whether an item is annotated with `#[repr(packed)]`
2403     pub fn lookup_packed(self, did: DefId) -> bool {
2404         self.lookup_repr_hints(did).contains(&attr::ReprPacked)
2405     }
2406
2407     /// Determine whether an item is annotated with `#[simd]`
2408     pub fn lookup_simd(self, did: DefId) -> bool {
2409         self.has_attr(did, "simd")
2410             || self.lookup_repr_hints(did).contains(&attr::ReprSimd)
2411     }
2412
2413     pub fn item_variances(self, item_id: DefId) -> Rc<Vec<ty::Variance>> {
2414         lookup_locally_or_in_crate_store(
2415             "item_variance_map", item_id, &self.item_variance_map,
2416             || Rc::new(self.sess.cstore.item_variances(item_id)))
2417     }
2418
2419     pub fn trait_has_default_impl(self, trait_def_id: DefId) -> bool {
2420         self.populate_implementations_for_trait_if_necessary(trait_def_id);
2421
2422         let def = self.lookup_trait_def(trait_def_id);
2423         def.flags.get().intersects(TraitFlags::HAS_DEFAULT_IMPL)
2424     }
2425
2426     /// Records a trait-to-implementation mapping.
2427     pub fn record_trait_has_default_impl(self, trait_def_id: DefId) {
2428         let def = self.lookup_trait_def(trait_def_id);
2429         def.flags.set(def.flags.get() | TraitFlags::HAS_DEFAULT_IMPL)
2430     }
2431
2432     /// Populates the type context with all the inherent implementations for
2433     /// the given type if necessary.
2434     pub fn populate_inherent_implementations_for_type_if_necessary(self,
2435                                                                    type_id: DefId) {
2436         if type_id.is_local() {
2437             return
2438         }
2439
2440         // The type is not local, hence we are reading this out of
2441         // metadata and don't need to track edges.
2442         let _ignore = self.dep_graph.in_ignore();
2443
2444         if self.populated_external_types.borrow().contains(&type_id) {
2445             return
2446         }
2447
2448         debug!("populate_inherent_implementations_for_type_if_necessary: searching for {:?}",
2449                type_id);
2450
2451         let inherent_impls = self.sess.cstore.inherent_implementations_for_type(type_id);
2452
2453         self.inherent_impls.borrow_mut().insert(type_id, inherent_impls);
2454         self.populated_external_types.borrow_mut().insert(type_id);
2455     }
2456
2457     /// Populates the type context with all the implementations for the given
2458     /// trait if necessary.
2459     pub fn populate_implementations_for_trait_if_necessary(self, trait_id: DefId) {
2460         if trait_id.is_local() {
2461             return
2462         }
2463
2464         // The type is not local, hence we are reading this out of
2465         // metadata and don't need to track edges.
2466         let _ignore = self.dep_graph.in_ignore();
2467
2468         let def = self.lookup_trait_def(trait_id);
2469         if def.flags.get().intersects(TraitFlags::IMPLS_VALID) {
2470             return;
2471         }
2472
2473         debug!("populate_implementations_for_trait_if_necessary: searching for {:?}", def);
2474
2475         if self.sess.cstore.is_defaulted_trait(trait_id) {
2476             self.record_trait_has_default_impl(trait_id);
2477         }
2478
2479         for impl_def_id in self.sess.cstore.implementations_of_trait(Some(trait_id)) {
2480             let trait_ref = self.impl_trait_ref(impl_def_id).unwrap();
2481
2482             // Record the trait->implementation mapping.
2483             let parent = self.sess.cstore.impl_parent(impl_def_id).unwrap_or(trait_id);
2484             def.record_remote_impl(self, impl_def_id, trait_ref, parent);
2485         }
2486
2487         def.flags.set(def.flags.get() | TraitFlags::IMPLS_VALID);
2488     }
2489
2490     pub fn closure_kind(self, def_id: DefId) -> ty::ClosureKind {
2491         // If this is a local def-id, it should be inserted into the
2492         // tables by typeck; else, it will be retreived from
2493         // the external crate metadata.
2494         if let Some(&kind) = self.closure_kinds.borrow().get(&def_id) {
2495             return kind;
2496         }
2497
2498         let kind = self.sess.cstore.closure_kind(def_id);
2499         self.closure_kinds.borrow_mut().insert(def_id, kind);
2500         kind
2501     }
2502
2503     pub fn closure_type(self,
2504                         def_id: DefId,
2505                         substs: ClosureSubsts<'tcx>)
2506                         -> ty::ClosureTy<'tcx>
2507     {
2508         // If this is a local def-id, it should be inserted into the
2509         // tables by typeck; else, it will be retreived from
2510         // the external crate metadata.
2511         if let Some(ty) = self.closure_tys.borrow().get(&def_id) {
2512             return ty.subst(self, substs.substs);
2513         }
2514
2515         let ty = self.sess.cstore.closure_ty(self.global_tcx(), def_id);
2516         self.closure_tys.borrow_mut().insert(def_id, ty.clone());
2517         ty.subst(self, substs.substs)
2518     }
2519
2520     /// Given the def_id of an impl, return the def_id of the trait it implements.
2521     /// If it implements no trait, return `None`.
2522     pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2523         self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2524     }
2525
2526     /// If the given def ID describes a method belonging to an impl, return the
2527     /// ID of the impl that the method belongs to. Otherwise, return `None`.
2528     pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2529         if def_id.krate != LOCAL_CRATE {
2530             return self.sess.cstore.associated_item(def_id).and_then(|item| {
2531                 match item.container {
2532                     TraitContainer(_) => None,
2533                     ImplContainer(def_id) => Some(def_id),
2534                 }
2535             });
2536         }
2537         match self.associated_items.borrow().get(&def_id).cloned() {
2538             Some(trait_item) => {
2539                 match trait_item.container {
2540                     TraitContainer(_) => None,
2541                     ImplContainer(def_id) => Some(def_id),
2542                 }
2543             }
2544             None => None
2545         }
2546     }
2547
2548     /// If the given def ID describes an item belonging to a trait,
2549     /// return the ID of the trait that the trait item belongs to.
2550     /// Otherwise, return `None`.
2551     pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
2552         if def_id.krate != LOCAL_CRATE {
2553             return self.sess.cstore.trait_of_item(def_id);
2554         }
2555         match self.associated_items.borrow().get(&def_id) {
2556             Some(associated_item) => {
2557                 match associated_item.container {
2558                     TraitContainer(def_id) => Some(def_id),
2559                     ImplContainer(_) => None
2560                 }
2561             }
2562             None => None
2563         }
2564     }
2565
2566     /// Construct a parameter environment suitable for static contexts or other contexts where there
2567     /// are no free type/lifetime parameters in scope.
2568     pub fn empty_parameter_environment(self) -> ParameterEnvironment<'tcx> {
2569
2570         // for an empty parameter environment, there ARE no free
2571         // regions, so it shouldn't matter what we use for the free id
2572         let free_id_outlive = self.region_maps.node_extent(ast::DUMMY_NODE_ID);
2573         ty::ParameterEnvironment {
2574             free_substs: self.intern_substs(&[]),
2575             caller_bounds: Vec::new(),
2576             implicit_region_bound: self.mk_region(ty::ReEmpty),
2577             free_id_outlive: free_id_outlive,
2578             is_copy_cache: RefCell::new(FxHashMap()),
2579             is_sized_cache: RefCell::new(FxHashMap()),
2580         }
2581     }
2582
2583     /// Constructs and returns a substitution that can be applied to move from
2584     /// the "outer" view of a type or method to the "inner" view.
2585     /// In general, this means converting from bound parameters to
2586     /// free parameters. Since we currently represent bound/free type
2587     /// parameters in the same way, this only has an effect on regions.
2588     pub fn construct_free_substs(self, def_id: DefId,
2589                                  free_id_outlive: CodeExtent)
2590                                  -> &'gcx Substs<'gcx> {
2591
2592         let substs = Substs::for_item(self.global_tcx(), def_id, |def, _| {
2593             // map bound 'a => free 'a
2594             self.global_tcx().mk_region(ReFree(FreeRegion {
2595                 scope: free_id_outlive,
2596                 bound_region: def.to_bound_region()
2597             }))
2598         }, |def, _| {
2599             // map T => T
2600             self.global_tcx().mk_param_from_def(def)
2601         });
2602
2603         debug!("construct_parameter_environment: {:?}", substs);
2604         substs
2605     }
2606
2607     /// See `ParameterEnvironment` struct def'n for details.
2608     /// If you were using `free_id: NodeId`, you might try `self.region_maps.item_extent(free_id)`
2609     /// for the `free_id_outlive` parameter. (But note that this is not always quite right.)
2610     pub fn construct_parameter_environment(self,
2611                                            span: Span,
2612                                            def_id: DefId,
2613                                            free_id_outlive: CodeExtent)
2614                                            -> ParameterEnvironment<'gcx>
2615     {
2616         //
2617         // Construct the free substs.
2618         //
2619
2620         let free_substs = self.construct_free_substs(def_id, free_id_outlive);
2621
2622         //
2623         // Compute the bounds on Self and the type parameters.
2624         //
2625
2626         let tcx = self.global_tcx();
2627         let generic_predicates = tcx.item_predicates(def_id);
2628         let bounds = generic_predicates.instantiate(tcx, free_substs);
2629         let bounds = tcx.liberate_late_bound_regions(free_id_outlive, &ty::Binder(bounds));
2630         let predicates = bounds.predicates;
2631
2632         // Finally, we have to normalize the bounds in the environment, in
2633         // case they contain any associated type projections. This process
2634         // can yield errors if the put in illegal associated types, like
2635         // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2636         // report these errors right here; this doesn't actually feel
2637         // right to me, because constructing the environment feels like a
2638         // kind of a "idempotent" action, but I'm not sure where would be
2639         // a better place. In practice, we construct environments for
2640         // every fn once during type checking, and we'll abort if there
2641         // are any errors at that point, so after type checking you can be
2642         // sure that this will succeed without errors anyway.
2643         //
2644
2645         let unnormalized_env = ty::ParameterEnvironment {
2646             free_substs: free_substs,
2647             implicit_region_bound: tcx.mk_region(ty::ReScope(free_id_outlive)),
2648             caller_bounds: predicates,
2649             free_id_outlive: free_id_outlive,
2650             is_copy_cache: RefCell::new(FxHashMap()),
2651             is_sized_cache: RefCell::new(FxHashMap()),
2652         };
2653
2654         let cause = traits::ObligationCause::misc(span, free_id_outlive.node_id(&self.region_maps));
2655         traits::normalize_param_env_or_error(tcx, unnormalized_env, cause)
2656     }
2657
2658     pub fn node_scope_region(self, id: NodeId) -> &'tcx Region {
2659         self.mk_region(ty::ReScope(self.region_maps.node_extent(id)))
2660     }
2661
2662     pub fn visit_all_item_likes_in_krate<V,F>(self,
2663                                               dep_node_fn: F,
2664                                               visitor: &mut V)
2665         where F: FnMut(DefId) -> DepNode<DefId>, V: ItemLikeVisitor<'gcx>
2666     {
2667         dep_graph::visit_all_item_likes_in_krate(self.global_tcx(), dep_node_fn, visitor);
2668     }
2669
2670     /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2671     /// with the name of the crate containing the impl.
2672     pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2673         if impl_did.is_local() {
2674             let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2675             Ok(self.hir.span(node_id))
2676         } else {
2677             Err(self.sess.cstore.crate_name(impl_did.krate))
2678         }
2679     }
2680 }
2681
2682 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2683     pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2684         F: FnOnce(&[hir::Freevar]) -> T,
2685     {
2686         match self.freevars.borrow().get(&fid) {
2687             None => f(&[]),
2688             Some(d) => f(&d[..])
2689         }
2690     }
2691 }