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