]> git.proxmox.com Git - rustc.git/blob - src/librustc_middle/ty/mod.rs
New upstream version 1.46.0~beta.2+dfsg1
[rustc.git] / src / librustc_middle / ty / mod.rs
1 // ignore-tidy-filelength
2
3 pub use self::fold::{TypeFoldable, TypeVisitor};
4 pub use self::AssocItemContainer::*;
5 pub use self::BorrowKind::*;
6 pub use self::IntVarValue::*;
7 pub use self::Variance::*;
8
9 use crate::hir::exports::ExportMap;
10 use crate::ich::StableHashingContext;
11 use crate::infer::canonical::Canonical;
12 use crate::middle::cstore::CrateStoreDyn;
13 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
14 use crate::mir::interpret::ErrorHandled;
15 use crate::mir::Body;
16 use crate::mir::GeneratorLayout;
17 use crate::traits::{self, Reveal};
18 use crate::ty;
19 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
20 use crate::ty::util::{Discr, IntTypeExt};
21 use rustc_ast::ast;
22 use rustc_attr as attr;
23 use rustc_data_structures::captures::Captures;
24 use rustc_data_structures::fingerprint::Fingerprint;
25 use rustc_data_structures::fx::FxHashMap;
26 use rustc_data_structures::fx::FxHashSet;
27 use rustc_data_structures::fx::FxIndexMap;
28 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
29 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
30 use rustc_data_structures::sync::{self, par_iter, ParallelIterator};
31 use rustc_errors::ErrorReported;
32 use rustc_hir as hir;
33 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
34 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
35 use rustc_hir::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
36 use rustc_hir::{Constness, Node};
37 use rustc_index::vec::{Idx, IndexVec};
38 use rustc_macros::HashStable;
39 use rustc_serialize::{self, Encodable, Encoder};
40 use rustc_session::DataTypeKind;
41 use rustc_span::hygiene::ExpnId;
42 use rustc_span::symbol::{kw, sym, Ident, Symbol};
43 use rustc_span::Span;
44 use rustc_target::abi::{Align, VariantIdx};
45
46 use std::cell::RefCell;
47 use std::cmp::Ordering;
48 use std::fmt;
49 use std::hash::{Hash, Hasher};
50 use std::marker::PhantomData;
51 use std::ops::Range;
52 use std::ptr;
53
54 pub use self::sty::BoundRegion::*;
55 pub use self::sty::InferTy::*;
56 pub use self::sty::RegionKind;
57 pub use self::sty::RegionKind::*;
58 pub use self::sty::TyKind::*;
59 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
60 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
61 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
62 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
63 pub use self::sty::{Const, ConstKind, ExistentialProjection, PolyExistentialProjection};
64 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
65 pub use self::sty::{ExistentialPredicate, InferConst, InferTy, ParamConst, ParamTy, ProjectionTy};
66 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
67 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
68 pub use crate::ty::diagnostics::*;
69
70 pub use self::binding::BindingMode;
71 pub use self::binding::BindingMode::*;
72
73 pub use self::context::{tls, FreeRegionInfo, TyCtxt};
74 pub use self::context::{
75 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
76 UserType, UserTypeAnnotationIndex,
77 };
78 pub use self::context::{
79 CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables,
80 };
81
82 pub use self::instance::{Instance, InstanceDef};
83
84 pub use self::list::List;
85
86 pub use self::trait_def::TraitDef;
87
88 pub use self::query::queries;
89
90 pub use self::consts::ConstInt;
91
92 pub mod adjustment;
93 pub mod binding;
94 pub mod cast;
95 #[macro_use]
96 pub mod codec;
97 pub mod _match;
98 mod erase_regions;
99 pub mod error;
100 pub mod fast_reject;
101 pub mod flags;
102 pub mod fold;
103 pub mod inhabitedness;
104 pub mod layout;
105 pub mod normalize_erasing_regions;
106 pub mod outlives;
107 pub mod print;
108 pub mod query;
109 pub mod relate;
110 pub mod steal;
111 pub mod subst;
112 pub mod trait_def;
113 pub mod util;
114 pub mod walk;
115
116 mod consts;
117 mod context;
118 mod diagnostics;
119 mod instance;
120 mod list;
121 mod structural_impls;
122 mod sty;
123
124 // Data types
125
126 pub struct ResolverOutputs {
127 pub definitions: rustc_hir::definitions::Definitions,
128 pub cstore: Box<CrateStoreDyn>,
129 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
130 pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
131 pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
132 pub export_map: ExportMap<LocalDefId>,
133 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
134 /// Extern prelude entries. The value is `true` if the entry was introduced
135 /// via `extern crate` item and not `--extern` option or compiler built-in.
136 pub extern_prelude: FxHashMap<Symbol, bool>,
137 }
138
139 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
140 pub enum AssocItemContainer {
141 TraitContainer(DefId),
142 ImplContainer(DefId),
143 }
144
145 impl AssocItemContainer {
146 /// Asserts that this is the `DefId` of an associated item declared
147 /// in a trait, and returns the trait `DefId`.
148 pub fn assert_trait(&self) -> DefId {
149 match *self {
150 TraitContainer(id) => id,
151 _ => bug!("associated item has wrong container type: {:?}", self),
152 }
153 }
154
155 pub fn id(&self) -> DefId {
156 match *self {
157 TraitContainer(id) => id,
158 ImplContainer(id) => id,
159 }
160 }
161 }
162
163 /// The "header" of an impl is everything outside the body: a Self type, a trait
164 /// ref (in the case of a trait impl), and a set of predicates (from the
165 /// bounds / where-clauses).
166 #[derive(Clone, Debug, TypeFoldable)]
167 pub struct ImplHeader<'tcx> {
168 pub impl_def_id: DefId,
169 pub self_ty: Ty<'tcx>,
170 pub trait_ref: Option<TraitRef<'tcx>>,
171 pub predicates: Vec<Predicate<'tcx>>,
172 }
173
174 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
175 pub enum ImplPolarity {
176 /// `impl Trait for Type`
177 Positive,
178 /// `impl !Trait for Type`
179 Negative,
180 /// `#[rustc_reservation_impl] impl Trait for Type`
181 ///
182 /// This is a "stability hack", not a real Rust feature.
183 /// See #64631 for details.
184 Reservation,
185 }
186
187 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
188 pub struct AssocItem {
189 pub def_id: DefId,
190 #[stable_hasher(project(name))]
191 pub ident: Ident,
192 pub kind: AssocKind,
193 pub vis: Visibility,
194 pub defaultness: hir::Defaultness,
195 pub container: AssocItemContainer,
196
197 /// Whether this is a method with an explicit self
198 /// as its first parameter, allowing method calls.
199 pub fn_has_self_parameter: bool,
200 }
201
202 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
203 pub enum AssocKind {
204 Const,
205 Fn,
206 Type,
207 }
208
209 impl AssocKind {
210 pub fn namespace(&self) -> Namespace {
211 match *self {
212 ty::AssocKind::Type => Namespace::TypeNS,
213 ty::AssocKind::Const | ty::AssocKind::Fn => Namespace::ValueNS,
214 }
215 }
216
217 pub fn as_def_kind(&self) -> DefKind {
218 match self {
219 AssocKind::Const => DefKind::AssocConst,
220 AssocKind::Fn => DefKind::AssocFn,
221 AssocKind::Type => DefKind::AssocTy,
222 }
223 }
224 }
225
226 impl AssocItem {
227 pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
228 match self.kind {
229 ty::AssocKind::Fn => {
230 // We skip the binder here because the binder would deanonymize all
231 // late-bound regions, and we don't want method signatures to show up
232 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
233 // regions just fine, showing `fn(&MyType)`.
234 tcx.fn_sig(self.def_id).skip_binder().to_string()
235 }
236 ty::AssocKind::Type => format!("type {};", self.ident),
237 ty::AssocKind::Const => {
238 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
239 }
240 }
241 }
242 }
243
244 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
245 ///
246 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
247 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
248 /// done only on items with the same name.
249 #[derive(Debug, Clone, PartialEq, HashStable)]
250 pub struct AssociatedItems<'tcx> {
251 items: SortedIndexMultiMap<u32, Symbol, &'tcx ty::AssocItem>,
252 }
253
254 impl<'tcx> AssociatedItems<'tcx> {
255 /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
256 pub fn new(items_in_def_order: impl IntoIterator<Item = &'tcx ty::AssocItem>) -> Self {
257 let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
258 AssociatedItems { items }
259 }
260
261 /// Returns a slice of associated items in the order they were defined.
262 ///
263 /// New code should avoid relying on definition order. If you need a particular associated item
264 /// for a known trait, make that trait a lang item instead of indexing this array.
265 pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
266 self.items.iter().map(|(_, v)| *v)
267 }
268
269 /// Returns an iterator over all associated items with the given name, ignoring hygiene.
270 pub fn filter_by_name_unhygienic(
271 &self,
272 name: Symbol,
273 ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
274 self.items.get_by_key(&name).copied()
275 }
276
277 /// Returns an iterator over all associated items with the given name.
278 ///
279 /// Multiple items may have the same name if they are in different `Namespace`s. For example,
280 /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
281 /// methods below if you know which item you are looking for.
282 pub fn filter_by_name(
283 &'a self,
284 tcx: TyCtxt<'a>,
285 ident: Ident,
286 parent_def_id: DefId,
287 ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
288 self.filter_by_name_unhygienic(ident.name)
289 .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
290 }
291
292 /// Returns the associated item with the given name and `AssocKind`, if one exists.
293 pub fn find_by_name_and_kind(
294 &self,
295 tcx: TyCtxt<'_>,
296 ident: Ident,
297 kind: AssocKind,
298 parent_def_id: DefId,
299 ) -> Option<&ty::AssocItem> {
300 self.filter_by_name_unhygienic(ident.name)
301 .filter(|item| item.kind == kind)
302 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
303 }
304
305 /// Returns the associated item with the given name in the given `Namespace`, if one exists.
306 pub fn find_by_name_and_namespace(
307 &self,
308 tcx: TyCtxt<'_>,
309 ident: Ident,
310 ns: Namespace,
311 parent_def_id: DefId,
312 ) -> Option<&ty::AssocItem> {
313 self.filter_by_name_unhygienic(ident.name)
314 .filter(|item| item.kind.namespace() == ns)
315 .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
316 }
317 }
318
319 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable)]
320 pub enum Visibility {
321 /// Visible everywhere (including in other crates).
322 Public,
323 /// Visible only in the given crate-local module.
324 Restricted(DefId),
325 /// Not visible anywhere in the local crate. This is the visibility of private external items.
326 Invisible,
327 }
328
329 pub trait DefIdTree: Copy {
330 fn parent(self, id: DefId) -> Option<DefId>;
331
332 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
333 if descendant.krate != ancestor.krate {
334 return false;
335 }
336
337 while descendant != ancestor {
338 match self.parent(descendant) {
339 Some(parent) => descendant = parent,
340 None => return false,
341 }
342 }
343 true
344 }
345 }
346
347 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
348 fn parent(self, id: DefId) -> Option<DefId> {
349 self.def_key(id).parent.map(|index| DefId { index, ..id })
350 }
351 }
352
353 impl Visibility {
354 pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
355 match visibility.node {
356 hir::VisibilityKind::Public => Visibility::Public,
357 hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
358 hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
359 // If there is no resolution, `resolve` will have already reported an error, so
360 // assume that the visibility is public to avoid reporting more privacy errors.
361 Res::Err => Visibility::Public,
362 def => Visibility::Restricted(def.def_id()),
363 },
364 hir::VisibilityKind::Inherited => {
365 Visibility::Restricted(tcx.parent_module(id).to_def_id())
366 }
367 }
368 }
369
370 /// Returns `true` if an item with this visibility is accessible from the given block.
371 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
372 let restriction = match self {
373 // Public items are visible everywhere.
374 Visibility::Public => return true,
375 // Private items from other crates are visible nowhere.
376 Visibility::Invisible => return false,
377 // Restricted items are visible in an arbitrary local module.
378 Visibility::Restricted(other) if other.krate != module.krate => return false,
379 Visibility::Restricted(module) => module,
380 };
381
382 tree.is_descendant_of(module, restriction)
383 }
384
385 /// Returns `true` if this visibility is at least as accessible as the given visibility
386 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
387 let vis_restriction = match vis {
388 Visibility::Public => return self == Visibility::Public,
389 Visibility::Invisible => return true,
390 Visibility::Restricted(module) => module,
391 };
392
393 self.is_accessible_from(vis_restriction, tree)
394 }
395
396 // Returns `true` if this item is visible anywhere in the local crate.
397 pub fn is_visible_locally(self) -> bool {
398 match self {
399 Visibility::Public => true,
400 Visibility::Restricted(def_id) => def_id.is_local(),
401 Visibility::Invisible => false,
402 }
403 }
404 }
405
406 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
407 pub enum Variance {
408 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
409 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
410 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
411 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
412 }
413
414 /// The crate variances map is computed during typeck and contains the
415 /// variance of every item in the local crate. You should not use it
416 /// directly, because to do so will make your pass dependent on the
417 /// HIR of every item in the local crate. Instead, use
418 /// `tcx.variances_of()` to get the variance for a *particular*
419 /// item.
420 #[derive(HashStable)]
421 pub struct CrateVariancesMap<'tcx> {
422 /// For each item with generics, maps to a vector of the variance
423 /// of its generics. If an item has no generics, it will have no
424 /// entry.
425 pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
426 }
427
428 impl Variance {
429 /// `a.xform(b)` combines the variance of a context with the
430 /// variance of a type with the following meaning. If we are in a
431 /// context with variance `a`, and we encounter a type argument in
432 /// a position with variance `b`, then `a.xform(b)` is the new
433 /// variance with which the argument appears.
434 ///
435 /// Example 1:
436 ///
437 /// *mut Vec<i32>
438 ///
439 /// Here, the "ambient" variance starts as covariant. `*mut T` is
440 /// invariant with respect to `T`, so the variance in which the
441 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
442 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
443 /// respect to its type argument `T`, and hence the variance of
444 /// the `i32` here is `Invariant.xform(Covariant)`, which results
445 /// (again) in `Invariant`.
446 ///
447 /// Example 2:
448 ///
449 /// fn(*const Vec<i32>, *mut Vec<i32)
450 ///
451 /// The ambient variance is covariant. A `fn` type is
452 /// contravariant with respect to its parameters, so the variance
453 /// within which both pointer types appear is
454 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
455 /// T` is covariant with respect to `T`, so the variance within
456 /// which the first `Vec<i32>` appears is
457 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
458 /// is true for its `i32` argument. In the `*mut T` case, the
459 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
460 /// and hence the outermost type is `Invariant` with respect to
461 /// `Vec<i32>` (and its `i32` argument).
462 ///
463 /// Source: Figure 1 of "Taming the Wildcards:
464 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
465 pub fn xform(self, v: ty::Variance) -> ty::Variance {
466 match (self, v) {
467 // Figure 1, column 1.
468 (ty::Covariant, ty::Covariant) => ty::Covariant,
469 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
470 (ty::Covariant, ty::Invariant) => ty::Invariant,
471 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
472
473 // Figure 1, column 2.
474 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
475 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
476 (ty::Contravariant, ty::Invariant) => ty::Invariant,
477 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
478
479 // Figure 1, column 3.
480 (ty::Invariant, _) => ty::Invariant,
481
482 // Figure 1, column 4.
483 (ty::Bivariant, _) => ty::Bivariant,
484 }
485 }
486 }
487
488 // Contains information needed to resolve types and (in the future) look up
489 // the types of AST nodes.
490 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
491 pub struct CReaderCacheKey {
492 pub cnum: CrateNum,
493 pub pos: usize,
494 }
495
496 bitflags! {
497 /// Flags that we track on types. These flags are propagated upwards
498 /// through the type during type construction, so that we can quickly check
499 /// whether the type has various kinds of types in it without recursing
500 /// over the type itself.
501 pub struct TypeFlags: u32 {
502 // Does this have parameters? Used to determine whether substitution is
503 // required.
504 /// Does this have [Param]?
505 const HAS_TY_PARAM = 1 << 0;
506 /// Does this have [ReEarlyBound]?
507 const HAS_RE_PARAM = 1 << 1;
508 /// Does this have [ConstKind::Param]?
509 const HAS_CT_PARAM = 1 << 2;
510
511 const NEEDS_SUBST = TypeFlags::HAS_TY_PARAM.bits
512 | TypeFlags::HAS_RE_PARAM.bits
513 | TypeFlags::HAS_CT_PARAM.bits;
514
515 /// Does this have [Infer]?
516 const HAS_TY_INFER = 1 << 3;
517 /// Does this have [ReVar]?
518 const HAS_RE_INFER = 1 << 4;
519 /// Does this have [ConstKind::Infer]?
520 const HAS_CT_INFER = 1 << 5;
521
522 /// Does this have inference variables? Used to determine whether
523 /// inference is required.
524 const NEEDS_INFER = TypeFlags::HAS_TY_INFER.bits
525 | TypeFlags::HAS_RE_INFER.bits
526 | TypeFlags::HAS_CT_INFER.bits;
527
528 /// Does this have [Placeholder]?
529 const HAS_TY_PLACEHOLDER = 1 << 6;
530 /// Does this have [RePlaceholder]?
531 const HAS_RE_PLACEHOLDER = 1 << 7;
532 /// Does this have [ConstKind::Placeholder]?
533 const HAS_CT_PLACEHOLDER = 1 << 8;
534
535 /// `true` if there are "names" of regions and so forth
536 /// that are local to a particular fn/inferctxt
537 const HAS_FREE_LOCAL_REGIONS = 1 << 9;
538
539 /// `true` if there are "names" of types and regions and so forth
540 /// that are local to a particular fn
541 const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_PARAM.bits
542 | TypeFlags::HAS_CT_PARAM.bits
543 | TypeFlags::HAS_TY_INFER.bits
544 | TypeFlags::HAS_CT_INFER.bits
545 | TypeFlags::HAS_TY_PLACEHOLDER.bits
546 | TypeFlags::HAS_CT_PLACEHOLDER.bits
547 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
548
549 /// Does this have [Projection]?
550 const HAS_TY_PROJECTION = 1 << 10;
551 /// Does this have [Opaque]?
552 const HAS_TY_OPAQUE = 1 << 11;
553 /// Does this have [ConstKind::Unevaluated]?
554 const HAS_CT_PROJECTION = 1 << 12;
555
556 /// Could this type be normalized further?
557 const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
558 | TypeFlags::HAS_TY_OPAQUE.bits
559 | TypeFlags::HAS_CT_PROJECTION.bits;
560
561 /// Is an error type/const reachable?
562 const HAS_ERROR = 1 << 13;
563
564 /// Does this have any region that "appears free" in the type?
565 /// Basically anything but [ReLateBound] and [ReErased].
566 const HAS_FREE_REGIONS = 1 << 14;
567
568 /// Does this have any [ReLateBound] regions? Used to check
569 /// if a global bound is safe to evaluate.
570 const HAS_RE_LATE_BOUND = 1 << 15;
571
572 /// Does this have any [ReErased] regions?
573 const HAS_RE_ERASED = 1 << 16;
574
575 /// Does this value have parameters/placeholders/inference variables which could be
576 /// replaced later, in a way that would change the results of `impl` specialization?
577 const STILL_FURTHER_SPECIALIZABLE = 1 << 17;
578 }
579 }
580
581 #[allow(rustc::usage_of_ty_tykind)]
582 pub struct TyS<'tcx> {
583 pub kind: TyKind<'tcx>,
584 pub flags: TypeFlags,
585
586 /// This is a kind of confusing thing: it stores the smallest
587 /// binder such that
588 ///
589 /// (a) the binder itself captures nothing but
590 /// (b) all the late-bound things within the type are captured
591 /// by some sub-binder.
592 ///
593 /// So, for a type without any late-bound things, like `u32`, this
594 /// will be *innermost*, because that is the innermost binder that
595 /// captures nothing. But for a type `&'D u32`, where `'D` is a
596 /// late-bound region with De Bruijn index `D`, this would be `D + 1`
597 /// -- the binder itself does not capture `D`, but `D` is captured
598 /// by an inner binder.
599 ///
600 /// We call this concept an "exclusive" binder `D` because all
601 /// De Bruijn indices within the type are contained within `0..D`
602 /// (exclusive).
603 outer_exclusive_binder: ty::DebruijnIndex,
604 }
605
606 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
607 #[cfg(target_arch = "x86_64")]
608 static_assert_size!(TyS<'_>, 32);
609
610 impl<'tcx> Ord for TyS<'tcx> {
611 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
612 self.kind.cmp(&other.kind)
613 }
614 }
615
616 impl<'tcx> PartialOrd for TyS<'tcx> {
617 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
618 Some(self.kind.cmp(&other.kind))
619 }
620 }
621
622 impl<'tcx> PartialEq for TyS<'tcx> {
623 #[inline]
624 fn eq(&self, other: &TyS<'tcx>) -> bool {
625 ptr::eq(self, other)
626 }
627 }
628 impl<'tcx> Eq for TyS<'tcx> {}
629
630 impl<'tcx> Hash for TyS<'tcx> {
631 fn hash<H: Hasher>(&self, s: &mut H) {
632 (self as *const TyS<'_>).hash(s)
633 }
634 }
635
636 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
637 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
638 let ty::TyS {
639 ref kind,
640
641 // The other fields just provide fast access to information that is
642 // also contained in `kind`, so no need to hash them.
643 flags: _,
644
645 outer_exclusive_binder: _,
646 } = *self;
647
648 kind.hash_stable(hcx, hasher);
649 }
650 }
651
652 #[rustc_diagnostic_item = "Ty"]
653 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
654
655 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
656 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
657 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
658
659 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
660
661 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
662 pub struct UpvarPath {
663 pub hir_id: hir::HirId,
664 }
665
666 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
667 /// the original var ID (that is, the root variable that is referenced
668 /// by the upvar) and the ID of the closure expression.
669 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
670 pub struct UpvarId {
671 pub var_path: UpvarPath,
672 pub closure_expr_id: LocalDefId,
673 }
674
675 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
676 pub enum BorrowKind {
677 /// Data must be immutable and is aliasable.
678 ImmBorrow,
679
680 /// Data must be immutable but not aliasable. This kind of borrow
681 /// cannot currently be expressed by the user and is used only in
682 /// implicit closure bindings. It is needed when the closure
683 /// is borrowing or mutating a mutable referent, e.g.:
684 ///
685 /// let x: &mut isize = ...;
686 /// let y = || *x += 5;
687 ///
688 /// If we were to try to translate this closure into a more explicit
689 /// form, we'd encounter an error with the code as written:
690 ///
691 /// struct Env { x: & &mut isize }
692 /// let x: &mut isize = ...;
693 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
694 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
695 ///
696 /// This is then illegal because you cannot mutate a `&mut` found
697 /// in an aliasable location. To solve, you'd have to translate with
698 /// an `&mut` borrow:
699 ///
700 /// struct Env { x: & &mut isize }
701 /// let x: &mut isize = ...;
702 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
703 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
704 ///
705 /// Now the assignment to `**env.x` is legal, but creating a
706 /// mutable pointer to `x` is not because `x` is not mutable. We
707 /// could fix this by declaring `x` as `let mut x`. This is ok in
708 /// user code, if awkward, but extra weird for closures, since the
709 /// borrow is hidden.
710 ///
711 /// So we introduce a "unique imm" borrow -- the referent is
712 /// immutable, but not aliasable. This solves the problem. For
713 /// simplicity, we don't give users the way to express this
714 /// borrow, it's just used when translating closures.
715 UniqueImmBorrow,
716
717 /// Data is mutable and not aliasable.
718 MutBorrow,
719 }
720
721 /// Information describing the capture of an upvar. This is computed
722 /// during `typeck`, specifically by `regionck`.
723 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
724 pub enum UpvarCapture<'tcx> {
725 /// Upvar is captured by value. This is always true when the
726 /// closure is labeled `move`, but can also be true in other cases
727 /// depending on inference.
728 ByValue,
729
730 /// Upvar is captured by reference.
731 ByRef(UpvarBorrow<'tcx>),
732 }
733
734 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
735 pub struct UpvarBorrow<'tcx> {
736 /// The kind of borrow: by-ref upvars have access to shared
737 /// immutable borrows, which are not part of the normal language
738 /// syntax.
739 pub kind: BorrowKind,
740
741 /// Region of the resulting reference.
742 pub region: ty::Region<'tcx>,
743 }
744
745 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
746 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
747
748 #[derive(Clone, Copy, PartialEq, Eq)]
749 pub enum IntVarValue {
750 IntType(ast::IntTy),
751 UintType(ast::UintTy),
752 }
753
754 #[derive(Clone, Copy, PartialEq, Eq)]
755 pub struct FloatVarValue(pub ast::FloatTy);
756
757 impl ty::EarlyBoundRegion {
758 pub fn to_bound_region(&self) -> ty::BoundRegion {
759 ty::BoundRegion::BrNamed(self.def_id, self.name)
760 }
761
762 /// Does this early bound region have a name? Early bound regions normally
763 /// always have names except when using anonymous lifetimes (`'_`).
764 pub fn has_name(&self) -> bool {
765 self.name != kw::UnderscoreLifetime
766 }
767 }
768
769 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
770 pub enum GenericParamDefKind {
771 Lifetime,
772 Type {
773 has_default: bool,
774 object_lifetime_default: ObjectLifetimeDefault,
775 synthetic: Option<hir::SyntheticTyParamKind>,
776 },
777 Const,
778 }
779
780 impl GenericParamDefKind {
781 pub fn descr(&self) -> &'static str {
782 match self {
783 GenericParamDefKind::Lifetime => "lifetime",
784 GenericParamDefKind::Type { .. } => "type",
785 GenericParamDefKind::Const => "constant",
786 }
787 }
788 }
789
790 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
791 pub struct GenericParamDef {
792 pub name: Symbol,
793 pub def_id: DefId,
794 pub index: u32,
795
796 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
797 /// on generic parameter `'a`/`T`, asserts data behind the parameter
798 /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
799 pub pure_wrt_drop: bool,
800
801 pub kind: GenericParamDefKind,
802 }
803
804 impl GenericParamDef {
805 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
806 if let GenericParamDefKind::Lifetime = self.kind {
807 ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
808 } else {
809 bug!("cannot convert a non-lifetime parameter def to an early bound region")
810 }
811 }
812
813 pub fn to_bound_region(&self) -> ty::BoundRegion {
814 if let GenericParamDefKind::Lifetime = self.kind {
815 self.to_early_bound_region_data().to_bound_region()
816 } else {
817 bug!("cannot convert a non-lifetime parameter def to an early bound region")
818 }
819 }
820 }
821
822 #[derive(Default)]
823 pub struct GenericParamCount {
824 pub lifetimes: usize,
825 pub types: usize,
826 pub consts: usize,
827 }
828
829 /// Information about the formal type/lifetime parameters associated
830 /// with an item or method. Analogous to `hir::Generics`.
831 ///
832 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
833 /// `Self` (optionally), `Lifetime` params..., `Type` params...
834 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
835 pub struct Generics {
836 pub parent: Option<DefId>,
837 pub parent_count: usize,
838 pub params: Vec<GenericParamDef>,
839
840 /// Reverse map to the `index` field of each `GenericParamDef`.
841 #[stable_hasher(ignore)]
842 pub param_def_id_to_index: FxHashMap<DefId, u32>,
843
844 pub has_self: bool,
845 pub has_late_bound_regions: Option<Span>,
846 }
847
848 impl<'tcx> Generics {
849 pub fn count(&self) -> usize {
850 self.parent_count + self.params.len()
851 }
852
853 pub fn own_counts(&self) -> GenericParamCount {
854 // We could cache this as a property of `GenericParamCount`, but
855 // the aim is to refactor this away entirely eventually and the
856 // presence of this method will be a constant reminder.
857 let mut own_counts: GenericParamCount = Default::default();
858
859 for param in &self.params {
860 match param.kind {
861 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
862 GenericParamDefKind::Type { .. } => own_counts.types += 1,
863 GenericParamDefKind::Const => own_counts.consts += 1,
864 };
865 }
866
867 own_counts
868 }
869
870 pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
871 if self.own_requires_monomorphization() {
872 return true;
873 }
874
875 if let Some(parent_def_id) = self.parent {
876 let parent = tcx.generics_of(parent_def_id);
877 parent.requires_monomorphization(tcx)
878 } else {
879 false
880 }
881 }
882
883 pub fn own_requires_monomorphization(&self) -> bool {
884 for param in &self.params {
885 match param.kind {
886 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
887 GenericParamDefKind::Lifetime => {}
888 }
889 }
890 false
891 }
892
893 pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
894 if let Some(index) = param_index.checked_sub(self.parent_count) {
895 &self.params[index]
896 } else {
897 tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
898 .param_at(param_index, tcx)
899 }
900 }
901
902 pub fn region_param(
903 &'tcx self,
904 param: &EarlyBoundRegion,
905 tcx: TyCtxt<'tcx>,
906 ) -> &'tcx GenericParamDef {
907 let param = self.param_at(param.index as usize, tcx);
908 match param.kind {
909 GenericParamDefKind::Lifetime => param,
910 _ => bug!("expected lifetime parameter, but found another generic parameter"),
911 }
912 }
913
914 /// Returns the `GenericParamDef` associated with this `ParamTy`.
915 pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
916 let param = self.param_at(param.index as usize, tcx);
917 match param.kind {
918 GenericParamDefKind::Type { .. } => param,
919 _ => bug!("expected type parameter, but found another generic parameter"),
920 }
921 }
922
923 /// Returns the `ConstParameterDef` associated with this `ParamConst`.
924 pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
925 let param = self.param_at(param.index as usize, tcx);
926 match param.kind {
927 GenericParamDefKind::Const => param,
928 _ => bug!("expected const parameter, but found another generic parameter"),
929 }
930 }
931 }
932
933 /// Bounds on generics.
934 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
935 pub struct GenericPredicates<'tcx> {
936 pub parent: Option<DefId>,
937 pub predicates: &'tcx [(Predicate<'tcx>, Span)],
938 }
939
940 impl<'tcx> GenericPredicates<'tcx> {
941 pub fn instantiate(
942 &self,
943 tcx: TyCtxt<'tcx>,
944 substs: SubstsRef<'tcx>,
945 ) -> InstantiatedPredicates<'tcx> {
946 let mut instantiated = InstantiatedPredicates::empty();
947 self.instantiate_into(tcx, &mut instantiated, substs);
948 instantiated
949 }
950
951 pub fn instantiate_own(
952 &self,
953 tcx: TyCtxt<'tcx>,
954 substs: SubstsRef<'tcx>,
955 ) -> InstantiatedPredicates<'tcx> {
956 InstantiatedPredicates {
957 predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
958 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
959 }
960 }
961
962 fn instantiate_into(
963 &self,
964 tcx: TyCtxt<'tcx>,
965 instantiated: &mut InstantiatedPredicates<'tcx>,
966 substs: SubstsRef<'tcx>,
967 ) {
968 if let Some(def_id) = self.parent {
969 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
970 }
971 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
972 instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
973 }
974
975 pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
976 let mut instantiated = InstantiatedPredicates::empty();
977 self.instantiate_identity_into(tcx, &mut instantiated);
978 instantiated
979 }
980
981 fn instantiate_identity_into(
982 &self,
983 tcx: TyCtxt<'tcx>,
984 instantiated: &mut InstantiatedPredicates<'tcx>,
985 ) {
986 if let Some(def_id) = self.parent {
987 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
988 }
989 instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
990 instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
991 }
992
993 pub fn instantiate_supertrait(
994 &self,
995 tcx: TyCtxt<'tcx>,
996 poly_trait_ref: &ty::PolyTraitRef<'tcx>,
997 ) -> InstantiatedPredicates<'tcx> {
998 assert_eq!(self.parent, None);
999 InstantiatedPredicates {
1000 predicates: self
1001 .predicates
1002 .iter()
1003 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1004 .collect(),
1005 spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1006 }
1007 }
1008 }
1009
1010 #[derive(Debug)]
1011 crate struct PredicateInner<'tcx> {
1012 kind: PredicateKind<'tcx>,
1013 flags: TypeFlags,
1014 /// See the comment for the corresponding field of [TyS].
1015 outer_exclusive_binder: ty::DebruijnIndex,
1016 }
1017
1018 #[cfg(target_arch = "x86_64")]
1019 static_assert_size!(PredicateInner<'_>, 40);
1020
1021 #[derive(Clone, Copy, Lift)]
1022 pub struct Predicate<'tcx> {
1023 inner: &'tcx PredicateInner<'tcx>,
1024 }
1025
1026 impl rustc_serialize::UseSpecializedEncodable for Predicate<'_> {}
1027 impl rustc_serialize::UseSpecializedDecodable for Predicate<'_> {}
1028
1029 impl<'tcx> PartialEq for Predicate<'tcx> {
1030 fn eq(&self, other: &Self) -> bool {
1031 // `self.kind` is always interned.
1032 ptr::eq(self.inner, other.inner)
1033 }
1034 }
1035
1036 impl Hash for Predicate<'_> {
1037 fn hash<H: Hasher>(&self, s: &mut H) {
1038 (self.inner as *const PredicateInner<'_>).hash(s)
1039 }
1040 }
1041
1042 impl<'tcx> Eq for Predicate<'tcx> {}
1043
1044 impl<'tcx> Predicate<'tcx> {
1045 #[inline(always)]
1046 pub fn kind(self) -> &'tcx PredicateKind<'tcx> {
1047 &self.inner.kind
1048 }
1049 }
1050
1051 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
1052 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1053 let PredicateInner {
1054 ref kind,
1055
1056 // The other fields just provide fast access to information that is
1057 // also contained in `kind`, so no need to hash them.
1058 flags: _,
1059 outer_exclusive_binder: _,
1060 } = self.inner;
1061
1062 kind.hash_stable(hcx, hasher);
1063 }
1064 }
1065
1066 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1067 #[derive(HashStable, TypeFoldable)]
1068 pub enum PredicateKind<'tcx> {
1069 /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1070 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1071 /// would be the type parameters.
1072 ///
1073 /// A trait predicate will have `Constness::Const` if it originates
1074 /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1075 /// `const fn foobar<Foo: Bar>() {}`).
1076 Trait(PolyTraitPredicate<'tcx>, Constness),
1077
1078 /// `where 'a: 'b`
1079 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1080
1081 /// `where T: 'a`
1082 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1083
1084 /// `where <T as TraitRef>::Name == X`, approximately.
1085 /// See the `ProjectionPredicate` struct for details.
1086 Projection(PolyProjectionPredicate<'tcx>),
1087
1088 /// No syntax: `T` well-formed.
1089 WellFormed(GenericArg<'tcx>),
1090
1091 /// Trait must be object-safe.
1092 ObjectSafe(DefId),
1093
1094 /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1095 /// for some substitutions `...` and `T` being a closure type.
1096 /// Satisfied (or refuted) once we know the closure's kind.
1097 ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1098
1099 /// `T1 <: T2`
1100 Subtype(PolySubtypePredicate<'tcx>),
1101
1102 /// Constant initializer must evaluate successfully.
1103 ConstEvaluatable(DefId, SubstsRef<'tcx>),
1104
1105 /// Constants must be equal. The first component is the const that is expected.
1106 ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
1107 }
1108
1109 /// The crate outlives map is computed during typeck and contains the
1110 /// outlives of every item in the local crate. You should not use it
1111 /// directly, because to do so will make your pass dependent on the
1112 /// HIR of every item in the local crate. Instead, use
1113 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1114 /// item.
1115 #[derive(HashStable)]
1116 pub struct CratePredicatesMap<'tcx> {
1117 /// For each struct with outlive bounds, maps to a vector of the
1118 /// predicate of its outlive bounds. If an item has no outlives
1119 /// bounds, it will have no entry.
1120 pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1121 }
1122
1123 impl<'tcx> Predicate<'tcx> {
1124 /// Performs a substitution suitable for going from a
1125 /// poly-trait-ref to supertraits that must hold if that
1126 /// poly-trait-ref holds. This is slightly different from a normal
1127 /// substitution in terms of what happens with bound regions. See
1128 /// lengthy comment below for details.
1129 pub fn subst_supertrait(
1130 self,
1131 tcx: TyCtxt<'tcx>,
1132 trait_ref: &ty::PolyTraitRef<'tcx>,
1133 ) -> ty::Predicate<'tcx> {
1134 // The interaction between HRTB and supertraits is not entirely
1135 // obvious. Let me walk you (and myself) through an example.
1136 //
1137 // Let's start with an easy case. Consider two traits:
1138 //
1139 // trait Foo<'a>: Bar<'a,'a> { }
1140 // trait Bar<'b,'c> { }
1141 //
1142 // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1143 // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1144 // knew that `Foo<'x>` (for any 'x) then we also know that
1145 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1146 // normal substitution.
1147 //
1148 // In terms of why this is sound, the idea is that whenever there
1149 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1150 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1151 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1152 // `'a`.
1153 //
1154 // Another example to be careful of is this:
1155 //
1156 // trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1157 // trait Bar1<'b,'c> { }
1158 //
1159 // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1160 // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1161 // reason is similar to the previous example: any impl of
1162 // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
1163 // basically we would want to collapse the bound lifetimes from
1164 // the input (`trait_ref`) and the supertraits.
1165 //
1166 // To achieve this in practice is fairly straightforward. Let's
1167 // consider the more complicated scenario:
1168 //
1169 // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1170 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1171 // where both `'x` and `'b` would have a DB index of 1.
1172 // The substitution from the input trait-ref is therefore going to be
1173 // `'a => 'x` (where `'x` has a DB index of 1).
1174 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1175 // early-bound parameter and `'b' is a late-bound parameter with a
1176 // DB index of 1.
1177 // - If we replace `'a` with `'x` from the input, it too will have
1178 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1179 // just as we wanted.
1180 //
1181 // There is only one catch. If we just apply the substitution `'a
1182 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1183 // adjust the DB index because we substituting into a binder (it
1184 // tries to be so smart...) resulting in `for<'x> for<'b>
1185 // Bar1<'x,'b>` (we have no syntax for this, so use your
1186 // imagination). Basically the 'x will have DB index of 2 and 'b
1187 // will have DB index of 1. Not quite what we want. So we apply
1188 // the substitution to the *contents* of the trait reference,
1189 // rather than the trait reference itself (put another way, the
1190 // substitution code expects equal binding levels in the values
1191 // from the substitution and the value being substituted into, and
1192 // this trick achieves that).
1193
1194 let substs = &trait_ref.skip_binder().substs;
1195 let kind = self.kind();
1196 let new = match kind {
1197 &PredicateKind::Trait(ref binder, constness) => {
1198 PredicateKind::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness)
1199 }
1200 PredicateKind::Subtype(binder) => {
1201 PredicateKind::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1202 }
1203 PredicateKind::RegionOutlives(binder) => {
1204 PredicateKind::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1205 }
1206 PredicateKind::TypeOutlives(binder) => {
1207 PredicateKind::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1208 }
1209 PredicateKind::Projection(binder) => {
1210 PredicateKind::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1211 }
1212 &PredicateKind::WellFormed(data) => PredicateKind::WellFormed(data.subst(tcx, substs)),
1213 &PredicateKind::ObjectSafe(trait_def_id) => PredicateKind::ObjectSafe(trait_def_id),
1214 &PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
1215 PredicateKind::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1216 }
1217 &PredicateKind::ConstEvaluatable(def_id, const_substs) => {
1218 PredicateKind::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1219 }
1220 PredicateKind::ConstEquate(c1, c2) => {
1221 PredicateKind::ConstEquate(c1.subst(tcx, substs), c2.subst(tcx, substs))
1222 }
1223 };
1224
1225 if new != *kind { new.to_predicate(tcx) } else { self }
1226 }
1227 }
1228
1229 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1230 #[derive(HashStable, TypeFoldable)]
1231 pub struct TraitPredicate<'tcx> {
1232 pub trait_ref: TraitRef<'tcx>,
1233 }
1234
1235 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1236
1237 impl<'tcx> TraitPredicate<'tcx> {
1238 pub fn def_id(self) -> DefId {
1239 self.trait_ref.def_id
1240 }
1241
1242 pub fn self_ty(self) -> Ty<'tcx> {
1243 self.trait_ref.self_ty()
1244 }
1245 }
1246
1247 impl<'tcx> PolyTraitPredicate<'tcx> {
1248 pub fn def_id(self) -> DefId {
1249 // Ok to skip binder since trait `DefId` does not care about regions.
1250 self.skip_binder().def_id()
1251 }
1252 }
1253
1254 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1255 #[derive(HashStable, TypeFoldable)]
1256 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1257 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1258 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1259 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1260 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1261 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1262
1263 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1264 #[derive(HashStable, TypeFoldable)]
1265 pub struct SubtypePredicate<'tcx> {
1266 pub a_is_expected: bool,
1267 pub a: Ty<'tcx>,
1268 pub b: Ty<'tcx>,
1269 }
1270 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1271
1272 /// This kind of predicate has no *direct* correspondent in the
1273 /// syntax, but it roughly corresponds to the syntactic forms:
1274 ///
1275 /// 1. `T: TraitRef<..., Item = Type>`
1276 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1277 ///
1278 /// In particular, form #1 is "desugared" to the combination of a
1279 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1280 /// predicates. Form #2 is a broader form in that it also permits
1281 /// equality between arbitrary types. Processing an instance of
1282 /// Form #2 eventually yields one of these `ProjectionPredicate`
1283 /// instances to normalize the LHS.
1284 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1285 #[derive(HashStable, TypeFoldable)]
1286 pub struct ProjectionPredicate<'tcx> {
1287 pub projection_ty: ProjectionTy<'tcx>,
1288 pub ty: Ty<'tcx>,
1289 }
1290
1291 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1292
1293 impl<'tcx> PolyProjectionPredicate<'tcx> {
1294 /// Returns the `DefId` of the associated item being projected.
1295 pub fn item_def_id(&self) -> DefId {
1296 self.skip_binder().projection_ty.item_def_id
1297 }
1298
1299 #[inline]
1300 pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1301 // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1302 // `self.0.trait_ref` is permitted to have escaping regions.
1303 // This is because here `self` has a `Binder` and so does our
1304 // return value, so we are preserving the number of binding
1305 // levels.
1306 self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1307 }
1308
1309 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1310 self.map_bound(|predicate| predicate.ty)
1311 }
1312
1313 /// The `DefId` of the `TraitItem` for the associated type.
1314 ///
1315 /// Note that this is not the `DefId` of the `TraitRef` containing this
1316 /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1317 pub fn projection_def_id(&self) -> DefId {
1318 // Ok to skip binder since trait `DefId` does not care about regions.
1319 self.skip_binder().projection_ty.item_def_id
1320 }
1321 }
1322
1323 pub trait ToPolyTraitRef<'tcx> {
1324 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1325 }
1326
1327 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1328 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1329 ty::Binder::dummy(*self)
1330 }
1331 }
1332
1333 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1334 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1335 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1336 }
1337 }
1338
1339 pub trait ToPredicate<'tcx> {
1340 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
1341 }
1342
1343 impl ToPredicate<'tcx> for PredicateKind<'tcx> {
1344 #[inline(always)]
1345 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1346 tcx.mk_predicate(self)
1347 }
1348 }
1349
1350 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1351 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1352 ty::PredicateKind::Trait(
1353 ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }),
1354 self.constness,
1355 )
1356 .to_predicate(tcx)
1357 }
1358 }
1359
1360 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> {
1361 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1362 ty::PredicateKind::Trait(
1363 ty::Binder::dummy(ty::TraitPredicate { trait_ref: *self.value }),
1364 self.constness,
1365 )
1366 .to_predicate(tcx)
1367 }
1368 }
1369
1370 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1371 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1372 ty::PredicateKind::Trait(self.value.to_poly_trait_predicate(), self.constness)
1373 .to_predicate(tcx)
1374 }
1375 }
1376
1377 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&PolyTraitRef<'tcx>> {
1378 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1379 ty::PredicateKind::Trait(self.value.to_poly_trait_predicate(), self.constness)
1380 .to_predicate(tcx)
1381 }
1382 }
1383
1384 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1385 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1386 PredicateKind::RegionOutlives(self).to_predicate(tcx)
1387 }
1388 }
1389
1390 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1391 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1392 PredicateKind::TypeOutlives(self).to_predicate(tcx)
1393 }
1394 }
1395
1396 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1397 fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1398 PredicateKind::Projection(self).to_predicate(tcx)
1399 }
1400 }
1401
1402 impl<'tcx> Predicate<'tcx> {
1403 pub fn to_opt_poly_trait_ref(self) -> Option<PolyTraitRef<'tcx>> {
1404 match self.kind() {
1405 &PredicateKind::Trait(ref t, _) => Some(t.to_poly_trait_ref()),
1406 PredicateKind::Projection(..)
1407 | PredicateKind::Subtype(..)
1408 | PredicateKind::RegionOutlives(..)
1409 | PredicateKind::WellFormed(..)
1410 | PredicateKind::ObjectSafe(..)
1411 | PredicateKind::ClosureKind(..)
1412 | PredicateKind::TypeOutlives(..)
1413 | PredicateKind::ConstEvaluatable(..)
1414 | PredicateKind::ConstEquate(..) => None,
1415 }
1416 }
1417
1418 pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1419 match self.kind() {
1420 &PredicateKind::TypeOutlives(data) => Some(data),
1421 PredicateKind::Trait(..)
1422 | PredicateKind::Projection(..)
1423 | PredicateKind::Subtype(..)
1424 | PredicateKind::RegionOutlives(..)
1425 | PredicateKind::WellFormed(..)
1426 | PredicateKind::ObjectSafe(..)
1427 | PredicateKind::ClosureKind(..)
1428 | PredicateKind::ConstEvaluatable(..)
1429 | PredicateKind::ConstEquate(..) => None,
1430 }
1431 }
1432 }
1433
1434 /// Represents the bounds declared on a particular set of type
1435 /// parameters. Should eventually be generalized into a flag list of
1436 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1437 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1438 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1439 /// the `GenericPredicates` are expressed in terms of the bound type
1440 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1441 /// represented a set of bounds for some particular instantiation,
1442 /// meaning that the generic parameters have been substituted with
1443 /// their values.
1444 ///
1445 /// Example:
1446 ///
1447 /// struct Foo<T, U: Bar<T>> { ... }
1448 ///
1449 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1450 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1451 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1452 /// [usize:Bar<isize>]]`.
1453 #[derive(Clone, Debug, TypeFoldable)]
1454 pub struct InstantiatedPredicates<'tcx> {
1455 pub predicates: Vec<Predicate<'tcx>>,
1456 pub spans: Vec<Span>,
1457 }
1458
1459 impl<'tcx> InstantiatedPredicates<'tcx> {
1460 pub fn empty() -> InstantiatedPredicates<'tcx> {
1461 InstantiatedPredicates { predicates: vec![], spans: vec![] }
1462 }
1463
1464 pub fn is_empty(&self) -> bool {
1465 self.predicates.is_empty()
1466 }
1467 }
1468
1469 rustc_index::newtype_index! {
1470 /// "Universes" are used during type- and trait-checking in the
1471 /// presence of `for<..>` binders to control what sets of names are
1472 /// visible. Universes are arranged into a tree: the root universe
1473 /// contains names that are always visible. Each child then adds a new
1474 /// set of names that are visible, in addition to those of its parent.
1475 /// We say that the child universe "extends" the parent universe with
1476 /// new names.
1477 ///
1478 /// To make this more concrete, consider this program:
1479 ///
1480 /// ```
1481 /// struct Foo { }
1482 /// fn bar<T>(x: T) {
1483 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1484 /// }
1485 /// ```
1486 ///
1487 /// The struct name `Foo` is in the root universe U0. But the type
1488 /// parameter `T`, introduced on `bar`, is in an extended universe U1
1489 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1490 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1491 /// region `'a` is in a universe U2 that extends U1, because we can
1492 /// name it inside the fn type but not outside.
1493 ///
1494 /// Universes are used to do type- and trait-checking around these
1495 /// "forall" binders (also called **universal quantification**). The
1496 /// idea is that when, in the body of `bar`, we refer to `T` as a
1497 /// type, we aren't referring to any type in particular, but rather a
1498 /// kind of "fresh" type that is distinct from all other types we have
1499 /// actually declared. This is called a **placeholder** type, and we
1500 /// use universes to talk about this. In other words, a type name in
1501 /// universe 0 always corresponds to some "ground" type that the user
1502 /// declared, but a type name in a non-zero universe is a placeholder
1503 /// type -- an idealized representative of "types in general" that we
1504 /// use for checking generic functions.
1505 pub struct UniverseIndex {
1506 derive [HashStable]
1507 DEBUG_FORMAT = "U{}",
1508 }
1509 }
1510
1511 impl UniverseIndex {
1512 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1513
1514 /// Returns the "next" universe index in order -- this new index
1515 /// is considered to extend all previous universes. This
1516 /// corresponds to entering a `forall` quantifier. So, for
1517 /// example, suppose we have this type in universe `U`:
1518 ///
1519 /// ```
1520 /// for<'a> fn(&'a u32)
1521 /// ```
1522 ///
1523 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1524 /// new universe that extends `U` -- in this new universe, we can
1525 /// name the region `'a`, but that region was not nameable from
1526 /// `U` because it was not in scope there.
1527 pub fn next_universe(self) -> UniverseIndex {
1528 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1529 }
1530
1531 /// Returns `true` if `self` can name a name from `other` -- in other words,
1532 /// if the set of names in `self` is a superset of those in
1533 /// `other` (`self >= other`).
1534 pub fn can_name(self, other: UniverseIndex) -> bool {
1535 self.private >= other.private
1536 }
1537
1538 /// Returns `true` if `self` cannot name some names from `other` -- in other
1539 /// words, if the set of names in `self` is a strict subset of
1540 /// those in `other` (`self < other`).
1541 pub fn cannot_name(self, other: UniverseIndex) -> bool {
1542 self.private < other.private
1543 }
1544 }
1545
1546 /// The "placeholder index" fully defines a placeholder region.
1547 /// Placeholder regions are identified by both a **universe** as well
1548 /// as a "bound-region" within that universe. The `bound_region` is
1549 /// basically a name -- distinct bound regions within the same
1550 /// universe are just two regions with an unknown relationship to one
1551 /// another.
1552 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1553 pub struct Placeholder<T> {
1554 pub universe: UniverseIndex,
1555 pub name: T,
1556 }
1557
1558 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1559 where
1560 T: HashStable<StableHashingContext<'a>>,
1561 {
1562 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1563 self.universe.hash_stable(hcx, hasher);
1564 self.name.hash_stable(hcx, hasher);
1565 }
1566 }
1567
1568 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1569
1570 pub type PlaceholderType = Placeholder<BoundVar>;
1571
1572 pub type PlaceholderConst = Placeholder<BoundVar>;
1573
1574 /// When type checking, we use the `ParamEnv` to track
1575 /// details about the set of where-clauses that are in scope at this
1576 /// particular point.
1577 #[derive(Copy, Clone)]
1578 pub struct ParamEnv<'tcx> {
1579 // We pack the caller_bounds List pointer and a Reveal enum into this usize.
1580 // Specifically, the low bit represents Reveal, with 0 meaning `UserFacing`
1581 // and 1 meaning `All`. The rest is the pointer.
1582 //
1583 // This relies on the List<ty::Predicate<'tcx>> type having at least 2-byte
1584 // alignment. Lists start with a usize and are repr(C) so this should be
1585 // fine; there is a debug_assert in the constructor as well.
1586 //
1587 // Note that the choice of 0 for UserFacing is intentional -- since it is the
1588 // first variant in Reveal this means that joining the pointer is a simple `or`.
1589 packed_data: usize,
1590
1591 /// `Obligation`s that the caller must satisfy. This is basically
1592 /// the set of bounds on the in-scope type parameters, translated
1593 /// into `Obligation`s, and elaborated and normalized.
1594 ///
1595 /// Note: This is packed into the `packed_data` usize above, use the
1596 /// `caller_bounds()` method to access it.
1597 caller_bounds: PhantomData<&'tcx List<ty::Predicate<'tcx>>>,
1598
1599 /// Typically, this is `Reveal::UserFacing`, but during codegen we
1600 /// want `Reveal::All`.
1601 ///
1602 /// Note: This is packed into the caller_bounds usize above, use the reveal()
1603 /// method to access it.
1604 reveal: PhantomData<traits::Reveal>,
1605
1606 /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1607 /// register that `def_id` (useful for transitioning to the chalk trait
1608 /// solver).
1609 pub def_id: Option<DefId>,
1610 }
1611
1612 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1614 f.debug_struct("ParamEnv")
1615 .field("caller_bounds", &self.caller_bounds())
1616 .field("reveal", &self.reveal())
1617 .field("def_id", &self.def_id)
1618 .finish()
1619 }
1620 }
1621
1622 impl<'tcx> Hash for ParamEnv<'tcx> {
1623 fn hash<H: Hasher>(&self, state: &mut H) {
1624 // List hashes as the raw pointer, so we can skip splitting into the
1625 // pointer and the enum.
1626 self.packed_data.hash(state);
1627 self.def_id.hash(state);
1628 }
1629 }
1630
1631 impl<'tcx> PartialEq for ParamEnv<'tcx> {
1632 fn eq(&self, other: &Self) -> bool {
1633 self.caller_bounds() == other.caller_bounds()
1634 && self.reveal() == other.reveal()
1635 && self.def_id == other.def_id
1636 }
1637 }
1638 impl<'tcx> Eq for ParamEnv<'tcx> {}
1639
1640 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1641 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1642 self.caller_bounds().hash_stable(hcx, hasher);
1643 self.reveal().hash_stable(hcx, hasher);
1644 self.def_id.hash_stable(hcx, hasher);
1645 }
1646 }
1647
1648 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1649 fn super_fold_with<F: ty::fold::TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
1650 ParamEnv::new(
1651 self.caller_bounds().fold_with(folder),
1652 self.reveal().fold_with(folder),
1653 self.def_id.fold_with(folder),
1654 )
1655 }
1656
1657 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1658 self.caller_bounds().visit_with(visitor)
1659 || self.reveal().visit_with(visitor)
1660 || self.def_id.visit_with(visitor)
1661 }
1662 }
1663
1664 impl<'tcx> ParamEnv<'tcx> {
1665 /// Construct a trait environment suitable for contexts where
1666 /// there are no where-clauses in scope. Hidden types (like `impl
1667 /// Trait`) are left hidden, so this is suitable for ordinary
1668 /// type-checking.
1669 #[inline]
1670 pub fn empty() -> Self {
1671 Self::new(List::empty(), Reveal::UserFacing, None)
1672 }
1673
1674 #[inline]
1675 pub fn caller_bounds(self) -> &'tcx List<ty::Predicate<'tcx>> {
1676 // mask out bottom bit
1677 unsafe { &*((self.packed_data & (!1)) as *const _) }
1678 }
1679
1680 #[inline]
1681 pub fn reveal(self) -> traits::Reveal {
1682 if self.packed_data & 1 == 0 { traits::Reveal::UserFacing } else { traits::Reveal::All }
1683 }
1684
1685 /// Construct a trait environment with no where-clauses in scope
1686 /// where the values of all `impl Trait` and other hidden types
1687 /// are revealed. This is suitable for monomorphized, post-typeck
1688 /// environments like codegen or doing optimizations.
1689 ///
1690 /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1691 /// or invoke `param_env.with_reveal_all()`.
1692 #[inline]
1693 pub fn reveal_all() -> Self {
1694 Self::new(List::empty(), Reveal::All, None)
1695 }
1696
1697 /// Construct a trait environment with the given set of predicates.
1698 #[inline]
1699 pub fn new(
1700 caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1701 reveal: Reveal,
1702 def_id: Option<DefId>,
1703 ) -> Self {
1704 let packed_data = caller_bounds as *const _ as usize;
1705 // Check that we can pack the reveal data into the pointer.
1706 debug_assert!(packed_data & 1 == 0);
1707 ty::ParamEnv {
1708 packed_data: packed_data
1709 | match reveal {
1710 Reveal::UserFacing => 0,
1711 Reveal::All => 1,
1712 },
1713 caller_bounds: PhantomData,
1714 reveal: PhantomData,
1715 def_id,
1716 }
1717 }
1718
1719 pub fn with_user_facing(mut self) -> Self {
1720 // clear bottom bit
1721 self.packed_data &= !1;
1722 self
1723 }
1724
1725 /// Returns a new parameter environment with the same clauses, but
1726 /// which "reveals" the true results of projections in all cases
1727 /// (even for associated types that are specializable). This is
1728 /// the desired behavior during codegen and certain other special
1729 /// contexts; normally though we want to use `Reveal::UserFacing`,
1730 /// which is the default.
1731 pub fn with_reveal_all(mut self) -> Self {
1732 self.packed_data |= 1;
1733 self
1734 }
1735
1736 /// Returns this same environment but with no caller bounds.
1737 pub fn without_caller_bounds(self) -> Self {
1738 Self::new(List::empty(), self.reveal(), self.def_id)
1739 }
1740
1741 /// Creates a suitable environment in which to perform trait
1742 /// queries on the given value. When type-checking, this is simply
1743 /// the pair of the environment plus value. But when reveal is set to
1744 /// All, then if `value` does not reference any type parameters, we will
1745 /// pair it with the empty environment. This improves caching and is generally
1746 /// invisible.
1747 ///
1748 /// N.B., we preserve the environment when type-checking because it
1749 /// is possible for the user to have wacky where-clauses like
1750 /// `where Box<u32>: Copy`, which are clearly never
1751 /// satisfiable. We generally want to behave as if they were true,
1752 /// although the surrounding function is never reachable.
1753 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1754 match self.reveal() {
1755 Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1756
1757 Reveal::All => {
1758 if value.is_global() {
1759 ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1760 } else {
1761 ParamEnvAnd { param_env: self, value }
1762 }
1763 }
1764 }
1765 }
1766 }
1767
1768 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1769 pub struct ConstnessAnd<T> {
1770 pub constness: Constness,
1771 pub value: T,
1772 }
1773
1774 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1775 // the constness of trait bounds is being propagated correctly.
1776 pub trait WithConstness: Sized {
1777 #[inline]
1778 fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
1779 ConstnessAnd { constness, value: self }
1780 }
1781
1782 #[inline]
1783 fn with_const(self) -> ConstnessAnd<Self> {
1784 self.with_constness(Constness::Const)
1785 }
1786
1787 #[inline]
1788 fn without_const(self) -> ConstnessAnd<Self> {
1789 self.with_constness(Constness::NotConst)
1790 }
1791 }
1792
1793 impl<T> WithConstness for T {}
1794
1795 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
1796 pub struct ParamEnvAnd<'tcx, T> {
1797 pub param_env: ParamEnv<'tcx>,
1798 pub value: T,
1799 }
1800
1801 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1802 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1803 (self.param_env, self.value)
1804 }
1805 }
1806
1807 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
1808 where
1809 T: HashStable<StableHashingContext<'a>>,
1810 {
1811 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1812 let ParamEnvAnd { ref param_env, ref value } = *self;
1813
1814 param_env.hash_stable(hcx, hasher);
1815 value.hash_stable(hcx, hasher);
1816 }
1817 }
1818
1819 #[derive(Copy, Clone, Debug, HashStable)]
1820 pub struct Destructor {
1821 /// The `DefId` of the destructor method
1822 pub did: DefId,
1823 }
1824
1825 bitflags! {
1826 #[derive(HashStable)]
1827 pub struct AdtFlags: u32 {
1828 const NO_ADT_FLAGS = 0;
1829 /// Indicates whether the ADT is an enum.
1830 const IS_ENUM = 1 << 0;
1831 /// Indicates whether the ADT is a union.
1832 const IS_UNION = 1 << 1;
1833 /// Indicates whether the ADT is a struct.
1834 const IS_STRUCT = 1 << 2;
1835 /// Indicates whether the ADT is a struct and has a constructor.
1836 const HAS_CTOR = 1 << 3;
1837 /// Indicates whether the type is `PhantomData`.
1838 const IS_PHANTOM_DATA = 1 << 4;
1839 /// Indicates whether the type has a `#[fundamental]` attribute.
1840 const IS_FUNDAMENTAL = 1 << 5;
1841 /// Indicates whether the type is `Box`.
1842 const IS_BOX = 1 << 6;
1843 /// Indicates whether the type is `ManuallyDrop`.
1844 const IS_MANUALLY_DROP = 1 << 7;
1845 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
1846 /// (i.e., this flag is never set unless this ADT is an enum).
1847 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
1848 }
1849 }
1850
1851 bitflags! {
1852 #[derive(HashStable)]
1853 pub struct VariantFlags: u32 {
1854 const NO_VARIANT_FLAGS = 0;
1855 /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1856 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1857 }
1858 }
1859
1860 /// Definition of a variant -- a struct's fields or a enum variant.
1861 #[derive(Debug, HashStable)]
1862 pub struct VariantDef {
1863 /// `DefId` that identifies the variant itself.
1864 /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1865 pub def_id: DefId,
1866 /// `DefId` that identifies the variant's constructor.
1867 /// If this variant is a struct variant, then this is `None`.
1868 pub ctor_def_id: Option<DefId>,
1869 /// Variant or struct name.
1870 #[stable_hasher(project(name))]
1871 pub ident: Ident,
1872 /// Discriminant of this variant.
1873 pub discr: VariantDiscr,
1874 /// Fields of this variant.
1875 pub fields: Vec<FieldDef>,
1876 /// Type of constructor of variant.
1877 pub ctor_kind: CtorKind,
1878 /// Flags of the variant (e.g. is field list non-exhaustive)?
1879 flags: VariantFlags,
1880 /// Variant is obtained as part of recovering from a syntactic error.
1881 /// May be incomplete or bogus.
1882 pub recovered: bool,
1883 }
1884
1885 impl<'tcx> VariantDef {
1886 /// Creates a new `VariantDef`.
1887 ///
1888 /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1889 /// represents an enum variant).
1890 ///
1891 /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1892 /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1893 ///
1894 /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1895 /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1896 /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1897 /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1898 /// built-in trait), and we do not want to load attributes twice.
1899 ///
1900 /// If someone speeds up attribute loading to not be a performance concern, they can
1901 /// remove this hack and use the constructor `DefId` everywhere.
1902 pub fn new(
1903 tcx: TyCtxt<'tcx>,
1904 ident: Ident,
1905 variant_did: Option<DefId>,
1906 ctor_def_id: Option<DefId>,
1907 discr: VariantDiscr,
1908 fields: Vec<FieldDef>,
1909 ctor_kind: CtorKind,
1910 adt_kind: AdtKind,
1911 parent_did: DefId,
1912 recovered: bool,
1913 ) -> Self {
1914 debug!(
1915 "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1916 fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1917 ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1918 );
1919
1920 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1921 if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
1922 debug!("found non-exhaustive field list for {:?}", parent_did);
1923 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1924 } else if let Some(variant_did) = variant_did {
1925 if tcx.has_attr(variant_did, sym::non_exhaustive) {
1926 debug!("found non-exhaustive field list for {:?}", variant_did);
1927 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1928 }
1929 }
1930
1931 VariantDef {
1932 def_id: variant_did.unwrap_or(parent_did),
1933 ctor_def_id,
1934 ident,
1935 discr,
1936 fields,
1937 ctor_kind,
1938 flags,
1939 recovered,
1940 }
1941 }
1942
1943 /// Is this field list non-exhaustive?
1944 #[inline]
1945 pub fn is_field_list_non_exhaustive(&self) -> bool {
1946 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1947 }
1948
1949 /// `repr(transparent)` structs can have a single non-ZST field, this function returns that
1950 /// field.
1951 pub fn transparent_newtype_field(&self, tcx: TyCtxt<'tcx>) -> Option<&FieldDef> {
1952 for field in &self.fields {
1953 let field_ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, self.def_id));
1954 if !field_ty.is_zst(tcx, self.def_id) {
1955 return Some(field);
1956 }
1957 }
1958
1959 None
1960 }
1961 }
1962
1963 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1964 pub enum VariantDiscr {
1965 /// Explicit value for this variant, i.e., `X = 123`.
1966 /// The `DefId` corresponds to the embedded constant.
1967 Explicit(DefId),
1968
1969 /// The previous variant's discriminant plus one.
1970 /// For efficiency reasons, the distance from the
1971 /// last `Explicit` discriminant is being stored,
1972 /// or `0` for the first variant, if it has none.
1973 Relative(u32),
1974 }
1975
1976 #[derive(Debug, HashStable)]
1977 pub struct FieldDef {
1978 pub did: DefId,
1979 #[stable_hasher(project(name))]
1980 pub ident: Ident,
1981 pub vis: Visibility,
1982 }
1983
1984 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
1985 ///
1986 /// These are all interned (by `alloc_adt_def`) into the global arena.
1987 ///
1988 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
1989 /// This is slightly wrong because `union`s are not ADTs.
1990 /// Moreover, Rust only allows recursive data types through indirection.
1991 ///
1992 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
1993 pub struct AdtDef {
1994 /// The `DefId` of the struct, enum or union item.
1995 pub did: DefId,
1996 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
1997 pub variants: IndexVec<VariantIdx, VariantDef>,
1998 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
1999 flags: AdtFlags,
2000 /// Repr options provided by the user.
2001 pub repr: ReprOptions,
2002 }
2003
2004 impl PartialOrd for AdtDef {
2005 fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2006 Some(self.cmp(&other))
2007 }
2008 }
2009
2010 /// There should be only one AdtDef for each `did`, therefore
2011 /// it is fine to implement `Ord` only based on `did`.
2012 impl Ord for AdtDef {
2013 fn cmp(&self, other: &AdtDef) -> Ordering {
2014 self.did.cmp(&other.did)
2015 }
2016 }
2017
2018 impl PartialEq for AdtDef {
2019 // `AdtDef`s are always interned, and this is part of `TyS` equality.
2020 #[inline]
2021 fn eq(&self, other: &Self) -> bool {
2022 ptr::eq(self, other)
2023 }
2024 }
2025
2026 impl Eq for AdtDef {}
2027
2028 impl Hash for AdtDef {
2029 #[inline]
2030 fn hash<H: Hasher>(&self, s: &mut H) {
2031 (self as *const AdtDef).hash(s)
2032 }
2033 }
2034
2035 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
2036 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2037 self.did.encode(s)
2038 }
2039 }
2040
2041 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2042
2043 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2044 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2045 thread_local! {
2046 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2047 }
2048
2049 let hash: Fingerprint = CACHE.with(|cache| {
2050 let addr = self as *const AdtDef as usize;
2051 *cache.borrow_mut().entry(addr).or_insert_with(|| {
2052 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2053
2054 let mut hasher = StableHasher::new();
2055 did.hash_stable(hcx, &mut hasher);
2056 variants.hash_stable(hcx, &mut hasher);
2057 flags.hash_stable(hcx, &mut hasher);
2058 repr.hash_stable(hcx, &mut hasher);
2059
2060 hasher.finish()
2061 })
2062 });
2063
2064 hash.hash_stable(hcx, hasher);
2065 }
2066 }
2067
2068 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2069 pub enum AdtKind {
2070 Struct,
2071 Union,
2072 Enum,
2073 }
2074
2075 impl Into<DataTypeKind> for AdtKind {
2076 fn into(self) -> DataTypeKind {
2077 match self {
2078 AdtKind::Struct => DataTypeKind::Struct,
2079 AdtKind::Union => DataTypeKind::Union,
2080 AdtKind::Enum => DataTypeKind::Enum,
2081 }
2082 }
2083 }
2084
2085 bitflags! {
2086 #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
2087 pub struct ReprFlags: u8 {
2088 const IS_C = 1 << 0;
2089 const IS_SIMD = 1 << 1;
2090 const IS_TRANSPARENT = 1 << 2;
2091 // Internal only for now. If true, don't reorder fields.
2092 const IS_LINEAR = 1 << 3;
2093 // If true, don't expose any niche to type's context.
2094 const HIDE_NICHE = 1 << 4;
2095 // Any of these flags being set prevent field reordering optimisation.
2096 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
2097 ReprFlags::IS_SIMD.bits |
2098 ReprFlags::IS_LINEAR.bits;
2099 }
2100 }
2101
2102 /// Represents the repr options provided by the user,
2103 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2104 pub struct ReprOptions {
2105 pub int: Option<attr::IntType>,
2106 pub align: Option<Align>,
2107 pub pack: Option<Align>,
2108 pub flags: ReprFlags,
2109 }
2110
2111 impl ReprOptions {
2112 pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2113 let mut flags = ReprFlags::empty();
2114 let mut size = None;
2115 let mut max_align: Option<Align> = None;
2116 let mut min_pack: Option<Align> = None;
2117 for attr in tcx.get_attrs(did).iter() {
2118 for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2119 flags.insert(match r {
2120 attr::ReprC => ReprFlags::IS_C,
2121 attr::ReprPacked(pack) => {
2122 let pack = Align::from_bytes(pack as u64).unwrap();
2123 min_pack = Some(if let Some(min_pack) = min_pack {
2124 min_pack.min(pack)
2125 } else {
2126 pack
2127 });
2128 ReprFlags::empty()
2129 }
2130 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2131 attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2132 attr::ReprSimd => ReprFlags::IS_SIMD,
2133 attr::ReprInt(i) => {
2134 size = Some(i);
2135 ReprFlags::empty()
2136 }
2137 attr::ReprAlign(align) => {
2138 max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2139 ReprFlags::empty()
2140 }
2141 });
2142 }
2143 }
2144
2145 // This is here instead of layout because the choice must make it into metadata.
2146 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2147 flags.insert(ReprFlags::IS_LINEAR);
2148 }
2149 ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2150 }
2151
2152 #[inline]
2153 pub fn simd(&self) -> bool {
2154 self.flags.contains(ReprFlags::IS_SIMD)
2155 }
2156 #[inline]
2157 pub fn c(&self) -> bool {
2158 self.flags.contains(ReprFlags::IS_C)
2159 }
2160 #[inline]
2161 pub fn packed(&self) -> bool {
2162 self.pack.is_some()
2163 }
2164 #[inline]
2165 pub fn transparent(&self) -> bool {
2166 self.flags.contains(ReprFlags::IS_TRANSPARENT)
2167 }
2168 #[inline]
2169 pub fn linear(&self) -> bool {
2170 self.flags.contains(ReprFlags::IS_LINEAR)
2171 }
2172 #[inline]
2173 pub fn hide_niche(&self) -> bool {
2174 self.flags.contains(ReprFlags::HIDE_NICHE)
2175 }
2176
2177 /// Returns the discriminant type, given these `repr` options.
2178 /// This must only be called on enums!
2179 pub fn discr_type(&self) -> attr::IntType {
2180 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2181 }
2182
2183 /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2184 /// layout" optimizations, such as representing `Foo<&T>` as a
2185 /// single pointer.
2186 pub fn inhibit_enum_layout_opt(&self) -> bool {
2187 self.c() || self.int.is_some()
2188 }
2189
2190 /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2191 /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2192 pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2193 if let Some(pack) = self.pack {
2194 if pack.bytes() == 1 {
2195 return true;
2196 }
2197 }
2198 self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2199 }
2200
2201 /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2202 pub fn inhibit_union_abi_opt(&self) -> bool {
2203 self.c()
2204 }
2205 }
2206
2207 impl<'tcx> AdtDef {
2208 /// Creates a new `AdtDef`.
2209 fn new(
2210 tcx: TyCtxt<'_>,
2211 did: DefId,
2212 kind: AdtKind,
2213 variants: IndexVec<VariantIdx, VariantDef>,
2214 repr: ReprOptions,
2215 ) -> Self {
2216 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2217 let mut flags = AdtFlags::NO_ADT_FLAGS;
2218
2219 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2220 debug!("found non-exhaustive variant list for {:?}", did);
2221 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2222 }
2223
2224 flags |= match kind {
2225 AdtKind::Enum => AdtFlags::IS_ENUM,
2226 AdtKind::Union => AdtFlags::IS_UNION,
2227 AdtKind::Struct => AdtFlags::IS_STRUCT,
2228 };
2229
2230 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2231 flags |= AdtFlags::HAS_CTOR;
2232 }
2233
2234 let attrs = tcx.get_attrs(did);
2235 if attr::contains_name(&attrs, sym::fundamental) {
2236 flags |= AdtFlags::IS_FUNDAMENTAL;
2237 }
2238 if Some(did) == tcx.lang_items().phantom_data() {
2239 flags |= AdtFlags::IS_PHANTOM_DATA;
2240 }
2241 if Some(did) == tcx.lang_items().owned_box() {
2242 flags |= AdtFlags::IS_BOX;
2243 }
2244 if Some(did) == tcx.lang_items().manually_drop() {
2245 flags |= AdtFlags::IS_MANUALLY_DROP;
2246 }
2247
2248 AdtDef { did, variants, flags, repr }
2249 }
2250
2251 /// Returns `true` if this is a struct.
2252 #[inline]
2253 pub fn is_struct(&self) -> bool {
2254 self.flags.contains(AdtFlags::IS_STRUCT)
2255 }
2256
2257 /// Returns `true` if this is a union.
2258 #[inline]
2259 pub fn is_union(&self) -> bool {
2260 self.flags.contains(AdtFlags::IS_UNION)
2261 }
2262
2263 /// Returns `true` if this is a enum.
2264 #[inline]
2265 pub fn is_enum(&self) -> bool {
2266 self.flags.contains(AdtFlags::IS_ENUM)
2267 }
2268
2269 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2270 #[inline]
2271 pub fn is_variant_list_non_exhaustive(&self) -> bool {
2272 self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2273 }
2274
2275 /// Returns the kind of the ADT.
2276 #[inline]
2277 pub fn adt_kind(&self) -> AdtKind {
2278 if self.is_enum() {
2279 AdtKind::Enum
2280 } else if self.is_union() {
2281 AdtKind::Union
2282 } else {
2283 AdtKind::Struct
2284 }
2285 }
2286
2287 /// Returns a description of this abstract data type.
2288 pub fn descr(&self) -> &'static str {
2289 match self.adt_kind() {
2290 AdtKind::Struct => "struct",
2291 AdtKind::Union => "union",
2292 AdtKind::Enum => "enum",
2293 }
2294 }
2295
2296 /// Returns a description of a variant of this abstract data type.
2297 #[inline]
2298 pub fn variant_descr(&self) -> &'static str {
2299 match self.adt_kind() {
2300 AdtKind::Struct => "struct",
2301 AdtKind::Union => "union",
2302 AdtKind::Enum => "variant",
2303 }
2304 }
2305
2306 /// If this function returns `true`, it implies that `is_struct` must return `true`.
2307 #[inline]
2308 pub fn has_ctor(&self) -> bool {
2309 self.flags.contains(AdtFlags::HAS_CTOR)
2310 }
2311
2312 /// Returns `true` if this type is `#[fundamental]` for the purposes
2313 /// of coherence checking.
2314 #[inline]
2315 pub fn is_fundamental(&self) -> bool {
2316 self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2317 }
2318
2319 /// Returns `true` if this is `PhantomData<T>`.
2320 #[inline]
2321 pub fn is_phantom_data(&self) -> bool {
2322 self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2323 }
2324
2325 /// Returns `true` if this is Box<T>.
2326 #[inline]
2327 pub fn is_box(&self) -> bool {
2328 self.flags.contains(AdtFlags::IS_BOX)
2329 }
2330
2331 /// Returns `true` if this is `ManuallyDrop<T>`.
2332 #[inline]
2333 pub fn is_manually_drop(&self) -> bool {
2334 self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2335 }
2336
2337 /// Returns `true` if this type has a destructor.
2338 pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2339 self.destructor(tcx).is_some()
2340 }
2341
2342 /// Asserts this is a struct or union and returns its unique variant.
2343 pub fn non_enum_variant(&self) -> &VariantDef {
2344 assert!(self.is_struct() || self.is_union());
2345 &self.variants[VariantIdx::new(0)]
2346 }
2347
2348 #[inline]
2349 pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2350 tcx.predicates_of(self.did)
2351 }
2352
2353 /// Returns an iterator over all fields contained
2354 /// by this ADT.
2355 #[inline]
2356 pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2357 self.variants.iter().flat_map(|v| v.fields.iter())
2358 }
2359
2360 pub fn is_payloadfree(&self) -> bool {
2361 !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2362 }
2363
2364 /// Return a `VariantDef` given a variant id.
2365 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2366 self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2367 }
2368
2369 /// Return a `VariantDef` given a constructor id.
2370 pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2371 self.variants
2372 .iter()
2373 .find(|v| v.ctor_def_id == Some(cid))
2374 .expect("variant_with_ctor_id: unknown variant")
2375 }
2376
2377 /// Return the index of `VariantDef` given a variant id.
2378 pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2379 self.variants
2380 .iter_enumerated()
2381 .find(|(_, v)| v.def_id == vid)
2382 .expect("variant_index_with_id: unknown variant")
2383 .0
2384 }
2385
2386 /// Return the index of `VariantDef` given a constructor id.
2387 pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2388 self.variants
2389 .iter_enumerated()
2390 .find(|(_, v)| v.ctor_def_id == Some(cid))
2391 .expect("variant_index_with_ctor_id: unknown variant")
2392 .0
2393 }
2394
2395 pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2396 match res {
2397 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2398 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2399 Res::Def(DefKind::Struct, _)
2400 | Res::Def(DefKind::Union, _)
2401 | Res::Def(DefKind::TyAlias, _)
2402 | Res::Def(DefKind::AssocTy, _)
2403 | Res::SelfTy(..)
2404 | Res::SelfCtor(..) => self.non_enum_variant(),
2405 _ => bug!("unexpected res {:?} in variant_of_res", res),
2406 }
2407 }
2408
2409 #[inline]
2410 pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2411 assert!(self.is_enum());
2412 let param_env = tcx.param_env(expr_did);
2413 let repr_type = self.repr.discr_type();
2414 match tcx.const_eval_poly(expr_did) {
2415 Ok(val) => {
2416 let ty = repr_type.to_ty(tcx);
2417 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2418 trace!("discriminants: {} ({:?})", b, repr_type);
2419 Some(Discr { val: b, ty })
2420 } else {
2421 info!("invalid enum discriminant: {:#?}", val);
2422 crate::mir::interpret::struct_error(
2423 tcx.at(tcx.def_span(expr_did)),
2424 "constant evaluation of enum discriminant resulted in non-integer",
2425 )
2426 .emit();
2427 None
2428 }
2429 }
2430 Err(err) => {
2431 let msg = match err {
2432 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
2433 "enum discriminant evaluation failed"
2434 }
2435 ErrorHandled::TooGeneric => "enum discriminant depends on generics",
2436 };
2437 tcx.sess.delay_span_bug(tcx.def_span(expr_did), msg);
2438 None
2439 }
2440 }
2441 }
2442
2443 #[inline]
2444 pub fn discriminants(
2445 &'tcx self,
2446 tcx: TyCtxt<'tcx>,
2447 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2448 assert!(self.is_enum());
2449 let repr_type = self.repr.discr_type();
2450 let initial = repr_type.initial_discriminant(tcx);
2451 let mut prev_discr = None::<Discr<'tcx>>;
2452 self.variants.iter_enumerated().map(move |(i, v)| {
2453 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2454 if let VariantDiscr::Explicit(expr_did) = v.discr {
2455 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2456 discr = new_discr;
2457 }
2458 }
2459 prev_discr = Some(discr);
2460
2461 (i, discr)
2462 })
2463 }
2464
2465 #[inline]
2466 pub fn variant_range(&self) -> Range<VariantIdx> {
2467 VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2468 }
2469
2470 /// Computes the discriminant value used by a specific variant.
2471 /// Unlike `discriminants`, this is (amortized) constant-time,
2472 /// only doing at most one query for evaluating an explicit
2473 /// discriminant (the last one before the requested variant),
2474 /// assuming there are no constant-evaluation errors there.
2475 #[inline]
2476 pub fn discriminant_for_variant(
2477 &self,
2478 tcx: TyCtxt<'tcx>,
2479 variant_index: VariantIdx,
2480 ) -> Discr<'tcx> {
2481 assert!(self.is_enum());
2482 let (val, offset) = self.discriminant_def_for_variant(variant_index);
2483 let explicit_value = val
2484 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2485 .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2486 explicit_value.checked_add(tcx, offset as u128).0
2487 }
2488
2489 /// Yields a `DefId` for the discriminant and an offset to add to it
2490 /// Alternatively, if there is no explicit discriminant, returns the
2491 /// inferred discriminant directly.
2492 pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2493 assert!(!self.variants.is_empty());
2494 let mut explicit_index = variant_index.as_u32();
2495 let expr_did;
2496 loop {
2497 match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2498 ty::VariantDiscr::Relative(0) => {
2499 expr_did = None;
2500 break;
2501 }
2502 ty::VariantDiscr::Relative(distance) => {
2503 explicit_index -= distance;
2504 }
2505 ty::VariantDiscr::Explicit(did) => {
2506 expr_did = Some(did);
2507 break;
2508 }
2509 }
2510 }
2511 (expr_did, variant_index.as_u32() - explicit_index)
2512 }
2513
2514 pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2515 tcx.adt_destructor(self.did)
2516 }
2517
2518 /// Returns a list of types such that `Self: Sized` if and only
2519 /// if that type is `Sized`, or `TyErr` if this type is recursive.
2520 ///
2521 /// Oddly enough, checking that the sized-constraint is `Sized` is
2522 /// actually more expressive than checking all members:
2523 /// the `Sized` trait is inductive, so an associated type that references
2524 /// `Self` would prevent its containing ADT from being `Sized`.
2525 ///
2526 /// Due to normalization being eager, this applies even if
2527 /// the associated type is behind a pointer (e.g., issue #31299).
2528 pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2529 tcx.adt_sized_constraint(self.did).0
2530 }
2531 }
2532
2533 impl<'tcx> FieldDef {
2534 /// Returns the type of this field. The `subst` is typically obtained
2535 /// via the second field of `TyKind::AdtDef`.
2536 pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2537 tcx.type_of(self.did).subst(tcx, subst)
2538 }
2539 }
2540
2541 /// Represents the various closure traits in the language. This
2542 /// will determine the type of the environment (`self`, in the
2543 /// desugaring) argument that the closure expects.
2544 ///
2545 /// You can get the environment type of a closure using
2546 /// `tcx.closure_env_ty()`.
2547 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
2548 #[derive(HashStable)]
2549 pub enum ClosureKind {
2550 // Warning: Ordering is significant here! The ordering is chosen
2551 // because the trait Fn is a subtrait of FnMut and so in turn, and
2552 // hence we order it so that Fn < FnMut < FnOnce.
2553 Fn,
2554 FnMut,
2555 FnOnce,
2556 }
2557
2558 impl<'tcx> ClosureKind {
2559 // This is the initial value used when doing upvar inference.
2560 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2561
2562 pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2563 match *self {
2564 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2565 ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2566 ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2567 }
2568 }
2569
2570 /// Returns `true` if this a type that impls this closure kind
2571 /// must also implement `other`.
2572 pub fn extends(self, other: ty::ClosureKind) -> bool {
2573 match (self, other) {
2574 (ClosureKind::Fn, ClosureKind::Fn) => true,
2575 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2576 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2577 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2578 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2579 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2580 _ => false,
2581 }
2582 }
2583
2584 /// Returns the representative scalar type for this closure kind.
2585 /// See `TyS::to_opt_closure_kind` for more details.
2586 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2587 match self {
2588 ty::ClosureKind::Fn => tcx.types.i8,
2589 ty::ClosureKind::FnMut => tcx.types.i16,
2590 ty::ClosureKind::FnOnce => tcx.types.i32,
2591 }
2592 }
2593 }
2594
2595 impl BorrowKind {
2596 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2597 match m {
2598 hir::Mutability::Mut => MutBorrow,
2599 hir::Mutability::Not => ImmBorrow,
2600 }
2601 }
2602
2603 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2604 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2605 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2606 /// question.
2607 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2608 match self {
2609 MutBorrow => hir::Mutability::Mut,
2610 ImmBorrow => hir::Mutability::Not,
2611
2612 // We have no type corresponding to a unique imm borrow, so
2613 // use `&mut`. It gives all the capabilities of an `&uniq`
2614 // and hence is a safe "over approximation".
2615 UniqueImmBorrow => hir::Mutability::Mut,
2616 }
2617 }
2618
2619 pub fn to_user_str(&self) -> &'static str {
2620 match *self {
2621 MutBorrow => "mutable",
2622 ImmBorrow => "immutable",
2623 UniqueImmBorrow => "uniquely immutable",
2624 }
2625 }
2626 }
2627
2628 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
2629
2630 #[derive(Debug, PartialEq, Eq)]
2631 pub enum ImplOverlapKind {
2632 /// These impls are always allowed to overlap.
2633 Permitted {
2634 /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2635 marker: bool,
2636 },
2637 /// These impls are allowed to overlap, but that raises
2638 /// an issue #33140 future-compatibility warning.
2639 ///
2640 /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2641 /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2642 ///
2643 /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2644 /// that difference, making what reduces to the following set of impls:
2645 ///
2646 /// ```
2647 /// trait Trait {}
2648 /// impl Trait for dyn Send + Sync {}
2649 /// impl Trait for dyn Sync + Send {}
2650 /// ```
2651 ///
2652 /// Obviously, once we made these types be identical, that code causes a coherence
2653 /// error and a fairly big headache for us. However, luckily for us, the trait
2654 /// `Trait` used in this case is basically a marker trait, and therefore having
2655 /// overlapping impls for it is sound.
2656 ///
2657 /// To handle this, we basically regard the trait as a marker trait, with an additional
2658 /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2659 /// it has the following restrictions:
2660 ///
2661 /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2662 /// positive impls.
2663 /// 2. The trait-ref of both impls must be equal.
2664 /// 3. The trait-ref of both impls must be a trait object type consisting only of
2665 /// marker traits.
2666 /// 4. Neither of the impls can have any where-clauses.
2667 ///
2668 /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2669 Issue33140,
2670 }
2671
2672 impl<'tcx> TyCtxt<'tcx> {
2673 pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> {
2674 self.typeck_tables_of(self.hir().body_owner_def_id(body))
2675 }
2676
2677 /// Returns an iterator of the `DefId`s for all body-owners in this
2678 /// crate. If you would prefer to iterate over the bodies
2679 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2680 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
2681 self.hir()
2682 .krate()
2683 .body_ids
2684 .iter()
2685 .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2686 }
2687
2688 pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
2689 par_iter(&self.hir().krate().body_ids)
2690 .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2691 }
2692
2693 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2694 self.associated_items(id)
2695 .in_definition_order()
2696 .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
2697 }
2698
2699 pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2700 def_id
2701 .as_local()
2702 .and_then(|def_id| self.hir().get(self.hir().as_local_hir_id(def_id)).ident())
2703 }
2704
2705 pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2706 let is_associated_item = if let Some(def_id) = def_id.as_local() {
2707 match self.hir().get(self.hir().as_local_hir_id(def_id)) {
2708 Node::TraitItem(_) | Node::ImplItem(_) => true,
2709 _ => false,
2710 }
2711 } else {
2712 match self.def_kind(def_id) {
2713 DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy => true,
2714 _ => false,
2715 }
2716 };
2717
2718 is_associated_item.then(|| self.associated_item(def_id))
2719 }
2720
2721 pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize {
2722 tables.field_indices().get(hir_id).cloned().expect("no index for a field")
2723 }
2724
2725 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2726 variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
2727 }
2728
2729 /// Returns `true` if the impls are the same polarity and the trait either
2730 /// has no items or is annotated `#[marker]` and prevents item overrides.
2731 pub fn impls_are_allowed_to_overlap(
2732 self,
2733 def_id1: DefId,
2734 def_id2: DefId,
2735 ) -> Option<ImplOverlapKind> {
2736 // If either trait impl references an error, they're allowed to overlap,
2737 // as one of them essentially doesn't exist.
2738 if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2739 || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2740 {
2741 return Some(ImplOverlapKind::Permitted { marker: false });
2742 }
2743
2744 match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2745 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2746 // `#[rustc_reservation_impl]` impls don't overlap with anything
2747 debug!(
2748 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2749 def_id1, def_id2
2750 );
2751 return Some(ImplOverlapKind::Permitted { marker: false });
2752 }
2753 (ImplPolarity::Positive, ImplPolarity::Negative)
2754 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2755 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2756 debug!(
2757 "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2758 def_id1, def_id2
2759 );
2760 return None;
2761 }
2762 (ImplPolarity::Positive, ImplPolarity::Positive)
2763 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2764 };
2765
2766 let is_marker_overlap = {
2767 let is_marker_impl = |def_id: DefId| -> bool {
2768 let trait_ref = self.impl_trait_ref(def_id);
2769 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2770 };
2771 is_marker_impl(def_id1) && is_marker_impl(def_id2)
2772 };
2773
2774 if is_marker_overlap {
2775 debug!(
2776 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2777 def_id1, def_id2
2778 );
2779 Some(ImplOverlapKind::Permitted { marker: true })
2780 } else {
2781 if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2782 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2783 if self_ty1 == self_ty2 {
2784 debug!(
2785 "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2786 def_id1, def_id2
2787 );
2788 return Some(ImplOverlapKind::Issue33140);
2789 } else {
2790 debug!(
2791 "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2792 def_id1, def_id2, self_ty1, self_ty2
2793 );
2794 }
2795 }
2796 }
2797
2798 debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2799 None
2800 }
2801 }
2802
2803 /// Returns `ty::VariantDef` if `res` refers to a struct,
2804 /// or variant or their constructors, panics otherwise.
2805 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2806 match res {
2807 Res::Def(DefKind::Variant, did) => {
2808 let enum_did = self.parent(did).unwrap();
2809 self.adt_def(enum_did).variant_with_id(did)
2810 }
2811 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2812 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2813 let variant_did = self.parent(variant_ctor_did).unwrap();
2814 let enum_did = self.parent(variant_did).unwrap();
2815 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2816 }
2817 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2818 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
2819 self.adt_def(struct_did).non_enum_variant()
2820 }
2821 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2822 }
2823 }
2824
2825 pub fn item_name(self, id: DefId) -> Symbol {
2826 if id.index == CRATE_DEF_INDEX {
2827 self.original_crate_name(id.krate)
2828 } else {
2829 let def_key = self.def_key(id);
2830 match def_key.disambiguated_data.data {
2831 // The name of a constructor is that of its parent.
2832 rustc_hir::definitions::DefPathData::Ctor => {
2833 self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
2834 }
2835 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2836 bug!("item_name: no name for {:?}", self.def_path(id));
2837 }),
2838 }
2839 }
2840 }
2841
2842 /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2843 pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2844 match instance {
2845 ty::InstanceDef::Item(did) => self.optimized_mir(did),
2846 ty::InstanceDef::VtableShim(..)
2847 | ty::InstanceDef::ReifyShim(..)
2848 | ty::InstanceDef::Intrinsic(..)
2849 | ty::InstanceDef::FnPtrShim(..)
2850 | ty::InstanceDef::Virtual(..)
2851 | ty::InstanceDef::ClosureOnceShim { .. }
2852 | ty::InstanceDef::DropGlue(..)
2853 | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2854 }
2855 }
2856
2857 /// Gets the attributes of a definition.
2858 pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
2859 if let Some(did) = did.as_local() {
2860 self.hir().attrs(self.hir().as_local_hir_id(did))
2861 } else {
2862 self.item_attrs(did)
2863 }
2864 }
2865
2866 /// Determines whether an item is annotated with an attribute.
2867 pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2868 attr::contains_name(&self.get_attrs(did), attr)
2869 }
2870
2871 /// Returns `true` if this is an `auto trait`.
2872 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2873 self.trait_def(trait_def_id).has_auto_impl
2874 }
2875
2876 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2877 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2878 }
2879
2880 /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2881 /// If it implements no trait, returns `None`.
2882 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2883 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2884 }
2885
2886 /// If the given defid describes a method belonging to an impl, returns the
2887 /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2888 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2889 self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
2890 TraitContainer(_) => None,
2891 ImplContainer(def_id) => Some(def_id),
2892 })
2893 }
2894
2895 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2896 /// with the name of the crate containing the impl.
2897 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2898 if let Some(impl_did) = impl_did.as_local() {
2899 let hir_id = self.hir().as_local_hir_id(impl_did);
2900 Ok(self.hir().span(hir_id))
2901 } else {
2902 Err(self.crate_name(impl_did.krate))
2903 }
2904 }
2905
2906 /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2907 /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2908 /// definition's parent/scope to perform comparison.
2909 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2910 // We could use `Ident::eq` here, but we deliberately don't. The name
2911 // comparison fails frequently, and we want to avoid the expensive
2912 // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2913 use_name.name == def_name.name
2914 && use_name
2915 .span
2916 .ctxt()
2917 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
2918 }
2919
2920 fn expansion_that_defined(self, scope: DefId) -> ExpnId {
2921 match scope.as_local() {
2922 Some(scope) => self.hir().definitions().expansion_that_defined(scope),
2923 None => ExpnId::root(),
2924 }
2925 }
2926
2927 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2928 ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
2929 ident
2930 }
2931
2932 pub fn adjust_ident_and_get_scope(
2933 self,
2934 mut ident: Ident,
2935 scope: DefId,
2936 block: hir::HirId,
2937 ) -> (Ident, DefId) {
2938 let scope =
2939 match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
2940 {
2941 Some(actual_expansion) => {
2942 self.hir().definitions().parent_module_of_macro_def(actual_expansion)
2943 }
2944 None => self.parent_module(block).to_def_id(),
2945 };
2946 (ident, scope)
2947 }
2948
2949 pub fn is_object_safe(self, key: DefId) -> bool {
2950 self.object_safety_violations(key).is_empty()
2951 }
2952 }
2953
2954 #[derive(Clone, HashStable)]
2955 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
2956
2957 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
2958 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
2959 if let Some(def_id) = def_id.as_local() {
2960 if let Node::Item(item) = tcx.hir().get(tcx.hir().as_local_hir_id(def_id)) {
2961 if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2962 return opaque_ty.impl_trait_fn;
2963 }
2964 }
2965 }
2966 None
2967 }
2968
2969 pub fn provide(providers: &mut ty::query::Providers) {
2970 context::provide(providers);
2971 erase_regions::provide(providers);
2972 layout::provide(providers);
2973 super::util::bug::provide(providers);
2974 *providers = ty::query::Providers {
2975 trait_impls_of: trait_def::trait_impls_of_provider,
2976 all_local_trait_impls: trait_def::all_local_trait_impls,
2977 ..*providers
2978 };
2979 }
2980
2981 /// A map for the local crate mapping each type to a vector of its
2982 /// inherent impls. This is not meant to be used outside of coherence;
2983 /// rather, you should request the vector for a specific type via
2984 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2985 /// (constructing this map requires touching the entire crate).
2986 #[derive(Clone, Debug, Default, HashStable)]
2987 pub struct CrateInherentImpls {
2988 pub inherent_impls: DefIdMap<Vec<DefId>>,
2989 }
2990
2991 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2992 pub struct SymbolName {
2993 // FIXME: we don't rely on interning or equality here - better have
2994 // this be a `&'tcx str`.
2995 pub name: Symbol,
2996 }
2997
2998 impl SymbolName {
2999 pub fn new(name: &str) -> SymbolName {
3000 SymbolName { name: Symbol::intern(name) }
3001 }
3002 }
3003
3004 impl PartialOrd for SymbolName {
3005 fn partial_cmp(&self, other: &SymbolName) -> Option<Ordering> {
3006 self.name.as_str().partial_cmp(&other.name.as_str())
3007 }
3008 }
3009
3010 /// Ordering must use the chars to ensure reproducible builds.
3011 impl Ord for SymbolName {
3012 fn cmp(&self, other: &SymbolName) -> Ordering {
3013 self.name.as_str().cmp(&other.name.as_str())
3014 }
3015 }
3016
3017 impl fmt::Display for SymbolName {
3018 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3019 fmt::Display::fmt(&self.name, fmt)
3020 }
3021 }
3022
3023 impl fmt::Debug for SymbolName {
3024 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3025 fmt::Display::fmt(&self.name, fmt)
3026 }
3027 }