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