]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/mod.rs
a195c944ff28d89ce7d3393233f961ce14e412ea
[rust.git] / src / librustc / ty / mod.rs
1 // ignore-tidy-filelength
2
3 pub use self::fold::{TypeFoldable, TypeVisitor};
4 pub use self::AssocItemContainer::*;
5 pub use self::BorrowKind::*;
6 pub use self::IntVarValue::*;
7 pub use self::Variance::*;
8
9 use crate::arena::Arena;
10 use crate::hir::exports::ExportMap;
11 use crate::hir::map as hir_map;
12
13 use crate::ich::Fingerprint;
14 use crate::ich::StableHashingContext;
15 use crate::infer::canonical::Canonical;
16 use crate::middle::cstore::CrateStoreDyn;
17 use crate::middle::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
18 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
19 use crate::mir::interpret::ErrorHandled;
20 use crate::mir::GeneratorLayout;
21 use crate::mir::ReadOnlyBodyAndCache;
22 use crate::session::DataTypeKind;
23 use crate::traits::{self, Reveal};
24 use crate::ty;
25 use crate::ty::layout::VariantIdx;
26 use crate::ty::subst::{InternalSubsts, Subst, SubstsRef};
27 use crate::ty::util::{Discr, IntTypeExt};
28 use crate::ty::walk::TypeWalker;
29 use rustc_attr as attr;
30 use rustc_data_structures::captures::Captures;
31 use rustc_data_structures::fx::FxHashMap;
32 use rustc_data_structures::fx::FxIndexMap;
33 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
34 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
35 use rustc_data_structures::sync::{self, par_iter, Lrc, ParallelIterator};
36 use rustc_hir as hir;
37 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
38 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
39 use rustc_hir::{Constness, GlobMap, Node, TraitMap};
40 use rustc_index::vec::{Idx, IndexVec};
41 use rustc_macros::HashStable;
42 use rustc_serialize::{self, Encodable, Encoder};
43 use rustc_span::hygiene::ExpnId;
44 use rustc_span::symbol::{kw, sym, Symbol};
45 use rustc_span::Span;
46 use rustc_target::abi::Align;
47 use syntax::ast::{self, Ident, Name};
48 use syntax::node_id::{NodeId, NodeMap, NodeSet};
49
50 use std::cell::RefCell;
51 use std::cmp::{self, Ordering};
52 use std::fmt;
53 use std::hash::{Hash, Hasher};
54 use std::ops::Deref;
55 use std::ops::Range;
56 use std::slice;
57 use std::{mem, ptr};
58
59 pub use self::sty::BoundRegion::*;
60 pub use self::sty::InferTy::*;
61 pub use self::sty::RegionKind;
62 pub use self::sty::RegionKind::*;
63 pub use self::sty::TyKind::*;
64 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
65 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
66 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
67 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
68 pub use self::sty::{Const, ConstKind, ExistentialProjection, PolyExistentialProjection};
69 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
70 pub use self::sty::{ExistentialPredicate, InferConst, InferTy, ParamConst, ParamTy, ProjectionTy};
71 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
72 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
73 pub use crate::ty::diagnostics::*;
74
75 pub use self::binding::BindingMode;
76 pub use self::binding::BindingMode::*;
77
78 pub use self::context::{keep_local, tls, FreeRegionInfo, TyCtxt};
79 pub use self::context::{
80     CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
81     UserType, UserTypeAnnotationIndex,
82 };
83 pub use self::context::{
84     CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables,
85 };
86
87 pub use self::instance::RESOLVE_INSTANCE;
88 pub use self::instance::{Instance, InstanceDef};
89
90 pub use self::trait_def::TraitDef;
91
92 pub use self::query::queries;
93
94 pub mod adjustment;
95 pub mod binding;
96 pub mod cast;
97 #[macro_use]
98 pub mod codec;
99 pub mod _match;
100 mod erase_regions;
101 pub mod error;
102 pub mod fast_reject;
103 pub mod flags;
104 pub mod fold;
105 pub mod free_region_map;
106 pub mod inhabitedness;
107 pub mod layout;
108 pub mod normalize_erasing_regions;
109 pub mod outlives;
110 pub mod print;
111 pub mod query;
112 pub mod relate;
113 pub mod steal;
114 pub mod subst;
115 pub mod trait_def;
116 pub mod util;
117 pub mod walk;
118
119 mod context;
120 mod diagnostics;
121 mod instance;
122 mod structural_impls;
123 mod sty;
124
125 // Data types
126
127 pub struct ResolverOutputs {
128     pub definitions: hir_map::Definitions,
129     pub cstore: Box<CrateStoreDyn>,
130     pub extern_crate_map: NodeMap<CrateNum>,
131     pub trait_map: TraitMap<NodeId>,
132     pub maybe_unused_trait_imports: NodeSet,
133     pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
134     pub export_map: ExportMap<NodeId>,
135     pub glob_map: GlobMap,
136     /// Extern prelude entries. The value is `true` if the entry was introduced
137     /// via `extern crate` item and not `--extern` option or compiler built-in.
138     pub extern_prelude: FxHashMap<Name, bool>,
139 }
140
141 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
142 pub enum AssocItemContainer {
143     TraitContainer(DefId),
144     ImplContainer(DefId),
145 }
146
147 impl AssocItemContainer {
148     /// Asserts that this is the `DefId` of an associated item declared
149     /// in a trait, and returns the trait `DefId`.
150     pub fn assert_trait(&self) -> DefId {
151         match *self {
152             TraitContainer(id) => id,
153             _ => bug!("associated item has wrong container type: {:?}", self),
154         }
155     }
156
157     pub fn id(&self) -> DefId {
158         match *self {
159             TraitContainer(id) => id,
160             ImplContainer(id) => id,
161         }
162     }
163 }
164
165 /// The "header" of an impl is everything outside the body: a Self type, a trait
166 /// ref (in the case of a trait impl), and a set of predicates (from the
167 /// bounds / where-clauses).
168 #[derive(Clone, Debug, TypeFoldable)]
169 pub struct ImplHeader<'tcx> {
170     pub impl_def_id: DefId,
171     pub self_ty: Ty<'tcx>,
172     pub trait_ref: Option<TraitRef<'tcx>>,
173     pub predicates: Vec<Predicate<'tcx>>,
174 }
175
176 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
177 pub enum ImplPolarity {
178     /// `impl Trait for Type`
179     Positive,
180     /// `impl !Trait for Type`
181     Negative,
182     /// `#[rustc_reservation_impl] impl Trait for Type`
183     ///
184     /// This is a "stability hack", not a real Rust feature.
185     /// See #64631 for details.
186     Reservation,
187 }
188
189 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
190 pub struct AssocItem {
191     pub def_id: DefId,
192     #[stable_hasher(project(name))]
193     pub ident: Ident,
194     pub kind: AssocKind,
195     pub vis: Visibility,
196     pub defaultness: hir::Defaultness,
197     pub container: AssocItemContainer,
198
199     /// Whether this is a method with an explicit self
200     /// as its first argument, allowing method calls.
201     pub method_has_self_argument: bool,
202 }
203
204 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
205 pub enum AssocKind {
206     Const,
207     Method,
208     OpaqueTy,
209     Type,
210 }
211
212 impl AssocKind {
213     pub fn suggestion_descr(&self) -> &'static str {
214         match self {
215             ty::AssocKind::Method => "method call",
216             ty::AssocKind::Type | ty::AssocKind::OpaqueTy => "associated type",
217             ty::AssocKind::Const => "associated constant",
218         }
219     }
220
221     pub fn namespace(&self) -> Namespace {
222         match *self {
223             ty::AssocKind::OpaqueTy | ty::AssocKind::Type => Namespace::TypeNS,
224             ty::AssocKind::Const | ty::AssocKind::Method => Namespace::ValueNS,
225         }
226     }
227 }
228
229 impl AssocItem {
230     pub fn def_kind(&self) -> DefKind {
231         match self.kind {
232             AssocKind::Const => DefKind::AssocConst,
233             AssocKind::Method => DefKind::Method,
234             AssocKind::Type => DefKind::AssocTy,
235             AssocKind::OpaqueTy => DefKind::AssocOpaqueTy,
236         }
237     }
238
239     /// Tests whether the associated item admits a non-trivial implementation
240     /// for !
241     pub fn relevant_for_never(&self) -> bool {
242         match self.kind {
243             AssocKind::OpaqueTy | AssocKind::Const | AssocKind::Type => true,
244             // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
245             AssocKind::Method => !self.method_has_self_argument,
246         }
247     }
248
249     pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
250         match self.kind {
251             ty::AssocKind::Method => {
252                 // We skip the binder here because the binder would deanonymize all
253                 // late-bound regions, and we don't want method signatures to show up
254                 // `as for<'r> fn(&'r MyType)`.  Pretty-printing handles late-bound
255                 // regions just fine, showing `fn(&MyType)`.
256                 tcx.fn_sig(self.def_id).skip_binder().to_string()
257             }
258             ty::AssocKind::Type => format!("type {};", self.ident),
259             // FIXME(type_alias_impl_trait): we should print bounds here too.
260             ty::AssocKind::OpaqueTy => format!("type {};", self.ident),
261             ty::AssocKind::Const => {
262                 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
263             }
264         }
265     }
266 }
267
268 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
269 ///
270 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
271 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
272 /// done only on items with the same name.
273 #[derive(Debug, Clone, PartialEq, HashStable)]
274 pub struct AssociatedItems {
275     items: SortedIndexMultiMap<u32, Symbol, ty::AssocItem>,
276 }
277
278 impl AssociatedItems {
279     /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
280     pub fn new(items_in_def_order: impl IntoIterator<Item = ty::AssocItem>) -> Self {
281         let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
282         AssociatedItems { items }
283     }
284
285     /// Returns a slice of associated items in the order they were defined.
286     ///
287     /// New code should avoid relying on definition order. If you need a particular associated item
288     /// for a known trait, make that trait a lang item instead of indexing this array.
289     pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
290         self.items.iter().map(|(_, v)| v)
291     }
292
293     /// Returns an iterator over all associated items with the given name, ignoring hygiene.
294     pub fn filter_by_name_unhygienic(
295         &self,
296         name: Symbol,
297     ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
298         self.items.get_by_key(&name)
299     }
300
301     /// Returns an iterator over all associated items with the given name.
302     ///
303     /// Multiple items may have the same name if they are in different `Namespace`s. For example,
304     /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
305     /// methods below if you know which item you are looking for.
306     pub fn filter_by_name(
307         &'a self,
308         tcx: TyCtxt<'a>,
309         ident: Ident,
310         parent_def_id: DefId,
311     ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
312         self.filter_by_name_unhygienic(ident.name)
313             .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
314     }
315
316     /// Returns the associated item with the given name and `AssocKind`, if one exists.
317     pub fn find_by_name_and_kind(
318         &self,
319         tcx: TyCtxt<'_>,
320         ident: Ident,
321         kind: AssocKind,
322         parent_def_id: DefId,
323     ) -> Option<&ty::AssocItem> {
324         self.filter_by_name_unhygienic(ident.name)
325             .filter(|item| item.kind == kind)
326             .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
327     }
328
329     /// Returns the associated item with the given name in the given `Namespace`, if one exists.
330     pub fn find_by_name_and_namespace(
331         &self,
332         tcx: TyCtxt<'_>,
333         ident: Ident,
334         ns: Namespace,
335         parent_def_id: DefId,
336     ) -> Option<&ty::AssocItem> {
337         self.filter_by_name_unhygienic(ident.name)
338             .filter(|item| item.kind.namespace() == ns)
339             .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
340     }
341 }
342
343 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
344 pub enum Visibility {
345     /// Visible everywhere (including in other crates).
346     Public,
347     /// Visible only in the given crate-local module.
348     Restricted(DefId),
349     /// Not visible anywhere in the local crate. This is the visibility of private external items.
350     Invisible,
351 }
352
353 pub trait DefIdTree: Copy {
354     fn parent(self, id: DefId) -> Option<DefId>;
355
356     fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
357         if descendant.krate != ancestor.krate {
358             return false;
359         }
360
361         while descendant != ancestor {
362             match self.parent(descendant) {
363                 Some(parent) => descendant = parent,
364                 None => return false,
365             }
366         }
367         true
368     }
369 }
370
371 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
372     fn parent(self, id: DefId) -> Option<DefId> {
373         self.def_key(id).parent.map(|index| DefId { index: index, ..id })
374     }
375 }
376
377 impl Visibility {
378     pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
379         match visibility.node {
380             hir::VisibilityKind::Public => Visibility::Public,
381             hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
382             hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
383                 // If there is no resolution, `resolve` will have already reported an error, so
384                 // assume that the visibility is public to avoid reporting more privacy errors.
385                 Res::Err => Visibility::Public,
386                 def => Visibility::Restricted(def.def_id()),
387             },
388             hir::VisibilityKind::Inherited => {
389                 Visibility::Restricted(tcx.hir().get_module_parent(id))
390             }
391         }
392     }
393
394     /// Returns `true` if an item with this visibility is accessible from the given block.
395     pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
396         let restriction = match self {
397             // Public items are visible everywhere.
398             Visibility::Public => return true,
399             // Private items from other crates are visible nowhere.
400             Visibility::Invisible => return false,
401             // Restricted items are visible in an arbitrary local module.
402             Visibility::Restricted(other) if other.krate != module.krate => return false,
403             Visibility::Restricted(module) => module,
404         };
405
406         tree.is_descendant_of(module, restriction)
407     }
408
409     /// Returns `true` if this visibility is at least as accessible as the given visibility
410     pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
411         let vis_restriction = match vis {
412             Visibility::Public => return self == Visibility::Public,
413             Visibility::Invisible => return true,
414             Visibility::Restricted(module) => module,
415         };
416
417         self.is_accessible_from(vis_restriction, tree)
418     }
419
420     // Returns `true` if this item is visible anywhere in the local crate.
421     pub fn is_visible_locally(self) -> bool {
422         match self {
423             Visibility::Public => true,
424             Visibility::Restricted(def_id) => def_id.is_local(),
425             Visibility::Invisible => false,
426         }
427     }
428 }
429
430 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
431 pub enum Variance {
432     Covariant,     // T<A> <: T<B> iff A <: B -- e.g., function return type
433     Invariant,     // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
434     Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
435     Bivariant,     // T<A> <: T<B>            -- e.g., unused type parameter
436 }
437
438 /// The crate variances map is computed during typeck and contains the
439 /// variance of every item in the local crate. You should not use it
440 /// directly, because to do so will make your pass dependent on the
441 /// HIR of every item in the local crate. Instead, use
442 /// `tcx.variances_of()` to get the variance for a *particular*
443 /// item.
444 #[derive(HashStable)]
445 pub struct CrateVariancesMap<'tcx> {
446     /// For each item with generics, maps to a vector of the variance
447     /// of its generics. If an item has no generics, it will have no
448     /// entry.
449     pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
450 }
451
452 impl Variance {
453     /// `a.xform(b)` combines the variance of a context with the
454     /// variance of a type with the following meaning. If we are in a
455     /// context with variance `a`, and we encounter a type argument in
456     /// a position with variance `b`, then `a.xform(b)` is the new
457     /// variance with which the argument appears.
458     ///
459     /// Example 1:
460     ///
461     ///     *mut Vec<i32>
462     ///
463     /// Here, the "ambient" variance starts as covariant. `*mut T` is
464     /// invariant with respect to `T`, so the variance in which the
465     /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
466     /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
467     /// respect to its type argument `T`, and hence the variance of
468     /// the `i32` here is `Invariant.xform(Covariant)`, which results
469     /// (again) in `Invariant`.
470     ///
471     /// Example 2:
472     ///
473     ///     fn(*const Vec<i32>, *mut Vec<i32)
474     ///
475     /// The ambient variance is covariant. A `fn` type is
476     /// contravariant with respect to its parameters, so the variance
477     /// within which both pointer types appear is
478     /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
479     /// T` is covariant with respect to `T`, so the variance within
480     /// which the first `Vec<i32>` appears is
481     /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
482     /// is true for its `i32` argument. In the `*mut T` case, the
483     /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
484     /// and hence the outermost type is `Invariant` with respect to
485     /// `Vec<i32>` (and its `i32` argument).
486     ///
487     /// Source: Figure 1 of "Taming the Wildcards:
488     /// Combining Definition- and Use-Site Variance" published in PLDI'11.
489     pub fn xform(self, v: ty::Variance) -> ty::Variance {
490         match (self, v) {
491             // Figure 1, column 1.
492             (ty::Covariant, ty::Covariant) => ty::Covariant,
493             (ty::Covariant, ty::Contravariant) => ty::Contravariant,
494             (ty::Covariant, ty::Invariant) => ty::Invariant,
495             (ty::Covariant, ty::Bivariant) => ty::Bivariant,
496
497             // Figure 1, column 2.
498             (ty::Contravariant, ty::Covariant) => ty::Contravariant,
499             (ty::Contravariant, ty::Contravariant) => ty::Covariant,
500             (ty::Contravariant, ty::Invariant) => ty::Invariant,
501             (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
502
503             // Figure 1, column 3.
504             (ty::Invariant, _) => ty::Invariant,
505
506             // Figure 1, column 4.
507             (ty::Bivariant, _) => ty::Bivariant,
508         }
509     }
510 }
511
512 // Contains information needed to resolve types and (in the future) look up
513 // the types of AST nodes.
514 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
515 pub struct CReaderCacheKey {
516     pub cnum: CrateNum,
517     pub pos: usize,
518 }
519
520 // Flags that we track on types. These flags are propagated upwards
521 // through the type during type construction, so that we can quickly
522 // check whether the type has various kinds of types in it without
523 // recursing over the type itself.
524 bitflags! {
525     pub struct TypeFlags: u32 {
526         const HAS_PARAMS         = 1 << 0;
527         const HAS_TY_INFER       = 1 << 1;
528         const HAS_RE_INFER       = 1 << 2;
529         const HAS_RE_PLACEHOLDER = 1 << 3;
530
531         /// Does this have any `ReEarlyBound` regions? Used to
532         /// determine whether substitition is required, since those
533         /// represent regions that are bound in a `ty::Generics` and
534         /// hence may be substituted.
535         const HAS_RE_EARLY_BOUND = 1 << 4;
536
537         /// Does this have any region that "appears free" in the type?
538         /// Basically anything but `ReLateBound` and `ReErased`.
539         const HAS_FREE_REGIONS   = 1 << 5;
540
541         /// Is an error type reachable?
542         const HAS_TY_ERR         = 1 << 6;
543         const HAS_PROJECTION     = 1 << 7;
544
545         // FIXME: Rename this to the actual property since it's used for generators too
546         const HAS_TY_CLOSURE     = 1 << 8;
547
548         /// `true` if there are "names" of types and regions and so forth
549         /// that are local to a particular fn
550         const HAS_FREE_LOCAL_NAMES = 1 << 9;
551
552         /// Present if the type belongs in a local type context.
553         /// Only set for Infer other than Fresh.
554         const KEEP_IN_LOCAL_TCX  = 1 << 10;
555
556         /// Does this have any `ReLateBound` regions? Used to check
557         /// if a global bound is safe to evaluate.
558         const HAS_RE_LATE_BOUND  = 1 << 11;
559
560         /// Does this have any `ReErased` regions?
561         const HAS_RE_ERASED  = 1 << 12;
562
563         const HAS_TY_PLACEHOLDER = 1 << 13;
564
565         const HAS_CT_INFER       = 1 << 14;
566         const HAS_CT_PLACEHOLDER = 1 << 15;
567         /// Does this have any [Opaque] types.
568         const HAS_TY_OPAQUE      = 1 << 16;
569
570         const NEEDS_SUBST        = TypeFlags::HAS_PARAMS.bits |
571                                    TypeFlags::HAS_RE_EARLY_BOUND.bits;
572
573         /// Flags representing the nominal content of a type,
574         /// computed by FlagsComputation. If you add a new nominal
575         /// flag, it should be added here too.
576         const NOMINAL_FLAGS     = TypeFlags::HAS_PARAMS.bits |
577                                   TypeFlags::HAS_TY_INFER.bits |
578                                   TypeFlags::HAS_RE_INFER.bits |
579                                   TypeFlags::HAS_RE_PLACEHOLDER.bits |
580                                   TypeFlags::HAS_RE_EARLY_BOUND.bits |
581                                   TypeFlags::HAS_FREE_REGIONS.bits |
582                                   TypeFlags::HAS_TY_ERR.bits |
583                                   TypeFlags::HAS_PROJECTION.bits |
584                                   TypeFlags::HAS_TY_CLOSURE.bits |
585                                   TypeFlags::HAS_FREE_LOCAL_NAMES.bits |
586                                   TypeFlags::KEEP_IN_LOCAL_TCX.bits |
587                                   TypeFlags::HAS_RE_LATE_BOUND.bits |
588                                   TypeFlags::HAS_RE_ERASED.bits |
589                                   TypeFlags::HAS_TY_PLACEHOLDER.bits |
590                                   TypeFlags::HAS_CT_INFER.bits |
591                                   TypeFlags::HAS_CT_PLACEHOLDER.bits |
592                                   TypeFlags::HAS_TY_OPAQUE.bits;
593     }
594 }
595
596 #[allow(rustc::usage_of_ty_tykind)]
597 pub struct TyS<'tcx> {
598     pub kind: TyKind<'tcx>,
599     pub flags: TypeFlags,
600
601     /// This is a kind of confusing thing: it stores the smallest
602     /// binder such that
603     ///
604     /// (a) the binder itself captures nothing but
605     /// (b) all the late-bound things within the type are captured
606     ///     by some sub-binder.
607     ///
608     /// So, for a type without any late-bound things, like `u32`, this
609     /// will be *innermost*, because that is the innermost binder that
610     /// captures nothing. But for a type `&'D u32`, where `'D` is a
611     /// late-bound region with De Bruijn index `D`, this would be `D + 1`
612     /// -- the binder itself does not capture `D`, but `D` is captured
613     /// by an inner binder.
614     ///
615     /// We call this concept an "exclusive" binder `D` because all
616     /// De Bruijn indices within the type are contained within `0..D`
617     /// (exclusive).
618     outer_exclusive_binder: ty::DebruijnIndex,
619 }
620
621 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
622 #[cfg(target_arch = "x86_64")]
623 static_assert_size!(TyS<'_>, 32);
624
625 impl<'tcx> Ord for TyS<'tcx> {
626     fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
627         self.kind.cmp(&other.kind)
628     }
629 }
630
631 impl<'tcx> PartialOrd for TyS<'tcx> {
632     fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
633         Some(self.kind.cmp(&other.kind))
634     }
635 }
636
637 impl<'tcx> PartialEq for TyS<'tcx> {
638     #[inline]
639     fn eq(&self, other: &TyS<'tcx>) -> bool {
640         ptr::eq(self, other)
641     }
642 }
643 impl<'tcx> Eq for TyS<'tcx> {}
644
645 impl<'tcx> Hash for TyS<'tcx> {
646     fn hash<H: Hasher>(&self, s: &mut H) {
647         (self as *const TyS<'_>).hash(s)
648     }
649 }
650
651 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::TyS<'tcx> {
652     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
653         let ty::TyS {
654             ref kind,
655
656             // The other fields just provide fast access to information that is
657             // also contained in `kind`, so no need to hash them.
658             flags: _,
659
660             outer_exclusive_binder: _,
661         } = *self;
662
663         kind.hash_stable(hcx, hasher);
664     }
665 }
666
667 #[rustc_diagnostic_item = "Ty"]
668 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
669
670 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
671 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
672
673 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
674
675 extern "C" {
676     /// A dummy type used to force `List` to be unsized while not requiring references to it be wide
677     /// pointers.
678     type OpaqueListContents;
679 }
680
681 /// A wrapper for slices with the additional invariant
682 /// that the slice is interned and no other slice with
683 /// the same contents can exist in the same context.
684 /// This means we can use pointer for both
685 /// equality comparisons and hashing.
686 /// Note: `Slice` was already taken by the `Ty`.
687 #[repr(C)]
688 pub struct List<T> {
689     len: usize,
690     data: [T; 0],
691     opaque: OpaqueListContents,
692 }
693
694 unsafe impl<T: Sync> Sync for List<T> {}
695
696 impl<T: Copy> List<T> {
697     #[inline]
698     fn from_arena<'tcx>(arena: &'tcx Arena<'tcx>, slice: &[T]) -> &'tcx List<T> {
699         assert!(!mem::needs_drop::<T>());
700         assert!(mem::size_of::<T>() != 0);
701         assert!(slice.len() != 0);
702
703         // Align up the size of the len (usize) field
704         let align = mem::align_of::<T>();
705         let align_mask = align - 1;
706         let offset = mem::size_of::<usize>();
707         let offset = (offset + align_mask) & !align_mask;
708
709         let size = offset + slice.len() * mem::size_of::<T>();
710
711         let mem = arena
712             .dropless
713             .alloc_raw(size, cmp::max(mem::align_of::<T>(), mem::align_of::<usize>()));
714         unsafe {
715             let result = &mut *(mem.as_mut_ptr() as *mut List<T>);
716             // Write the length
717             result.len = slice.len();
718
719             // Write the elements
720             let arena_slice = slice::from_raw_parts_mut(result.data.as_mut_ptr(), result.len);
721             arena_slice.copy_from_slice(slice);
722
723             result
724         }
725     }
726 }
727
728 impl<T: fmt::Debug> fmt::Debug for List<T> {
729     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
730         (**self).fmt(f)
731     }
732 }
733
734 impl<T: Encodable> Encodable for List<T> {
735     #[inline]
736     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
737         (**self).encode(s)
738     }
739 }
740
741 impl<T> Ord for List<T>
742 where
743     T: Ord,
744 {
745     fn cmp(&self, other: &List<T>) -> Ordering {
746         if self == other { Ordering::Equal } else { <[T] as Ord>::cmp(&**self, &**other) }
747     }
748 }
749
750 impl<T> PartialOrd for List<T>
751 where
752     T: PartialOrd,
753 {
754     fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
755         if self == other {
756             Some(Ordering::Equal)
757         } else {
758             <[T] as PartialOrd>::partial_cmp(&**self, &**other)
759         }
760     }
761 }
762
763 impl<T: PartialEq> PartialEq for List<T> {
764     #[inline]
765     fn eq(&self, other: &List<T>) -> bool {
766         ptr::eq(self, other)
767     }
768 }
769 impl<T: Eq> Eq for List<T> {}
770
771 impl<T> Hash for List<T> {
772     #[inline]
773     fn hash<H: Hasher>(&self, s: &mut H) {
774         (self as *const List<T>).hash(s)
775     }
776 }
777
778 impl<T> Deref for List<T> {
779     type Target = [T];
780     #[inline(always)]
781     fn deref(&self) -> &[T] {
782         self.as_ref()
783     }
784 }
785
786 impl<T> AsRef<[T]> for List<T> {
787     #[inline(always)]
788     fn as_ref(&self) -> &[T] {
789         unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
790     }
791 }
792
793 impl<'a, T> IntoIterator for &'a List<T> {
794     type Item = &'a T;
795     type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
796     #[inline(always)]
797     fn into_iter(self) -> Self::IntoIter {
798         self[..].iter()
799     }
800 }
801
802 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
803
804 impl<T> List<T> {
805     #[inline(always)]
806     pub fn empty<'a>() -> &'a List<T> {
807         #[repr(align(64), C)]
808         struct EmptySlice([u8; 64]);
809         static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
810         assert!(mem::align_of::<T>() <= 64);
811         unsafe { &*(&EMPTY_SLICE as *const _ as *const List<T>) }
812     }
813 }
814
815 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
816 pub struct UpvarPath {
817     pub hir_id: hir::HirId,
818 }
819
820 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
821 /// the original var ID (that is, the root variable that is referenced
822 /// by the upvar) and the ID of the closure expression.
823 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
824 pub struct UpvarId {
825     pub var_path: UpvarPath,
826     pub closure_expr_id: LocalDefId,
827 }
828
829 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
830 pub enum BorrowKind {
831     /// Data must be immutable and is aliasable.
832     ImmBorrow,
833
834     /// Data must be immutable but not aliasable. This kind of borrow
835     /// cannot currently be expressed by the user and is used only in
836     /// implicit closure bindings. It is needed when the closure
837     /// is borrowing or mutating a mutable referent, e.g.:
838     ///
839     ///    let x: &mut isize = ...;
840     ///    let y = || *x += 5;
841     ///
842     /// If we were to try to translate this closure into a more explicit
843     /// form, we'd encounter an error with the code as written:
844     ///
845     ///    struct Env { x: & &mut isize }
846     ///    let x: &mut isize = ...;
847     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
848     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
849     ///
850     /// This is then illegal because you cannot mutate a `&mut` found
851     /// in an aliasable location. To solve, you'd have to translate with
852     /// an `&mut` borrow:
853     ///
854     ///    struct Env { x: & &mut isize }
855     ///    let x: &mut isize = ...;
856     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
857     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
858     ///
859     /// Now the assignment to `**env.x` is legal, but creating a
860     /// mutable pointer to `x` is not because `x` is not mutable. We
861     /// could fix this by declaring `x` as `let mut x`. This is ok in
862     /// user code, if awkward, but extra weird for closures, since the
863     /// borrow is hidden.
864     ///
865     /// So we introduce a "unique imm" borrow -- the referent is
866     /// immutable, but not aliasable. This solves the problem. For
867     /// simplicity, we don't give users the way to express this
868     /// borrow, it's just used when translating closures.
869     UniqueImmBorrow,
870
871     /// Data is mutable and not aliasable.
872     MutBorrow,
873 }
874
875 /// Information describing the capture of an upvar. This is computed
876 /// during `typeck`, specifically by `regionck`.
877 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
878 pub enum UpvarCapture<'tcx> {
879     /// Upvar is captured by value. This is always true when the
880     /// closure is labeled `move`, but can also be true in other cases
881     /// depending on inference.
882     ByValue,
883
884     /// Upvar is captured by reference.
885     ByRef(UpvarBorrow<'tcx>),
886 }
887
888 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
889 pub struct UpvarBorrow<'tcx> {
890     /// The kind of borrow: by-ref upvars have access to shared
891     /// immutable borrows, which are not part of the normal language
892     /// syntax.
893     pub kind: BorrowKind,
894
895     /// Region of the resulting reference.
896     pub region: ty::Region<'tcx>,
897 }
898
899 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
900 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
901
902 #[derive(Clone, Copy, PartialEq, Eq)]
903 pub enum IntVarValue {
904     IntType(ast::IntTy),
905     UintType(ast::UintTy),
906 }
907
908 #[derive(Clone, Copy, PartialEq, Eq)]
909 pub struct FloatVarValue(pub ast::FloatTy);
910
911 impl ty::EarlyBoundRegion {
912     pub fn to_bound_region(&self) -> ty::BoundRegion {
913         ty::BoundRegion::BrNamed(self.def_id, self.name)
914     }
915
916     /// Does this early bound region have a name? Early bound regions normally
917     /// always have names except when using anonymous lifetimes (`'_`).
918     pub fn has_name(&self) -> bool {
919         self.name != kw::UnderscoreLifetime
920     }
921 }
922
923 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
924 pub enum GenericParamDefKind {
925     Lifetime,
926     Type {
927         has_default: bool,
928         object_lifetime_default: ObjectLifetimeDefault,
929         synthetic: Option<hir::SyntheticTyParamKind>,
930     },
931     Const,
932 }
933
934 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
935 pub struct GenericParamDef {
936     pub name: Symbol,
937     pub def_id: DefId,
938     pub index: u32,
939
940     /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
941     /// on generic parameter `'a`/`T`, asserts data behind the parameter
942     /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
943     pub pure_wrt_drop: bool,
944
945     pub kind: GenericParamDefKind,
946 }
947
948 impl GenericParamDef {
949     pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
950         if let GenericParamDefKind::Lifetime = self.kind {
951             ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
952         } else {
953             bug!("cannot convert a non-lifetime parameter def to an early bound region")
954         }
955     }
956
957     pub fn to_bound_region(&self) -> ty::BoundRegion {
958         if let GenericParamDefKind::Lifetime = self.kind {
959             self.to_early_bound_region_data().to_bound_region()
960         } else {
961             bug!("cannot convert a non-lifetime parameter def to an early bound region")
962         }
963     }
964 }
965
966 #[derive(Default)]
967 pub struct GenericParamCount {
968     pub lifetimes: usize,
969     pub types: usize,
970     pub consts: usize,
971 }
972
973 /// Information about the formal type/lifetime parameters associated
974 /// with an item or method. Analogous to `hir::Generics`.
975 ///
976 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
977 /// `Self` (optionally), `Lifetime` params..., `Type` params...
978 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
979 pub struct Generics {
980     pub parent: Option<DefId>,
981     pub parent_count: usize,
982     pub params: Vec<GenericParamDef>,
983
984     /// Reverse map to the `index` field of each `GenericParamDef`.
985     #[stable_hasher(ignore)]
986     pub param_def_id_to_index: FxHashMap<DefId, u32>,
987
988     pub has_self: bool,
989     pub has_late_bound_regions: Option<Span>,
990 }
991
992 impl<'tcx> Generics {
993     pub fn count(&self) -> usize {
994         self.parent_count + self.params.len()
995     }
996
997     pub fn own_counts(&self) -> GenericParamCount {
998         // We could cache this as a property of `GenericParamCount`, but
999         // the aim is to refactor this away entirely eventually and the
1000         // presence of this method will be a constant reminder.
1001         let mut own_counts: GenericParamCount = Default::default();
1002
1003         for param in &self.params {
1004             match param.kind {
1005                 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
1006                 GenericParamDefKind::Type { .. } => own_counts.types += 1,
1007                 GenericParamDefKind::Const => own_counts.consts += 1,
1008             };
1009         }
1010
1011         own_counts
1012     }
1013
1014     pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
1015         if self.own_requires_monomorphization() {
1016             return true;
1017         }
1018
1019         if let Some(parent_def_id) = self.parent {
1020             let parent = tcx.generics_of(parent_def_id);
1021             parent.requires_monomorphization(tcx)
1022         } else {
1023             false
1024         }
1025     }
1026
1027     pub fn own_requires_monomorphization(&self) -> bool {
1028         for param in &self.params {
1029             match param.kind {
1030                 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
1031                 GenericParamDefKind::Lifetime => {}
1032             }
1033         }
1034         false
1035     }
1036
1037     pub fn region_param(
1038         &'tcx self,
1039         param: &EarlyBoundRegion,
1040         tcx: TyCtxt<'tcx>,
1041     ) -> &'tcx GenericParamDef {
1042         if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1043             let param = &self.params[index as usize];
1044             match param.kind {
1045                 GenericParamDefKind::Lifetime => param,
1046                 _ => bug!("expected lifetime parameter, but found another generic parameter"),
1047             }
1048         } else {
1049             tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1050                 .region_param(param, tcx)
1051         }
1052     }
1053
1054     /// Returns the `GenericParamDef` associated with this `ParamTy`.
1055     pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
1056         if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1057             let param = &self.params[index as usize];
1058             match param.kind {
1059                 GenericParamDefKind::Type { .. } => param,
1060                 _ => bug!("expected type parameter, but found another generic parameter"),
1061             }
1062         } else {
1063             tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
1064                 .type_param(param, tcx)
1065         }
1066     }
1067
1068     /// Returns the `ConstParameterDef` associated with this `ParamConst`.
1069     pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
1070         if let Some(index) = param.index.checked_sub(self.parent_count as u32) {
1071             let param = &self.params[index as usize];
1072             match param.kind {
1073                 GenericParamDefKind::Const => param,
1074                 _ => bug!("expected const parameter, but found another generic parameter"),
1075             }
1076         } else {
1077             tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
1078                 .const_param(param, tcx)
1079         }
1080     }
1081 }
1082
1083 /// Bounds on generics.
1084 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
1085 pub struct GenericPredicates<'tcx> {
1086     pub parent: Option<DefId>,
1087     pub predicates: &'tcx [(Predicate<'tcx>, Span)],
1088 }
1089
1090 impl<'tcx> GenericPredicates<'tcx> {
1091     pub fn instantiate(
1092         &self,
1093         tcx: TyCtxt<'tcx>,
1094         substs: SubstsRef<'tcx>,
1095     ) -> InstantiatedPredicates<'tcx> {
1096         let mut instantiated = InstantiatedPredicates::empty();
1097         self.instantiate_into(tcx, &mut instantiated, substs);
1098         instantiated
1099     }
1100
1101     pub fn instantiate_own(
1102         &self,
1103         tcx: TyCtxt<'tcx>,
1104         substs: SubstsRef<'tcx>,
1105     ) -> InstantiatedPredicates<'tcx> {
1106         InstantiatedPredicates {
1107             predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
1108             spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1109         }
1110     }
1111
1112     fn instantiate_into(
1113         &self,
1114         tcx: TyCtxt<'tcx>,
1115         instantiated: &mut InstantiatedPredicates<'tcx>,
1116         substs: SubstsRef<'tcx>,
1117     ) {
1118         if let Some(def_id) = self.parent {
1119             tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
1120         }
1121         instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
1122         instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
1123     }
1124
1125     pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
1126         let mut instantiated = InstantiatedPredicates::empty();
1127         self.instantiate_identity_into(tcx, &mut instantiated);
1128         instantiated
1129     }
1130
1131     fn instantiate_identity_into(
1132         &self,
1133         tcx: TyCtxt<'tcx>,
1134         instantiated: &mut InstantiatedPredicates<'tcx>,
1135     ) {
1136         if let Some(def_id) = self.parent {
1137             tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
1138         }
1139         instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
1140         instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
1141     }
1142
1143     pub fn instantiate_supertrait(
1144         &self,
1145         tcx: TyCtxt<'tcx>,
1146         poly_trait_ref: &ty::PolyTraitRef<'tcx>,
1147     ) -> InstantiatedPredicates<'tcx> {
1148         assert_eq!(self.parent, None);
1149         InstantiatedPredicates {
1150             predicates: self
1151                 .predicates
1152                 .iter()
1153                 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1154                 .collect(),
1155             spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1156         }
1157     }
1158 }
1159
1160 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1161 #[derive(HashStable, TypeFoldable)]
1162 pub enum Predicate<'tcx> {
1163     /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1164     /// the `Self` type of the trait reference and `A`, `B`, and `C`
1165     /// would be the type parameters.
1166     ///
1167     /// A trait predicate will have `Constness::Const` if it originates
1168     /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1169     /// `const fn foobar<Foo: Bar>() {}`).
1170     Trait(PolyTraitPredicate<'tcx>, Constness),
1171
1172     /// `where 'a: 'b`
1173     RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1174
1175     /// `where T: 'a`
1176     TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1177
1178     /// `where <T as TraitRef>::Name == X`, approximately.
1179     /// See the `ProjectionPredicate` struct for details.
1180     Projection(PolyProjectionPredicate<'tcx>),
1181
1182     /// No syntax: `T` well-formed.
1183     WellFormed(Ty<'tcx>),
1184
1185     /// Trait must be object-safe.
1186     ObjectSafe(DefId),
1187
1188     /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1189     /// for some substitutions `...` and `T` being a closure type.
1190     /// Satisfied (or refuted) once we know the closure's kind.
1191     ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1192
1193     /// `T1 <: T2`
1194     Subtype(PolySubtypePredicate<'tcx>),
1195
1196     /// Constant initializer must evaluate successfully.
1197     ConstEvaluatable(DefId, SubstsRef<'tcx>),
1198 }
1199
1200 /// The crate outlives map is computed during typeck and contains the
1201 /// outlives of every item in the local crate. You should not use it
1202 /// directly, because to do so will make your pass dependent on the
1203 /// HIR of every item in the local crate. Instead, use
1204 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1205 /// item.
1206 #[derive(HashStable)]
1207 pub struct CratePredicatesMap<'tcx> {
1208     /// For each struct with outlive bounds, maps to a vector of the
1209     /// predicate of its outlive bounds. If an item has no outlives
1210     /// bounds, it will have no entry.
1211     pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1212 }
1213
1214 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
1215     fn as_ref(&self) -> &Predicate<'tcx> {
1216         self
1217     }
1218 }
1219
1220 impl<'tcx> Predicate<'tcx> {
1221     /// Performs a substitution suitable for going from a
1222     /// poly-trait-ref to supertraits that must hold if that
1223     /// poly-trait-ref holds. This is slightly different from a normal
1224     /// substitution in terms of what happens with bound regions. See
1225     /// lengthy comment below for details.
1226     pub fn subst_supertrait(
1227         &self,
1228         tcx: TyCtxt<'tcx>,
1229         trait_ref: &ty::PolyTraitRef<'tcx>,
1230     ) -> ty::Predicate<'tcx> {
1231         // The interaction between HRTB and supertraits is not entirely
1232         // obvious. Let me walk you (and myself) through an example.
1233         //
1234         // Let's start with an easy case. Consider two traits:
1235         //
1236         //     trait Foo<'a>: Bar<'a,'a> { }
1237         //     trait Bar<'b,'c> { }
1238         //
1239         // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1240         // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1241         // knew that `Foo<'x>` (for any 'x) then we also know that
1242         // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1243         // normal substitution.
1244         //
1245         // In terms of why this is sound, the idea is that whenever there
1246         // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1247         // holds.  So if there is an impl of `T:Foo<'a>` that applies to
1248         // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1249         // `'a`.
1250         //
1251         // Another example to be careful of is this:
1252         //
1253         //     trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1254         //     trait Bar1<'b,'c> { }
1255         //
1256         // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1257         // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1258         // reason is similar to the previous example: any impl of
1259         // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`.  So
1260         // basically we would want to collapse the bound lifetimes from
1261         // the input (`trait_ref`) and the supertraits.
1262         //
1263         // To achieve this in practice is fairly straightforward. Let's
1264         // consider the more complicated scenario:
1265         //
1266         // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1267         //   has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1268         //   where both `'x` and `'b` would have a DB index of 1.
1269         //   The substitution from the input trait-ref is therefore going to be
1270         //   `'a => 'x` (where `'x` has a DB index of 1).
1271         // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1272         //   early-bound parameter and `'b' is a late-bound parameter with a
1273         //   DB index of 1.
1274         // - If we replace `'a` with `'x` from the input, it too will have
1275         //   a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1276         //   just as we wanted.
1277         //
1278         // There is only one catch. If we just apply the substitution `'a
1279         // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1280         // adjust the DB index because we substituting into a binder (it
1281         // tries to be so smart...) resulting in `for<'x> for<'b>
1282         // Bar1<'x,'b>` (we have no syntax for this, so use your
1283         // imagination). Basically the 'x will have DB index of 2 and 'b
1284         // will have DB index of 1. Not quite what we want. So we apply
1285         // the substitution to the *contents* of the trait reference,
1286         // rather than the trait reference itself (put another way, the
1287         // substitution code expects equal binding levels in the values
1288         // from the substitution and the value being substituted into, and
1289         // this trick achieves that).
1290
1291         let substs = &trait_ref.skip_binder().substs;
1292         match *self {
1293             Predicate::Trait(ref binder, constness) => {
1294                 Predicate::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness)
1295             }
1296             Predicate::Subtype(ref binder) => {
1297                 Predicate::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1298             }
1299             Predicate::RegionOutlives(ref binder) => {
1300                 Predicate::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1301             }
1302             Predicate::TypeOutlives(ref binder) => {
1303                 Predicate::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1304             }
1305             Predicate::Projection(ref binder) => {
1306                 Predicate::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1307             }
1308             Predicate::WellFormed(data) => Predicate::WellFormed(data.subst(tcx, substs)),
1309             Predicate::ObjectSafe(trait_def_id) => Predicate::ObjectSafe(trait_def_id),
1310             Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1311                 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1312             }
1313             Predicate::ConstEvaluatable(def_id, const_substs) => {
1314                 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1315             }
1316         }
1317     }
1318 }
1319
1320 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1321 #[derive(HashStable, TypeFoldable)]
1322 pub struct TraitPredicate<'tcx> {
1323     pub trait_ref: TraitRef<'tcx>,
1324 }
1325
1326 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1327
1328 impl<'tcx> TraitPredicate<'tcx> {
1329     pub fn def_id(&self) -> DefId {
1330         self.trait_ref.def_id
1331     }
1332
1333     pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
1334         self.trait_ref.input_types()
1335     }
1336
1337     pub fn self_ty(&self) -> Ty<'tcx> {
1338         self.trait_ref.self_ty()
1339     }
1340 }
1341
1342 impl<'tcx> PolyTraitPredicate<'tcx> {
1343     pub fn def_id(&self) -> DefId {
1344         // Ok to skip binder since trait `DefId` does not care about regions.
1345         self.skip_binder().def_id()
1346     }
1347 }
1348
1349 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1350 #[derive(HashStable, TypeFoldable)]
1351 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1352 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1353 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1354 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1355 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1356 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1357
1358 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1359 #[derive(HashStable, TypeFoldable)]
1360 pub struct SubtypePredicate<'tcx> {
1361     pub a_is_expected: bool,
1362     pub a: Ty<'tcx>,
1363     pub b: Ty<'tcx>,
1364 }
1365 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1366
1367 /// This kind of predicate has no *direct* correspondent in the
1368 /// syntax, but it roughly corresponds to the syntactic forms:
1369 ///
1370 /// 1. `T: TraitRef<..., Item = Type>`
1371 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1372 ///
1373 /// In particular, form #1 is "desugared" to the combination of a
1374 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1375 /// predicates. Form #2 is a broader form in that it also permits
1376 /// equality between arbitrary types. Processing an instance of
1377 /// Form #2 eventually yields one of these `ProjectionPredicate`
1378 /// instances to normalize the LHS.
1379 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1380 #[derive(HashStable, TypeFoldable)]
1381 pub struct ProjectionPredicate<'tcx> {
1382     pub projection_ty: ProjectionTy<'tcx>,
1383     pub ty: Ty<'tcx>,
1384 }
1385
1386 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1387
1388 impl<'tcx> PolyProjectionPredicate<'tcx> {
1389     /// Returns the `DefId` of the associated item being projected.
1390     pub fn item_def_id(&self) -> DefId {
1391         self.skip_binder().projection_ty.item_def_id
1392     }
1393
1394     #[inline]
1395     pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1396         // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1397         // `self.0.trait_ref` is permitted to have escaping regions.
1398         // This is because here `self` has a `Binder` and so does our
1399         // return value, so we are preserving the number of binding
1400         // levels.
1401         self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1402     }
1403
1404     pub fn ty(&self) -> Binder<Ty<'tcx>> {
1405         self.map_bound(|predicate| predicate.ty)
1406     }
1407
1408     /// The `DefId` of the `TraitItem` for the associated type.
1409     ///
1410     /// Note that this is not the `DefId` of the `TraitRef` containing this
1411     /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1412     pub fn projection_def_id(&self) -> DefId {
1413         // Ok to skip binder since trait `DefId` does not care about regions.
1414         self.skip_binder().projection_ty.item_def_id
1415     }
1416 }
1417
1418 pub trait ToPolyTraitRef<'tcx> {
1419     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1420 }
1421
1422 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1423     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1424         ty::Binder::dummy(*self)
1425     }
1426 }
1427
1428 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1429     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1430         self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1431     }
1432 }
1433
1434 pub trait ToPredicate<'tcx> {
1435     fn to_predicate(&self) -> Predicate<'tcx>;
1436 }
1437
1438 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1439     fn to_predicate(&self) -> Predicate<'tcx> {
1440         ty::Predicate::Trait(
1441             ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }),
1442             self.constness,
1443         )
1444     }
1445 }
1446
1447 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> {
1448     fn to_predicate(&self) -> Predicate<'tcx> {
1449         ty::Predicate::Trait(
1450             ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value.clone() }),
1451             self.constness,
1452         )
1453     }
1454 }
1455
1456 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1457     fn to_predicate(&self) -> Predicate<'tcx> {
1458         ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1459     }
1460 }
1461
1462 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&PolyTraitRef<'tcx>> {
1463     fn to_predicate(&self) -> Predicate<'tcx> {
1464         ty::Predicate::Trait(self.value.to_poly_trait_predicate(), self.constness)
1465     }
1466 }
1467
1468 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1469     fn to_predicate(&self) -> Predicate<'tcx> {
1470         Predicate::RegionOutlives(*self)
1471     }
1472 }
1473
1474 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1475     fn to_predicate(&self) -> Predicate<'tcx> {
1476         Predicate::TypeOutlives(*self)
1477     }
1478 }
1479
1480 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1481     fn to_predicate(&self) -> Predicate<'tcx> {
1482         Predicate::Projection(*self)
1483     }
1484 }
1485
1486 // A custom iterator used by `Predicate::walk_tys`.
1487 enum WalkTysIter<'tcx, I, J, K>
1488 where
1489     I: Iterator<Item = Ty<'tcx>>,
1490     J: Iterator<Item = Ty<'tcx>>,
1491     K: Iterator<Item = Ty<'tcx>>,
1492 {
1493     None,
1494     One(Ty<'tcx>),
1495     Two(Ty<'tcx>, Ty<'tcx>),
1496     Types(I),
1497     InputTypes(J),
1498     ProjectionTypes(K),
1499 }
1500
1501 impl<'tcx, I, J, K> Iterator for WalkTysIter<'tcx, I, J, K>
1502 where
1503     I: Iterator<Item = Ty<'tcx>>,
1504     J: Iterator<Item = Ty<'tcx>>,
1505     K: Iterator<Item = Ty<'tcx>>,
1506 {
1507     type Item = Ty<'tcx>;
1508
1509     fn next(&mut self) -> Option<Ty<'tcx>> {
1510         match *self {
1511             WalkTysIter::None => None,
1512             WalkTysIter::One(item) => {
1513                 *self = WalkTysIter::None;
1514                 Some(item)
1515             }
1516             WalkTysIter::Two(item1, item2) => {
1517                 *self = WalkTysIter::One(item2);
1518                 Some(item1)
1519             }
1520             WalkTysIter::Types(ref mut iter) => iter.next(),
1521             WalkTysIter::InputTypes(ref mut iter) => iter.next(),
1522             WalkTysIter::ProjectionTypes(ref mut iter) => iter.next(),
1523         }
1524     }
1525 }
1526
1527 impl<'tcx> Predicate<'tcx> {
1528     /// Iterates over the types in this predicate. Note that in all
1529     /// cases this is skipping over a binder, so late-bound regions
1530     /// with depth 0 are bound by the predicate.
1531     pub fn walk_tys(&'a self) -> impl Iterator<Item = Ty<'tcx>> + 'a {
1532         match *self {
1533             ty::Predicate::Trait(ref data, _) => {
1534                 WalkTysIter::InputTypes(data.skip_binder().input_types())
1535             }
1536             ty::Predicate::Subtype(binder) => {
1537                 let SubtypePredicate { a, b, a_is_expected: _ } = binder.skip_binder();
1538                 WalkTysIter::Two(a, b)
1539             }
1540             ty::Predicate::TypeOutlives(binder) => WalkTysIter::One(binder.skip_binder().0),
1541             ty::Predicate::RegionOutlives(..) => WalkTysIter::None,
1542             ty::Predicate::Projection(ref data) => {
1543                 let inner = data.skip_binder();
1544                 WalkTysIter::ProjectionTypes(
1545                     inner.projection_ty.substs.types().chain(Some(inner.ty)),
1546                 )
1547             }
1548             ty::Predicate::WellFormed(data) => WalkTysIter::One(data),
1549             ty::Predicate::ObjectSafe(_trait_def_id) => WalkTysIter::None,
1550             ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1551                 WalkTysIter::Types(closure_substs.types())
1552             }
1553             ty::Predicate::ConstEvaluatable(_, substs) => WalkTysIter::Types(substs.types()),
1554         }
1555     }
1556
1557     pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1558         match *self {
1559             Predicate::Trait(ref t, _) => Some(t.to_poly_trait_ref()),
1560             Predicate::Projection(..)
1561             | Predicate::Subtype(..)
1562             | Predicate::RegionOutlives(..)
1563             | Predicate::WellFormed(..)
1564             | Predicate::ObjectSafe(..)
1565             | Predicate::ClosureKind(..)
1566             | Predicate::TypeOutlives(..)
1567             | Predicate::ConstEvaluatable(..) => None,
1568         }
1569     }
1570
1571     pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1572         match *self {
1573             Predicate::TypeOutlives(data) => Some(data),
1574             Predicate::Trait(..)
1575             | Predicate::Projection(..)
1576             | Predicate::Subtype(..)
1577             | Predicate::RegionOutlives(..)
1578             | Predicate::WellFormed(..)
1579             | Predicate::ObjectSafe(..)
1580             | Predicate::ClosureKind(..)
1581             | Predicate::ConstEvaluatable(..) => None,
1582         }
1583     }
1584 }
1585
1586 /// Represents the bounds declared on a particular set of type
1587 /// parameters. Should eventually be generalized into a flag list of
1588 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1589 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1590 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1591 /// the `GenericPredicates` are expressed in terms of the bound type
1592 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1593 /// represented a set of bounds for some particular instantiation,
1594 /// meaning that the generic parameters have been substituted with
1595 /// their values.
1596 ///
1597 /// Example:
1598 ///
1599 ///     struct Foo<T, U: Bar<T>> { ... }
1600 ///
1601 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1602 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1603 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1604 /// [usize:Bar<isize>]]`.
1605 #[derive(Clone, Debug, TypeFoldable)]
1606 pub struct InstantiatedPredicates<'tcx> {
1607     pub predicates: Vec<Predicate<'tcx>>,
1608     pub spans: Vec<Span>,
1609 }
1610
1611 impl<'tcx> InstantiatedPredicates<'tcx> {
1612     pub fn empty() -> InstantiatedPredicates<'tcx> {
1613         InstantiatedPredicates { predicates: vec![], spans: vec![] }
1614     }
1615
1616     pub fn is_empty(&self) -> bool {
1617         self.predicates.is_empty()
1618     }
1619 }
1620
1621 rustc_index::newtype_index! {
1622     /// "Universes" are used during type- and trait-checking in the
1623     /// presence of `for<..>` binders to control what sets of names are
1624     /// visible. Universes are arranged into a tree: the root universe
1625     /// contains names that are always visible. Each child then adds a new
1626     /// set of names that are visible, in addition to those of its parent.
1627     /// We say that the child universe "extends" the parent universe with
1628     /// new names.
1629     ///
1630     /// To make this more concrete, consider this program:
1631     ///
1632     /// ```
1633     /// struct Foo { }
1634     /// fn bar<T>(x: T) {
1635     ///   let y: for<'a> fn(&'a u8, Foo) = ...;
1636     /// }
1637     /// ```
1638     ///
1639     /// The struct name `Foo` is in the root universe U0. But the type
1640     /// parameter `T`, introduced on `bar`, is in an extended universe U1
1641     /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1642     /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1643     /// region `'a` is in a universe U2 that extends U1, because we can
1644     /// name it inside the fn type but not outside.
1645     ///
1646     /// Universes are used to do type- and trait-checking around these
1647     /// "forall" binders (also called **universal quantification**). The
1648     /// idea is that when, in the body of `bar`, we refer to `T` as a
1649     /// type, we aren't referring to any type in particular, but rather a
1650     /// kind of "fresh" type that is distinct from all other types we have
1651     /// actually declared. This is called a **placeholder** type, and we
1652     /// use universes to talk about this. In other words, a type name in
1653     /// universe 0 always corresponds to some "ground" type that the user
1654     /// declared, but a type name in a non-zero universe is a placeholder
1655     /// type -- an idealized representative of "types in general" that we
1656     /// use for checking generic functions.
1657     pub struct UniverseIndex {
1658         derive [HashStable]
1659         DEBUG_FORMAT = "U{}",
1660     }
1661 }
1662
1663 impl UniverseIndex {
1664     pub const ROOT: UniverseIndex = UniverseIndex::from_u32_const(0);
1665
1666     /// Returns the "next" universe index in order -- this new index
1667     /// is considered to extend all previous universes. This
1668     /// corresponds to entering a `forall` quantifier. So, for
1669     /// example, suppose we have this type in universe `U`:
1670     ///
1671     /// ```
1672     /// for<'a> fn(&'a u32)
1673     /// ```
1674     ///
1675     /// Once we "enter" into this `for<'a>` quantifier, we are in a
1676     /// new universe that extends `U` -- in this new universe, we can
1677     /// name the region `'a`, but that region was not nameable from
1678     /// `U` because it was not in scope there.
1679     pub fn next_universe(self) -> UniverseIndex {
1680         UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1681     }
1682
1683     /// Returns `true` if `self` can name a name from `other` -- in other words,
1684     /// if the set of names in `self` is a superset of those in
1685     /// `other` (`self >= other`).
1686     pub fn can_name(self, other: UniverseIndex) -> bool {
1687         self.private >= other.private
1688     }
1689
1690     /// Returns `true` if `self` cannot name some names from `other` -- in other
1691     /// words, if the set of names in `self` is a strict subset of
1692     /// those in `other` (`self < other`).
1693     pub fn cannot_name(self, other: UniverseIndex) -> bool {
1694         self.private < other.private
1695     }
1696 }
1697
1698 /// The "placeholder index" fully defines a placeholder region.
1699 /// Placeholder regions are identified by both a **universe** as well
1700 /// as a "bound-region" within that universe. The `bound_region` is
1701 /// basically a name -- distinct bound regions within the same
1702 /// universe are just two regions with an unknown relationship to one
1703 /// another.
1704 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1705 pub struct Placeholder<T> {
1706     pub universe: UniverseIndex,
1707     pub name: T,
1708 }
1709
1710 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1711 where
1712     T: HashStable<StableHashingContext<'a>>,
1713 {
1714     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1715         self.universe.hash_stable(hcx, hasher);
1716         self.name.hash_stable(hcx, hasher);
1717     }
1718 }
1719
1720 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1721
1722 pub type PlaceholderType = Placeholder<BoundVar>;
1723
1724 pub type PlaceholderConst = Placeholder<BoundVar>;
1725
1726 /// When type checking, we use the `ParamEnv` to track
1727 /// details about the set of where-clauses that are in scope at this
1728 /// particular point.
1729 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TypeFoldable)]
1730 pub struct ParamEnv<'tcx> {
1731     /// `Obligation`s that the caller must satisfy. This is basically
1732     /// the set of bounds on the in-scope type parameters, translated
1733     /// into `Obligation`s, and elaborated and normalized.
1734     pub caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1735
1736     /// Typically, this is `Reveal::UserFacing`, but during codegen we
1737     /// want `Reveal::All` -- note that this is always paired with an
1738     /// empty environment. To get that, use `ParamEnv::reveal()`.
1739     pub reveal: traits::Reveal,
1740
1741     /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1742     /// register that `def_id` (useful for transitioning to the chalk trait
1743     /// solver).
1744     pub def_id: Option<DefId>,
1745 }
1746
1747 impl<'tcx> ParamEnv<'tcx> {
1748     /// Construct a trait environment suitable for contexts where
1749     /// there are no where-clauses in scope. Hidden types (like `impl
1750     /// Trait`) are left hidden, so this is suitable for ordinary
1751     /// type-checking.
1752     #[inline]
1753     pub fn empty() -> Self {
1754         Self::new(List::empty(), Reveal::UserFacing, None)
1755     }
1756
1757     /// Construct a trait environment with no where-clauses in scope
1758     /// where the values of all `impl Trait` and other hidden types
1759     /// are revealed. This is suitable for monomorphized, post-typeck
1760     /// environments like codegen or doing optimizations.
1761     ///
1762     /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1763     /// or invoke `param_env.with_reveal_all()`.
1764     #[inline]
1765     pub fn reveal_all() -> Self {
1766         Self::new(List::empty(), Reveal::All, None)
1767     }
1768
1769     /// Construct a trait environment with the given set of predicates.
1770     #[inline]
1771     pub fn new(
1772         caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1773         reveal: Reveal,
1774         def_id: Option<DefId>,
1775     ) -> Self {
1776         ty::ParamEnv { caller_bounds, reveal, def_id }
1777     }
1778
1779     /// Returns a new parameter environment with the same clauses, but
1780     /// which "reveals" the true results of projections in all cases
1781     /// (even for associated types that are specializable). This is
1782     /// the desired behavior during codegen and certain other special
1783     /// contexts; normally though we want to use `Reveal::UserFacing`,
1784     /// which is the default.
1785     pub fn with_reveal_all(self) -> Self {
1786         ty::ParamEnv { reveal: Reveal::All, ..self }
1787     }
1788
1789     /// Returns this same environment but with no caller bounds.
1790     pub fn without_caller_bounds(self) -> Self {
1791         ty::ParamEnv { caller_bounds: List::empty(), ..self }
1792     }
1793
1794     /// Creates a suitable environment in which to perform trait
1795     /// queries on the given value. When type-checking, this is simply
1796     /// the pair of the environment plus value. But when reveal is set to
1797     /// All, then if `value` does not reference any type parameters, we will
1798     /// pair it with the empty environment. This improves caching and is generally
1799     /// invisible.
1800     ///
1801     /// N.B., we preserve the environment when type-checking because it
1802     /// is possible for the user to have wacky where-clauses like
1803     /// `where Box<u32>: Copy`, which are clearly never
1804     /// satisfiable. We generally want to behave as if they were true,
1805     /// although the surrounding function is never reachable.
1806     pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1807         match self.reveal {
1808             Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1809
1810             Reveal::All => {
1811                 if value.has_placeholders() || value.needs_infer() || value.has_param_types() {
1812                     ParamEnvAnd { param_env: self, value }
1813                 } else {
1814                     ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1815                 }
1816             }
1817         }
1818     }
1819 }
1820
1821 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1822 pub struct ConstnessAnd<T> {
1823     pub constness: Constness,
1824     pub value: T,
1825 }
1826
1827 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate()` to ensure that
1828 // the constness of trait bounds is being propagated correctly.
1829 pub trait WithConstness: Sized {
1830     #[inline]
1831     fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1832         ConstnessAnd { constness, value: self }
1833     }
1834
1835     #[inline]
1836     fn with_const(self) -> ConstnessAnd<Self> {
1837         self.with_constness(Constness::Const)
1838     }
1839
1840     #[inline]
1841     fn without_const(self) -> ConstnessAnd<Self> {
1842         self.with_constness(Constness::NotConst)
1843     }
1844 }
1845
1846 impl<T> WithConstness for T {}
1847
1848 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1849 pub struct ParamEnvAnd<'tcx, T> {
1850     pub param_env: ParamEnv<'tcx>,
1851     pub value: T,
1852 }
1853
1854 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1855     pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1856         (self.param_env, self.value)
1857     }
1858 }
1859
1860 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1861 where
1862     T: HashStable<StableHashingContext<'a>>,
1863 {
1864     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1865         let ParamEnvAnd { ref param_env, ref value } = *self;
1866
1867         param_env.hash_stable(hcx, hasher);
1868         value.hash_stable(hcx, hasher);
1869     }
1870 }
1871
1872 #[derive(Copy, Clone, Debug, HashStable)]
1873 pub struct Destructor {
1874     /// The `DefId` of the destructor method
1875     pub did: DefId,
1876 }
1877
1878 bitflags! {
1879     #[derive(HashStable)]
1880     pub struct AdtFlags: u32 {
1881         const NO_ADT_FLAGS        = 0;
1882         /// Indicates whether the ADT is an enum.
1883         const IS_ENUM             = 1 << 0;
1884         /// Indicates whether the ADT is a union.
1885         const IS_UNION            = 1 << 1;
1886         /// Indicates whether the ADT is a struct.
1887         const IS_STRUCT           = 1 << 2;
1888         /// Indicates whether the ADT is a struct and has a constructor.
1889         const HAS_CTOR            = 1 << 3;
1890         /// Indicates whether the type is `PhantomData`.
1891         const IS_PHANTOM_DATA     = 1 << 4;
1892         /// Indicates whether the type has a `#[fundamental]` attribute.
1893         const IS_FUNDAMENTAL      = 1 << 5;
1894         /// Indicates whether the type is `Box`.
1895         const IS_BOX              = 1 << 6;
1896         /// Indicates whether the type is `ManuallyDrop`.
1897         const IS_MANUALLY_DROP    = 1 << 7;
1898         // FIXME(matthewjasper) replace these with diagnostic items
1899         /// Indicates whether the type is an `Arc`.
1900         const IS_ARC              = 1 << 8;
1901         /// Indicates whether the type is an `Rc`.
1902         const IS_RC               = 1 << 9;
1903         /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1904         /// (i.e., this flag is never set unless this ADT is an enum).
1905         const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 10;
1906     }
1907 }
1908
1909 bitflags! {
1910     #[derive(HashStable)]
1911     pub struct VariantFlags: u32 {
1912         const NO_VARIANT_FLAGS        = 0;
1913         /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1914         const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1915     }
1916 }
1917
1918 /// Definition of a variant -- a struct's fields or a enum variant.
1919 #[derive(Debug, HashStable)]
1920 pub struct VariantDef {
1921     /// `DefId` that identifies the variant itself.
1922     /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1923     pub def_id: DefId,
1924     /// `DefId` that identifies the variant's constructor.
1925     /// If this variant is a struct variant, then this is `None`.
1926     pub ctor_def_id: Option<DefId>,
1927     /// Variant or struct name.
1928     #[stable_hasher(project(name))]
1929     pub ident: Ident,
1930     /// Discriminant of this variant.
1931     pub discr: VariantDiscr,
1932     /// Fields of this variant.
1933     pub fields: Vec<FieldDef>,
1934     /// Type of constructor of variant.
1935     pub ctor_kind: CtorKind,
1936     /// Flags of the variant (e.g. is field list non-exhaustive)?
1937     flags: VariantFlags,
1938     /// Variant is obtained as part of recovering from a syntactic error.
1939     /// May be incomplete or bogus.
1940     pub recovered: bool,
1941 }
1942
1943 impl<'tcx> VariantDef {
1944     /// Creates a new `VariantDef`.
1945     ///
1946     /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1947     /// represents an enum variant).
1948     ///
1949     /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1950     /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1951     ///
1952     /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1953     /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1954     /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1955     /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1956     /// built-in trait), and we do not want to load attributes twice.
1957     ///
1958     /// If someone speeds up attribute loading to not be a performance concern, they can
1959     /// remove this hack and use the constructor `DefId` everywhere.
1960     pub fn new(
1961         tcx: TyCtxt<'tcx>,
1962         ident: Ident,
1963         variant_did: Option<DefId>,
1964         ctor_def_id: Option<DefId>,
1965         discr: VariantDiscr,
1966         fields: Vec<FieldDef>,
1967         ctor_kind: CtorKind,
1968         adt_kind: AdtKind,
1969         parent_did: DefId,
1970         recovered: bool,
1971     ) -> Self {
1972         debug!(
1973             "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1974              fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1975             ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1976         );
1977
1978         let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1979         if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
1980             debug!("found non-exhaustive field list for {:?}", parent_did);
1981             flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1982         } else if let Some(variant_did) = variant_did {
1983             if tcx.has_attr(variant_did, sym::non_exhaustive) {
1984                 debug!("found non-exhaustive field list for {:?}", variant_did);
1985                 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1986             }
1987         }
1988
1989         VariantDef {
1990             def_id: variant_did.unwrap_or(parent_did),
1991             ctor_def_id,
1992             ident,
1993             discr,
1994             fields,
1995             ctor_kind,
1996             flags,
1997             recovered,
1998         }
1999     }
2000
2001     /// Is this field list non-exhaustive?
2002     #[inline]
2003     pub fn is_field_list_non_exhaustive(&self) -> bool {
2004         self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2005     }
2006 }
2007
2008 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2009 pub enum VariantDiscr {
2010     /// Explicit value for this variant, i.e., `X = 123`.
2011     /// The `DefId` corresponds to the embedded constant.
2012     Explicit(DefId),
2013
2014     /// The previous variant's discriminant plus one.
2015     /// For efficiency reasons, the distance from the
2016     /// last `Explicit` discriminant is being stored,
2017     /// or `0` for the first variant, if it has none.
2018     Relative(u32),
2019 }
2020
2021 #[derive(Debug, HashStable)]
2022 pub struct FieldDef {
2023     pub did: DefId,
2024     #[stable_hasher(project(name))]
2025     pub ident: Ident,
2026     pub vis: Visibility,
2027 }
2028
2029 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
2030 ///
2031 /// These are all interned (by `intern_adt_def`) into the `adt_defs` table.
2032 ///
2033 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
2034 /// This is slightly wrong because `union`s are not ADTs.
2035 /// Moreover, Rust only allows recursive data types through indirection.
2036 ///
2037 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2038 pub struct AdtDef {
2039     /// The `DefId` of the struct, enum or union item.
2040     pub did: DefId,
2041     /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2042     pub variants: IndexVec<self::layout::VariantIdx, VariantDef>,
2043     /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2044     flags: AdtFlags,
2045     /// Repr options provided by the user.
2046     pub repr: ReprOptions,
2047 }
2048
2049 impl PartialOrd for AdtDef {
2050     fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2051         Some(self.cmp(&other))
2052     }
2053 }
2054
2055 /// There should be only one AdtDef for each `did`, therefore
2056 /// it is fine to implement `Ord` only based on `did`.
2057 impl Ord for AdtDef {
2058     fn cmp(&self, other: &AdtDef) -> Ordering {
2059         self.did.cmp(&other.did)
2060     }
2061 }
2062
2063 impl PartialEq for AdtDef {
2064     // `AdtDef`s are always interned, and this is part of `TyS` equality.
2065     #[inline]
2066     fn eq(&self, other: &Self) -> bool {
2067         ptr::eq(self, other)
2068     }
2069 }
2070
2071 impl Eq for AdtDef {}
2072
2073 impl Hash for AdtDef {
2074     #[inline]
2075     fn hash<H: Hasher>(&self, s: &mut H) {
2076         (self as *const AdtDef).hash(s)
2077     }
2078 }
2079
2080 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
2081     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2082         self.did.encode(s)
2083     }
2084 }
2085
2086 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2087
2088 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2089     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2090         thread_local! {
2091             static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2092         }
2093
2094         let hash: Fingerprint = CACHE.with(|cache| {
2095             let addr = self as *const AdtDef as usize;
2096             *cache.borrow_mut().entry(addr).or_insert_with(|| {
2097                 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2098
2099                 let mut hasher = StableHasher::new();
2100                 did.hash_stable(hcx, &mut hasher);
2101                 variants.hash_stable(hcx, &mut hasher);
2102                 flags.hash_stable(hcx, &mut hasher);
2103                 repr.hash_stable(hcx, &mut hasher);
2104
2105                 hasher.finish()
2106             })
2107         });
2108
2109         hash.hash_stable(hcx, hasher);
2110     }
2111 }
2112
2113 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2114 pub enum AdtKind {
2115     Struct,
2116     Union,
2117     Enum,
2118 }
2119
2120 impl Into<DataTypeKind> for AdtKind {
2121     fn into(self) -> DataTypeKind {
2122         match self {
2123             AdtKind::Struct => DataTypeKind::Struct,
2124             AdtKind::Union => DataTypeKind::Union,
2125             AdtKind::Enum => DataTypeKind::Enum,
2126         }
2127     }
2128 }
2129
2130 bitflags! {
2131     #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
2132     pub struct ReprFlags: u8 {
2133         const IS_C               = 1 << 0;
2134         const IS_SIMD            = 1 << 1;
2135         const IS_TRANSPARENT     = 1 << 2;
2136         // Internal only for now. If true, don't reorder fields.
2137         const IS_LINEAR          = 1 << 3;
2138         // If true, don't expose any niche to type's context.
2139         const HIDE_NICHE         = 1 << 4;
2140         // Any of these flags being set prevent field reordering optimisation.
2141         const IS_UNOPTIMISABLE   = ReprFlags::IS_C.bits |
2142                                    ReprFlags::IS_SIMD.bits |
2143                                    ReprFlags::IS_LINEAR.bits;
2144     }
2145 }
2146
2147 /// Represents the repr options provided by the user,
2148 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2149 pub struct ReprOptions {
2150     pub int: Option<attr::IntType>,
2151     pub align: Option<Align>,
2152     pub pack: Option<Align>,
2153     pub flags: ReprFlags,
2154 }
2155
2156 impl ReprOptions {
2157     pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2158         let mut flags = ReprFlags::empty();
2159         let mut size = None;
2160         let mut max_align: Option<Align> = None;
2161         let mut min_pack: Option<Align> = None;
2162         for attr in tcx.get_attrs(did).iter() {
2163             for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2164                 flags.insert(match r {
2165                     attr::ReprC => ReprFlags::IS_C,
2166                     attr::ReprPacked(pack) => {
2167                         let pack = Align::from_bytes(pack as u64).unwrap();
2168                         min_pack = Some(if let Some(min_pack) = min_pack {
2169                             min_pack.min(pack)
2170                         } else {
2171                             pack
2172                         });
2173                         ReprFlags::empty()
2174                     }
2175                     attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2176                     attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2177                     attr::ReprSimd => ReprFlags::IS_SIMD,
2178                     attr::ReprInt(i) => {
2179                         size = Some(i);
2180                         ReprFlags::empty()
2181                     }
2182                     attr::ReprAlign(align) => {
2183                         max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2184                         ReprFlags::empty()
2185                     }
2186                 });
2187             }
2188         }
2189
2190         // This is here instead of layout because the choice must make it into metadata.
2191         if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2192             flags.insert(ReprFlags::IS_LINEAR);
2193         }
2194         ReprOptions { int: size, align: max_align, pack: min_pack, flags: flags }
2195     }
2196
2197     #[inline]
2198     pub fn simd(&self) -> bool {
2199         self.flags.contains(ReprFlags::IS_SIMD)
2200     }
2201     #[inline]
2202     pub fn c(&self) -> bool {
2203         self.flags.contains(ReprFlags::IS_C)
2204     }
2205     #[inline]
2206     pub fn packed(&self) -> bool {
2207         self.pack.is_some()
2208     }
2209     #[inline]
2210     pub fn transparent(&self) -> bool {
2211         self.flags.contains(ReprFlags::IS_TRANSPARENT)
2212     }
2213     #[inline]
2214     pub fn linear(&self) -> bool {
2215         self.flags.contains(ReprFlags::IS_LINEAR)
2216     }
2217     #[inline]
2218     pub fn hide_niche(&self) -> bool {
2219         self.flags.contains(ReprFlags::HIDE_NICHE)
2220     }
2221
2222     pub fn discr_type(&self) -> attr::IntType {
2223         self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2224     }
2225
2226     /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2227     /// layout" optimizations, such as representing `Foo<&T>` as a
2228     /// single pointer.
2229     pub fn inhibit_enum_layout_opt(&self) -> bool {
2230         self.c() || self.int.is_some()
2231     }
2232
2233     /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2234     /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2235     pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2236         if let Some(pack) = self.pack {
2237             if pack.bytes() == 1 {
2238                 return true;
2239             }
2240         }
2241         self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2242     }
2243
2244     /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2245     pub fn inhibit_union_abi_opt(&self) -> bool {
2246         self.c()
2247     }
2248 }
2249
2250 impl<'tcx> AdtDef {
2251     /// Creates a new `AdtDef`.
2252     fn new(
2253         tcx: TyCtxt<'_>,
2254         did: DefId,
2255         kind: AdtKind,
2256         variants: IndexVec<VariantIdx, VariantDef>,
2257         repr: ReprOptions,
2258     ) -> Self {
2259         debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2260         let mut flags = AdtFlags::NO_ADT_FLAGS;
2261
2262         if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2263             debug!("found non-exhaustive variant list for {:?}", did);
2264             flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2265         }
2266
2267         flags |= match kind {
2268             AdtKind::Enum => AdtFlags::IS_ENUM,
2269             AdtKind::Union => AdtFlags::IS_UNION,
2270             AdtKind::Struct => AdtFlags::IS_STRUCT,
2271         };
2272
2273         if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2274             flags |= AdtFlags::HAS_CTOR;
2275         }
2276
2277         let attrs = tcx.get_attrs(did);
2278         if attr::contains_name(&attrs, sym::fundamental) {
2279             flags |= AdtFlags::IS_FUNDAMENTAL;
2280         }
2281         if Some(did) == tcx.lang_items().phantom_data() {
2282             flags |= AdtFlags::IS_PHANTOM_DATA;
2283         }
2284         if Some(did) == tcx.lang_items().owned_box() {
2285             flags |= AdtFlags::IS_BOX;
2286         }
2287         if Some(did) == tcx.lang_items().manually_drop() {
2288             flags |= AdtFlags::IS_MANUALLY_DROP;
2289         }
2290         if Some(did) == tcx.lang_items().arc() {
2291             flags |= AdtFlags::IS_ARC;
2292         }
2293         if Some(did) == tcx.lang_items().rc() {
2294             flags |= AdtFlags::IS_RC;
2295         }
2296
2297         AdtDef { did, variants, flags, repr }
2298     }
2299
2300     /// Returns `true` if this is a struct.
2301     #[inline]
2302     pub fn is_struct(&self) -> bool {
2303         self.flags.contains(AdtFlags::IS_STRUCT)
2304     }
2305
2306     /// Returns `true` if this is a union.
2307     #[inline]
2308     pub fn is_union(&self) -> bool {
2309         self.flags.contains(AdtFlags::IS_UNION)
2310     }
2311
2312     /// Returns `true` if this is a enum.
2313     #[inline]
2314     pub fn is_enum(&self) -> bool {
2315         self.flags.contains(AdtFlags::IS_ENUM)
2316     }
2317
2318     /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2319     #[inline]
2320     pub fn is_variant_list_non_exhaustive(&self) -> bool {
2321         self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2322     }
2323
2324     /// Returns the kind of the ADT.
2325     #[inline]
2326     pub fn adt_kind(&self) -> AdtKind {
2327         if self.is_enum() {
2328             AdtKind::Enum
2329         } else if self.is_union() {
2330             AdtKind::Union
2331         } else {
2332             AdtKind::Struct
2333         }
2334     }
2335
2336     /// Returns a description of this abstract data type.
2337     pub fn descr(&self) -> &'static str {
2338         match self.adt_kind() {
2339             AdtKind::Struct => "struct",
2340             AdtKind::Union => "union",
2341             AdtKind::Enum => "enum",
2342         }
2343     }
2344
2345     /// Returns a description of a variant of this abstract data type.
2346     #[inline]
2347     pub fn variant_descr(&self) -> &'static str {
2348         match self.adt_kind() {
2349             AdtKind::Struct => "struct",
2350             AdtKind::Union => "union",
2351             AdtKind::Enum => "variant",
2352         }
2353     }
2354
2355     /// If this function returns `true`, it implies that `is_struct` must return `true`.
2356     #[inline]
2357     pub fn has_ctor(&self) -> bool {
2358         self.flags.contains(AdtFlags::HAS_CTOR)
2359     }
2360
2361     /// Returns `true` if this type is `#[fundamental]` for the purposes
2362     /// of coherence checking.
2363     #[inline]
2364     pub fn is_fundamental(&self) -> bool {
2365         self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2366     }
2367
2368     /// Returns `true` if this is `PhantomData<T>`.
2369     #[inline]
2370     pub fn is_phantom_data(&self) -> bool {
2371         self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2372     }
2373
2374     /// Returns `true` if this is `Arc<T>`.
2375     pub fn is_arc(&self) -> bool {
2376         self.flags.contains(AdtFlags::IS_ARC)
2377     }
2378
2379     /// Returns `true` if this is `Rc<T>`.
2380     pub fn is_rc(&self) -> bool {
2381         self.flags.contains(AdtFlags::IS_RC)
2382     }
2383
2384     /// Returns `true` if this is Box<T>.
2385     #[inline]
2386     pub fn is_box(&self) -> bool {
2387         self.flags.contains(AdtFlags::IS_BOX)
2388     }
2389
2390     /// Returns `true` if this is `ManuallyDrop<T>`.
2391     #[inline]
2392     pub fn is_manually_drop(&self) -> bool {
2393         self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2394     }
2395
2396     /// Returns `true` if this type has a destructor.
2397     pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2398         self.destructor(tcx).is_some()
2399     }
2400
2401     /// Asserts this is a struct or union and returns its unique variant.
2402     pub fn non_enum_variant(&self) -> &VariantDef {
2403         assert!(self.is_struct() || self.is_union());
2404         &self.variants[VariantIdx::new(0)]
2405     }
2406
2407     #[inline]
2408     pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2409         tcx.predicates_of(self.did)
2410     }
2411
2412     /// Returns an iterator over all fields contained
2413     /// by this ADT.
2414     #[inline]
2415     pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2416         self.variants.iter().flat_map(|v| v.fields.iter())
2417     }
2418
2419     pub fn is_payloadfree(&self) -> bool {
2420         !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2421     }
2422
2423     /// Return a `VariantDef` given a variant id.
2424     pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2425         self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2426     }
2427
2428     /// Return a `VariantDef` given a constructor id.
2429     pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2430         self.variants
2431             .iter()
2432             .find(|v| v.ctor_def_id == Some(cid))
2433             .expect("variant_with_ctor_id: unknown variant")
2434     }
2435
2436     /// Return the index of `VariantDef` given a variant id.
2437     pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2438         self.variants
2439             .iter_enumerated()
2440             .find(|(_, v)| v.def_id == vid)
2441             .expect("variant_index_with_id: unknown variant")
2442             .0
2443     }
2444
2445     /// Return the index of `VariantDef` given a constructor id.
2446     pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2447         self.variants
2448             .iter_enumerated()
2449             .find(|(_, v)| v.ctor_def_id == Some(cid))
2450             .expect("variant_index_with_ctor_id: unknown variant")
2451             .0
2452     }
2453
2454     pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2455         match res {
2456             Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2457             Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2458             Res::Def(DefKind::Struct, _)
2459             | Res::Def(DefKind::Union, _)
2460             | Res::Def(DefKind::TyAlias, _)
2461             | Res::Def(DefKind::AssocTy, _)
2462             | Res::SelfTy(..)
2463             | Res::SelfCtor(..) => self.non_enum_variant(),
2464             _ => bug!("unexpected res {:?} in variant_of_res", res),
2465         }
2466     }
2467
2468     #[inline]
2469     pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2470         let param_env = tcx.param_env(expr_did);
2471         let repr_type = self.repr.discr_type();
2472         match tcx.const_eval_poly(expr_did) {
2473             Ok(val) => {
2474                 let ty = repr_type.to_ty(tcx);
2475                 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2476                     trace!("discriminants: {} ({:?})", b, repr_type);
2477                     Some(Discr { val: b, ty })
2478                 } else {
2479                     info!("invalid enum discriminant: {:#?}", val);
2480                     crate::mir::interpret::struct_error(
2481                         tcx.at(tcx.def_span(expr_did)),
2482                         "constant evaluation of enum discriminant resulted in non-integer",
2483                     )
2484                     .emit();
2485                     None
2486                 }
2487             }
2488             Err(ErrorHandled::Reported) => {
2489                 if !expr_did.is_local() {
2490                     span_bug!(
2491                         tcx.def_span(expr_did),
2492                         "variant discriminant evaluation succeeded \
2493                          in its crate but failed locally"
2494                     );
2495                 }
2496                 None
2497             }
2498             Err(ErrorHandled::TooGeneric) => {
2499                 span_bug!(tcx.def_span(expr_did), "enum discriminant depends on generic arguments",)
2500             }
2501         }
2502     }
2503
2504     #[inline]
2505     pub fn discriminants(
2506         &'tcx self,
2507         tcx: TyCtxt<'tcx>,
2508     ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2509         let repr_type = self.repr.discr_type();
2510         let initial = repr_type.initial_discriminant(tcx);
2511         let mut prev_discr = None::<Discr<'tcx>>;
2512         self.variants.iter_enumerated().map(move |(i, v)| {
2513             let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2514             if let VariantDiscr::Explicit(expr_did) = v.discr {
2515                 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2516                     discr = new_discr;
2517                 }
2518             }
2519             prev_discr = Some(discr);
2520
2521             (i, discr)
2522         })
2523     }
2524
2525     #[inline]
2526     pub fn variant_range(&self) -> Range<VariantIdx> {
2527         VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2528     }
2529
2530     /// Computes the discriminant value used by a specific variant.
2531     /// Unlike `discriminants`, this is (amortized) constant-time,
2532     /// only doing at most one query for evaluating an explicit
2533     /// discriminant (the last one before the requested variant),
2534     /// assuming there are no constant-evaluation errors there.
2535     #[inline]
2536     pub fn discriminant_for_variant(
2537         &self,
2538         tcx: TyCtxt<'tcx>,
2539         variant_index: VariantIdx,
2540     ) -> Discr<'tcx> {
2541         let (val, offset) = self.discriminant_def_for_variant(variant_index);
2542         let explicit_value = val
2543             .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2544             .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2545         explicit_value.checked_add(tcx, offset as u128).0
2546     }
2547
2548     /// Yields a `DefId` for the discriminant and an offset to add to it
2549     /// Alternatively, if there is no explicit discriminant, returns the
2550     /// inferred discriminant directly.
2551     pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2552         let mut explicit_index = variant_index.as_u32();
2553         let expr_did;
2554         loop {
2555             match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2556                 ty::VariantDiscr::Relative(0) => {
2557                     expr_did = None;
2558                     break;
2559                 }
2560                 ty::VariantDiscr::Relative(distance) => {
2561                     explicit_index -= distance;
2562                 }
2563                 ty::VariantDiscr::Explicit(did) => {
2564                     expr_did = Some(did);
2565                     break;
2566                 }
2567             }
2568         }
2569         (expr_did, variant_index.as_u32() - explicit_index)
2570     }
2571
2572     pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2573         tcx.adt_destructor(self.did)
2574     }
2575
2576     /// Returns a list of types such that `Self: Sized` if and only
2577     /// if that type is `Sized`, or `TyErr` if this type is recursive.
2578     ///
2579     /// Oddly enough, checking that the sized-constraint is `Sized` is
2580     /// actually more expressive than checking all members:
2581     /// the `Sized` trait is inductive, so an associated type that references
2582     /// `Self` would prevent its containing ADT from being `Sized`.
2583     ///
2584     /// Due to normalization being eager, this applies even if
2585     /// the associated type is behind a pointer (e.g., issue #31299).
2586     pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2587         tcx.adt_sized_constraint(self.did).0
2588     }
2589 }
2590
2591 impl<'tcx> FieldDef {
2592     /// Returns the type of this field. The `subst` is typically obtained
2593     /// via the second field of `TyKind::AdtDef`.
2594     pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2595         tcx.type_of(self.did).subst(tcx, subst)
2596     }
2597 }
2598
2599 /// Represents the various closure traits in the language. This
2600 /// will determine the type of the environment (`self`, in the
2601 /// desugaring) argument that the closure expects.
2602 ///
2603 /// You can get the environment type of a closure using
2604 /// `tcx.closure_env_ty()`.
2605 #[derive(
2606     Clone,
2607     Copy,
2608     PartialOrd,
2609     Ord,
2610     PartialEq,
2611     Eq,
2612     Hash,
2613     Debug,
2614     RustcEncodable,
2615     RustcDecodable,
2616     HashStable
2617 )]
2618 pub enum ClosureKind {
2619     // Warning: Ordering is significant here! The ordering is chosen
2620     // because the trait Fn is a subtrait of FnMut and so in turn, and
2621     // hence we order it so that Fn < FnMut < FnOnce.
2622     Fn,
2623     FnMut,
2624     FnOnce,
2625 }
2626
2627 impl<'tcx> ClosureKind {
2628     // This is the initial value used when doing upvar inference.
2629     pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2630
2631     pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2632         match *self {
2633             ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2634             ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2635             ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2636         }
2637     }
2638
2639     /// Returns `true` if this a type that impls this closure kind
2640     /// must also implement `other`.
2641     pub fn extends(self, other: ty::ClosureKind) -> bool {
2642         match (self, other) {
2643             (ClosureKind::Fn, ClosureKind::Fn) => true,
2644             (ClosureKind::Fn, ClosureKind::FnMut) => true,
2645             (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2646             (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2647             (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2648             (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2649             _ => false,
2650         }
2651     }
2652
2653     /// Returns the representative scalar type for this closure kind.
2654     /// See `TyS::to_opt_closure_kind` for more details.
2655     pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2656         match self {
2657             ty::ClosureKind::Fn => tcx.types.i8,
2658             ty::ClosureKind::FnMut => tcx.types.i16,
2659             ty::ClosureKind::FnOnce => tcx.types.i32,
2660         }
2661     }
2662 }
2663
2664 impl<'tcx> TyS<'tcx> {
2665     /// Iterator that walks `self` and any types reachable from
2666     /// `self`, in depth-first order. Note that just walks the types
2667     /// that appear in `self`, it does not descend into the fields of
2668     /// structs or variants. For example:
2669     ///
2670     /// ```notrust
2671     /// isize => { isize }
2672     /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2673     /// [isize] => { [isize], isize }
2674     /// ```
2675     pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2676         TypeWalker::new(self)
2677     }
2678
2679     /// Iterator that walks the immediate children of `self`. Hence
2680     /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2681     /// (but not `i32`, like `walk`).
2682     pub fn walk_shallow(&'tcx self) -> smallvec::IntoIter<walk::TypeWalkerArray<'tcx>> {
2683         walk::walk_shallow(self)
2684     }
2685
2686     /// Walks `ty` and any types appearing within `ty`, invoking the
2687     /// callback `f` on each type. If the callback returns `false`, then the
2688     /// children of the current type are ignored.
2689     ///
2690     /// Note: prefer `ty.walk()` where possible.
2691     pub fn maybe_walk<F>(&'tcx self, mut f: F)
2692     where
2693         F: FnMut(Ty<'tcx>) -> bool,
2694     {
2695         let mut walker = self.walk();
2696         while let Some(ty) = walker.next() {
2697             if !f(ty) {
2698                 walker.skip_current_subtree();
2699             }
2700         }
2701     }
2702 }
2703
2704 impl BorrowKind {
2705     pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2706         match m {
2707             hir::Mutability::Mut => MutBorrow,
2708             hir::Mutability::Not => ImmBorrow,
2709         }
2710     }
2711
2712     /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2713     /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2714     /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2715     /// question.
2716     pub fn to_mutbl_lossy(self) -> hir::Mutability {
2717         match self {
2718             MutBorrow => hir::Mutability::Mut,
2719             ImmBorrow => hir::Mutability::Not,
2720
2721             // We have no type corresponding to a unique imm borrow, so
2722             // use `&mut`. It gives all the capabilities of an `&uniq`
2723             // and hence is a safe "over approximation".
2724             UniqueImmBorrow => hir::Mutability::Mut,
2725         }
2726     }
2727
2728     pub fn to_user_str(&self) -> &'static str {
2729         match *self {
2730             MutBorrow => "mutable",
2731             ImmBorrow => "immutable",
2732             UniqueImmBorrow => "uniquely immutable",
2733         }
2734     }
2735 }
2736
2737 #[derive(Debug, Clone)]
2738 pub enum Attributes<'tcx> {
2739     Owned(Lrc<[ast::Attribute]>),
2740     Borrowed(&'tcx [ast::Attribute]),
2741 }
2742
2743 impl<'tcx> ::std::ops::Deref for Attributes<'tcx> {
2744     type Target = [ast::Attribute];
2745
2746     fn deref(&self) -> &[ast::Attribute] {
2747         match self {
2748             &Attributes::Owned(ref data) => &data,
2749             &Attributes::Borrowed(data) => data,
2750         }
2751     }
2752 }
2753
2754 #[derive(Debug, PartialEq, Eq)]
2755 pub enum ImplOverlapKind {
2756     /// These impls are always allowed to overlap.
2757     Permitted {
2758         /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2759         marker: bool,
2760     },
2761     /// These impls are allowed to overlap, but that raises
2762     /// an issue #33140 future-compatibility warning.
2763     ///
2764     /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2765     /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2766     ///
2767     /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2768     /// that difference, making what reduces to the following set of impls:
2769     ///
2770     /// ```
2771     /// trait Trait {}
2772     /// impl Trait for dyn Send + Sync {}
2773     /// impl Trait for dyn Sync + Send {}
2774     /// ```
2775     ///
2776     /// Obviously, once we made these types be identical, that code causes a coherence
2777     /// error and a fairly big headache for us. However, luckily for us, the trait
2778     /// `Trait` used in this case is basically a marker trait, and therefore having
2779     /// overlapping impls for it is sound.
2780     ///
2781     /// To handle this, we basically regard the trait as a marker trait, with an additional
2782     /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2783     /// it has the following restrictions:
2784     ///
2785     /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2786     /// positive impls.
2787     /// 2. The trait-ref of both impls must be equal.
2788     /// 3. The trait-ref of both impls must be a trait object type consisting only of
2789     /// marker traits.
2790     /// 4. Neither of the impls can have any where-clauses.
2791     ///
2792     /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2793     Issue33140,
2794 }
2795
2796 impl<'tcx> TyCtxt<'tcx> {
2797     pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2798         self.typeck_tables_of(self.hir().body_owner_def_id(body))
2799     }
2800
2801     /// Returns an iterator of the `DefId`s for all body-owners in this
2802     /// crate. If you would prefer to iterate over the bodies
2803     /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2804     pub fn body_owners(self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'tcx {
2805         self.hir()
2806             .krate()
2807             .body_ids
2808             .iter()
2809             .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2810     }
2811
2812     pub fn par_body_owners<F: Fn(DefId) + sync::Sync + sync::Send>(self, f: F) {
2813         par_iter(&self.hir().krate().body_ids)
2814             .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2815     }
2816
2817     pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2818         self.associated_items(id)
2819             .in_definition_order()
2820             .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value())
2821     }
2822
2823     pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2824         self.associated_items(did).in_definition_order().any(|item| item.relevant_for_never())
2825     }
2826
2827     pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2828         self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
2829     }
2830
2831     pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
2832         let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
2833             match self.hir().get(hir_id) {
2834                 Node::TraitItem(_) | Node::ImplItem(_) => true,
2835                 _ => false,
2836             }
2837         } else {
2838             match self.def_kind(def_id).expect("no def for `DefId`") {
2839                 DefKind::AssocConst | DefKind::Method | DefKind::AssocTy => true,
2840                 _ => false,
2841             }
2842         };
2843
2844         is_associated_item.then(|| self.associated_item(def_id))
2845     }
2846
2847     pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2848         tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2849     }
2850
2851     pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2852         variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2853     }
2854
2855     /// Returns `true` if the impls are the same polarity and the trait either
2856     /// has no items or is annotated #[marker] and prevents item overrides.
2857     pub fn impls_are_allowed_to_overlap(
2858         self,
2859         def_id1: DefId,
2860         def_id2: DefId,
2861     ) -> Option<ImplOverlapKind> {
2862         // If either trait impl references an error, they're allowed to overlap,
2863         // as one of them essentially doesn't exist.
2864         if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2865             || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2866         {
2867             return Some(ImplOverlapKind::Permitted { marker: false });
2868         }
2869
2870         match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2871             (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2872                 // `#[rustc_reservation_impl]` impls don't overlap with anything
2873                 debug!(
2874                     "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2875                     def_id1, def_id2
2876                 );
2877                 return Some(ImplOverlapKind::Permitted { marker: false });
2878             }
2879             (ImplPolarity::Positive, ImplPolarity::Negative)
2880             | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2881                 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2882                 debug!(
2883                     "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2884                     def_id1, def_id2
2885                 );
2886                 return None;
2887             }
2888             (ImplPolarity::Positive, ImplPolarity::Positive)
2889             | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2890         };
2891
2892         let is_marker_overlap = {
2893             let is_marker_impl = |def_id: DefId| -> bool {
2894                 let trait_ref = self.impl_trait_ref(def_id);
2895                 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2896             };
2897             is_marker_impl(def_id1) && is_marker_impl(def_id2)
2898         };
2899
2900         if is_marker_overlap {
2901             debug!(
2902                 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2903                 def_id1, def_id2
2904             );
2905             Some(ImplOverlapKind::Permitted { marker: true })
2906         } else {
2907             if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2908                 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2909                     if self_ty1 == self_ty2 {
2910                         debug!(
2911                             "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2912                             def_id1, def_id2
2913                         );
2914                         return Some(ImplOverlapKind::Issue33140);
2915                     } else {
2916                         debug!(
2917                             "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2918                             def_id1, def_id2, self_ty1, self_ty2
2919                         );
2920                     }
2921                 }
2922             }
2923
2924             debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2925             None
2926         }
2927     }
2928
2929     /// Returns `ty::VariantDef` if `res` refers to a struct,
2930     /// or variant or their constructors, panics otherwise.
2931     pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2932         match res {
2933             Res::Def(DefKind::Variant, did) => {
2934                 let enum_did = self.parent(did).unwrap();
2935                 self.adt_def(enum_did).variant_with_id(did)
2936             }
2937             Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did) => {
2938                 self.adt_def(did).non_enum_variant()
2939             }
2940             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2941                 let variant_did = self.parent(variant_ctor_did).unwrap();
2942                 let enum_did = self.parent(variant_did).unwrap();
2943                 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2944             }
2945             Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2946                 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2947                 self.adt_def(struct_did).non_enum_variant()
2948             }
2949             _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2950         }
2951     }
2952
2953     pub fn item_name(self, id: DefId) -> Symbol {
2954         if id.index == CRATE_DEF_INDEX {
2955             self.original_crate_name(id.krate)
2956         } else {
2957             let def_key = self.def_key(id);
2958             match def_key.disambiguated_data.data {
2959                 // The name of a constructor is that of its parent.
2960                 hir_map::DefPathData::Ctor => {
2961                     self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2962                 }
2963                 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2964                     bug!("item_name: no name for {:?}", self.def_path(id));
2965                 }),
2966             }
2967         }
2968     }
2969
2970     /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2971     pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> ReadOnlyBodyAndCache<'tcx, 'tcx> {
2972         match instance {
2973             ty::InstanceDef::Item(did) => self.optimized_mir(did).unwrap_read_only(),
2974             ty::InstanceDef::VtableShim(..)
2975             | ty::InstanceDef::ReifyShim(..)
2976             | ty::InstanceDef::Intrinsic(..)
2977             | ty::InstanceDef::FnPtrShim(..)
2978             | ty::InstanceDef::Virtual(..)
2979             | ty::InstanceDef::ClosureOnceShim { .. }
2980             | ty::InstanceDef::DropGlue(..)
2981             | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance).unwrap_read_only(),
2982         }
2983     }
2984
2985     /// Gets the attributes of a definition.
2986     pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2987         if let Some(id) = self.hir().as_local_hir_id(did) {
2988             Attributes::Borrowed(self.hir().attrs(id))
2989         } else {
2990             Attributes::Owned(self.item_attrs(did))
2991         }
2992     }
2993
2994     /// Determines whether an item is annotated with an attribute.
2995     pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2996         attr::contains_name(&self.get_attrs(did), attr)
2997     }
2998
2999     /// Returns `true` if this is an `auto trait`.
3000     pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
3001         self.trait_def(trait_def_id).has_auto_impl
3002     }
3003
3004     pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
3005         self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
3006     }
3007
3008     /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
3009     /// If it implements no trait, returns `None`.
3010     pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
3011         self.impl_trait_ref(def_id).map(|tr| tr.def_id)
3012     }
3013
3014     /// If the given defid describes a method belonging to an impl, returns the
3015     /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
3016     pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3017         let item = if def_id.krate != LOCAL_CRATE {
3018             if let Some(DefKind::Method) = self.def_kind(def_id) {
3019                 Some(self.associated_item(def_id))
3020             } else {
3021                 None
3022             }
3023         } else {
3024             self.opt_associated_item(def_id)
3025         };
3026
3027         item.and_then(|trait_item| match trait_item.container {
3028             TraitContainer(_) => None,
3029             ImplContainer(def_id) => Some(def_id),
3030         })
3031     }
3032
3033     /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3034     /// with the name of the crate containing the impl.
3035     pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3036         if impl_did.is_local() {
3037             let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
3038             Ok(self.hir().span(hir_id))
3039         } else {
3040             Err(self.crate_name(impl_did.krate))
3041         }
3042     }
3043
3044     /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3045     /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3046     /// definition's parent/scope to perform comparison.
3047     pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3048         // We could use `Ident::eq` here, but we deliberately don't. The name
3049         // comparison fails frequently, and we want to avoid the expensive
3050         // `modern()` calls required for the span comparison whenever possible.
3051         use_name.name == def_name.name
3052             && use_name
3053                 .span
3054                 .ctxt()
3055                 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3056     }
3057
3058     fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3059         match scope.krate {
3060             LOCAL_CRATE => self.hir().definitions().expansion_that_defined(scope.index),
3061             _ => ExpnId::root(),
3062         }
3063     }
3064
3065     pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3066         ident.span.modernize_and_adjust(self.expansion_that_defined(scope));
3067         ident
3068     }
3069
3070     pub fn adjust_ident_and_get_scope(
3071         self,
3072         mut ident: Ident,
3073         scope: DefId,
3074         block: hir::HirId,
3075     ) -> (Ident, DefId) {
3076         let scope = match ident.span.modernize_and_adjust(self.expansion_that_defined(scope)) {
3077             Some(actual_expansion) => {
3078                 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3079             }
3080             None => self.hir().get_module_parent(block),
3081         };
3082         (ident, scope)
3083     }
3084
3085     pub fn is_object_safe(self, key: DefId) -> bool {
3086         self.object_safety_violations(key).is_empty()
3087     }
3088 }
3089
3090 #[derive(Clone, HashStable)]
3091 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3092
3093 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3094 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3095     if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
3096         if let Node::Item(item) = tcx.hir().get(hir_id) {
3097             if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3098                 return opaque_ty.impl_trait_fn;
3099             }
3100         }
3101     }
3102     None
3103 }
3104
3105 pub fn provide(providers: &mut ty::query::Providers<'_>) {
3106     context::provide(providers);
3107     erase_regions::provide(providers);
3108     layout::provide(providers);
3109     *providers =
3110         ty::query::Providers { trait_impls_of: trait_def::trait_impls_of_provider, ..*providers };
3111 }
3112
3113 /// A map for the local crate mapping each type to a vector of its
3114 /// inherent impls. This is not meant to be used outside of coherence;
3115 /// rather, you should request the vector for a specific type via
3116 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3117 /// (constructing this map requires touching the entire crate).
3118 #[derive(Clone, Debug, Default, HashStable)]
3119 pub struct CrateInherentImpls {
3120     pub inherent_impls: DefIdMap<Vec<DefId>>,
3121 }
3122
3123 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
3124 pub struct SymbolName {
3125     // FIXME: we don't rely on interning or equality here - better have
3126     // this be a `&'tcx str`.
3127     pub name: Symbol,
3128 }
3129
3130 impl SymbolName {
3131     pub fn new(name: &str) -> SymbolName {
3132         SymbolName { name: Symbol::intern(name) }
3133     }
3134 }
3135
3136 impl PartialOrd for SymbolName {
3137     fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
3138         self.name.as_str().partial_cmp(&other.name.as_str())
3139     }
3140 }
3141
3142 /// Ordering must use the chars to ensure reproducible builds.
3143 impl Ord for SymbolName {
3144     fn cmp(&self, other: &SymbolName) -> Ordering {
3145         self.name.as_str().cmp(&other.name.as_str())
3146     }
3147 }
3148
3149 impl fmt::Display for SymbolName {
3150     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3151         fmt::Display::fmt(&self.name, fmt)
3152     }
3153 }
3154
3155 impl fmt::Debug for SymbolName {
3156     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3157         fmt::Display::fmt(&self.name, fmt)
3158     }
3159 }