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