]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/mod.rs
Rollup merge of #107085 - tmiasko:custom-mir-operators, r=oli-obk
[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 rustc-dev-guide.
9 //!
10 //! ["The `ty` module: representing types"]: https://rustc-dev-guide.rust-lang.org/ty.html
11
12 #![allow(rustc::usage_of_ty_tykind)]
13
14 pub use self::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable};
15 pub use self::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor};
16 pub use self::AssocItemContainer::*;
17 pub use self::BorrowKind::*;
18 pub use self::IntVarValue::*;
19 pub use self::Variance::*;
20 use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
21 use crate::metadata::ModChild;
22 use crate::middle::privacy::EffectiveVisibilities;
23 use crate::mir::{Body, GeneratorLayout};
24 use crate::traits::{self, Reveal};
25 use crate::ty;
26 use crate::ty::fast_reject::SimplifiedType;
27 use crate::ty::util::Discr;
28 pub use adt::*;
29 pub use assoc::*;
30 pub use generics::*;
31 use rustc_ast as ast;
32 use rustc_ast::node_id::NodeMap;
33 use rustc_attr as attr;
34 use rustc_data_structures::fingerprint::Fingerprint;
35 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
36 use rustc_data_structures::intern::Interned;
37 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
38 use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
39 use rustc_hir as hir;
40 use rustc_hir::def::{CtorKind, CtorOf, DefKind, LifetimeRes, Res};
41 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
42 use rustc_hir::Node;
43 use rustc_index::vec::IndexVec;
44 use rustc_macros::HashStable;
45 use rustc_query_system::ich::StableHashingContext;
46 use rustc_serialize::{Decodable, Encodable};
47 use rustc_session::cstore::Untracked;
48 use rustc_span::hygiene::MacroKind;
49 use rustc_span::symbol::{kw, sym, Ident, Symbol};
50 use rustc_span::{ExpnId, Span};
51 use rustc_target::abi::{Align, Integer, IntegerType, VariantIdx};
52 pub use rustc_target::abi::{ReprFlags, ReprOptions};
53 use rustc_type_ir::WithCachedTypeInfo;
54 pub use subst::*;
55 pub use vtable::*;
56
57 use std::fmt::Debug;
58 use std::hash::{Hash, Hasher};
59 use std::marker::PhantomData;
60 use std::mem;
61 use std::num::NonZeroUsize;
62 use std::ops::ControlFlow;
63 use std::{fmt, str};
64
65 pub use crate::ty::diagnostics::*;
66 pub use rustc_type_ir::AliasKind::*;
67 pub use rustc_type_ir::DynKind::*;
68 pub use rustc_type_ir::InferTy::*;
69 pub use rustc_type_ir::RegionKind::*;
70 pub use rustc_type_ir::TyKind::*;
71 pub use rustc_type_ir::*;
72
73 pub use self::binding::BindingMode;
74 pub use self::binding::BindingMode::*;
75 pub use self::closure::{
76     is_ancestor_or_same_capture, place_to_string_for_capture, BorrowKind, CaptureInfo,
77     CapturedPlace, ClosureKind, MinCaptureInformationMap, MinCaptureList,
78     RootVariableMinCaptureList, UpvarCapture, UpvarCaptureMap, UpvarId, UpvarListMap, UpvarPath,
79     CAPTURE_STRUCT_LOCAL,
80 };
81 pub use self::consts::{
82     Const, ConstData, ConstInt, ConstKind, Expr, InferConst, ScalarInt, UnevaluatedConst, ValTree,
83 };
84 pub use self::context::{
85     tls, CtxtInterners, DeducedParamAttrs, FreeRegionInfo, GlobalCtxt, Lift, OnDiskCache, TyCtxt,
86     TyCtxtFeed,
87 };
88 pub use self::instance::{Instance, InstanceDef, ShortInstance, UnusedGenericParams};
89 pub use self::list::List;
90 pub use self::parameterized::ParameterizedOverTcx;
91 pub use self::rvalue_scopes::RvalueScopes;
92 pub use self::sty::BoundRegionKind::*;
93 pub use self::sty::{
94     AliasTy, Article, Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar,
95     BoundVariableKind, CanonicalPolyFnSig, ClosureSubsts, ClosureSubstsParts, ConstVid,
96     EarlyBoundRegion, ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FnSig,
97     FreeRegion, GenSig, GeneratorSubsts, GeneratorSubstsParts, InlineConstSubsts,
98     InlineConstSubstsParts, ParamConst, ParamTy, PolyExistentialPredicate,
99     PolyExistentialProjection, PolyExistentialTraitRef, PolyFnSig, PolyGenSig, PolyTraitRef,
100     Region, RegionKind, RegionVid, TraitRef, TyKind, TypeAndMut, UpvarSubsts, VarianceDiagInfo,
101 };
102 pub use self::trait_def::TraitDef;
103 pub use self::typeck_results::{
104     CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
105     GeneratorDiagnosticData, GeneratorInteriorTypeCause, TypeckResults, UserType,
106     UserTypeAnnotationIndex,
107 };
108
109 pub mod _match;
110 pub mod abstract_const;
111 pub mod adjustment;
112 pub mod binding;
113 pub mod cast;
114 pub mod codec;
115 pub mod error;
116 pub mod fast_reject;
117 pub mod flags;
118 pub mod fold;
119 pub mod inhabitedness;
120 pub mod layout;
121 pub mod normalize_erasing_regions;
122 pub mod print;
123 pub mod query;
124 pub mod relate;
125 pub mod subst;
126 pub mod trait_def;
127 pub mod util;
128 pub mod visit;
129 pub mod vtable;
130 pub mod walk;
131
132 mod adt;
133 mod assoc;
134 mod closure;
135 mod consts;
136 mod context;
137 mod diagnostics;
138 mod erase_regions;
139 mod generics;
140 mod impls_ty;
141 mod instance;
142 mod list;
143 mod opaque_types;
144 mod parameterized;
145 mod rvalue_scopes;
146 mod structural_impls;
147 mod sty;
148 mod typeck_results;
149
150 // Data types
151
152 pub type RegisteredTools = FxHashSet<Ident>;
153
154 pub struct ResolverOutputs {
155     pub global_ctxt: ResolverGlobalCtxt,
156     pub ast_lowering: ResolverAstLowering,
157     pub untracked: Untracked,
158 }
159
160 #[derive(Debug)]
161 pub struct ResolverGlobalCtxt {
162     pub visibilities: FxHashMap<LocalDefId, Visibility>,
163     /// This field is used to decide whether we should make `PRIVATE_IN_PUBLIC` a hard error.
164     pub has_pub_restricted: bool,
165     /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
166     pub expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
167     pub effective_visibilities: EffectiveVisibilities,
168     pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
169     pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
170     pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
171     pub reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
172     pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
173     /// Extern prelude entries. The value is `true` if the entry was introduced
174     /// via `extern crate` item and not `--extern` option or compiler built-in.
175     pub extern_prelude: FxHashMap<Symbol, bool>,
176     pub main_def: Option<MainDefinition>,
177     pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
178     /// A list of proc macro LocalDefIds, written out in the order in which
179     /// they are declared in the static array generated by proc_macro_harness.
180     pub proc_macros: Vec<LocalDefId>,
181     /// Mapping from ident span to path span for paths that don't exist as written, but that
182     /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
183     pub confused_type_with_std_module: FxHashMap<Span, Span>,
184     pub registered_tools: RegisteredTools,
185 }
186
187 /// Resolutions that should only be used for lowering.
188 /// This struct is meant to be consumed by lowering.
189 #[derive(Debug)]
190 pub struct ResolverAstLowering {
191     pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
192
193     /// Resolutions for nodes that have a single resolution.
194     pub partial_res_map: NodeMap<hir::def::PartialRes>,
195     /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
196     pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
197     /// Resolutions for labels (node IDs of their corresponding blocks or loops).
198     pub label_res_map: NodeMap<ast::NodeId>,
199     /// Resolutions for lifetimes.
200     pub lifetimes_res_map: NodeMap<LifetimeRes>,
201     /// Lifetime parameters that lowering will have to introduce.
202     pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
203
204     pub next_node_id: ast::NodeId,
205
206     pub node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
207     pub def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
208
209     pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
210     /// A small map keeping true kinds of built-in macros that appear to be fn-like on
211     /// the surface (`macro` items in libcore), but are actually attributes or derives.
212     pub builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
213     /// List functions and methods for which lifetime elision was successful.
214     pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
215 }
216
217 #[derive(Clone, Copy, Debug)]
218 pub struct MainDefinition {
219     pub res: Res<ast::NodeId>,
220     pub is_import: bool,
221     pub span: Span,
222 }
223
224 impl MainDefinition {
225     pub fn opt_fn_def_id(self) -> Option<DefId> {
226         if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
227     }
228 }
229
230 /// The "header" of an impl is everything outside the body: a Self type, a trait
231 /// ref (in the case of a trait impl), and a set of predicates (from the
232 /// bounds / where-clauses).
233 #[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
234 pub struct ImplHeader<'tcx> {
235     pub impl_def_id: DefId,
236     pub self_ty: Ty<'tcx>,
237     pub trait_ref: Option<TraitRef<'tcx>>,
238     pub predicates: Vec<Predicate<'tcx>>,
239 }
240
241 #[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable)]
242 pub enum ImplSubject<'tcx> {
243     Trait(TraitRef<'tcx>),
244     Inherent(Ty<'tcx>),
245 }
246
247 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
248 #[derive(TypeFoldable, TypeVisitable)]
249 pub enum ImplPolarity {
250     /// `impl Trait for Type`
251     Positive,
252     /// `impl !Trait for Type`
253     Negative,
254     /// `#[rustc_reservation_impl] impl Trait for Type`
255     ///
256     /// This is a "stability hack", not a real Rust feature.
257     /// See #64631 for details.
258     Reservation,
259 }
260
261 impl ImplPolarity {
262     /// Flips polarity by turning `Positive` into `Negative` and `Negative` into `Positive`.
263     pub fn flip(&self) -> Option<ImplPolarity> {
264         match self {
265             ImplPolarity::Positive => Some(ImplPolarity::Negative),
266             ImplPolarity::Negative => Some(ImplPolarity::Positive),
267             ImplPolarity::Reservation => None,
268         }
269     }
270 }
271
272 impl fmt::Display for ImplPolarity {
273     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274         match self {
275             Self::Positive => f.write_str("positive"),
276             Self::Negative => f.write_str("negative"),
277             Self::Reservation => f.write_str("reservation"),
278         }
279     }
280 }
281
282 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, Decodable, HashStable)]
283 pub enum Visibility<Id = LocalDefId> {
284     /// Visible everywhere (including in other crates).
285     Public,
286     /// Visible only in the given crate-local module.
287     Restricted(Id),
288 }
289
290 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
291 pub enum BoundConstness {
292     /// `T: Trait`
293     NotConst,
294     /// `T: ~const Trait`
295     ///
296     /// Requires resolving to const only when we are in a const context.
297     ConstIfConst,
298 }
299
300 impl BoundConstness {
301     /// Reduce `self` and `constness` to two possible combined states instead of four.
302     pub fn and(&mut self, constness: hir::Constness) -> hir::Constness {
303         match (constness, self) {
304             (hir::Constness::Const, BoundConstness::ConstIfConst) => hir::Constness::Const,
305             (_, this) => {
306                 *this = BoundConstness::NotConst;
307                 hir::Constness::NotConst
308             }
309         }
310     }
311 }
312
313 impl fmt::Display for BoundConstness {
314     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315         match self {
316             Self::NotConst => f.write_str("normal"),
317             Self::ConstIfConst => f.write_str("`~const`"),
318         }
319     }
320 }
321
322 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
323 #[derive(TypeFoldable, TypeVisitable)]
324 pub struct ClosureSizeProfileData<'tcx> {
325     /// Tuple containing the types of closure captures before the feature `capture_disjoint_fields`
326     pub before_feature_tys: Ty<'tcx>,
327     /// Tuple containing the types of closure captures after the feature `capture_disjoint_fields`
328     pub after_feature_tys: Ty<'tcx>,
329 }
330
331 pub trait DefIdTree: Copy {
332     fn opt_parent(self, id: DefId) -> Option<DefId>;
333
334     #[inline]
335     #[track_caller]
336     fn parent(self, id: DefId) -> DefId {
337         match self.opt_parent(id) {
338             Some(id) => id,
339             // not `unwrap_or_else` to avoid breaking caller tracking
340             None => bug!("{id:?} doesn't have a parent"),
341         }
342     }
343
344     #[inline]
345     #[track_caller]
346     fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
347         self.opt_parent(id.to_def_id()).map(DefId::expect_local)
348     }
349
350     #[inline]
351     #[track_caller]
352     fn local_parent(self, id: LocalDefId) -> LocalDefId {
353         self.parent(id.to_def_id()).expect_local()
354     }
355
356     fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
357         if descendant.krate != ancestor.krate {
358             return false;
359         }
360
361         while descendant != ancestor {
362             match self.opt_parent(descendant) {
363                 Some(parent) => descendant = parent,
364                 None => return false,
365             }
366         }
367         true
368     }
369 }
370
371 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
372     #[inline]
373     fn opt_parent(self, id: DefId) -> Option<DefId> {
374         self.def_key(id).parent.map(|index| DefId { index, ..id })
375     }
376 }
377
378 impl<Id> Visibility<Id> {
379     pub fn is_public(self) -> bool {
380         matches!(self, Visibility::Public)
381     }
382
383     pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
384         match self {
385             Visibility::Public => Visibility::Public,
386             Visibility::Restricted(id) => Visibility::Restricted(f(id)),
387         }
388     }
389 }
390
391 impl<Id: Into<DefId>> Visibility<Id> {
392     pub fn to_def_id(self) -> Visibility<DefId> {
393         self.map_id(Into::into)
394     }
395
396     /// Returns `true` if an item with this visibility is accessible from the given module.
397     pub fn is_accessible_from(self, module: impl Into<DefId>, tree: impl DefIdTree) -> bool {
398         match self {
399             // Public items are visible everywhere.
400             Visibility::Public => true,
401             Visibility::Restricted(id) => tree.is_descendant_of(module.into(), id.into()),
402         }
403     }
404
405     /// Returns `true` if this visibility is at least as accessible as the given visibility
406     pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tree: impl DefIdTree) -> bool {
407         match vis {
408             Visibility::Public => self.is_public(),
409             Visibility::Restricted(id) => self.is_accessible_from(id, tree),
410         }
411     }
412 }
413
414 impl Visibility<DefId> {
415     pub fn expect_local(self) -> Visibility {
416         self.map_id(|id| id.expect_local())
417     }
418
419     /// Returns `true` if this item is visible anywhere in the local crate.
420     pub fn is_visible_locally(self) -> bool {
421         match self {
422             Visibility::Public => true,
423             Visibility::Restricted(def_id) => def_id.is_local(),
424         }
425     }
426 }
427
428 /// The crate variances map is computed during typeck and contains the
429 /// variance of every item in the local crate. You should not use it
430 /// directly, because to do so will make your pass dependent on the
431 /// HIR of every item in the local crate. Instead, use
432 /// `tcx.variances_of()` to get the variance for a *particular*
433 /// item.
434 #[derive(HashStable, Debug)]
435 pub struct CrateVariancesMap<'tcx> {
436     /// For each item with generics, maps to a vector of the variance
437     /// of its generics. If an item has no generics, it will have no
438     /// entry.
439     pub variances: DefIdMap<&'tcx [ty::Variance]>,
440 }
441
442 // Contains information needed to resolve types and (in the future) look up
443 // the types of AST nodes.
444 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
445 pub struct CReaderCacheKey {
446     pub cnum: Option<CrateNum>,
447     pub pos: usize,
448 }
449
450 /// Use this rather than `TyKind`, whenever possible.
451 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
452 #[rustc_diagnostic_item = "Ty"]
453 #[rustc_pass_by_value]
454 pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
455
456 impl<'tcx> TyCtxt<'tcx> {
457     /// A "bool" type used in rustc_mir_transform unit tests when we
458     /// have not spun up a TyCtxt.
459     pub const BOOL_TY_FOR_UNIT_TESTING: Ty<'tcx> =
460         Ty(Interned::new_unchecked(&WithCachedTypeInfo {
461             internee: ty::Bool,
462             stable_hash: Fingerprint::ZERO,
463             flags: TypeFlags::empty(),
464             outer_exclusive_binder: DebruijnIndex::from_usize(0),
465         }));
466 }
467
468 impl ty::EarlyBoundRegion {
469     /// Does this early bound region have a name? Early bound regions normally
470     /// always have names except when using anonymous lifetimes (`'_`).
471     pub fn has_name(&self) -> bool {
472         self.name != kw::UnderscoreLifetime && self.name != kw::Empty
473     }
474 }
475
476 /// Use this rather than `PredicateKind`, whenever possible.
477 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable)]
478 #[rustc_pass_by_value]
479 pub struct Predicate<'tcx>(
480     Interned<'tcx, WithCachedTypeInfo<ty::Binder<'tcx, PredicateKind<'tcx>>>>,
481 );
482
483 impl<'tcx> Predicate<'tcx> {
484     /// Gets the inner `Binder<'tcx, PredicateKind<'tcx>>`.
485     #[inline]
486     pub fn kind(self) -> Binder<'tcx, PredicateKind<'tcx>> {
487         self.0.internee
488     }
489
490     #[inline(always)]
491     pub fn flags(self) -> TypeFlags {
492         self.0.flags
493     }
494
495     #[inline(always)]
496     pub fn outer_exclusive_binder(self) -> DebruijnIndex {
497         self.0.outer_exclusive_binder
498     }
499
500     /// Flips the polarity of a Predicate.
501     ///
502     /// Given `T: Trait` predicate it returns `T: !Trait` and given `T: !Trait` returns `T: Trait`.
503     pub fn flip_polarity(self, tcx: TyCtxt<'tcx>) -> Option<Predicate<'tcx>> {
504         let kind = self
505             .kind()
506             .map_bound(|kind| match kind {
507                 PredicateKind::Clause(Clause::Trait(TraitPredicate {
508                     trait_ref,
509                     constness,
510                     polarity,
511                 })) => Some(PredicateKind::Clause(Clause::Trait(TraitPredicate {
512                     trait_ref,
513                     constness,
514                     polarity: polarity.flip()?,
515                 }))),
516
517                 _ => None,
518             })
519             .transpose()?;
520
521         Some(tcx.mk_predicate(kind))
522     }
523
524     pub fn without_const(mut self, tcx: TyCtxt<'tcx>) -> Self {
525         if let PredicateKind::Clause(Clause::Trait(TraitPredicate { trait_ref, constness, polarity })) = self.kind().skip_binder()
526             && constness != BoundConstness::NotConst
527         {
528             self = tcx.mk_predicate(self.kind().rebind(PredicateKind::Clause(Clause::Trait(TraitPredicate {
529                 trait_ref,
530                 constness: BoundConstness::NotConst,
531                 polarity,
532             }))));
533         }
534         self
535     }
536
537     #[instrument(level = "debug", skip(tcx), ret)]
538     pub fn is_coinductive(self, tcx: TyCtxt<'tcx>) -> bool {
539         match self.kind().skip_binder() {
540             ty::PredicateKind::Clause(ty::Clause::Trait(data)) => {
541                 tcx.trait_is_coinductive(data.def_id())
542             }
543             ty::PredicateKind::WellFormed(_) => true,
544             _ => false,
545         }
546     }
547
548     /// Whether this projection can be soundly normalized.
549     ///
550     /// Wf predicates must not be normalized, as normalization
551     /// can remove required bounds which would cause us to
552     /// unsoundly accept some programs. See #91068.
553     #[inline]
554     pub fn allow_normalization(self) -> bool {
555         match self.kind().skip_binder() {
556             PredicateKind::WellFormed(_) => false,
557             PredicateKind::Clause(Clause::Trait(_))
558             | PredicateKind::Clause(Clause::RegionOutlives(_))
559             | PredicateKind::Clause(Clause::TypeOutlives(_))
560             | PredicateKind::Clause(Clause::Projection(_))
561             | PredicateKind::ObjectSafe(_)
562             | PredicateKind::ClosureKind(_, _, _)
563             | PredicateKind::Subtype(_)
564             | PredicateKind::Coerce(_)
565             | PredicateKind::ConstEvaluatable(_)
566             | PredicateKind::ConstEquate(_, _)
567             | PredicateKind::Ambiguous
568             | PredicateKind::TypeWellFormedFromEnv(_) => true,
569         }
570     }
571 }
572
573 impl rustc_errors::IntoDiagnosticArg for Predicate<'_> {
574     fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
575         rustc_errors::DiagnosticArgValue::Str(std::borrow::Cow::Owned(self.to_string()))
576     }
577 }
578
579 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
580 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
581 /// A clause is something that can appear in where bounds or be inferred
582 /// by implied bounds.
583 pub enum Clause<'tcx> {
584     /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
585     /// the `Self` type of the trait reference and `A`, `B`, and `C`
586     /// would be the type parameters.
587     Trait(TraitPredicate<'tcx>),
588
589     /// `where 'a: 'b`
590     RegionOutlives(RegionOutlivesPredicate<'tcx>),
591
592     /// `where T: 'a`
593     TypeOutlives(TypeOutlivesPredicate<'tcx>),
594
595     /// `where <T as TraitRef>::Name == X`, approximately.
596     /// See the `ProjectionPredicate` struct for details.
597     Projection(ProjectionPredicate<'tcx>),
598 }
599
600 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
601 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
602 pub enum PredicateKind<'tcx> {
603     /// Prove a clause
604     Clause(Clause<'tcx>),
605
606     /// No syntax: `T` well-formed.
607     WellFormed(GenericArg<'tcx>),
608
609     /// Trait must be object-safe.
610     ObjectSafe(DefId),
611
612     /// No direct syntax. May be thought of as `where T: FnFoo<...>`
613     /// for some substitutions `...` and `T` being a closure type.
614     /// Satisfied (or refuted) once we know the closure's kind.
615     ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
616
617     /// `T1 <: T2`
618     ///
619     /// This obligation is created most often when we have two
620     /// unresolved type variables and hence don't have enough
621     /// information to process the subtyping obligation yet.
622     Subtype(SubtypePredicate<'tcx>),
623
624     /// `T1` coerced to `T2`
625     ///
626     /// Like a subtyping obligation, this is created most often
627     /// when we have two unresolved type variables and hence
628     /// don't have enough information to process the coercion
629     /// obligation yet. At the moment, we actually process coercions
630     /// very much like subtyping and don't handle the full coercion
631     /// logic.
632     Coerce(CoercePredicate<'tcx>),
633
634     /// Constant initializer must evaluate successfully.
635     ConstEvaluatable(ty::Const<'tcx>),
636
637     /// Constants must be equal. The first component is the const that is expected.
638     ConstEquate(Const<'tcx>, Const<'tcx>),
639
640     /// Represents a type found in the environment that we can use for implied bounds.
641     ///
642     /// Only used for Chalk.
643     TypeWellFormedFromEnv(Ty<'tcx>),
644
645     /// A marker predicate that is always ambiguous.
646     /// Used for coherence to mark opaque types as possibly equal to each other but ambiguous.
647     Ambiguous,
648 }
649
650 /// The crate outlives map is computed during typeck and contains the
651 /// outlives of every item in the local crate. You should not use it
652 /// directly, because to do so will make your pass dependent on the
653 /// HIR of every item in the local crate. Instead, use
654 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
655 /// item.
656 #[derive(HashStable, Debug)]
657 pub struct CratePredicatesMap<'tcx> {
658     /// For each struct with outlive bounds, maps to a vector of the
659     /// predicate of its outlive bounds. If an item has no outlives
660     /// bounds, it will have no entry.
661     pub predicates: FxHashMap<DefId, &'tcx [(Clause<'tcx>, Span)]>,
662 }
663
664 impl<'tcx> Predicate<'tcx> {
665     /// Performs a substitution suitable for going from a
666     /// poly-trait-ref to supertraits that must hold if that
667     /// poly-trait-ref holds. This is slightly different from a normal
668     /// substitution in terms of what happens with bound regions. See
669     /// lengthy comment below for details.
670     pub fn subst_supertrait(
671         self,
672         tcx: TyCtxt<'tcx>,
673         trait_ref: &ty::PolyTraitRef<'tcx>,
674     ) -> Predicate<'tcx> {
675         // The interaction between HRTB and supertraits is not entirely
676         // obvious. Let me walk you (and myself) through an example.
677         //
678         // Let's start with an easy case. Consider two traits:
679         //
680         //     trait Foo<'a>: Bar<'a,'a> { }
681         //     trait Bar<'b,'c> { }
682         //
683         // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
684         // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
685         // knew that `Foo<'x>` (for any 'x) then we also know that
686         // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
687         // normal substitution.
688         //
689         // In terms of why this is sound, the idea is that whenever there
690         // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
691         // holds. So if there is an impl of `T:Foo<'a>` that applies to
692         // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
693         // `'a`.
694         //
695         // Another example to be careful of is this:
696         //
697         //     trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
698         //     trait Bar1<'b,'c> { }
699         //
700         // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
701         // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
702         // reason is similar to the previous example: any impl of
703         // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
704         // basically we would want to collapse the bound lifetimes from
705         // the input (`trait_ref`) and the supertraits.
706         //
707         // To achieve this in practice is fairly straightforward. Let's
708         // consider the more complicated scenario:
709         //
710         // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
711         //   has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
712         //   where both `'x` and `'b` would have a DB index of 1.
713         //   The substitution from the input trait-ref is therefore going to be
714         //   `'a => 'x` (where `'x` has a DB index of 1).
715         // - The supertrait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
716         //   early-bound parameter and `'b' is a late-bound parameter with a
717         //   DB index of 1.
718         // - If we replace `'a` with `'x` from the input, it too will have
719         //   a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
720         //   just as we wanted.
721         //
722         // There is only one catch. If we just apply the substitution `'a
723         // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
724         // adjust the DB index because we substituting into a binder (it
725         // tries to be so smart...) resulting in `for<'x> for<'b>
726         // Bar1<'x,'b>` (we have no syntax for this, so use your
727         // imagination). Basically the 'x will have DB index of 2 and 'b
728         // will have DB index of 1. Not quite what we want. So we apply
729         // the substitution to the *contents* of the trait reference,
730         // rather than the trait reference itself (put another way, the
731         // substitution code expects equal binding levels in the values
732         // from the substitution and the value being substituted into, and
733         // this trick achieves that).
734
735         // Working through the second example:
736         // trait_ref: for<'x> T: Foo1<'^0.0>; substs: [T, '^0.0]
737         // predicate: for<'b> Self: Bar1<'a, '^0.0>; substs: [Self, 'a, '^0.0]
738         // We want to end up with:
739         //     for<'x, 'b> T: Bar1<'^0.0, '^0.1>
740         // To do this:
741         // 1) We must shift all bound vars in predicate by the length
742         //    of trait ref's bound vars. So, we would end up with predicate like
743         //    Self: Bar1<'a, '^0.1>
744         // 2) We can then apply the trait substs to this, ending up with
745         //    T: Bar1<'^0.0, '^0.1>
746         // 3) Finally, to create the final bound vars, we concatenate the bound
747         //    vars of the trait ref with those of the predicate:
748         //    ['x, 'b]
749         let bound_pred = self.kind();
750         let pred_bound_vars = bound_pred.bound_vars();
751         let trait_bound_vars = trait_ref.bound_vars();
752         // 1) Self: Bar1<'a, '^0.0> -> Self: Bar1<'a, '^0.1>
753         let shifted_pred =
754             tcx.shift_bound_var_indices(trait_bound_vars.len(), bound_pred.skip_binder());
755         // 2) Self: Bar1<'a, '^0.1> -> T: Bar1<'^0.0, '^0.1>
756         let new = EarlyBinder(shifted_pred).subst(tcx, trait_ref.skip_binder().substs);
757         // 3) ['x] + ['b] -> ['x, 'b]
758         let bound_vars =
759             tcx.mk_bound_variable_kinds(trait_bound_vars.iter().chain(pred_bound_vars));
760         tcx.reuse_or_mk_predicate(self, ty::Binder::bind_with_vars(new, bound_vars))
761     }
762 }
763
764 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
765 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
766 pub struct TraitPredicate<'tcx> {
767     pub trait_ref: TraitRef<'tcx>,
768
769     pub constness: BoundConstness,
770
771     /// If polarity is Positive: we are proving that the trait is implemented.
772     ///
773     /// If polarity is Negative: we are proving that a negative impl of this trait
774     /// exists. (Note that coherence also checks whether negative impls of supertraits
775     /// exist via a series of predicates.)
776     ///
777     /// If polarity is Reserved: that's a bug.
778     pub polarity: ImplPolarity,
779 }
780
781 pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>;
782
783 impl<'tcx> TraitPredicate<'tcx> {
784     pub fn remap_constness(&mut self, param_env: &mut ParamEnv<'tcx>) {
785         *param_env = param_env.with_constness(self.constness.and(param_env.constness()))
786     }
787
788     /// Remap the constness of this predicate before emitting it for diagnostics.
789     pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
790         // this is different to `remap_constness` that callees want to print this predicate
791         // in case of selection errors. `T: ~const Drop` bounds cannot end up here when the
792         // param_env is not const because it is always satisfied in non-const contexts.
793         if let hir::Constness::NotConst = param_env.constness() {
794             self.constness = ty::BoundConstness::NotConst;
795         }
796     }
797
798     pub fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
799         Self { trait_ref: self.trait_ref.with_self_ty(tcx, self_ty), ..self }
800     }
801
802     pub fn def_id(self) -> DefId {
803         self.trait_ref.def_id
804     }
805
806     pub fn self_ty(self) -> Ty<'tcx> {
807         self.trait_ref.self_ty()
808     }
809
810     #[inline]
811     pub fn is_const_if_const(self) -> bool {
812         self.constness == BoundConstness::ConstIfConst
813     }
814
815     pub fn is_constness_satisfied_by(self, constness: hir::Constness) -> bool {
816         match (self.constness, constness) {
817             (BoundConstness::NotConst, _)
818             | (BoundConstness::ConstIfConst, hir::Constness::Const) => true,
819             (BoundConstness::ConstIfConst, hir::Constness::NotConst) => false,
820         }
821     }
822
823     pub fn without_const(mut self) -> Self {
824         self.constness = BoundConstness::NotConst;
825         self
826     }
827 }
828
829 impl<'tcx> PolyTraitPredicate<'tcx> {
830     pub fn def_id(self) -> DefId {
831         // Ok to skip binder since trait `DefId` does not care about regions.
832         self.skip_binder().def_id()
833     }
834
835     pub fn self_ty(self) -> ty::Binder<'tcx, Ty<'tcx>> {
836         self.map_bound(|trait_ref| trait_ref.self_ty())
837     }
838
839     /// Remap the constness of this predicate before emitting it for diagnostics.
840     pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
841         *self = self.map_bound(|mut p| {
842             p.remap_constness_diag(param_env);
843             p
844         });
845     }
846
847     #[inline]
848     pub fn is_const_if_const(self) -> bool {
849         self.skip_binder().is_const_if_const()
850     }
851 }
852
853 /// `A: B`
854 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
855 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
856 pub struct OutlivesPredicate<A, B>(pub A, pub B);
857 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
858 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
859 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<'tcx, RegionOutlivesPredicate<'tcx>>;
860 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<'tcx, TypeOutlivesPredicate<'tcx>>;
861
862 /// Encodes that `a` must be a subtype of `b`. The `a_is_expected` flag indicates
863 /// whether the `a` type is the type that we should label as "expected" when
864 /// presenting user diagnostics.
865 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
866 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
867 pub struct SubtypePredicate<'tcx> {
868     pub a_is_expected: bool,
869     pub a: Ty<'tcx>,
870     pub b: Ty<'tcx>,
871 }
872 pub type PolySubtypePredicate<'tcx> = ty::Binder<'tcx, SubtypePredicate<'tcx>>;
873
874 /// Encodes that we have to coerce *from* the `a` type to the `b` type.
875 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
876 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
877 pub struct CoercePredicate<'tcx> {
878     pub a: Ty<'tcx>,
879     pub b: Ty<'tcx>,
880 }
881 pub type PolyCoercePredicate<'tcx> = ty::Binder<'tcx, CoercePredicate<'tcx>>;
882
883 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
884 pub struct Term<'tcx> {
885     ptr: NonZeroUsize,
886     marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
887 }
888
889 impl Debug for Term<'_> {
890     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
891         let data = if let Some(ty) = self.ty() {
892             format!("Term::Ty({:?})", ty)
893         } else if let Some(ct) = self.ct() {
894             format!("Term::Ct({:?})", ct)
895         } else {
896             unreachable!()
897         };
898         f.write_str(&data)
899     }
900 }
901
902 impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
903     fn from(ty: Ty<'tcx>) -> Self {
904         TermKind::Ty(ty).pack()
905     }
906 }
907
908 impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
909     fn from(c: Const<'tcx>) -> Self {
910         TermKind::Const(c).pack()
911     }
912 }
913
914 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
915     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
916         self.unpack().hash_stable(hcx, hasher);
917     }
918 }
919
920 impl<'tcx> TypeFoldable<'tcx> for Term<'tcx> {
921     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
922         Ok(self.unpack().try_fold_with(folder)?.pack())
923     }
924 }
925
926 impl<'tcx> TypeVisitable<'tcx> for Term<'tcx> {
927     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
928         self.unpack().visit_with(visitor)
929     }
930 }
931
932 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for Term<'tcx> {
933     fn encode(&self, e: &mut E) {
934         self.unpack().encode(e)
935     }
936 }
937
938 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for Term<'tcx> {
939     fn decode(d: &mut D) -> Self {
940         let res: TermKind<'tcx> = Decodable::decode(d);
941         res.pack()
942     }
943 }
944
945 impl<'tcx> Term<'tcx> {
946     #[inline]
947     pub fn unpack(self) -> TermKind<'tcx> {
948         let ptr = self.ptr.get();
949         // SAFETY: use of `Interned::new_unchecked` here is ok because these
950         // pointers were originally created from `Interned` types in `pack()`,
951         // and this is just going in the other direction.
952         unsafe {
953             match ptr & TAG_MASK {
954                 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
955                     &*((ptr & !TAG_MASK) as *const WithCachedTypeInfo<ty::TyKind<'tcx>>),
956                 ))),
957                 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
958                     &*((ptr & !TAG_MASK) as *const ty::ConstData<'tcx>),
959                 ))),
960                 _ => core::intrinsics::unreachable(),
961             }
962         }
963     }
964
965     pub fn ty(&self) -> Option<Ty<'tcx>> {
966         if let TermKind::Ty(ty) = self.unpack() { Some(ty) } else { None }
967     }
968
969     pub fn ct(&self) -> Option<Const<'tcx>> {
970         if let TermKind::Const(c) = self.unpack() { Some(c) } else { None }
971     }
972
973     pub fn into_arg(self) -> GenericArg<'tcx> {
974         match self.unpack() {
975             TermKind::Ty(ty) => ty.into(),
976             TermKind::Const(c) => c.into(),
977         }
978     }
979 }
980
981 const TAG_MASK: usize = 0b11;
982 const TYPE_TAG: usize = 0b00;
983 const CONST_TAG: usize = 0b01;
984
985 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, TyEncodable, TyDecodable)]
986 #[derive(HashStable, TypeFoldable, TypeVisitable)]
987 pub enum TermKind<'tcx> {
988     Ty(Ty<'tcx>),
989     Const(Const<'tcx>),
990 }
991
992 impl<'tcx> TermKind<'tcx> {
993     #[inline]
994     fn pack(self) -> Term<'tcx> {
995         let (tag, ptr) = match self {
996             TermKind::Ty(ty) => {
997                 // Ensure we can use the tag bits.
998                 assert_eq!(mem::align_of_val(&*ty.0.0) & TAG_MASK, 0);
999                 (TYPE_TAG, ty.0.0 as *const WithCachedTypeInfo<ty::TyKind<'tcx>> as usize)
1000             }
1001             TermKind::Const(ct) => {
1002                 // Ensure we can use the tag bits.
1003                 assert_eq!(mem::align_of_val(&*ct.0.0) & TAG_MASK, 0);
1004                 (CONST_TAG, ct.0.0 as *const ty::ConstData<'tcx> as usize)
1005             }
1006         };
1007
1008         Term { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData }
1009     }
1010 }
1011
1012 /// This kind of predicate has no *direct* correspondent in the
1013 /// syntax, but it roughly corresponds to the syntactic forms:
1014 ///
1015 /// 1. `T: TraitRef<..., Item = Type>`
1016 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1017 ///
1018 /// In particular, form #1 is "desugared" to the combination of a
1019 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1020 /// predicates. Form #2 is a broader form in that it also permits
1021 /// equality between arbitrary types. Processing an instance of
1022 /// Form #2 eventually yields one of these `ProjectionPredicate`
1023 /// instances to normalize the LHS.
1024 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1025 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
1026 pub struct ProjectionPredicate<'tcx> {
1027     pub projection_ty: AliasTy<'tcx>,
1028     pub term: Term<'tcx>,
1029 }
1030
1031 impl<'tcx> ProjectionPredicate<'tcx> {
1032     pub fn self_ty(self) -> Ty<'tcx> {
1033         self.projection_ty.self_ty()
1034     }
1035
1036     pub fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ProjectionPredicate<'tcx> {
1037         Self { projection_ty: self.projection_ty.with_self_ty(tcx, self_ty), ..self }
1038     }
1039
1040     pub fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId {
1041         self.projection_ty.trait_def_id(tcx)
1042     }
1043
1044     pub fn def_id(self) -> DefId {
1045         self.projection_ty.def_id
1046     }
1047 }
1048
1049 pub type PolyProjectionPredicate<'tcx> = Binder<'tcx, ProjectionPredicate<'tcx>>;
1050
1051 impl<'tcx> PolyProjectionPredicate<'tcx> {
1052     /// Returns the `DefId` of the trait of the associated item being projected.
1053     #[inline]
1054     pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
1055         self.skip_binder().projection_ty.trait_def_id(tcx)
1056     }
1057
1058     /// Get the [PolyTraitRef] required for this projection to be well formed.
1059     /// Note that for generic associated types the predicates of the associated
1060     /// type also need to be checked.
1061     #[inline]
1062     pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1063         // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1064         // `self.0.trait_ref` is permitted to have escaping regions.
1065         // This is because here `self` has a `Binder` and so does our
1066         // return value, so we are preserving the number of binding
1067         // levels.
1068         self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1069     }
1070
1071     pub fn term(&self) -> Binder<'tcx, Term<'tcx>> {
1072         self.map_bound(|predicate| predicate.term)
1073     }
1074
1075     /// The `DefId` of the `TraitItem` for the associated type.
1076     ///
1077     /// Note that this is not the `DefId` of the `TraitRef` containing this
1078     /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1079     pub fn projection_def_id(&self) -> DefId {
1080         // Ok to skip binder since trait `DefId` does not care about regions.
1081         self.skip_binder().projection_ty.def_id
1082     }
1083 }
1084
1085 pub trait ToPolyTraitRef<'tcx> {
1086     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1087 }
1088
1089 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1090     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1091         self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1092     }
1093 }
1094
1095 pub trait ToPredicate<'tcx, P = Predicate<'tcx>> {
1096     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> P;
1097 }
1098
1099 impl<'tcx, T> ToPredicate<'tcx, T> for T {
1100     fn to_predicate(self, _tcx: TyCtxt<'tcx>) -> T {
1101         self
1102     }
1103 }
1104
1105 impl<'tcx> ToPredicate<'tcx> for Binder<'tcx, PredicateKind<'tcx>> {
1106     #[inline(always)]
1107     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1108         tcx.mk_predicate(self)
1109     }
1110 }
1111
1112 impl<'tcx> ToPredicate<'tcx> for Clause<'tcx> {
1113     #[inline(always)]
1114     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1115         tcx.mk_predicate(ty::Binder::dummy(ty::PredicateKind::Clause(self)))
1116     }
1117 }
1118
1119 impl<'tcx> ToPredicate<'tcx> for Binder<'tcx, TraitRef<'tcx>> {
1120     #[inline(always)]
1121     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1122         let pred: PolyTraitPredicate<'tcx> = self.to_predicate(tcx);
1123         pred.to_predicate(tcx)
1124     }
1125 }
1126
1127 impl<'tcx> ToPredicate<'tcx, PolyTraitPredicate<'tcx>> for Binder<'tcx, TraitRef<'tcx>> {
1128     #[inline(always)]
1129     fn to_predicate(self, _: TyCtxt<'tcx>) -> PolyTraitPredicate<'tcx> {
1130         self.map_bound(|trait_ref| TraitPredicate {
1131             trait_ref,
1132             constness: ty::BoundConstness::NotConst,
1133             polarity: ty::ImplPolarity::Positive,
1134         })
1135     }
1136 }
1137
1138 impl<'tcx> ToPredicate<'tcx> for PolyTraitPredicate<'tcx> {
1139     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1140         self.map_bound(|p| PredicateKind::Clause(Clause::Trait(p))).to_predicate(tcx)
1141     }
1142 }
1143
1144 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1145     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1146         self.map_bound(|p| PredicateKind::Clause(Clause::RegionOutlives(p))).to_predicate(tcx)
1147     }
1148 }
1149
1150 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1151     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1152         self.map_bound(|p| PredicateKind::Clause(Clause::TypeOutlives(p))).to_predicate(tcx)
1153     }
1154 }
1155
1156 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1157     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1158         self.map_bound(|p| PredicateKind::Clause(Clause::Projection(p))).to_predicate(tcx)
1159     }
1160 }
1161
1162 impl<'tcx> Predicate<'tcx> {
1163     pub fn to_opt_poly_trait_pred(self) -> Option<PolyTraitPredicate<'tcx>> {
1164         let predicate = self.kind();
1165         match predicate.skip_binder() {
1166             PredicateKind::Clause(Clause::Trait(t)) => Some(predicate.rebind(t)),
1167             PredicateKind::Clause(Clause::Projection(..))
1168             | PredicateKind::Subtype(..)
1169             | PredicateKind::Coerce(..)
1170             | PredicateKind::Clause(Clause::RegionOutlives(..))
1171             | PredicateKind::WellFormed(..)
1172             | PredicateKind::ObjectSafe(..)
1173             | PredicateKind::ClosureKind(..)
1174             | PredicateKind::Clause(Clause::TypeOutlives(..))
1175             | PredicateKind::ConstEvaluatable(..)
1176             | PredicateKind::ConstEquate(..)
1177             | PredicateKind::Ambiguous
1178             | PredicateKind::TypeWellFormedFromEnv(..) => None,
1179         }
1180     }
1181
1182     pub fn to_opt_poly_projection_pred(self) -> Option<PolyProjectionPredicate<'tcx>> {
1183         let predicate = self.kind();
1184         match predicate.skip_binder() {
1185             PredicateKind::Clause(Clause::Projection(t)) => Some(predicate.rebind(t)),
1186             PredicateKind::Clause(Clause::Trait(..))
1187             | PredicateKind::Subtype(..)
1188             | PredicateKind::Coerce(..)
1189             | PredicateKind::Clause(Clause::RegionOutlives(..))
1190             | PredicateKind::WellFormed(..)
1191             | PredicateKind::ObjectSafe(..)
1192             | PredicateKind::ClosureKind(..)
1193             | PredicateKind::Clause(Clause::TypeOutlives(..))
1194             | PredicateKind::ConstEvaluatable(..)
1195             | PredicateKind::ConstEquate(..)
1196             | PredicateKind::Ambiguous
1197             | PredicateKind::TypeWellFormedFromEnv(..) => None,
1198         }
1199     }
1200
1201     pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1202         let predicate = self.kind();
1203         match predicate.skip_binder() {
1204             PredicateKind::Clause(Clause::TypeOutlives(data)) => Some(predicate.rebind(data)),
1205             PredicateKind::Clause(Clause::Trait(..))
1206             | PredicateKind::Clause(Clause::Projection(..))
1207             | PredicateKind::Subtype(..)
1208             | PredicateKind::Coerce(..)
1209             | PredicateKind::Clause(Clause::RegionOutlives(..))
1210             | PredicateKind::WellFormed(..)
1211             | PredicateKind::ObjectSafe(..)
1212             | PredicateKind::ClosureKind(..)
1213             | PredicateKind::ConstEvaluatable(..)
1214             | PredicateKind::ConstEquate(..)
1215             | PredicateKind::Ambiguous
1216             | PredicateKind::TypeWellFormedFromEnv(..) => None,
1217         }
1218     }
1219 }
1220
1221 /// Represents the bounds declared on a particular set of type
1222 /// parameters. Should eventually be generalized into a flag list of
1223 /// where-clauses. You can obtain an `InstantiatedPredicates` list from a
1224 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1225 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1226 /// the `GenericPredicates` are expressed in terms of the bound type
1227 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1228 /// represented a set of bounds for some particular instantiation,
1229 /// meaning that the generic parameters have been substituted with
1230 /// their values.
1231 ///
1232 /// Example:
1233 /// ```ignore (illustrative)
1234 /// struct Foo<T, U: Bar<T>> { ... }
1235 /// ```
1236 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1237 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1238 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1239 /// [usize:Bar<isize>]]`.
1240 #[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
1241 pub struct InstantiatedPredicates<'tcx> {
1242     pub predicates: Vec<Predicate<'tcx>>,
1243     pub spans: Vec<Span>,
1244 }
1245
1246 impl<'tcx> InstantiatedPredicates<'tcx> {
1247     pub fn empty() -> InstantiatedPredicates<'tcx> {
1248         InstantiatedPredicates { predicates: vec![], spans: vec![] }
1249     }
1250
1251     pub fn is_empty(&self) -> bool {
1252         self.predicates.is_empty()
1253     }
1254
1255     pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
1256         (&self).into_iter()
1257     }
1258 }
1259
1260 impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
1261     type Item = (Predicate<'tcx>, Span);
1262
1263     type IntoIter = std::iter::Zip<std::vec::IntoIter<Predicate<'tcx>>, std::vec::IntoIter<Span>>;
1264
1265     fn into_iter(self) -> Self::IntoIter {
1266         debug_assert_eq!(self.predicates.len(), self.spans.len());
1267         std::iter::zip(self.predicates, self.spans)
1268     }
1269 }
1270
1271 impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
1272     type Item = (Predicate<'tcx>, Span);
1273
1274     type IntoIter = std::iter::Zip<
1275         std::iter::Copied<std::slice::Iter<'a, Predicate<'tcx>>>,
1276         std::iter::Copied<std::slice::Iter<'a, Span>>,
1277     >;
1278
1279     fn into_iter(self) -> Self::IntoIter {
1280         debug_assert_eq!(self.predicates.len(), self.spans.len());
1281         std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
1282     }
1283 }
1284
1285 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable, Lift)]
1286 #[derive(TypeFoldable, TypeVisitable)]
1287 pub struct OpaqueTypeKey<'tcx> {
1288     pub def_id: LocalDefId,
1289     pub substs: SubstsRef<'tcx>,
1290 }
1291
1292 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
1293 pub struct OpaqueHiddenType<'tcx> {
1294     /// The span of this particular definition of the opaque type. So
1295     /// for example:
1296     ///
1297     /// ```ignore (incomplete snippet)
1298     /// type Foo = impl Baz;
1299     /// fn bar() -> Foo {
1300     /// //          ^^^ This is the span we are looking for!
1301     /// }
1302     /// ```
1303     ///
1304     /// In cases where the fn returns `(impl Trait, impl Trait)` or
1305     /// other such combinations, the result is currently
1306     /// over-approximated, but better than nothing.
1307     pub span: Span,
1308
1309     /// The type variable that represents the value of the opaque type
1310     /// that we require. In other words, after we compile this function,
1311     /// we will be created a constraint like:
1312     /// ```ignore (pseudo-rust)
1313     /// Foo<'a, T> = ?C
1314     /// ```
1315     /// where `?C` is the value of this type variable. =) It may
1316     /// naturally refer to the type and lifetime parameters in scope
1317     /// in this function, though ultimately it should only reference
1318     /// those that are arguments to `Foo` in the constraint above. (In
1319     /// other words, `?C` should not include `'b`, even though it's a
1320     /// lifetime parameter on `foo`.)
1321     pub ty: Ty<'tcx>,
1322 }
1323
1324 impl<'tcx> OpaqueHiddenType<'tcx> {
1325     pub fn report_mismatch(&self, other: &Self, tcx: TyCtxt<'tcx>) {
1326         // Found different concrete types for the opaque type.
1327         let sub_diag = if self.span == other.span {
1328             TypeMismatchReason::ConflictType { span: self.span }
1329         } else {
1330             TypeMismatchReason::PreviousUse { span: self.span }
1331         };
1332         tcx.sess.emit_err(OpaqueHiddenTypeMismatch {
1333             self_ty: self.ty,
1334             other_ty: other.ty,
1335             other_span: other.span,
1336             sub: sub_diag,
1337         });
1338     }
1339
1340     #[instrument(level = "debug", skip(tcx), ret)]
1341     pub fn remap_generic_params_to_declaration_params(
1342         self,
1343         opaque_type_key: OpaqueTypeKey<'tcx>,
1344         tcx: TyCtxt<'tcx>,
1345         // typeck errors have subpar spans for opaque types, so delay error reporting until borrowck.
1346         ignore_errors: bool,
1347     ) -> Self {
1348         let OpaqueTypeKey { def_id, substs } = opaque_type_key;
1349
1350         // Use substs to build up a reverse map from regions to their
1351         // identity mappings. This is necessary because of `impl
1352         // Trait` lifetimes are computed by replacing existing
1353         // lifetimes with 'static and remapping only those used in the
1354         // `impl Trait` return type, resulting in the parameters
1355         // shifting.
1356         let id_substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
1357         debug!(?id_substs);
1358
1359         // This zip may have several times the same lifetime in `substs` paired with a different
1360         // lifetime from `id_substs`. Simply `collect`ing the iterator is the correct behaviour:
1361         // it will pick the last one, which is the one we introduced in the impl-trait desugaring.
1362         let map = substs.iter().zip(id_substs).collect();
1363         debug!("map = {:#?}", map);
1364
1365         // Convert the type from the function into a type valid outside
1366         // the function, by replacing invalid regions with 'static,
1367         // after producing an error for each of them.
1368         self.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span, ignore_errors))
1369     }
1370 }
1371
1372 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1373 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1374 /// regions/types/consts within the same universe simply have an unknown relationship to one
1375 /// another.
1376 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
1377 #[derive(HashStable, TyEncodable, TyDecodable)]
1378 pub struct Placeholder<T> {
1379     pub universe: UniverseIndex,
1380     pub name: T,
1381 }
1382
1383 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
1384
1385 pub type PlaceholderType = Placeholder<BoundVar>;
1386
1387 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1388 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1389 pub struct BoundConst<'tcx> {
1390     pub var: BoundVar,
1391     pub ty: Ty<'tcx>,
1392 }
1393
1394 pub type PlaceholderConst<'tcx> = Placeholder<BoundVar>;
1395
1396 /// A `DefId` which, in case it is a const argument, is potentially bundled with
1397 /// the `DefId` of the generic parameter it instantiates.
1398 ///
1399 /// This is used to avoid calls to `type_of` for const arguments during typeck
1400 /// which cause cycle errors.
1401 ///
1402 /// ```rust
1403 /// struct A;
1404 /// impl A {
1405 ///     fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1406 ///     //           ^ const parameter
1407 /// }
1408 /// struct B;
1409 /// impl B {
1410 ///     fn foo<const M: u8>(&self) -> usize { 42 }
1411 ///     //           ^ const parameter
1412 /// }
1413 ///
1414 /// fn main() {
1415 ///     let a = A;
1416 ///     let _b = a.foo::<{ 3 + 7 }>();
1417 ///     //               ^^^^^^^^^ const argument
1418 /// }
1419 /// ```
1420 ///
1421 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1422 /// which `foo` is used until we know the type of `a`.
1423 ///
1424 /// We only know the type of `a` once we are inside of `typeck(main)`.
1425 /// We also end up normalizing the type of `_b` during `typeck(main)` which
1426 /// requires us to evaluate the const argument.
1427 ///
1428 /// To evaluate that const argument we need to know its type,
1429 /// which we would get using `type_of(const_arg)`. This requires us to
1430 /// resolve `foo` as it can be either `usize` or `u8` in this example.
1431 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1432 /// which results in a cycle.
1433 ///
1434 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1435 ///
1436 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1437 /// already resolved `foo` so we know which const parameter this argument instantiates.
1438 /// This means that we also know the expected result of `type_of(const_arg)` even if we
1439 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1440 /// trivial to compute.
1441 ///
1442 /// If we now want to use that constant in a place which potentially needs its type
1443 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1444 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1445 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1446 /// to get the type of `did`.
1447 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift, TyEncodable, TyDecodable)]
1448 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1449 #[derive(Hash, HashStable)]
1450 pub struct WithOptConstParam<T> {
1451     pub did: T,
1452     /// The `DefId` of the corresponding generic parameter in case `did` is
1453     /// a const argument.
1454     ///
1455     /// Note that even if `did` is a const argument, this may still be `None`.
1456     /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1457     /// to potentially update `param_did` in the case it is `None`.
1458     pub const_param_did: Option<DefId>,
1459 }
1460
1461 impl<T> WithOptConstParam<T> {
1462     /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1463     #[inline(always)]
1464     pub fn unknown(did: T) -> WithOptConstParam<T> {
1465         WithOptConstParam { did, const_param_did: None }
1466     }
1467 }
1468
1469 impl WithOptConstParam<LocalDefId> {
1470     /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1471     /// `None` otherwise.
1472     #[inline(always)]
1473     pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1474         tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1475     }
1476
1477     /// In case `self` is unknown but `self.did` is a const argument, this returns
1478     /// a `WithOptConstParam` with the correct `const_param_did`.
1479     #[inline(always)]
1480     pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1481         if self.const_param_did.is_none() {
1482             if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1483                 return Some(WithOptConstParam { did: self.did, const_param_did });
1484             }
1485         }
1486
1487         None
1488     }
1489
1490     pub fn to_global(self) -> WithOptConstParam<DefId> {
1491         WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1492     }
1493
1494     pub fn def_id_for_type_of(self) -> DefId {
1495         if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1496     }
1497 }
1498
1499 impl WithOptConstParam<DefId> {
1500     pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1501         self.did
1502             .as_local()
1503             .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1504     }
1505
1506     pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1507         if let Some(param_did) = self.const_param_did {
1508             if let Some(did) = self.did.as_local() {
1509                 return Some((did, param_did));
1510             }
1511         }
1512
1513         None
1514     }
1515
1516     pub fn is_local(self) -> bool {
1517         self.did.is_local()
1518     }
1519
1520     pub fn def_id_for_type_of(self) -> DefId {
1521         self.const_param_did.unwrap_or(self.did)
1522     }
1523 }
1524
1525 /// When type checking, we use the `ParamEnv` to track
1526 /// details about the set of where-clauses that are in scope at this
1527 /// particular point.
1528 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1529 pub struct ParamEnv<'tcx> {
1530     /// This packs both caller bounds and the reveal enum into one pointer.
1531     ///
1532     /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1533     /// basically the set of bounds on the in-scope type parameters, translated
1534     /// into `Obligation`s, and elaborated and normalized.
1535     ///
1536     /// Use the `caller_bounds()` method to access.
1537     ///
1538     /// Typically, this is `Reveal::UserFacing`, but during codegen we
1539     /// want `Reveal::All`.
1540     ///
1541     /// Note: This is packed, use the reveal() method to access it.
1542     packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, ParamTag, true>,
1543 }
1544
1545 #[derive(Copy, Clone)]
1546 struct ParamTag {
1547     reveal: traits::Reveal,
1548     constness: hir::Constness,
1549 }
1550
1551 unsafe impl rustc_data_structures::tagged_ptr::Tag for ParamTag {
1552     const BITS: usize = 2;
1553     #[inline]
1554     fn into_usize(self) -> usize {
1555         match self {
1556             Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst } => 0,
1557             Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst } => 1,
1558             Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const } => 2,
1559             Self { reveal: traits::Reveal::All, constness: hir::Constness::Const } => 3,
1560         }
1561     }
1562     #[inline]
1563     unsafe fn from_usize(ptr: usize) -> Self {
1564         match ptr {
1565             0 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst },
1566             1 => Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst },
1567             2 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const },
1568             3 => Self { reveal: traits::Reveal::All, constness: hir::Constness::Const },
1569             _ => std::hint::unreachable_unchecked(),
1570         }
1571     }
1572 }
1573
1574 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1575     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1576         f.debug_struct("ParamEnv")
1577             .field("caller_bounds", &self.caller_bounds())
1578             .field("reveal", &self.reveal())
1579             .field("constness", &self.constness())
1580             .finish()
1581     }
1582 }
1583
1584 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1585     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1586         self.caller_bounds().hash_stable(hcx, hasher);
1587         self.reveal().hash_stable(hcx, hasher);
1588         self.constness().hash_stable(hcx, hasher);
1589     }
1590 }
1591
1592 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1593     fn try_fold_with<F: ty::fold::FallibleTypeFolder<'tcx>>(
1594         self,
1595         folder: &mut F,
1596     ) -> Result<Self, F::Error> {
1597         Ok(ParamEnv::new(
1598             self.caller_bounds().try_fold_with(folder)?,
1599             self.reveal().try_fold_with(folder)?,
1600             self.constness(),
1601         ))
1602     }
1603 }
1604
1605 impl<'tcx> TypeVisitable<'tcx> for ParamEnv<'tcx> {
1606     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1607         self.caller_bounds().visit_with(visitor)?;
1608         self.reveal().visit_with(visitor)
1609     }
1610 }
1611
1612 impl<'tcx> ParamEnv<'tcx> {
1613     /// Construct a trait environment suitable for contexts where
1614     /// there are no where-clauses in scope. Hidden types (like `impl
1615     /// Trait`) are left hidden, so this is suitable for ordinary
1616     /// type-checking.
1617     #[inline]
1618     pub fn empty() -> Self {
1619         Self::new(List::empty(), Reveal::UserFacing, hir::Constness::NotConst)
1620     }
1621
1622     #[inline]
1623     pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1624         self.packed.pointer()
1625     }
1626
1627     #[inline]
1628     pub fn reveal(self) -> traits::Reveal {
1629         self.packed.tag().reveal
1630     }
1631
1632     #[inline]
1633     pub fn constness(self) -> hir::Constness {
1634         self.packed.tag().constness
1635     }
1636
1637     #[inline]
1638     pub fn is_const(self) -> bool {
1639         self.packed.tag().constness == hir::Constness::Const
1640     }
1641
1642     /// Construct a trait environment with no where-clauses in scope
1643     /// where the values of all `impl Trait` and other hidden types
1644     /// are revealed. This is suitable for monomorphized, post-typeck
1645     /// environments like codegen or doing optimizations.
1646     ///
1647     /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1648     /// or invoke `param_env.with_reveal_all()`.
1649     #[inline]
1650     pub fn reveal_all() -> Self {
1651         Self::new(List::empty(), Reveal::All, hir::Constness::NotConst)
1652     }
1653
1654     /// Construct a trait environment with the given set of predicates.
1655     #[inline]
1656     pub fn new(
1657         caller_bounds: &'tcx List<Predicate<'tcx>>,
1658         reveal: Reveal,
1659         constness: hir::Constness,
1660     ) -> Self {
1661         ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, ParamTag { reveal, constness }) }
1662     }
1663
1664     pub fn with_user_facing(mut self) -> Self {
1665         self.packed.set_tag(ParamTag { reveal: Reveal::UserFacing, ..self.packed.tag() });
1666         self
1667     }
1668
1669     #[inline]
1670     pub fn with_constness(mut self, constness: hir::Constness) -> Self {
1671         self.packed.set_tag(ParamTag { constness, ..self.packed.tag() });
1672         self
1673     }
1674
1675     #[inline]
1676     pub fn with_const(mut self) -> Self {
1677         self.packed.set_tag(ParamTag { constness: hir::Constness::Const, ..self.packed.tag() });
1678         self
1679     }
1680
1681     #[inline]
1682     pub fn without_const(mut self) -> Self {
1683         self.packed.set_tag(ParamTag { constness: hir::Constness::NotConst, ..self.packed.tag() });
1684         self
1685     }
1686
1687     #[inline]
1688     pub fn remap_constness_with(&mut self, mut constness: ty::BoundConstness) {
1689         *self = self.with_constness(constness.and(self.constness()))
1690     }
1691
1692     /// Returns a new parameter environment with the same clauses, but
1693     /// which "reveals" the true results of projections in all cases
1694     /// (even for associated types that are specializable). This is
1695     /// the desired behavior during codegen and certain other special
1696     /// contexts; normally though we want to use `Reveal::UserFacing`,
1697     /// which is the default.
1698     /// All opaque types in the caller_bounds of the `ParamEnv`
1699     /// will be normalized to their underlying types.
1700     /// See PR #65989 and issue #65918 for more details
1701     pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1702         if self.packed.tag().reveal == traits::Reveal::All {
1703             return self;
1704         }
1705
1706         ParamEnv::new(
1707             tcx.reveal_opaque_types_in_bounds(self.caller_bounds()),
1708             Reveal::All,
1709             self.constness(),
1710         )
1711     }
1712
1713     /// Returns this same environment but with no caller bounds.
1714     #[inline]
1715     pub fn without_caller_bounds(self) -> Self {
1716         Self::new(List::empty(), self.reveal(), self.constness())
1717     }
1718
1719     /// Creates a suitable environment in which to perform trait
1720     /// queries on the given value. When type-checking, this is simply
1721     /// the pair of the environment plus value. But when reveal is set to
1722     /// All, then if `value` does not reference any type parameters, we will
1723     /// pair it with the empty environment. This improves caching and is generally
1724     /// invisible.
1725     ///
1726     /// N.B., we preserve the environment when type-checking because it
1727     /// is possible for the user to have wacky where-clauses like
1728     /// `where Box<u32>: Copy`, which are clearly never
1729     /// satisfiable. We generally want to behave as if they were true,
1730     /// although the surrounding function is never reachable.
1731     pub fn and<T: TypeVisitable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1732         match self.reveal() {
1733             Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1734
1735             Reveal::All => {
1736                 if value.is_global() {
1737                     ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1738                 } else {
1739                     ParamEnvAnd { param_env: self, value }
1740                 }
1741             }
1742         }
1743     }
1744 }
1745
1746 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1747 // the constness of trait bounds is being propagated correctly.
1748 impl<'tcx> PolyTraitRef<'tcx> {
1749     #[inline]
1750     pub fn with_constness(self, constness: BoundConstness) -> PolyTraitPredicate<'tcx> {
1751         self.map_bound(|trait_ref| ty::TraitPredicate {
1752             trait_ref,
1753             constness,
1754             polarity: ty::ImplPolarity::Positive,
1755         })
1756     }
1757
1758     #[inline]
1759     pub fn without_const(self) -> PolyTraitPredicate<'tcx> {
1760         self.with_constness(BoundConstness::NotConst)
1761     }
1762 }
1763
1764 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1765 #[derive(HashStable, Lift)]
1766 pub struct ParamEnvAnd<'tcx, T> {
1767     pub param_env: ParamEnv<'tcx>,
1768     pub value: T,
1769 }
1770
1771 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1772     pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1773         (self.param_env, self.value)
1774     }
1775
1776     #[inline]
1777     pub fn without_const(mut self) -> Self {
1778         self.param_env = self.param_env.without_const();
1779         self
1780     }
1781 }
1782
1783 #[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1784 pub struct Destructor {
1785     /// The `DefId` of the destructor method
1786     pub did: DefId,
1787     /// The constness of the destructor method
1788     pub constness: hir::Constness,
1789 }
1790
1791 bitflags! {
1792     #[derive(HashStable, TyEncodable, TyDecodable)]
1793     pub struct VariantFlags: u32 {
1794         const NO_VARIANT_FLAGS        = 0;
1795         /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1796         const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1797         /// Indicates whether this variant was obtained as part of recovering from
1798         /// a syntactic error. May be incomplete or bogus.
1799         const IS_RECOVERED = 1 << 1;
1800     }
1801 }
1802
1803 /// Definition of a variant -- a struct's fields or an enum variant.
1804 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1805 pub struct VariantDef {
1806     /// `DefId` that identifies the variant itself.
1807     /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1808     pub def_id: DefId,
1809     /// `DefId` that identifies the variant's constructor.
1810     /// If this variant is a struct variant, then this is `None`.
1811     pub ctor: Option<(CtorKind, DefId)>,
1812     /// Variant or struct name.
1813     pub name: Symbol,
1814     /// Discriminant of this variant.
1815     pub discr: VariantDiscr,
1816     /// Fields of this variant.
1817     pub fields: Vec<FieldDef>,
1818     /// Flags of the variant (e.g. is field list non-exhaustive)?
1819     flags: VariantFlags,
1820 }
1821
1822 impl VariantDef {
1823     /// Creates a new `VariantDef`.
1824     ///
1825     /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1826     /// represents an enum variant).
1827     ///
1828     /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1829     /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1830     ///
1831     /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1832     /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1833     /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1834     /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1835     /// built-in trait), and we do not want to load attributes twice.
1836     ///
1837     /// If someone speeds up attribute loading to not be a performance concern, they can
1838     /// remove this hack and use the constructor `DefId` everywhere.
1839     pub fn new(
1840         name: Symbol,
1841         variant_did: Option<DefId>,
1842         ctor: Option<(CtorKind, DefId)>,
1843         discr: VariantDiscr,
1844         fields: Vec<FieldDef>,
1845         adt_kind: AdtKind,
1846         parent_did: DefId,
1847         recovered: bool,
1848         is_field_list_non_exhaustive: bool,
1849     ) -> Self {
1850         debug!(
1851             "VariantDef::new(name = {:?}, variant_did = {:?}, ctor = {:?}, discr = {:?},
1852              fields = {:?}, adt_kind = {:?}, parent_did = {:?})",
1853             name, variant_did, ctor, discr, fields, adt_kind, parent_did,
1854         );
1855
1856         let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1857         if is_field_list_non_exhaustive {
1858             flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1859         }
1860
1861         if recovered {
1862             flags |= VariantFlags::IS_RECOVERED;
1863         }
1864
1865         VariantDef { def_id: variant_did.unwrap_or(parent_did), ctor, name, discr, fields, flags }
1866     }
1867
1868     /// Is this field list non-exhaustive?
1869     #[inline]
1870     pub fn is_field_list_non_exhaustive(&self) -> bool {
1871         self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1872     }
1873
1874     /// Was this variant obtained as part of recovering from a syntactic error?
1875     #[inline]
1876     pub fn is_recovered(&self) -> bool {
1877         self.flags.intersects(VariantFlags::IS_RECOVERED)
1878     }
1879
1880     /// Computes the `Ident` of this variant by looking up the `Span`
1881     pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1882         Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1883     }
1884
1885     #[inline]
1886     pub fn ctor_kind(&self) -> Option<CtorKind> {
1887         self.ctor.map(|(kind, _)| kind)
1888     }
1889
1890     #[inline]
1891     pub fn ctor_def_id(&self) -> Option<DefId> {
1892         self.ctor.map(|(_, def_id)| def_id)
1893     }
1894 }
1895
1896 impl PartialEq for VariantDef {
1897     #[inline]
1898     fn eq(&self, other: &Self) -> bool {
1899         // There should be only one `VariantDef` for each `def_id`, therefore
1900         // it is fine to implement `PartialEq` only based on `def_id`.
1901         //
1902         // Below, we exhaustively destructure `self` and `other` so that if the
1903         // definition of `VariantDef` changes, a compile-error will be produced,
1904         // reminding us to revisit this assumption.
1905
1906         let Self { def_id: lhs_def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = &self;
1907         let Self { def_id: rhs_def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = other;
1908         lhs_def_id == rhs_def_id
1909     }
1910 }
1911
1912 impl Eq for VariantDef {}
1913
1914 impl Hash for VariantDef {
1915     #[inline]
1916     fn hash<H: Hasher>(&self, s: &mut H) {
1917         // There should be only one `VariantDef` for each `def_id`, therefore
1918         // it is fine to implement `Hash` only based on `def_id`.
1919         //
1920         // Below, we exhaustively destructure `self` so that if the definition
1921         // of `VariantDef` changes, a compile-error will be produced, reminding
1922         // us to revisit this assumption.
1923
1924         let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = &self;
1925         def_id.hash(s)
1926     }
1927 }
1928
1929 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1930 pub enum VariantDiscr {
1931     /// Explicit value for this variant, i.e., `X = 123`.
1932     /// The `DefId` corresponds to the embedded constant.
1933     Explicit(DefId),
1934
1935     /// The previous variant's discriminant plus one.
1936     /// For efficiency reasons, the distance from the
1937     /// last `Explicit` discriminant is being stored,
1938     /// or `0` for the first variant, if it has none.
1939     Relative(u32),
1940 }
1941
1942 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1943 pub struct FieldDef {
1944     pub did: DefId,
1945     pub name: Symbol,
1946     pub vis: Visibility<DefId>,
1947 }
1948
1949 impl PartialEq for FieldDef {
1950     #[inline]
1951     fn eq(&self, other: &Self) -> bool {
1952         // There should be only one `FieldDef` for each `did`, therefore it is
1953         // fine to implement `PartialEq` only based on `did`.
1954         //
1955         // Below, we exhaustively destructure `self` so that if the definition
1956         // of `FieldDef` changes, a compile-error will be produced, reminding
1957         // us to revisit this assumption.
1958
1959         let Self { did: lhs_did, name: _, vis: _ } = &self;
1960
1961         let Self { did: rhs_did, name: _, vis: _ } = other;
1962
1963         lhs_did == rhs_did
1964     }
1965 }
1966
1967 impl Eq for FieldDef {}
1968
1969 impl Hash for FieldDef {
1970     #[inline]
1971     fn hash<H: Hasher>(&self, s: &mut H) {
1972         // There should be only one `FieldDef` for each `did`, therefore it is
1973         // fine to implement `Hash` only based on `did`.
1974         //
1975         // Below, we exhaustively destructure `self` so that if the definition
1976         // of `FieldDef` changes, a compile-error will be produced, reminding
1977         // us to revisit this assumption.
1978
1979         let Self { did, name: _, vis: _ } = &self;
1980
1981         did.hash(s)
1982     }
1983 }
1984
1985 impl<'tcx> FieldDef {
1986     /// Returns the type of this field. The resulting type is not normalized. The `subst` is
1987     /// typically obtained via the second field of [`TyKind::Adt`].
1988     pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
1989         tcx.bound_type_of(self.did).subst(tcx, subst)
1990     }
1991
1992     /// Computes the `Ident` of this variant by looking up the `Span`
1993     pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1994         Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1995     }
1996 }
1997
1998 pub type Attributes<'tcx> = impl Iterator<Item = &'tcx ast::Attribute>;
1999 #[derive(Debug, PartialEq, Eq)]
2000 pub enum ImplOverlapKind {
2001     /// These impls are always allowed to overlap.
2002     Permitted {
2003         /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2004         marker: bool,
2005     },
2006     /// These impls are allowed to overlap, but that raises
2007     /// an issue #33140 future-compatibility warning.
2008     ///
2009     /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2010     /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2011     ///
2012     /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2013     /// that difference, making what reduces to the following set of impls:
2014     ///
2015     /// ```compile_fail,(E0119)
2016     /// trait Trait {}
2017     /// impl Trait for dyn Send + Sync {}
2018     /// impl Trait for dyn Sync + Send {}
2019     /// ```
2020     ///
2021     /// Obviously, once we made these types be identical, that code causes a coherence
2022     /// error and a fairly big headache for us. However, luckily for us, the trait
2023     /// `Trait` used in this case is basically a marker trait, and therefore having
2024     /// overlapping impls for it is sound.
2025     ///
2026     /// To handle this, we basically regard the trait as a marker trait, with an additional
2027     /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2028     /// it has the following restrictions:
2029     ///
2030     /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2031     /// positive impls.
2032     /// 2. The trait-ref of both impls must be equal.
2033     /// 3. The trait-ref of both impls must be a trait object type consisting only of
2034     /// marker traits.
2035     /// 4. Neither of the impls can have any where-clauses.
2036     ///
2037     /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2038     Issue33140,
2039 }
2040
2041 impl<'tcx> TyCtxt<'tcx> {
2042     pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
2043         self.typeck(self.hir().body_owner_def_id(body))
2044     }
2045
2046     pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2047         self.associated_items(id)
2048             .in_definition_order()
2049             .filter(move |item| item.kind == AssocKind::Fn && item.defaultness(self).has_value())
2050     }
2051
2052     pub fn repr_options_of_def(self, did: DefId) -> ReprOptions {
2053         let mut flags = ReprFlags::empty();
2054         let mut size = None;
2055         let mut max_align: Option<Align> = None;
2056         let mut min_pack: Option<Align> = None;
2057
2058         // Generate a deterministically-derived seed from the item's path hash
2059         // to allow for cross-crate compilation to actually work
2060         let mut field_shuffle_seed = self.def_path_hash(did).0.to_smaller_hash();
2061
2062         // If the user defined a custom seed for layout randomization, xor the item's
2063         // path hash with the user defined seed, this will allowing determinism while
2064         // still allowing users to further randomize layout generation for e.g. fuzzing
2065         if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
2066             field_shuffle_seed ^= user_seed;
2067         }
2068
2069         for attr in self.get_attrs(did, sym::repr) {
2070             for r in attr::parse_repr_attr(&self.sess, attr) {
2071                 flags.insert(match r {
2072                     attr::ReprC => ReprFlags::IS_C,
2073                     attr::ReprPacked(pack) => {
2074                         let pack = Align::from_bytes(pack as u64).unwrap();
2075                         min_pack = Some(if let Some(min_pack) = min_pack {
2076                             min_pack.min(pack)
2077                         } else {
2078                             pack
2079                         });
2080                         ReprFlags::empty()
2081                     }
2082                     attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2083                     attr::ReprSimd => ReprFlags::IS_SIMD,
2084                     attr::ReprInt(i) => {
2085                         size = Some(match i {
2086                             attr::IntType::SignedInt(x) => match x {
2087                                 ast::IntTy::Isize => IntegerType::Pointer(true),
2088                                 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
2089                                 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
2090                                 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
2091                                 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
2092                                 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
2093                             },
2094                             attr::IntType::UnsignedInt(x) => match x {
2095                                 ast::UintTy::Usize => IntegerType::Pointer(false),
2096                                 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
2097                                 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
2098                                 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
2099                                 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
2100                                 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
2101                             },
2102                         });
2103                         ReprFlags::empty()
2104                     }
2105                     attr::ReprAlign(align) => {
2106                         max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2107                         ReprFlags::empty()
2108                     }
2109                 });
2110             }
2111         }
2112
2113         // If `-Z randomize-layout` was enabled for the type definition then we can
2114         // consider performing layout randomization
2115         if self.sess.opts.unstable_opts.randomize_layout {
2116             flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
2117         }
2118
2119         // This is here instead of layout because the choice must make it into metadata.
2120         if !self.consider_optimizing(|| format!("Reorder fields of {:?}", self.def_path_str(did))) {
2121             flags.insert(ReprFlags::IS_LINEAR);
2122         }
2123
2124         ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
2125     }
2126
2127     /// Look up the name of a definition across crates. This does not look at HIR.
2128     pub fn opt_item_name(self, def_id: DefId) -> Option<Symbol> {
2129         if let Some(cnum) = def_id.as_crate_root() {
2130             Some(self.crate_name(cnum))
2131         } else {
2132             let def_key = self.def_key(def_id);
2133             match def_key.disambiguated_data.data {
2134                 // The name of a constructor is that of its parent.
2135                 rustc_hir::definitions::DefPathData::Ctor => self
2136                     .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
2137                 // The name of opaque types only exists in HIR.
2138                 rustc_hir::definitions::DefPathData::ImplTrait
2139                     if let Some(def_id) = def_id.as_local() =>
2140                     self.hir().opt_name(self.hir().local_def_id_to_hir_id(def_id)),
2141                 _ => def_key.get_opt_name(),
2142             }
2143         }
2144     }
2145
2146     /// Look up the name of a definition across crates. This does not look at HIR.
2147     ///
2148     /// This method will ICE if the corresponding item does not have a name. In these cases, use
2149     /// [`opt_item_name`] instead.
2150     ///
2151     /// [`opt_item_name`]: Self::opt_item_name
2152     pub fn item_name(self, id: DefId) -> Symbol {
2153         self.opt_item_name(id).unwrap_or_else(|| {
2154             bug!("item_name: no name for {:?}", self.def_path(id));
2155         })
2156     }
2157
2158     /// Look up the name and span of a definition.
2159     ///
2160     /// See [`item_name`][Self::item_name] for more information.
2161     pub fn opt_item_ident(self, def_id: DefId) -> Option<Ident> {
2162         let def = self.opt_item_name(def_id)?;
2163         let span = def_id
2164             .as_local()
2165             .and_then(|id| self.def_ident_span(id))
2166             .unwrap_or(rustc_span::DUMMY_SP);
2167         Some(Ident::new(def, span))
2168     }
2169
2170     pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2171         if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2172             Some(self.associated_item(def_id))
2173         } else {
2174             None
2175         }
2176     }
2177
2178     pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2179         variant
2180             .fields
2181             .iter()
2182             .position(|field| self.hygienic_eq(ident, field.ident(self), variant.def_id))
2183     }
2184
2185     /// Returns `true` if the impls are the same polarity and the trait either
2186     /// has no items or is annotated `#[marker]` and prevents item overrides.
2187     pub fn impls_are_allowed_to_overlap(
2188         self,
2189         def_id1: DefId,
2190         def_id2: DefId,
2191     ) -> Option<ImplOverlapKind> {
2192         // If either trait impl references an error, they're allowed to overlap,
2193         // as one of them essentially doesn't exist.
2194         if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.subst_identity().references_error())
2195             || self
2196                 .impl_trait_ref(def_id2)
2197                 .map_or(false, |tr| tr.subst_identity().references_error())
2198         {
2199             return Some(ImplOverlapKind::Permitted { marker: false });
2200         }
2201
2202         match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2203             (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2204                 // `#[rustc_reservation_impl]` impls don't overlap with anything
2205                 debug!(
2206                     "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2207                     def_id1, def_id2
2208                 );
2209                 return Some(ImplOverlapKind::Permitted { marker: false });
2210             }
2211             (ImplPolarity::Positive, ImplPolarity::Negative)
2212             | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2213                 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2214                 debug!(
2215                     "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2216                     def_id1, def_id2
2217                 );
2218                 return None;
2219             }
2220             (ImplPolarity::Positive, ImplPolarity::Positive)
2221             | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2222         };
2223
2224         let is_marker_overlap = {
2225             let is_marker_impl = |def_id: DefId| -> bool {
2226                 let trait_ref = self.impl_trait_ref(def_id);
2227                 trait_ref.map_or(false, |tr| self.trait_def(tr.skip_binder().def_id).is_marker)
2228             };
2229             is_marker_impl(def_id1) && is_marker_impl(def_id2)
2230         };
2231
2232         if is_marker_overlap {
2233             debug!(
2234                 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2235                 def_id1, def_id2
2236             );
2237             Some(ImplOverlapKind::Permitted { marker: true })
2238         } else {
2239             if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2240                 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2241                     if self_ty1 == self_ty2 {
2242                         debug!(
2243                             "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2244                             def_id1, def_id2
2245                         );
2246                         return Some(ImplOverlapKind::Issue33140);
2247                     } else {
2248                         debug!(
2249                             "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2250                             def_id1, def_id2, self_ty1, self_ty2
2251                         );
2252                     }
2253                 }
2254             }
2255
2256             debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2257             None
2258         }
2259     }
2260
2261     /// Returns `ty::VariantDef` if `res` refers to a struct,
2262     /// or variant or their constructors, panics otherwise.
2263     pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2264         match res {
2265             Res::Def(DefKind::Variant, did) => {
2266                 let enum_did = self.parent(did);
2267                 self.adt_def(enum_did).variant_with_id(did)
2268             }
2269             Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2270             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2271                 let variant_did = self.parent(variant_ctor_did);
2272                 let enum_did = self.parent(variant_did);
2273                 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2274             }
2275             Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2276                 let struct_did = self.parent(ctor_did);
2277                 self.adt_def(struct_did).non_enum_variant()
2278             }
2279             _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2280         }
2281     }
2282
2283     /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2284     #[instrument(skip(self), level = "debug")]
2285     pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2286         match instance {
2287             ty::InstanceDef::Item(def) => {
2288                 debug!("calling def_kind on def: {:?}", def);
2289                 let def_kind = self.def_kind(def.did);
2290                 debug!("returned from def_kind: {:?}", def_kind);
2291                 match def_kind {
2292                     DefKind::Const
2293                     | DefKind::Static(..)
2294                     | DefKind::AssocConst
2295                     | DefKind::Ctor(..)
2296                     | DefKind::AnonConst
2297                     | DefKind::InlineConst => self.mir_for_ctfe_opt_const_arg(def),
2298                     // If the caller wants `mir_for_ctfe` of a function they should not be using
2299                     // `instance_mir`, so we'll assume const fn also wants the optimized version.
2300                     _ => {
2301                         assert_eq!(def.const_param_did, None);
2302                         self.optimized_mir(def.did)
2303                     }
2304                 }
2305             }
2306             ty::InstanceDef::VTableShim(..)
2307             | ty::InstanceDef::ReifyShim(..)
2308             | ty::InstanceDef::Intrinsic(..)
2309             | ty::InstanceDef::FnPtrShim(..)
2310             | ty::InstanceDef::Virtual(..)
2311             | ty::InstanceDef::ClosureOnceShim { .. }
2312             | ty::InstanceDef::DropGlue(..)
2313             | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2314         }
2315     }
2316
2317     // FIXME(@lcnr): Remove this function.
2318     pub fn get_attrs_unchecked(self, did: DefId) -> &'tcx [ast::Attribute] {
2319         if let Some(did) = did.as_local() {
2320             self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
2321         } else {
2322             self.item_attrs(did)
2323         }
2324     }
2325
2326     /// Gets all attributes with the given name.
2327     pub fn get_attrs(self, did: DefId, attr: Symbol) -> ty::Attributes<'tcx> {
2328         let filter_fn = move |a: &&ast::Attribute| a.has_name(attr);
2329         if let Some(did) = did.as_local() {
2330             self.hir().attrs(self.hir().local_def_id_to_hir_id(did)).iter().filter(filter_fn)
2331         } else if cfg!(debug_assertions) && rustc_feature::is_builtin_only_local(attr) {
2332             bug!("tried to access the `only_local` attribute `{}` from an extern crate", attr);
2333         } else {
2334             self.item_attrs(did).iter().filter(filter_fn)
2335         }
2336     }
2337
2338     pub fn get_attr(self, did: DefId, attr: Symbol) -> Option<&'tcx ast::Attribute> {
2339         if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
2340             bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
2341         } else {
2342             self.get_attrs(did, attr).next()
2343         }
2344     }
2345
2346     /// Determines whether an item is annotated with an attribute.
2347     pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2348         if cfg!(debug_assertions) && !did.is_local() && rustc_feature::is_builtin_only_local(attr) {
2349             bug!("tried to access the `only_local` attribute `{}` from an extern crate", attr);
2350         } else {
2351             self.get_attrs(did, attr).next().is_some()
2352         }
2353     }
2354
2355     /// Returns `true` if this is an `auto trait`.
2356     pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2357         self.trait_def(trait_def_id).has_auto_impl
2358     }
2359
2360     /// Returns `true` if this is a trait alias.
2361     pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
2362         self.def_kind(trait_def_id) == DefKind::TraitAlias
2363     }
2364
2365     pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
2366         self.trait_is_auto(trait_def_id) || self.lang_items().sized_trait() == Some(trait_def_id)
2367     }
2368
2369     /// Returns layout of a generator. Layout might be unavailable if the
2370     /// generator is tainted by errors.
2371     pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
2372         self.optimized_mir(def_id).generator_layout()
2373     }
2374
2375     /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2376     /// If it implements no trait, returns `None`.
2377     pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2378         self.impl_trait_ref(def_id).map(|tr| tr.skip_binder().def_id)
2379     }
2380
2381     /// If the given `DefId` describes an item belonging to a trait,
2382     /// returns the `DefId` of the trait that the trait item belongs to;
2383     /// otherwise, returns `None`.
2384     pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
2385         if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2386             let parent = self.parent(def_id);
2387             if let DefKind::Trait | DefKind::TraitAlias = self.def_kind(parent) {
2388                 return Some(parent);
2389             }
2390         }
2391         None
2392     }
2393
2394     /// If the given `DefId` describes a method belonging to an impl, returns the
2395     /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2396     pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2397         if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2398             let parent = self.parent(def_id);
2399             if let DefKind::Impl = self.def_kind(parent) {
2400                 return Some(parent);
2401             }
2402         }
2403         None
2404     }
2405
2406     /// If the given `DefId` belongs to a trait that was automatically derived, returns `true`.
2407     pub fn is_builtin_derive(self, def_id: DefId) -> bool {
2408         self.has_attr(def_id, sym::automatically_derived)
2409     }
2410
2411     /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2412     /// with the name of the crate containing the impl.
2413     pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2414         if let Some(impl_def_id) = impl_def_id.as_local() {
2415             Ok(self.def_span(impl_def_id))
2416         } else {
2417             Err(self.crate_name(impl_def_id.krate))
2418         }
2419     }
2420
2421     /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2422     /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2423     /// definition's parent/scope to perform comparison.
2424     pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2425         // We could use `Ident::eq` here, but we deliberately don't. The name
2426         // comparison fails frequently, and we want to avoid the expensive
2427         // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2428         use_name.name == def_name.name
2429             && use_name
2430                 .span
2431                 .ctxt()
2432                 .hygienic_eq(def_name.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2433     }
2434
2435     pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2436         ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2437         ident
2438     }
2439
2440     // FIXME(vincenzoapalzzo): move the HirId to a LocalDefId
2441     pub fn adjust_ident_and_get_scope(
2442         self,
2443         mut ident: Ident,
2444         scope: DefId,
2445         block: hir::HirId,
2446     ) -> (Ident, DefId) {
2447         let scope = ident
2448             .span
2449             .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2450             .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2451             .unwrap_or_else(|| self.parent_module(block).to_def_id());
2452         (ident, scope)
2453     }
2454
2455     /// Returns `true` if the debuginfo for `span` should be collapsed to the outermost expansion
2456     /// site. Only applies when `Span` is the result of macro expansion.
2457     ///
2458     /// - If the `collapse_debuginfo` feature is enabled then debuginfo is not collapsed by default
2459     ///   and only when a macro definition is annotated with `#[collapse_debuginfo]`.
2460     /// - If `collapse_debuginfo` is not enabled, then debuginfo is collapsed by default.
2461     ///
2462     /// When `-Zdebug-macros` is provided then debuginfo will never be collapsed.
2463     pub fn should_collapse_debuginfo(self, span: Span) -> bool {
2464         !self.sess.opts.unstable_opts.debug_macros
2465             && if self.features().collapse_debuginfo {
2466                 span.in_macro_expansion_with_collapse_debuginfo()
2467             } else {
2468                 // Inlined spans should not be collapsed as that leads to all of the
2469                 // inlined code being attributed to the inline callsite.
2470                 span.from_expansion() && !span.is_inlined()
2471             }
2472     }
2473
2474     pub fn is_object_safe(self, key: DefId) -> bool {
2475         self.object_safety_violations(key).is_empty()
2476     }
2477
2478     #[inline]
2479     pub fn is_const_fn_raw(self, def_id: DefId) -> bool {
2480         matches!(
2481             self.def_kind(def_id),
2482             DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::Closure
2483         ) && self.constness(def_id) == hir::Constness::Const
2484     }
2485
2486     #[inline]
2487     pub fn is_const_default_method(self, def_id: DefId) -> bool {
2488         matches!(self.trait_of_item(def_id), Some(trait_id) if self.has_attr(trait_id, sym::const_trait))
2489     }
2490
2491     pub fn impl_trait_in_trait_parent(self, mut def_id: DefId) -> DefId {
2492         while let def_kind = self.def_kind(def_id) && def_kind != DefKind::AssocFn {
2493             debug_assert_eq!(def_kind, DefKind::ImplTraitPlaceholder);
2494             def_id = self.parent(def_id);
2495         }
2496         def_id
2497     }
2498 }
2499
2500 /// Yields the parent function's `LocalDefId` if `def_id` is an `impl Trait` definition.
2501 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<LocalDefId> {
2502     let def_id = def_id.as_local()?;
2503     if let Node::Item(item) = tcx.hir().get_by_def_id(def_id) {
2504         if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2505             return match opaque_ty.origin {
2506                 hir::OpaqueTyOrigin::FnReturn(parent) | hir::OpaqueTyOrigin::AsyncFn(parent) => {
2507                     Some(parent)
2508                 }
2509                 hir::OpaqueTyOrigin::TyAlias => None,
2510             };
2511         }
2512     }
2513     None
2514 }
2515
2516 pub fn int_ty(ity: ast::IntTy) -> IntTy {
2517     match ity {
2518         ast::IntTy::Isize => IntTy::Isize,
2519         ast::IntTy::I8 => IntTy::I8,
2520         ast::IntTy::I16 => IntTy::I16,
2521         ast::IntTy::I32 => IntTy::I32,
2522         ast::IntTy::I64 => IntTy::I64,
2523         ast::IntTy::I128 => IntTy::I128,
2524     }
2525 }
2526
2527 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2528     match uty {
2529         ast::UintTy::Usize => UintTy::Usize,
2530         ast::UintTy::U8 => UintTy::U8,
2531         ast::UintTy::U16 => UintTy::U16,
2532         ast::UintTy::U32 => UintTy::U32,
2533         ast::UintTy::U64 => UintTy::U64,
2534         ast::UintTy::U128 => UintTy::U128,
2535     }
2536 }
2537
2538 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2539     match fty {
2540         ast::FloatTy::F32 => FloatTy::F32,
2541         ast::FloatTy::F64 => FloatTy::F64,
2542     }
2543 }
2544
2545 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2546     match ity {
2547         IntTy::Isize => ast::IntTy::Isize,
2548         IntTy::I8 => ast::IntTy::I8,
2549         IntTy::I16 => ast::IntTy::I16,
2550         IntTy::I32 => ast::IntTy::I32,
2551         IntTy::I64 => ast::IntTy::I64,
2552         IntTy::I128 => ast::IntTy::I128,
2553     }
2554 }
2555
2556 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2557     match uty {
2558         UintTy::Usize => ast::UintTy::Usize,
2559         UintTy::U8 => ast::UintTy::U8,
2560         UintTy::U16 => ast::UintTy::U16,
2561         UintTy::U32 => ast::UintTy::U32,
2562         UintTy::U64 => ast::UintTy::U64,
2563         UintTy::U128 => ast::UintTy::U128,
2564     }
2565 }
2566
2567 pub fn provide(providers: &mut ty::query::Providers) {
2568     closure::provide(providers);
2569     context::provide(providers);
2570     erase_regions::provide(providers);
2571     inhabitedness::provide(providers);
2572     util::provide(providers);
2573     print::provide(providers);
2574     super::util::bug::provide(providers);
2575     super::middle::provide(providers);
2576     *providers = ty::query::Providers {
2577         trait_impls_of: trait_def::trait_impls_of_provider,
2578         incoherent_impls: trait_def::incoherent_impls_provider,
2579         const_param_default: consts::const_param_default,
2580         vtable_allocation: vtable::vtable_allocation_provider,
2581         ..*providers
2582     };
2583 }
2584
2585 /// A map for the local crate mapping each type to a vector of its
2586 /// inherent impls. This is not meant to be used outside of coherence;
2587 /// rather, you should request the vector for a specific type via
2588 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2589 /// (constructing this map requires touching the entire crate).
2590 #[derive(Clone, Debug, Default, HashStable)]
2591 pub struct CrateInherentImpls {
2592     pub inherent_impls: LocalDefIdMap<Vec<DefId>>,
2593     pub incoherent_impls: FxHashMap<SimplifiedType, Vec<LocalDefId>>,
2594 }
2595
2596 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2597 pub struct SymbolName<'tcx> {
2598     /// `&str` gives a consistent ordering, which ensures reproducible builds.
2599     pub name: &'tcx str,
2600 }
2601
2602 impl<'tcx> SymbolName<'tcx> {
2603     pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2604         SymbolName {
2605             name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
2606         }
2607     }
2608 }
2609
2610 impl<'tcx> fmt::Display for SymbolName<'tcx> {
2611     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2612         fmt::Display::fmt(&self.name, fmt)
2613     }
2614 }
2615
2616 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2617     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2618         fmt::Display::fmt(&self.name, fmt)
2619     }
2620 }
2621
2622 #[derive(Debug, Default, Copy, Clone)]
2623 pub struct InferVarInfo {
2624     /// This is true if we identified that this Ty (`?T`) is found in a `?T: Foo`
2625     /// obligation, where:
2626     ///
2627     ///  * `Foo` is not `Sized`
2628     ///  * `(): Foo` may be satisfied
2629     pub self_in_trait: bool,
2630     /// This is true if we identified that this Ty (`?T`) is found in a `<_ as
2631     /// _>::AssocType = ?T`
2632     pub output: bool,
2633 }
2634
2635 /// The constituent parts of a type level constant of kind ADT or array.
2636 #[derive(Copy, Clone, Debug, HashStable)]
2637 pub struct DestructuredConst<'tcx> {
2638     pub variant: Option<VariantIdx>,
2639     pub fields: &'tcx [ty::Const<'tcx>],
2640 }
2641
2642 // Some types are used a lot. Make sure they don't unintentionally get bigger.
2643 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2644 mod size_asserts {
2645     use super::*;
2646     use rustc_data_structures::static_assert_size;
2647     // tidy-alphabetical-start
2648     static_assert_size!(PredicateKind<'_>, 32);
2649     static_assert_size!(WithCachedTypeInfo<TyKind<'_>>, 56);
2650     // tidy-alphabetical-end
2651 }