1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::Variance::*;
12 pub use self::AssociatedItemContainer::*;
13 pub use self::BorrowKind::*;
14 pub use self::IntVarValue::*;
15 pub use self::LvaluePreference::*;
16 pub use self::fold::TypeFoldable;
18 use dep_graph::DepNode;
19 use hir::{map as hir_map, FreevarMap, TraitMap};
20 use hir::def::{Def, CtorKind, ExportMap};
21 use hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
22 use ich::{self, StableHashingContext};
23 use middle::const_val::ConstVal;
24 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
25 use middle::privacy::AccessLevels;
26 use middle::resolve_lifetime::ObjectLifetimeDefault;
27 use middle::region::CodeExtent;
31 use ty::subst::{Subst, Substs};
32 use ty::util::IntTypeExt;
33 use ty::walk::TypeWalker;
34 use util::common::ErrorReported;
35 use util::nodemap::{NodeSet, DefIdMap, FxHashMap, FxHashSet};
37 use serialize::{self, Encodable, Encoder};
38 use std::collections::BTreeMap;
41 use std::hash::{Hash, Hasher};
42 use std::iter::FromIterator;
46 use std::vec::IntoIter;
48 use syntax::ast::{self, DUMMY_NODE_ID, Name, Ident, NodeId};
50 use syntax::ext::hygiene::{Mark, SyntaxContext};
51 use syntax::symbol::{Symbol, InternedString};
52 use syntax_pos::{DUMMY_SP, Span};
53 use rustc_const_math::ConstInt;
55 use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
56 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
58 use rustc_data_structures::transitive_relation::TransitiveRelation;
62 pub use self::sty::{Binder, DebruijnIndex};
63 pub use self::sty::{FnSig, PolyFnSig};
64 pub use self::sty::{InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
65 pub use self::sty::{ClosureSubsts, TypeAndMut};
66 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
67 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
68 pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
69 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
70 pub use self::sty::RegionKind;
71 pub use self::sty::Issue32330;
72 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid, SkolemizedRegionVid};
73 pub use self::sty::BoundRegion::*;
74 pub use self::sty::InferTy::*;
75 pub use self::sty::RegionKind::*;
76 pub use self::sty::TypeVariants::*;
78 pub use self::context::{TyCtxt, GlobalArenas, tls};
79 pub use self::context::{Lift, TypeckTables};
81 pub use self::instance::{Instance, InstanceDef};
83 pub use self::trait_def::TraitDef;
85 pub use self::maps::queries;
92 pub mod inhabitedness;
109 mod structural_impls;
114 /// The complete set of all analyses described in this module. This is
115 /// produced by the driver and fed to trans and later passes.
117 /// NB: These contents are being migrated into queries using the
118 /// *on-demand* infrastructure.
120 pub struct CrateAnalysis {
121 pub access_levels: Rc<AccessLevels>,
122 pub reachable: Rc<NodeSet>,
124 pub glob_map: Option<hir::GlobMap>,
128 pub struct Resolutions {
129 pub freevars: FreevarMap,
130 pub trait_map: TraitMap,
131 pub maybe_unused_trait_imports: NodeSet,
132 pub export_map: ExportMap,
135 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
136 pub enum AssociatedItemContainer {
137 TraitContainer(DefId),
138 ImplContainer(DefId),
141 impl AssociatedItemContainer {
142 pub fn id(&self) -> DefId {
144 TraitContainer(id) => id,
145 ImplContainer(id) => id,
150 /// The "header" of an impl is everything outside the body: a Self type, a trait
151 /// ref (in the case of a trait impl), and a set of predicates (from the
152 /// bounds/where clauses).
153 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
154 pub struct ImplHeader<'tcx> {
155 pub impl_def_id: DefId,
156 pub self_ty: Ty<'tcx>,
157 pub trait_ref: Option<TraitRef<'tcx>>,
158 pub predicates: Vec<Predicate<'tcx>>,
161 impl<'a, 'gcx, 'tcx> ImplHeader<'tcx> {
162 pub fn with_fresh_ty_vars(selcx: &mut traits::SelectionContext<'a, 'gcx, 'tcx>,
166 let tcx = selcx.tcx();
167 let impl_substs = selcx.infcx().fresh_substs_for_item(DUMMY_SP, impl_def_id);
169 let header = ImplHeader {
170 impl_def_id: impl_def_id,
171 self_ty: tcx.type_of(impl_def_id),
172 trait_ref: tcx.impl_trait_ref(impl_def_id),
173 predicates: tcx.predicates_of(impl_def_id).predicates
174 }.subst(tcx, impl_substs);
176 let traits::Normalized { value: mut header, obligations } =
177 traits::normalize(selcx, traits::ObligationCause::dummy(), &header);
179 header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
184 #[derive(Copy, Clone, Debug)]
185 pub struct AssociatedItem {
188 pub kind: AssociatedKind,
190 pub defaultness: hir::Defaultness,
191 pub container: AssociatedItemContainer,
193 /// Whether this is a method with an explicit self
194 /// as its first argument, allowing method calls.
195 pub method_has_self_argument: bool,
198 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
199 pub enum AssociatedKind {
205 impl AssociatedItem {
206 pub fn def(&self) -> Def {
208 AssociatedKind::Const => Def::AssociatedConst(self.def_id),
209 AssociatedKind::Method => Def::Method(self.def_id),
210 AssociatedKind::Type => Def::AssociatedTy(self.def_id),
214 /// Tests whether the associated item admits a non-trivial implementation
216 pub fn relevant_for_never<'tcx>(&self) -> bool {
218 AssociatedKind::Const => true,
219 AssociatedKind::Type => true,
220 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
221 AssociatedKind::Method => !self.method_has_self_argument,
226 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
227 pub enum Visibility {
228 /// Visible everywhere (including in other crates).
230 /// Visible only in the given crate-local module.
232 /// Not visible anywhere in the local crate. This is the visibility of private external items.
236 pub trait DefIdTree: Copy {
237 fn parent(self, id: DefId) -> Option<DefId>;
239 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
240 if descendant.krate != ancestor.krate {
244 while descendant != ancestor {
245 match self.parent(descendant) {
246 Some(parent) => descendant = parent,
247 None => return false,
254 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
255 fn parent(self, id: DefId) -> Option<DefId> {
256 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
261 pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
263 hir::Public => Visibility::Public,
264 hir::Visibility::Crate => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
265 hir::Visibility::Restricted { ref path, .. } => match path.def {
266 // If there is no resolution, `resolve` will have already reported an error, so
267 // assume that the visibility is public to avoid reporting more privacy errors.
268 Def::Err => Visibility::Public,
269 def => Visibility::Restricted(def.def_id()),
272 Visibility::Restricted(tcx.hir.get_module_parent(id))
277 /// Returns true if an item with this visibility is accessible from the given block.
278 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
279 let restriction = match self {
280 // Public items are visible everywhere.
281 Visibility::Public => return true,
282 // Private items from other crates are visible nowhere.
283 Visibility::Invisible => return false,
284 // Restricted items are visible in an arbitrary local module.
285 Visibility::Restricted(other) if other.krate != module.krate => return false,
286 Visibility::Restricted(module) => module,
289 tree.is_descendant_of(module, restriction)
292 /// Returns true if this visibility is at least as accessible as the given visibility
293 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
294 let vis_restriction = match vis {
295 Visibility::Public => return self == Visibility::Public,
296 Visibility::Invisible => return true,
297 Visibility::Restricted(module) => module,
300 self.is_accessible_from(vis_restriction, tree)
304 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
306 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
307 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
308 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
309 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
312 /// The crate variances map is computed during typeck and contains the
313 /// variance of every item in the local crate. You should not use it
314 /// directly, because to do so will make your pass dependent on the
315 /// HIR of every item in the local crate. Instead, use
316 /// `tcx.variances_of()` to get the variance for a *particular*
318 pub struct CrateVariancesMap {
319 /// This relation tracks the dependencies between the variance of
320 /// various items. In particular, if `a < b`, then the variance of
321 /// `a` depends on the sources of `b`.
322 pub dependencies: TransitiveRelation<DefId>,
324 /// For each item with generics, maps to a vector of the variance
325 /// of its generics. If an item has no generics, it will have no
327 pub variances: FxHashMap<DefId, Rc<Vec<ty::Variance>>>,
329 /// An empty vector, useful for cloning.
330 pub empty_variance: Rc<Vec<ty::Variance>>,
334 /// `a.xform(b)` combines the variance of a context with the
335 /// variance of a type with the following meaning. If we are in a
336 /// context with variance `a`, and we encounter a type argument in
337 /// a position with variance `b`, then `a.xform(b)` is the new
338 /// variance with which the argument appears.
344 /// Here, the "ambient" variance starts as covariant. `*mut T` is
345 /// invariant with respect to `T`, so the variance in which the
346 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
347 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
348 /// respect to its type argument `T`, and hence the variance of
349 /// the `i32` here is `Invariant.xform(Covariant)`, which results
350 /// (again) in `Invariant`.
354 /// fn(*const Vec<i32>, *mut Vec<i32)
356 /// The ambient variance is covariant. A `fn` type is
357 /// contravariant with respect to its parameters, so the variance
358 /// within which both pointer types appear is
359 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
360 /// T` is covariant with respect to `T`, so the variance within
361 /// which the first `Vec<i32>` appears is
362 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
363 /// is true for its `i32` argument. In the `*mut T` case, the
364 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
365 /// and hence the outermost type is `Invariant` with respect to
366 /// `Vec<i32>` (and its `i32` argument).
368 /// Source: Figure 1 of "Taming the Wildcards:
369 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
370 pub fn xform(self, v: ty::Variance) -> ty::Variance {
372 // Figure 1, column 1.
373 (ty::Covariant, ty::Covariant) => ty::Covariant,
374 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
375 (ty::Covariant, ty::Invariant) => ty::Invariant,
376 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
378 // Figure 1, column 2.
379 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
380 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
381 (ty::Contravariant, ty::Invariant) => ty::Invariant,
382 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
384 // Figure 1, column 3.
385 (ty::Invariant, _) => ty::Invariant,
387 // Figure 1, column 4.
388 (ty::Bivariant, _) => ty::Bivariant,
393 #[derive(Clone, Copy, Debug, RustcDecodable, RustcEncodable)]
394 pub struct MethodCallee<'tcx> {
395 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
397 pub substs: &'tcx Substs<'tcx>,
399 /// Instantiated method signature, i.e. it has been substituted,
400 /// normalized, and has had late-bound lifetimes replaced
401 /// (with inference variables, during type-checking).
402 pub sig: FnSig<'tcx>,
405 // Contains information needed to resolve types and (in the future) look up
406 // the types of AST nodes.
407 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
408 pub struct CReaderCacheKey {
413 // Flags that we track on types. These flags are propagated upwards
414 // through the type during type construction, so that we can quickly
415 // check whether the type has various kinds of types in it without
416 // recursing over the type itself.
418 flags TypeFlags: u32 {
419 const HAS_PARAMS = 1 << 0,
420 const HAS_SELF = 1 << 1,
421 const HAS_TY_INFER = 1 << 2,
422 const HAS_RE_INFER = 1 << 3,
423 const HAS_RE_SKOL = 1 << 4,
424 const HAS_RE_EARLY_BOUND = 1 << 5,
425 const HAS_FREE_REGIONS = 1 << 6,
426 const HAS_TY_ERR = 1 << 7,
427 const HAS_PROJECTION = 1 << 8,
428 const HAS_TY_CLOSURE = 1 << 9,
430 // true if there are "names" of types and regions and so forth
431 // that are local to a particular fn
432 const HAS_LOCAL_NAMES = 1 << 10,
434 // Present if the type belongs in a local type context.
435 // Only set for TyInfer other than Fresh.
436 const KEEP_IN_LOCAL_TCX = 1 << 11,
438 // Is there a projection that does not involve a bound region?
439 // Currently we can't normalize projections w/ bound regions.
440 const HAS_NORMALIZABLE_PROJECTION = 1 << 12,
442 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
443 TypeFlags::HAS_SELF.bits |
444 TypeFlags::HAS_RE_EARLY_BOUND.bits,
446 // Flags representing the nominal content of a type,
447 // computed by FlagsComputation. If you add a new nominal
448 // flag, it should be added here too.
449 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
450 TypeFlags::HAS_SELF.bits |
451 TypeFlags::HAS_TY_INFER.bits |
452 TypeFlags::HAS_RE_INFER.bits |
453 TypeFlags::HAS_RE_SKOL.bits |
454 TypeFlags::HAS_RE_EARLY_BOUND.bits |
455 TypeFlags::HAS_FREE_REGIONS.bits |
456 TypeFlags::HAS_TY_ERR.bits |
457 TypeFlags::HAS_PROJECTION.bits |
458 TypeFlags::HAS_TY_CLOSURE.bits |
459 TypeFlags::HAS_LOCAL_NAMES.bits |
460 TypeFlags::KEEP_IN_LOCAL_TCX.bits,
464 pub struct TyS<'tcx> {
465 pub sty: TypeVariants<'tcx>,
466 pub flags: TypeFlags,
468 // the maximal depth of any bound regions appearing in this type.
472 impl<'tcx> PartialEq for TyS<'tcx> {
474 fn eq(&self, other: &TyS<'tcx>) -> bool {
475 // (self as *const _) == (other as *const _)
476 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
479 impl<'tcx> Eq for TyS<'tcx> {}
481 impl<'tcx> Hash for TyS<'tcx> {
482 fn hash<H: Hasher>(&self, s: &mut H) {
483 (self as *const TyS).hash(s)
487 impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::TyS<'tcx> {
488 fn hash_stable<W: StableHasherResult>(&self,
489 hcx: &mut StableHashingContext<'a, 'tcx>,
490 hasher: &mut StableHasher<W>) {
494 // The other fields just provide fast access to information that is
495 // also contained in `sty`, so no need to hash them.
500 sty.hash_stable(hcx, hasher);
504 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
506 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
507 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
509 /// A wrapper for slices with the additional invariant
510 /// that the slice is interned and no other slice with
511 /// the same contents can exist in the same context.
512 /// This means we can use pointer + length for both
513 /// equality comparisons and hashing.
514 #[derive(Debug, RustcEncodable)]
515 pub struct Slice<T>([T]);
517 impl<T> PartialEq for Slice<T> {
519 fn eq(&self, other: &Slice<T>) -> bool {
520 (&self.0 as *const [T]) == (&other.0 as *const [T])
523 impl<T> Eq for Slice<T> {}
525 impl<T> Hash for Slice<T> {
526 fn hash<H: Hasher>(&self, s: &mut H) {
527 (self.as_ptr(), self.len()).hash(s)
531 impl<T> Deref for Slice<T> {
533 fn deref(&self) -> &[T] {
538 impl<'a, T> IntoIterator for &'a Slice<T> {
540 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
541 fn into_iter(self) -> Self::IntoIter {
546 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
549 pub fn empty<'a>() -> &'a Slice<T> {
551 mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
556 /// Upvars do not get their own node-id. Instead, we use the pair of
557 /// the original var id (that is, the root variable that is referenced
558 /// by the upvar) and the id of the closure expression.
559 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
562 pub closure_expr_id: NodeId,
565 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
566 pub enum BorrowKind {
567 /// Data must be immutable and is aliasable.
570 /// Data must be immutable but not aliasable. This kind of borrow
571 /// cannot currently be expressed by the user and is used only in
572 /// implicit closure bindings. It is needed when the closure
573 /// is borrowing or mutating a mutable referent, e.g.:
575 /// let x: &mut isize = ...;
576 /// let y = || *x += 5;
578 /// If we were to try to translate this closure into a more explicit
579 /// form, we'd encounter an error with the code as written:
581 /// struct Env { x: & &mut isize }
582 /// let x: &mut isize = ...;
583 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
584 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
586 /// This is then illegal because you cannot mutate a `&mut` found
587 /// in an aliasable location. To solve, you'd have to translate with
588 /// an `&mut` borrow:
590 /// struct Env { x: & &mut isize }
591 /// let x: &mut isize = ...;
592 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
593 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
595 /// Now the assignment to `**env.x` is legal, but creating a
596 /// mutable pointer to `x` is not because `x` is not mutable. We
597 /// could fix this by declaring `x` as `let mut x`. This is ok in
598 /// user code, if awkward, but extra weird for closures, since the
599 /// borrow is hidden.
601 /// So we introduce a "unique imm" borrow -- the referent is
602 /// immutable, but not aliasable. This solves the problem. For
603 /// simplicity, we don't give users the way to express this
604 /// borrow, it's just used when translating closures.
607 /// Data is mutable and not aliasable.
611 /// Information describing the capture of an upvar. This is computed
612 /// during `typeck`, specifically by `regionck`.
613 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
614 pub enum UpvarCapture<'tcx> {
615 /// Upvar is captured by value. This is always true when the
616 /// closure is labeled `move`, but can also be true in other cases
617 /// depending on inference.
620 /// Upvar is captured by reference.
621 ByRef(UpvarBorrow<'tcx>),
624 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
625 pub struct UpvarBorrow<'tcx> {
626 /// The kind of borrow: by-ref upvars have access to shared
627 /// immutable borrows, which are not part of the normal language
629 pub kind: BorrowKind,
631 /// Region of the resulting reference.
632 pub region: ty::Region<'tcx>,
635 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
637 #[derive(Copy, Clone)]
638 pub struct ClosureUpvar<'tcx> {
644 #[derive(Clone, Copy, PartialEq)]
645 pub enum IntVarValue {
647 UintType(ast::UintTy),
650 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
651 pub struct TypeParameterDef {
655 pub has_default: bool,
656 pub object_lifetime_default: ObjectLifetimeDefault,
658 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
659 /// on generic parameter `T`, asserts data behind the parameter
660 /// `T` won't be accessed during the parent type's `Drop` impl.
661 pub pure_wrt_drop: bool,
664 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
665 pub struct RegionParameterDef {
669 pub issue_32330: Option<ty::Issue32330>,
671 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
672 /// on generic parameter `'a`, asserts data of lifetime `'a`
673 /// won't be accessed during the parent type's `Drop` impl.
674 pub pure_wrt_drop: bool,
677 impl RegionParameterDef {
678 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
679 ty::EarlyBoundRegion {
686 pub fn to_bound_region(&self) -> ty::BoundRegion {
687 self.to_early_bound_region_data().to_bound_region()
691 impl ty::EarlyBoundRegion {
692 pub fn to_bound_region(&self) -> ty::BoundRegion {
693 ty::BoundRegion::BrNamed(self.def_id, self.name)
697 /// Information about the formal type/lifetime parameters associated
698 /// with an item or method. Analogous to hir::Generics.
699 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
700 pub struct Generics {
701 pub parent: Option<DefId>,
702 pub parent_regions: u32,
703 pub parent_types: u32,
704 pub regions: Vec<RegionParameterDef>,
705 pub types: Vec<TypeParameterDef>,
707 /// Reverse map to each `TypeParameterDef`'s `index` field, from
708 /// `def_id.index` (`def_id.krate` is the same as the item's).
709 pub type_param_to_index: BTreeMap<DefIndex, u32>,
715 pub fn parent_count(&self) -> usize {
716 self.parent_regions as usize + self.parent_types as usize
719 pub fn own_count(&self) -> usize {
720 self.regions.len() + self.types.len()
723 pub fn count(&self) -> usize {
724 self.parent_count() + self.own_count()
727 pub fn region_param(&self, param: &EarlyBoundRegion) -> &RegionParameterDef {
728 assert_eq!(self.parent_count(), 0);
729 &self.regions[param.index as usize - self.has_self as usize]
732 pub fn type_param(&self, param: &ParamTy) -> &TypeParameterDef {
733 assert_eq!(self.parent_count(), 0);
734 &self.types[param.idx as usize - self.has_self as usize - self.regions.len()]
738 /// Bounds on generics.
739 #[derive(Clone, Default)]
740 pub struct GenericPredicates<'tcx> {
741 pub parent: Option<DefId>,
742 pub predicates: Vec<Predicate<'tcx>>,
745 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
746 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
748 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
749 pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
750 -> InstantiatedPredicates<'tcx> {
751 let mut instantiated = InstantiatedPredicates::empty();
752 self.instantiate_into(tcx, &mut instantiated, substs);
755 pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
756 -> InstantiatedPredicates<'tcx> {
757 InstantiatedPredicates {
758 predicates: self.predicates.subst(tcx, substs)
762 fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
763 instantiated: &mut InstantiatedPredicates<'tcx>,
764 substs: &Substs<'tcx>) {
765 if let Some(def_id) = self.parent {
766 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
768 instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
771 pub fn instantiate_identity(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
772 -> InstantiatedPredicates<'tcx> {
773 let mut instantiated = InstantiatedPredicates::empty();
774 self.instantiate_identity_into(tcx, &mut instantiated);
778 fn instantiate_identity_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
779 instantiated: &mut InstantiatedPredicates<'tcx>) {
780 if let Some(def_id) = self.parent {
781 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
783 instantiated.predicates.extend(&self.predicates)
786 pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
787 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
788 -> InstantiatedPredicates<'tcx>
790 assert_eq!(self.parent, None);
791 InstantiatedPredicates {
792 predicates: self.predicates.iter().map(|pred| {
793 pred.subst_supertrait(tcx, poly_trait_ref)
799 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
800 pub enum Predicate<'tcx> {
801 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
802 /// the `Self` type of the trait reference and `A`, `B`, and `C`
803 /// would be the type parameters.
804 Trait(PolyTraitPredicate<'tcx>),
806 /// where `T1 == T2`.
807 Equate(PolyEquatePredicate<'tcx>),
810 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
813 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
815 /// where <T as TraitRef>::Name == X, approximately.
816 /// See `ProjectionPredicate` struct for details.
817 Projection(PolyProjectionPredicate<'tcx>),
820 WellFormed(Ty<'tcx>),
822 /// trait must be object-safe
825 /// No direct syntax. May be thought of as `where T : FnFoo<...>`
826 /// for some substitutions `...` and T being a closure type.
827 /// Satisfied (or refuted) once we know the closure's kind.
828 ClosureKind(DefId, ClosureKind),
831 Subtype(PolySubtypePredicate<'tcx>),
834 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
835 /// Performs a substitution suitable for going from a
836 /// poly-trait-ref to supertraits that must hold if that
837 /// poly-trait-ref holds. This is slightly different from a normal
838 /// substitution in terms of what happens with bound regions. See
839 /// lengthy comment below for details.
840 pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
841 trait_ref: &ty::PolyTraitRef<'tcx>)
842 -> ty::Predicate<'tcx>
844 // The interaction between HRTB and supertraits is not entirely
845 // obvious. Let me walk you (and myself) through an example.
847 // Let's start with an easy case. Consider two traits:
849 // trait Foo<'a> : Bar<'a,'a> { }
850 // trait Bar<'b,'c> { }
852 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
853 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
854 // knew that `Foo<'x>` (for any 'x) then we also know that
855 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
856 // normal substitution.
858 // In terms of why this is sound, the idea is that whenever there
859 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
860 // holds. So if there is an impl of `T:Foo<'a>` that applies to
861 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
864 // Another example to be careful of is this:
866 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
867 // trait Bar1<'b,'c> { }
869 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
870 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
871 // reason is similar to the previous example: any impl of
872 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
873 // basically we would want to collapse the bound lifetimes from
874 // the input (`trait_ref`) and the supertraits.
876 // To achieve this in practice is fairly straightforward. Let's
877 // consider the more complicated scenario:
879 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
880 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
881 // where both `'x` and `'b` would have a DB index of 1.
882 // The substitution from the input trait-ref is therefore going to be
883 // `'a => 'x` (where `'x` has a DB index of 1).
884 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
885 // early-bound parameter and `'b' is a late-bound parameter with a
887 // - If we replace `'a` with `'x` from the input, it too will have
888 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
889 // just as we wanted.
891 // There is only one catch. If we just apply the substitution `'a
892 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
893 // adjust the DB index because we substituting into a binder (it
894 // tries to be so smart...) resulting in `for<'x> for<'b>
895 // Bar1<'x,'b>` (we have no syntax for this, so use your
896 // imagination). Basically the 'x will have DB index of 2 and 'b
897 // will have DB index of 1. Not quite what we want. So we apply
898 // the substitution to the *contents* of the trait reference,
899 // rather than the trait reference itself (put another way, the
900 // substitution code expects equal binding levels in the values
901 // from the substitution and the value being substituted into, and
902 // this trick achieves that).
904 let substs = &trait_ref.0.substs;
906 Predicate::Trait(ty::Binder(ref data)) =>
907 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
908 Predicate::Equate(ty::Binder(ref data)) =>
909 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
910 Predicate::Subtype(ty::Binder(ref data)) =>
911 Predicate::Subtype(ty::Binder(data.subst(tcx, substs))),
912 Predicate::RegionOutlives(ty::Binder(ref data)) =>
913 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
914 Predicate::TypeOutlives(ty::Binder(ref data)) =>
915 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
916 Predicate::Projection(ty::Binder(ref data)) =>
917 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
918 Predicate::WellFormed(data) =>
919 Predicate::WellFormed(data.subst(tcx, substs)),
920 Predicate::ObjectSafe(trait_def_id) =>
921 Predicate::ObjectSafe(trait_def_id),
922 Predicate::ClosureKind(closure_def_id, kind) =>
923 Predicate::ClosureKind(closure_def_id, kind),
928 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
929 pub struct TraitPredicate<'tcx> {
930 pub trait_ref: TraitRef<'tcx>
932 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
934 impl<'tcx> TraitPredicate<'tcx> {
935 pub fn def_id(&self) -> DefId {
936 self.trait_ref.def_id
939 /// Creates the dep-node for selecting/evaluating this trait reference.
940 fn dep_node(&self) -> DepNode<DefId> {
941 // Extact the trait-def and first def-id from inputs. See the
942 // docs for `DepNode::TraitSelect` for more information.
943 let trait_def_id = self.def_id();
946 .flat_map(|t| t.walk())
947 .filter_map(|t| match t.sty {
948 ty::TyAdt(adt_def, _) => Some(adt_def.did),
952 .unwrap_or(trait_def_id);
953 DepNode::TraitSelect {
954 trait_def_id: trait_def_id,
955 input_def_id: input_def_id
959 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
960 self.trait_ref.input_types()
963 pub fn self_ty(&self) -> Ty<'tcx> {
964 self.trait_ref.self_ty()
968 impl<'tcx> PolyTraitPredicate<'tcx> {
969 pub fn def_id(&self) -> DefId {
970 // ok to skip binder since trait def-id does not care about regions
974 pub fn dep_node(&self) -> DepNode<DefId> {
975 // ok to skip binder since depnode does not care about regions
980 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
981 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
982 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
984 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
985 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
986 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
987 pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<ty::Region<'tcx>,
989 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
991 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
992 pub struct SubtypePredicate<'tcx> {
993 pub a_is_expected: bool,
997 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
999 /// This kind of predicate has no *direct* correspondent in the
1000 /// syntax, but it roughly corresponds to the syntactic forms:
1002 /// 1. `T : TraitRef<..., Item=Type>`
1003 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1005 /// In particular, form #1 is "desugared" to the combination of a
1006 /// normal trait predicate (`T : TraitRef<...>`) and one of these
1007 /// predicates. Form #2 is a broader form in that it also permits
1008 /// equality between arbitrary types. Processing an instance of Form
1009 /// #2 eventually yields one of these `ProjectionPredicate`
1010 /// instances to normalize the LHS.
1011 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1012 pub struct ProjectionPredicate<'tcx> {
1013 pub projection_ty: ProjectionTy<'tcx>,
1017 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1019 impl<'tcx> PolyProjectionPredicate<'tcx> {
1020 pub fn item_name(&self) -> Name {
1021 self.0.projection_ty.item_name // safe to skip the binder to access a name
1025 pub trait ToPolyTraitRef<'tcx> {
1026 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1029 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1030 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1031 assert!(!self.has_escaping_regions());
1032 ty::Binder(self.clone())
1036 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1037 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1038 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1042 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
1043 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1044 // Note: unlike with TraitRef::to_poly_trait_ref(),
1045 // self.0.trait_ref is permitted to have escaping regions.
1046 // This is because here `self` has a `Binder` and so does our
1047 // return value, so we are preserving the number of binding
1049 ty::Binder(self.0.projection_ty.trait_ref)
1053 pub trait ToPredicate<'tcx> {
1054 fn to_predicate(&self) -> Predicate<'tcx>;
1057 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1058 fn to_predicate(&self) -> Predicate<'tcx> {
1059 // we're about to add a binder, so let's check that we don't
1060 // accidentally capture anything, or else that might be some
1061 // weird debruijn accounting.
1062 assert!(!self.has_escaping_regions());
1064 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1065 trait_ref: self.clone()
1070 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1071 fn to_predicate(&self) -> Predicate<'tcx> {
1072 ty::Predicate::Trait(self.to_poly_trait_predicate())
1076 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
1077 fn to_predicate(&self) -> Predicate<'tcx> {
1078 Predicate::Equate(self.clone())
1082 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1083 fn to_predicate(&self) -> Predicate<'tcx> {
1084 Predicate::RegionOutlives(self.clone())
1088 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1089 fn to_predicate(&self) -> Predicate<'tcx> {
1090 Predicate::TypeOutlives(self.clone())
1094 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1095 fn to_predicate(&self) -> Predicate<'tcx> {
1096 Predicate::Projection(self.clone())
1100 impl<'tcx> Predicate<'tcx> {
1101 /// Iterates over the types in this predicate. Note that in all
1102 /// cases this is skipping over a binder, so late-bound regions
1103 /// with depth 0 are bound by the predicate.
1104 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1105 let vec: Vec<_> = match *self {
1106 ty::Predicate::Trait(ref data) => {
1107 data.skip_binder().input_types().collect()
1109 ty::Predicate::Equate(ty::Binder(ref data)) => {
1110 vec![data.0, data.1]
1112 ty::Predicate::Subtype(ty::Binder(SubtypePredicate { a, b, a_is_expected: _ })) => {
1115 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1118 ty::Predicate::RegionOutlives(..) => {
1121 ty::Predicate::Projection(ref data) => {
1122 let trait_inputs = data.0.projection_ty.trait_ref.input_types();
1123 trait_inputs.chain(Some(data.0.ty)).collect()
1125 ty::Predicate::WellFormed(data) => {
1128 ty::Predicate::ObjectSafe(_trait_def_id) => {
1131 ty::Predicate::ClosureKind(_closure_def_id, _kind) => {
1136 // The only reason to collect into a vector here is that I was
1137 // too lazy to make the full (somewhat complicated) iterator
1138 // type that would be needed here. But I wanted this fn to
1139 // return an iterator conceptually, rather than a `Vec`, so as
1140 // to be closer to `Ty::walk`.
1144 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1146 Predicate::Trait(ref t) => {
1147 Some(t.to_poly_trait_ref())
1149 Predicate::Projection(..) |
1150 Predicate::Equate(..) |
1151 Predicate::Subtype(..) |
1152 Predicate::RegionOutlives(..) |
1153 Predicate::WellFormed(..) |
1154 Predicate::ObjectSafe(..) |
1155 Predicate::ClosureKind(..) |
1156 Predicate::TypeOutlives(..) => {
1163 /// Represents the bounds declared on a particular set of type
1164 /// parameters. Should eventually be generalized into a flag list of
1165 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
1166 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1167 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1168 /// the `GenericPredicates` are expressed in terms of the bound type
1169 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1170 /// represented a set of bounds for some particular instantiation,
1171 /// meaning that the generic parameters have been substituted with
1176 /// struct Foo<T,U:Bar<T>> { ... }
1178 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1179 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1180 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1181 /// [usize:Bar<isize>]]`.
1183 pub struct InstantiatedPredicates<'tcx> {
1184 pub predicates: Vec<Predicate<'tcx>>,
1187 impl<'tcx> InstantiatedPredicates<'tcx> {
1188 pub fn empty() -> InstantiatedPredicates<'tcx> {
1189 InstantiatedPredicates { predicates: vec![] }
1192 pub fn is_empty(&self) -> bool {
1193 self.predicates.is_empty()
1197 /// When type checking, we use the `ParamEnv` to track
1198 /// details about the set of where-clauses that are in scope at this
1199 /// particular point.
1200 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1201 pub struct ParamEnv<'tcx> {
1202 /// Obligations that the caller must satisfy. This is basically
1203 /// the set of bounds on the in-scope type parameters, translated
1204 /// into Obligations, and elaborated and normalized.
1205 pub caller_bounds: &'tcx Slice<ty::Predicate<'tcx>>,
1208 impl<'tcx> ParamEnv<'tcx> {
1209 /// Creates a suitable environment in which to perform trait
1210 /// queries on the given value. This will either be `self` *or*
1211 /// the empty environment, depending on whether `value` references
1212 /// type parameters that are in scope. (If it doesn't, then any
1213 /// judgements should be completely independent of the context,
1214 /// and hence we can safely use the empty environment so as to
1215 /// enable more sharing across functions.)
1217 /// NB: This is a mildly dubious thing to do, in that a function
1218 /// (or other environment) might have wacky where-clauses like
1219 /// `where Box<u32>: Copy`, which are clearly never
1220 /// satisfiable. The code will at present ignore these,
1221 /// effectively, when type-checking the body of said
1222 /// function. This preserves existing behavior in any
1223 /// case. --nmatsakis
1224 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1225 assert!(!value.needs_infer());
1226 if value.has_param_types() || value.has_self_ty() {
1233 param_env: ParamEnv::empty(),
1240 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1241 pub struct ParamEnvAnd<'tcx, T> {
1242 pub param_env: ParamEnv<'tcx>,
1246 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1247 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1248 (self.param_env, self.value)
1252 #[derive(Copy, Clone, Debug)]
1253 pub struct Destructor {
1254 /// The def-id of the destructor method
1259 flags AdtFlags: u32 {
1260 const NO_ADT_FLAGS = 0,
1261 const IS_ENUM = 1 << 0,
1262 const IS_PHANTOM_DATA = 1 << 1,
1263 const IS_FUNDAMENTAL = 1 << 2,
1264 const IS_UNION = 1 << 3,
1265 const IS_BOX = 1 << 4,
1270 pub struct VariantDef {
1271 /// The variant's DefId. If this is a tuple-like struct,
1272 /// this is the DefId of the struct's ctor.
1274 pub name: Name, // struct's name if this is a struct
1275 pub discr: VariantDiscr,
1276 pub fields: Vec<FieldDef>,
1277 pub ctor_kind: CtorKind,
1280 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1281 pub enum VariantDiscr {
1282 /// Explicit value for this variant, i.e. `X = 123`.
1283 /// The `DefId` corresponds to the embedded constant.
1286 /// The previous variant's discriminant plus one.
1287 /// For efficiency reasons, the distance from the
1288 /// last `Explicit` discriminant is being stored,
1289 /// or `0` for the first variant, if it has none.
1294 pub struct FieldDef {
1297 pub vis: Visibility,
1300 /// The definition of an abstract data type - a struct or enum.
1302 /// These are all interned (by intern_adt_def) into the adt_defs
1306 pub variants: Vec<VariantDef>,
1308 pub repr: ReprOptions,
1311 impl PartialEq for AdtDef {
1312 // AdtDef are always interned and this is part of TyS equality
1314 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1317 impl Eq for AdtDef {}
1319 impl Hash for AdtDef {
1321 fn hash<H: Hasher>(&self, s: &mut H) {
1322 (self as *const AdtDef).hash(s)
1326 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1327 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1332 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1335 impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for AdtDef {
1336 fn hash_stable<W: StableHasherResult>(&self,
1337 hcx: &mut StableHashingContext<'a, 'tcx>,
1338 hasher: &mut StableHasher<W>) {
1346 did.hash_stable(hcx, hasher);
1347 variants.hash_stable(hcx, hasher);
1348 flags.hash_stable(hcx, hasher);
1349 repr.hash_stable(hcx, hasher);
1353 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1354 pub enum AdtKind { Struct, Union, Enum }
1357 #[derive(RustcEncodable, RustcDecodable, Default)]
1358 flags ReprFlags: u8 {
1359 const IS_C = 1 << 0,
1360 const IS_PACKED = 1 << 1,
1361 const IS_SIMD = 1 << 2,
1362 // Internal only for now. If true, don't reorder fields.
1363 const IS_LINEAR = 1 << 3,
1365 // Any of these flags being set prevent field reordering optimisation.
1366 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1367 ReprFlags::IS_PACKED.bits |
1368 ReprFlags::IS_SIMD.bits |
1369 ReprFlags::IS_LINEAR.bits,
1373 impl_stable_hash_for!(struct ReprFlags {
1379 /// Represents the repr options provided by the user,
1380 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1381 pub struct ReprOptions {
1382 pub int: Option<attr::IntType>,
1384 pub flags: ReprFlags,
1387 impl_stable_hash_for!(struct ReprOptions {
1394 pub fn new(tcx: TyCtxt, did: DefId) -> ReprOptions {
1395 let mut flags = ReprFlags::empty();
1396 let mut size = None;
1397 let mut max_align = 0;
1398 for attr in tcx.get_attrs(did).iter() {
1399 for r in attr::find_repr_attrs(tcx.sess.diagnostic(), attr) {
1400 flags.insert(match r {
1401 attr::ReprExtern => ReprFlags::IS_C,
1402 attr::ReprPacked => ReprFlags::IS_PACKED,
1403 attr::ReprSimd => ReprFlags::IS_SIMD,
1404 attr::ReprInt(i) => {
1408 attr::ReprAlign(align) => {
1409 max_align = cmp::max(align, max_align);
1416 // FIXME(eddyb) This is deprecated and should be removed.
1417 if tcx.has_attr(did, "simd") {
1418 flags.insert(ReprFlags::IS_SIMD);
1421 // This is here instead of layout because the choice must make it into metadata.
1422 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.item_path_str(did))) {
1423 flags.insert(ReprFlags::IS_LINEAR);
1425 ReprOptions { int: size, align: max_align, flags: flags }
1429 pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
1431 pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
1433 pub fn packed(&self) -> bool { self.flags.contains(ReprFlags::IS_PACKED) }
1435 pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
1437 pub fn discr_type(&self) -> attr::IntType {
1438 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Is))
1441 /// Returns true if this `#[repr()]` should inhabit "smart enum
1442 /// layout" optimizations, such as representing `Foo<&T>` as a
1444 pub fn inhibit_enum_layout_opt(&self) -> bool {
1445 self.c() || self.int.is_some()
1449 impl<'a, 'gcx, 'tcx> AdtDef {
1453 variants: Vec<VariantDef>,
1454 repr: ReprOptions) -> Self {
1455 let mut flags = AdtFlags::NO_ADT_FLAGS;
1456 let attrs = tcx.get_attrs(did);
1457 if attr::contains_name(&attrs, "fundamental") {
1458 flags = flags | AdtFlags::IS_FUNDAMENTAL;
1460 if Some(did) == tcx.lang_items.phantom_data() {
1461 flags = flags | AdtFlags::IS_PHANTOM_DATA;
1463 if Some(did) == tcx.lang_items.owned_box() {
1464 flags = flags | AdtFlags::IS_BOX;
1467 AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1468 AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1469 AdtKind::Struct => {}
1480 pub fn is_struct(&self) -> bool {
1481 !self.is_union() && !self.is_enum()
1485 pub fn is_union(&self) -> bool {
1486 self.flags.intersects(AdtFlags::IS_UNION)
1490 pub fn is_enum(&self) -> bool {
1491 self.flags.intersects(AdtFlags::IS_ENUM)
1494 /// Returns the kind of the ADT - Struct or Enum.
1496 pub fn adt_kind(&self) -> AdtKind {
1499 } else if self.is_union() {
1506 pub fn descr(&self) -> &'static str {
1507 match self.adt_kind() {
1508 AdtKind::Struct => "struct",
1509 AdtKind::Union => "union",
1510 AdtKind::Enum => "enum",
1514 pub fn variant_descr(&self) -> &'static str {
1515 match self.adt_kind() {
1516 AdtKind::Struct => "struct",
1517 AdtKind::Union => "union",
1518 AdtKind::Enum => "variant",
1522 /// Returns whether this type is #[fundamental] for the purposes
1523 /// of coherence checking.
1525 pub fn is_fundamental(&self) -> bool {
1526 self.flags.intersects(AdtFlags::IS_FUNDAMENTAL)
1529 /// Returns true if this is PhantomData<T>.
1531 pub fn is_phantom_data(&self) -> bool {
1532 self.flags.intersects(AdtFlags::IS_PHANTOM_DATA)
1535 /// Returns true if this is Box<T>.
1537 pub fn is_box(&self) -> bool {
1538 self.flags.intersects(AdtFlags::IS_BOX)
1541 /// Returns whether this type has a destructor.
1542 pub fn has_dtor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1543 self.destructor(tcx).is_some()
1546 /// Asserts this is a struct and returns the struct's unique
1548 pub fn struct_variant(&self) -> &VariantDef {
1549 assert!(!self.is_enum());
1554 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1555 tcx.predicates_of(self.did)
1558 /// Returns an iterator over all fields contained
1561 pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1562 self.variants.iter().flat_map(|v| v.fields.iter())
1566 pub fn is_univariant(&self) -> bool {
1567 self.variants.len() == 1
1570 pub fn is_payloadfree(&self) -> bool {
1571 !self.variants.is_empty() &&
1572 self.variants.iter().all(|v| v.fields.is_empty())
1575 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1578 .find(|v| v.did == vid)
1579 .expect("variant_with_id: unknown variant")
1582 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1585 .position(|v| v.did == vid)
1586 .expect("variant_index_with_id: unknown variant")
1589 pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1591 Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1592 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1593 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.struct_variant(),
1594 _ => bug!("unexpected def {:?} in variant_of_def", def)
1599 pub fn discriminants(&'a self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
1600 -> impl Iterator<Item=ConstInt> + 'a {
1601 let repr_type = self.repr.discr_type();
1602 let initial = repr_type.initial_discriminant(tcx.global_tcx());
1603 let mut prev_discr = None::<ConstInt>;
1604 self.variants.iter().map(move |v| {
1605 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr());
1606 if let VariantDiscr::Explicit(expr_did) = v.discr {
1607 let substs = Substs::empty();
1608 match tcx.const_eval((expr_did, substs)) {
1609 Ok(ConstVal::Integral(v)) => {
1613 if !expr_did.is_local() {
1614 span_bug!(tcx.def_span(expr_did),
1615 "variant discriminant evaluation succeeded \
1616 in its crate but failed locally: {:?}", err);
1621 prev_discr = Some(discr);
1627 /// Compute the discriminant value used by a specific variant.
1628 /// Unlike `discriminants`, this is (amortized) constant-time,
1629 /// only doing at most one query for evaluating an explicit
1630 /// discriminant (the last one before the requested variant),
1631 /// assuming there are no constant-evaluation errors there.
1632 pub fn discriminant_for_variant(&self,
1633 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1634 variant_index: usize)
1636 let repr_type = self.repr.discr_type();
1637 let mut explicit_value = repr_type.initial_discriminant(tcx.global_tcx());
1638 let mut explicit_index = variant_index;
1640 match self.variants[explicit_index].discr {
1641 ty::VariantDiscr::Relative(0) => break,
1642 ty::VariantDiscr::Relative(distance) => {
1643 explicit_index -= distance;
1645 ty::VariantDiscr::Explicit(expr_did) => {
1646 let substs = Substs::empty();
1647 match tcx.const_eval((expr_did, substs)) {
1648 Ok(ConstVal::Integral(v)) => {
1653 if !expr_did.is_local() {
1654 span_bug!(tcx.def_span(expr_did),
1655 "variant discriminant evaluation succeeded \
1656 in its crate but failed locally: {:?}", err);
1658 if explicit_index == 0 {
1661 explicit_index -= 1;
1667 let discr = explicit_value.to_u128_unchecked()
1668 .wrapping_add((variant_index - explicit_index) as u128);
1670 attr::UnsignedInt(ty) => {
1671 ConstInt::new_unsigned_truncating(discr, ty,
1672 tcx.sess.target.uint_type)
1674 attr::SignedInt(ty) => {
1675 ConstInt::new_signed_truncating(discr as i128, ty,
1676 tcx.sess.target.int_type)
1681 pub fn destructor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Destructor> {
1682 tcx.adt_destructor(self.did)
1685 /// Returns a list of types such that `Self: Sized` if and only
1686 /// if that type is Sized, or `TyErr` if this type is recursive.
1688 /// Oddly enough, checking that the sized-constraint is Sized is
1689 /// actually more expressive than checking all members:
1690 /// the Sized trait is inductive, so an associated type that references
1691 /// Self would prevent its containing ADT from being Sized.
1693 /// Due to normalization being eager, this applies even if
1694 /// the associated type is behind a pointer, e.g. issue #31299.
1695 pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] {
1696 match queries::adt_sized_constraint::try_get(tcx, DUMMY_SP, self.did) {
1699 debug!("adt_sized_constraint: {:?} is recursive", self);
1700 // This should be reported as an error by `check_representable`.
1702 // Consider the type as Sized in the meanwhile to avoid
1704 tcx.intern_type_list(&[tcx.types.err])
1709 fn sized_constraint_for_ty(&self,
1710 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1713 let result = match ty.sty {
1714 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
1715 TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
1716 TyArray(..) | TyClosure(..) | TyNever => {
1720 TyStr | TyDynamic(..) | TySlice(_) | TyError => {
1721 // these are never sized - return the target type
1725 TyTuple(ref tys, _) => {
1728 Some(ty) => self.sized_constraint_for_ty(tcx, ty)
1732 TyAdt(adt, substs) => {
1734 let adt_tys = adt.sized_constraint(tcx);
1735 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
1738 .map(|ty| ty.subst(tcx, substs))
1739 .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
1743 TyProjection(..) | TyAnon(..) => {
1744 // must calculate explicitly.
1745 // FIXME: consider special-casing always-Sized projections
1750 // perf hack: if there is a `T: Sized` bound, then
1751 // we know that `T` is Sized and do not need to check
1754 let sized_trait = match tcx.lang_items.sized_trait() {
1756 _ => return vec![ty]
1758 let sized_predicate = Binder(TraitRef {
1759 def_id: sized_trait,
1760 substs: tcx.mk_substs_trait(ty, &[])
1762 let predicates = tcx.predicates_of(self.did).predicates;
1763 if predicates.into_iter().any(|p| p == sized_predicate) {
1771 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
1775 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
1780 impl<'a, 'gcx, 'tcx> VariantDef {
1782 pub fn find_field_named(&self, name: ast::Name) -> Option<&FieldDef> {
1783 self.index_of_field_named(name).map(|index| &self.fields[index])
1786 pub fn index_of_field_named(&self, name: ast::Name) -> Option<usize> {
1787 if let Some(index) = self.fields.iter().position(|f| f.name == name) {
1790 let mut ident = name.to_ident();
1791 while ident.ctxt != SyntaxContext::empty() {
1792 ident.ctxt.remove_mark();
1793 if let Some(field) = self.fields.iter().position(|f| f.name.to_ident() == ident) {
1801 pub fn field_named(&self, name: ast::Name) -> &FieldDef {
1802 self.find_field_named(name).unwrap()
1806 impl<'a, 'gcx, 'tcx> FieldDef {
1807 pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1808 tcx.type_of(self.did).subst(tcx, subst)
1812 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1813 pub enum ClosureKind {
1814 // Warning: Ordering is significant here! The ordering is chosen
1815 // because the trait Fn is a subtrait of FnMut and so in turn, and
1816 // hence we order it so that Fn < FnMut < FnOnce.
1822 impl<'a, 'tcx> ClosureKind {
1823 pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
1825 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
1826 ClosureKind::FnMut => {
1827 tcx.require_lang_item(FnMutTraitLangItem)
1829 ClosureKind::FnOnce => {
1830 tcx.require_lang_item(FnOnceTraitLangItem)
1835 /// True if this a type that impls this closure kind
1836 /// must also implement `other`.
1837 pub fn extends(self, other: ty::ClosureKind) -> bool {
1838 match (self, other) {
1839 (ClosureKind::Fn, ClosureKind::Fn) => true,
1840 (ClosureKind::Fn, ClosureKind::FnMut) => true,
1841 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
1842 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
1843 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
1844 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
1850 impl<'tcx> TyS<'tcx> {
1851 /// Iterator that walks `self` and any types reachable from
1852 /// `self`, in depth-first order. Note that just walks the types
1853 /// that appear in `self`, it does not descend into the fields of
1854 /// structs or variants. For example:
1857 /// isize => { isize }
1858 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
1859 /// [isize] => { [isize], isize }
1861 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
1862 TypeWalker::new(self)
1865 /// Iterator that walks the immediate children of `self`. Hence
1866 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
1867 /// (but not `i32`, like `walk`).
1868 pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
1869 walk::walk_shallow(self)
1872 /// Walks `ty` and any types appearing within `ty`, invoking the
1873 /// callback `f` on each type. If the callback returns false, then the
1874 /// children of the current type are ignored.
1876 /// Note: prefer `ty.walk()` where possible.
1877 pub fn maybe_walk<F>(&'tcx self, mut f: F)
1878 where F : FnMut(Ty<'tcx>) -> bool
1880 let mut walker = self.walk();
1881 while let Some(ty) = walker.next() {
1883 walker.skip_current_subtree();
1889 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1890 pub enum LvaluePreference {
1895 impl LvaluePreference {
1896 pub fn from_mutbl(m: hir::Mutability) -> Self {
1898 hir::MutMutable => PreferMutLvalue,
1899 hir::MutImmutable => NoPreference,
1905 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
1907 hir::MutMutable => MutBorrow,
1908 hir::MutImmutable => ImmBorrow,
1912 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
1913 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
1914 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
1916 pub fn to_mutbl_lossy(self) -> hir::Mutability {
1918 MutBorrow => hir::MutMutable,
1919 ImmBorrow => hir::MutImmutable,
1921 // We have no type corresponding to a unique imm borrow, so
1922 // use `&mut`. It gives all the capabilities of an `&uniq`
1923 // and hence is a safe "over approximation".
1924 UniqueImmBorrow => hir::MutMutable,
1928 pub fn to_user_str(&self) -> &'static str {
1930 MutBorrow => "mutable",
1931 ImmBorrow => "immutable",
1932 UniqueImmBorrow => "uniquely immutable",
1937 #[derive(Debug, Clone)]
1938 pub enum Attributes<'gcx> {
1939 Owned(Rc<[ast::Attribute]>),
1940 Borrowed(&'gcx [ast::Attribute])
1943 impl<'gcx> ::std::ops::Deref for Attributes<'gcx> {
1944 type Target = [ast::Attribute];
1946 fn deref(&self) -> &[ast::Attribute] {
1948 &Attributes::Owned(ref data) => &data,
1949 &Attributes::Borrowed(data) => data
1954 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1955 pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
1956 self.typeck_tables_of(self.hir.body_owner_def_id(body))
1959 /// Returns an iterator of the def-ids for all body-owners in this
1960 /// crate. If you would prefer to iterate over the bodies
1961 /// themselves, you can do `self.hir.krate().body_ids.iter()`.
1962 pub fn body_owners(self) -> impl Iterator<Item = DefId> + 'a {
1966 .map(move |&body_id| self.hir.body_owner_def_id(body_id))
1969 pub fn expr_span(self, id: NodeId) -> Span {
1970 match self.hir.find(id) {
1971 Some(hir_map::NodeExpr(e)) => {
1975 bug!("Node id {} is not an expr: {:?}", id, f);
1978 bug!("Node id {} is not present in the node map", id);
1983 pub fn local_var_name_str(self, id: NodeId) -> InternedString {
1984 match self.hir.find(id) {
1985 Some(hir_map::NodeLocal(pat)) => {
1987 hir::PatKind::Binding(_, _, ref path1, _) => path1.node.as_str(),
1989 bug!("Variable id {} maps to {:?}, not local", id, pat);
1993 r => bug!("Variable id {} maps to {:?}, not local", id, r),
1997 pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
1999 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
2001 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
2006 hir::ExprType(ref e, _) => {
2007 self.expr_is_lval(e)
2010 hir::ExprUnary(hir::UnDeref, _) |
2011 hir::ExprField(..) |
2012 hir::ExprTupField(..) |
2013 hir::ExprIndex(..) => {
2017 // Partially qualified paths in expressions can only legally
2018 // refer to associated items which are always rvalues.
2019 hir::ExprPath(hir::QPath::TypeRelative(..)) |
2022 hir::ExprMethodCall(..) |
2023 hir::ExprStruct(..) |
2026 hir::ExprMatch(..) |
2027 hir::ExprClosure(..) |
2028 hir::ExprBlock(..) |
2029 hir::ExprRepeat(..) |
2030 hir::ExprArray(..) |
2031 hir::ExprBreak(..) |
2032 hir::ExprAgain(..) |
2034 hir::ExprWhile(..) |
2036 hir::ExprAssign(..) |
2037 hir::ExprInlineAsm(..) |
2038 hir::ExprAssignOp(..) |
2040 hir::ExprUnary(..) |
2042 hir::ExprAddrOf(..) |
2043 hir::ExprBinary(..) |
2044 hir::ExprCast(..) => {
2050 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2051 self.associated_items(id)
2052 .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2056 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2057 self.associated_items(did).any(|item| {
2058 item.relevant_for_never()
2062 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssociatedItem> {
2063 let is_associated_item = if let Some(node_id) = self.hir.as_local_node_id(def_id) {
2064 match self.hir.get(node_id) {
2065 hir_map::NodeTraitItem(_) | hir_map::NodeImplItem(_) => true,
2069 match self.describe_def(def_id).expect("no def for def-id") {
2070 Def::AssociatedConst(_) | Def::Method(_) | Def::AssociatedTy(_) => true,
2075 if is_associated_item {
2076 Some(self.associated_item(def_id))
2082 fn associated_item_from_trait_item_ref(self,
2083 parent_def_id: DefId,
2084 parent_vis: &hir::Visibility,
2085 trait_item_ref: &hir::TraitItemRef)
2087 let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2088 let (kind, has_self) = match trait_item_ref.kind {
2089 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2090 hir::AssociatedItemKind::Method { has_self } => {
2091 (ty::AssociatedKind::Method, has_self)
2093 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2097 name: trait_item_ref.name,
2099 // Visibility of trait items is inherited from their traits.
2100 vis: Visibility::from_hir(parent_vis, trait_item_ref.id.node_id, self),
2101 defaultness: trait_item_ref.defaultness,
2103 container: TraitContainer(parent_def_id),
2104 method_has_self_argument: has_self
2108 fn associated_item_from_impl_item_ref(self,
2109 parent_def_id: DefId,
2110 impl_item_ref: &hir::ImplItemRef)
2112 let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2113 let (kind, has_self) = match impl_item_ref.kind {
2114 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2115 hir::AssociatedItemKind::Method { has_self } => {
2116 (ty::AssociatedKind::Method, has_self)
2118 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2121 ty::AssociatedItem {
2122 name: impl_item_ref.name,
2124 // Visibility of trait impl items doesn't matter.
2125 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.node_id, self),
2126 defaultness: impl_item_ref.defaultness,
2128 container: ImplContainer(parent_def_id),
2129 method_has_self_argument: has_self
2133 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2134 pub fn associated_items(self, def_id: DefId)
2135 -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2136 let def_ids = self.associated_item_def_ids(def_id);
2137 (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2140 /// Returns true if the impls are the same polarity and are implementing
2141 /// a trait which contains no items
2142 pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId) -> bool {
2143 if !self.sess.features.borrow().overlapping_marker_traits {
2146 let trait1_is_empty = self.impl_trait_ref(def_id1)
2147 .map_or(false, |trait_ref| {
2148 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2150 let trait2_is_empty = self.impl_trait_ref(def_id2)
2151 .map_or(false, |trait_ref| {
2152 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2154 self.impl_polarity(def_id1) == self.impl_polarity(def_id2)
2159 // Returns `ty::VariantDef` if `def` refers to a struct,
2160 // or variant or their constructors, panics otherwise.
2161 pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2163 Def::Variant(did) | Def::VariantCtor(did, ..) => {
2164 let enum_did = self.parent_def_id(did).unwrap();
2165 self.adt_def(enum_did).variant_with_id(did)
2167 Def::Struct(did) | Def::Union(did) => {
2168 self.adt_def(did).struct_variant()
2170 Def::StructCtor(ctor_did, ..) => {
2171 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2172 self.adt_def(did).struct_variant()
2174 _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2178 pub fn def_key(self, id: DefId) -> hir_map::DefKey {
2180 self.hir.def_key(id)
2182 self.sess.cstore.def_key(id)
2186 /// Convert a `DefId` into its fully expanded `DefPath` (every
2187 /// `DefId` is really just an interned def-path).
2189 /// Note that if `id` is not local to this crate, the result will
2190 /// be a non-local `DefPath`.
2191 pub fn def_path(self, id: DefId) -> hir_map::DefPath {
2193 self.hir.def_path(id)
2195 self.sess.cstore.def_path(id)
2200 pub fn def_path_hash(self, def_id: DefId) -> ich::Fingerprint {
2201 if def_id.is_local() {
2202 self.hir.definitions().def_path_hash(def_id.index)
2204 self.sess.cstore.def_path_hash(def_id)
2208 pub fn item_name(self, id: DefId) -> ast::Name {
2209 if let Some(id) = self.hir.as_local_node_id(id) {
2211 } else if id.index == CRATE_DEF_INDEX {
2212 self.sess.cstore.original_crate_name(id.krate)
2214 let def_key = self.sess.cstore.def_key(id);
2215 // The name of a StructCtor is that of its struct parent.
2216 if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2217 self.item_name(DefId {
2219 index: def_key.parent.unwrap()
2222 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2223 bug!("item_name: no name for {:?}", self.def_path(id));
2229 /// Return the possibly-auto-generated MIR of a (DefId, Subst) pair.
2230 pub fn instance_mir(self, instance: ty::InstanceDef<'gcx>)
2234 ty::InstanceDef::Item(did) => {
2235 self.optimized_mir(did)
2237 ty::InstanceDef::Intrinsic(..) |
2238 ty::InstanceDef::FnPtrShim(..) |
2239 ty::InstanceDef::Virtual(..) |
2240 ty::InstanceDef::ClosureOnceShim { .. } |
2241 ty::InstanceDef::DropGlue(..) => {
2242 self.mir_shims(instance)
2247 /// Given the DefId of an item, returns its MIR, borrowed immutably.
2248 /// Returns None if there is no MIR for the DefId
2249 pub fn maybe_optimized_mir(self, did: DefId) -> Option<&'gcx Mir<'gcx>> {
2250 if self.is_mir_available(did) {
2251 Some(self.optimized_mir(did))
2257 /// Get the attributes of a definition.
2258 pub fn get_attrs(self, did: DefId) -> Attributes<'gcx> {
2259 if let Some(id) = self.hir.as_local_node_id(did) {
2260 Attributes::Borrowed(self.hir.attrs(id))
2262 Attributes::Owned(self.item_attrs(did))
2266 /// Determine whether an item is annotated with an attribute
2267 pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2268 self.get_attrs(did).iter().any(|item| item.check_name(attr))
2271 pub fn trait_has_default_impl(self, trait_def_id: DefId) -> bool {
2272 self.trait_def(trait_def_id).has_default_impl
2275 /// Given the def_id of an impl, return the def_id of the trait it implements.
2276 /// If it implements no trait, return `None`.
2277 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2278 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2281 /// If the given def ID describes a method belonging to an impl, return the
2282 /// ID of the impl that the method belongs to. Otherwise, return `None`.
2283 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2284 let item = if def_id.krate != LOCAL_CRATE {
2285 if let Some(Def::Method(_)) = self.describe_def(def_id) {
2286 Some(self.associated_item(def_id))
2291 self.opt_associated_item(def_id)
2295 Some(trait_item) => {
2296 match trait_item.container {
2297 TraitContainer(_) => None,
2298 ImplContainer(def_id) => Some(def_id),
2305 pub fn node_scope_region(self, id: NodeId) -> Region<'tcx> {
2306 self.mk_region(ty::ReScope(CodeExtent::Misc(id)))
2309 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2310 /// with the name of the crate containing the impl.
2311 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2312 if impl_did.is_local() {
2313 let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2314 Ok(self.hir.span(node_id))
2316 Err(self.sess.cstore.crate_name(impl_did.krate))
2320 pub fn adjust(self, name: Name, scope: DefId, block: NodeId) -> (Ident, DefId) {
2321 self.adjust_ident(name.to_ident(), scope, block)
2324 pub fn adjust_ident(self, mut ident: Ident, scope: DefId, block: NodeId) -> (Ident, DefId) {
2325 let expansion = match scope.krate {
2326 LOCAL_CRATE => self.hir.definitions().expansion(scope.index),
2329 let scope = match ident.ctxt.adjust(expansion) {
2330 Some(macro_def) => self.hir.definitions().macro_def_scope(macro_def),
2331 None => self.hir.get_module_parent(block),
2337 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2338 pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2339 F: FnOnce(&[hir::Freevar]) -> T,
2341 match self.freevars.borrow().get(&fid) {
2343 Some(d) => f(&d[..])
2348 fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
2351 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2352 let parent_id = tcx.hir.get_parent(id);
2353 let parent_def_id = tcx.hir.local_def_id(parent_id);
2354 let parent_item = tcx.hir.expect_item(parent_id);
2355 match parent_item.node {
2356 hir::ItemImpl(.., ref impl_item_refs) => {
2357 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.node_id == id) {
2358 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
2360 debug_assert_eq!(assoc_item.def_id, def_id);
2365 hir::ItemTrait(.., ref trait_item_refs) => {
2366 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.node_id == id) {
2367 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
2370 debug_assert_eq!(assoc_item.def_id, def_id);
2378 span_bug!(parent_item.span,
2379 "unexpected parent of trait or impl item or item not found: {:?}",
2383 /// Calculates the Sized-constraint.
2385 /// In fact, there are only a few options for the types in the constraint:
2386 /// - an obviously-unsized type
2387 /// - a type parameter or projection whose Sizedness can't be known
2388 /// - a tuple of type parameters or projections, if there are multiple
2390 /// - a TyError, if a type contained itself. The representability
2391 /// check should catch this case.
2392 fn adt_sized_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2394 -> &'tcx [Ty<'tcx>] {
2395 let def = tcx.adt_def(def_id);
2397 let result = tcx.intern_type_list(&def.variants.iter().flat_map(|v| {
2400 def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
2401 }).collect::<Vec<_>>());
2403 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
2408 /// Calculates the dtorck constraint for a type.
2409 fn adt_dtorck_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2411 -> DtorckConstraint<'tcx> {
2412 let def = tcx.adt_def(def_id);
2413 let span = tcx.def_span(def_id);
2414 debug!("dtorck_constraint: {:?}", def);
2416 if def.is_phantom_data() {
2417 let result = DtorckConstraint {
2420 tcx.mk_param_from_def(&tcx.generics_of(def_id).types[0])
2423 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2427 let mut result = def.all_fields()
2428 .map(|field| tcx.type_of(field.did))
2429 .map(|fty| tcx.dtorck_constraint_for_ty(span, fty, 0, fty))
2430 .collect::<Result<DtorckConstraint, ErrorReported>>()
2431 .unwrap_or(DtorckConstraint::empty());
2432 result.outlives.extend(tcx.destructor_constraints(def));
2435 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2440 fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2443 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2444 let item = tcx.hir.expect_item(id);
2445 let vec: Vec<_> = match item.node {
2446 hir::ItemTrait(.., ref trait_item_refs) => {
2447 trait_item_refs.iter()
2448 .map(|trait_item_ref| trait_item_ref.id)
2449 .map(|id| tcx.hir.local_def_id(id.node_id))
2452 hir::ItemImpl(.., ref impl_item_refs) => {
2453 impl_item_refs.iter()
2454 .map(|impl_item_ref| impl_item_ref.id)
2455 .map(|id| tcx.hir.local_def_id(id.node_id))
2458 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2463 fn def_span<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Span {
2464 tcx.hir.span_if_local(def_id).unwrap()
2467 /// If the given def ID describes an item belonging to a trait,
2468 /// return the ID of the trait that the trait item belongs to.
2469 /// Otherwise, return `None`.
2470 fn trait_of_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
2471 tcx.opt_associated_item(def_id)
2472 .and_then(|associated_item| {
2473 match associated_item.container {
2474 TraitContainer(def_id) => Some(def_id),
2475 ImplContainer(_) => None
2480 /// See `ParamEnv` struct def'n for details.
2481 fn param_env<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2484 // Compute the bounds on Self and the type parameters.
2486 let bounds = tcx.predicates_of(def_id).instantiate_identity(tcx);
2487 let predicates = bounds.predicates;
2489 // Finally, we have to normalize the bounds in the environment, in
2490 // case they contain any associated type projections. This process
2491 // can yield errors if the put in illegal associated types, like
2492 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2493 // report these errors right here; this doesn't actually feel
2494 // right to me, because constructing the environment feels like a
2495 // kind of a "idempotent" action, but I'm not sure where would be
2496 // a better place. In practice, we construct environments for
2497 // every fn once during type checking, and we'll abort if there
2498 // are any errors at that point, so after type checking you can be
2499 // sure that this will succeed without errors anyway.
2501 let unnormalized_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates));
2503 let body_id = tcx.hir.as_local_node_id(def_id).map_or(DUMMY_NODE_ID, |id| {
2504 tcx.hir.maybe_body_owned_by(id).map_or(id, |body| body.node_id)
2506 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
2507 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
2510 pub fn provide(providers: &mut ty::maps::Providers) {
2511 util::provide(providers);
2512 *providers = ty::maps::Providers {
2514 associated_item_def_ids,
2515 adt_sized_constraint,
2516 adt_dtorck_constraint,
2520 trait_impls_of: trait_def::trait_impls_of_provider,
2521 relevant_trait_impls_for: trait_def::relevant_trait_impls_provider,
2526 pub fn provide_extern(providers: &mut ty::maps::Providers) {
2527 *providers = ty::maps::Providers {
2528 adt_sized_constraint,
2529 adt_dtorck_constraint,
2530 trait_impls_of: trait_def::trait_impls_of_provider,
2531 relevant_trait_impls_for: trait_def::relevant_trait_impls_provider,
2538 /// A map for the local crate mapping each type to a vector of its
2539 /// inherent impls. This is not meant to be used outside of coherence;
2540 /// rather, you should request the vector for a specific type via
2541 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2542 /// (constructing this map requires touching the entire crate).
2543 #[derive(Clone, Debug)]
2544 pub struct CrateInherentImpls {
2545 pub inherent_impls: DefIdMap<Rc<Vec<DefId>>>,
2548 /// A set of constraints that need to be satisfied in order for
2549 /// a type to be valid for destruction.
2550 #[derive(Clone, Debug)]
2551 pub struct DtorckConstraint<'tcx> {
2552 /// Types that are required to be alive in order for this
2553 /// type to be valid for destruction.
2554 pub outlives: Vec<ty::subst::Kind<'tcx>>,
2555 /// Types that could not be resolved: projections and params.
2556 pub dtorck_types: Vec<Ty<'tcx>>,
2559 impl<'tcx> FromIterator<DtorckConstraint<'tcx>> for DtorckConstraint<'tcx>
2561 fn from_iter<I: IntoIterator<Item=DtorckConstraint<'tcx>>>(iter: I) -> Self {
2562 let mut result = Self::empty();
2564 for constraint in iter {
2565 result.outlives.extend(constraint.outlives);
2566 result.dtorck_types.extend(constraint.dtorck_types);
2574 impl<'tcx> DtorckConstraint<'tcx> {
2575 fn empty() -> DtorckConstraint<'tcx> {
2578 dtorck_types: vec![]
2582 fn dedup<'a>(&mut self) {
2583 let mut outlives = FxHashSet();
2584 let mut dtorck_types = FxHashSet();
2586 self.outlives.retain(|&val| outlives.replace(val).is_none());
2587 self.dtorck_types.retain(|&val| dtorck_types.replace(val).is_none());
2591 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
2592 pub struct SymbolName {
2593 // FIXME: we don't rely on interning or equality here - better have
2594 // this be a `&'tcx str`.
2595 pub name: InternedString
2598 impl Deref for SymbolName {
2601 fn deref(&self) -> &str { &self.name }
2604 impl fmt::Display for SymbolName {
2605 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2606 fmt::Display::fmt(&self.name, fmt)