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 dep_graph::{self, DepNode};
19 use hir::{map as hir_map, FreevarMap, TraitMap};
20 use hir::def::{Def, CtorKind, ExportMap};
21 use hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
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::region::CodeExtent;
27 use middle::resolve_lifetime::ObjectLifetimeDefault;
31 use ty::subst::{Subst, Substs};
32 use ty::util::IntTypeExt;
33 use ty::walk::TypeWalker;
34 use util::common::ErrorReported;
35 use util::nodemap::{NodeSet, DefIdMap, FxHashMap, FxHashSet};
37 use serialize::{self, Encodable, Encoder};
38 use std::cell::{Cell, RefCell};
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, NodeId};
51 use syntax::symbol::{Symbol, InternedString};
52 use syntax_pos::{DUMMY_SP, Span};
53 use rustc_const_math::ConstInt;
55 use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
56 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
58 use rustc_data_structures::transitive_relation::TransitiveRelation;
61 use hir::itemlikevisit::ItemLikeVisitor;
63 pub use self::sty::{Binder, DebruijnIndex};
64 pub use self::sty::{FnSig, PolyFnSig};
65 pub use self::sty::{InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
66 pub use self::sty::{ClosureSubsts, TypeAndMut};
67 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
68 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
69 pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
70 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
71 pub use self::sty::RegionKind;
72 pub use self::sty::Issue32330;
73 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid, SkolemizedRegionVid};
74 pub use self::sty::BoundRegion::*;
75 pub use self::sty::InferTy::*;
76 pub use self::sty::RegionKind::*;
77 pub use self::sty::TypeVariants::*;
79 pub use self::context::{TyCtxt, GlobalArenas, tls};
80 pub use self::context::{Lift, TypeckTables};
82 pub use self::instance::{Instance, InstanceDef};
84 pub use self::trait_def::{TraitDef, TraitFlags};
86 pub use self::maps::queries;
93 pub mod inhabitedness;
110 mod structural_impls;
115 /// The complete set of all analyses described in this module. This is
116 /// produced by the driver and fed to trans and later passes.
118 /// NB: These contents are being migrated into queries using the
119 /// *on-demand* infrastructure.
121 pub struct CrateAnalysis {
122 pub access_levels: Rc<AccessLevels>,
123 pub reachable: Rc<NodeSet>,
125 pub glob_map: Option<hir::GlobMap>,
129 pub struct Resolutions {
130 pub freevars: FreevarMap,
131 pub trait_map: TraitMap,
132 pub maybe_unused_trait_imports: NodeSet,
133 pub export_map: ExportMap,
136 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
137 pub enum AssociatedItemContainer {
138 TraitContainer(DefId),
139 ImplContainer(DefId),
142 impl AssociatedItemContainer {
143 pub fn id(&self) -> DefId {
145 TraitContainer(id) => id,
146 ImplContainer(id) => id,
151 /// The "header" of an impl is everything outside the body: a Self type, a trait
152 /// ref (in the case of a trait impl), and a set of predicates (from the
153 /// bounds/where clauses).
154 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
155 pub struct ImplHeader<'tcx> {
156 pub impl_def_id: DefId,
157 pub self_ty: Ty<'tcx>,
158 pub trait_ref: Option<TraitRef<'tcx>>,
159 pub predicates: Vec<Predicate<'tcx>>,
162 impl<'a, 'gcx, 'tcx> ImplHeader<'tcx> {
163 pub fn with_fresh_ty_vars(selcx: &mut traits::SelectionContext<'a, 'gcx, 'tcx>,
167 let tcx = selcx.tcx();
168 let impl_substs = selcx.infcx().fresh_substs_for_item(DUMMY_SP, impl_def_id);
170 let header = ImplHeader {
171 impl_def_id: impl_def_id,
172 self_ty: tcx.type_of(impl_def_id),
173 trait_ref: tcx.impl_trait_ref(impl_def_id),
174 predicates: tcx.predicates_of(impl_def_id).predicates
175 }.subst(tcx, impl_substs);
177 let traits::Normalized { value: mut header, obligations } =
178 traits::normalize(selcx, traits::ObligationCause::dummy(), &header);
180 header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
185 #[derive(Copy, Clone, Debug)]
186 pub struct AssociatedItem {
189 pub kind: AssociatedKind,
191 pub defaultness: hir::Defaultness,
192 pub container: AssociatedItemContainer,
194 /// Whether this is a method with an explicit self
195 /// as its first argument, allowing method calls.
196 pub method_has_self_argument: bool,
199 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
200 pub enum AssociatedKind {
206 impl AssociatedItem {
207 pub fn def(&self) -> Def {
209 AssociatedKind::Const => Def::AssociatedConst(self.def_id),
210 AssociatedKind::Method => Def::Method(self.def_id),
211 AssociatedKind::Type => Def::AssociatedTy(self.def_id),
215 /// Tests whether the associated item admits a non-trivial implementation
217 pub fn relevant_for_never<'tcx>(&self) -> bool {
219 AssociatedKind::Const => true,
220 AssociatedKind::Type => true,
221 // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
222 AssociatedKind::Method => !self.method_has_self_argument,
227 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
228 pub enum Visibility {
229 /// Visible everywhere (including in other crates).
231 /// Visible only in the given crate-local module.
233 /// Not visible anywhere in the local crate. This is the visibility of private external items.
237 pub trait DefIdTree: Copy {
238 fn parent(self, id: DefId) -> Option<DefId>;
240 fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
241 if descendant.krate != ancestor.krate {
245 while descendant != ancestor {
246 match self.parent(descendant) {
247 Some(parent) => descendant = parent,
248 None => return false,
255 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
256 fn parent(self, id: DefId) -> Option<DefId> {
257 self.def_key(id).parent.map(|index| DefId { index: index, ..id })
262 pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
264 hir::Public => Visibility::Public,
265 hir::Visibility::Crate => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
266 hir::Visibility::Restricted { ref path, .. } => match path.def {
267 // If there is no resolution, `resolve` will have already reported an error, so
268 // assume that the visibility is public to avoid reporting more privacy errors.
269 Def::Err => Visibility::Public,
270 def => Visibility::Restricted(def.def_id()),
273 Visibility::Restricted(tcx.hir.local_def_id(tcx.hir.get_module_parent(id)))
278 /// Returns true if an item with this visibility is accessible from the given block.
279 pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
280 let restriction = match self {
281 // Public items are visible everywhere.
282 Visibility::Public => return true,
283 // Private items from other crates are visible nowhere.
284 Visibility::Invisible => return false,
285 // Restricted items are visible in an arbitrary local module.
286 Visibility::Restricted(other) if other.krate != module.krate => return false,
287 Visibility::Restricted(module) => module,
290 tree.is_descendant_of(module, restriction)
293 /// Returns true if this visibility is at least as accessible as the given visibility
294 pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
295 let vis_restriction = match vis {
296 Visibility::Public => return self == Visibility::Public,
297 Visibility::Invisible => return true,
298 Visibility::Restricted(module) => module,
301 self.is_accessible_from(vis_restriction, tree)
305 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
307 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
308 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
309 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
310 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
313 /// The crate variances map is computed during typeck and contains the
314 /// variance of every item in the local crate. You should not use it
315 /// directly, because to do so will make your pass dependent on the
316 /// HIR of every item in the local crate. Instead, use
317 /// `tcx.item_variances()` to get the variance for a *particular*
319 pub struct CrateVariancesMap {
320 /// This relation tracks the dependencies between the variance of
321 /// various items. In particular, if `a < b`, then the variance of
322 /// `a` depends on the sources of `b`.
323 pub dependencies: TransitiveRelation<DefId>,
325 /// For each item with generics, maps to a vector of the variance
326 /// of its generics. If an item has no generics, it will have no
328 pub variances: FxHashMap<DefId, Rc<Vec<ty::Variance>>>,
330 /// An empty vector, useful for cloning.
331 pub empty_variance: Rc<Vec<ty::Variance>>,
334 #[derive(Clone, Copy, Debug, RustcDecodable, RustcEncodable)]
335 pub struct MethodCallee<'tcx> {
336 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
339 pub substs: &'tcx Substs<'tcx>
342 /// With method calls, we store some extra information in
343 /// side tables (i.e method_map). We use
344 /// MethodCall as a key to index into these tables instead of
345 /// just directly using the expression's NodeId. The reason
346 /// for this being that we may apply adjustments (coercions)
347 /// with the resulting expression also needing to use the
348 /// side tables. The problem with this is that we don't
349 /// assign a separate NodeId to this new expression
350 /// and so it would clash with the base expression if both
351 /// needed to add to the side tables. Thus to disambiguate
352 /// we also keep track of whether there's an adjustment in
354 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
355 pub struct MethodCall {
361 pub fn expr(id: NodeId) -> MethodCall {
368 pub fn autoderef(expr_id: NodeId, autoderef: u32) -> MethodCall {
371 autoderef: 1 + autoderef
376 // maps from an expression id that corresponds to a method call to the details
377 // of the method to be invoked
378 pub type MethodMap<'tcx> = FxHashMap<MethodCall, MethodCallee<'tcx>>;
380 // Contains information needed to resolve types and (in the future) look up
381 // the types of AST nodes.
382 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
383 pub struct CReaderCacheKey {
388 /// Describes the fragment-state associated with a NodeId.
390 /// Currently only unfragmented paths have entries in the table,
391 /// but longer-term this enum is expected to expand to also
392 /// include data for fragmented paths.
393 #[derive(Copy, Clone, Debug)]
394 pub enum FragmentInfo {
395 Moved { var: NodeId, move_expr: NodeId },
396 Assigned { var: NodeId, assign_expr: NodeId, assignee_id: NodeId },
399 // Flags that we track on types. These flags are propagated upwards
400 // through the type during type construction, so that we can quickly
401 // check whether the type has various kinds of types in it without
402 // recursing over the type itself.
404 flags TypeFlags: u32 {
405 const HAS_PARAMS = 1 << 0,
406 const HAS_SELF = 1 << 1,
407 const HAS_TY_INFER = 1 << 2,
408 const HAS_RE_INFER = 1 << 3,
409 const HAS_RE_SKOL = 1 << 4,
410 const HAS_RE_EARLY_BOUND = 1 << 5,
411 const HAS_FREE_REGIONS = 1 << 6,
412 const HAS_TY_ERR = 1 << 7,
413 const HAS_PROJECTION = 1 << 8,
414 const HAS_TY_CLOSURE = 1 << 9,
416 // true if there are "names" of types and regions and so forth
417 // that are local to a particular fn
418 const HAS_LOCAL_NAMES = 1 << 10,
420 // Present if the type belongs in a local type context.
421 // Only set for TyInfer other than Fresh.
422 const KEEP_IN_LOCAL_TCX = 1 << 11,
424 // Is there a projection that does not involve a bound region?
425 // Currently we can't normalize projections w/ bound regions.
426 const HAS_NORMALIZABLE_PROJECTION = 1 << 12,
428 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
429 TypeFlags::HAS_SELF.bits |
430 TypeFlags::HAS_RE_EARLY_BOUND.bits,
432 // Flags representing the nominal content of a type,
433 // computed by FlagsComputation. If you add a new nominal
434 // flag, it should be added here too.
435 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
436 TypeFlags::HAS_SELF.bits |
437 TypeFlags::HAS_TY_INFER.bits |
438 TypeFlags::HAS_RE_INFER.bits |
439 TypeFlags::HAS_RE_SKOL.bits |
440 TypeFlags::HAS_RE_EARLY_BOUND.bits |
441 TypeFlags::HAS_FREE_REGIONS.bits |
442 TypeFlags::HAS_TY_ERR.bits |
443 TypeFlags::HAS_PROJECTION.bits |
444 TypeFlags::HAS_TY_CLOSURE.bits |
445 TypeFlags::HAS_LOCAL_NAMES.bits |
446 TypeFlags::KEEP_IN_LOCAL_TCX.bits,
448 // Caches for type_is_sized, type_moves_by_default
449 const SIZEDNESS_CACHED = 1 << 16,
450 const IS_SIZED = 1 << 17,
451 const MOVENESS_CACHED = 1 << 18,
452 const MOVES_BY_DEFAULT = 1 << 19,
453 const FREEZENESS_CACHED = 1 << 20,
454 const IS_FREEZE = 1 << 21,
455 const NEEDS_DROP_CACHED = 1 << 22,
456 const NEEDS_DROP = 1 << 23,
460 pub struct TyS<'tcx> {
461 pub sty: TypeVariants<'tcx>,
462 pub flags: Cell<TypeFlags>,
464 // the maximal depth of any bound regions appearing in this type.
468 impl<'tcx> PartialEq for TyS<'tcx> {
470 fn eq(&self, other: &TyS<'tcx>) -> bool {
471 // (self as *const _) == (other as *const _)
472 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
475 impl<'tcx> Eq for TyS<'tcx> {}
477 impl<'tcx> Hash for TyS<'tcx> {
478 fn hash<H: Hasher>(&self, s: &mut H) {
479 (self as *const TyS).hash(s)
483 impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::TyS<'tcx> {
484 fn hash_stable<W: StableHasherResult>(&self,
485 hcx: &mut StableHashingContext<'a, 'tcx>,
486 hasher: &mut StableHasher<W>) {
490 // The other fields just provide fast access to information that is
491 // also contained in `sty`, so no need to hash them.
496 sty.hash_stable(hcx, hasher);
500 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
502 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
503 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
505 /// A wrapper for slices with the additional invariant
506 /// that the slice is interned and no other slice with
507 /// the same contents can exist in the same context.
508 /// This means we can use pointer + length for both
509 /// equality comparisons and hashing.
510 #[derive(Debug, RustcEncodable)]
511 pub struct Slice<T>([T]);
513 impl<T> PartialEq for Slice<T> {
515 fn eq(&self, other: &Slice<T>) -> bool {
516 (&self.0 as *const [T]) == (&other.0 as *const [T])
519 impl<T> Eq for Slice<T> {}
521 impl<T> Hash for Slice<T> {
522 fn hash<H: Hasher>(&self, s: &mut H) {
523 (self.as_ptr(), self.len()).hash(s)
527 impl<T> Deref for Slice<T> {
529 fn deref(&self) -> &[T] {
534 impl<'a, T> IntoIterator for &'a Slice<T> {
536 type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
537 fn into_iter(self) -> Self::IntoIter {
542 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
545 pub fn empty<'a>() -> &'a Slice<T> {
547 mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
552 /// Upvars do not get their own node-id. Instead, we use the pair of
553 /// the original var id (that is, the root variable that is referenced
554 /// by the upvar) and the id of the closure expression.
555 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
558 pub closure_expr_id: NodeId,
561 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
562 pub enum BorrowKind {
563 /// Data must be immutable and is aliasable.
566 /// Data must be immutable but not aliasable. This kind of borrow
567 /// cannot currently be expressed by the user and is used only in
568 /// implicit closure bindings. It is needed when the closure
569 /// is borrowing or mutating a mutable referent, e.g.:
571 /// let x: &mut isize = ...;
572 /// let y = || *x += 5;
574 /// If we were to try to translate this closure into a more explicit
575 /// form, we'd encounter an error with the code as written:
577 /// struct Env { x: & &mut isize }
578 /// let x: &mut isize = ...;
579 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
580 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
582 /// This is then illegal because you cannot mutate a `&mut` found
583 /// in an aliasable location. To solve, you'd have to translate with
584 /// an `&mut` borrow:
586 /// struct Env { x: & &mut isize }
587 /// let x: &mut isize = ...;
588 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
589 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
591 /// Now the assignment to `**env.x` is legal, but creating a
592 /// mutable pointer to `x` is not because `x` is not mutable. We
593 /// could fix this by declaring `x` as `let mut x`. This is ok in
594 /// user code, if awkward, but extra weird for closures, since the
595 /// borrow is hidden.
597 /// So we introduce a "unique imm" borrow -- the referent is
598 /// immutable, but not aliasable. This solves the problem. For
599 /// simplicity, we don't give users the way to express this
600 /// borrow, it's just used when translating closures.
603 /// Data is mutable and not aliasable.
607 /// Information describing the capture of an upvar. This is computed
608 /// during `typeck`, specifically by `regionck`.
609 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
610 pub enum UpvarCapture<'tcx> {
611 /// Upvar is captured by value. This is always true when the
612 /// closure is labeled `move`, but can also be true in other cases
613 /// depending on inference.
616 /// Upvar is captured by reference.
617 ByRef(UpvarBorrow<'tcx>),
620 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
621 pub struct UpvarBorrow<'tcx> {
622 /// The kind of borrow: by-ref upvars have access to shared
623 /// immutable borrows, which are not part of the normal language
625 pub kind: BorrowKind,
627 /// Region of the resulting reference.
628 pub region: ty::Region<'tcx>,
631 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
633 #[derive(Copy, Clone)]
634 pub struct ClosureUpvar<'tcx> {
640 #[derive(Clone, Copy, PartialEq)]
641 pub enum IntVarValue {
643 UintType(ast::UintTy),
646 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
647 pub struct TypeParameterDef {
651 pub has_default: bool,
652 pub object_lifetime_default: ObjectLifetimeDefault,
654 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
655 /// on generic parameter `T`, asserts data behind the parameter
656 /// `T` won't be accessed during the parent type's `Drop` impl.
657 pub pure_wrt_drop: bool,
660 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
661 pub struct RegionParameterDef {
665 pub issue_32330: Option<ty::Issue32330>,
667 /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
668 /// on generic parameter `'a`, asserts data of lifetime `'a`
669 /// won't be accessed during the parent type's `Drop` impl.
670 pub pure_wrt_drop: bool,
673 impl RegionParameterDef {
674 pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
675 ty::EarlyBoundRegion {
681 pub fn to_bound_region(&self) -> ty::BoundRegion {
682 ty::BoundRegion::BrNamed(self.def_id, self.name)
686 /// Information about the formal type/lifetime parameters associated
687 /// with an item or method. Analogous to hir::Generics.
688 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
689 pub struct Generics {
690 pub parent: Option<DefId>,
691 pub parent_regions: u32,
692 pub parent_types: u32,
693 pub regions: Vec<RegionParameterDef>,
694 pub types: Vec<TypeParameterDef>,
696 /// Reverse map to each `TypeParameterDef`'s `index` field, from
697 /// `def_id.index` (`def_id.krate` is the same as the item's).
698 pub type_param_to_index: BTreeMap<DefIndex, u32>,
704 pub fn parent_count(&self) -> usize {
705 self.parent_regions as usize + self.parent_types as usize
708 pub fn own_count(&self) -> usize {
709 self.regions.len() + self.types.len()
712 pub fn count(&self) -> usize {
713 self.parent_count() + self.own_count()
716 pub fn region_param(&self, param: &EarlyBoundRegion) -> &RegionParameterDef {
717 assert_eq!(self.parent_count(), 0);
718 &self.regions[param.index as usize - self.has_self as usize]
721 pub fn type_param(&self, param: &ParamTy) -> &TypeParameterDef {
722 assert_eq!(self.parent_count(), 0);
723 &self.types[param.idx as usize - self.has_self as usize - self.regions.len()]
727 /// Bounds on generics.
728 #[derive(Clone, Default)]
729 pub struct GenericPredicates<'tcx> {
730 pub parent: Option<DefId>,
731 pub predicates: Vec<Predicate<'tcx>>,
734 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
735 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
737 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
738 pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
739 -> InstantiatedPredicates<'tcx> {
740 let mut instantiated = InstantiatedPredicates::empty();
741 self.instantiate_into(tcx, &mut instantiated, substs);
744 pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
745 -> InstantiatedPredicates<'tcx> {
746 InstantiatedPredicates {
747 predicates: self.predicates.subst(tcx, substs)
751 fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
752 instantiated: &mut InstantiatedPredicates<'tcx>,
753 substs: &Substs<'tcx>) {
754 if let Some(def_id) = self.parent {
755 tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
757 instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
760 pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
761 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
762 -> InstantiatedPredicates<'tcx>
764 assert_eq!(self.parent, None);
765 InstantiatedPredicates {
766 predicates: self.predicates.iter().map(|pred| {
767 pred.subst_supertrait(tcx, poly_trait_ref)
773 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
774 pub enum Predicate<'tcx> {
775 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
776 /// the `Self` type of the trait reference and `A`, `B`, and `C`
777 /// would be the type parameters.
778 Trait(PolyTraitPredicate<'tcx>),
780 /// where `T1 == T2`.
781 Equate(PolyEquatePredicate<'tcx>),
784 RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
787 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
789 /// where <T as TraitRef>::Name == X, approximately.
790 /// See `ProjectionPredicate` struct for details.
791 Projection(PolyProjectionPredicate<'tcx>),
794 WellFormed(Ty<'tcx>),
796 /// trait must be object-safe
799 /// No direct syntax. May be thought of as `where T : FnFoo<...>`
800 /// for some substitutions `...` and T being a closure type.
801 /// Satisfied (or refuted) once we know the closure's kind.
802 ClosureKind(DefId, ClosureKind),
805 Subtype(PolySubtypePredicate<'tcx>),
808 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
809 /// Performs a substitution suitable for going from a
810 /// poly-trait-ref to supertraits that must hold if that
811 /// poly-trait-ref holds. This is slightly different from a normal
812 /// substitution in terms of what happens with bound regions. See
813 /// lengthy comment below for details.
814 pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
815 trait_ref: &ty::PolyTraitRef<'tcx>)
816 -> ty::Predicate<'tcx>
818 // The interaction between HRTB and supertraits is not entirely
819 // obvious. Let me walk you (and myself) through an example.
821 // Let's start with an easy case. Consider two traits:
823 // trait Foo<'a> : Bar<'a,'a> { }
824 // trait Bar<'b,'c> { }
826 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
827 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
828 // knew that `Foo<'x>` (for any 'x) then we also know that
829 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
830 // normal substitution.
832 // In terms of why this is sound, the idea is that whenever there
833 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
834 // holds. So if there is an impl of `T:Foo<'a>` that applies to
835 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
838 // Another example to be careful of is this:
840 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
841 // trait Bar1<'b,'c> { }
843 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
844 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
845 // reason is similar to the previous example: any impl of
846 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
847 // basically we would want to collapse the bound lifetimes from
848 // the input (`trait_ref`) and the supertraits.
850 // To achieve this in practice is fairly straightforward. Let's
851 // consider the more complicated scenario:
853 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
854 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
855 // where both `'x` and `'b` would have a DB index of 1.
856 // The substitution from the input trait-ref is therefore going to be
857 // `'a => 'x` (where `'x` has a DB index of 1).
858 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
859 // early-bound parameter and `'b' is a late-bound parameter with a
861 // - If we replace `'a` with `'x` from the input, it too will have
862 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
863 // just as we wanted.
865 // There is only one catch. If we just apply the substitution `'a
866 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
867 // adjust the DB index because we substituting into a binder (it
868 // tries to be so smart...) resulting in `for<'x> for<'b>
869 // Bar1<'x,'b>` (we have no syntax for this, so use your
870 // imagination). Basically the 'x will have DB index of 2 and 'b
871 // will have DB index of 1. Not quite what we want. So we apply
872 // the substitution to the *contents* of the trait reference,
873 // rather than the trait reference itself (put another way, the
874 // substitution code expects equal binding levels in the values
875 // from the substitution and the value being substituted into, and
876 // this trick achieves that).
878 let substs = &trait_ref.0.substs;
880 Predicate::Trait(ty::Binder(ref data)) =>
881 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
882 Predicate::Equate(ty::Binder(ref data)) =>
883 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
884 Predicate::Subtype(ty::Binder(ref data)) =>
885 Predicate::Subtype(ty::Binder(data.subst(tcx, substs))),
886 Predicate::RegionOutlives(ty::Binder(ref data)) =>
887 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
888 Predicate::TypeOutlives(ty::Binder(ref data)) =>
889 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
890 Predicate::Projection(ty::Binder(ref data)) =>
891 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
892 Predicate::WellFormed(data) =>
893 Predicate::WellFormed(data.subst(tcx, substs)),
894 Predicate::ObjectSafe(trait_def_id) =>
895 Predicate::ObjectSafe(trait_def_id),
896 Predicate::ClosureKind(closure_def_id, kind) =>
897 Predicate::ClosureKind(closure_def_id, kind),
902 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
903 pub struct TraitPredicate<'tcx> {
904 pub trait_ref: TraitRef<'tcx>
906 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
908 impl<'tcx> TraitPredicate<'tcx> {
909 pub fn def_id(&self) -> DefId {
910 self.trait_ref.def_id
913 /// Creates the dep-node for selecting/evaluating this trait reference.
914 fn dep_node(&self) -> DepNode<DefId> {
915 // Extact the trait-def and first def-id from inputs. See the
916 // docs for `DepNode::TraitSelect` for more information.
917 let trait_def_id = self.def_id();
920 .flat_map(|t| t.walk())
921 .filter_map(|t| match t.sty {
922 ty::TyAdt(adt_def, _) => Some(adt_def.did),
926 .unwrap_or(trait_def_id);
927 DepNode::TraitSelect {
928 trait_def_id: trait_def_id,
929 input_def_id: input_def_id
933 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
934 self.trait_ref.input_types()
937 pub fn self_ty(&self) -> Ty<'tcx> {
938 self.trait_ref.self_ty()
942 impl<'tcx> PolyTraitPredicate<'tcx> {
943 pub fn def_id(&self) -> DefId {
944 // ok to skip binder since trait def-id does not care about regions
948 pub fn dep_node(&self) -> DepNode<DefId> {
949 // ok to skip binder since depnode does not care about regions
954 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
955 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
956 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
958 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
959 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
960 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
961 pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<ty::Region<'tcx>,
963 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
965 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
966 pub struct SubtypePredicate<'tcx> {
967 pub a_is_expected: bool,
971 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
973 /// This kind of predicate has no *direct* correspondent in the
974 /// syntax, but it roughly corresponds to the syntactic forms:
976 /// 1. `T : TraitRef<..., Item=Type>`
977 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
979 /// In particular, form #1 is "desugared" to the combination of a
980 /// normal trait predicate (`T : TraitRef<...>`) and one of these
981 /// predicates. Form #2 is a broader form in that it also permits
982 /// equality between arbitrary types. Processing an instance of Form
983 /// #2 eventually yields one of these `ProjectionPredicate`
984 /// instances to normalize the LHS.
985 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
986 pub struct ProjectionPredicate<'tcx> {
987 pub projection_ty: ProjectionTy<'tcx>,
991 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
993 impl<'tcx> PolyProjectionPredicate<'tcx> {
994 pub fn item_name(&self) -> Name {
995 self.0.projection_ty.item_name // safe to skip the binder to access a name
999 pub trait ToPolyTraitRef<'tcx> {
1000 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1003 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1004 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1005 assert!(!self.has_escaping_regions());
1006 ty::Binder(self.clone())
1010 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1011 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1012 self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1016 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
1017 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1018 // Note: unlike with TraitRef::to_poly_trait_ref(),
1019 // self.0.trait_ref is permitted to have escaping regions.
1020 // This is because here `self` has a `Binder` and so does our
1021 // return value, so we are preserving the number of binding
1023 ty::Binder(self.0.projection_ty.trait_ref)
1027 pub trait ToPredicate<'tcx> {
1028 fn to_predicate(&self) -> Predicate<'tcx>;
1031 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1032 fn to_predicate(&self) -> Predicate<'tcx> {
1033 // we're about to add a binder, so let's check that we don't
1034 // accidentally capture anything, or else that might be some
1035 // weird debruijn accounting.
1036 assert!(!self.has_escaping_regions());
1038 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1039 trait_ref: self.clone()
1044 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1045 fn to_predicate(&self) -> Predicate<'tcx> {
1046 ty::Predicate::Trait(self.to_poly_trait_predicate())
1050 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
1051 fn to_predicate(&self) -> Predicate<'tcx> {
1052 Predicate::Equate(self.clone())
1056 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1057 fn to_predicate(&self) -> Predicate<'tcx> {
1058 Predicate::RegionOutlives(self.clone())
1062 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1063 fn to_predicate(&self) -> Predicate<'tcx> {
1064 Predicate::TypeOutlives(self.clone())
1068 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1069 fn to_predicate(&self) -> Predicate<'tcx> {
1070 Predicate::Projection(self.clone())
1074 impl<'tcx> Predicate<'tcx> {
1075 /// Iterates over the types in this predicate. Note that in all
1076 /// cases this is skipping over a binder, so late-bound regions
1077 /// with depth 0 are bound by the predicate.
1078 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1079 let vec: Vec<_> = match *self {
1080 ty::Predicate::Trait(ref data) => {
1081 data.skip_binder().input_types().collect()
1083 ty::Predicate::Equate(ty::Binder(ref data)) => {
1084 vec![data.0, data.1]
1086 ty::Predicate::Subtype(ty::Binder(SubtypePredicate { a, b, a_is_expected: _ })) => {
1089 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1092 ty::Predicate::RegionOutlives(..) => {
1095 ty::Predicate::Projection(ref data) => {
1096 let trait_inputs = data.0.projection_ty.trait_ref.input_types();
1097 trait_inputs.chain(Some(data.0.ty)).collect()
1099 ty::Predicate::WellFormed(data) => {
1102 ty::Predicate::ObjectSafe(_trait_def_id) => {
1105 ty::Predicate::ClosureKind(_closure_def_id, _kind) => {
1110 // The only reason to collect into a vector here is that I was
1111 // too lazy to make the full (somewhat complicated) iterator
1112 // type that would be needed here. But I wanted this fn to
1113 // return an iterator conceptually, rather than a `Vec`, so as
1114 // to be closer to `Ty::walk`.
1118 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1120 Predicate::Trait(ref t) => {
1121 Some(t.to_poly_trait_ref())
1123 Predicate::Projection(..) |
1124 Predicate::Equate(..) |
1125 Predicate::Subtype(..) |
1126 Predicate::RegionOutlives(..) |
1127 Predicate::WellFormed(..) |
1128 Predicate::ObjectSafe(..) |
1129 Predicate::ClosureKind(..) |
1130 Predicate::TypeOutlives(..) => {
1137 /// Represents the bounds declared on a particular set of type
1138 /// parameters. Should eventually be generalized into a flag list of
1139 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
1140 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1141 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1142 /// the `GenericPredicates` are expressed in terms of the bound type
1143 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1144 /// represented a set of bounds for some particular instantiation,
1145 /// meaning that the generic parameters have been substituted with
1150 /// struct Foo<T,U:Bar<T>> { ... }
1152 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1153 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1154 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1155 /// [usize:Bar<isize>]]`.
1157 pub struct InstantiatedPredicates<'tcx> {
1158 pub predicates: Vec<Predicate<'tcx>>,
1161 impl<'tcx> InstantiatedPredicates<'tcx> {
1162 pub fn empty() -> InstantiatedPredicates<'tcx> {
1163 InstantiatedPredicates { predicates: vec![] }
1166 pub fn is_empty(&self) -> bool {
1167 self.predicates.is_empty()
1171 /// When type checking, we use the `ParameterEnvironment` to track
1172 /// details about the type/lifetime parameters that are in scope.
1173 /// It primarily stores the bounds information.
1175 /// Note: This information might seem to be redundant with the data in
1176 /// `tcx.ty_param_defs`, but it is not. That table contains the
1177 /// parameter definitions from an "outside" perspective, but this
1178 /// struct will contain the bounds for a parameter as seen from inside
1179 /// the function body. Currently the only real distinction is that
1180 /// bound lifetime parameters are replaced with free ones, but in the
1181 /// future I hope to refine the representation of types so as to make
1182 /// more distinctions clearer.
1184 pub struct ParameterEnvironment<'tcx> {
1185 /// See `construct_free_substs` for details.
1186 pub free_substs: &'tcx Substs<'tcx>,
1188 /// Each type parameter has an implicit region bound that
1189 /// indicates it must outlive at least the function body (the user
1190 /// may specify stronger requirements). This field indicates the
1191 /// region of the callee. If it is `None`, then the parameter
1192 /// environment is for an item or something where the "callee" is
1194 pub implicit_region_bound: Option<ty::Region<'tcx>>,
1196 /// Obligations that the caller must satisfy. This is basically
1197 /// the set of bounds on the in-scope type parameters, translated
1198 /// into Obligations, and elaborated and normalized.
1199 pub caller_bounds: Vec<ty::Predicate<'tcx>>,
1201 /// Scope that is attached to free regions for this scope. This is
1202 /// usually the id of the fn body, but for more abstract scopes
1203 /// like structs we use None or the item extent.
1205 /// FIXME(#3696). It would be nice to refactor so that free
1206 /// regions don't have this implicit scope and instead introduce
1207 /// relationships in the environment.
1208 pub free_id_outlive: Option<CodeExtent<'tcx>>,
1210 /// A cache for `moves_by_default`.
1211 pub is_copy_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
1213 /// A cache for `type_is_sized`
1214 pub is_sized_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
1216 /// A cache for `type_is_freeze`
1217 pub is_freeze_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
1220 impl<'a, 'tcx> ParameterEnvironment<'tcx> {
1221 pub fn with_caller_bounds(&self,
1222 caller_bounds: Vec<ty::Predicate<'tcx>>)
1223 -> ParameterEnvironment<'tcx>
1225 ParameterEnvironment {
1226 free_substs: self.free_substs,
1227 implicit_region_bound: self.implicit_region_bound,
1228 caller_bounds: caller_bounds,
1229 free_id_outlive: self.free_id_outlive,
1230 is_copy_cache: RefCell::new(FxHashMap()),
1231 is_sized_cache: RefCell::new(FxHashMap()),
1232 is_freeze_cache: RefCell::new(FxHashMap()),
1236 /// Construct a parameter environment given an item, impl item, or trait item
1237 pub fn for_item(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: NodeId)
1238 -> ParameterEnvironment<'tcx> {
1239 match tcx.hir.find(id) {
1240 Some(hir_map::NodeImplItem(ref impl_item)) => {
1241 match impl_item.node {
1242 hir::ImplItemKind::Type(_) | hir::ImplItemKind::Const(..) => {
1243 // associated types don't have their own entry (for some reason),
1244 // so for now just grab environment for the impl
1245 let impl_id = tcx.hir.get_parent(id);
1246 let impl_def_id = tcx.hir.local_def_id(impl_id);
1247 tcx.construct_parameter_environment(impl_item.span,
1249 Some(tcx.item_extent(id)))
1251 hir::ImplItemKind::Method(_, ref body) => {
1252 tcx.construct_parameter_environment(
1254 tcx.hir.local_def_id(id),
1255 Some(tcx.call_site_extent(id, body.node_id)))
1259 Some(hir_map::NodeTraitItem(trait_item)) => {
1260 match trait_item.node {
1261 hir::TraitItemKind::Type(..) | hir::TraitItemKind::Const(..) => {
1262 // associated types don't have their own entry (for some reason),
1263 // so for now just grab environment for the trait
1264 let trait_id = tcx.hir.get_parent(id);
1265 let trait_def_id = tcx.hir.local_def_id(trait_id);
1266 tcx.construct_parameter_environment(trait_item.span,
1268 Some(tcx.item_extent(id)))
1270 hir::TraitItemKind::Method(_, ref body) => {
1271 // Use call-site for extent (unless this is a
1272 // trait method with no default; then fallback
1273 // to the method id).
1274 let extent = if let hir::TraitMethod::Provided(body_id) = *body {
1275 // default impl: use call_site extent as free_id_outlive bound.
1276 tcx.call_site_extent(id, body_id.node_id)
1278 // no default impl: use item extent as free_id_outlive bound.
1281 tcx.construct_parameter_environment(
1283 tcx.hir.local_def_id(id),
1288 Some(hir_map::NodeItem(item)) => {
1290 hir::ItemFn(.., body_id) => {
1291 // We assume this is a function.
1292 let fn_def_id = tcx.hir.local_def_id(id);
1294 tcx.construct_parameter_environment(
1297 Some(tcx.call_site_extent(id, body_id.node_id)))
1300 hir::ItemStruct(..) |
1301 hir::ItemUnion(..) |
1304 hir::ItemConst(..) |
1305 hir::ItemStatic(..) => {
1306 let def_id = tcx.hir.local_def_id(id);
1307 tcx.construct_parameter_environment(item.span,
1309 Some(tcx.item_extent(id)))
1311 hir::ItemTrait(..) => {
1312 let def_id = tcx.hir.local_def_id(id);
1313 tcx.construct_parameter_environment(item.span,
1315 Some(tcx.item_extent(id)))
1318 span_bug!(item.span,
1319 "ParameterEnvironment::for_item():
1320 can't create a parameter \
1321 environment for this kind of item")
1325 Some(hir_map::NodeExpr(expr)) => {
1326 // This is a convenience to allow closures to work.
1327 if let hir::ExprClosure(.., body, _) = expr.node {
1328 let def_id = tcx.hir.local_def_id(id);
1329 let base_def_id = tcx.closure_base_def_id(def_id);
1330 tcx.construct_parameter_environment(
1333 Some(tcx.call_site_extent(id, body.node_id)))
1335 tcx.empty_parameter_environment()
1338 Some(hir_map::NodeForeignItem(item)) => {
1339 let def_id = tcx.hir.local_def_id(id);
1340 tcx.construct_parameter_environment(item.span,
1344 Some(hir_map::NodeStructCtor(..)) |
1345 Some(hir_map::NodeVariant(..)) => {
1346 let def_id = tcx.hir.local_def_id(id);
1347 tcx.construct_parameter_environment(tcx.hir.span(id),
1352 bug!("ParameterEnvironment::from_item(): \
1353 `{}` = {:?} is unsupported",
1354 tcx.hir.node_to_string(id), it)
1360 #[derive(Copy, Clone, Debug)]
1361 pub struct Destructor {
1362 /// The def-id of the destructor method
1367 flags AdtFlags: u32 {
1368 const NO_ADT_FLAGS = 0,
1369 const IS_ENUM = 1 << 0,
1370 const IS_PHANTOM_DATA = 1 << 1,
1371 const IS_FUNDAMENTAL = 1 << 2,
1372 const IS_UNION = 1 << 3,
1373 const IS_BOX = 1 << 4,
1378 pub struct VariantDef {
1379 /// The variant's DefId. If this is a tuple-like struct,
1380 /// this is the DefId of the struct's ctor.
1382 pub name: Name, // struct's name if this is a struct
1383 pub discr: VariantDiscr,
1384 pub fields: Vec<FieldDef>,
1385 pub ctor_kind: CtorKind,
1388 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1389 pub enum VariantDiscr {
1390 /// Explicit value for this variant, i.e. `X = 123`.
1391 /// The `DefId` corresponds to the embedded constant.
1394 /// The previous variant's discriminant plus one.
1395 /// For efficiency reasons, the distance from the
1396 /// last `Explicit` discriminant is being stored,
1397 /// or `0` for the first variant, if it has none.
1402 pub struct FieldDef {
1405 pub vis: Visibility,
1408 /// The definition of an abstract data type - a struct or enum.
1410 /// These are all interned (by intern_adt_def) into the adt_defs
1414 pub variants: Vec<VariantDef>,
1416 pub repr: ReprOptions,
1419 impl PartialEq for AdtDef {
1420 // AdtDef are always interned and this is part of TyS equality
1422 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1425 impl Eq for AdtDef {}
1427 impl Hash for AdtDef {
1429 fn hash<H: Hasher>(&self, s: &mut H) {
1430 (self as *const AdtDef).hash(s)
1434 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1435 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1440 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1443 impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for AdtDef {
1444 fn hash_stable<W: StableHasherResult>(&self,
1445 hcx: &mut StableHashingContext<'a, 'tcx>,
1446 hasher: &mut StableHasher<W>) {
1454 did.hash_stable(hcx, hasher);
1455 variants.hash_stable(hcx, hasher);
1456 flags.hash_stable(hcx, hasher);
1457 repr.hash_stable(hcx, hasher);
1461 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1462 pub enum AdtKind { Struct, Union, Enum }
1465 #[derive(RustcEncodable, RustcDecodable, Default)]
1466 flags ReprFlags: u8 {
1467 const IS_C = 1 << 0,
1468 const IS_PACKED = 1 << 1,
1469 const IS_SIMD = 1 << 2,
1470 // Internal only for now. If true, don't reorder fields.
1471 const IS_LINEAR = 1 << 3,
1473 // Any of these flags being set prevent field reordering optimisation.
1474 const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits |
1475 ReprFlags::IS_PACKED.bits |
1476 ReprFlags::IS_SIMD.bits |
1477 ReprFlags::IS_LINEAR.bits,
1481 impl_stable_hash_for!(struct ReprFlags {
1487 /// Represents the repr options provided by the user,
1488 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1489 pub struct ReprOptions {
1490 pub int: Option<attr::IntType>,
1492 pub flags: ReprFlags,
1495 impl_stable_hash_for!(struct ReprOptions {
1502 pub fn new(tcx: TyCtxt, did: DefId) -> ReprOptions {
1503 let mut flags = ReprFlags::empty();
1504 let mut size = None;
1505 let mut max_align = 0;
1506 for attr in tcx.get_attrs(did).iter() {
1507 for r in attr::find_repr_attrs(tcx.sess.diagnostic(), attr) {
1508 flags.insert(match r {
1509 attr::ReprExtern => ReprFlags::IS_C,
1510 attr::ReprPacked => ReprFlags::IS_PACKED,
1511 attr::ReprSimd => ReprFlags::IS_SIMD,
1512 attr::ReprInt(i) => {
1516 attr::ReprAlign(align) => {
1517 max_align = cmp::max(align, max_align);
1524 // FIXME(eddyb) This is deprecated and should be removed.
1525 if tcx.has_attr(did, "simd") {
1526 flags.insert(ReprFlags::IS_SIMD);
1529 // This is here instead of layout because the choice must make it into metadata.
1530 if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.item_path_str(did))) {
1531 flags.insert(ReprFlags::IS_LINEAR);
1533 ReprOptions { int: size, align: max_align, flags: flags }
1537 pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
1539 pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
1541 pub fn packed(&self) -> bool { self.flags.contains(ReprFlags::IS_PACKED) }
1543 pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
1545 pub fn discr_type(&self) -> attr::IntType {
1546 self.int.unwrap_or(attr::SignedInt(ast::IntTy::Is))
1549 /// Returns true if this `#[repr()]` should inhabit "smart enum
1550 /// layout" optimizations, such as representing `Foo<&T>` as a
1552 pub fn inhibit_enum_layout_opt(&self) -> bool {
1553 self.c() || self.int.is_some()
1557 impl<'a, 'gcx, 'tcx> AdtDef {
1561 variants: Vec<VariantDef>,
1562 repr: ReprOptions) -> Self {
1563 let mut flags = AdtFlags::NO_ADT_FLAGS;
1564 let attrs = tcx.get_attrs(did);
1565 if attr::contains_name(&attrs, "fundamental") {
1566 flags = flags | AdtFlags::IS_FUNDAMENTAL;
1568 if Some(did) == tcx.lang_items.phantom_data() {
1569 flags = flags | AdtFlags::IS_PHANTOM_DATA;
1571 if Some(did) == tcx.lang_items.owned_box() {
1572 flags = flags | AdtFlags::IS_BOX;
1575 AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1576 AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1577 AdtKind::Struct => {}
1588 pub fn is_struct(&self) -> bool {
1589 !self.is_union() && !self.is_enum()
1593 pub fn is_union(&self) -> bool {
1594 self.flags.intersects(AdtFlags::IS_UNION)
1598 pub fn is_enum(&self) -> bool {
1599 self.flags.intersects(AdtFlags::IS_ENUM)
1602 /// Returns the kind of the ADT - Struct or Enum.
1604 pub fn adt_kind(&self) -> AdtKind {
1607 } else if self.is_union() {
1614 pub fn descr(&self) -> &'static str {
1615 match self.adt_kind() {
1616 AdtKind::Struct => "struct",
1617 AdtKind::Union => "union",
1618 AdtKind::Enum => "enum",
1622 pub fn variant_descr(&self) -> &'static str {
1623 match self.adt_kind() {
1624 AdtKind::Struct => "struct",
1625 AdtKind::Union => "union",
1626 AdtKind::Enum => "variant",
1630 /// Returns whether this type is #[fundamental] for the purposes
1631 /// of coherence checking.
1633 pub fn is_fundamental(&self) -> bool {
1634 self.flags.intersects(AdtFlags::IS_FUNDAMENTAL)
1637 /// Returns true if this is PhantomData<T>.
1639 pub fn is_phantom_data(&self) -> bool {
1640 self.flags.intersects(AdtFlags::IS_PHANTOM_DATA)
1643 /// Returns true if this is Box<T>.
1645 pub fn is_box(&self) -> bool {
1646 self.flags.intersects(AdtFlags::IS_BOX)
1649 /// Returns whether this type has a destructor.
1650 pub fn has_dtor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1651 self.destructor(tcx).is_some()
1654 /// Asserts this is a struct and returns the struct's unique
1656 pub fn struct_variant(&self) -> &VariantDef {
1657 assert!(!self.is_enum());
1662 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1663 tcx.predicates_of(self.did)
1666 /// Returns an iterator over all fields contained
1669 pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1670 self.variants.iter().flat_map(|v| v.fields.iter())
1674 pub fn is_univariant(&self) -> bool {
1675 self.variants.len() == 1
1678 pub fn is_payloadfree(&self) -> bool {
1679 !self.variants.is_empty() &&
1680 self.variants.iter().all(|v| v.fields.is_empty())
1683 pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1686 .find(|v| v.did == vid)
1687 .expect("variant_with_id: unknown variant")
1690 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1693 .position(|v| v.did == vid)
1694 .expect("variant_index_with_id: unknown variant")
1697 pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1699 Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1700 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1701 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.struct_variant(),
1702 _ => bug!("unexpected def {:?} in variant_of_def", def)
1707 pub fn discriminants(&'a self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
1708 -> impl Iterator<Item=ConstInt> + 'a {
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::empty();
1716 match tcx.const_eval((expr_did, substs)) {
1717 Ok(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 repr_type = self.repr.discr_type();
1745 let mut explicit_value = repr_type.initial_discriminant(tcx.global_tcx());
1746 let mut explicit_index = variant_index;
1748 match self.variants[explicit_index].discr {
1749 ty::VariantDiscr::Relative(0) => break,
1750 ty::VariantDiscr::Relative(distance) => {
1751 explicit_index -= distance;
1753 ty::VariantDiscr::Explicit(expr_did) => {
1754 let substs = Substs::empty();
1755 match tcx.const_eval((expr_did, substs)) {
1756 Ok(ConstVal::Integral(v)) => {
1761 if !expr_did.is_local() {
1762 span_bug!(tcx.def_span(expr_did),
1763 "variant discriminant evaluation succeeded \
1764 in its crate but failed locally: {:?}", err);
1766 if explicit_index == 0 {
1769 explicit_index -= 1;
1775 let discr = explicit_value.to_u128_unchecked()
1776 .wrapping_add((variant_index - explicit_index) as u128);
1778 attr::UnsignedInt(ty) => {
1779 ConstInt::new_unsigned_truncating(discr, ty,
1780 tcx.sess.target.uint_type)
1782 attr::SignedInt(ty) => {
1783 ConstInt::new_signed_truncating(discr as i128, ty,
1784 tcx.sess.target.int_type)
1789 pub fn destructor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Destructor> {
1790 tcx.adt_destructor(self.did)
1793 /// Returns a list of types such that `Self: Sized` if and only
1794 /// if that type is Sized, or `TyErr` if this type is recursive.
1796 /// Oddly enough, checking that the sized-constraint is Sized is
1797 /// actually more expressive than checking all members:
1798 /// the Sized trait is inductive, so an associated type that references
1799 /// Self would prevent its containing ADT from being Sized.
1801 /// Due to normalization being eager, this applies even if
1802 /// the associated type is behind a pointer, e.g. issue #31299.
1803 pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] {
1804 match queries::adt_sized_constraint::try_get(tcx, DUMMY_SP, self.did) {
1807 debug!("adt_sized_constraint: {:?} is recursive", self);
1808 // This should be reported as an error by `check_representable`.
1810 // Consider the type as Sized in the meanwhile to avoid
1812 tcx.intern_type_list(&[tcx.types.err])
1817 fn sized_constraint_for_ty(&self,
1818 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1821 let result = match ty.sty {
1822 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
1823 TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
1824 TyArray(..) | TyClosure(..) | TyNever => {
1828 TyStr | TyDynamic(..) | TySlice(_) | TyError => {
1829 // these are never sized - return the target type
1833 TyTuple(ref tys, _) => {
1836 Some(ty) => self.sized_constraint_for_ty(tcx, ty)
1840 TyAdt(adt, substs) => {
1842 let adt_tys = adt.sized_constraint(tcx);
1843 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
1846 .map(|ty| ty.subst(tcx, substs))
1847 .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
1851 TyProjection(..) | TyAnon(..) => {
1852 // must calculate explicitly.
1853 // FIXME: consider special-casing always-Sized projections
1858 // perf hack: if there is a `T: Sized` bound, then
1859 // we know that `T` is Sized and do not need to check
1862 let sized_trait = match tcx.lang_items.sized_trait() {
1864 _ => return vec![ty]
1866 let sized_predicate = Binder(TraitRef {
1867 def_id: sized_trait,
1868 substs: tcx.mk_substs_trait(ty, &[])
1870 let predicates = tcx.predicates_of(self.did).predicates;
1871 if predicates.into_iter().any(|p| p == sized_predicate) {
1879 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
1883 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
1888 impl<'a, 'gcx, 'tcx> VariantDef {
1890 pub fn find_field_named(&self,
1892 -> Option<&FieldDef> {
1893 self.fields.iter().find(|f| f.name == name)
1897 pub fn index_of_field_named(&self,
1900 self.fields.iter().position(|f| f.name == name)
1904 pub fn field_named(&self, name: ast::Name) -> &FieldDef {
1905 self.find_field_named(name).unwrap()
1909 impl<'a, 'gcx, 'tcx> FieldDef {
1910 pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1911 tcx.type_of(self.did).subst(tcx, subst)
1915 /// Records the substitutions used to translate the polytype for an
1916 /// item into the monotype of an item reference.
1917 #[derive(Clone, RustcEncodable, RustcDecodable)]
1918 pub struct ItemSubsts<'tcx> {
1919 pub substs: &'tcx Substs<'tcx>,
1922 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1923 pub enum ClosureKind {
1924 // Warning: Ordering is significant here! The ordering is chosen
1925 // because the trait Fn is a subtrait of FnMut and so in turn, and
1926 // hence we order it so that Fn < FnMut < FnOnce.
1932 impl<'a, 'tcx> ClosureKind {
1933 pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
1935 ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
1936 ClosureKind::FnMut => {
1937 tcx.require_lang_item(FnMutTraitLangItem)
1939 ClosureKind::FnOnce => {
1940 tcx.require_lang_item(FnOnceTraitLangItem)
1945 /// True if this a type that impls this closure kind
1946 /// must also implement `other`.
1947 pub fn extends(self, other: ty::ClosureKind) -> bool {
1948 match (self, other) {
1949 (ClosureKind::Fn, ClosureKind::Fn) => true,
1950 (ClosureKind::Fn, ClosureKind::FnMut) => true,
1951 (ClosureKind::Fn, ClosureKind::FnOnce) => true,
1952 (ClosureKind::FnMut, ClosureKind::FnMut) => true,
1953 (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
1954 (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
1960 impl<'tcx> TyS<'tcx> {
1961 /// Iterator that walks `self` and any types reachable from
1962 /// `self`, in depth-first order. Note that just walks the types
1963 /// that appear in `self`, it does not descend into the fields of
1964 /// structs or variants. For example:
1967 /// isize => { isize }
1968 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
1969 /// [isize] => { [isize], isize }
1971 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
1972 TypeWalker::new(self)
1975 /// Iterator that walks the immediate children of `self`. Hence
1976 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
1977 /// (but not `i32`, like `walk`).
1978 pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
1979 walk::walk_shallow(self)
1982 /// Walks `ty` and any types appearing within `ty`, invoking the
1983 /// callback `f` on each type. If the callback returns false, then the
1984 /// children of the current type are ignored.
1986 /// Note: prefer `ty.walk()` where possible.
1987 pub fn maybe_walk<F>(&'tcx self, mut f: F)
1988 where F : FnMut(Ty<'tcx>) -> bool
1990 let mut walker = self.walk();
1991 while let Some(ty) = walker.next() {
1993 walker.skip_current_subtree();
1999 impl<'tcx> ItemSubsts<'tcx> {
2000 pub fn is_noop(&self) -> bool {
2001 self.substs.is_noop()
2005 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
2006 pub enum LvaluePreference {
2011 impl LvaluePreference {
2012 pub fn from_mutbl(m: hir::Mutability) -> Self {
2014 hir::MutMutable => PreferMutLvalue,
2015 hir::MutImmutable => NoPreference,
2021 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2023 hir::MutMutable => MutBorrow,
2024 hir::MutImmutable => ImmBorrow,
2028 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2029 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2030 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2032 pub fn to_mutbl_lossy(self) -> hir::Mutability {
2034 MutBorrow => hir::MutMutable,
2035 ImmBorrow => hir::MutImmutable,
2037 // We have no type corresponding to a unique imm borrow, so
2038 // use `&mut`. It gives all the capabilities of an `&uniq`
2039 // and hence is a safe "over approximation".
2040 UniqueImmBorrow => hir::MutMutable,
2044 pub fn to_user_str(&self) -> &'static str {
2046 MutBorrow => "mutable",
2047 ImmBorrow => "immutable",
2048 UniqueImmBorrow => "uniquely immutable",
2053 #[derive(Debug, Clone)]
2054 pub enum Attributes<'gcx> {
2055 Owned(Rc<[ast::Attribute]>),
2056 Borrowed(&'gcx [ast::Attribute])
2059 impl<'gcx> ::std::ops::Deref for Attributes<'gcx> {
2060 type Target = [ast::Attribute];
2062 fn deref(&self) -> &[ast::Attribute] {
2064 &Attributes::Owned(ref data) => &data,
2065 &Attributes::Borrowed(data) => data
2070 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2071 pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
2072 self.typeck_tables_of(self.hir.body_owner_def_id(body))
2075 /// Returns an iterator of the def-ids for all body-owners in this
2076 /// crate. If you would prefer to iterate over the bodies
2077 /// themselves, you can do `self.hir.krate().body_ids.iter()`.
2078 pub fn body_owners(self) -> impl Iterator<Item = DefId> + 'a {
2082 .map(move |&body_id| self.hir.body_owner_def_id(body_id))
2085 pub fn expr_span(self, id: NodeId) -> Span {
2086 match self.hir.find(id) {
2087 Some(hir_map::NodeExpr(e)) => {
2091 bug!("Node id {} is not an expr: {:?}", id, f);
2094 bug!("Node id {} is not present in the node map", id);
2099 pub fn local_var_name_str(self, id: NodeId) -> InternedString {
2100 match self.hir.find(id) {
2101 Some(hir_map::NodeLocal(pat)) => {
2103 hir::PatKind::Binding(_, _, ref path1, _) => path1.node.as_str(),
2105 bug!("Variable id {} maps to {:?}, not local", id, pat);
2109 r => bug!("Variable id {} maps to {:?}, not local", id, r),
2113 pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
2115 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
2117 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
2122 hir::ExprType(ref e, _) => {
2123 self.expr_is_lval(e)
2126 hir::ExprUnary(hir::UnDeref, _) |
2127 hir::ExprField(..) |
2128 hir::ExprTupField(..) |
2129 hir::ExprIndex(..) => {
2133 // Partially qualified paths in expressions can only legally
2134 // refer to associated items which are always rvalues.
2135 hir::ExprPath(hir::QPath::TypeRelative(..)) |
2138 hir::ExprMethodCall(..) |
2139 hir::ExprStruct(..) |
2142 hir::ExprMatch(..) |
2143 hir::ExprClosure(..) |
2144 hir::ExprBlock(..) |
2145 hir::ExprRepeat(..) |
2146 hir::ExprArray(..) |
2147 hir::ExprBreak(..) |
2148 hir::ExprAgain(..) |
2150 hir::ExprWhile(..) |
2152 hir::ExprAssign(..) |
2153 hir::ExprInlineAsm(..) |
2154 hir::ExprAssignOp(..) |
2156 hir::ExprUnary(..) |
2158 hir::ExprAddrOf(..) |
2159 hir::ExprBinary(..) |
2160 hir::ExprCast(..) => {
2166 pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2167 self.associated_items(id)
2168 .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2172 pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2173 self.associated_items(did).any(|item| {
2174 item.relevant_for_never()
2178 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssociatedItem> {
2179 let is_associated_item = if let Some(node_id) = self.hir.as_local_node_id(def_id) {
2180 match self.hir.get(node_id) {
2181 hir_map::NodeTraitItem(_) | hir_map::NodeImplItem(_) => true,
2185 match self.describe_def(def_id).expect("no def for def-id") {
2186 Def::AssociatedConst(_) | Def::Method(_) | Def::AssociatedTy(_) => true,
2191 if is_associated_item {
2192 Some(self.associated_item(def_id))
2198 fn associated_item_from_trait_item_ref(self,
2199 parent_def_id: DefId,
2200 parent_vis: &hir::Visibility,
2201 trait_item_ref: &hir::TraitItemRef)
2203 let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2204 let (kind, has_self) = match trait_item_ref.kind {
2205 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2206 hir::AssociatedItemKind::Method { has_self } => {
2207 (ty::AssociatedKind::Method, has_self)
2209 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2213 name: trait_item_ref.name,
2215 // Visibility of trait items is inherited from their traits.
2216 vis: Visibility::from_hir(parent_vis, trait_item_ref.id.node_id, self),
2217 defaultness: trait_item_ref.defaultness,
2219 container: TraitContainer(parent_def_id),
2220 method_has_self_argument: has_self
2224 fn associated_item_from_impl_item_ref(self,
2225 parent_def_id: DefId,
2226 impl_item_ref: &hir::ImplItemRef)
2228 let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2229 let (kind, has_self) = match impl_item_ref.kind {
2230 hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2231 hir::AssociatedItemKind::Method { has_self } => {
2232 (ty::AssociatedKind::Method, has_self)
2234 hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2237 ty::AssociatedItem {
2238 name: impl_item_ref.name,
2240 // Visibility of trait impl items doesn't matter.
2241 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.node_id, self),
2242 defaultness: impl_item_ref.defaultness,
2244 container: ImplContainer(parent_def_id),
2245 method_has_self_argument: has_self
2249 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2250 pub fn associated_items(self, def_id: DefId)
2251 -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2252 let def_ids = self.associated_item_def_ids(def_id);
2253 (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2256 /// Returns true if the impls are the same polarity and are implementing
2257 /// a trait which contains no items
2258 pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId) -> bool {
2259 if !self.sess.features.borrow().overlapping_marker_traits {
2262 let trait1_is_empty = self.impl_trait_ref(def_id1)
2263 .map_or(false, |trait_ref| {
2264 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2266 let trait2_is_empty = self.impl_trait_ref(def_id2)
2267 .map_or(false, |trait_ref| {
2268 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2270 self.impl_polarity(def_id1) == self.impl_polarity(def_id2)
2275 // Returns `ty::VariantDef` if `def` refers to a struct,
2276 // or variant or their constructors, panics otherwise.
2277 pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2279 Def::Variant(did) | Def::VariantCtor(did, ..) => {
2280 let enum_did = self.parent_def_id(did).unwrap();
2281 self.adt_def(enum_did).variant_with_id(did)
2283 Def::Struct(did) | Def::Union(did) => {
2284 self.adt_def(did).struct_variant()
2286 Def::StructCtor(ctor_did, ..) => {
2287 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2288 self.adt_def(did).struct_variant()
2290 _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2294 pub fn def_key(self, id: DefId) -> hir_map::DefKey {
2296 self.hir.def_key(id)
2298 self.sess.cstore.def_key(id)
2302 /// Convert a `DefId` into its fully expanded `DefPath` (every
2303 /// `DefId` is really just an interned def-path).
2305 /// Note that if `id` is not local to this crate, the result will
2306 /// be a non-local `DefPath`.
2307 pub fn def_path(self, id: DefId) -> hir_map::DefPath {
2309 self.hir.def_path(id)
2311 self.sess.cstore.def_path(id)
2316 pub fn def_path_hash(self, def_id: DefId) -> u64 {
2317 if def_id.is_local() {
2318 self.hir.definitions().def_path_hash(def_id.index)
2320 self.sess.cstore.def_path_hash(def_id)
2324 pub fn vis_is_accessible_from(self, vis: Visibility, block: NodeId) -> bool {
2325 vis.is_accessible_from(self.hir.local_def_id(self.hir.get_module_parent(block)), self)
2328 pub fn item_name(self, id: DefId) -> ast::Name {
2329 if let Some(id) = self.hir.as_local_node_id(id) {
2331 } else if id.index == CRATE_DEF_INDEX {
2332 self.sess.cstore.original_crate_name(id.krate)
2334 let def_key = self.sess.cstore.def_key(id);
2335 // The name of a StructCtor is that of its struct parent.
2336 if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2337 self.item_name(DefId {
2339 index: def_key.parent.unwrap()
2342 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2343 bug!("item_name: no name for {:?}", self.def_path(id));
2349 /// Return the possibly-auto-generated MIR of a (DefId, Subst) pair.
2350 pub fn instance_mir(self, instance: ty::InstanceDef<'gcx>)
2354 ty::InstanceDef::Item(did) => {
2355 self.optimized_mir(did)
2357 ty::InstanceDef::Intrinsic(..) |
2358 ty::InstanceDef::FnPtrShim(..) |
2359 ty::InstanceDef::Virtual(..) |
2360 ty::InstanceDef::ClosureOnceShim { .. } |
2361 ty::InstanceDef::DropGlue(..) => {
2362 self.mir_shims(instance)
2367 /// Given the DefId of an item, returns its MIR, borrowed immutably.
2368 /// Returns None if there is no MIR for the DefId
2369 pub fn maybe_optimized_mir(self, did: DefId) -> Option<&'gcx Mir<'gcx>> {
2370 if self.is_mir_available(did) {
2371 Some(self.optimized_mir(did))
2377 /// Get the attributes of a definition.
2378 pub fn get_attrs(self, did: DefId) -> Attributes<'gcx> {
2379 if let Some(id) = self.hir.as_local_node_id(did) {
2380 Attributes::Borrowed(self.hir.attrs(id))
2382 Attributes::Owned(self.sess.cstore.item_attrs(did))
2386 /// Determine whether an item is annotated with an attribute
2387 pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2388 self.get_attrs(did).iter().any(|item| item.check_name(attr))
2391 pub fn trait_has_default_impl(self, trait_def_id: DefId) -> bool {
2392 let def = self.trait_def(trait_def_id);
2393 def.flags.get().intersects(TraitFlags::HAS_DEFAULT_IMPL)
2396 /// Populates the type context with all the implementations for the given
2397 /// trait if necessary.
2398 pub fn populate_implementations_for_trait_if_necessary(self, trait_id: DefId) {
2399 if trait_id.is_local() {
2403 // The type is not local, hence we are reading this out of
2404 // metadata and don't need to track edges.
2405 let _ignore = self.dep_graph.in_ignore();
2407 let def = self.trait_def(trait_id);
2408 if def.flags.get().intersects(TraitFlags::HAS_REMOTE_IMPLS) {
2412 debug!("populate_implementations_for_trait_if_necessary: searching for {:?}", def);
2414 for impl_def_id in self.sess.cstore.implementations_of_trait(Some(trait_id)) {
2415 let trait_ref = self.impl_trait_ref(impl_def_id).unwrap();
2417 // Record the trait->implementation mapping.
2418 let parent = self.sess.cstore.impl_parent(impl_def_id).unwrap_or(trait_id);
2419 def.record_remote_impl(self, impl_def_id, trait_ref, parent);
2422 def.flags.set(def.flags.get() | TraitFlags::HAS_REMOTE_IMPLS);
2425 /// Given the def_id of an impl, return the def_id of the trait it implements.
2426 /// If it implements no trait, return `None`.
2427 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2428 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2431 /// If the given def ID describes a method belonging to an impl, return the
2432 /// ID of the impl that the method belongs to. Otherwise, return `None`.
2433 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2434 let item = if def_id.krate != LOCAL_CRATE {
2435 if let Some(Def::Method(_)) = self.describe_def(def_id) {
2436 Some(self.associated_item(def_id))
2441 self.opt_associated_item(def_id)
2445 Some(trait_item) => {
2446 match trait_item.container {
2447 TraitContainer(_) => None,
2448 ImplContainer(def_id) => Some(def_id),
2455 /// If the given def ID describes an item belonging to a trait,
2456 /// return the ID of the trait that the trait item belongs to.
2457 /// Otherwise, return `None`.
2458 pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
2459 if def_id.krate != LOCAL_CRATE {
2460 return self.sess.cstore.trait_of_item(def_id);
2462 self.opt_associated_item(def_id)
2463 .and_then(|associated_item| {
2464 match associated_item.container {
2465 TraitContainer(def_id) => Some(def_id),
2466 ImplContainer(_) => None
2471 /// Construct a parameter environment suitable for static contexts or other contexts where there
2472 /// are no free type/lifetime parameters in scope.
2473 pub fn empty_parameter_environment(self) -> ParameterEnvironment<'tcx> {
2474 ty::ParameterEnvironment {
2475 free_substs: self.intern_substs(&[]),
2476 caller_bounds: Vec::new(),
2477 implicit_region_bound: None,
2478 free_id_outlive: None,
2479 is_copy_cache: RefCell::new(FxHashMap()),
2480 is_sized_cache: RefCell::new(FxHashMap()),
2481 is_freeze_cache: RefCell::new(FxHashMap()),
2485 /// Constructs and returns a substitution that can be applied to move from
2486 /// the "outer" view of a type or method to the "inner" view.
2487 /// In general, this means converting from bound parameters to
2488 /// free parameters. Since we currently represent bound/free type
2489 /// parameters in the same way, this only has an effect on regions.
2490 pub fn construct_free_substs(self,
2492 free_id_outlive: Option<CodeExtent<'gcx>>)
2493 -> &'gcx Substs<'gcx> {
2495 let substs = Substs::for_item(self.global_tcx(), def_id, |def, _| {
2496 // map bound 'a => free 'a
2497 self.global_tcx().mk_region(ReFree(FreeRegion {
2498 scope: free_id_outlive,
2499 bound_region: def.to_bound_region()
2503 self.global_tcx().mk_param_from_def(def)
2506 debug!("construct_parameter_environment: {:?}", substs);
2510 /// See `ParameterEnvironment` struct def'n for details.
2511 /// If you were using `free_id: NodeId`, you might try `self.region_maps().item_extent(free_id)`
2512 /// for the `free_id_outlive` parameter. (But note that this is not always quite right.)
2513 pub fn construct_parameter_environment(self,
2516 free_id_outlive: Option<CodeExtent<'gcx>>)
2517 -> ParameterEnvironment<'gcx>
2520 // Construct the free substs.
2523 let free_substs = self.construct_free_substs(def_id, free_id_outlive);
2526 // Compute the bounds on Self and the type parameters.
2529 let tcx = self.global_tcx();
2530 let generic_predicates = tcx.predicates_of(def_id);
2531 let bounds = generic_predicates.instantiate(tcx, free_substs);
2532 let bounds = tcx.liberate_late_bound_regions(free_id_outlive, &ty::Binder(bounds));
2533 let predicates = bounds.predicates;
2535 // Finally, we have to normalize the bounds in the environment, in
2536 // case they contain any associated type projections. This process
2537 // can yield errors if the put in illegal associated types, like
2538 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2539 // report these errors right here; this doesn't actually feel
2540 // right to me, because constructing the environment feels like a
2541 // kind of a "idempotent" action, but I'm not sure where would be
2542 // a better place. In practice, we construct environments for
2543 // every fn once during type checking, and we'll abort if there
2544 // are any errors at that point, so after type checking you can be
2545 // sure that this will succeed without errors anyway.
2548 let unnormalized_env = ty::ParameterEnvironment {
2549 free_substs: free_substs,
2550 implicit_region_bound: free_id_outlive.map(|f| tcx.mk_region(ty::ReScope(f))),
2551 caller_bounds: predicates,
2552 free_id_outlive: free_id_outlive,
2553 is_copy_cache: RefCell::new(FxHashMap()),
2554 is_sized_cache: RefCell::new(FxHashMap()),
2555 is_freeze_cache: RefCell::new(FxHashMap()),
2558 let body_id = free_id_outlive.map(|f| f.node_id())
2559 .unwrap_or(DUMMY_NODE_ID);
2560 let cause = traits::ObligationCause::misc(span, body_id);
2561 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
2564 pub fn node_scope_region(self, id: NodeId) -> Region<'tcx> {
2565 self.mk_region(ty::ReScope(self.node_extent(id)))
2568 pub fn visit_all_item_likes_in_krate<V,F>(self,
2571 where F: FnMut(DefId) -> DepNode<DefId>, V: ItemLikeVisitor<'gcx>
2573 dep_graph::visit_all_item_likes_in_krate(self.global_tcx(), dep_node_fn, visitor);
2576 /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2577 /// with the name of the crate containing the impl.
2578 pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2579 if impl_did.is_local() {
2580 let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2581 Ok(self.hir.span(node_id))
2583 Err(self.sess.cstore.crate_name(impl_did.krate))
2588 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2589 pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2590 F: FnOnce(&[hir::Freevar]) -> T,
2592 match self.freevars.borrow().get(&fid) {
2594 Some(d) => f(&d[..])
2599 fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
2602 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2603 let parent_id = tcx.hir.get_parent(id);
2604 let parent_def_id = tcx.hir.local_def_id(parent_id);
2605 let parent_item = tcx.hir.expect_item(parent_id);
2606 match parent_item.node {
2607 hir::ItemImpl(.., ref impl_item_refs) => {
2608 if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.node_id == id) {
2609 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
2611 debug_assert_eq!(assoc_item.def_id, def_id);
2616 hir::ItemTrait(.., ref trait_item_refs) => {
2617 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.node_id == id) {
2618 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
2621 debug_assert_eq!(assoc_item.def_id, def_id);
2629 span_bug!(parent_item.span,
2630 "unexpected parent of trait or impl item or item not found: {:?}",
2634 /// Calculates the Sized-constraint.
2636 /// In fact, there are only a few options for the types in the constraint:
2637 /// - an obviously-unsized type
2638 /// - a type parameter or projection whose Sizedness can't be known
2639 /// - a tuple of type parameters or projections, if there are multiple
2641 /// - a TyError, if a type contained itself. The representability
2642 /// check should catch this case.
2643 fn adt_sized_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2645 -> &'tcx [Ty<'tcx>] {
2646 let def = tcx.adt_def(def_id);
2648 let result = tcx.intern_type_list(&def.variants.iter().flat_map(|v| {
2651 def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
2652 }).collect::<Vec<_>>());
2654 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
2659 /// Calculates the dtorck constraint for a type.
2660 fn adt_dtorck_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2662 -> DtorckConstraint<'tcx> {
2663 let def = tcx.adt_def(def_id);
2664 let span = tcx.def_span(def_id);
2665 debug!("dtorck_constraint: {:?}", def);
2667 if def.is_phantom_data() {
2668 let result = DtorckConstraint {
2671 tcx.mk_param_from_def(&tcx.generics_of(def_id).types[0])
2674 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2678 let mut result = def.all_fields()
2679 .map(|field| tcx.type_of(field.did))
2680 .map(|fty| tcx.dtorck_constraint_for_ty(span, fty, 0, fty))
2681 .collect::<Result<DtorckConstraint, ErrorReported>>()
2682 .unwrap_or(DtorckConstraint::empty());
2683 result.outlives.extend(tcx.destructor_constraints(def));
2686 debug!("dtorck_constraint: {:?} => {:?}", def, result);
2691 fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2694 let id = tcx.hir.as_local_node_id(def_id).unwrap();
2695 let item = tcx.hir.expect_item(id);
2696 let vec: Vec<_> = match item.node {
2697 hir::ItemTrait(.., ref trait_item_refs) => {
2698 trait_item_refs.iter()
2699 .map(|trait_item_ref| trait_item_ref.id)
2700 .map(|id| tcx.hir.local_def_id(id.node_id))
2703 hir::ItemImpl(.., ref impl_item_refs) => {
2704 impl_item_refs.iter()
2705 .map(|impl_item_ref| impl_item_ref.id)
2706 .map(|id| tcx.hir.local_def_id(id.node_id))
2709 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2714 fn def_span<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Span {
2715 tcx.hir.span_if_local(def_id).unwrap()
2718 pub fn provide(providers: &mut ty::maps::Providers) {
2719 *providers = ty::maps::Providers {
2721 associated_item_def_ids,
2722 adt_sized_constraint,
2723 adt_dtorck_constraint,
2729 pub fn provide_extern(providers: &mut ty::maps::Providers) {
2730 *providers = ty::maps::Providers {
2731 adt_sized_constraint,
2732 adt_dtorck_constraint,
2738 /// A map for the local crate mapping each type to a vector of its
2739 /// inherent impls. This is not meant to be used outside of coherence;
2740 /// rather, you should request the vector for a specific type via
2741 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2742 /// (constructing this map requires touching the entire crate).
2743 #[derive(Clone, Debug)]
2744 pub struct CrateInherentImpls {
2745 pub inherent_impls: DefIdMap<Rc<Vec<DefId>>>,
2748 /// A set of constraints that need to be satisfied in order for
2749 /// a type to be valid for destruction.
2750 #[derive(Clone, Debug)]
2751 pub struct DtorckConstraint<'tcx> {
2752 /// Types that are required to be alive in order for this
2753 /// type to be valid for destruction.
2754 pub outlives: Vec<ty::subst::Kind<'tcx>>,
2755 /// Types that could not be resolved: projections and params.
2756 pub dtorck_types: Vec<Ty<'tcx>>,
2759 impl<'tcx> FromIterator<DtorckConstraint<'tcx>> for DtorckConstraint<'tcx>
2761 fn from_iter<I: IntoIterator<Item=DtorckConstraint<'tcx>>>(iter: I) -> Self {
2762 let mut result = Self::empty();
2764 for constraint in iter {
2765 result.outlives.extend(constraint.outlives);
2766 result.dtorck_types.extend(constraint.dtorck_types);
2774 impl<'tcx> DtorckConstraint<'tcx> {
2775 fn empty() -> DtorckConstraint<'tcx> {
2778 dtorck_types: vec![]
2782 fn dedup<'a>(&mut self) {
2783 let mut outlives = FxHashSet();
2784 let mut dtorck_types = FxHashSet();
2786 self.outlives.retain(|&val| outlives.replace(val).is_none());
2787 self.dtorck_types.retain(|&val| dtorck_types.replace(val).is_none());
2791 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
2792 pub struct SymbolName {
2793 // FIXME: we don't rely on interning or equality here - better have
2794 // this be a `&'tcx str`.
2795 pub name: InternedString
2798 impl Deref for SymbolName {
2801 fn deref(&self) -> &str { &self.name }
2804 impl fmt::Display for SymbolName {
2805 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2806 fmt::Display::fmt(&self.name, fmt)