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