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