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