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