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