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