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::{self, 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 middle::const_val::ConstVal;
23 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
24 use middle::privacy::AccessLevels;
25 use middle::region::{CodeExtent, ROOT_CODE_EXTENT};
26 use middle::resolve_lifetime::ObjectLifetimeDefault;
30 use ty::subst::{Subst, Substs};
31 use ty::util::IntTypeExt;
32 use ty::walk::TypeWalker;
33 use util::common::MemoizationMap;
34 use util::nodemap::{NodeSet, DefIdMap, FxHashMap};
36 use serialize::{self, Encodable, Encoder};
38 use std::cell::{Cell, RefCell, Ref};
39 use std::collections::BTreeMap;
40 use std::hash::{Hash, Hasher};
44 use std::vec::IntoIter;
46 use syntax::ast::{self, Name, NodeId};
48 use syntax::symbol::{Symbol, InternedString};
49 use syntax_pos::{DUMMY_SP, Span};
50 use rustc_const_math::ConstInt;
52 use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
55 use hir::itemlikevisit::ItemLikeVisitor;
57 pub use self::sty::{Binder, DebruijnIndex};
58 pub use self::sty::{FnSig, PolyFnSig};
59 pub use self::sty::{InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
60 pub use self::sty::{ClosureSubsts, TypeAndMut};
61 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
62 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
63 pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
64 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
65 pub use self::sty::Issue32330;
66 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid, SkolemizedRegionVid};
67 pub use self::sty::BoundRegion::*;
68 pub use self::sty::InferTy::*;
69 pub use self::sty::Region::*;
70 pub use self::sty::TypeVariants::*;
72 pub use self::contents::TypeContents;
73 pub use self::context::{TyCtxt, GlobalArenas, tls};
74 pub use self::context::{Lift, TypeckTables};
76 pub use self::instance::{Instance, InstanceDef};
78 pub use self::trait_def::{TraitDef, TraitFlags};
80 pub use self::maps::queries;
87 pub mod inhabitedness;
104 mod structural_impls;
109 /// The complete set of all analyses described in this module. This is
110 /// produced by the driver and fed to trans and later passes.
112 /// NB: These contents are being migrated into queries using the
113 /// *on-demand* infrastructure.
115 pub struct CrateAnalysis {
116 pub access_levels: Rc<AccessLevels>,
117 pub reachable: NodeSet,
119 pub glob_map: Option<hir::GlobMap>,
123 pub struct Resolutions {
124 pub freevars: FreevarMap,
125 pub trait_map: TraitMap,
126 pub maybe_unused_trait_imports: NodeSet,
127 pub export_map: ExportMap,
130 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
131 pub enum AssociatedItemContainer {
132 TraitContainer(DefId),
133 ImplContainer(DefId),
136 impl AssociatedItemContainer {
137 pub fn id(&self) -> DefId {
139 TraitContainer(id) => id,
140 ImplContainer(id) => id,
145 /// The "header" of an impl is everything outside the body: a Self type, a trait
146 /// ref (in the case of a trait impl), and a set of predicates (from the
147 /// bounds/where clauses).
148 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
149 pub struct ImplHeader<'tcx> {
150 pub impl_def_id: DefId,
151 pub self_ty: Ty<'tcx>,
152 pub trait_ref: Option<TraitRef<'tcx>>,
153 pub predicates: Vec<Predicate<'tcx>>,
156 impl<'a, 'gcx, 'tcx> ImplHeader<'tcx> {
157 pub fn with_fresh_ty_vars(selcx: &mut traits::SelectionContext<'a, 'gcx, 'tcx>,
161 let tcx = selcx.tcx();
162 let impl_substs = selcx.infcx().fresh_substs_for_item(DUMMY_SP, impl_def_id);
164 let header = ImplHeader {
165 impl_def_id: impl_def_id,
166 self_ty: tcx.item_type(impl_def_id),
167 trait_ref: tcx.impl_trait_ref(impl_def_id),
168 predicates: tcx.item_predicates(impl_def_id).predicates
169 }.subst(tcx, impl_substs);
171 let traits::Normalized { value: mut header, obligations } =
172 traits::normalize(selcx, traits::ObligationCause::dummy(), &header);
174 header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
179 #[derive(Copy, Clone, Debug)]
180 pub struct AssociatedItem {
183 pub kind: AssociatedKind,
185 pub defaultness: hir::Defaultness,
186 pub container: AssociatedItemContainer,
188 /// Whether this is a method with an explicit self
189 /// as its first argument, allowing method calls.
190 pub method_has_self_argument: bool,
193 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
194 pub enum AssociatedKind {
200 impl AssociatedItem {
201 pub fn def(&self) -> Def {
203 AssociatedKind::Const => Def::AssociatedConst(self.def_id),
204 AssociatedKind::Method => Def::Method(self.def_id),
205 AssociatedKind::Type => Def::AssociatedTy(self.def_id),
209 /// Tests whether the associated item admits a non-trivial implementation
211 pub fn relevant_for_never<'tcx>(&self) -> bool {
213 AssociatedKind::Const => true,
214 AssociatedKind::Type => true,
215 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
216 AssociatedKind::Method => !self.method_has_self_argument,
221 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
222 pub enum Visibility {
223 /// Visible everywhere (including in other crates).
225 /// Visible only in the given crate-local module.
227 /// Not visible anywhere in the local crate. This is the visibility of private external items.
231 pub trait DefIdTree: Copy {
232 fn parent(self, id: DefId) -> Option<DefId>;
234 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
235 if descendant.krate != ancestor.krate {
239 while descendant != ancestor {
240 match self.parent(descendant) {
241 Some(parent) => descendant = parent,
242 None => return false,
249 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
250 fn parent(self, id: DefId) -> Option<DefId> {
251 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
256 pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
258 hir::Public => Visibility::Public,
259 hir::Visibility::Crate => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
260 hir::Visibility::Restricted { ref path, .. } => match path.def {
261 // If there is no resolution, `resolve` will have already reported an error, so
262 // assume that the visibility is public to avoid reporting more privacy errors.
263 Def::Err => Visibility::Public,
264 def => Visibility::Restricted(def.def_id()),
267 Visibility::Restricted(tcx.hir.local_def_id(tcx.hir.get_module_parent(id)))
272 /// Returns true if an item with this visibility is accessible from the given block.
273 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
274 let restriction = match self {
275 // Public items are visible everywhere.
276 Visibility::Public => return true,
277 // Private items from other crates are visible nowhere.
278 Visibility::Invisible => return false,
279 // Restricted items are visible in an arbitrary local module.
280 Visibility::Restricted(other) if other.krate != module.krate => return false,
281 Visibility::Restricted(module) => module,
284 tree.is_descendant_of(module, restriction)
287 /// Returns true if this visibility is at least as accessible as the given visibility
288 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
289 let vis_restriction = match vis {
290 Visibility::Public => return self == Visibility::Public,
291 Visibility::Invisible => return true,
292 Visibility::Restricted(module) => module,
295 self.is_accessible_from(vis_restriction, tree)
299 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
301 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
302 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
303 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
304 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
307 #[derive(Clone, Copy, Debug, RustcDecodable, RustcEncodable)]
308 pub struct MethodCallee<'tcx> {
309 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
312 pub substs: &'tcx Substs<'tcx>
315 /// With method calls, we store some extra information in
316 /// side tables (i.e method_map). We use
317 /// MethodCall as a key to index into these tables instead of
318 /// just directly using the expression's NodeId. The reason
319 /// for this being that we may apply adjustments (coercions)
320 /// with the resulting expression also needing to use the
321 /// side tables. The problem with this is that we don't
322 /// assign a separate NodeId to this new expression
323 /// and so it would clash with the base expression if both
324 /// needed to add to the side tables. Thus to disambiguate
325 /// we also keep track of whether there's an adjustment in
327 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
328 pub struct MethodCall {
334 pub fn expr(id: NodeId) -> MethodCall {
341 pub fn autoderef(expr_id: NodeId, autoderef: u32) -> MethodCall {
344 autoderef: 1 + autoderef
349 // maps from an expression id that corresponds to a method call to the details
350 // of the method to be invoked
351 pub type MethodMap<'tcx> = FxHashMap<MethodCall, MethodCallee<'tcx>>;
353 // Contains information needed to resolve types and (in the future) look up
354 // the types of AST nodes.
355 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
356 pub struct CReaderCacheKey {
361 /// Describes the fragment-state associated with a NodeId.
363 /// Currently only unfragmented paths have entries in the table,
364 /// but longer-term this enum is expected to expand to also
365 /// include data for fragmented paths.
366 #[derive(Copy, Clone, Debug)]
367 pub enum FragmentInfo {
368 Moved { var: NodeId, move_expr: NodeId },
369 Assigned { var: NodeId, assign_expr: NodeId, assignee_id: NodeId },
372 // Flags that we track on types. These flags are propagated upwards
373 // through the type during type construction, so that we can quickly
374 // check whether the type has various kinds of types in it without
375 // recursing over the type itself.
377 flags TypeFlags: u32 {
378 const HAS_PARAMS = 1 << 0,
379 const HAS_SELF = 1 << 1,
380 const HAS_TY_INFER = 1 << 2,
381 const HAS_RE_INFER = 1 << 3,
382 const HAS_RE_SKOL = 1 << 4,
383 const HAS_RE_EARLY_BOUND = 1 << 5,
384 const HAS_FREE_REGIONS = 1 << 6,
385 const HAS_TY_ERR = 1 << 7,
386 const HAS_PROJECTION = 1 << 8,
387 const HAS_TY_CLOSURE = 1 << 9,
389 // true if there are "names" of types and regions and so forth
390 // that are local to a particular fn
391 const HAS_LOCAL_NAMES = 1 << 10,
393 // Present if the type belongs in a local type context.
394 // Only set for TyInfer other than Fresh.
395 const KEEP_IN_LOCAL_TCX = 1 << 11,
397 // Is there a projection that does not involve a bound region?
398 // Currently we can't normalize projections w/ bound regions.
399 const HAS_NORMALIZABLE_PROJECTION = 1 << 12,
401 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
402 TypeFlags::HAS_SELF.bits |
403 TypeFlags::HAS_RE_EARLY_BOUND.bits,
405 // Flags representing the nominal content of a type,
406 // computed by FlagsComputation. If you add a new nominal
407 // flag, it should be added here too.
408 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
409 TypeFlags::HAS_SELF.bits |
410 TypeFlags::HAS_TY_INFER.bits |
411 TypeFlags::HAS_RE_INFER.bits |
412 TypeFlags::HAS_RE_SKOL.bits |
413 TypeFlags::HAS_RE_EARLY_BOUND.bits |
414 TypeFlags::HAS_FREE_REGIONS.bits |
415 TypeFlags::HAS_TY_ERR.bits |
416 TypeFlags::HAS_PROJECTION.bits |
417 TypeFlags::HAS_TY_CLOSURE.bits |
418 TypeFlags::HAS_LOCAL_NAMES.bits |
419 TypeFlags::KEEP_IN_LOCAL_TCX.bits,
421 // Caches for type_is_sized, type_moves_by_default
422 const SIZEDNESS_CACHED = 1 << 16,
423 const IS_SIZED = 1 << 17,
424 const MOVENESS_CACHED = 1 << 18,
425 const MOVES_BY_DEFAULT = 1 << 19,
429 pub struct TyS<'tcx> {
430 pub sty: TypeVariants<'tcx>,
431 pub flags: Cell<TypeFlags>,
433 // the maximal depth of any bound regions appearing in this type.
437 impl<'tcx> PartialEq for TyS<'tcx> {
439 fn eq(&self, other: &TyS<'tcx>) -> bool {
440 // (self as *const _) == (other as *const _)
441 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
444 impl<'tcx> Eq for TyS<'tcx> {}
446 impl<'tcx> Hash for TyS<'tcx> {
447 fn hash<H: Hasher>(&self, s: &mut H) {
448 (self as *const TyS).hash(s)
452 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
454 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
455 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
457 /// A wrapper for slices with the additional invariant
458 /// that the slice is interned and no other slice with
459 /// the same contents can exist in the same context.
460 /// This means we can use pointer + length for both
461 /// equality comparisons and hashing.
462 #[derive(Debug, RustcEncodable)]
463 pub struct Slice<T>([T]);
465 impl<T> PartialEq for Slice<T> {
467 fn eq(&self, other: &Slice<T>) -> bool {
468 (&self.0 as *const [T]) == (&other.0 as *const [T])
471 impl<T> Eq for Slice<T> {}
473 impl<T> Hash for Slice<T> {
474 fn hash<H: Hasher>(&self, s: &mut H) {
475 (self.as_ptr(), self.len()).hash(s)
479 impl<T> Deref for Slice<T> {
481 fn deref(&self) -> &[T] {
486 impl<'a, T> IntoIterator for &'a Slice<T> {
488 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
489 fn into_iter(self) -> Self::IntoIter {
494 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
497 pub fn empty<'a>() -> &'a Slice<T> {
499 mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
504 /// Upvars do not get their own node-id. Instead, we use the pair of
505 /// the original var id (that is, the root variable that is referenced
506 /// by the upvar) and the id of the closure expression.
507 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
510 pub closure_expr_id: NodeId,
513 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
514 pub enum BorrowKind {
515 /// Data must be immutable and is aliasable.
518 /// Data must be immutable but not aliasable. This kind of borrow
519 /// cannot currently be expressed by the user and is used only in
520 /// implicit closure bindings. It is needed when the closure
521 /// is borrowing or mutating a mutable referent, e.g.:
523 /// let x: &mut isize = ...;
524 /// let y = || *x += 5;
526 /// If we were to try to translate this closure into a more explicit
527 /// form, we'd encounter an error with the code as written:
529 /// struct Env { x: & &mut isize }
530 /// let x: &mut isize = ...;
531 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
532 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
534 /// This is then illegal because you cannot mutate a `&mut` found
535 /// in an aliasable location. To solve, you'd have to translate with
536 /// an `&mut` borrow:
538 /// struct Env { x: & &mut isize }
539 /// let x: &mut isize = ...;
540 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
541 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
543 /// Now the assignment to `**env.x` is legal, but creating a
544 /// mutable pointer to `x` is not because `x` is not mutable. We
545 /// could fix this by declaring `x` as `let mut x`. This is ok in
546 /// user code, if awkward, but extra weird for closures, since the
547 /// borrow is hidden.
549 /// So we introduce a "unique imm" borrow -- the referent is
550 /// immutable, but not aliasable. This solves the problem. For
551 /// simplicity, we don't give users the way to express this
552 /// borrow, it's just used when translating closures.
555 /// Data is mutable and not aliasable.
559 /// Information describing the capture of an upvar. This is computed
560 /// during `typeck`, specifically by `regionck`.
561 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
562 pub enum UpvarCapture<'tcx> {
563 /// Upvar is captured by value. This is always true when the
564 /// closure is labeled `move`, but can also be true in other cases
565 /// depending on inference.
568 /// Upvar is captured by reference.
569 ByRef(UpvarBorrow<'tcx>),
572 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
573 pub struct UpvarBorrow<'tcx> {
574 /// The kind of borrow: by-ref upvars have access to shared
575 /// immutable borrows, which are not part of the normal language
577 pub kind: BorrowKind,
579 /// Region of the resulting reference.
580 pub region: &'tcx ty::Region,
583 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
585 #[derive(Copy, Clone)]
586 pub struct ClosureUpvar<'tcx> {
592 #[derive(Clone, Copy, PartialEq)]
593 pub enum IntVarValue {
595 UintType(ast::UintTy),
598 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
599 pub struct TypeParameterDef {
603 pub has_default: bool,
604 pub object_lifetime_default: ObjectLifetimeDefault,
606 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
607 /// on generic parameter `T`, asserts data behind the parameter
608 /// `T` won't be accessed during the parent type's `Drop` impl.
609 pub pure_wrt_drop: bool,
612 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
613 pub struct RegionParameterDef {
617 pub issue_32330: Option<ty::Issue32330>,
619 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
620 /// on generic parameter `'a`, asserts data of lifetime `'a`
621 /// won't be accessed during the parent type's `Drop` impl.
622 pub pure_wrt_drop: bool,
625 impl RegionParameterDef {
626 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
627 ty::EarlyBoundRegion {
633 pub fn to_bound_region(&self) -> ty::BoundRegion {
634 ty::BoundRegion::BrNamed(self.def_id, self.name)
638 /// Information about the formal type/lifetime parameters associated
639 /// with an item or method. Analogous to hir::Generics.
640 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
641 pub struct Generics {
642 pub parent: Option<DefId>,
643 pub parent_regions: u32,
644 pub parent_types: u32,
645 pub regions: Vec<RegionParameterDef>,
646 pub types: Vec<TypeParameterDef>,
648 /// Reverse map to each `TypeParameterDef`'s `index` field, from
649 /// `def_id.index` (`def_id.krate` is the same as the item's).
650 pub type_param_to_index: BTreeMap<DefIndex, u32>,
656 pub fn parent_count(&self) -> usize {
657 self.parent_regions as usize + self.parent_types as usize
660 pub fn own_count(&self) -> usize {
661 self.regions.len() + self.types.len()
664 pub fn count(&self) -> usize {
665 self.parent_count() + self.own_count()
668 pub fn region_param(&self, param: &EarlyBoundRegion) -> &RegionParameterDef {
669 assert_eq!(self.parent_count(), 0);
670 &self.regions[param.index as usize - self.has_self as usize]
673 pub fn type_param(&self, param: &ParamTy) -> &TypeParameterDef {
674 assert_eq!(self.parent_count(), 0);
675 &self.types[param.idx as usize - self.has_self as usize - self.regions.len()]
679 /// Bounds on generics.
680 #[derive(Clone, Default)]
681 pub struct GenericPredicates<'tcx> {
682 pub parent: Option<DefId>,
683 pub predicates: Vec<Predicate<'tcx>>,
686 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
687 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
689 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
690 pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
691 -> InstantiatedPredicates<'tcx> {
692 let mut instantiated = InstantiatedPredicates::empty();
693 self.instantiate_into(tcx, &mut instantiated, substs);
696 pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
697 -> InstantiatedPredicates<'tcx> {
698 InstantiatedPredicates {
699 predicates: self.predicates.subst(tcx, substs)
703 fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
704 instantiated: &mut InstantiatedPredicates<'tcx>,
705 substs: &Substs<'tcx>) {
706 if let Some(def_id) = self.parent {
707 tcx.item_predicates(def_id).instantiate_into(tcx, instantiated, substs);
709 instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
712 pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
713 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
714 -> InstantiatedPredicates<'tcx>
716 assert_eq!(self.parent, None);
717 InstantiatedPredicates {
718 predicates: self.predicates.iter().map(|pred| {
719 pred.subst_supertrait(tcx, poly_trait_ref)
725 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
726 pub enum Predicate<'tcx> {
727 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
728 /// the `Self` type of the trait reference and `A`, `B`, and `C`
729 /// would be the type parameters.
730 Trait(PolyTraitPredicate<'tcx>),
732 /// where `T1 == T2`.
733 Equate(PolyEquatePredicate<'tcx>),
736 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
739 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
741 /// where <T as TraitRef>::Name == X, approximately.
742 /// See `ProjectionPredicate` struct for details.
743 Projection(PolyProjectionPredicate<'tcx>),
746 WellFormed(Ty<'tcx>),
748 /// trait must be object-safe
751 /// No direct syntax. May be thought of as `where T : FnFoo<...>`
752 /// for some substitutions `...` and T being a closure type.
753 /// Satisfied (or refuted) once we know the closure's kind.
754 ClosureKind(DefId, ClosureKind),
757 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
758 /// Performs a substitution suitable for going from a
759 /// poly-trait-ref to supertraits that must hold if that
760 /// poly-trait-ref holds. This is slightly different from a normal
761 /// substitution in terms of what happens with bound regions. See
762 /// lengthy comment below for details.
763 pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
764 trait_ref: &ty::PolyTraitRef<'tcx>)
765 -> ty::Predicate<'tcx>
767 // The interaction between HRTB and supertraits is not entirely
768 // obvious. Let me walk you (and myself) through an example.
770 // Let's start with an easy case. Consider two traits:
772 // trait Foo<'a> : Bar<'a,'a> { }
773 // trait Bar<'b,'c> { }
775 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
776 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
777 // knew that `Foo<'x>` (for any 'x) then we also know that
778 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
779 // normal substitution.
781 // In terms of why this is sound, the idea is that whenever there
782 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
783 // holds. So if there is an impl of `T:Foo<'a>` that applies to
784 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
787 // Another example to be careful of is this:
789 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
790 // trait Bar1<'b,'c> { }
792 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
793 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
794 // reason is similar to the previous example: any impl of
795 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
796 // basically we would want to collapse the bound lifetimes from
797 // the input (`trait_ref`) and the supertraits.
799 // To achieve this in practice is fairly straightforward. Let's
800 // consider the more complicated scenario:
802 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
803 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
804 // where both `'x` and `'b` would have a DB index of 1.
805 // The substitution from the input trait-ref is therefore going to be
806 // `'a => 'x` (where `'x` has a DB index of 1).
807 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
808 // early-bound parameter and `'b' is a late-bound parameter with a
810 // - If we replace `'a` with `'x` from the input, it too will have
811 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
812 // just as we wanted.
814 // There is only one catch. If we just apply the substitution `'a
815 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
816 // adjust the DB index because we substituting into a binder (it
817 // tries to be so smart...) resulting in `for<'x> for<'b>
818 // Bar1<'x,'b>` (we have no syntax for this, so use your
819 // imagination). Basically the 'x will have DB index of 2 and 'b
820 // will have DB index of 1. Not quite what we want. So we apply
821 // the substitution to the *contents* of the trait reference,
822 // rather than the trait reference itself (put another way, the
823 // substitution code expects equal binding levels in the values
824 // from the substitution and the value being substituted into, and
825 // this trick achieves that).
827 let substs = &trait_ref.0.substs;
829 Predicate::Trait(ty::Binder(ref data)) =>
830 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
831 Predicate::Equate(ty::Binder(ref data)) =>
832 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
833 Predicate::RegionOutlives(ty::Binder(ref data)) =>
834 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
835 Predicate::TypeOutlives(ty::Binder(ref data)) =>
836 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
837 Predicate::Projection(ty::Binder(ref data)) =>
838 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
839 Predicate::WellFormed(data) =>
840 Predicate::WellFormed(data.subst(tcx, substs)),
841 Predicate::ObjectSafe(trait_def_id) =>
842 Predicate::ObjectSafe(trait_def_id),
843 Predicate::ClosureKind(closure_def_id, kind) =>
844 Predicate::ClosureKind(closure_def_id, kind),
849 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
850 pub struct TraitPredicate<'tcx> {
851 pub trait_ref: TraitRef<'tcx>
853 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
855 impl<'tcx> TraitPredicate<'tcx> {
856 pub fn def_id(&self) -> DefId {
857 self.trait_ref.def_id
860 /// Creates the dep-node for selecting/evaluating this trait reference.
861 fn dep_node(&self) -> DepNode<DefId> {
862 // Extact the trait-def and first def-id from inputs. See the
863 // docs for `DepNode::TraitSelect` for more information.
864 let trait_def_id = self.def_id();
867 .flat_map(|t| t.walk())
868 .filter_map(|t| match t.sty {
869 ty::TyAdt(adt_def, _) => Some(adt_def.did),
873 .unwrap_or(trait_def_id);
874 DepNode::TraitSelect {
875 trait_def_id: trait_def_id,
876 input_def_id: input_def_id
880 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
881 self.trait_ref.input_types()
884 pub fn self_ty(&self) -> Ty<'tcx> {
885 self.trait_ref.self_ty()
889 impl<'tcx> PolyTraitPredicate<'tcx> {
890 pub fn def_id(&self) -> DefId {
891 // ok to skip binder since trait def-id does not care about regions
895 pub fn dep_node(&self) -> DepNode<DefId> {
896 // ok to skip binder since depnode does not care about regions
901 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
902 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
903 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
905 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
906 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
907 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
908 pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<&'tcx ty::Region,
910 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, &'tcx ty::Region>;
912 /// This kind of predicate has no *direct* correspondent in the
913 /// syntax, but it roughly corresponds to the syntactic forms:
915 /// 1. `T : TraitRef<..., Item=Type>`
916 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
918 /// In particular, form #1 is "desugared" to the combination of a
919 /// normal trait predicate (`T : TraitRef<...>`) and one of these
920 /// predicates. Form #2 is a broader form in that it also permits
921 /// equality between arbitrary types. Processing an instance of Form
922 /// #2 eventually yields one of these `ProjectionPredicate`
923 /// instances to normalize the LHS.
924 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
925 pub struct ProjectionPredicate<'tcx> {
926 pub projection_ty: ProjectionTy<'tcx>,
930 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
932 impl<'tcx> PolyProjectionPredicate<'tcx> {
933 pub fn item_name(&self) -> Name {
934 self.0.projection_ty.item_name // safe to skip the binder to access a name
938 pub trait ToPolyTraitRef<'tcx> {
939 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
942 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
943 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
944 assert!(!self.has_escaping_regions());
945 ty::Binder(self.clone())
949 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
950 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
951 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
955 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
956 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
957 // Note: unlike with TraitRef::to_poly_trait_ref(),
958 // self.0.trait_ref is permitted to have escaping regions.
959 // This is because here `self` has a `Binder` and so does our
960 // return value, so we are preserving the number of binding
962 ty::Binder(self.0.projection_ty.trait_ref)
966 pub trait ToPredicate<'tcx> {
967 fn to_predicate(&self) -> Predicate<'tcx>;
970 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
971 fn to_predicate(&self) -> Predicate<'tcx> {
972 // we're about to add a binder, so let's check that we don't
973 // accidentally capture anything, or else that might be some
974 // weird debruijn accounting.
975 assert!(!self.has_escaping_regions());
977 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
978 trait_ref: self.clone()
983 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
984 fn to_predicate(&self) -> Predicate<'tcx> {
985 ty::Predicate::Trait(self.to_poly_trait_predicate())
989 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
990 fn to_predicate(&self) -> Predicate<'tcx> {
991 Predicate::Equate(self.clone())
995 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
996 fn to_predicate(&self) -> Predicate<'tcx> {
997 Predicate::RegionOutlives(self.clone())
1001 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1002 fn to_predicate(&self) -> Predicate<'tcx> {
1003 Predicate::TypeOutlives(self.clone())
1007 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1008 fn to_predicate(&self) -> Predicate<'tcx> {
1009 Predicate::Projection(self.clone())
1013 impl<'tcx> Predicate<'tcx> {
1014 /// Iterates over the types in this predicate. Note that in all
1015 /// cases this is skipping over a binder, so late-bound regions
1016 /// with depth 0 are bound by the predicate.
1017 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1018 let vec: Vec<_> = match *self {
1019 ty::Predicate::Trait(ref data) => {
1020 data.skip_binder().input_types().collect()
1022 ty::Predicate::Equate(ty::Binder(ref data)) => {
1023 vec![data.0, data.1]
1025 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1028 ty::Predicate::RegionOutlives(..) => {
1031 ty::Predicate::Projection(ref data) => {
1032 let trait_inputs = data.0.projection_ty.trait_ref.input_types();
1033 trait_inputs.chain(Some(data.0.ty)).collect()
1035 ty::Predicate::WellFormed(data) => {
1038 ty::Predicate::ObjectSafe(_trait_def_id) => {
1041 ty::Predicate::ClosureKind(_closure_def_id, _kind) => {
1046 // The only reason to collect into a vector here is that I was
1047 // too lazy to make the full (somewhat complicated) iterator
1048 // type that would be needed here. But I wanted this fn to
1049 // return an iterator conceptually, rather than a `Vec`, so as
1050 // to be closer to `Ty::walk`.
1054 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1056 Predicate::Trait(ref t) => {
1057 Some(t.to_poly_trait_ref())
1059 Predicate::Projection(..) |
1060 Predicate::Equate(..) |
1061 Predicate::RegionOutlives(..) |
1062 Predicate::WellFormed(..) |
1063 Predicate::ObjectSafe(..) |
1064 Predicate::ClosureKind(..) |
1065 Predicate::TypeOutlives(..) => {
1072 /// Represents the bounds declared on a particular set of type
1073 /// parameters. Should eventually be generalized into a flag list of
1074 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
1075 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1076 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1077 /// the `GenericPredicates` are expressed in terms of the bound type
1078 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1079 /// represented a set of bounds for some particular instantiation,
1080 /// meaning that the generic parameters have been substituted with
1085 /// struct Foo<T,U:Bar<T>> { ... }
1087 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1088 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1089 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1090 /// [usize:Bar<isize>]]`.
1092 pub struct InstantiatedPredicates<'tcx> {
1093 pub predicates: Vec<Predicate<'tcx>>,
1096 impl<'tcx> InstantiatedPredicates<'tcx> {
1097 pub fn empty() -> InstantiatedPredicates<'tcx> {
1098 InstantiatedPredicates { predicates: vec![] }
1101 pub fn is_empty(&self) -> bool {
1102 self.predicates.is_empty()
1106 /// When type checking, we use the `ParameterEnvironment` to track
1107 /// details about the type/lifetime parameters that are in scope.
1108 /// It primarily stores the bounds information.
1110 /// Note: This information might seem to be redundant with the data in
1111 /// `tcx.ty_param_defs`, but it is not. That table contains the
1112 /// parameter definitions from an "outside" perspective, but this
1113 /// struct will contain the bounds for a parameter as seen from inside
1114 /// the function body. Currently the only real distinction is that
1115 /// bound lifetime parameters are replaced with free ones, but in the
1116 /// future I hope to refine the representation of types so as to make
1117 /// more distinctions clearer.
1119 pub struct ParameterEnvironment<'tcx> {
1120 /// See `construct_free_substs` for details.
1121 pub free_substs: &'tcx Substs<'tcx>,
1123 /// Each type parameter has an implicit region bound that
1124 /// indicates it must outlive at least the function body (the user
1125 /// may specify stronger requirements). This field indicates the
1126 /// region of the callee.
1127 pub implicit_region_bound: &'tcx ty::Region,
1129 /// Obligations that the caller must satisfy. This is basically
1130 /// the set of bounds on the in-scope type parameters, translated
1131 /// into Obligations, and elaborated and normalized.
1132 pub caller_bounds: Vec<ty::Predicate<'tcx>>,
1134 /// Scope that is attached to free regions for this scope. This
1135 /// is usually the id of the fn body, but for more abstract scopes
1136 /// like structs we often use the node-id of the struct.
1138 /// FIXME(#3696). It would be nice to refactor so that free
1139 /// regions don't have this implicit scope and instead introduce
1140 /// relationships in the environment.
1141 pub free_id_outlive: CodeExtent,
1143 /// A cache for `moves_by_default`.
1144 pub is_copy_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
1146 /// A cache for `type_is_sized`
1147 pub is_sized_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
1150 impl<'a, 'tcx> ParameterEnvironment<'tcx> {
1151 pub fn with_caller_bounds(&self,
1152 caller_bounds: Vec<ty::Predicate<'tcx>>)
1153 -> ParameterEnvironment<'tcx>
1155 ParameterEnvironment {
1156 free_substs: self.free_substs,
1157 implicit_region_bound: self.implicit_region_bound,
1158 caller_bounds: caller_bounds,
1159 free_id_outlive: self.free_id_outlive,
1160 is_copy_cache: RefCell::new(FxHashMap()),
1161 is_sized_cache: RefCell::new(FxHashMap()),
1165 /// Construct a parameter environment given an item, impl item, or trait item
1166 pub fn for_item(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: NodeId)
1167 -> ParameterEnvironment<'tcx> {
1168 match tcx.hir.find(id) {
1169 Some(hir_map::NodeImplItem(ref impl_item)) => {
1170 match impl_item.node {
1171 hir::ImplItemKind::Type(_) | hir::ImplItemKind::Const(..) => {
1172 // associated types don't have their own entry (for some reason),
1173 // so for now just grab environment for the impl
1174 let impl_id = tcx.hir.get_parent(id);
1175 let impl_def_id = tcx.hir.local_def_id(impl_id);
1176 tcx.construct_parameter_environment(impl_item.span,
1178 tcx.region_maps.item_extent(id))
1180 hir::ImplItemKind::Method(_, ref body) => {
1181 tcx.construct_parameter_environment(
1183 tcx.hir.local_def_id(id),
1184 tcx.region_maps.call_site_extent(id, body.node_id))
1188 Some(hir_map::NodeTraitItem(trait_item)) => {
1189 match trait_item.node {
1190 hir::TraitItemKind::Type(..) | hir::TraitItemKind::Const(..) => {
1191 // associated types don't have their own entry (for some reason),
1192 // so for now just grab environment for the trait
1193 let trait_id = tcx.hir.get_parent(id);
1194 let trait_def_id = tcx.hir.local_def_id(trait_id);
1195 tcx.construct_parameter_environment(trait_item.span,
1197 tcx.region_maps.item_extent(id))
1199 hir::TraitItemKind::Method(_, ref body) => {
1200 // Use call-site for extent (unless this is a
1201 // trait method with no default; then fallback
1202 // to the method id).
1203 let extent = if let hir::TraitMethod::Provided(body_id) = *body {
1204 // default impl: use call_site extent as free_id_outlive bound.
1205 tcx.region_maps.call_site_extent(id, body_id.node_id)
1207 // no default impl: use item extent as free_id_outlive bound.
1208 tcx.region_maps.item_extent(id)
1210 tcx.construct_parameter_environment(
1212 tcx.hir.local_def_id(id),
1217 Some(hir_map::NodeItem(item)) => {
1219 hir::ItemFn(.., body_id) => {
1220 // We assume this is a function.
1221 let fn_def_id = tcx.hir.local_def_id(id);
1223 tcx.construct_parameter_environment(
1226 tcx.region_maps.call_site_extent(id, body_id.node_id))
1229 hir::ItemStruct(..) |
1230 hir::ItemUnion(..) |
1233 hir::ItemConst(..) |
1234 hir::ItemStatic(..) => {
1235 let def_id = tcx.hir.local_def_id(id);
1236 tcx.construct_parameter_environment(item.span,
1238 tcx.region_maps.item_extent(id))
1240 hir::ItemTrait(..) => {
1241 let def_id = tcx.hir.local_def_id(id);
1242 tcx.construct_parameter_environment(item.span,
1244 tcx.region_maps.item_extent(id))
1247 span_bug!(item.span,
1248 "ParameterEnvironment::for_item():
1249 can't create a parameter \
1250 environment for this kind of item")
1254 Some(hir_map::NodeExpr(expr)) => {
1255 // This is a convenience to allow closures to work.
1256 if let hir::ExprClosure(.., body, _) = expr.node {
1257 let def_id = tcx.hir.local_def_id(id);
1258 let base_def_id = tcx.closure_base_def_id(def_id);
1259 tcx.construct_parameter_environment(
1262 tcx.region_maps.call_site_extent(id, body.node_id))
1264 tcx.empty_parameter_environment()
1267 Some(hir_map::NodeForeignItem(item)) => {
1268 let def_id = tcx.hir.local_def_id(id);
1269 tcx.construct_parameter_environment(item.span,
1273 Some(hir_map::NodeStructCtor(..)) |
1274 Some(hir_map::NodeVariant(..)) => {
1275 let def_id = tcx.hir.local_def_id(id);
1276 tcx.construct_parameter_environment(tcx.hir.span(id),
1281 bug!("ParameterEnvironment::from_item(): \
1282 `{}` = {:?} is unsupported",
1283 tcx.hir.node_to_string(id), it)
1289 #[derive(Copy, Clone, Debug)]
1290 pub struct Destructor {
1291 /// The def-id of the destructor method
1293 /// Invoking the destructor of a dtorck type during usual cleanup
1294 /// (e.g. the glue emitted for stack unwinding) requires all
1295 /// lifetimes in the type-structure of `adt` to strictly outlive
1296 /// the adt value itself.
1298 /// If `adt` is not dtorck, then the adt's destructor can be
1299 /// invoked even when there are lifetimes in the type-structure of
1300 /// `adt` that do not strictly outlive the adt value itself.
1301 /// (This allows programs to make cyclic structures without
1302 /// resorting to unsafe means; see RFCs 769 and 1238).
1303 pub is_dtorck: bool,
1307 flags AdtFlags: u32 {
1308 const NO_ADT_FLAGS = 0,
1309 const IS_ENUM = 1 << 0,
1310 const IS_PHANTOM_DATA = 1 << 1,
1311 const IS_FUNDAMENTAL = 1 << 2,
1312 const IS_UNION = 1 << 3,
1313 const IS_BOX = 1 << 4,
1318 pub struct VariantDef {
1319 /// The variant's DefId. If this is a tuple-like struct,
1320 /// this is the DefId of the struct's ctor.
1322 pub name: Name, // struct's name if this is a struct
1323 pub discr: VariantDiscr,
1324 pub fields: Vec<FieldDef>,
1325 pub ctor_kind: CtorKind,
1328 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1329 pub enum VariantDiscr {
1330 /// Explicit value for this variant, i.e. `X = 123`.
1331 /// The `DefId` corresponds to the embedded constant.
1334 /// The previous variant's discriminant plus one.
1335 /// For efficiency reasons, the distance from the
1336 /// last `Explicit` discriminant is being stored,
1337 /// or `0` for the first variant, if it has none.
1342 pub struct FieldDef {
1345 pub vis: Visibility,
1348 /// The definition of an abstract data type - a struct or enum.
1350 /// These are all interned (by intern_adt_def) into the adt_defs
1354 pub variants: Vec<VariantDef>,
1356 pub repr: ReprOptions,
1359 impl PartialEq for AdtDef {
1360 // AdtDef are always interned and this is part of TyS equality
1362 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1365 impl Eq for AdtDef {}
1367 impl Hash for AdtDef {
1369 fn hash<H: Hasher>(&self, s: &mut H) {
1370 (self as *const AdtDef).hash(s)
1374 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1375 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1380 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1382 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1383 pub enum AdtKind { Struct, Union, Enum }
1385 /// Represents the repr options provided by the user,
1386 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1387 pub struct ReprOptions {
1391 pub int: Option<attr::IntType>,
1395 pub fn new(tcx: TyCtxt, did: DefId) -> ReprOptions {
1396 let mut ret = ReprOptions::default();
1398 for attr in tcx.get_attrs(did).iter() {
1399 for r in attr::find_repr_attrs(tcx.sess.diagnostic(), attr) {
1401 attr::ReprExtern => ret.c = true,
1402 attr::ReprPacked => ret.packed = true,
1403 attr::ReprSimd => ret.simd = true,
1404 attr::ReprInt(i) => ret.int = Some(i),
1409 // FIXME(eddyb) This is deprecated and should be removed.
1410 if tcx.has_attr(did, "simd") {
1417 pub fn discr_type(&self) -> attr::IntType {
1418 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Is))
1421 /// Returns true if this `#[repr()]` should inhabit "smart enum
1422 /// layout" optimizations, such as representing `Foo<&T>` as a
1424 pub fn inhibit_enum_layout_opt(&self) -> bool {
1425 self.c || self.int.is_some()
1429 impl<'a, 'gcx, 'tcx> AdtDef {
1433 variants: Vec<VariantDef>,
1434 repr: ReprOptions) -> Self {
1435 let mut flags = AdtFlags::NO_ADT_FLAGS;
1436 let attrs = tcx.get_attrs(did);
1437 if attr::contains_name(&attrs, "fundamental") {
1438 flags = flags | AdtFlags::IS_FUNDAMENTAL;
1440 if Some(did) == tcx.lang_items.phantom_data() {
1441 flags = flags | AdtFlags::IS_PHANTOM_DATA;
1443 if Some(did) == tcx.lang_items.owned_box() {
1444 flags = flags | AdtFlags::IS_BOX;
1447 AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1448 AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1449 AdtKind::Struct => {}
1460 pub fn is_struct(&self) -> bool {
1461 !self.is_union() && !self.is_enum()
1465 pub fn is_union(&self) -> bool {
1466 self.flags.intersects(AdtFlags::IS_UNION)
1470 pub fn is_enum(&self) -> bool {
1471 self.flags.intersects(AdtFlags::IS_ENUM)
1474 /// Returns the kind of the ADT - Struct or Enum.
1476 pub fn adt_kind(&self) -> AdtKind {
1479 } else if self.is_union() {
1486 pub fn descr(&self) -> &'static str {
1487 match self.adt_kind() {
1488 AdtKind::Struct => "struct",
1489 AdtKind::Union => "union",
1490 AdtKind::Enum => "enum",
1494 pub fn variant_descr(&self) -> &'static str {
1495 match self.adt_kind() {
1496 AdtKind::Struct => "struct",
1497 AdtKind::Union => "union",
1498 AdtKind::Enum => "variant",
1502 /// Returns whether this is a dtorck type. If this returns
1503 /// true, this type being safe for destruction requires it to be
1504 /// alive; Otherwise, only the contents are required to be.
1506 pub fn is_dtorck(&'gcx self, tcx: TyCtxt) -> bool {
1507 self.destructor(tcx).map_or(false, |d| d.is_dtorck)
1510 /// Returns whether this type is #[fundamental] for the purposes
1511 /// of coherence checking.
1513 pub fn is_fundamental(&self) -> bool {
1514 self.flags.intersects(AdtFlags::IS_FUNDAMENTAL)
1517 /// Returns true if this is PhantomData<T>.
1519 pub fn is_phantom_data(&self) -> bool {
1520 self.flags.intersects(AdtFlags::IS_PHANTOM_DATA)
1523 /// Returns true if this is Box<T>.
1525 pub fn is_box(&self) -> bool {
1526 self.flags.intersects(AdtFlags::IS_BOX)
1529 /// Returns whether this type has a destructor.
1530 pub fn has_dtor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1531 self.destructor(tcx).is_some()
1534 /// Asserts this is a struct and returns the struct's unique
1536 pub fn struct_variant(&self) -> &VariantDef {
1537 assert!(!self.is_enum());
1542 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1543 tcx.item_predicates(self.did)
1546 /// Returns an iterator over all fields contained
1549 pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1550 self.variants.iter().flat_map(|v| v.fields.iter())
1554 pub fn is_univariant(&self) -> bool {
1555 self.variants.len() == 1
1558 pub fn is_payloadfree(&self) -> bool {
1559 !self.variants.is_empty() &&
1560 self.variants.iter().all(|v| v.fields.is_empty())
1563 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1566 .find(|v| v.did == vid)
1567 .expect("variant_with_id: unknown variant")
1570 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1573 .position(|v| v.did == vid)
1574 .expect("variant_index_with_id: unknown variant")
1577 pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1579 Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1580 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1581 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.struct_variant(),
1582 _ => bug!("unexpected def {:?} in variant_of_def", def)
1586 pub fn discriminants(&'a self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
1587 -> impl Iterator<Item=ConstInt> + 'a {
1588 let repr_type = self.repr.discr_type();
1589 let initial = repr_type.initial_discriminant(tcx.global_tcx());
1590 let mut prev_discr = None::<ConstInt>;
1591 self.variants.iter().map(move |v| {
1592 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr());
1593 if let VariantDiscr::Explicit(expr_did) = v.discr {
1594 match tcx.maps.monomorphic_const_eval.borrow()[&expr_did] {
1595 Ok(ConstVal::Integral(v)) => {
1601 prev_discr = Some(discr);
1607 pub fn destructor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Destructor> {
1608 queries::adt_destructor::get(tcx, DUMMY_SP, self.did)
1611 /// Returns a simpler type such that `Self: Sized` if and only
1612 /// if that type is Sized, or `TyErr` if this type is recursive.
1614 /// HACK: instead of returning a list of types, this function can
1615 /// return a tuple. In that case, the result is Sized only if
1616 /// all elements of the tuple are Sized.
1618 /// This is generally the `struct_tail` if this is a struct, or a
1619 /// tuple of them if this is an enum.
1621 /// Oddly enough, checking that the sized-constraint is Sized is
1622 /// actually more expressive than checking all members:
1623 /// the Sized trait is inductive, so an associated type that references
1624 /// Self would prevent its containing ADT from being Sized.
1626 /// Due to normalization being eager, this applies even if
1627 /// the associated type is behind a pointer, e.g. issue #31299.
1628 pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1629 self.calculate_sized_constraint_inner(tcx.global_tcx(), &mut Vec::new())
1632 /// Calculates the Sized-constraint.
1634 /// As the Sized-constraint of enums can be a *set* of types,
1635 /// the Sized-constraint may need to be a set also. Because introducing
1636 /// a new type of IVar is currently a complex affair, the Sized-constraint
1639 /// In fact, there are only a few options for the constraint:
1640 /// - `bool`, if the type is always Sized
1641 /// - an obviously-unsized type
1642 /// - a type parameter or projection whose Sizedness can't be known
1643 /// - a tuple of type parameters or projections, if there are multiple
1645 /// - a TyError, if a type contained itself. The representability
1646 /// check should catch this case.
1647 fn calculate_sized_constraint_inner(&self,
1648 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1649 stack: &mut Vec<DefId>)
1652 if let Some(ty) = tcx.maps.adt_sized_constraint.borrow().get(&self.did) {
1656 // Follow the memoization pattern: push the computation of
1657 // DepNode::SizedConstraint as our current task.
1658 let _task = tcx.dep_graph.in_task(DepNode::SizedConstraint(self.did));
1660 if stack.contains(&self.did) {
1661 debug!("calculate_sized_constraint: {:?} is recursive", self);
1662 // This should be reported as an error by `check_representable`.
1664 // Consider the type as Sized in the meanwhile to avoid
1666 tcx.maps.adt_sized_constraint.borrow_mut().insert(self.did, tcx.types.err);
1667 return tcx.types.err;
1670 stack.push(self.did);
1673 self.variants.iter().flat_map(|v| {
1676 let ty = tcx.item_type(f.did);
1677 self.sized_constraint_for_ty(tcx, stack, ty)
1680 let self_ = stack.pop().unwrap();
1681 assert_eq!(self_, self.did);
1683 let ty = match tys.len() {
1684 _ if tys.references_error() => tcx.types.err,
1685 0 => tcx.types.bool,
1687 _ => tcx.intern_tup(&tys[..], false)
1690 let old = tcx.maps.adt_sized_constraint.borrow().get(&self.did).cloned();
1693 debug!("calculate_sized_constraint: {:?} recurred", self);
1694 assert_eq!(old_ty, tcx.types.err);
1698 debug!("calculate_sized_constraint: {:?} => {:?}", self, ty);
1699 tcx.maps.adt_sized_constraint.borrow_mut().insert(self.did, ty);
1705 fn sized_constraint_for_ty(&self,
1706 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1707 stack: &mut Vec<DefId>,
1710 let result = match ty.sty {
1711 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
1712 TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
1713 TyArray(..) | TyClosure(..) | TyNever => {
1717 TyStr | TyDynamic(..) | TySlice(_) | TyError => {
1718 // these are never sized - return the target type
1722 TyTuple(ref tys, _) => {
1725 Some(ty) => self.sized_constraint_for_ty(tcx, stack, ty)
1729 TyAdt(adt, substs) => {
1732 adt.calculate_sized_constraint_inner(tcx, stack)
1733 .subst(tcx, substs);
1734 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
1736 if let ty::TyTuple(ref tys, _) = adt_ty.sty {
1737 tys.iter().flat_map(|ty| {
1738 self.sized_constraint_for_ty(tcx, stack, ty)
1741 self.sized_constraint_for_ty(tcx, stack, adt_ty)
1745 TyProjection(..) | TyAnon(..) => {
1746 // must calculate explicitly.
1747 // FIXME: consider special-casing always-Sized projections
1752 // perf hack: if there is a `T: Sized` bound, then
1753 // we know that `T` is Sized and do not need to check
1756 let sized_trait = match tcx.lang_items.sized_trait() {
1758 _ => return vec![ty]
1760 let sized_predicate = Binder(TraitRef {
1761 def_id: sized_trait,
1762 substs: tcx.mk_substs_trait(ty, &[])
1764 let predicates = tcx.item_predicates(self.did).predicates;
1765 if predicates.into_iter().any(|p| p == sized_predicate) {
1773 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
1777 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
1782 impl<'a, 'gcx, 'tcx> VariantDef {
1784 pub fn find_field_named(&self,
1786 -> Option<&FieldDef> {
1787 self.fields.iter().find(|f| f.name == name)
1791 pub fn index_of_field_named(&self,
1794 self.fields.iter().position(|f| f.name == name)
1798 pub fn field_named(&self, name: ast::Name) -> &FieldDef {
1799 self.find_field_named(name).unwrap()
1803 impl<'a, 'gcx, 'tcx> FieldDef {
1804 pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1805 tcx.item_type(self.did).subst(tcx, subst)
1809 /// Records the substitutions used to translate the polytype for an
1810 /// item into the monotype of an item reference.
1811 #[derive(Clone, RustcEncodable, RustcDecodable)]
1812 pub struct ItemSubsts<'tcx> {
1813 pub substs: &'tcx Substs<'tcx>,
1816 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1817 pub enum ClosureKind {
1818 // Warning: Ordering is significant here! The ordering is chosen
1819 // because the trait Fn is a subtrait of FnMut and so in turn, and
1820 // hence we order it so that Fn < FnMut < FnOnce.
1826 impl<'a, 'tcx> ClosureKind {
1827 pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
1829 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
1830 ClosureKind::FnMut => {
1831 tcx.require_lang_item(FnMutTraitLangItem)
1833 ClosureKind::FnOnce => {
1834 tcx.require_lang_item(FnOnceTraitLangItem)
1839 /// True if this a type that impls this closure kind
1840 /// must also implement `other`.
1841 pub fn extends(self, other: ty::ClosureKind) -> bool {
1842 match (self, other) {
1843 (ClosureKind::Fn, ClosureKind::Fn) => true,
1844 (ClosureKind::Fn, ClosureKind::FnMut) => true,
1845 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
1846 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
1847 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
1848 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
1854 impl<'tcx> TyS<'tcx> {
1855 /// Iterator that walks `self` and any types reachable from
1856 /// `self`, in depth-first order. Note that just walks the types
1857 /// that appear in `self`, it does not descend into the fields of
1858 /// structs or variants. For example:
1861 /// isize => { isize }
1862 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
1863 /// [isize] => { [isize], isize }
1865 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
1866 TypeWalker::new(self)
1869 /// Iterator that walks the immediate children of `self`. Hence
1870 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
1871 /// (but not `i32`, like `walk`).
1872 pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
1873 walk::walk_shallow(self)
1876 /// Walks `ty` and any types appearing within `ty`, invoking the
1877 /// callback `f` on each type. If the callback returns false, then the
1878 /// children of the current type are ignored.
1880 /// Note: prefer `ty.walk()` where possible.
1881 pub fn maybe_walk<F>(&'tcx self, mut f: F)
1882 where F : FnMut(Ty<'tcx>) -> bool
1884 let mut walker = self.walk();
1885 while let Some(ty) = walker.next() {
1887 walker.skip_current_subtree();
1893 impl<'tcx> ItemSubsts<'tcx> {
1894 pub fn is_noop(&self) -> bool {
1895 self.substs.is_noop()
1899 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1900 pub enum LvaluePreference {
1905 impl LvaluePreference {
1906 pub fn from_mutbl(m: hir::Mutability) -> Self {
1908 hir::MutMutable => PreferMutLvalue,
1909 hir::MutImmutable => NoPreference,
1915 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
1917 hir::MutMutable => MutBorrow,
1918 hir::MutImmutable => ImmBorrow,
1922 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
1923 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
1924 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
1926 pub fn to_mutbl_lossy(self) -> hir::Mutability {
1928 MutBorrow => hir::MutMutable,
1929 ImmBorrow => hir::MutImmutable,
1931 // We have no type corresponding to a unique imm borrow, so
1932 // use `&mut`. It gives all the capabilities of an `&uniq`
1933 // and hence is a safe "over approximation".
1934 UniqueImmBorrow => hir::MutMutable,
1938 pub fn to_user_str(&self) -> &'static str {
1940 MutBorrow => "mutable",
1941 ImmBorrow => "immutable",
1942 UniqueImmBorrow => "uniquely immutable",
1947 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1948 pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
1949 self.item_tables(self.hir.body_owner_def_id(body))
1952 pub fn item_tables(self, def_id: DefId) -> &'gcx TypeckTables<'gcx> {
1953 queries::typeck_tables::get(self, DUMMY_SP, def_id)
1956 pub fn expr_span(self, id: NodeId) -> Span {
1957 match self.hir.find(id) {
1958 Some(hir_map::NodeExpr(e)) => {
1962 bug!("Node id {} is not an expr: {:?}", id, f);
1965 bug!("Node id {} is not present in the node map", id);
1970 pub fn local_var_name_str(self, id: NodeId) -> InternedString {
1971 match self.hir.find(id) {
1972 Some(hir_map::NodeLocal(pat)) => {
1974 hir::PatKind::Binding(_, _, ref path1, _) => path1.node.as_str(),
1976 bug!("Variable id {} maps to {:?}, not local", id, pat);
1980 r => bug!("Variable id {} maps to {:?}, not local", id, r),
1984 pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
1986 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
1988 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
1993 hir::ExprType(ref e, _) => {
1994 self.expr_is_lval(e)
1997 hir::ExprUnary(hir::UnDeref, _) |
1998 hir::ExprField(..) |
1999 hir::ExprTupField(..) |
2000 hir::ExprIndex(..) => {
2004 // Partially qualified paths in expressions can only legally
2005 // refer to associated items which are always rvalues.
2006 hir::ExprPath(hir::QPath::TypeRelative(..)) |
2009 hir::ExprMethodCall(..) |
2010 hir::ExprStruct(..) |
2013 hir::ExprMatch(..) |
2014 hir::ExprClosure(..) |
2015 hir::ExprBlock(..) |
2016 hir::ExprRepeat(..) |
2017 hir::ExprArray(..) |
2018 hir::ExprBreak(..) |
2019 hir::ExprAgain(..) |
2021 hir::ExprWhile(..) |
2023 hir::ExprAssign(..) |
2024 hir::ExprInlineAsm(..) |
2025 hir::ExprAssignOp(..) |
2027 hir::ExprUnary(..) |
2029 hir::ExprAddrOf(..) |
2030 hir::ExprBinary(..) |
2031 hir::ExprCast(..) => {
2037 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2038 self.associated_items(id)
2039 .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2043 pub fn trait_impl_polarity(self, id: DefId) -> hir::ImplPolarity {
2044 if let Some(id) = self.hir.as_local_node_id(id) {
2045 match self.hir.expect_item(id).node {
2046 hir::ItemImpl(_, polarity, ..) => polarity,
2047 ref item => bug!("trait_impl_polarity: {:?} not an impl", item)
2050 self.sess.cstore.impl_polarity(id)
2054 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2055 self.associated_items(did).any(|item| {
2056 item.relevant_for_never()
2060 pub fn coerce_unsized_info(self, did: DefId) -> adjustment::CoerceUnsizedInfo {
2061 queries::coerce_unsized_info::get(self, DUMMY_SP, did)
2064 pub fn associated_item(self, def_id: DefId) -> AssociatedItem {
2065 queries::associated_item::get(self, DUMMY_SP, def_id)
2068 fn associated_item_from_trait_item_ref(self,
2069 parent_def_id: DefId,
2070 trait_item_ref: &hir::TraitItemRef)
2072 let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2073 let (kind, has_self) = match trait_item_ref.kind {
2074 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2075 hir::AssociatedItemKind::Method { has_self } => {
2076 (ty::AssociatedKind::Method, has_self)
2078 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2082 name: trait_item_ref.name,
2084 vis: Visibility::from_hir(&hir::Inherited, trait_item_ref.id.node_id, self),
2085 defaultness: trait_item_ref.defaultness,
2087 container: TraitContainer(parent_def_id),
2088 method_has_self_argument: has_self
2092 fn associated_item_from_impl_item_ref(self,
2093 parent_def_id: DefId,
2094 from_trait_impl: bool,
2095 impl_item_ref: &hir::ImplItemRef)
2097 let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2098 let (kind, has_self) = match impl_item_ref.kind {
2099 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2100 hir::AssociatedItemKind::Method { has_self } => {
2101 (ty::AssociatedKind::Method, has_self)
2103 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2106 // Trait impl items are always public.
2107 let public = hir::Public;
2108 let vis = if from_trait_impl { &public } else { &impl_item_ref.vis };
2110 ty::AssociatedItem {
2111 name: impl_item_ref.name,
2113 vis: ty::Visibility::from_hir(vis, impl_item_ref.id.node_id, self),
2114 defaultness: impl_item_ref.defaultness,
2116 container: ImplContainer(parent_def_id),
2117 method_has_self_argument: has_self
2121 pub fn associated_item_def_ids(self, def_id: DefId) -> Rc<Vec<DefId>> {
2122 if !def_id.is_local() {
2123 return queries::associated_item_def_ids::get(self, DUMMY_SP, def_id);
2126 self.maps.associated_item_def_ids.memoize(def_id, || {
2127 let id = self.hir.as_local_node_id(def_id).unwrap();
2128 let item = self.hir.expect_item(id);
2129 let vec: Vec<_> = match item.node {
2130 hir::ItemTrait(.., ref trait_item_refs) => {
2131 trait_item_refs.iter()
2132 .map(|trait_item_ref| trait_item_ref.id)
2133 .map(|id| self.hir.local_def_id(id.node_id))
2136 hir::ItemImpl(.., ref impl_item_refs) => {
2137 impl_item_refs.iter()
2138 .map(|impl_item_ref| impl_item_ref.id)
2139 .map(|id| self.hir.local_def_id(id.node_id))
2142 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2148 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2149 pub fn associated_items(self, def_id: DefId)
2150 -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2151 let def_ids = self.associated_item_def_ids(def_id);
2152 (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2155 /// Returns the trait-ref corresponding to a given impl, or None if it is
2156 /// an inherent impl.
2157 pub fn impl_trait_ref(self, id: DefId) -> Option<TraitRef<'gcx>> {
2158 queries::impl_trait_ref::get(self, DUMMY_SP, id)
2161 // Returns `ty::VariantDef` if `def` refers to a struct,
2162 // or variant or their constructors, panics otherwise.
2163 pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2165 Def::Variant(did) | Def::VariantCtor(did, ..) => {
2166 let enum_did = self.parent_def_id(did).unwrap();
2167 self.lookup_adt_def(enum_did).variant_with_id(did)
2169 Def::Struct(did) | Def::Union(did) => {
2170 self.lookup_adt_def(did).struct_variant()
2172 Def::StructCtor(ctor_did, ..) => {
2173 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2174 self.lookup_adt_def(did).struct_variant()
2176 _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2180 pub fn def_key(self, id: DefId) -> hir_map::DefKey {
2182 self.hir.def_key(id)
2184 self.sess.cstore.def_key(id)
2188 /// Convert a `DefId` into its fully expanded `DefPath` (every
2189 /// `DefId` is really just an interned def-path).
2191 /// Note that if `id` is not local to this crate, the result will
2192 // be a non-local `DefPath`.
2193 pub fn def_path(self, id: DefId) -> hir_map::DefPath {
2195 self.hir.def_path(id)
2197 self.sess.cstore.def_path(id)
2201 pub fn def_span(self, def_id: DefId) -> Span {
2202 if let Some(id) = self.hir.as_local_node_id(def_id) {
2205 self.sess.cstore.def_span(&self.sess, def_id)
2209 pub fn vis_is_accessible_from(self, vis: Visibility, block: NodeId) -> bool {
2210 vis.is_accessible_from(self.hir.local_def_id(self.hir.get_module_parent(block)), self)
2213 pub fn item_name(self, id: DefId) -> ast::Name {
2214 if let Some(id) = self.hir.as_local_node_id(id) {
2216 } else if id.index == CRATE_DEF_INDEX {
2217 self.sess.cstore.original_crate_name(id.krate)
2219 let def_key = self.sess.cstore.def_key(id);
2220 // The name of a StructCtor is that of its struct parent.
2221 if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2222 self.item_name(DefId {
2224 index: def_key.parent.unwrap()
2227 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2228 bug!("item_name: no name for {:?}", self.def_path(id));
2234 // If the given item is in an external crate, looks up its type and adds it to
2235 // the type cache. Returns the type parameters and type.
2236 pub fn item_type(self, did: DefId) -> Ty<'gcx> {
2237 queries::ty::get(self, DUMMY_SP, did)
2240 /// Given the did of a trait, returns its canonical trait ref.
2241 pub fn lookup_trait_def(self, did: DefId) -> &'gcx TraitDef {
2242 queries::trait_def::get(self, DUMMY_SP, did)
2245 /// Given the did of an ADT, return a reference to its definition.
2246 pub fn lookup_adt_def(self, did: DefId) -> &'gcx AdtDef {
2247 queries::adt_def::get(self, DUMMY_SP, did)
2250 /// Given the did of an item, returns its generics.
2251 pub fn item_generics(self, did: DefId) -> &'gcx Generics {
2252 queries::generics::get(self, DUMMY_SP, did)
2255 /// Given the did of an item, returns its full set of predicates.
2256 pub fn item_predicates(self, did: DefId) -> GenericPredicates<'gcx> {
2257 queries::predicates::get(self, DUMMY_SP, did)
2260 /// Given the did of a trait, returns its superpredicates.
2261 pub fn item_super_predicates(self, did: DefId) -> GenericPredicates<'gcx> {
2262 queries::super_predicates::get(self, DUMMY_SP, did)
2265 /// Given the did of an item, returns its MIR, borrowed immutably.
2266 pub fn item_mir(self, did: DefId) -> Ref<'gcx, Mir<'gcx>> {
2267 queries::mir::get(self, DUMMY_SP, did).borrow()
2270 /// Return the possibly-auto-generated MIR of a (DefId, Subst) pair.
2271 pub fn instance_mir(self, instance: ty::InstanceDef<'gcx>)
2272 -> Ref<'gcx, Mir<'gcx>>
2275 ty::InstanceDef::Item(did) if true => self.item_mir(did),
2276 _ => queries::mir_shims::get(self, DUMMY_SP, instance).borrow(),
2280 /// Given the DefId of an item, returns its MIR, borrowed immutably.
2281 /// Returns None if there is no MIR for the DefId
2282 pub fn maybe_item_mir(self, did: DefId) -> Option<Ref<'gcx, Mir<'gcx>>> {
2283 if did.is_local() && !self.maps.mir.borrow().contains_key(&did) {
2287 if !did.is_local() && !self.sess.cstore.is_item_mir_available(did) {
2291 Some(self.item_mir(did))
2294 /// If `type_needs_drop` returns true, then `ty` is definitely
2295 /// non-copy and *might* have a destructor attached; if it returns
2296 /// false, then `ty` definitely has no destructor (i.e. no drop glue).
2298 /// (Note that this implies that if `ty` has a destructor attached,
2299 /// then `type_needs_drop` will definitely return `true` for `ty`.)
2300 pub fn type_needs_drop_given_env(self,
2302 param_env: &ty::ParameterEnvironment<'gcx>) -> bool {
2303 // Issue #22536: We first query type_moves_by_default. It sees a
2304 // normalized version of the type, and therefore will definitely
2305 // know whether the type implements Copy (and thus needs no
2306 // cleanup/drop/zeroing) ...
2307 let tcx = self.global_tcx();
2308 let implements_copy = !ty.moves_by_default(tcx, param_env, DUMMY_SP);
2310 if implements_copy { return false; }
2312 // ... (issue #22536 continued) but as an optimization, still use
2313 // prior logic of asking if the `needs_drop` bit is set; we need
2314 // not zero non-Copy types if they have no destructor.
2316 // FIXME(#22815): Note that calling `ty::type_contents` is a
2317 // conservative heuristic; it may report that `needs_drop` is set
2318 // when actual type does not actually have a destructor associated
2319 // with it. But since `ty` absolutely did not have the `Copy`
2320 // bound attached (see above), it is sound to treat it as having a
2321 // destructor (e.g. zero its memory on move).
2323 let contents = ty.type_contents(tcx);
2324 debug!("type_needs_drop ty={:?} contents={:?}", ty, contents);
2325 contents.needs_drop(tcx)
2328 /// Get the attributes of a definition.
2329 pub fn get_attrs(self, did: DefId) -> Cow<'gcx, [ast::Attribute]> {
2330 if let Some(id) = self.hir.as_local_node_id(did) {
2331 Cow::Borrowed(self.hir.attrs(id))
2333 Cow::Owned(self.sess.cstore.item_attrs(did))
2337 /// Determine whether an item is annotated with an attribute
2338 pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2339 self.get_attrs(did).iter().any(|item| item.check_name(attr))
2342 pub fn item_variances(self, item_id: DefId) -> Rc<Vec<ty::Variance>> {
2343 queries::variances::get(self, DUMMY_SP, item_id)
2346 pub fn trait_has_default_impl(self, trait_def_id: DefId) -> bool {
2347 let def = self.lookup_trait_def(trait_def_id);
2348 def.flags.get().intersects(TraitFlags::HAS_DEFAULT_IMPL)
2351 /// Populates the type context with all the implementations for the given
2352 /// trait if necessary.
2353 pub fn populate_implementations_for_trait_if_necessary(self, trait_id: DefId) {
2354 if trait_id.is_local() {
2358 // The type is not local, hence we are reading this out of
2359 // metadata and don't need to track edges.
2360 let _ignore = self.dep_graph.in_ignore();
2362 let def = self.lookup_trait_def(trait_id);
2363 if def.flags.get().intersects(TraitFlags::HAS_REMOTE_IMPLS) {
2367 debug!("populate_implementations_for_trait_if_necessary: searching for {:?}", def);
2369 for impl_def_id in self.sess.cstore.implementations_of_trait(Some(trait_id)) {
2370 let trait_ref = self.impl_trait_ref(impl_def_id).unwrap();
2372 // Record the trait->implementation mapping.
2373 let parent = self.sess.cstore.impl_parent(impl_def_id).unwrap_or(trait_id);
2374 def.record_remote_impl(self, impl_def_id, trait_ref, parent);
2377 def.flags.set(def.flags.get() | TraitFlags::HAS_REMOTE_IMPLS);
2380 pub fn closure_kind(self, def_id: DefId) -> ty::ClosureKind {
2381 queries::closure_kind::get(self, DUMMY_SP, def_id)
2384 pub fn closure_type(self, def_id: DefId) -> ty::PolyFnSig<'tcx> {
2385 queries::closure_type::get(self, DUMMY_SP, def_id)
2388 /// Given the def_id of an impl, return the def_id of the trait it implements.
2389 /// If it implements no trait, return `None`.
2390 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2391 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2394 /// If the given def ID describes a method belonging to an impl, return the
2395 /// ID of the impl that the method belongs to. Otherwise, return `None`.
2396 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2397 let item = if def_id.krate != LOCAL_CRATE {
2398 if let Some(Def::Method(_)) = self.sess.cstore.describe_def(def_id) {
2399 Some(self.associated_item(def_id))
2404 self.maps.associated_item.borrow().get(&def_id).cloned()
2408 Some(trait_item) => {
2409 match trait_item.container {
2410 TraitContainer(_) => None,
2411 ImplContainer(def_id) => Some(def_id),
2418 /// If the given def ID describes an item belonging to a trait,
2419 /// return the ID of the trait that the trait item belongs to.
2420 /// Otherwise, return `None`.
2421 pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
2422 if def_id.krate != LOCAL_CRATE {
2423 return self.sess.cstore.trait_of_item(def_id);
2425 match self.maps.associated_item.borrow().get(&def_id) {
2426 Some(associated_item) => {
2427 match associated_item.container {
2428 TraitContainer(def_id) => Some(def_id),
2429 ImplContainer(_) => None
2436 /// Construct a parameter environment suitable for static contexts or other contexts where there
2437 /// are no free type/lifetime parameters in scope.
2438 pub fn empty_parameter_environment(self) -> ParameterEnvironment<'tcx> {
2440 // for an empty parameter environment, there ARE no free
2441 // regions, so it shouldn't matter what we use for the free id
2442 let free_id_outlive = self.region_maps.node_extent(ast::DUMMY_NODE_ID);
2443 ty::ParameterEnvironment {
2444 free_substs: self.intern_substs(&[]),
2445 caller_bounds: Vec::new(),
2446 implicit_region_bound: self.mk_region(ty::ReEmpty),
2447 free_id_outlive: free_id_outlive,
2448 is_copy_cache: RefCell::new(FxHashMap()),
2449 is_sized_cache: RefCell::new(FxHashMap()),
2453 /// Constructs and returns a substitution that can be applied to move from
2454 /// the "outer" view of a type or method to the "inner" view.
2455 /// In general, this means converting from bound parameters to
2456 /// free parameters. Since we currently represent bound/free type
2457 /// parameters in the same way, this only has an effect on regions.
2458 pub fn construct_free_substs(self, def_id: DefId,
2459 free_id_outlive: CodeExtent)
2460 -> &'gcx Substs<'gcx> {
2462 let substs = Substs::for_item(self.global_tcx(), def_id, |def, _| {
2463 // map bound 'a => free 'a
2464 self.global_tcx().mk_region(ReFree(FreeRegion {
2465 scope: free_id_outlive,
2466 bound_region: def.to_bound_region()
2470 self.global_tcx().mk_param_from_def(def)
2473 debug!("construct_parameter_environment: {:?}", substs);
2477 /// See `ParameterEnvironment` struct def'n for details.
2478 /// If you were using `free_id: NodeId`, you might try `self.region_maps.item_extent(free_id)`
2479 /// for the `free_id_outlive` parameter. (But note that this is not always quite right.)
2480 pub fn construct_parameter_environment(self,
2483 free_id_outlive: CodeExtent)
2484 -> ParameterEnvironment<'gcx>
2487 // Construct the free substs.
2490 let free_substs = self.construct_free_substs(def_id, free_id_outlive);
2493 // Compute the bounds on Self and the type parameters.
2496 let tcx = self.global_tcx();
2497 let generic_predicates = tcx.item_predicates(def_id);
2498 let bounds = generic_predicates.instantiate(tcx, free_substs);
2499 let bounds = tcx.liberate_late_bound_regions(free_id_outlive, &ty::Binder(bounds));
2500 let predicates = bounds.predicates;
2502 // Finally, we have to normalize the bounds in the environment, in
2503 // case they contain any associated type projections. This process
2504 // can yield errors if the put in illegal associated types, like
2505 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2506 // report these errors right here; this doesn't actually feel
2507 // right to me, because constructing the environment feels like a
2508 // kind of a "idempotent" action, but I'm not sure where would be
2509 // a better place. In practice, we construct environments for
2510 // every fn once during type checking, and we'll abort if there
2511 // are any errors at that point, so after type checking you can be
2512 // sure that this will succeed without errors anyway.
2515 let unnormalized_env = ty::ParameterEnvironment {
2516 free_substs: free_substs,
2517 implicit_region_bound: tcx.mk_region(ty::ReScope(free_id_outlive)),
2518 caller_bounds: predicates,
2519 free_id_outlive: free_id_outlive,
2520 is_copy_cache: RefCell::new(FxHashMap()),
2521 is_sized_cache: RefCell::new(FxHashMap()),
2524 let cause = traits::ObligationCause::misc(span, free_id_outlive.node_id(&self.region_maps));
2525 traits::normalize_param_env_or_error(tcx, unnormalized_env, cause)
2528 pub fn node_scope_region(self, id: NodeId) -> &'tcx Region {
2529 self.mk_region(ty::ReScope(self.region_maps.node_extent(id)))
2532 pub fn visit_all_item_likes_in_krate<V,F>(self,
2535 where F: FnMut(DefId) -> DepNode<DefId>, V: ItemLikeVisitor<'gcx>
2537 dep_graph::visit_all_item_likes_in_krate(self.global_tcx(), dep_node_fn, visitor);
2540 /// Invokes `callback` for each body in the krate. This will
2541 /// create a read edge from `DepNode::Krate` to the current task;
2542 /// it is meant to be run in the context of some global task like
2543 /// `BorrowckCrate`. The callback would then create a task like
2544 /// `BorrowckBody(DefId)` to process each individual item.
2545 pub fn visit_all_bodies_in_krate<C>(self, callback: C)
2546 where C: Fn(/* body_owner */ DefId, /* body id */ hir::BodyId),
2548 dep_graph::visit_all_bodies_in_krate(self.global_tcx(), callback)
2551 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2552 /// with the name of the crate containing the impl.
2553 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2554 if impl_did.is_local() {
2555 let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2556 Ok(self.hir.span(node_id))
2558 Err(self.sess.cstore.crate_name(impl_did.krate))
2563 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2564 pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2565 F: FnOnce(&[hir::Freevar]) -> T,
2567 match self.freevars.borrow().get(&fid) {
2569 Some(d) => f(&d[..])
2574 fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
2577 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2578 let parent_id = tcx.hir.get_parent(id);
2579 let parent_def_id = tcx.hir.local_def_id(parent_id);
2580 let parent_item = tcx.hir.expect_item(parent_id);
2581 match parent_item.node {
2582 hir::ItemImpl(.., ref impl_trait_ref, _, ref impl_item_refs) => {
2583 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.node_id == id) {
2585 tcx.associated_item_from_impl_item_ref(parent_def_id,
2586 impl_trait_ref.is_some(),
2588 debug_assert_eq!(assoc_item.def_id, def_id);
2593 hir::ItemTrait(.., ref trait_item_refs) => {
2594 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.node_id == id) {
2596 tcx.associated_item_from_trait_item_ref(parent_def_id, trait_item_ref);
2597 debug_assert_eq!(assoc_item.def_id, def_id);
2603 panic!("unexpected container of associated items: {:?}", r)
2606 panic!("associated item not found for def_id: {:?}", def_id);
2609 pub fn provide(providers: &mut ty::maps::Providers) {
2610 *providers = ty::maps::Providers {
2617 /// A map for the local crate mapping each type to a vector of its
2618 /// inherent impls. This is not meant to be used outside of coherence;
2619 /// rather, you should request the vector for a specific type via
2620 /// `ty::queries::inherent_impls::get(def_id)` so as to minimize your
2621 /// dependencies (constructing this map requires touching the entire
2623 #[derive(Clone, Debug)]
2624 pub struct CrateInherentImpls {
2625 pub inherent_impls: DefIdMap<Rc<Vec<DefId>>>,