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