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