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