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