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