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