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