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