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