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