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