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::ImplOrTraitItemId::*;
12 pub use self::Variance::*;
13 pub use self::DtorKind::*;
14 pub use self::ImplOrTraitItemContainer::*;
15 pub use self::BorrowKind::*;
16 pub use self::ImplOrTraitItem::*;
17 pub use self::IntVarValue::*;
18 pub use self::LvaluePreference::*;
19 pub use self::fold::TypeFoldable;
21 use dep_graph::{self, DepNode};
22 use front::map as ast_map;
23 use front::map::LinkedPath;
25 use middle::cstore::{self, CrateStore, LOCAL_CRATE};
26 use middle::def::{self, Def, ExportMap};
27 use middle::def_id::DefId;
28 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
29 use middle::region::{CodeExtent};
30 use middle::subst::{self, Subst, Substs, VecPerParamSpace};
33 use middle::ty::fold::TypeFolder;
34 use middle::ty::walk::TypeWalker;
35 use util::common::MemoizationMap;
36 use util::nodemap::{NodeMap, NodeSet};
37 use util::nodemap::FnvHashMap;
39 use serialize::{Encodable, Encoder, Decodable, Decoder};
40 use std::borrow::{Borrow, Cow};
42 use std::hash::{Hash, Hasher};
46 use std::vec::IntoIter;
47 use std::collections::{HashMap, HashSet};
48 use syntax::ast::{self, CrateNum, Name, NodeId};
49 use syntax::attr::{self, AttrMetaMethods};
50 use syntax::codemap::{DUMMY_SP, Span};
51 use syntax::parse::token::InternedString;
53 use rustc_const_eval::ConstInt;
56 use rustc_front::hir::{ItemImpl, ItemTrait, PatKind};
57 use rustc_front::intravisit::Visitor;
59 pub use self::sty::{Binder, DebruijnIndex};
60 pub use self::sty::{BuiltinBound, BuiltinBounds, ExistentialBounds};
61 pub use self::sty::{BareFnTy, FnSig, PolyFnSig, FnOutput, PolyFnOutput};
62 pub use self::sty::{ClosureTy, InferTy, ParamTy, ProjectionTy, TraitTy};
63 pub use self::sty::{ClosureSubsts, TypeAndMut};
64 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
65 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
66 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid, SkolemizedRegionVid};
67 pub use self::sty::BoundRegion::*;
68 pub use self::sty::FnOutput::*;
69 pub use self::sty::InferTy::*;
70 pub use self::sty::Region::*;
71 pub use self::sty::TypeVariants::*;
73 pub use self::sty::BuiltinBound::Send as BoundSend;
74 pub use self::sty::BuiltinBound::Sized as BoundSized;
75 pub use self::sty::BuiltinBound::Copy as BoundCopy;
76 pub use self::sty::BuiltinBound::Sync as BoundSync;
78 pub use self::contents::TypeContents;
79 pub use self::context::{TyCtxt, tls};
80 pub use self::context::{CtxtArenas, Lift, Tables};
82 pub use self::trait_def::{TraitDef, TraitFlags};
102 mod structural_impls;
105 pub type Disr = ConstInt;
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.
111 pub struct CrateAnalysis<'a> {
112 pub export_map: ExportMap,
113 pub access_levels: middle::privacy::AccessLevels,
114 pub reachable: NodeSet,
116 pub glob_map: Option<GlobMap>,
119 #[derive(Copy, Clone)]
126 pub fn is_present(&self) -> bool {
128 TraitDtor(..) => true,
133 pub fn has_drop_flag(&self) -> bool {
136 &TraitDtor(flag) => flag
141 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
142 pub enum ImplOrTraitItemContainer {
143 TraitContainer(DefId),
144 ImplContainer(DefId),
147 impl ImplOrTraitItemContainer {
148 pub fn id(&self) -> DefId {
150 TraitContainer(id) => id,
151 ImplContainer(id) => id,
156 /// The "header" of an impl is everything outside the body: a Self type, a trait
157 /// ref (in the case of a trait impl), and a set of predicates (from the
158 /// bounds/where clauses).
159 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
160 pub struct ImplHeader<'tcx> {
161 pub impl_def_id: DefId,
162 pub self_ty: Ty<'tcx>,
163 pub trait_ref: Option<TraitRef<'tcx>>,
164 pub predicates: Vec<Predicate<'tcx>>,
167 impl<'tcx> ImplHeader<'tcx> {
168 pub fn with_fresh_ty_vars<'a>(selcx: &mut traits::SelectionContext<'a, 'tcx>,
172 let tcx = selcx.tcx();
173 let impl_generics = tcx.lookup_item_type(impl_def_id).generics;
174 let impl_substs = selcx.infcx().fresh_substs_for_generics(DUMMY_SP, &impl_generics);
176 let header = ImplHeader {
177 impl_def_id: impl_def_id,
178 self_ty: tcx.lookup_item_type(impl_def_id).ty,
179 trait_ref: tcx.impl_trait_ref(impl_def_id),
180 predicates: tcx.lookup_predicates(impl_def_id).predicates.into_vec(),
181 }.subst(tcx, &impl_substs);
183 let traits::Normalized { value: mut header, obligations } =
184 traits::normalize(selcx, traits::ObligationCause::dummy(), &header);
186 header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
192 pub enum ImplOrTraitItem<'tcx> {
193 ConstTraitItem(Rc<AssociatedConst<'tcx>>),
194 MethodTraitItem(Rc<Method<'tcx>>),
195 TypeTraitItem(Rc<AssociatedType<'tcx>>),
198 impl<'tcx> ImplOrTraitItem<'tcx> {
199 fn id(&self) -> ImplOrTraitItemId {
201 ConstTraitItem(ref associated_const) => {
202 ConstTraitItemId(associated_const.def_id)
204 MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
205 TypeTraitItem(ref associated_type) => {
206 TypeTraitItemId(associated_type.def_id)
211 pub fn def(&self) -> Def {
213 ConstTraitItem(ref associated_const) => Def::AssociatedConst(associated_const.def_id),
214 MethodTraitItem(ref method) => Def::Method(method.def_id),
215 TypeTraitItem(ref ty) => Def::AssociatedTy(ty.container.id(), ty.def_id),
219 pub fn def_id(&self) -> DefId {
221 ConstTraitItem(ref associated_const) => associated_const.def_id,
222 MethodTraitItem(ref method) => method.def_id,
223 TypeTraitItem(ref associated_type) => associated_type.def_id,
227 pub fn name(&self) -> Name {
229 ConstTraitItem(ref associated_const) => associated_const.name,
230 MethodTraitItem(ref method) => method.name,
231 TypeTraitItem(ref associated_type) => associated_type.name,
235 pub fn vis(&self) -> hir::Visibility {
237 ConstTraitItem(ref associated_const) => associated_const.vis,
238 MethodTraitItem(ref method) => method.vis,
239 TypeTraitItem(ref associated_type) => associated_type.vis,
243 pub fn container(&self) -> ImplOrTraitItemContainer {
245 ConstTraitItem(ref associated_const) => associated_const.container,
246 MethodTraitItem(ref method) => method.container,
247 TypeTraitItem(ref associated_type) => associated_type.container,
251 pub fn as_opt_method(&self) -> Option<Rc<Method<'tcx>>> {
253 MethodTraitItem(ref m) => Some((*m).clone()),
259 #[derive(Clone, Copy, Debug)]
260 pub enum ImplOrTraitItemId {
261 ConstTraitItemId(DefId),
262 MethodTraitItemId(DefId),
263 TypeTraitItemId(DefId),
266 impl ImplOrTraitItemId {
267 pub fn def_id(&self) -> DefId {
269 ConstTraitItemId(def_id) => def_id,
270 MethodTraitItemId(def_id) => def_id,
271 TypeTraitItemId(def_id) => def_id,
276 #[derive(Clone, Debug)]
277 pub struct Method<'tcx> {
279 pub generics: Generics<'tcx>,
280 pub predicates: GenericPredicates<'tcx>,
281 pub fty: BareFnTy<'tcx>,
282 pub explicit_self: ExplicitSelfCategory,
283 pub vis: hir::Visibility,
284 pub defaultness: hir::Defaultness,
286 pub container: ImplOrTraitItemContainer,
289 impl<'tcx> Method<'tcx> {
290 pub fn new(name: Name,
291 generics: ty::Generics<'tcx>,
292 predicates: GenericPredicates<'tcx>,
294 explicit_self: ExplicitSelfCategory,
295 vis: hir::Visibility,
296 defaultness: hir::Defaultness,
298 container: ImplOrTraitItemContainer)
303 predicates: predicates,
305 explicit_self: explicit_self,
307 defaultness: defaultness,
309 container: container,
313 pub fn container_id(&self) -> DefId {
314 match self.container {
315 TraitContainer(id) => id,
316 ImplContainer(id) => id,
321 impl<'tcx> PartialEq for Method<'tcx> {
323 fn eq(&self, other: &Self) -> bool { self.def_id == other.def_id }
326 impl<'tcx> Eq for Method<'tcx> {}
328 impl<'tcx> Hash for Method<'tcx> {
330 fn hash<H: Hasher>(&self, s: &mut H) {
335 #[derive(Clone, Copy, Debug)]
336 pub struct AssociatedConst<'tcx> {
339 pub vis: hir::Visibility,
340 pub defaultness: hir::Defaultness,
342 pub container: ImplOrTraitItemContainer,
346 #[derive(Clone, Copy, Debug)]
347 pub struct AssociatedType<'tcx> {
349 pub ty: Option<Ty<'tcx>>,
350 pub vis: hir::Visibility,
351 pub defaultness: hir::Defaultness,
353 pub container: ImplOrTraitItemContainer,
356 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
357 pub struct ItemVariances {
358 pub types: VecPerParamSpace<Variance>,
359 pub regions: VecPerParamSpace<Variance>,
362 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
364 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
365 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
366 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
367 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
370 #[derive(Clone, Copy, Debug)]
371 pub struct MethodCallee<'tcx> {
372 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
375 pub substs: &'tcx subst::Substs<'tcx>
378 /// With method calls, we store some extra information in
379 /// side tables (i.e method_map). We use
380 /// MethodCall as a key to index into these tables instead of
381 /// just directly using the expression's NodeId. The reason
382 /// for this being that we may apply adjustments (coercions)
383 /// with the resulting expression also needing to use the
384 /// side tables. The problem with this is that we don't
385 /// assign a separate NodeId to this new expression
386 /// and so it would clash with the base expression if both
387 /// needed to add to the side tables. Thus to disambiguate
388 /// we also keep track of whether there's an adjustment in
390 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
391 pub struct MethodCall {
397 pub fn expr(id: NodeId) -> MethodCall {
404 pub fn autoderef(expr_id: NodeId, autoderef: u32) -> MethodCall {
407 autoderef: 1 + autoderef
412 // maps from an expression id that corresponds to a method call to the details
413 // of the method to be invoked
414 pub type MethodMap<'tcx> = FnvHashMap<MethodCall, MethodCallee<'tcx>>;
416 // Contains information needed to resolve types and (in the future) look up
417 // the types of AST nodes.
418 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
419 pub struct CReaderCacheKey {
424 /// A restriction that certain types must be the same size. The use of
425 /// `transmute` gives rise to these restrictions. These generally
426 /// cannot be checked until trans; therefore, each call to `transmute`
427 /// will push one or more such restriction into the
428 /// `transmute_restrictions` vector during `intrinsicck`. They are
429 /// then checked during `trans` by the fn `check_intrinsics`.
430 #[derive(Copy, Clone)]
431 pub struct TransmuteRestriction<'tcx> {
432 /// The span whence the restriction comes.
435 /// The type being transmuted from.
436 pub original_from: Ty<'tcx>,
438 /// The type being transmuted to.
439 pub original_to: Ty<'tcx>,
441 /// The type being transmuted from, with all type parameters
442 /// substituted for an arbitrary representative. Not to be shown
444 pub substituted_from: Ty<'tcx>,
446 /// The type being transmuted to, with all type parameters
447 /// substituted for an arbitrary representative. Not to be shown
449 pub substituted_to: Ty<'tcx>,
451 /// NodeId of the transmute intrinsic.
455 /// Describes the fragment-state associated with a NodeId.
457 /// Currently only unfragmented paths have entries in the table,
458 /// but longer-term this enum is expected to expand to also
459 /// include data for fragmented paths.
460 #[derive(Copy, Clone, Debug)]
461 pub enum FragmentInfo {
462 Moved { var: NodeId, move_expr: NodeId },
463 Assigned { var: NodeId, assign_expr: NodeId, assignee_id: NodeId },
466 // Flags that we track on types. These flags are propagated upwards
467 // through the type during type construction, so that we can quickly
468 // check whether the type has various kinds of types in it without
469 // recursing over the type itself.
471 flags TypeFlags: u32 {
472 const HAS_PARAMS = 1 << 0,
473 const HAS_SELF = 1 << 1,
474 const HAS_TY_INFER = 1 << 2,
475 const HAS_RE_INFER = 1 << 3,
476 const HAS_RE_EARLY_BOUND = 1 << 4,
477 const HAS_FREE_REGIONS = 1 << 5,
478 const HAS_TY_ERR = 1 << 6,
479 const HAS_PROJECTION = 1 << 7,
480 const HAS_TY_CLOSURE = 1 << 8,
482 // true if there are "names" of types and regions and so forth
483 // that are local to a particular fn
484 const HAS_LOCAL_NAMES = 1 << 9,
486 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
487 TypeFlags::HAS_SELF.bits |
488 TypeFlags::HAS_RE_EARLY_BOUND.bits,
490 // Flags representing the nominal content of a type,
491 // computed by FlagsComputation. If you add a new nominal
492 // flag, it should be added here too.
493 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
494 TypeFlags::HAS_SELF.bits |
495 TypeFlags::HAS_TY_INFER.bits |
496 TypeFlags::HAS_RE_INFER.bits |
497 TypeFlags::HAS_RE_EARLY_BOUND.bits |
498 TypeFlags::HAS_FREE_REGIONS.bits |
499 TypeFlags::HAS_TY_ERR.bits |
500 TypeFlags::HAS_PROJECTION.bits |
501 TypeFlags::HAS_TY_CLOSURE.bits |
502 TypeFlags::HAS_LOCAL_NAMES.bits,
504 // Caches for type_is_sized, type_moves_by_default
505 const SIZEDNESS_CACHED = 1 << 16,
506 const IS_SIZED = 1 << 17,
507 const MOVENESS_CACHED = 1 << 18,
508 const MOVES_BY_DEFAULT = 1 << 19,
512 pub struct TyS<'tcx> {
513 pub sty: TypeVariants<'tcx>,
514 pub flags: Cell<TypeFlags>,
516 // the maximal depth of any bound regions appearing in this type.
520 impl<'tcx> PartialEq for TyS<'tcx> {
522 fn eq(&self, other: &TyS<'tcx>) -> bool {
523 // (self as *const _) == (other as *const _)
524 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
527 impl<'tcx> Eq for TyS<'tcx> {}
529 impl<'tcx> Hash for TyS<'tcx> {
530 fn hash<H: Hasher>(&self, s: &mut H) {
531 (self as *const TyS).hash(s)
535 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
537 impl<'tcx> Encodable for Ty<'tcx> {
538 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
539 cstore::tls::with_encoding_context(s, |ecx, rbml_w| {
540 ecx.encode_ty(rbml_w, *self);
546 impl<'tcx> Decodable for Ty<'tcx> {
547 fn decode<D: Decoder>(d: &mut D) -> Result<Ty<'tcx>, D::Error> {
548 cstore::tls::with_decoding_context(d, |dcx, rbml_r| {
549 Ok(dcx.decode_ty(rbml_r))
555 /// Upvars do not get their own node-id. Instead, we use the pair of
556 /// the original var id (that is, the root variable that is referenced
557 /// by the upvar) and the id of the closure expression.
558 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
561 pub closure_expr_id: NodeId,
564 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
565 pub enum BorrowKind {
566 /// Data must be immutable and is aliasable.
569 /// Data must be immutable but not aliasable. This kind of borrow
570 /// cannot currently be expressed by the user and is used only in
571 /// implicit closure bindings. It is needed when you the closure
572 /// is borrowing or mutating a mutable referent, e.g.:
574 /// let x: &mut isize = ...;
575 /// let y = || *x += 5;
577 /// If we were to try to translate this closure into a more explicit
578 /// form, we'd encounter an error with the code as written:
580 /// struct Env { x: & &mut isize }
581 /// let x: &mut isize = ...;
582 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
583 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
585 /// This is then illegal because you cannot mutate a `&mut` found
586 /// in an aliasable location. To solve, you'd have to translate with
587 /// an `&mut` borrow:
589 /// struct Env { x: & &mut isize }
590 /// let x: &mut isize = ...;
591 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
592 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
594 /// Now the assignment to `**env.x` is legal, but creating a
595 /// mutable pointer to `x` is not because `x` is not mutable. We
596 /// could fix this by declaring `x` as `let mut x`. This is ok in
597 /// user code, if awkward, but extra weird for closures, since the
598 /// borrow is hidden.
600 /// So we introduce a "unique imm" borrow -- the referent is
601 /// immutable, but not aliasable. This solves the problem. For
602 /// simplicity, we don't give users the way to express this
603 /// borrow, it's just used when translating closures.
606 /// Data is mutable and not aliasable.
610 /// Information describing the capture of an upvar. This is computed
611 /// during `typeck`, specifically by `regionck`.
612 #[derive(PartialEq, Clone, Debug, Copy)]
613 pub enum UpvarCapture {
614 /// Upvar is captured by value. This is always true when the
615 /// closure is labeled `move`, but can also be true in other cases
616 /// depending on inference.
619 /// Upvar is captured by reference.
623 #[derive(PartialEq, Clone, Copy)]
624 pub struct UpvarBorrow {
625 /// The kind of borrow: by-ref upvars have access to shared
626 /// immutable borrows, which are not part of the normal language
628 pub kind: BorrowKind,
630 /// Region of the resulting reference.
631 pub region: ty::Region,
634 pub type UpvarCaptureMap = FnvHashMap<UpvarId, UpvarCapture>;
636 #[derive(Copy, Clone)]
637 pub struct ClosureUpvar<'tcx> {
643 #[derive(Clone, Copy, PartialEq)]
644 pub enum IntVarValue {
646 UintType(ast::UintTy),
649 /// Default region to use for the bound of objects that are
650 /// supplied as the value for this type parameter. This is derived
651 /// from `T:'a` annotations appearing in the type definition. If
652 /// this is `None`, then the default is inherited from the
653 /// surrounding context. See RFC #599 for details.
654 #[derive(Copy, Clone)]
655 pub enum ObjectLifetimeDefault {
656 /// Require an explicit annotation. Occurs when multiple
657 /// `T:'a` constraints are found.
660 /// Use the base default, typically 'static, but in a fn body it is a fresh variable
663 /// Use the given region as the default.
668 pub struct TypeParameterDef<'tcx> {
671 pub space: subst::ParamSpace,
673 pub default_def_id: DefId, // for use in error reporing about defaults
674 pub default: Option<Ty<'tcx>>,
675 pub object_lifetime_default: ObjectLifetimeDefault,
679 pub struct RegionParameterDef {
682 pub space: subst::ParamSpace,
684 pub bounds: Vec<ty::Region>,
687 impl RegionParameterDef {
688 pub fn to_early_bound_region(&self) -> ty::Region {
689 ty::ReEarlyBound(ty::EarlyBoundRegion {
695 pub fn to_bound_region(&self) -> ty::BoundRegion {
696 ty::BoundRegion::BrNamed(self.def_id, self.name)
700 /// Information about the formal type/lifetime parameters associated
701 /// with an item or method. Analogous to hir::Generics.
702 #[derive(Clone, Debug)]
703 pub struct Generics<'tcx> {
704 pub types: VecPerParamSpace<TypeParameterDef<'tcx>>,
705 pub regions: VecPerParamSpace<RegionParameterDef>,
708 impl<'tcx> Generics<'tcx> {
709 pub fn empty() -> Generics<'tcx> {
711 types: VecPerParamSpace::empty(),
712 regions: VecPerParamSpace::empty(),
716 pub fn is_empty(&self) -> bool {
717 self.types.is_empty() && self.regions.is_empty()
720 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
721 !self.types.is_empty_in(space)
724 pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
725 !self.regions.is_empty_in(space)
729 /// Bounds on generics.
731 pub struct GenericPredicates<'tcx> {
732 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
735 impl<'tcx> GenericPredicates<'tcx> {
736 pub fn empty() -> GenericPredicates<'tcx> {
738 predicates: VecPerParamSpace::empty(),
742 pub fn instantiate(&self, tcx: &TyCtxt<'tcx>, substs: &Substs<'tcx>)
743 -> InstantiatedPredicates<'tcx> {
744 InstantiatedPredicates {
745 predicates: self.predicates.subst(tcx, substs),
749 pub fn instantiate_supertrait(&self,
751 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
752 -> InstantiatedPredicates<'tcx>
754 InstantiatedPredicates {
755 predicates: self.predicates.map(|pred| pred.subst_supertrait(tcx, poly_trait_ref))
760 #[derive(Clone, PartialEq, Eq, Hash)]
761 pub enum Predicate<'tcx> {
762 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
763 /// the `Self` type of the trait reference and `A`, `B`, and `C`
764 /// would be the parameters in the `TypeSpace`.
765 Trait(PolyTraitPredicate<'tcx>),
767 /// where `T1 == T2`.
768 Equate(PolyEquatePredicate<'tcx>),
771 RegionOutlives(PolyRegionOutlivesPredicate),
774 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
776 /// where <T as TraitRef>::Name == X, approximately.
777 /// See `ProjectionPredicate` struct for details.
778 Projection(PolyProjectionPredicate<'tcx>),
781 WellFormed(Ty<'tcx>),
783 /// trait must be object-safe
787 impl<'tcx> Predicate<'tcx> {
788 /// Performs a substitution suitable for going from a
789 /// poly-trait-ref to supertraits that must hold if that
790 /// poly-trait-ref holds. This is slightly different from a normal
791 /// substitution in terms of what happens with bound regions. See
792 /// lengthy comment below for details.
793 pub fn subst_supertrait(&self,
795 trait_ref: &ty::PolyTraitRef<'tcx>)
796 -> ty::Predicate<'tcx>
798 // The interaction between HRTB and supertraits is not entirely
799 // obvious. Let me walk you (and myself) through an example.
801 // Let's start with an easy case. Consider two traits:
803 // trait Foo<'a> : Bar<'a,'a> { }
804 // trait Bar<'b,'c> { }
806 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
807 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
808 // knew that `Foo<'x>` (for any 'x) then we also know that
809 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
810 // normal substitution.
812 // In terms of why this is sound, the idea is that whenever there
813 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
814 // holds. So if there is an impl of `T:Foo<'a>` that applies to
815 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
818 // Another example to be careful of is this:
820 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
821 // trait Bar1<'b,'c> { }
823 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
824 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
825 // reason is similar to the previous example: any impl of
826 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
827 // basically we would want to collapse the bound lifetimes from
828 // the input (`trait_ref`) and the supertraits.
830 // To achieve this in practice is fairly straightforward. Let's
831 // consider the more complicated scenario:
833 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
834 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
835 // where both `'x` and `'b` would have a DB index of 1.
836 // The substitution from the input trait-ref is therefore going to be
837 // `'a => 'x` (where `'x` has a DB index of 1).
838 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
839 // early-bound parameter and `'b' is a late-bound parameter with a
841 // - If we replace `'a` with `'x` from the input, it too will have
842 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
843 // just as we wanted.
845 // There is only one catch. If we just apply the substitution `'a
846 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
847 // adjust the DB index because we substituting into a binder (it
848 // tries to be so smart...) resulting in `for<'x> for<'b>
849 // Bar1<'x,'b>` (we have no syntax for this, so use your
850 // imagination). Basically the 'x will have DB index of 2 and 'b
851 // will have DB index of 1. Not quite what we want. So we apply
852 // the substitution to the *contents* of the trait reference,
853 // rather than the trait reference itself (put another way, the
854 // substitution code expects equal binding levels in the values
855 // from the substitution and the value being substituted into, and
856 // this trick achieves that).
858 let substs = &trait_ref.0.substs;
860 Predicate::Trait(ty::Binder(ref data)) =>
861 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
862 Predicate::Equate(ty::Binder(ref data)) =>
863 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
864 Predicate::RegionOutlives(ty::Binder(ref data)) =>
865 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
866 Predicate::TypeOutlives(ty::Binder(ref data)) =>
867 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
868 Predicate::Projection(ty::Binder(ref data)) =>
869 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
870 Predicate::WellFormed(data) =>
871 Predicate::WellFormed(data.subst(tcx, substs)),
872 Predicate::ObjectSafe(trait_def_id) =>
873 Predicate::ObjectSafe(trait_def_id),
878 #[derive(Clone, PartialEq, Eq, Hash)]
879 pub struct TraitPredicate<'tcx> {
880 pub trait_ref: TraitRef<'tcx>
882 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
884 impl<'tcx> TraitPredicate<'tcx> {
885 pub fn def_id(&self) -> DefId {
886 self.trait_ref.def_id
889 /// Creates the dep-node for selecting/evaluating this trait reference.
890 fn dep_node(&self) -> DepNode {
891 DepNode::TraitSelect(self.def_id())
894 pub fn input_types(&self) -> &[Ty<'tcx>] {
895 self.trait_ref.substs.types.as_slice()
898 pub fn self_ty(&self) -> Ty<'tcx> {
899 self.trait_ref.self_ty()
903 impl<'tcx> PolyTraitPredicate<'tcx> {
904 pub fn def_id(&self) -> DefId {
905 // ok to skip binder since trait def-id does not care about regions
909 pub fn dep_node(&self) -> DepNode {
910 // ok to skip binder since depnode does not care about regions
915 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
916 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
917 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
919 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
920 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
921 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
922 pub type PolyRegionOutlivesPredicate = PolyOutlivesPredicate<ty::Region, ty::Region>;
923 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region>;
925 /// This kind of predicate has no *direct* correspondent in the
926 /// syntax, but it roughly corresponds to the syntactic forms:
928 /// 1. `T : TraitRef<..., Item=Type>`
929 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
931 /// In particular, form #1 is "desugared" to the combination of a
932 /// normal trait predicate (`T : TraitRef<...>`) and one of these
933 /// predicates. Form #2 is a broader form in that it also permits
934 /// equality between arbitrary types. Processing an instance of Form
935 /// #2 eventually yields one of these `ProjectionPredicate`
936 /// instances to normalize the LHS.
937 #[derive(Clone, PartialEq, Eq, Hash)]
938 pub struct ProjectionPredicate<'tcx> {
939 pub projection_ty: ProjectionTy<'tcx>,
943 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
945 impl<'tcx> PolyProjectionPredicate<'tcx> {
946 pub fn item_name(&self) -> Name {
947 self.0.projection_ty.item_name // safe to skip the binder to access a name
950 pub fn sort_key(&self) -> (DefId, Name) {
951 self.0.projection_ty.sort_key()
955 pub trait ToPolyTraitRef<'tcx> {
956 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
959 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
960 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
961 assert!(!self.has_escaping_regions());
962 ty::Binder(self.clone())
966 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
967 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
968 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
972 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
973 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
974 // Note: unlike with TraitRef::to_poly_trait_ref(),
975 // self.0.trait_ref is permitted to have escaping regions.
976 // This is because here `self` has a `Binder` and so does our
977 // return value, so we are preserving the number of binding
979 ty::Binder(self.0.projection_ty.trait_ref)
983 pub trait ToPredicate<'tcx> {
984 fn to_predicate(&self) -> Predicate<'tcx>;
987 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
988 fn to_predicate(&self) -> Predicate<'tcx> {
989 // we're about to add a binder, so let's check that we don't
990 // accidentally capture anything, or else that might be some
991 // weird debruijn accounting.
992 assert!(!self.has_escaping_regions());
994 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
995 trait_ref: self.clone()
1000 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1001 fn to_predicate(&self) -> Predicate<'tcx> {
1002 ty::Predicate::Trait(self.to_poly_trait_predicate())
1006 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
1007 fn to_predicate(&self) -> Predicate<'tcx> {
1008 Predicate::Equate(self.clone())
1012 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate {
1013 fn to_predicate(&self) -> Predicate<'tcx> {
1014 Predicate::RegionOutlives(self.clone())
1018 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1019 fn to_predicate(&self) -> Predicate<'tcx> {
1020 Predicate::TypeOutlives(self.clone())
1024 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1025 fn to_predicate(&self) -> Predicate<'tcx> {
1026 Predicate::Projection(self.clone())
1030 impl<'tcx> Predicate<'tcx> {
1031 /// Iterates over the types in this predicate. Note that in all
1032 /// cases this is skipping over a binder, so late-bound regions
1033 /// with depth 0 are bound by the predicate.
1034 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1035 let vec: Vec<_> = match *self {
1036 ty::Predicate::Trait(ref data) => {
1037 data.0.trait_ref.substs.types.as_slice().to_vec()
1039 ty::Predicate::Equate(ty::Binder(ref data)) => {
1040 vec![data.0, data.1]
1042 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1045 ty::Predicate::RegionOutlives(..) => {
1048 ty::Predicate::Projection(ref data) => {
1049 let trait_inputs = data.0.projection_ty.trait_ref.substs.types.as_slice();
1052 .chain(Some(data.0.ty))
1055 ty::Predicate::WellFormed(data) => {
1058 ty::Predicate::ObjectSafe(_trait_def_id) => {
1063 // The only reason to collect into a vector here is that I was
1064 // too lazy to make the full (somewhat complicated) iterator
1065 // type that would be needed here. But I wanted this fn to
1066 // return an iterator conceptually, rather than a `Vec`, so as
1067 // to be closer to `Ty::walk`.
1071 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1073 Predicate::Trait(ref t) => {
1074 Some(t.to_poly_trait_ref())
1076 Predicate::Projection(..) |
1077 Predicate::Equate(..) |
1078 Predicate::RegionOutlives(..) |
1079 Predicate::WellFormed(..) |
1080 Predicate::ObjectSafe(..) |
1081 Predicate::TypeOutlives(..) => {
1088 /// Represents the bounds declared on a particular set of type
1089 /// parameters. Should eventually be generalized into a flag list of
1090 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
1091 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1092 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1093 /// the `GenericPredicates` are expressed in terms of the bound type
1094 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1095 /// represented a set of bounds for some particular instantiation,
1096 /// meaning that the generic parameters have been substituted with
1101 /// struct Foo<T,U:Bar<T>> { ... }
1103 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1104 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1105 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1106 /// [usize:Bar<isize>]]`.
1108 pub struct InstantiatedPredicates<'tcx> {
1109 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
1112 impl<'tcx> InstantiatedPredicates<'tcx> {
1113 pub fn empty() -> InstantiatedPredicates<'tcx> {
1114 InstantiatedPredicates { predicates: VecPerParamSpace::empty() }
1117 pub fn is_empty(&self) -> bool {
1118 self.predicates.is_empty()
1122 impl<'tcx> TraitRef<'tcx> {
1123 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
1124 TraitRef { def_id: def_id, substs: substs }
1127 pub fn self_ty(&self) -> Ty<'tcx> {
1128 self.substs.self_ty().unwrap()
1131 pub fn input_types(&self) -> &[Ty<'tcx>] {
1132 // Select only the "input types" from a trait-reference. For
1133 // now this is all the types that appear in the
1134 // trait-reference, but it should eventually exclude
1135 // associated types.
1136 self.substs.types.as_slice()
1140 /// When type checking, we use the `ParameterEnvironment` to track
1141 /// details about the type/lifetime parameters that are in scope.
1142 /// It primarily stores the bounds information.
1144 /// Note: This information might seem to be redundant with the data in
1145 /// `tcx.ty_param_defs`, but it is not. That table contains the
1146 /// parameter definitions from an "outside" perspective, but this
1147 /// struct will contain the bounds for a parameter as seen from inside
1148 /// the function body. Currently the only real distinction is that
1149 /// bound lifetime parameters are replaced with free ones, but in the
1150 /// future I hope to refine the representation of types so as to make
1151 /// more distinctions clearer.
1153 pub struct ParameterEnvironment<'a, 'tcx:'a> {
1154 pub tcx: &'a TyCtxt<'tcx>,
1156 /// See `construct_free_substs` for details.
1157 pub free_substs: Substs<'tcx>,
1159 /// Each type parameter has an implicit region bound that
1160 /// indicates it must outlive at least the function body (the user
1161 /// may specify stronger requirements). This field indicates the
1162 /// region of the callee.
1163 pub implicit_region_bound: ty::Region,
1165 /// Obligations that the caller must satisfy. This is basically
1166 /// the set of bounds on the in-scope type parameters, translated
1167 /// into Obligations, and elaborated and normalized.
1168 pub caller_bounds: Vec<ty::Predicate<'tcx>>,
1170 /// Caches the results of trait selection. This cache is used
1171 /// for things that have to do with the parameters in scope.
1172 pub selection_cache: traits::SelectionCache<'tcx>,
1174 /// Caches the results of trait evaluation.
1175 pub evaluation_cache: traits::EvaluationCache<'tcx>,
1177 /// Scope that is attached to free regions for this scope. This
1178 /// is usually the id of the fn body, but for more abstract scopes
1179 /// like structs we often use the node-id of the struct.
1181 /// FIXME(#3696). It would be nice to refactor so that free
1182 /// regions don't have this implicit scope and instead introduce
1183 /// relationships in the environment.
1184 pub free_id_outlive: CodeExtent,
1187 impl<'a, 'tcx> ParameterEnvironment<'a, 'tcx> {
1188 pub fn with_caller_bounds(&self,
1189 caller_bounds: Vec<ty::Predicate<'tcx>>)
1190 -> ParameterEnvironment<'a,'tcx>
1192 ParameterEnvironment {
1194 free_substs: self.free_substs.clone(),
1195 implicit_region_bound: self.implicit_region_bound,
1196 caller_bounds: caller_bounds,
1197 selection_cache: traits::SelectionCache::new(),
1198 evaluation_cache: traits::EvaluationCache::new(),
1199 free_id_outlive: self.free_id_outlive,
1203 pub fn for_item(cx: &'a TyCtxt<'tcx>, id: NodeId) -> ParameterEnvironment<'a, 'tcx> {
1204 match cx.map.find(id) {
1205 Some(ast_map::NodeImplItem(ref impl_item)) => {
1206 match impl_item.node {
1207 hir::ImplItemKind::Type(_) => {
1208 // associated types don't have their own entry (for some reason),
1209 // so for now just grab environment for the impl
1210 let impl_id = cx.map.get_parent(id);
1211 let impl_def_id = cx.map.local_def_id(impl_id);
1212 let scheme = cx.lookup_item_type(impl_def_id);
1213 let predicates = cx.lookup_predicates(impl_def_id);
1214 cx.construct_parameter_environment(impl_item.span,
1217 cx.region_maps.item_extent(id))
1219 hir::ImplItemKind::Const(_, _) => {
1220 let def_id = cx.map.local_def_id(id);
1221 let scheme = cx.lookup_item_type(def_id);
1222 let predicates = cx.lookup_predicates(def_id);
1223 cx.construct_parameter_environment(impl_item.span,
1226 cx.region_maps.item_extent(id))
1228 hir::ImplItemKind::Method(_, ref body) => {
1229 let method_def_id = cx.map.local_def_id(id);
1230 match cx.impl_or_trait_item(method_def_id) {
1231 MethodTraitItem(ref method_ty) => {
1232 let method_generics = &method_ty.generics;
1233 let method_bounds = &method_ty.predicates;
1234 cx.construct_parameter_environment(
1238 cx.region_maps.call_site_extent(id, body.id))
1242 .bug("ParameterEnvironment::for_item(): \
1243 got non-method item from impl method?!")
1249 Some(ast_map::NodeTraitItem(trait_item)) => {
1250 match trait_item.node {
1251 hir::TypeTraitItem(..) => {
1252 // associated types don't have their own entry (for some reason),
1253 // so for now just grab environment for the trait
1254 let trait_id = cx.map.get_parent(id);
1255 let trait_def_id = cx.map.local_def_id(trait_id);
1256 let trait_def = cx.lookup_trait_def(trait_def_id);
1257 let predicates = cx.lookup_predicates(trait_def_id);
1258 cx.construct_parameter_environment(trait_item.span,
1259 &trait_def.generics,
1261 cx.region_maps.item_extent(id))
1263 hir::ConstTraitItem(..) => {
1264 let def_id = cx.map.local_def_id(id);
1265 let scheme = cx.lookup_item_type(def_id);
1266 let predicates = cx.lookup_predicates(def_id);
1267 cx.construct_parameter_environment(trait_item.span,
1270 cx.region_maps.item_extent(id))
1272 hir::MethodTraitItem(_, ref body) => {
1273 // Use call-site for extent (unless this is a
1274 // trait method with no default; then fallback
1275 // to the method id).
1276 let method_def_id = cx.map.local_def_id(id);
1277 match cx.impl_or_trait_item(method_def_id) {
1278 MethodTraitItem(ref method_ty) => {
1279 let method_generics = &method_ty.generics;
1280 let method_bounds = &method_ty.predicates;
1281 let extent = if let Some(ref body) = *body {
1282 // default impl: use call_site extent as free_id_outlive bound.
1283 cx.region_maps.call_site_extent(id, body.id)
1285 // no default impl: use item extent as free_id_outlive bound.
1286 cx.region_maps.item_extent(id)
1288 cx.construct_parameter_environment(
1296 .bug("ParameterEnvironment::for_item(): \
1297 got non-method item from provided \
1304 Some(ast_map::NodeItem(item)) => {
1306 hir::ItemFn(_, _, _, _, _, ref body) => {
1307 // We assume this is a function.
1308 let fn_def_id = cx.map.local_def_id(id);
1309 let fn_scheme = cx.lookup_item_type(fn_def_id);
1310 let fn_predicates = cx.lookup_predicates(fn_def_id);
1312 cx.construct_parameter_environment(item.span,
1313 &fn_scheme.generics,
1315 cx.region_maps.call_site_extent(id,
1319 hir::ItemStruct(..) |
1321 hir::ItemConst(..) |
1322 hir::ItemStatic(..) => {
1323 let def_id = cx.map.local_def_id(id);
1324 let scheme = cx.lookup_item_type(def_id);
1325 let predicates = cx.lookup_predicates(def_id);
1326 cx.construct_parameter_environment(item.span,
1329 cx.region_maps.item_extent(id))
1331 hir::ItemTrait(..) => {
1332 let def_id = cx.map.local_def_id(id);
1333 let trait_def = cx.lookup_trait_def(def_id);
1334 let predicates = cx.lookup_predicates(def_id);
1335 cx.construct_parameter_environment(item.span,
1336 &trait_def.generics,
1338 cx.region_maps.item_extent(id))
1341 cx.sess.span_bug(item.span,
1342 "ParameterEnvironment::from_item():
1343 can't create a parameter \
1344 environment for this kind of item")
1348 Some(ast_map::NodeExpr(..)) => {
1349 // This is a convenience to allow closures to work.
1350 ParameterEnvironment::for_item(cx, cx.map.get_parent(id))
1353 cx.sess.bug(&format!("ParameterEnvironment::from_item(): \
1354 `{}` is not an item",
1355 cx.map.node_to_string(id)))
1361 /// A "type scheme", in ML terminology, is a type combined with some
1362 /// set of generic types that the type is, well, generic over. In Rust
1363 /// terms, it is the "type" of a fn item or struct -- this type will
1364 /// include various generic parameters that must be substituted when
1365 /// the item/struct is referenced. That is called converting the type
1366 /// scheme to a monotype.
1368 /// - `generics`: the set of type parameters and their bounds
1369 /// - `ty`: the base types, which may reference the parameters defined
1372 /// Note that TypeSchemes are also sometimes called "polytypes" (and
1373 /// in fact this struct used to carry that name, so you may find some
1374 /// stray references in a comment or something). We try to reserve the
1375 /// "poly" prefix to refer to higher-ranked things, as in
1378 /// Note that each item also comes with predicates, see
1379 /// `lookup_predicates`.
1380 #[derive(Clone, Debug)]
1381 pub struct TypeScheme<'tcx> {
1382 pub generics: Generics<'tcx>,
1387 flags AdtFlags: u32 {
1388 const NO_ADT_FLAGS = 0,
1389 const IS_ENUM = 1 << 0,
1390 const IS_DTORCK = 1 << 1, // is this a dtorck type?
1391 const IS_DTORCK_VALID = 1 << 2,
1392 const IS_PHANTOM_DATA = 1 << 3,
1393 const IS_SIMD = 1 << 4,
1394 const IS_FUNDAMENTAL = 1 << 5,
1395 const IS_NO_DROP_FLAG = 1 << 6,
1399 pub type AdtDef<'tcx> = &'tcx AdtDefData<'tcx, 'static>;
1400 pub type VariantDef<'tcx> = &'tcx VariantDefData<'tcx, 'static>;
1401 pub type FieldDef<'tcx> = &'tcx FieldDefData<'tcx, 'static>;
1403 // See comment on AdtDefData for explanation
1404 pub type AdtDefMaster<'tcx> = &'tcx AdtDefData<'tcx, 'tcx>;
1405 pub type VariantDefMaster<'tcx> = &'tcx VariantDefData<'tcx, 'tcx>;
1406 pub type FieldDefMaster<'tcx> = &'tcx FieldDefData<'tcx, 'tcx>;
1408 pub struct VariantDefData<'tcx, 'container: 'tcx> {
1409 /// The variant's DefId. If this is a tuple-like struct,
1410 /// this is the DefId of the struct's ctor.
1412 pub name: Name, // struct's name if this is a struct
1414 pub fields: Vec<FieldDefData<'tcx, 'container>>,
1415 pub kind: VariantKind,
1418 pub struct FieldDefData<'tcx, 'container: 'tcx> {
1419 /// The field's DefId. NOTE: the fields of tuple-like enum variants
1420 /// are not real items, and don't have entries in tcache etc.
1423 pub vis: hir::Visibility,
1424 /// TyIVar is used here to allow for variance (see the doc at
1427 /// Note: direct accesses to `ty` must also add dep edges.
1428 ty: ivar::TyIVar<'tcx, 'container>
1431 /// The definition of an abstract data type - a struct or enum.
1433 /// These are all interned (by intern_adt_def) into the adt_defs
1436 /// Because of the possibility of nested tcx-s, this type
1437 /// needs 2 lifetimes: the traditional variant lifetime ('tcx)
1438 /// bounding the lifetime of the inner types is of course necessary.
1439 /// However, it is not sufficient - types from a child tcx must
1440 /// not be leaked into the master tcx by being stored in an AdtDefData.
1442 /// The 'container lifetime ensures that by outliving the container
1443 /// tcx and preventing shorter-lived types from being inserted. When
1444 /// write access is not needed, the 'container lifetime can be
1445 /// erased to 'static, which can be done by the AdtDef wrapper.
1446 pub struct AdtDefData<'tcx, 'container: 'tcx> {
1448 pub variants: Vec<VariantDefData<'tcx, 'container>>,
1449 destructor: Cell<Option<DefId>>,
1450 flags: Cell<AdtFlags>,
1453 impl<'tcx, 'container> PartialEq for AdtDefData<'tcx, 'container> {
1454 // AdtDefData are always interned and this is part of TyS equality
1456 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1459 impl<'tcx, 'container> Eq for AdtDefData<'tcx, 'container> {}
1461 impl<'tcx, 'container> Hash for AdtDefData<'tcx, 'container> {
1463 fn hash<H: Hasher>(&self, s: &mut H) {
1464 (self as *const AdtDefData).hash(s)
1468 impl<'tcx> Encodable for AdtDef<'tcx> {
1469 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1474 impl<'tcx> Decodable for AdtDef<'tcx> {
1475 fn decode<D: Decoder>(d: &mut D) -> Result<AdtDef<'tcx>, D::Error> {
1476 let def_id: DefId = Decodable::decode(d)?;
1478 cstore::tls::with_decoding_context(d, |dcx, _| {
1479 let def_id = dcx.translate_def_id(def_id);
1480 Ok(dcx.tcx().lookup_adt_def(def_id))
1486 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1487 pub enum AdtKind { Struct, Enum }
1489 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1490 pub enum VariantKind { Struct, Tuple, Unit }
1493 pub fn from_variant_data(vdata: &hir::VariantData) -> Self {
1495 hir::VariantData::Struct(..) => VariantKind::Struct,
1496 hir::VariantData::Tuple(..) => VariantKind::Tuple,
1497 hir::VariantData::Unit(..) => VariantKind::Unit,
1502 impl<'tcx, 'container> AdtDefData<'tcx, 'container> {
1503 fn new(tcx: &TyCtxt<'tcx>,
1506 variants: Vec<VariantDefData<'tcx, 'container>>) -> Self {
1507 let mut flags = AdtFlags::NO_ADT_FLAGS;
1508 let attrs = tcx.get_attrs(did);
1509 if attr::contains_name(&attrs, "fundamental") {
1510 flags = flags | AdtFlags::IS_FUNDAMENTAL;
1512 if attr::contains_name(&attrs, "unsafe_no_drop_flag") {
1513 flags = flags | AdtFlags::IS_NO_DROP_FLAG;
1515 if tcx.lookup_simd(did) {
1516 flags = flags | AdtFlags::IS_SIMD;
1518 if Some(did) == tcx.lang_items.phantom_data() {
1519 flags = flags | AdtFlags::IS_PHANTOM_DATA;
1521 if let AdtKind::Enum = kind {
1522 flags = flags | AdtFlags::IS_ENUM;
1527 flags: Cell::new(flags),
1528 destructor: Cell::new(None)
1532 fn calculate_dtorck(&'tcx self, tcx: &TyCtxt<'tcx>) {
1533 if tcx.is_adt_dtorck(self) {
1534 self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK);
1536 self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK_VALID)
1539 /// Returns the kind of the ADT - Struct or Enum.
1541 pub fn adt_kind(&self) -> AdtKind {
1542 if self.flags.get().intersects(AdtFlags::IS_ENUM) {
1549 /// Returns whether this is a dtorck type. If this returns
1550 /// true, this type being safe for destruction requires it to be
1551 /// alive; Otherwise, only the contents are required to be.
1553 pub fn is_dtorck(&'tcx self, tcx: &TyCtxt<'tcx>) -> bool {
1554 if !self.flags.get().intersects(AdtFlags::IS_DTORCK_VALID) {
1555 self.calculate_dtorck(tcx)
1557 self.flags.get().intersects(AdtFlags::IS_DTORCK)
1560 /// Returns whether this type is #[fundamental] for the purposes
1561 /// of coherence checking.
1563 pub fn is_fundamental(&self) -> bool {
1564 self.flags.get().intersects(AdtFlags::IS_FUNDAMENTAL)
1568 pub fn is_simd(&self) -> bool {
1569 self.flags.get().intersects(AdtFlags::IS_SIMD)
1572 /// Returns true if this is PhantomData<T>.
1574 pub fn is_phantom_data(&self) -> bool {
1575 self.flags.get().intersects(AdtFlags::IS_PHANTOM_DATA)
1578 /// Returns whether this type has a destructor.
1579 pub fn has_dtor(&self) -> bool {
1580 match self.dtor_kind() {
1582 TraitDtor(..) => true
1586 /// Asserts this is a struct and returns the struct's unique
1588 pub fn struct_variant(&self) -> &VariantDefData<'tcx, 'container> {
1589 assert_eq!(self.adt_kind(), AdtKind::Struct);
1594 pub fn type_scheme(&self, tcx: &TyCtxt<'tcx>) -> TypeScheme<'tcx> {
1595 tcx.lookup_item_type(self.did)
1599 pub fn predicates(&self, tcx: &TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
1600 tcx.lookup_predicates(self.did)
1603 /// Returns an iterator over all fields contained
1606 pub fn all_fields(&self) ->
1608 slice::Iter<VariantDefData<'tcx, 'container>>,
1609 slice::Iter<FieldDefData<'tcx, 'container>>,
1610 for<'s> fn(&'s VariantDefData<'tcx, 'container>)
1611 -> slice::Iter<'s, FieldDefData<'tcx, 'container>>
1613 self.variants.iter().flat_map(VariantDefData::fields_iter)
1617 pub fn is_empty(&self) -> bool {
1618 self.variants.is_empty()
1622 pub fn is_univariant(&self) -> bool {
1623 self.variants.len() == 1
1626 pub fn is_payloadfree(&self) -> bool {
1627 !self.variants.is_empty() &&
1628 self.variants.iter().all(|v| v.fields.is_empty())
1631 pub fn variant_with_id(&self, vid: DefId) -> &VariantDefData<'tcx, 'container> {
1634 .find(|v| v.did == vid)
1635 .expect("variant_with_id: unknown variant")
1638 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1641 .position(|v| v.did == vid)
1642 .expect("variant_index_with_id: unknown variant")
1645 pub fn variant_of_def(&self, def: Def) -> &VariantDefData<'tcx, 'container> {
1647 Def::Variant(_, vid) => self.variant_with_id(vid),
1648 Def::Struct(..) | Def::TyAlias(..) => self.struct_variant(),
1649 _ => panic!("unexpected def {:?} in variant_of_def", def)
1653 pub fn destructor(&self) -> Option<DefId> {
1654 self.destructor.get()
1657 pub fn set_destructor(&self, dtor: DefId) {
1658 self.destructor.set(Some(dtor));
1661 pub fn dtor_kind(&self) -> DtorKind {
1662 match self.destructor.get() {
1664 TraitDtor(!self.flags.get().intersects(AdtFlags::IS_NO_DROP_FLAG))
1671 impl<'tcx, 'container> VariantDefData<'tcx, 'container> {
1673 fn fields_iter(&self) -> slice::Iter<FieldDefData<'tcx, 'container>> {
1677 pub fn kind(&self) -> VariantKind {
1681 pub fn is_tuple_struct(&self) -> bool {
1682 self.kind() == VariantKind::Tuple
1686 pub fn find_field_named(&self,
1688 -> Option<&FieldDefData<'tcx, 'container>> {
1689 self.fields.iter().find(|f| f.name == name)
1693 pub fn index_of_field_named(&self,
1696 self.fields.iter().position(|f| f.name == name)
1700 pub fn field_named(&self, name: ast::Name) -> &FieldDefData<'tcx, 'container> {
1701 self.find_field_named(name).unwrap()
1705 impl<'tcx, 'container> FieldDefData<'tcx, 'container> {
1706 pub fn new(did: DefId,
1708 vis: hir::Visibility) -> Self {
1713 ty: ivar::TyIVar::new()
1717 pub fn ty(&self, tcx: &TyCtxt<'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1718 self.unsubst_ty().subst(tcx, subst)
1721 pub fn unsubst_ty(&self) -> Ty<'tcx> {
1722 self.ty.unwrap(DepNode::FieldTy(self.did))
1725 pub fn fulfill_ty(&self, ty: Ty<'container>) {
1726 self.ty.fulfill(DepNode::FieldTy(self.did), ty);
1730 /// Records the substitutions used to translate the polytype for an
1731 /// item into the monotype of an item reference.
1733 pub struct ItemSubsts<'tcx> {
1734 pub substs: Substs<'tcx>,
1737 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
1738 pub enum ClosureKind {
1739 // Warning: Ordering is significant here! The ordering is chosen
1740 // because the trait Fn is a subtrait of FnMut and so in turn, and
1741 // hence we order it so that Fn < FnMut < FnOnce.
1748 pub fn trait_did(&self, cx: &TyCtxt) -> DefId {
1749 let result = match *self {
1750 ClosureKind::Fn => cx.lang_items.require(FnTraitLangItem),
1751 ClosureKind::FnMut => {
1752 cx.lang_items.require(FnMutTraitLangItem)
1754 ClosureKind::FnOnce => {
1755 cx.lang_items.require(FnOnceTraitLangItem)
1759 Ok(trait_did) => trait_did,
1760 Err(err) => cx.sess.fatal(&err[..]),
1764 /// True if this a type that impls this closure kind
1765 /// must also implement `other`.
1766 pub fn extends(self, other: ty::ClosureKind) -> bool {
1767 match (self, other) {
1768 (ClosureKind::Fn, ClosureKind::Fn) => true,
1769 (ClosureKind::Fn, ClosureKind::FnMut) => true,
1770 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
1771 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
1772 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
1773 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
1779 impl<'tcx> TyS<'tcx> {
1780 /// Iterator that walks `self` and any types reachable from
1781 /// `self`, in depth-first order. Note that just walks the types
1782 /// that appear in `self`, it does not descend into the fields of
1783 /// structs or variants. For example:
1786 /// isize => { isize }
1787 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
1788 /// [isize] => { [isize], isize }
1790 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
1791 TypeWalker::new(self)
1794 /// Iterator that walks the immediate children of `self`. Hence
1795 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
1796 /// (but not `i32`, like `walk`).
1797 pub fn walk_shallow(&'tcx self) -> IntoIter<Ty<'tcx>> {
1798 walk::walk_shallow(self)
1801 /// Walks `ty` and any types appearing within `ty`, invoking the
1802 /// callback `f` on each type. If the callback returns false, then the
1803 /// children of the current type are ignored.
1805 /// Note: prefer `ty.walk()` where possible.
1806 pub fn maybe_walk<F>(&'tcx self, mut f: F)
1807 where F : FnMut(Ty<'tcx>) -> bool
1809 let mut walker = self.walk();
1810 while let Some(ty) = walker.next() {
1812 walker.skip_current_subtree();
1818 impl<'tcx> ItemSubsts<'tcx> {
1819 pub fn empty() -> ItemSubsts<'tcx> {
1820 ItemSubsts { substs: Substs::empty() }
1823 pub fn is_noop(&self) -> bool {
1824 self.substs.is_noop()
1828 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1829 pub enum LvaluePreference {
1834 impl LvaluePreference {
1835 pub fn from_mutbl(m: hir::Mutability) -> Self {
1837 hir::MutMutable => PreferMutLvalue,
1838 hir::MutImmutable => NoPreference,
1843 /// Helper for looking things up in the various maps that are populated during
1844 /// typeck::collect (e.g., `cx.impl_or_trait_items`, `cx.tcache`, etc). All of
1845 /// these share the pattern that if the id is local, it should have been loaded
1846 /// into the map by the `typeck::collect` phase. If the def-id is external,
1847 /// then we have to go consult the crate loading code (and cache the result for
1849 fn lookup_locally_or_in_crate_store<M, F>(descr: &str,
1854 M: MemoizationMap<Key=DefId>,
1855 F: FnOnce() -> M::Value,
1857 map.memoize(def_id, || {
1858 if def_id.is_local() {
1859 panic!("No def'n found for {:?} in tcx.{}", def_id, descr);
1866 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
1868 hir::MutMutable => MutBorrow,
1869 hir::MutImmutable => ImmBorrow,
1873 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
1874 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
1875 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
1877 pub fn to_mutbl_lossy(self) -> hir::Mutability {
1879 MutBorrow => hir::MutMutable,
1880 ImmBorrow => hir::MutImmutable,
1882 // We have no type corresponding to a unique imm borrow, so
1883 // use `&mut`. It gives all the capabilities of an `&uniq`
1884 // and hence is a safe "over approximation".
1885 UniqueImmBorrow => hir::MutMutable,
1889 pub fn to_user_str(&self) -> &'static str {
1891 MutBorrow => "mutable",
1892 ImmBorrow => "immutable",
1893 UniqueImmBorrow => "uniquely immutable",
1898 impl<'tcx> TyCtxt<'tcx> {
1899 pub fn node_id_to_type(&self, id: NodeId) -> Ty<'tcx> {
1900 match self.node_id_to_type_opt(id) {
1902 None => self.sess.bug(
1903 &format!("node_id_to_type: no type for node `{}`",
1904 self.map.node_to_string(id)))
1908 pub fn node_id_to_type_opt(&self, id: NodeId) -> Option<Ty<'tcx>> {
1909 self.tables.borrow().node_types.get(&id).cloned()
1912 pub fn node_id_item_substs(&self, id: NodeId) -> ItemSubsts<'tcx> {
1913 match self.tables.borrow().item_substs.get(&id) {
1914 None => ItemSubsts::empty(),
1915 Some(ts) => ts.clone(),
1919 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
1920 // doesn't provide type parameter substitutions.
1921 pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
1922 self.node_id_to_type(pat.id)
1924 pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
1925 self.node_id_to_type_opt(pat.id)
1928 // Returns the type of an expression as a monotype.
1930 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
1931 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
1932 // auto-ref. The type returned by this function does not consider such
1933 // adjustments. See `expr_ty_adjusted()` instead.
1935 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
1936 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
1937 // instead of "fn(ty) -> T with T = isize".
1938 pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
1939 self.node_id_to_type(expr.id)
1942 pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
1943 self.node_id_to_type_opt(expr.id)
1946 /// Returns the type of `expr`, considering any `AutoAdjustment`
1947 /// entry recorded for that expression.
1949 /// It would almost certainly be better to store the adjusted ty in with
1950 /// the `AutoAdjustment`, but I opted not to do this because it would
1951 /// require serializing and deserializing the type and, although that's not
1952 /// hard to do, I just hate that code so much I didn't want to touch it
1953 /// unless it was to fix it properly, which seemed a distraction from the
1954 /// thread at hand! -nmatsakis
1955 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
1957 .adjust(self, expr.span, expr.id,
1958 self.tables.borrow().adjustments.get(&expr.id),
1960 self.tables.borrow().method_map.get(&method_call).map(|method| method.ty)
1964 pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
1965 self.expr_ty_opt(expr).map(|t| t.adjust(self,
1968 self.tables.borrow().adjustments.get(&expr.id),
1970 self.tables.borrow().method_map.get(&method_call).map(|method| method.ty)
1974 pub fn expr_span(&self, id: NodeId) -> Span {
1975 match self.map.find(id) {
1976 Some(ast_map::NodeExpr(e)) => {
1980 self.sess.bug(&format!("Node id {} is not an expr: {:?}",
1984 self.sess.bug(&format!("Node id {} is not present \
1985 in the node map", id));
1990 pub fn local_var_name_str(&self, id: NodeId) -> InternedString {
1991 match self.map.find(id) {
1992 Some(ast_map::NodeLocal(pat)) => {
1994 PatKind::Ident(_, ref path1, _) => path1.node.name.as_str(),
1996 self.sess.bug(&format!("Variable id {} maps to {:?}, not local", id, pat));
2000 r => self.sess.bug(&format!("Variable id {} maps to {:?}, not local", id, r)),
2004 pub fn resolve_expr(&self, expr: &hir::Expr) -> Def {
2005 match self.def_map.borrow().get(&expr.id) {
2006 Some(def) => def.full_def(),
2008 self.sess.span_bug(expr.span, &format!(
2009 "no def-map entry for expr {}", expr.id));
2014 pub fn expr_is_lval(&self, expr: &hir::Expr) -> bool {
2016 hir::ExprPath(..) => {
2017 // We can't use resolve_expr here, as this needs to run on broken
2018 // programs. We don't need to through - associated items are all
2020 match self.def_map.borrow().get(&expr.id) {
2021 Some(&def::PathResolution {
2022 base_def: Def::Static(..), ..
2023 }) | Some(&def::PathResolution {
2024 base_def: Def::Upvar(..), ..
2025 }) | Some(&def::PathResolution {
2026 base_def: Def::Local(..), ..
2030 Some(&def::PathResolution { base_def: Def::Err, .. })=> true,
2032 None => self.sess.span_bug(expr.span, &format!(
2033 "no def for path {}", expr.id))
2037 hir::ExprType(ref e, _) => {
2038 self.expr_is_lval(e)
2041 hir::ExprUnary(hir::UnDeref, _) |
2042 hir::ExprField(..) |
2043 hir::ExprTupField(..) |
2044 hir::ExprIndex(..) => {
2049 hir::ExprMethodCall(..) |
2050 hir::ExprStruct(..) |
2053 hir::ExprMatch(..) |
2054 hir::ExprClosure(..) |
2055 hir::ExprBlock(..) |
2056 hir::ExprRepeat(..) |
2058 hir::ExprBreak(..) |
2059 hir::ExprAgain(..) |
2061 hir::ExprWhile(..) |
2063 hir::ExprAssign(..) |
2064 hir::ExprInlineAsm(..) |
2065 hir::ExprAssignOp(..) |
2067 hir::ExprUnary(..) |
2069 hir::ExprAddrOf(..) |
2070 hir::ExprBinary(..) |
2071 hir::ExprCast(..) => {
2077 pub fn provided_trait_methods(&self, id: DefId) -> Vec<Rc<Method<'tcx>>> {
2078 if let Some(id) = self.map.as_local_node_id(id) {
2079 if let ItemTrait(_, _, _, ref ms) = self.map.expect_item(id).node {
2080 ms.iter().filter_map(|ti| {
2081 if let hir::MethodTraitItem(_, Some(_)) = ti.node {
2082 match self.impl_or_trait_item(self.map.local_def_id(ti.id)) {
2083 MethodTraitItem(m) => Some(m),
2085 self.sess.bug("provided_trait_methods(): \
2086 non-method item found from \
2087 looking up provided method?!")
2095 self.sess.bug(&format!("provided_trait_methods: `{:?}` is not a trait", id))
2098 self.sess.cstore.provided_trait_methods(self, id)
2102 pub fn associated_consts(&self, id: DefId) -> Vec<Rc<AssociatedConst<'tcx>>> {
2103 if let Some(id) = self.map.as_local_node_id(id) {
2104 match self.map.expect_item(id).node {
2105 ItemTrait(_, _, _, ref tis) => {
2106 tis.iter().filter_map(|ti| {
2107 if let hir::ConstTraitItem(_, _) = ti.node {
2108 match self.impl_or_trait_item(self.map.local_def_id(ti.id)) {
2109 ConstTraitItem(ac) => Some(ac),
2111 self.sess.bug("associated_consts(): \
2112 non-const item found from \
2113 looking up a constant?!")
2121 ItemImpl(_, _, _, _, _, ref iis) => {
2122 iis.iter().filter_map(|ii| {
2123 if let hir::ImplItemKind::Const(_, _) = ii.node {
2124 match self.impl_or_trait_item(self.map.local_def_id(ii.id)) {
2125 ConstTraitItem(ac) => Some(ac),
2127 self.sess.bug("associated_consts(): \
2128 non-const item found from \
2129 looking up a constant?!")
2138 self.sess.bug(&format!("associated_consts: `{:?}` is not a trait \
2143 self.sess.cstore.associated_consts(self, id)
2147 pub fn trait_impl_polarity(&self, id: DefId) -> Option<hir::ImplPolarity> {
2148 if let Some(id) = self.map.as_local_node_id(id) {
2149 match self.map.find(id) {
2150 Some(ast_map::NodeItem(item)) => {
2152 hir::ItemImpl(_, polarity, _, _, _, _) => Some(polarity),
2159 self.sess.cstore.impl_polarity(id)
2163 pub fn custom_coerce_unsized_kind(&self, did: DefId) -> adjustment::CustomCoerceUnsized {
2164 self.custom_coerce_unsized_kinds.memoize(did, || {
2165 let (kind, src) = if did.krate != LOCAL_CRATE {
2166 (self.sess.cstore.custom_coerce_unsized_kind(did), "external")
2174 self.sess.bug(&format!("custom_coerce_unsized_kind: \
2175 {} impl `{}` is missing its kind",
2176 src, self.item_path_str(did)));
2182 pub fn impl_or_trait_item(&self, id: DefId) -> ImplOrTraitItem<'tcx> {
2183 lookup_locally_or_in_crate_store(
2184 "impl_or_trait_items", id, &self.impl_or_trait_items,
2185 || self.sess.cstore.impl_or_trait_item(self, id)
2186 .expect("missing ImplOrTraitItem in metadata"))
2189 pub fn trait_item_def_ids(&self, id: DefId) -> Rc<Vec<ImplOrTraitItemId>> {
2190 lookup_locally_or_in_crate_store(
2191 "trait_item_def_ids", id, &self.trait_item_def_ids,
2192 || Rc::new(self.sess.cstore.trait_item_def_ids(id)))
2195 /// Returns the trait-ref corresponding to a given impl, or None if it is
2196 /// an inherent impl.
2197 pub fn impl_trait_ref(&self, id: DefId) -> Option<TraitRef<'tcx>> {
2198 lookup_locally_or_in_crate_store(
2199 "impl_trait_refs", id, &self.impl_trait_refs,
2200 || self.sess.cstore.impl_trait_ref(self, id))
2203 /// Returns whether this DefId refers to an impl
2204 pub fn is_impl(&self, id: DefId) -> bool {
2205 if let Some(id) = self.map.as_local_node_id(id) {
2206 if let Some(ast_map::NodeItem(
2207 &hir::Item { node: hir::ItemImpl(..), .. })) = self.map.find(id) {
2213 self.sess.cstore.is_impl(id)
2217 pub fn trait_ref_to_def_id(&self, tr: &hir::TraitRef) -> DefId {
2218 self.def_map.borrow().get(&tr.ref_id).expect("no def-map entry for trait").def_id()
2221 pub fn item_path_str(&self, id: DefId) -> String {
2222 self.with_path(id, |path| ast_map::path_to_string(path))
2225 /// Returns the `DefPath` of an item. Note that if `id` is not
2226 /// local to this crate -- or is inlined into this crate -- the
2227 /// result will be a non-local `DefPath`.
2228 pub fn def_path(&self, id: DefId) -> ast_map::DefPath {
2230 self.map.def_path(id)
2232 self.sess.cstore.relative_def_path(id)
2236 pub fn with_path<T, F>(&self, id: DefId, f: F) -> T where
2237 F: FnOnce(ast_map::PathElems) -> T,
2239 if let Some(id) = self.map.as_local_node_id(id) {
2240 self.map.with_path(id, f)
2242 let mut path: Vec<_>;
2243 if let Some(extern_crate) = self.sess.cstore.extern_crate(id.krate) {
2244 if !extern_crate.direct {
2245 // this comes from some crate that we don't have a direct
2246 // path to; we'll settle for just prepending the name of
2248 path = self.sess.cstore.extern_item_path(id)
2250 // start with the path to the extern crate, then
2251 // add the relative path to the actual item
2252 fn collector(elems: ast_map::PathElems) -> Vec<ast_map::PathElem> {
2255 path = self.with_path(extern_crate.def_id, collector);
2256 path.extend(self.sess.cstore.relative_item_path(id));
2259 // if this was injected, just make a path with name of crate
2260 path = self.sess.cstore.extern_item_path(id);
2262 f(path.iter().cloned().chain(LinkedPath::empty()))
2266 pub fn item_name(&self, id: DefId) -> ast::Name {
2267 if let Some(id) = self.map.as_local_node_id(id) {
2268 self.map.get_path_elem(id).name()
2270 self.sess.cstore.item_name(id)
2274 // Register a given item type
2275 pub fn register_item_type(&self, did: DefId, ty: TypeScheme<'tcx>) {
2276 self.tcache.borrow_mut().insert(did, ty);
2279 // If the given item is in an external crate, looks up its type and adds it to
2280 // the type cache. Returns the type parameters and type.
2281 pub fn lookup_item_type(&self, did: DefId) -> TypeScheme<'tcx> {
2282 lookup_locally_or_in_crate_store(
2283 "tcache", did, &self.tcache,
2284 || self.sess.cstore.item_type(self, did))
2287 /// Given the did of a trait, returns its canonical trait ref.
2288 pub fn lookup_trait_def(&self, did: DefId) -> &'tcx TraitDef<'tcx> {
2289 lookup_locally_or_in_crate_store(
2290 "trait_defs", did, &self.trait_defs,
2291 || self.alloc_trait_def(self.sess.cstore.trait_def(self, did))
2295 /// Given the did of an ADT, return a master reference to its
2296 /// definition. Unless you are planning on fulfilling the ADT's fields,
2297 /// use lookup_adt_def instead.
2298 pub fn lookup_adt_def_master(&self, did: DefId) -> AdtDefMaster<'tcx> {
2299 lookup_locally_or_in_crate_store(
2300 "adt_defs", did, &self.adt_defs,
2301 || self.sess.cstore.adt_def(self, did)
2305 /// Given the did of an ADT, return a reference to its definition.
2306 pub fn lookup_adt_def(&self, did: DefId) -> AdtDef<'tcx> {
2307 // when reverse-variance goes away, a transmute::<AdtDefMaster,AdtDef>
2308 // would be needed here.
2309 self.lookup_adt_def_master(did)
2312 /// Given the did of an item, returns its full set of predicates.
2313 pub fn lookup_predicates(&self, did: DefId) -> GenericPredicates<'tcx> {
2314 lookup_locally_or_in_crate_store(
2315 "predicates", did, &self.predicates,
2316 || self.sess.cstore.item_predicates(self, did))
2319 /// Given the did of a trait, returns its superpredicates.
2320 pub fn lookup_super_predicates(&self, did: DefId) -> GenericPredicates<'tcx> {
2321 lookup_locally_or_in_crate_store(
2322 "super_predicates", did, &self.super_predicates,
2323 || self.sess.cstore.item_super_predicates(self, did))
2326 /// If `type_needs_drop` returns true, then `ty` is definitely
2327 /// non-copy and *might* have a destructor attached; if it returns
2328 /// false, then `ty` definitely has no destructor (i.e. no drop glue).
2330 /// (Note that this implies that if `ty` has a destructor attached,
2331 /// then `type_needs_drop` will definitely return `true` for `ty`.)
2332 pub fn type_needs_drop_given_env<'a>(&self,
2334 param_env: &ty::ParameterEnvironment<'a,'tcx>) -> bool {
2335 // Issue #22536: We first query type_moves_by_default. It sees a
2336 // normalized version of the type, and therefore will definitely
2337 // know whether the type implements Copy (and thus needs no
2338 // cleanup/drop/zeroing) ...
2339 let implements_copy = !ty.moves_by_default(param_env, DUMMY_SP);
2341 if implements_copy { return false; }
2343 // ... (issue #22536 continued) but as an optimization, still use
2344 // prior logic of asking if the `needs_drop` bit is set; we need
2345 // not zero non-Copy types if they have no destructor.
2347 // FIXME(#22815): Note that calling `ty::type_contents` is a
2348 // conservative heuristic; it may report that `needs_drop` is set
2349 // when actual type does not actually have a destructor associated
2350 // with it. But since `ty` absolutely did not have the `Copy`
2351 // bound attached (see above), it is sound to treat it as having a
2352 // destructor (e.g. zero its memory on move).
2354 let contents = ty.type_contents(self);
2355 debug!("type_needs_drop ty={:?} contents={:?}", ty, contents);
2356 contents.needs_drop(self)
2359 /// Get the attributes of a definition.
2360 pub fn get_attrs(&self, did: DefId) -> Cow<'tcx, [ast::Attribute]> {
2361 if let Some(id) = self.map.as_local_node_id(did) {
2362 Cow::Borrowed(self.map.attrs(id))
2364 Cow::Owned(self.sess.cstore.item_attrs(did))
2368 /// Determine whether an item is annotated with an attribute
2369 pub fn has_attr(&self, did: DefId, attr: &str) -> bool {
2370 self.get_attrs(did).iter().any(|item| item.check_name(attr))
2373 /// Determine whether an item is annotated with `#[repr(packed)]`
2374 pub fn lookup_packed(&self, did: DefId) -> bool {
2375 self.lookup_repr_hints(did).contains(&attr::ReprPacked)
2378 /// Determine whether an item is annotated with `#[simd]`
2379 pub fn lookup_simd(&self, did: DefId) -> bool {
2380 self.has_attr(did, "simd")
2381 || self.lookup_repr_hints(did).contains(&attr::ReprSimd)
2384 pub fn item_variances(&self, item_id: DefId) -> Rc<ItemVariances> {
2385 lookup_locally_or_in_crate_store(
2386 "item_variance_map", item_id, &self.item_variance_map,
2387 || Rc::new(self.sess.cstore.item_variances(item_id)))
2390 pub fn trait_has_default_impl(&self, trait_def_id: DefId) -> bool {
2391 self.populate_implementations_for_trait_if_necessary(trait_def_id);
2393 let def = self.lookup_trait_def(trait_def_id);
2394 def.flags.get().intersects(TraitFlags::HAS_DEFAULT_IMPL)
2397 /// Records a trait-to-implementation mapping.
2398 pub fn record_trait_has_default_impl(&self, trait_def_id: DefId) {
2399 let def = self.lookup_trait_def(trait_def_id);
2400 def.flags.set(def.flags.get() | TraitFlags::HAS_DEFAULT_IMPL)
2403 /// Load primitive inherent implementations if necessary
2404 pub fn populate_implementations_for_primitive_if_necessary(&self,
2405 primitive_def_id: DefId) {
2406 if primitive_def_id.is_local() {
2410 // The primitive is not local, hence we are reading this out
2412 let _ignore = self.dep_graph.in_ignore();
2414 if self.populated_external_primitive_impls.borrow().contains(&primitive_def_id) {
2418 debug!("populate_implementations_for_primitive_if_necessary: searching for {:?}",
2421 let impl_items = self.sess.cstore.impl_items(primitive_def_id);
2423 // Store the implementation info.
2424 self.impl_items.borrow_mut().insert(primitive_def_id, impl_items);
2425 self.populated_external_primitive_impls.borrow_mut().insert(primitive_def_id);
2428 /// Populates the type context with all the inherent implementations for
2429 /// the given type if necessary.
2430 pub fn populate_inherent_implementations_for_type_if_necessary(&self,
2432 if type_id.is_local() {
2436 // The type is not local, hence we are reading this out of
2437 // metadata and don't need to track edges.
2438 let _ignore = self.dep_graph.in_ignore();
2440 if self.populated_external_types.borrow().contains(&type_id) {
2444 debug!("populate_inherent_implementations_for_type_if_necessary: searching for {:?}",
2447 let inherent_impls = self.sess.cstore.inherent_implementations_for_type(type_id);
2448 for &impl_def_id in &inherent_impls {
2449 // Store the implementation info.
2450 let impl_items = self.sess.cstore.impl_items(impl_def_id);
2451 self.impl_items.borrow_mut().insert(impl_def_id, impl_items);
2454 self.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
2455 self.populated_external_types.borrow_mut().insert(type_id);
2458 /// Populates the type context with all the implementations for the given
2459 /// trait if necessary.
2460 pub fn populate_implementations_for_trait_if_necessary(&self, trait_id: DefId) {
2461 if trait_id.is_local() {
2465 // The type is not local, hence we are reading this out of
2466 // metadata and don't need to track edges.
2467 let _ignore = self.dep_graph.in_ignore();
2469 let def = self.lookup_trait_def(trait_id);
2470 if def.flags.get().intersects(TraitFlags::IMPLS_VALID) {
2474 debug!("populate_implementations_for_trait_if_necessary: searching for {:?}", def);
2476 if self.sess.cstore.is_defaulted_trait(trait_id) {
2477 self.record_trait_has_default_impl(trait_id);
2480 for impl_def_id in self.sess.cstore.implementations_of_trait(trait_id) {
2481 let impl_items = self.sess.cstore.impl_items(impl_def_id);
2482 let trait_ref = self.impl_trait_ref(impl_def_id).unwrap();
2484 // Record the trait->implementation mapping.
2485 if let Some(parent) = self.sess.cstore.impl_parent(impl_def_id) {
2486 def.record_remote_impl(self, impl_def_id, trait_ref, parent);
2488 def.record_remote_impl(self, impl_def_id, trait_ref, trait_id);
2491 // For any methods that use a default implementation, add them to
2492 // the map. This is a bit unfortunate.
2493 for impl_item_def_id in &impl_items {
2494 let method_def_id = impl_item_def_id.def_id();
2495 // load impl items eagerly for convenience
2496 // FIXME: we may want to load these lazily
2497 self.impl_or_trait_item(method_def_id);
2500 // Store the implementation info.
2501 self.impl_items.borrow_mut().insert(impl_def_id, impl_items);
2504 def.flags.set(def.flags.get() | TraitFlags::IMPLS_VALID);
2507 pub fn closure_kind(&self, def_id: DefId) -> ty::ClosureKind {
2508 Tables::closure_kind(&self.tables, self, def_id)
2511 pub fn closure_type(&self,
2513 substs: &ClosureSubsts<'tcx>)
2514 -> ty::ClosureTy<'tcx>
2516 Tables::closure_type(&self.tables, self, def_id, substs)
2519 /// Given the def_id of an impl, return the def_id of the trait it implements.
2520 /// If it implements no trait, return `None`.
2521 pub fn trait_id_of_impl(&self, def_id: DefId) -> Option<DefId> {
2522 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2525 /// If the given def ID describes a method belonging to an impl, return the
2526 /// ID of the impl that the method belongs to. Otherwise, return `None`.
2527 pub fn impl_of_method(&self, def_id: DefId) -> Option<DefId> {
2528 if def_id.krate != LOCAL_CRATE {
2529 return self.sess.cstore.impl_or_trait_item(self, def_id).and_then(|item| {
2530 match item.container() {
2531 TraitContainer(_) => None,
2532 ImplContainer(def_id) => Some(def_id),
2536 match self.impl_or_trait_items.borrow().get(&def_id).cloned() {
2537 Some(trait_item) => {
2538 match trait_item.container() {
2539 TraitContainer(_) => None,
2540 ImplContainer(def_id) => Some(def_id),
2547 /// If the given def ID describes an item belonging to a trait (either a
2548 /// default method or an implementation of a trait method), return the ID of
2549 /// the trait that the method belongs to. Otherwise, return `None`.
2550 pub fn trait_of_item(&self, def_id: DefId) -> Option<DefId> {
2551 if def_id.krate != LOCAL_CRATE {
2552 return self.sess.cstore.trait_of_item(self, def_id);
2554 match self.impl_or_trait_items.borrow().get(&def_id).cloned() {
2555 Some(impl_or_trait_item) => {
2556 match impl_or_trait_item.container() {
2557 TraitContainer(def_id) => Some(def_id),
2558 ImplContainer(def_id) => self.trait_id_of_impl(def_id),
2565 /// If the given def ID describes an item belonging to a trait, (either a
2566 /// default method or an implementation of a trait method), return the ID of
2567 /// the method inside trait definition (this means that if the given def ID
2568 /// is already that of the original trait method, then the return value is
2570 /// Otherwise, return `None`.
2571 pub fn trait_item_of_item(&self, def_id: DefId) -> Option<ImplOrTraitItemId> {
2572 let impl_item = match self.impl_or_trait_items.borrow().get(&def_id) {
2573 Some(m) => m.clone(),
2574 None => return None,
2576 let name = impl_item.name();
2577 match self.trait_of_item(def_id) {
2578 Some(trait_did) => {
2579 self.trait_items(trait_did).iter()
2580 .find(|item| item.name() == name)
2581 .map(|item| item.id())
2587 /// Construct a parameter environment suitable for static contexts or other contexts where there
2588 /// are no free type/lifetime parameters in scope.
2589 pub fn empty_parameter_environment<'a>(&'a self)
2590 -> ParameterEnvironment<'a,'tcx> {
2592 // for an empty parameter environment, there ARE no free
2593 // regions, so it shouldn't matter what we use for the free id
2594 let free_id_outlive = self.region_maps.node_extent(ast::DUMMY_NODE_ID);
2595 ty::ParameterEnvironment { tcx: self,
2596 free_substs: Substs::empty(),
2597 caller_bounds: Vec::new(),
2598 implicit_region_bound: ty::ReEmpty,
2599 selection_cache: traits::SelectionCache::new(),
2600 evaluation_cache: traits::EvaluationCache::new(),
2601 free_id_outlive: free_id_outlive }
2604 /// Constructs and returns a substitution that can be applied to move from
2605 /// the "outer" view of a type or method to the "inner" view.
2606 /// In general, this means converting from bound parameters to
2607 /// free parameters. Since we currently represent bound/free type
2608 /// parameters in the same way, this only has an effect on regions.
2609 pub fn construct_free_substs(&self, generics: &Generics<'tcx>,
2610 free_id_outlive: CodeExtent) -> Substs<'tcx> {
2612 let mut types = VecPerParamSpace::empty();
2613 for def in generics.types.as_slice() {
2614 debug!("construct_parameter_environment(): push_types_from_defs: def={:?}",
2616 types.push(def.space, self.mk_param_from_def(def));
2619 // map bound 'a => free 'a
2620 let mut regions = VecPerParamSpace::empty();
2621 for def in generics.regions.as_slice() {
2623 ReFree(FreeRegion { scope: free_id_outlive,
2624 bound_region: BrNamed(def.def_id, def.name) });
2625 debug!("push_region_params {:?}", region);
2626 regions.push(def.space, region);
2635 /// See `ParameterEnvironment` struct def'n for details.
2636 /// If you were using `free_id: NodeId`, you might try `self.region_maps.item_extent(free_id)`
2637 /// for the `free_id_outlive` parameter. (But note that that is not always quite right.)
2638 pub fn construct_parameter_environment<'a>(&'a self,
2640 generics: &ty::Generics<'tcx>,
2641 generic_predicates: &ty::GenericPredicates<'tcx>,
2642 free_id_outlive: CodeExtent)
2643 -> ParameterEnvironment<'a, 'tcx>
2646 // Construct the free substs.
2649 let free_substs = self.construct_free_substs(generics, free_id_outlive);
2652 // Compute the bounds on Self and the type parameters.
2655 let bounds = generic_predicates.instantiate(self, &free_substs);
2656 let bounds = self.liberate_late_bound_regions(free_id_outlive, &ty::Binder(bounds));
2657 let predicates = bounds.predicates.into_vec();
2659 // Finally, we have to normalize the bounds in the environment, in
2660 // case they contain any associated type projections. This process
2661 // can yield errors if the put in illegal associated types, like
2662 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2663 // report these errors right here; this doesn't actually feel
2664 // right to me, because constructing the environment feels like a
2665 // kind of a "idempotent" action, but I'm not sure where would be
2666 // a better place. In practice, we construct environments for
2667 // every fn once during type checking, and we'll abort if there
2668 // are any errors at that point, so after type checking you can be
2669 // sure that this will succeed without errors anyway.
2672 let unnormalized_env = ty::ParameterEnvironment {
2674 free_substs: free_substs,
2675 implicit_region_bound: ty::ReScope(free_id_outlive),
2676 caller_bounds: predicates,
2677 selection_cache: traits::SelectionCache::new(),
2678 evaluation_cache: traits::EvaluationCache::new(),
2679 free_id_outlive: free_id_outlive,
2682 let cause = traits::ObligationCause::misc(span, free_id_outlive.node_id(&self.region_maps));
2683 traits::normalize_param_env_or_error(unnormalized_env, cause)
2686 pub fn is_method_call(&self, expr_id: NodeId) -> bool {
2687 self.tables.borrow().method_map.contains_key(&MethodCall::expr(expr_id))
2690 pub fn is_overloaded_autoderef(&self, expr_id: NodeId, autoderefs: u32) -> bool {
2691 self.tables.borrow().method_map.contains_key(&MethodCall::autoderef(expr_id,
2695 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
2696 Some(self.tables.borrow().upvar_capture_map.get(&upvar_id).unwrap().clone())
2699 pub fn visit_all_items_in_krate<V,F>(&self,
2702 where F: FnMut(DefId) -> DepNode, V: Visitor<'tcx>
2704 dep_graph::visit_all_items_in_krate(self, dep_node_fn, visitor);
2707 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2708 /// with the name of the crate containing the impl.
2709 pub fn span_of_impl(&self, impl_did: DefId) -> Result<Span, InternedString> {
2710 if impl_did.is_local() {
2711 let node_id = self.map.as_local_node_id(impl_did).unwrap();
2712 Ok(self.map.span(node_id))
2714 Err(self.sess.cstore.crate_name(impl_did.krate))
2719 /// The category of explicit self.
2720 #[derive(Clone, Copy, Eq, PartialEq, Debug)]
2721 pub enum ExplicitSelfCategory {
2724 ByReference(Region, hir::Mutability),
2728 /// A free variable referred to in a function.
2729 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
2730 pub struct Freevar {
2731 /// The variable being accessed free.
2734 // First span where it is accessed (there can be multiple).
2738 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2740 pub type CaptureModeMap = NodeMap<hir::CaptureClause>;
2742 // Trait method resolution
2743 pub type TraitMap = NodeMap<Vec<DefId>>;
2745 // Map from the NodeId of a glob import to a list of items which are actually
2747 pub type GlobMap = HashMap<NodeId, HashSet<Name>>;
2749 impl<'tcx> TyCtxt<'tcx> {
2750 pub fn with_freevars<T, F>(&self, fid: NodeId, f: F) -> T where
2751 F: FnOnce(&[Freevar]) -> T,
2753 match self.freevars.borrow().get(&fid) {
2755 Some(d) => f(&d[..])