1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::Variance::*;
12 pub use self::AssociatedItemContainer::*;
13 pub use self::BorrowKind::*;
14 pub use self::IntVarValue::*;
15 pub use self::LvaluePreference::*;
16 pub use self::fold::TypeFoldable;
18 use dep_graph::DepNode;
19 use hir::{map as hir_map, FreevarMap, TraitMap};
20 use hir::def::{Def, CtorKind, ExportMap};
21 use hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
22 use ich::StableHashingContext;
23 use middle::const_val::ConstVal;
24 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
25 use middle::privacy::AccessLevels;
26 use middle::resolve_lifetime::ObjectLifetimeDefault;
27 use middle::region::CodeExtent;
31 use ty::subst::{Subst, Substs};
32 use ty::util::IntTypeExt;
33 use ty::walk::TypeWalker;
34 use util::common::ErrorReported;
35 use util::nodemap::{NodeSet, DefIdMap, FxHashMap, FxHashSet};
37 use serialize::{self, Encodable, Encoder};
38 use std::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.
398 pub substs: &'tcx Substs<'tcx>
401 /// With method calls, we store some extra information in
402 /// side tables (i.e method_map). We use
403 /// MethodCall as a key to index into these tables instead of
404 /// just directly using the expression's NodeId. The reason
405 /// for this being that we may apply adjustments (coercions)
406 /// with the resulting expression also needing to use the
407 /// side tables. The problem with this is that we don't
408 /// assign a separate NodeId to this new expression
409 /// and so it would clash with the base expression if both
410 /// needed to add to the side tables. Thus to disambiguate
411 /// we also keep track of whether there's an adjustment in
413 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
414 pub struct MethodCall {
420 pub fn expr(id: NodeId) -> MethodCall {
427 pub fn autoderef(expr_id: NodeId, autoderef: u32) -> MethodCall {
430 autoderef: 1 + autoderef
435 // maps from an expression id that corresponds to a method call to the details
436 // of the method to be invoked
437 pub type MethodMap<'tcx> = FxHashMap<MethodCall, MethodCallee<'tcx>>;
439 // Contains information needed to resolve types and (in the future) look up
440 // the types of AST nodes.
441 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
442 pub struct CReaderCacheKey {
447 // Flags that we track on types. These flags are propagated upwards
448 // through the type during type construction, so that we can quickly
449 // check whether the type has various kinds of types in it without
450 // recursing over the type itself.
452 flags TypeFlags: u32 {
453 const HAS_PARAMS = 1 << 0,
454 const HAS_SELF = 1 << 1,
455 const HAS_TY_INFER = 1 << 2,
456 const HAS_RE_INFER = 1 << 3,
457 const HAS_RE_SKOL = 1 << 4,
458 const HAS_RE_EARLY_BOUND = 1 << 5,
459 const HAS_FREE_REGIONS = 1 << 6,
460 const HAS_TY_ERR = 1 << 7,
461 const HAS_PROJECTION = 1 << 8,
462 const HAS_TY_CLOSURE = 1 << 9,
464 // true if there are "names" of types and regions and so forth
465 // that are local to a particular fn
466 const HAS_LOCAL_NAMES = 1 << 10,
468 // Present if the type belongs in a local type context.
469 // Only set for TyInfer other than Fresh.
470 const KEEP_IN_LOCAL_TCX = 1 << 11,
472 // Is there a projection that does not involve a bound region?
473 // Currently we can't normalize projections w/ bound regions.
474 const HAS_NORMALIZABLE_PROJECTION = 1 << 12,
476 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
477 TypeFlags::HAS_SELF.bits |
478 TypeFlags::HAS_RE_EARLY_BOUND.bits,
480 // Flags representing the nominal content of a type,
481 // computed by FlagsComputation. If you add a new nominal
482 // flag, it should be added here too.
483 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
484 TypeFlags::HAS_SELF.bits |
485 TypeFlags::HAS_TY_INFER.bits |
486 TypeFlags::HAS_RE_INFER.bits |
487 TypeFlags::HAS_RE_SKOL.bits |
488 TypeFlags::HAS_RE_EARLY_BOUND.bits |
489 TypeFlags::HAS_FREE_REGIONS.bits |
490 TypeFlags::HAS_TY_ERR.bits |
491 TypeFlags::HAS_PROJECTION.bits |
492 TypeFlags::HAS_TY_CLOSURE.bits |
493 TypeFlags::HAS_LOCAL_NAMES.bits |
494 TypeFlags::KEEP_IN_LOCAL_TCX.bits,
498 pub struct TyS<'tcx> {
499 pub sty: TypeVariants<'tcx>,
500 pub flags: TypeFlags,
502 // the maximal depth of any bound regions appearing in this type.
506 impl<'tcx> PartialEq for TyS<'tcx> {
508 fn eq(&self, other: &TyS<'tcx>) -> bool {
509 // (self as *const _) == (other as *const _)
510 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
513 impl<'tcx> Eq for TyS<'tcx> {}
515 impl<'tcx> Hash for TyS<'tcx> {
516 fn hash<H: Hasher>(&self, s: &mut H) {
517 (self as *const TyS).hash(s)
521 impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::TyS<'tcx> {
522 fn hash_stable<W: StableHasherResult>(&self,
523 hcx: &mut StableHashingContext<'a, 'tcx>,
524 hasher: &mut StableHasher<W>) {
528 // The other fields just provide fast access to information that is
529 // also contained in `sty`, so no need to hash them.
534 sty.hash_stable(hcx, hasher);
538 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
540 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
541 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
543 /// A wrapper for slices with the additional invariant
544 /// that the slice is interned and no other slice with
545 /// the same contents can exist in the same context.
546 /// This means we can use pointer + length for both
547 /// equality comparisons and hashing.
548 #[derive(Debug, RustcEncodable)]
549 pub struct Slice<T>([T]);
551 impl<T> PartialEq for Slice<T> {
553 fn eq(&self, other: &Slice<T>) -> bool {
554 (&self.0 as *const [T]) == (&other.0 as *const [T])
557 impl<T> Eq for Slice<T> {}
559 impl<T> Hash for Slice<T> {
560 fn hash<H: Hasher>(&self, s: &mut H) {
561 (self.as_ptr(), self.len()).hash(s)
565 impl<T> Deref for Slice<T> {
567 fn deref(&self) -> &[T] {
572 impl<'a, T> IntoIterator for &'a Slice<T> {
574 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
575 fn into_iter(self) -> Self::IntoIter {
580 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
583 pub fn empty<'a>() -> &'a Slice<T> {
585 mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
590 /// Upvars do not get their own node-id. Instead, we use the pair of
591 /// the original var id (that is, the root variable that is referenced
592 /// by the upvar) and the id of the closure expression.
593 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
596 pub closure_expr_id: NodeId,
599 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
600 pub enum BorrowKind {
601 /// Data must be immutable and is aliasable.
604 /// Data must be immutable but not aliasable. This kind of borrow
605 /// cannot currently be expressed by the user and is used only in
606 /// implicit closure bindings. It is needed when the closure
607 /// is borrowing or mutating a mutable referent, e.g.:
609 /// let x: &mut isize = ...;
610 /// let y = || *x += 5;
612 /// If we were to try to translate this closure into a more explicit
613 /// form, we'd encounter an error with the code as written:
615 /// struct Env { x: & &mut isize }
616 /// let x: &mut isize = ...;
617 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
618 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
620 /// This is then illegal because you cannot mutate a `&mut` found
621 /// in an aliasable location. To solve, you'd have to translate with
622 /// an `&mut` borrow:
624 /// struct Env { x: & &mut isize }
625 /// let x: &mut isize = ...;
626 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
627 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
629 /// Now the assignment to `**env.x` is legal, but creating a
630 /// mutable pointer to `x` is not because `x` is not mutable. We
631 /// could fix this by declaring `x` as `let mut x`. This is ok in
632 /// user code, if awkward, but extra weird for closures, since the
633 /// borrow is hidden.
635 /// So we introduce a "unique imm" borrow -- the referent is
636 /// immutable, but not aliasable. This solves the problem. For
637 /// simplicity, we don't give users the way to express this
638 /// borrow, it's just used when translating closures.
641 /// Data is mutable and not aliasable.
645 /// Information describing the capture of an upvar. This is computed
646 /// during `typeck`, specifically by `regionck`.
647 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
648 pub enum UpvarCapture<'tcx> {
649 /// Upvar is captured by value. This is always true when the
650 /// closure is labeled `move`, but can also be true in other cases
651 /// depending on inference.
654 /// Upvar is captured by reference.
655 ByRef(UpvarBorrow<'tcx>),
658 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
659 pub struct UpvarBorrow<'tcx> {
660 /// The kind of borrow: by-ref upvars have access to shared
661 /// immutable borrows, which are not part of the normal language
663 pub kind: BorrowKind,
665 /// Region of the resulting reference.
666 pub region: ty::Region<'tcx>,
669 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
671 #[derive(Copy, Clone)]
672 pub struct ClosureUpvar<'tcx> {
678 #[derive(Clone, Copy, PartialEq)]
679 pub enum IntVarValue {
681 UintType(ast::UintTy),
684 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
685 pub struct TypeParameterDef {
689 pub has_default: bool,
690 pub object_lifetime_default: ObjectLifetimeDefault,
692 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
693 /// on generic parameter `T`, asserts data behind the parameter
694 /// `T` won't be accessed during the parent type's `Drop` impl.
695 pub pure_wrt_drop: bool,
698 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
699 pub struct RegionParameterDef {
703 pub issue_32330: Option<ty::Issue32330>,
705 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
706 /// on generic parameter `'a`, asserts data of lifetime `'a`
707 /// won't be accessed during the parent type's `Drop` impl.
708 pub pure_wrt_drop: bool,
711 impl RegionParameterDef {
712 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
713 ty::EarlyBoundRegion {
720 pub fn to_bound_region(&self) -> ty::BoundRegion {
721 self.to_early_bound_region_data().to_bound_region()
725 impl ty::EarlyBoundRegion {
726 pub fn to_bound_region(&self) -> ty::BoundRegion {
727 ty::BoundRegion::BrNamed(self.def_id, self.name)
731 /// Information about the formal type/lifetime parameters associated
732 /// with an item or method. Analogous to hir::Generics.
733 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
734 pub struct Generics {
735 pub parent: Option<DefId>,
736 pub parent_regions: u32,
737 pub parent_types: u32,
738 pub regions: Vec<RegionParameterDef>,
739 pub types: Vec<TypeParameterDef>,
741 /// Reverse map to each `TypeParameterDef`'s `index` field, from
742 /// `def_id.index` (`def_id.krate` is the same as the item's).
743 pub type_param_to_index: BTreeMap<DefIndex, u32>,
749 pub fn parent_count(&self) -> usize {
750 self.parent_regions as usize + self.parent_types as usize
753 pub fn own_count(&self) -> usize {
754 self.regions.len() + self.types.len()
757 pub fn count(&self) -> usize {
758 self.parent_count() + self.own_count()
761 pub fn region_param(&self, param: &EarlyBoundRegion) -> &RegionParameterDef {
762 assert_eq!(self.parent_count(), 0);
763 &self.regions[param.index as usize - self.has_self as usize]
766 pub fn type_param(&self, param: &ParamTy) -> &TypeParameterDef {
767 assert_eq!(self.parent_count(), 0);
768 &self.types[param.idx as usize - self.has_self as usize - self.regions.len()]
772 /// Bounds on generics.
773 #[derive(Clone, Default)]
774 pub struct GenericPredicates<'tcx> {
775 pub parent: Option<DefId>,
776 pub predicates: Vec<Predicate<'tcx>>,
779 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
780 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
782 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
783 pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
784 -> InstantiatedPredicates<'tcx> {
785 let mut instantiated = InstantiatedPredicates::empty();
786 self.instantiate_into(tcx, &mut instantiated, substs);
789 pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
790 -> InstantiatedPredicates<'tcx> {
791 InstantiatedPredicates {
792 predicates: self.predicates.subst(tcx, substs)
796 fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
797 instantiated: &mut InstantiatedPredicates<'tcx>,
798 substs: &Substs<'tcx>) {
799 if let Some(def_id) = self.parent {
800 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
802 instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
805 pub fn instantiate_identity(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
806 -> InstantiatedPredicates<'tcx> {
807 let mut instantiated = InstantiatedPredicates::empty();
808 self.instantiate_identity_into(tcx, &mut instantiated);
812 fn instantiate_identity_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
813 instantiated: &mut InstantiatedPredicates<'tcx>) {
814 if let Some(def_id) = self.parent {
815 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
817 instantiated.predicates.extend(&self.predicates)
820 pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
821 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
822 -> InstantiatedPredicates<'tcx>
824 assert_eq!(self.parent, None);
825 InstantiatedPredicates {
826 predicates: self.predicates.iter().map(|pred| {
827 pred.subst_supertrait(tcx, poly_trait_ref)
833 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
834 pub enum Predicate<'tcx> {
835 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
836 /// the `Self` type of the trait reference and `A`, `B`, and `C`
837 /// would be the type parameters.
838 Trait(PolyTraitPredicate<'tcx>),
840 /// where `T1 == T2`.
841 Equate(PolyEquatePredicate<'tcx>),
844 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
847 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
849 /// where <T as TraitRef>::Name == X, approximately.
850 /// See `ProjectionPredicate` struct for details.
851 Projection(PolyProjectionPredicate<'tcx>),
854 WellFormed(Ty<'tcx>),
856 /// trait must be object-safe
859 /// No direct syntax. May be thought of as `where T : FnFoo<...>`
860 /// for some substitutions `...` and T being a closure type.
861 /// Satisfied (or refuted) once we know the closure's kind.
862 ClosureKind(DefId, ClosureKind),
865 Subtype(PolySubtypePredicate<'tcx>),
868 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
869 /// Performs a substitution suitable for going from a
870 /// poly-trait-ref to supertraits that must hold if that
871 /// poly-trait-ref holds. This is slightly different from a normal
872 /// substitution in terms of what happens with bound regions. See
873 /// lengthy comment below for details.
874 pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
875 trait_ref: &ty::PolyTraitRef<'tcx>)
876 -> ty::Predicate<'tcx>
878 // The interaction between HRTB and supertraits is not entirely
879 // obvious. Let me walk you (and myself) through an example.
881 // Let's start with an easy case. Consider two traits:
883 // trait Foo<'a> : Bar<'a,'a> { }
884 // trait Bar<'b,'c> { }
886 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
887 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
888 // knew that `Foo<'x>` (for any 'x) then we also know that
889 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
890 // normal substitution.
892 // In terms of why this is sound, the idea is that whenever there
893 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
894 // holds. So if there is an impl of `T:Foo<'a>` that applies to
895 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
898 // Another example to be careful of is this:
900 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
901 // trait Bar1<'b,'c> { }
903 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
904 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
905 // reason is similar to the previous example: any impl of
906 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
907 // basically we would want to collapse the bound lifetimes from
908 // the input (`trait_ref`) and the supertraits.
910 // To achieve this in practice is fairly straightforward. Let's
911 // consider the more complicated scenario:
913 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
914 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
915 // where both `'x` and `'b` would have a DB index of 1.
916 // The substitution from the input trait-ref is therefore going to be
917 // `'a => 'x` (where `'x` has a DB index of 1).
918 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
919 // early-bound parameter and `'b' is a late-bound parameter with a
921 // - If we replace `'a` with `'x` from the input, it too will have
922 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
923 // just as we wanted.
925 // There is only one catch. If we just apply the substitution `'a
926 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
927 // adjust the DB index because we substituting into a binder (it
928 // tries to be so smart...) resulting in `for<'x> for<'b>
929 // Bar1<'x,'b>` (we have no syntax for this, so use your
930 // imagination). Basically the 'x will have DB index of 2 and 'b
931 // will have DB index of 1. Not quite what we want. So we apply
932 // the substitution to the *contents* of the trait reference,
933 // rather than the trait reference itself (put another way, the
934 // substitution code expects equal binding levels in the values
935 // from the substitution and the value being substituted into, and
936 // this trick achieves that).
938 let substs = &trait_ref.0.substs;
940 Predicate::Trait(ty::Binder(ref data)) =>
941 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
942 Predicate::Equate(ty::Binder(ref data)) =>
943 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
944 Predicate::Subtype(ty::Binder(ref data)) =>
945 Predicate::Subtype(ty::Binder(data.subst(tcx, substs))),
946 Predicate::RegionOutlives(ty::Binder(ref data)) =>
947 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
948 Predicate::TypeOutlives(ty::Binder(ref data)) =>
949 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
950 Predicate::Projection(ty::Binder(ref data)) =>
951 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
952 Predicate::WellFormed(data) =>
953 Predicate::WellFormed(data.subst(tcx, substs)),
954 Predicate::ObjectSafe(trait_def_id) =>
955 Predicate::ObjectSafe(trait_def_id),
956 Predicate::ClosureKind(closure_def_id, kind) =>
957 Predicate::ClosureKind(closure_def_id, kind),
962 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
963 pub struct TraitPredicate<'tcx> {
964 pub trait_ref: TraitRef<'tcx>
966 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
968 impl<'tcx> TraitPredicate<'tcx> {
969 pub fn def_id(&self) -> DefId {
970 self.trait_ref.def_id
973 /// Creates the dep-node for selecting/evaluating this trait reference.
974 fn dep_node(&self) -> DepNode<DefId> {
975 // Extact the trait-def and first def-id from inputs. See the
976 // docs for `DepNode::TraitSelect` for more information.
977 let trait_def_id = self.def_id();
980 .flat_map(|t| t.walk())
981 .filter_map(|t| match t.sty {
982 ty::TyAdt(adt_def, _) => Some(adt_def.did),
986 .unwrap_or(trait_def_id);
987 DepNode::TraitSelect {
988 trait_def_id: trait_def_id,
989 input_def_id: input_def_id
993 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
994 self.trait_ref.input_types()
997 pub fn self_ty(&self) -> Ty<'tcx> {
998 self.trait_ref.self_ty()
1002 impl<'tcx> PolyTraitPredicate<'tcx> {
1003 pub fn def_id(&self) -> DefId {
1004 // ok to skip binder since trait def-id does not care about regions
1008 pub fn dep_node(&self) -> DepNode<DefId> {
1009 // ok to skip binder since depnode does not care about regions
1014 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1015 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
1016 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
1018 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1019 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
1020 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
1021 pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<ty::Region<'tcx>,
1023 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1025 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1026 pub struct SubtypePredicate<'tcx> {
1027 pub a_is_expected: bool,
1031 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1033 /// This kind of predicate has no *direct* correspondent in the
1034 /// syntax, but it roughly corresponds to the syntactic forms:
1036 /// 1. `T : TraitRef<..., Item=Type>`
1037 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1039 /// In particular, form #1 is "desugared" to the combination of a
1040 /// normal trait predicate (`T : TraitRef<...>`) and one of these
1041 /// predicates. Form #2 is a broader form in that it also permits
1042 /// equality between arbitrary types. Processing an instance of Form
1043 /// #2 eventually yields one of these `ProjectionPredicate`
1044 /// instances to normalize the LHS.
1045 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1046 pub struct ProjectionPredicate<'tcx> {
1047 pub projection_ty: ProjectionTy<'tcx>,
1051 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1053 impl<'tcx> PolyProjectionPredicate<'tcx> {
1054 pub fn item_name(&self) -> Name {
1055 self.0.projection_ty.item_name // safe to skip the binder to access a name
1059 pub trait ToPolyTraitRef<'tcx> {
1060 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1063 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1064 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1065 assert!(!self.has_escaping_regions());
1066 ty::Binder(self.clone())
1070 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1071 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1072 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1076 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
1077 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1078 // Note: unlike with TraitRef::to_poly_trait_ref(),
1079 // self.0.trait_ref is permitted to have escaping regions.
1080 // This is because here `self` has a `Binder` and so does our
1081 // return value, so we are preserving the number of binding
1083 ty::Binder(self.0.projection_ty.trait_ref)
1087 pub trait ToPredicate<'tcx> {
1088 fn to_predicate(&self) -> Predicate<'tcx>;
1091 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1092 fn to_predicate(&self) -> Predicate<'tcx> {
1093 // we're about to add a binder, so let's check that we don't
1094 // accidentally capture anything, or else that might be some
1095 // weird debruijn accounting.
1096 assert!(!self.has_escaping_regions());
1098 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1099 trait_ref: self.clone()
1104 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1105 fn to_predicate(&self) -> Predicate<'tcx> {
1106 ty::Predicate::Trait(self.to_poly_trait_predicate())
1110 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
1111 fn to_predicate(&self) -> Predicate<'tcx> {
1112 Predicate::Equate(self.clone())
1116 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1117 fn to_predicate(&self) -> Predicate<'tcx> {
1118 Predicate::RegionOutlives(self.clone())
1122 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1123 fn to_predicate(&self) -> Predicate<'tcx> {
1124 Predicate::TypeOutlives(self.clone())
1128 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1129 fn to_predicate(&self) -> Predicate<'tcx> {
1130 Predicate::Projection(self.clone())
1134 impl<'tcx> Predicate<'tcx> {
1135 /// Iterates over the types in this predicate. Note that in all
1136 /// cases this is skipping over a binder, so late-bound regions
1137 /// with depth 0 are bound by the predicate.
1138 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1139 let vec: Vec<_> = match *self {
1140 ty::Predicate::Trait(ref data) => {
1141 data.skip_binder().input_types().collect()
1143 ty::Predicate::Equate(ty::Binder(ref data)) => {
1144 vec![data.0, data.1]
1146 ty::Predicate::Subtype(ty::Binder(SubtypePredicate { a, b, a_is_expected: _ })) => {
1149 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1152 ty::Predicate::RegionOutlives(..) => {
1155 ty::Predicate::Projection(ref data) => {
1156 let trait_inputs = data.0.projection_ty.trait_ref.input_types();
1157 trait_inputs.chain(Some(data.0.ty)).collect()
1159 ty::Predicate::WellFormed(data) => {
1162 ty::Predicate::ObjectSafe(_trait_def_id) => {
1165 ty::Predicate::ClosureKind(_closure_def_id, _kind) => {
1170 // The only reason to collect into a vector here is that I was
1171 // too lazy to make the full (somewhat complicated) iterator
1172 // type that would be needed here. But I wanted this fn to
1173 // return an iterator conceptually, rather than a `Vec`, so as
1174 // to be closer to `Ty::walk`.
1178 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1180 Predicate::Trait(ref t) => {
1181 Some(t.to_poly_trait_ref())
1183 Predicate::Projection(..) |
1184 Predicate::Equate(..) |
1185 Predicate::Subtype(..) |
1186 Predicate::RegionOutlives(..) |
1187 Predicate::WellFormed(..) |
1188 Predicate::ObjectSafe(..) |
1189 Predicate::ClosureKind(..) |
1190 Predicate::TypeOutlives(..) => {
1197 /// Represents the bounds declared on a particular set of type
1198 /// parameters. Should eventually be generalized into a flag list of
1199 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
1200 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1201 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1202 /// the `GenericPredicates` are expressed in terms of the bound type
1203 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1204 /// represented a set of bounds for some particular instantiation,
1205 /// meaning that the generic parameters have been substituted with
1210 /// struct Foo<T,U:Bar<T>> { ... }
1212 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1213 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1214 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1215 /// [usize:Bar<isize>]]`.
1217 pub struct InstantiatedPredicates<'tcx> {
1218 pub predicates: Vec<Predicate<'tcx>>,
1221 impl<'tcx> InstantiatedPredicates<'tcx> {
1222 pub fn empty() -> InstantiatedPredicates<'tcx> {
1223 InstantiatedPredicates { predicates: vec![] }
1226 pub fn is_empty(&self) -> bool {
1227 self.predicates.is_empty()
1231 /// When type checking, we use the `ParamEnv` to track
1232 /// details about the set of where-clauses that are in scope at this
1233 /// particular point.
1234 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1235 pub struct ParamEnv<'tcx> {
1236 /// Obligations that the caller must satisfy. This is basically
1237 /// the set of bounds on the in-scope type parameters, translated
1238 /// into Obligations, and elaborated and normalized.
1239 pub caller_bounds: &'tcx Slice<ty::Predicate<'tcx>>,
1242 impl<'tcx> ParamEnv<'tcx> {
1243 /// Creates a suitable environment in which to perform trait
1244 /// queries on the given value. This will either be `self` *or*
1245 /// the empty environment, depending on whether `value` references
1246 /// type parameters that are in scope. (If it doesn't, then any
1247 /// judgements should be completely independent of the context,
1248 /// and hence we can safely use the empty environment so as to
1249 /// enable more sharing across functions.)
1251 /// NB: This is a mildly dubious thing to do, in that a function
1252 /// (or other environment) might have wacky where-clauses like
1253 /// `where Box<u32>: Copy`, which are clearly never
1254 /// satisfiable. The code will at present ignore these,
1255 /// effectively, when type-checking the body of said
1256 /// function. This preserves existing behavior in any
1257 /// case. --nmatsakis
1258 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1259 assert!(!value.needs_infer());
1260 if value.has_param_types() || value.has_self_ty() {
1267 param_env: ParamEnv::empty(),
1274 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1275 pub struct ParamEnvAnd<'tcx, T> {
1276 pub param_env: ParamEnv<'tcx>,
1280 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1281 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1282 (self.param_env, self.value)
1286 #[derive(Copy, Clone, Debug)]
1287 pub struct Destructor {
1288 /// The def-id of the destructor method
1293 flags AdtFlags: u32 {
1294 const NO_ADT_FLAGS = 0,
1295 const IS_ENUM = 1 << 0,
1296 const IS_PHANTOM_DATA = 1 << 1,
1297 const IS_FUNDAMENTAL = 1 << 2,
1298 const IS_UNION = 1 << 3,
1299 const IS_BOX = 1 << 4,
1304 pub struct VariantDef {
1305 /// The variant's DefId. If this is a tuple-like struct,
1306 /// this is the DefId of the struct's ctor.
1308 pub name: Name, // struct's name if this is a struct
1309 pub discr: VariantDiscr,
1310 pub fields: Vec<FieldDef>,
1311 pub ctor_kind: CtorKind,
1314 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1315 pub enum VariantDiscr {
1316 /// Explicit value for this variant, i.e. `X = 123`.
1317 /// The `DefId` corresponds to the embedded constant.
1320 /// The previous variant's discriminant plus one.
1321 /// For efficiency reasons, the distance from the
1322 /// last `Explicit` discriminant is being stored,
1323 /// or `0` for the first variant, if it has none.
1328 pub struct FieldDef {
1331 pub vis: Visibility,
1334 /// The definition of an abstract data type - a struct or enum.
1336 /// These are all interned (by intern_adt_def) into the adt_defs
1340 pub variants: Vec<VariantDef>,
1342 pub repr: ReprOptions,
1345 impl PartialEq for AdtDef {
1346 // AdtDef are always interned and this is part of TyS equality
1348 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1351 impl Eq for AdtDef {}
1353 impl Hash for AdtDef {
1355 fn hash<H: Hasher>(&self, s: &mut H) {
1356 (self as *const AdtDef).hash(s)
1360 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1361 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1366 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1369 impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for AdtDef {
1370 fn hash_stable<W: StableHasherResult>(&self,
1371 hcx: &mut StableHashingContext<'a, 'tcx>,
1372 hasher: &mut StableHasher<W>) {
1380 did.hash_stable(hcx, hasher);
1381 variants.hash_stable(hcx, hasher);
1382 flags.hash_stable(hcx, hasher);
1383 repr.hash_stable(hcx, hasher);
1387 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1388 pub enum AdtKind { Struct, Union, Enum }
1391 #[derive(RustcEncodable, RustcDecodable, Default)]
1392 flags ReprFlags: u8 {
1393 const IS_C = 1 << 0,
1394 const IS_PACKED = 1 << 1,
1395 const IS_SIMD = 1 << 2,
1396 // Internal only for now. If true, don't reorder fields.
1397 const IS_LINEAR = 1 << 3,
1399 // Any of these flags being set prevent field reordering optimisation.
1400 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1401 ReprFlags::IS_PACKED.bits |
1402 ReprFlags::IS_SIMD.bits |
1403 ReprFlags::IS_LINEAR.bits,
1407 impl_stable_hash_for!(struct ReprFlags {
1413 /// Represents the repr options provided by the user,
1414 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1415 pub struct ReprOptions {
1416 pub int: Option<attr::IntType>,
1418 pub flags: ReprFlags,
1421 impl_stable_hash_for!(struct ReprOptions {
1428 pub fn new(tcx: TyCtxt, did: DefId) -> ReprOptions {
1429 let mut flags = ReprFlags::empty();
1430 let mut size = None;
1431 let mut max_align = 0;
1432 for attr in tcx.get_attrs(did).iter() {
1433 for r in attr::find_repr_attrs(tcx.sess.diagnostic(), attr) {
1434 flags.insert(match r {
1435 attr::ReprExtern => ReprFlags::IS_C,
1436 attr::ReprPacked => ReprFlags::IS_PACKED,
1437 attr::ReprSimd => ReprFlags::IS_SIMD,
1438 attr::ReprInt(i) => {
1442 attr::ReprAlign(align) => {
1443 max_align = cmp::max(align, max_align);
1450 // FIXME(eddyb) This is deprecated and should be removed.
1451 if tcx.has_attr(did, "simd") {
1452 flags.insert(ReprFlags::IS_SIMD);
1455 // This is here instead of layout because the choice must make it into metadata.
1456 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.item_path_str(did))) {
1457 flags.insert(ReprFlags::IS_LINEAR);
1459 ReprOptions { int: size, align: max_align, flags: flags }
1463 pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
1465 pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
1467 pub fn packed(&self) -> bool { self.flags.contains(ReprFlags::IS_PACKED) }
1469 pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
1471 pub fn discr_type(&self) -> attr::IntType {
1472 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Is))
1475 /// Returns true if this `#[repr()]` should inhabit "smart enum
1476 /// layout" optimizations, such as representing `Foo<&T>` as a
1478 pub fn inhibit_enum_layout_opt(&self) -> bool {
1479 self.c() || self.int.is_some()
1483 impl<'a, 'gcx, 'tcx> AdtDef {
1487 variants: Vec<VariantDef>,
1488 repr: ReprOptions) -> Self {
1489 let mut flags = AdtFlags::NO_ADT_FLAGS;
1490 let attrs = tcx.get_attrs(did);
1491 if attr::contains_name(&attrs, "fundamental") {
1492 flags = flags | AdtFlags::IS_FUNDAMENTAL;
1494 if Some(did) == tcx.lang_items.phantom_data() {
1495 flags = flags | AdtFlags::IS_PHANTOM_DATA;
1497 if Some(did) == tcx.lang_items.owned_box() {
1498 flags = flags | AdtFlags::IS_BOX;
1501 AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1502 AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1503 AdtKind::Struct => {}
1514 pub fn is_struct(&self) -> bool {
1515 !self.is_union() && !self.is_enum()
1519 pub fn is_union(&self) -> bool {
1520 self.flags.intersects(AdtFlags::IS_UNION)
1524 pub fn is_enum(&self) -> bool {
1525 self.flags.intersects(AdtFlags::IS_ENUM)
1528 /// Returns the kind of the ADT - Struct or Enum.
1530 pub fn adt_kind(&self) -> AdtKind {
1533 } else if self.is_union() {
1540 pub fn descr(&self) -> &'static str {
1541 match self.adt_kind() {
1542 AdtKind::Struct => "struct",
1543 AdtKind::Union => "union",
1544 AdtKind::Enum => "enum",
1548 pub fn variant_descr(&self) -> &'static str {
1549 match self.adt_kind() {
1550 AdtKind::Struct => "struct",
1551 AdtKind::Union => "union",
1552 AdtKind::Enum => "variant",
1556 /// Returns whether this type is #[fundamental] for the purposes
1557 /// of coherence checking.
1559 pub fn is_fundamental(&self) -> bool {
1560 self.flags.intersects(AdtFlags::IS_FUNDAMENTAL)
1563 /// Returns true if this is PhantomData<T>.
1565 pub fn is_phantom_data(&self) -> bool {
1566 self.flags.intersects(AdtFlags::IS_PHANTOM_DATA)
1569 /// Returns true if this is Box<T>.
1571 pub fn is_box(&self) -> bool {
1572 self.flags.intersects(AdtFlags::IS_BOX)
1575 /// Returns whether this type has a destructor.
1576 pub fn has_dtor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1577 self.destructor(tcx).is_some()
1580 /// Asserts this is a struct and returns the struct's unique
1582 pub fn struct_variant(&self) -> &VariantDef {
1583 assert!(!self.is_enum());
1588 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1589 tcx.predicates_of(self.did)
1592 /// Returns an iterator over all fields contained
1595 pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1596 self.variants.iter().flat_map(|v| v.fields.iter())
1600 pub fn is_univariant(&self) -> bool {
1601 self.variants.len() == 1
1604 pub fn is_payloadfree(&self) -> bool {
1605 !self.variants.is_empty() &&
1606 self.variants.iter().all(|v| v.fields.is_empty())
1609 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1612 .find(|v| v.did == vid)
1613 .expect("variant_with_id: unknown variant")
1616 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1619 .position(|v| v.did == vid)
1620 .expect("variant_index_with_id: unknown variant")
1623 pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1625 Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1626 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1627 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.struct_variant(),
1628 _ => bug!("unexpected def {:?} in variant_of_def", def)
1633 pub fn discriminants(&'a self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
1634 -> impl Iterator<Item=ConstInt> + 'a {
1635 let repr_type = self.repr.discr_type();
1636 let initial = repr_type.initial_discriminant(tcx.global_tcx());
1637 let mut prev_discr = None::<ConstInt>;
1638 self.variants.iter().map(move |v| {
1639 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr());
1640 if let VariantDiscr::Explicit(expr_did) = v.discr {
1641 let substs = Substs::empty();
1642 match tcx.const_eval((expr_did, substs)) {
1643 Ok(ConstVal::Integral(v)) => {
1647 if !expr_did.is_local() {
1648 span_bug!(tcx.def_span(expr_did),
1649 "variant discriminant evaluation succeeded \
1650 in its crate but failed locally: {:?}", err);
1655 prev_discr = Some(discr);
1661 /// Compute the discriminant value used by a specific variant.
1662 /// Unlike `discriminants`, this is (amortized) constant-time,
1663 /// only doing at most one query for evaluating an explicit
1664 /// discriminant (the last one before the requested variant),
1665 /// assuming there are no constant-evaluation errors there.
1666 pub fn discriminant_for_variant(&self,
1667 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1668 variant_index: usize)
1670 let repr_type = self.repr.discr_type();
1671 let mut explicit_value = repr_type.initial_discriminant(tcx.global_tcx());
1672 let mut explicit_index = variant_index;
1674 match self.variants[explicit_index].discr {
1675 ty::VariantDiscr::Relative(0) => break,
1676 ty::VariantDiscr::Relative(distance) => {
1677 explicit_index -= distance;
1679 ty::VariantDiscr::Explicit(expr_did) => {
1680 let substs = Substs::empty();
1681 match tcx.const_eval((expr_did, substs)) {
1682 Ok(ConstVal::Integral(v)) => {
1687 if !expr_did.is_local() {
1688 span_bug!(tcx.def_span(expr_did),
1689 "variant discriminant evaluation succeeded \
1690 in its crate but failed locally: {:?}", err);
1692 if explicit_index == 0 {
1695 explicit_index -= 1;
1701 let discr = explicit_value.to_u128_unchecked()
1702 .wrapping_add((variant_index - explicit_index) as u128);
1704 attr::UnsignedInt(ty) => {
1705 ConstInt::new_unsigned_truncating(discr, ty,
1706 tcx.sess.target.uint_type)
1708 attr::SignedInt(ty) => {
1709 ConstInt::new_signed_truncating(discr as i128, ty,
1710 tcx.sess.target.int_type)
1715 pub fn destructor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Destructor> {
1716 tcx.adt_destructor(self.did)
1719 /// Returns a list of types such that `Self: Sized` if and only
1720 /// if that type is Sized, or `TyErr` if this type is recursive.
1722 /// Oddly enough, checking that the sized-constraint is Sized is
1723 /// actually more expressive than checking all members:
1724 /// the Sized trait is inductive, so an associated type that references
1725 /// Self would prevent its containing ADT from being Sized.
1727 /// Due to normalization being eager, this applies even if
1728 /// the associated type is behind a pointer, e.g. issue #31299.
1729 pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] {
1730 match queries::adt_sized_constraint::try_get(tcx, DUMMY_SP, self.did) {
1733 debug!("adt_sized_constraint: {:?} is recursive", self);
1734 // This should be reported as an error by `check_representable`.
1736 // Consider the type as Sized in the meanwhile to avoid
1738 tcx.intern_type_list(&[tcx.types.err])
1743 fn sized_constraint_for_ty(&self,
1744 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1747 let result = match ty.sty {
1748 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
1749 TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
1750 TyArray(..) | TyClosure(..) | TyNever => {
1754 TyStr | TyDynamic(..) | TySlice(_) | TyError => {
1755 // these are never sized - return the target type
1759 TyTuple(ref tys, _) => {
1762 Some(ty) => self.sized_constraint_for_ty(tcx, ty)
1766 TyAdt(adt, substs) => {
1768 let adt_tys = adt.sized_constraint(tcx);
1769 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
1772 .map(|ty| ty.subst(tcx, substs))
1773 .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
1777 TyProjection(..) | TyAnon(..) => {
1778 // must calculate explicitly.
1779 // FIXME: consider special-casing always-Sized projections
1784 // perf hack: if there is a `T: Sized` bound, then
1785 // we know that `T` is Sized and do not need to check
1788 let sized_trait = match tcx.lang_items.sized_trait() {
1790 _ => return vec![ty]
1792 let sized_predicate = Binder(TraitRef {
1793 def_id: sized_trait,
1794 substs: tcx.mk_substs_trait(ty, &[])
1796 let predicates = tcx.predicates_of(self.did).predicates;
1797 if predicates.into_iter().any(|p| p == sized_predicate) {
1805 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
1809 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
1814 impl<'a, 'gcx, 'tcx> VariantDef {
1816 pub fn find_field_named(&self, name: ast::Name) -> Option<&FieldDef> {
1817 self.index_of_field_named(name).map(|index| &self.fields[index])
1820 pub fn index_of_field_named(&self, name: ast::Name) -> Option<usize> {
1821 if let Some(index) = self.fields.iter().position(|f| f.name == name) {
1824 let mut ident = name.to_ident();
1825 while ident.ctxt != SyntaxContext::empty() {
1826 ident.ctxt.remove_mark();
1827 if let Some(field) = self.fields.iter().position(|f| f.name.to_ident() == ident) {
1835 pub fn field_named(&self, name: ast::Name) -> &FieldDef {
1836 self.find_field_named(name).unwrap()
1840 impl<'a, 'gcx, 'tcx> FieldDef {
1841 pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1842 tcx.type_of(self.did).subst(tcx, subst)
1846 /// Records the substitutions used to translate the polytype for an
1847 /// item into the monotype of an item reference.
1848 #[derive(Clone, RustcEncodable, RustcDecodable)]
1849 pub struct ItemSubsts<'tcx> {
1850 pub substs: &'tcx Substs<'tcx>,
1853 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1854 pub enum ClosureKind {
1855 // Warning: Ordering is significant here! The ordering is chosen
1856 // because the trait Fn is a subtrait of FnMut and so in turn, and
1857 // hence we order it so that Fn < FnMut < FnOnce.
1863 impl<'a, 'tcx> ClosureKind {
1864 pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
1866 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
1867 ClosureKind::FnMut => {
1868 tcx.require_lang_item(FnMutTraitLangItem)
1870 ClosureKind::FnOnce => {
1871 tcx.require_lang_item(FnOnceTraitLangItem)
1876 /// True if this a type that impls this closure kind
1877 /// must also implement `other`.
1878 pub fn extends(self, other: ty::ClosureKind) -> bool {
1879 match (self, other) {
1880 (ClosureKind::Fn, ClosureKind::Fn) => true,
1881 (ClosureKind::Fn, ClosureKind::FnMut) => true,
1882 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
1883 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
1884 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
1885 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
1891 impl<'tcx> TyS<'tcx> {
1892 /// Iterator that walks `self` and any types reachable from
1893 /// `self`, in depth-first order. Note that just walks the types
1894 /// that appear in `self`, it does not descend into the fields of
1895 /// structs or variants. For example:
1898 /// isize => { isize }
1899 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
1900 /// [isize] => { [isize], isize }
1902 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
1903 TypeWalker::new(self)
1906 /// Iterator that walks the immediate children of `self`. Hence
1907 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
1908 /// (but not `i32`, like `walk`).
1909 pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
1910 walk::walk_shallow(self)
1913 /// Walks `ty` and any types appearing within `ty`, invoking the
1914 /// callback `f` on each type. If the callback returns false, then the
1915 /// children of the current type are ignored.
1917 /// Note: prefer `ty.walk()` where possible.
1918 pub fn maybe_walk<F>(&'tcx self, mut f: F)
1919 where F : FnMut(Ty<'tcx>) -> bool
1921 let mut walker = self.walk();
1922 while let Some(ty) = walker.next() {
1924 walker.skip_current_subtree();
1930 impl<'tcx> ItemSubsts<'tcx> {
1931 pub fn is_noop(&self) -> bool {
1932 self.substs.is_noop()
1936 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1937 pub enum LvaluePreference {
1942 impl LvaluePreference {
1943 pub fn from_mutbl(m: hir::Mutability) -> Self {
1945 hir::MutMutable => PreferMutLvalue,
1946 hir::MutImmutable => NoPreference,
1952 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
1954 hir::MutMutable => MutBorrow,
1955 hir::MutImmutable => ImmBorrow,
1959 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
1960 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
1961 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
1963 pub fn to_mutbl_lossy(self) -> hir::Mutability {
1965 MutBorrow => hir::MutMutable,
1966 ImmBorrow => hir::MutImmutable,
1968 // We have no type corresponding to a unique imm borrow, so
1969 // use `&mut`. It gives all the capabilities of an `&uniq`
1970 // and hence is a safe "over approximation".
1971 UniqueImmBorrow => hir::MutMutable,
1975 pub fn to_user_str(&self) -> &'static str {
1977 MutBorrow => "mutable",
1978 ImmBorrow => "immutable",
1979 UniqueImmBorrow => "uniquely immutable",
1984 #[derive(Debug, Clone)]
1985 pub enum Attributes<'gcx> {
1986 Owned(Rc<[ast::Attribute]>),
1987 Borrowed(&'gcx [ast::Attribute])
1990 impl<'gcx> ::std::ops::Deref for Attributes<'gcx> {
1991 type Target = [ast::Attribute];
1993 fn deref(&self) -> &[ast::Attribute] {
1995 &Attributes::Owned(ref data) => &data,
1996 &Attributes::Borrowed(data) => data
2001 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2002 pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
2003 self.typeck_tables_of(self.hir.body_owner_def_id(body))
2006 /// Returns an iterator of the def-ids for all body-owners in this
2007 /// crate. If you would prefer to iterate over the bodies
2008 /// themselves, you can do `self.hir.krate().body_ids.iter()`.
2009 pub fn body_owners(self) -> impl Iterator<Item = DefId> + 'a {
2013 .map(move |&body_id| self.hir.body_owner_def_id(body_id))
2016 pub fn expr_span(self, id: NodeId) -> Span {
2017 match self.hir.find(id) {
2018 Some(hir_map::NodeExpr(e)) => {
2022 bug!("Node id {} is not an expr: {:?}", id, f);
2025 bug!("Node id {} is not present in the node map", id);
2030 pub fn local_var_name_str(self, id: NodeId) -> InternedString {
2031 match self.hir.find(id) {
2032 Some(hir_map::NodeLocal(pat)) => {
2034 hir::PatKind::Binding(_, _, ref path1, _) => path1.node.as_str(),
2036 bug!("Variable id {} maps to {:?}, not local", id, pat);
2040 r => bug!("Variable id {} maps to {:?}, not local", id, r),
2044 pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
2046 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
2048 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
2053 hir::ExprType(ref e, _) => {
2054 self.expr_is_lval(e)
2057 hir::ExprUnary(hir::UnDeref, _) |
2058 hir::ExprField(..) |
2059 hir::ExprTupField(..) |
2060 hir::ExprIndex(..) => {
2064 // Partially qualified paths in expressions can only legally
2065 // refer to associated items which are always rvalues.
2066 hir::ExprPath(hir::QPath::TypeRelative(..)) |
2069 hir::ExprMethodCall(..) |
2070 hir::ExprStruct(..) |
2073 hir::ExprMatch(..) |
2074 hir::ExprClosure(..) |
2075 hir::ExprBlock(..) |
2076 hir::ExprRepeat(..) |
2077 hir::ExprArray(..) |
2078 hir::ExprBreak(..) |
2079 hir::ExprAgain(..) |
2081 hir::ExprWhile(..) |
2083 hir::ExprAssign(..) |
2084 hir::ExprInlineAsm(..) |
2085 hir::ExprAssignOp(..) |
2087 hir::ExprUnary(..) |
2089 hir::ExprAddrOf(..) |
2090 hir::ExprBinary(..) |
2091 hir::ExprCast(..) => {
2097 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2098 self.associated_items(id)
2099 .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2103 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2104 self.associated_items(did).any(|item| {
2105 item.relevant_for_never()
2109 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssociatedItem> {
2110 let is_associated_item = if let Some(node_id) = self.hir.as_local_node_id(def_id) {
2111 match self.hir.get(node_id) {
2112 hir_map::NodeTraitItem(_) | hir_map::NodeImplItem(_) => true,
2116 match self.describe_def(def_id).expect("no def for def-id") {
2117 Def::AssociatedConst(_) | Def::Method(_) | Def::AssociatedTy(_) => true,
2122 if is_associated_item {
2123 Some(self.associated_item(def_id))
2129 fn associated_item_from_trait_item_ref(self,
2130 parent_def_id: DefId,
2131 parent_vis: &hir::Visibility,
2132 trait_item_ref: &hir::TraitItemRef)
2134 let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2135 let (kind, has_self) = match trait_item_ref.kind {
2136 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2137 hir::AssociatedItemKind::Method { has_self } => {
2138 (ty::AssociatedKind::Method, has_self)
2140 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2144 name: trait_item_ref.name,
2146 // Visibility of trait items is inherited from their traits.
2147 vis: Visibility::from_hir(parent_vis, trait_item_ref.id.node_id, self),
2148 defaultness: trait_item_ref.defaultness,
2150 container: TraitContainer(parent_def_id),
2151 method_has_self_argument: has_self
2155 fn associated_item_from_impl_item_ref(self,
2156 parent_def_id: DefId,
2157 impl_item_ref: &hir::ImplItemRef)
2159 let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2160 let (kind, has_self) = match impl_item_ref.kind {
2161 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2162 hir::AssociatedItemKind::Method { has_self } => {
2163 (ty::AssociatedKind::Method, has_self)
2165 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2168 ty::AssociatedItem {
2169 name: impl_item_ref.name,
2171 // Visibility of trait impl items doesn't matter.
2172 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.node_id, self),
2173 defaultness: impl_item_ref.defaultness,
2175 container: ImplContainer(parent_def_id),
2176 method_has_self_argument: has_self
2180 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2181 pub fn associated_items(self, def_id: DefId)
2182 -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2183 let def_ids = self.associated_item_def_ids(def_id);
2184 (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2187 /// Returns true if the impls are the same polarity and are implementing
2188 /// a trait which contains no items
2189 pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId) -> bool {
2190 if !self.sess.features.borrow().overlapping_marker_traits {
2193 let trait1_is_empty = self.impl_trait_ref(def_id1)
2194 .map_or(false, |trait_ref| {
2195 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2197 let trait2_is_empty = self.impl_trait_ref(def_id2)
2198 .map_or(false, |trait_ref| {
2199 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2201 self.impl_polarity(def_id1) == self.impl_polarity(def_id2)
2206 // Returns `ty::VariantDef` if `def` refers to a struct,
2207 // or variant or their constructors, panics otherwise.
2208 pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2210 Def::Variant(did) | Def::VariantCtor(did, ..) => {
2211 let enum_did = self.parent_def_id(did).unwrap();
2212 self.adt_def(enum_did).variant_with_id(did)
2214 Def::Struct(did) | Def::Union(did) => {
2215 self.adt_def(did).struct_variant()
2217 Def::StructCtor(ctor_did, ..) => {
2218 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2219 self.adt_def(did).struct_variant()
2221 _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2225 pub fn def_key(self, id: DefId) -> hir_map::DefKey {
2227 self.hir.def_key(id)
2229 self.sess.cstore.def_key(id)
2233 /// Convert a `DefId` into its fully expanded `DefPath` (every
2234 /// `DefId` is really just an interned def-path).
2236 /// Note that if `id` is not local to this crate, the result will
2237 /// be a non-local `DefPath`.
2238 pub fn def_path(self, id: DefId) -> hir_map::DefPath {
2240 self.hir.def_path(id)
2242 self.sess.cstore.def_path(id)
2247 pub fn def_path_hash(self, def_id: DefId) -> hir_map::DefPathHash {
2248 if def_id.is_local() {
2249 self.hir.definitions().def_path_hash(def_id.index)
2251 self.sess.cstore.def_path_hash(def_id)
2255 pub fn item_name(self, id: DefId) -> ast::Name {
2256 if let Some(id) = self.hir.as_local_node_id(id) {
2258 } else if id.index == CRATE_DEF_INDEX {
2259 self.sess.cstore.original_crate_name(id.krate)
2261 let def_key = self.sess.cstore.def_key(id);
2262 // The name of a StructCtor is that of its struct parent.
2263 if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2264 self.item_name(DefId {
2266 index: def_key.parent.unwrap()
2269 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2270 bug!("item_name: no name for {:?}", self.def_path(id));
2276 /// Return the possibly-auto-generated MIR of a (DefId, Subst) pair.
2277 pub fn instance_mir(self, instance: ty::InstanceDef<'gcx>)
2281 ty::InstanceDef::Item(did) => {
2282 self.optimized_mir(did)
2284 ty::InstanceDef::Intrinsic(..) |
2285 ty::InstanceDef::FnPtrShim(..) |
2286 ty::InstanceDef::Virtual(..) |
2287 ty::InstanceDef::ClosureOnceShim { .. } |
2288 ty::InstanceDef::DropGlue(..) => {
2289 self.mir_shims(instance)
2294 /// Given the DefId of an item, returns its MIR, borrowed immutably.
2295 /// Returns None if there is no MIR for the DefId
2296 pub fn maybe_optimized_mir(self, did: DefId) -> Option<&'gcx Mir<'gcx>> {
2297 if self.is_mir_available(did) {
2298 Some(self.optimized_mir(did))
2304 /// Get the attributes of a definition.
2305 pub fn get_attrs(self, did: DefId) -> Attributes<'gcx> {
2306 if let Some(id) = self.hir.as_local_node_id(did) {
2307 Attributes::Borrowed(self.hir.attrs(id))
2309 Attributes::Owned(self.item_attrs(did))
2313 /// Determine whether an item is annotated with an attribute
2314 pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2315 self.get_attrs(did).iter().any(|item| item.check_name(attr))
2318 pub fn trait_has_default_impl(self, trait_def_id: DefId) -> bool {
2319 self.trait_def(trait_def_id).has_default_impl
2322 /// Given the def_id of an impl, return the def_id of the trait it implements.
2323 /// If it implements no trait, return `None`.
2324 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2325 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2328 /// If the given def ID describes a method belonging to an impl, return the
2329 /// ID of the impl that the method belongs to. Otherwise, return `None`.
2330 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2331 let item = if def_id.krate != LOCAL_CRATE {
2332 if let Some(Def::Method(_)) = self.describe_def(def_id) {
2333 Some(self.associated_item(def_id))
2338 self.opt_associated_item(def_id)
2342 Some(trait_item) => {
2343 match trait_item.container {
2344 TraitContainer(_) => None,
2345 ImplContainer(def_id) => Some(def_id),
2352 pub fn node_scope_region(self, id: NodeId) -> Region<'tcx> {
2353 self.mk_region(ty::ReScope(CodeExtent::Misc(id)))
2356 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2357 /// with the name of the crate containing the impl.
2358 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2359 if impl_did.is_local() {
2360 let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2361 Ok(self.hir.span(node_id))
2363 Err(self.sess.cstore.crate_name(impl_did.krate))
2367 pub fn adjust(self, name: Name, scope: DefId, block: NodeId) -> (Ident, DefId) {
2368 self.adjust_ident(name.to_ident(), scope, block)
2371 pub fn adjust_ident(self, mut ident: Ident, scope: DefId, block: NodeId) -> (Ident, DefId) {
2372 let expansion = match scope.krate {
2373 LOCAL_CRATE => self.hir.definitions().expansion(scope.index),
2376 let scope = match ident.ctxt.adjust(expansion) {
2377 Some(macro_def) => self.hir.definitions().macro_def_scope(macro_def),
2378 None => self.hir.get_module_parent(block),
2384 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2385 pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2386 F: FnOnce(&[hir::Freevar]) -> T,
2388 match self.freevars.borrow().get(&fid) {
2390 Some(d) => f(&d[..])
2395 fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
2398 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2399 let parent_id = tcx.hir.get_parent(id);
2400 let parent_def_id = tcx.hir.local_def_id(parent_id);
2401 let parent_item = tcx.hir.expect_item(parent_id);
2402 match parent_item.node {
2403 hir::ItemImpl(.., ref impl_item_refs) => {
2404 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.node_id == id) {
2405 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
2407 debug_assert_eq!(assoc_item.def_id, def_id);
2412 hir::ItemTrait(.., ref trait_item_refs) => {
2413 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.node_id == id) {
2414 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
2417 debug_assert_eq!(assoc_item.def_id, def_id);
2425 span_bug!(parent_item.span,
2426 "unexpected parent of trait or impl item or item not found: {:?}",
2430 /// Calculates the Sized-constraint.
2432 /// In fact, there are only a few options for the types in the constraint:
2433 /// - an obviously-unsized type
2434 /// - a type parameter or projection whose Sizedness can't be known
2435 /// - a tuple of type parameters or projections, if there are multiple
2437 /// - a TyError, if a type contained itself. The representability
2438 /// check should catch this case.
2439 fn adt_sized_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2441 -> &'tcx [Ty<'tcx>] {
2442 let def = tcx.adt_def(def_id);
2444 let result = tcx.intern_type_list(&def.variants.iter().flat_map(|v| {
2447 def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
2448 }).collect::<Vec<_>>());
2450 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
2455 /// Calculates the dtorck constraint for a type.
2456 fn adt_dtorck_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2458 -> DtorckConstraint<'tcx> {
2459 let def = tcx.adt_def(def_id);
2460 let span = tcx.def_span(def_id);
2461 debug!("dtorck_constraint: {:?}", def);
2463 if def.is_phantom_data() {
2464 let result = DtorckConstraint {
2467 tcx.mk_param_from_def(&tcx.generics_of(def_id).types[0])
2470 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2474 let mut result = def.all_fields()
2475 .map(|field| tcx.type_of(field.did))
2476 .map(|fty| tcx.dtorck_constraint_for_ty(span, fty, 0, fty))
2477 .collect::<Result<DtorckConstraint, ErrorReported>>()
2478 .unwrap_or(DtorckConstraint::empty());
2479 result.outlives.extend(tcx.destructor_constraints(def));
2482 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2487 fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2490 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2491 let item = tcx.hir.expect_item(id);
2492 let vec: Vec<_> = match item.node {
2493 hir::ItemTrait(.., ref trait_item_refs) => {
2494 trait_item_refs.iter()
2495 .map(|trait_item_ref| trait_item_ref.id)
2496 .map(|id| tcx.hir.local_def_id(id.node_id))
2499 hir::ItemImpl(.., ref impl_item_refs) => {
2500 impl_item_refs.iter()
2501 .map(|impl_item_ref| impl_item_ref.id)
2502 .map(|id| tcx.hir.local_def_id(id.node_id))
2505 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2510 fn def_span<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Span {
2511 tcx.hir.span_if_local(def_id).unwrap()
2514 /// If the given def ID describes an item belonging to a trait,
2515 /// return the ID of the trait that the trait item belongs to.
2516 /// Otherwise, return `None`.
2517 fn trait_of_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
2518 tcx.opt_associated_item(def_id)
2519 .and_then(|associated_item| {
2520 match associated_item.container {
2521 TraitContainer(def_id) => Some(def_id),
2522 ImplContainer(_) => None
2527 /// See `ParamEnv` struct def'n for details.
2528 fn param_env<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2531 // Compute the bounds on Self and the type parameters.
2533 let bounds = tcx.predicates_of(def_id).instantiate_identity(tcx);
2534 let predicates = bounds.predicates;
2536 // Finally, we have to normalize the bounds in the environment, in
2537 // case they contain any associated type projections. This process
2538 // can yield errors if the put in illegal associated types, like
2539 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2540 // report these errors right here; this doesn't actually feel
2541 // right to me, because constructing the environment feels like a
2542 // kind of a "idempotent" action, but I'm not sure where would be
2543 // a better place. In practice, we construct environments for
2544 // every fn once during type checking, and we'll abort if there
2545 // are any errors at that point, so after type checking you can be
2546 // sure that this will succeed without errors anyway.
2548 let unnormalized_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates));
2550 let body_id = tcx.hir.as_local_node_id(def_id).map_or(DUMMY_NODE_ID, |id| {
2551 tcx.hir.maybe_body_owned_by(id).map_or(id, |body| body.node_id)
2553 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
2554 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
2557 pub fn provide(providers: &mut ty::maps::Providers) {
2558 util::provide(providers);
2559 *providers = ty::maps::Providers {
2561 associated_item_def_ids,
2562 adt_sized_constraint,
2563 adt_dtorck_constraint,
2567 trait_impls_of: trait_def::trait_impls_of_provider,
2568 relevant_trait_impls_for: trait_def::relevant_trait_impls_provider,
2573 pub fn provide_extern(providers: &mut ty::maps::Providers) {
2574 *providers = ty::maps::Providers {
2575 adt_sized_constraint,
2576 adt_dtorck_constraint,
2577 trait_impls_of: trait_def::trait_impls_of_provider,
2578 relevant_trait_impls_for: trait_def::relevant_trait_impls_provider,
2585 /// A map for the local crate mapping each type to a vector of its
2586 /// inherent impls. This is not meant to be used outside of coherence;
2587 /// rather, you should request the vector for a specific type via
2588 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2589 /// (constructing this map requires touching the entire crate).
2590 #[derive(Clone, Debug)]
2591 pub struct CrateInherentImpls {
2592 pub inherent_impls: DefIdMap<Rc<Vec<DefId>>>,
2595 /// A set of constraints that need to be satisfied in order for
2596 /// a type to be valid for destruction.
2597 #[derive(Clone, Debug)]
2598 pub struct DtorckConstraint<'tcx> {
2599 /// Types that are required to be alive in order for this
2600 /// type to be valid for destruction.
2601 pub outlives: Vec<ty::subst::Kind<'tcx>>,
2602 /// Types that could not be resolved: projections and params.
2603 pub dtorck_types: Vec<Ty<'tcx>>,
2606 impl<'tcx> FromIterator<DtorckConstraint<'tcx>> for DtorckConstraint<'tcx>
2608 fn from_iter<I: IntoIterator<Item=DtorckConstraint<'tcx>>>(iter: I) -> Self {
2609 let mut result = Self::empty();
2611 for constraint in iter {
2612 result.outlives.extend(constraint.outlives);
2613 result.dtorck_types.extend(constraint.dtorck_types);
2621 impl<'tcx> DtorckConstraint<'tcx> {
2622 fn empty() -> DtorckConstraint<'tcx> {
2625 dtorck_types: vec![]
2629 fn dedup<'a>(&mut self) {
2630 let mut outlives = FxHashSet();
2631 let mut dtorck_types = FxHashSet();
2633 self.outlives.retain(|&val| outlives.replace(val).is_none());
2634 self.dtorck_types.retain(|&val| dtorck_types.replace(val).is_none());
2638 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
2639 pub struct SymbolName {
2640 // FIXME: we don't rely on interning or equality here - better have
2641 // this be a `&'tcx str`.
2642 pub name: InternedString
2645 impl Deref for SymbolName {
2648 fn deref(&self) -> &str { &self.name }
2651 impl fmt::Display for SymbolName {
2652 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2653 fmt::Display::fmt(&self.name, fmt)