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::interpret::{GlobalId, Value, PrimVal};
30 use mir::GeneratorLayout;
31 use session::CrateDisambiguator;
32 use traits::{self, Reveal};
34 use ty::subst::{Subst, Substs};
35 use ty::util::{IntTypeExt, Discr};
36 use ty::walk::TypeWalker;
37 use util::nodemap::{NodeSet, DefIdMap, FxHashMap};
39 use serialize::{self, Encodable, Encoder};
40 use std::cell::RefCell;
43 use std::hash::{Hash, Hasher};
45 use rustc_data_structures::sync::Lrc;
47 use std::vec::IntoIter;
49 use syntax::ast::{self, DUMMY_NODE_ID, Name, Ident, NodeId};
51 use syntax::ext::hygiene::{Mark, SyntaxContext};
52 use syntax::symbol::{Symbol, InternedString};
53 use syntax_pos::{DUMMY_SP, Span};
55 use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
56 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
61 pub use self::sty::{Binder, CanonicalVar, DebruijnIndex};
62 pub use self::sty::{FnSig, GenSig, PolyFnSig, PolyGenSig};
63 pub use self::sty::{InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
64 pub use self::sty::{ClosureSubsts, GeneratorInterior, TypeAndMut};
65 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
66 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
67 pub use self::sty::{ExistentialProjection, PolyExistentialProjection, Const};
68 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
69 pub use self::sty::RegionKind;
70 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid};
71 pub use self::sty::BoundRegion::*;
72 pub use self::sty::InferTy::*;
73 pub use self::sty::RegionKind::*;
74 pub use self::sty::TypeVariants::*;
76 pub use self::binding::BindingMode;
77 pub use self::binding::BindingMode::*;
79 pub use self::context::{TyCtxt, GlobalArenas, AllArenas, tls, keep_local};
80 pub use self::context::{Lift, TypeckTables, InterpretInterner};
82 pub use self::instance::{Instance, InstanceDef};
84 pub use self::trait_def::TraitDef;
86 pub use self::maps::queries;
97 pub mod inhabitedness;
114 mod structural_impls;
119 /// The complete set of all analyses described in this module. This is
120 /// produced by the driver and fed to trans and later passes.
122 /// NB: These contents are being migrated into queries using the
123 /// *on-demand* infrastructure.
125 pub struct CrateAnalysis {
126 pub access_levels: Lrc<AccessLevels>,
128 pub glob_map: Option<hir::GlobMap>,
132 pub struct Resolutions {
133 pub freevars: FreevarMap,
134 pub trait_map: TraitMap,
135 pub maybe_unused_trait_imports: NodeSet,
136 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
137 pub export_map: ExportMap,
140 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
141 pub enum AssociatedItemContainer {
142 TraitContainer(DefId),
143 ImplContainer(DefId),
146 impl AssociatedItemContainer {
147 /// Asserts that this is the def-id of an associated item declared
148 /// in a trait, and returns the trait def-id.
149 pub fn assert_trait(&self) -> DefId {
151 TraitContainer(id) => id,
152 _ => bug!("associated item has wrong container type: {:?}", self)
156 pub fn id(&self) -> DefId {
158 TraitContainer(id) => id,
159 ImplContainer(id) => id,
164 /// The "header" of an impl is everything outside the body: a Self type, a trait
165 /// ref (in the case of a trait impl), and a set of predicates (from the
166 /// bounds/where clauses).
167 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
168 pub struct ImplHeader<'tcx> {
169 pub impl_def_id: DefId,
170 pub self_ty: Ty<'tcx>,
171 pub trait_ref: Option<TraitRef<'tcx>>,
172 pub predicates: Vec<Predicate<'tcx>>,
175 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
176 pub struct AssociatedItem {
179 pub kind: AssociatedKind,
181 pub defaultness: hir::Defaultness,
182 pub container: AssociatedItemContainer,
184 /// Whether this is a method with an explicit self
185 /// as its first argument, allowing method calls.
186 pub method_has_self_argument: bool,
189 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, RustcEncodable, RustcDecodable)]
190 pub enum AssociatedKind {
196 impl AssociatedItem {
197 pub fn def(&self) -> Def {
199 AssociatedKind::Const => Def::AssociatedConst(self.def_id),
200 AssociatedKind::Method => Def::Method(self.def_id),
201 AssociatedKind::Type => Def::AssociatedTy(self.def_id),
205 /// Tests whether the associated item admits a non-trivial implementation
207 pub fn relevant_for_never<'tcx>(&self) -> bool {
209 AssociatedKind::Const => true,
210 AssociatedKind::Type => true,
211 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
212 AssociatedKind::Method => !self.method_has_self_argument,
216 pub fn signature<'a, 'tcx>(&self, tcx: &TyCtxt<'a, 'tcx, 'tcx>) -> String {
218 ty::AssociatedKind::Method => {
219 // We skip the binder here because the binder would deanonymize all
220 // late-bound regions, and we don't want method signatures to show up
221 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
222 // regions just fine, showing `fn(&MyType)`.
223 format!("{}", tcx.fn_sig(self.def_id).skip_binder())
225 ty::AssociatedKind::Type => format!("type {};", self.name.to_string()),
226 ty::AssociatedKind::Const => {
227 format!("const {}: {:?};", self.name.to_string(), tcx.type_of(self.def_id))
233 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
234 pub enum Visibility {
235 /// Visible everywhere (including in other crates).
237 /// Visible only in the given crate-local module.
239 /// Not visible anywhere in the local crate. This is the visibility of private external items.
243 pub trait DefIdTree: Copy {
244 fn parent(self, id: DefId) -> Option<DefId>;
246 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
247 if descendant.krate != ancestor.krate {
251 while descendant != ancestor {
252 match self.parent(descendant) {
253 Some(parent) => descendant = parent,
254 None => return false,
261 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
262 fn parent(self, id: DefId) -> Option<DefId> {
263 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
268 pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
270 hir::Public => Visibility::Public,
271 hir::Visibility::Crate => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
272 hir::Visibility::Restricted { ref path, .. } => match path.def {
273 // If there is no resolution, `resolve` will have already reported an error, so
274 // assume that the visibility is public to avoid reporting more privacy errors.
275 Def::Err => Visibility::Public,
276 def => Visibility::Restricted(def.def_id()),
279 Visibility::Restricted(tcx.hir.get_module_parent(id))
284 /// Returns true if an item with this visibility is accessible from the given block.
285 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
286 let restriction = match self {
287 // Public items are visible everywhere.
288 Visibility::Public => return true,
289 // Private items from other crates are visible nowhere.
290 Visibility::Invisible => return false,
291 // Restricted items are visible in an arbitrary local module.
292 Visibility::Restricted(other) if other.krate != module.krate => return false,
293 Visibility::Restricted(module) => module,
296 tree.is_descendant_of(module, restriction)
299 /// Returns true if this visibility is at least as accessible as the given visibility
300 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
301 let vis_restriction = match vis {
302 Visibility::Public => return self == Visibility::Public,
303 Visibility::Invisible => return true,
304 Visibility::Restricted(module) => module,
307 self.is_accessible_from(vis_restriction, tree)
310 // Returns true if this item is visible anywhere in the local crate.
311 pub fn is_visible_locally(self) -> bool {
313 Visibility::Public => true,
314 Visibility::Restricted(def_id) => def_id.is_local(),
315 Visibility::Invisible => false,
320 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
322 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
323 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
324 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
325 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
328 /// The crate variances map is computed during typeck and contains the
329 /// variance of every item in the local crate. You should not use it
330 /// directly, because to do so will make your pass dependent on the
331 /// HIR of every item in the local crate. Instead, use
332 /// `tcx.variances_of()` to get the variance for a *particular*
334 pub struct CrateVariancesMap {
335 /// For each item with generics, maps to a vector of the variance
336 /// of its generics. If an item has no generics, it will have no
338 pub variances: FxHashMap<DefId, Lrc<Vec<ty::Variance>>>,
340 /// An empty vector, useful for cloning.
341 pub empty_variance: Lrc<Vec<ty::Variance>>,
345 /// `a.xform(b)` combines the variance of a context with the
346 /// variance of a type with the following meaning. If we are in a
347 /// context with variance `a`, and we encounter a type argument in
348 /// a position with variance `b`, then `a.xform(b)` is the new
349 /// variance with which the argument appears.
355 /// Here, the "ambient" variance starts as covariant. `*mut T` is
356 /// invariant with respect to `T`, so the variance in which the
357 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
358 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
359 /// respect to its type argument `T`, and hence the variance of
360 /// the `i32` here is `Invariant.xform(Covariant)`, which results
361 /// (again) in `Invariant`.
365 /// fn(*const Vec<i32>, *mut Vec<i32)
367 /// The ambient variance is covariant. A `fn` type is
368 /// contravariant with respect to its parameters, so the variance
369 /// within which both pointer types appear is
370 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
371 /// T` is covariant with respect to `T`, so the variance within
372 /// which the first `Vec<i32>` appears is
373 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
374 /// is true for its `i32` argument. In the `*mut T` case, the
375 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
376 /// and hence the outermost type is `Invariant` with respect to
377 /// `Vec<i32>` (and its `i32` argument).
379 /// Source: Figure 1 of "Taming the Wildcards:
380 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
381 pub fn xform(self, v: ty::Variance) -> ty::Variance {
383 // Figure 1, column 1.
384 (ty::Covariant, ty::Covariant) => ty::Covariant,
385 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
386 (ty::Covariant, ty::Invariant) => ty::Invariant,
387 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
389 // Figure 1, column 2.
390 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
391 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
392 (ty::Contravariant, ty::Invariant) => ty::Invariant,
393 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
395 // Figure 1, column 3.
396 (ty::Invariant, _) => ty::Invariant,
398 // Figure 1, column 4.
399 (ty::Bivariant, _) => ty::Bivariant,
404 // Contains information needed to resolve types and (in the future) look up
405 // the types of AST nodes.
406 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
407 pub struct CReaderCacheKey {
412 // Flags that we track on types. These flags are propagated upwards
413 // through the type during type construction, so that we can quickly
414 // check whether the type has various kinds of types in it without
415 // recursing over the type itself.
417 pub struct TypeFlags: u32 {
418 const HAS_PARAMS = 1 << 0;
419 const HAS_SELF = 1 << 1;
420 const HAS_TY_INFER = 1 << 2;
421 const HAS_RE_INFER = 1 << 3;
422 const HAS_RE_SKOL = 1 << 4;
424 /// Does this have any `ReEarlyBound` regions? Used to
425 /// determine whether substitition is required, since those
426 /// represent regions that are bound in a `ty::Generics` and
427 /// hence may be substituted.
428 const HAS_RE_EARLY_BOUND = 1 << 5;
430 /// Does this have any region that "appears free" in the type?
431 /// Basically anything but `ReLateBound` and `ReErased`.
432 const HAS_FREE_REGIONS = 1 << 6;
434 /// Is an error type reachable?
435 const HAS_TY_ERR = 1 << 7;
436 const HAS_PROJECTION = 1 << 8;
438 // FIXME: Rename this to the actual property since it's used for generators too
439 const HAS_TY_CLOSURE = 1 << 9;
441 // true if there are "names" of types and regions and so forth
442 // that are local to a particular fn
443 const HAS_LOCAL_NAMES = 1 << 10;
445 // Present if the type belongs in a local type context.
446 // Only set for TyInfer other than Fresh.
447 const KEEP_IN_LOCAL_TCX = 1 << 11;
449 // Is there a projection that does not involve a bound region?
450 // Currently we can't normalize projections w/ bound regions.
451 const HAS_NORMALIZABLE_PROJECTION = 1 << 12;
453 // Set if this includes a "canonical" type or region var --
454 // ought to be true only for the results of canonicalization.
455 const HAS_CANONICAL_VARS = 1 << 13;
457 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
458 TypeFlags::HAS_SELF.bits |
459 TypeFlags::HAS_RE_EARLY_BOUND.bits;
461 // Flags representing the nominal content of a type,
462 // computed by FlagsComputation. If you add a new nominal
463 // flag, it should be added here too.
464 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
465 TypeFlags::HAS_SELF.bits |
466 TypeFlags::HAS_TY_INFER.bits |
467 TypeFlags::HAS_RE_INFER.bits |
468 TypeFlags::HAS_RE_SKOL.bits |
469 TypeFlags::HAS_RE_EARLY_BOUND.bits |
470 TypeFlags::HAS_FREE_REGIONS.bits |
471 TypeFlags::HAS_TY_ERR.bits |
472 TypeFlags::HAS_PROJECTION.bits |
473 TypeFlags::HAS_TY_CLOSURE.bits |
474 TypeFlags::HAS_LOCAL_NAMES.bits |
475 TypeFlags::KEEP_IN_LOCAL_TCX.bits |
476 TypeFlags::HAS_CANONICAL_VARS.bits;
480 pub struct TyS<'tcx> {
481 pub sty: TypeVariants<'tcx>,
482 pub flags: TypeFlags,
484 // the maximal depth of any bound regions appearing in this type.
488 impl<'tcx> PartialEq for TyS<'tcx> {
490 fn eq(&self, other: &TyS<'tcx>) -> bool {
491 // (self as *const _) == (other as *const _)
492 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
495 impl<'tcx> Eq for TyS<'tcx> {}
497 impl<'tcx> Hash for TyS<'tcx> {
498 fn hash<H: Hasher>(&self, s: &mut H) {
499 (self as *const TyS).hash(s)
503 impl<'tcx> TyS<'tcx> {
504 pub fn is_primitive_ty(&self) -> bool {
506 TypeVariants::TyBool |
507 TypeVariants::TyChar |
508 TypeVariants::TyInt(_) |
509 TypeVariants::TyUint(_) |
510 TypeVariants::TyFloat(_) |
511 TypeVariants::TyInfer(InferTy::IntVar(_)) |
512 TypeVariants::TyInfer(InferTy::FloatVar(_)) |
513 TypeVariants::TyInfer(InferTy::FreshIntTy(_)) |
514 TypeVariants::TyInfer(InferTy::FreshFloatTy(_)) => true,
515 TypeVariants::TyRef(_, x) => x.ty.is_primitive_ty(),
520 pub fn is_suggestable(&self) -> bool {
522 TypeVariants::TyAnon(..) |
523 TypeVariants::TyFnDef(..) |
524 TypeVariants::TyFnPtr(..) |
525 TypeVariants::TyDynamic(..) |
526 TypeVariants::TyClosure(..) |
527 TypeVariants::TyInfer(..) |
528 TypeVariants::TyProjection(..) => false,
534 impl<'a, 'gcx> HashStable<StableHashingContext<'a>> for ty::TyS<'gcx> {
535 fn hash_stable<W: StableHasherResult>(&self,
536 hcx: &mut StableHashingContext<'a>,
537 hasher: &mut StableHasher<W>) {
541 // The other fields just provide fast access to information that is
542 // also contained in `sty`, so no need to hash them.
547 sty.hash_stable(hcx, hasher);
551 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
553 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
554 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
556 /// A wrapper for slices with the additional invariant
557 /// that the slice is interned and no other slice with
558 /// the same contents can exist in the same context.
559 /// This means we can use pointer + length for both
560 /// equality comparisons and hashing.
561 #[derive(Debug, RustcEncodable)]
562 pub struct Slice<T>([T]);
564 impl<T> PartialEq for Slice<T> {
566 fn eq(&self, other: &Slice<T>) -> bool {
567 (&self.0 as *const [T]) == (&other.0 as *const [T])
570 impl<T> Eq for Slice<T> {}
572 impl<T> Hash for Slice<T> {
573 fn hash<H: Hasher>(&self, s: &mut H) {
574 (self.as_ptr(), self.len()).hash(s)
578 impl<T> Deref for Slice<T> {
580 fn deref(&self) -> &[T] {
585 impl<'a, T> IntoIterator for &'a Slice<T> {
587 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
588 fn into_iter(self) -> Self::IntoIter {
593 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
596 pub fn empty<'a>() -> &'a Slice<T> {
598 mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
603 /// Upvars do not get their own node-id. Instead, we use the pair of
604 /// the original var id (that is, the root variable that is referenced
605 /// by the upvar) and the id of the closure expression.
606 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
608 pub var_id: hir::HirId,
609 pub closure_expr_id: LocalDefId,
612 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
613 pub enum BorrowKind {
614 /// Data must be immutable and is aliasable.
617 /// Data must be immutable but not aliasable. This kind of borrow
618 /// cannot currently be expressed by the user and is used only in
619 /// implicit closure bindings. It is needed when the closure
620 /// is borrowing or mutating a mutable referent, e.g.:
622 /// let x: &mut isize = ...;
623 /// let y = || *x += 5;
625 /// If we were to try to translate this closure into a more explicit
626 /// form, we'd encounter an error with the code as written:
628 /// struct Env { x: & &mut isize }
629 /// let x: &mut isize = ...;
630 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
631 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
633 /// This is then illegal because you cannot mutate a `&mut` found
634 /// in an aliasable location. To solve, you'd have to translate with
635 /// an `&mut` borrow:
637 /// struct Env { x: & &mut isize }
638 /// let x: &mut isize = ...;
639 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
640 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
642 /// Now the assignment to `**env.x` is legal, but creating a
643 /// mutable pointer to `x` is not because `x` is not mutable. We
644 /// could fix this by declaring `x` as `let mut x`. This is ok in
645 /// user code, if awkward, but extra weird for closures, since the
646 /// borrow is hidden.
648 /// So we introduce a "unique imm" borrow -- the referent is
649 /// immutable, but not aliasable. This solves the problem. For
650 /// simplicity, we don't give users the way to express this
651 /// borrow, it's just used when translating closures.
654 /// Data is mutable and not aliasable.
658 /// Information describing the capture of an upvar. This is computed
659 /// during `typeck`, specifically by `regionck`.
660 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
661 pub enum UpvarCapture<'tcx> {
662 /// Upvar is captured by value. This is always true when the
663 /// closure is labeled `move`, but can also be true in other cases
664 /// depending on inference.
667 /// Upvar is captured by reference.
668 ByRef(UpvarBorrow<'tcx>),
671 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
672 pub struct UpvarBorrow<'tcx> {
673 /// The kind of borrow: by-ref upvars have access to shared
674 /// immutable borrows, which are not part of the normal language
676 pub kind: BorrowKind,
678 /// Region of the resulting reference.
679 pub region: ty::Region<'tcx>,
682 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
684 #[derive(Copy, Clone)]
685 pub struct ClosureUpvar<'tcx> {
691 #[derive(Clone, Copy, PartialEq, Eq)]
692 pub enum IntVarValue {
694 UintType(ast::UintTy),
697 #[derive(Clone, Copy, PartialEq, Eq)]
698 pub struct FloatVarValue(pub ast::FloatTy);
700 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
701 pub struct TypeParameterDef {
705 pub has_default: bool,
706 pub object_lifetime_default: ObjectLifetimeDefault,
708 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
709 /// on generic parameter `T`, asserts data behind the parameter
710 /// `T` won't be accessed during the parent type's `Drop` impl.
711 pub pure_wrt_drop: bool,
713 pub synthetic: Option<hir::SyntheticTyParamKind>,
716 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
717 pub struct RegionParameterDef {
722 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
723 /// on generic parameter `'a`, asserts data of lifetime `'a`
724 /// won't be accessed during the parent type's `Drop` impl.
725 pub pure_wrt_drop: bool,
728 impl RegionParameterDef {
729 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
730 ty::EarlyBoundRegion {
737 pub fn to_bound_region(&self) -> ty::BoundRegion {
738 self.to_early_bound_region_data().to_bound_region()
742 impl ty::EarlyBoundRegion {
743 pub fn to_bound_region(&self) -> ty::BoundRegion {
744 ty::BoundRegion::BrNamed(self.def_id, self.name)
748 /// Information about the formal type/lifetime parameters associated
749 /// with an item or method. Analogous to hir::Generics.
751 /// Note that in the presence of a `Self` parameter, the ordering here
752 /// is different from the ordering in a Substs. Substs are ordered as
753 /// Self, *Regions, *Other Type Params, (...child generics)
754 /// while this struct is ordered as
755 /// regions = Regions
756 /// types = [Self, *Other Type Params]
757 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
758 pub struct Generics {
759 pub parent: Option<DefId>,
760 pub parent_regions: u32,
761 pub parent_types: u32,
762 pub regions: Vec<RegionParameterDef>,
763 pub types: Vec<TypeParameterDef>,
765 /// Reverse map to each `TypeParameterDef`'s `index` field
766 pub type_param_to_index: FxHashMap<DefId, u32>,
769 pub has_late_bound_regions: Option<Span>,
772 impl<'a, 'gcx, 'tcx> Generics {
773 pub fn parent_count(&self) -> usize {
774 self.parent_regions as usize + self.parent_types as usize
777 pub fn own_count(&self) -> usize {
778 self.regions.len() + self.types.len()
781 pub fn count(&self) -> usize {
782 self.parent_count() + self.own_count()
785 pub fn region_param(&'tcx self,
786 param: &EarlyBoundRegion,
787 tcx: TyCtxt<'a, 'gcx, 'tcx>)
788 -> &'tcx RegionParameterDef
790 if let Some(index) = param.index.checked_sub(self.parent_count() as u32) {
791 &self.regions[index as usize - self.has_self as usize]
793 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
794 .region_param(param, tcx)
798 /// Returns the `TypeParameterDef` associated with this `ParamTy`.
799 pub fn type_param(&'tcx self,
801 tcx: TyCtxt<'a, 'gcx, 'tcx>)
802 -> &TypeParameterDef {
803 if let Some(idx) = param.idx.checked_sub(self.parent_count() as u32) {
804 // non-Self type parameters are always offset by exactly
805 // `self.regions.len()`. In the absence of a Self, this is obvious,
806 // but even in the presence of a `Self` we just have to "compensate"
809 // Without a `Self` (or in a nested generics that doesn't have
810 // a `Self` in itself, even through it parent does), for example
811 // for `fn foo<'a, T1, T2>()`, the situation is:
819 // And with a `Self`, for example for `trait Foo<'a, 'b, T1, T2>`, the
828 // And it can be seen that in both cases, to move from a substs
829 // offset to a generics offset you just have to offset by the
830 // number of regions.
831 let type_param_offset = self.regions.len();
833 let has_self = self.has_self && self.parent.is_none();
834 let is_separated_self = type_param_offset != 0 && idx == 0 && has_self;
836 if let Some(idx) = (idx as usize).checked_sub(type_param_offset) {
837 assert!(!is_separated_self, "found a Self after type_param_offset");
840 assert!(is_separated_self, "non-Self param before type_param_offset");
844 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
845 .type_param(param, tcx)
850 /// Bounds on generics.
851 #[derive(Clone, Default)]
852 pub struct GenericPredicates<'tcx> {
853 pub parent: Option<DefId>,
854 pub predicates: Vec<Predicate<'tcx>>,
857 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
858 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
860 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
861 pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
862 -> InstantiatedPredicates<'tcx> {
863 let mut instantiated = InstantiatedPredicates::empty();
864 self.instantiate_into(tcx, &mut instantiated, substs);
867 pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
868 -> InstantiatedPredicates<'tcx> {
869 InstantiatedPredicates {
870 predicates: self.predicates.subst(tcx, substs)
874 fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
875 instantiated: &mut InstantiatedPredicates<'tcx>,
876 substs: &Substs<'tcx>) {
877 if let Some(def_id) = self.parent {
878 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
880 instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
883 pub fn instantiate_identity(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
884 -> InstantiatedPredicates<'tcx> {
885 let mut instantiated = InstantiatedPredicates::empty();
886 self.instantiate_identity_into(tcx, &mut instantiated);
890 fn instantiate_identity_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
891 instantiated: &mut InstantiatedPredicates<'tcx>) {
892 if let Some(def_id) = self.parent {
893 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
895 instantiated.predicates.extend(&self.predicates)
898 pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
899 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
900 -> InstantiatedPredicates<'tcx>
902 assert_eq!(self.parent, None);
903 InstantiatedPredicates {
904 predicates: self.predicates.iter().map(|pred| {
905 pred.subst_supertrait(tcx, poly_trait_ref)
911 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
912 pub enum Predicate<'tcx> {
913 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
914 /// the `Self` type of the trait reference and `A`, `B`, and `C`
915 /// would be the type parameters.
916 Trait(PolyTraitPredicate<'tcx>),
919 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
922 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
924 /// where <T as TraitRef>::Name == X, approximately.
925 /// See `ProjectionPredicate` struct for details.
926 Projection(PolyProjectionPredicate<'tcx>),
929 WellFormed(Ty<'tcx>),
931 /// trait must be object-safe
934 /// No direct syntax. May be thought of as `where T : FnFoo<...>`
935 /// for some substitutions `...` and T being a closure type.
936 /// Satisfied (or refuted) once we know the closure's kind.
937 ClosureKind(DefId, ClosureSubsts<'tcx>, ClosureKind),
940 Subtype(PolySubtypePredicate<'tcx>),
942 /// Constant initializer must evaluate successfully.
943 ConstEvaluatable(DefId, &'tcx Substs<'tcx>),
946 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
947 fn as_ref(&self) -> &Predicate<'tcx> {
952 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
953 /// Performs a substitution suitable for going from a
954 /// poly-trait-ref to supertraits that must hold if that
955 /// poly-trait-ref holds. This is slightly different from a normal
956 /// substitution in terms of what happens with bound regions. See
957 /// lengthy comment below for details.
958 pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
959 trait_ref: &ty::PolyTraitRef<'tcx>)
960 -> ty::Predicate<'tcx>
962 // The interaction between HRTB and supertraits is not entirely
963 // obvious. Let me walk you (and myself) through an example.
965 // Let's start with an easy case. Consider two traits:
967 // trait Foo<'a> : Bar<'a,'a> { }
968 // trait Bar<'b,'c> { }
970 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
971 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
972 // knew that `Foo<'x>` (for any 'x) then we also know that
973 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
974 // normal substitution.
976 // In terms of why this is sound, the idea is that whenever there
977 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
978 // holds. So if there is an impl of `T:Foo<'a>` that applies to
979 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
982 // Another example to be careful of is this:
984 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
985 // trait Bar1<'b,'c> { }
987 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
988 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
989 // reason is similar to the previous example: any impl of
990 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
991 // basically we would want to collapse the bound lifetimes from
992 // the input (`trait_ref`) and the supertraits.
994 // To achieve this in practice is fairly straightforward. Let's
995 // consider the more complicated scenario:
997 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
998 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
999 // where both `'x` and `'b` would have a DB index of 1.
1000 // The substitution from the input trait-ref is therefore going to be
1001 // `'a => 'x` (where `'x` has a DB index of 1).
1002 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1003 // early-bound parameter and `'b' is a late-bound parameter with a
1005 // - If we replace `'a` with `'x` from the input, it too will have
1006 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1007 // just as we wanted.
1009 // There is only one catch. If we just apply the substitution `'a
1010 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1011 // adjust the DB index because we substituting into a binder (it
1012 // tries to be so smart...) resulting in `for<'x> for<'b>
1013 // Bar1<'x,'b>` (we have no syntax for this, so use your
1014 // imagination). Basically the 'x will have DB index of 2 and 'b
1015 // will have DB index of 1. Not quite what we want. So we apply
1016 // the substitution to the *contents* of the trait reference,
1017 // rather than the trait reference itself (put another way, the
1018 // substitution code expects equal binding levels in the values
1019 // from the substitution and the value being substituted into, and
1020 // this trick achieves that).
1022 let substs = &trait_ref.0.substs;
1024 Predicate::Trait(ty::Binder(ref data)) =>
1025 Predicate::Trait(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 OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
1075 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
1076 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>,
1078 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>,
1080 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1081 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1083 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1084 pub struct SubtypePredicate<'tcx> {
1085 pub a_is_expected: bool,
1089 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1091 /// This kind of predicate has no *direct* correspondent in the
1092 /// syntax, but it roughly corresponds to the syntactic forms:
1094 /// 1. `T : TraitRef<..., Item=Type>`
1095 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1097 /// In particular, form #1 is "desugared" to the combination of a
1098 /// normal trait predicate (`T : TraitRef<...>`) and one of these
1099 /// predicates. Form #2 is a broader form in that it also permits
1100 /// equality between arbitrary types. Processing an instance of
1101 /// Form #2 eventually yields one of these `ProjectionPredicate`
1102 /// instances to normalize the LHS.
1103 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1104 pub struct ProjectionPredicate<'tcx> {
1105 pub projection_ty: ProjectionTy<'tcx>,
1109 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1111 impl<'tcx> PolyProjectionPredicate<'tcx> {
1112 pub fn to_poly_trait_ref(&self, tcx: TyCtxt) -> PolyTraitRef<'tcx> {
1113 // Note: unlike with TraitRef::to_poly_trait_ref(),
1114 // self.0.trait_ref is permitted to have escaping regions.
1115 // This is because here `self` has a `Binder` and so does our
1116 // return value, so we are preserving the number of binding
1118 ty::Binder(self.0.projection_ty.trait_ref(tcx))
1121 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1122 Binder(self.skip_binder().ty) // preserves binding levels
1126 pub trait ToPolyTraitRef<'tcx> {
1127 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1130 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1131 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1132 assert!(!self.has_escaping_regions());
1133 ty::Binder(self.clone())
1137 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1138 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1139 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1143 pub trait ToPredicate<'tcx> {
1144 fn to_predicate(&self) -> Predicate<'tcx>;
1147 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1148 fn to_predicate(&self) -> Predicate<'tcx> {
1149 // we're about to add a binder, so let's check that we don't
1150 // accidentally capture anything, or else that might be some
1151 // weird debruijn accounting.
1152 assert!(!self.has_escaping_regions());
1154 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1155 trait_ref: self.clone()
1160 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1161 fn to_predicate(&self) -> Predicate<'tcx> {
1162 ty::Predicate::Trait(self.to_poly_trait_predicate())
1166 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1167 fn to_predicate(&self) -> Predicate<'tcx> {
1168 Predicate::RegionOutlives(self.clone())
1172 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1173 fn to_predicate(&self) -> Predicate<'tcx> {
1174 Predicate::TypeOutlives(self.clone())
1178 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1179 fn to_predicate(&self) -> Predicate<'tcx> {
1180 Predicate::Projection(self.clone())
1184 impl<'tcx> Predicate<'tcx> {
1185 /// Iterates over the types in this predicate. Note that in all
1186 /// cases this is skipping over a binder, so late-bound regions
1187 /// with depth 0 are bound by the predicate.
1188 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1189 let vec: Vec<_> = match *self {
1190 ty::Predicate::Trait(ref data) => {
1191 data.skip_binder().input_types().collect()
1193 ty::Predicate::Subtype(ty::Binder(SubtypePredicate { a, b, a_is_expected: _ })) => {
1196 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1199 ty::Predicate::RegionOutlives(..) => {
1202 ty::Predicate::Projection(ref data) => {
1203 data.0.projection_ty.substs.types().chain(Some(data.0.ty)).collect()
1205 ty::Predicate::WellFormed(data) => {
1208 ty::Predicate::ObjectSafe(_trait_def_id) => {
1211 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1212 closure_substs.substs.types().collect()
1214 ty::Predicate::ConstEvaluatable(_, substs) => {
1215 substs.types().collect()
1219 // The only reason to collect into a vector here is that I was
1220 // too lazy to make the full (somewhat complicated) iterator
1221 // type that would be needed here. But I wanted this fn to
1222 // return an iterator conceptually, rather than a `Vec`, so as
1223 // to be closer to `Ty::walk`.
1227 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1229 Predicate::Trait(ref t) => {
1230 Some(t.to_poly_trait_ref())
1232 Predicate::Projection(..) |
1233 Predicate::Subtype(..) |
1234 Predicate::RegionOutlives(..) |
1235 Predicate::WellFormed(..) |
1236 Predicate::ObjectSafe(..) |
1237 Predicate::ClosureKind(..) |
1238 Predicate::TypeOutlives(..) |
1239 Predicate::ConstEvaluatable(..) => {
1245 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1247 Predicate::TypeOutlives(data) => {
1250 Predicate::Trait(..) |
1251 Predicate::Projection(..) |
1252 Predicate::Subtype(..) |
1253 Predicate::RegionOutlives(..) |
1254 Predicate::WellFormed(..) |
1255 Predicate::ObjectSafe(..) |
1256 Predicate::ClosureKind(..) |
1257 Predicate::ConstEvaluatable(..) => {
1264 /// Represents the bounds declared on a particular set of type
1265 /// parameters. Should eventually be generalized into a flag list of
1266 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
1267 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1268 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1269 /// the `GenericPredicates` are expressed in terms of the bound type
1270 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1271 /// represented a set of bounds for some particular instantiation,
1272 /// meaning that the generic parameters have been substituted with
1277 /// struct Foo<T,U:Bar<T>> { ... }
1279 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1280 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1281 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1282 /// [usize:Bar<isize>]]`.
1284 pub struct InstantiatedPredicates<'tcx> {
1285 pub predicates: Vec<Predicate<'tcx>>,
1288 impl<'tcx> InstantiatedPredicates<'tcx> {
1289 pub fn empty() -> InstantiatedPredicates<'tcx> {
1290 InstantiatedPredicates { predicates: vec![] }
1293 pub fn is_empty(&self) -> bool {
1294 self.predicates.is_empty()
1298 /// "Universes" are used during type- and trait-checking in the
1299 /// presence of `for<..>` binders to control what sets of names are
1300 /// visible. Universes are arranged into a tree: the root universe
1301 /// contains names that are always visible. But when you enter into
1302 /// some subuniverse, then it may add names that are only visible
1303 /// within that subtree (but it can still name the names of its
1304 /// ancestor universes).
1306 /// To make this more concrete, consider this program:
1310 /// fn bar<T>(x: T) {
1311 /// let y: for<'a> fn(&'a u8, Foo) = ...;
1315 /// The struct name `Foo` is in the root universe U0. But the type
1316 /// parameter `T`, introduced on `bar`, is in a subuniverse U1 --
1317 /// i.e., within `bar`, we can name both `T` and `Foo`, but outside of
1318 /// `bar`, we cannot name `T`. Then, within the type of `y`, the
1319 /// region `'a` is in a subuniverse U2 of U1, because we can name it
1320 /// inside the fn type but not outside.
1322 /// Universes are related to **skolemization** -- which is a way of
1323 /// doing type- and trait-checking around these "forall" binders (also
1324 /// called **universal quantification**). The idea is that when, in
1325 /// the body of `bar`, we refer to `T` as a type, we aren't referring
1326 /// to any type in particular, but rather a kind of "fresh" type that
1327 /// is distinct from all other types we have actually declared. This
1328 /// is called a **skolemized** type, and we use universes to talk
1329 /// about this. In other words, a type name in universe 0 always
1330 /// corresponds to some "ground" type that the user declared, but a
1331 /// type name in a non-zero universe is a skolemized type -- an
1332 /// idealized representative of "types in general" that we use for
1333 /// checking generic functions.
1334 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1335 pub struct UniverseIndex(u32);
1337 impl UniverseIndex {
1338 /// The root universe, where things that the user defined are
1340 pub const ROOT: UniverseIndex = UniverseIndex(0);
1342 /// A "subuniverse" corresponds to being inside a `forall` quantifier.
1343 /// So, for example, suppose we have this type in universe `U`:
1346 /// for<'a> fn(&'a u32)
1349 /// Once we "enter" into this `for<'a>` quantifier, we are in a
1350 /// subuniverse of `U` -- in this new universe, we can name the
1351 /// region `'a`, but that region was not nameable from `U` because
1352 /// it was not in scope there.
1353 pub fn subuniverse(self) -> UniverseIndex {
1354 UniverseIndex(self.0.checked_add(1).unwrap())
1357 pub fn from(v: u32) -> UniverseIndex {
1361 pub fn as_u32(&self) -> u32 {
1365 pub fn as_usize(&self) -> usize {
1369 /// Gets the "depth" of this universe in the universe tree. This
1370 /// is not really useful except for e.g. the `HashStable`
1372 pub fn depth(&self) -> u32 {
1377 /// When type checking, we use the `ParamEnv` to track
1378 /// details about the set of where-clauses that are in scope at this
1379 /// particular point.
1380 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1381 pub struct ParamEnv<'tcx> {
1382 /// Obligations that the caller must satisfy. This is basically
1383 /// the set of bounds on the in-scope type parameters, translated
1384 /// into Obligations, and elaborated and normalized.
1385 pub caller_bounds: &'tcx Slice<ty::Predicate<'tcx>>,
1387 /// Typically, this is `Reveal::UserFacing`, but during trans we
1388 /// want `Reveal::All` -- note that this is always paired with an
1389 /// empty environment. To get that, use `ParamEnv::reveal()`.
1390 pub reveal: traits::Reveal,
1392 /// What is the innermost universe we have created? Starts out as
1393 /// `UniverseIndex::root()` but grows from there as we enter
1394 /// universal quantifiers.
1396 /// NB: At present, we exclude the universal quantifiers on the
1397 /// item we are type-checking, and just consider those names as
1398 /// part of the root universe. So this would only get incremented
1399 /// when we enter into a higher-ranked (`for<..>`) type or trait
1401 pub universe: UniverseIndex,
1404 impl<'tcx> ParamEnv<'tcx> {
1405 /// Construct a trait environment suitable for contexts where
1406 /// there are no where clauses in scope. Hidden types (like `impl
1407 /// Trait`) are left hidden, so this is suitable for ordinary
1409 pub fn empty() -> Self {
1410 Self::new(ty::Slice::empty(), Reveal::UserFacing, ty::UniverseIndex::ROOT)
1413 /// Construct a trait environment with no where clauses in scope
1414 /// where the values of all `impl Trait` and other hidden types
1415 /// are revealed. This is suitable for monomorphized, post-typeck
1416 /// environments like trans or doing optimizations.
1418 /// NB. If you want to have predicates in scope, use `ParamEnv::new`,
1419 /// or invoke `param_env.with_reveal_all()`.
1420 pub fn reveal_all() -> Self {
1421 Self::new(ty::Slice::empty(), Reveal::All, ty::UniverseIndex::ROOT)
1424 /// Construct a trait environment with the given set of predicates.
1425 pub fn new(caller_bounds: &'tcx ty::Slice<ty::Predicate<'tcx>>,
1427 universe: ty::UniverseIndex)
1429 ty::ParamEnv { caller_bounds, reveal, universe }
1432 /// Returns a new parameter environment with the same clauses, but
1433 /// which "reveals" the true results of projections in all cases
1434 /// (even for associated types that are specializable). This is
1435 /// the desired behavior during trans and certain other special
1436 /// contexts; normally though we want to use `Reveal::UserFacing`,
1437 /// which is the default.
1438 pub fn with_reveal_all(self) -> Self {
1439 ty::ParamEnv { reveal: Reveal::All, ..self }
1442 /// Returns this same environment but with no caller bounds.
1443 pub fn without_caller_bounds(self) -> Self {
1444 ty::ParamEnv { caller_bounds: ty::Slice::empty(), ..self }
1447 /// Creates a suitable environment in which to perform trait
1448 /// queries on the given value. When type-checking, this is simply
1449 /// the pair of the environment plus value. But when reveal is set to
1450 /// All, then if `value` does not reference any type parameters, we will
1451 /// pair it with the empty environment. This improves caching and is generally
1454 /// NB: We preserve the environment when type-checking because it
1455 /// is possible for the user to have wacky where-clauses like
1456 /// `where Box<u32>: Copy`, which are clearly never
1457 /// satisfiable. We generally want to behave as if they were true,
1458 /// although the surrounding function is never reachable.
1459 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1461 Reveal::UserFacing => {
1469 if value.needs_infer() || value.has_param_types() || value.has_self_ty() {
1476 param_env: self.without_caller_bounds(),
1485 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1486 pub struct ParamEnvAnd<'tcx, T> {
1487 pub param_env: ParamEnv<'tcx>,
1491 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1492 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1493 (self.param_env, self.value)
1497 impl<'a, 'gcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'gcx, T>
1498 where T: HashStable<StableHashingContext<'a>>
1500 fn hash_stable<W: StableHasherResult>(&self,
1501 hcx: &mut StableHashingContext<'a>,
1502 hasher: &mut StableHasher<W>) {
1508 param_env.hash_stable(hcx, hasher);
1509 value.hash_stable(hcx, hasher);
1513 #[derive(Copy, Clone, Debug)]
1514 pub struct Destructor {
1515 /// The def-id of the destructor method
1520 pub struct AdtFlags: u32 {
1521 const NO_ADT_FLAGS = 0;
1522 const IS_ENUM = 1 << 0;
1523 const IS_PHANTOM_DATA = 1 << 1;
1524 const IS_FUNDAMENTAL = 1 << 2;
1525 const IS_UNION = 1 << 3;
1526 const IS_BOX = 1 << 4;
1527 /// Indicates whether this abstract data type will be expanded on in future (new
1528 /// fields/variants) and as such, whether downstream crates must match exhaustively on the
1529 /// fields/variants of this data type.
1531 /// See RFC 2008 (<https://github.com/rust-lang/rfcs/pull/2008>).
1532 const IS_NON_EXHAUSTIVE = 1 << 5;
1537 pub struct VariantDef {
1538 /// The variant's DefId. If this is a tuple-like struct,
1539 /// this is the DefId of the struct's ctor.
1541 pub name: Name, // struct's name if this is a struct
1542 pub discr: VariantDiscr,
1543 pub fields: Vec<FieldDef>,
1544 pub ctor_kind: CtorKind,
1547 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1548 pub enum VariantDiscr {
1549 /// Explicit value for this variant, i.e. `X = 123`.
1550 /// The `DefId` corresponds to the embedded constant.
1553 /// The previous variant's discriminant plus one.
1554 /// For efficiency reasons, the distance from the
1555 /// last `Explicit` discriminant is being stored,
1556 /// or `0` for the first variant, if it has none.
1561 pub struct FieldDef {
1564 pub vis: Visibility,
1567 /// The definition of an abstract data type - a struct or enum.
1569 /// These are all interned (by intern_adt_def) into the adt_defs
1573 pub variants: Vec<VariantDef>,
1575 pub repr: ReprOptions,
1578 impl PartialEq for AdtDef {
1579 // AdtDef are always interned and this is part of TyS equality
1581 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1584 impl Eq for AdtDef {}
1586 impl Hash for AdtDef {
1588 fn hash<H: Hasher>(&self, s: &mut H) {
1589 (self as *const AdtDef).hash(s)
1593 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1594 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1599 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1602 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
1603 fn hash_stable<W: StableHasherResult>(&self,
1604 hcx: &mut StableHashingContext<'a>,
1605 hasher: &mut StableHasher<W>) {
1607 static CACHE: RefCell<FxHashMap<usize, Fingerprint>> =
1608 RefCell::new(FxHashMap());
1611 let hash: Fingerprint = CACHE.with(|cache| {
1612 let addr = self as *const AdtDef as usize;
1613 *cache.borrow_mut().entry(addr).or_insert_with(|| {
1621 let mut hasher = StableHasher::new();
1622 did.hash_stable(hcx, &mut hasher);
1623 variants.hash_stable(hcx, &mut hasher);
1624 flags.hash_stable(hcx, &mut hasher);
1625 repr.hash_stable(hcx, &mut hasher);
1631 hash.hash_stable(hcx, hasher);
1635 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1636 pub enum AdtKind { Struct, Union, Enum }
1639 #[derive(RustcEncodable, RustcDecodable, Default)]
1640 pub struct ReprFlags: u8 {
1641 const IS_C = 1 << 0;
1642 const IS_PACKED = 1 << 1;
1643 const IS_SIMD = 1 << 2;
1644 const IS_TRANSPARENT = 1 << 3;
1645 // Internal only for now. If true, don't reorder fields.
1646 const IS_LINEAR = 1 << 4;
1648 // Any of these flags being set prevent field reordering optimisation.
1649 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1650 ReprFlags::IS_PACKED.bits |
1651 ReprFlags::IS_SIMD.bits |
1652 ReprFlags::IS_LINEAR.bits;
1656 impl_stable_hash_for!(struct ReprFlags {
1662 /// Represents the repr options provided by the user,
1663 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1664 pub struct ReprOptions {
1665 pub int: Option<attr::IntType>,
1667 pub flags: ReprFlags,
1670 impl_stable_hash_for!(struct ReprOptions {
1677 pub fn new(tcx: TyCtxt, did: DefId) -> ReprOptions {
1678 let mut flags = ReprFlags::empty();
1679 let mut size = None;
1680 let mut max_align = 0;
1681 for attr in tcx.get_attrs(did).iter() {
1682 for r in attr::find_repr_attrs(tcx.sess.diagnostic(), attr) {
1683 flags.insert(match r {
1684 attr::ReprC => ReprFlags::IS_C,
1685 attr::ReprPacked => ReprFlags::IS_PACKED,
1686 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1687 attr::ReprSimd => ReprFlags::IS_SIMD,
1688 attr::ReprInt(i) => {
1692 attr::ReprAlign(align) => {
1693 max_align = cmp::max(align, max_align);
1700 // This is here instead of layout because the choice must make it into metadata.
1701 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.item_path_str(did))) {
1702 flags.insert(ReprFlags::IS_LINEAR);
1704 ReprOptions { int: size, align: max_align, flags: flags }
1708 pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
1710 pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
1712 pub fn packed(&self) -> bool { self.flags.contains(ReprFlags::IS_PACKED) }
1714 pub fn transparent(&self) -> bool { self.flags.contains(ReprFlags::IS_TRANSPARENT) }
1716 pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
1718 pub fn discr_type(&self) -> attr::IntType {
1719 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
1722 /// Returns true if this `#[repr()]` should inhabit "smart enum
1723 /// layout" optimizations, such as representing `Foo<&T>` as a
1725 pub fn inhibit_enum_layout_opt(&self) -> bool {
1726 self.c() || self.int.is_some()
1730 impl<'a, 'gcx, 'tcx> AdtDef {
1734 variants: Vec<VariantDef>,
1735 repr: ReprOptions) -> Self {
1736 let mut flags = AdtFlags::NO_ADT_FLAGS;
1737 let attrs = tcx.get_attrs(did);
1738 if attr::contains_name(&attrs, "fundamental") {
1739 flags = flags | AdtFlags::IS_FUNDAMENTAL;
1741 if Some(did) == tcx.lang_items().phantom_data() {
1742 flags = flags | AdtFlags::IS_PHANTOM_DATA;
1744 if Some(did) == tcx.lang_items().owned_box() {
1745 flags = flags | AdtFlags::IS_BOX;
1747 if tcx.has_attr(did, "non_exhaustive") {
1748 flags = flags | AdtFlags::IS_NON_EXHAUSTIVE;
1751 AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1752 AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1753 AdtKind::Struct => {}
1764 pub fn is_struct(&self) -> bool {
1765 !self.is_union() && !self.is_enum()
1769 pub fn is_union(&self) -> bool {
1770 self.flags.intersects(AdtFlags::IS_UNION)
1774 pub fn is_enum(&self) -> bool {
1775 self.flags.intersects(AdtFlags::IS_ENUM)
1779 pub fn is_non_exhaustive(&self) -> bool {
1780 self.flags.intersects(AdtFlags::IS_NON_EXHAUSTIVE)
1783 /// Returns the kind of the ADT - Struct or Enum.
1785 pub fn adt_kind(&self) -> AdtKind {
1788 } else if self.is_union() {
1795 pub fn descr(&self) -> &'static str {
1796 match self.adt_kind() {
1797 AdtKind::Struct => "struct",
1798 AdtKind::Union => "union",
1799 AdtKind::Enum => "enum",
1803 pub fn variant_descr(&self) -> &'static str {
1804 match self.adt_kind() {
1805 AdtKind::Struct => "struct",
1806 AdtKind::Union => "union",
1807 AdtKind::Enum => "variant",
1811 /// Returns whether this type is #[fundamental] for the purposes
1812 /// of coherence checking.
1814 pub fn is_fundamental(&self) -> bool {
1815 self.flags.intersects(AdtFlags::IS_FUNDAMENTAL)
1818 /// Returns true if this is PhantomData<T>.
1820 pub fn is_phantom_data(&self) -> bool {
1821 self.flags.intersects(AdtFlags::IS_PHANTOM_DATA)
1824 /// Returns true if this is Box<T>.
1826 pub fn is_box(&self) -> bool {
1827 self.flags.intersects(AdtFlags::IS_BOX)
1830 /// Returns whether this type has a destructor.
1831 pub fn has_dtor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1832 self.destructor(tcx).is_some()
1835 /// Asserts this is a struct or union and returns its unique variant.
1836 pub fn non_enum_variant(&self) -> &VariantDef {
1837 assert!(self.is_struct() || self.is_union());
1842 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1843 tcx.predicates_of(self.did)
1846 /// Returns an iterator over all fields contained
1849 pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1850 self.variants.iter().flat_map(|v| v.fields.iter())
1853 pub fn is_payloadfree(&self) -> bool {
1854 !self.variants.is_empty() &&
1855 self.variants.iter().all(|v| v.fields.is_empty())
1858 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1861 .find(|v| v.did == vid)
1862 .expect("variant_with_id: unknown variant")
1865 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1868 .position(|v| v.did == vid)
1869 .expect("variant_index_with_id: unknown variant")
1872 pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1874 Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1875 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1876 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.non_enum_variant(),
1877 _ => bug!("unexpected def {:?} in variant_of_def", def)
1882 pub fn eval_explicit_discr(
1884 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1886 ) -> Option<Discr<'tcx>> {
1887 let param_env = ParamEnv::empty();
1888 let repr_type = self.repr.discr_type();
1889 let bit_size = layout::Integer::from_attr(tcx, repr_type).size().bits();
1890 let substs = Substs::identity_for_item(tcx.global_tcx(), expr_did);
1891 let instance = ty::Instance::new(expr_did, substs);
1892 let cid = GlobalId {
1896 match tcx.const_eval(param_env.and(cid)) {
1898 val: ConstVal::Value(Value::ByVal(PrimVal::Bytes(b))),
1901 trace!("discriminants: {} ({:?})", b, repr_type);
1902 let ty = repr_type.to_ty(tcx);
1903 if repr_type.is_signed() {
1904 let val = b as i128;
1905 // sign extend to i128
1906 let amt = 128 - bit_size;
1907 let val = (val << amt) >> amt;
1920 val: ConstVal::Value(other),
1923 info!("invalid enum discriminant: {:#?}", other);
1924 ::middle::const_val::struct_error(
1926 tcx.def_span(expr_did),
1927 "constant evaluation of enum discriminant resulted in non-integer",
1932 err.report(tcx, tcx.def_span(expr_did), "enum discriminant");
1933 if !expr_did.is_local() {
1934 span_bug!(tcx.def_span(expr_did),
1935 "variant discriminant evaluation succeeded \
1936 in its crate but failed locally");
1940 _ => span_bug!(tcx.def_span(expr_did), "const eval "),
1945 pub fn discriminants(&'a self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
1946 -> impl Iterator<Item=Discr<'tcx>> + 'a {
1947 let repr_type = self.repr.discr_type();
1948 let initial = repr_type.initial_discriminant(tcx.global_tcx());
1949 let mut prev_discr = None::<Discr<'tcx>>;
1950 self.variants.iter().map(move |v| {
1951 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
1952 if let VariantDiscr::Explicit(expr_did) = v.discr {
1953 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
1957 prev_discr = Some(discr);
1963 /// Compute the discriminant value used by a specific variant.
1964 /// Unlike `discriminants`, this is (amortized) constant-time,
1965 /// only doing at most one query for evaluating an explicit
1966 /// discriminant (the last one before the requested variant),
1967 /// assuming there are no constant-evaluation errors there.
1968 pub fn discriminant_for_variant(&self,
1969 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1970 variant_index: usize)
1972 let repr_type = self.repr.discr_type();
1973 let mut explicit_value = repr_type.initial_discriminant(tcx.global_tcx());
1974 let mut explicit_index = variant_index;
1976 match self.variants[explicit_index].discr {
1977 ty::VariantDiscr::Relative(0) => break,
1978 ty::VariantDiscr::Relative(distance) => {
1979 explicit_index -= distance;
1981 ty::VariantDiscr::Explicit(expr_did) => {
1982 match self.eval_explicit_discr(tcx, expr_did) {
1984 explicit_value = discr;
1988 if explicit_index == 0 {
1991 explicit_index -= 1;
1997 explicit_value.checked_add(tcx, (variant_index - explicit_index) as u128).0
2000 pub fn destructor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Destructor> {
2001 tcx.adt_destructor(self.did)
2004 /// Returns a list of types such that `Self: Sized` if and only
2005 /// if that type is Sized, or `TyErr` if this type is recursive.
2007 /// Oddly enough, checking that the sized-constraint is Sized is
2008 /// actually more expressive than checking all members:
2009 /// the Sized trait is inductive, so an associated type that references
2010 /// Self would prevent its containing ADT from being Sized.
2012 /// Due to normalization being eager, this applies even if
2013 /// the associated type is behind a pointer, e.g. issue #31299.
2014 pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] {
2015 match queries::adt_sized_constraint::try_get(tcx, DUMMY_SP, self.did) {
2018 debug!("adt_sized_constraint: {:?} is recursive", self);
2019 // This should be reported as an error by `check_representable`.
2021 // Consider the type as Sized in the meanwhile to avoid
2022 // further errors. Delay our `bug` diagnostic here to get
2023 // emitted later as well in case we accidentally otherwise don't
2026 tcx.intern_type_list(&[tcx.types.err])
2031 fn sized_constraint_for_ty(&self,
2032 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2035 let result = match ty.sty {
2036 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
2037 TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
2038 TyArray(..) | TyClosure(..) | TyGenerator(..) | TyNever => {
2047 TyGeneratorWitness(..) => {
2048 // these are never sized - return the target type
2052 TyTuple(ref tys) => {
2055 Some(ty) => self.sized_constraint_for_ty(tcx, ty)
2059 TyAdt(adt, substs) => {
2061 let adt_tys = adt.sized_constraint(tcx);
2062 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
2065 .map(|ty| ty.subst(tcx, substs))
2066 .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
2070 TyProjection(..) | TyAnon(..) => {
2071 // must calculate explicitly.
2072 // FIXME: consider special-casing always-Sized projections
2077 // perf hack: if there is a `T: Sized` bound, then
2078 // we know that `T` is Sized and do not need to check
2081 let sized_trait = match tcx.lang_items().sized_trait() {
2083 _ => return vec![ty]
2085 let sized_predicate = Binder(TraitRef {
2086 def_id: sized_trait,
2087 substs: tcx.mk_substs_trait(ty, &[])
2089 let predicates = tcx.predicates_of(self.did).predicates;
2090 if predicates.into_iter().any(|p| p == sized_predicate) {
2098 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
2102 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
2107 impl<'a, 'gcx, 'tcx> VariantDef {
2109 pub fn find_field_named(&self, name: ast::Name) -> Option<&FieldDef> {
2110 self.index_of_field_named(name).map(|index| &self.fields[index])
2113 pub fn index_of_field_named(&self, name: ast::Name) -> Option<usize> {
2114 if let Some(index) = self.fields.iter().position(|f| f.name == name) {
2117 let mut ident = name.to_ident();
2118 while ident.ctxt != SyntaxContext::empty() {
2119 ident.ctxt.remove_mark();
2120 if let Some(field) = self.fields.iter().position(|f| f.name.to_ident() == ident) {
2128 pub fn field_named(&self, name: ast::Name) -> &FieldDef {
2129 self.find_field_named(name).unwrap()
2133 impl<'a, 'gcx, 'tcx> FieldDef {
2134 pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
2135 tcx.type_of(self.did).subst(tcx, subst)
2139 /// Represents the various closure traits in the Rust language. This
2140 /// will determine the type of the environment (`self`, in the
2141 /// desuaring) argument that the closure expects.
2143 /// You can get the environment type of a closure using
2144 /// `tcx.closure_env_ty()`.
2145 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
2146 pub enum ClosureKind {
2147 // Warning: Ordering is significant here! The ordering is chosen
2148 // because the trait Fn is a subtrait of FnMut and so in turn, and
2149 // hence we order it so that Fn < FnMut < FnOnce.
2155 impl<'a, 'tcx> ClosureKind {
2156 // This is the initial value used when doing upvar inference.
2157 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2159 pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
2161 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
2162 ClosureKind::FnMut => {
2163 tcx.require_lang_item(FnMutTraitLangItem)
2165 ClosureKind::FnOnce => {
2166 tcx.require_lang_item(FnOnceTraitLangItem)
2171 /// True if this a type that impls this closure kind
2172 /// must also implement `other`.
2173 pub fn extends(self, other: ty::ClosureKind) -> bool {
2174 match (self, other) {
2175 (ClosureKind::Fn, ClosureKind::Fn) => true,
2176 (ClosureKind::Fn, ClosureKind::FnMut) => true,
2177 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2178 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2179 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2180 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2185 /// Returns the representative scalar type for this closure kind.
2186 /// See `TyS::to_opt_closure_kind` for more details.
2187 pub fn to_ty(self, tcx: TyCtxt<'_, '_, 'tcx>) -> Ty<'tcx> {
2189 ty::ClosureKind::Fn => tcx.types.i8,
2190 ty::ClosureKind::FnMut => tcx.types.i16,
2191 ty::ClosureKind::FnOnce => tcx.types.i32,
2196 impl<'tcx> TyS<'tcx> {
2197 /// Iterator that walks `self` and any types reachable from
2198 /// `self`, in depth-first order. Note that just walks the types
2199 /// that appear in `self`, it does not descend into the fields of
2200 /// structs or variants. For example:
2203 /// isize => { isize }
2204 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2205 /// [isize] => { [isize], isize }
2207 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2208 TypeWalker::new(self)
2211 /// Iterator that walks the immediate children of `self`. Hence
2212 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
2213 /// (but not `i32`, like `walk`).
2214 pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
2215 walk::walk_shallow(self)
2218 /// Walks `ty` and any types appearing within `ty`, invoking the
2219 /// callback `f` on each type. If the callback returns false, then the
2220 /// children of the current type are ignored.
2222 /// Note: prefer `ty.walk()` where possible.
2223 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2224 where F : FnMut(Ty<'tcx>) -> bool
2226 let mut walker = self.walk();
2227 while let Some(ty) = walker.next() {
2229 walker.skip_current_subtree();
2236 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2238 hir::MutMutable => MutBorrow,
2239 hir::MutImmutable => ImmBorrow,
2243 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2244 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2245 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2247 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2249 MutBorrow => hir::MutMutable,
2250 ImmBorrow => hir::MutImmutable,
2252 // We have no type corresponding to a unique imm borrow, so
2253 // use `&mut`. It gives all the capabilities of an `&uniq`
2254 // and hence is a safe "over approximation".
2255 UniqueImmBorrow => hir::MutMutable,
2259 pub fn to_user_str(&self) -> &'static str {
2261 MutBorrow => "mutable",
2262 ImmBorrow => "immutable",
2263 UniqueImmBorrow => "uniquely immutable",
2268 #[derive(Debug, Clone)]
2269 pub enum Attributes<'gcx> {
2270 Owned(Lrc<[ast::Attribute]>),
2271 Borrowed(&'gcx [ast::Attribute])
2274 impl<'gcx> ::std::ops::Deref for Attributes<'gcx> {
2275 type Target = [ast::Attribute];
2277 fn deref(&self) -> &[ast::Attribute] {
2279 &Attributes::Owned(ref data) => &data,
2280 &Attributes::Borrowed(data) => data
2285 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2286 pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
2287 self.typeck_tables_of(self.hir.body_owner_def_id(body))
2290 /// Returns an iterator of the def-ids for all body-owners in this
2291 /// crate. If you would prefer to iterate over the bodies
2292 /// themselves, you can do `self.hir.krate().body_ids.iter()`.
2293 pub fn body_owners(self) -> impl Iterator<Item = DefId> + 'a {
2297 .map(move |&body_id| self.hir.body_owner_def_id(body_id))
2300 pub fn expr_span(self, id: NodeId) -> Span {
2301 match self.hir.find(id) {
2302 Some(hir_map::NodeExpr(e)) => {
2306 bug!("Node id {} is not an expr: {:?}", id, f);
2309 bug!("Node id {} is not present in the node map", id);
2314 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2315 self.associated_items(id)
2316 .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2320 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2321 self.associated_items(did).any(|item| {
2322 item.relevant_for_never()
2326 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssociatedItem> {
2327 let is_associated_item = if let Some(node_id) = self.hir.as_local_node_id(def_id) {
2328 match self.hir.get(node_id) {
2329 hir_map::NodeTraitItem(_) | hir_map::NodeImplItem(_) => true,
2333 match self.describe_def(def_id).expect("no def for def-id") {
2334 Def::AssociatedConst(_) | Def::Method(_) | Def::AssociatedTy(_) => true,
2339 if is_associated_item {
2340 Some(self.associated_item(def_id))
2346 fn associated_item_from_trait_item_ref(self,
2347 parent_def_id: DefId,
2348 parent_vis: &hir::Visibility,
2349 trait_item_ref: &hir::TraitItemRef)
2351 let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2352 let (kind, has_self) = match trait_item_ref.kind {
2353 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2354 hir::AssociatedItemKind::Method { has_self } => {
2355 (ty::AssociatedKind::Method, has_self)
2357 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2361 name: trait_item_ref.name,
2363 // Visibility of trait items is inherited from their traits.
2364 vis: Visibility::from_hir(parent_vis, trait_item_ref.id.node_id, self),
2365 defaultness: trait_item_ref.defaultness,
2367 container: TraitContainer(parent_def_id),
2368 method_has_self_argument: has_self
2372 fn associated_item_from_impl_item_ref(self,
2373 parent_def_id: DefId,
2374 impl_item_ref: &hir::ImplItemRef)
2376 let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2377 let (kind, has_self) = match impl_item_ref.kind {
2378 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2379 hir::AssociatedItemKind::Method { has_self } => {
2380 (ty::AssociatedKind::Method, has_self)
2382 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2385 ty::AssociatedItem {
2386 name: impl_item_ref.name,
2388 // Visibility of trait impl items doesn't matter.
2389 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.node_id, self),
2390 defaultness: impl_item_ref.defaultness,
2392 container: ImplContainer(parent_def_id),
2393 method_has_self_argument: has_self
2397 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2398 pub fn associated_items(self, def_id: DefId)
2399 -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2400 let def_ids = self.associated_item_def_ids(def_id);
2401 (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2404 /// Returns true if the impls are the same polarity and are implementing
2405 /// a trait which contains no items
2406 pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId) -> bool {
2407 if !self.features().overlapping_marker_traits {
2410 let trait1_is_empty = self.impl_trait_ref(def_id1)
2411 .map_or(false, |trait_ref| {
2412 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2414 let trait2_is_empty = self.impl_trait_ref(def_id2)
2415 .map_or(false, |trait_ref| {
2416 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2418 self.impl_polarity(def_id1) == self.impl_polarity(def_id2)
2423 // Returns `ty::VariantDef` if `def` refers to a struct,
2424 // or variant or their constructors, panics otherwise.
2425 pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2427 Def::Variant(did) | Def::VariantCtor(did, ..) => {
2428 let enum_did = self.parent_def_id(did).unwrap();
2429 self.adt_def(enum_did).variant_with_id(did)
2431 Def::Struct(did) | Def::Union(did) => {
2432 self.adt_def(did).non_enum_variant()
2434 Def::StructCtor(ctor_did, ..) => {
2435 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2436 self.adt_def(did).non_enum_variant()
2438 _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2442 /// Given a `VariantDef`, returns the def-id of the `AdtDef` of which it is a part.
2443 pub fn adt_def_id_of_variant(self, variant_def: &'tcx VariantDef) -> DefId {
2444 let def_key = self.def_key(variant_def.did);
2445 match def_key.disambiguated_data.data {
2446 // for enum variants and tuple structs, the def-id of the ADT itself
2447 // is the *parent* of the variant
2448 DefPathData::EnumVariant(..) | DefPathData::StructCtor =>
2449 DefId { krate: variant_def.did.krate, index: def_key.parent.unwrap() },
2451 // otherwise, for structs and unions, they share a def-id
2452 _ => variant_def.did,
2456 pub fn item_name(self, id: DefId) -> InternedString {
2457 if id.index == CRATE_DEF_INDEX {
2458 self.original_crate_name(id.krate).as_str()
2460 let def_key = self.def_key(id);
2461 // The name of a StructCtor is that of its struct parent.
2462 if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2463 self.item_name(DefId {
2465 index: def_key.parent.unwrap()
2468 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2469 bug!("item_name: no name for {:?}", self.def_path(id));
2475 /// Return the possibly-auto-generated MIR of a (DefId, Subst) pair.
2476 pub fn instance_mir(self, instance: ty::InstanceDef<'gcx>)
2480 ty::InstanceDef::Item(did) => {
2481 self.optimized_mir(did)
2483 ty::InstanceDef::Intrinsic(..) |
2484 ty::InstanceDef::FnPtrShim(..) |
2485 ty::InstanceDef::Virtual(..) |
2486 ty::InstanceDef::ClosureOnceShim { .. } |
2487 ty::InstanceDef::DropGlue(..) |
2488 ty::InstanceDef::CloneShim(..) => {
2489 self.mir_shims(instance)
2494 /// Given the DefId of an item, returns its MIR, borrowed immutably.
2495 /// Returns None if there is no MIR for the DefId
2496 pub fn maybe_optimized_mir(self, did: DefId) -> Option<&'gcx Mir<'gcx>> {
2497 if self.is_mir_available(did) {
2498 Some(self.optimized_mir(did))
2504 /// Get the attributes of a definition.
2505 pub fn get_attrs(self, did: DefId) -> Attributes<'gcx> {
2506 if let Some(id) = self.hir.as_local_node_id(did) {
2507 Attributes::Borrowed(self.hir.attrs(id))
2509 Attributes::Owned(self.item_attrs(did))
2513 /// Determine whether an item is annotated with an attribute
2514 pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2515 attr::contains_name(&self.get_attrs(did), attr)
2518 /// Returns true if this is an `auto trait`.
2519 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2520 self.trait_def(trait_def_id).has_auto_impl
2523 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2524 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2527 /// Given the def_id of an impl, return the def_id of the trait it implements.
2528 /// If it implements no trait, return `None`.
2529 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2530 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2533 /// If the given def ID describes a method belonging to an impl, return the
2534 /// ID of the impl that the method belongs to. Otherwise, return `None`.
2535 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2536 let item = if def_id.krate != LOCAL_CRATE {
2537 if let Some(Def::Method(_)) = self.describe_def(def_id) {
2538 Some(self.associated_item(def_id))
2543 self.opt_associated_item(def_id)
2547 Some(trait_item) => {
2548 match trait_item.container {
2549 TraitContainer(_) => None,
2550 ImplContainer(def_id) => Some(def_id),
2557 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2558 /// with the name of the crate containing the impl.
2559 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2560 if impl_did.is_local() {
2561 let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2562 Ok(self.hir.span(node_id))
2564 Err(self.crate_name(impl_did.krate))
2568 // Hygienically compare a use-site name (`use_name`) for a field or an associated item with its
2569 // supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2570 // definition's parent/scope to perform comparison.
2571 pub fn hygienic_eq(self, use_name: Name, def_name: Name, def_parent_def_id: DefId) -> bool {
2572 self.adjust(use_name, def_parent_def_id, DUMMY_NODE_ID).0 == def_name.to_ident()
2575 pub fn adjust(self, name: Name, scope: DefId, block: NodeId) -> (Ident, DefId) {
2576 self.adjust_ident(name.to_ident(), scope, block)
2579 pub fn adjust_ident(self, mut ident: Ident, scope: DefId, block: NodeId) -> (Ident, DefId) {
2580 let expansion = match scope.krate {
2581 LOCAL_CRATE => self.hir.definitions().expansion(scope.index),
2584 let scope = match ident.ctxt.adjust(expansion) {
2585 Some(macro_def) => self.hir.definitions().macro_def_scope(macro_def),
2586 None if block == DUMMY_NODE_ID => DefId::local(CRATE_DEF_INDEX), // Dummy DefId
2587 None => self.hir.get_module_parent(block),
2593 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2594 pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2595 F: FnOnce(&[hir::Freevar]) -> T,
2597 let def_id = self.hir.local_def_id(fid);
2598 match self.freevars(def_id) {
2605 fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
2608 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2609 let parent_id = tcx.hir.get_parent(id);
2610 let parent_def_id = tcx.hir.local_def_id(parent_id);
2611 let parent_item = tcx.hir.expect_item(parent_id);
2612 match parent_item.node {
2613 hir::ItemImpl(.., ref impl_item_refs) => {
2614 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.node_id == id) {
2615 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
2617 debug_assert_eq!(assoc_item.def_id, def_id);
2622 hir::ItemTrait(.., ref trait_item_refs) => {
2623 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.node_id == id) {
2624 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
2627 debug_assert_eq!(assoc_item.def_id, def_id);
2635 span_bug!(parent_item.span,
2636 "unexpected parent of trait or impl item or item not found: {:?}",
2640 /// Calculates the Sized-constraint.
2642 /// In fact, there are only a few options for the types in the constraint:
2643 /// - an obviously-unsized type
2644 /// - a type parameter or projection whose Sizedness can't be known
2645 /// - a tuple of type parameters or projections, if there are multiple
2647 /// - a TyError, if a type contained itself. The representability
2648 /// check should catch this case.
2649 fn adt_sized_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2651 -> &'tcx [Ty<'tcx>] {
2652 let def = tcx.adt_def(def_id);
2654 let result = tcx.intern_type_list(&def.variants.iter().flat_map(|v| {
2657 def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
2658 }).collect::<Vec<_>>());
2660 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
2665 fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2667 -> Lrc<Vec<DefId>> {
2668 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2669 let item = tcx.hir.expect_item(id);
2670 let vec: Vec<_> = match item.node {
2671 hir::ItemTrait(.., ref trait_item_refs) => {
2672 trait_item_refs.iter()
2673 .map(|trait_item_ref| trait_item_ref.id)
2674 .map(|id| tcx.hir.local_def_id(id.node_id))
2677 hir::ItemImpl(.., ref impl_item_refs) => {
2678 impl_item_refs.iter()
2679 .map(|impl_item_ref| impl_item_ref.id)
2680 .map(|id| tcx.hir.local_def_id(id.node_id))
2683 hir::ItemTraitAlias(..) => vec![],
2684 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2689 fn def_span<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Span {
2690 tcx.hir.span_if_local(def_id).unwrap()
2693 /// If the given def ID describes an item belonging to a trait,
2694 /// return the ID of the trait that the trait item belongs to.
2695 /// Otherwise, return `None`.
2696 fn trait_of_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
2697 tcx.opt_associated_item(def_id)
2698 .and_then(|associated_item| {
2699 match associated_item.container {
2700 TraitContainer(def_id) => Some(def_id),
2701 ImplContainer(_) => None
2706 /// See `ParamEnv` struct def'n for details.
2707 fn param_env<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2710 // Compute the bounds on Self and the type parameters.
2712 let bounds = tcx.predicates_of(def_id).instantiate_identity(tcx);
2713 let predicates = bounds.predicates;
2715 // Finally, we have to normalize the bounds in the environment, in
2716 // case they contain any associated type projections. This process
2717 // can yield errors if the put in illegal associated types, like
2718 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2719 // report these errors right here; this doesn't actually feel
2720 // right to me, because constructing the environment feels like a
2721 // kind of a "idempotent" action, but I'm not sure where would be
2722 // a better place. In practice, we construct environments for
2723 // every fn once during type checking, and we'll abort if there
2724 // are any errors at that point, so after type checking you can be
2725 // sure that this will succeed without errors anyway.
2727 let unnormalized_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
2728 traits::Reveal::UserFacing,
2729 ty::UniverseIndex::ROOT);
2731 let body_id = tcx.hir.as_local_node_id(def_id).map_or(DUMMY_NODE_ID, |id| {
2732 tcx.hir.maybe_body_owned_by(id).map_or(id, |body| body.node_id)
2734 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
2735 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
2738 fn crate_disambiguator<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2739 crate_num: CrateNum) -> CrateDisambiguator {
2740 assert_eq!(crate_num, LOCAL_CRATE);
2741 tcx.sess.local_crate_disambiguator()
2744 fn original_crate_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2745 crate_num: CrateNum) -> Symbol {
2746 assert_eq!(crate_num, LOCAL_CRATE);
2747 tcx.crate_name.clone()
2750 fn crate_hash<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2751 crate_num: CrateNum)
2753 assert_eq!(crate_num, LOCAL_CRATE);
2757 fn instance_def_size_estimate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2758 instance_def: InstanceDef<'tcx>)
2760 match instance_def {
2761 InstanceDef::Item(..) |
2762 InstanceDef::DropGlue(..) => {
2763 let mir = tcx.instance_mir(instance_def);
2764 mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
2766 // Estimate the size of other compiler-generated shims to be 1.
2771 pub fn provide(providers: &mut ty::maps::Providers) {
2772 context::provide(providers);
2773 erase_regions::provide(providers);
2774 layout::provide(providers);
2775 util::provide(providers);
2776 *providers = ty::maps::Providers {
2778 associated_item_def_ids,
2779 adt_sized_constraint,
2783 crate_disambiguator,
2784 original_crate_name,
2786 trait_impls_of: trait_def::trait_impls_of_provider,
2787 instance_def_size_estimate,
2792 /// A map for the local crate mapping each type to a vector of its
2793 /// inherent impls. This is not meant to be used outside of coherence;
2794 /// rather, you should request the vector for a specific type via
2795 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2796 /// (constructing this map requires touching the entire crate).
2797 #[derive(Clone, Debug)]
2798 pub struct CrateInherentImpls {
2799 pub inherent_impls: DefIdMap<Lrc<Vec<DefId>>>,
2802 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
2803 pub struct SymbolName {
2804 // FIXME: we don't rely on interning or equality here - better have
2805 // this be a `&'tcx str`.
2806 pub name: InternedString
2809 impl_stable_hash_for!(struct self::SymbolName {
2814 pub fn new(name: &str) -> SymbolName {
2816 name: Symbol::intern(name).as_str()
2821 impl Deref for SymbolName {
2824 fn deref(&self) -> &str { &self.name }
2827 impl fmt::Display for SymbolName {
2828 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2829 fmt::Display::fmt(&self.name, fmt)
2833 impl fmt::Debug for SymbolName {
2834 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2835 fmt::Display::fmt(&self.name, fmt)