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