1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::Variance::*;
12 pub use self::AssociatedItemContainer::*;
13 pub use self::BorrowKind::*;
14 pub use self::IntVarValue::*;
15 pub use self::LvaluePreference::*;
16 pub use self::fold::TypeFoldable;
18 use dep_graph::DepNode;
19 use hir::{map as hir_map, FreevarMap, TraitMap};
20 use hir::def::{Def, CtorKind, ExportMap};
21 use hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
22 use ich::StableHashingContext;
23 use middle::const_val::ConstVal;
24 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
25 use middle::privacy::AccessLevels;
26 use middle::resolve_lifetime::ObjectLifetimeDefault;
27 use middle::region::CodeExtent;
31 use ty::subst::{Subst, Substs};
32 use ty::util::IntTypeExt;
33 use ty::walk::TypeWalker;
34 use util::common::ErrorReported;
35 use util::nodemap::{NodeSet, DefIdMap, FxHashMap, FxHashSet};
37 use serialize::{self, Encodable, Encoder};
38 use std::cell::{Cell, RefCell};
39 use std::collections::BTreeMap;
42 use std::hash::{Hash, Hasher};
43 use std::iter::FromIterator;
47 use std::vec::IntoIter;
49 use syntax::ast::{self, DUMMY_NODE_ID, Name, NodeId};
51 use syntax::symbol::{Symbol, InternedString};
52 use syntax_pos::{DUMMY_SP, Span};
53 use rustc_const_math::ConstInt;
55 use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
56 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
58 use rustc_data_structures::transitive_relation::TransitiveRelation;
62 pub use self::sty::{Binder, DebruijnIndex};
63 pub use self::sty::{FnSig, PolyFnSig};
64 pub use self::sty::{InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
65 pub use self::sty::{ClosureSubsts, TypeAndMut};
66 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
67 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
68 pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
69 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
70 pub use self::sty::RegionKind;
71 pub use self::sty::Issue32330;
72 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid, SkolemizedRegionVid};
73 pub use self::sty::BoundRegion::*;
74 pub use self::sty::InferTy::*;
75 pub use self::sty::RegionKind::*;
76 pub use self::sty::TypeVariants::*;
78 pub use self::context::{TyCtxt, GlobalArenas, tls};
79 pub use self::context::{Lift, TypeckTables};
81 pub use self::instance::{Instance, InstanceDef};
83 pub use self::trait_def::{TraitDef, TraitFlags};
85 pub use self::maps::queries;
92 pub mod inhabitedness;
109 mod structural_impls;
114 /// The complete set of all analyses described in this module. This is
115 /// produced by the driver and fed to trans and later passes.
117 /// NB: These contents are being migrated into queries using the
118 /// *on-demand* infrastructure.
120 pub struct CrateAnalysis {
121 pub access_levels: Rc<AccessLevels>,
122 pub reachable: Rc<NodeSet>,
124 pub glob_map: Option<hir::GlobMap>,
128 pub struct Resolutions {
129 pub freevars: FreevarMap,
130 pub trait_map: TraitMap,
131 pub maybe_unused_trait_imports: NodeSet,
132 pub export_map: ExportMap,
135 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
136 pub enum AssociatedItemContainer {
137 TraitContainer(DefId),
138 ImplContainer(DefId),
141 impl AssociatedItemContainer {
142 pub fn id(&self) -> DefId {
144 TraitContainer(id) => id,
145 ImplContainer(id) => id,
150 /// The "header" of an impl is everything outside the body: a Self type, a trait
151 /// ref (in the case of a trait impl), and a set of predicates (from the
152 /// bounds/where clauses).
153 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
154 pub struct ImplHeader<'tcx> {
155 pub impl_def_id: DefId,
156 pub self_ty: Ty<'tcx>,
157 pub trait_ref: Option<TraitRef<'tcx>>,
158 pub predicates: Vec<Predicate<'tcx>>,
161 impl<'a, 'gcx, 'tcx> ImplHeader<'tcx> {
162 pub fn with_fresh_ty_vars(selcx: &mut traits::SelectionContext<'a, 'gcx, 'tcx>,
166 let tcx = selcx.tcx();
167 let impl_substs = selcx.infcx().fresh_substs_for_item(DUMMY_SP, impl_def_id);
169 let header = ImplHeader {
170 impl_def_id: impl_def_id,
171 self_ty: tcx.type_of(impl_def_id),
172 trait_ref: tcx.impl_trait_ref(impl_def_id),
173 predicates: tcx.predicates_of(impl_def_id).predicates
174 }.subst(tcx, impl_substs);
176 let traits::Normalized { value: mut header, obligations } =
177 traits::normalize(selcx, traits::ObligationCause::dummy(), &header);
179 header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
184 #[derive(Copy, Clone, Debug)]
185 pub struct AssociatedItem {
188 pub kind: AssociatedKind,
190 pub defaultness: hir::Defaultness,
191 pub container: AssociatedItemContainer,
193 /// Whether this is a method with an explicit self
194 /// as its first argument, allowing method calls.
195 pub method_has_self_argument: bool,
198 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
199 pub enum AssociatedKind {
205 impl AssociatedItem {
206 pub fn def(&self) -> Def {
208 AssociatedKind::Const => Def::AssociatedConst(self.def_id),
209 AssociatedKind::Method => Def::Method(self.def_id),
210 AssociatedKind::Type => Def::AssociatedTy(self.def_id),
214 /// Tests whether the associated item admits a non-trivial implementation
216 pub fn relevant_for_never<'tcx>(&self) -> bool {
218 AssociatedKind::Const => true,
219 AssociatedKind::Type => true,
220 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
221 AssociatedKind::Method => !self.method_has_self_argument,
226 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
227 pub enum Visibility {
228 /// Visible everywhere (including in other crates).
230 /// Visible only in the given crate-local module.
232 /// Not visible anywhere in the local crate. This is the visibility of private external items.
236 pub trait DefIdTree: Copy {
237 fn parent(self, id: DefId) -> Option<DefId>;
239 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
240 if descendant.krate != ancestor.krate {
244 while descendant != ancestor {
245 match self.parent(descendant) {
246 Some(parent) => descendant = parent,
247 None => return false,
254 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
255 fn parent(self, id: DefId) -> Option<DefId> {
256 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
261 pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
263 hir::Public => Visibility::Public,
264 hir::Visibility::Crate => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
265 hir::Visibility::Restricted { ref path, .. } => match path.def {
266 // If there is no resolution, `resolve` will have already reported an error, so
267 // assume that the visibility is public to avoid reporting more privacy errors.
268 Def::Err => Visibility::Public,
269 def => Visibility::Restricted(def.def_id()),
272 Visibility::Restricted(tcx.hir.local_def_id(tcx.hir.get_module_parent(id)))
277 /// Returns true if an item with this visibility is accessible from the given block.
278 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
279 let restriction = match self {
280 // Public items are visible everywhere.
281 Visibility::Public => return true,
282 // Private items from other crates are visible nowhere.
283 Visibility::Invisible => return false,
284 // Restricted items are visible in an arbitrary local module.
285 Visibility::Restricted(other) if other.krate != module.krate => return false,
286 Visibility::Restricted(module) => module,
289 tree.is_descendant_of(module, restriction)
292 /// Returns true if this visibility is at least as accessible as the given visibility
293 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
294 let vis_restriction = match vis {
295 Visibility::Public => return self == Visibility::Public,
296 Visibility::Invisible => return true,
297 Visibility::Restricted(module) => module,
300 self.is_accessible_from(vis_restriction, tree)
304 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
306 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
307 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
308 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
309 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
312 /// The crate variances map is computed during typeck and contains the
313 /// variance of every item in the local crate. You should not use it
314 /// directly, because to do so will make your pass dependent on the
315 /// HIR of every item in the local crate. Instead, use
316 /// `tcx.variances_of()` to get the variance for a *particular*
318 pub struct CrateVariancesMap {
319 /// This relation tracks the dependencies between the variance of
320 /// various items. In particular, if `a < b`, then the variance of
321 /// `a` depends on the sources of `b`.
322 pub dependencies: TransitiveRelation<DefId>,
324 /// For each item with generics, maps to a vector of the variance
325 /// of its generics. If an item has no generics, it will have no
327 pub variances: FxHashMap<DefId, Rc<Vec<ty::Variance>>>,
329 /// An empty vector, useful for cloning.
330 pub empty_variance: Rc<Vec<ty::Variance>>,
334 /// `a.xform(b)` combines the variance of a context with the
335 /// variance of a type with the following meaning. If we are in a
336 /// context with variance `a`, and we encounter a type argument in
337 /// a position with variance `b`, then `a.xform(b)` is the new
338 /// variance with which the argument appears.
344 /// Here, the "ambient" variance starts as covariant. `*mut T` is
345 /// invariant with respect to `T`, so the variance in which the
346 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
347 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
348 /// respect to its type argument `T`, and hence the variance of
349 /// the `i32` here is `Invariant.xform(Covariant)`, which results
350 /// (again) in `Invariant`.
354 /// fn(*const Vec<i32>, *mut Vec<i32)
356 /// The ambient variance is covariant. A `fn` type is
357 /// contravariant with respect to its parameters, so the variance
358 /// within which both pointer types appear is
359 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
360 /// T` is covariant with respect to `T`, so the variance within
361 /// which the first `Vec<i32>` appears is
362 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
363 /// is true for its `i32` argument. In the `*mut T` case, the
364 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
365 /// and hence the outermost type is `Invariant` with respect to
366 /// `Vec<i32>` (and its `i32` argument).
368 /// Source: Figure 1 of "Taming the Wildcards:
369 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
370 pub fn xform(self, v: ty::Variance) -> ty::Variance {
372 // Figure 1, column 1.
373 (ty::Covariant, ty::Covariant) => ty::Covariant,
374 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
375 (ty::Covariant, ty::Invariant) => ty::Invariant,
376 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
378 // Figure 1, column 2.
379 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
380 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
381 (ty::Contravariant, ty::Invariant) => ty::Invariant,
382 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
384 // Figure 1, column 3.
385 (ty::Invariant, _) => ty::Invariant,
387 // Figure 1, column 4.
388 (ty::Bivariant, _) => ty::Bivariant,
393 #[derive(Clone, Copy, Debug, RustcDecodable, RustcEncodable)]
394 pub struct MethodCallee<'tcx> {
395 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
398 pub substs: &'tcx Substs<'tcx>
401 /// With method calls, we store some extra information in
402 /// side tables (i.e method_map). We use
403 /// MethodCall as a key to index into these tables instead of
404 /// just directly using the expression's NodeId. The reason
405 /// for this being that we may apply adjustments (coercions)
406 /// with the resulting expression also needing to use the
407 /// side tables. The problem with this is that we don't
408 /// assign a separate NodeId to this new expression
409 /// and so it would clash with the base expression if both
410 /// needed to add to the side tables. Thus to disambiguate
411 /// we also keep track of whether there's an adjustment in
413 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
414 pub struct MethodCall {
420 pub fn expr(id: NodeId) -> MethodCall {
427 pub fn autoderef(expr_id: NodeId, autoderef: u32) -> MethodCall {
430 autoderef: 1 + autoderef
435 // maps from an expression id that corresponds to a method call to the details
436 // of the method to be invoked
437 pub type MethodMap<'tcx> = FxHashMap<MethodCall, MethodCallee<'tcx>>;
439 // Contains information needed to resolve types and (in the future) look up
440 // the types of AST nodes.
441 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
442 pub struct CReaderCacheKey {
447 /// Describes the fragment-state associated with a NodeId.
449 /// Currently only unfragmented paths have entries in the table,
450 /// but longer-term this enum is expected to expand to also
451 /// include data for fragmented paths.
452 #[derive(Copy, Clone, Debug)]
453 pub enum FragmentInfo {
454 Moved { var: NodeId, move_expr: NodeId },
455 Assigned { var: NodeId, assign_expr: NodeId, assignee_id: NodeId },
458 // Flags that we track on types. These flags are propagated upwards
459 // through the type during type construction, so that we can quickly
460 // check whether the type has various kinds of types in it without
461 // recursing over the type itself.
463 flags TypeFlags: u32 {
464 const HAS_PARAMS = 1 << 0,
465 const HAS_SELF = 1 << 1,
466 const HAS_TY_INFER = 1 << 2,
467 const HAS_RE_INFER = 1 << 3,
468 const HAS_RE_SKOL = 1 << 4,
469 const HAS_RE_EARLY_BOUND = 1 << 5,
470 const HAS_FREE_REGIONS = 1 << 6,
471 const HAS_TY_ERR = 1 << 7,
472 const HAS_PROJECTION = 1 << 8,
473 const HAS_TY_CLOSURE = 1 << 9,
475 // true if there are "names" of types and regions and so forth
476 // that are local to a particular fn
477 const HAS_LOCAL_NAMES = 1 << 10,
479 // Present if the type belongs in a local type context.
480 // Only set for TyInfer other than Fresh.
481 const KEEP_IN_LOCAL_TCX = 1 << 11,
483 // Is there a projection that does not involve a bound region?
484 // Currently we can't normalize projections w/ bound regions.
485 const HAS_NORMALIZABLE_PROJECTION = 1 << 12,
487 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
488 TypeFlags::HAS_SELF.bits |
489 TypeFlags::HAS_RE_EARLY_BOUND.bits,
491 // Flags representing the nominal content of a type,
492 // computed by FlagsComputation. If you add a new nominal
493 // flag, it should be added here too.
494 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
495 TypeFlags::HAS_SELF.bits |
496 TypeFlags::HAS_TY_INFER.bits |
497 TypeFlags::HAS_RE_INFER.bits |
498 TypeFlags::HAS_RE_SKOL.bits |
499 TypeFlags::HAS_RE_EARLY_BOUND.bits |
500 TypeFlags::HAS_FREE_REGIONS.bits |
501 TypeFlags::HAS_TY_ERR.bits |
502 TypeFlags::HAS_PROJECTION.bits |
503 TypeFlags::HAS_TY_CLOSURE.bits |
504 TypeFlags::HAS_LOCAL_NAMES.bits |
505 TypeFlags::KEEP_IN_LOCAL_TCX.bits,
507 // Caches for type_is_sized, type_moves_by_default
508 const SIZEDNESS_CACHED = 1 << 16,
509 const IS_SIZED = 1 << 17,
510 const MOVENESS_CACHED = 1 << 18,
511 const MOVES_BY_DEFAULT = 1 << 19,
512 const FREEZENESS_CACHED = 1 << 20,
513 const IS_FREEZE = 1 << 21,
514 const NEEDS_DROP_CACHED = 1 << 22,
515 const NEEDS_DROP = 1 << 23,
519 pub struct TyS<'tcx> {
520 pub sty: TypeVariants<'tcx>,
521 pub flags: Cell<TypeFlags>,
523 // the maximal depth of any bound regions appearing in this type.
527 impl<'tcx> PartialEq for TyS<'tcx> {
529 fn eq(&self, other: &TyS<'tcx>) -> bool {
530 // (self as *const _) == (other as *const _)
531 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
534 impl<'tcx> Eq for TyS<'tcx> {}
536 impl<'tcx> Hash for TyS<'tcx> {
537 fn hash<H: Hasher>(&self, s: &mut H) {
538 (self as *const TyS).hash(s)
542 impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::TyS<'tcx> {
543 fn hash_stable<W: StableHasherResult>(&self,
544 hcx: &mut StableHashingContext<'a, 'tcx>,
545 hasher: &mut StableHasher<W>) {
549 // The other fields just provide fast access to information that is
550 // also contained in `sty`, so no need to hash them.
555 sty.hash_stable(hcx, hasher);
559 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
561 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
562 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
564 /// A wrapper for slices with the additional invariant
565 /// that the slice is interned and no other slice with
566 /// the same contents can exist in the same context.
567 /// This means we can use pointer + length for both
568 /// equality comparisons and hashing.
569 #[derive(Debug, RustcEncodable)]
570 pub struct Slice<T>([T]);
572 impl<T> PartialEq for Slice<T> {
574 fn eq(&self, other: &Slice<T>) -> bool {
575 (&self.0 as *const [T]) == (&other.0 as *const [T])
578 impl<T> Eq for Slice<T> {}
580 impl<T> Hash for Slice<T> {
581 fn hash<H: Hasher>(&self, s: &mut H) {
582 (self.as_ptr(), self.len()).hash(s)
586 impl<T> Deref for Slice<T> {
588 fn deref(&self) -> &[T] {
593 impl<'a, T> IntoIterator for &'a Slice<T> {
595 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
596 fn into_iter(self) -> Self::IntoIter {
601 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
604 pub fn empty<'a>() -> &'a Slice<T> {
606 mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
611 /// Upvars do not get their own node-id. Instead, we use the pair of
612 /// the original var id (that is, the root variable that is referenced
613 /// by the upvar) and the id of the closure expression.
614 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
617 pub closure_expr_id: NodeId,
620 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
621 pub enum BorrowKind {
622 /// Data must be immutable and is aliasable.
625 /// Data must be immutable but not aliasable. This kind of borrow
626 /// cannot currently be expressed by the user and is used only in
627 /// implicit closure bindings. It is needed when the closure
628 /// is borrowing or mutating a mutable referent, e.g.:
630 /// let x: &mut isize = ...;
631 /// let y = || *x += 5;
633 /// If we were to try to translate this closure into a more explicit
634 /// form, we'd encounter an error with the code as written:
636 /// struct Env { x: & &mut isize }
637 /// let x: &mut isize = ...;
638 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
639 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
641 /// This is then illegal because you cannot mutate a `&mut` found
642 /// in an aliasable location. To solve, you'd have to translate with
643 /// an `&mut` borrow:
645 /// struct Env { x: & &mut isize }
646 /// let x: &mut isize = ...;
647 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
648 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
650 /// Now the assignment to `**env.x` is legal, but creating a
651 /// mutable pointer to `x` is not because `x` is not mutable. We
652 /// could fix this by declaring `x` as `let mut x`. This is ok in
653 /// user code, if awkward, but extra weird for closures, since the
654 /// borrow is hidden.
656 /// So we introduce a "unique imm" borrow -- the referent is
657 /// immutable, but not aliasable. This solves the problem. For
658 /// simplicity, we don't give users the way to express this
659 /// borrow, it's just used when translating closures.
662 /// Data is mutable and not aliasable.
666 /// Information describing the capture of an upvar. This is computed
667 /// during `typeck`, specifically by `regionck`.
668 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
669 pub enum UpvarCapture<'tcx> {
670 /// Upvar is captured by value. This is always true when the
671 /// closure is labeled `move`, but can also be true in other cases
672 /// depending on inference.
675 /// Upvar is captured by reference.
676 ByRef(UpvarBorrow<'tcx>),
679 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
680 pub struct UpvarBorrow<'tcx> {
681 /// The kind of borrow: by-ref upvars have access to shared
682 /// immutable borrows, which are not part of the normal language
684 pub kind: BorrowKind,
686 /// Region of the resulting reference.
687 pub region: ty::Region<'tcx>,
690 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
692 #[derive(Copy, Clone)]
693 pub struct ClosureUpvar<'tcx> {
699 #[derive(Clone, Copy, PartialEq)]
700 pub enum IntVarValue {
702 UintType(ast::UintTy),
705 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
706 pub struct TypeParameterDef {
710 pub has_default: bool,
711 pub object_lifetime_default: ObjectLifetimeDefault,
713 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
714 /// on generic parameter `T`, asserts data behind the parameter
715 /// `T` won't be accessed during the parent type's `Drop` impl.
716 pub pure_wrt_drop: bool,
719 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
720 pub struct RegionParameterDef {
724 pub issue_32330: Option<ty::Issue32330>,
726 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
727 /// on generic parameter `'a`, asserts data of lifetime `'a`
728 /// won't be accessed during the parent type's `Drop` impl.
729 pub pure_wrt_drop: bool,
732 impl RegionParameterDef {
733 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
734 ty::EarlyBoundRegion {
741 pub fn to_bound_region(&self) -> ty::BoundRegion {
742 self.to_early_bound_region_data().to_bound_region()
746 impl ty::EarlyBoundRegion {
747 pub fn to_bound_region(&self) -> ty::BoundRegion {
748 ty::BoundRegion::BrNamed(self.def_id, self.name)
752 /// Information about the formal type/lifetime parameters associated
753 /// with an item or method. Analogous to hir::Generics.
754 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
755 pub struct Generics {
756 pub parent: Option<DefId>,
757 pub parent_regions: u32,
758 pub parent_types: u32,
759 pub regions: Vec<RegionParameterDef>,
760 pub types: Vec<TypeParameterDef>,
762 /// Reverse map to each `TypeParameterDef`'s `index` field, from
763 /// `def_id.index` (`def_id.krate` is the same as the item's).
764 pub type_param_to_index: BTreeMap<DefIndex, u32>,
770 pub fn parent_count(&self) -> usize {
771 self.parent_regions as usize + self.parent_types as usize
774 pub fn own_count(&self) -> usize {
775 self.regions.len() + self.types.len()
778 pub fn count(&self) -> usize {
779 self.parent_count() + self.own_count()
782 pub fn region_param(&self, param: &EarlyBoundRegion) -> &RegionParameterDef {
783 assert_eq!(self.parent_count(), 0);
784 &self.regions[param.index as usize - self.has_self as usize]
787 pub fn type_param(&self, param: &ParamTy) -> &TypeParameterDef {
788 assert_eq!(self.parent_count(), 0);
789 &self.types[param.idx as usize - self.has_self as usize - self.regions.len()]
793 /// Bounds on generics.
794 #[derive(Clone, Default)]
795 pub struct GenericPredicates<'tcx> {
796 pub parent: Option<DefId>,
797 pub predicates: Vec<Predicate<'tcx>>,
800 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
801 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
803 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
804 pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
805 -> InstantiatedPredicates<'tcx> {
806 let mut instantiated = InstantiatedPredicates::empty();
807 self.instantiate_into(tcx, &mut instantiated, substs);
810 pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
811 -> InstantiatedPredicates<'tcx> {
812 InstantiatedPredicates {
813 predicates: self.predicates.subst(tcx, substs)
817 fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
818 instantiated: &mut InstantiatedPredicates<'tcx>,
819 substs: &Substs<'tcx>) {
820 if let Some(def_id) = self.parent {
821 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
823 instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
826 pub fn instantiate_identity(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
827 -> InstantiatedPredicates<'tcx> {
828 let mut instantiated = InstantiatedPredicates::empty();
829 self.instantiate_identity_into(tcx, &mut instantiated);
833 fn instantiate_identity_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
834 instantiated: &mut InstantiatedPredicates<'tcx>) {
835 if let Some(def_id) = self.parent {
836 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
838 instantiated.predicates.extend(&self.predicates)
841 pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
842 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
843 -> InstantiatedPredicates<'tcx>
845 assert_eq!(self.parent, None);
846 InstantiatedPredicates {
847 predicates: self.predicates.iter().map(|pred| {
848 pred.subst_supertrait(tcx, poly_trait_ref)
854 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
855 pub enum Predicate<'tcx> {
856 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
857 /// the `Self` type of the trait reference and `A`, `B`, and `C`
858 /// would be the type parameters.
859 Trait(PolyTraitPredicate<'tcx>),
861 /// where `T1 == T2`.
862 Equate(PolyEquatePredicate<'tcx>),
865 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
868 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
870 /// where <T as TraitRef>::Name == X, approximately.
871 /// See `ProjectionPredicate` struct for details.
872 Projection(PolyProjectionPredicate<'tcx>),
875 WellFormed(Ty<'tcx>),
877 /// trait must be object-safe
880 /// No direct syntax. May be thought of as `where T : FnFoo<...>`
881 /// for some substitutions `...` and T being a closure type.
882 /// Satisfied (or refuted) once we know the closure's kind.
883 ClosureKind(DefId, ClosureKind),
886 Subtype(PolySubtypePredicate<'tcx>),
889 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
890 /// Performs a substitution suitable for going from a
891 /// poly-trait-ref to supertraits that must hold if that
892 /// poly-trait-ref holds. This is slightly different from a normal
893 /// substitution in terms of what happens with bound regions. See
894 /// lengthy comment below for details.
895 pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
896 trait_ref: &ty::PolyTraitRef<'tcx>)
897 -> ty::Predicate<'tcx>
899 // The interaction between HRTB and supertraits is not entirely
900 // obvious. Let me walk you (and myself) through an example.
902 // Let's start with an easy case. Consider two traits:
904 // trait Foo<'a> : Bar<'a,'a> { }
905 // trait Bar<'b,'c> { }
907 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
908 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
909 // knew that `Foo<'x>` (for any 'x) then we also know that
910 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
911 // normal substitution.
913 // In terms of why this is sound, the idea is that whenever there
914 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
915 // holds. So if there is an impl of `T:Foo<'a>` that applies to
916 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
919 // Another example to be careful of is this:
921 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
922 // trait Bar1<'b,'c> { }
924 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
925 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
926 // reason is similar to the previous example: any impl of
927 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
928 // basically we would want to collapse the bound lifetimes from
929 // the input (`trait_ref`) and the supertraits.
931 // To achieve this in practice is fairly straightforward. Let's
932 // consider the more complicated scenario:
934 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
935 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
936 // where both `'x` and `'b` would have a DB index of 1.
937 // The substitution from the input trait-ref is therefore going to be
938 // `'a => 'x` (where `'x` has a DB index of 1).
939 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
940 // early-bound parameter and `'b' is a late-bound parameter with a
942 // - If we replace `'a` with `'x` from the input, it too will have
943 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
944 // just as we wanted.
946 // There is only one catch. If we just apply the substitution `'a
947 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
948 // adjust the DB index because we substituting into a binder (it
949 // tries to be so smart...) resulting in `for<'x> for<'b>
950 // Bar1<'x,'b>` (we have no syntax for this, so use your
951 // imagination). Basically the 'x will have DB index of 2 and 'b
952 // will have DB index of 1. Not quite what we want. So we apply
953 // the substitution to the *contents* of the trait reference,
954 // rather than the trait reference itself (put another way, the
955 // substitution code expects equal binding levels in the values
956 // from the substitution and the value being substituted into, and
957 // this trick achieves that).
959 let substs = &trait_ref.0.substs;
961 Predicate::Trait(ty::Binder(ref data)) =>
962 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
963 Predicate::Equate(ty::Binder(ref data)) =>
964 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
965 Predicate::Subtype(ty::Binder(ref data)) =>
966 Predicate::Subtype(ty::Binder(data.subst(tcx, substs))),
967 Predicate::RegionOutlives(ty::Binder(ref data)) =>
968 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
969 Predicate::TypeOutlives(ty::Binder(ref data)) =>
970 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
971 Predicate::Projection(ty::Binder(ref data)) =>
972 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
973 Predicate::WellFormed(data) =>
974 Predicate::WellFormed(data.subst(tcx, substs)),
975 Predicate::ObjectSafe(trait_def_id) =>
976 Predicate::ObjectSafe(trait_def_id),
977 Predicate::ClosureKind(closure_def_id, kind) =>
978 Predicate::ClosureKind(closure_def_id, kind),
983 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
984 pub struct TraitPredicate<'tcx> {
985 pub trait_ref: TraitRef<'tcx>
987 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
989 impl<'tcx> TraitPredicate<'tcx> {
990 pub fn def_id(&self) -> DefId {
991 self.trait_ref.def_id
994 /// Creates the dep-node for selecting/evaluating this trait reference.
995 fn dep_node(&self) -> DepNode<DefId> {
996 // Extact the trait-def and first def-id from inputs. See the
997 // docs for `DepNode::TraitSelect` for more information.
998 let trait_def_id = self.def_id();
1001 .flat_map(|t| t.walk())
1002 .filter_map(|t| match t.sty {
1003 ty::TyAdt(adt_def, _) => Some(adt_def.did),
1007 .unwrap_or(trait_def_id);
1008 DepNode::TraitSelect {
1009 trait_def_id: trait_def_id,
1010 input_def_id: input_def_id
1014 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
1015 self.trait_ref.input_types()
1018 pub fn self_ty(&self) -> Ty<'tcx> {
1019 self.trait_ref.self_ty()
1023 impl<'tcx> PolyTraitPredicate<'tcx> {
1024 pub fn def_id(&self) -> DefId {
1025 // ok to skip binder since trait def-id does not care about regions
1029 pub fn dep_node(&self) -> DepNode<DefId> {
1030 // ok to skip binder since depnode does not care about regions
1035 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1036 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
1037 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
1039 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1040 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
1041 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
1042 pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<ty::Region<'tcx>,
1044 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1046 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1047 pub struct SubtypePredicate<'tcx> {
1048 pub a_is_expected: bool,
1052 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1054 /// This kind of predicate has no *direct* correspondent in the
1055 /// syntax, but it roughly corresponds to the syntactic forms:
1057 /// 1. `T : TraitRef<..., Item=Type>`
1058 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1060 /// In particular, form #1 is "desugared" to the combination of a
1061 /// normal trait predicate (`T : TraitRef<...>`) and one of these
1062 /// predicates. Form #2 is a broader form in that it also permits
1063 /// equality between arbitrary types. Processing an instance of Form
1064 /// #2 eventually yields one of these `ProjectionPredicate`
1065 /// instances to normalize the LHS.
1066 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1067 pub struct ProjectionPredicate<'tcx> {
1068 pub projection_ty: ProjectionTy<'tcx>,
1072 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1074 impl<'tcx> PolyProjectionPredicate<'tcx> {
1075 pub fn item_name(&self) -> Name {
1076 self.0.projection_ty.item_name // safe to skip the binder to access a name
1080 pub trait ToPolyTraitRef<'tcx> {
1081 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1084 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1085 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1086 assert!(!self.has_escaping_regions());
1087 ty::Binder(self.clone())
1091 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1092 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1093 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1097 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
1098 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1099 // Note: unlike with TraitRef::to_poly_trait_ref(),
1100 // self.0.trait_ref is permitted to have escaping regions.
1101 // This is because here `self` has a `Binder` and so does our
1102 // return value, so we are preserving the number of binding
1104 ty::Binder(self.0.projection_ty.trait_ref)
1108 pub trait ToPredicate<'tcx> {
1109 fn to_predicate(&self) -> Predicate<'tcx>;
1112 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1113 fn to_predicate(&self) -> Predicate<'tcx> {
1114 // we're about to add a binder, so let's check that we don't
1115 // accidentally capture anything, or else that might be some
1116 // weird debruijn accounting.
1117 assert!(!self.has_escaping_regions());
1119 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1120 trait_ref: self.clone()
1125 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1126 fn to_predicate(&self) -> Predicate<'tcx> {
1127 ty::Predicate::Trait(self.to_poly_trait_predicate())
1131 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
1132 fn to_predicate(&self) -> Predicate<'tcx> {
1133 Predicate::Equate(self.clone())
1137 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1138 fn to_predicate(&self) -> Predicate<'tcx> {
1139 Predicate::RegionOutlives(self.clone())
1143 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1144 fn to_predicate(&self) -> Predicate<'tcx> {
1145 Predicate::TypeOutlives(self.clone())
1149 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1150 fn to_predicate(&self) -> Predicate<'tcx> {
1151 Predicate::Projection(self.clone())
1155 impl<'tcx> Predicate<'tcx> {
1156 /// Iterates over the types in this predicate. Note that in all
1157 /// cases this is skipping over a binder, so late-bound regions
1158 /// with depth 0 are bound by the predicate.
1159 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1160 let vec: Vec<_> = match *self {
1161 ty::Predicate::Trait(ref data) => {
1162 data.skip_binder().input_types().collect()
1164 ty::Predicate::Equate(ty::Binder(ref data)) => {
1165 vec![data.0, data.1]
1167 ty::Predicate::Subtype(ty::Binder(SubtypePredicate { a, b, a_is_expected: _ })) => {
1170 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1173 ty::Predicate::RegionOutlives(..) => {
1176 ty::Predicate::Projection(ref data) => {
1177 let trait_inputs = data.0.projection_ty.trait_ref.input_types();
1178 trait_inputs.chain(Some(data.0.ty)).collect()
1180 ty::Predicate::WellFormed(data) => {
1183 ty::Predicate::ObjectSafe(_trait_def_id) => {
1186 ty::Predicate::ClosureKind(_closure_def_id, _kind) => {
1191 // The only reason to collect into a vector here is that I was
1192 // too lazy to make the full (somewhat complicated) iterator
1193 // type that would be needed here. But I wanted this fn to
1194 // return an iterator conceptually, rather than a `Vec`, so as
1195 // to be closer to `Ty::walk`.
1199 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1201 Predicate::Trait(ref t) => {
1202 Some(t.to_poly_trait_ref())
1204 Predicate::Projection(..) |
1205 Predicate::Equate(..) |
1206 Predicate::Subtype(..) |
1207 Predicate::RegionOutlives(..) |
1208 Predicate::WellFormed(..) |
1209 Predicate::ObjectSafe(..) |
1210 Predicate::ClosureKind(..) |
1211 Predicate::TypeOutlives(..) => {
1218 /// Represents the bounds declared on a particular set of type
1219 /// parameters. Should eventually be generalized into a flag list of
1220 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
1221 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1222 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1223 /// the `GenericPredicates` are expressed in terms of the bound type
1224 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1225 /// represented a set of bounds for some particular instantiation,
1226 /// meaning that the generic parameters have been substituted with
1231 /// struct Foo<T,U:Bar<T>> { ... }
1233 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1234 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1235 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1236 /// [usize:Bar<isize>]]`.
1238 pub struct InstantiatedPredicates<'tcx> {
1239 pub predicates: Vec<Predicate<'tcx>>,
1242 impl<'tcx> InstantiatedPredicates<'tcx> {
1243 pub fn empty() -> InstantiatedPredicates<'tcx> {
1244 InstantiatedPredicates { predicates: vec![] }
1247 pub fn is_empty(&self) -> bool {
1248 self.predicates.is_empty()
1252 /// When type checking, we use the `ParameterEnvironment` to track
1253 /// details about the type/lifetime parameters that are in scope.
1254 /// It primarily stores the bounds information.
1256 /// Note: This information might seem to be redundant with the data in
1257 /// `tcx.ty_param_defs`, but it is not. That table contains the
1258 /// parameter definitions from an "outside" perspective, but this
1259 /// struct will contain the bounds for a parameter as seen from inside
1260 /// the function body. Currently the only real distinction is that
1261 /// bound lifetime parameters are replaced with free ones, but in the
1262 /// future I hope to refine the representation of types so as to make
1263 /// more distinctions clearer.
1265 pub struct ParameterEnvironment<'tcx> {
1266 /// Obligations that the caller must satisfy. This is basically
1267 /// the set of bounds on the in-scope type parameters, translated
1268 /// into Obligations, and elaborated and normalized.
1269 pub caller_bounds: &'tcx [ty::Predicate<'tcx>],
1271 /// A cache for `moves_by_default`.
1272 pub is_copy_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
1274 /// A cache for `type_is_sized`
1275 pub is_sized_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
1277 /// A cache for `type_is_freeze`
1278 pub is_freeze_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
1281 impl<'a, 'tcx> ParameterEnvironment<'tcx> {
1282 pub fn with_caller_bounds(&self,
1283 caller_bounds: &'tcx [ty::Predicate<'tcx>])
1284 -> ParameterEnvironment<'tcx>
1286 ParameterEnvironment {
1287 caller_bounds: caller_bounds,
1288 is_copy_cache: RefCell::new(FxHashMap()),
1289 is_sized_cache: RefCell::new(FxHashMap()),
1290 is_freeze_cache: RefCell::new(FxHashMap()),
1295 #[derive(Copy, Clone, Debug)]
1296 pub struct Destructor {
1297 /// The def-id of the destructor method
1302 flags AdtFlags: u32 {
1303 const NO_ADT_FLAGS = 0,
1304 const IS_ENUM = 1 << 0,
1305 const IS_PHANTOM_DATA = 1 << 1,
1306 const IS_FUNDAMENTAL = 1 << 2,
1307 const IS_UNION = 1 << 3,
1308 const IS_BOX = 1 << 4,
1313 pub struct VariantDef {
1314 /// The variant's DefId. If this is a tuple-like struct,
1315 /// this is the DefId of the struct's ctor.
1317 pub name: Name, // struct's name if this is a struct
1318 pub discr: VariantDiscr,
1319 pub fields: Vec<FieldDef>,
1320 pub ctor_kind: CtorKind,
1323 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1324 pub enum VariantDiscr {
1325 /// Explicit value for this variant, i.e. `X = 123`.
1326 /// The `DefId` corresponds to the embedded constant.
1329 /// The previous variant's discriminant plus one.
1330 /// For efficiency reasons, the distance from the
1331 /// last `Explicit` discriminant is being stored,
1332 /// or `0` for the first variant, if it has none.
1337 pub struct FieldDef {
1340 pub vis: Visibility,
1343 /// The definition of an abstract data type - a struct or enum.
1345 /// These are all interned (by intern_adt_def) into the adt_defs
1349 pub variants: Vec<VariantDef>,
1351 pub repr: ReprOptions,
1354 impl PartialEq for AdtDef {
1355 // AdtDef are always interned and this is part of TyS equality
1357 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1360 impl Eq for AdtDef {}
1362 impl Hash for AdtDef {
1364 fn hash<H: Hasher>(&self, s: &mut H) {
1365 (self as *const AdtDef).hash(s)
1369 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1370 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1375 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1378 impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for AdtDef {
1379 fn hash_stable<W: StableHasherResult>(&self,
1380 hcx: &mut StableHashingContext<'a, 'tcx>,
1381 hasher: &mut StableHasher<W>) {
1389 did.hash_stable(hcx, hasher);
1390 variants.hash_stable(hcx, hasher);
1391 flags.hash_stable(hcx, hasher);
1392 repr.hash_stable(hcx, hasher);
1396 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1397 pub enum AdtKind { Struct, Union, Enum }
1400 #[derive(RustcEncodable, RustcDecodable, Default)]
1401 flags ReprFlags: u8 {
1402 const IS_C = 1 << 0,
1403 const IS_PACKED = 1 << 1,
1404 const IS_SIMD = 1 << 2,
1405 // Internal only for now. If true, don't reorder fields.
1406 const IS_LINEAR = 1 << 3,
1408 // Any of these flags being set prevent field reordering optimisation.
1409 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1410 ReprFlags::IS_PACKED.bits |
1411 ReprFlags::IS_SIMD.bits |
1412 ReprFlags::IS_LINEAR.bits,
1416 impl_stable_hash_for!(struct ReprFlags {
1422 /// Represents the repr options provided by the user,
1423 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1424 pub struct ReprOptions {
1425 pub int: Option<attr::IntType>,
1427 pub flags: ReprFlags,
1430 impl_stable_hash_for!(struct ReprOptions {
1437 pub fn new(tcx: TyCtxt, did: DefId) -> ReprOptions {
1438 let mut flags = ReprFlags::empty();
1439 let mut size = None;
1440 let mut max_align = 0;
1441 for attr in tcx.get_attrs(did).iter() {
1442 for r in attr::find_repr_attrs(tcx.sess.diagnostic(), attr) {
1443 flags.insert(match r {
1444 attr::ReprExtern => ReprFlags::IS_C,
1445 attr::ReprPacked => ReprFlags::IS_PACKED,
1446 attr::ReprSimd => ReprFlags::IS_SIMD,
1447 attr::ReprInt(i) => {
1451 attr::ReprAlign(align) => {
1452 max_align = cmp::max(align, max_align);
1459 // FIXME(eddyb) This is deprecated and should be removed.
1460 if tcx.has_attr(did, "simd") {
1461 flags.insert(ReprFlags::IS_SIMD);
1464 // This is here instead of layout because the choice must make it into metadata.
1465 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.item_path_str(did))) {
1466 flags.insert(ReprFlags::IS_LINEAR);
1468 ReprOptions { int: size, align: max_align, flags: flags }
1472 pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
1474 pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
1476 pub fn packed(&self) -> bool { self.flags.contains(ReprFlags::IS_PACKED) }
1478 pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
1480 pub fn discr_type(&self) -> attr::IntType {
1481 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Is))
1484 /// Returns true if this `#[repr()]` should inhabit "smart enum
1485 /// layout" optimizations, such as representing `Foo<&T>` as a
1487 pub fn inhibit_enum_layout_opt(&self) -> bool {
1488 self.c() || self.int.is_some()
1492 impl<'a, 'gcx, 'tcx> AdtDef {
1496 variants: Vec<VariantDef>,
1497 repr: ReprOptions) -> Self {
1498 let mut flags = AdtFlags::NO_ADT_FLAGS;
1499 let attrs = tcx.get_attrs(did);
1500 if attr::contains_name(&attrs, "fundamental") {
1501 flags = flags | AdtFlags::IS_FUNDAMENTAL;
1503 if Some(did) == tcx.lang_items.phantom_data() {
1504 flags = flags | AdtFlags::IS_PHANTOM_DATA;
1506 if Some(did) == tcx.lang_items.owned_box() {
1507 flags = flags | AdtFlags::IS_BOX;
1510 AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1511 AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1512 AdtKind::Struct => {}
1523 pub fn is_struct(&self) -> bool {
1524 !self.is_union() && !self.is_enum()
1528 pub fn is_union(&self) -> bool {
1529 self.flags.intersects(AdtFlags::IS_UNION)
1533 pub fn is_enum(&self) -> bool {
1534 self.flags.intersects(AdtFlags::IS_ENUM)
1537 /// Returns the kind of the ADT - Struct or Enum.
1539 pub fn adt_kind(&self) -> AdtKind {
1542 } else if self.is_union() {
1549 pub fn descr(&self) -> &'static str {
1550 match self.adt_kind() {
1551 AdtKind::Struct => "struct",
1552 AdtKind::Union => "union",
1553 AdtKind::Enum => "enum",
1557 pub fn variant_descr(&self) -> &'static str {
1558 match self.adt_kind() {
1559 AdtKind::Struct => "struct",
1560 AdtKind::Union => "union",
1561 AdtKind::Enum => "variant",
1565 /// Returns whether this type is #[fundamental] for the purposes
1566 /// of coherence checking.
1568 pub fn is_fundamental(&self) -> bool {
1569 self.flags.intersects(AdtFlags::IS_FUNDAMENTAL)
1572 /// Returns true if this is PhantomData<T>.
1574 pub fn is_phantom_data(&self) -> bool {
1575 self.flags.intersects(AdtFlags::IS_PHANTOM_DATA)
1578 /// Returns true if this is Box<T>.
1580 pub fn is_box(&self) -> bool {
1581 self.flags.intersects(AdtFlags::IS_BOX)
1584 /// Returns whether this type has a destructor.
1585 pub fn has_dtor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1586 self.destructor(tcx).is_some()
1589 /// Asserts this is a struct and returns the struct's unique
1591 pub fn struct_variant(&self) -> &VariantDef {
1592 assert!(!self.is_enum());
1597 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1598 tcx.predicates_of(self.did)
1601 /// Returns an iterator over all fields contained
1604 pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1605 self.variants.iter().flat_map(|v| v.fields.iter())
1609 pub fn is_univariant(&self) -> bool {
1610 self.variants.len() == 1
1613 pub fn is_payloadfree(&self) -> bool {
1614 !self.variants.is_empty() &&
1615 self.variants.iter().all(|v| v.fields.is_empty())
1618 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1621 .find(|v| v.did == vid)
1622 .expect("variant_with_id: unknown variant")
1625 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1628 .position(|v| v.did == vid)
1629 .expect("variant_index_with_id: unknown variant")
1632 pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1634 Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1635 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1636 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.struct_variant(),
1637 _ => bug!("unexpected def {:?} in variant_of_def", def)
1642 pub fn discriminants(&'a self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
1643 -> impl Iterator<Item=ConstInt> + 'a {
1644 let repr_type = self.repr.discr_type();
1645 let initial = repr_type.initial_discriminant(tcx.global_tcx());
1646 let mut prev_discr = None::<ConstInt>;
1647 self.variants.iter().map(move |v| {
1648 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr());
1649 if let VariantDiscr::Explicit(expr_did) = v.discr {
1650 let substs = Substs::empty();
1651 match tcx.const_eval((expr_did, substs)) {
1652 Ok(ConstVal::Integral(v)) => {
1656 if !expr_did.is_local() {
1657 span_bug!(tcx.def_span(expr_did),
1658 "variant discriminant evaluation succeeded \
1659 in its crate but failed locally: {:?}", err);
1664 prev_discr = Some(discr);
1670 /// Compute the discriminant value used by a specific variant.
1671 /// Unlike `discriminants`, this is (amortized) constant-time,
1672 /// only doing at most one query for evaluating an explicit
1673 /// discriminant (the last one before the requested variant),
1674 /// assuming there are no constant-evaluation errors there.
1675 pub fn discriminant_for_variant(&self,
1676 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1677 variant_index: usize)
1679 let repr_type = self.repr.discr_type();
1680 let mut explicit_value = repr_type.initial_discriminant(tcx.global_tcx());
1681 let mut explicit_index = variant_index;
1683 match self.variants[explicit_index].discr {
1684 ty::VariantDiscr::Relative(0) => break,
1685 ty::VariantDiscr::Relative(distance) => {
1686 explicit_index -= distance;
1688 ty::VariantDiscr::Explicit(expr_did) => {
1689 let substs = Substs::empty();
1690 match tcx.const_eval((expr_did, substs)) {
1691 Ok(ConstVal::Integral(v)) => {
1696 if !expr_did.is_local() {
1697 span_bug!(tcx.def_span(expr_did),
1698 "variant discriminant evaluation succeeded \
1699 in its crate but failed locally: {:?}", err);
1701 if explicit_index == 0 {
1704 explicit_index -= 1;
1710 let discr = explicit_value.to_u128_unchecked()
1711 .wrapping_add((variant_index - explicit_index) as u128);
1713 attr::UnsignedInt(ty) => {
1714 ConstInt::new_unsigned_truncating(discr, ty,
1715 tcx.sess.target.uint_type)
1717 attr::SignedInt(ty) => {
1718 ConstInt::new_signed_truncating(discr as i128, ty,
1719 tcx.sess.target.int_type)
1724 pub fn destructor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Destructor> {
1725 tcx.adt_destructor(self.did)
1728 /// Returns a list of types such that `Self: Sized` if and only
1729 /// if that type is Sized, or `TyErr` if this type is recursive.
1731 /// Oddly enough, checking that the sized-constraint is Sized is
1732 /// actually more expressive than checking all members:
1733 /// the Sized trait is inductive, so an associated type that references
1734 /// Self would prevent its containing ADT from being Sized.
1736 /// Due to normalization being eager, this applies even if
1737 /// the associated type is behind a pointer, e.g. issue #31299.
1738 pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] {
1739 match queries::adt_sized_constraint::try_get(tcx, DUMMY_SP, self.did) {
1742 debug!("adt_sized_constraint: {:?} is recursive", self);
1743 // This should be reported as an error by `check_representable`.
1745 // Consider the type as Sized in the meanwhile to avoid
1747 tcx.intern_type_list(&[tcx.types.err])
1752 fn sized_constraint_for_ty(&self,
1753 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1756 let result = match ty.sty {
1757 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
1758 TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
1759 TyArray(..) | TyClosure(..) | TyNever => {
1763 TyStr | TyDynamic(..) | TySlice(_) | TyError => {
1764 // these are never sized - return the target type
1768 TyTuple(ref tys, _) => {
1771 Some(ty) => self.sized_constraint_for_ty(tcx, ty)
1775 TyAdt(adt, substs) => {
1777 let adt_tys = adt.sized_constraint(tcx);
1778 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
1781 .map(|ty| ty.subst(tcx, substs))
1782 .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
1786 TyProjection(..) | TyAnon(..) => {
1787 // must calculate explicitly.
1788 // FIXME: consider special-casing always-Sized projections
1793 // perf hack: if there is a `T: Sized` bound, then
1794 // we know that `T` is Sized and do not need to check
1797 let sized_trait = match tcx.lang_items.sized_trait() {
1799 _ => return vec![ty]
1801 let sized_predicate = Binder(TraitRef {
1802 def_id: sized_trait,
1803 substs: tcx.mk_substs_trait(ty, &[])
1805 let predicates = tcx.predicates_of(self.did).predicates;
1806 if predicates.into_iter().any(|p| p == sized_predicate) {
1814 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
1818 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
1823 impl<'a, 'gcx, 'tcx> VariantDef {
1825 pub fn find_field_named(&self,
1827 -> Option<&FieldDef> {
1828 self.fields.iter().find(|f| f.name == name)
1832 pub fn index_of_field_named(&self,
1835 self.fields.iter().position(|f| f.name == name)
1839 pub fn field_named(&self, name: ast::Name) -> &FieldDef {
1840 self.find_field_named(name).unwrap()
1844 impl<'a, 'gcx, 'tcx> FieldDef {
1845 pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1846 tcx.type_of(self.did).subst(tcx, subst)
1850 /// Records the substitutions used to translate the polytype for an
1851 /// item into the monotype of an item reference.
1852 #[derive(Clone, RustcEncodable, RustcDecodable)]
1853 pub struct ItemSubsts<'tcx> {
1854 pub substs: &'tcx Substs<'tcx>,
1857 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1858 pub enum ClosureKind {
1859 // Warning: Ordering is significant here! The ordering is chosen
1860 // because the trait Fn is a subtrait of FnMut and so in turn, and
1861 // hence we order it so that Fn < FnMut < FnOnce.
1867 impl<'a, 'tcx> ClosureKind {
1868 pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
1870 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
1871 ClosureKind::FnMut => {
1872 tcx.require_lang_item(FnMutTraitLangItem)
1874 ClosureKind::FnOnce => {
1875 tcx.require_lang_item(FnOnceTraitLangItem)
1880 /// True if this a type that impls this closure kind
1881 /// must also implement `other`.
1882 pub fn extends(self, other: ty::ClosureKind) -> bool {
1883 match (self, other) {
1884 (ClosureKind::Fn, ClosureKind::Fn) => true,
1885 (ClosureKind::Fn, ClosureKind::FnMut) => true,
1886 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
1887 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
1888 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
1889 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
1895 impl<'tcx> TyS<'tcx> {
1896 /// Iterator that walks `self` and any types reachable from
1897 /// `self`, in depth-first order. Note that just walks the types
1898 /// that appear in `self`, it does not descend into the fields of
1899 /// structs or variants. For example:
1902 /// isize => { isize }
1903 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
1904 /// [isize] => { [isize], isize }
1906 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
1907 TypeWalker::new(self)
1910 /// Iterator that walks the immediate children of `self`. Hence
1911 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
1912 /// (but not `i32`, like `walk`).
1913 pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
1914 walk::walk_shallow(self)
1917 /// Walks `ty` and any types appearing within `ty`, invoking the
1918 /// callback `f` on each type. If the callback returns false, then the
1919 /// children of the current type are ignored.
1921 /// Note: prefer `ty.walk()` where possible.
1922 pub fn maybe_walk<F>(&'tcx self, mut f: F)
1923 where F : FnMut(Ty<'tcx>) -> bool
1925 let mut walker = self.walk();
1926 while let Some(ty) = walker.next() {
1928 walker.skip_current_subtree();
1934 impl<'tcx> ItemSubsts<'tcx> {
1935 pub fn is_noop(&self) -> bool {
1936 self.substs.is_noop()
1940 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1941 pub enum LvaluePreference {
1946 impl LvaluePreference {
1947 pub fn from_mutbl(m: hir::Mutability) -> Self {
1949 hir::MutMutable => PreferMutLvalue,
1950 hir::MutImmutable => NoPreference,
1956 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
1958 hir::MutMutable => MutBorrow,
1959 hir::MutImmutable => ImmBorrow,
1963 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
1964 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
1965 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
1967 pub fn to_mutbl_lossy(self) -> hir::Mutability {
1969 MutBorrow => hir::MutMutable,
1970 ImmBorrow => hir::MutImmutable,
1972 // We have no type corresponding to a unique imm borrow, so
1973 // use `&mut`. It gives all the capabilities of an `&uniq`
1974 // and hence is a safe "over approximation".
1975 UniqueImmBorrow => hir::MutMutable,
1979 pub fn to_user_str(&self) -> &'static str {
1981 MutBorrow => "mutable",
1982 ImmBorrow => "immutable",
1983 UniqueImmBorrow => "uniquely immutable",
1988 #[derive(Debug, Clone)]
1989 pub enum Attributes<'gcx> {
1990 Owned(Rc<[ast::Attribute]>),
1991 Borrowed(&'gcx [ast::Attribute])
1994 impl<'gcx> ::std::ops::Deref for Attributes<'gcx> {
1995 type Target = [ast::Attribute];
1997 fn deref(&self) -> &[ast::Attribute] {
1999 &Attributes::Owned(ref data) => &data,
2000 &Attributes::Borrowed(data) => data
2005 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2006 pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
2007 self.typeck_tables_of(self.hir.body_owner_def_id(body))
2010 /// Returns an iterator of the def-ids for all body-owners in this
2011 /// crate. If you would prefer to iterate over the bodies
2012 /// themselves, you can do `self.hir.krate().body_ids.iter()`.
2013 pub fn body_owners(self) -> impl Iterator<Item = DefId> + 'a {
2017 .map(move |&body_id| self.hir.body_owner_def_id(body_id))
2020 pub fn expr_span(self, id: NodeId) -> Span {
2021 match self.hir.find(id) {
2022 Some(hir_map::NodeExpr(e)) => {
2026 bug!("Node id {} is not an expr: {:?}", id, f);
2029 bug!("Node id {} is not present in the node map", id);
2034 pub fn local_var_name_str(self, id: NodeId) -> InternedString {
2035 match self.hir.find(id) {
2036 Some(hir_map::NodeLocal(pat)) => {
2038 hir::PatKind::Binding(_, _, ref path1, _) => path1.node.as_str(),
2040 bug!("Variable id {} maps to {:?}, not local", id, pat);
2044 r => bug!("Variable id {} maps to {:?}, not local", id, r),
2048 pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
2050 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
2052 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
2057 hir::ExprType(ref e, _) => {
2058 self.expr_is_lval(e)
2061 hir::ExprUnary(hir::UnDeref, _) |
2062 hir::ExprField(..) |
2063 hir::ExprTupField(..) |
2064 hir::ExprIndex(..) => {
2068 // Partially qualified paths in expressions can only legally
2069 // refer to associated items which are always rvalues.
2070 hir::ExprPath(hir::QPath::TypeRelative(..)) |
2073 hir::ExprMethodCall(..) |
2074 hir::ExprStruct(..) |
2077 hir::ExprMatch(..) |
2078 hir::ExprClosure(..) |
2079 hir::ExprBlock(..) |
2080 hir::ExprRepeat(..) |
2081 hir::ExprArray(..) |
2082 hir::ExprBreak(..) |
2083 hir::ExprAgain(..) |
2085 hir::ExprWhile(..) |
2087 hir::ExprAssign(..) |
2088 hir::ExprInlineAsm(..) |
2089 hir::ExprAssignOp(..) |
2091 hir::ExprUnary(..) |
2093 hir::ExprAddrOf(..) |
2094 hir::ExprBinary(..) |
2095 hir::ExprCast(..) => {
2101 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2102 self.associated_items(id)
2103 .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2107 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2108 self.associated_items(did).any(|item| {
2109 item.relevant_for_never()
2113 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssociatedItem> {
2114 let is_associated_item = if let Some(node_id) = self.hir.as_local_node_id(def_id) {
2115 match self.hir.get(node_id) {
2116 hir_map::NodeTraitItem(_) | hir_map::NodeImplItem(_) => true,
2120 match self.describe_def(def_id).expect("no def for def-id") {
2121 Def::AssociatedConst(_) | Def::Method(_) | Def::AssociatedTy(_) => true,
2126 if is_associated_item {
2127 Some(self.associated_item(def_id))
2133 fn associated_item_from_trait_item_ref(self,
2134 parent_def_id: DefId,
2135 parent_vis: &hir::Visibility,
2136 trait_item_ref: &hir::TraitItemRef)
2138 let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2139 let (kind, has_self) = match trait_item_ref.kind {
2140 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2141 hir::AssociatedItemKind::Method { has_self } => {
2142 (ty::AssociatedKind::Method, has_self)
2144 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2148 name: trait_item_ref.name,
2150 // Visibility of trait items is inherited from their traits.
2151 vis: Visibility::from_hir(parent_vis, trait_item_ref.id.node_id, self),
2152 defaultness: trait_item_ref.defaultness,
2154 container: TraitContainer(parent_def_id),
2155 method_has_self_argument: has_self
2159 fn associated_item_from_impl_item_ref(self,
2160 parent_def_id: DefId,
2161 impl_item_ref: &hir::ImplItemRef)
2163 let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2164 let (kind, has_self) = match impl_item_ref.kind {
2165 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2166 hir::AssociatedItemKind::Method { has_self } => {
2167 (ty::AssociatedKind::Method, has_self)
2169 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2172 ty::AssociatedItem {
2173 name: impl_item_ref.name,
2175 // Visibility of trait impl items doesn't matter.
2176 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.node_id, self),
2177 defaultness: impl_item_ref.defaultness,
2179 container: ImplContainer(parent_def_id),
2180 method_has_self_argument: has_self
2184 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2185 pub fn associated_items(self, def_id: DefId)
2186 -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2187 let def_ids = self.associated_item_def_ids(def_id);
2188 (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2191 /// Returns true if the impls are the same polarity and are implementing
2192 /// a trait which contains no items
2193 pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId) -> bool {
2194 if !self.sess.features.borrow().overlapping_marker_traits {
2197 let trait1_is_empty = self.impl_trait_ref(def_id1)
2198 .map_or(false, |trait_ref| {
2199 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2201 let trait2_is_empty = self.impl_trait_ref(def_id2)
2202 .map_or(false, |trait_ref| {
2203 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2205 self.impl_polarity(def_id1) == self.impl_polarity(def_id2)
2210 // Returns `ty::VariantDef` if `def` refers to a struct,
2211 // or variant or their constructors, panics otherwise.
2212 pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2214 Def::Variant(did) | Def::VariantCtor(did, ..) => {
2215 let enum_did = self.parent_def_id(did).unwrap();
2216 self.adt_def(enum_did).variant_with_id(did)
2218 Def::Struct(did) | Def::Union(did) => {
2219 self.adt_def(did).struct_variant()
2221 Def::StructCtor(ctor_did, ..) => {
2222 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2223 self.adt_def(did).struct_variant()
2225 _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2229 pub fn def_key(self, id: DefId) -> hir_map::DefKey {
2231 self.hir.def_key(id)
2233 self.sess.cstore.def_key(id)
2237 /// Convert a `DefId` into its fully expanded `DefPath` (every
2238 /// `DefId` is really just an interned def-path).
2240 /// Note that if `id` is not local to this crate, the result will
2241 /// be a non-local `DefPath`.
2242 pub fn def_path(self, id: DefId) -> hir_map::DefPath {
2244 self.hir.def_path(id)
2246 self.sess.cstore.def_path(id)
2251 pub fn def_path_hash(self, def_id: DefId) -> u64 {
2252 if def_id.is_local() {
2253 self.hir.definitions().def_path_hash(def_id.index)
2255 self.sess.cstore.def_path_hash(def_id)
2259 pub fn vis_is_accessible_from(self, vis: Visibility, block: NodeId) -> bool {
2260 vis.is_accessible_from(self.hir.local_def_id(self.hir.get_module_parent(block)), self)
2263 pub fn item_name(self, id: DefId) -> ast::Name {
2264 if let Some(id) = self.hir.as_local_node_id(id) {
2266 } else if id.index == CRATE_DEF_INDEX {
2267 self.sess.cstore.original_crate_name(id.krate)
2269 let def_key = self.sess.cstore.def_key(id);
2270 // The name of a StructCtor is that of its struct parent.
2271 if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2272 self.item_name(DefId {
2274 index: def_key.parent.unwrap()
2277 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2278 bug!("item_name: no name for {:?}", self.def_path(id));
2284 /// Return the possibly-auto-generated MIR of a (DefId, Subst) pair.
2285 pub fn instance_mir(self, instance: ty::InstanceDef<'gcx>)
2289 ty::InstanceDef::Item(did) => {
2290 self.optimized_mir(did)
2292 ty::InstanceDef::Intrinsic(..) |
2293 ty::InstanceDef::FnPtrShim(..) |
2294 ty::InstanceDef::Virtual(..) |
2295 ty::InstanceDef::ClosureOnceShim { .. } |
2296 ty::InstanceDef::DropGlue(..) => {
2297 self.mir_shims(instance)
2302 /// Given the DefId of an item, returns its MIR, borrowed immutably.
2303 /// Returns None if there is no MIR for the DefId
2304 pub fn maybe_optimized_mir(self, did: DefId) -> Option<&'gcx Mir<'gcx>> {
2305 if self.is_mir_available(did) {
2306 Some(self.optimized_mir(did))
2312 /// Get the attributes of a definition.
2313 pub fn get_attrs(self, did: DefId) -> Attributes<'gcx> {
2314 if let Some(id) = self.hir.as_local_node_id(did) {
2315 Attributes::Borrowed(self.hir.attrs(id))
2317 Attributes::Owned(self.item_attrs(did))
2321 /// Determine whether an item is annotated with an attribute
2322 pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2323 self.get_attrs(did).iter().any(|item| item.check_name(attr))
2326 pub fn trait_has_default_impl(self, trait_def_id: DefId) -> bool {
2327 let def = self.trait_def(trait_def_id);
2328 def.flags.get().intersects(TraitFlags::HAS_DEFAULT_IMPL)
2331 /// Populates the type context with all the implementations for the given
2332 /// trait if necessary.
2333 pub fn populate_implementations_for_trait_if_necessary(self, trait_id: DefId) {
2334 if trait_id.is_local() {
2338 // The type is not local, hence we are reading this out of
2339 // metadata and don't need to track edges.
2340 let _ignore = self.dep_graph.in_ignore();
2342 let def = self.trait_def(trait_id);
2343 if def.flags.get().intersects(TraitFlags::HAS_REMOTE_IMPLS) {
2347 debug!("populate_implementations_for_trait_if_necessary: searching for {:?}", def);
2349 for impl_def_id in self.sess.cstore.implementations_of_trait(Some(trait_id)) {
2350 let trait_ref = self.impl_trait_ref(impl_def_id).unwrap();
2352 // Record the trait->implementation mapping.
2353 let parent = self.impl_parent(impl_def_id).unwrap_or(trait_id);
2354 def.record_remote_impl(self, impl_def_id, trait_ref, parent);
2357 def.flags.set(def.flags.get() | TraitFlags::HAS_REMOTE_IMPLS);
2360 /// Given the def_id of an impl, return the def_id of the trait it implements.
2361 /// If it implements no trait, return `None`.
2362 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2363 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2366 /// If the given def ID describes a method belonging to an impl, return the
2367 /// ID of the impl that the method belongs to. Otherwise, return `None`.
2368 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2369 let item = if def_id.krate != LOCAL_CRATE {
2370 if let Some(Def::Method(_)) = self.describe_def(def_id) {
2371 Some(self.associated_item(def_id))
2376 self.opt_associated_item(def_id)
2380 Some(trait_item) => {
2381 match trait_item.container {
2382 TraitContainer(_) => None,
2383 ImplContainer(def_id) => Some(def_id),
2390 /// Construct a parameter environment suitable for static contexts or other contexts where there
2391 /// are no free type/lifetime parameters in scope.
2392 pub fn empty_parameter_environment(self) -> ParameterEnvironment<'tcx> {
2393 ty::ParameterEnvironment {
2394 caller_bounds: Slice::empty(),
2395 is_copy_cache: RefCell::new(FxHashMap()),
2396 is_sized_cache: RefCell::new(FxHashMap()),
2397 is_freeze_cache: RefCell::new(FxHashMap()),
2401 /// See `ParameterEnvironment` struct def'n for details.
2402 pub fn parameter_environment(self, def_id: DefId) -> ParameterEnvironment<'gcx> {
2404 // Compute the bounds on Self and the type parameters.
2407 let tcx = self.global_tcx();
2408 let bounds = tcx.predicates_of(def_id).instantiate_identity(tcx);
2409 let predicates = bounds.predicates;
2411 // Finally, we have to normalize the bounds in the environment, in
2412 // case they contain any associated type projections. This process
2413 // can yield errors if the put in illegal associated types, like
2414 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2415 // report these errors right here; this doesn't actually feel
2416 // right to me, because constructing the environment feels like a
2417 // kind of a "idempotent" action, but I'm not sure where would be
2418 // a better place. In practice, we construct environments for
2419 // every fn once during type checking, and we'll abort if there
2420 // are any errors at that point, so after type checking you can be
2421 // sure that this will succeed without errors anyway.
2424 let unnormalized_env = ty::ParameterEnvironment {
2425 caller_bounds: tcx.intern_predicates(&predicates),
2426 is_copy_cache: RefCell::new(FxHashMap()),
2427 is_sized_cache: RefCell::new(FxHashMap()),
2428 is_freeze_cache: RefCell::new(FxHashMap()),
2431 let body_id = self.hir.as_local_node_id(def_id).map_or(DUMMY_NODE_ID, |id| {
2432 self.hir.maybe_body_owned_by(id).map_or(id, |body| body.node_id)
2434 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
2435 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
2438 pub fn node_scope_region(self, id: NodeId) -> Region<'tcx> {
2439 self.mk_region(ty::ReScope(CodeExtent::Misc(id)))
2442 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2443 /// with the name of the crate containing the impl.
2444 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2445 if impl_did.is_local() {
2446 let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2447 Ok(self.hir.span(node_id))
2449 Err(self.sess.cstore.crate_name(impl_did.krate))
2454 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2455 pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2456 F: FnOnce(&[hir::Freevar]) -> T,
2458 match self.freevars.borrow().get(&fid) {
2460 Some(d) => f(&d[..])
2465 fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
2468 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2469 let parent_id = tcx.hir.get_parent(id);
2470 let parent_def_id = tcx.hir.local_def_id(parent_id);
2471 let parent_item = tcx.hir.expect_item(parent_id);
2472 match parent_item.node {
2473 hir::ItemImpl(.., ref impl_item_refs) => {
2474 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.node_id == id) {
2475 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
2477 debug_assert_eq!(assoc_item.def_id, def_id);
2482 hir::ItemTrait(.., ref trait_item_refs) => {
2483 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.node_id == id) {
2484 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
2487 debug_assert_eq!(assoc_item.def_id, def_id);
2495 span_bug!(parent_item.span,
2496 "unexpected parent of trait or impl item or item not found: {:?}",
2500 /// Calculates the Sized-constraint.
2502 /// In fact, there are only a few options for the types in the constraint:
2503 /// - an obviously-unsized type
2504 /// - a type parameter or projection whose Sizedness can't be known
2505 /// - a tuple of type parameters or projections, if there are multiple
2507 /// - a TyError, if a type contained itself. The representability
2508 /// check should catch this case.
2509 fn adt_sized_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2511 -> &'tcx [Ty<'tcx>] {
2512 let def = tcx.adt_def(def_id);
2514 let result = tcx.intern_type_list(&def.variants.iter().flat_map(|v| {
2517 def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
2518 }).collect::<Vec<_>>());
2520 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
2525 /// Calculates the dtorck constraint for a type.
2526 fn adt_dtorck_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2528 -> DtorckConstraint<'tcx> {
2529 let def = tcx.adt_def(def_id);
2530 let span = tcx.def_span(def_id);
2531 debug!("dtorck_constraint: {:?}", def);
2533 if def.is_phantom_data() {
2534 let result = DtorckConstraint {
2537 tcx.mk_param_from_def(&tcx.generics_of(def_id).types[0])
2540 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2544 let mut result = def.all_fields()
2545 .map(|field| tcx.type_of(field.did))
2546 .map(|fty| tcx.dtorck_constraint_for_ty(span, fty, 0, fty))
2547 .collect::<Result<DtorckConstraint, ErrorReported>>()
2548 .unwrap_or(DtorckConstraint::empty());
2549 result.outlives.extend(tcx.destructor_constraints(def));
2552 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2557 fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2560 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2561 let item = tcx.hir.expect_item(id);
2562 let vec: Vec<_> = match item.node {
2563 hir::ItemTrait(.., ref trait_item_refs) => {
2564 trait_item_refs.iter()
2565 .map(|trait_item_ref| trait_item_ref.id)
2566 .map(|id| tcx.hir.local_def_id(id.node_id))
2569 hir::ItemImpl(.., ref impl_item_refs) => {
2570 impl_item_refs.iter()
2571 .map(|impl_item_ref| impl_item_ref.id)
2572 .map(|id| tcx.hir.local_def_id(id.node_id))
2575 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2580 fn def_span<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Span {
2581 tcx.hir.span_if_local(def_id).unwrap()
2584 /// If the given def ID describes an item belonging to a trait,
2585 /// return the ID of the trait that the trait item belongs to.
2586 /// Otherwise, return `None`.
2587 fn trait_of_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
2588 tcx.opt_associated_item(def_id)
2589 .and_then(|associated_item| {
2590 match associated_item.container {
2591 TraitContainer(def_id) => Some(def_id),
2592 ImplContainer(_) => None
2598 pub fn provide(providers: &mut ty::maps::Providers) {
2599 *providers = ty::maps::Providers {
2601 associated_item_def_ids,
2602 adt_sized_constraint,
2603 adt_dtorck_constraint,
2610 pub fn provide_extern(providers: &mut ty::maps::Providers) {
2611 *providers = ty::maps::Providers {
2612 adt_sized_constraint,
2613 adt_dtorck_constraint,
2619 /// A map for the local crate mapping each type to a vector of its
2620 /// inherent impls. This is not meant to be used outside of coherence;
2621 /// rather, you should request the vector for a specific type via
2622 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2623 /// (constructing this map requires touching the entire crate).
2624 #[derive(Clone, Debug)]
2625 pub struct CrateInherentImpls {
2626 pub inherent_impls: DefIdMap<Rc<Vec<DefId>>>,
2629 /// A set of constraints that need to be satisfied in order for
2630 /// a type to be valid for destruction.
2631 #[derive(Clone, Debug)]
2632 pub struct DtorckConstraint<'tcx> {
2633 /// Types that are required to be alive in order for this
2634 /// type to be valid for destruction.
2635 pub outlives: Vec<ty::subst::Kind<'tcx>>,
2636 /// Types that could not be resolved: projections and params.
2637 pub dtorck_types: Vec<Ty<'tcx>>,
2640 impl<'tcx> FromIterator<DtorckConstraint<'tcx>> for DtorckConstraint<'tcx>
2642 fn from_iter<I: IntoIterator<Item=DtorckConstraint<'tcx>>>(iter: I) -> Self {
2643 let mut result = Self::empty();
2645 for constraint in iter {
2646 result.outlives.extend(constraint.outlives);
2647 result.dtorck_types.extend(constraint.dtorck_types);
2655 impl<'tcx> DtorckConstraint<'tcx> {
2656 fn empty() -> DtorckConstraint<'tcx> {
2659 dtorck_types: vec![]
2663 fn dedup<'a>(&mut self) {
2664 let mut outlives = FxHashSet();
2665 let mut dtorck_types = FxHashSet();
2667 self.outlives.retain(|&val| outlives.replace(val).is_none());
2668 self.dtorck_types.retain(|&val| dtorck_types.replace(val).is_none());
2672 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
2673 pub struct SymbolName {
2674 // FIXME: we don't rely on interning or equality here - better have
2675 // this be a `&'tcx str`.
2676 pub name: InternedString
2679 impl Deref for SymbolName {
2682 fn deref(&self) -> &str { &self.name }
2685 impl fmt::Display for SymbolName {
2686 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2687 fmt::Display::fmt(&self.name, fmt)