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