1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::Variance::*;
12 pub use self::AssociatedItemContainer::*;
13 pub use self::BorrowKind::*;
14 pub use self::IntVarValue::*;
15 pub use self::LvaluePreference::*;
16 pub use self::fold::TypeFoldable;
18 use hir::{map as hir_map, FreevarMap, TraitMap};
19 use hir::def::{Def, CtorKind, ExportMap};
20 use hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
21 use hir::map::DefPathData;
22 use ich::StableHashingContext;
23 use middle::const_val::ConstVal;
24 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
25 use middle::privacy::AccessLevels;
26 use middle::resolve_lifetime::ObjectLifetimeDefault;
28 use mir::GeneratorLayout;
29 use session::CrateDisambiguator;
32 use ty::subst::{Subst, Substs};
33 use ty::util::IntTypeExt;
34 use ty::walk::TypeWalker;
35 use util::common::ErrorReported;
36 use util::nodemap::{NodeSet, DefIdMap, FxHashMap, FxHashSet};
38 use serialize::{self, Encodable, Encoder};
39 use std::collections::BTreeMap;
42 use std::hash::{Hash, Hasher};
43 use std::iter::FromIterator;
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};
54 use rustc_const_math::ConstInt;
56 use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
57 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
62 pub use self::sty::{Binder, DebruijnIndex};
63 pub use self::sty::{FnSig, GenSig, PolyFnSig, PolyGenSig};
64 pub use self::sty::{InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
65 pub use self::sty::{ClosureSubsts, GeneratorInterior, TypeAndMut};
66 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
67 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
68 pub use self::sty::{ExistentialProjection, PolyExistentialProjection, Const};
69 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
70 pub use self::sty::RegionKind;
71 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid, SkolemizedRegionVid};
72 pub use self::sty::BoundRegion::*;
73 pub use self::sty::InferTy::*;
74 pub use self::sty::RegionKind::*;
75 pub use self::sty::TypeVariants::*;
77 pub use self::binding::BindingMode;
78 pub use self::binding::BindingMode::*;
80 pub use self::context::{TyCtxt, GlobalArenas, tls, keep_local};
81 pub use self::context::{Lift, TypeckTables};
83 pub use self::instance::{Instance, InstanceDef};
85 pub use self::trait_def::TraitDef;
87 pub use self::maps::queries;
98 pub mod inhabitedness;
115 mod structural_impls;
120 /// The complete set of all analyses described in this module. This is
121 /// produced by the driver and fed to trans and later passes.
123 /// NB: These contents are being migrated into queries using the
124 /// *on-demand* infrastructure.
126 pub struct CrateAnalysis {
127 pub access_levels: Rc<AccessLevels>,
129 pub glob_map: Option<hir::GlobMap>,
133 pub struct Resolutions {
134 pub freevars: FreevarMap,
135 pub trait_map: TraitMap,
136 pub maybe_unused_trait_imports: NodeSet,
137 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
138 pub export_map: ExportMap,
141 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
142 pub enum AssociatedItemContainer {
143 TraitContainer(DefId),
144 ImplContainer(DefId),
147 impl AssociatedItemContainer {
148 /// Asserts that this is the def-id of an associated item declared
149 /// in a trait, and returns the trait def-id.
150 pub fn assert_trait(&self) -> DefId {
152 TraitContainer(id) => id,
153 _ => bug!("associated item has wrong container type: {:?}", self)
157 pub fn id(&self) -> DefId {
159 TraitContainer(id) => id,
160 ImplContainer(id) => id,
165 /// The "header" of an impl is everything outside the body: a Self type, a trait
166 /// ref (in the case of a trait impl), and a set of predicates (from the
167 /// bounds/where clauses).
168 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
169 pub struct ImplHeader<'tcx> {
170 pub impl_def_id: DefId,
171 pub self_ty: Ty<'tcx>,
172 pub trait_ref: Option<TraitRef<'tcx>>,
173 pub predicates: Vec<Predicate<'tcx>>,
176 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
177 pub struct AssociatedItem {
180 pub kind: AssociatedKind,
182 pub defaultness: hir::Defaultness,
183 pub container: AssociatedItemContainer,
185 /// Whether this is a method with an explicit self
186 /// as its first argument, allowing method calls.
187 pub method_has_self_argument: bool,
190 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, RustcEncodable, RustcDecodable)]
191 pub enum AssociatedKind {
197 impl AssociatedItem {
198 pub fn def(&self) -> Def {
200 AssociatedKind::Const => Def::AssociatedConst(self.def_id),
201 AssociatedKind::Method => Def::Method(self.def_id),
202 AssociatedKind::Type => Def::AssociatedTy(self.def_id),
206 /// Tests whether the associated item admits a non-trivial implementation
208 pub fn relevant_for_never<'tcx>(&self) -> bool {
210 AssociatedKind::Const => true,
211 AssociatedKind::Type => true,
212 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
213 AssociatedKind::Method => !self.method_has_self_argument,
217 pub fn signature<'a, 'tcx>(&self, tcx: &TyCtxt<'a, 'tcx, 'tcx>) -> String {
219 ty::AssociatedKind::Method => {
220 // We skip the binder here because the binder would deanonymize all
221 // late-bound regions, and we don't want method signatures to show up
222 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
223 // regions just fine, showing `fn(&MyType)`.
224 format!("{}", tcx.fn_sig(self.def_id).skip_binder())
226 ty::AssociatedKind::Type => format!("type {};", self.name.to_string()),
227 ty::AssociatedKind::Const => {
228 format!("const {}: {:?};", self.name.to_string(), tcx.type_of(self.def_id))
234 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
235 pub enum Visibility {
236 /// Visible everywhere (including in other crates).
238 /// Visible only in the given crate-local module.
240 /// Not visible anywhere in the local crate. This is the visibility of private external items.
244 pub trait DefIdTree: Copy {
245 fn parent(self, id: DefId) -> Option<DefId>;
247 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
248 if descendant.krate != ancestor.krate {
252 while descendant != ancestor {
253 match self.parent(descendant) {
254 Some(parent) => descendant = parent,
255 None => return false,
262 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
263 fn parent(self, id: DefId) -> Option<DefId> {
264 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
269 pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
271 hir::Public => Visibility::Public,
272 hir::Visibility::Crate => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
273 hir::Visibility::Restricted { ref path, .. } => match path.def {
274 // If there is no resolution, `resolve` will have already reported an error, so
275 // assume that the visibility is public to avoid reporting more privacy errors.
276 Def::Err => Visibility::Public,
277 def => Visibility::Restricted(def.def_id()),
280 Visibility::Restricted(tcx.hir.get_module_parent(id))
285 /// Returns true if an item with this visibility is accessible from the given block.
286 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
287 let restriction = match self {
288 // Public items are visible everywhere.
289 Visibility::Public => return true,
290 // Private items from other crates are visible nowhere.
291 Visibility::Invisible => return false,
292 // Restricted items are visible in an arbitrary local module.
293 Visibility::Restricted(other) if other.krate != module.krate => return false,
294 Visibility::Restricted(module) => module,
297 tree.is_descendant_of(module, restriction)
300 /// Returns true if this visibility is at least as accessible as the given visibility
301 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
302 let vis_restriction = match vis {
303 Visibility::Public => return self == Visibility::Public,
304 Visibility::Invisible => return true,
305 Visibility::Restricted(module) => module,
308 self.is_accessible_from(vis_restriction, tree)
312 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
314 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
315 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
316 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
317 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
320 /// The crate variances map is computed during typeck and contains the
321 /// variance of every item in the local crate. You should not use it
322 /// directly, because to do so will make your pass dependent on the
323 /// HIR of every item in the local crate. Instead, use
324 /// `tcx.variances_of()` to get the variance for a *particular*
326 pub struct CrateVariancesMap {
327 /// For each item with generics, maps to a vector of the variance
328 /// of its generics. If an item has no generics, it will have no
330 pub variances: FxHashMap<DefId, Rc<Vec<ty::Variance>>>,
332 /// An empty vector, useful for cloning.
333 pub empty_variance: Rc<Vec<ty::Variance>>,
337 /// `a.xform(b)` combines the variance of a context with the
338 /// variance of a type with the following meaning. If we are in a
339 /// context with variance `a`, and we encounter a type argument in
340 /// a position with variance `b`, then `a.xform(b)` is the new
341 /// variance with which the argument appears.
347 /// Here, the "ambient" variance starts as covariant. `*mut T` is
348 /// invariant with respect to `T`, so the variance in which the
349 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
350 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
351 /// respect to its type argument `T`, and hence the variance of
352 /// the `i32` here is `Invariant.xform(Covariant)`, which results
353 /// (again) in `Invariant`.
357 /// fn(*const Vec<i32>, *mut Vec<i32)
359 /// The ambient variance is covariant. A `fn` type is
360 /// contravariant with respect to its parameters, so the variance
361 /// within which both pointer types appear is
362 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
363 /// T` is covariant with respect to `T`, so the variance within
364 /// which the first `Vec<i32>` appears is
365 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
366 /// is true for its `i32` argument. In the `*mut T` case, the
367 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
368 /// and hence the outermost type is `Invariant` with respect to
369 /// `Vec<i32>` (and its `i32` argument).
371 /// Source: Figure 1 of "Taming the Wildcards:
372 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
373 pub fn xform(self, v: ty::Variance) -> ty::Variance {
375 // Figure 1, column 1.
376 (ty::Covariant, ty::Covariant) => ty::Covariant,
377 (ty::Covariant, ty::Contravariant) => ty::Contravariant,
378 (ty::Covariant, ty::Invariant) => ty::Invariant,
379 (ty::Covariant, ty::Bivariant) => ty::Bivariant,
381 // Figure 1, column 2.
382 (ty::Contravariant, ty::Covariant) => ty::Contravariant,
383 (ty::Contravariant, ty::Contravariant) => ty::Covariant,
384 (ty::Contravariant, ty::Invariant) => ty::Invariant,
385 (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
387 // Figure 1, column 3.
388 (ty::Invariant, _) => ty::Invariant,
390 // Figure 1, column 4.
391 (ty::Bivariant, _) => ty::Bivariant,
396 // Contains information needed to resolve types and (in the future) look up
397 // the types of AST nodes.
398 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
399 pub struct CReaderCacheKey {
404 // Flags that we track on types. These flags are propagated upwards
405 // through the type during type construction, so that we can quickly
406 // check whether the type has various kinds of types in it without
407 // recursing over the type itself.
409 pub struct TypeFlags: u32 {
410 const HAS_PARAMS = 1 << 0;
411 const HAS_SELF = 1 << 1;
412 const HAS_TY_INFER = 1 << 2;
413 const HAS_RE_INFER = 1 << 3;
414 const HAS_RE_SKOL = 1 << 4;
415 const HAS_RE_EARLY_BOUND = 1 << 5;
416 const HAS_FREE_REGIONS = 1 << 6;
417 const HAS_TY_ERR = 1 << 7;
418 const HAS_PROJECTION = 1 << 8;
420 // FIXME: Rename this to the actual property since it's used for generators too
421 const HAS_TY_CLOSURE = 1 << 9;
423 // true if there are "names" of types and regions and so forth
424 // that are local to a particular fn
425 const HAS_LOCAL_NAMES = 1 << 10;
427 // Present if the type belongs in a local type context.
428 // Only set for TyInfer other than Fresh.
429 const KEEP_IN_LOCAL_TCX = 1 << 11;
431 // Is there a projection that does not involve a bound region?
432 // Currently we can't normalize projections w/ bound regions.
433 const HAS_NORMALIZABLE_PROJECTION = 1 << 12;
435 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
436 TypeFlags::HAS_SELF.bits |
437 TypeFlags::HAS_RE_EARLY_BOUND.bits;
439 // Flags representing the nominal content of a type,
440 // computed by FlagsComputation. If you add a new nominal
441 // flag, it should be added here too.
442 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
443 TypeFlags::HAS_SELF.bits |
444 TypeFlags::HAS_TY_INFER.bits |
445 TypeFlags::HAS_RE_INFER.bits |
446 TypeFlags::HAS_RE_SKOL.bits |
447 TypeFlags::HAS_RE_EARLY_BOUND.bits |
448 TypeFlags::HAS_FREE_REGIONS.bits |
449 TypeFlags::HAS_TY_ERR.bits |
450 TypeFlags::HAS_PROJECTION.bits |
451 TypeFlags::HAS_TY_CLOSURE.bits |
452 TypeFlags::HAS_LOCAL_NAMES.bits |
453 TypeFlags::KEEP_IN_LOCAL_TCX.bits;
457 pub struct TyS<'tcx> {
458 pub sty: TypeVariants<'tcx>,
459 pub flags: TypeFlags,
461 // the maximal depth of any bound regions appearing in this type.
465 impl<'tcx> PartialEq for TyS<'tcx> {
467 fn eq(&self, other: &TyS<'tcx>) -> bool {
468 // (self as *const _) == (other as *const _)
469 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
472 impl<'tcx> Eq for TyS<'tcx> {}
474 impl<'tcx> Hash for TyS<'tcx> {
475 fn hash<H: Hasher>(&self, s: &mut H) {
476 (self as *const TyS).hash(s)
480 impl<'tcx> TyS<'tcx> {
481 pub fn is_primitive_ty(&self) -> bool {
483 TypeVariants::TyBool |
484 TypeVariants::TyChar |
485 TypeVariants::TyInt(_) |
486 TypeVariants::TyUint(_) |
487 TypeVariants::TyFloat(_) |
488 TypeVariants::TyInfer(InferTy::IntVar(_)) |
489 TypeVariants::TyInfer(InferTy::FloatVar(_)) |
490 TypeVariants::TyInfer(InferTy::FreshIntTy(_)) |
491 TypeVariants::TyInfer(InferTy::FreshFloatTy(_)) => true,
492 TypeVariants::TyRef(_, x) => x.ty.is_primitive_ty(),
497 pub fn is_suggestable(&self) -> bool {
499 TypeVariants::TyAnon(..) |
500 TypeVariants::TyFnDef(..) |
501 TypeVariants::TyFnPtr(..) |
502 TypeVariants::TyDynamic(..) |
503 TypeVariants::TyClosure(..) |
504 TypeVariants::TyInfer(..) |
505 TypeVariants::TyProjection(..) => false,
511 impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::TyS<'gcx> {
512 fn hash_stable<W: StableHasherResult>(&self,
513 hcx: &mut StableHashingContext<'gcx>,
514 hasher: &mut StableHasher<W>) {
518 // The other fields just provide fast access to information that is
519 // also contained in `sty`, so no need to hash them.
524 sty.hash_stable(hcx, hasher);
528 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
530 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
531 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
533 /// A wrapper for slices with the additional invariant
534 /// that the slice is interned and no other slice with
535 /// the same contents can exist in the same context.
536 /// This means we can use pointer + length for both
537 /// equality comparisons and hashing.
538 #[derive(Debug, RustcEncodable)]
539 pub struct Slice<T>([T]);
541 impl<T> PartialEq for Slice<T> {
543 fn eq(&self, other: &Slice<T>) -> bool {
544 (&self.0 as *const [T]) == (&other.0 as *const [T])
547 impl<T> Eq for Slice<T> {}
549 impl<T> Hash for Slice<T> {
550 fn hash<H: Hasher>(&self, s: &mut H) {
551 (self.as_ptr(), self.len()).hash(s)
555 impl<T> Deref for Slice<T> {
557 fn deref(&self) -> &[T] {
562 impl<'a, T> IntoIterator for &'a Slice<T> {
564 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
565 fn into_iter(self) -> Self::IntoIter {
570 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
573 pub fn empty<'a>() -> &'a Slice<T> {
575 mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
580 /// Upvars do not get their own node-id. Instead, we use the pair of
581 /// the original var id (that is, the root variable that is referenced
582 /// by the upvar) and the id of the closure expression.
583 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
585 pub var_id: hir::HirId,
586 pub closure_expr_id: LocalDefId,
589 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
590 pub enum BorrowKind {
591 /// Data must be immutable and is aliasable.
594 /// Data must be immutable but not aliasable. This kind of borrow
595 /// cannot currently be expressed by the user and is used only in
596 /// implicit closure bindings. It is needed when the closure
597 /// is borrowing or mutating a mutable referent, e.g.:
599 /// let x: &mut isize = ...;
600 /// let y = || *x += 5;
602 /// If we were to try to translate this closure into a more explicit
603 /// form, we'd encounter an error with the code as written:
605 /// struct Env { x: & &mut isize }
606 /// let x: &mut isize = ...;
607 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
608 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
610 /// This is then illegal because you cannot mutate a `&mut` found
611 /// in an aliasable location. To solve, you'd have to translate with
612 /// an `&mut` borrow:
614 /// struct Env { x: & &mut isize }
615 /// let x: &mut isize = ...;
616 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
617 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
619 /// Now the assignment to `**env.x` is legal, but creating a
620 /// mutable pointer to `x` is not because `x` is not mutable. We
621 /// could fix this by declaring `x` as `let mut x`. This is ok in
622 /// user code, if awkward, but extra weird for closures, since the
623 /// borrow is hidden.
625 /// So we introduce a "unique imm" borrow -- the referent is
626 /// immutable, but not aliasable. This solves the problem. For
627 /// simplicity, we don't give users the way to express this
628 /// borrow, it's just used when translating closures.
631 /// Data is mutable and not aliasable.
635 /// Information describing the capture of an upvar. This is computed
636 /// during `typeck`, specifically by `regionck`.
637 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
638 pub enum UpvarCapture<'tcx> {
639 /// Upvar is captured by value. This is always true when the
640 /// closure is labeled `move`, but can also be true in other cases
641 /// depending on inference.
644 /// Upvar is captured by reference.
645 ByRef(UpvarBorrow<'tcx>),
648 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
649 pub struct UpvarBorrow<'tcx> {
650 /// The kind of borrow: by-ref upvars have access to shared
651 /// immutable borrows, which are not part of the normal language
653 pub kind: BorrowKind,
655 /// Region of the resulting reference.
656 pub region: ty::Region<'tcx>,
659 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
661 #[derive(Copy, Clone)]
662 pub struct ClosureUpvar<'tcx> {
668 #[derive(Clone, Copy, PartialEq)]
669 pub enum IntVarValue {
671 UintType(ast::UintTy),
674 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
675 pub struct TypeParameterDef {
679 pub has_default: bool,
680 pub object_lifetime_default: ObjectLifetimeDefault,
682 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
683 /// on generic parameter `T`, asserts data behind the parameter
684 /// `T` won't be accessed during the parent type's `Drop` impl.
685 pub pure_wrt_drop: bool,
687 pub synthetic: Option<hir::SyntheticTyParamKind>,
690 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
691 pub struct RegionParameterDef {
696 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
697 /// on generic parameter `'a`, asserts data of lifetime `'a`
698 /// won't be accessed during the parent type's `Drop` impl.
699 pub pure_wrt_drop: bool,
702 impl RegionParameterDef {
703 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
704 ty::EarlyBoundRegion {
711 pub fn to_bound_region(&self) -> ty::BoundRegion {
712 self.to_early_bound_region_data().to_bound_region()
716 impl ty::EarlyBoundRegion {
717 pub fn to_bound_region(&self) -> ty::BoundRegion {
718 ty::BoundRegion::BrNamed(self.def_id, self.name)
722 /// Information about the formal type/lifetime parameters associated
723 /// with an item or method. Analogous to hir::Generics.
725 /// Note that in the presence of a `Self` parameter, the ordering here
726 /// is different from the ordering in a Substs. Substs are ordered as
727 /// Self, *Regions, *Other Type Params, (...child generics)
728 /// while this struct is ordered as
729 /// regions = Regions
730 /// types = [Self, *Other Type Params]
731 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
732 pub struct Generics {
733 pub parent: Option<DefId>,
734 pub parent_regions: u32,
735 pub parent_types: u32,
736 pub regions: Vec<RegionParameterDef>,
737 pub types: Vec<TypeParameterDef>,
739 /// Reverse map to each `TypeParameterDef`'s `index` field, from
740 /// `def_id.index` (`def_id.krate` is the same as the item's).
741 pub type_param_to_index: BTreeMap<DefIndex, u32>,
744 pub has_late_bound_regions: Option<Span>,
747 impl<'a, 'gcx, 'tcx> Generics {
748 pub fn parent_count(&self) -> usize {
749 self.parent_regions as usize + self.parent_types as usize
752 pub fn own_count(&self) -> usize {
753 self.regions.len() + self.types.len()
756 pub fn count(&self) -> usize {
757 self.parent_count() + self.own_count()
760 pub fn region_param(&'tcx self,
761 param: &EarlyBoundRegion,
762 tcx: TyCtxt<'a, 'gcx, 'tcx>)
763 -> &'tcx RegionParameterDef
765 if let Some(index) = param.index.checked_sub(self.parent_count() as u32) {
766 &self.regions[index as usize - self.has_self as usize]
768 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
769 .region_param(param, tcx)
773 /// Returns the `TypeParameterDef` associated with this `ParamTy`.
774 pub fn type_param(&'tcx self,
776 tcx: TyCtxt<'a, 'gcx, 'tcx>)
777 -> &TypeParameterDef {
778 if let Some(idx) = param.idx.checked_sub(self.parent_count() as u32) {
779 // non-Self type parameters are always offset by exactly
780 // `self.regions.len()`. In the absence of a Self, this is obvious,
781 // but even in the absence of a `Self` we just have to "compensate"
784 // For example, for `trait Foo<'a, 'b, T1, T2>`, the
792 // And it can be seen that to move from a substs offset to a
793 // generics offset you just have to offset by the number of regions.
794 let type_param_offset = self.regions.len();
795 if let Some(idx) = (idx as usize).checked_sub(type_param_offset) {
796 assert!(!(self.has_self && idx == 0));
799 assert!(self.has_self && idx == 0);
803 tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
804 .type_param(param, tcx)
809 /// Bounds on generics.
810 #[derive(Clone, Default)]
811 pub struct GenericPredicates<'tcx> {
812 pub parent: Option<DefId>,
813 pub predicates: Vec<Predicate<'tcx>>,
816 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
817 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
819 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
820 pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
821 -> InstantiatedPredicates<'tcx> {
822 let mut instantiated = InstantiatedPredicates::empty();
823 self.instantiate_into(tcx, &mut instantiated, substs);
826 pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
827 -> InstantiatedPredicates<'tcx> {
828 InstantiatedPredicates {
829 predicates: self.predicates.subst(tcx, substs)
833 fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
834 instantiated: &mut InstantiatedPredicates<'tcx>,
835 substs: &Substs<'tcx>) {
836 if let Some(def_id) = self.parent {
837 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
839 instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
842 pub fn instantiate_identity(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
843 -> InstantiatedPredicates<'tcx> {
844 let mut instantiated = InstantiatedPredicates::empty();
845 self.instantiate_identity_into(tcx, &mut instantiated);
849 fn instantiate_identity_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
850 instantiated: &mut InstantiatedPredicates<'tcx>) {
851 if let Some(def_id) = self.parent {
852 tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
854 instantiated.predicates.extend(&self.predicates)
857 pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
858 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
859 -> InstantiatedPredicates<'tcx>
861 assert_eq!(self.parent, None);
862 InstantiatedPredicates {
863 predicates: self.predicates.iter().map(|pred| {
864 pred.subst_supertrait(tcx, poly_trait_ref)
870 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
871 pub enum Predicate<'tcx> {
872 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
873 /// the `Self` type of the trait reference and `A`, `B`, and `C`
874 /// would be the type parameters.
875 Trait(PolyTraitPredicate<'tcx>),
877 /// where `T1 == T2`.
878 Equate(PolyEquatePredicate<'tcx>),
881 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
884 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
886 /// where <T as TraitRef>::Name == X, approximately.
887 /// See `ProjectionPredicate` struct for details.
888 Projection(PolyProjectionPredicate<'tcx>),
891 WellFormed(Ty<'tcx>),
893 /// trait must be object-safe
896 /// No direct syntax. May be thought of as `where T : FnFoo<...>`
897 /// for some substitutions `...` and T being a closure type.
898 /// Satisfied (or refuted) once we know the closure's kind.
899 ClosureKind(DefId, ClosureSubsts<'tcx>, ClosureKind),
902 Subtype(PolySubtypePredicate<'tcx>),
904 /// Constant initializer must evaluate successfully.
905 ConstEvaluatable(DefId, &'tcx Substs<'tcx>),
908 impl<'tcx> AsRef<Predicate<'tcx>> for Predicate<'tcx> {
909 fn as_ref(&self) -> &Predicate<'tcx> {
914 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
915 /// Performs a substitution suitable for going from a
916 /// poly-trait-ref to supertraits that must hold if that
917 /// poly-trait-ref holds. This is slightly different from a normal
918 /// substitution in terms of what happens with bound regions. See
919 /// lengthy comment below for details.
920 pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
921 trait_ref: &ty::PolyTraitRef<'tcx>)
922 -> ty::Predicate<'tcx>
924 // The interaction between HRTB and supertraits is not entirely
925 // obvious. Let me walk you (and myself) through an example.
927 // Let's start with an easy case. Consider two traits:
929 // trait Foo<'a> : Bar<'a,'a> { }
930 // trait Bar<'b,'c> { }
932 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
933 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
934 // knew that `Foo<'x>` (for any 'x) then we also know that
935 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
936 // normal substitution.
938 // In terms of why this is sound, the idea is that whenever there
939 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
940 // holds. So if there is an impl of `T:Foo<'a>` that applies to
941 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
944 // Another example to be careful of is this:
946 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
947 // trait Bar1<'b,'c> { }
949 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
950 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
951 // reason is similar to the previous example: any impl of
952 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
953 // basically we would want to collapse the bound lifetimes from
954 // the input (`trait_ref`) and the supertraits.
956 // To achieve this in practice is fairly straightforward. Let's
957 // consider the more complicated scenario:
959 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
960 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
961 // where both `'x` and `'b` would have a DB index of 1.
962 // The substitution from the input trait-ref is therefore going to be
963 // `'a => 'x` (where `'x` has a DB index of 1).
964 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
965 // early-bound parameter and `'b' is a late-bound parameter with a
967 // - If we replace `'a` with `'x` from the input, it too will have
968 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
969 // just as we wanted.
971 // There is only one catch. If we just apply the substitution `'a
972 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
973 // adjust the DB index because we substituting into a binder (it
974 // tries to be so smart...) resulting in `for<'x> for<'b>
975 // Bar1<'x,'b>` (we have no syntax for this, so use your
976 // imagination). Basically the 'x will have DB index of 2 and 'b
977 // will have DB index of 1. Not quite what we want. So we apply
978 // the substitution to the *contents* of the trait reference,
979 // rather than the trait reference itself (put another way, the
980 // substitution code expects equal binding levels in the values
981 // from the substitution and the value being substituted into, and
982 // this trick achieves that).
984 let substs = &trait_ref.0.substs;
986 Predicate::Trait(ty::Binder(ref data)) =>
987 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
988 Predicate::Equate(ty::Binder(ref data)) =>
989 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
990 Predicate::Subtype(ty::Binder(ref data)) =>
991 Predicate::Subtype(ty::Binder(data.subst(tcx, substs))),
992 Predicate::RegionOutlives(ty::Binder(ref data)) =>
993 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
994 Predicate::TypeOutlives(ty::Binder(ref data)) =>
995 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
996 Predicate::Projection(ty::Binder(ref data)) =>
997 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
998 Predicate::WellFormed(data) =>
999 Predicate::WellFormed(data.subst(tcx, substs)),
1000 Predicate::ObjectSafe(trait_def_id) =>
1001 Predicate::ObjectSafe(trait_def_id),
1002 Predicate::ClosureKind(closure_def_id, closure_substs, kind) =>
1003 Predicate::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind),
1004 Predicate::ConstEvaluatable(def_id, const_substs) =>
1005 Predicate::ConstEvaluatable(def_id, const_substs.subst(tcx, substs)),
1010 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1011 pub struct TraitPredicate<'tcx> {
1012 pub trait_ref: TraitRef<'tcx>
1014 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1016 impl<'tcx> TraitPredicate<'tcx> {
1017 pub fn def_id(&self) -> DefId {
1018 self.trait_ref.def_id
1021 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
1022 self.trait_ref.input_types()
1025 pub fn self_ty(&self) -> Ty<'tcx> {
1026 self.trait_ref.self_ty()
1030 impl<'tcx> PolyTraitPredicate<'tcx> {
1031 pub fn def_id(&self) -> DefId {
1032 // ok to skip binder since trait def-id does not care about regions
1037 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1038 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
1039 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
1041 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1042 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
1043 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
1044 pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<ty::Region<'tcx>,
1046 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1048 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1049 pub struct SubtypePredicate<'tcx> {
1050 pub a_is_expected: bool,
1054 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1056 /// This kind of predicate has no *direct* correspondent in the
1057 /// syntax, but it roughly corresponds to the syntactic forms:
1059 /// 1. `T : TraitRef<..., Item=Type>`
1060 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1062 /// In particular, form #1 is "desugared" to the combination of a
1063 /// normal trait predicate (`T : TraitRef<...>`) and one of these
1064 /// predicates. Form #2 is a broader form in that it also permits
1065 /// equality between arbitrary types. Processing an instance of Form
1066 /// #2 eventually yields one of these `ProjectionPredicate`
1067 /// instances to normalize the LHS.
1068 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1069 pub struct ProjectionPredicate<'tcx> {
1070 pub projection_ty: ProjectionTy<'tcx>,
1074 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1076 impl<'tcx> PolyProjectionPredicate<'tcx> {
1077 pub fn to_poly_trait_ref(&self, tcx: TyCtxt) -> PolyTraitRef<'tcx> {
1078 // Note: unlike with TraitRef::to_poly_trait_ref(),
1079 // self.0.trait_ref is permitted to have escaping regions.
1080 // This is because here `self` has a `Binder` and so does our
1081 // return value, so we are preserving the number of binding
1083 ty::Binder(self.0.projection_ty.trait_ref(tcx))
1086 pub fn ty(&self) -> Binder<Ty<'tcx>> {
1087 Binder(self.skip_binder().ty) // preserves binding levels
1091 pub trait ToPolyTraitRef<'tcx> {
1092 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1095 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1096 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1097 assert!(!self.has_escaping_regions());
1098 ty::Binder(self.clone())
1102 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1103 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1104 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1108 pub trait ToPredicate<'tcx> {
1109 fn to_predicate(&self) -> Predicate<'tcx>;
1112 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1113 fn to_predicate(&self) -> Predicate<'tcx> {
1114 // we're about to add a binder, so let's check that we don't
1115 // accidentally capture anything, or else that might be some
1116 // weird debruijn accounting.
1117 assert!(!self.has_escaping_regions());
1119 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1120 trait_ref: self.clone()
1125 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1126 fn to_predicate(&self) -> Predicate<'tcx> {
1127 ty::Predicate::Trait(self.to_poly_trait_predicate())
1131 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
1132 fn to_predicate(&self) -> Predicate<'tcx> {
1133 Predicate::Equate(self.clone())
1137 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1138 fn to_predicate(&self) -> Predicate<'tcx> {
1139 Predicate::RegionOutlives(self.clone())
1143 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1144 fn to_predicate(&self) -> Predicate<'tcx> {
1145 Predicate::TypeOutlives(self.clone())
1149 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1150 fn to_predicate(&self) -> Predicate<'tcx> {
1151 Predicate::Projection(self.clone())
1155 impl<'tcx> Predicate<'tcx> {
1156 /// Iterates over the types in this predicate. Note that in all
1157 /// cases this is skipping over a binder, so late-bound regions
1158 /// with depth 0 are bound by the predicate.
1159 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1160 let vec: Vec<_> = match *self {
1161 ty::Predicate::Trait(ref data) => {
1162 data.skip_binder().input_types().collect()
1164 ty::Predicate::Equate(ty::Binder(ref data)) => {
1165 vec![data.0, data.1]
1167 ty::Predicate::Subtype(ty::Binder(SubtypePredicate { a, b, a_is_expected: _ })) => {
1170 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1173 ty::Predicate::RegionOutlives(..) => {
1176 ty::Predicate::Projection(ref data) => {
1177 data.0.projection_ty.substs.types().chain(Some(data.0.ty)).collect()
1179 ty::Predicate::WellFormed(data) => {
1182 ty::Predicate::ObjectSafe(_trait_def_id) => {
1185 ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => {
1186 closure_substs.substs.types().collect()
1188 ty::Predicate::ConstEvaluatable(_, substs) => {
1189 substs.types().collect()
1193 // The only reason to collect into a vector here is that I was
1194 // too lazy to make the full (somewhat complicated) iterator
1195 // type that would be needed here. But I wanted this fn to
1196 // return an iterator conceptually, rather than a `Vec`, so as
1197 // to be closer to `Ty::walk`.
1201 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1203 Predicate::Trait(ref t) => {
1204 Some(t.to_poly_trait_ref())
1206 Predicate::Projection(..) |
1207 Predicate::Equate(..) |
1208 Predicate::Subtype(..) |
1209 Predicate::RegionOutlives(..) |
1210 Predicate::WellFormed(..) |
1211 Predicate::ObjectSafe(..) |
1212 Predicate::ClosureKind(..) |
1213 Predicate::TypeOutlives(..) |
1214 Predicate::ConstEvaluatable(..) => {
1220 pub fn to_opt_type_outlives(&self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1222 Predicate::TypeOutlives(data) => {
1225 Predicate::Trait(..) |
1226 Predicate::Projection(..) |
1227 Predicate::Equate(..) |
1228 Predicate::Subtype(..) |
1229 Predicate::RegionOutlives(..) |
1230 Predicate::WellFormed(..) |
1231 Predicate::ObjectSafe(..) |
1232 Predicate::ClosureKind(..) |
1233 Predicate::ConstEvaluatable(..) => {
1240 /// Represents the bounds declared on a particular set of type
1241 /// parameters. Should eventually be generalized into a flag list of
1242 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
1243 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1244 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1245 /// the `GenericPredicates` are expressed in terms of the bound type
1246 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1247 /// represented a set of bounds for some particular instantiation,
1248 /// meaning that the generic parameters have been substituted with
1253 /// struct Foo<T,U:Bar<T>> { ... }
1255 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1256 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1257 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1258 /// [usize:Bar<isize>]]`.
1260 pub struct InstantiatedPredicates<'tcx> {
1261 pub predicates: Vec<Predicate<'tcx>>,
1264 impl<'tcx> InstantiatedPredicates<'tcx> {
1265 pub fn empty() -> InstantiatedPredicates<'tcx> {
1266 InstantiatedPredicates { predicates: vec![] }
1269 pub fn is_empty(&self) -> bool {
1270 self.predicates.is_empty()
1274 /// When type checking, we use the `ParamEnv` to track
1275 /// details about the set of where-clauses that are in scope at this
1276 /// particular point.
1277 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1278 pub struct ParamEnv<'tcx> {
1279 /// Obligations that the caller must satisfy. This is basically
1280 /// the set of bounds on the in-scope type parameters, translated
1281 /// into Obligations, and elaborated and normalized.
1282 pub caller_bounds: &'tcx Slice<ty::Predicate<'tcx>>,
1284 /// Typically, this is `Reveal::UserFacing`, but during trans we
1285 /// want `Reveal::All` -- note that this is always paired with an
1286 /// empty environment. To get that, use `ParamEnv::reveal()`.
1287 pub reveal: traits::Reveal,
1290 impl<'tcx> ParamEnv<'tcx> {
1291 /// Creates a suitable environment in which to perform trait
1292 /// queries on the given value. This will either be `self` *or*
1293 /// the empty environment, depending on whether `value` references
1294 /// type parameters that are in scope. (If it doesn't, then any
1295 /// judgements should be completely independent of the context,
1296 /// and hence we can safely use the empty environment so as to
1297 /// enable more sharing across functions.)
1299 /// NB: This is a mildly dubious thing to do, in that a function
1300 /// (or other environment) might have wacky where-clauses like
1301 /// `where Box<u32>: Copy`, which are clearly never
1302 /// satisfiable. The code will at present ignore these,
1303 /// effectively, when type-checking the body of said
1304 /// function. This preserves existing behavior in any
1305 /// case. --nmatsakis
1306 pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1307 assert!(!value.needs_infer());
1308 if value.has_param_types() || value.has_self_ty() {
1315 param_env: ParamEnv::empty(self.reveal),
1322 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1323 pub struct ParamEnvAnd<'tcx, T> {
1324 pub param_env: ParamEnv<'tcx>,
1328 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1329 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1330 (self.param_env, self.value)
1334 impl<'gcx, T> HashStable<StableHashingContext<'gcx>> for ParamEnvAnd<'gcx, T>
1335 where T: HashStable<StableHashingContext<'gcx>>
1337 fn hash_stable<W: StableHasherResult>(&self,
1338 hcx: &mut StableHashingContext<'gcx>,
1339 hasher: &mut StableHasher<W>) {
1345 param_env.hash_stable(hcx, hasher);
1346 value.hash_stable(hcx, hasher);
1350 #[derive(Copy, Clone, Debug)]
1351 pub struct Destructor {
1352 /// The def-id of the destructor method
1357 pub struct AdtFlags: u32 {
1358 const NO_ADT_FLAGS = 0;
1359 const IS_ENUM = 1 << 0;
1360 const IS_PHANTOM_DATA = 1 << 1;
1361 const IS_FUNDAMENTAL = 1 << 2;
1362 const IS_UNION = 1 << 3;
1363 const IS_BOX = 1 << 4;
1364 /// Indicates whether this abstract data type will be expanded on in future (new
1365 /// fields/variants) and as such, whether downstream crates must match exhaustively on the
1366 /// fields/variants of this data type.
1368 /// See RFC 2008 (https://github.com/rust-lang/rfcs/pull/2008).
1369 const IS_NON_EXHAUSTIVE = 1 << 5;
1374 pub struct VariantDef {
1375 /// The variant's DefId. If this is a tuple-like struct,
1376 /// this is the DefId of the struct's ctor.
1378 pub name: Name, // struct's name if this is a struct
1379 pub discr: VariantDiscr,
1380 pub fields: Vec<FieldDef>,
1381 pub ctor_kind: CtorKind,
1384 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1385 pub enum VariantDiscr {
1386 /// Explicit value for this variant, i.e. `X = 123`.
1387 /// The `DefId` corresponds to the embedded constant.
1390 /// The previous variant's discriminant plus one.
1391 /// For efficiency reasons, the distance from the
1392 /// last `Explicit` discriminant is being stored,
1393 /// or `0` for the first variant, if it has none.
1398 pub struct FieldDef {
1401 pub vis: Visibility,
1404 /// The definition of an abstract data type - a struct or enum.
1406 /// These are all interned (by intern_adt_def) into the adt_defs
1410 pub variants: Vec<VariantDef>,
1412 pub repr: ReprOptions,
1415 impl PartialEq for AdtDef {
1416 // AdtDef are always interned and this is part of TyS equality
1418 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1421 impl Eq for AdtDef {}
1423 impl Hash for AdtDef {
1425 fn hash<H: Hasher>(&self, s: &mut H) {
1426 (self as *const AdtDef).hash(s)
1430 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1431 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1436 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1439 impl<'gcx> HashStable<StableHashingContext<'gcx>> for AdtDef {
1440 fn hash_stable<W: StableHasherResult>(&self,
1441 hcx: &mut StableHashingContext<'gcx>,
1442 hasher: &mut StableHasher<W>) {
1450 did.hash_stable(hcx, hasher);
1451 variants.hash_stable(hcx, hasher);
1452 flags.hash_stable(hcx, hasher);
1453 repr.hash_stable(hcx, hasher);
1457 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1458 pub enum AdtKind { Struct, Union, Enum }
1461 #[derive(RustcEncodable, RustcDecodable, Default)]
1462 pub struct ReprFlags: u8 {
1463 const IS_C = 1 << 0;
1464 const IS_PACKED = 1 << 1;
1465 const IS_SIMD = 1 << 2;
1466 // Internal only for now. If true, don't reorder fields.
1467 const IS_LINEAR = 1 << 3;
1469 // Any of these flags being set prevent field reordering optimisation.
1470 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1471 ReprFlags::IS_PACKED.bits |
1472 ReprFlags::IS_SIMD.bits |
1473 ReprFlags::IS_LINEAR.bits;
1477 impl_stable_hash_for!(struct ReprFlags {
1483 /// Represents the repr options provided by the user,
1484 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1485 pub struct ReprOptions {
1486 pub int: Option<attr::IntType>,
1488 pub flags: ReprFlags,
1491 impl_stable_hash_for!(struct ReprOptions {
1498 pub fn new(tcx: TyCtxt, did: DefId) -> ReprOptions {
1499 let mut flags = ReprFlags::empty();
1500 let mut size = None;
1501 let mut max_align = 0;
1502 for attr in tcx.get_attrs(did).iter() {
1503 for r in attr::find_repr_attrs(tcx.sess.diagnostic(), attr) {
1504 flags.insert(match r {
1505 attr::ReprExtern => ReprFlags::IS_C,
1506 attr::ReprPacked => ReprFlags::IS_PACKED,
1507 attr::ReprSimd => ReprFlags::IS_SIMD,
1508 attr::ReprInt(i) => {
1512 attr::ReprAlign(align) => {
1513 max_align = cmp::max(align, max_align);
1520 // FIXME(eddyb) This is deprecated and should be removed.
1521 if tcx.has_attr(did, "simd") {
1522 flags.insert(ReprFlags::IS_SIMD);
1525 // This is here instead of layout because the choice must make it into metadata.
1526 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.item_path_str(did))) {
1527 flags.insert(ReprFlags::IS_LINEAR);
1529 ReprOptions { int: size, align: max_align, flags: flags }
1533 pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
1535 pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
1537 pub fn packed(&self) -> bool { self.flags.contains(ReprFlags::IS_PACKED) }
1539 pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
1541 pub fn discr_type(&self) -> attr::IntType {
1542 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Is))
1545 /// Returns true if this `#[repr()]` should inhabit "smart enum
1546 /// layout" optimizations, such as representing `Foo<&T>` as a
1548 pub fn inhibit_enum_layout_opt(&self) -> bool {
1549 self.c() || self.int.is_some()
1553 impl<'a, 'gcx, 'tcx> AdtDef {
1557 variants: Vec<VariantDef>,
1558 repr: ReprOptions) -> Self {
1559 let mut flags = AdtFlags::NO_ADT_FLAGS;
1560 let attrs = tcx.get_attrs(did);
1561 if attr::contains_name(&attrs, "fundamental") {
1562 flags = flags | AdtFlags::IS_FUNDAMENTAL;
1564 if Some(did) == tcx.lang_items().phantom_data() {
1565 flags = flags | AdtFlags::IS_PHANTOM_DATA;
1567 if Some(did) == tcx.lang_items().owned_box() {
1568 flags = flags | AdtFlags::IS_BOX;
1570 if tcx.has_attr(did, "non_exhaustive") {
1571 flags = flags | AdtFlags::IS_NON_EXHAUSTIVE;
1574 AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1575 AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1576 AdtKind::Struct => {}
1587 pub fn is_struct(&self) -> bool {
1588 !self.is_union() && !self.is_enum()
1592 pub fn is_union(&self) -> bool {
1593 self.flags.intersects(AdtFlags::IS_UNION)
1597 pub fn is_enum(&self) -> bool {
1598 self.flags.intersects(AdtFlags::IS_ENUM)
1602 pub fn is_non_exhaustive(&self) -> bool {
1603 self.flags.intersects(AdtFlags::IS_NON_EXHAUSTIVE)
1606 /// Returns the kind of the ADT - Struct or Enum.
1608 pub fn adt_kind(&self) -> AdtKind {
1611 } else if self.is_union() {
1618 pub fn descr(&self) -> &'static str {
1619 match self.adt_kind() {
1620 AdtKind::Struct => "struct",
1621 AdtKind::Union => "union",
1622 AdtKind::Enum => "enum",
1626 pub fn variant_descr(&self) -> &'static str {
1627 match self.adt_kind() {
1628 AdtKind::Struct => "struct",
1629 AdtKind::Union => "union",
1630 AdtKind::Enum => "variant",
1634 /// Returns whether this type is #[fundamental] for the purposes
1635 /// of coherence checking.
1637 pub fn is_fundamental(&self) -> bool {
1638 self.flags.intersects(AdtFlags::IS_FUNDAMENTAL)
1641 /// Returns true if this is PhantomData<T>.
1643 pub fn is_phantom_data(&self) -> bool {
1644 self.flags.intersects(AdtFlags::IS_PHANTOM_DATA)
1647 /// Returns true if this is Box<T>.
1649 pub fn is_box(&self) -> bool {
1650 self.flags.intersects(AdtFlags::IS_BOX)
1653 /// Returns whether this type has a destructor.
1654 pub fn has_dtor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1655 self.destructor(tcx).is_some()
1658 /// Asserts this is a struct and returns the struct's unique
1660 pub fn struct_variant(&self) -> &VariantDef {
1661 assert!(!self.is_enum());
1666 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1667 tcx.predicates_of(self.did)
1670 /// Returns an iterator over all fields contained
1673 pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1674 self.variants.iter().flat_map(|v| v.fields.iter())
1677 pub fn is_payloadfree(&self) -> bool {
1678 !self.variants.is_empty() &&
1679 self.variants.iter().all(|v| v.fields.is_empty())
1682 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1685 .find(|v| v.did == vid)
1686 .expect("variant_with_id: unknown variant")
1689 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1692 .position(|v| v.did == vid)
1693 .expect("variant_index_with_id: unknown variant")
1696 pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1698 Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1699 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1700 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.struct_variant(),
1701 _ => bug!("unexpected def {:?} in variant_of_def", def)
1706 pub fn discriminants(&'a self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
1707 -> impl Iterator<Item=ConstInt> + 'a {
1708 let param_env = ParamEnv::empty(traits::Reveal::UserFacing);
1709 let repr_type = self.repr.discr_type();
1710 let initial = repr_type.initial_discriminant(tcx.global_tcx());
1711 let mut prev_discr = None::<ConstInt>;
1712 self.variants.iter().map(move |v| {
1713 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr());
1714 if let VariantDiscr::Explicit(expr_did) = v.discr {
1715 let substs = Substs::identity_for_item(tcx.global_tcx(), expr_did);
1716 match tcx.const_eval(param_env.and((expr_did, substs))) {
1717 Ok(&ty::Const { val: ConstVal::Integral(v), .. }) => {
1721 if !expr_did.is_local() {
1722 span_bug!(tcx.def_span(expr_did),
1723 "variant discriminant evaluation succeeded \
1724 in its crate but failed locally: {:?}", err);
1729 prev_discr = Some(discr);
1735 /// Compute the discriminant value used by a specific variant.
1736 /// Unlike `discriminants`, this is (amortized) constant-time,
1737 /// only doing at most one query for evaluating an explicit
1738 /// discriminant (the last one before the requested variant),
1739 /// assuming there are no constant-evaluation errors there.
1740 pub fn discriminant_for_variant(&self,
1741 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1742 variant_index: usize)
1744 let param_env = ParamEnv::empty(traits::Reveal::UserFacing);
1745 let repr_type = self.repr.discr_type();
1746 let mut explicit_value = repr_type.initial_discriminant(tcx.global_tcx());
1747 let mut explicit_index = variant_index;
1749 match self.variants[explicit_index].discr {
1750 ty::VariantDiscr::Relative(0) => break,
1751 ty::VariantDiscr::Relative(distance) => {
1752 explicit_index -= distance;
1754 ty::VariantDiscr::Explicit(expr_did) => {
1755 let substs = Substs::identity_for_item(tcx.global_tcx(), expr_did);
1756 match tcx.const_eval(param_env.and((expr_did, substs))) {
1757 Ok(&ty::Const { val: ConstVal::Integral(v), .. }) => {
1762 if !expr_did.is_local() {
1763 span_bug!(tcx.def_span(expr_did),
1764 "variant discriminant evaluation succeeded \
1765 in its crate but failed locally: {:?}", err);
1767 if explicit_index == 0 {
1770 explicit_index -= 1;
1776 let discr = explicit_value.to_u128_unchecked()
1777 .wrapping_add((variant_index - explicit_index) as u128);
1779 attr::UnsignedInt(ty) => {
1780 ConstInt::new_unsigned_truncating(discr, ty,
1781 tcx.sess.target.usize_ty)
1783 attr::SignedInt(ty) => {
1784 ConstInt::new_signed_truncating(discr as i128, ty,
1785 tcx.sess.target.isize_ty)
1790 pub fn destructor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Destructor> {
1791 tcx.adt_destructor(self.did)
1794 /// Returns a list of types such that `Self: Sized` if and only
1795 /// if that type is Sized, or `TyErr` if this type is recursive.
1797 /// Oddly enough, checking that the sized-constraint is Sized is
1798 /// actually more expressive than checking all members:
1799 /// the Sized trait is inductive, so an associated type that references
1800 /// Self would prevent its containing ADT from being Sized.
1802 /// Due to normalization being eager, this applies even if
1803 /// the associated type is behind a pointer, e.g. issue #31299.
1804 pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] {
1805 match queries::adt_sized_constraint::try_get(tcx, DUMMY_SP, self.did) {
1808 debug!("adt_sized_constraint: {:?} is recursive", self);
1809 // This should be reported as an error by `check_representable`.
1811 // Consider the type as Sized in the meanwhile to avoid
1812 // further errors. Delay our `bug` diagnostic here to get
1813 // emitted later as well in case we accidentally otherwise don't
1816 tcx.intern_type_list(&[tcx.types.err])
1821 fn sized_constraint_for_ty(&self,
1822 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1825 let result = match ty.sty {
1826 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
1827 TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
1828 TyArray(..) | TyClosure(..) | TyGenerator(..) | TyNever => {
1832 TyStr | TyDynamic(..) | TySlice(_) | TyForeign(..) | TyError => {
1833 // these are never sized - return the target type
1837 TyTuple(ref tys, _) => {
1840 Some(ty) => self.sized_constraint_for_ty(tcx, ty)
1844 TyAdt(adt, substs) => {
1846 let adt_tys = adt.sized_constraint(tcx);
1847 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
1850 .map(|ty| ty.subst(tcx, substs))
1851 .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
1855 TyProjection(..) | TyAnon(..) => {
1856 // must calculate explicitly.
1857 // FIXME: consider special-casing always-Sized projections
1862 // perf hack: if there is a `T: Sized` bound, then
1863 // we know that `T` is Sized and do not need to check
1866 let sized_trait = match tcx.lang_items().sized_trait() {
1868 _ => return vec![ty]
1870 let sized_predicate = Binder(TraitRef {
1871 def_id: sized_trait,
1872 substs: tcx.mk_substs_trait(ty, &[])
1874 let predicates = tcx.predicates_of(self.did).predicates;
1875 if predicates.into_iter().any(|p| p == sized_predicate) {
1883 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
1887 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
1892 impl<'a, 'gcx, 'tcx> VariantDef {
1894 pub fn find_field_named(&self, name: ast::Name) -> Option<&FieldDef> {
1895 self.index_of_field_named(name).map(|index| &self.fields[index])
1898 pub fn index_of_field_named(&self, name: ast::Name) -> Option<usize> {
1899 if let Some(index) = self.fields.iter().position(|f| f.name == name) {
1902 let mut ident = name.to_ident();
1903 while ident.ctxt != SyntaxContext::empty() {
1904 ident.ctxt.remove_mark();
1905 if let Some(field) = self.fields.iter().position(|f| f.name.to_ident() == ident) {
1913 pub fn field_named(&self, name: ast::Name) -> &FieldDef {
1914 self.find_field_named(name).unwrap()
1918 impl<'a, 'gcx, 'tcx> FieldDef {
1919 pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1920 tcx.type_of(self.did).subst(tcx, subst)
1924 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1925 pub enum ClosureKind {
1926 // Warning: Ordering is significant here! The ordering is chosen
1927 // because the trait Fn is a subtrait of FnMut and so in turn, and
1928 // hence we order it so that Fn < FnMut < FnOnce.
1934 impl<'a, 'tcx> ClosureKind {
1935 // This is the initial value used when doing upvar inference.
1936 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
1938 pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
1940 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
1941 ClosureKind::FnMut => {
1942 tcx.require_lang_item(FnMutTraitLangItem)
1944 ClosureKind::FnOnce => {
1945 tcx.require_lang_item(FnOnceTraitLangItem)
1950 /// True if this a type that impls this closure kind
1951 /// must also implement `other`.
1952 pub fn extends(self, other: ty::ClosureKind) -> bool {
1953 match (self, other) {
1954 (ClosureKind::Fn, ClosureKind::Fn) => true,
1955 (ClosureKind::Fn, ClosureKind::FnMut) => true,
1956 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
1957 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
1958 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
1959 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
1964 /// Returns the representative scalar type for this closure kind.
1965 /// See `TyS::to_opt_closure_kind` for more details.
1966 pub fn to_ty(self, tcx: TyCtxt<'_, '_, 'tcx>) -> Ty<'tcx> {
1968 ty::ClosureKind::Fn => tcx.types.i8,
1969 ty::ClosureKind::FnMut => tcx.types.i16,
1970 ty::ClosureKind::FnOnce => tcx.types.i32,
1975 impl<'tcx> TyS<'tcx> {
1976 /// Iterator that walks `self` and any types reachable from
1977 /// `self`, in depth-first order. Note that just walks the types
1978 /// that appear in `self`, it does not descend into the fields of
1979 /// structs or variants. For example:
1982 /// isize => { isize }
1983 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
1984 /// [isize] => { [isize], isize }
1986 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
1987 TypeWalker::new(self)
1990 /// Iterator that walks the immediate children of `self`. Hence
1991 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
1992 /// (but not `i32`, like `walk`).
1993 pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
1994 walk::walk_shallow(self)
1997 /// Walks `ty` and any types appearing within `ty`, invoking the
1998 /// callback `f` on each type. If the callback returns false, then the
1999 /// children of the current type are ignored.
2001 /// Note: prefer `ty.walk()` where possible.
2002 pub fn maybe_walk<F>(&'tcx self, mut f: F)
2003 where F : FnMut(Ty<'tcx>) -> bool
2005 let mut walker = self.walk();
2006 while let Some(ty) = walker.next() {
2008 walker.skip_current_subtree();
2014 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
2015 pub enum LvaluePreference {
2020 impl LvaluePreference {
2021 pub fn from_mutbl(m: hir::Mutability) -> Self {
2023 hir::MutMutable => PreferMutLvalue,
2024 hir::MutImmutable => NoPreference,
2030 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2032 hir::MutMutable => MutBorrow,
2033 hir::MutImmutable => ImmBorrow,
2037 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2038 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2039 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2041 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2043 MutBorrow => hir::MutMutable,
2044 ImmBorrow => hir::MutImmutable,
2046 // We have no type corresponding to a unique imm borrow, so
2047 // use `&mut`. It gives all the capabilities of an `&uniq`
2048 // and hence is a safe "over approximation".
2049 UniqueImmBorrow => hir::MutMutable,
2053 pub fn to_user_str(&self) -> &'static str {
2055 MutBorrow => "mutable",
2056 ImmBorrow => "immutable",
2057 UniqueImmBorrow => "uniquely immutable",
2062 #[derive(Debug, Clone)]
2063 pub enum Attributes<'gcx> {
2064 Owned(Rc<[ast::Attribute]>),
2065 Borrowed(&'gcx [ast::Attribute])
2068 impl<'gcx> ::std::ops::Deref for Attributes<'gcx> {
2069 type Target = [ast::Attribute];
2071 fn deref(&self) -> &[ast::Attribute] {
2073 &Attributes::Owned(ref data) => &data,
2074 &Attributes::Borrowed(data) => data
2079 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2080 pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
2081 self.typeck_tables_of(self.hir.body_owner_def_id(body))
2084 /// Returns an iterator of the def-ids for all body-owners in this
2085 /// crate. If you would prefer to iterate over the bodies
2086 /// themselves, you can do `self.hir.krate().body_ids.iter()`.
2087 pub fn body_owners(self) -> impl Iterator<Item = DefId> + 'a {
2091 .map(move |&body_id| self.hir.body_owner_def_id(body_id))
2094 pub fn expr_span(self, id: NodeId) -> Span {
2095 match self.hir.find(id) {
2096 Some(hir_map::NodeExpr(e)) => {
2100 bug!("Node id {} is not an expr: {:?}", id, f);
2103 bug!("Node id {} is not present in the node map", id);
2108 pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
2110 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
2112 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
2117 hir::ExprType(ref e, _) => {
2118 self.expr_is_lval(e)
2121 hir::ExprUnary(hir::UnDeref, _) |
2122 hir::ExprField(..) |
2123 hir::ExprTupField(..) |
2124 hir::ExprIndex(..) => {
2128 // Partially qualified paths in expressions can only legally
2129 // refer to associated items which are always rvalues.
2130 hir::ExprPath(hir::QPath::TypeRelative(..)) |
2133 hir::ExprMethodCall(..) |
2134 hir::ExprStruct(..) |
2137 hir::ExprMatch(..) |
2138 hir::ExprClosure(..) |
2139 hir::ExprBlock(..) |
2140 hir::ExprRepeat(..) |
2141 hir::ExprArray(..) |
2142 hir::ExprBreak(..) |
2143 hir::ExprAgain(..) |
2145 hir::ExprWhile(..) |
2147 hir::ExprAssign(..) |
2148 hir::ExprInlineAsm(..) |
2149 hir::ExprAssignOp(..) |
2151 hir::ExprUnary(..) |
2153 hir::ExprAddrOf(..) |
2154 hir::ExprBinary(..) |
2155 hir::ExprYield(..) |
2156 hir::ExprCast(..) => {
2162 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2163 self.associated_items(id)
2164 .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2168 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2169 self.associated_items(did).any(|item| {
2170 item.relevant_for_never()
2174 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssociatedItem> {
2175 let is_associated_item = if let Some(node_id) = self.hir.as_local_node_id(def_id) {
2176 match self.hir.get(node_id) {
2177 hir_map::NodeTraitItem(_) | hir_map::NodeImplItem(_) => true,
2181 match self.describe_def(def_id).expect("no def for def-id") {
2182 Def::AssociatedConst(_) | Def::Method(_) | Def::AssociatedTy(_) => true,
2187 if is_associated_item {
2188 Some(self.associated_item(def_id))
2194 fn associated_item_from_trait_item_ref(self,
2195 parent_def_id: DefId,
2196 parent_vis: &hir::Visibility,
2197 trait_item_ref: &hir::TraitItemRef)
2199 let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2200 let (kind, has_self) = match trait_item_ref.kind {
2201 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2202 hir::AssociatedItemKind::Method { has_self } => {
2203 (ty::AssociatedKind::Method, has_self)
2205 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2209 name: trait_item_ref.name,
2211 // Visibility of trait items is inherited from their traits.
2212 vis: Visibility::from_hir(parent_vis, trait_item_ref.id.node_id, self),
2213 defaultness: trait_item_ref.defaultness,
2215 container: TraitContainer(parent_def_id),
2216 method_has_self_argument: has_self
2220 fn associated_item_from_impl_item_ref(self,
2221 parent_def_id: DefId,
2222 impl_item_ref: &hir::ImplItemRef)
2224 let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2225 let (kind, has_self) = match impl_item_ref.kind {
2226 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2227 hir::AssociatedItemKind::Method { has_self } => {
2228 (ty::AssociatedKind::Method, has_self)
2230 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2233 ty::AssociatedItem {
2234 name: impl_item_ref.name,
2236 // Visibility of trait impl items doesn't matter.
2237 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.node_id, self),
2238 defaultness: impl_item_ref.defaultness,
2240 container: ImplContainer(parent_def_id),
2241 method_has_self_argument: has_self
2245 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2246 pub fn associated_items(self, def_id: DefId)
2247 -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2248 let def_ids = self.associated_item_def_ids(def_id);
2249 (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2252 /// Returns true if the impls are the same polarity and are implementing
2253 /// a trait which contains no items
2254 pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId) -> bool {
2255 if !self.sess.features.borrow().overlapping_marker_traits {
2258 let trait1_is_empty = self.impl_trait_ref(def_id1)
2259 .map_or(false, |trait_ref| {
2260 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2262 let trait2_is_empty = self.impl_trait_ref(def_id2)
2263 .map_or(false, |trait_ref| {
2264 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2266 self.impl_polarity(def_id1) == self.impl_polarity(def_id2)
2271 // Returns `ty::VariantDef` if `def` refers to a struct,
2272 // or variant or their constructors, panics otherwise.
2273 pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2275 Def::Variant(did) | Def::VariantCtor(did, ..) => {
2276 let enum_did = self.parent_def_id(did).unwrap();
2277 self.adt_def(enum_did).variant_with_id(did)
2279 Def::Struct(did) | Def::Union(did) => {
2280 self.adt_def(did).struct_variant()
2282 Def::StructCtor(ctor_did, ..) => {
2283 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2284 self.adt_def(did).struct_variant()
2286 _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2290 /// Given a `VariantDef`, returns the def-id of the `AdtDef` of which it is a part.
2291 pub fn adt_def_id_of_variant(self, variant_def: &'tcx VariantDef) -> DefId {
2292 let def_key = self.def_key(variant_def.did);
2293 match def_key.disambiguated_data.data {
2294 // for enum variants and tuple structs, the def-id of the ADT itself
2295 // is the *parent* of the variant
2296 DefPathData::EnumVariant(..) | DefPathData::StructCtor =>
2297 DefId { krate: variant_def.did.krate, index: def_key.parent.unwrap() },
2299 // otherwise, for structs and unions, they share a def-id
2300 _ => variant_def.did,
2304 pub fn item_name(self, id: DefId) -> InternedString {
2305 if let Some(id) = self.hir.as_local_node_id(id) {
2306 self.hir.name(id).as_str()
2307 } else if id.index == CRATE_DEF_INDEX {
2308 self.original_crate_name(id.krate).as_str()
2310 let def_key = self.def_key(id);
2311 // The name of a StructCtor is that of its struct parent.
2312 if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2313 self.item_name(DefId {
2315 index: def_key.parent.unwrap()
2318 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2319 bug!("item_name: no name for {:?}", self.def_path(id));
2325 /// Return the possibly-auto-generated MIR of a (DefId, Subst) pair.
2326 pub fn instance_mir(self, instance: ty::InstanceDef<'gcx>)
2330 ty::InstanceDef::Item(did) => {
2331 self.optimized_mir(did)
2333 ty::InstanceDef::Intrinsic(..) |
2334 ty::InstanceDef::FnPtrShim(..) |
2335 ty::InstanceDef::Virtual(..) |
2336 ty::InstanceDef::ClosureOnceShim { .. } |
2337 ty::InstanceDef::DropGlue(..) |
2338 ty::InstanceDef::CloneShim(..) => {
2339 self.mir_shims(instance)
2344 /// Given the DefId of an item, returns its MIR, borrowed immutably.
2345 /// Returns None if there is no MIR for the DefId
2346 pub fn maybe_optimized_mir(self, did: DefId) -> Option<&'gcx Mir<'gcx>> {
2347 if self.is_mir_available(did) {
2348 Some(self.optimized_mir(did))
2354 /// Get the attributes of a definition.
2355 pub fn get_attrs(self, did: DefId) -> Attributes<'gcx> {
2356 if let Some(id) = self.hir.as_local_node_id(did) {
2357 Attributes::Borrowed(self.hir.attrs(id))
2359 Attributes::Owned(self.item_attrs(did))
2363 /// Determine whether an item is annotated with an attribute
2364 pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2365 self.get_attrs(did).iter().any(|item| item.check_name(attr))
2368 /// Returns true if this is an `auto trait`.
2370 /// NB. For a limited time, also returns true if `impl Trait for .. { }` is in the code-base.
2371 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2372 self.trait_def(trait_def_id).has_auto_impl
2375 pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
2376 self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
2379 /// Given the def_id of an impl, return the def_id of the trait it implements.
2380 /// If it implements no trait, return `None`.
2381 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2382 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2385 /// If the given def ID describes a method belonging to an impl, return the
2386 /// ID of the impl that the method belongs to. Otherwise, return `None`.
2387 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2388 let item = if def_id.krate != LOCAL_CRATE {
2389 if let Some(Def::Method(_)) = self.describe_def(def_id) {
2390 Some(self.associated_item(def_id))
2395 self.opt_associated_item(def_id)
2399 Some(trait_item) => {
2400 match trait_item.container {
2401 TraitContainer(_) => None,
2402 ImplContainer(def_id) => Some(def_id),
2409 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2410 /// with the name of the crate containing the impl.
2411 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2412 if impl_did.is_local() {
2413 let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2414 Ok(self.hir.span(node_id))
2416 Err(self.crate_name(impl_did.krate))
2420 // Hygienically compare a use-site name (`use_name`) for a field or an associated item with its
2421 // supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2422 // definition's parent/scope to perform comparison.
2423 pub fn hygienic_eq(self, use_name: Name, def_name: Name, def_parent_def_id: DefId) -> bool {
2424 self.adjust(use_name, def_parent_def_id, DUMMY_NODE_ID).0 == def_name.to_ident()
2427 pub fn adjust(self, name: Name, scope: DefId, block: NodeId) -> (Ident, DefId) {
2428 self.adjust_ident(name.to_ident(), scope, block)
2431 pub fn adjust_ident(self, mut ident: Ident, scope: DefId, block: NodeId) -> (Ident, DefId) {
2432 let expansion = match scope.krate {
2433 LOCAL_CRATE => self.hir.definitions().expansion(scope.index),
2436 let scope = match ident.ctxt.adjust(expansion) {
2437 Some(macro_def) => self.hir.definitions().macro_def_scope(macro_def),
2438 None if block == DUMMY_NODE_ID => DefId::local(CRATE_DEF_INDEX), // Dummy DefId
2439 None => self.hir.get_module_parent(block),
2445 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2446 pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2447 F: FnOnce(&[hir::Freevar]) -> T,
2449 let def_id = self.hir.local_def_id(fid);
2450 match self.freevars(def_id) {
2457 fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
2460 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2461 let parent_id = tcx.hir.get_parent(id);
2462 let parent_def_id = tcx.hir.local_def_id(parent_id);
2463 let parent_item = tcx.hir.expect_item(parent_id);
2464 match parent_item.node {
2465 hir::ItemImpl(.., ref impl_item_refs) => {
2466 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.node_id == id) {
2467 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
2469 debug_assert_eq!(assoc_item.def_id, def_id);
2474 hir::ItemTrait(.., ref trait_item_refs) => {
2475 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.node_id == id) {
2476 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
2479 debug_assert_eq!(assoc_item.def_id, def_id);
2487 span_bug!(parent_item.span,
2488 "unexpected parent of trait or impl item or item not found: {:?}",
2492 /// Calculates the Sized-constraint.
2494 /// In fact, there are only a few options for the types in the constraint:
2495 /// - an obviously-unsized type
2496 /// - a type parameter or projection whose Sizedness can't be known
2497 /// - a tuple of type parameters or projections, if there are multiple
2499 /// - a TyError, if a type contained itself. The representability
2500 /// check should catch this case.
2501 fn adt_sized_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2503 -> &'tcx [Ty<'tcx>] {
2504 let def = tcx.adt_def(def_id);
2506 let result = tcx.intern_type_list(&def.variants.iter().flat_map(|v| {
2509 def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
2510 }).collect::<Vec<_>>());
2512 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
2517 /// Calculates the dtorck constraint for a type.
2518 fn adt_dtorck_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2520 -> DtorckConstraint<'tcx> {
2521 let def = tcx.adt_def(def_id);
2522 let span = tcx.def_span(def_id);
2523 debug!("dtorck_constraint: {:?}", def);
2525 if def.is_phantom_data() {
2526 let result = DtorckConstraint {
2529 tcx.mk_param_from_def(&tcx.generics_of(def_id).types[0])
2532 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2536 let mut result = def.all_fields()
2537 .map(|field| tcx.type_of(field.did))
2538 .map(|fty| tcx.dtorck_constraint_for_ty(span, fty, 0, fty))
2539 .collect::<Result<DtorckConstraint, ErrorReported>>()
2540 .unwrap_or(DtorckConstraint::empty());
2541 result.outlives.extend(tcx.destructor_constraints(def));
2544 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2549 fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2552 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2553 let item = tcx.hir.expect_item(id);
2554 let vec: Vec<_> = match item.node {
2555 hir::ItemTrait(.., ref trait_item_refs) => {
2556 trait_item_refs.iter()
2557 .map(|trait_item_ref| trait_item_ref.id)
2558 .map(|id| tcx.hir.local_def_id(id.node_id))
2561 hir::ItemImpl(.., ref impl_item_refs) => {
2562 impl_item_refs.iter()
2563 .map(|impl_item_ref| impl_item_ref.id)
2564 .map(|id| tcx.hir.local_def_id(id.node_id))
2567 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2572 fn def_span<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Span {
2573 tcx.hir.span_if_local(def_id).unwrap()
2576 /// If the given def ID describes an item belonging to a trait,
2577 /// return the ID of the trait that the trait item belongs to.
2578 /// Otherwise, return `None`.
2579 fn trait_of_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
2580 tcx.opt_associated_item(def_id)
2581 .and_then(|associated_item| {
2582 match associated_item.container {
2583 TraitContainer(def_id) => Some(def_id),
2584 ImplContainer(_) => None
2589 /// See `ParamEnv` struct def'n for details.
2590 fn param_env<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2593 // Compute the bounds on Self and the type parameters.
2595 let bounds = tcx.predicates_of(def_id).instantiate_identity(tcx);
2596 let predicates = bounds.predicates;
2598 // Finally, we have to normalize the bounds in the environment, in
2599 // case they contain any associated type projections. This process
2600 // can yield errors if the put in illegal associated types, like
2601 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2602 // report these errors right here; this doesn't actually feel
2603 // right to me, because constructing the environment feels like a
2604 // kind of a "idempotent" action, but I'm not sure where would be
2605 // a better place. In practice, we construct environments for
2606 // every fn once during type checking, and we'll abort if there
2607 // are any errors at that point, so after type checking you can be
2608 // sure that this will succeed without errors anyway.
2610 let unnormalized_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
2611 traits::Reveal::UserFacing);
2613 let body_id = tcx.hir.as_local_node_id(def_id).map_or(DUMMY_NODE_ID, |id| {
2614 tcx.hir.maybe_body_owned_by(id).map_or(id, |body| body.node_id)
2616 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
2617 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
2620 fn crate_disambiguator<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2621 crate_num: CrateNum) -> CrateDisambiguator {
2622 assert_eq!(crate_num, LOCAL_CRATE);
2623 tcx.sess.local_crate_disambiguator()
2626 fn original_crate_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2627 crate_num: CrateNum) -> Symbol {
2628 assert_eq!(crate_num, LOCAL_CRATE);
2629 tcx.crate_name.clone()
2632 pub fn provide(providers: &mut ty::maps::Providers) {
2633 context::provide(providers);
2634 erase_regions::provide(providers);
2635 layout::provide(providers);
2636 util::provide(providers);
2637 *providers = ty::maps::Providers {
2639 associated_item_def_ids,
2640 adt_sized_constraint,
2641 adt_dtorck_constraint,
2645 crate_disambiguator,
2646 original_crate_name,
2647 trait_impls_of: trait_def::trait_impls_of_provider,
2652 /// A map for the local crate mapping each type to a vector of its
2653 /// inherent impls. This is not meant to be used outside of coherence;
2654 /// rather, you should request the vector for a specific type via
2655 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2656 /// (constructing this map requires touching the entire crate).
2657 #[derive(Clone, Debug)]
2658 pub struct CrateInherentImpls {
2659 pub inherent_impls: DefIdMap<Rc<Vec<DefId>>>,
2662 /// A set of constraints that need to be satisfied in order for
2663 /// a type to be valid for destruction.
2664 #[derive(Clone, Debug)]
2665 pub struct DtorckConstraint<'tcx> {
2666 /// Types that are required to be alive in order for this
2667 /// type to be valid for destruction.
2668 pub outlives: Vec<ty::subst::Kind<'tcx>>,
2669 /// Types that could not be resolved: projections and params.
2670 pub dtorck_types: Vec<Ty<'tcx>>,
2673 impl<'tcx> FromIterator<DtorckConstraint<'tcx>> for DtorckConstraint<'tcx>
2675 fn from_iter<I: IntoIterator<Item=DtorckConstraint<'tcx>>>(iter: I) -> Self {
2676 let mut result = Self::empty();
2678 for constraint in iter {
2679 result.outlives.extend(constraint.outlives);
2680 result.dtorck_types.extend(constraint.dtorck_types);
2688 impl<'tcx> DtorckConstraint<'tcx> {
2689 fn empty() -> DtorckConstraint<'tcx> {
2692 dtorck_types: vec![]
2696 fn dedup<'a>(&mut self) {
2697 let mut outlives = FxHashSet();
2698 let mut dtorck_types = FxHashSet();
2700 self.outlives.retain(|&val| outlives.replace(val).is_none());
2701 self.dtorck_types.retain(|&val| dtorck_types.replace(val).is_none());
2705 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
2706 pub struct SymbolName {
2707 // FIXME: we don't rely on interning or equality here - better have
2708 // this be a `&'tcx str`.
2709 pub name: InternedString
2712 impl_stable_hash_for!(struct self::SymbolName {
2716 impl Deref for SymbolName {
2719 fn deref(&self) -> &str { &self.name }
2722 impl fmt::Display for SymbolName {
2723 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2724 fmt::Display::fmt(&self.name, fmt)