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