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