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