]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_middle/src/ty/mod.rs
New upstream version 1.57.0+dfsg1
[rustc.git] / compiler / rustc_middle / src / ty / mod.rs
CommitLineData
fc512014
XL
1//! Defines how the compiler represents types internally.
2//!
3//! Two important entities in this module are:
4//!
5//! - [`rustc_middle::ty::Ty`], used to represent the semantics of a type.
6//! - [`rustc_middle::ty::TyCtxt`], the central data structure in the compiler.
7//!
8//! For more information, see ["The `ty` module: representing types"] in the ructc-dev-guide.
9//!
10//! ["The `ty` module: representing types"]: https://rustc-dev-guide.rust-lang.org/ty.html
11
3dfed10e 12pub use self::fold::{TypeFoldable, TypeFolder, TypeVisitor};
dc9dc135 13pub use self::AssocItemContainer::*;
e9174d1e 14pub use self::BorrowKind::*;
e9174d1e 15pub use self::IntVarValue::*;
dfeec247 16pub use self::Variance::*;
6a06907d
XL
17pub use adt::*;
18pub use assoc::*;
6a06907d 19pub use generics::*;
136023e0 20pub use vtable::*;
dfeec247 21
dfeec247 22use crate::hir::exports::ExportMap;
6a06907d 23use crate::mir::{Body, GeneratorLayout};
9fa01778
XL
24use crate::traits::{self, Reveal};
25use crate::ty;
f035d41b 26use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
6a06907d 27use crate::ty::util::Discr;
3dfed10e 28use rustc_ast as ast;
74b04a01 29use rustc_attr as attr;
6a06907d 30use rustc_data_structures::fx::{FxHashMap, FxHashSet};
dfeec247 31use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
3dfed10e 32use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
dfeec247 33use rustc_hir as hir;
6a06907d 34use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
17df50a5 35use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalDefIdMap, CRATE_DEF_INDEX};
94222f64 36use rustc_hir::Node;
dfeec247 37use rustc_macros::HashStable;
c295e0f8
XL
38use rustc_query_system::ich::StableHashingContext;
39use rustc_session::cstore::CrateStoreDyn;
6a06907d 40use rustc_span::symbol::{kw, Ident, Symbol};
c295e0f8 41use rustc_span::{sym, Span};
6a06907d 42use rustc_target::abi::Align;
74b04a01 43
f9f354fc 44use std::cmp::Ordering;
94222f64 45use std::collections::BTreeMap;
e9174d1e 46use std::hash::{Hash, Hasher};
6a06907d
XL
47use std::ops::ControlFlow;
48use std::{fmt, ptr, str};
54a0048b 49
60c5eb7d 50pub use crate::ty::diagnostics::*;
5869c6ff
XL
51pub use rustc_type_ir::InferTy::*;
52pub use rustc_type_ir::*;
e9174d1e 53
3b2f2976
XL
54pub use self::binding::BindingMode;
55pub use self::binding::BindingMode::*;
94222f64
XL
56pub use self::closure::{
57 is_ancestor_or_same_capture, place_to_string_for_capture, BorrowKind, CaptureInfo,
58 CapturedPlace, ClosureKind, MinCaptureInformationMap, MinCaptureList,
59 RootVariableMinCaptureList, UpvarBorrow, UpvarCapture, UpvarCaptureMap, UpvarId, UpvarListMap,
60 UpvarPath, CAPTURE_STRUCT_LOCAL,
61};
cdc7bbd5 62pub use self::consts::{Const, ConstInt, ConstKind, InferConst, ScalarInt, Unevaluated, ValTree};
0731742a 63pub use self::context::{
6a06907d
XL
64 tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
65 CtxtInterners, DelaySpanBugEmitted, FreeRegionInfo, GeneratorInteriorTypeCause, GlobalCtxt,
136023e0 66 Lift, OnDiskCache, TyCtxt, TypeckResults, UserType, UserTypeAnnotationIndex,
0731742a 67};
cc61c64b 68pub use self::instance::{Instance, InstanceDef};
f9f354fc 69pub use self::list::List;
6a06907d
XL
70pub use self::sty::BoundRegionKind::*;
71pub use self::sty::RegionKind::*;
72pub use self::sty::TyKind::*;
73pub use self::sty::{
cdc7bbd5
XL
74 Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar, BoundVariableKind,
75 CanonicalPolyFnSig, ClosureSubsts, ClosureSubstsParts, ConstVid, EarlyBoundRegion,
76 ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FnSig, FreeRegion, GenSig,
77 GeneratorSubsts, GeneratorSubstsParts, ParamConst, ParamTy, PolyExistentialProjection,
78 PolyExistentialTraitRef, PolyFnSig, PolyGenSig, PolyTraitRef, ProjectionTy, Region, RegionKind,
17df50a5 79 RegionVid, TraitRef, TyKind, TypeAndMut, UpvarSubsts, VarianceDiagInfo, VarianceDiagMutKind,
6a06907d 80};
7cac9316 81pub use self::trait_def::TraitDef;
9cc50fc6 82
3dfed10e 83pub mod _match;
e9174d1e 84pub mod adjustment;
3b2f2976 85pub mod binding;
e9174d1e 86pub mod cast;
abe05a73 87pub mod codec;
dfeec247 88pub mod error;
e9174d1e 89pub mod fast_reject;
48663c56 90pub mod flags;
e9174d1e 91pub mod fold;
32a655c1 92pub mod inhabitedness;
54a0048b 93pub mod layout;
dfeec247 94pub mod normalize_erasing_regions;
532ac7d7 95pub mod print;
94b46f34 96pub mod query;
e9174d1e 97pub mod relate;
54a0048b 98pub mod subst;
9cc50fc6 99pub mod trait_def;
e9174d1e 100pub mod util;
136023e0 101pub mod vtable;
dfeec247 102pub mod walk;
e9174d1e 103
6a06907d
XL
104mod adt;
105mod assoc;
106mod closure;
f035d41b 107mod consts;
e9174d1e 108mod context;
dfeec247 109mod diagnostics;
6a06907d
XL
110mod erase_regions;
111mod generics;
c295e0f8 112mod impls_ty;
cc61c64b 113mod instance;
f9f354fc 114mod list;
e9174d1e
SL
115mod structural_impls;
116mod sty;
117
e9174d1e
SL
118// Data types
119
136023e0 120#[derive(Debug)]
e74abb32 121pub struct ResolverOutputs {
ba9703b0 122 pub definitions: rustc_hir::definitions::Definitions,
e74abb32 123 pub cstore: Box<CrateStoreDyn>,
29967ef6 124 pub visibilities: FxHashMap<LocalDefId, Visibility>,
f9f354fc 125 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
f9f354fc
XL
126 pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
127 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
c295e0f8 128 pub export_map: ExportMap,
f9f354fc 129 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
0bf4aa26
XL
130 /// Extern prelude entries. The value is `true` if the entry was introduced
131 /// via `extern crate` item and not `--extern` option or compiler built-in.
f9f354fc 132 pub extern_prelude: FxHashMap<Symbol, bool>,
cdc7bbd5 133 pub main_def: Option<MainDefinition>,
94222f64
XL
134 pub trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
135 /// A list of proc macro LocalDefIds, written out in the order in which
136 /// they are declared in the static array generated by proc_macro_harness.
137 pub proc_macros: Vec<LocalDefId>,
c295e0f8
XL
138 /// Mapping from ident span to path span for paths that don't exist as written, but that
139 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
140 pub confused_type_with_std_module: FxHashMap<Span, Span>,
cdc7bbd5
XL
141}
142
136023e0 143#[derive(Clone, Copy, Debug)]
cdc7bbd5
XL
144pub struct MainDefinition {
145 pub res: Res<ast::NodeId>,
146 pub is_import: bool,
147 pub span: Span,
148}
149
150impl MainDefinition {
151 pub fn opt_fn_def_id(self) -> Option<DefId> {
152 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
153 }
e9174d1e
SL
154}
155
54a0048b
SL
156/// The "header" of an impl is everything outside the body: a Self type, a trait
157/// ref (in the case of a trait impl), and a set of predicates (from the
9fa01778 158/// bounds / where-clauses).
60c5eb7d 159#[derive(Clone, Debug, TypeFoldable)]
54a0048b
SL
160pub struct ImplHeader<'tcx> {
161 pub impl_def_id: DefId,
162 pub self_ty: Ty<'tcx>,
163 pub trait_ref: Option<TraitRef<'tcx>>,
164 pub predicates: Vec<Predicate<'tcx>>,
165}
166
5869c6ff 167#[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable, Debug)]
e74abb32
XL
168pub enum ImplPolarity {
169 /// `impl Trait for Type`
170 Positive,
171 /// `impl !Trait for Type`
172 Negative,
173 /// `#[rustc_reservation_impl] impl Trait for Type`
174 ///
175 /// This is a "stability hack", not a real Rust feature.
176 /// See #64631 for details.
177 Reservation,
178}
179
3dfed10e 180#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
54a0048b
SL
181pub enum Visibility {
182 /// Visible everywhere (including in other crates).
183 Public,
184 /// Visible only in the given crate-local module.
32a655c1 185 Restricted(DefId),
54a0048b 186 /// Not visible anywhere in the local crate. This is the visibility of private external items.
32a655c1 187 Invisible,
54a0048b
SL
188}
189
94222f64
XL
190#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
191pub enum BoundConstness {
192 /// `T: Trait`
193 NotConst,
194 /// `T: ~const Trait`
195 ///
196 /// Requires resolving to const only when we are in a const context.
197 ConstIfConst,
198}
199
200impl fmt::Display for BoundConstness {
201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202 match self {
203 Self::NotConst => f.write_str("normal"),
204 Self::ConstIfConst => f.write_str("`~const`"),
205 }
206 }
207}
208
136023e0
XL
209#[derive(
210 Clone,
211 Debug,
212 PartialEq,
213 Eq,
214 Copy,
215 Hash,
216 TyEncodable,
217 TyDecodable,
218 HashStable,
219 TypeFoldable
220)]
221pub struct ClosureSizeProfileData<'tcx> {
222 /// Tuple containing the types of closure captures before the feature `capture_disjoint_fields`
223 pub before_feature_tys: Ty<'tcx>,
224 /// Tuple containing the types of closure captures after the feature `capture_disjoint_fields`
225 pub after_feature_tys: Ty<'tcx>,
226}
227
32a655c1
SL
228pub trait DefIdTree: Copy {
229 fn parent(self, id: DefId) -> Option<DefId>;
a7813a04 230
32a655c1
SL
231 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
232 if descendant.krate != ancestor.krate {
233 return false;
234 }
235
236 while descendant != ancestor {
237 match self.parent(descendant) {
238 Some(parent) => descendant = parent,
239 None => return false,
a7813a04 240 }
a7813a04
XL
241 }
242 true
243 }
244}
245
dc9dc135 246impl<'tcx> DefIdTree for TyCtxt<'tcx> {
32a655c1 247 fn parent(self, id: DefId) -> Option<DefId> {
74b04a01 248 self.def_key(id).parent.map(|index| DefId { index, ..id })
32a655c1
SL
249 }
250}
251
54a0048b 252impl Visibility {
dfeec247 253 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
8faf50e0
XL
254 match visibility.node {
255 hir::VisibilityKind::Public => Visibility::Public,
256 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
48663c56 257 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
a7813a04
XL
258 // If there is no resolution, `resolve` will have already reported an error, so
259 // assume that the visibility is public to avoid reporting more privacy errors.
48663c56 260 Res::Err => Visibility::Public,
32a655c1 261 def => Visibility::Restricted(def.def_id()),
a7813a04 262 },
ba9703b0
XL
263 hir::VisibilityKind::Inherited => {
264 Visibility::Restricted(tcx.parent_module(id).to_def_id())
265 }
54a0048b
SL
266 }
267 }
268
a1dfa0c6 269 /// Returns `true` if an item with this visibility is accessible from the given block.
32a655c1 270 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
54a0048b
SL
271 let restriction = match self {
272 // Public items are visible everywhere.
273 Visibility::Public => return true,
274 // Private items from other crates are visible nowhere.
32a655c1 275 Visibility::Invisible => return false,
54a0048b 276 // Restricted items are visible in an arbitrary local module.
32a655c1 277 Visibility::Restricted(other) if other.krate != module.krate => return false,
54a0048b
SL
278 Visibility::Restricted(module) => module,
279 };
280
32a655c1 281 tree.is_descendant_of(module, restriction)
54a0048b
SL
282 }
283
a1dfa0c6 284 /// Returns `true` if this visibility is at least as accessible as the given visibility
32a655c1 285 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
54a0048b
SL
286 let vis_restriction = match vis {
287 Visibility::Public => return self == Visibility::Public,
32a655c1 288 Visibility::Invisible => return true,
54a0048b
SL
289 Visibility::Restricted(module) => module,
290 };
291
a7813a04 292 self.is_accessible_from(vis_restriction, tree)
54a0048b 293 }
ff7c6d11 294
a1dfa0c6 295 // Returns `true` if this item is visible anywhere in the local crate.
ff7c6d11
XL
296 pub fn is_visible_locally(self) -> bool {
297 match self {
298 Visibility::Public => true,
299 Visibility::Restricted(def_id) => def_id.is_local(),
300 Visibility::Invisible => false,
301 }
302 }
54a0048b
SL
303}
304
7cac9316
XL
305/// The crate variances map is computed during typeck and contains the
306/// variance of every item in the local crate. You should not use it
307/// directly, because to do so will make your pass dependent on the
308/// HIR of every item in the local crate. Instead, use
309/// `tcx.variances_of()` to get the variance for a *particular*
310/// item.
5869c6ff 311#[derive(HashStable, Debug)]
48663c56 312pub struct CrateVariancesMap<'tcx> {
7cac9316 313 /// For each item with generics, maps to a vector of the variance
9fa01778 314 /// of its generics. If an item has no generics, it will have no
7cac9316 315 /// entry.
48663c56 316 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
7cac9316
XL
317}
318
e9174d1e
SL
319// Contains information needed to resolve types and (in the future) look up
320// the types of AST nodes.
321#[derive(Copy, Clone, PartialEq, Eq, Hash)]
322pub struct CReaderCacheKey {
17df50a5 323 pub cnum: Option<CrateNum>,
e9174d1e 324 pub pos: usize,
e9174d1e
SL
325}
326
e1599b0c 327#[allow(rustc::usage_of_ty_tykind)]
e9174d1e 328pub struct TyS<'tcx> {
1b1a35ee
XL
329 /// This field shouldn't be used directly and may be removed in the future.
330 /// Use `TyS::kind()` instead.
331 kind: TyKind<'tcx>,
332 /// This field shouldn't be used directly and may be removed in the future.
333 /// Use `TyS::flags()` instead.
334 flags: TypeFlags,
e9174d1e 335
94b46f34
XL
336 /// This is a kind of confusing thing: it stores the smallest
337 /// binder such that
338 ///
339 /// (a) the binder itself captures nothing but
340 /// (b) all the late-bound things within the type are captured
341 /// by some sub-binder.
342 ///
343 /// So, for a type without any late-bound things, like `u32`, this
0731742a 344 /// will be *innermost*, because that is the innermost binder that
94b46f34 345 /// captures nothing. But for a type `&'D u32`, where `'D` is a
9fa01778 346 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
0731742a
XL
347 /// -- the binder itself does not capture `D`, but `D` is captured
348 /// by an inner binder.
94b46f34 349 ///
0731742a 350 /// We call this concept an "exclusive" binder `D` because all
9fa01778 351 /// De Bruijn indices within the type are contained within `0..D`
0731742a 352 /// (exclusive).
94b46f34
XL
353 outer_exclusive_binder: ty::DebruijnIndex,
354}
355
fc512014
XL
356impl<'tcx> TyS<'tcx> {
357 /// A constructor used only for internal testing.
358 #[allow(rustc::usage_of_ty_tykind)]
359 pub fn make_for_test(
360 kind: TyKind<'tcx>,
361 flags: TypeFlags,
362 outer_exclusive_binder: ty::DebruijnIndex,
363 ) -> TyS<'tcx> {
364 TyS { kind, flags, outer_exclusive_binder }
365 }
366}
367
a1dfa0c6 368// `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
6a06907d 369#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
cdc7bbd5 370static_assert_size!(TyS<'_>, 40);
a1dfa0c6 371
94b46f34
XL
372impl<'tcx> Ord for TyS<'tcx> {
373 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
1b1a35ee 374 self.kind().cmp(other.kind())
94b46f34
XL
375 }
376}
377
378impl<'tcx> PartialOrd for TyS<'tcx> {
379 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
1b1a35ee 380 Some(self.kind().cmp(other.kind()))
94b46f34 381 }
e9174d1e
SL
382}
383
384impl<'tcx> PartialEq for TyS<'tcx> {
385 #[inline]
386 fn eq(&self, other: &TyS<'tcx>) -> bool {
8faf50e0 387 ptr::eq(self, other)
e9174d1e
SL
388 }
389}
390impl<'tcx> Eq for TyS<'tcx> {}
391
392impl<'tcx> Hash for TyS<'tcx> {
393 fn hash<H: Hasher>(&self, s: &mut H) {
0bf4aa26 394 (self as *const TyS<'_>).hash(s)
e9174d1e
SL
395 }
396}
397
f035d41b 398impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
e74abb32 399 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
cc61c64b 400 let ty::TyS {
e74abb32 401 ref kind,
cc61c64b
XL
402
403 // The other fields just provide fast access to information that is
e74abb32 404 // also contained in `kind`, so no need to hash them.
cc61c64b 405 flags: _,
94b46f34
XL
406
407 outer_exclusive_binder: _,
cc61c64b
XL
408 } = *self;
409
e74abb32 410 kind.hash_stable(hcx, hasher);
cc61c64b
XL
411 }
412}
413
e74abb32 414#[rustc_diagnostic_item = "Ty"]
e9174d1e
SL
415pub type Ty<'tcx> = &'tcx TyS<'tcx>;
416
94b46f34 417impl ty::EarlyBoundRegion {
b7449926
XL
418 /// Does this early bound region have a name? Early bound regions normally
419 /// always have names except when using anonymous lifetimes (`'_`).
420 pub fn has_name(&self) -> bool {
e74abb32 421 self.name != kw::UnderscoreLifetime
b7449926 422 }
94b46f34 423}
ea8adc8c 424
f035d41b
XL
425#[derive(Debug)]
426crate struct PredicateInner<'tcx> {
cdc7bbd5 427 kind: Binder<'tcx, PredicateKind<'tcx>>,
f035d41b
XL
428 flags: TypeFlags,
429 /// See the comment for the corresponding field of [TyS].
430 outer_exclusive_binder: ty::DebruijnIndex,
431}
432
6a06907d 433#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
cdc7bbd5 434static_assert_size!(PredicateInner<'_>, 48);
f035d41b
XL
435
436#[derive(Clone, Copy, Lift)]
f9f354fc 437pub struct Predicate<'tcx> {
f035d41b 438 inner: &'tcx PredicateInner<'tcx>,
f9f354fc
XL
439}
440
441impl<'tcx> PartialEq for Predicate<'tcx> {
442 fn eq(&self, other: &Self) -> bool {
443 // `self.kind` is always interned.
f035d41b
XL
444 ptr::eq(self.inner, other.inner)
445 }
446}
447
448impl Hash for Predicate<'_> {
449 fn hash<H: Hasher>(&self, s: &mut H) {
450 (self.inner as *const PredicateInner<'_>).hash(s)
f9f354fc
XL
451 }
452}
453
454impl<'tcx> Eq for Predicate<'tcx> {}
455
456impl<'tcx> Predicate<'tcx> {
cdc7bbd5 457 /// Gets the inner `Binder<'tcx, PredicateKind<'tcx>>`.
6a06907d 458 #[inline]
cdc7bbd5 459 pub fn kind(self) -> Binder<'tcx, PredicateKind<'tcx>> {
5869c6ff 460 self.inner.kind
3dfed10e 461 }
f035d41b
XL
462}
463
464impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
465 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
466 let PredicateInner {
467 ref kind,
468
469 // The other fields just provide fast access to information that is
470 // also contained in `kind`, so no need to hash them.
471 flags: _,
472 outer_exclusive_binder: _,
473 } = self.inner;
474
475 kind.hash_stable(hcx, hasher);
f9f354fc
XL
476 }
477}
478
3dfed10e 479#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
60c5eb7d 480#[derive(HashStable, TypeFoldable)]
f9f354fc 481pub enum PredicateKind<'tcx> {
dc9dc135 482 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
e9174d1e 483 /// the `Self` type of the trait reference and `A`, `B`, and `C`
9e0c209e 484 /// would be the type parameters.
94222f64 485 Trait(TraitPredicate<'tcx>),
e9174d1e 486
dc9dc135 487 /// `where 'a: 'b`
3dfed10e 488 RegionOutlives(RegionOutlivesPredicate<'tcx>),
e9174d1e 489
dc9dc135 490 /// `where T: 'a`
3dfed10e 491 TypeOutlives(TypeOutlivesPredicate<'tcx>),
e9174d1e 492
dc9dc135 493 /// `where <T as TraitRef>::Name == X`, approximately.
a1dfa0c6 494 /// See the `ProjectionPredicate` struct for details.
3dfed10e 495 Projection(ProjectionPredicate<'tcx>),
e9174d1e 496
dc9dc135 497 /// No syntax: `T` well-formed.
f035d41b 498 WellFormed(GenericArg<'tcx>),
e9174d1e 499
dc9dc135 500 /// Trait must be object-safe.
e9174d1e 501 ObjectSafe(DefId),
a7813a04 502
a1dfa0c6
XL
503 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
504 /// for some substitutions `...` and `T` being a closure type.
9e0c209e 505 /// Satisfied (or refuted) once we know the closure's kind.
e74abb32 506 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
cc61c64b
XL
507
508 /// `T1 <: T2`
94222f64
XL
509 ///
510 /// This obligation is created most often when we have two
511 /// unresolved type variables and hence don't have enough
512 /// information to process the subtyping obligation yet.
3dfed10e 513 Subtype(SubtypePredicate<'tcx>),
ea8adc8c 514
94222f64
XL
515 /// `T1` coerced to `T2`
516 ///
517 /// Like a subtyping obligation, this is created most often
518 /// when we have two unresolved type variables and hence
519 /// don't have enough information to process the coercion
520 /// obligation yet. At the moment, we actually process coercions
521 /// very much like subtyping and don't handle the full coercion
522 /// logic.
523 Coerce(CoercePredicate<'tcx>),
524
ea8adc8c 525 /// Constant initializer must evaluate successfully.
94222f64 526 ConstEvaluatable(ty::Unevaluated<'tcx, ()>),
f9f354fc
XL
527
528 /// Constants must be equal. The first component is the const that is expected.
529 ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
1b1a35ee
XL
530
531 /// Represents a type found in the environment that we can use for implied bounds.
532 ///
533 /// Only used for Chalk.
534 TypeWellFormedFromEnv(Ty<'tcx>),
e9174d1e
SL
535}
536
83c7162d
XL
537/// The crate outlives map is computed during typeck and contains the
538/// outlives of every item in the local crate. You should not use it
539/// directly, because to do so will make your pass dependent on the
540/// HIR of every item in the local crate. Instead, use
541/// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
542/// item.
5869c6ff 543#[derive(HashStable, Debug)]
83c7162d
XL
544pub struct CratePredicatesMap<'tcx> {
545 /// For each struct with outlive bounds, maps to a vector of the
546 /// predicate of its outlive bounds. If an item has no outlives
547 /// bounds, it will have no entry.
3dfed10e 548 pub predicates: FxHashMap<DefId, &'tcx [(Predicate<'tcx>, Span)]>,
83c7162d
XL
549}
550
dc9dc135 551impl<'tcx> Predicate<'tcx> {
e9174d1e
SL
552 /// Performs a substitution suitable for going from a
553 /// poly-trait-ref to supertraits that must hold if that
554 /// poly-trait-ref holds. This is slightly different from a normal
9fa01778 555 /// substitution in terms of what happens with bound regions. See
e9174d1e 556 /// lengthy comment below for details.
dc9dc135 557 pub fn subst_supertrait(
f9f354fc 558 self,
dc9dc135
XL
559 tcx: TyCtxt<'tcx>,
560 trait_ref: &ty::PolyTraitRef<'tcx>,
3dfed10e 561 ) -> Predicate<'tcx> {
e9174d1e
SL
562 // The interaction between HRTB and supertraits is not entirely
563 // obvious. Let me walk you (and myself) through an example.
564 //
565 // Let's start with an easy case. Consider two traits:
566 //
a1dfa0c6 567 // trait Foo<'a>: Bar<'a,'a> { }
e9174d1e
SL
568 // trait Bar<'b,'c> { }
569 //
a1dfa0c6
XL
570 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
571 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
e9174d1e
SL
572 // knew that `Foo<'x>` (for any 'x) then we also know that
573 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
574 // normal substitution.
575 //
576 // In terms of why this is sound, the idea is that whenever there
577 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
578 // holds. So if there is an impl of `T:Foo<'a>` that applies to
579 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
580 // `'a`.
581 //
582 // Another example to be careful of is this:
583 //
a1dfa0c6 584 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
e9174d1e
SL
585 // trait Bar1<'b,'c> { }
586 //
a1dfa0c6
XL
587 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
588 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
e9174d1e 589 // reason is similar to the previous example: any impl of
a1dfa0c6 590 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
e9174d1e
SL
591 // basically we would want to collapse the bound lifetimes from
592 // the input (`trait_ref`) and the supertraits.
593 //
594 // To achieve this in practice is fairly straightforward. Let's
595 // consider the more complicated scenario:
596 //
a1dfa0c6
XL
597 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
598 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
e9174d1e
SL
599 // where both `'x` and `'b` would have a DB index of 1.
600 // The substitution from the input trait-ref is therefore going to be
601 // `'a => 'x` (where `'x` has a DB index of 1).
c295e0f8 602 // - The supertrait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
e9174d1e
SL
603 // early-bound parameter and `'b' is a late-bound parameter with a
604 // DB index of 1.
605 // - If we replace `'a` with `'x` from the input, it too will have
606 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
607 // just as we wanted.
608 //
609 // There is only one catch. If we just apply the substitution `'a
610 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
611 // adjust the DB index because we substituting into a binder (it
612 // tries to be so smart...) resulting in `for<'x> for<'b>
613 // Bar1<'x,'b>` (we have no syntax for this, so use your
614 // imagination). Basically the 'x will have DB index of 2 and 'b
615 // will have DB index of 1. Not quite what we want. So we apply
616 // the substitution to the *contents* of the trait reference,
617 // rather than the trait reference itself (put another way, the
618 // substitution code expects equal binding levels in the values
619 // from the substitution and the value being substituted into, and
620 // this trick achieves that).
cdc7bbd5
XL
621
622 // Working through the second example:
623 // trait_ref: for<'x> T: Foo1<'^0.0>; substs: [T, '^0.0]
624 // predicate: for<'b> Self: Bar1<'a, '^0.0>; substs: [Self, 'a, '^0.0]
625 // We want to end up with:
626 // for<'x, 'b> T: Bar1<'^0.0, '^0.1>
627 // To do this:
628 // 1) We must shift all bound vars in predicate by the length
629 // of trait ref's bound vars. So, we would end up with predicate like
630 // Self: Bar1<'a, '^0.1>
631 // 2) We can then apply the trait substs to this, ending up with
632 // T: Bar1<'^0.0, '^0.1>
633 // 3) Finally, to create the final bound vars, we concatenate the bound
634 // vars of the trait ref with those of the predicate:
635 // ['x, 'b]
636 let bound_pred = self.kind();
637 let pred_bound_vars = bound_pred.bound_vars();
638 let trait_bound_vars = trait_ref.bound_vars();
639 // 1) Self: Bar1<'a, '^0.0> -> Self: Bar1<'a, '^0.1>
640 let shifted_pred =
641 tcx.shift_bound_var_indices(trait_bound_vars.len(), bound_pred.skip_binder());
642 // 2) Self: Bar1<'a, '^0.1> -> T: Bar1<'^0.0, '^0.1>
643 let new = shifted_pred.subst(tcx, trait_ref.skip_binder().substs);
644 // 3) ['x] + ['b] -> ['x, 'b]
645 let bound_vars =
646 tcx.mk_bound_variable_kinds(trait_bound_vars.iter().chain(pred_bound_vars));
647 tcx.reuse_or_mk_predicate(self, ty::Binder::bind_with_vars(new, bound_vars))
e9174d1e
SL
648 }
649}
650
3dfed10e 651#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
60c5eb7d 652#[derive(HashStable, TypeFoldable)]
e9174d1e 653pub struct TraitPredicate<'tcx> {
dfeec247 654 pub trait_ref: TraitRef<'tcx>,
94222f64
XL
655
656 pub constness: BoundConstness,
e9174d1e 657}
a1dfa0c6 658
cdc7bbd5 659pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>;
e9174d1e
SL
660
661impl<'tcx> TraitPredicate<'tcx> {
f9f354fc 662 pub fn def_id(self) -> DefId {
e9174d1e
SL
663 self.trait_ref.def_id
664 }
665
f9f354fc 666 pub fn self_ty(self) -> Ty<'tcx> {
e9174d1e
SL
667 self.trait_ref.self_ty()
668 }
669}
670
671impl<'tcx> PolyTraitPredicate<'tcx> {
f9f354fc 672 pub fn def_id(self) -> DefId {
416331ca 673 // Ok to skip binder since trait `DefId` does not care about regions.
83c7162d 674 self.skip_binder().def_id()
e9174d1e 675 }
fc512014 676
cdc7bbd5 677 pub fn self_ty(self) -> ty::Binder<'tcx, Ty<'tcx>> {
fc512014
XL
678 self.map_bound(|trait_ref| trait_ref.self_ty())
679 }
e9174d1e
SL
680}
681
3dfed10e 682#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
60c5eb7d 683#[derive(HashStable, TypeFoldable)]
dc9dc135 684pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
dc9dc135
XL
685pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
686pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
cdc7bbd5
XL
687pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<'tcx, RegionOutlivesPredicate<'tcx>>;
688pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<'tcx, TypeOutlivesPredicate<'tcx>>;
e9174d1e 689
94222f64
XL
690/// Encodes that `a` must be a subtype of `b`. The `a_is_expected` flag indicates
691/// whether the `a` type is the type that we should label as "expected" when
692/// presenting user diagnostics.
3dfed10e 693#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
60c5eb7d 694#[derive(HashStable, TypeFoldable)]
cc61c64b
XL
695pub struct SubtypePredicate<'tcx> {
696 pub a_is_expected: bool,
697 pub a: Ty<'tcx>,
dfeec247 698 pub b: Ty<'tcx>,
cc61c64b 699}
cdc7bbd5 700pub type PolySubtypePredicate<'tcx> = ty::Binder<'tcx, SubtypePredicate<'tcx>>;
cc61c64b 701
94222f64
XL
702/// Encodes that we have to coerce *from* the `a` type to the `b` type.
703#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
704#[derive(HashStable, TypeFoldable)]
705pub struct CoercePredicate<'tcx> {
706 pub a: Ty<'tcx>,
707 pub b: Ty<'tcx>,
708}
709pub type PolyCoercePredicate<'tcx> = ty::Binder<'tcx, CoercePredicate<'tcx>>;
710
e9174d1e
SL
711/// This kind of predicate has no *direct* correspondent in the
712/// syntax, but it roughly corresponds to the syntactic forms:
713///
9fa01778 714/// 1. `T: TraitRef<..., Item = Type>`
e9174d1e
SL
715/// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
716///
717/// In particular, form #1 is "desugared" to the combination of a
a1dfa0c6 718/// normal trait predicate (`T: TraitRef<...>`) and one of these
e9174d1e 719/// predicates. Form #2 is a broader form in that it also permits
ff7c6d11
XL
720/// equality between arbitrary types. Processing an instance of
721/// Form #2 eventually yields one of these `ProjectionPredicate`
e9174d1e 722/// instances to normalize the LHS.
3dfed10e 723#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
60c5eb7d 724#[derive(HashStable, TypeFoldable)]
e9174d1e
SL
725pub struct ProjectionPredicate<'tcx> {
726 pub projection_ty: ProjectionTy<'tcx>,
727 pub ty: Ty<'tcx>,
728}
729
cdc7bbd5 730pub type PolyProjectionPredicate<'tcx> = Binder<'tcx, ProjectionPredicate<'tcx>>;
e9174d1e
SL
731
732impl<'tcx> PolyProjectionPredicate<'tcx> {
6a06907d
XL
733 /// Returns the `DefId` of the trait of the associated item being projected.
734 #[inline]
735 pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
736 self.skip_binder().projection_ty.trait_def_id(tcx)
737 }
738
6a06907d
XL
739 /// Get the [PolyTraitRef] required for this projection to be well formed.
740 /// Note that for generic associated types the predicates of the associated
741 /// type also need to be checked.
a1dfa0c6 742 #[inline]
6a06907d 743 pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
a1dfa0c6
XL
744 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
745 // `self.0.trait_ref` is permitted to have escaping regions.
041b39d2
XL
746 // This is because here `self` has a `Binder` and so does our
747 // return value, so we are preserving the number of binding
748 // levels.
83c7162d 749 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
e9174d1e 750 }
3b2f2976 751
cdc7bbd5 752 pub fn ty(&self) -> Binder<'tcx, Ty<'tcx>> {
83c7162d
XL
753 self.map_bound(|predicate| predicate.ty)
754 }
755
a1dfa0c6 756 /// The `DefId` of the `TraitItem` for the associated type.
83c7162d 757 ///
a1dfa0c6
XL
758 /// Note that this is not the `DefId` of the `TraitRef` containing this
759 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
83c7162d 760 pub fn projection_def_id(&self) -> DefId {
416331ca 761 // Ok to skip binder since trait `DefId` does not care about regions.
83c7162d 762 self.skip_binder().projection_ty.item_def_id
3b2f2976 763 }
e9174d1e
SL
764}
765
766pub trait ToPolyTraitRef<'tcx> {
767 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
768}
769
e9174d1e
SL
770impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
771 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
7453a54e 772 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
e9174d1e
SL
773 }
774}
775
e9174d1e 776pub trait ToPredicate<'tcx> {
f035d41b 777 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
f9f354fc
XL
778}
779
cdc7bbd5 780impl ToPredicate<'tcx> for Binder<'tcx, PredicateKind<'tcx>> {
f9f354fc 781 #[inline(always)]
f035d41b
XL
782 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
783 tcx.mk_predicate(self)
f9f354fc 784 }
e9174d1e
SL
785}
786
dfeec247 787impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
f035d41b 788 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
cdc7bbd5
XL
789 self.value
790 .map_bound(|trait_ref| {
94222f64 791 PredicateKind::Trait(ty::TraitPredicate { trait_ref, constness: self.constness })
cdc7bbd5
XL
792 })
793 .to_predicate(tcx)
dfeec247
XL
794 }
795}
796
94222f64 797impl<'tcx> ToPredicate<'tcx> for PolyTraitPredicate<'tcx> {
f035d41b 798 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
94222f64 799 self.map_bound(PredicateKind::Trait).to_predicate(tcx)
e9174d1e
SL
800 }
801}
802
9e0c209e 803impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
f035d41b 804 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
5869c6ff 805 self.map_bound(PredicateKind::RegionOutlives).to_predicate(tcx)
e9174d1e
SL
806 }
807}
808
809impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
f035d41b 810 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
5869c6ff 811 self.map_bound(PredicateKind::TypeOutlives).to_predicate(tcx)
e9174d1e
SL
812 }
813}
814
815impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
f035d41b 816 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
5869c6ff 817 self.map_bound(PredicateKind::Projection).to_predicate(tcx)
e9174d1e
SL
818 }
819}
820
821impl<'tcx> Predicate<'tcx> {
fc512014 822 pub fn to_opt_poly_trait_ref(self) -> Option<ConstnessAnd<PolyTraitRef<'tcx>>> {
5869c6ff 823 let predicate = self.kind();
fc512014 824 match predicate.skip_binder() {
94222f64
XL
825 PredicateKind::Trait(t) => {
826 Some(ConstnessAnd { constness: t.constness, value: predicate.rebind(t.trait_ref) })
fc512014 827 }
5869c6ff
XL
828 PredicateKind::Projection(..)
829 | PredicateKind::Subtype(..)
94222f64 830 | PredicateKind::Coerce(..)
5869c6ff
XL
831 | PredicateKind::RegionOutlives(..)
832 | PredicateKind::WellFormed(..)
833 | PredicateKind::ObjectSafe(..)
834 | PredicateKind::ClosureKind(..)
835 | PredicateKind::TypeOutlives(..)
836 | PredicateKind::ConstEvaluatable(..)
837 | PredicateKind::ConstEquate(..)
838 | PredicateKind::TypeWellFormedFromEnv(..) => None,
e9174d1e
SL
839 }
840 }
abe05a73 841
f9f354fc 842 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
5869c6ff 843 let predicate = self.kind();
fc512014 844 match predicate.skip_binder() {
5869c6ff
XL
845 PredicateKind::TypeOutlives(data) => Some(predicate.rebind(data)),
846 PredicateKind::Trait(..)
847 | PredicateKind::Projection(..)
848 | PredicateKind::Subtype(..)
94222f64 849 | PredicateKind::Coerce(..)
5869c6ff
XL
850 | PredicateKind::RegionOutlives(..)
851 | PredicateKind::WellFormed(..)
852 | PredicateKind::ObjectSafe(..)
853 | PredicateKind::ClosureKind(..)
854 | PredicateKind::ConstEvaluatable(..)
855 | PredicateKind::ConstEquate(..)
856 | PredicateKind::TypeWellFormedFromEnv(..) => None,
abe05a73
XL
857 }
858 }
e9174d1e
SL
859}
860
861/// Represents the bounds declared on a particular set of type
9fa01778 862/// parameters. Should eventually be generalized into a flag list of
94222f64 863/// where-clauses. You can obtain an `InstantiatedPredicates` list from a
e9174d1e
SL
864/// `GenericPredicates` by using the `instantiate` method. Note that this method
865/// reflects an important semantic invariant of `InstantiatedPredicates`: while
866/// the `GenericPredicates` are expressed in terms of the bound type
867/// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
868/// represented a set of bounds for some particular instantiation,
869/// meaning that the generic parameters have been substituted with
870/// their values.
871///
872/// Example:
873///
dc9dc135 874/// struct Foo<T, U: Bar<T>> { ... }
e9174d1e
SL
875///
876/// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
9fa01778 877/// `[[], [U:Bar<T>]]`. Now if there were some particular reference
e9174d1e
SL
878/// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
879/// [usize:Bar<isize>]]`.
60c5eb7d 880#[derive(Clone, Debug, TypeFoldable)]
e9174d1e 881pub struct InstantiatedPredicates<'tcx> {
9e0c209e 882 pub predicates: Vec<Predicate<'tcx>>,
74b04a01 883 pub spans: Vec<Span>,
e9174d1e
SL
884}
885
886impl<'tcx> InstantiatedPredicates<'tcx> {
887 pub fn empty() -> InstantiatedPredicates<'tcx> {
74b04a01 888 InstantiatedPredicates { predicates: vec![], spans: vec![] }
e9174d1e
SL
889 }
890
891 pub fn is_empty(&self) -> bool {
892 self.predicates.is_empty()
893 }
894}
895
136023e0 896#[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable, TypeFoldable)]
17df50a5
XL
897pub struct OpaqueTypeKey<'tcx> {
898 pub def_id: DefId,
899 pub substs: SubstsRef<'tcx>,
900}
901
e74abb32 902rustc_index::newtype_index! {
532ac7d7
XL
903 /// "Universes" are used during type- and trait-checking in the
904 /// presence of `for<..>` binders to control what sets of names are
905 /// visible. Universes are arranged into a tree: the root universe
906 /// contains names that are always visible. Each child then adds a new
907 /// set of names that are visible, in addition to those of its parent.
908 /// We say that the child universe "extends" the parent universe with
909 /// new names.
910 ///
911 /// To make this more concrete, consider this program:
912 ///
913 /// ```
914 /// struct Foo { }
915 /// fn bar<T>(x: T) {
916 /// let y: for<'a> fn(&'a u8, Foo) = ...;
917 /// }
918 /// ```
919 ///
920 /// The struct name `Foo` is in the root universe U0. But the type
921 /// parameter `T`, introduced on `bar`, is in an extended universe U1
922 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
923 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
924 /// region `'a` is in a universe U2 that extends U1, because we can
925 /// name it inside the fn type but not outside.
926 ///
927 /// Universes are used to do type- and trait-checking around these
928 /// "forall" binders (also called **universal quantification**). The
929 /// idea is that when, in the body of `bar`, we refer to `T` as a
930 /// type, we aren't referring to any type in particular, but rather a
931 /// kind of "fresh" type that is distinct from all other types we have
932 /// actually declared. This is called a **placeholder** type, and we
933 /// use universes to talk about this. In other words, a type name in
934 /// universe 0 always corresponds to some "ground" type that the user
935 /// declared, but a type name in a non-zero universe is a placeholder
936 /// type -- an idealized representative of "types in general" that we
937 /// use for checking generic functions.
0bf4aa26 938 pub struct UniverseIndex {
60c5eb7d 939 derive [HashStable]
0bf4aa26
XL
940 DEBUG_FORMAT = "U{}",
941 }
942}
0531ce1d 943
0bf4aa26 944impl UniverseIndex {
ba9703b0 945 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
8faf50e0 946
0bf4aa26
XL
947 /// Returns the "next" universe index in order -- this new index
948 /// is considered to extend all previous universes. This
9fa01778 949 /// corresponds to entering a `forall` quantifier. So, for
0bf4aa26 950 /// example, suppose we have this type in universe `U`:
0531ce1d
XL
951 ///
952 /// ```
953 /// for<'a> fn(&'a u32)
954 /// ```
955 ///
956 /// Once we "enter" into this `for<'a>` quantifier, we are in a
0bf4aa26
XL
957 /// new universe that extends `U` -- in this new universe, we can
958 /// name the region `'a`, but that region was not nameable from
959 /// `U` because it was not in scope there.
960 pub fn next_universe(self) -> UniverseIndex {
961 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
8faf50e0
XL
962 }
963
a1dfa0c6 964 /// Returns `true` if `self` can name a name from `other` -- in other words,
0bf4aa26 965 /// if the set of names in `self` is a superset of those in
a1dfa0c6 966 /// `other` (`self >= other`).
0bf4aa26
XL
967 pub fn can_name(self, other: UniverseIndex) -> bool {
968 self.private >= other.private
83c7162d 969 }
a1dfa0c6
XL
970
971 /// Returns `true` if `self` cannot name some names from `other` -- in other
972 /// words, if the set of names in `self` is a strict subset of
973 /// those in `other` (`self < other`).
974 pub fn cannot_name(self, other: UniverseIndex) -> bool {
975 self.private < other.private
976 }
83c7162d
XL
977}
978
fc512014
XL
979/// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
980/// identified by both a universe, as well as a name residing within that universe. Distinct bound
981/// regions/types/consts within the same universe simply have an unknown relationship to one
0bf4aa26 982/// another.
3dfed10e 983#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
a1dfa0c6 984pub struct Placeholder<T> {
0bf4aa26 985 pub universe: UniverseIndex,
a1dfa0c6 986 pub name: T,
0531ce1d
XL
987}
988
dc9dc135
XL
989impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
990where
991 T: HashStable<StableHashingContext<'a>>,
a1dfa0c6 992{
e74abb32 993 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
a1dfa0c6
XL
994 self.universe.hash_stable(hcx, hasher);
995 self.name.hash_stable(hcx, hasher);
996 }
997}
998
fc512014 999pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
a1dfa0c6
XL
1000
1001pub type PlaceholderType = Placeholder<BoundVar>;
1002
fc512014
XL
1003#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1004#[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1005pub struct BoundConst<'tcx> {
1006 pub var: BoundVar,
1007 pub ty: Ty<'tcx>,
1008}
1009
1010pub type PlaceholderConst<'tcx> = Placeholder<BoundConst<'tcx>>;
48663c56 1011
fc512014
XL
1012/// A `DefId` which, in case it is a const argument, is potentially bundled with
1013/// the `DefId` of the generic parameter it instantiates.
3dfed10e 1014///
fc512014
XL
1015/// This is used to avoid calls to `type_of` for const arguments during typeck
1016/// which cause cycle errors.
3dfed10e
XL
1017///
1018/// ```rust
3dfed10e
XL
1019/// struct A;
1020/// impl A {
fc512014
XL
1021/// fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1022/// // ^ const parameter
3dfed10e
XL
1023/// }
1024/// struct B;
1025/// impl B {
fc512014
XL
1026/// fn foo<const M: u8>(&self) -> usize { 42 }
1027/// // ^ const parameter
3dfed10e
XL
1028/// }
1029///
1030/// fn main() {
1031/// let a = A;
fc512014
XL
1032/// let _b = a.foo::<{ 3 + 7 }>();
1033/// // ^^^^^^^^^ const argument
3dfed10e
XL
1034/// }
1035/// ```
fc512014
XL
1036///
1037/// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1038/// which `foo` is used until we know the type of `a`.
1039///
1040/// We only know the type of `a` once we are inside of `typeck(main)`.
1041/// We also end up normalizing the type of `_b` during `typeck(main)` which
1042/// requires us to evaluate the const argument.
1043///
1044/// To evaluate that const argument we need to know its type,
1045/// which we would get using `type_of(const_arg)`. This requires us to
1046/// resolve `foo` as it can be either `usize` or `u8` in this example.
1047/// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1048/// which results in a cycle.
1049///
1050/// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1051///
1052/// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1053/// already resolved `foo` so we know which const parameter this argument instantiates.
1054/// This means that we also know the expected result of `type_of(const_arg)` even if we
1055/// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1056/// trivial to compute.
1057///
1058/// If we now want to use that constant in a place which potentionally needs its type
1059/// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1060/// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1061/// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1062/// to get the type of `did`.
3dfed10e
XL
1063#[derive(Copy, Clone, Debug, TypeFoldable, Lift, TyEncodable, TyDecodable)]
1064#[derive(PartialEq, Eq, PartialOrd, Ord)]
1065#[derive(Hash, HashStable)]
1066pub struct WithOptConstParam<T> {
1067 pub did: T,
29967ef6 1068 /// The `DefId` of the corresponding generic parameter in case `did` is
3dfed10e
XL
1069 /// a const argument.
1070 ///
1071 /// Note that even if `did` is a const argument, this may still be `None`.
1072 /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
fc512014 1073 /// to potentially update `param_did` in the case it is `None`.
3dfed10e
XL
1074 pub const_param_did: Option<DefId>,
1075}
1076
1077impl<T> WithOptConstParam<T> {
1078 /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1079 #[inline(always)]
1080 pub fn unknown(did: T) -> WithOptConstParam<T> {
1081 WithOptConstParam { did, const_param_did: None }
1082 }
1083}
1084
1085impl WithOptConstParam<LocalDefId> {
1086 /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1087 /// `None` otherwise.
1088 #[inline(always)]
1089 pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1090 tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1091 }
1092
1093 /// In case `self` is unknown but `self.did` is a const argument, this returns
1094 /// a `WithOptConstParam` with the correct `const_param_did`.
1095 #[inline(always)]
1096 pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1097 if self.const_param_did.is_none() {
1098 if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1099 return Some(WithOptConstParam { did: self.did, const_param_did });
1100 }
1101 }
1102
1103 None
1104 }
1105
1106 pub fn to_global(self) -> WithOptConstParam<DefId> {
1107 WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1108 }
1109
1110 pub fn def_id_for_type_of(self) -> DefId {
1111 if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1112 }
1113}
1114
1115impl WithOptConstParam<DefId> {
1116 pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1117 self.did
1118 .as_local()
1119 .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1120 }
1121
1122 pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1123 if let Some(param_did) = self.const_param_did {
1124 if let Some(did) = self.did.as_local() {
1125 return Some((did, param_did));
1126 }
1127 }
1128
1129 None
1130 }
1131
3dfed10e
XL
1132 pub fn is_local(self) -> bool {
1133 self.did.is_local()
1134 }
1135
1136 pub fn def_id_for_type_of(self) -> DefId {
1137 self.const_param_did.unwrap_or(self.did)
1138 }
1139}
1140
7cac9316
XL
1141/// When type checking, we use the `ParamEnv` to track
1142/// details about the set of where-clauses that are in scope at this
1143/// particular point.
3dfed10e 1144#[derive(Copy, Clone, Hash, PartialEq, Eq)]
7cac9316 1145pub struct ParamEnv<'tcx> {
3dfed10e
XL
1146 /// This packs both caller bounds and the reveal enum into one pointer.
1147 ///
1148 /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1149 /// basically the set of bounds on the in-scope type parameters, translated
416331ca 1150 /// into `Obligation`s, and elaborated and normalized.
f035d41b 1151 ///
3dfed10e
XL
1152 /// Use the `caller_bounds()` method to access.
1153 ///
94b46f34 1154 /// Typically, this is `Reveal::UserFacing`, but during codegen we
f035d41b
XL
1155 /// want `Reveal::All`.
1156 ///
3dfed10e
XL
1157 /// Note: This is packed, use the reveal() method to access it.
1158 packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, traits::Reveal, true>,
7cac9316
XL
1159}
1160
3dfed10e
XL
1161unsafe impl rustc_data_structures::tagged_ptr::Tag for traits::Reveal {
1162 const BITS: usize = 1;
17df50a5 1163 #[inline]
3dfed10e
XL
1164 fn into_usize(self) -> usize {
1165 match self {
1166 traits::Reveal::UserFacing => 0,
1167 traits::Reveal::All => 1,
1168 }
1169 }
17df50a5 1170 #[inline]
3dfed10e
XL
1171 unsafe fn from_usize(ptr: usize) -> Self {
1172 match ptr {
1173 0 => traits::Reveal::UserFacing,
1174 1 => traits::Reveal::All,
1175 _ => std::hint::unreachable_unchecked(),
1176 }
1177 }
1178}
1179
f035d41b
XL
1180impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1182 f.debug_struct("ParamEnv")
1183 .field("caller_bounds", &self.caller_bounds())
1184 .field("reveal", &self.reveal())
f035d41b
XL
1185 .finish()
1186 }
1187}
1188
f035d41b
XL
1189impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1190 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1191 self.caller_bounds().hash_stable(hcx, hasher);
1192 self.reveal().hash_stable(hcx, hasher);
f035d41b
XL
1193 }
1194}
1195
1196impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
fc512014 1197 fn super_fold_with<F: ty::fold::TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
1b1a35ee 1198 ParamEnv::new(self.caller_bounds().fold_with(folder), self.reveal().fold_with(folder))
f035d41b
XL
1199 }
1200
fc512014 1201 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
29967ef6
XL
1202 self.caller_bounds().visit_with(visitor)?;
1203 self.reveal().visit_with(visitor)
f035d41b
XL
1204 }
1205}
1206
7cac9316 1207impl<'tcx> ParamEnv<'tcx> {
0531ce1d 1208 /// Construct a trait environment suitable for contexts where
9fa01778 1209 /// there are no where-clauses in scope. Hidden types (like `impl
0531ce1d
XL
1210 /// Trait`) are left hidden, so this is suitable for ordinary
1211 /// type-checking.
a1dfa0c6 1212 #[inline]
0531ce1d 1213 pub fn empty() -> Self {
1b1a35ee 1214 Self::new(List::empty(), Reveal::UserFacing)
0531ce1d
XL
1215 }
1216
f035d41b 1217 #[inline]
3dfed10e
XL
1218 pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1219 self.packed.pointer()
f035d41b
XL
1220 }
1221
1222 #[inline]
1223 pub fn reveal(self) -> traits::Reveal {
3dfed10e 1224 self.packed.tag()
f035d41b
XL
1225 }
1226
9fa01778 1227 /// Construct a trait environment with no where-clauses in scope
0531ce1d
XL
1228 /// where the values of all `impl Trait` and other hidden types
1229 /// are revealed. This is suitable for monomorphized, post-typeck
94b46f34 1230 /// environments like codegen or doing optimizations.
0531ce1d 1231 ///
9fa01778 1232 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
0531ce1d 1233 /// or invoke `param_env.with_reveal_all()`.
a1dfa0c6 1234 #[inline]
0531ce1d 1235 pub fn reveal_all() -> Self {
1b1a35ee 1236 Self::new(List::empty(), Reveal::All)
0531ce1d
XL
1237 }
1238
1239 /// Construct a trait environment with the given set of predicates.
a1dfa0c6 1240 #[inline]
1b1a35ee
XL
1241 pub fn new(caller_bounds: &'tcx List<Predicate<'tcx>>, reveal: Reveal) -> Self {
1242 ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, reveal) }
f035d41b
XL
1243 }
1244
1245 pub fn with_user_facing(mut self) -> Self {
3dfed10e 1246 self.packed.set_tag(Reveal::UserFacing);
f035d41b 1247 self
0531ce1d
XL
1248 }
1249
1250 /// Returns a new parameter environment with the same clauses, but
1251 /// which "reveals" the true results of projections in all cases
9fa01778 1252 /// (even for associated types that are specializable). This is
94b46f34 1253 /// the desired behavior during codegen and certain other special
0531ce1d
XL
1254 /// contexts; normally though we want to use `Reveal::UserFacing`,
1255 /// which is the default.
3dfed10e
XL
1256 /// All opaque types in the caller_bounds of the `ParamEnv`
1257 /// will be normalized to their underlying types.
1258 /// See PR #65989 and issue #65918 for more details
1259 pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1260 if self.packed.tag() == traits::Reveal::All {
1261 return self;
1262 }
1263
1b1a35ee 1264 ParamEnv::new(tcx.normalize_opaque_types(self.caller_bounds()), Reveal::All)
0531ce1d
XL
1265 }
1266
1267 /// Returns this same environment but with no caller bounds.
17df50a5 1268 #[inline]
0531ce1d 1269 pub fn without_caller_bounds(self) -> Self {
1b1a35ee 1270 Self::new(List::empty(), self.reveal())
0531ce1d
XL
1271 }
1272
7cac9316 1273 /// Creates a suitable environment in which to perform trait
0531ce1d
XL
1274 /// queries on the given value. When type-checking, this is simply
1275 /// the pair of the environment plus value. But when reveal is set to
1276 /// All, then if `value` does not reference any type parameters, we will
1277 /// pair it with the empty environment. This improves caching and is generally
1278 /// invisible.
e9174d1e 1279 ///
0731742a 1280 /// N.B., we preserve the environment when type-checking because it
0531ce1d 1281 /// is possible for the user to have wacky where-clauses like
7cac9316 1282 /// `where Box<u32>: Copy`, which are clearly never
0531ce1d
XL
1283 /// satisfiable. We generally want to behave as if they were true,
1284 /// although the surrounding function is never reachable.
7cac9316 1285 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
f035d41b 1286 match self.reveal() {
dfeec247 1287 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
0531ce1d
XL
1288
1289 Reveal::All => {
94222f64 1290 if value.is_known_global() {
dfeec247 1291 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
74b04a01
XL
1292 } else {
1293 ParamEnvAnd { param_env: self, value }
0531ce1d 1294 }
e9174d1e
SL
1295 }
1296 }
1297 }
1298}
1299
fc512014 1300#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
dfeec247 1301pub struct ConstnessAnd<T> {
94222f64 1302 pub constness: BoundConstness,
dfeec247
XL
1303 pub value: T,
1304}
1305
f9f354fc 1306// FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
dfeec247
XL
1307// the constness of trait bounds is being propagated correctly.
1308pub trait WithConstness: Sized {
1309 #[inline]
94222f64 1310 fn with_constness(self, constness: BoundConstness) -> ConstnessAnd<Self> {
dfeec247
XL
1311 ConstnessAnd { constness, value: self }
1312 }
1313
1314 #[inline]
94222f64
XL
1315 fn with_const_if_const(self) -> ConstnessAnd<Self> {
1316 self.with_constness(BoundConstness::ConstIfConst)
dfeec247
XL
1317 }
1318
1319 #[inline]
1320 fn without_const(self) -> ConstnessAnd<Self> {
94222f64 1321 self.with_constness(BoundConstness::NotConst)
dfeec247
XL
1322 }
1323}
1324
1325impl<T> WithConstness for T {}
1326
60c5eb7d 1327#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
7cac9316
XL
1328pub struct ParamEnvAnd<'tcx, T> {
1329 pub param_env: ParamEnv<'tcx>,
1330 pub value: T,
1331}
1332
1333impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1334 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1335 (self.param_env, self.value)
1336 }
1337}
1338
dc9dc135
XL
1339impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1340where
1341 T: HashStable<StableHashingContext<'a>>,
ea8adc8c 1342{
e74abb32 1343 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
dfeec247 1344 let ParamEnvAnd { ref param_env, ref value } = *self;
ea8adc8c
XL
1345
1346 param_env.hash_stable(hcx, hasher);
1347 value.hash_stable(hcx, hasher);
1348 }
1349}
1350
532ac7d7 1351#[derive(Copy, Clone, Debug, HashStable)]
8bb4bdeb 1352pub struct Destructor {
9fa01778 1353 /// The `DefId` of the destructor method
8bb4bdeb 1354 pub did: DefId,
c295e0f8
XL
1355 /// The constness of the destructor method
1356 pub constness: hir::Constness,
8bb4bdeb
XL
1357}
1358
b7449926 1359bitflags! {
532ac7d7 1360 #[derive(HashStable)]
b7449926
XL
1361 pub struct VariantFlags: u32 {
1362 const NO_VARIANT_FLAGS = 0;
1363 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1364 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1b1a35ee
XL
1365 /// Indicates whether this variant was obtained as part of recovering from
1366 /// a syntactic error. May be incomplete or bogus.
1367 const IS_RECOVERED = 1 << 1;
e9174d1e
SL
1368 }
1369}
1370
94222f64 1371/// Definition of a variant -- a struct's fields or an enum variant.
60c5eb7d 1372#[derive(Debug, HashStable)]
476ff2be 1373pub struct VariantDef {
532ac7d7
XL
1374 /// `DefId` that identifies the variant itself.
1375 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1376 pub def_id: DefId,
1377 /// `DefId` that identifies the variant's constructor.
1378 /// If this variant is a struct variant, then this is `None`.
1379 pub ctor_def_id: Option<DefId>,
1380 /// Variant or struct name.
60c5eb7d 1381 #[stable_hasher(project(name))]
532ac7d7
XL
1382 pub ident: Ident,
1383 /// Discriminant of this variant.
8bb4bdeb 1384 pub discr: VariantDiscr,
532ac7d7 1385 /// Fields of this variant.
476ff2be 1386 pub fields: Vec<FieldDef>,
532ac7d7 1387 /// Type of constructor of variant.
c30ab7b3 1388 pub ctor_kind: CtorKind,
532ac7d7 1389 /// Flags of the variant (e.g. is field list non-exhaustive)?
b7449926 1390 flags: VariantFlags,
e9174d1e
SL
1391}
1392
1b1a35ee 1393impl VariantDef {
9fa01778 1394 /// Creates a new `VariantDef`.
b7449926 1395 ///
532ac7d7
XL
1396 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1397 /// represents an enum variant).
1398 ///
1399 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1400 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
0bf4aa26 1401 ///
532ac7d7
XL
1402 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1403 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1404 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1405 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
0bf4aa26
XL
1406 /// built-in trait), and we do not want to load attributes twice.
1407 ///
1408 /// If someone speeds up attribute loading to not be a performance concern, they can
9fa01778 1409 /// remove this hack and use the constructor `DefId` everywhere.
532ac7d7 1410 pub fn new(
532ac7d7
XL
1411 ident: Ident,
1412 variant_did: Option<DefId>,
1413 ctor_def_id: Option<DefId>,
1414 discr: VariantDiscr,
1415 fields: Vec<FieldDef>,
1416 ctor_kind: CtorKind,
1417 adt_kind: AdtKind,
1418 parent_did: DefId,
1419 recovered: bool,
3dfed10e 1420 is_field_list_non_exhaustive: bool,
532ac7d7
XL
1421 ) -> Self {
1422 debug!(
1423 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1424 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
dfeec247 1425 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
532ac7d7
XL
1426 );
1427
b7449926 1428 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
3dfed10e
XL
1429 if is_field_list_non_exhaustive {
1430 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
b7449926 1431 }
532ac7d7 1432
1b1a35ee
XL
1433 if recovered {
1434 flags |= VariantFlags::IS_RECOVERED;
1435 }
1436
b7449926 1437 VariantDef {
532ac7d7
XL
1438 def_id: variant_did.unwrap_or(parent_did),
1439 ctor_def_id,
0731742a 1440 ident,
b7449926
XL
1441 discr,
1442 fields,
1443 ctor_kind,
532ac7d7 1444 flags,
b7449926
XL
1445 }
1446 }
1447
532ac7d7 1448 /// Is this field list non-exhaustive?
b7449926
XL
1449 #[inline]
1450 pub fn is_field_list_non_exhaustive(&self) -> bool {
1451 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1452 }
f035d41b 1453
1b1a35ee
XL
1454 /// Was this variant obtained as part of recovering from a syntactic error?
1455 #[inline]
1456 pub fn is_recovered(&self) -> bool {
1457 self.flags.intersects(VariantFlags::IS_RECOVERED)
f035d41b 1458 }
b7449926
XL
1459}
1460
3dfed10e 1461#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
8bb4bdeb 1462pub enum VariantDiscr {
0731742a 1463 /// Explicit value for this variant, i.e., `X = 123`.
8bb4bdeb
XL
1464 /// The `DefId` corresponds to the embedded constant.
1465 Explicit(DefId),
1466
1467 /// The previous variant's discriminant plus one.
1468 /// For efficiency reasons, the distance from the
1469 /// last `Explicit` discriminant is being stored,
1470 /// or `0` for the first variant, if it has none.
a1dfa0c6 1471 Relative(u32),
8bb4bdeb
XL
1472}
1473
532ac7d7 1474#[derive(Debug, HashStable)]
476ff2be 1475pub struct FieldDef {
e9174d1e 1476 pub did: DefId,
532ac7d7 1477 #[stable_hasher(project(name))]
94b46f34 1478 pub ident: Ident,
54a0048b 1479 pub vis: Visibility,
e9174d1e
SL
1480}
1481
cc61c64b 1482bitflags! {
3dfed10e 1483 #[derive(TyEncodable, TyDecodable, Default, HashStable)]
ea8adc8c
XL
1484 pub struct ReprFlags: u8 {
1485 const IS_C = 1 << 0;
83c7162d
XL
1486 const IS_SIMD = 1 << 1;
1487 const IS_TRANSPARENT = 1 << 2;
cc61c64b 1488 // Internal only for now. If true, don't reorder fields.
83c7162d 1489 const IS_LINEAR = 1 << 3;
74b04a01
XL
1490 // If true, don't expose any niche to type's context.
1491 const HIDE_NICHE = 1 << 4;
c295e0f8
XL
1492 // If true, the type's layout can be randomized using
1493 // the seed stored in `ReprOptions.layout_seed`
1494 const RANDOMIZE_LAYOUT = 1 << 5;
cc61c64b
XL
1495 // Any of these flags being set prevent field reordering optimisation.
1496 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
cc61c64b 1497 ReprFlags::IS_SIMD.bits |
ea8adc8c 1498 ReprFlags::IS_LINEAR.bits;
cc61c64b
XL
1499 }
1500}
1501
8bb4bdeb 1502/// Represents the repr options provided by the user,
3dfed10e 1503#[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Default, HashStable)]
8bb4bdeb 1504pub struct ReprOptions {
8bb4bdeb 1505 pub int: Option<attr::IntType>,
e1599b0c
XL
1506 pub align: Option<Align>,
1507 pub pack: Option<Align>,
cc61c64b 1508 pub flags: ReprFlags,
c295e0f8
XL
1509 /// The seed to be used for randomizing a type's layout
1510 ///
1511 /// Note: This could technically be a `[u8; 16]` (a `u128`) which would
1512 /// be the "most accurate" hash as it'd encompass the item and crate
1513 /// hash without loss, but it does pay the price of being larger.
1514 /// Everything's a tradeoff, a `u64` seed should be sufficient for our
1515 /// purposes (primarily `-Z randomize-layout`)
1516 pub field_shuffle_seed: u64,
8bb4bdeb
XL
1517}
1518
1519impl ReprOptions {
dc9dc135 1520 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
cc61c64b
XL
1521 let mut flags = ReprFlags::empty();
1522 let mut size = None;
e1599b0c
XL
1523 let mut max_align: Option<Align> = None;
1524 let mut min_pack: Option<Align> = None;
c295e0f8
XL
1525
1526 // Generate a deterministically-derived seed from the item's path hash
1527 // to allow for cross-crate compilation to actually work
1528 let field_shuffle_seed = tcx.def_path_hash(did).0.to_smaller_hash();
1529
8bb4bdeb 1530 for attr in tcx.get_attrs(did).iter() {
3dfed10e 1531 for r in attr::find_repr_attrs(&tcx.sess, attr) {
cc61c64b 1532 flags.insert(match r {
2c00a5a8 1533 attr::ReprC => ReprFlags::IS_C,
83c7162d 1534 attr::ReprPacked(pack) => {
e1599b0c
XL
1535 let pack = Align::from_bytes(pack as u64).unwrap();
1536 min_pack = Some(if let Some(min_pack) = min_pack {
1537 min_pack.min(pack)
83c7162d
XL
1538 } else {
1539 pack
e1599b0c 1540 });
83c7162d 1541 ReprFlags::empty()
dfeec247 1542 }
2c00a5a8 1543 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
74b04a01 1544 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
cc61c64b
XL
1545 attr::ReprSimd => ReprFlags::IS_SIMD,
1546 attr::ReprInt(i) => {
1547 size = Some(i);
1548 ReprFlags::empty()
dfeec247 1549 }
cc61c64b 1550 attr::ReprAlign(align) => {
e1599b0c 1551 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
cc61c64b 1552 ReprFlags::empty()
dfeec247 1553 }
cc61c64b 1554 });
8bb4bdeb
XL
1555 }
1556 }
1557
c295e0f8
XL
1558 // If `-Z randomize-layout` was enabled for the type definition then we can
1559 // consider performing layout randomization
1560 if tcx.sess.opts.debugging_opts.randomize_layout {
1561 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1562 }
1563
cc61c64b 1564 // This is here instead of layout because the choice must make it into metadata.
532ac7d7 1565 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
cc61c64b
XL
1566 flags.insert(ReprFlags::IS_LINEAR);
1567 }
c295e0f8
XL
1568
1569 Self { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
8bb4bdeb
XL
1570 }
1571
cc61c64b 1572 #[inline]
dfeec247
XL
1573 pub fn simd(&self) -> bool {
1574 self.flags.contains(ReprFlags::IS_SIMD)
1575 }
c295e0f8 1576
cc61c64b 1577 #[inline]
dfeec247
XL
1578 pub fn c(&self) -> bool {
1579 self.flags.contains(ReprFlags::IS_C)
1580 }
c295e0f8 1581
cc61c64b 1582 #[inline]
dfeec247
XL
1583 pub fn packed(&self) -> bool {
1584 self.pack.is_some()
1585 }
c295e0f8 1586
cc61c64b 1587 #[inline]
dfeec247
XL
1588 pub fn transparent(&self) -> bool {
1589 self.flags.contains(ReprFlags::IS_TRANSPARENT)
1590 }
c295e0f8 1591
2c00a5a8 1592 #[inline]
dfeec247
XL
1593 pub fn linear(&self) -> bool {
1594 self.flags.contains(ReprFlags::IS_LINEAR)
1595 }
c295e0f8 1596
74b04a01
XL
1597 #[inline]
1598 pub fn hide_niche(&self) -> bool {
1599 self.flags.contains(ReprFlags::HIDE_NICHE)
1600 }
cc61c64b 1601
f9f354fc
XL
1602 /// Returns the discriminant type, given these `repr` options.
1603 /// This must only be called on enums!
8bb4bdeb 1604 pub fn discr_type(&self) -> attr::IntType {
2c00a5a8 1605 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
8bb4bdeb
XL
1606 }
1607
a1dfa0c6 1608 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
8bb4bdeb
XL
1609 /// layout" optimizations, such as representing `Foo<&T>` as a
1610 /// single pointer.
1611 pub fn inhibit_enum_layout_opt(&self) -> bool {
cc61c64b 1612 self.c() || self.int.is_some()
8bb4bdeb 1613 }
83c7162d 1614
a1dfa0c6 1615 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
9fa01778 1616 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
83c7162d 1617 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
e1599b0c
XL
1618 if let Some(pack) = self.pack {
1619 if pack.bytes() == 1 {
1620 return true;
1621 }
1622 }
c295e0f8 1623
e1599b0c 1624 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
83c7162d 1625 }
a1dfa0c6 1626
c295e0f8
XL
1627 /// Returns `true` if this type is valid for reordering and `-Z randomize-layout`
1628 /// was enabled for its declaration crate
1629 pub fn can_randomize_type_layout(&self) -> bool {
1630 !self.inhibit_struct_field_reordering_opt()
1631 && self.flags.contains(ReprFlags::RANDOMIZE_LAYOUT)
1632 }
1633
9fa01778 1634 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
a1dfa0c6
XL
1635 pub fn inhibit_union_abi_opt(&self) -> bool {
1636 self.c()
1637 }
8bb4bdeb
XL
1638}
1639
dc9dc135 1640impl<'tcx> FieldDef {
c295e0f8
XL
1641 /// Returns the type of this field. The resulting type is not normalized. The `subst` is
1642 /// typically obtained via the second field of `TyKind::AdtDef`.
dc9dc135 1643 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
7cac9316 1644 tcx.type_of(self.did).subst(tcx, subst)
e9174d1e 1645 }
e9174d1e
SL
1646}
1647
ba9703b0 1648pub type Attributes<'tcx> = &'tcx [ast::Attribute];
cc61c64b 1649
0731742a
XL
1650#[derive(Debug, PartialEq, Eq)]
1651pub enum ImplOverlapKind {
1652 /// These impls are always allowed to overlap.
dfeec247 1653 Permitted {
74b04a01 1654 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
dfeec247
XL
1655 marker: bool,
1656 },
0731742a
XL
1657 /// These impls are allowed to overlap, but that raises
1658 /// an issue #33140 future-compatibility warning.
1659 ///
1660 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
1661 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
1662 ///
1663 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
1664 /// that difference, making what reduces to the following set of impls:
1665 ///
1666 /// ```
1667 /// trait Trait {}
1668 /// impl Trait for dyn Send + Sync {}
1669 /// impl Trait for dyn Sync + Send {}
1670 /// ```
1671 ///
1672 /// Obviously, once we made these types be identical, that code causes a coherence
1673 /// error and a fairly big headache for us. However, luckily for us, the trait
1674 /// `Trait` used in this case is basically a marker trait, and therefore having
1675 /// overlapping impls for it is sound.
1676 ///
1677 /// To handle this, we basically regard the trait as a marker trait, with an additional
1678 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
1679 /// it has the following restrictions:
1680 ///
1681 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
1682 /// positive impls.
1683 /// 2. The trait-ref of both impls must be equal.
1684 /// 3. The trait-ref of both impls must be a trait object type consisting only of
1685 /// marker traits.
1686 /// 4. Neither of the impls can have any where-clauses.
1687 ///
1688 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
dfeec247 1689 Issue33140,
0731742a
XL
1690}
1691
dc9dc135 1692impl<'tcx> TyCtxt<'tcx> {
3dfed10e
XL
1693 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1694 self.typeck(self.hir().body_owner_def_id(body))
32a655c1
SL
1695 }
1696
74b04a01 1697 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
476ff2be 1698 self.associated_items(id)
74b04a01 1699 .in_definition_order()
ba9703b0 1700 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
e9174d1e
SL
1701 }
1702
29967ef6
XL
1703 fn item_name_from_hir(self, def_id: DefId) -> Option<Ident> {
1704 self.hir().get_if_local(def_id).and_then(|node| node.ident())
1705 }
1706
1707 fn item_name_from_def_id(self, def_id: DefId) -> Option<Symbol> {
1708 if def_id.index == CRATE_DEF_INDEX {
17df50a5 1709 Some(self.crate_name(def_id.krate))
29967ef6
XL
1710 } else {
1711 let def_key = self.def_key(def_id);
1712 match def_key.disambiguated_data.data {
1713 // The name of a constructor is that of its parent.
1714 rustc_hir::definitions::DefPathData::Ctor => self.item_name_from_def_id(DefId {
1715 krate: def_id.krate,
1716 index: def_key.parent.unwrap(),
1717 }),
1718 _ => def_key.disambiguated_data.data.get_opt_name(),
1719 }
1720 }
1721 }
1722
1723 /// Look up the name of an item across crates. This does not look at HIR.
1724 ///
1725 /// When possible, this function should be used for cross-crate lookups over
1726 /// [`opt_item_name`] to avoid invalidating the incremental cache. If you
1727 /// need to handle items without a name, or HIR items that will not be
1728 /// serialized cross-crate, or if you need the span of the item, use
1729 /// [`opt_item_name`] instead.
1730 ///
1731 /// [`opt_item_name`]: Self::opt_item_name
1732 pub fn item_name(self, id: DefId) -> Symbol {
1733 // Look at cross-crate items first to avoid invalidating the incremental cache
1734 // unless we have to.
1735 self.item_name_from_def_id(id).unwrap_or_else(|| {
1736 bug!("item_name: no name for {:?}", self.def_path(id));
1737 })
1738 }
1739
1740 /// Look up the name and span of an item or [`Node`].
1741 ///
1742 /// See [`item_name`][Self::item_name] for more information.
e1599b0c 1743 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
29967ef6
XL
1744 // Look at the HIR first so the span will be correct if this is a local item.
1745 self.item_name_from_hir(def_id)
1746 .or_else(|| self.item_name_from_def_id(def_id).map(Ident::with_dummy_span))
e1599b0c
XL
1747 }
1748
f9f354fc 1749 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
5869c6ff
XL
1750 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1751 Some(self.associated_item(def_id))
7cac9316 1752 } else {
5869c6ff
XL
1753 None
1754 }
e9174d1e
SL
1755 }
1756
3dfed10e
XL
1757 pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
1758 typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
83c7162d
XL
1759 }
1760
1761 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
dfeec247 1762 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
83c7162d
XL
1763 }
1764
a1dfa0c6 1765 /// Returns `true` if the impls are the same polarity and the trait either
f9f354fc 1766 /// has no items or is annotated `#[marker]` and prevents item overrides.
dfeec247
XL
1767 pub fn impls_are_allowed_to_overlap(
1768 self,
1769 def_id1: DefId,
1770 def_id2: DefId,
1771 ) -> Option<ImplOverlapKind> {
e1599b0c
XL
1772 // If either trait impl references an error, they're allowed to overlap,
1773 // as one of them essentially doesn't exist.
dfeec247
XL
1774 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
1775 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
1776 {
1777 return Some(ImplOverlapKind::Permitted { marker: false });
e1599b0c
XL
1778 }
1779
e74abb32 1780 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
dfeec247 1781 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
e74abb32 1782 // `#[rustc_reservation_impl]` impls don't overlap with anything
dfeec247
XL
1783 debug!(
1784 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
1785 def_id1, def_id2
1786 );
1787 return Some(ImplOverlapKind::Permitted { marker: false });
e74abb32 1788 }
dfeec247
XL
1789 (ImplPolarity::Positive, ImplPolarity::Negative)
1790 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
e74abb32 1791 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
dfeec247
XL
1792 debug!(
1793 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
1794 def_id1, def_id2
1795 );
e74abb32
XL
1796 return None;
1797 }
dfeec247
XL
1798 (ImplPolarity::Positive, ImplPolarity::Positive)
1799 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
e74abb32
XL
1800 };
1801
74b04a01 1802 let is_marker_overlap = {
0bf4aa26
XL
1803 let is_marker_impl = |def_id: DefId| -> bool {
1804 let trait_ref = self.impl_trait_ref(def_id);
1805 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
1806 };
e74abb32 1807 is_marker_impl(def_id1) && is_marker_impl(def_id2)
0731742a
XL
1808 };
1809
e74abb32 1810 if is_marker_overlap {
dfeec247
XL
1811 debug!(
1812 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
1813 def_id1, def_id2
1814 );
1815 Some(ImplOverlapKind::Permitted { marker: true })
0bf4aa26 1816 } else {
0731742a
XL
1817 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
1818 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
1819 if self_ty1 == self_ty2 {
dfeec247
XL
1820 debug!(
1821 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
1822 def_id1, def_id2
1823 );
0731742a
XL
1824 return Some(ImplOverlapKind::Issue33140);
1825 } else {
dfeec247
XL
1826 debug!(
1827 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
1828 def_id1, def_id2, self_ty1, self_ty2
1829 );
0731742a
XL
1830 }
1831 }
1832 }
1833
dfeec247 1834 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
0731742a 1835 None
cc61c64b 1836 }
cc61c64b
XL
1837 }
1838
48663c56 1839 /// Returns `ty::VariantDef` if `res` refers to a struct,
532ac7d7 1840 /// or variant or their constructors, panics otherwise.
48663c56
XL
1841 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1842 match res {
1843 Res::Def(DefKind::Variant, did) => {
532ac7d7 1844 let enum_did = self.parent(did).unwrap();
7cac9316 1845 self.adt_def(enum_did).variant_with_id(did)
5bcae85e 1846 }
ba9703b0 1847 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
48663c56 1848 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
532ac7d7
XL
1849 let variant_did = self.parent(variant_ctor_did).unwrap();
1850 let enum_did = self.parent(variant_did).unwrap();
1851 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1852 }
48663c56 1853 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
532ac7d7
XL
1854 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
1855 self.adt_def(struct_did).non_enum_variant()
c30ab7b3 1856 }
dfeec247 1857 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
5bcae85e
SL
1858 }
1859 }
1860
9fa01778 1861 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
f9f354fc 1862 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
cc61c64b 1863 match instance {
5869c6ff
XL
1864 ty::InstanceDef::Item(def) => match self.def_kind(def.did) {
1865 DefKind::Const
1866 | DefKind::Static
1867 | DefKind::AssocConst
1868 | DefKind::Ctor(..)
1869 | DefKind::AnonConst => self.mir_for_ctfe_opt_const_arg(def),
1870 // If the caller wants `mir_for_ctfe` of a function they should not be using
1871 // `instance_mir`, so we'll assume const fn also wants the optimized version.
6a06907d
XL
1872 _ => {
1873 assert_eq!(def.const_param_did, None);
1874 self.optimized_mir(def.did)
1875 }
5869c6ff 1876 },
dfeec247
XL
1877 ty::InstanceDef::VtableShim(..)
1878 | ty::InstanceDef::ReifyShim(..)
1879 | ty::InstanceDef::Intrinsic(..)
1880 | ty::InstanceDef::FnPtrShim(..)
1881 | ty::InstanceDef::Virtual(..)
1882 | ty::InstanceDef::ClosureOnceShim { .. }
1883 | ty::InstanceDef::DropGlue(..)
f9f354fc 1884 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
cc61c64b
XL
1885 }
1886 }
1887
9fa01778 1888 /// Gets the attributes of a definition.
dc9dc135 1889 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
f9f354fc 1890 if let Some(did) = did.as_local() {
3dfed10e 1891 self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
e9174d1e 1892 } else {
ba9703b0 1893 self.item_attrs(did)
e9174d1e
SL
1894 }
1895 }
1896
9fa01778 1897 /// Determines whether an item is annotated with an attribute.
48663c56 1898 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
3dfed10e 1899 self.sess.contains_name(&self.get_attrs(did), attr)
e9174d1e
SL
1900 }
1901
c295e0f8
XL
1902 /// Determines whether an item is annotated with `doc(hidden)`.
1903 pub fn is_doc_hidden(self, did: DefId) -> bool {
1904 self.get_attrs(did)
1905 .iter()
1906 .filter_map(|attr| if attr.has_name(sym::doc) { attr.meta_item_list() } else { None })
1907 .any(|items| items.iter().any(|item| item.has_name(sym::hidden)))
1908 }
1909
a1dfa0c6 1910 /// Returns `true` if this is an `auto trait`.
abe05a73
XL
1911 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1912 self.trait_def(trait_def_id).has_auto_impl
b039eaaf
SL
1913 }
1914
5869c6ff
XL
1915 /// Returns layout of a generator. Layout might be unavailable if the
1916 /// generator is tainted by errors.
1917 pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
6a06907d 1918 self.optimized_mir(def_id).generator_layout()
ea8adc8c
XL
1919 }
1920
9fa01778
XL
1921 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
1922 /// If it implements no trait, returns `None`.
a7813a04 1923 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
e9174d1e
SL
1924 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
1925 }
1926
9fa01778
XL
1927 /// If the given defid describes a method belonging to an impl, returns the
1928 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
a7813a04 1929 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
ba9703b0 1930 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
dfeec247
XL
1931 TraitContainer(_) => None,
1932 ImplContainer(def_id) => Some(def_id),
1933 })
e9174d1e
SL
1934 }
1935
54a0048b
SL
1936 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
1937 /// with the name of the crate containing the impl.
476ff2be 1938 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
f9f354fc 1939 if let Some(impl_did) = impl_did.as_local() {
3dfed10e 1940 let hir_id = self.hir().local_def_id_to_hir_id(impl_did);
dc9dc135 1941 Ok(self.hir().span(hir_id))
54a0048b 1942 } else {
ea8adc8c 1943 Err(self.crate_name(impl_did.krate))
54a0048b
SL
1944 }
1945 }
7cac9316 1946
9fa01778
XL
1947 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
1948 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
1949 /// definition's parent/scope to perform comparison.
8faf50e0 1950 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
dc9dc135
XL
1951 // We could use `Ident::eq` here, but we deliberately don't. The name
1952 // comparison fails frequently, and we want to avoid the expensive
ba9703b0 1953 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
dfeec247
XL
1954 use_name.name == def_name.name
1955 && use_name
1956 .span
1957 .ctxt()
17df50a5 1958 .hygienic_eq(def_name.span.ctxt(), self.expn_that_defined(def_parent_def_id))
dc9dc135
XL
1959 }
1960
1961 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
17df50a5 1962 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
dc9dc135
XL
1963 ident
1964 }
1965
dfeec247
XL
1966 pub fn adjust_ident_and_get_scope(
1967 self,
1968 mut ident: Ident,
1969 scope: DefId,
1970 block: hir::HirId,
1971 ) -> (Ident, DefId) {
136023e0
XL
1972 let scope = ident
1973 .span
1974 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
1975 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
1976 .unwrap_or_else(|| self.parent_module(block).to_def_id());
7cac9316
XL
1977 (ident, scope)
1978 }
a1dfa0c6 1979
74b04a01
XL
1980 pub fn is_object_safe(self, key: DefId) -> bool {
1981 self.object_safety_violations(key).is_empty()
a1dfa0c6
XL
1982 }
1983}
1984
a1dfa0c6 1985/// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
dc9dc135 1986pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
f9f354fc 1987 if let Some(def_id) = def_id.as_local() {
3dfed10e 1988 if let Node::Item(item) = tcx.hir().get(tcx.hir().local_def_id_to_hir_id(def_id)) {
e74abb32 1989 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
416331ca 1990 return opaque_ty.impl_trait_fn;
8faf50e0
XL
1991 }
1992 }
1993 }
1994 None
1995}
1996
5869c6ff
XL
1997pub fn int_ty(ity: ast::IntTy) -> IntTy {
1998 match ity {
1999 ast::IntTy::Isize => IntTy::Isize,
2000 ast::IntTy::I8 => IntTy::I8,
2001 ast::IntTy::I16 => IntTy::I16,
2002 ast::IntTy::I32 => IntTy::I32,
2003 ast::IntTy::I64 => IntTy::I64,
2004 ast::IntTy::I128 => IntTy::I128,
2005 }
2006}
2007
2008pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2009 match uty {
2010 ast::UintTy::Usize => UintTy::Usize,
2011 ast::UintTy::U8 => UintTy::U8,
2012 ast::UintTy::U16 => UintTy::U16,
2013 ast::UintTy::U32 => UintTy::U32,
2014 ast::UintTy::U64 => UintTy::U64,
2015 ast::UintTy::U128 => UintTy::U128,
2016 }
2017}
2018
2019pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2020 match fty {
2021 ast::FloatTy::F32 => FloatTy::F32,
2022 ast::FloatTy::F64 => FloatTy::F64,
2023 }
2024}
2025
2026pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2027 match ity {
2028 IntTy::Isize => ast::IntTy::Isize,
2029 IntTy::I8 => ast::IntTy::I8,
2030 IntTy::I16 => ast::IntTy::I16,
2031 IntTy::I32 => ast::IntTy::I32,
2032 IntTy::I64 => ast::IntTy::I64,
2033 IntTy::I128 => ast::IntTy::I128,
2034 }
2035}
2036
2037pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2038 match uty {
2039 UintTy::Usize => ast::UintTy::Usize,
2040 UintTy::U8 => ast::UintTy::U8,
2041 UintTy::U16 => ast::UintTy::U16,
2042 UintTy::U32 => ast::UintTy::U32,
2043 UintTy::U64 => ast::UintTy::U64,
2044 UintTy::U128 => ast::UintTy::U128,
2045 }
2046}
2047
f035d41b 2048pub fn provide(providers: &mut ty::query::Providers) {
94222f64 2049 closure::provide(providers);
ea8adc8c 2050 context::provide(providers);
abe05a73 2051 erase_regions::provide(providers);
ff7c6d11 2052 layout::provide(providers);
3dfed10e 2053 util::provide(providers);
1b1a35ee 2054 print::provide(providers);
ba9703b0 2055 super::util::bug::provide(providers);
136023e0 2056 super::middle::provide(providers);
ba9703b0
XL
2057 *providers = ty::query::Providers {
2058 trait_impls_of: trait_def::trait_impls_of_provider,
5869c6ff 2059 type_uninhabited_from: inhabitedness::type_uninhabited_from,
cdc7bbd5 2060 const_param_default: consts::const_param_default,
dc3f5686 2061 vtable_allocation: vtable::vtable_allocation_provider,
ba9703b0
XL
2062 ..*providers
2063 };
cc61c64b
XL
2064}
2065
cc61c64b
XL
2066/// A map for the local crate mapping each type to a vector of its
2067/// inherent impls. This is not meant to be used outside of coherence;
2068/// rather, you should request the vector for a specific type via
7cac9316
XL
2069/// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2070/// (constructing this map requires touching the entire crate).
532ac7d7 2071#[derive(Clone, Debug, Default, HashStable)]
cc61c64b 2072pub struct CrateInherentImpls {
17df50a5 2073 pub inherent_impls: LocalDefIdMap<Vec<DefId>>,
cc61c64b
XL
2074}
2075
3dfed10e
XL
2076#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2077pub struct SymbolName<'tcx> {
2078 /// `&str` gives a consistent ordering, which ensures reproducible builds.
2079 pub name: &'tcx str,
7cac9316
XL
2080}
2081
3dfed10e
XL
2082impl<'tcx> SymbolName<'tcx> {
2083 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2084 SymbolName {
2085 name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
2086 }
e74abb32
XL
2087 }
2088}
2089
3dfed10e 2090impl<'tcx> fmt::Display for SymbolName<'tcx> {
0bf4aa26 2091 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
7cac9316
XL
2092 fmt::Display::fmt(&self.name, fmt)
2093 }
2094}
0531ce1d 2095
3dfed10e 2096impl<'tcx> fmt::Debug for SymbolName<'tcx> {
0bf4aa26 2097 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
0531ce1d
XL
2098 fmt::Display::fmt(&self.name, fmt)
2099 }
2100}
c295e0f8
XL
2101
2102#[derive(Debug, Default, Copy, Clone)]
2103pub struct FoundRelationships {
2104 /// This is true if we identified that this Ty (`?T`) is found in a `?T: Foo`
2105 /// obligation, where:
2106 ///
2107 /// * `Foo` is not `Sized`
2108 /// * `(): Foo` may be satisfied
2109 pub self_in_trait: bool,
2110 /// This is true if we identified that this Ty (`?T`) is found in a `<_ as
2111 /// _>::AssocType = ?T`
2112 pub output: bool,
2113}