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