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