]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/mod.rs
Unignore u128 test for stage 0,1
[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
610     /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
611     /// on generic parameter `'a`, asserts data of lifetime `'a`
612     /// won't be accessed during the parent type's `Drop` impl.
613     pub pure_wrt_drop: bool,
614 }
615
616 impl RegionParameterDef {
617     pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
618         ty::EarlyBoundRegion {
619             index: self.index,
620             name: self.name,
621         }
622     }
623
624     pub fn to_bound_region(&self) -> ty::BoundRegion {
625         // this is an early bound region, so unaffected by #32330
626         ty::BoundRegion::BrNamed(self.def_id, self.name, Issue32330::WontChange)
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 }
1332
1333 impl PartialEq for AdtDef {
1334     // AdtDef are always interned and this is part of TyS equality
1335     #[inline]
1336     fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1337 }
1338
1339 impl Eq for AdtDef {}
1340
1341 impl Hash for AdtDef {
1342     #[inline]
1343     fn hash<H: Hasher>(&self, s: &mut H) {
1344         (self as *const AdtDef).hash(s)
1345     }
1346 }
1347
1348 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1349     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1350         self.did.encode(s)
1351     }
1352 }
1353
1354 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1355
1356 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1357 pub enum AdtKind { Struct, Union, Enum }
1358
1359 impl<'a, 'gcx, 'tcx> AdtDef {
1360     fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1361            did: DefId,
1362            kind: AdtKind,
1363            variants: Vec<VariantDef>) -> Self {
1364         let mut flags = AdtFlags::NO_ADT_FLAGS;
1365         let attrs = tcx.get_attrs(did);
1366         if attr::contains_name(&attrs, "fundamental") {
1367             flags = flags | AdtFlags::IS_FUNDAMENTAL;
1368         }
1369         if tcx.lookup_simd(did) {
1370             flags = flags | AdtFlags::IS_SIMD;
1371         }
1372         if Some(did) == tcx.lang_items.phantom_data() {
1373             flags = flags | AdtFlags::IS_PHANTOM_DATA;
1374         }
1375         if Some(did) == tcx.lang_items.owned_box() {
1376             flags = flags | AdtFlags::IS_BOX;
1377         }
1378         match kind {
1379             AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1380             AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1381             AdtKind::Struct => {}
1382         }
1383         AdtDef {
1384             did: did,
1385             variants: variants,
1386             flags: Cell::new(flags),
1387             destructor: Cell::new(None),
1388         }
1389     }
1390
1391     fn calculate_dtorck(&'gcx self, tcx: TyCtxt) {
1392         if tcx.is_adt_dtorck(self) {
1393             self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK);
1394         }
1395         self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK_VALID)
1396     }
1397
1398     #[inline]
1399     pub fn is_struct(&self) -> bool {
1400         !self.is_union() && !self.is_enum()
1401     }
1402
1403     #[inline]
1404     pub fn is_union(&self) -> bool {
1405         self.flags.get().intersects(AdtFlags::IS_UNION)
1406     }
1407
1408     #[inline]
1409     pub fn is_enum(&self) -> bool {
1410         self.flags.get().intersects(AdtFlags::IS_ENUM)
1411     }
1412
1413     /// Returns the kind of the ADT - Struct or Enum.
1414     #[inline]
1415     pub fn adt_kind(&self) -> AdtKind {
1416         if self.is_enum() {
1417             AdtKind::Enum
1418         } else if self.is_union() {
1419             AdtKind::Union
1420         } else {
1421             AdtKind::Struct
1422         }
1423     }
1424
1425     pub fn descr(&self) -> &'static str {
1426         match self.adt_kind() {
1427             AdtKind::Struct => "struct",
1428             AdtKind::Union => "union",
1429             AdtKind::Enum => "enum",
1430         }
1431     }
1432
1433     pub fn variant_descr(&self) -> &'static str {
1434         match self.adt_kind() {
1435             AdtKind::Struct => "struct",
1436             AdtKind::Union => "union",
1437             AdtKind::Enum => "variant",
1438         }
1439     }
1440
1441     /// Returns whether this is a dtorck type. If this returns
1442     /// true, this type being safe for destruction requires it to be
1443     /// alive; Otherwise, only the contents are required to be.
1444     #[inline]
1445     pub fn is_dtorck(&'gcx self, tcx: TyCtxt) -> bool {
1446         if !self.flags.get().intersects(AdtFlags::IS_DTORCK_VALID) {
1447             self.calculate_dtorck(tcx)
1448         }
1449         self.flags.get().intersects(AdtFlags::IS_DTORCK)
1450     }
1451
1452     /// Returns whether this type is #[fundamental] for the purposes
1453     /// of coherence checking.
1454     #[inline]
1455     pub fn is_fundamental(&self) -> bool {
1456         self.flags.get().intersects(AdtFlags::IS_FUNDAMENTAL)
1457     }
1458
1459     #[inline]
1460     pub fn is_simd(&self) -> bool {
1461         self.flags.get().intersects(AdtFlags::IS_SIMD)
1462     }
1463
1464     /// Returns true if this is PhantomData<T>.
1465     #[inline]
1466     pub fn is_phantom_data(&self) -> bool {
1467         self.flags.get().intersects(AdtFlags::IS_PHANTOM_DATA)
1468     }
1469
1470     /// Returns true if this is Box<T>.
1471     #[inline]
1472     pub fn is_box(&self) -> bool {
1473         self.flags.get().intersects(AdtFlags::IS_BOX)
1474     }
1475
1476     /// Returns whether this type has a destructor.
1477     pub fn has_dtor(&self) -> bool {
1478         self.destructor.get().is_some()
1479     }
1480
1481     /// Asserts this is a struct and returns the struct's unique
1482     /// variant.
1483     pub fn struct_variant(&self) -> &VariantDef {
1484         assert!(!self.is_enum());
1485         &self.variants[0]
1486     }
1487
1488     #[inline]
1489     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1490         tcx.item_predicates(self.did)
1491     }
1492
1493     /// Returns an iterator over all fields contained
1494     /// by this ADT.
1495     #[inline]
1496     pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1497         self.variants.iter().flat_map(|v| v.fields.iter())
1498     }
1499
1500     #[inline]
1501     pub fn is_univariant(&self) -> bool {
1502         self.variants.len() == 1
1503     }
1504
1505     pub fn is_payloadfree(&self) -> bool {
1506         !self.variants.is_empty() &&
1507             self.variants.iter().all(|v| v.fields.is_empty())
1508     }
1509
1510     pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1511         self.variants
1512             .iter()
1513             .find(|v| v.did == vid)
1514             .expect("variant_with_id: unknown variant")
1515     }
1516
1517     pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1518         self.variants
1519             .iter()
1520             .position(|v| v.did == vid)
1521             .expect("variant_index_with_id: unknown variant")
1522     }
1523
1524     pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1525         match def {
1526             Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1527             Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1528             Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.struct_variant(),
1529             _ => bug!("unexpected def {:?} in variant_of_def", def)
1530         }
1531     }
1532
1533     pub fn destructor(&self) -> Option<DefId> {
1534         self.destructor.get()
1535     }
1536
1537     pub fn set_destructor(&self, dtor: DefId) {
1538         self.destructor.set(Some(dtor));
1539     }
1540
1541     /// Returns a simpler type such that `Self: Sized` if and only
1542     /// if that type is Sized, or `TyErr` if this type is recursive.
1543     ///
1544     /// HACK: instead of returning a list of types, this function can
1545     /// return a tuple. In that case, the result is Sized only if
1546     /// all elements of the tuple are Sized.
1547     ///
1548     /// This is generally the `struct_tail` if this is a struct, or a
1549     /// tuple of them if this is an enum.
1550     ///
1551     /// Oddly enough, checking that the sized-constraint is Sized is
1552     /// actually more expressive than checking all members:
1553     /// the Sized trait is inductive, so an associated type that references
1554     /// Self would prevent its containing ADT from being Sized.
1555     ///
1556     /// Due to normalization being eager, this applies even if
1557     /// the associated type is behind a pointer, e.g. issue #31299.
1558     pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1559         self.calculate_sized_constraint_inner(tcx.global_tcx(), &mut Vec::new())
1560     }
1561
1562     /// Calculates the Sized-constraint.
1563     ///
1564     /// As the Sized-constraint of enums can be a *set* of types,
1565     /// the Sized-constraint may need to be a set also. Because introducing
1566     /// a new type of IVar is currently a complex affair, the Sized-constraint
1567     /// may be a tuple.
1568     ///
1569     /// In fact, there are only a few options for the constraint:
1570     ///     - `bool`, if the type is always Sized
1571     ///     - an obviously-unsized type
1572     ///     - a type parameter or projection whose Sizedness can't be known
1573     ///     - a tuple of type parameters or projections, if there are multiple
1574     ///       such.
1575     ///     - a TyError, if a type contained itself. The representability
1576     ///       check should catch this case.
1577     fn calculate_sized_constraint_inner(&self,
1578                                         tcx: TyCtxt<'a, 'tcx, 'tcx>,
1579                                         stack: &mut Vec<DefId>)
1580                                         -> Ty<'tcx>
1581     {
1582         if let Some(ty) = tcx.adt_sized_constraint.borrow().get(&self.did) {
1583             return ty;
1584         }
1585
1586         // Follow the memoization pattern: push the computation of
1587         // DepNode::SizedConstraint as our current task.
1588         let _task = tcx.dep_graph.in_task(DepNode::SizedConstraint(self.did));
1589
1590         if stack.contains(&self.did) {
1591             debug!("calculate_sized_constraint: {:?} is recursive", self);
1592             // This should be reported as an error by `check_representable`.
1593             //
1594             // Consider the type as Sized in the meanwhile to avoid
1595             // further errors.
1596             tcx.adt_sized_constraint.borrow_mut().insert(self.did, tcx.types.err);
1597             return tcx.types.err;
1598         }
1599
1600         stack.push(self.did);
1601
1602         let tys : Vec<_> =
1603             self.variants.iter().flat_map(|v| {
1604                 v.fields.last()
1605             }).flat_map(|f| {
1606                 let ty = tcx.item_type(f.did);
1607                 self.sized_constraint_for_ty(tcx, stack, ty)
1608             }).collect();
1609
1610         let self_ = stack.pop().unwrap();
1611         assert_eq!(self_, self.did);
1612
1613         let ty = match tys.len() {
1614             _ if tys.references_error() => tcx.types.err,
1615             0 => tcx.types.bool,
1616             1 => tys[0],
1617             _ => tcx.intern_tup(&tys[..], false)
1618         };
1619
1620         let old = tcx.adt_sized_constraint.borrow().get(&self.did).cloned();
1621         match old {
1622             Some(old_ty) => {
1623                 debug!("calculate_sized_constraint: {:?} recurred", self);
1624                 assert_eq!(old_ty, tcx.types.err);
1625                 old_ty
1626             }
1627             None => {
1628                 debug!("calculate_sized_constraint: {:?} => {:?}", self, ty);
1629                 tcx.adt_sized_constraint.borrow_mut().insert(self.did, ty);
1630                 ty
1631             }
1632         }
1633     }
1634
1635     fn sized_constraint_for_ty(&self,
1636                                tcx: TyCtxt<'a, 'tcx, 'tcx>,
1637                                stack: &mut Vec<DefId>,
1638                                ty: Ty<'tcx>)
1639                                -> Vec<Ty<'tcx>> {
1640         let result = match ty.sty {
1641             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
1642             TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
1643             TyArray(..) | TyClosure(..) | TyNever => {
1644                 vec![]
1645             }
1646
1647             TyStr | TyDynamic(..) | TySlice(_) | TyError => {
1648                 // these are never sized - return the target type
1649                 vec![ty]
1650             }
1651
1652             TyTuple(ref tys, _) => {
1653                 match tys.last() {
1654                     None => vec![],
1655                     Some(ty) => self.sized_constraint_for_ty(tcx, stack, ty)
1656                 }
1657             }
1658
1659             TyAdt(adt, substs) => {
1660                 // recursive case
1661                 let adt_ty =
1662                     adt.calculate_sized_constraint_inner(tcx, stack)
1663                        .subst(tcx, substs);
1664                 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
1665                        ty, adt_ty);
1666                 if let ty::TyTuple(ref tys, _) = adt_ty.sty {
1667                     tys.iter().flat_map(|ty| {
1668                         self.sized_constraint_for_ty(tcx, stack, ty)
1669                     }).collect()
1670                 } else {
1671                     self.sized_constraint_for_ty(tcx, stack, adt_ty)
1672                 }
1673             }
1674
1675             TyProjection(..) | TyAnon(..) => {
1676                 // must calculate explicitly.
1677                 // FIXME: consider special-casing always-Sized projections
1678                 vec![ty]
1679             }
1680
1681             TyParam(..) => {
1682                 // perf hack: if there is a `T: Sized` bound, then
1683                 // we know that `T` is Sized and do not need to check
1684                 // it on the impl.
1685
1686                 let sized_trait = match tcx.lang_items.sized_trait() {
1687                     Some(x) => x,
1688                     _ => return vec![ty]
1689                 };
1690                 let sized_predicate = Binder(TraitRef {
1691                     def_id: sized_trait,
1692                     substs: tcx.mk_substs_trait(ty, &[])
1693                 }).to_predicate();
1694                 let predicates = tcx.item_predicates(self.did).predicates;
1695                 if predicates.into_iter().any(|p| p == sized_predicate) {
1696                     vec![]
1697                 } else {
1698                     vec![ty]
1699                 }
1700             }
1701
1702             TyInfer(..) => {
1703                 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
1704                      ty)
1705             }
1706         };
1707         debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
1708         result
1709     }
1710 }
1711
1712 impl<'a, 'gcx, 'tcx> VariantDef {
1713     #[inline]
1714     pub fn find_field_named(&self,
1715                             name: ast::Name)
1716                             -> Option<&FieldDef> {
1717         self.fields.iter().find(|f| f.name == name)
1718     }
1719
1720     #[inline]
1721     pub fn index_of_field_named(&self,
1722                                 name: ast::Name)
1723                                 -> Option<usize> {
1724         self.fields.iter().position(|f| f.name == name)
1725     }
1726
1727     #[inline]
1728     pub fn field_named(&self, name: ast::Name) -> &FieldDef {
1729         self.find_field_named(name).unwrap()
1730     }
1731 }
1732
1733 impl<'a, 'gcx, 'tcx> FieldDef {
1734     pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1735         tcx.item_type(self.did).subst(tcx, subst)
1736     }
1737 }
1738
1739 /// Records the substitutions used to translate the polytype for an
1740 /// item into the monotype of an item reference.
1741 #[derive(Clone, RustcEncodable, RustcDecodable)]
1742 pub struct ItemSubsts<'tcx> {
1743     pub substs: &'tcx Substs<'tcx>,
1744 }
1745
1746 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1747 pub enum ClosureKind {
1748     // Warning: Ordering is significant here! The ordering is chosen
1749     // because the trait Fn is a subtrait of FnMut and so in turn, and
1750     // hence we order it so that Fn < FnMut < FnOnce.
1751     Fn,
1752     FnMut,
1753     FnOnce,
1754 }
1755
1756 impl<'a, 'tcx> ClosureKind {
1757     pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
1758         match *self {
1759             ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
1760             ClosureKind::FnMut => {
1761                 tcx.require_lang_item(FnMutTraitLangItem)
1762             }
1763             ClosureKind::FnOnce => {
1764                 tcx.require_lang_item(FnOnceTraitLangItem)
1765             }
1766         }
1767     }
1768
1769     /// True if this a type that impls this closure kind
1770     /// must also implement `other`.
1771     pub fn extends(self, other: ty::ClosureKind) -> bool {
1772         match (self, other) {
1773             (ClosureKind::Fn, ClosureKind::Fn) => true,
1774             (ClosureKind::Fn, ClosureKind::FnMut) => true,
1775             (ClosureKind::Fn, ClosureKind::FnOnce) => true,
1776             (ClosureKind::FnMut, ClosureKind::FnMut) => true,
1777             (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
1778             (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
1779             _ => false,
1780         }
1781     }
1782 }
1783
1784 impl<'tcx> TyS<'tcx> {
1785     /// Iterator that walks `self` and any types reachable from
1786     /// `self`, in depth-first order. Note that just walks the types
1787     /// that appear in `self`, it does not descend into the fields of
1788     /// structs or variants. For example:
1789     ///
1790     /// ```notrust
1791     /// isize => { isize }
1792     /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
1793     /// [isize] => { [isize], isize }
1794     /// ```
1795     pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
1796         TypeWalker::new(self)
1797     }
1798
1799     /// Iterator that walks the immediate children of `self`.  Hence
1800     /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
1801     /// (but not `i32`, like `walk`).
1802     pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
1803         walk::walk_shallow(self)
1804     }
1805
1806     /// Walks `ty` and any types appearing within `ty`, invoking the
1807     /// callback `f` on each type. If the callback returns false, then the
1808     /// children of the current type are ignored.
1809     ///
1810     /// Note: prefer `ty.walk()` where possible.
1811     pub fn maybe_walk<F>(&'tcx self, mut f: F)
1812         where F : FnMut(Ty<'tcx>) -> bool
1813     {
1814         let mut walker = self.walk();
1815         while let Some(ty) = walker.next() {
1816             if !f(ty) {
1817                 walker.skip_current_subtree();
1818             }
1819         }
1820     }
1821 }
1822
1823 impl<'tcx> ItemSubsts<'tcx> {
1824     pub fn is_noop(&self) -> bool {
1825         self.substs.is_noop()
1826     }
1827 }
1828
1829 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1830 pub enum LvaluePreference {
1831     PreferMutLvalue,
1832     NoPreference
1833 }
1834
1835 impl LvaluePreference {
1836     pub fn from_mutbl(m: hir::Mutability) -> Self {
1837         match m {
1838             hir::MutMutable => PreferMutLvalue,
1839             hir::MutImmutable => NoPreference,
1840         }
1841     }
1842 }
1843
1844 /// Helper for looking things up in the various maps that are populated during
1845 /// typeck::collect (e.g., `tcx.associated_items`, `tcx.types`, etc).  All of
1846 /// these share the pattern that if the id is local, it should have been loaded
1847 /// into the map by the `typeck::collect` phase.  If the def-id is external,
1848 /// then we have to go consult the crate loading code (and cache the result for
1849 /// the future).
1850 fn lookup_locally_or_in_crate_store<M, F>(descr: &str,
1851                                           def_id: DefId,
1852                                           map: &M,
1853                                           load_external: F)
1854                                           -> M::Value where
1855     M: MemoizationMap<Key=DefId>,
1856     F: FnOnce() -> M::Value,
1857 {
1858     map.memoize(def_id, || {
1859         if def_id.is_local() {
1860             bug!("No def'n found for {:?} in tcx.{}", def_id, descr);
1861         }
1862         load_external()
1863     })
1864 }
1865
1866 impl BorrowKind {
1867     pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
1868         match m {
1869             hir::MutMutable => MutBorrow,
1870             hir::MutImmutable => ImmBorrow,
1871         }
1872     }
1873
1874     /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
1875     /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
1876     /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
1877     /// question.
1878     pub fn to_mutbl_lossy(self) -> hir::Mutability {
1879         match self {
1880             MutBorrow => hir::MutMutable,
1881             ImmBorrow => hir::MutImmutable,
1882
1883             // We have no type corresponding to a unique imm borrow, so
1884             // use `&mut`. It gives all the capabilities of an `&uniq`
1885             // and hence is a safe "over approximation".
1886             UniqueImmBorrow => hir::MutMutable,
1887         }
1888     }
1889
1890     pub fn to_user_str(&self) -> &'static str {
1891         match *self {
1892             MutBorrow => "mutable",
1893             ImmBorrow => "immutable",
1894             UniqueImmBorrow => "uniquely immutable",
1895         }
1896     }
1897 }
1898
1899 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1900     pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
1901         self.item_tables(self.hir.body_owner_def_id(body))
1902     }
1903
1904     pub fn item_tables(self, def_id: DefId) -> &'gcx TypeckTables<'gcx> {
1905         self.tables.memoize(def_id, || {
1906             if def_id.is_local() {
1907                 // Closures' tables come from their outermost function,
1908                 // as they are part of the same "inference environment".
1909                 let outer_def_id = self.closure_base_def_id(def_id);
1910                 if outer_def_id != def_id {
1911                     return self.item_tables(outer_def_id);
1912                 }
1913
1914                 bug!("No def'n found for {:?} in tcx.tables", def_id);
1915             }
1916
1917             // Cross-crate side-tables only exist alongside serialized HIR.
1918             self.sess.cstore.maybe_get_item_body(self.global_tcx(), def_id).map(|_| {
1919                 self.tables.borrow()[&def_id]
1920             }).unwrap_or_else(|| {
1921                 bug!("tcx.item_tables({:?}): missing from metadata", def_id)
1922             })
1923         })
1924     }
1925
1926     pub fn expr_span(self, id: NodeId) -> Span {
1927         match self.hir.find(id) {
1928             Some(hir_map::NodeExpr(e)) => {
1929                 e.span
1930             }
1931             Some(f) => {
1932                 bug!("Node id {} is not an expr: {:?}", id, f);
1933             }
1934             None => {
1935                 bug!("Node id {} is not present in the node map", id);
1936             }
1937         }
1938     }
1939
1940     pub fn local_var_name_str(self, id: NodeId) -> InternedString {
1941         match self.hir.find(id) {
1942             Some(hir_map::NodeLocal(pat)) => {
1943                 match pat.node {
1944                     hir::PatKind::Binding(_, _, ref path1, _) => path1.node.as_str(),
1945                     _ => {
1946                         bug!("Variable id {} maps to {:?}, not local", id, pat);
1947                     },
1948                 }
1949             },
1950             r => bug!("Variable id {} maps to {:?}, not local", id, r),
1951         }
1952     }
1953
1954     pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
1955          match expr.node {
1956             hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
1957                 match path.def {
1958                     Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
1959                     _ => false,
1960                 }
1961             }
1962
1963             hir::ExprType(ref e, _) => {
1964                 self.expr_is_lval(e)
1965             }
1966
1967             hir::ExprUnary(hir::UnDeref, _) |
1968             hir::ExprField(..) |
1969             hir::ExprTupField(..) |
1970             hir::ExprIndex(..) => {
1971                 true
1972             }
1973
1974             // Partially qualified paths in expressions can only legally
1975             // refer to associated items which are always rvalues.
1976             hir::ExprPath(hir::QPath::TypeRelative(..)) |
1977
1978             hir::ExprCall(..) |
1979             hir::ExprMethodCall(..) |
1980             hir::ExprStruct(..) |
1981             hir::ExprTup(..) |
1982             hir::ExprIf(..) |
1983             hir::ExprMatch(..) |
1984             hir::ExprClosure(..) |
1985             hir::ExprBlock(..) |
1986             hir::ExprRepeat(..) |
1987             hir::ExprArray(..) |
1988             hir::ExprBreak(..) |
1989             hir::ExprAgain(..) |
1990             hir::ExprRet(..) |
1991             hir::ExprWhile(..) |
1992             hir::ExprLoop(..) |
1993             hir::ExprAssign(..) |
1994             hir::ExprInlineAsm(..) |
1995             hir::ExprAssignOp(..) |
1996             hir::ExprLit(_) |
1997             hir::ExprUnary(..) |
1998             hir::ExprBox(..) |
1999             hir::ExprAddrOf(..) |
2000             hir::ExprBinary(..) |
2001             hir::ExprCast(..) => {
2002                 false
2003             }
2004         }
2005     }
2006
2007     pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2008         self.associated_items(id)
2009             .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2010             .collect()
2011     }
2012
2013     pub fn trait_impl_polarity(self, id: DefId) -> hir::ImplPolarity {
2014         if let Some(id) = self.hir.as_local_node_id(id) {
2015             match self.hir.expect_item(id).node {
2016                 hir::ItemImpl(_, polarity, ..) => polarity,
2017                 ref item => bug!("trait_impl_polarity: {:?} not an impl", item)
2018             }
2019         } else {
2020             self.sess.cstore.impl_polarity(id)
2021         }
2022     }
2023
2024     pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2025         self.associated_items(did).any(|item| {
2026             item.relevant_for_never()
2027         })
2028     }
2029
2030     pub fn custom_coerce_unsized_kind(self, did: DefId) -> adjustment::CustomCoerceUnsized {
2031         self.custom_coerce_unsized_kinds.memoize(did, || {
2032             let (kind, src) = if did.krate != LOCAL_CRATE {
2033                 (self.sess.cstore.custom_coerce_unsized_kind(did), "external")
2034             } else {
2035                 (None, "local")
2036             };
2037
2038             match kind {
2039                 Some(kind) => kind,
2040                 None => {
2041                     bug!("custom_coerce_unsized_kind: \
2042                           {} impl `{}` is missing its kind",
2043                           src, self.item_path_str(did));
2044                 }
2045             }
2046         })
2047     }
2048
2049     pub fn associated_item(self, def_id: DefId) -> AssociatedItem {
2050         self.associated_items.memoize(def_id, || {
2051             if !def_id.is_local() {
2052                 return self.sess.cstore.associated_item(def_id)
2053                            .expect("missing AssociatedItem in metadata");
2054             }
2055
2056             // When the user asks for a given associated item, we
2057             // always go ahead and convert all the associated items in
2058             // the container. Note that we are also careful only to
2059             // ever register a read on the *container* of the assoc
2060             // item, not the assoc item itself. This prevents changes
2061             // in the details of an item (for example, the type to
2062             // which an associated type is bound) from contaminating
2063             // those tasks that just need to scan the names of items
2064             // and so forth.
2065
2066             let id = self.hir.as_local_node_id(def_id).unwrap();
2067             let parent_id = self.hir.get_parent(id);
2068             let parent_def_id = self.hir.local_def_id(parent_id);
2069             let parent_item = self.hir.expect_item(parent_id);
2070             match parent_item.node {
2071                 hir::ItemImpl(.., ref impl_trait_ref, _, ref impl_item_refs) => {
2072                     for impl_item_ref in impl_item_refs {
2073                         let assoc_item =
2074                             self.associated_item_from_impl_item_ref(parent_def_id,
2075                                                                     impl_trait_ref.is_some(),
2076                                                                     impl_item_ref);
2077                         self.associated_items.borrow_mut().insert(assoc_item.def_id, assoc_item);
2078                     }
2079                 }
2080
2081                 hir::ItemTrait(.., ref trait_item_refs) => {
2082                     for trait_item_ref in trait_item_refs {
2083                         let assoc_item =
2084                             self.associated_item_from_trait_item_ref(parent_def_id, trait_item_ref);
2085                         self.associated_items.borrow_mut().insert(assoc_item.def_id, assoc_item);
2086                     }
2087                 }
2088
2089                 ref r => {
2090                     panic!("unexpected container of associated items: {:?}", r)
2091                 }
2092             }
2093
2094             // memoize wants us to return something, so return
2095             // the one we generated for this def-id
2096             *self.associated_items.borrow().get(&def_id).unwrap()
2097         })
2098     }
2099
2100     fn associated_item_from_trait_item_ref(self,
2101                                            parent_def_id: DefId,
2102                                            trait_item_ref: &hir::TraitItemRef)
2103                                            -> AssociatedItem {
2104         let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2105         let (kind, has_self) = match trait_item_ref.kind {
2106             hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2107             hir::AssociatedItemKind::Method { has_self } => {
2108                 (ty::AssociatedKind::Method, has_self)
2109             }
2110             hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2111         };
2112
2113         AssociatedItem {
2114             name: trait_item_ref.name,
2115             kind: kind,
2116             vis: Visibility::from_hir(&hir::Inherited, trait_item_ref.id.node_id, self),
2117             defaultness: trait_item_ref.defaultness,
2118             def_id: def_id,
2119             container: TraitContainer(parent_def_id),
2120             method_has_self_argument: has_self
2121         }
2122     }
2123
2124     fn associated_item_from_impl_item_ref(self,
2125                                           parent_def_id: DefId,
2126                                           from_trait_impl: bool,
2127                                           impl_item_ref: &hir::ImplItemRef)
2128                                           -> AssociatedItem {
2129         let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2130         let (kind, has_self) = match impl_item_ref.kind {
2131             hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2132             hir::AssociatedItemKind::Method { has_self } => {
2133                 (ty::AssociatedKind::Method, has_self)
2134             }
2135             hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2136         };
2137
2138         // Trait impl items are always public.
2139         let public = hir::Public;
2140         let vis = if from_trait_impl { &public } else { &impl_item_ref.vis };
2141
2142         ty::AssociatedItem {
2143             name: impl_item_ref.name,
2144             kind: kind,
2145             vis: ty::Visibility::from_hir(vis, impl_item_ref.id.node_id, self),
2146             defaultness: impl_item_ref.defaultness,
2147             def_id: def_id,
2148             container: ImplContainer(parent_def_id),
2149             method_has_self_argument: has_self
2150         }
2151     }
2152
2153     pub fn associated_item_def_ids(self, def_id: DefId) -> Rc<Vec<DefId>> {
2154         self.associated_item_def_ids.memoize(def_id, || {
2155             if !def_id.is_local() {
2156                 return Rc::new(self.sess.cstore.associated_item_def_ids(def_id));
2157             }
2158
2159             let id = self.hir.as_local_node_id(def_id).unwrap();
2160             let item = self.hir.expect_item(id);
2161             let vec: Vec<_> = match item.node {
2162                 hir::ItemTrait(.., ref trait_item_refs) => {
2163                     trait_item_refs.iter()
2164                                    .map(|trait_item_ref| trait_item_ref.id)
2165                                    .map(|id| self.hir.local_def_id(id.node_id))
2166                                    .collect()
2167                 }
2168                 hir::ItemImpl(.., ref impl_item_refs) => {
2169                     impl_item_refs.iter()
2170                                   .map(|impl_item_ref| impl_item_ref.id)
2171                                   .map(|id| self.hir.local_def_id(id.node_id))
2172                                   .collect()
2173                 }
2174                 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2175             };
2176             Rc::new(vec)
2177         })
2178     }
2179
2180     #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2181     pub fn associated_items(self, def_id: DefId)
2182                             -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2183         let def_ids = self.associated_item_def_ids(def_id);
2184         (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2185     }
2186
2187     /// Returns the trait-ref corresponding to a given impl, or None if it is
2188     /// an inherent impl.
2189     pub fn impl_trait_ref(self, id: DefId) -> Option<TraitRef<'gcx>> {
2190         lookup_locally_or_in_crate_store(
2191             "impl_trait_refs", id, &self.impl_trait_refs,
2192             || self.sess.cstore.impl_trait_ref(self.global_tcx(), id))
2193     }
2194
2195     // Returns `ty::VariantDef` if `def` refers to a struct,
2196     // or variant or their constructors, panics otherwise.
2197     pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2198         match def {
2199             Def::Variant(did) | Def::VariantCtor(did, ..) => {
2200                 let enum_did = self.parent_def_id(did).unwrap();
2201                 self.lookup_adt_def(enum_did).variant_with_id(did)
2202             }
2203             Def::Struct(did) | Def::Union(did) => {
2204                 self.lookup_adt_def(did).struct_variant()
2205             }
2206             Def::StructCtor(ctor_did, ..) => {
2207                 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2208                 self.lookup_adt_def(did).struct_variant()
2209             }
2210             _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2211         }
2212     }
2213
2214     pub fn def_key(self, id: DefId) -> hir_map::DefKey {
2215         if id.is_local() {
2216             self.hir.def_key(id)
2217         } else {
2218             self.sess.cstore.def_key(id)
2219         }
2220     }
2221
2222     /// Convert a `DefId` into its fully expanded `DefPath` (every
2223     /// `DefId` is really just an interned def-path).
2224     ///
2225     /// Note that if `id` is not local to this crate, the result will
2226     //  be a non-local `DefPath`.
2227     pub fn def_path(self, id: DefId) -> hir_map::DefPath {
2228         if id.is_local() {
2229             self.hir.def_path(id)
2230         } else {
2231             self.sess.cstore.def_path(id)
2232         }
2233     }
2234
2235     pub fn def_span(self, def_id: DefId) -> Span {
2236         if let Some(id) = self.hir.as_local_node_id(def_id) {
2237             self.hir.span(id)
2238         } else {
2239             self.sess.cstore.def_span(&self.sess, def_id)
2240         }
2241     }
2242
2243     pub fn vis_is_accessible_from(self, vis: Visibility, block: NodeId) -> bool {
2244         vis.is_accessible_from(self.hir.local_def_id(self.hir.get_module_parent(block)), self)
2245     }
2246
2247     pub fn item_name(self, id: DefId) -> ast::Name {
2248         if let Some(id) = self.hir.as_local_node_id(id) {
2249             self.hir.name(id)
2250         } else if id.index == CRATE_DEF_INDEX {
2251             self.sess.cstore.original_crate_name(id.krate)
2252         } else {
2253             let def_key = self.sess.cstore.def_key(id);
2254             // The name of a StructCtor is that of its struct parent.
2255             if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2256                 self.item_name(DefId {
2257                     krate: id.krate,
2258                     index: def_key.parent.unwrap()
2259                 })
2260             } else {
2261                 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2262                     bug!("item_name: no name for {:?}", self.def_path(id));
2263                 })
2264             }
2265         }
2266     }
2267
2268     // If the given item is in an external crate, looks up its type and adds it to
2269     // the type cache. Returns the type parameters and type.
2270     pub fn item_type(self, did: DefId) -> Ty<'gcx> {
2271         lookup_locally_or_in_crate_store(
2272             "item_types", did, &self.item_types,
2273             || self.sess.cstore.item_type(self.global_tcx(), did))
2274     }
2275
2276     /// Given the did of a trait, returns its canonical trait ref.
2277     pub fn lookup_trait_def(self, did: DefId) -> &'gcx TraitDef {
2278         lookup_locally_or_in_crate_store(
2279             "trait_defs", did, &self.trait_defs,
2280             || self.alloc_trait_def(self.sess.cstore.trait_def(self.global_tcx(), did))
2281         )
2282     }
2283
2284     /// Given the did of an ADT, return a reference to its definition.
2285     pub fn lookup_adt_def(self, did: DefId) -> &'gcx AdtDef {
2286         lookup_locally_or_in_crate_store(
2287             "adt_defs", did, &self.adt_defs,
2288             || self.sess.cstore.adt_def(self.global_tcx(), did))
2289     }
2290
2291     /// Given the did of an item, returns its generics.
2292     pub fn item_generics(self, did: DefId) -> &'gcx Generics<'gcx> {
2293         lookup_locally_or_in_crate_store(
2294             "generics", did, &self.generics,
2295             || self.alloc_generics(self.sess.cstore.item_generics(self.global_tcx(), did)))
2296     }
2297
2298     /// Given the did of an item, returns its full set of predicates.
2299     pub fn item_predicates(self, did: DefId) -> GenericPredicates<'gcx> {
2300         lookup_locally_or_in_crate_store(
2301             "predicates", did, &self.predicates,
2302             || self.sess.cstore.item_predicates(self.global_tcx(), did))
2303     }
2304
2305     /// Given the did of a trait, returns its superpredicates.
2306     pub fn item_super_predicates(self, did: DefId) -> GenericPredicates<'gcx> {
2307         lookup_locally_or_in_crate_store(
2308             "super_predicates", did, &self.super_predicates,
2309             || self.sess.cstore.item_super_predicates(self.global_tcx(), did))
2310     }
2311
2312     /// Given the did of an item, returns its MIR, borrowed immutably.
2313     pub fn item_mir(self, did: DefId) -> Ref<'gcx, Mir<'gcx>> {
2314         lookup_locally_or_in_crate_store("mir_map", did, &self.mir_map, || {
2315             let mir = self.sess.cstore.get_item_mir(self.global_tcx(), did);
2316             let mir = self.alloc_mir(mir);
2317
2318             // Perma-borrow MIR from extern crates to prevent mutation.
2319             mem::forget(mir.borrow());
2320
2321             mir
2322         }).borrow()
2323     }
2324
2325     /// If `type_needs_drop` returns true, then `ty` is definitely
2326     /// non-copy and *might* have a destructor attached; if it returns
2327     /// false, then `ty` definitely has no destructor (i.e. no drop glue).
2328     ///
2329     /// (Note that this implies that if `ty` has a destructor attached,
2330     /// then `type_needs_drop` will definitely return `true` for `ty`.)
2331     pub fn type_needs_drop_given_env(self,
2332                                      ty: Ty<'gcx>,
2333                                      param_env: &ty::ParameterEnvironment<'gcx>) -> bool {
2334         // Issue #22536: We first query type_moves_by_default.  It sees a
2335         // normalized version of the type, and therefore will definitely
2336         // know whether the type implements Copy (and thus needs no
2337         // cleanup/drop/zeroing) ...
2338         let tcx = self.global_tcx();
2339         let implements_copy = !ty.moves_by_default(tcx, param_env, DUMMY_SP);
2340
2341         if implements_copy { return false; }
2342
2343         // ... (issue #22536 continued) but as an optimization, still use
2344         // prior logic of asking if the `needs_drop` bit is set; we need
2345         // not zero non-Copy types if they have no destructor.
2346
2347         // FIXME(#22815): Note that calling `ty::type_contents` is a
2348         // conservative heuristic; it may report that `needs_drop` is set
2349         // when actual type does not actually have a destructor associated
2350         // with it. But since `ty` absolutely did not have the `Copy`
2351         // bound attached (see above), it is sound to treat it as having a
2352         // destructor (e.g. zero its memory on move).
2353
2354         let contents = ty.type_contents(tcx);
2355         debug!("type_needs_drop ty={:?} contents={:?}", ty, contents);
2356         contents.needs_drop(tcx)
2357     }
2358
2359     /// Get the attributes of a definition.
2360     pub fn get_attrs(self, did: DefId) -> Cow<'gcx, [ast::Attribute]> {
2361         if let Some(id) = self.hir.as_local_node_id(did) {
2362             Cow::Borrowed(self.hir.attrs(id))
2363         } else {
2364             Cow::Owned(self.sess.cstore.item_attrs(did))
2365         }
2366     }
2367
2368     /// Determine whether an item is annotated with an attribute
2369     pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2370         self.get_attrs(did).iter().any(|item| item.check_name(attr))
2371     }
2372
2373     /// Determine whether an item is annotated with `#[repr(packed)]`
2374     pub fn lookup_packed(self, did: DefId) -> bool {
2375         self.lookup_repr_hints(did).contains(&attr::ReprPacked)
2376     }
2377
2378     /// Determine whether an item is annotated with `#[simd]`
2379     pub fn lookup_simd(self, did: DefId) -> bool {
2380         self.has_attr(did, "simd")
2381             || self.lookup_repr_hints(did).contains(&attr::ReprSimd)
2382     }
2383
2384     pub fn item_variances(self, item_id: DefId) -> Rc<Vec<ty::Variance>> {
2385         lookup_locally_or_in_crate_store(
2386             "item_variance_map", item_id, &self.item_variance_map,
2387             || Rc::new(self.sess.cstore.item_variances(item_id)))
2388     }
2389
2390     pub fn trait_has_default_impl(self, trait_def_id: DefId) -> bool {
2391         self.populate_implementations_for_trait_if_necessary(trait_def_id);
2392
2393         let def = self.lookup_trait_def(trait_def_id);
2394         def.flags.get().intersects(TraitFlags::HAS_DEFAULT_IMPL)
2395     }
2396
2397     /// Records a trait-to-implementation mapping.
2398     pub fn record_trait_has_default_impl(self, trait_def_id: DefId) {
2399         let def = self.lookup_trait_def(trait_def_id);
2400         def.flags.set(def.flags.get() | TraitFlags::HAS_DEFAULT_IMPL)
2401     }
2402
2403     /// Populates the type context with all the inherent implementations for
2404     /// the given type if necessary.
2405     pub fn populate_inherent_implementations_for_type_if_necessary(self,
2406                                                                    type_id: DefId) {
2407         if type_id.is_local() {
2408             return
2409         }
2410
2411         // The type is not local, hence we are reading this out of
2412         // metadata and don't need to track edges.
2413         let _ignore = self.dep_graph.in_ignore();
2414
2415         if self.populated_external_types.borrow().contains(&type_id) {
2416             return
2417         }
2418
2419         debug!("populate_inherent_implementations_for_type_if_necessary: searching for {:?}",
2420                type_id);
2421
2422         let inherent_impls = self.sess.cstore.inherent_implementations_for_type(type_id);
2423
2424         self.inherent_impls.borrow_mut().insert(type_id, inherent_impls);
2425         self.populated_external_types.borrow_mut().insert(type_id);
2426     }
2427
2428     /// Populates the type context with all the implementations for the given
2429     /// trait if necessary.
2430     pub fn populate_implementations_for_trait_if_necessary(self, trait_id: DefId) {
2431         if trait_id.is_local() {
2432             return
2433         }
2434
2435         // The type is not local, hence we are reading this out of
2436         // metadata and don't need to track edges.
2437         let _ignore = self.dep_graph.in_ignore();
2438
2439         let def = self.lookup_trait_def(trait_id);
2440         if def.flags.get().intersects(TraitFlags::IMPLS_VALID) {
2441             return;
2442         }
2443
2444         debug!("populate_implementations_for_trait_if_necessary: searching for {:?}", def);
2445
2446         if self.sess.cstore.is_defaulted_trait(trait_id) {
2447             self.record_trait_has_default_impl(trait_id);
2448         }
2449
2450         for impl_def_id in self.sess.cstore.implementations_of_trait(Some(trait_id)) {
2451             let trait_ref = self.impl_trait_ref(impl_def_id).unwrap();
2452
2453             // Record the trait->implementation mapping.
2454             let parent = self.sess.cstore.impl_parent(impl_def_id).unwrap_or(trait_id);
2455             def.record_remote_impl(self, impl_def_id, trait_ref, parent);
2456         }
2457
2458         def.flags.set(def.flags.get() | TraitFlags::IMPLS_VALID);
2459     }
2460
2461     pub fn closure_kind(self, def_id: DefId) -> ty::ClosureKind {
2462         // If this is a local def-id, it should be inserted into the
2463         // tables by typeck; else, it will be retreived from
2464         // the external crate metadata.
2465         if let Some(&kind) = self.closure_kinds.borrow().get(&def_id) {
2466             return kind;
2467         }
2468
2469         let kind = self.sess.cstore.closure_kind(def_id);
2470         self.closure_kinds.borrow_mut().insert(def_id, kind);
2471         kind
2472     }
2473
2474     pub fn closure_type(self,
2475                         def_id: DefId,
2476                         substs: ClosureSubsts<'tcx>)
2477                         -> ty::ClosureTy<'tcx>
2478     {
2479         // If this is a local def-id, it should be inserted into the
2480         // tables by typeck; else, it will be retreived from
2481         // the external crate metadata.
2482         if let Some(ty) = self.closure_tys.borrow().get(&def_id) {
2483             return ty.subst(self, substs.substs);
2484         }
2485
2486         let ty = self.sess.cstore.closure_ty(self.global_tcx(), def_id);
2487         self.closure_tys.borrow_mut().insert(def_id, ty.clone());
2488         ty.subst(self, substs.substs)
2489     }
2490
2491     /// Given the def_id of an impl, return the def_id of the trait it implements.
2492     /// If it implements no trait, return `None`.
2493     pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2494         self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2495     }
2496
2497     /// If the given def ID describes a method belonging to an impl, return the
2498     /// ID of the impl that the method belongs to. Otherwise, return `None`.
2499     pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2500         if def_id.krate != LOCAL_CRATE {
2501             return self.sess.cstore.associated_item(def_id).and_then(|item| {
2502                 match item.container {
2503                     TraitContainer(_) => None,
2504                     ImplContainer(def_id) => Some(def_id),
2505                 }
2506             });
2507         }
2508         match self.associated_items.borrow().get(&def_id).cloned() {
2509             Some(trait_item) => {
2510                 match trait_item.container {
2511                     TraitContainer(_) => None,
2512                     ImplContainer(def_id) => Some(def_id),
2513                 }
2514             }
2515             None => None
2516         }
2517     }
2518
2519     /// If the given def ID describes an item belonging to a trait,
2520     /// return the ID of the trait that the trait item belongs to.
2521     /// Otherwise, return `None`.
2522     pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
2523         if def_id.krate != LOCAL_CRATE {
2524             return self.sess.cstore.trait_of_item(def_id);
2525         }
2526         match self.associated_items.borrow().get(&def_id) {
2527             Some(associated_item) => {
2528                 match associated_item.container {
2529                     TraitContainer(def_id) => Some(def_id),
2530                     ImplContainer(_) => None
2531                 }
2532             }
2533             None => None
2534         }
2535     }
2536
2537     /// Construct a parameter environment suitable for static contexts or other contexts where there
2538     /// are no free type/lifetime parameters in scope.
2539     pub fn empty_parameter_environment(self) -> ParameterEnvironment<'tcx> {
2540
2541         // for an empty parameter environment, there ARE no free
2542         // regions, so it shouldn't matter what we use for the free id
2543         let free_id_outlive = self.region_maps.node_extent(ast::DUMMY_NODE_ID);
2544         ty::ParameterEnvironment {
2545             free_substs: self.intern_substs(&[]),
2546             caller_bounds: Vec::new(),
2547             implicit_region_bound: self.mk_region(ty::ReEmpty),
2548             free_id_outlive: free_id_outlive,
2549             is_copy_cache: RefCell::new(FxHashMap()),
2550             is_sized_cache: RefCell::new(FxHashMap()),
2551         }
2552     }
2553
2554     /// Constructs and returns a substitution that can be applied to move from
2555     /// the "outer" view of a type or method to the "inner" view.
2556     /// In general, this means converting from bound parameters to
2557     /// free parameters. Since we currently represent bound/free type
2558     /// parameters in the same way, this only has an effect on regions.
2559     pub fn construct_free_substs(self, def_id: DefId,
2560                                  free_id_outlive: CodeExtent)
2561                                  -> &'gcx Substs<'gcx> {
2562
2563         let substs = Substs::for_item(self.global_tcx(), def_id, |def, _| {
2564             // map bound 'a => free 'a
2565             self.global_tcx().mk_region(ReFree(FreeRegion {
2566                 scope: free_id_outlive,
2567                 bound_region: def.to_bound_region()
2568             }))
2569         }, |def, _| {
2570             // map T => T
2571             self.global_tcx().mk_param_from_def(def)
2572         });
2573
2574         debug!("construct_parameter_environment: {:?}", substs);
2575         substs
2576     }
2577
2578     /// See `ParameterEnvironment` struct def'n for details.
2579     /// If you were using `free_id: NodeId`, you might try `self.region_maps.item_extent(free_id)`
2580     /// for the `free_id_outlive` parameter. (But note that this is not always quite right.)
2581     pub fn construct_parameter_environment(self,
2582                                            span: Span,
2583                                            def_id: DefId,
2584                                            free_id_outlive: CodeExtent)
2585                                            -> ParameterEnvironment<'gcx>
2586     {
2587         //
2588         // Construct the free substs.
2589         //
2590
2591         let free_substs = self.construct_free_substs(def_id, free_id_outlive);
2592
2593         //
2594         // Compute the bounds on Self and the type parameters.
2595         //
2596
2597         let tcx = self.global_tcx();
2598         let generic_predicates = tcx.item_predicates(def_id);
2599         let bounds = generic_predicates.instantiate(tcx, free_substs);
2600         let bounds = tcx.liberate_late_bound_regions(free_id_outlive, &ty::Binder(bounds));
2601         let predicates = bounds.predicates;
2602
2603         // Finally, we have to normalize the bounds in the environment, in
2604         // case they contain any associated type projections. This process
2605         // can yield errors if the put in illegal associated types, like
2606         // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2607         // report these errors right here; this doesn't actually feel
2608         // right to me, because constructing the environment feels like a
2609         // kind of a "idempotent" action, but I'm not sure where would be
2610         // a better place. In practice, we construct environments for
2611         // every fn once during type checking, and we'll abort if there
2612         // are any errors at that point, so after type checking you can be
2613         // sure that this will succeed without errors anyway.
2614         //
2615
2616         let unnormalized_env = ty::ParameterEnvironment {
2617             free_substs: free_substs,
2618             implicit_region_bound: tcx.mk_region(ty::ReScope(free_id_outlive)),
2619             caller_bounds: predicates,
2620             free_id_outlive: free_id_outlive,
2621             is_copy_cache: RefCell::new(FxHashMap()),
2622             is_sized_cache: RefCell::new(FxHashMap()),
2623         };
2624
2625         let cause = traits::ObligationCause::misc(span, free_id_outlive.node_id(&self.region_maps));
2626         traits::normalize_param_env_or_error(tcx, unnormalized_env, cause)
2627     }
2628
2629     pub fn node_scope_region(self, id: NodeId) -> &'tcx Region {
2630         self.mk_region(ty::ReScope(self.region_maps.node_extent(id)))
2631     }
2632
2633     pub fn visit_all_item_likes_in_krate<V,F>(self,
2634                                               dep_node_fn: F,
2635                                               visitor: &mut V)
2636         where F: FnMut(DefId) -> DepNode<DefId>, V: ItemLikeVisitor<'gcx>
2637     {
2638         dep_graph::visit_all_item_likes_in_krate(self.global_tcx(), dep_node_fn, visitor);
2639     }
2640
2641     /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2642     /// with the name of the crate containing the impl.
2643     pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2644         if impl_did.is_local() {
2645             let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2646             Ok(self.hir.span(node_id))
2647         } else {
2648             Err(self.sess.cstore.crate_name(impl_did.krate))
2649         }
2650     }
2651 }
2652
2653 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2654     pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2655         F: FnOnce(&[hir::Freevar]) -> T,
2656     {
2657         match self.freevars.borrow().get(&fid) {
2658             None => f(&[]),
2659             Some(d) => f(&d[..])
2660         }
2661     }
2662 }