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