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