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