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