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