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};
21 use hir::def::{Def, CtorKind, ExportMap};
22 use hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
23 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
24 use middle::region::{CodeExtent, ROOT_CODE_EXTENT};
28 use ty::subst::{Subst, Substs};
29 use ty::walk::TypeWalker;
30 use util::common::MemoizationMap;
31 use util::nodemap::{NodeSet, NodeMap, FxHashMap};
33 use serialize::{self, Encodable, Encoder};
35 use std::cell::{Cell, RefCell, Ref};
36 use std::hash::{Hash, Hasher};
41 use std::vec::IntoIter;
43 use syntax::ast::{self, Name, NodeId};
45 use syntax::symbol::{Symbol, InternedString};
46 use syntax_pos::{DUMMY_SP, Span};
48 use rustc_const_math::ConstInt;
49 use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
52 use hir::itemlikevisit::ItemLikeVisitor;
54 pub use self::sty::{Binder, DebruijnIndex};
55 pub use self::sty::{BareFnTy, FnSig, PolyFnSig};
56 pub use self::sty::{ClosureTy, InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
57 pub use self::sty::{ClosureSubsts, TypeAndMut};
58 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
59 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
60 pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
61 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
62 pub use self::sty::Issue32330;
63 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid, SkolemizedRegionVid};
64 pub use self::sty::BoundRegion::*;
65 pub use self::sty::InferTy::*;
66 pub use self::sty::Region::*;
67 pub use self::sty::TypeVariants::*;
69 pub use self::contents::TypeContents;
70 pub use self::context::{TyCtxt, GlobalArenas, tls};
71 pub use self::context::{Lift, TypeckTables};
73 pub use self::trait_def::{TraitDef, TraitFlags};
80 pub mod inhabitedness;
99 pub type Disr = ConstInt;
103 /// The complete set of all analyses described in this module. This is
104 /// produced by the driver and fed to trans and later passes.
106 pub struct CrateAnalysis<'tcx> {
107 pub export_map: ExportMap,
108 pub access_levels: middle::privacy::AccessLevels,
109 pub reachable: NodeSet,
111 pub glob_map: Option<hir::GlobMap>,
112 pub hir_ty_to_ty: NodeMap<Ty<'tcx>>,
116 pub struct Resolutions {
117 pub freevars: FreevarMap,
118 pub trait_map: TraitMap,
119 pub maybe_unused_trait_imports: NodeSet,
122 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
123 pub enum AssociatedItemContainer {
124 TraitContainer(DefId),
125 ImplContainer(DefId),
128 impl AssociatedItemContainer {
129 pub fn id(&self) -> DefId {
131 TraitContainer(id) => id,
132 ImplContainer(id) => id,
137 /// The "header" of an impl is everything outside the body: a Self type, a trait
138 /// ref (in the case of a trait impl), and a set of predicates (from the
139 /// bounds/where clauses).
140 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
141 pub struct ImplHeader<'tcx> {
142 pub impl_def_id: DefId,
143 pub self_ty: Ty<'tcx>,
144 pub trait_ref: Option<TraitRef<'tcx>>,
145 pub predicates: Vec<Predicate<'tcx>>,
148 impl<'a, 'gcx, 'tcx> ImplHeader<'tcx> {
149 pub fn with_fresh_ty_vars(selcx: &mut traits::SelectionContext<'a, 'gcx, 'tcx>,
153 let tcx = selcx.tcx();
154 let impl_substs = selcx.infcx().fresh_substs_for_item(DUMMY_SP, impl_def_id);
156 let header = ImplHeader {
157 impl_def_id: impl_def_id,
158 self_ty: tcx.item_type(impl_def_id),
159 trait_ref: tcx.impl_trait_ref(impl_def_id),
160 predicates: tcx.item_predicates(impl_def_id).predicates
161 }.subst(tcx, impl_substs);
163 let traits::Normalized { value: mut header, obligations } =
164 traits::normalize(selcx, traits::ObligationCause::dummy(), &header);
166 header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
171 #[derive(Copy, Clone, Debug)]
172 pub struct AssociatedItem {
175 pub kind: AssociatedKind,
177 pub defaultness: hir::Defaultness,
178 pub container: AssociatedItemContainer,
180 /// Whether this is a method with an explicit self
181 /// as its first argument, allowing method calls.
182 pub method_has_self_argument: bool,
185 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
186 pub enum AssociatedKind {
192 impl AssociatedItem {
193 pub fn def(&self) -> Def {
195 AssociatedKind::Const => Def::AssociatedConst(self.def_id),
196 AssociatedKind::Method => Def::Method(self.def_id),
197 AssociatedKind::Type => Def::AssociatedTy(self.def_id),
201 /// Tests whether the associated item admits a non-trivial implementation
203 pub fn relevant_for_never<'tcx>(&self) -> bool {
205 AssociatedKind::Const => true,
206 AssociatedKind::Type => true,
207 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
208 AssociatedKind::Method => !self.method_has_self_argument,
213 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
214 pub enum Visibility {
215 /// Visible everywhere (including in other crates).
217 /// Visible only in the given crate-local module.
219 /// Not visible anywhere in the local crate. This is the visibility of private external items.
223 pub trait DefIdTree: Copy {
224 fn parent(self, id: DefId) -> Option<DefId>;
226 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
227 if descendant.krate != ancestor.krate {
231 while descendant != ancestor {
232 match self.parent(descendant) {
233 Some(parent) => descendant = parent,
234 None => return false,
241 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
242 fn parent(self, id: DefId) -> Option<DefId> {
243 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
248 pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
250 hir::Public => Visibility::Public,
251 hir::Visibility::Crate => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
252 hir::Visibility::Restricted { ref path, .. } => match path.def {
253 // If there is no resolution, `resolve` will have already reported an error, so
254 // assume that the visibility is public to avoid reporting more privacy errors.
255 Def::Err => Visibility::Public,
256 def => Visibility::Restricted(def.def_id()),
259 Visibility::Restricted(tcx.hir.local_def_id(tcx.hir.get_module_parent(id)))
264 /// Returns true if an item with this visibility is accessible from the given block.
265 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
266 let restriction = match self {
267 // Public items are visible everywhere.
268 Visibility::Public => return true,
269 // Private items from other crates are visible nowhere.
270 Visibility::Invisible => return false,
271 // Restricted items are visible in an arbitrary local module.
272 Visibility::Restricted(other) if other.krate != module.krate => return false,
273 Visibility::Restricted(module) => module,
276 tree.is_descendant_of(module, restriction)
279 /// Returns true if this visibility is at least as accessible as the given visibility
280 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
281 let vis_restriction = match vis {
282 Visibility::Public => return self == Visibility::Public,
283 Visibility::Invisible => return true,
284 Visibility::Restricted(module) => module,
287 self.is_accessible_from(vis_restriction, tree)
291 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
293 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
294 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
295 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
296 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
299 #[derive(Clone, Copy, Debug, RustcDecodable, RustcEncodable)]
300 pub struct MethodCallee<'tcx> {
301 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
304 pub substs: &'tcx Substs<'tcx>
307 /// With method calls, we store some extra information in
308 /// side tables (i.e method_map). We use
309 /// MethodCall as a key to index into these tables instead of
310 /// just directly using the expression's NodeId. The reason
311 /// for this being that we may apply adjustments (coercions)
312 /// with the resulting expression also needing to use the
313 /// side tables. The problem with this is that we don't
314 /// assign a separate NodeId to this new expression
315 /// and so it would clash with the base expression if both
316 /// needed to add to the side tables. Thus to disambiguate
317 /// we also keep track of whether there's an adjustment in
319 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
320 pub struct MethodCall {
326 pub fn expr(id: NodeId) -> MethodCall {
333 pub fn autoderef(expr_id: NodeId, autoderef: u32) -> MethodCall {
336 autoderef: 1 + autoderef
341 // maps from an expression id that corresponds to a method call to the details
342 // of the method to be invoked
343 pub type MethodMap<'tcx> = FxHashMap<MethodCall, MethodCallee<'tcx>>;
345 // Contains information needed to resolve types and (in the future) look up
346 // the types of AST nodes.
347 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
348 pub struct CReaderCacheKey {
353 /// Describes the fragment-state associated with a NodeId.
355 /// Currently only unfragmented paths have entries in the table,
356 /// but longer-term this enum is expected to expand to also
357 /// include data for fragmented paths.
358 #[derive(Copy, Clone, Debug)]
359 pub enum FragmentInfo {
360 Moved { var: NodeId, move_expr: NodeId },
361 Assigned { var: NodeId, assign_expr: NodeId, assignee_id: NodeId },
364 // Flags that we track on types. These flags are propagated upwards
365 // through the type during type construction, so that we can quickly
366 // check whether the type has various kinds of types in it without
367 // recursing over the type itself.
369 flags TypeFlags: u32 {
370 const HAS_PARAMS = 1 << 0,
371 const HAS_SELF = 1 << 1,
372 const HAS_TY_INFER = 1 << 2,
373 const HAS_RE_INFER = 1 << 3,
374 const HAS_RE_SKOL = 1 << 4,
375 const HAS_RE_EARLY_BOUND = 1 << 5,
376 const HAS_FREE_REGIONS = 1 << 6,
377 const HAS_TY_ERR = 1 << 7,
378 const HAS_PROJECTION = 1 << 8,
379 const HAS_TY_CLOSURE = 1 << 9,
381 // true if there are "names" of types and regions and so forth
382 // that are local to a particular fn
383 const HAS_LOCAL_NAMES = 1 << 10,
385 // Present if the type belongs in a local type context.
386 // Only set for TyInfer other than Fresh.
387 const KEEP_IN_LOCAL_TCX = 1 << 11,
389 // Is there a projection that does not involve a bound region?
390 // Currently we can't normalize projections w/ bound regions.
391 const HAS_NORMALIZABLE_PROJECTION = 1 << 12,
393 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
394 TypeFlags::HAS_SELF.bits |
395 TypeFlags::HAS_RE_EARLY_BOUND.bits,
397 // Flags representing the nominal content of a type,
398 // computed by FlagsComputation. If you add a new nominal
399 // flag, it should be added here too.
400 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
401 TypeFlags::HAS_SELF.bits |
402 TypeFlags::HAS_TY_INFER.bits |
403 TypeFlags::HAS_RE_INFER.bits |
404 TypeFlags::HAS_RE_SKOL.bits |
405 TypeFlags::HAS_RE_EARLY_BOUND.bits |
406 TypeFlags::HAS_FREE_REGIONS.bits |
407 TypeFlags::HAS_TY_ERR.bits |
408 TypeFlags::HAS_PROJECTION.bits |
409 TypeFlags::HAS_TY_CLOSURE.bits |
410 TypeFlags::HAS_LOCAL_NAMES.bits |
411 TypeFlags::KEEP_IN_LOCAL_TCX.bits,
413 // Caches for type_is_sized, type_moves_by_default
414 const SIZEDNESS_CACHED = 1 << 16,
415 const IS_SIZED = 1 << 17,
416 const MOVENESS_CACHED = 1 << 18,
417 const MOVES_BY_DEFAULT = 1 << 19,
421 pub struct TyS<'tcx> {
422 pub sty: TypeVariants<'tcx>,
423 pub flags: Cell<TypeFlags>,
425 // the maximal depth of any bound regions appearing in this type.
429 impl<'tcx> PartialEq for TyS<'tcx> {
431 fn eq(&self, other: &TyS<'tcx>) -> bool {
432 // (self as *const _) == (other as *const _)
433 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
436 impl<'tcx> Eq for TyS<'tcx> {}
438 impl<'tcx> Hash for TyS<'tcx> {
439 fn hash<H: Hasher>(&self, s: &mut H) {
440 (self as *const TyS).hash(s)
444 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
446 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
447 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
449 /// A wrapper for slices with the additional invariant
450 /// that the slice is interned and no other slice with
451 /// the same contents can exist in the same context.
452 /// This means we can use pointer + length for both
453 /// equality comparisons and hashing.
454 #[derive(Debug, RustcEncodable)]
455 pub struct Slice<T>([T]);
457 impl<T> PartialEq for Slice<T> {
459 fn eq(&self, other: &Slice<T>) -> bool {
460 (&self.0 as *const [T]) == (&other.0 as *const [T])
463 impl<T> Eq for Slice<T> {}
465 impl<T> Hash for Slice<T> {
466 fn hash<H: Hasher>(&self, s: &mut H) {
467 (self.as_ptr(), self.len()).hash(s)
471 impl<T> Deref for Slice<T> {
473 fn deref(&self) -> &[T] {
478 impl<'a, T> IntoIterator for &'a Slice<T> {
480 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
481 fn into_iter(self) -> Self::IntoIter {
486 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
489 pub fn empty<'a>() -> &'a Slice<T> {
491 mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
496 /// Upvars do not get their own node-id. Instead, we use the pair of
497 /// the original var id (that is, the root variable that is referenced
498 /// by the upvar) and the id of the closure expression.
499 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
502 pub closure_expr_id: NodeId,
505 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
506 pub enum BorrowKind {
507 /// Data must be immutable and is aliasable.
510 /// Data must be immutable but not aliasable. This kind of borrow
511 /// cannot currently be expressed by the user and is used only in
512 /// implicit closure bindings. It is needed when the closure
513 /// is borrowing or mutating a mutable referent, e.g.:
515 /// let x: &mut isize = ...;
516 /// let y = || *x += 5;
518 /// If we were to try to translate this closure into a more explicit
519 /// form, we'd encounter an error with the code as written:
521 /// struct Env { x: & &mut isize }
522 /// let x: &mut isize = ...;
523 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
524 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
526 /// This is then illegal because you cannot mutate a `&mut` found
527 /// in an aliasable location. To solve, you'd have to translate with
528 /// an `&mut` borrow:
530 /// struct Env { x: & &mut isize }
531 /// let x: &mut isize = ...;
532 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
533 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
535 /// Now the assignment to `**env.x` is legal, but creating a
536 /// mutable pointer to `x` is not because `x` is not mutable. We
537 /// could fix this by declaring `x` as `let mut x`. This is ok in
538 /// user code, if awkward, but extra weird for closures, since the
539 /// borrow is hidden.
541 /// So we introduce a "unique imm" borrow -- the referent is
542 /// immutable, but not aliasable. This solves the problem. For
543 /// simplicity, we don't give users the way to express this
544 /// borrow, it's just used when translating closures.
547 /// Data is mutable and not aliasable.
551 /// Information describing the capture of an upvar. This is computed
552 /// during `typeck`, specifically by `regionck`.
553 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
554 pub enum UpvarCapture<'tcx> {
555 /// Upvar is captured by value. This is always true when the
556 /// closure is labeled `move`, but can also be true in other cases
557 /// depending on inference.
560 /// Upvar is captured by reference.
561 ByRef(UpvarBorrow<'tcx>),
564 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
565 pub struct UpvarBorrow<'tcx> {
566 /// The kind of borrow: by-ref upvars have access to shared
567 /// immutable borrows, which are not part of the normal language
569 pub kind: BorrowKind,
571 /// Region of the resulting reference.
572 pub region: &'tcx ty::Region,
575 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
577 #[derive(Copy, Clone)]
578 pub struct ClosureUpvar<'tcx> {
584 #[derive(Clone, Copy, PartialEq)]
585 pub enum IntVarValue {
587 UintType(ast::UintTy),
590 #[derive(Clone, RustcEncodable, RustcDecodable)]
591 pub struct TypeParameterDef<'tcx> {
595 pub default_def_id: DefId, // for use in error reporing about defaults
596 pub default: Option<Ty<'tcx>>,
598 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
599 /// on generic parameter `T`, asserts data behind the parameter
600 /// `T` won't be accessed during the parent type's `Drop` impl.
601 pub pure_wrt_drop: bool,
604 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
605 pub struct RegionParameterDef {
609 pub issue_32330: Option<ty::Issue32330>,
611 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
612 /// on generic parameter `'a`, asserts data of lifetime `'a`
613 /// won't be accessed during the parent type's `Drop` impl.
614 pub pure_wrt_drop: bool,
617 impl RegionParameterDef {
618 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
619 ty::EarlyBoundRegion {
625 pub fn to_bound_region(&self) -> ty::BoundRegion {
626 ty::BoundRegion::BrNamed(self.def_id, self.name)
630 /// Information about the formal type/lifetime parameters associated
631 /// with an item or method. Analogous to hir::Generics.
632 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
633 pub struct Generics<'tcx> {
634 pub parent: Option<DefId>,
635 pub parent_regions: u32,
636 pub parent_types: u32,
637 pub regions: Vec<RegionParameterDef>,
638 pub types: Vec<TypeParameterDef<'tcx>>,
642 impl<'tcx> Generics<'tcx> {
643 pub fn parent_count(&self) -> usize {
644 self.parent_regions as usize + self.parent_types as usize
647 pub fn own_count(&self) -> usize {
648 self.regions.len() + self.types.len()
651 pub fn count(&self) -> usize {
652 self.parent_count() + self.own_count()
655 pub fn region_param(&self, param: &EarlyBoundRegion) -> &RegionParameterDef {
656 &self.regions[param.index as usize - self.has_self as usize]
659 pub fn type_param(&self, param: &ParamTy) -> &TypeParameterDef<'tcx> {
660 &self.types[param.idx as usize - self.has_self as usize - self.regions.len()]
664 /// Bounds on generics.
666 pub struct GenericPredicates<'tcx> {
667 pub parent: Option<DefId>,
668 pub predicates: Vec<Predicate<'tcx>>,
671 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
672 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
674 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
675 pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
676 -> InstantiatedPredicates<'tcx> {
677 let mut instantiated = InstantiatedPredicates::empty();
678 self.instantiate_into(tcx, &mut instantiated, substs);
681 pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
682 -> InstantiatedPredicates<'tcx> {
683 InstantiatedPredicates {
684 predicates: self.predicates.subst(tcx, substs)
688 fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
689 instantiated: &mut InstantiatedPredicates<'tcx>,
690 substs: &Substs<'tcx>) {
691 if let Some(def_id) = self.parent {
692 tcx.item_predicates(def_id).instantiate_into(tcx, instantiated, substs);
694 instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
697 pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
698 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
699 -> InstantiatedPredicates<'tcx>
701 assert_eq!(self.parent, None);
702 InstantiatedPredicates {
703 predicates: self.predicates.iter().map(|pred| {
704 pred.subst_supertrait(tcx, poly_trait_ref)
710 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
711 pub enum Predicate<'tcx> {
712 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
713 /// the `Self` type of the trait reference and `A`, `B`, and `C`
714 /// would be the type parameters.
715 Trait(PolyTraitPredicate<'tcx>),
717 /// where `T1 == T2`.
718 Equate(PolyEquatePredicate<'tcx>),
721 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
724 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
726 /// where <T as TraitRef>::Name == X, approximately.
727 /// See `ProjectionPredicate` struct for details.
728 Projection(PolyProjectionPredicate<'tcx>),
731 WellFormed(Ty<'tcx>),
733 /// trait must be object-safe
736 /// No direct syntax. May be thought of as `where T : FnFoo<...>`
737 /// for some substitutions `...` and T being a closure type.
738 /// Satisfied (or refuted) once we know the closure's kind.
739 ClosureKind(DefId, ClosureKind),
742 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
743 /// Performs a substitution suitable for going from a
744 /// poly-trait-ref to supertraits that must hold if that
745 /// poly-trait-ref holds. This is slightly different from a normal
746 /// substitution in terms of what happens with bound regions. See
747 /// lengthy comment below for details.
748 pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
749 trait_ref: &ty::PolyTraitRef<'tcx>)
750 -> ty::Predicate<'tcx>
752 // The interaction between HRTB and supertraits is not entirely
753 // obvious. Let me walk you (and myself) through an example.
755 // Let's start with an easy case. Consider two traits:
757 // trait Foo<'a> : Bar<'a,'a> { }
758 // trait Bar<'b,'c> { }
760 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
761 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
762 // knew that `Foo<'x>` (for any 'x) then we also know that
763 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
764 // normal substitution.
766 // In terms of why this is sound, the idea is that whenever there
767 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
768 // holds. So if there is an impl of `T:Foo<'a>` that applies to
769 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
772 // Another example to be careful of is this:
774 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
775 // trait Bar1<'b,'c> { }
777 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
778 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
779 // reason is similar to the previous example: any impl of
780 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
781 // basically we would want to collapse the bound lifetimes from
782 // the input (`trait_ref`) and the supertraits.
784 // To achieve this in practice is fairly straightforward. Let's
785 // consider the more complicated scenario:
787 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
788 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
789 // where both `'x` and `'b` would have a DB index of 1.
790 // The substitution from the input trait-ref is therefore going to be
791 // `'a => 'x` (where `'x` has a DB index of 1).
792 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
793 // early-bound parameter and `'b' is a late-bound parameter with a
795 // - If we replace `'a` with `'x` from the input, it too will have
796 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
797 // just as we wanted.
799 // There is only one catch. If we just apply the substitution `'a
800 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
801 // adjust the DB index because we substituting into a binder (it
802 // tries to be so smart...) resulting in `for<'x> for<'b>
803 // Bar1<'x,'b>` (we have no syntax for this, so use your
804 // imagination). Basically the 'x will have DB index of 2 and 'b
805 // will have DB index of 1. Not quite what we want. So we apply
806 // the substitution to the *contents* of the trait reference,
807 // rather than the trait reference itself (put another way, the
808 // substitution code expects equal binding levels in the values
809 // from the substitution and the value being substituted into, and
810 // this trick achieves that).
812 let substs = &trait_ref.0.substs;
814 Predicate::Trait(ty::Binder(ref data)) =>
815 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
816 Predicate::Equate(ty::Binder(ref data)) =>
817 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
818 Predicate::RegionOutlives(ty::Binder(ref data)) =>
819 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
820 Predicate::TypeOutlives(ty::Binder(ref data)) =>
821 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
822 Predicate::Projection(ty::Binder(ref data)) =>
823 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
824 Predicate::WellFormed(data) =>
825 Predicate::WellFormed(data.subst(tcx, substs)),
826 Predicate::ObjectSafe(trait_def_id) =>
827 Predicate::ObjectSafe(trait_def_id),
828 Predicate::ClosureKind(closure_def_id, kind) =>
829 Predicate::ClosureKind(closure_def_id, kind),
834 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
835 pub struct TraitPredicate<'tcx> {
836 pub trait_ref: TraitRef<'tcx>
838 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
840 impl<'tcx> TraitPredicate<'tcx> {
841 pub fn def_id(&self) -> DefId {
842 self.trait_ref.def_id
845 /// Creates the dep-node for selecting/evaluating this trait reference.
846 fn dep_node(&self) -> DepNode<DefId> {
847 // Ideally, the dep-node would just have all the input types
848 // in it. But they are limited to including def-ids. So as an
849 // approximation we include the def-ids for all nominal types
850 // found somewhere. This means that we will e.g. conflate the
851 // dep-nodes for `u32: SomeTrait` and `u64: SomeTrait`, but we
852 // would have distinct dep-nodes for `Vec<u32>: SomeTrait`,
853 // `Rc<u32>: SomeTrait`, and `(Vec<u32>, Rc<u32>): SomeTrait`.
854 // Note that it's always sound to conflate dep-nodes, it just
855 // leads to more recompilation.
856 let def_ids: Vec<_> =
858 .flat_map(|t| t.walk())
859 .filter_map(|t| match t.sty {
860 ty::TyAdt(adt_def, _) =>
865 .chain(iter::once(self.def_id()))
867 DepNode::TraitSelect(def_ids)
870 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
871 self.trait_ref.input_types()
874 pub fn self_ty(&self) -> Ty<'tcx> {
875 self.trait_ref.self_ty()
879 impl<'tcx> PolyTraitPredicate<'tcx> {
880 pub fn def_id(&self) -> DefId {
881 // ok to skip binder since trait def-id does not care about regions
885 pub fn dep_node(&self) -> DepNode<DefId> {
886 // ok to skip binder since depnode does not care about regions
891 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
892 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
893 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
895 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
896 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
897 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
898 pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<&'tcx ty::Region,
900 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, &'tcx ty::Region>;
902 /// This kind of predicate has no *direct* correspondent in the
903 /// syntax, but it roughly corresponds to the syntactic forms:
905 /// 1. `T : TraitRef<..., Item=Type>`
906 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
908 /// In particular, form #1 is "desugared" to the combination of a
909 /// normal trait predicate (`T : TraitRef<...>`) and one of these
910 /// predicates. Form #2 is a broader form in that it also permits
911 /// equality between arbitrary types. Processing an instance of Form
912 /// #2 eventually yields one of these `ProjectionPredicate`
913 /// instances to normalize the LHS.
914 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
915 pub struct ProjectionPredicate<'tcx> {
916 pub projection_ty: ProjectionTy<'tcx>,
920 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
922 impl<'tcx> PolyProjectionPredicate<'tcx> {
923 pub fn item_name(&self) -> Name {
924 self.0.projection_ty.item_name // safe to skip the binder to access a name
928 pub trait ToPolyTraitRef<'tcx> {
929 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
932 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
933 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
934 assert!(!self.has_escaping_regions());
935 ty::Binder(self.clone())
939 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
940 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
941 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
945 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
946 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
947 // Note: unlike with TraitRef::to_poly_trait_ref(),
948 // self.0.trait_ref is permitted to have escaping regions.
949 // This is because here `self` has a `Binder` and so does our
950 // return value, so we are preserving the number of binding
952 ty::Binder(self.0.projection_ty.trait_ref)
956 pub trait ToPredicate<'tcx> {
957 fn to_predicate(&self) -> Predicate<'tcx>;
960 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
961 fn to_predicate(&self) -> Predicate<'tcx> {
962 // we're about to add a binder, so let's check that we don't
963 // accidentally capture anything, or else that might be some
964 // weird debruijn accounting.
965 assert!(!self.has_escaping_regions());
967 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
968 trait_ref: self.clone()
973 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
974 fn to_predicate(&self) -> Predicate<'tcx> {
975 ty::Predicate::Trait(self.to_poly_trait_predicate())
979 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
980 fn to_predicate(&self) -> Predicate<'tcx> {
981 Predicate::Equate(self.clone())
985 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
986 fn to_predicate(&self) -> Predicate<'tcx> {
987 Predicate::RegionOutlives(self.clone())
991 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
992 fn to_predicate(&self) -> Predicate<'tcx> {
993 Predicate::TypeOutlives(self.clone())
997 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
998 fn to_predicate(&self) -> Predicate<'tcx> {
999 Predicate::Projection(self.clone())
1003 impl<'tcx> Predicate<'tcx> {
1004 /// Iterates over the types in this predicate. Note that in all
1005 /// cases this is skipping over a binder, so late-bound regions
1006 /// with depth 0 are bound by the predicate.
1007 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1008 let vec: Vec<_> = match *self {
1009 ty::Predicate::Trait(ref data) => {
1010 data.skip_binder().input_types().collect()
1012 ty::Predicate::Equate(ty::Binder(ref data)) => {
1013 vec![data.0, data.1]
1015 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1018 ty::Predicate::RegionOutlives(..) => {
1021 ty::Predicate::Projection(ref data) => {
1022 let trait_inputs = data.0.projection_ty.trait_ref.input_types();
1023 trait_inputs.chain(Some(data.0.ty)).collect()
1025 ty::Predicate::WellFormed(data) => {
1028 ty::Predicate::ObjectSafe(_trait_def_id) => {
1031 ty::Predicate::ClosureKind(_closure_def_id, _kind) => {
1036 // The only reason to collect into a vector here is that I was
1037 // too lazy to make the full (somewhat complicated) iterator
1038 // type that would be needed here. But I wanted this fn to
1039 // return an iterator conceptually, rather than a `Vec`, so as
1040 // to be closer to `Ty::walk`.
1044 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1046 Predicate::Trait(ref t) => {
1047 Some(t.to_poly_trait_ref())
1049 Predicate::Projection(..) |
1050 Predicate::Equate(..) |
1051 Predicate::RegionOutlives(..) |
1052 Predicate::WellFormed(..) |
1053 Predicate::ObjectSafe(..) |
1054 Predicate::ClosureKind(..) |
1055 Predicate::TypeOutlives(..) => {
1062 /// Represents the bounds declared on a particular set of type
1063 /// parameters. Should eventually be generalized into a flag list of
1064 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
1065 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1066 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1067 /// the `GenericPredicates` are expressed in terms of the bound type
1068 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1069 /// represented a set of bounds for some particular instantiation,
1070 /// meaning that the generic parameters have been substituted with
1075 /// struct Foo<T,U:Bar<T>> { ... }
1077 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1078 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1079 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1080 /// [usize:Bar<isize>]]`.
1082 pub struct InstantiatedPredicates<'tcx> {
1083 pub predicates: Vec<Predicate<'tcx>>,
1086 impl<'tcx> InstantiatedPredicates<'tcx> {
1087 pub fn empty() -> InstantiatedPredicates<'tcx> {
1088 InstantiatedPredicates { predicates: vec![] }
1091 pub fn is_empty(&self) -> bool {
1092 self.predicates.is_empty()
1096 impl<'tcx> TraitRef<'tcx> {
1097 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
1098 TraitRef { def_id: def_id, substs: substs }
1101 pub fn self_ty(&self) -> Ty<'tcx> {
1102 self.substs.type_at(0)
1105 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
1106 // Select only the "input types" from a trait-reference. For
1107 // now this is all the types that appear in the
1108 // trait-reference, but it should eventually exclude
1109 // associated types.
1114 /// When type checking, we use the `ParameterEnvironment` to track
1115 /// details about the type/lifetime parameters that are in scope.
1116 /// It primarily stores the bounds information.
1118 /// Note: This information might seem to be redundant with the data in
1119 /// `tcx.ty_param_defs`, but it is not. That table contains the
1120 /// parameter definitions from an "outside" perspective, but this
1121 /// struct will contain the bounds for a parameter as seen from inside
1122 /// the function body. Currently the only real distinction is that
1123 /// bound lifetime parameters are replaced with free ones, but in the
1124 /// future I hope to refine the representation of types so as to make
1125 /// more distinctions clearer.
1127 pub struct ParameterEnvironment<'tcx> {
1128 /// See `construct_free_substs` for details.
1129 pub free_substs: &'tcx Substs<'tcx>,
1131 /// Each type parameter has an implicit region bound that
1132 /// indicates it must outlive at least the function body (the user
1133 /// may specify stronger requirements). This field indicates the
1134 /// region of the callee.
1135 pub implicit_region_bound: &'tcx ty::Region,
1137 /// Obligations that the caller must satisfy. This is basically
1138 /// the set of bounds on the in-scope type parameters, translated
1139 /// into Obligations, and elaborated and normalized.
1140 pub caller_bounds: Vec<ty::Predicate<'tcx>>,
1142 /// Scope that is attached to free regions for this scope. This
1143 /// is usually the id of the fn body, but for more abstract scopes
1144 /// like structs we often use the node-id of the struct.
1146 /// FIXME(#3696). It would be nice to refactor so that free
1147 /// regions don't have this implicit scope and instead introduce
1148 /// relationships in the environment.
1149 pub free_id_outlive: CodeExtent,
1151 /// A cache for `moves_by_default`.
1152 pub is_copy_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
1154 /// A cache for `type_is_sized`
1155 pub is_sized_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
1158 impl<'a, 'tcx> ParameterEnvironment<'tcx> {
1159 pub fn with_caller_bounds(&self,
1160 caller_bounds: Vec<ty::Predicate<'tcx>>)
1161 -> ParameterEnvironment<'tcx>
1163 ParameterEnvironment {
1164 free_substs: self.free_substs,
1165 implicit_region_bound: self.implicit_region_bound,
1166 caller_bounds: caller_bounds,
1167 free_id_outlive: self.free_id_outlive,
1168 is_copy_cache: RefCell::new(FxHashMap()),
1169 is_sized_cache: RefCell::new(FxHashMap()),
1173 /// Construct a parameter environment given an item, impl item, or trait item
1174 pub fn for_item(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: NodeId)
1175 -> ParameterEnvironment<'tcx> {
1176 match tcx.hir.find(id) {
1177 Some(hir_map::NodeImplItem(ref impl_item)) => {
1178 match impl_item.node {
1179 hir::ImplItemKind::Type(_) | hir::ImplItemKind::Const(..) => {
1180 // associated types don't have their own entry (for some reason),
1181 // so for now just grab environment for the impl
1182 let impl_id = tcx.hir.get_parent(id);
1183 let impl_def_id = tcx.hir.local_def_id(impl_id);
1184 tcx.construct_parameter_environment(impl_item.span,
1186 tcx.region_maps.item_extent(id))
1188 hir::ImplItemKind::Method(_, ref body) => {
1189 tcx.construct_parameter_environment(
1191 tcx.hir.local_def_id(id),
1192 tcx.region_maps.call_site_extent(id, body.node_id))
1196 Some(hir_map::NodeTraitItem(trait_item)) => {
1197 match trait_item.node {
1198 hir::TraitItemKind::Type(..) | hir::TraitItemKind::Const(..) => {
1199 // associated types don't have their own entry (for some reason),
1200 // so for now just grab environment for the trait
1201 let trait_id = tcx.hir.get_parent(id);
1202 let trait_def_id = tcx.hir.local_def_id(trait_id);
1203 tcx.construct_parameter_environment(trait_item.span,
1205 tcx.region_maps.item_extent(id))
1207 hir::TraitItemKind::Method(_, ref body) => {
1208 // Use call-site for extent (unless this is a
1209 // trait method with no default; then fallback
1210 // to the method id).
1211 let extent = if let hir::TraitMethod::Provided(body_id) = *body {
1212 // default impl: use call_site extent as free_id_outlive bound.
1213 tcx.region_maps.call_site_extent(id, body_id.node_id)
1215 // no default impl: use item extent as free_id_outlive bound.
1216 tcx.region_maps.item_extent(id)
1218 tcx.construct_parameter_environment(
1220 tcx.hir.local_def_id(id),
1225 Some(hir_map::NodeItem(item)) => {
1227 hir::ItemFn(.., body_id) => {
1228 // We assume this is a function.
1229 let fn_def_id = tcx.hir.local_def_id(id);
1231 tcx.construct_parameter_environment(
1234 tcx.region_maps.call_site_extent(id, body_id.node_id))
1237 hir::ItemStruct(..) |
1238 hir::ItemUnion(..) |
1241 hir::ItemConst(..) |
1242 hir::ItemStatic(..) => {
1243 let def_id = tcx.hir.local_def_id(id);
1244 tcx.construct_parameter_environment(item.span,
1246 tcx.region_maps.item_extent(id))
1248 hir::ItemTrait(..) => {
1249 let def_id = tcx.hir.local_def_id(id);
1250 tcx.construct_parameter_environment(item.span,
1252 tcx.region_maps.item_extent(id))
1255 span_bug!(item.span,
1256 "ParameterEnvironment::for_item():
1257 can't create a parameter \
1258 environment for this kind of item")
1262 Some(hir_map::NodeExpr(expr)) => {
1263 // This is a convenience to allow closures to work.
1264 if let hir::ExprClosure(.., body, _) = expr.node {
1265 let def_id = tcx.hir.local_def_id(id);
1266 let base_def_id = tcx.closure_base_def_id(def_id);
1267 tcx.construct_parameter_environment(
1270 tcx.region_maps.call_site_extent(id, body.node_id))
1272 tcx.empty_parameter_environment()
1275 Some(hir_map::NodeForeignItem(item)) => {
1276 let def_id = tcx.hir.local_def_id(id);
1277 tcx.construct_parameter_environment(item.span,
1282 bug!("ParameterEnvironment::from_item(): \
1283 `{}` is not an item",
1284 tcx.hir.node_to_string(id))
1291 flags AdtFlags: u32 {
1292 const NO_ADT_FLAGS = 0,
1293 const IS_ENUM = 1 << 0,
1294 const IS_DTORCK = 1 << 1, // is this a dtorck type?
1295 const IS_DTORCK_VALID = 1 << 2,
1296 const IS_PHANTOM_DATA = 1 << 3,
1297 const IS_SIMD = 1 << 4,
1298 const IS_FUNDAMENTAL = 1 << 5,
1299 const IS_UNION = 1 << 6,
1300 const IS_BOX = 1 << 7,
1305 pub struct VariantDef {
1306 /// The variant's DefId. If this is a tuple-like struct,
1307 /// this is the DefId of the struct's ctor.
1309 pub name: Name, // struct's name if this is a struct
1311 pub fields: Vec<FieldDef>,
1312 pub ctor_kind: CtorKind,
1316 pub struct FieldDef {
1319 pub vis: Visibility,
1322 /// The definition of an abstract data type - a struct or enum.
1324 /// These are all interned (by intern_adt_def) into the adt_defs
1328 pub variants: Vec<VariantDef>,
1329 destructor: Cell<Option<DefId>>,
1330 flags: Cell<AdtFlags>,
1331 pub repr: ReprOptions,
1334 impl PartialEq for AdtDef {
1335 // AdtDef are always interned and this is part of TyS equality
1337 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1340 impl Eq for AdtDef {}
1342 impl Hash for AdtDef {
1344 fn hash<H: Hasher>(&self, s: &mut H) {
1345 (self as *const AdtDef).hash(s)
1349 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1350 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1355 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1357 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1358 pub enum AdtKind { Struct, Union, Enum }
1360 /// Represents the repr options provided by the user,
1361 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1362 pub struct ReprOptions {
1366 pub int: Option<attr::IntType>,
1370 pub fn new<'a, 'gcx, 'tcx>(tcx: &TyCtxt<'a, 'gcx, 'tcx>, did: DefId) -> ReprOptions {
1371 let mut ret = ReprOptions::default();
1372 let attrs = tcx.lookup_repr_hints(did);
1373 for r in attrs.iter() {
1375 attr::ReprExtern => ret.c = true,
1376 attr::ReprPacked => ret.packed = true,
1377 attr::ReprSimd => ret.simd = true,
1378 attr::ReprInt(i) => ret.int = Some(i),
1379 attr::ReprAny => (),
1386 impl<'a, 'gcx, 'tcx> AdtDef {
1387 fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1390 variants: Vec<VariantDef>,
1391 repr: ReprOptions) -> Self {
1392 let mut flags = AdtFlags::NO_ADT_FLAGS;
1393 let attrs = tcx.get_attrs(did);
1394 if attr::contains_name(&attrs, "fundamental") {
1395 flags = flags | AdtFlags::IS_FUNDAMENTAL;
1397 if tcx.lookup_simd(did) {
1398 flags = flags | AdtFlags::IS_SIMD;
1400 if Some(did) == tcx.lang_items.phantom_data() {
1401 flags = flags | AdtFlags::IS_PHANTOM_DATA;
1403 if Some(did) == tcx.lang_items.owned_box() {
1404 flags = flags | AdtFlags::IS_BOX;
1407 AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1408 AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1409 AdtKind::Struct => {}
1414 flags: Cell::new(flags),
1415 destructor: Cell::new(None),
1420 fn calculate_dtorck(&'gcx self, tcx: TyCtxt) {
1421 if tcx.is_adt_dtorck(self) {
1422 self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK);
1424 self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK_VALID)
1428 pub fn is_struct(&self) -> bool {
1429 !self.is_union() && !self.is_enum()
1433 pub fn is_union(&self) -> bool {
1434 self.flags.get().intersects(AdtFlags::IS_UNION)
1438 pub fn is_enum(&self) -> bool {
1439 self.flags.get().intersects(AdtFlags::IS_ENUM)
1442 /// Returns the kind of the ADT - Struct or Enum.
1444 pub fn adt_kind(&self) -> AdtKind {
1447 } else if self.is_union() {
1454 pub fn descr(&self) -> &'static str {
1455 match self.adt_kind() {
1456 AdtKind::Struct => "struct",
1457 AdtKind::Union => "union",
1458 AdtKind::Enum => "enum",
1462 pub fn variant_descr(&self) -> &'static str {
1463 match self.adt_kind() {
1464 AdtKind::Struct => "struct",
1465 AdtKind::Union => "union",
1466 AdtKind::Enum => "variant",
1470 /// Returns whether this is a dtorck type. If this returns
1471 /// true, this type being safe for destruction requires it to be
1472 /// alive; Otherwise, only the contents are required to be.
1474 pub fn is_dtorck(&'gcx self, tcx: TyCtxt) -> bool {
1475 if !self.flags.get().intersects(AdtFlags::IS_DTORCK_VALID) {
1476 self.calculate_dtorck(tcx)
1478 self.flags.get().intersects(AdtFlags::IS_DTORCK)
1481 /// Returns whether this type is #[fundamental] for the purposes
1482 /// of coherence checking.
1484 pub fn is_fundamental(&self) -> bool {
1485 self.flags.get().intersects(AdtFlags::IS_FUNDAMENTAL)
1489 pub fn is_simd(&self) -> bool {
1490 self.flags.get().intersects(AdtFlags::IS_SIMD)
1493 /// Returns true if this is PhantomData<T>.
1495 pub fn is_phantom_data(&self) -> bool {
1496 self.flags.get().intersects(AdtFlags::IS_PHANTOM_DATA)
1499 /// Returns true if this is Box<T>.
1501 pub fn is_box(&self) -> bool {
1502 self.flags.get().intersects(AdtFlags::IS_BOX)
1505 /// Returns whether this type has a destructor.
1506 pub fn has_dtor(&self) -> bool {
1507 self.destructor.get().is_some()
1510 /// Asserts this is a struct and returns the struct's unique
1512 pub fn struct_variant(&self) -> &VariantDef {
1513 assert!(!self.is_enum());
1518 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1519 tcx.item_predicates(self.did)
1522 /// Returns an iterator over all fields contained
1525 pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1526 self.variants.iter().flat_map(|v| v.fields.iter())
1530 pub fn is_univariant(&self) -> bool {
1531 self.variants.len() == 1
1534 pub fn is_payloadfree(&self) -> bool {
1535 !self.variants.is_empty() &&
1536 self.variants.iter().all(|v| v.fields.is_empty())
1539 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1542 .find(|v| v.did == vid)
1543 .expect("variant_with_id: unknown variant")
1546 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1549 .position(|v| v.did == vid)
1550 .expect("variant_index_with_id: unknown variant")
1553 pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1555 Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1556 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1557 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.struct_variant(),
1558 _ => bug!("unexpected def {:?} in variant_of_def", def)
1562 pub fn destructor(&self) -> Option<DefId> {
1563 self.destructor.get()
1566 pub fn set_destructor(&self, dtor: DefId) {
1567 self.destructor.set(Some(dtor));
1570 /// Returns a simpler type such that `Self: Sized` if and only
1571 /// if that type is Sized, or `TyErr` if this type is recursive.
1573 /// HACK: instead of returning a list of types, this function can
1574 /// return a tuple. In that case, the result is Sized only if
1575 /// all elements of the tuple are Sized.
1577 /// This is generally the `struct_tail` if this is a struct, or a
1578 /// tuple of them if this is an enum.
1580 /// Oddly enough, checking that the sized-constraint is Sized is
1581 /// actually more expressive than checking all members:
1582 /// the Sized trait is inductive, so an associated type that references
1583 /// Self would prevent its containing ADT from being Sized.
1585 /// Due to normalization being eager, this applies even if
1586 /// the associated type is behind a pointer, e.g. issue #31299.
1587 pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1588 self.calculate_sized_constraint_inner(tcx.global_tcx(), &mut Vec::new())
1591 /// Calculates the Sized-constraint.
1593 /// As the Sized-constraint of enums can be a *set* of types,
1594 /// the Sized-constraint may need to be a set also. Because introducing
1595 /// a new type of IVar is currently a complex affair, the Sized-constraint
1598 /// In fact, there are only a few options for the constraint:
1599 /// - `bool`, if the type is always Sized
1600 /// - an obviously-unsized type
1601 /// - a type parameter or projection whose Sizedness can't be known
1602 /// - a tuple of type parameters or projections, if there are multiple
1604 /// - a TyError, if a type contained itself. The representability
1605 /// check should catch this case.
1606 fn calculate_sized_constraint_inner(&self,
1607 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1608 stack: &mut Vec<DefId>)
1611 if let Some(ty) = tcx.adt_sized_constraint.borrow().get(&self.did) {
1615 // Follow the memoization pattern: push the computation of
1616 // DepNode::SizedConstraint as our current task.
1617 let _task = tcx.dep_graph.in_task(DepNode::SizedConstraint(self.did));
1619 if stack.contains(&self.did) {
1620 debug!("calculate_sized_constraint: {:?} is recursive", self);
1621 // This should be reported as an error by `check_representable`.
1623 // Consider the type as Sized in the meanwhile to avoid
1625 tcx.adt_sized_constraint.borrow_mut().insert(self.did, tcx.types.err);
1626 return tcx.types.err;
1629 stack.push(self.did);
1632 self.variants.iter().flat_map(|v| {
1635 let ty = tcx.item_type(f.did);
1636 self.sized_constraint_for_ty(tcx, stack, ty)
1639 let self_ = stack.pop().unwrap();
1640 assert_eq!(self_, self.did);
1642 let ty = match tys.len() {
1643 _ if tys.references_error() => tcx.types.err,
1644 0 => tcx.types.bool,
1646 _ => tcx.intern_tup(&tys[..], false)
1649 let old = tcx.adt_sized_constraint.borrow().get(&self.did).cloned();
1652 debug!("calculate_sized_constraint: {:?} recurred", self);
1653 assert_eq!(old_ty, tcx.types.err);
1657 debug!("calculate_sized_constraint: {:?} => {:?}", self, ty);
1658 tcx.adt_sized_constraint.borrow_mut().insert(self.did, ty);
1664 fn sized_constraint_for_ty(&self,
1665 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1666 stack: &mut Vec<DefId>,
1669 let result = match ty.sty {
1670 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
1671 TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
1672 TyArray(..) | TyClosure(..) | TyNever => {
1676 TyStr | TyDynamic(..) | TySlice(_) | TyError => {
1677 // these are never sized - return the target type
1681 TyTuple(ref tys, _) => {
1684 Some(ty) => self.sized_constraint_for_ty(tcx, stack, ty)
1688 TyAdt(adt, substs) => {
1691 adt.calculate_sized_constraint_inner(tcx, stack)
1692 .subst(tcx, substs);
1693 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
1695 if let ty::TyTuple(ref tys, _) = adt_ty.sty {
1696 tys.iter().flat_map(|ty| {
1697 self.sized_constraint_for_ty(tcx, stack, ty)
1700 self.sized_constraint_for_ty(tcx, stack, adt_ty)
1704 TyProjection(..) | TyAnon(..) => {
1705 // must calculate explicitly.
1706 // FIXME: consider special-casing always-Sized projections
1711 // perf hack: if there is a `T: Sized` bound, then
1712 // we know that `T` is Sized and do not need to check
1715 let sized_trait = match tcx.lang_items.sized_trait() {
1717 _ => return vec![ty]
1719 let sized_predicate = Binder(TraitRef {
1720 def_id: sized_trait,
1721 substs: tcx.mk_substs_trait(ty, &[])
1723 let predicates = tcx.item_predicates(self.did).predicates;
1724 if predicates.into_iter().any(|p| p == sized_predicate) {
1732 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
1736 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
1741 impl<'a, 'gcx, 'tcx> VariantDef {
1743 pub fn find_field_named(&self,
1745 -> Option<&FieldDef> {
1746 self.fields.iter().find(|f| f.name == name)
1750 pub fn index_of_field_named(&self,
1753 self.fields.iter().position(|f| f.name == name)
1757 pub fn field_named(&self, name: ast::Name) -> &FieldDef {
1758 self.find_field_named(name).unwrap()
1762 impl<'a, 'gcx, 'tcx> FieldDef {
1763 pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1764 tcx.item_type(self.did).subst(tcx, subst)
1768 /// Records the substitutions used to translate the polytype for an
1769 /// item into the monotype of an item reference.
1770 #[derive(Clone, RustcEncodable, RustcDecodable)]
1771 pub struct ItemSubsts<'tcx> {
1772 pub substs: &'tcx Substs<'tcx>,
1775 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1776 pub enum ClosureKind {
1777 // Warning: Ordering is significant here! The ordering is chosen
1778 // because the trait Fn is a subtrait of FnMut and so in turn, and
1779 // hence we order it so that Fn < FnMut < FnOnce.
1785 impl<'a, 'tcx> ClosureKind {
1786 pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
1788 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
1789 ClosureKind::FnMut => {
1790 tcx.require_lang_item(FnMutTraitLangItem)
1792 ClosureKind::FnOnce => {
1793 tcx.require_lang_item(FnOnceTraitLangItem)
1798 /// True if this a type that impls this closure kind
1799 /// must also implement `other`.
1800 pub fn extends(self, other: ty::ClosureKind) -> bool {
1801 match (self, other) {
1802 (ClosureKind::Fn, ClosureKind::Fn) => true,
1803 (ClosureKind::Fn, ClosureKind::FnMut) => true,
1804 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
1805 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
1806 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
1807 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
1813 impl<'tcx> TyS<'tcx> {
1814 /// Iterator that walks `self` and any types reachable from
1815 /// `self`, in depth-first order. Note that just walks the types
1816 /// that appear in `self`, it does not descend into the fields of
1817 /// structs or variants. For example:
1820 /// isize => { isize }
1821 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
1822 /// [isize] => { [isize], isize }
1824 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
1825 TypeWalker::new(self)
1828 /// Iterator that walks the immediate children of `self`. Hence
1829 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
1830 /// (but not `i32`, like `walk`).
1831 pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
1832 walk::walk_shallow(self)
1835 /// Walks `ty` and any types appearing within `ty`, invoking the
1836 /// callback `f` on each type. If the callback returns false, then the
1837 /// children of the current type are ignored.
1839 /// Note: prefer `ty.walk()` where possible.
1840 pub fn maybe_walk<F>(&'tcx self, mut f: F)
1841 where F : FnMut(Ty<'tcx>) -> bool
1843 let mut walker = self.walk();
1844 while let Some(ty) = walker.next() {
1846 walker.skip_current_subtree();
1852 impl<'tcx> ItemSubsts<'tcx> {
1853 pub fn is_noop(&self) -> bool {
1854 self.substs.is_noop()
1858 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1859 pub enum LvaluePreference {
1864 impl LvaluePreference {
1865 pub fn from_mutbl(m: hir::Mutability) -> Self {
1867 hir::MutMutable => PreferMutLvalue,
1868 hir::MutImmutable => NoPreference,
1873 /// Helper for looking things up in the various maps that are populated during
1874 /// typeck::collect (e.g., `tcx.associated_items`, `tcx.types`, etc). All of
1875 /// these share the pattern that if the id is local, it should have been loaded
1876 /// into the map by the `typeck::collect` phase. If the def-id is external,
1877 /// then we have to go consult the crate loading code (and cache the result for
1879 fn lookup_locally_or_in_crate_store<M, F>(descr: &str,
1884 M: MemoizationMap<Key=DefId>,
1885 F: FnOnce() -> M::Value,
1887 map.memoize(def_id, || {
1888 if def_id.is_local() {
1889 bug!("No def'n found for {:?} in tcx.{}", def_id, descr);
1896 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
1898 hir::MutMutable => MutBorrow,
1899 hir::MutImmutable => ImmBorrow,
1903 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
1904 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
1905 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
1907 pub fn to_mutbl_lossy(self) -> hir::Mutability {
1909 MutBorrow => hir::MutMutable,
1910 ImmBorrow => hir::MutImmutable,
1912 // We have no type corresponding to a unique imm borrow, so
1913 // use `&mut`. It gives all the capabilities of an `&uniq`
1914 // and hence is a safe "over approximation".
1915 UniqueImmBorrow => hir::MutMutable,
1919 pub fn to_user_str(&self) -> &'static str {
1921 MutBorrow => "mutable",
1922 ImmBorrow => "immutable",
1923 UniqueImmBorrow => "uniquely immutable",
1928 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1929 pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
1930 self.item_tables(self.hir.body_owner_def_id(body))
1933 pub fn item_tables(self, def_id: DefId) -> &'gcx TypeckTables<'gcx> {
1934 self.tables.memoize(def_id, || {
1935 if def_id.is_local() {
1936 // Closures' tables come from their outermost function,
1937 // as they are part of the same "inference environment".
1938 let outer_def_id = self.closure_base_def_id(def_id);
1939 if outer_def_id != def_id {
1940 return self.item_tables(outer_def_id);
1943 bug!("No def'n found for {:?} in tcx.tables", def_id);
1946 // Cross-crate side-tables only exist alongside serialized HIR.
1947 self.sess.cstore.maybe_get_item_body(self.global_tcx(), def_id).map(|_| {
1948 self.tables.borrow()[&def_id]
1949 }).unwrap_or_else(|| {
1950 bug!("tcx.item_tables({:?}): missing from metadata", def_id)
1955 pub fn expr_span(self, id: NodeId) -> Span {
1956 match self.hir.find(id) {
1957 Some(hir_map::NodeExpr(e)) => {
1961 bug!("Node id {} is not an expr: {:?}", id, f);
1964 bug!("Node id {} is not present in the node map", id);
1969 pub fn local_var_name_str(self, id: NodeId) -> InternedString {
1970 match self.hir.find(id) {
1971 Some(hir_map::NodeLocal(pat)) => {
1973 hir::PatKind::Binding(_, _, ref path1, _) => path1.node.as_str(),
1975 bug!("Variable id {} maps to {:?}, not local", id, pat);
1979 r => bug!("Variable id {} maps to {:?}, not local", id, r),
1983 pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
1985 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
1987 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
1992 hir::ExprType(ref e, _) => {
1993 self.expr_is_lval(e)
1996 hir::ExprUnary(hir::UnDeref, _) |
1997 hir::ExprField(..) |
1998 hir::ExprTupField(..) |
1999 hir::ExprIndex(..) => {
2003 // Partially qualified paths in expressions can only legally
2004 // refer to associated items which are always rvalues.
2005 hir::ExprPath(hir::QPath::TypeRelative(..)) |
2008 hir::ExprMethodCall(..) |
2009 hir::ExprStruct(..) |
2012 hir::ExprMatch(..) |
2013 hir::ExprClosure(..) |
2014 hir::ExprBlock(..) |
2015 hir::ExprRepeat(..) |
2016 hir::ExprArray(..) |
2017 hir::ExprBreak(..) |
2018 hir::ExprAgain(..) |
2020 hir::ExprWhile(..) |
2022 hir::ExprAssign(..) |
2023 hir::ExprInlineAsm(..) |
2024 hir::ExprAssignOp(..) |
2026 hir::ExprUnary(..) |
2028 hir::ExprAddrOf(..) |
2029 hir::ExprBinary(..) |
2030 hir::ExprCast(..) => {
2036 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2037 self.associated_items(id)
2038 .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2042 pub fn trait_impl_polarity(self, id: DefId) -> hir::ImplPolarity {
2043 if let Some(id) = self.hir.as_local_node_id(id) {
2044 match self.hir.expect_item(id).node {
2045 hir::ItemImpl(_, polarity, ..) => polarity,
2046 ref item => bug!("trait_impl_polarity: {:?} not an impl", item)
2049 self.sess.cstore.impl_polarity(id)
2053 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2054 self.associated_items(did).any(|item| {
2055 item.relevant_for_never()
2059 pub fn custom_coerce_unsized_kind(self, did: DefId) -> adjustment::CustomCoerceUnsized {
2060 self.custom_coerce_unsized_kinds.memoize(did, || {
2061 let (kind, src) = if did.krate != LOCAL_CRATE {
2062 (self.sess.cstore.custom_coerce_unsized_kind(did), "external")
2070 bug!("custom_coerce_unsized_kind: \
2071 {} impl `{}` is missing its kind",
2072 src, self.item_path_str(did));
2078 pub fn associated_item(self, def_id: DefId) -> AssociatedItem {
2079 self.associated_items.memoize(def_id, || {
2080 if !def_id.is_local() {
2081 return self.sess.cstore.associated_item(def_id)
2082 .expect("missing AssociatedItem in metadata");
2085 // When the user asks for a given associated item, we
2086 // always go ahead and convert all the associated items in
2087 // the container. Note that we are also careful only to
2088 // ever register a read on the *container* of the assoc
2089 // item, not the assoc item itself. This prevents changes
2090 // in the details of an item (for example, the type to
2091 // which an associated type is bound) from contaminating
2092 // those tasks that just need to scan the names of items
2095 let id = self.hir.as_local_node_id(def_id).unwrap();
2096 let parent_id = self.hir.get_parent(id);
2097 let parent_def_id = self.hir.local_def_id(parent_id);
2098 let parent_item = self.hir.expect_item(parent_id);
2099 match parent_item.node {
2100 hir::ItemImpl(.., ref impl_trait_ref, _, ref impl_item_refs) => {
2101 for impl_item_ref in impl_item_refs {
2103 self.associated_item_from_impl_item_ref(parent_def_id,
2104 impl_trait_ref.is_some(),
2106 self.associated_items.borrow_mut().insert(assoc_item.def_id, assoc_item);
2110 hir::ItemTrait(.., ref trait_item_refs) => {
2111 for trait_item_ref in trait_item_refs {
2113 self.associated_item_from_trait_item_ref(parent_def_id, trait_item_ref);
2114 self.associated_items.borrow_mut().insert(assoc_item.def_id, assoc_item);
2119 panic!("unexpected container of associated items: {:?}", r)
2123 // memoize wants us to return something, so return
2124 // the one we generated for this def-id
2125 *self.associated_items.borrow().get(&def_id).unwrap()
2129 fn associated_item_from_trait_item_ref(self,
2130 parent_def_id: DefId,
2131 trait_item_ref: &hir::TraitItemRef)
2133 let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2134 let (kind, has_self) = match trait_item_ref.kind {
2135 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2136 hir::AssociatedItemKind::Method { has_self } => {
2137 (ty::AssociatedKind::Method, has_self)
2139 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2143 name: trait_item_ref.name,
2145 vis: Visibility::from_hir(&hir::Inherited, trait_item_ref.id.node_id, self),
2146 defaultness: trait_item_ref.defaultness,
2148 container: TraitContainer(parent_def_id),
2149 method_has_self_argument: has_self
2153 fn associated_item_from_impl_item_ref(self,
2154 parent_def_id: DefId,
2155 from_trait_impl: bool,
2156 impl_item_ref: &hir::ImplItemRef)
2158 let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2159 let (kind, has_self) = match impl_item_ref.kind {
2160 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2161 hir::AssociatedItemKind::Method { has_self } => {
2162 (ty::AssociatedKind::Method, has_self)
2164 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2167 // Trait impl items are always public.
2168 let public = hir::Public;
2169 let vis = if from_trait_impl { &public } else { &impl_item_ref.vis };
2171 ty::AssociatedItem {
2172 name: impl_item_ref.name,
2174 vis: ty::Visibility::from_hir(vis, impl_item_ref.id.node_id, self),
2175 defaultness: impl_item_ref.defaultness,
2177 container: ImplContainer(parent_def_id),
2178 method_has_self_argument: has_self
2182 pub fn associated_item_def_ids(self, def_id: DefId) -> Rc<Vec<DefId>> {
2183 self.associated_item_def_ids.memoize(def_id, || {
2184 if !def_id.is_local() {
2185 return Rc::new(self.sess.cstore.associated_item_def_ids(def_id));
2188 let id = self.hir.as_local_node_id(def_id).unwrap();
2189 let item = self.hir.expect_item(id);
2190 let vec: Vec<_> = match item.node {
2191 hir::ItemTrait(.., ref trait_item_refs) => {
2192 trait_item_refs.iter()
2193 .map(|trait_item_ref| trait_item_ref.id)
2194 .map(|id| self.hir.local_def_id(id.node_id))
2197 hir::ItemImpl(.., ref impl_item_refs) => {
2198 impl_item_refs.iter()
2199 .map(|impl_item_ref| impl_item_ref.id)
2200 .map(|id| self.hir.local_def_id(id.node_id))
2203 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2209 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2210 pub fn associated_items(self, def_id: DefId)
2211 -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2212 let def_ids = self.associated_item_def_ids(def_id);
2213 (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2216 /// Returns the trait-ref corresponding to a given impl, or None if it is
2217 /// an inherent impl.
2218 pub fn impl_trait_ref(self, id: DefId) -> Option<TraitRef<'gcx>> {
2219 lookup_locally_or_in_crate_store(
2220 "impl_trait_refs", id, &self.impl_trait_refs,
2221 || self.sess.cstore.impl_trait_ref(self.global_tcx(), id))
2224 // Returns `ty::VariantDef` if `def` refers to a struct,
2225 // or variant or their constructors, panics otherwise.
2226 pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2228 Def::Variant(did) | Def::VariantCtor(did, ..) => {
2229 let enum_did = self.parent_def_id(did).unwrap();
2230 self.lookup_adt_def(enum_did).variant_with_id(did)
2232 Def::Struct(did) | Def::Union(did) => {
2233 self.lookup_adt_def(did).struct_variant()
2235 Def::StructCtor(ctor_did, ..) => {
2236 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2237 self.lookup_adt_def(did).struct_variant()
2239 _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2243 pub fn def_key(self, id: DefId) -> hir_map::DefKey {
2245 self.hir.def_key(id)
2247 self.sess.cstore.def_key(id)
2251 /// Convert a `DefId` into its fully expanded `DefPath` (every
2252 /// `DefId` is really just an interned def-path).
2254 /// Note that if `id` is not local to this crate, the result will
2255 // be a non-local `DefPath`.
2256 pub fn def_path(self, id: DefId) -> hir_map::DefPath {
2258 self.hir.def_path(id)
2260 self.sess.cstore.def_path(id)
2264 pub fn def_span(self, def_id: DefId) -> Span {
2265 if let Some(id) = self.hir.as_local_node_id(def_id) {
2268 self.sess.cstore.def_span(&self.sess, def_id)
2272 pub fn vis_is_accessible_from(self, vis: Visibility, block: NodeId) -> bool {
2273 vis.is_accessible_from(self.hir.local_def_id(self.hir.get_module_parent(block)), self)
2276 pub fn item_name(self, id: DefId) -> ast::Name {
2277 if let Some(id) = self.hir.as_local_node_id(id) {
2279 } else if id.index == CRATE_DEF_INDEX {
2280 self.sess.cstore.original_crate_name(id.krate)
2282 let def_key = self.sess.cstore.def_key(id);
2283 // The name of a StructCtor is that of its struct parent.
2284 if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2285 self.item_name(DefId {
2287 index: def_key.parent.unwrap()
2290 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2291 bug!("item_name: no name for {:?}", self.def_path(id));
2297 // If the given item is in an external crate, looks up its type and adds it to
2298 // the type cache. Returns the type parameters and type.
2299 pub fn item_type(self, did: DefId) -> Ty<'gcx> {
2300 lookup_locally_or_in_crate_store(
2301 "item_types", did, &self.item_types,
2302 || self.sess.cstore.item_type(self.global_tcx(), did))
2305 /// Given the did of a trait, returns its canonical trait ref.
2306 pub fn lookup_trait_def(self, did: DefId) -> &'gcx TraitDef {
2307 lookup_locally_or_in_crate_store(
2308 "trait_defs", did, &self.trait_defs,
2309 || self.alloc_trait_def(self.sess.cstore.trait_def(self.global_tcx(), did))
2313 /// Given the did of an ADT, return a reference to its definition.
2314 pub fn lookup_adt_def(self, did: DefId) -> &'gcx AdtDef {
2315 lookup_locally_or_in_crate_store(
2316 "adt_defs", did, &self.adt_defs,
2317 || self.sess.cstore.adt_def(self.global_tcx(), did))
2320 /// Given the did of an item, returns its generics.
2321 pub fn item_generics(self, did: DefId) -> &'gcx Generics<'gcx> {
2322 lookup_locally_or_in_crate_store(
2323 "generics", did, &self.generics,
2324 || self.alloc_generics(self.sess.cstore.item_generics(self.global_tcx(), did)))
2327 /// Given the did of an item, returns its full set of predicates.
2328 pub fn item_predicates(self, did: DefId) -> GenericPredicates<'gcx> {
2329 lookup_locally_or_in_crate_store(
2330 "predicates", did, &self.predicates,
2331 || self.sess.cstore.item_predicates(self.global_tcx(), did))
2334 /// Given the did of a trait, returns its superpredicates.
2335 pub fn item_super_predicates(self, did: DefId) -> GenericPredicates<'gcx> {
2336 lookup_locally_or_in_crate_store(
2337 "super_predicates", did, &self.super_predicates,
2338 || self.sess.cstore.item_super_predicates(self.global_tcx(), did))
2341 /// Given the did of an item, returns its MIR, borrowed immutably.
2342 pub fn item_mir(self, did: DefId) -> Ref<'gcx, Mir<'gcx>> {
2343 lookup_locally_or_in_crate_store("mir_map", did, &self.mir_map, || {
2344 let mir = self.sess.cstore.get_item_mir(self.global_tcx(), did);
2345 let mir = self.alloc_mir(mir);
2347 // Perma-borrow MIR from extern crates to prevent mutation.
2348 mem::forget(mir.borrow());
2354 /// If `type_needs_drop` returns true, then `ty` is definitely
2355 /// non-copy and *might* have a destructor attached; if it returns
2356 /// false, then `ty` definitely has no destructor (i.e. no drop glue).
2358 /// (Note that this implies that if `ty` has a destructor attached,
2359 /// then `type_needs_drop` will definitely return `true` for `ty`.)
2360 pub fn type_needs_drop_given_env(self,
2362 param_env: &ty::ParameterEnvironment<'gcx>) -> bool {
2363 // Issue #22536: We first query type_moves_by_default. It sees a
2364 // normalized version of the type, and therefore will definitely
2365 // know whether the type implements Copy (and thus needs no
2366 // cleanup/drop/zeroing) ...
2367 let tcx = self.global_tcx();
2368 let implements_copy = !ty.moves_by_default(tcx, param_env, DUMMY_SP);
2370 if implements_copy { return false; }
2372 // ... (issue #22536 continued) but as an optimization, still use
2373 // prior logic of asking if the `needs_drop` bit is set; we need
2374 // not zero non-Copy types if they have no destructor.
2376 // FIXME(#22815): Note that calling `ty::type_contents` is a
2377 // conservative heuristic; it may report that `needs_drop` is set
2378 // when actual type does not actually have a destructor associated
2379 // with it. But since `ty` absolutely did not have the `Copy`
2380 // bound attached (see above), it is sound to treat it as having a
2381 // destructor (e.g. zero its memory on move).
2383 let contents = ty.type_contents(tcx);
2384 debug!("type_needs_drop ty={:?} contents={:?}", ty, contents);
2385 contents.needs_drop(tcx)
2388 /// Get the attributes of a definition.
2389 pub fn get_attrs(self, did: DefId) -> Cow<'gcx, [ast::Attribute]> {
2390 if let Some(id) = self.hir.as_local_node_id(did) {
2391 Cow::Borrowed(self.hir.attrs(id))
2393 Cow::Owned(self.sess.cstore.item_attrs(did))
2397 /// Determine whether an item is annotated with an attribute
2398 pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2399 self.get_attrs(did).iter().any(|item| item.check_name(attr))
2402 /// Determine whether an item is annotated with `#[repr(packed)]`
2403 pub fn lookup_packed(self, did: DefId) -> bool {
2404 self.lookup_repr_hints(did).contains(&attr::ReprPacked)
2407 /// Determine whether an item is annotated with `#[simd]`
2408 pub fn lookup_simd(self, did: DefId) -> bool {
2409 self.has_attr(did, "simd")
2410 || self.lookup_repr_hints(did).contains(&attr::ReprSimd)
2413 pub fn item_variances(self, item_id: DefId) -> Rc<Vec<ty::Variance>> {
2414 lookup_locally_or_in_crate_store(
2415 "item_variance_map", item_id, &self.item_variance_map,
2416 || Rc::new(self.sess.cstore.item_variances(item_id)))
2419 pub fn trait_has_default_impl(self, trait_def_id: DefId) -> bool {
2420 self.populate_implementations_for_trait_if_necessary(trait_def_id);
2422 let def = self.lookup_trait_def(trait_def_id);
2423 def.flags.get().intersects(TraitFlags::HAS_DEFAULT_IMPL)
2426 /// Records a trait-to-implementation mapping.
2427 pub fn record_trait_has_default_impl(self, trait_def_id: DefId) {
2428 let def = self.lookup_trait_def(trait_def_id);
2429 def.flags.set(def.flags.get() | TraitFlags::HAS_DEFAULT_IMPL)
2432 /// Populates the type context with all the inherent implementations for
2433 /// the given type if necessary.
2434 pub fn populate_inherent_implementations_for_type_if_necessary(self,
2436 if type_id.is_local() {
2440 // The type is not local, hence we are reading this out of
2441 // metadata and don't need to track edges.
2442 let _ignore = self.dep_graph.in_ignore();
2444 if self.populated_external_types.borrow().contains(&type_id) {
2448 debug!("populate_inherent_implementations_for_type_if_necessary: searching for {:?}",
2451 let inherent_impls = self.sess.cstore.inherent_implementations_for_type(type_id);
2453 self.inherent_impls.borrow_mut().insert(type_id, inherent_impls);
2454 self.populated_external_types.borrow_mut().insert(type_id);
2457 /// Populates the type context with all the implementations for the given
2458 /// trait if necessary.
2459 pub fn populate_implementations_for_trait_if_necessary(self, trait_id: DefId) {
2460 if trait_id.is_local() {
2464 // The type is not local, hence we are reading this out of
2465 // metadata and don't need to track edges.
2466 let _ignore = self.dep_graph.in_ignore();
2468 let def = self.lookup_trait_def(trait_id);
2469 if def.flags.get().intersects(TraitFlags::IMPLS_VALID) {
2473 debug!("populate_implementations_for_trait_if_necessary: searching for {:?}", def);
2475 if self.sess.cstore.is_defaulted_trait(trait_id) {
2476 self.record_trait_has_default_impl(trait_id);
2479 for impl_def_id in self.sess.cstore.implementations_of_trait(Some(trait_id)) {
2480 let trait_ref = self.impl_trait_ref(impl_def_id).unwrap();
2482 // Record the trait->implementation mapping.
2483 let parent = self.sess.cstore.impl_parent(impl_def_id).unwrap_or(trait_id);
2484 def.record_remote_impl(self, impl_def_id, trait_ref, parent);
2487 def.flags.set(def.flags.get() | TraitFlags::IMPLS_VALID);
2490 pub fn closure_kind(self, def_id: DefId) -> ty::ClosureKind {
2491 // If this is a local def-id, it should be inserted into the
2492 // tables by typeck; else, it will be retreived from
2493 // the external crate metadata.
2494 if let Some(&kind) = self.closure_kinds.borrow().get(&def_id) {
2498 let kind = self.sess.cstore.closure_kind(def_id);
2499 self.closure_kinds.borrow_mut().insert(def_id, kind);
2503 pub fn closure_type(self,
2505 substs: ClosureSubsts<'tcx>)
2506 -> ty::ClosureTy<'tcx>
2508 // If this is a local def-id, it should be inserted into the
2509 // tables by typeck; else, it will be retreived from
2510 // the external crate metadata.
2511 if let Some(ty) = self.closure_tys.borrow().get(&def_id) {
2512 return ty.subst(self, substs.substs);
2515 let ty = self.sess.cstore.closure_ty(self.global_tcx(), def_id);
2516 self.closure_tys.borrow_mut().insert(def_id, ty.clone());
2517 ty.subst(self, substs.substs)
2520 /// Given the def_id of an impl, return the def_id of the trait it implements.
2521 /// If it implements no trait, return `None`.
2522 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2523 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2526 /// If the given def ID describes a method belonging to an impl, return the
2527 /// ID of the impl that the method belongs to. Otherwise, return `None`.
2528 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2529 if def_id.krate != LOCAL_CRATE {
2530 return self.sess.cstore.associated_item(def_id).and_then(|item| {
2531 match item.container {
2532 TraitContainer(_) => None,
2533 ImplContainer(def_id) => Some(def_id),
2537 match self.associated_items.borrow().get(&def_id).cloned() {
2538 Some(trait_item) => {
2539 match trait_item.container {
2540 TraitContainer(_) => None,
2541 ImplContainer(def_id) => Some(def_id),
2548 /// If the given def ID describes an item belonging to a trait,
2549 /// return the ID of the trait that the trait item belongs to.
2550 /// Otherwise, return `None`.
2551 pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
2552 if def_id.krate != LOCAL_CRATE {
2553 return self.sess.cstore.trait_of_item(def_id);
2555 match self.associated_items.borrow().get(&def_id) {
2556 Some(associated_item) => {
2557 match associated_item.container {
2558 TraitContainer(def_id) => Some(def_id),
2559 ImplContainer(_) => None
2566 /// Construct a parameter environment suitable for static contexts or other contexts where there
2567 /// are no free type/lifetime parameters in scope.
2568 pub fn empty_parameter_environment(self) -> ParameterEnvironment<'tcx> {
2570 // for an empty parameter environment, there ARE no free
2571 // regions, so it shouldn't matter what we use for the free id
2572 let free_id_outlive = self.region_maps.node_extent(ast::DUMMY_NODE_ID);
2573 ty::ParameterEnvironment {
2574 free_substs: self.intern_substs(&[]),
2575 caller_bounds: Vec::new(),
2576 implicit_region_bound: self.mk_region(ty::ReEmpty),
2577 free_id_outlive: free_id_outlive,
2578 is_copy_cache: RefCell::new(FxHashMap()),
2579 is_sized_cache: RefCell::new(FxHashMap()),
2583 /// Constructs and returns a substitution that can be applied to move from
2584 /// the "outer" view of a type or method to the "inner" view.
2585 /// In general, this means converting from bound parameters to
2586 /// free parameters. Since we currently represent bound/free type
2587 /// parameters in the same way, this only has an effect on regions.
2588 pub fn construct_free_substs(self, def_id: DefId,
2589 free_id_outlive: CodeExtent)
2590 -> &'gcx Substs<'gcx> {
2592 let substs = Substs::for_item(self.global_tcx(), def_id, |def, _| {
2593 // map bound 'a => free 'a
2594 self.global_tcx().mk_region(ReFree(FreeRegion {
2595 scope: free_id_outlive,
2596 bound_region: def.to_bound_region()
2600 self.global_tcx().mk_param_from_def(def)
2603 debug!("construct_parameter_environment: {:?}", substs);
2607 /// See `ParameterEnvironment` struct def'n for details.
2608 /// If you were using `free_id: NodeId`, you might try `self.region_maps.item_extent(free_id)`
2609 /// for the `free_id_outlive` parameter. (But note that this is not always quite right.)
2610 pub fn construct_parameter_environment(self,
2613 free_id_outlive: CodeExtent)
2614 -> ParameterEnvironment<'gcx>
2617 // Construct the free substs.
2620 let free_substs = self.construct_free_substs(def_id, free_id_outlive);
2623 // Compute the bounds on Self and the type parameters.
2626 let tcx = self.global_tcx();
2627 let generic_predicates = tcx.item_predicates(def_id);
2628 let bounds = generic_predicates.instantiate(tcx, free_substs);
2629 let bounds = tcx.liberate_late_bound_regions(free_id_outlive, &ty::Binder(bounds));
2630 let predicates = bounds.predicates;
2632 // Finally, we have to normalize the bounds in the environment, in
2633 // case they contain any associated type projections. This process
2634 // can yield errors if the put in illegal associated types, like
2635 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2636 // report these errors right here; this doesn't actually feel
2637 // right to me, because constructing the environment feels like a
2638 // kind of a "idempotent" action, but I'm not sure where would be
2639 // a better place. In practice, we construct environments for
2640 // every fn once during type checking, and we'll abort if there
2641 // are any errors at that point, so after type checking you can be
2642 // sure that this will succeed without errors anyway.
2645 let unnormalized_env = ty::ParameterEnvironment {
2646 free_substs: free_substs,
2647 implicit_region_bound: tcx.mk_region(ty::ReScope(free_id_outlive)),
2648 caller_bounds: predicates,
2649 free_id_outlive: free_id_outlive,
2650 is_copy_cache: RefCell::new(FxHashMap()),
2651 is_sized_cache: RefCell::new(FxHashMap()),
2654 let cause = traits::ObligationCause::misc(span, free_id_outlive.node_id(&self.region_maps));
2655 traits::normalize_param_env_or_error(tcx, unnormalized_env, cause)
2658 pub fn node_scope_region(self, id: NodeId) -> &'tcx Region {
2659 self.mk_region(ty::ReScope(self.region_maps.node_extent(id)))
2662 pub fn visit_all_item_likes_in_krate<V,F>(self,
2665 where F: FnMut(DefId) -> DepNode<DefId>, V: ItemLikeVisitor<'gcx>
2667 dep_graph::visit_all_item_likes_in_krate(self.global_tcx(), dep_node_fn, visitor);
2670 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2671 /// with the name of the crate containing the impl.
2672 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2673 if impl_did.is_local() {
2674 let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2675 Ok(self.hir.span(node_id))
2677 Err(self.sess.cstore.crate_name(impl_did.krate))
2682 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2683 pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2684 F: FnOnce(&[hir::Freevar]) -> T,
2686 match self.freevars.borrow().get(&fid) {
2688 Some(d) => f(&d[..])