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