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