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, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
21 use hir::map::DefPathData;
23 use ich::StableHashingContext;
24 use middle::const_val::ConstVal;
25 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
26 use middle::privacy::AccessLevels;
27 use middle::resolve_lifetime::ObjectLifetimeDefault;
29 use mir::GeneratorLayout;
30 use session::CrateDisambiguator;
33 use ty::subst::{Subst, Substs};
34 use ty::util::IntTypeExt;
35 use ty::walk::TypeWalker;
36 use util::common::ErrorReported;
37 use util::nodemap::{NodeSet, DefIdMap, FxHashMap, FxHashSet};
39 use serialize::{self, Encodable, Encoder};
40 use std::collections::BTreeMap;
43 use std::hash::{Hash, Hasher};
44 use std::iter::FromIterator;
48 use std::vec::IntoIter;
50 use syntax::ast::{self, DUMMY_NODE_ID, Name, Ident, NodeId};
52 use syntax::ext::hygiene::{Mark, SyntaxContext};
53 use syntax::symbol::{Symbol, InternedString};
54 use syntax_pos::{DUMMY_SP, Span};
55 use rustc_const_math::ConstInt;
57 use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
58 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
63 pub use self::sty::{Binder, DebruijnIndex};
64 pub use self::sty::{FnSig, GenSig, PolyFnSig, PolyGenSig};
65 pub use self::sty::{InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
66 pub use self::sty::{ClosureSubsts, GeneratorInterior, TypeAndMut};
67 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
68 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
69 pub use self::sty::{ExistentialProjection, PolyExistentialProjection, Const};
70 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
71 pub use self::sty::RegionKind;
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::binding::BindingMode;
79 pub use self::binding::BindingMode::*;
81 pub use self::context::{TyCtxt, GlobalArenas, AllArenas, tls, keep_local};
82 pub use self::context::{Lift, TypeckTables};
84 pub use self::instance::{Instance, InstanceDef};
86 pub use self::trait_def::TraitDef;
88 pub use self::maps::queries;
99 pub mod inhabitedness;
116 mod structural_impls;
121 /// The complete set of all analyses described in this module. This is
122 /// produced by the driver and fed to trans and later passes.
124 /// NB: These contents are being migrated into queries using the
125 /// *on-demand* infrastructure.
127 pub struct CrateAnalysis {
128 pub access_levels: Rc<AccessLevels>,
130 pub glob_map: Option<hir::GlobMap>,
134 pub struct Resolutions {
135 pub freevars: FreevarMap,
136 pub trait_map: TraitMap,
137 pub maybe_unused_trait_imports: NodeSet,
138 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
139 pub export_map: ExportMap,
142 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
143 pub enum AssociatedItemContainer {
144 TraitContainer(DefId),
145 ImplContainer(DefId),
148 impl AssociatedItemContainer {
149 /// Asserts that this is the def-id of an associated item declared
150 /// in a trait, and returns the trait def-id.
151 pub fn assert_trait(&self) -> DefId {
153 TraitContainer(id) => id,
154 _ => bug!("associated item has wrong container type: {:?}", self)
158 pub fn id(&self) -> DefId {
160 TraitContainer(id) => id,
161 ImplContainer(id) => id,
166 /// The "header" of an impl is everything outside the body: a Self type, a trait
167 /// ref (in the case of a trait impl), and a set of predicates (from the
168 /// bounds/where clauses).
169 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
170 pub struct ImplHeader<'tcx> {
171 pub impl_def_id: DefId,
172 pub self_ty: Ty<'tcx>,
173 pub trait_ref: Option<TraitRef<'tcx>>,
174 pub predicates: Vec<Predicate<'tcx>>,
177 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
178 pub struct AssociatedItem {
181 pub kind: AssociatedKind,
183 pub defaultness: hir::Defaultness,
184 pub container: AssociatedItemContainer,
186 /// Whether this is a method with an explicit self
187 /// as its first argument, allowing method calls.
188 pub method_has_self_argument: bool,
191 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, RustcEncodable, RustcDecodable)]
192 pub enum AssociatedKind {
198 impl AssociatedItem {
199 pub fn def(&self) -> Def {
201 AssociatedKind::Const => Def::AssociatedConst(self.def_id),
202 AssociatedKind::Method => Def::Method(self.def_id),
203 AssociatedKind::Type => Def::AssociatedTy(self.def_id),
207 /// Tests whether the associated item admits a non-trivial implementation
209 pub fn relevant_for_never<'tcx>(&self) -> bool {
211 AssociatedKind::Const => true,
212 AssociatedKind::Type => true,
213 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
214 AssociatedKind::Method => !self.method_has_self_argument,
218 pub fn signature<'a, 'tcx>(&self, tcx: &TyCtxt<'a, 'tcx, 'tcx>) -> String {
220 ty::AssociatedKind::Method => {
221 // We skip the binder here because the binder would deanonymize all
222 // late-bound regions, and we don't want method signatures to show up
223 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
224 // regions just fine, showing `fn(&MyType)`.
225 format!("{}", tcx.fn_sig(self.def_id).skip_binder())
227 ty::AssociatedKind::Type => format!("type {};", self.name.to_string()),
228 ty::AssociatedKind::Const => {
229 format!("const {}: {:?};", self.name.to_string(), tcx.type_of(self.def_id))
235 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
236 pub enum Visibility {
237 /// Visible everywhere (including in other crates).
239 /// Visible only in the given crate-local module.
241 /// Not visible anywhere in the local crate. This is the visibility of private external items.
245 pub trait DefIdTree: Copy {
246 fn parent(self, id: DefId) -> Option<DefId>;
248 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
249 if descendant.krate != ancestor.krate {
253 while descendant != ancestor {
254 match self.parent(descendant) {
255 Some(parent) => descendant = parent,
256 None => return false,
263 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
264 fn parent(self, id: DefId) -> Option<DefId> {
265 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
270 pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
272 hir::Public => Visibility::Public,
273 hir::Visibility::Crate => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
274 hir::Visibility::Restricted { ref path, .. } => match path.def {
275 // If there is no resolution, `resolve` will have already reported an error, so
276 // assume that the visibility is public to avoid reporting more privacy errors.
277 Def::Err => Visibility::Public,
278 def => Visibility::Restricted(def.def_id()),
281 Visibility::Restricted(tcx.hir.get_module_parent(id))
286 /// Returns true if an item with this visibility is accessible from the given block.
287 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
288 let restriction = match self {
289 // Public items are visible everywhere.
290 Visibility::Public => return true,
291 // Private items from other crates are visible nowhere.
292 Visibility::Invisible => return false,
293 // Restricted items are visible in an arbitrary local module.
294 Visibility::Restricted(other) if other.krate != module.krate => return false,
295 Visibility::Restricted(module) => module,
298 tree.is_descendant_of(module, restriction)
301 /// Returns true if this visibility is at least as accessible as the given visibility
302 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
303 let vis_restriction = match vis {
304 Visibility::Public => return self == Visibility::Public,
305 Visibility::Invisible => return true,
306 Visibility::Restricted(module) => module,
309 self.is_accessible_from(vis_restriction, tree)
312 // Returns true if this item is visible anywhere in the local crate.
313 pub fn is_visible_locally(self) -> bool {
315 Visibility::Public => true,
316 Visibility::Restricted(def_id) => def_id.is_local(),
317 Visibility::Invisible => false,
322 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
324 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
325 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
326 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
327 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
330 /// The crate variances map is computed during typeck and contains the
331 /// variance of every item in the local crate. You should not use it
332 /// directly, because to do so will make your pass dependent on the
333 /// HIR of every item in the local crate. Instead, use
334 /// `tcx.variances_of()` to get the variance for a *particular*
336 pub struct CrateVariancesMap {
337 /// For each item with generics, maps to a vector of the variance
338 /// of its generics. If an item has no generics, it will have no
340 pub variances: FxHashMap<DefId, Rc<Vec<ty::Variance>>>,
342 /// An empty vector, useful for cloning.
343 pub empty_variance: Rc<Vec<ty::Variance>>,
347 /// `a.xform(b)` combines the variance of a context with the
348 /// variance of a type with the following meaning. If we are in a
349 /// context with variance `a`, and we encounter a type argument in
350 /// a position with variance `b`, then `a.xform(b)` is the new
351 /// variance with which the argument appears.
357 /// Here, the "ambient" variance starts as covariant. `*mut T` is
358 /// invariant with respect to `T`, so the variance in which the
359 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
360 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
361 /// respect to its type argument `T`, and hence the variance of
362 /// the `i32` here is `Invariant.xform(Covariant)`, which results
363 /// (again) in `Invariant`.
367 /// fn(*const Vec<i32>, *mut Vec<i32)
369 /// The ambient variance is covariant. A `fn` type is
370 /// contravariant with respect to its parameters, so the variance
371 /// within which both pointer types appear is
372 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
373 /// T` is covariant with respect to `T`, so the variance within
374 /// which the first `Vec<i32>` appears is
375 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
376 /// is true for its `i32` argument. In the `*mut T` case, the
377 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
378 /// and hence the outermost type is `Invariant` with respect to
379 /// `Vec<i32>` (and its `i32` argument).
381 /// Source: Figure 1 of "Taming the Wildcards:
382 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
383 pub fn xform(self, v: ty::Variance) -> ty::Variance {
385 // Figure 1, column 1.
386 (ty::Covariant, ty::Covariant) => ty::Covariant,
387 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
388 (ty::Covariant, ty::Invariant) => ty::Invariant,
389 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
391 // Figure 1, column 2.
392 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
393 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
394 (ty::Contravariant, ty::Invariant) => ty::Invariant,
395 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
397 // Figure 1, column 3.
398 (ty::Invariant, _) => ty::Invariant,
400 // Figure 1, column 4.
401 (ty::Bivariant, _) => ty::Bivariant,
406 // Contains information needed to resolve types and (in the future) look up
407 // the types of AST nodes.
408 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
409 pub struct CReaderCacheKey {
414 // Flags that we track on types. These flags are propagated upwards
415 // through the type during type construction, so that we can quickly
416 // check whether the type has various kinds of types in it without
417 // recursing over the type itself.
419 pub struct TypeFlags: u32 {
420 const HAS_PARAMS = 1 << 0;
421 const HAS_SELF = 1 << 1;
422 const HAS_TY_INFER = 1 << 2;
423 const HAS_RE_INFER = 1 << 3;
424 const HAS_RE_SKOL = 1 << 4;
426 /// Does this have any `ReEarlyBound` regions? Used to
427 /// determine whether substitition is required, since those
428 /// represent regions that are bound in a `ty::Generics` and
429 /// hence may be substituted.
430 const HAS_RE_EARLY_BOUND = 1 << 5;
432 /// Does this have any region that "appears free" in the type?
433 /// Basically anything but `ReLateBound` and `ReErased`.
434 const HAS_FREE_REGIONS = 1 << 6;
436 /// Is an error type reachable?
437 const HAS_TY_ERR = 1 << 7;
438 const HAS_PROJECTION = 1 << 8;
440 // FIXME: Rename this to the actual property since it's used for generators too
441 const HAS_TY_CLOSURE = 1 << 9;
443 // true if there are "names" of types and regions and so forth
444 // that are local to a particular fn
445 const HAS_LOCAL_NAMES = 1 << 10;
447 // Present if the type belongs in a local type context.
448 // Only set for TyInfer other than Fresh.
449 const KEEP_IN_LOCAL_TCX = 1 << 11;
451 // Is there a projection that does not involve a bound region?
452 // Currently we can't normalize projections w/ bound regions.
453 const HAS_NORMALIZABLE_PROJECTION = 1 << 12;
455 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
456 TypeFlags::HAS_SELF.bits |
457 TypeFlags::HAS_RE_EARLY_BOUND.bits;
459 // Flags representing the nominal content of a type,
460 // computed by FlagsComputation. If you add a new nominal
461 // flag, it should be added here too.
462 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
463 TypeFlags::HAS_SELF.bits |
464 TypeFlags::HAS_TY_INFER.bits |
465 TypeFlags::HAS_RE_INFER.bits |
466 TypeFlags::HAS_RE_SKOL.bits |
467 TypeFlags::HAS_RE_EARLY_BOUND.bits |
468 TypeFlags::HAS_FREE_REGIONS.bits |
469 TypeFlags::HAS_TY_ERR.bits |
470 TypeFlags::HAS_PROJECTION.bits |
471 TypeFlags::HAS_TY_CLOSURE.bits |
472 TypeFlags::HAS_LOCAL_NAMES.bits |
473 TypeFlags::KEEP_IN_LOCAL_TCX.bits;
477 pub struct TyS<'tcx> {
478 pub sty: TypeVariants<'tcx>,
479 pub flags: TypeFlags,
481 // the maximal depth of any bound regions appearing in this type.
485 impl<'tcx> PartialEq for TyS<'tcx> {
487 fn eq(&self, other: &TyS<'tcx>) -> bool {
488 // (self as *const _) == (other as *const _)
489 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
492 impl<'tcx> Eq for TyS<'tcx> {}
494 impl<'tcx> Hash for TyS<'tcx> {
495 fn hash<H: Hasher>(&self, s: &mut H) {
496 (self as *const TyS).hash(s)
500 impl<'tcx> TyS<'tcx> {
501 pub fn is_primitive_ty(&self) -> bool {
503 TypeVariants::TyBool |
504 TypeVariants::TyChar |
505 TypeVariants::TyInt(_) |
506 TypeVariants::TyUint(_) |
507 TypeVariants::TyFloat(_) |
508 TypeVariants::TyInfer(InferTy::IntVar(_)) |
509 TypeVariants::TyInfer(InferTy::FloatVar(_)) |
510 TypeVariants::TyInfer(InferTy::FreshIntTy(_)) |
511 TypeVariants::TyInfer(InferTy::FreshFloatTy(_)) => true,
512 TypeVariants::TyRef(_, x) => x.ty.is_primitive_ty(),
517 pub fn is_suggestable(&self) -> bool {
519 TypeVariants::TyAnon(..) |
520 TypeVariants::TyFnDef(..) |
521 TypeVariants::TyFnPtr(..) |
522 TypeVariants::TyDynamic(..) |
523 TypeVariants::TyClosure(..) |
524 TypeVariants::TyInfer(..) |
525 TypeVariants::TyProjection(..) => false,
531 impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::TyS<'gcx> {
532 fn hash_stable<W: StableHasherResult>(&self,
533 hcx: &mut StableHashingContext<'gcx>,
534 hasher: &mut StableHasher<W>) {
538 // The other fields just provide fast access to information that is
539 // also contained in `sty`, so no need to hash them.
544 sty.hash_stable(hcx, hasher);
548 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
550 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
551 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
553 /// A wrapper for slices with the additional invariant
554 /// that the slice is interned and no other slice with
555 /// the same contents can exist in the same context.
556 /// This means we can use pointer + length for both
557 /// equality comparisons and hashing.
558 #[derive(Debug, RustcEncodable)]
559 pub struct Slice<T>([T]);
561 impl<T> PartialEq for Slice<T> {
563 fn eq(&self, other: &Slice<T>) -> bool {
564 (&self.0 as *const [T]) == (&other.0 as *const [T])
567 impl<T> Eq for Slice<T> {}
569 impl<T> Hash for Slice<T> {
570 fn hash<H: Hasher>(&self, s: &mut H) {
571 (self.as_ptr(), self.len()).hash(s)
575 impl<T> Deref for Slice<T> {
577 fn deref(&self) -> &[T] {
582 impl<'a, T> IntoIterator for &'a Slice<T> {
584 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
585 fn into_iter(self) -> Self::IntoIter {
590 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
593 pub fn empty<'a>() -> &'a Slice<T> {
595 mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
600 /// Upvars do not get their own node-id. Instead, we use the pair of
601 /// the original var id (that is, the root variable that is referenced
602 /// by the upvar) and the id of the closure expression.
603 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
605 pub var_id: hir::HirId,
606 pub closure_expr_id: LocalDefId,
609 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
610 pub enum BorrowKind {
611 /// Data must be immutable and is aliasable.
614 /// Data must be immutable but not aliasable. This kind of borrow
615 /// cannot currently be expressed by the user and is used only in
616 /// implicit closure bindings. It is needed when the closure
617 /// is borrowing or mutating a mutable referent, e.g.:
619 /// let x: &mut isize = ...;
620 /// let y = || *x += 5;
622 /// If we were to try to translate this closure into a more explicit
623 /// form, we'd encounter an error with the code as written:
625 /// struct Env { x: & &mut isize }
626 /// let x: &mut isize = ...;
627 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
628 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
630 /// This is then illegal because you cannot mutate a `&mut` found
631 /// in an aliasable location. To solve, you'd have to translate with
632 /// an `&mut` borrow:
634 /// struct Env { x: & &mut isize }
635 /// let x: &mut isize = ...;
636 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
637 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
639 /// Now the assignment to `**env.x` is legal, but creating a
640 /// mutable pointer to `x` is not because `x` is not mutable. We
641 /// could fix this by declaring `x` as `let mut x`. This is ok in
642 /// user code, if awkward, but extra weird for closures, since the
643 /// borrow is hidden.
645 /// So we introduce a "unique imm" borrow -- the referent is
646 /// immutable, but not aliasable. This solves the problem. For
647 /// simplicity, we don't give users the way to express this
648 /// borrow, it's just used when translating closures.
651 /// Data is mutable and not aliasable.
655 /// Information describing the capture of an upvar. This is computed
656 /// during `typeck`, specifically by `regionck`.
657 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
658 pub enum UpvarCapture<'tcx> {
659 /// Upvar is captured by value. This is always true when the
660 /// closure is labeled `move`, but can also be true in other cases
661 /// depending on inference.
664 /// Upvar is captured by reference.
665 ByRef(UpvarBorrow<'tcx>),
668 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
669 pub struct UpvarBorrow<'tcx> {
670 /// The kind of borrow: by-ref upvars have access to shared
671 /// immutable borrows, which are not part of the normal language
673 pub kind: BorrowKind,
675 /// Region of the resulting reference.
676 pub region: ty::Region<'tcx>,
679 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
681 #[derive(Copy, Clone)]
682 pub struct ClosureUpvar<'tcx> {
688 #[derive(Clone, Copy, PartialEq)]
689 pub enum IntVarValue {
691 UintType(ast::UintTy),
694 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
695 pub struct TypeParameterDef {
699 pub has_default: bool,
700 pub object_lifetime_default: ObjectLifetimeDefault,
702 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
703 /// on generic parameter `T`, asserts data behind the parameter
704 /// `T` won't be accessed during the parent type's `Drop` impl.
705 pub pure_wrt_drop: bool,
707 pub synthetic: Option<hir::SyntheticTyParamKind>,
710 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
711 pub struct RegionParameterDef {
716 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
717 /// on generic parameter `'a`, asserts data of lifetime `'a`
718 /// won't be accessed during the parent type's `Drop` impl.
719 pub pure_wrt_drop: bool,
722 impl RegionParameterDef {
723 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
724 ty::EarlyBoundRegion {
731 pub fn to_bound_region(&self) -> ty::BoundRegion {
732 self.to_early_bound_region_data().to_bound_region()
736 impl ty::EarlyBoundRegion {
737 pub fn to_bound_region(&self) -> ty::BoundRegion {
738 ty::BoundRegion::BrNamed(self.def_id, self.name)
742 /// Information about the formal type/lifetime parameters associated
743 /// with an item or method. Analogous to hir::Generics.
745 /// Note that in the presence of a `Self` parameter, the ordering here
746 /// is different from the ordering in a Substs. Substs are ordered as
747 /// Self, *Regions, *Other Type Params, (...child generics)
748 /// while this struct is ordered as
749 /// regions = Regions
750 /// types = [Self, *Other Type Params]
751 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
752 pub struct Generics {
753 pub parent: Option<DefId>,
754 pub parent_regions: u32,
755 pub parent_types: u32,
756 pub regions: Vec<RegionParameterDef>,
757 pub types: Vec<TypeParameterDef>,
759 /// Reverse map to each `TypeParameterDef`'s `index` field, from
760 /// `def_id.index` (`def_id.krate` is the same as the item's).
761 pub type_param_to_index: BTreeMap<DefIndex, u32>,
764 pub has_late_bound_regions: Option<Span>,
767 impl<'a, 'gcx, 'tcx> Generics {
768 pub fn parent_count(&self) -> usize {
769 self.parent_regions as usize + self.parent_types as usize
772 pub fn own_count(&self) -> usize {
773 self.regions.len() + self.types.len()
776 pub fn count(&self) -> usize {
777 self.parent_count() + self.own_count()
780 pub fn region_param(&'tcx self,
781 param: &EarlyBoundRegion,
782 tcx: TyCtxt<'a, 'gcx, 'tcx>)
783 -> &'tcx RegionParameterDef
785 if let Some(index) = param.index.checked_sub(self.parent_count() as u32) {
786 &self.regions[index as usize - self.has_self as usize]
788 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
789 .region_param(param, tcx)
793 /// Returns the `TypeParameterDef` associated with this `ParamTy`.
794 pub fn type_param(&'tcx self,
796 tcx: TyCtxt<'a, 'gcx, 'tcx>)
797 -> &TypeParameterDef {
798 if let Some(idx) = param.idx.checked_sub(self.parent_count() as u32) {
799 // non-Self type parameters are always offset by exactly
800 // `self.regions.len()`. In the absence of a Self, this is obvious,
801 // but even in the presence of a `Self` we just have to "compensate"
804 // Without a `Self` (or in a nested generics that doesn't have
805 // a `Self` in itself, even through it parent does), for example
806 // for `fn foo<'a, T1, T2>()`, the situation is:
814 // And with a `Self`, for example for `trait Foo<'a, 'b, T1, T2>`, the
823 // And it can be seen that in both cases, to move from a substs
824 // offset to a generics offset you just have to offset by the
825 // number of regions.
826 let type_param_offset = self.regions.len();
828 let has_self = self.has_self && self.parent.is_none();
829 let is_separated_self = type_param_offset != 0 && idx == 0 && has_self;
831 if let Some(idx) = (idx as usize).checked_sub(type_param_offset) {
832 assert!(!is_separated_self, "found a Self after type_param_offset");
835 assert!(is_separated_self, "non-Self param before type_param_offset");
839 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
840 .type_param(param, tcx)
845 /// Bounds on generics.
846 #[derive(Clone, Default)]
847 pub struct GenericPredicates<'tcx> {
848 pub parent: Option<DefId>,
849 pub predicates: Vec<Predicate<'tcx>>,
852 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
853 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
855 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
856 pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
857 -> InstantiatedPredicates<'tcx> {
858 let mut instantiated = InstantiatedPredicates::empty();
859 self.instantiate_into(tcx, &mut instantiated, substs);
862 pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
863 -> InstantiatedPredicates<'tcx> {
864 InstantiatedPredicates {
865 predicates: self.predicates.subst(tcx, substs)
869 fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
870 instantiated: &mut InstantiatedPredicates<'tcx>,
871 substs: &Substs<'tcx>) {
872 if let Some(def_id) = self.parent {
873 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
875 instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
878 pub fn instantiate_identity(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
879 -> InstantiatedPredicates<'tcx> {
880 let mut instantiated = InstantiatedPredicates::empty();
881 self.instantiate_identity_into(tcx, &mut instantiated);
885 fn instantiate_identity_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
886 instantiated: &mut InstantiatedPredicates<'tcx>) {
887 if let Some(def_id) = self.parent {
888 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
890 instantiated.predicates.extend(&self.predicates)
893 pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
894 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
895 -> InstantiatedPredicates<'tcx>
897 assert_eq!(self.parent, None);
898 InstantiatedPredicates {
899 predicates: self.predicates.iter().map(|pred| {
900 pred.subst_supertrait(tcx, poly_trait_ref)
906 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
907 pub enum Predicate<'tcx> {
908 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
909 /// the `Self` type of the trait reference and `A`, `B`, and `C`
910 /// would be the type parameters.
911 Trait(PolyTraitPredicate<'tcx>),
913 /// where `T1 == T2`.
914 Equate(PolyEquatePredicate<'tcx>),
917 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
920 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
922 /// where <T as TraitRef>::Name == X, approximately.
923 /// See `ProjectionPredicate` struct for details.
924 Projection(PolyProjectionPredicate<'tcx>),
927 WellFormed(Ty<'tcx>),
929 /// trait must be object-safe
932 /// No direct syntax. May be thought of as `where T : FnFoo<...>`
933 /// for some substitutions `...` and T being a closure type.
934 /// Satisfied (or refuted) once we know the closure's kind.
935 ClosureKind(DefId, ClosureSubsts<'tcx>, ClosureKind),
938 Subtype(PolySubtypePredicate<'tcx>),
940 /// Constant initializer must evaluate successfully.
941 ConstEvaluatable(DefId, &'tcx Substs<'tcx>),
944 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
945 fn as_ref(&self) -> &Predicate<'tcx> {
950 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
951 /// Performs a substitution suitable for going from a
952 /// poly-trait-ref to supertraits that must hold if that
953 /// poly-trait-ref holds. This is slightly different from a normal
954 /// substitution in terms of what happens with bound regions. See
955 /// lengthy comment below for details.
956 pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
957 trait_ref: &ty::PolyTraitRef<'tcx>)
958 -> ty::Predicate<'tcx>
960 // The interaction between HRTB and supertraits is not entirely
961 // obvious. Let me walk you (and myself) through an example.
963 // Let's start with an easy case. Consider two traits:
965 // trait Foo<'a> : Bar<'a,'a> { }
966 // trait Bar<'b,'c> { }
968 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
969 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
970 // knew that `Foo<'x>` (for any 'x) then we also know that
971 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
972 // normal substitution.
974 // In terms of why this is sound, the idea is that whenever there
975 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
976 // holds. So if there is an impl of `T:Foo<'a>` that applies to
977 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
980 // Another example to be careful of is this:
982 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
983 // trait Bar1<'b,'c> { }
985 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
986 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
987 // reason is similar to the previous example: any impl of
988 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
989 // basically we would want to collapse the bound lifetimes from
990 // the input (`trait_ref`) and the supertraits.
992 // To achieve this in practice is fairly straightforward. Let's
993 // consider the more complicated scenario:
995 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
996 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
997 // where both `'x` and `'b` would have a DB index of 1.
998 // The substitution from the input trait-ref is therefore going to be
999 // `'a => 'x` (where `'x` has a DB index of 1).
1000 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1001 // early-bound parameter and `'b' is a late-bound parameter with a
1003 // - If we replace `'a` with `'x` from the input, it too will have
1004 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1005 // just as we wanted.
1007 // There is only one catch. If we just apply the substitution `'a
1008 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1009 // adjust the DB index because we substituting into a binder (it
1010 // tries to be so smart...) resulting in `for<'x> for<'b>
1011 // Bar1<'x,'b>` (we have no syntax for this, so use your
1012 // imagination). Basically the 'x will have DB index of 2 and 'b
1013 // will have DB index of 1. Not quite what we want. So we apply
1014 // the substitution to the *contents* of the trait reference,
1015 // rather than the trait reference itself (put another way, the
1016 // substitution code expects equal binding levels in the values
1017 // from the substitution and the value being substituted into, and
1018 // this trick achieves that).
1020 let substs = &trait_ref.0.substs;
1022 Predicate::Trait(ty::Binder(ref data)) =>
1023 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
1024 Predicate::Equate(ty::Binder(ref data)) =>
1025 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
1026 Predicate::Subtype(ty::Binder(ref data)) =>
1027 Predicate::Subtype(ty::Binder(data.subst(tcx, substs))),
1028 Predicate::RegionOutlives(ty::Binder(ref data)) =>
1029 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
1030 Predicate::TypeOutlives(ty::Binder(ref data)) =>
1031 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
1032 Predicate::Projection(ty::Binder(ref data)) =>
1033 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
1034 Predicate::WellFormed(data) =>
1035 Predicate::WellFormed(data.subst(tcx, substs)),
1036 Predicate::ObjectSafe(trait_def_id) =>
1037 Predicate::ObjectSafe(trait_def_id),
1038 Predicate::ClosureKind(closure_def_id, closure_substs, kind) =>
1039 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind),
1040 Predicate::ConstEvaluatable(def_id, const_substs) =>
1041 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs)),
1046 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1047 pub struct TraitPredicate<'tcx> {
1048 pub trait_ref: TraitRef<'tcx>
1050 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1052 impl<'tcx> TraitPredicate<'tcx> {
1053 pub fn def_id(&self) -> DefId {
1054 self.trait_ref.def_id
1057 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
1058 self.trait_ref.input_types()
1061 pub fn self_ty(&self) -> Ty<'tcx> {
1062 self.trait_ref.self_ty()
1066 impl<'tcx> PolyTraitPredicate<'tcx> {
1067 pub fn def_id(&self) -> DefId {
1068 // ok to skip binder since trait def-id does not care about regions
1073 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1074 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
1075 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
1077 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1078 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
1079 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
1080 pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<ty::Region<'tcx>,
1082 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1084 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1085 pub struct SubtypePredicate<'tcx> {
1086 pub a_is_expected: bool,
1090 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1092 /// This kind of predicate has no *direct* correspondent in the
1093 /// syntax, but it roughly corresponds to the syntactic forms:
1095 /// 1. `T : TraitRef<..., Item=Type>`
1096 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1098 /// In particular, form #1 is "desugared" to the combination of a
1099 /// normal trait predicate (`T : TraitRef<...>`) and one of these
1100 /// predicates. Form #2 is a broader form in that it also permits
1101 /// equality between arbitrary types. Processing an instance of
1102 /// Form #2 eventually yields one of these `ProjectionPredicate`
1103 /// instances to normalize the LHS.
1104 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1105 pub struct ProjectionPredicate<'tcx> {
1106 pub projection_ty: ProjectionTy<'tcx>,
1110 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1112 impl<'tcx> PolyProjectionPredicate<'tcx> {
1113 pub fn to_poly_trait_ref(&self, tcx: TyCtxt) -> PolyTraitRef<'tcx> {
1114 // Note: unlike with TraitRef::to_poly_trait_ref(),
1115 // self.0.trait_ref is permitted to have escaping regions.
1116 // This is because here `self` has a `Binder` and so does our
1117 // return value, so we are preserving the number of binding
1119 ty::Binder(self.0.projection_ty.trait_ref(tcx))
1122 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1123 Binder(self.skip_binder().ty) // preserves binding levels
1127 pub trait ToPolyTraitRef<'tcx> {
1128 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1131 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1132 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1133 assert!(!self.has_escaping_regions());
1134 ty::Binder(self.clone())
1138 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1139 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1140 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1144 pub trait ToPredicate<'tcx> {
1145 fn to_predicate(&self) -> Predicate<'tcx>;
1148 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1149 fn to_predicate(&self) -> Predicate<'tcx> {
1150 // we're about to add a binder, so let's check that we don't
1151 // accidentally capture anything, or else that might be some
1152 // weird debruijn accounting.
1153 assert!(!self.has_escaping_regions());
1155 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1156 trait_ref: self.clone()
1161 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1162 fn to_predicate(&self) -> Predicate<'tcx> {
1163 ty::Predicate::Trait(self.to_poly_trait_predicate())
1167 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
1168 fn to_predicate(&self) -> Predicate<'tcx> {
1169 Predicate::Equate(self.clone())
1173 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1174 fn to_predicate(&self) -> Predicate<'tcx> {
1175 Predicate::RegionOutlives(self.clone())
1179 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1180 fn to_predicate(&self) -> Predicate<'tcx> {
1181 Predicate::TypeOutlives(self.clone())
1185 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1186 fn to_predicate(&self) -> Predicate<'tcx> {
1187 Predicate::Projection(self.clone())
1191 impl<'tcx> Predicate<'tcx> {
1192 /// Iterates over the types in this predicate. Note that in all
1193 /// cases this is skipping over a binder, so late-bound regions
1194 /// with depth 0 are bound by the predicate.
1195 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1196 let vec: Vec<_> = match *self {
1197 ty::Predicate::Trait(ref data) => {
1198 data.skip_binder().input_types().collect()
1200 ty::Predicate::Equate(ty::Binder(ref data)) => {
1201 vec![data.0, data.1]
1203 ty::Predicate::Subtype(ty::Binder(SubtypePredicate { a, b, a_is_expected: _ })) => {
1206 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1209 ty::Predicate::RegionOutlives(..) => {
1212 ty::Predicate::Projection(ref data) => {
1213 data.0.projection_ty.substs.types().chain(Some(data.0.ty)).collect()
1215 ty::Predicate::WellFormed(data) => {
1218 ty::Predicate::ObjectSafe(_trait_def_id) => {
1221 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1222 closure_substs.substs.types().collect()
1224 ty::Predicate::ConstEvaluatable(_, substs) => {
1225 substs.types().collect()
1229 // The only reason to collect into a vector here is that I was
1230 // too lazy to make the full (somewhat complicated) iterator
1231 // type that would be needed here. But I wanted this fn to
1232 // return an iterator conceptually, rather than a `Vec`, so as
1233 // to be closer to `Ty::walk`.
1237 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1239 Predicate::Trait(ref t) => {
1240 Some(t.to_poly_trait_ref())
1242 Predicate::Projection(..) |
1243 Predicate::Equate(..) |
1244 Predicate::Subtype(..) |
1245 Predicate::RegionOutlives(..) |
1246 Predicate::WellFormed(..) |
1247 Predicate::ObjectSafe(..) |
1248 Predicate::ClosureKind(..) |
1249 Predicate::TypeOutlives(..) |
1250 Predicate::ConstEvaluatable(..) => {
1256 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1258 Predicate::TypeOutlives(data) => {
1261 Predicate::Trait(..) |
1262 Predicate::Projection(..) |
1263 Predicate::Equate(..) |
1264 Predicate::Subtype(..) |
1265 Predicate::RegionOutlives(..) |
1266 Predicate::WellFormed(..) |
1267 Predicate::ObjectSafe(..) |
1268 Predicate::ClosureKind(..) |
1269 Predicate::ConstEvaluatable(..) => {
1276 /// Represents the bounds declared on a particular set of type
1277 /// parameters. Should eventually be generalized into a flag list of
1278 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
1279 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1280 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1281 /// the `GenericPredicates` are expressed in terms of the bound type
1282 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1283 /// represented a set of bounds for some particular instantiation,
1284 /// meaning that the generic parameters have been substituted with
1289 /// struct Foo<T,U:Bar<T>> { ... }
1291 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1292 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1293 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1294 /// [usize:Bar<isize>]]`.
1296 pub struct InstantiatedPredicates<'tcx> {
1297 pub predicates: Vec<Predicate<'tcx>>,
1300 impl<'tcx> InstantiatedPredicates<'tcx> {
1301 pub fn empty() -> InstantiatedPredicates<'tcx> {
1302 InstantiatedPredicates { predicates: vec![] }
1305 pub fn is_empty(&self) -> bool {
1306 self.predicates.is_empty()
1310 /// When type checking, we use the `ParamEnv` to track
1311 /// details about the set of where-clauses that are in scope at this
1312 /// particular point.
1313 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1314 pub struct ParamEnv<'tcx> {
1315 /// Obligations that the caller must satisfy. This is basically
1316 /// the set of bounds on the in-scope type parameters, translated
1317 /// into Obligations, and elaborated and normalized.
1318 pub caller_bounds: &'tcx Slice<ty::Predicate<'tcx>>,
1320 /// Typically, this is `Reveal::UserFacing`, but during trans we
1321 /// want `Reveal::All` -- note that this is always paired with an
1322 /// empty environment. To get that, use `ParamEnv::reveal()`.
1323 pub reveal: traits::Reveal,
1326 impl<'tcx> ParamEnv<'tcx> {
1327 /// Creates a suitable environment in which to perform trait
1328 /// queries on the given value. This will either be `self` *or*
1329 /// the empty environment, depending on whether `value` references
1330 /// type parameters that are in scope. (If it doesn't, then any
1331 /// judgements should be completely independent of the context,
1332 /// and hence we can safely use the empty environment so as to
1333 /// enable more sharing across functions.)
1335 /// NB: This is a mildly dubious thing to do, in that a function
1336 /// (or other environment) might have wacky where-clauses like
1337 /// `where Box<u32>: Copy`, which are clearly never
1338 /// satisfiable. The code will at present ignore these,
1339 /// effectively, when type-checking the body of said
1340 /// function. This preserves existing behavior in any
1341 /// case. --nmatsakis
1342 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1343 assert!(!value.needs_infer());
1344 if value.has_param_types() || value.has_self_ty() {
1351 param_env: ParamEnv::empty(self.reveal),
1358 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1359 pub struct ParamEnvAnd<'tcx, T> {
1360 pub param_env: ParamEnv<'tcx>,
1364 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1365 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1366 (self.param_env, self.value)
1370 impl<'gcx, T> HashStable<StableHashingContext<'gcx>> for ParamEnvAnd<'gcx, T>
1371 where T: HashStable<StableHashingContext<'gcx>>
1373 fn hash_stable<W: StableHasherResult>(&self,
1374 hcx: &mut StableHashingContext<'gcx>,
1375 hasher: &mut StableHasher<W>) {
1381 param_env.hash_stable(hcx, hasher);
1382 value.hash_stable(hcx, hasher);
1386 #[derive(Copy, Clone, Debug)]
1387 pub struct Destructor {
1388 /// The def-id of the destructor method
1393 pub struct AdtFlags: u32 {
1394 const NO_ADT_FLAGS = 0;
1395 const IS_ENUM = 1 << 0;
1396 const IS_PHANTOM_DATA = 1 << 1;
1397 const IS_FUNDAMENTAL = 1 << 2;
1398 const IS_UNION = 1 << 3;
1399 const IS_BOX = 1 << 4;
1400 /// Indicates whether this abstract data type will be expanded on in future (new
1401 /// fields/variants) and as such, whether downstream crates must match exhaustively on the
1402 /// fields/variants of this data type.
1404 /// See RFC 2008 (<https://github.com/rust-lang/rfcs/pull/2008>).
1405 const IS_NON_EXHAUSTIVE = 1 << 5;
1410 pub struct VariantDef {
1411 /// The variant's DefId. If this is a tuple-like struct,
1412 /// this is the DefId of the struct's ctor.
1414 pub name: Name, // struct's name if this is a struct
1415 pub discr: VariantDiscr,
1416 pub fields: Vec<FieldDef>,
1417 pub ctor_kind: CtorKind,
1420 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1421 pub enum VariantDiscr {
1422 /// Explicit value for this variant, i.e. `X = 123`.
1423 /// The `DefId` corresponds to the embedded constant.
1426 /// The previous variant's discriminant plus one.
1427 /// For efficiency reasons, the distance from the
1428 /// last `Explicit` discriminant is being stored,
1429 /// or `0` for the first variant, if it has none.
1434 pub struct FieldDef {
1437 pub vis: Visibility,
1440 /// The definition of an abstract data type - a struct or enum.
1442 /// These are all interned (by intern_adt_def) into the adt_defs
1446 pub variants: Vec<VariantDef>,
1448 pub repr: ReprOptions,
1451 impl PartialEq for AdtDef {
1452 // AdtDef are always interned and this is part of TyS equality
1454 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1457 impl Eq for AdtDef {}
1459 impl Hash for AdtDef {
1461 fn hash<H: Hasher>(&self, s: &mut H) {
1462 (self as *const AdtDef).hash(s)
1466 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1467 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1472 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1475 impl<'gcx> HashStable<StableHashingContext<'gcx>> for AdtDef {
1476 fn hash_stable<W: StableHasherResult>(&self,
1477 hcx: &mut StableHashingContext<'gcx>,
1478 hasher: &mut StableHasher<W>) {
1486 did.hash_stable(hcx, hasher);
1487 variants.hash_stable(hcx, hasher);
1488 flags.hash_stable(hcx, hasher);
1489 repr.hash_stable(hcx, hasher);
1493 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1494 pub enum AdtKind { Struct, Union, Enum }
1497 #[derive(RustcEncodable, RustcDecodable, Default)]
1498 pub struct ReprFlags: u8 {
1499 const IS_C = 1 << 0;
1500 const IS_PACKED = 1 << 1;
1501 const IS_SIMD = 1 << 2;
1502 // Internal only for now. If true, don't reorder fields.
1503 const IS_LINEAR = 1 << 3;
1505 // Any of these flags being set prevent field reordering optimisation.
1506 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1507 ReprFlags::IS_PACKED.bits |
1508 ReprFlags::IS_SIMD.bits |
1509 ReprFlags::IS_LINEAR.bits;
1513 impl_stable_hash_for!(struct ReprFlags {
1519 /// Represents the repr options provided by the user,
1520 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1521 pub struct ReprOptions {
1522 pub int: Option<attr::IntType>,
1524 pub flags: ReprFlags,
1527 impl_stable_hash_for!(struct ReprOptions {
1534 pub fn new(tcx: TyCtxt, did: DefId) -> ReprOptions {
1535 let mut flags = ReprFlags::empty();
1536 let mut size = None;
1537 let mut max_align = 0;
1538 for attr in tcx.get_attrs(did).iter() {
1539 for r in attr::find_repr_attrs(tcx.sess.diagnostic(), attr) {
1540 flags.insert(match r {
1541 attr::ReprC => ReprFlags::IS_C,
1542 attr::ReprPacked => ReprFlags::IS_PACKED,
1543 attr::ReprSimd => ReprFlags::IS_SIMD,
1544 attr::ReprInt(i) => {
1548 attr::ReprAlign(align) => {
1549 max_align = cmp::max(align, max_align);
1556 // This is here instead of layout because the choice must make it into metadata.
1557 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.item_path_str(did))) {
1558 flags.insert(ReprFlags::IS_LINEAR);
1560 ReprOptions { int: size, align: max_align, flags: flags }
1564 pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
1566 pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
1568 pub fn packed(&self) -> bool { self.flags.contains(ReprFlags::IS_PACKED) }
1570 pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
1572 pub fn discr_type(&self) -> attr::IntType {
1573 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
1576 /// Returns true if this `#[repr()]` should inhabit "smart enum
1577 /// layout" optimizations, such as representing `Foo<&T>` as a
1579 pub fn inhibit_enum_layout_opt(&self) -> bool {
1580 self.c() || self.int.is_some()
1584 impl<'a, 'gcx, 'tcx> AdtDef {
1588 variants: Vec<VariantDef>,
1589 repr: ReprOptions) -> Self {
1590 let mut flags = AdtFlags::NO_ADT_FLAGS;
1591 let attrs = tcx.get_attrs(did);
1592 if attr::contains_name(&attrs, "fundamental") {
1593 flags = flags | AdtFlags::IS_FUNDAMENTAL;
1595 if Some(did) == tcx.lang_items().phantom_data() {
1596 flags = flags | AdtFlags::IS_PHANTOM_DATA;
1598 if Some(did) == tcx.lang_items().owned_box() {
1599 flags = flags | AdtFlags::IS_BOX;
1601 if tcx.has_attr(did, "non_exhaustive") {
1602 flags = flags | AdtFlags::IS_NON_EXHAUSTIVE;
1605 AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1606 AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1607 AdtKind::Struct => {}
1618 pub fn is_struct(&self) -> bool {
1619 !self.is_union() && !self.is_enum()
1623 pub fn is_union(&self) -> bool {
1624 self.flags.intersects(AdtFlags::IS_UNION)
1628 pub fn is_enum(&self) -> bool {
1629 self.flags.intersects(AdtFlags::IS_ENUM)
1633 pub fn is_non_exhaustive(&self) -> bool {
1634 self.flags.intersects(AdtFlags::IS_NON_EXHAUSTIVE)
1637 /// Returns the kind of the ADT - Struct or Enum.
1639 pub fn adt_kind(&self) -> AdtKind {
1642 } else if self.is_union() {
1649 pub fn descr(&self) -> &'static str {
1650 match self.adt_kind() {
1651 AdtKind::Struct => "struct",
1652 AdtKind::Union => "union",
1653 AdtKind::Enum => "enum",
1657 pub fn variant_descr(&self) -> &'static str {
1658 match self.adt_kind() {
1659 AdtKind::Struct => "struct",
1660 AdtKind::Union => "union",
1661 AdtKind::Enum => "variant",
1665 /// Returns whether this type is #[fundamental] for the purposes
1666 /// of coherence checking.
1668 pub fn is_fundamental(&self) -> bool {
1669 self.flags.intersects(AdtFlags::IS_FUNDAMENTAL)
1672 /// Returns true if this is PhantomData<T>.
1674 pub fn is_phantom_data(&self) -> bool {
1675 self.flags.intersects(AdtFlags::IS_PHANTOM_DATA)
1678 /// Returns true if this is Box<T>.
1680 pub fn is_box(&self) -> bool {
1681 self.flags.intersects(AdtFlags::IS_BOX)
1684 /// Returns whether this type has a destructor.
1685 pub fn has_dtor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1686 self.destructor(tcx).is_some()
1689 /// Asserts this is a struct or union and returns its unique variant.
1690 pub fn non_enum_variant(&self) -> &VariantDef {
1691 assert!(self.is_struct() || self.is_union());
1696 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1697 tcx.predicates_of(self.did)
1700 /// Returns an iterator over all fields contained
1703 pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1704 self.variants.iter().flat_map(|v| v.fields.iter())
1707 pub fn is_payloadfree(&self) -> bool {
1708 !self.variants.is_empty() &&
1709 self.variants.iter().all(|v| v.fields.is_empty())
1712 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1715 .find(|v| v.did == vid)
1716 .expect("variant_with_id: unknown variant")
1719 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1722 .position(|v| v.did == vid)
1723 .expect("variant_index_with_id: unknown variant")
1726 pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1728 Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1729 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1730 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.non_enum_variant(),
1731 _ => bug!("unexpected def {:?} in variant_of_def", def)
1736 pub fn discriminants(&'a self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
1737 -> impl Iterator<Item=ConstInt> + 'a {
1738 let param_env = ParamEnv::empty(traits::Reveal::UserFacing);
1739 let repr_type = self.repr.discr_type();
1740 let initial = repr_type.initial_discriminant(tcx.global_tcx());
1741 let mut prev_discr = None::<ConstInt>;
1742 self.variants.iter().map(move |v| {
1743 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr());
1744 if let VariantDiscr::Explicit(expr_did) = v.discr {
1745 let substs = Substs::identity_for_item(tcx.global_tcx(), expr_did);
1746 match tcx.const_eval(param_env.and((expr_did, substs))) {
1747 Ok(&ty::Const { val: ConstVal::Integral(v), .. }) => {
1751 if !expr_did.is_local() {
1752 span_bug!(tcx.def_span(expr_did),
1753 "variant discriminant evaluation succeeded \
1754 in its crate but failed locally: {:?}", err);
1759 prev_discr = Some(discr);
1765 /// Compute the discriminant value used by a specific variant.
1766 /// Unlike `discriminants`, this is (amortized) constant-time,
1767 /// only doing at most one query for evaluating an explicit
1768 /// discriminant (the last one before the requested variant),
1769 /// assuming there are no constant-evaluation errors there.
1770 pub fn discriminant_for_variant(&self,
1771 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1772 variant_index: usize)
1774 let param_env = ParamEnv::empty(traits::Reveal::UserFacing);
1775 let repr_type = self.repr.discr_type();
1776 let mut explicit_value = repr_type.initial_discriminant(tcx.global_tcx());
1777 let mut explicit_index = variant_index;
1779 match self.variants[explicit_index].discr {
1780 ty::VariantDiscr::Relative(0) => break,
1781 ty::VariantDiscr::Relative(distance) => {
1782 explicit_index -= distance;
1784 ty::VariantDiscr::Explicit(expr_did) => {
1785 let substs = Substs::identity_for_item(tcx.global_tcx(), expr_did);
1786 match tcx.const_eval(param_env.and((expr_did, substs))) {
1787 Ok(&ty::Const { val: ConstVal::Integral(v), .. }) => {
1792 if !expr_did.is_local() {
1793 span_bug!(tcx.def_span(expr_did),
1794 "variant discriminant evaluation succeeded \
1795 in its crate but failed locally: {:?}", err);
1797 if explicit_index == 0 {
1800 explicit_index -= 1;
1806 let discr = explicit_value.to_u128_unchecked()
1807 .wrapping_add((variant_index - explicit_index) as u128);
1809 attr::UnsignedInt(ty) => {
1810 ConstInt::new_unsigned_truncating(discr, ty,
1811 tcx.sess.target.usize_ty)
1813 attr::SignedInt(ty) => {
1814 ConstInt::new_signed_truncating(discr as i128, ty,
1815 tcx.sess.target.isize_ty)
1820 pub fn destructor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Destructor> {
1821 tcx.adt_destructor(self.did)
1824 /// Returns a list of types such that `Self: Sized` if and only
1825 /// if that type is Sized, or `TyErr` if this type is recursive.
1827 /// Oddly enough, checking that the sized-constraint is Sized is
1828 /// actually more expressive than checking all members:
1829 /// the Sized trait is inductive, so an associated type that references
1830 /// Self would prevent its containing ADT from being Sized.
1832 /// Due to normalization being eager, this applies even if
1833 /// the associated type is behind a pointer, e.g. issue #31299.
1834 pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] {
1835 match queries::adt_sized_constraint::try_get(tcx, DUMMY_SP, self.did) {
1838 debug!("adt_sized_constraint: {:?} is recursive", self);
1839 // This should be reported as an error by `check_representable`.
1841 // Consider the type as Sized in the meanwhile to avoid
1842 // further errors. Delay our `bug` diagnostic here to get
1843 // emitted later as well in case we accidentally otherwise don't
1846 tcx.intern_type_list(&[tcx.types.err])
1851 fn sized_constraint_for_ty(&self,
1852 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1855 let result = match ty.sty {
1856 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
1857 TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
1858 TyArray(..) | TyClosure(..) | TyGenerator(..) | TyNever => {
1862 TyStr | TyDynamic(..) | TySlice(_) | TyForeign(..) | TyError => {
1863 // these are never sized - return the target type
1867 TyTuple(ref tys, _) => {
1870 Some(ty) => self.sized_constraint_for_ty(tcx, ty)
1874 TyAdt(adt, substs) => {
1876 let adt_tys = adt.sized_constraint(tcx);
1877 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
1880 .map(|ty| ty.subst(tcx, substs))
1881 .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
1885 TyProjection(..) | TyAnon(..) => {
1886 // must calculate explicitly.
1887 // FIXME: consider special-casing always-Sized projections
1892 // perf hack: if there is a `T: Sized` bound, then
1893 // we know that `T` is Sized and do not need to check
1896 let sized_trait = match tcx.lang_items().sized_trait() {
1898 _ => return vec![ty]
1900 let sized_predicate = Binder(TraitRef {
1901 def_id: sized_trait,
1902 substs: tcx.mk_substs_trait(ty, &[])
1904 let predicates = tcx.predicates_of(self.did).predicates;
1905 if predicates.into_iter().any(|p| p == sized_predicate) {
1913 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
1917 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
1922 impl<'a, 'gcx, 'tcx> VariantDef {
1924 pub fn find_field_named(&self, name: ast::Name) -> Option<&FieldDef> {
1925 self.index_of_field_named(name).map(|index| &self.fields[index])
1928 pub fn index_of_field_named(&self, name: ast::Name) -> Option<usize> {
1929 if let Some(index) = self.fields.iter().position(|f| f.name == name) {
1932 let mut ident = name.to_ident();
1933 while ident.ctxt != SyntaxContext::empty() {
1934 ident.ctxt.remove_mark();
1935 if let Some(field) = self.fields.iter().position(|f| f.name.to_ident() == ident) {
1943 pub fn field_named(&self, name: ast::Name) -> &FieldDef {
1944 self.find_field_named(name).unwrap()
1948 impl<'a, 'gcx, 'tcx> FieldDef {
1949 pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1950 tcx.type_of(self.did).subst(tcx, subst)
1954 /// Represents the various closure traits in the Rust language. This
1955 /// will determine the type of the environment (`self`, in the
1956 /// desuaring) argument that the closure expects.
1958 /// You can get the environment type of a closure using
1959 /// `tcx.closure_env_ty()`.
1960 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1961 pub enum ClosureKind {
1962 // Warning: Ordering is significant here! The ordering is chosen
1963 // because the trait Fn is a subtrait of FnMut and so in turn, and
1964 // hence we order it so that Fn < FnMut < FnOnce.
1970 impl<'a, 'tcx> ClosureKind {
1971 // This is the initial value used when doing upvar inference.
1972 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
1974 pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
1976 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
1977 ClosureKind::FnMut => {
1978 tcx.require_lang_item(FnMutTraitLangItem)
1980 ClosureKind::FnOnce => {
1981 tcx.require_lang_item(FnOnceTraitLangItem)
1986 /// True if this a type that impls this closure kind
1987 /// must also implement `other`.
1988 pub fn extends(self, other: ty::ClosureKind) -> bool {
1989 match (self, other) {
1990 (ClosureKind::Fn, ClosureKind::Fn) => true,
1991 (ClosureKind::Fn, ClosureKind::FnMut) => true,
1992 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
1993 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
1994 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
1995 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2000 /// Returns the representative scalar type for this closure kind.
2001 /// See `TyS::to_opt_closure_kind` for more details.
2002 pub fn to_ty(self, tcx: TyCtxt<'_, '_, 'tcx>) -> Ty<'tcx> {
2004 ty::ClosureKind::Fn => tcx.types.i8,
2005 ty::ClosureKind::FnMut => tcx.types.i16,
2006 ty::ClosureKind::FnOnce => tcx.types.i32,
2011 impl<'tcx> TyS<'tcx> {
2012 /// Iterator that walks `self` and any types reachable from
2013 /// `self`, in depth-first order. Note that just walks the types
2014 /// that appear in `self`, it does not descend into the fields of
2015 /// structs or variants. For example:
2018 /// isize => { isize }
2019 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2020 /// [isize] => { [isize], isize }
2022 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2023 TypeWalker::new(self)
2026 /// Iterator that walks the immediate children of `self`. Hence
2027 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2028 /// (but not `i32`, like `walk`).
2029 pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
2030 walk::walk_shallow(self)
2033 /// Walks `ty` and any types appearing within `ty`, invoking the
2034 /// callback `f` on each type. If the callback returns false, then the
2035 /// children of the current type are ignored.
2037 /// Note: prefer `ty.walk()` where possible.
2038 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2039 where F : FnMut(Ty<'tcx>) -> bool
2041 let mut walker = self.walk();
2042 while let Some(ty) = walker.next() {
2044 walker.skip_current_subtree();
2050 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
2051 pub enum LvaluePreference {
2056 impl LvaluePreference {
2057 pub fn from_mutbl(m: hir::Mutability) -> Self {
2059 hir::MutMutable => PreferMutLvalue,
2060 hir::MutImmutable => NoPreference,
2066 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2068 hir::MutMutable => MutBorrow,
2069 hir::MutImmutable => ImmBorrow,
2073 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2074 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2075 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2077 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2079 MutBorrow => hir::MutMutable,
2080 ImmBorrow => hir::MutImmutable,
2082 // We have no type corresponding to a unique imm borrow, so
2083 // use `&mut`. It gives all the capabilities of an `&uniq`
2084 // and hence is a safe "over approximation".
2085 UniqueImmBorrow => hir::MutMutable,
2089 pub fn to_user_str(&self) -> &'static str {
2091 MutBorrow => "mutable",
2092 ImmBorrow => "immutable",
2093 UniqueImmBorrow => "uniquely immutable",
2098 #[derive(Debug, Clone)]
2099 pub enum Attributes<'gcx> {
2100 Owned(Rc<[ast::Attribute]>),
2101 Borrowed(&'gcx [ast::Attribute])
2104 impl<'gcx> ::std::ops::Deref for Attributes<'gcx> {
2105 type Target = [ast::Attribute];
2107 fn deref(&self) -> &[ast::Attribute] {
2109 &Attributes::Owned(ref data) => &data,
2110 &Attributes::Borrowed(data) => data
2115 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2116 pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
2117 self.typeck_tables_of(self.hir.body_owner_def_id(body))
2120 /// Returns an iterator of the def-ids for all body-owners in this
2121 /// crate. If you would prefer to iterate over the bodies
2122 /// themselves, you can do `self.hir.krate().body_ids.iter()`.
2123 pub fn body_owners(self) -> impl Iterator<Item = DefId> + 'a {
2127 .map(move |&body_id| self.hir.body_owner_def_id(body_id))
2130 pub fn expr_span(self, id: NodeId) -> Span {
2131 match self.hir.find(id) {
2132 Some(hir_map::NodeExpr(e)) => {
2136 bug!("Node id {} is not an expr: {:?}", id, f);
2139 bug!("Node id {} is not present in the node map", id);
2144 pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
2146 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
2148 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
2153 hir::ExprType(ref e, _) => {
2154 self.expr_is_lval(e)
2157 hir::ExprUnary(hir::UnDeref, _) |
2158 hir::ExprField(..) |
2159 hir::ExprTupField(..) |
2160 hir::ExprIndex(..) => {
2164 // Partially qualified paths in expressions can only legally
2165 // refer to associated items which are always rvalues.
2166 hir::ExprPath(hir::QPath::TypeRelative(..)) |
2169 hir::ExprMethodCall(..) |
2170 hir::ExprStruct(..) |
2173 hir::ExprMatch(..) |
2174 hir::ExprClosure(..) |
2175 hir::ExprBlock(..) |
2176 hir::ExprRepeat(..) |
2177 hir::ExprArray(..) |
2178 hir::ExprBreak(..) |
2179 hir::ExprAgain(..) |
2181 hir::ExprWhile(..) |
2183 hir::ExprAssign(..) |
2184 hir::ExprInlineAsm(..) |
2185 hir::ExprAssignOp(..) |
2187 hir::ExprUnary(..) |
2189 hir::ExprAddrOf(..) |
2190 hir::ExprBinary(..) |
2191 hir::ExprYield(..) |
2192 hir::ExprCast(..) => {
2198 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2199 self.associated_items(id)
2200 .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2204 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2205 self.associated_items(did).any(|item| {
2206 item.relevant_for_never()
2210 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssociatedItem> {
2211 let is_associated_item = if let Some(node_id) = self.hir.as_local_node_id(def_id) {
2212 match self.hir.get(node_id) {
2213 hir_map::NodeTraitItem(_) | hir_map::NodeImplItem(_) => true,
2217 match self.describe_def(def_id).expect("no def for def-id") {
2218 Def::AssociatedConst(_) | Def::Method(_) | Def::AssociatedTy(_) => true,
2223 if is_associated_item {
2224 Some(self.associated_item(def_id))
2230 fn associated_item_from_trait_item_ref(self,
2231 parent_def_id: DefId,
2232 parent_vis: &hir::Visibility,
2233 trait_item_ref: &hir::TraitItemRef)
2235 let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2236 let (kind, has_self) = match trait_item_ref.kind {
2237 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2238 hir::AssociatedItemKind::Method { has_self } => {
2239 (ty::AssociatedKind::Method, has_self)
2241 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2245 name: trait_item_ref.name,
2247 // Visibility of trait items is inherited from their traits.
2248 vis: Visibility::from_hir(parent_vis, trait_item_ref.id.node_id, self),
2249 defaultness: trait_item_ref.defaultness,
2251 container: TraitContainer(parent_def_id),
2252 method_has_self_argument: has_self
2256 fn associated_item_from_impl_item_ref(self,
2257 parent_def_id: DefId,
2258 impl_item_ref: &hir::ImplItemRef)
2260 let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2261 let (kind, has_self) = match impl_item_ref.kind {
2262 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2263 hir::AssociatedItemKind::Method { has_self } => {
2264 (ty::AssociatedKind::Method, has_self)
2266 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2269 ty::AssociatedItem {
2270 name: impl_item_ref.name,
2272 // Visibility of trait impl items doesn't matter.
2273 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.node_id, self),
2274 defaultness: impl_item_ref.defaultness,
2276 container: ImplContainer(parent_def_id),
2277 method_has_self_argument: has_self
2281 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2282 pub fn associated_items(self, def_id: DefId)
2283 -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2284 let def_ids = self.associated_item_def_ids(def_id);
2285 (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2288 /// Returns true if the impls are the same polarity and are implementing
2289 /// a trait which contains no items
2290 pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId) -> bool {
2291 if !self.sess.features.borrow().overlapping_marker_traits {
2294 let trait1_is_empty = self.impl_trait_ref(def_id1)
2295 .map_or(false, |trait_ref| {
2296 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2298 let trait2_is_empty = self.impl_trait_ref(def_id2)
2299 .map_or(false, |trait_ref| {
2300 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2302 self.impl_polarity(def_id1) == self.impl_polarity(def_id2)
2307 // Returns `ty::VariantDef` if `def` refers to a struct,
2308 // or variant or their constructors, panics otherwise.
2309 pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2311 Def::Variant(did) | Def::VariantCtor(did, ..) => {
2312 let enum_did = self.parent_def_id(did).unwrap();
2313 self.adt_def(enum_did).variant_with_id(did)
2315 Def::Struct(did) | Def::Union(did) => {
2316 self.adt_def(did).non_enum_variant()
2318 Def::StructCtor(ctor_did, ..) => {
2319 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2320 self.adt_def(did).non_enum_variant()
2322 _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2326 /// Given a `VariantDef`, returns the def-id of the `AdtDef` of which it is a part.
2327 pub fn adt_def_id_of_variant(self, variant_def: &'tcx VariantDef) -> DefId {
2328 let def_key = self.def_key(variant_def.did);
2329 match def_key.disambiguated_data.data {
2330 // for enum variants and tuple structs, the def-id of the ADT itself
2331 // is the *parent* of the variant
2332 DefPathData::EnumVariant(..) | DefPathData::StructCtor =>
2333 DefId { krate: variant_def.did.krate, index: def_key.parent.unwrap() },
2335 // otherwise, for structs and unions, they share a def-id
2336 _ => variant_def.did,
2340 pub fn item_name(self, id: DefId) -> InternedString {
2341 if id.index == CRATE_DEF_INDEX {
2342 self.original_crate_name(id.krate).as_str()
2344 let def_key = self.def_key(id);
2345 // The name of a StructCtor is that of its struct parent.
2346 if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2347 self.item_name(DefId {
2349 index: def_key.parent.unwrap()
2352 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2353 bug!("item_name: no name for {:?}", self.def_path(id));
2359 /// Return the possibly-auto-generated MIR of a (DefId, Subst) pair.
2360 pub fn instance_mir(self, instance: ty::InstanceDef<'gcx>)
2364 ty::InstanceDef::Item(did) => {
2365 self.optimized_mir(did)
2367 ty::InstanceDef::Intrinsic(..) |
2368 ty::InstanceDef::FnPtrShim(..) |
2369 ty::InstanceDef::Virtual(..) |
2370 ty::InstanceDef::ClosureOnceShim { .. } |
2371 ty::InstanceDef::DropGlue(..) |
2372 ty::InstanceDef::CloneShim(..) => {
2373 self.mir_shims(instance)
2378 /// Given the DefId of an item, returns its MIR, borrowed immutably.
2379 /// Returns None if there is no MIR for the DefId
2380 pub fn maybe_optimized_mir(self, did: DefId) -> Option<&'gcx Mir<'gcx>> {
2381 if self.is_mir_available(did) {
2382 Some(self.optimized_mir(did))
2388 /// Get the attributes of a definition.
2389 pub fn get_attrs(self, did: DefId) -> Attributes<'gcx> {
2390 if let Some(id) = self.hir.as_local_node_id(did) {
2391 Attributes::Borrowed(self.hir.attrs(id))
2393 Attributes::Owned(self.item_attrs(did))
2397 /// Determine whether an item is annotated with an attribute
2398 pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2399 attr::contains_name(&self.get_attrs(did), attr)
2402 /// Returns true if this is an `auto trait`.
2404 /// NB. For a limited time, also returns true if `impl Trait for .. { }` is in the code-base.
2405 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2406 self.trait_def(trait_def_id).has_auto_impl
2409 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2410 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2413 /// Given the def_id of an impl, return the def_id of the trait it implements.
2414 /// If it implements no trait, return `None`.
2415 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2416 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2419 /// If the given def ID describes a method belonging to an impl, return the
2420 /// ID of the impl that the method belongs to. Otherwise, return `None`.
2421 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2422 let item = if def_id.krate != LOCAL_CRATE {
2423 if let Some(Def::Method(_)) = self.describe_def(def_id) {
2424 Some(self.associated_item(def_id))
2429 self.opt_associated_item(def_id)
2433 Some(trait_item) => {
2434 match trait_item.container {
2435 TraitContainer(_) => None,
2436 ImplContainer(def_id) => Some(def_id),
2443 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2444 /// with the name of the crate containing the impl.
2445 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2446 if impl_did.is_local() {
2447 let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2448 Ok(self.hir.span(node_id))
2450 Err(self.crate_name(impl_did.krate))
2454 // Hygienically compare a use-site name (`use_name`) for a field or an associated item with its
2455 // supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2456 // definition's parent/scope to perform comparison.
2457 pub fn hygienic_eq(self, use_name: Name, def_name: Name, def_parent_def_id: DefId) -> bool {
2458 self.adjust(use_name, def_parent_def_id, DUMMY_NODE_ID).0 == def_name.to_ident()
2461 pub fn adjust(self, name: Name, scope: DefId, block: NodeId) -> (Ident, DefId) {
2462 self.adjust_ident(name.to_ident(), scope, block)
2465 pub fn adjust_ident(self, mut ident: Ident, scope: DefId, block: NodeId) -> (Ident, DefId) {
2466 let expansion = match scope.krate {
2467 LOCAL_CRATE => self.hir.definitions().expansion(scope.index),
2470 let scope = match ident.ctxt.adjust(expansion) {
2471 Some(macro_def) => self.hir.definitions().macro_def_scope(macro_def),
2472 None if block == DUMMY_NODE_ID => DefId::local(CRATE_DEF_INDEX), // Dummy DefId
2473 None => self.hir.get_module_parent(block),
2479 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2480 pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2481 F: FnOnce(&[hir::Freevar]) -> T,
2483 let def_id = self.hir.local_def_id(fid);
2484 match self.freevars(def_id) {
2491 fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
2494 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2495 let parent_id = tcx.hir.get_parent(id);
2496 let parent_def_id = tcx.hir.local_def_id(parent_id);
2497 let parent_item = tcx.hir.expect_item(parent_id);
2498 match parent_item.node {
2499 hir::ItemImpl(.., ref impl_item_refs) => {
2500 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.node_id == id) {
2501 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
2503 debug_assert_eq!(assoc_item.def_id, def_id);
2508 hir::ItemTrait(.., ref trait_item_refs) => {
2509 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.node_id == id) {
2510 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
2513 debug_assert_eq!(assoc_item.def_id, def_id);
2521 span_bug!(parent_item.span,
2522 "unexpected parent of trait or impl item or item not found: {:?}",
2526 /// Calculates the Sized-constraint.
2528 /// In fact, there are only a few options for the types in the constraint:
2529 /// - an obviously-unsized type
2530 /// - a type parameter or projection whose Sizedness can't be known
2531 /// - a tuple of type parameters or projections, if there are multiple
2533 /// - a TyError, if a type contained itself. The representability
2534 /// check should catch this case.
2535 fn adt_sized_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2537 -> &'tcx [Ty<'tcx>] {
2538 let def = tcx.adt_def(def_id);
2540 let result = tcx.intern_type_list(&def.variants.iter().flat_map(|v| {
2543 def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
2544 }).collect::<Vec<_>>());
2546 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
2551 /// Calculates the dtorck constraint for a type.
2552 fn adt_dtorck_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2554 -> DtorckConstraint<'tcx> {
2555 let def = tcx.adt_def(def_id);
2556 let span = tcx.def_span(def_id);
2557 debug!("dtorck_constraint: {:?}", def);
2559 if def.is_phantom_data() {
2560 let result = DtorckConstraint {
2563 tcx.mk_param_from_def(&tcx.generics_of(def_id).types[0])
2566 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2570 let mut result = def.all_fields()
2571 .map(|field| tcx.type_of(field.did))
2572 .map(|fty| tcx.dtorck_constraint_for_ty(span, fty, 0, fty))
2573 .collect::<Result<DtorckConstraint, ErrorReported>>()
2574 .unwrap_or(DtorckConstraint::empty());
2575 result.outlives.extend(tcx.destructor_constraints(def));
2578 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2583 fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2586 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2587 let item = tcx.hir.expect_item(id);
2588 let vec: Vec<_> = match item.node {
2589 hir::ItemTrait(.., ref trait_item_refs) => {
2590 trait_item_refs.iter()
2591 .map(|trait_item_ref| trait_item_ref.id)
2592 .map(|id| tcx.hir.local_def_id(id.node_id))
2595 hir::ItemImpl(.., ref impl_item_refs) => {
2596 impl_item_refs.iter()
2597 .map(|impl_item_ref| impl_item_ref.id)
2598 .map(|id| tcx.hir.local_def_id(id.node_id))
2601 hir::ItemTraitAlias(..) => vec![],
2602 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2607 fn def_span<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Span {
2608 tcx.hir.span_if_local(def_id).unwrap()
2611 /// If the given def ID describes an item belonging to a trait,
2612 /// return the ID of the trait that the trait item belongs to.
2613 /// Otherwise, return `None`.
2614 fn trait_of_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
2615 tcx.opt_associated_item(def_id)
2616 .and_then(|associated_item| {
2617 match associated_item.container {
2618 TraitContainer(def_id) => Some(def_id),
2619 ImplContainer(_) => None
2624 /// See `ParamEnv` struct def'n for details.
2625 fn param_env<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2628 // Compute the bounds on Self and the type parameters.
2630 let bounds = tcx.predicates_of(def_id).instantiate_identity(tcx);
2631 let predicates = bounds.predicates;
2633 // Finally, we have to normalize the bounds in the environment, in
2634 // case they contain any associated type projections. This process
2635 // can yield errors if the put in illegal associated types, like
2636 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2637 // report these errors right here; this doesn't actually feel
2638 // right to me, because constructing the environment feels like a
2639 // kind of a "idempotent" action, but I'm not sure where would be
2640 // a better place. In practice, we construct environments for
2641 // every fn once during type checking, and we'll abort if there
2642 // are any errors at that point, so after type checking you can be
2643 // sure that this will succeed without errors anyway.
2645 let unnormalized_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
2646 traits::Reveal::UserFacing);
2648 let body_id = tcx.hir.as_local_node_id(def_id).map_or(DUMMY_NODE_ID, |id| {
2649 tcx.hir.maybe_body_owned_by(id).map_or(id, |body| body.node_id)
2651 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
2652 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
2655 fn crate_disambiguator<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2656 crate_num: CrateNum) -> CrateDisambiguator {
2657 assert_eq!(crate_num, LOCAL_CRATE);
2658 tcx.sess.local_crate_disambiguator()
2661 fn original_crate_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2662 crate_num: CrateNum) -> Symbol {
2663 assert_eq!(crate_num, LOCAL_CRATE);
2664 tcx.crate_name.clone()
2667 fn crate_hash<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2668 crate_num: CrateNum)
2670 assert_eq!(crate_num, LOCAL_CRATE);
2674 pub fn provide(providers: &mut ty::maps::Providers) {
2675 context::provide(providers);
2676 erase_regions::provide(providers);
2677 layout::provide(providers);
2678 util::provide(providers);
2679 *providers = ty::maps::Providers {
2681 associated_item_def_ids,
2682 adt_sized_constraint,
2683 adt_dtorck_constraint,
2687 crate_disambiguator,
2688 original_crate_name,
2690 trait_impls_of: trait_def::trait_impls_of_provider,
2695 /// A map for the local crate mapping each type to a vector of its
2696 /// inherent impls. This is not meant to be used outside of coherence;
2697 /// rather, you should request the vector for a specific type via
2698 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2699 /// (constructing this map requires touching the entire crate).
2700 #[derive(Clone, Debug)]
2701 pub struct CrateInherentImpls {
2702 pub inherent_impls: DefIdMap<Rc<Vec<DefId>>>,
2705 /// A set of constraints that need to be satisfied in order for
2706 /// a type to be valid for destruction.
2707 #[derive(Clone, Debug)]
2708 pub struct DtorckConstraint<'tcx> {
2709 /// Types that are required to be alive in order for this
2710 /// type to be valid for destruction.
2711 pub outlives: Vec<ty::subst::Kind<'tcx>>,
2712 /// Types that could not be resolved: projections and params.
2713 pub dtorck_types: Vec<Ty<'tcx>>,
2716 impl<'tcx> FromIterator<DtorckConstraint<'tcx>> for DtorckConstraint<'tcx>
2718 fn from_iter<I: IntoIterator<Item=DtorckConstraint<'tcx>>>(iter: I) -> Self {
2719 let mut result = Self::empty();
2721 for constraint in iter {
2722 result.outlives.extend(constraint.outlives);
2723 result.dtorck_types.extend(constraint.dtorck_types);
2731 impl<'tcx> DtorckConstraint<'tcx> {
2732 fn empty() -> DtorckConstraint<'tcx> {
2735 dtorck_types: vec![]
2739 fn dedup<'a>(&mut self) {
2740 let mut outlives = FxHashSet();
2741 let mut dtorck_types = FxHashSet();
2743 self.outlives.retain(|&val| outlives.replace(val).is_none());
2744 self.dtorck_types.retain(|&val| dtorck_types.replace(val).is_none());
2748 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
2749 pub struct SymbolName {
2750 // FIXME: we don't rely on interning or equality here - better have
2751 // this be a `&'tcx str`.
2752 pub name: InternedString
2755 impl_stable_hash_for!(struct self::SymbolName {
2759 impl Deref for SymbolName {
2762 fn deref(&self) -> &str { &self.name }
2765 impl fmt::Display for SymbolName {
2766 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2767 fmt::Display::fmt(&self.name, fmt)