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 hir::{map as hir_map, FreevarMap, TraitMap};
19 use hir::def::{Def, CtorKind, ExportMap};
20 use hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
21 use hir::map::DefPathData;
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;
28 use mir::GeneratorLayout;
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, GenSig, PolyFnSig, PolyGenSig};
64 pub use self::sty::{InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
65 pub use self::sty::{ClosureSubsts, GeneratorInterior, TypeAndMut};
66 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
67 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
68 pub use self::sty::{ExistentialProjection, PolyExistentialProjection, Const};
69 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
70 pub use self::sty::RegionKind;
71 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid, SkolemizedRegionVid};
72 pub use self::sty::BoundRegion::*;
73 pub use self::sty::InferTy::*;
74 pub use self::sty::RegionKind::*;
75 pub use self::sty::TypeVariants::*;
77 pub use self::binding::BindingMode;
78 pub use self::binding::BindingMode::*;
80 pub use self::context::{TyCtxt, GlobalArenas, tls, keep_local};
81 pub use self::context::{Lift, TypeckTables};
83 pub use self::instance::{Instance, InstanceDef};
85 pub use self::trait_def::TraitDef;
87 pub use self::maps::queries;
96 pub mod inhabitedness;
113 mod structural_impls;
118 /// The complete set of all analyses described in this module. This is
119 /// produced by the driver and fed to trans and later passes.
121 /// NB: These contents are being migrated into queries using the
122 /// *on-demand* infrastructure.
124 pub struct CrateAnalysis {
125 pub access_levels: Rc<AccessLevels>,
127 pub glob_map: Option<hir::GlobMap>,
131 pub struct Resolutions {
132 pub freevars: FreevarMap,
133 pub trait_map: TraitMap,
134 pub maybe_unused_trait_imports: NodeSet,
135 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
136 pub export_map: ExportMap,
139 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
140 pub enum AssociatedItemContainer {
141 TraitContainer(DefId),
142 ImplContainer(DefId),
145 impl AssociatedItemContainer {
146 pub fn id(&self) -> DefId {
148 TraitContainer(id) => id,
149 ImplContainer(id) => id,
154 /// The "header" of an impl is everything outside the body: a Self type, a trait
155 /// ref (in the case of a trait impl), and a set of predicates (from the
156 /// bounds/where clauses).
157 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
158 pub struct ImplHeader<'tcx> {
159 pub impl_def_id: DefId,
160 pub self_ty: Ty<'tcx>,
161 pub trait_ref: Option<TraitRef<'tcx>>,
162 pub predicates: Vec<Predicate<'tcx>>,
165 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
166 pub struct AssociatedItem {
169 pub kind: AssociatedKind,
171 pub defaultness: hir::Defaultness,
172 pub container: AssociatedItemContainer,
174 /// Whether this is a method with an explicit self
175 /// as its first argument, allowing method calls.
176 pub method_has_self_argument: bool,
179 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, RustcEncodable, RustcDecodable)]
180 pub enum AssociatedKind {
186 impl AssociatedItem {
187 pub fn def(&self) -> Def {
189 AssociatedKind::Const => Def::AssociatedConst(self.def_id),
190 AssociatedKind::Method => Def::Method(self.def_id),
191 AssociatedKind::Type => Def::AssociatedTy(self.def_id),
195 /// Tests whether the associated item admits a non-trivial implementation
197 pub fn relevant_for_never<'tcx>(&self) -> bool {
199 AssociatedKind::Const => true,
200 AssociatedKind::Type => true,
201 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
202 AssociatedKind::Method => !self.method_has_self_argument,
206 pub fn signature<'a, 'tcx>(&self, tcx: &TyCtxt<'a, 'tcx, 'tcx>) -> String {
208 ty::AssociatedKind::Method => {
209 // We skip the binder here because the binder would deanonymize all
210 // late-bound regions, and we don't want method signatures to show up
211 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
212 // regions just fine, showing `fn(&MyType)`.
213 format!("{}", tcx.fn_sig(self.def_id).skip_binder())
215 ty::AssociatedKind::Type => format!("type {};", self.name.to_string()),
216 ty::AssociatedKind::Const => {
217 format!("const {}: {:?};", self.name.to_string(), tcx.type_of(self.def_id))
223 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
224 pub enum Visibility {
225 /// Visible everywhere (including in other crates).
227 /// Visible only in the given crate-local module.
229 /// Not visible anywhere in the local crate. This is the visibility of private external items.
233 pub trait DefIdTree: Copy {
234 fn parent(self, id: DefId) -> Option<DefId>;
236 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
237 if descendant.krate != ancestor.krate {
241 while descendant != ancestor {
242 match self.parent(descendant) {
243 Some(parent) => descendant = parent,
244 None => return false,
251 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
252 fn parent(self, id: DefId) -> Option<DefId> {
253 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
258 pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
260 hir::Public => Visibility::Public,
261 hir::Visibility::Crate => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
262 hir::Visibility::Restricted { ref path, .. } => match path.def {
263 // If there is no resolution, `resolve` will have already reported an error, so
264 // assume that the visibility is public to avoid reporting more privacy errors.
265 Def::Err => Visibility::Public,
266 def => Visibility::Restricted(def.def_id()),
269 Visibility::Restricted(tcx.hir.get_module_parent(id))
274 /// Returns true if an item with this visibility is accessible from the given block.
275 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
276 let restriction = match self {
277 // Public items are visible everywhere.
278 Visibility::Public => return true,
279 // Private items from other crates are visible nowhere.
280 Visibility::Invisible => return false,
281 // Restricted items are visible in an arbitrary local module.
282 Visibility::Restricted(other) if other.krate != module.krate => return false,
283 Visibility::Restricted(module) => module,
286 tree.is_descendant_of(module, restriction)
289 /// Returns true if this visibility is at least as accessible as the given visibility
290 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
291 let vis_restriction = match vis {
292 Visibility::Public => return self == Visibility::Public,
293 Visibility::Invisible => return true,
294 Visibility::Restricted(module) => module,
297 self.is_accessible_from(vis_restriction, tree)
301 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
303 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
304 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
305 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
306 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
309 /// The crate variances map is computed during typeck and contains the
310 /// variance of every item in the local crate. You should not use it
311 /// directly, because to do so will make your pass dependent on the
312 /// HIR of every item in the local crate. Instead, use
313 /// `tcx.variances_of()` to get the variance for a *particular*
315 pub struct CrateVariancesMap {
316 /// This relation tracks the dependencies between the variance of
317 /// various items. In particular, if `a < b`, then the variance of
318 /// `a` depends on the sources of `b`.
319 pub dependencies: TransitiveRelation<DefId>,
321 /// For each item with generics, maps to a vector of the variance
322 /// of its generics. If an item has no generics, it will have no
324 pub variances: FxHashMap<DefId, Rc<Vec<ty::Variance>>>,
326 /// An empty vector, useful for cloning.
327 pub empty_variance: Rc<Vec<ty::Variance>>,
331 /// `a.xform(b)` combines the variance of a context with the
332 /// variance of a type with the following meaning. If we are in a
333 /// context with variance `a`, and we encounter a type argument in
334 /// a position with variance `b`, then `a.xform(b)` is the new
335 /// variance with which the argument appears.
341 /// Here, the "ambient" variance starts as covariant. `*mut T` is
342 /// invariant with respect to `T`, so the variance in which the
343 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
344 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
345 /// respect to its type argument `T`, and hence the variance of
346 /// the `i32` here is `Invariant.xform(Covariant)`, which results
347 /// (again) in `Invariant`.
351 /// fn(*const Vec<i32>, *mut Vec<i32)
353 /// The ambient variance is covariant. A `fn` type is
354 /// contravariant with respect to its parameters, so the variance
355 /// within which both pointer types appear is
356 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
357 /// T` is covariant with respect to `T`, so the variance within
358 /// which the first `Vec<i32>` appears is
359 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
360 /// is true for its `i32` argument. In the `*mut T` case, the
361 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
362 /// and hence the outermost type is `Invariant` with respect to
363 /// `Vec<i32>` (and its `i32` argument).
365 /// Source: Figure 1 of "Taming the Wildcards:
366 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
367 pub fn xform(self, v: ty::Variance) -> ty::Variance {
369 // Figure 1, column 1.
370 (ty::Covariant, ty::Covariant) => ty::Covariant,
371 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
372 (ty::Covariant, ty::Invariant) => ty::Invariant,
373 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
375 // Figure 1, column 2.
376 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
377 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
378 (ty::Contravariant, ty::Invariant) => ty::Invariant,
379 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
381 // Figure 1, column 3.
382 (ty::Invariant, _) => ty::Invariant,
384 // Figure 1, column 4.
385 (ty::Bivariant, _) => ty::Bivariant,
390 // Contains information needed to resolve types and (in the future) look up
391 // the types of AST nodes.
392 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
393 pub struct CReaderCacheKey {
398 // Flags that we track on types. These flags are propagated upwards
399 // through the type during type construction, so that we can quickly
400 // check whether the type has various kinds of types in it without
401 // recursing over the type itself.
403 pub struct TypeFlags: u32 {
404 const HAS_PARAMS = 1 << 0;
405 const HAS_SELF = 1 << 1;
406 const HAS_TY_INFER = 1 << 2;
407 const HAS_RE_INFER = 1 << 3;
408 const HAS_RE_SKOL = 1 << 4;
409 const HAS_RE_EARLY_BOUND = 1 << 5;
410 const HAS_FREE_REGIONS = 1 << 6;
411 const HAS_TY_ERR = 1 << 7;
412 const HAS_PROJECTION = 1 << 8;
414 // FIXME: Rename this to the actual property since it's used for generators too
415 const HAS_TY_CLOSURE = 1 << 9;
417 // true if there are "names" of types and regions and so forth
418 // that are local to a particular fn
419 const HAS_LOCAL_NAMES = 1 << 10;
421 // Present if the type belongs in a local type context.
422 // Only set for TyInfer other than Fresh.
423 const KEEP_IN_LOCAL_TCX = 1 << 11;
425 // Is there a projection that does not involve a bound region?
426 // Currently we can't normalize projections w/ bound regions.
427 const HAS_NORMALIZABLE_PROJECTION = 1 << 12;
429 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
430 TypeFlags::HAS_SELF.bits |
431 TypeFlags::HAS_RE_EARLY_BOUND.bits;
433 // Flags representing the nominal content of a type,
434 // computed by FlagsComputation. If you add a new nominal
435 // flag, it should be added here too.
436 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
437 TypeFlags::HAS_SELF.bits |
438 TypeFlags::HAS_TY_INFER.bits |
439 TypeFlags::HAS_RE_INFER.bits |
440 TypeFlags::HAS_RE_SKOL.bits |
441 TypeFlags::HAS_RE_EARLY_BOUND.bits |
442 TypeFlags::HAS_FREE_REGIONS.bits |
443 TypeFlags::HAS_TY_ERR.bits |
444 TypeFlags::HAS_PROJECTION.bits |
445 TypeFlags::HAS_TY_CLOSURE.bits |
446 TypeFlags::HAS_LOCAL_NAMES.bits |
447 TypeFlags::KEEP_IN_LOCAL_TCX.bits;
451 pub struct TyS<'tcx> {
452 pub sty: TypeVariants<'tcx>,
453 pub flags: TypeFlags,
455 // the maximal depth of any bound regions appearing in this type.
459 impl<'tcx> PartialEq for TyS<'tcx> {
461 fn eq(&self, other: &TyS<'tcx>) -> bool {
462 // (self as *const _) == (other as *const _)
463 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
466 impl<'tcx> Eq for TyS<'tcx> {}
468 impl<'tcx> Hash for TyS<'tcx> {
469 fn hash<H: Hasher>(&self, s: &mut H) {
470 (self as *const TyS).hash(s)
474 impl<'tcx> TyS<'tcx> {
475 pub fn is_primitive_ty(&self) -> bool {
477 TypeVariants::TyBool |
478 TypeVariants::TyChar |
479 TypeVariants::TyInt(_) |
480 TypeVariants::TyUint(_) |
481 TypeVariants::TyFloat(_) |
482 TypeVariants::TyInfer(InferTy::IntVar(_)) |
483 TypeVariants::TyInfer(InferTy::FloatVar(_)) |
484 TypeVariants::TyInfer(InferTy::FreshIntTy(_)) |
485 TypeVariants::TyInfer(InferTy::FreshFloatTy(_)) => true,
486 TypeVariants::TyRef(_, x) => x.ty.is_primitive_ty(),
491 pub fn is_suggestable(&self) -> bool {
493 TypeVariants::TyAnon(..) |
494 TypeVariants::TyFnDef(..) |
495 TypeVariants::TyFnPtr(..) |
496 TypeVariants::TyDynamic(..) |
497 TypeVariants::TyClosure(..) |
498 TypeVariants::TyInfer(..) |
499 TypeVariants::TyProjection(..) => false,
505 impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::TyS<'gcx> {
506 fn hash_stable<W: StableHasherResult>(&self,
507 hcx: &mut StableHashingContext<'gcx>,
508 hasher: &mut StableHasher<W>) {
512 // The other fields just provide fast access to information that is
513 // also contained in `sty`, so no need to hash them.
518 sty.hash_stable(hcx, hasher);
522 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
524 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
525 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
527 /// A wrapper for slices with the additional invariant
528 /// that the slice is interned and no other slice with
529 /// the same contents can exist in the same context.
530 /// This means we can use pointer + length for both
531 /// equality comparisons and hashing.
532 #[derive(Debug, RustcEncodable)]
533 pub struct Slice<T>([T]);
535 impl<T> PartialEq for Slice<T> {
537 fn eq(&self, other: &Slice<T>) -> bool {
538 (&self.0 as *const [T]) == (&other.0 as *const [T])
541 impl<T> Eq for Slice<T> {}
543 impl<T> Hash for Slice<T> {
544 fn hash<H: Hasher>(&self, s: &mut H) {
545 (self.as_ptr(), self.len()).hash(s)
549 impl<T> Deref for Slice<T> {
551 fn deref(&self) -> &[T] {
556 impl<'a, T> IntoIterator for &'a Slice<T> {
558 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
559 fn into_iter(self) -> Self::IntoIter {
564 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
567 pub fn empty<'a>() -> &'a Slice<T> {
569 mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
574 /// Upvars do not get their own node-id. Instead, we use the pair of
575 /// the original var id (that is, the root variable that is referenced
576 /// by the upvar) and the id of the closure expression.
577 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
579 pub var_id: hir::HirId,
580 pub closure_expr_id: DefIndex,
583 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
584 pub enum BorrowKind {
585 /// Data must be immutable and is aliasable.
588 /// Data must be immutable but not aliasable. This kind of borrow
589 /// cannot currently be expressed by the user and is used only in
590 /// implicit closure bindings. It is needed when the closure
591 /// is borrowing or mutating a mutable referent, e.g.:
593 /// let x: &mut isize = ...;
594 /// let y = || *x += 5;
596 /// If we were to try to translate this closure into a more explicit
597 /// form, we'd encounter an error with the code as written:
599 /// struct Env { x: & &mut isize }
600 /// let x: &mut isize = ...;
601 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
602 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
604 /// This is then illegal because you cannot mutate a `&mut` found
605 /// in an aliasable location. To solve, you'd have to translate with
606 /// an `&mut` borrow:
608 /// struct Env { x: & &mut isize }
609 /// let x: &mut isize = ...;
610 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
611 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
613 /// Now the assignment to `**env.x` is legal, but creating a
614 /// mutable pointer to `x` is not because `x` is not mutable. We
615 /// could fix this by declaring `x` as `let mut x`. This is ok in
616 /// user code, if awkward, but extra weird for closures, since the
617 /// borrow is hidden.
619 /// So we introduce a "unique imm" borrow -- the referent is
620 /// immutable, but not aliasable. This solves the problem. For
621 /// simplicity, we don't give users the way to express this
622 /// borrow, it's just used when translating closures.
625 /// Data is mutable and not aliasable.
629 /// Information describing the capture of an upvar. This is computed
630 /// during `typeck`, specifically by `regionck`.
631 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
632 pub enum UpvarCapture<'tcx> {
633 /// Upvar is captured by value. This is always true when the
634 /// closure is labeled `move`, but can also be true in other cases
635 /// depending on inference.
638 /// Upvar is captured by reference.
639 ByRef(UpvarBorrow<'tcx>),
642 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
643 pub struct UpvarBorrow<'tcx> {
644 /// The kind of borrow: by-ref upvars have access to shared
645 /// immutable borrows, which are not part of the normal language
647 pub kind: BorrowKind,
649 /// Region of the resulting reference.
650 pub region: ty::Region<'tcx>,
653 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
655 #[derive(Copy, Clone)]
656 pub struct ClosureUpvar<'tcx> {
662 #[derive(Clone, Copy, PartialEq)]
663 pub enum IntVarValue {
665 UintType(ast::UintTy),
668 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
669 pub struct TypeParameterDef {
673 pub has_default: bool,
674 pub object_lifetime_default: ObjectLifetimeDefault,
676 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
677 /// on generic parameter `T`, asserts data behind the parameter
678 /// `T` won't be accessed during the parent type's `Drop` impl.
679 pub pure_wrt_drop: bool,
681 pub synthetic: Option<hir::SyntheticTyParamKind>,
684 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
685 pub struct RegionParameterDef {
690 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
691 /// on generic parameter `'a`, asserts data of lifetime `'a`
692 /// won't be accessed during the parent type's `Drop` impl.
693 pub pure_wrt_drop: bool,
696 impl RegionParameterDef {
697 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
698 ty::EarlyBoundRegion {
705 pub fn to_bound_region(&self) -> ty::BoundRegion {
706 self.to_early_bound_region_data().to_bound_region()
710 impl ty::EarlyBoundRegion {
711 pub fn to_bound_region(&self) -> ty::BoundRegion {
712 ty::BoundRegion::BrNamed(self.def_id, self.name)
716 /// Information about the formal type/lifetime parameters associated
717 /// with an item or method. Analogous to hir::Generics.
719 /// Note that in the presence of a `Self` parameter, the ordering here
720 /// is different from the ordering in a Substs. Substs are ordered as
721 /// Self, *Regions, *Other Type Params, (...child generics)
722 /// while this struct is ordered as
723 /// regions = Regions
724 /// types = [Self, *Other Type Params]
725 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
726 pub struct Generics {
727 pub parent: Option<DefId>,
728 pub parent_regions: u32,
729 pub parent_types: u32,
730 pub regions: Vec<RegionParameterDef>,
731 pub types: Vec<TypeParameterDef>,
733 /// Reverse map to each `TypeParameterDef`'s `index` field, from
734 /// `def_id.index` (`def_id.krate` is the same as the item's).
735 pub type_param_to_index: BTreeMap<DefIndex, u32>,
738 pub has_late_bound_regions: Option<Span>,
741 impl<'a, 'gcx, 'tcx> Generics {
742 pub fn parent_count(&self) -> usize {
743 self.parent_regions as usize + self.parent_types as usize
746 pub fn own_count(&self) -> usize {
747 self.regions.len() + self.types.len()
750 pub fn count(&self) -> usize {
751 self.parent_count() + self.own_count()
754 pub fn region_param(&'tcx self,
755 param: &EarlyBoundRegion,
756 tcx: TyCtxt<'a, 'gcx, 'tcx>)
757 -> &'tcx RegionParameterDef
759 if let Some(index) = param.index.checked_sub(self.parent_count() as u32) {
760 &self.regions[index as usize - self.has_self as usize]
762 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
763 .region_param(param, tcx)
767 /// Returns the `TypeParameterDef` associated with this `ParamTy`.
768 pub fn type_param(&'tcx self,
770 tcx: TyCtxt<'a, 'gcx, 'tcx>)
771 -> &TypeParameterDef {
772 if let Some(idx) = param.idx.checked_sub(self.parent_count() as u32) {
773 // non-Self type parameters are always offset by exactly
774 // `self.regions.len()`. In the absence of a Self, this is obvious,
775 // but even in the absence of a `Self` we just have to "compensate"
778 // For example, for `trait Foo<'a, 'b, T1, T2>`, the
786 // And it can be seen that to move from a substs offset to a
787 // generics offset you just have to offset by the number of regions.
788 let type_param_offset = self.regions.len();
789 if let Some(idx) = (idx as usize).checked_sub(type_param_offset) {
790 assert!(!(self.has_self && idx == 0));
793 assert!(self.has_self && idx == 0);
797 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
798 .type_param(param, tcx)
803 /// Bounds on generics.
804 #[derive(Clone, Default)]
805 pub struct GenericPredicates<'tcx> {
806 pub parent: Option<DefId>,
807 pub predicates: Vec<Predicate<'tcx>>,
810 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
811 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
813 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
814 pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
815 -> InstantiatedPredicates<'tcx> {
816 let mut instantiated = InstantiatedPredicates::empty();
817 self.instantiate_into(tcx, &mut instantiated, substs);
820 pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
821 -> InstantiatedPredicates<'tcx> {
822 InstantiatedPredicates {
823 predicates: self.predicates.subst(tcx, substs)
827 fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
828 instantiated: &mut InstantiatedPredicates<'tcx>,
829 substs: &Substs<'tcx>) {
830 if let Some(def_id) = self.parent {
831 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
833 instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
836 pub fn instantiate_identity(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
837 -> InstantiatedPredicates<'tcx> {
838 let mut instantiated = InstantiatedPredicates::empty();
839 self.instantiate_identity_into(tcx, &mut instantiated);
843 fn instantiate_identity_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
844 instantiated: &mut InstantiatedPredicates<'tcx>) {
845 if let Some(def_id) = self.parent {
846 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
848 instantiated.predicates.extend(&self.predicates)
851 pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
852 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
853 -> InstantiatedPredicates<'tcx>
855 assert_eq!(self.parent, None);
856 InstantiatedPredicates {
857 predicates: self.predicates.iter().map(|pred| {
858 pred.subst_supertrait(tcx, poly_trait_ref)
864 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
865 pub enum Predicate<'tcx> {
866 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
867 /// the `Self` type of the trait reference and `A`, `B`, and `C`
868 /// would be the type parameters.
869 Trait(PolyTraitPredicate<'tcx>),
871 /// where `T1 == T2`.
872 Equate(PolyEquatePredicate<'tcx>),
875 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
878 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
880 /// where <T as TraitRef>::Name == X, approximately.
881 /// See `ProjectionPredicate` struct for details.
882 Projection(PolyProjectionPredicate<'tcx>),
885 WellFormed(Ty<'tcx>),
887 /// trait must be object-safe
890 /// No direct syntax. May be thought of as `where T : FnFoo<...>`
891 /// for some substitutions `...` and T being a closure type.
892 /// Satisfied (or refuted) once we know the closure's kind.
893 ClosureKind(DefId, ClosureKind),
896 Subtype(PolySubtypePredicate<'tcx>),
898 /// Constant initializer must evaluate successfully.
899 ConstEvaluatable(DefId, &'tcx Substs<'tcx>),
902 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
903 /// Performs a substitution suitable for going from a
904 /// poly-trait-ref to supertraits that must hold if that
905 /// poly-trait-ref holds. This is slightly different from a normal
906 /// substitution in terms of what happens with bound regions. See
907 /// lengthy comment below for details.
908 pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
909 trait_ref: &ty::PolyTraitRef<'tcx>)
910 -> ty::Predicate<'tcx>
912 // The interaction between HRTB and supertraits is not entirely
913 // obvious. Let me walk you (and myself) through an example.
915 // Let's start with an easy case. Consider two traits:
917 // trait Foo<'a> : Bar<'a,'a> { }
918 // trait Bar<'b,'c> { }
920 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
921 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
922 // knew that `Foo<'x>` (for any 'x) then we also know that
923 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
924 // normal substitution.
926 // In terms of why this is sound, the idea is that whenever there
927 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
928 // holds. So if there is an impl of `T:Foo<'a>` that applies to
929 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
932 // Another example to be careful of is this:
934 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
935 // trait Bar1<'b,'c> { }
937 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
938 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
939 // reason is similar to the previous example: any impl of
940 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
941 // basically we would want to collapse the bound lifetimes from
942 // the input (`trait_ref`) and the supertraits.
944 // To achieve this in practice is fairly straightforward. Let's
945 // consider the more complicated scenario:
947 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
948 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
949 // where both `'x` and `'b` would have a DB index of 1.
950 // The substitution from the input trait-ref is therefore going to be
951 // `'a => 'x` (where `'x` has a DB index of 1).
952 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
953 // early-bound parameter and `'b' is a late-bound parameter with a
955 // - If we replace `'a` with `'x` from the input, it too will have
956 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
957 // just as we wanted.
959 // There is only one catch. If we just apply the substitution `'a
960 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
961 // adjust the DB index because we substituting into a binder (it
962 // tries to be so smart...) resulting in `for<'x> for<'b>
963 // Bar1<'x,'b>` (we have no syntax for this, so use your
964 // imagination). Basically the 'x will have DB index of 2 and 'b
965 // will have DB index of 1. Not quite what we want. So we apply
966 // the substitution to the *contents* of the trait reference,
967 // rather than the trait reference itself (put another way, the
968 // substitution code expects equal binding levels in the values
969 // from the substitution and the value being substituted into, and
970 // this trick achieves that).
972 let substs = &trait_ref.0.substs;
974 Predicate::Trait(ty::Binder(ref data)) =>
975 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
976 Predicate::Equate(ty::Binder(ref data)) =>
977 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
978 Predicate::Subtype(ty::Binder(ref data)) =>
979 Predicate::Subtype(ty::Binder(data.subst(tcx, substs))),
980 Predicate::RegionOutlives(ty::Binder(ref data)) =>
981 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
982 Predicate::TypeOutlives(ty::Binder(ref data)) =>
983 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
984 Predicate::Projection(ty::Binder(ref data)) =>
985 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
986 Predicate::WellFormed(data) =>
987 Predicate::WellFormed(data.subst(tcx, substs)),
988 Predicate::ObjectSafe(trait_def_id) =>
989 Predicate::ObjectSafe(trait_def_id),
990 Predicate::ClosureKind(closure_def_id, kind) =>
991 Predicate::ClosureKind(closure_def_id, kind),
992 Predicate::ConstEvaluatable(def_id, const_substs) =>
993 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs)),
998 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
999 pub struct TraitPredicate<'tcx> {
1000 pub trait_ref: TraitRef<'tcx>
1002 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1004 impl<'tcx> TraitPredicate<'tcx> {
1005 pub fn def_id(&self) -> DefId {
1006 self.trait_ref.def_id
1009 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
1010 self.trait_ref.input_types()
1013 pub fn self_ty(&self) -> Ty<'tcx> {
1014 self.trait_ref.self_ty()
1018 impl<'tcx> PolyTraitPredicate<'tcx> {
1019 pub fn def_id(&self) -> DefId {
1020 // ok to skip binder since trait def-id does not care about regions
1025 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1026 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
1027 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
1029 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1030 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
1031 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
1032 pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<ty::Region<'tcx>,
1034 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1036 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1037 pub struct SubtypePredicate<'tcx> {
1038 pub a_is_expected: bool,
1042 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1044 /// This kind of predicate has no *direct* correspondent in the
1045 /// syntax, but it roughly corresponds to the syntactic forms:
1047 /// 1. `T : TraitRef<..., Item=Type>`
1048 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1050 /// In particular, form #1 is "desugared" to the combination of a
1051 /// normal trait predicate (`T : TraitRef<...>`) and one of these
1052 /// predicates. Form #2 is a broader form in that it also permits
1053 /// equality between arbitrary types. Processing an instance of Form
1054 /// #2 eventually yields one of these `ProjectionPredicate`
1055 /// instances to normalize the LHS.
1056 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1057 pub struct ProjectionPredicate<'tcx> {
1058 pub projection_ty: ProjectionTy<'tcx>,
1062 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1064 impl<'tcx> PolyProjectionPredicate<'tcx> {
1065 pub fn to_poly_trait_ref(&self, tcx: TyCtxt) -> PolyTraitRef<'tcx> {
1066 // Note: unlike with TraitRef::to_poly_trait_ref(),
1067 // self.0.trait_ref is permitted to have escaping regions.
1068 // This is because here `self` has a `Binder` and so does our
1069 // return value, so we are preserving the number of binding
1071 ty::Binder(self.0.projection_ty.trait_ref(tcx))
1074 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1075 Binder(self.skip_binder().ty) // preserves binding levels
1079 pub trait ToPolyTraitRef<'tcx> {
1080 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1083 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1084 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1085 assert!(!self.has_escaping_regions());
1086 ty::Binder(self.clone())
1090 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1091 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1092 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1096 pub trait ToPredicate<'tcx> {
1097 fn to_predicate(&self) -> Predicate<'tcx>;
1100 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1101 fn to_predicate(&self) -> Predicate<'tcx> {
1102 // we're about to add a binder, so let's check that we don't
1103 // accidentally capture anything, or else that might be some
1104 // weird debruijn accounting.
1105 assert!(!self.has_escaping_regions());
1107 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1108 trait_ref: self.clone()
1113 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1114 fn to_predicate(&self) -> Predicate<'tcx> {
1115 ty::Predicate::Trait(self.to_poly_trait_predicate())
1119 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
1120 fn to_predicate(&self) -> Predicate<'tcx> {
1121 Predicate::Equate(self.clone())
1125 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1126 fn to_predicate(&self) -> Predicate<'tcx> {
1127 Predicate::RegionOutlives(self.clone())
1131 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1132 fn to_predicate(&self) -> Predicate<'tcx> {
1133 Predicate::TypeOutlives(self.clone())
1137 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1138 fn to_predicate(&self) -> Predicate<'tcx> {
1139 Predicate::Projection(self.clone())
1143 impl<'tcx> Predicate<'tcx> {
1144 /// Iterates over the types in this predicate. Note that in all
1145 /// cases this is skipping over a binder, so late-bound regions
1146 /// with depth 0 are bound by the predicate.
1147 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1148 let vec: Vec<_> = match *self {
1149 ty::Predicate::Trait(ref data) => {
1150 data.skip_binder().input_types().collect()
1152 ty::Predicate::Equate(ty::Binder(ref data)) => {
1153 vec![data.0, data.1]
1155 ty::Predicate::Subtype(ty::Binder(SubtypePredicate { a, b, a_is_expected: _ })) => {
1158 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1161 ty::Predicate::RegionOutlives(..) => {
1164 ty::Predicate::Projection(ref data) => {
1165 data.0.projection_ty.substs.types().chain(Some(data.0.ty)).collect()
1167 ty::Predicate::WellFormed(data) => {
1170 ty::Predicate::ObjectSafe(_trait_def_id) => {
1173 ty::Predicate::ClosureKind(_closure_def_id, _kind) => {
1176 ty::Predicate::ConstEvaluatable(_, substs) => {
1177 substs.types().collect()
1181 // The only reason to collect into a vector here is that I was
1182 // too lazy to make the full (somewhat complicated) iterator
1183 // type that would be needed here. But I wanted this fn to
1184 // return an iterator conceptually, rather than a `Vec`, so as
1185 // to be closer to `Ty::walk`.
1189 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1191 Predicate::Trait(ref t) => {
1192 Some(t.to_poly_trait_ref())
1194 Predicate::Projection(..) |
1195 Predicate::Equate(..) |
1196 Predicate::Subtype(..) |
1197 Predicate::RegionOutlives(..) |
1198 Predicate::WellFormed(..) |
1199 Predicate::ObjectSafe(..) |
1200 Predicate::ClosureKind(..) |
1201 Predicate::TypeOutlives(..) |
1202 Predicate::ConstEvaluatable(..) => {
1209 /// Represents the bounds declared on a particular set of type
1210 /// parameters. Should eventually be generalized into a flag list of
1211 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
1212 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1213 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1214 /// the `GenericPredicates` are expressed in terms of the bound type
1215 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1216 /// represented a set of bounds for some particular instantiation,
1217 /// meaning that the generic parameters have been substituted with
1222 /// struct Foo<T,U:Bar<T>> { ... }
1224 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1225 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1226 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1227 /// [usize:Bar<isize>]]`.
1229 pub struct InstantiatedPredicates<'tcx> {
1230 pub predicates: Vec<Predicate<'tcx>>,
1233 impl<'tcx> InstantiatedPredicates<'tcx> {
1234 pub fn empty() -> InstantiatedPredicates<'tcx> {
1235 InstantiatedPredicates { predicates: vec![] }
1238 pub fn is_empty(&self) -> bool {
1239 self.predicates.is_empty()
1243 /// When type checking, we use the `ParamEnv` to track
1244 /// details about the set of where-clauses that are in scope at this
1245 /// particular point.
1246 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1247 pub struct ParamEnv<'tcx> {
1248 /// Obligations that the caller must satisfy. This is basically
1249 /// the set of bounds on the in-scope type parameters, translated
1250 /// into Obligations, and elaborated and normalized.
1251 pub caller_bounds: &'tcx Slice<ty::Predicate<'tcx>>,
1253 /// Typically, this is `Reveal::UserFacing`, but during trans we
1254 /// want `Reveal::All` -- note that this is always paired with an
1255 /// empty environment. To get that, use `ParamEnv::reveal()`.
1256 pub reveal: traits::Reveal,
1259 impl<'tcx> ParamEnv<'tcx> {
1260 /// Creates a suitable environment in which to perform trait
1261 /// queries on the given value. This will either be `self` *or*
1262 /// the empty environment, depending on whether `value` references
1263 /// type parameters that are in scope. (If it doesn't, then any
1264 /// judgements should be completely independent of the context,
1265 /// and hence we can safely use the empty environment so as to
1266 /// enable more sharing across functions.)
1268 /// NB: This is a mildly dubious thing to do, in that a function
1269 /// (or other environment) might have wacky where-clauses like
1270 /// `where Box<u32>: Copy`, which are clearly never
1271 /// satisfiable. The code will at present ignore these,
1272 /// effectively, when type-checking the body of said
1273 /// function. This preserves existing behavior in any
1274 /// case. --nmatsakis
1275 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1276 assert!(!value.needs_infer());
1277 if value.has_param_types() || value.has_self_ty() {
1284 param_env: ParamEnv::empty(self.reveal),
1291 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1292 pub struct ParamEnvAnd<'tcx, T> {
1293 pub param_env: ParamEnv<'tcx>,
1297 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1298 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1299 (self.param_env, self.value)
1303 impl<'gcx, T> HashStable<StableHashingContext<'gcx>> for ParamEnvAnd<'gcx, T>
1304 where T: HashStable<StableHashingContext<'gcx>>
1306 fn hash_stable<W: StableHasherResult>(&self,
1307 hcx: &mut StableHashingContext<'gcx>,
1308 hasher: &mut StableHasher<W>) {
1314 param_env.hash_stable(hcx, hasher);
1315 value.hash_stable(hcx, hasher);
1319 #[derive(Copy, Clone, Debug)]
1320 pub struct Destructor {
1321 /// The def-id of the destructor method
1326 pub struct AdtFlags: u32 {
1327 const NO_ADT_FLAGS = 0;
1328 const IS_ENUM = 1 << 0;
1329 const IS_PHANTOM_DATA = 1 << 1;
1330 const IS_FUNDAMENTAL = 1 << 2;
1331 const IS_UNION = 1 << 3;
1332 const IS_BOX = 1 << 4;
1337 pub struct VariantDef {
1338 /// The variant's DefId. If this is a tuple-like struct,
1339 /// this is the DefId of the struct's ctor.
1341 pub name: Name, // struct's name if this is a struct
1342 pub discr: VariantDiscr,
1343 pub fields: Vec<FieldDef>,
1344 pub ctor_kind: CtorKind,
1347 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1348 pub enum VariantDiscr {
1349 /// Explicit value for this variant, i.e. `X = 123`.
1350 /// The `DefId` corresponds to the embedded constant.
1353 /// The previous variant's discriminant plus one.
1354 /// For efficiency reasons, the distance from the
1355 /// last `Explicit` discriminant is being stored,
1356 /// or `0` for the first variant, if it has none.
1361 pub struct FieldDef {
1364 pub vis: Visibility,
1367 /// The definition of an abstract data type - a struct or enum.
1369 /// These are all interned (by intern_adt_def) into the adt_defs
1373 pub variants: Vec<VariantDef>,
1375 pub repr: ReprOptions,
1378 impl PartialEq for AdtDef {
1379 // AdtDef are always interned and this is part of TyS equality
1381 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1384 impl Eq for AdtDef {}
1386 impl Hash for AdtDef {
1388 fn hash<H: Hasher>(&self, s: &mut H) {
1389 (self as *const AdtDef).hash(s)
1393 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1394 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1399 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1402 impl<'gcx> HashStable<StableHashingContext<'gcx>> for AdtDef {
1403 fn hash_stable<W: StableHasherResult>(&self,
1404 hcx: &mut StableHashingContext<'gcx>,
1405 hasher: &mut StableHasher<W>) {
1413 did.hash_stable(hcx, hasher);
1414 variants.hash_stable(hcx, hasher);
1415 flags.hash_stable(hcx, hasher);
1416 repr.hash_stable(hcx, hasher);
1420 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1421 pub enum AdtKind { Struct, Union, Enum }
1424 #[derive(RustcEncodable, RustcDecodable, Default)]
1425 pub struct ReprFlags: u8 {
1426 const IS_C = 1 << 0;
1427 const IS_PACKED = 1 << 1;
1428 const IS_SIMD = 1 << 2;
1429 // Internal only for now. If true, don't reorder fields.
1430 const IS_LINEAR = 1 << 3;
1432 // Any of these flags being set prevent field reordering optimisation.
1433 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1434 ReprFlags::IS_PACKED.bits |
1435 ReprFlags::IS_SIMD.bits |
1436 ReprFlags::IS_LINEAR.bits;
1440 impl_stable_hash_for!(struct ReprFlags {
1446 /// Represents the repr options provided by the user,
1447 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1448 pub struct ReprOptions {
1449 pub int: Option<attr::IntType>,
1451 pub flags: ReprFlags,
1454 impl_stable_hash_for!(struct ReprOptions {
1461 pub fn new(tcx: TyCtxt, did: DefId) -> ReprOptions {
1462 let mut flags = ReprFlags::empty();
1463 let mut size = None;
1464 let mut max_align = 0;
1465 for attr in tcx.get_attrs(did).iter() {
1466 for r in attr::find_repr_attrs(tcx.sess.diagnostic(), attr) {
1467 flags.insert(match r {
1468 attr::ReprExtern => ReprFlags::IS_C,
1469 attr::ReprPacked => ReprFlags::IS_PACKED,
1470 attr::ReprSimd => ReprFlags::IS_SIMD,
1471 attr::ReprInt(i) => {
1475 attr::ReprAlign(align) => {
1476 max_align = cmp::max(align, max_align);
1483 // FIXME(eddyb) This is deprecated and should be removed.
1484 if tcx.has_attr(did, "simd") {
1485 flags.insert(ReprFlags::IS_SIMD);
1488 // This is here instead of layout because the choice must make it into metadata.
1489 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.item_path_str(did))) {
1490 flags.insert(ReprFlags::IS_LINEAR);
1492 ReprOptions { int: size, align: max_align, flags: flags }
1496 pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
1498 pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
1500 pub fn packed(&self) -> bool { self.flags.contains(ReprFlags::IS_PACKED) }
1502 pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
1504 pub fn discr_type(&self) -> attr::IntType {
1505 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Is))
1508 /// Returns true if this `#[repr()]` should inhabit "smart enum
1509 /// layout" optimizations, such as representing `Foo<&T>` as a
1511 pub fn inhibit_enum_layout_opt(&self) -> bool {
1512 self.c() || self.int.is_some()
1516 impl<'a, 'gcx, 'tcx> AdtDef {
1520 variants: Vec<VariantDef>,
1521 repr: ReprOptions) -> Self {
1522 let mut flags = AdtFlags::NO_ADT_FLAGS;
1523 let attrs = tcx.get_attrs(did);
1524 if attr::contains_name(&attrs, "fundamental") {
1525 flags = flags | AdtFlags::IS_FUNDAMENTAL;
1527 if Some(did) == tcx.lang_items().phantom_data() {
1528 flags = flags | AdtFlags::IS_PHANTOM_DATA;
1530 if Some(did) == tcx.lang_items().owned_box() {
1531 flags = flags | AdtFlags::IS_BOX;
1534 AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1535 AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1536 AdtKind::Struct => {}
1547 pub fn is_struct(&self) -> bool {
1548 !self.is_union() && !self.is_enum()
1552 pub fn is_union(&self) -> bool {
1553 self.flags.intersects(AdtFlags::IS_UNION)
1557 pub fn is_enum(&self) -> bool {
1558 self.flags.intersects(AdtFlags::IS_ENUM)
1561 /// Returns the kind of the ADT - Struct or Enum.
1563 pub fn adt_kind(&self) -> AdtKind {
1566 } else if self.is_union() {
1573 pub fn descr(&self) -> &'static str {
1574 match self.adt_kind() {
1575 AdtKind::Struct => "struct",
1576 AdtKind::Union => "union",
1577 AdtKind::Enum => "enum",
1581 pub fn variant_descr(&self) -> &'static str {
1582 match self.adt_kind() {
1583 AdtKind::Struct => "struct",
1584 AdtKind::Union => "union",
1585 AdtKind::Enum => "variant",
1589 /// Returns whether this type is #[fundamental] for the purposes
1590 /// of coherence checking.
1592 pub fn is_fundamental(&self) -> bool {
1593 self.flags.intersects(AdtFlags::IS_FUNDAMENTAL)
1596 /// Returns true if this is PhantomData<T>.
1598 pub fn is_phantom_data(&self) -> bool {
1599 self.flags.intersects(AdtFlags::IS_PHANTOM_DATA)
1602 /// Returns true if this is Box<T>.
1604 pub fn is_box(&self) -> bool {
1605 self.flags.intersects(AdtFlags::IS_BOX)
1608 /// Returns whether this type has a destructor.
1609 pub fn has_dtor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1610 self.destructor(tcx).is_some()
1613 /// Asserts this is a struct and returns the struct's unique
1615 pub fn struct_variant(&self) -> &VariantDef {
1616 assert!(!self.is_enum());
1621 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1622 tcx.predicates_of(self.did)
1625 /// Returns an iterator over all fields contained
1628 pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1629 self.variants.iter().flat_map(|v| v.fields.iter())
1633 pub fn is_univariant(&self) -> bool {
1634 self.variants.len() == 1
1637 pub fn is_payloadfree(&self) -> bool {
1638 !self.variants.is_empty() &&
1639 self.variants.iter().all(|v| v.fields.is_empty())
1642 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1645 .find(|v| v.did == vid)
1646 .expect("variant_with_id: unknown variant")
1649 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1652 .position(|v| v.did == vid)
1653 .expect("variant_index_with_id: unknown variant")
1656 pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1658 Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1659 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1660 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.struct_variant(),
1661 _ => bug!("unexpected def {:?} in variant_of_def", def)
1666 pub fn discriminants(&'a self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
1667 -> impl Iterator<Item=ConstInt> + 'a {
1668 let param_env = ParamEnv::empty(traits::Reveal::UserFacing);
1669 let repr_type = self.repr.discr_type();
1670 let initial = repr_type.initial_discriminant(tcx.global_tcx());
1671 let mut prev_discr = None::<ConstInt>;
1672 self.variants.iter().map(move |v| {
1673 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr());
1674 if let VariantDiscr::Explicit(expr_did) = v.discr {
1675 let substs = Substs::identity_for_item(tcx.global_tcx(), expr_did);
1676 match tcx.const_eval(param_env.and((expr_did, substs))) {
1677 Ok(&ty::Const { val: ConstVal::Integral(v), .. }) => {
1681 if !expr_did.is_local() {
1682 span_bug!(tcx.def_span(expr_did),
1683 "variant discriminant evaluation succeeded \
1684 in its crate but failed locally: {:?}", err);
1689 prev_discr = Some(discr);
1695 /// Compute the discriminant value used by a specific variant.
1696 /// Unlike `discriminants`, this is (amortized) constant-time,
1697 /// only doing at most one query for evaluating an explicit
1698 /// discriminant (the last one before the requested variant),
1699 /// assuming there are no constant-evaluation errors there.
1700 pub fn discriminant_for_variant(&self,
1701 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1702 variant_index: usize)
1704 let param_env = ParamEnv::empty(traits::Reveal::UserFacing);
1705 let repr_type = self.repr.discr_type();
1706 let mut explicit_value = repr_type.initial_discriminant(tcx.global_tcx());
1707 let mut explicit_index = variant_index;
1709 match self.variants[explicit_index].discr {
1710 ty::VariantDiscr::Relative(0) => break,
1711 ty::VariantDiscr::Relative(distance) => {
1712 explicit_index -= distance;
1714 ty::VariantDiscr::Explicit(expr_did) => {
1715 let substs = Substs::identity_for_item(tcx.global_tcx(), expr_did);
1716 match tcx.const_eval(param_env.and((expr_did, substs))) {
1717 Ok(&ty::Const { val: ConstVal::Integral(v), .. }) => {
1722 if !expr_did.is_local() {
1723 span_bug!(tcx.def_span(expr_did),
1724 "variant discriminant evaluation succeeded \
1725 in its crate but failed locally: {:?}", err);
1727 if explicit_index == 0 {
1730 explicit_index -= 1;
1736 let discr = explicit_value.to_u128_unchecked()
1737 .wrapping_add((variant_index - explicit_index) as u128);
1739 attr::UnsignedInt(ty) => {
1740 ConstInt::new_unsigned_truncating(discr, ty,
1741 tcx.sess.target.usize_ty)
1743 attr::SignedInt(ty) => {
1744 ConstInt::new_signed_truncating(discr as i128, ty,
1745 tcx.sess.target.isize_ty)
1750 pub fn destructor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Destructor> {
1751 tcx.adt_destructor(self.did)
1754 /// Returns a list of types such that `Self: Sized` if and only
1755 /// if that type is Sized, or `TyErr` if this type is recursive.
1757 /// Oddly enough, checking that the sized-constraint is Sized is
1758 /// actually more expressive than checking all members:
1759 /// the Sized trait is inductive, so an associated type that references
1760 /// Self would prevent its containing ADT from being Sized.
1762 /// Due to normalization being eager, this applies even if
1763 /// the associated type is behind a pointer, e.g. issue #31299.
1764 pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] {
1765 match queries::adt_sized_constraint::try_get(tcx, DUMMY_SP, self.did) {
1768 debug!("adt_sized_constraint: {:?} is recursive", self);
1769 // This should be reported as an error by `check_representable`.
1771 // Consider the type as Sized in the meanwhile to avoid
1772 // further errors. Delay our `bug` diagnostic here to get
1773 // emitted later as well in case we accidentally otherwise don't
1776 tcx.intern_type_list(&[tcx.types.err])
1781 fn sized_constraint_for_ty(&self,
1782 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1785 let result = match ty.sty {
1786 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
1787 TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
1788 TyArray(..) | TyClosure(..) | TyGenerator(..) | TyNever => {
1792 TyStr | TyDynamic(..) | TySlice(_) | TyError => {
1793 // these are never sized - return the target type
1797 TyTuple(ref tys, _) => {
1800 Some(ty) => self.sized_constraint_for_ty(tcx, ty)
1804 TyAdt(adt, substs) => {
1806 let adt_tys = adt.sized_constraint(tcx);
1807 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
1810 .map(|ty| ty.subst(tcx, substs))
1811 .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
1815 TyProjection(..) | TyAnon(..) => {
1816 // must calculate explicitly.
1817 // FIXME: consider special-casing always-Sized projections
1822 // perf hack: if there is a `T: Sized` bound, then
1823 // we know that `T` is Sized and do not need to check
1826 let sized_trait = match tcx.lang_items().sized_trait() {
1828 _ => return vec![ty]
1830 let sized_predicate = Binder(TraitRef {
1831 def_id: sized_trait,
1832 substs: tcx.mk_substs_trait(ty, &[])
1834 let predicates = tcx.predicates_of(self.did).predicates;
1835 if predicates.into_iter().any(|p| p == sized_predicate) {
1843 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
1847 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
1852 impl<'a, 'gcx, 'tcx> VariantDef {
1854 pub fn find_field_named(&self, name: ast::Name) -> Option<&FieldDef> {
1855 self.index_of_field_named(name).map(|index| &self.fields[index])
1858 pub fn index_of_field_named(&self, name: ast::Name) -> Option<usize> {
1859 if let Some(index) = self.fields.iter().position(|f| f.name == name) {
1862 let mut ident = name.to_ident();
1863 while ident.ctxt != SyntaxContext::empty() {
1864 ident.ctxt.remove_mark();
1865 if let Some(field) = self.fields.iter().position(|f| f.name.to_ident() == ident) {
1873 pub fn field_named(&self, name: ast::Name) -> &FieldDef {
1874 self.find_field_named(name).unwrap()
1878 impl<'a, 'gcx, 'tcx> FieldDef {
1879 pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1880 tcx.type_of(self.did).subst(tcx, subst)
1884 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1885 pub enum ClosureKind {
1886 // Warning: Ordering is significant here! The ordering is chosen
1887 // because the trait Fn is a subtrait of FnMut and so in turn, and
1888 // hence we order it so that Fn < FnMut < FnOnce.
1894 impl<'a, 'tcx> ClosureKind {
1895 pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
1897 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
1898 ClosureKind::FnMut => {
1899 tcx.require_lang_item(FnMutTraitLangItem)
1901 ClosureKind::FnOnce => {
1902 tcx.require_lang_item(FnOnceTraitLangItem)
1907 /// True if this a type that impls this closure kind
1908 /// must also implement `other`.
1909 pub fn extends(self, other: ty::ClosureKind) -> bool {
1910 match (self, other) {
1911 (ClosureKind::Fn, ClosureKind::Fn) => true,
1912 (ClosureKind::Fn, ClosureKind::FnMut) => true,
1913 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
1914 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
1915 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
1916 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
1922 impl<'tcx> TyS<'tcx> {
1923 /// Iterator that walks `self` and any types reachable from
1924 /// `self`, in depth-first order. Note that just walks the types
1925 /// that appear in `self`, it does not descend into the fields of
1926 /// structs or variants. For example:
1929 /// isize => { isize }
1930 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
1931 /// [isize] => { [isize], isize }
1933 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
1934 TypeWalker::new(self)
1937 /// Iterator that walks the immediate children of `self`. Hence
1938 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
1939 /// (but not `i32`, like `walk`).
1940 pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
1941 walk::walk_shallow(self)
1944 /// Walks `ty` and any types appearing within `ty`, invoking the
1945 /// callback `f` on each type. If the callback returns false, then the
1946 /// children of the current type are ignored.
1948 /// Note: prefer `ty.walk()` where possible.
1949 pub fn maybe_walk<F>(&'tcx self, mut f: F)
1950 where F : FnMut(Ty<'tcx>) -> bool
1952 let mut walker = self.walk();
1953 while let Some(ty) = walker.next() {
1955 walker.skip_current_subtree();
1961 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1962 pub enum LvaluePreference {
1967 impl LvaluePreference {
1968 pub fn from_mutbl(m: hir::Mutability) -> Self {
1970 hir::MutMutable => PreferMutLvalue,
1971 hir::MutImmutable => NoPreference,
1977 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
1979 hir::MutMutable => MutBorrow,
1980 hir::MutImmutable => ImmBorrow,
1984 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
1985 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
1986 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
1988 pub fn to_mutbl_lossy(self) -> hir::Mutability {
1990 MutBorrow => hir::MutMutable,
1991 ImmBorrow => hir::MutImmutable,
1993 // We have no type corresponding to a unique imm borrow, so
1994 // use `&mut`. It gives all the capabilities of an `&uniq`
1995 // and hence is a safe "over approximation".
1996 UniqueImmBorrow => hir::MutMutable,
2000 pub fn to_user_str(&self) -> &'static str {
2002 MutBorrow => "mutable",
2003 ImmBorrow => "immutable",
2004 UniqueImmBorrow => "uniquely immutable",
2009 #[derive(Debug, Clone)]
2010 pub enum Attributes<'gcx> {
2011 Owned(Rc<[ast::Attribute]>),
2012 Borrowed(&'gcx [ast::Attribute])
2015 impl<'gcx> ::std::ops::Deref for Attributes<'gcx> {
2016 type Target = [ast::Attribute];
2018 fn deref(&self) -> &[ast::Attribute] {
2020 &Attributes::Owned(ref data) => &data,
2021 &Attributes::Borrowed(data) => data
2026 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2027 pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
2028 self.typeck_tables_of(self.hir.body_owner_def_id(body))
2031 /// Returns an iterator of the def-ids for all body-owners in this
2032 /// crate. If you would prefer to iterate over the bodies
2033 /// themselves, you can do `self.hir.krate().body_ids.iter()`.
2034 pub fn body_owners(self) -> impl Iterator<Item = DefId> + 'a {
2038 .map(move |&body_id| self.hir.body_owner_def_id(body_id))
2041 pub fn expr_span(self, id: NodeId) -> Span {
2042 match self.hir.find(id) {
2043 Some(hir_map::NodeExpr(e)) => {
2047 bug!("Node id {} is not an expr: {:?}", id, f);
2050 bug!("Node id {} is not present in the node map", id);
2055 pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
2057 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
2059 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
2064 hir::ExprType(ref e, _) => {
2065 self.expr_is_lval(e)
2068 hir::ExprUnary(hir::UnDeref, _) |
2069 hir::ExprField(..) |
2070 hir::ExprTupField(..) |
2071 hir::ExprIndex(..) => {
2075 // Partially qualified paths in expressions can only legally
2076 // refer to associated items which are always rvalues.
2077 hir::ExprPath(hir::QPath::TypeRelative(..)) |
2080 hir::ExprMethodCall(..) |
2081 hir::ExprStruct(..) |
2084 hir::ExprMatch(..) |
2085 hir::ExprClosure(..) |
2086 hir::ExprBlock(..) |
2087 hir::ExprRepeat(..) |
2088 hir::ExprArray(..) |
2089 hir::ExprBreak(..) |
2090 hir::ExprAgain(..) |
2092 hir::ExprWhile(..) |
2094 hir::ExprAssign(..) |
2095 hir::ExprInlineAsm(..) |
2096 hir::ExprAssignOp(..) |
2098 hir::ExprUnary(..) |
2100 hir::ExprAddrOf(..) |
2101 hir::ExprBinary(..) |
2102 hir::ExprYield(..) |
2103 hir::ExprCast(..) => {
2109 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2110 self.associated_items(id)
2111 .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2115 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2116 self.associated_items(did).any(|item| {
2117 item.relevant_for_never()
2121 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssociatedItem> {
2122 let is_associated_item = if let Some(node_id) = self.hir.as_local_node_id(def_id) {
2123 match self.hir.get(node_id) {
2124 hir_map::NodeTraitItem(_) | hir_map::NodeImplItem(_) => true,
2128 match self.describe_def(def_id).expect("no def for def-id") {
2129 Def::AssociatedConst(_) | Def::Method(_) | Def::AssociatedTy(_) => true,
2134 if is_associated_item {
2135 Some(self.associated_item(def_id))
2141 fn associated_item_from_trait_item_ref(self,
2142 parent_def_id: DefId,
2143 parent_vis: &hir::Visibility,
2144 trait_item_ref: &hir::TraitItemRef)
2146 let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2147 let (kind, has_self) = match trait_item_ref.kind {
2148 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2149 hir::AssociatedItemKind::Method { has_self } => {
2150 (ty::AssociatedKind::Method, has_self)
2152 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2156 name: trait_item_ref.name,
2158 // Visibility of trait items is inherited from their traits.
2159 vis: Visibility::from_hir(parent_vis, trait_item_ref.id.node_id, self),
2160 defaultness: trait_item_ref.defaultness,
2162 container: TraitContainer(parent_def_id),
2163 method_has_self_argument: has_self
2167 fn associated_item_from_impl_item_ref(self,
2168 parent_def_id: DefId,
2169 impl_item_ref: &hir::ImplItemRef)
2171 let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2172 let (kind, has_self) = match impl_item_ref.kind {
2173 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2174 hir::AssociatedItemKind::Method { has_self } => {
2175 (ty::AssociatedKind::Method, has_self)
2177 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2180 ty::AssociatedItem {
2181 name: impl_item_ref.name,
2183 // Visibility of trait impl items doesn't matter.
2184 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.node_id, self),
2185 defaultness: impl_item_ref.defaultness,
2187 container: ImplContainer(parent_def_id),
2188 method_has_self_argument: has_self
2192 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2193 pub fn associated_items(self, def_id: DefId)
2194 -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2195 let def_ids = self.associated_item_def_ids(def_id);
2196 (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2199 /// Returns true if the impls are the same polarity and are implementing
2200 /// a trait which contains no items
2201 pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId) -> bool {
2202 if !self.sess.features.borrow().overlapping_marker_traits {
2205 let trait1_is_empty = self.impl_trait_ref(def_id1)
2206 .map_or(false, |trait_ref| {
2207 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2209 let trait2_is_empty = self.impl_trait_ref(def_id2)
2210 .map_or(false, |trait_ref| {
2211 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2213 self.impl_polarity(def_id1) == self.impl_polarity(def_id2)
2218 // Returns `ty::VariantDef` if `def` refers to a struct,
2219 // or variant or their constructors, panics otherwise.
2220 pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2222 Def::Variant(did) | Def::VariantCtor(did, ..) => {
2223 let enum_did = self.parent_def_id(did).unwrap();
2224 self.adt_def(enum_did).variant_with_id(did)
2226 Def::Struct(did) | Def::Union(did) => {
2227 self.adt_def(did).struct_variant()
2229 Def::StructCtor(ctor_did, ..) => {
2230 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2231 self.adt_def(did).struct_variant()
2233 _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2237 /// Given a `VariantDef`, returns the def-id of the `AdtDef` of which it is a part.
2238 pub fn adt_def_id_of_variant(self, variant_def: &'tcx VariantDef) -> DefId {
2239 let def_key = self.def_key(variant_def.did);
2240 match def_key.disambiguated_data.data {
2241 // for enum variants and tuple structs, the def-id of the ADT itself
2242 // is the *parent* of the variant
2243 DefPathData::EnumVariant(..) | DefPathData::StructCtor =>
2244 DefId { krate: variant_def.did.krate, index: def_key.parent.unwrap() },
2246 // otherwise, for structs and unions, they share a def-id
2247 _ => variant_def.did,
2251 pub fn item_name(self, id: DefId) -> InternedString {
2252 if let Some(id) = self.hir.as_local_node_id(id) {
2253 self.hir.name(id).as_str()
2254 } else if id.index == CRATE_DEF_INDEX {
2255 self.original_crate_name(id.krate).as_str()
2257 let def_key = self.def_key(id);
2258 // The name of a StructCtor is that of its struct parent.
2259 if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2260 self.item_name(DefId {
2262 index: def_key.parent.unwrap()
2265 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2266 bug!("item_name: no name for {:?}", self.def_path(id));
2272 /// Return the possibly-auto-generated MIR of a (DefId, Subst) pair.
2273 pub fn instance_mir(self, instance: ty::InstanceDef<'gcx>)
2277 ty::InstanceDef::Item(did) => {
2278 self.optimized_mir(did)
2280 ty::InstanceDef::Intrinsic(..) |
2281 ty::InstanceDef::FnPtrShim(..) |
2282 ty::InstanceDef::Virtual(..) |
2283 ty::InstanceDef::ClosureOnceShim { .. } |
2284 ty::InstanceDef::DropGlue(..) |
2285 ty::InstanceDef::CloneShim(..) => {
2286 self.mir_shims(instance)
2291 /// Given the DefId of an item, returns its MIR, borrowed immutably.
2292 /// Returns None if there is no MIR for the DefId
2293 pub fn maybe_optimized_mir(self, did: DefId) -> Option<&'gcx Mir<'gcx>> {
2294 if self.is_mir_available(did) {
2295 Some(self.optimized_mir(did))
2301 /// Get the attributes of a definition.
2302 pub fn get_attrs(self, did: DefId) -> Attributes<'gcx> {
2303 if let Some(id) = self.hir.as_local_node_id(did) {
2304 Attributes::Borrowed(self.hir.attrs(id))
2306 Attributes::Owned(self.item_attrs(did))
2310 /// Determine whether an item is annotated with an attribute
2311 pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2312 self.get_attrs(did).iter().any(|item| item.check_name(attr))
2315 pub fn trait_has_default_impl(self, trait_def_id: DefId) -> bool {
2316 self.trait_def(trait_def_id).has_default_impl
2319 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2320 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2323 /// Given the def_id of an impl, return the def_id of the trait it implements.
2324 /// If it implements no trait, return `None`.
2325 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2326 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2329 /// If the given def ID describes a method belonging to an impl, return the
2330 /// ID of the impl that the method belongs to. Otherwise, return `None`.
2331 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2332 let item = if def_id.krate != LOCAL_CRATE {
2333 if let Some(Def::Method(_)) = self.describe_def(def_id) {
2334 Some(self.associated_item(def_id))
2339 self.opt_associated_item(def_id)
2343 Some(trait_item) => {
2344 match trait_item.container {
2345 TraitContainer(_) => None,
2346 ImplContainer(def_id) => Some(def_id),
2353 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2354 /// with the name of the crate containing the impl.
2355 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2356 if impl_did.is_local() {
2357 let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2358 Ok(self.hir.span(node_id))
2360 Err(self.crate_name(impl_did.krate))
2364 // Hygienically compare a use-site name (`use_name`) for a field or an associated item with its
2365 // supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2366 // definition's parent/scope to perform comparison.
2367 pub fn hygienic_eq(self, use_name: Name, def_name: Name, def_parent_def_id: DefId) -> bool {
2368 self.adjust(use_name, def_parent_def_id, DUMMY_NODE_ID).0 == def_name.to_ident()
2371 pub fn adjust(self, name: Name, scope: DefId, block: NodeId) -> (Ident, DefId) {
2372 self.adjust_ident(name.to_ident(), scope, block)
2375 pub fn adjust_ident(self, mut ident: Ident, scope: DefId, block: NodeId) -> (Ident, DefId) {
2376 let expansion = match scope.krate {
2377 LOCAL_CRATE => self.hir.definitions().expansion(scope.index),
2380 let scope = match ident.ctxt.adjust(expansion) {
2381 Some(macro_def) => self.hir.definitions().macro_def_scope(macro_def),
2382 None if block == DUMMY_NODE_ID => DefId::local(CRATE_DEF_INDEX), // Dummy DefId
2383 None => self.hir.get_module_parent(block),
2389 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2390 pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2391 F: FnOnce(&[hir::Freevar]) -> T,
2393 let def_id = self.hir.local_def_id(fid);
2394 match self.freevars(def_id) {
2401 fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
2404 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2405 let parent_id = tcx.hir.get_parent(id);
2406 let parent_def_id = tcx.hir.local_def_id(parent_id);
2407 let parent_item = tcx.hir.expect_item(parent_id);
2408 match parent_item.node {
2409 hir::ItemImpl(.., ref impl_item_refs) => {
2410 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.node_id == id) {
2411 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
2413 debug_assert_eq!(assoc_item.def_id, def_id);
2418 hir::ItemTrait(.., ref trait_item_refs) => {
2419 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.node_id == id) {
2420 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
2423 debug_assert_eq!(assoc_item.def_id, def_id);
2431 span_bug!(parent_item.span,
2432 "unexpected parent of trait or impl item or item not found: {:?}",
2436 /// Calculates the Sized-constraint.
2438 /// In fact, there are only a few options for the types in the constraint:
2439 /// - an obviously-unsized type
2440 /// - a type parameter or projection whose Sizedness can't be known
2441 /// - a tuple of type parameters or projections, if there are multiple
2443 /// - a TyError, if a type contained itself. The representability
2444 /// check should catch this case.
2445 fn adt_sized_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2447 -> &'tcx [Ty<'tcx>] {
2448 let def = tcx.adt_def(def_id);
2450 let result = tcx.intern_type_list(&def.variants.iter().flat_map(|v| {
2453 def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
2454 }).collect::<Vec<_>>());
2456 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
2461 /// Calculates the dtorck constraint for a type.
2462 fn adt_dtorck_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2464 -> DtorckConstraint<'tcx> {
2465 let def = tcx.adt_def(def_id);
2466 let span = tcx.def_span(def_id);
2467 debug!("dtorck_constraint: {:?}", def);
2469 if def.is_phantom_data() {
2470 let result = DtorckConstraint {
2473 tcx.mk_param_from_def(&tcx.generics_of(def_id).types[0])
2476 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2480 let mut result = def.all_fields()
2481 .map(|field| tcx.type_of(field.did))
2482 .map(|fty| tcx.dtorck_constraint_for_ty(span, fty, 0, fty))
2483 .collect::<Result<DtorckConstraint, ErrorReported>>()
2484 .unwrap_or(DtorckConstraint::empty());
2485 result.outlives.extend(tcx.destructor_constraints(def));
2488 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2493 fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2496 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2497 let item = tcx.hir.expect_item(id);
2498 let vec: Vec<_> = match item.node {
2499 hir::ItemTrait(.., ref trait_item_refs) => {
2500 trait_item_refs.iter()
2501 .map(|trait_item_ref| trait_item_ref.id)
2502 .map(|id| tcx.hir.local_def_id(id.node_id))
2505 hir::ItemImpl(.., ref impl_item_refs) => {
2506 impl_item_refs.iter()
2507 .map(|impl_item_ref| impl_item_ref.id)
2508 .map(|id| tcx.hir.local_def_id(id.node_id))
2511 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2516 fn def_span<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Span {
2517 tcx.hir.span_if_local(def_id).unwrap()
2520 /// If the given def ID describes an item belonging to a trait,
2521 /// return the ID of the trait that the trait item belongs to.
2522 /// Otherwise, return `None`.
2523 fn trait_of_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
2524 tcx.opt_associated_item(def_id)
2525 .and_then(|associated_item| {
2526 match associated_item.container {
2527 TraitContainer(def_id) => Some(def_id),
2528 ImplContainer(_) => None
2533 /// See `ParamEnv` struct def'n for details.
2534 fn param_env<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2537 // Compute the bounds on Self and the type parameters.
2539 let bounds = tcx.predicates_of(def_id).instantiate_identity(tcx);
2540 let predicates = bounds.predicates;
2542 // Finally, we have to normalize the bounds in the environment, in
2543 // case they contain any associated type projections. This process
2544 // can yield errors if the put in illegal associated types, like
2545 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2546 // report these errors right here; this doesn't actually feel
2547 // right to me, because constructing the environment feels like a
2548 // kind of a "idempotent" action, but I'm not sure where would be
2549 // a better place. In practice, we construct environments for
2550 // every fn once during type checking, and we'll abort if there
2551 // are any errors at that point, so after type checking you can be
2552 // sure that this will succeed without errors anyway.
2554 let unnormalized_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
2555 traits::Reveal::UserFacing);
2557 let body_id = tcx.hir.as_local_node_id(def_id).map_or(DUMMY_NODE_ID, |id| {
2558 tcx.hir.maybe_body_owned_by(id).map_or(id, |body| body.node_id)
2560 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
2561 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
2564 fn crate_disambiguator<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2565 crate_num: CrateNum) -> Symbol {
2566 assert_eq!(crate_num, LOCAL_CRATE);
2567 tcx.sess.local_crate_disambiguator()
2570 fn original_crate_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2571 crate_num: CrateNum) -> Symbol {
2572 assert_eq!(crate_num, LOCAL_CRATE);
2573 tcx.crate_name.clone()
2576 pub fn provide(providers: &mut ty::maps::Providers) {
2577 util::provide(providers);
2578 context::provide(providers);
2579 erase_regions::provide(providers);
2580 *providers = ty::maps::Providers {
2582 associated_item_def_ids,
2583 adt_sized_constraint,
2584 adt_dtorck_constraint,
2588 crate_disambiguator,
2589 original_crate_name,
2590 trait_impls_of: trait_def::trait_impls_of_provider,
2595 pub fn provide_extern(providers: &mut ty::maps::Providers) {
2596 *providers = ty::maps::Providers {
2597 adt_sized_constraint,
2598 adt_dtorck_constraint,
2599 trait_impls_of: trait_def::trait_impls_of_provider,
2606 /// A map for the local crate mapping each type to a vector of its
2607 /// inherent impls. This is not meant to be used outside of coherence;
2608 /// rather, you should request the vector for a specific type via
2609 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2610 /// (constructing this map requires touching the entire crate).
2611 #[derive(Clone, Debug)]
2612 pub struct CrateInherentImpls {
2613 pub inherent_impls: DefIdMap<Rc<Vec<DefId>>>,
2616 /// A set of constraints that need to be satisfied in order for
2617 /// a type to be valid for destruction.
2618 #[derive(Clone, Debug)]
2619 pub struct DtorckConstraint<'tcx> {
2620 /// Types that are required to be alive in order for this
2621 /// type to be valid for destruction.
2622 pub outlives: Vec<ty::subst::Kind<'tcx>>,
2623 /// Types that could not be resolved: projections and params.
2624 pub dtorck_types: Vec<Ty<'tcx>>,
2627 impl<'tcx> FromIterator<DtorckConstraint<'tcx>> for DtorckConstraint<'tcx>
2629 fn from_iter<I: IntoIterator<Item=DtorckConstraint<'tcx>>>(iter: I) -> Self {
2630 let mut result = Self::empty();
2632 for constraint in iter {
2633 result.outlives.extend(constraint.outlives);
2634 result.dtorck_types.extend(constraint.dtorck_types);
2642 impl<'tcx> DtorckConstraint<'tcx> {
2643 fn empty() -> DtorckConstraint<'tcx> {
2646 dtorck_types: vec![]
2650 fn dedup<'a>(&mut self) {
2651 let mut outlives = FxHashSet();
2652 let mut dtorck_types = FxHashSet();
2654 self.outlives.retain(|&val| outlives.replace(val).is_none());
2655 self.dtorck_types.retain(|&val| dtorck_types.replace(val).is_none());
2659 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
2660 pub struct SymbolName {
2661 // FIXME: we don't rely on interning or equality here - better have
2662 // this be a `&'tcx str`.
2663 pub name: InternedString
2666 impl_stable_hash_for!(struct self::SymbolName {
2670 impl Deref for SymbolName {
2673 fn deref(&self) -> &str { &self.name }
2676 impl fmt::Display for SymbolName {
2677 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2678 fmt::Display::fmt(&self.name, fmt)