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