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::fold::TypeFoldable;
17 use hir::{map as hir_map, FreevarMap, TraitMap};
18 use hir::def::{Def, CtorKind, ExportMap};
19 use hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
20 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::cell::RefCell;
42 use std::cmp::Ordering;
44 use std::hash::{Hash, Hasher};
45 use std::iter::FromIterator;
49 use std::vec::IntoIter;
51 use syntax::ast::{self, DUMMY_NODE_ID, Name, Ident, NodeId};
53 use syntax::ext::hygiene::{Mark, SyntaxContext};
54 use syntax::symbol::{Symbol, InternedString};
55 use syntax_pos::{DUMMY_SP, Span};
56 use rustc_const_math::ConstInt;
58 use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
59 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
64 pub use self::sty::{Binder, DebruijnIndex};
65 pub use self::sty::{FnSig, GenSig, PolyFnSig, PolyGenSig};
66 pub use self::sty::{InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
67 pub use self::sty::{ClosureSubsts, GeneratorInterior, TypeAndMut};
68 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
69 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
70 pub use self::sty::{ExistentialProjection, PolyExistentialProjection, Const};
71 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
72 pub use self::sty::RegionKind;
73 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid, SkolemizedRegionVid};
74 pub use self::sty::BoundRegion::*;
75 pub use self::sty::InferTy::*;
76 pub use self::sty::RegionKind::*;
77 pub use self::sty::TypeVariants::*;
79 pub use self::binding::BindingMode;
80 pub use self::binding::BindingMode::*;
82 pub use self::context::{TyCtxt, GlobalArenas, AllArenas, tls, keep_local};
83 pub use self::context::{Lift, TypeckTables};
85 pub use self::instance::{Instance, InstanceDef};
87 pub use self::trait_def::TraitDef;
89 pub use self::maps::queries;
100 pub mod inhabitedness;
117 mod structural_impls;
122 /// The complete set of all analyses described in this module. This is
123 /// produced by the driver and fed to trans and later passes.
125 /// NB: These contents are being migrated into queries using the
126 /// *on-demand* infrastructure.
128 pub struct CrateAnalysis {
129 pub access_levels: Rc<AccessLevels>,
131 pub glob_map: Option<hir::GlobMap>,
135 pub struct Resolutions {
136 pub freevars: FreevarMap,
137 pub trait_map: TraitMap,
138 pub maybe_unused_trait_imports: NodeSet,
139 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
140 pub export_map: ExportMap,
143 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
144 pub enum AssociatedItemContainer {
145 TraitContainer(DefId),
146 ImplContainer(DefId),
149 impl AssociatedItemContainer {
150 /// Asserts that this is the def-id of an associated item declared
151 /// in a trait, and returns the trait def-id.
152 pub fn assert_trait(&self) -> DefId {
154 TraitContainer(id) => id,
155 _ => bug!("associated item has wrong container type: {:?}", self)
159 pub fn id(&self) -> DefId {
161 TraitContainer(id) => id,
162 ImplContainer(id) => id,
167 /// The "header" of an impl is everything outside the body: a Self type, a trait
168 /// ref (in the case of a trait impl), and a set of predicates (from the
169 /// bounds/where clauses).
170 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
171 pub struct ImplHeader<'tcx> {
172 pub impl_def_id: DefId,
173 pub self_ty: Ty<'tcx>,
174 pub trait_ref: Option<TraitRef<'tcx>>,
175 pub predicates: Vec<Predicate<'tcx>>,
178 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
179 pub struct AssociatedItem {
182 pub kind: AssociatedKind,
184 pub defaultness: hir::Defaultness,
185 pub container: AssociatedItemContainer,
187 /// Whether this is a method with an explicit self
188 /// as its first argument, allowing method calls.
189 pub method_has_self_argument: bool,
192 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, RustcEncodable, RustcDecodable)]
193 pub enum AssociatedKind {
199 impl AssociatedItem {
200 pub fn def(&self) -> Def {
202 AssociatedKind::Const => Def::AssociatedConst(self.def_id),
203 AssociatedKind::Method => Def::Method(self.def_id),
204 AssociatedKind::Type => Def::AssociatedTy(self.def_id),
208 /// Tests whether the associated item admits a non-trivial implementation
210 pub fn relevant_for_never<'tcx>(&self) -> bool {
212 AssociatedKind::Const => true,
213 AssociatedKind::Type => true,
214 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
215 AssociatedKind::Method => !self.method_has_self_argument,
219 pub fn signature<'a, 'tcx>(&self, tcx: &TyCtxt<'a, 'tcx, 'tcx>) -> String {
221 ty::AssociatedKind::Method => {
222 // We skip the binder here because the binder would deanonymize all
223 // late-bound regions, and we don't want method signatures to show up
224 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
225 // regions just fine, showing `fn(&MyType)`.
226 format!("{}", tcx.fn_sig(self.def_id).skip_binder())
228 ty::AssociatedKind::Type => format!("type {};", self.name.to_string()),
229 ty::AssociatedKind::Const => {
230 format!("const {}: {:?};", self.name.to_string(), tcx.type_of(self.def_id))
236 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
237 pub enum Visibility {
238 /// Visible everywhere (including in other crates).
240 /// Visible only in the given crate-local module.
242 /// Not visible anywhere in the local crate. This is the visibility of private external items.
246 pub trait DefIdTree: Copy {
247 fn parent(self, id: DefId) -> Option<DefId>;
249 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
250 if descendant.krate != ancestor.krate {
254 while descendant != ancestor {
255 match self.parent(descendant) {
256 Some(parent) => descendant = parent,
257 None => return false,
264 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
265 fn parent(self, id: DefId) -> Option<DefId> {
266 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
271 pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
273 hir::Public => Visibility::Public,
274 hir::Visibility::Crate => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
275 hir::Visibility::Restricted { ref path, .. } => match path.def {
276 // If there is no resolution, `resolve` will have already reported an error, so
277 // assume that the visibility is public to avoid reporting more privacy errors.
278 Def::Err => Visibility::Public,
279 def => Visibility::Restricted(def.def_id()),
282 Visibility::Restricted(tcx.hir.get_module_parent(id))
287 /// Returns true if an item with this visibility is accessible from the given block.
288 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
289 let restriction = match self {
290 // Public items are visible everywhere.
291 Visibility::Public => return true,
292 // Private items from other crates are visible nowhere.
293 Visibility::Invisible => return false,
294 // Restricted items are visible in an arbitrary local module.
295 Visibility::Restricted(other) if other.krate != module.krate => return false,
296 Visibility::Restricted(module) => module,
299 tree.is_descendant_of(module, restriction)
302 /// Returns true if this visibility is at least as accessible as the given visibility
303 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
304 let vis_restriction = match vis {
305 Visibility::Public => return self == Visibility::Public,
306 Visibility::Invisible => return true,
307 Visibility::Restricted(module) => module,
310 self.is_accessible_from(vis_restriction, tree)
313 // Returns true if this item is visible anywhere in the local crate.
314 pub fn is_visible_locally(self) -> bool {
316 Visibility::Public => true,
317 Visibility::Restricted(def_id) => def_id.is_local(),
318 Visibility::Invisible => false,
323 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
325 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
326 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
327 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
328 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
331 /// The crate variances map is computed during typeck and contains the
332 /// variance of every item in the local crate. You should not use it
333 /// directly, because to do so will make your pass dependent on the
334 /// HIR of every item in the local crate. Instead, use
335 /// `tcx.variances_of()` to get the variance for a *particular*
337 pub struct CrateVariancesMap {
338 /// For each item with generics, maps to a vector of the variance
339 /// of its generics. If an item has no generics, it will have no
341 pub variances: FxHashMap<DefId, Rc<Vec<ty::Variance>>>,
343 /// An empty vector, useful for cloning.
344 pub empty_variance: Rc<Vec<ty::Variance>>,
348 /// `a.xform(b)` combines the variance of a context with the
349 /// variance of a type with the following meaning. If we are in a
350 /// context with variance `a`, and we encounter a type argument in
351 /// a position with variance `b`, then `a.xform(b)` is the new
352 /// variance with which the argument appears.
358 /// Here, the "ambient" variance starts as covariant. `*mut T` is
359 /// invariant with respect to `T`, so the variance in which the
360 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
361 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
362 /// respect to its type argument `T`, and hence the variance of
363 /// the `i32` here is `Invariant.xform(Covariant)`, which results
364 /// (again) in `Invariant`.
368 /// fn(*const Vec<i32>, *mut Vec<i32)
370 /// The ambient variance is covariant. A `fn` type is
371 /// contravariant with respect to its parameters, so the variance
372 /// within which both pointer types appear is
373 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
374 /// T` is covariant with respect to `T`, so the variance within
375 /// which the first `Vec<i32>` appears is
376 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
377 /// is true for its `i32` argument. In the `*mut T` case, the
378 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
379 /// and hence the outermost type is `Invariant` with respect to
380 /// `Vec<i32>` (and its `i32` argument).
382 /// Source: Figure 1 of "Taming the Wildcards:
383 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
384 pub fn xform(self, v: ty::Variance) -> ty::Variance {
386 // Figure 1, column 1.
387 (ty::Covariant, ty::Covariant) => ty::Covariant,
388 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
389 (ty::Covariant, ty::Invariant) => ty::Invariant,
390 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
392 // Figure 1, column 2.
393 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
394 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
395 (ty::Contravariant, ty::Invariant) => ty::Invariant,
396 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
398 // Figure 1, column 3.
399 (ty::Invariant, _) => ty::Invariant,
401 // Figure 1, column 4.
402 (ty::Bivariant, _) => ty::Bivariant,
407 // Contains information needed to resolve types and (in the future) look up
408 // the types of AST nodes.
409 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
410 pub struct CReaderCacheKey {
415 // Flags that we track on types. These flags are propagated upwards
416 // through the type during type construction, so that we can quickly
417 // check whether the type has various kinds of types in it without
418 // recursing over the type itself.
420 pub struct TypeFlags: u32 {
421 const HAS_PARAMS = 1 << 0;
422 const HAS_SELF = 1 << 1;
423 const HAS_TY_INFER = 1 << 2;
424 const HAS_RE_INFER = 1 << 3;
425 const HAS_RE_SKOL = 1 << 4;
427 /// Does this have any `ReEarlyBound` regions? Used to
428 /// determine whether substitition is required, since those
429 /// represent regions that are bound in a `ty::Generics` and
430 /// hence may be substituted.
431 const HAS_RE_EARLY_BOUND = 1 << 5;
433 /// Does this have any region that "appears free" in the type?
434 /// Basically anything but `ReLateBound` and `ReErased`.
435 const HAS_FREE_REGIONS = 1 << 6;
437 /// Is an error type reachable?
438 const HAS_TY_ERR = 1 << 7;
439 const HAS_PROJECTION = 1 << 8;
441 // FIXME: Rename this to the actual property since it's used for generators too
442 const HAS_TY_CLOSURE = 1 << 9;
444 // true if there are "names" of types and regions and so forth
445 // that are local to a particular fn
446 const HAS_LOCAL_NAMES = 1 << 10;
448 // Present if the type belongs in a local type context.
449 // Only set for TyInfer other than Fresh.
450 const KEEP_IN_LOCAL_TCX = 1 << 11;
452 // Is there a projection that does not involve a bound region?
453 // Currently we can't normalize projections w/ bound regions.
454 const HAS_NORMALIZABLE_PROJECTION = 1 << 12;
456 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
457 TypeFlags::HAS_SELF.bits |
458 TypeFlags::HAS_RE_EARLY_BOUND.bits;
460 // Flags representing the nominal content of a type,
461 // computed by FlagsComputation. If you add a new nominal
462 // flag, it should be added here too.
463 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
464 TypeFlags::HAS_SELF.bits |
465 TypeFlags::HAS_TY_INFER.bits |
466 TypeFlags::HAS_RE_INFER.bits |
467 TypeFlags::HAS_RE_SKOL.bits |
468 TypeFlags::HAS_RE_EARLY_BOUND.bits |
469 TypeFlags::HAS_FREE_REGIONS.bits |
470 TypeFlags::HAS_TY_ERR.bits |
471 TypeFlags::HAS_PROJECTION.bits |
472 TypeFlags::HAS_TY_CLOSURE.bits |
473 TypeFlags::HAS_LOCAL_NAMES.bits |
474 TypeFlags::KEEP_IN_LOCAL_TCX.bits;
478 pub struct TyS<'tcx> {
479 pub sty: TypeVariants<'tcx>,
480 pub flags: TypeFlags,
482 // the maximal depth of any bound regions appearing in this type.
486 impl<'tcx> PartialEq for TyS<'tcx> {
488 fn eq(&self, other: &TyS<'tcx>) -> bool {
489 // (self as *const _) == (other as *const _)
490 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
493 impl<'tcx> Eq for TyS<'tcx> {}
495 impl<'tcx> Hash for TyS<'tcx> {
496 fn hash<H: Hasher>(&self, s: &mut H) {
497 (self as *const TyS).hash(s)
501 impl<'tcx> Ord for TyS<'tcx> {
503 fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
504 // (self as *const _).cmp(other as *const _)
505 (self as *const TyS<'tcx>).cmp(&(other as *const TyS<'tcx>))
508 impl<'tcx> PartialOrd for TyS<'tcx> {
510 fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
511 Some(self.cmp(other))
515 impl<'tcx> TyS<'tcx> {
516 pub fn is_primitive_ty(&self) -> bool {
518 TypeVariants::TyBool |
519 TypeVariants::TyChar |
520 TypeVariants::TyInt(_) |
521 TypeVariants::TyUint(_) |
522 TypeVariants::TyFloat(_) |
523 TypeVariants::TyInfer(InferTy::IntVar(_)) |
524 TypeVariants::TyInfer(InferTy::FloatVar(_)) |
525 TypeVariants::TyInfer(InferTy::FreshIntTy(_)) |
526 TypeVariants::TyInfer(InferTy::FreshFloatTy(_)) => true,
527 TypeVariants::TyRef(_, x) => x.ty.is_primitive_ty(),
532 pub fn is_suggestable(&self) -> bool {
534 TypeVariants::TyAnon(..) |
535 TypeVariants::TyFnDef(..) |
536 TypeVariants::TyFnPtr(..) |
537 TypeVariants::TyDynamic(..) |
538 TypeVariants::TyClosure(..) |
539 TypeVariants::TyInfer(..) |
540 TypeVariants::TyProjection(..) => false,
546 impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::TyS<'gcx> {
547 fn hash_stable<W: StableHasherResult>(&self,
548 hcx: &mut StableHashingContext<'gcx>,
549 hasher: &mut StableHasher<W>) {
553 // The other fields just provide fast access to information that is
554 // also contained in `sty`, so no need to hash them.
559 sty.hash_stable(hcx, hasher);
563 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
565 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
566 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
568 /// A wrapper for slices with the additional invariant
569 /// that the slice is interned and no other slice with
570 /// the same contents can exist in the same context.
571 /// This means we can use pointer + length for both
572 /// equality comparisons and hashing.
573 #[derive(Debug, RustcEncodable)]
574 pub struct Slice<T>([T]);
576 impl<T> PartialEq for Slice<T> {
578 fn eq(&self, other: &Slice<T>) -> bool {
579 (&self.0 as *const [T]) == (&other.0 as *const [T])
582 impl<T> Eq for Slice<T> {}
584 impl<T> Ord for Slice<T> {
586 fn cmp(&self, other: &Slice<T>) -> Ordering {
587 (&self.0 as *const [T]).cmp(&(&other.0 as *const [T]))
590 impl<T> PartialOrd for Slice<T> {
592 fn partial_cmp(&self, other: &Slice<T>) -> Option<Ordering> {
593 Some(self.cmp(other))
597 impl<T> Hash for Slice<T> {
598 fn hash<H: Hasher>(&self, s: &mut H) {
599 (self.as_ptr(), self.len()).hash(s)
603 impl<T> Deref for Slice<T> {
605 fn deref(&self) -> &[T] {
610 impl<'a, T> IntoIterator for &'a Slice<T> {
612 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
613 fn into_iter(self) -> Self::IntoIter {
618 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
621 pub fn empty<'a>() -> &'a Slice<T> {
623 mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
628 /// Upvars do not get their own node-id. Instead, we use the pair of
629 /// the original var id (that is, the root variable that is referenced
630 /// by the upvar) and the id of the closure expression.
631 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
633 pub var_id: hir::HirId,
634 pub closure_expr_id: LocalDefId,
637 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
638 pub enum BorrowKind {
639 /// Data must be immutable and is aliasable.
642 /// Data must be immutable but not aliasable. This kind of borrow
643 /// cannot currently be expressed by the user and is used only in
644 /// implicit closure bindings. It is needed when the closure
645 /// is borrowing or mutating a mutable referent, e.g.:
647 /// let x: &mut isize = ...;
648 /// let y = || *x += 5;
650 /// If we were to try to translate this closure into a more explicit
651 /// form, we'd encounter an error with the code as written:
653 /// struct Env { x: & &mut isize }
654 /// let x: &mut isize = ...;
655 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
656 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
658 /// This is then illegal because you cannot mutate a `&mut` found
659 /// in an aliasable location. To solve, you'd have to translate with
660 /// an `&mut` borrow:
662 /// struct Env { x: & &mut isize }
663 /// let x: &mut isize = ...;
664 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
665 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
667 /// Now the assignment to `**env.x` is legal, but creating a
668 /// mutable pointer to `x` is not because `x` is not mutable. We
669 /// could fix this by declaring `x` as `let mut x`. This is ok in
670 /// user code, if awkward, but extra weird for closures, since the
671 /// borrow is hidden.
673 /// So we introduce a "unique imm" borrow -- the referent is
674 /// immutable, but not aliasable. This solves the problem. For
675 /// simplicity, we don't give users the way to express this
676 /// borrow, it's just used when translating closures.
679 /// Data is mutable and not aliasable.
683 /// Information describing the capture of an upvar. This is computed
684 /// during `typeck`, specifically by `regionck`.
685 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
686 pub enum UpvarCapture<'tcx> {
687 /// Upvar is captured by value. This is always true when the
688 /// closure is labeled `move`, but can also be true in other cases
689 /// depending on inference.
692 /// Upvar is captured by reference.
693 ByRef(UpvarBorrow<'tcx>),
696 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
697 pub struct UpvarBorrow<'tcx> {
698 /// The kind of borrow: by-ref upvars have access to shared
699 /// immutable borrows, which are not part of the normal language
701 pub kind: BorrowKind,
703 /// Region of the resulting reference.
704 pub region: ty::Region<'tcx>,
707 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
709 #[derive(Copy, Clone)]
710 pub struct ClosureUpvar<'tcx> {
716 #[derive(Clone, Copy, PartialEq)]
717 pub enum IntVarValue {
719 UintType(ast::UintTy),
722 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
723 pub struct TypeParameterDef {
727 pub has_default: bool,
728 pub object_lifetime_default: ObjectLifetimeDefault,
730 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
731 /// on generic parameter `T`, asserts data behind the parameter
732 /// `T` won't be accessed during the parent type's `Drop` impl.
733 pub pure_wrt_drop: bool,
735 pub synthetic: Option<hir::SyntheticTyParamKind>,
738 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
739 pub struct RegionParameterDef {
744 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
745 /// on generic parameter `'a`, asserts data of lifetime `'a`
746 /// won't be accessed during the parent type's `Drop` impl.
747 pub pure_wrt_drop: bool,
750 impl RegionParameterDef {
751 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
752 ty::EarlyBoundRegion {
759 pub fn to_bound_region(&self) -> ty::BoundRegion {
760 self.to_early_bound_region_data().to_bound_region()
764 impl ty::EarlyBoundRegion {
765 pub fn to_bound_region(&self) -> ty::BoundRegion {
766 ty::BoundRegion::BrNamed(self.def_id, self.name)
770 /// Information about the formal type/lifetime parameters associated
771 /// with an item or method. Analogous to hir::Generics.
773 /// Note that in the presence of a `Self` parameter, the ordering here
774 /// is different from the ordering in a Substs. Substs are ordered as
775 /// Self, *Regions, *Other Type Params, (...child generics)
776 /// while this struct is ordered as
777 /// regions = Regions
778 /// types = [Self, *Other Type Params]
779 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
780 pub struct Generics {
781 pub parent: Option<DefId>,
782 pub parent_regions: u32,
783 pub parent_types: u32,
784 pub regions: Vec<RegionParameterDef>,
785 pub types: Vec<TypeParameterDef>,
787 /// Reverse map to each `TypeParameterDef`'s `index` field
788 pub type_param_to_index: FxHashMap<DefId, u32>,
791 pub has_late_bound_regions: Option<Span>,
794 impl<'a, 'gcx, 'tcx> Generics {
795 pub fn parent_count(&self) -> usize {
796 self.parent_regions as usize + self.parent_types as usize
799 pub fn own_count(&self) -> usize {
800 self.regions.len() + self.types.len()
803 pub fn count(&self) -> usize {
804 self.parent_count() + self.own_count()
807 pub fn region_param(&'tcx self,
808 param: &EarlyBoundRegion,
809 tcx: TyCtxt<'a, 'gcx, 'tcx>)
810 -> &'tcx RegionParameterDef
812 if let Some(index) = param.index.checked_sub(self.parent_count() as u32) {
813 &self.regions[index as usize - self.has_self as usize]
815 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
816 .region_param(param, tcx)
820 /// Returns the `TypeParameterDef` associated with this `ParamTy`.
821 pub fn type_param(&'tcx self,
823 tcx: TyCtxt<'a, 'gcx, 'tcx>)
824 -> &TypeParameterDef {
825 if let Some(idx) = param.idx.checked_sub(self.parent_count() as u32) {
826 // non-Self type parameters are always offset by exactly
827 // `self.regions.len()`. In the absence of a Self, this is obvious,
828 // but even in the presence of a `Self` we just have to "compensate"
831 // Without a `Self` (or in a nested generics that doesn't have
832 // a `Self` in itself, even through it parent does), for example
833 // for `fn foo<'a, T1, T2>()`, the situation is:
841 // And with a `Self`, for example for `trait Foo<'a, 'b, T1, T2>`, the
850 // And it can be seen that in both cases, to move from a substs
851 // offset to a generics offset you just have to offset by the
852 // number of regions.
853 let type_param_offset = self.regions.len();
855 let has_self = self.has_self && self.parent.is_none();
856 let is_separated_self = type_param_offset != 0 && idx == 0 && has_self;
858 if let Some(idx) = (idx as usize).checked_sub(type_param_offset) {
859 assert!(!is_separated_self, "found a Self after type_param_offset");
862 assert!(is_separated_self, "non-Self param before type_param_offset");
866 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
867 .type_param(param, tcx)
872 /// Bounds on generics.
873 #[derive(Clone, Default)]
874 pub struct GenericPredicates<'tcx> {
875 pub parent: Option<DefId>,
876 pub predicates: Vec<Predicate<'tcx>>,
879 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
880 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
882 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
883 pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
884 -> InstantiatedPredicates<'tcx> {
885 let mut instantiated = InstantiatedPredicates::empty();
886 self.instantiate_into(tcx, &mut instantiated, substs);
889 pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
890 -> InstantiatedPredicates<'tcx> {
891 InstantiatedPredicates {
892 predicates: self.predicates.subst(tcx, substs)
896 fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
897 instantiated: &mut InstantiatedPredicates<'tcx>,
898 substs: &Substs<'tcx>) {
899 if let Some(def_id) = self.parent {
900 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
902 instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
905 pub fn instantiate_identity(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
906 -> InstantiatedPredicates<'tcx> {
907 let mut instantiated = InstantiatedPredicates::empty();
908 self.instantiate_identity_into(tcx, &mut instantiated);
912 fn instantiate_identity_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
913 instantiated: &mut InstantiatedPredicates<'tcx>) {
914 if let Some(def_id) = self.parent {
915 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
917 instantiated.predicates.extend(&self.predicates)
920 pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
921 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
922 -> InstantiatedPredicates<'tcx>
924 assert_eq!(self.parent, None);
925 InstantiatedPredicates {
926 predicates: self.predicates.iter().map(|pred| {
927 pred.subst_supertrait(tcx, poly_trait_ref)
933 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
934 pub enum Predicate<'tcx> {
935 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
936 /// the `Self` type of the trait reference and `A`, `B`, and `C`
937 /// would be the type parameters.
938 Trait(PolyTraitPredicate<'tcx>),
940 /// where `T1 == T2`.
941 Equate(PolyEquatePredicate<'tcx>),
944 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
947 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
949 /// where <T as TraitRef>::Name == X, approximately.
950 /// See `ProjectionPredicate` struct for details.
951 Projection(PolyProjectionPredicate<'tcx>),
954 WellFormed(Ty<'tcx>),
956 /// trait must be object-safe
959 /// No direct syntax. May be thought of as `where T : FnFoo<...>`
960 /// for some substitutions `...` and T being a closure type.
961 /// Satisfied (or refuted) once we know the closure's kind.
962 ClosureKind(DefId, ClosureSubsts<'tcx>, ClosureKind),
965 Subtype(PolySubtypePredicate<'tcx>),
967 /// Constant initializer must evaluate successfully.
968 ConstEvaluatable(DefId, &'tcx Substs<'tcx>),
971 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
972 fn as_ref(&self) -> &Predicate<'tcx> {
977 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
978 /// Performs a substitution suitable for going from a
979 /// poly-trait-ref to supertraits that must hold if that
980 /// poly-trait-ref holds. This is slightly different from a normal
981 /// substitution in terms of what happens with bound regions. See
982 /// lengthy comment below for details.
983 pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
984 trait_ref: &ty::PolyTraitRef<'tcx>)
985 -> ty::Predicate<'tcx>
987 // The interaction between HRTB and supertraits is not entirely
988 // obvious. Let me walk you (and myself) through an example.
990 // Let's start with an easy case. Consider two traits:
992 // trait Foo<'a> : Bar<'a,'a> { }
993 // trait Bar<'b,'c> { }
995 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
996 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
997 // knew that `Foo<'x>` (for any 'x) then we also know that
998 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
999 // normal substitution.
1001 // In terms of why this is sound, the idea is that whenever there
1002 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1003 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1004 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1007 // Another example to be careful of is this:
1009 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
1010 // trait Bar1<'b,'c> { }
1012 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
1013 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
1014 // reason is similar to the previous example: any impl of
1015 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
1016 // basically we would want to collapse the bound lifetimes from
1017 // the input (`trait_ref`) and the supertraits.
1019 // To achieve this in practice is fairly straightforward. Let's
1020 // consider the more complicated scenario:
1022 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
1023 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
1024 // where both `'x` and `'b` would have a DB index of 1.
1025 // The substitution from the input trait-ref is therefore going to be
1026 // `'a => 'x` (where `'x` has a DB index of 1).
1027 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1028 // early-bound parameter and `'b' is a late-bound parameter with a
1030 // - If we replace `'a` with `'x` from the input, it too will have
1031 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1032 // just as we wanted.
1034 // There is only one catch. If we just apply the substitution `'a
1035 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1036 // adjust the DB index because we substituting into a binder (it
1037 // tries to be so smart...) resulting in `for<'x> for<'b>
1038 // Bar1<'x,'b>` (we have no syntax for this, so use your
1039 // imagination). Basically the 'x will have DB index of 2 and 'b
1040 // will have DB index of 1. Not quite what we want. So we apply
1041 // the substitution to the *contents* of the trait reference,
1042 // rather than the trait reference itself (put another way, the
1043 // substitution code expects equal binding levels in the values
1044 // from the substitution and the value being substituted into, and
1045 // this trick achieves that).
1047 let substs = &trait_ref.0.substs;
1049 Predicate::Trait(ty::Binder(ref data)) =>
1050 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
1051 Predicate::Equate(ty::Binder(ref data)) =>
1052 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
1053 Predicate::Subtype(ty::Binder(ref data)) =>
1054 Predicate::Subtype(ty::Binder(data.subst(tcx, substs))),
1055 Predicate::RegionOutlives(ty::Binder(ref data)) =>
1056 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
1057 Predicate::TypeOutlives(ty::Binder(ref data)) =>
1058 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
1059 Predicate::Projection(ty::Binder(ref data)) =>
1060 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
1061 Predicate::WellFormed(data) =>
1062 Predicate::WellFormed(data.subst(tcx, substs)),
1063 Predicate::ObjectSafe(trait_def_id) =>
1064 Predicate::ObjectSafe(trait_def_id),
1065 Predicate::ClosureKind(closure_def_id, closure_substs, kind) =>
1066 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind),
1067 Predicate::ConstEvaluatable(def_id, const_substs) =>
1068 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs)),
1073 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1074 pub struct TraitPredicate<'tcx> {
1075 pub trait_ref: TraitRef<'tcx>
1077 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1079 impl<'tcx> TraitPredicate<'tcx> {
1080 pub fn def_id(&self) -> DefId {
1081 self.trait_ref.def_id
1084 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
1085 self.trait_ref.input_types()
1088 pub fn self_ty(&self) -> Ty<'tcx> {
1089 self.trait_ref.self_ty()
1093 impl<'tcx> PolyTraitPredicate<'tcx> {
1094 pub fn def_id(&self) -> DefId {
1095 // ok to skip binder since trait def-id does not care about regions
1100 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1101 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
1102 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
1104 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1105 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
1106 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
1107 pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<ty::Region<'tcx>,
1109 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1111 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1112 pub struct SubtypePredicate<'tcx> {
1113 pub a_is_expected: bool,
1117 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1119 /// This kind of predicate has no *direct* correspondent in the
1120 /// syntax, but it roughly corresponds to the syntactic forms:
1122 /// 1. `T : TraitRef<..., Item=Type>`
1123 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1125 /// In particular, form #1 is "desugared" to the combination of a
1126 /// normal trait predicate (`T : TraitRef<...>`) and one of these
1127 /// predicates. Form #2 is a broader form in that it also permits
1128 /// equality between arbitrary types. Processing an instance of
1129 /// Form #2 eventually yields one of these `ProjectionPredicate`
1130 /// instances to normalize the LHS.
1131 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1132 pub struct ProjectionPredicate<'tcx> {
1133 pub projection_ty: ProjectionTy<'tcx>,
1137 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1139 impl<'tcx> PolyProjectionPredicate<'tcx> {
1140 pub fn to_poly_trait_ref(&self, tcx: TyCtxt) -> PolyTraitRef<'tcx> {
1141 // Note: unlike with TraitRef::to_poly_trait_ref(),
1142 // self.0.trait_ref is permitted to have escaping regions.
1143 // This is because here `self` has a `Binder` and so does our
1144 // return value, so we are preserving the number of binding
1146 ty::Binder(self.0.projection_ty.trait_ref(tcx))
1149 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1150 Binder(self.skip_binder().ty) // preserves binding levels
1154 pub trait ToPolyTraitRef<'tcx> {
1155 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1158 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1159 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1160 assert!(!self.has_escaping_regions());
1161 ty::Binder(self.clone())
1165 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1166 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1167 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1171 pub trait ToPredicate<'tcx> {
1172 fn to_predicate(&self) -> Predicate<'tcx>;
1175 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1176 fn to_predicate(&self) -> Predicate<'tcx> {
1177 // we're about to add a binder, so let's check that we don't
1178 // accidentally capture anything, or else that might be some
1179 // weird debruijn accounting.
1180 assert!(!self.has_escaping_regions());
1182 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1183 trait_ref: self.clone()
1188 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1189 fn to_predicate(&self) -> Predicate<'tcx> {
1190 ty::Predicate::Trait(self.to_poly_trait_predicate())
1194 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
1195 fn to_predicate(&self) -> Predicate<'tcx> {
1196 Predicate::Equate(self.clone())
1200 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1201 fn to_predicate(&self) -> Predicate<'tcx> {
1202 Predicate::RegionOutlives(self.clone())
1206 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1207 fn to_predicate(&self) -> Predicate<'tcx> {
1208 Predicate::TypeOutlives(self.clone())
1212 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1213 fn to_predicate(&self) -> Predicate<'tcx> {
1214 Predicate::Projection(self.clone())
1218 impl<'tcx> Predicate<'tcx> {
1219 /// Iterates over the types in this predicate. Note that in all
1220 /// cases this is skipping over a binder, so late-bound regions
1221 /// with depth 0 are bound by the predicate.
1222 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1223 let vec: Vec<_> = match *self {
1224 ty::Predicate::Trait(ref data) => {
1225 data.skip_binder().input_types().collect()
1227 ty::Predicate::Equate(ty::Binder(ref data)) => {
1228 vec![data.0, data.1]
1230 ty::Predicate::Subtype(ty::Binder(SubtypePredicate { a, b, a_is_expected: _ })) => {
1233 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1236 ty::Predicate::RegionOutlives(..) => {
1239 ty::Predicate::Projection(ref data) => {
1240 data.0.projection_ty.substs.types().chain(Some(data.0.ty)).collect()
1242 ty::Predicate::WellFormed(data) => {
1245 ty::Predicate::ObjectSafe(_trait_def_id) => {
1248 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1249 closure_substs.substs.types().collect()
1251 ty::Predicate::ConstEvaluatable(_, substs) => {
1252 substs.types().collect()
1256 // The only reason to collect into a vector here is that I was
1257 // too lazy to make the full (somewhat complicated) iterator
1258 // type that would be needed here. But I wanted this fn to
1259 // return an iterator conceptually, rather than a `Vec`, so as
1260 // to be closer to `Ty::walk`.
1264 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1266 Predicate::Trait(ref t) => {
1267 Some(t.to_poly_trait_ref())
1269 Predicate::Projection(..) |
1270 Predicate::Equate(..) |
1271 Predicate::Subtype(..) |
1272 Predicate::RegionOutlives(..) |
1273 Predicate::WellFormed(..) |
1274 Predicate::ObjectSafe(..) |
1275 Predicate::ClosureKind(..) |
1276 Predicate::TypeOutlives(..) |
1277 Predicate::ConstEvaluatable(..) => {
1283 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1285 Predicate::TypeOutlives(data) => {
1288 Predicate::Trait(..) |
1289 Predicate::Projection(..) |
1290 Predicate::Equate(..) |
1291 Predicate::Subtype(..) |
1292 Predicate::RegionOutlives(..) |
1293 Predicate::WellFormed(..) |
1294 Predicate::ObjectSafe(..) |
1295 Predicate::ClosureKind(..) |
1296 Predicate::ConstEvaluatable(..) => {
1303 /// Represents the bounds declared on a particular set of type
1304 /// parameters. Should eventually be generalized into a flag list of
1305 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
1306 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1307 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1308 /// the `GenericPredicates` are expressed in terms of the bound type
1309 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1310 /// represented a set of bounds for some particular instantiation,
1311 /// meaning that the generic parameters have been substituted with
1316 /// struct Foo<T,U:Bar<T>> { ... }
1318 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1319 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1320 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1321 /// [usize:Bar<isize>]]`.
1323 pub struct InstantiatedPredicates<'tcx> {
1324 pub predicates: Vec<Predicate<'tcx>>,
1327 impl<'tcx> InstantiatedPredicates<'tcx> {
1328 pub fn empty() -> InstantiatedPredicates<'tcx> {
1329 InstantiatedPredicates { predicates: vec![] }
1332 pub fn is_empty(&self) -> bool {
1333 self.predicates.is_empty()
1337 /// When type checking, we use the `ParamEnv` to track
1338 /// details about the set of where-clauses that are in scope at this
1339 /// particular point.
1340 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1341 pub struct ParamEnv<'tcx> {
1342 /// Obligations that the caller must satisfy. This is basically
1343 /// the set of bounds on the in-scope type parameters, translated
1344 /// into Obligations, and elaborated and normalized.
1345 pub caller_bounds: &'tcx Slice<ty::Predicate<'tcx>>,
1347 /// Typically, this is `Reveal::UserFacing`, but during trans we
1348 /// want `Reveal::All` -- note that this is always paired with an
1349 /// empty environment. To get that, use `ParamEnv::reveal()`.
1350 pub reveal: traits::Reveal,
1353 impl<'tcx> ParamEnv<'tcx> {
1354 /// Creates a suitable environment in which to perform trait
1355 /// queries on the given value. This will either be `self` *or*
1356 /// the empty environment, depending on whether `value` references
1357 /// type parameters that are in scope. (If it doesn't, then any
1358 /// judgements should be completely independent of the context,
1359 /// and hence we can safely use the empty environment so as to
1360 /// enable more sharing across functions.)
1362 /// NB: This is a mildly dubious thing to do, in that a function
1363 /// (or other environment) might have wacky where-clauses like
1364 /// `where Box<u32>: Copy`, which are clearly never
1365 /// satisfiable. The code will at present ignore these,
1366 /// effectively, when type-checking the body of said
1367 /// function. This preserves existing behavior in any
1368 /// case. --nmatsakis
1369 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1370 assert!(!value.needs_infer());
1371 if value.has_param_types() || value.has_self_ty() {
1378 param_env: ParamEnv::empty(self.reveal),
1385 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1386 pub struct ParamEnvAnd<'tcx, T> {
1387 pub param_env: ParamEnv<'tcx>,
1391 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1392 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1393 (self.param_env, self.value)
1397 impl<'gcx, T> HashStable<StableHashingContext<'gcx>> for ParamEnvAnd<'gcx, T>
1398 where T: HashStable<StableHashingContext<'gcx>>
1400 fn hash_stable<W: StableHasherResult>(&self,
1401 hcx: &mut StableHashingContext<'gcx>,
1402 hasher: &mut StableHasher<W>) {
1408 param_env.hash_stable(hcx, hasher);
1409 value.hash_stable(hcx, hasher);
1413 #[derive(Copy, Clone, Debug)]
1414 pub struct Destructor {
1415 /// The def-id of the destructor method
1420 pub struct AdtFlags: u32 {
1421 const NO_ADT_FLAGS = 0;
1422 const IS_ENUM = 1 << 0;
1423 const IS_PHANTOM_DATA = 1 << 1;
1424 const IS_FUNDAMENTAL = 1 << 2;
1425 const IS_UNION = 1 << 3;
1426 const IS_BOX = 1 << 4;
1427 /// Indicates whether this abstract data type will be expanded on in future (new
1428 /// fields/variants) and as such, whether downstream crates must match exhaustively on the
1429 /// fields/variants of this data type.
1431 /// See RFC 2008 (<https://github.com/rust-lang/rfcs/pull/2008>).
1432 const IS_NON_EXHAUSTIVE = 1 << 5;
1437 pub struct VariantDef {
1438 /// The variant's DefId. If this is a tuple-like struct,
1439 /// this is the DefId of the struct's ctor.
1441 pub name: Name, // struct's name if this is a struct
1442 pub discr: VariantDiscr,
1443 pub fields: Vec<FieldDef>,
1444 pub ctor_kind: CtorKind,
1447 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1448 pub enum VariantDiscr {
1449 /// Explicit value for this variant, i.e. `X = 123`.
1450 /// The `DefId` corresponds to the embedded constant.
1453 /// The previous variant's discriminant plus one.
1454 /// For efficiency reasons, the distance from the
1455 /// last `Explicit` discriminant is being stored,
1456 /// or `0` for the first variant, if it has none.
1461 pub struct FieldDef {
1464 pub vis: Visibility,
1467 /// The definition of an abstract data type - a struct or enum.
1469 /// These are all interned (by intern_adt_def) into the adt_defs
1473 pub variants: Vec<VariantDef>,
1475 pub repr: ReprOptions,
1478 impl PartialEq for AdtDef {
1479 // AdtDef are always interned and this is part of TyS equality
1481 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1484 impl Eq for AdtDef {}
1486 impl Hash for AdtDef {
1488 fn hash<H: Hasher>(&self, s: &mut H) {
1489 (self as *const AdtDef).hash(s)
1493 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1494 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1499 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1502 impl<'gcx> HashStable<StableHashingContext<'gcx>> for AdtDef {
1503 fn hash_stable<W: StableHasherResult>(&self,
1504 hcx: &mut StableHashingContext<'gcx>,
1505 hasher: &mut StableHasher<W>) {
1507 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> =
1508 RefCell::new(FxHashMap());
1511 let hash: Fingerprint = CACHE.with(|cache| {
1512 let addr = self as *const AdtDef as usize;
1513 *cache.borrow_mut().entry(addr).or_insert_with(|| {
1521 let mut hasher = StableHasher::new();
1522 did.hash_stable(hcx, &mut hasher);
1523 variants.hash_stable(hcx, &mut hasher);
1524 flags.hash_stable(hcx, &mut hasher);
1525 repr.hash_stable(hcx, &mut hasher);
1531 hash.hash_stable(hcx, hasher);
1535 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1536 pub enum AdtKind { Struct, Union, Enum }
1539 #[derive(RustcEncodable, RustcDecodable, Default)]
1540 pub struct ReprFlags: u8 {
1541 const IS_C = 1 << 0;
1542 const IS_PACKED = 1 << 1;
1543 const IS_SIMD = 1 << 2;
1544 const IS_TRANSPARENT = 1 << 3;
1545 // Internal only for now. If true, don't reorder fields.
1546 const IS_LINEAR = 1 << 4;
1548 // Any of these flags being set prevent field reordering optimisation.
1549 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1550 ReprFlags::IS_PACKED.bits |
1551 ReprFlags::IS_SIMD.bits |
1552 ReprFlags::IS_LINEAR.bits;
1556 impl_stable_hash_for!(struct ReprFlags {
1562 /// Represents the repr options provided by the user,
1563 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1564 pub struct ReprOptions {
1565 pub int: Option<attr::IntType>,
1567 pub flags: ReprFlags,
1570 impl_stable_hash_for!(struct ReprOptions {
1577 pub fn new(tcx: TyCtxt, did: DefId) -> ReprOptions {
1578 let mut flags = ReprFlags::empty();
1579 let mut size = None;
1580 let mut max_align = 0;
1581 for attr in tcx.get_attrs(did).iter() {
1582 for r in attr::find_repr_attrs(tcx.sess.diagnostic(), attr) {
1583 flags.insert(match r {
1584 attr::ReprC => ReprFlags::IS_C,
1585 attr::ReprPacked => ReprFlags::IS_PACKED,
1586 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1587 attr::ReprSimd => ReprFlags::IS_SIMD,
1588 attr::ReprInt(i) => {
1592 attr::ReprAlign(align) => {
1593 max_align = cmp::max(align, max_align);
1600 // This is here instead of layout because the choice must make it into metadata.
1601 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.item_path_str(did))) {
1602 flags.insert(ReprFlags::IS_LINEAR);
1604 ReprOptions { int: size, align: max_align, flags: flags }
1608 pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
1610 pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
1612 pub fn packed(&self) -> bool { self.flags.contains(ReprFlags::IS_PACKED) }
1614 pub fn transparent(&self) -> bool { self.flags.contains(ReprFlags::IS_TRANSPARENT) }
1616 pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
1618 pub fn discr_type(&self) -> attr::IntType {
1619 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
1622 /// Returns true if this `#[repr()]` should inhabit "smart enum
1623 /// layout" optimizations, such as representing `Foo<&T>` as a
1625 pub fn inhibit_enum_layout_opt(&self) -> bool {
1626 self.c() || self.int.is_some()
1630 impl<'a, 'gcx, 'tcx> AdtDef {
1634 variants: Vec<VariantDef>,
1635 repr: ReprOptions) -> Self {
1636 let mut flags = AdtFlags::NO_ADT_FLAGS;
1637 let attrs = tcx.get_attrs(did);
1638 if attr::contains_name(&attrs, "fundamental") {
1639 flags = flags | AdtFlags::IS_FUNDAMENTAL;
1641 if Some(did) == tcx.lang_items().phantom_data() {
1642 flags = flags | AdtFlags::IS_PHANTOM_DATA;
1644 if Some(did) == tcx.lang_items().owned_box() {
1645 flags = flags | AdtFlags::IS_BOX;
1647 if tcx.has_attr(did, "non_exhaustive") {
1648 flags = flags | AdtFlags::IS_NON_EXHAUSTIVE;
1651 AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1652 AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1653 AdtKind::Struct => {}
1664 pub fn is_struct(&self) -> bool {
1665 !self.is_union() && !self.is_enum()
1669 pub fn is_union(&self) -> bool {
1670 self.flags.intersects(AdtFlags::IS_UNION)
1674 pub fn is_enum(&self) -> bool {
1675 self.flags.intersects(AdtFlags::IS_ENUM)
1679 pub fn is_non_exhaustive(&self) -> bool {
1680 self.flags.intersects(AdtFlags::IS_NON_EXHAUSTIVE)
1683 /// Returns the kind of the ADT - Struct or Enum.
1685 pub fn adt_kind(&self) -> AdtKind {
1688 } else if self.is_union() {
1695 pub fn descr(&self) -> &'static str {
1696 match self.adt_kind() {
1697 AdtKind::Struct => "struct",
1698 AdtKind::Union => "union",
1699 AdtKind::Enum => "enum",
1703 pub fn variant_descr(&self) -> &'static str {
1704 match self.adt_kind() {
1705 AdtKind::Struct => "struct",
1706 AdtKind::Union => "union",
1707 AdtKind::Enum => "variant",
1711 /// Returns whether this type is #[fundamental] for the purposes
1712 /// of coherence checking.
1714 pub fn is_fundamental(&self) -> bool {
1715 self.flags.intersects(AdtFlags::IS_FUNDAMENTAL)
1718 /// Returns true if this is PhantomData<T>.
1720 pub fn is_phantom_data(&self) -> bool {
1721 self.flags.intersects(AdtFlags::IS_PHANTOM_DATA)
1724 /// Returns true if this is Box<T>.
1726 pub fn is_box(&self) -> bool {
1727 self.flags.intersects(AdtFlags::IS_BOX)
1730 /// Returns whether this type has a destructor.
1731 pub fn has_dtor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1732 self.destructor(tcx).is_some()
1735 /// Asserts this is a struct or union and returns its unique variant.
1736 pub fn non_enum_variant(&self) -> &VariantDef {
1737 assert!(self.is_struct() || self.is_union());
1742 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1743 tcx.predicates_of(self.did)
1746 /// Returns an iterator over all fields contained
1749 pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1750 self.variants.iter().flat_map(|v| v.fields.iter())
1753 pub fn is_payloadfree(&self) -> bool {
1754 !self.variants.is_empty() &&
1755 self.variants.iter().all(|v| v.fields.is_empty())
1758 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1761 .find(|v| v.did == vid)
1762 .expect("variant_with_id: unknown variant")
1765 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1768 .position(|v| v.did == vid)
1769 .expect("variant_index_with_id: unknown variant")
1772 pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1774 Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1775 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1776 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.non_enum_variant(),
1777 _ => bug!("unexpected def {:?} in variant_of_def", def)
1782 pub fn discriminants(&'a self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
1783 -> impl Iterator<Item=ConstInt> + 'a {
1784 let param_env = ParamEnv::empty(traits::Reveal::UserFacing);
1785 let repr_type = self.repr.discr_type();
1786 let initial = repr_type.initial_discriminant(tcx.global_tcx());
1787 let mut prev_discr = None::<ConstInt>;
1788 self.variants.iter().map(move |v| {
1789 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr());
1790 if let VariantDiscr::Explicit(expr_did) = v.discr {
1791 let substs = Substs::identity_for_item(tcx.global_tcx(), expr_did);
1792 match tcx.const_eval(param_env.and((expr_did, substs))) {
1793 Ok(&ty::Const { val: ConstVal::Integral(v), .. }) => {
1797 if !expr_did.is_local() {
1798 span_bug!(tcx.def_span(expr_did),
1799 "variant discriminant evaluation succeeded \
1800 in its crate but failed locally: {:?}", err);
1805 prev_discr = Some(discr);
1811 /// Compute the discriminant value used by a specific variant.
1812 /// Unlike `discriminants`, this is (amortized) constant-time,
1813 /// only doing at most one query for evaluating an explicit
1814 /// discriminant (the last one before the requested variant),
1815 /// assuming there are no constant-evaluation errors there.
1816 pub fn discriminant_for_variant(&self,
1817 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1818 variant_index: usize)
1820 let param_env = ParamEnv::empty(traits::Reveal::UserFacing);
1821 let repr_type = self.repr.discr_type();
1822 let mut explicit_value = repr_type.initial_discriminant(tcx.global_tcx());
1823 let mut explicit_index = variant_index;
1825 match self.variants[explicit_index].discr {
1826 ty::VariantDiscr::Relative(0) => break,
1827 ty::VariantDiscr::Relative(distance) => {
1828 explicit_index -= distance;
1830 ty::VariantDiscr::Explicit(expr_did) => {
1831 let substs = Substs::identity_for_item(tcx.global_tcx(), expr_did);
1832 match tcx.const_eval(param_env.and((expr_did, substs))) {
1833 Ok(&ty::Const { val: ConstVal::Integral(v), .. }) => {
1838 if !expr_did.is_local() {
1839 span_bug!(tcx.def_span(expr_did),
1840 "variant discriminant evaluation succeeded \
1841 in its crate but failed locally: {:?}", err);
1843 if explicit_index == 0 {
1846 explicit_index -= 1;
1852 let discr = explicit_value.to_u128_unchecked()
1853 .wrapping_add((variant_index - explicit_index) as u128);
1855 attr::UnsignedInt(ty) => {
1856 ConstInt::new_unsigned_truncating(discr, ty,
1857 tcx.sess.target.usize_ty)
1859 attr::SignedInt(ty) => {
1860 ConstInt::new_signed_truncating(discr as i128, ty,
1861 tcx.sess.target.isize_ty)
1866 pub fn destructor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Destructor> {
1867 tcx.adt_destructor(self.did)
1870 /// Returns a list of types such that `Self: Sized` if and only
1871 /// if that type is Sized, or `TyErr` if this type is recursive.
1873 /// Oddly enough, checking that the sized-constraint is Sized is
1874 /// actually more expressive than checking all members:
1875 /// the Sized trait is inductive, so an associated type that references
1876 /// Self would prevent its containing ADT from being Sized.
1878 /// Due to normalization being eager, this applies even if
1879 /// the associated type is behind a pointer, e.g. issue #31299.
1880 pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] {
1881 match queries::adt_sized_constraint::try_get(tcx, DUMMY_SP, self.did) {
1884 debug!("adt_sized_constraint: {:?} is recursive", self);
1885 // This should be reported as an error by `check_representable`.
1887 // Consider the type as Sized in the meanwhile to avoid
1888 // further errors. Delay our `bug` diagnostic here to get
1889 // emitted later as well in case we accidentally otherwise don't
1892 tcx.intern_type_list(&[tcx.types.err])
1897 fn sized_constraint_for_ty(&self,
1898 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1901 let result = match ty.sty {
1902 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
1903 TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
1904 TyArray(..) | TyClosure(..) | TyGenerator(..) | TyNever => {
1913 TyGeneratorWitness(..) => {
1914 // these are never sized - return the target type
1918 TyTuple(ref tys, _) => {
1921 Some(ty) => self.sized_constraint_for_ty(tcx, ty)
1925 TyAdt(adt, substs) => {
1927 let adt_tys = adt.sized_constraint(tcx);
1928 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
1931 .map(|ty| ty.subst(tcx, substs))
1932 .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
1936 TyProjection(..) | TyAnon(..) => {
1937 // must calculate explicitly.
1938 // FIXME: consider special-casing always-Sized projections
1943 // perf hack: if there is a `T: Sized` bound, then
1944 // we know that `T` is Sized and do not need to check
1947 let sized_trait = match tcx.lang_items().sized_trait() {
1949 _ => return vec![ty]
1951 let sized_predicate = Binder(TraitRef {
1952 def_id: sized_trait,
1953 substs: tcx.mk_substs_trait(ty, &[])
1955 let predicates = tcx.predicates_of(self.did).predicates;
1956 if predicates.into_iter().any(|p| p == sized_predicate) {
1964 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
1968 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
1973 impl<'a, 'gcx, 'tcx> VariantDef {
1975 pub fn find_field_named(&self, name: ast::Name) -> Option<&FieldDef> {
1976 self.index_of_field_named(name).map(|index| &self.fields[index])
1979 pub fn index_of_field_named(&self, name: ast::Name) -> Option<usize> {
1980 if let Some(index) = self.fields.iter().position(|f| f.name == name) {
1983 let mut ident = name.to_ident();
1984 while ident.ctxt != SyntaxContext::empty() {
1985 ident.ctxt.remove_mark();
1986 if let Some(field) = self.fields.iter().position(|f| f.name.to_ident() == ident) {
1994 pub fn field_named(&self, name: ast::Name) -> &FieldDef {
1995 self.find_field_named(name).unwrap()
1999 impl<'a, 'gcx, 'tcx> FieldDef {
2000 pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
2001 tcx.type_of(self.did).subst(tcx, subst)
2005 /// Represents the various closure traits in the Rust language. This
2006 /// will determine the type of the environment (`self`, in the
2007 /// desuaring) argument that the closure expects.
2009 /// You can get the environment type of a closure using
2010 /// `tcx.closure_env_ty()`.
2011 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
2012 pub enum ClosureKind {
2013 // Warning: Ordering is significant here! The ordering is chosen
2014 // because the trait Fn is a subtrait of FnMut and so in turn, and
2015 // hence we order it so that Fn < FnMut < FnOnce.
2021 impl<'a, 'tcx> ClosureKind {
2022 // This is the initial value used when doing upvar inference.
2023 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2025 pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
2027 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
2028 ClosureKind::FnMut => {
2029 tcx.require_lang_item(FnMutTraitLangItem)
2031 ClosureKind::FnOnce => {
2032 tcx.require_lang_item(FnOnceTraitLangItem)
2037 /// True if this a type that impls this closure kind
2038 /// must also implement `other`.
2039 pub fn extends(self, other: ty::ClosureKind) -> bool {
2040 match (self, other) {
2041 (ClosureKind::Fn, ClosureKind::Fn) => true,
2042 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2043 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2044 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2045 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2046 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2051 /// Returns the representative scalar type for this closure kind.
2052 /// See `TyS::to_opt_closure_kind` for more details.
2053 pub fn to_ty(self, tcx: TyCtxt<'_, '_, 'tcx>) -> Ty<'tcx> {
2055 ty::ClosureKind::Fn => tcx.types.i8,
2056 ty::ClosureKind::FnMut => tcx.types.i16,
2057 ty::ClosureKind::FnOnce => tcx.types.i32,
2062 impl<'tcx> TyS<'tcx> {
2063 /// Iterator that walks `self` and any types reachable from
2064 /// `self`, in depth-first order. Note that just walks the types
2065 /// that appear in `self`, it does not descend into the fields of
2066 /// structs or variants. For example:
2069 /// isize => { isize }
2070 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2071 /// [isize] => { [isize], isize }
2073 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2074 TypeWalker::new(self)
2077 /// Iterator that walks the immediate children of `self`. Hence
2078 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2079 /// (but not `i32`, like `walk`).
2080 pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
2081 walk::walk_shallow(self)
2084 /// Walks `ty` and any types appearing within `ty`, invoking the
2085 /// callback `f` on each type. If the callback returns false, then the
2086 /// children of the current type are ignored.
2088 /// Note: prefer `ty.walk()` where possible.
2089 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2090 where F : FnMut(Ty<'tcx>) -> bool
2092 let mut walker = self.walk();
2093 while let Some(ty) = walker.next() {
2095 walker.skip_current_subtree();
2102 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2104 hir::MutMutable => MutBorrow,
2105 hir::MutImmutable => ImmBorrow,
2109 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2110 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2111 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2113 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2115 MutBorrow => hir::MutMutable,
2116 ImmBorrow => hir::MutImmutable,
2118 // We have no type corresponding to a unique imm borrow, so
2119 // use `&mut`. It gives all the capabilities of an `&uniq`
2120 // and hence is a safe "over approximation".
2121 UniqueImmBorrow => hir::MutMutable,
2125 pub fn to_user_str(&self) -> &'static str {
2127 MutBorrow => "mutable",
2128 ImmBorrow => "immutable",
2129 UniqueImmBorrow => "uniquely immutable",
2134 #[derive(Debug, Clone)]
2135 pub enum Attributes<'gcx> {
2136 Owned(Rc<[ast::Attribute]>),
2137 Borrowed(&'gcx [ast::Attribute])
2140 impl<'gcx> ::std::ops::Deref for Attributes<'gcx> {
2141 type Target = [ast::Attribute];
2143 fn deref(&self) -> &[ast::Attribute] {
2145 &Attributes::Owned(ref data) => &data,
2146 &Attributes::Borrowed(data) => data
2151 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2152 pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
2153 self.typeck_tables_of(self.hir.body_owner_def_id(body))
2156 /// Returns an iterator of the def-ids for all body-owners in this
2157 /// crate. If you would prefer to iterate over the bodies
2158 /// themselves, you can do `self.hir.krate().body_ids.iter()`.
2159 pub fn body_owners(self) -> impl Iterator<Item = DefId> + 'a {
2163 .map(move |&body_id| self.hir.body_owner_def_id(body_id))
2166 pub fn expr_span(self, id: NodeId) -> Span {
2167 match self.hir.find(id) {
2168 Some(hir_map::NodeExpr(e)) => {
2172 bug!("Node id {} is not an expr: {:?}", id, f);
2175 bug!("Node id {} is not present in the node map", id);
2180 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2181 self.associated_items(id)
2182 .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2186 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2187 self.associated_items(did).any(|item| {
2188 item.relevant_for_never()
2192 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssociatedItem> {
2193 let is_associated_item = if let Some(node_id) = self.hir.as_local_node_id(def_id) {
2194 match self.hir.get(node_id) {
2195 hir_map::NodeTraitItem(_) | hir_map::NodeImplItem(_) => true,
2199 match self.describe_def(def_id).expect("no def for def-id") {
2200 Def::AssociatedConst(_) | Def::Method(_) | Def::AssociatedTy(_) => true,
2205 if is_associated_item {
2206 Some(self.associated_item(def_id))
2212 fn associated_item_from_trait_item_ref(self,
2213 parent_def_id: DefId,
2214 parent_vis: &hir::Visibility,
2215 trait_item_ref: &hir::TraitItemRef)
2217 let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2218 let (kind, has_self) = match trait_item_ref.kind {
2219 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2220 hir::AssociatedItemKind::Method { has_self } => {
2221 (ty::AssociatedKind::Method, has_self)
2223 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2227 name: trait_item_ref.name,
2229 // Visibility of trait items is inherited from their traits.
2230 vis: Visibility::from_hir(parent_vis, trait_item_ref.id.node_id, self),
2231 defaultness: trait_item_ref.defaultness,
2233 container: TraitContainer(parent_def_id),
2234 method_has_self_argument: has_self
2238 fn associated_item_from_impl_item_ref(self,
2239 parent_def_id: DefId,
2240 impl_item_ref: &hir::ImplItemRef)
2242 let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2243 let (kind, has_self) = match impl_item_ref.kind {
2244 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2245 hir::AssociatedItemKind::Method { has_self } => {
2246 (ty::AssociatedKind::Method, has_self)
2248 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2251 ty::AssociatedItem {
2252 name: impl_item_ref.name,
2254 // Visibility of trait impl items doesn't matter.
2255 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.node_id, self),
2256 defaultness: impl_item_ref.defaultness,
2258 container: ImplContainer(parent_def_id),
2259 method_has_self_argument: has_self
2263 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2264 pub fn associated_items(self, def_id: DefId)
2265 -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2266 let def_ids = self.associated_item_def_ids(def_id);
2267 (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2270 /// Returns true if the impls are the same polarity and are implementing
2271 /// a trait which contains no items
2272 pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId) -> bool {
2273 if !self.sess.features.borrow().overlapping_marker_traits {
2276 let trait1_is_empty = self.impl_trait_ref(def_id1)
2277 .map_or(false, |trait_ref| {
2278 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2280 let trait2_is_empty = self.impl_trait_ref(def_id2)
2281 .map_or(false, |trait_ref| {
2282 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2284 self.impl_polarity(def_id1) == self.impl_polarity(def_id2)
2289 // Returns `ty::VariantDef` if `def` refers to a struct,
2290 // or variant or their constructors, panics otherwise.
2291 pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2293 Def::Variant(did) | Def::VariantCtor(did, ..) => {
2294 let enum_did = self.parent_def_id(did).unwrap();
2295 self.adt_def(enum_did).variant_with_id(did)
2297 Def::Struct(did) | Def::Union(did) => {
2298 self.adt_def(did).non_enum_variant()
2300 Def::StructCtor(ctor_did, ..) => {
2301 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2302 self.adt_def(did).non_enum_variant()
2304 _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2308 /// Given a `VariantDef`, returns the def-id of the `AdtDef` of which it is a part.
2309 pub fn adt_def_id_of_variant(self, variant_def: &'tcx VariantDef) -> DefId {
2310 let def_key = self.def_key(variant_def.did);
2311 match def_key.disambiguated_data.data {
2312 // for enum variants and tuple structs, the def-id of the ADT itself
2313 // is the *parent* of the variant
2314 DefPathData::EnumVariant(..) | DefPathData::StructCtor =>
2315 DefId { krate: variant_def.did.krate, index: def_key.parent.unwrap() },
2317 // otherwise, for structs and unions, they share a def-id
2318 _ => variant_def.did,
2322 pub fn item_name(self, id: DefId) -> InternedString {
2323 if id.index == CRATE_DEF_INDEX {
2324 self.original_crate_name(id.krate).as_str()
2326 let def_key = self.def_key(id);
2327 // The name of a StructCtor is that of its struct parent.
2328 if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2329 self.item_name(DefId {
2331 index: def_key.parent.unwrap()
2334 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2335 bug!("item_name: no name for {:?}", self.def_path(id));
2341 /// Return the possibly-auto-generated MIR of a (DefId, Subst) pair.
2342 pub fn instance_mir(self, instance: ty::InstanceDef<'gcx>)
2346 ty::InstanceDef::Item(did) => {
2347 self.optimized_mir(did)
2349 ty::InstanceDef::Intrinsic(..) |
2350 ty::InstanceDef::FnPtrShim(..) |
2351 ty::InstanceDef::Virtual(..) |
2352 ty::InstanceDef::ClosureOnceShim { .. } |
2353 ty::InstanceDef::DropGlue(..) |
2354 ty::InstanceDef::CloneShim(..) => {
2355 self.mir_shims(instance)
2360 /// Given the DefId of an item, returns its MIR, borrowed immutably.
2361 /// Returns None if there is no MIR for the DefId
2362 pub fn maybe_optimized_mir(self, did: DefId) -> Option<&'gcx Mir<'gcx>> {
2363 if self.is_mir_available(did) {
2364 Some(self.optimized_mir(did))
2370 /// Get the attributes of a definition.
2371 pub fn get_attrs(self, did: DefId) -> Attributes<'gcx> {
2372 if let Some(id) = self.hir.as_local_node_id(did) {
2373 Attributes::Borrowed(self.hir.attrs(id))
2375 Attributes::Owned(self.item_attrs(did))
2379 /// Determine whether an item is annotated with an attribute
2380 pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2381 attr::contains_name(&self.get_attrs(did), attr)
2384 /// Returns true if this is an `auto trait`.
2385 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2386 self.trait_def(trait_def_id).has_auto_impl
2389 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2390 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2393 /// Given the def_id of an impl, return the def_id of the trait it implements.
2394 /// If it implements no trait, return `None`.
2395 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2396 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2399 /// If the given def ID describes a method belonging to an impl, return the
2400 /// ID of the impl that the method belongs to. Otherwise, return `None`.
2401 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2402 let item = if def_id.krate != LOCAL_CRATE {
2403 if let Some(Def::Method(_)) = self.describe_def(def_id) {
2404 Some(self.associated_item(def_id))
2409 self.opt_associated_item(def_id)
2413 Some(trait_item) => {
2414 match trait_item.container {
2415 TraitContainer(_) => None,
2416 ImplContainer(def_id) => Some(def_id),
2423 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2424 /// with the name of the crate containing the impl.
2425 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2426 if impl_did.is_local() {
2427 let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2428 Ok(self.hir.span(node_id))
2430 Err(self.crate_name(impl_did.krate))
2434 // Hygienically compare a use-site name (`use_name`) for a field or an associated item with its
2435 // supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2436 // definition's parent/scope to perform comparison.
2437 pub fn hygienic_eq(self, use_name: Name, def_name: Name, def_parent_def_id: DefId) -> bool {
2438 self.adjust(use_name, def_parent_def_id, DUMMY_NODE_ID).0 == def_name.to_ident()
2441 pub fn adjust(self, name: Name, scope: DefId, block: NodeId) -> (Ident, DefId) {
2442 self.adjust_ident(name.to_ident(), scope, block)
2445 pub fn adjust_ident(self, mut ident: Ident, scope: DefId, block: NodeId) -> (Ident, DefId) {
2446 let expansion = match scope.krate {
2447 LOCAL_CRATE => self.hir.definitions().expansion(scope.index),
2450 let scope = match ident.ctxt.adjust(expansion) {
2451 Some(macro_def) => self.hir.definitions().macro_def_scope(macro_def),
2452 None if block == DUMMY_NODE_ID => DefId::local(CRATE_DEF_INDEX), // Dummy DefId
2453 None => self.hir.get_module_parent(block),
2459 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2460 pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2461 F: FnOnce(&[hir::Freevar]) -> T,
2463 let def_id = self.hir.local_def_id(fid);
2464 match self.freevars(def_id) {
2471 fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
2474 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2475 let parent_id = tcx.hir.get_parent(id);
2476 let parent_def_id = tcx.hir.local_def_id(parent_id);
2477 let parent_item = tcx.hir.expect_item(parent_id);
2478 match parent_item.node {
2479 hir::ItemImpl(.., ref impl_item_refs) => {
2480 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.node_id == id) {
2481 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
2483 debug_assert_eq!(assoc_item.def_id, def_id);
2488 hir::ItemTrait(.., ref trait_item_refs) => {
2489 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.node_id == id) {
2490 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
2493 debug_assert_eq!(assoc_item.def_id, def_id);
2501 span_bug!(parent_item.span,
2502 "unexpected parent of trait or impl item or item not found: {:?}",
2506 /// Calculates the Sized-constraint.
2508 /// In fact, there are only a few options for the types in the constraint:
2509 /// - an obviously-unsized type
2510 /// - a type parameter or projection whose Sizedness can't be known
2511 /// - a tuple of type parameters or projections, if there are multiple
2513 /// - a TyError, if a type contained itself. The representability
2514 /// check should catch this case.
2515 fn adt_sized_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2517 -> &'tcx [Ty<'tcx>] {
2518 let def = tcx.adt_def(def_id);
2520 let result = tcx.intern_type_list(&def.variants.iter().flat_map(|v| {
2523 def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
2524 }).collect::<Vec<_>>());
2526 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
2531 /// Calculates the dtorck constraint for a type.
2532 fn adt_dtorck_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2534 -> DtorckConstraint<'tcx> {
2535 let def = tcx.adt_def(def_id);
2536 let span = tcx.def_span(def_id);
2537 debug!("dtorck_constraint: {:?}", def);
2539 if def.is_phantom_data() {
2540 let result = DtorckConstraint {
2543 tcx.mk_param_from_def(&tcx.generics_of(def_id).types[0])
2546 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2550 let mut result = def.all_fields()
2551 .map(|field| tcx.type_of(field.did))
2552 .map(|fty| tcx.dtorck_constraint_for_ty(span, fty, 0, fty))
2553 .collect::<Result<DtorckConstraint, ErrorReported>>()
2554 .unwrap_or(DtorckConstraint::empty());
2555 result.outlives.extend(tcx.destructor_constraints(def));
2558 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2563 fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2566 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2567 let item = tcx.hir.expect_item(id);
2568 let vec: Vec<_> = match item.node {
2569 hir::ItemTrait(.., ref trait_item_refs) => {
2570 trait_item_refs.iter()
2571 .map(|trait_item_ref| trait_item_ref.id)
2572 .map(|id| tcx.hir.local_def_id(id.node_id))
2575 hir::ItemImpl(.., ref impl_item_refs) => {
2576 impl_item_refs.iter()
2577 .map(|impl_item_ref| impl_item_ref.id)
2578 .map(|id| tcx.hir.local_def_id(id.node_id))
2581 hir::ItemTraitAlias(..) => vec![],
2582 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2587 fn def_span<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Span {
2588 tcx.hir.span_if_local(def_id).unwrap()
2591 /// If the given def ID describes an item belonging to a trait,
2592 /// return the ID of the trait that the trait item belongs to.
2593 /// Otherwise, return `None`.
2594 fn trait_of_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
2595 tcx.opt_associated_item(def_id)
2596 .and_then(|associated_item| {
2597 match associated_item.container {
2598 TraitContainer(def_id) => Some(def_id),
2599 ImplContainer(_) => None
2604 /// See `ParamEnv` struct def'n for details.
2605 fn param_env<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2608 // Compute the bounds on Self and the type parameters.
2610 let bounds = tcx.predicates_of(def_id).instantiate_identity(tcx);
2611 let predicates = bounds.predicates;
2613 // Finally, we have to normalize the bounds in the environment, in
2614 // case they contain any associated type projections. This process
2615 // can yield errors if the put in illegal associated types, like
2616 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2617 // report these errors right here; this doesn't actually feel
2618 // right to me, because constructing the environment feels like a
2619 // kind of a "idempotent" action, but I'm not sure where would be
2620 // a better place. In practice, we construct environments for
2621 // every fn once during type checking, and we'll abort if there
2622 // are any errors at that point, so after type checking you can be
2623 // sure that this will succeed without errors anyway.
2625 let unnormalized_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
2626 traits::Reveal::UserFacing);
2628 let body_id = tcx.hir.as_local_node_id(def_id).map_or(DUMMY_NODE_ID, |id| {
2629 tcx.hir.maybe_body_owned_by(id).map_or(id, |body| body.node_id)
2631 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
2632 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
2635 fn crate_disambiguator<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2636 crate_num: CrateNum) -> CrateDisambiguator {
2637 assert_eq!(crate_num, LOCAL_CRATE);
2638 tcx.sess.local_crate_disambiguator()
2641 fn original_crate_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2642 crate_num: CrateNum) -> Symbol {
2643 assert_eq!(crate_num, LOCAL_CRATE);
2644 tcx.crate_name.clone()
2647 fn crate_hash<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2648 crate_num: CrateNum)
2650 assert_eq!(crate_num, LOCAL_CRATE);
2654 fn instance_def_size_estimate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2655 instance_def: InstanceDef<'tcx>)
2657 match instance_def {
2658 InstanceDef::Item(..) |
2659 InstanceDef::DropGlue(..) => {
2660 let mir = tcx.instance_mir(instance_def);
2661 mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
2663 // Estimate the size of other compiler-generated shims to be 1.
2668 pub fn provide(providers: &mut ty::maps::Providers) {
2669 context::provide(providers);
2670 erase_regions::provide(providers);
2671 layout::provide(providers);
2672 util::provide(providers);
2673 *providers = ty::maps::Providers {
2675 associated_item_def_ids,
2676 adt_sized_constraint,
2677 adt_dtorck_constraint,
2681 crate_disambiguator,
2682 original_crate_name,
2684 trait_impls_of: trait_def::trait_impls_of_provider,
2685 instance_def_size_estimate,
2690 /// A map for the local crate mapping each type to a vector of its
2691 /// inherent impls. This is not meant to be used outside of coherence;
2692 /// rather, you should request the vector for a specific type via
2693 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2694 /// (constructing this map requires touching the entire crate).
2695 #[derive(Clone, Debug)]
2696 pub struct CrateInherentImpls {
2697 pub inherent_impls: DefIdMap<Rc<Vec<DefId>>>,
2700 /// A set of constraints that need to be satisfied in order for
2701 /// a type to be valid for destruction.
2702 #[derive(Clone, Debug)]
2703 pub struct DtorckConstraint<'tcx> {
2704 /// Types that are required to be alive in order for this
2705 /// type to be valid for destruction.
2706 pub outlives: Vec<ty::subst::Kind<'tcx>>,
2707 /// Types that could not be resolved: projections and params.
2708 pub dtorck_types: Vec<Ty<'tcx>>,
2711 impl<'tcx> FromIterator<DtorckConstraint<'tcx>> for DtorckConstraint<'tcx>
2713 fn from_iter<I: IntoIterator<Item=DtorckConstraint<'tcx>>>(iter: I) -> Self {
2714 let mut result = Self::empty();
2716 for constraint in iter {
2717 result.outlives.extend(constraint.outlives);
2718 result.dtorck_types.extend(constraint.dtorck_types);
2726 impl<'tcx> DtorckConstraint<'tcx> {
2727 fn empty() -> DtorckConstraint<'tcx> {
2730 dtorck_types: vec![]
2734 fn dedup<'a>(&mut self) {
2735 let mut outlives = FxHashSet();
2736 let mut dtorck_types = FxHashSet();
2738 self.outlives.retain(|&val| outlives.replace(val).is_none());
2739 self.dtorck_types.retain(|&val| dtorck_types.replace(val).is_none());
2743 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
2744 pub struct SymbolName {
2745 // FIXME: we don't rely on interning or equality here - better have
2746 // this be a `&'tcx str`.
2747 pub name: InternedString
2750 impl_stable_hash_for!(struct self::SymbolName {
2754 impl Deref for SymbolName {
2757 fn deref(&self) -> &str { &self.name }
2760 impl fmt::Display for SymbolName {
2761 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2762 fmt::Display::fmt(&self.name, fmt)