1 // Copyright 2012-2014 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 #![allow(non_camel_case_types)]
13 pub use self::terr_vstore_kind::*;
14 pub use self::type_err::*;
15 pub use self::BuiltinBound::*;
16 pub use self::InferTy::*;
17 pub use self::InferRegion::*;
18 pub use self::ImplOrTraitItemId::*;
19 pub use self::ClosureKind::*;
20 pub use self::Variance::*;
21 pub use self::AutoAdjustment::*;
22 pub use self::Representability::*;
23 pub use self::UnsizeKind::*;
24 pub use self::AutoRef::*;
25 pub use self::ExprKind::*;
26 pub use self::DtorKind::*;
27 pub use self::ExplicitSelfCategory::*;
28 pub use self::FnOutput::*;
29 pub use self::Region::*;
30 pub use self::ImplOrTraitItemContainer::*;
31 pub use self::BorrowKind::*;
32 pub use self::ImplOrTraitItem::*;
33 pub use self::BoundRegion::*;
35 pub use self::IntVarValue::*;
36 pub use self::ExprAdjustment::*;
37 pub use self::vtable_origin::*;
38 pub use self::MethodOrigin::*;
39 pub use self::CopyImplementationError::*;
44 use metadata::csearch;
46 use middle::check_const;
47 use middle::const_eval;
48 use middle::def::{self, DefMap, ExportMap};
49 use middle::dependency_format;
50 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
51 use middle::mem_categorization as mc;
53 use middle::resolve_lifetime;
56 use middle::stability;
57 use middle::subst::{self, ParamSpace, Subst, Substs, VecPerParamSpace};
60 use middle::ty_fold::{self, TypeFoldable, TypeFolder};
61 use middle::ty_walk::TypeWalker;
62 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_string};
63 use util::ppaux::ty_to_string;
64 use util::ppaux::{Repr, UserString};
65 use util::common::{memoized, ErrorReported};
66 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet};
67 use util::nodemap::FnvHashMap;
69 use arena::TypedArena;
70 use std::borrow::{Borrow, Cow};
71 use std::cell::{Cell, RefCell};
74 use std::hash::{Hash, SipHasher, Hasher};
78 use std::vec::IntoIter;
79 use collections::enum_set::{EnumSet, CLike};
80 use std::collections::{HashMap, HashSet};
82 use syntax::ast::{CrateNum, DefId, Ident, ItemTrait, LOCAL_CRATE};
83 use syntax::ast::{MutImmutable, MutMutable, Name, NamedField, NodeId};
84 use syntax::ast::{StmtExpr, StmtSemi, StructField, UnnamedField, Visibility};
85 use syntax::ast_util::{self, is_local, lit_is_str, local_def};
86 use syntax::attr::{self, AttrMetaMethods};
87 use syntax::codemap::Span;
88 use syntax::parse::token::{self, InternedString, special_idents};
89 use syntax::{ast, ast_map};
93 pub const INITIAL_DISCRIMINANT_VALUE: Disr = 0;
97 /// The complete set of all analyses described in this module. This is
98 /// produced by the driver and fed to trans and later passes.
99 pub struct CrateAnalysis<'tcx> {
100 pub export_map: ExportMap,
101 pub exported_items: middle::privacy::ExportedItems,
102 pub public_items: middle::privacy::PublicItems,
103 pub ty_cx: ty::ctxt<'tcx>,
104 pub reachable: NodeSet,
106 pub glob_map: Option<GlobMap>,
109 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
110 pub struct field<'tcx> {
115 #[derive(Clone, Copy, Debug)]
116 pub enum ImplOrTraitItemContainer {
117 TraitContainer(ast::DefId),
118 ImplContainer(ast::DefId),
121 impl ImplOrTraitItemContainer {
122 pub fn id(&self) -> ast::DefId {
124 TraitContainer(id) => id,
125 ImplContainer(id) => id,
130 #[derive(Clone, Debug)]
131 pub enum ImplOrTraitItem<'tcx> {
132 MethodTraitItem(Rc<Method<'tcx>>),
133 TypeTraitItem(Rc<AssociatedType>),
136 impl<'tcx> ImplOrTraitItem<'tcx> {
137 fn id(&self) -> ImplOrTraitItemId {
139 MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
140 TypeTraitItem(ref associated_type) => {
141 TypeTraitItemId(associated_type.def_id)
146 pub fn def_id(&self) -> ast::DefId {
148 MethodTraitItem(ref method) => method.def_id,
149 TypeTraitItem(ref associated_type) => associated_type.def_id,
153 pub fn name(&self) -> ast::Name {
155 MethodTraitItem(ref method) => method.name,
156 TypeTraitItem(ref associated_type) => associated_type.name,
160 pub fn container(&self) -> ImplOrTraitItemContainer {
162 MethodTraitItem(ref method) => method.container,
163 TypeTraitItem(ref associated_type) => associated_type.container,
167 pub fn as_opt_method(&self) -> Option<Rc<Method<'tcx>>> {
169 MethodTraitItem(ref m) => Some((*m).clone()),
170 TypeTraitItem(_) => None
175 #[derive(Clone, Copy, Debug)]
176 pub enum ImplOrTraitItemId {
177 MethodTraitItemId(ast::DefId),
178 TypeTraitItemId(ast::DefId),
181 impl ImplOrTraitItemId {
182 pub fn def_id(&self) -> ast::DefId {
184 MethodTraitItemId(def_id) => def_id,
185 TypeTraitItemId(def_id) => def_id,
190 #[derive(Clone, Debug)]
191 pub struct Method<'tcx> {
193 pub generics: Generics<'tcx>,
194 pub predicates: GenericPredicates<'tcx>,
195 pub fty: BareFnTy<'tcx>,
196 pub explicit_self: ExplicitSelfCategory,
197 pub vis: ast::Visibility,
198 pub def_id: ast::DefId,
199 pub container: ImplOrTraitItemContainer,
201 // If this method is provided, we need to know where it came from
202 pub provided_source: Option<ast::DefId>
205 impl<'tcx> Method<'tcx> {
206 pub fn new(name: ast::Name,
207 generics: ty::Generics<'tcx>,
208 predicates: GenericPredicates<'tcx>,
210 explicit_self: ExplicitSelfCategory,
211 vis: ast::Visibility,
213 container: ImplOrTraitItemContainer,
214 provided_source: Option<ast::DefId>)
219 predicates: predicates,
221 explicit_self: explicit_self,
224 container: container,
225 provided_source: provided_source
229 pub fn container_id(&self) -> ast::DefId {
230 match self.container {
231 TraitContainer(id) => id,
232 ImplContainer(id) => id,
237 #[derive(Clone, Copy, Debug)]
238 pub struct AssociatedType {
240 pub vis: ast::Visibility,
241 pub def_id: ast::DefId,
242 pub container: ImplOrTraitItemContainer,
245 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
246 pub struct mt<'tcx> {
248 pub mutbl: ast::Mutability,
251 #[derive(Clone, Copy, Debug)]
252 pub struct field_ty {
255 pub vis: ast::Visibility,
256 pub origin: ast::DefId, // The DefId of the struct in which the field is declared.
259 // Contains information needed to resolve types and (in the future) look up
260 // the types of AST nodes.
261 #[derive(Copy, PartialEq, Eq, Hash)]
262 pub struct creader_cache_key {
268 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
269 pub struct ItemVariances {
270 pub types: VecPerParamSpace<Variance>,
271 pub regions: VecPerParamSpace<Variance>,
274 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug, Copy)]
276 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
277 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
278 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
279 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
282 #[derive(Clone, Debug)]
283 pub enum AutoAdjustment<'tcx> {
284 AdjustReifyFnPointer(ast::DefId), // go from a fn-item type to a fn-pointer type
285 AdjustUnsafeFnPointer, // go from a safe fn pointer to an unsafe fn pointer
286 AdjustDerefRef(AutoDerefRef<'tcx>)
289 #[derive(Clone, PartialEq, Debug)]
290 pub enum UnsizeKind<'tcx> {
291 // [T, ..n] -> [T], the usize field is n.
293 // An unsize coercion applied to the tail field of a struct.
294 // The usize is the index of the type parameter which is unsized.
295 UnsizeStruct(Box<UnsizeKind<'tcx>>, usize),
296 UnsizeVtable(TyTrait<'tcx>, /* the self type of the trait */ Ty<'tcx>),
297 UnsizeUpcast(Ty<'tcx>),
300 #[derive(Clone, Debug)]
301 pub struct AutoDerefRef<'tcx> {
302 pub autoderefs: usize,
303 pub autoref: Option<AutoRef<'tcx>>
306 #[derive(Clone, PartialEq, Debug)]
307 pub enum AutoRef<'tcx> {
308 /// Convert from T to &T
309 /// The third field allows us to wrap other AutoRef adjustments.
310 AutoPtr(Region, ast::Mutability, Option<Box<AutoRef<'tcx>>>),
312 /// Convert [T, ..n] to [T] (or similar, depending on the kind)
313 AutoUnsize(UnsizeKind<'tcx>),
315 /// Convert Box<[T, ..n]> to Box<[T]> or something similar in a Box.
316 /// With DST and Box a library type, this should be replaced by UnsizeStruct.
317 AutoUnsizeUniq(UnsizeKind<'tcx>),
319 /// Convert from T to *T
320 /// Value to thin pointer
321 /// The second field allows us to wrap other AutoRef adjustments.
322 AutoUnsafe(ast::Mutability, Option<Box<AutoRef<'tcx>>>),
325 // Ugly little helper function. The first bool in the returned tuple is true if
326 // there is an 'unsize to trait object' adjustment at the bottom of the
327 // adjustment. If that is surrounded by an AutoPtr, then we also return the
328 // region of the AutoPtr (in the third argument). The second bool is true if the
329 // adjustment is unique.
330 fn autoref_object_region(autoref: &AutoRef) -> (bool, bool, Option<Region>) {
331 fn unsize_kind_is_object(k: &UnsizeKind) -> bool {
333 &UnsizeVtable(..) => true,
334 &UnsizeStruct(box ref k, _) => unsize_kind_is_object(k),
340 &AutoUnsize(ref k) => (unsize_kind_is_object(k), false, None),
341 &AutoUnsizeUniq(ref k) => (unsize_kind_is_object(k), true, None),
342 &AutoPtr(adj_r, _, Some(box ref autoref)) => {
343 let (b, u, r) = autoref_object_region(autoref);
344 if r.is_some() || u {
350 &AutoUnsafe(_, Some(box ref autoref)) => autoref_object_region(autoref),
351 _ => (false, false, None)
355 // If the adjustment introduces a borrowed reference to a trait object, then
356 // returns the region of the borrowed reference.
357 pub fn adjusted_object_region(adj: &AutoAdjustment) -> Option<Region> {
359 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
360 let (b, _, r) = autoref_object_region(autoref);
371 // Returns true if there is a trait cast at the bottom of the adjustment.
372 pub fn adjust_is_object(adj: &AutoAdjustment) -> bool {
374 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
375 let (b, _, _) = autoref_object_region(autoref);
382 // If possible, returns the type expected from the given adjustment. This is not
383 // possible if the adjustment depends on the type of the adjusted expression.
384 pub fn type_of_adjust<'tcx>(cx: &ctxt<'tcx>, adj: &AutoAdjustment<'tcx>) -> Option<Ty<'tcx>> {
385 fn type_of_autoref<'tcx>(cx: &ctxt<'tcx>, autoref: &AutoRef<'tcx>) -> Option<Ty<'tcx>> {
387 &AutoUnsize(ref k) => match k {
388 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
389 Some(mk_trait(cx, principal.clone(), bounds.clone()))
393 &AutoUnsizeUniq(ref k) => match k {
394 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
395 Some(mk_uniq(cx, mk_trait(cx, principal.clone(), bounds.clone())))
399 &AutoPtr(r, m, Some(box ref autoref)) => {
400 match type_of_autoref(cx, autoref) {
401 Some(ty) => Some(mk_rptr(cx, cx.mk_region(r), mt {mutbl: m, ty: ty})),
405 &AutoUnsafe(m, Some(box ref autoref)) => {
406 match type_of_autoref(cx, autoref) {
407 Some(ty) => Some(mk_ptr(cx, mt {mutbl: m, ty: ty})),
416 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
417 type_of_autoref(cx, autoref)
423 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Debug)]
424 pub struct param_index {
425 pub space: subst::ParamSpace,
429 #[derive(Clone, Debug)]
430 pub enum MethodOrigin<'tcx> {
431 // fully statically resolved method
432 MethodStatic(ast::DefId),
434 // fully statically resolved closure invocation
435 MethodStaticClosure(ast::DefId),
437 // method invoked on a type parameter with a bounded trait
438 MethodTypeParam(MethodParam<'tcx>),
440 // method invoked on a trait instance
441 MethodTraitObject(MethodObject<'tcx>),
445 // details for a method invoked with a receiver whose type is a type parameter
446 // with a bounded trait.
447 #[derive(Clone, Debug)]
448 pub struct MethodParam<'tcx> {
449 // the precise trait reference that occurs as a bound -- this may
450 // be a supertrait of what the user actually typed. Note that it
451 // never contains bound regions; those regions should have been
452 // instantiated with fresh variables at this point.
453 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
455 // index of usize in the list of trait items. Note that this is NOT
456 // the index into the vtable, because the list of trait items
457 // includes associated types.
458 pub method_num: usize,
460 /// The impl for the trait from which the method comes. This
461 /// should only be used for certain linting/heuristic purposes
462 /// since there is no guarantee that this is Some in every
463 /// situation that it could/should be.
464 pub impl_def_id: Option<ast::DefId>,
467 // details for a method invoked with a receiver whose type is an object
468 #[derive(Clone, Debug)]
469 pub struct MethodObject<'tcx> {
470 // the (super)trait containing the method to be invoked
471 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
473 // the actual base trait id of the object
474 pub object_trait_id: ast::DefId,
476 // index of the method to be invoked amongst the trait's items
477 pub method_num: usize,
479 // index into the actual runtime vtable.
480 // the vtable is formed by concatenating together the method lists of
481 // the base object trait and all supertraits; this is the index into
483 pub vtable_index: usize,
487 pub struct MethodCallee<'tcx> {
488 pub origin: MethodOrigin<'tcx>,
490 pub substs: subst::Substs<'tcx>
493 /// With method calls, we store some extra information in
494 /// side tables (i.e method_map). We use
495 /// MethodCall as a key to index into these tables instead of
496 /// just directly using the expression's NodeId. The reason
497 /// for this being that we may apply adjustments (coercions)
498 /// with the resulting expression also needing to use the
499 /// side tables. The problem with this is that we don't
500 /// assign a separate NodeId to this new expression
501 /// and so it would clash with the base expression if both
502 /// needed to add to the side tables. Thus to disambiguate
503 /// we also keep track of whether there's an adjustment in
505 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
506 pub struct MethodCall {
507 pub expr_id: ast::NodeId,
508 pub adjustment: ExprAdjustment
511 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
512 pub enum ExprAdjustment {
519 pub fn expr(id: ast::NodeId) -> MethodCall {
522 adjustment: NoAdjustment
526 pub fn autoobject(id: ast::NodeId) -> MethodCall {
529 adjustment: AutoObject
533 pub fn autoderef(expr_id: ast::NodeId, autoderef: usize) -> MethodCall {
536 adjustment: AutoDeref(1 + autoderef)
541 // maps from an expression id that corresponds to a method call to the details
542 // of the method to be invoked
543 pub type MethodMap<'tcx> = RefCell<FnvHashMap<MethodCall, MethodCallee<'tcx>>>;
545 pub type vtable_param_res<'tcx> = Vec<vtable_origin<'tcx>>;
547 // Resolutions for bounds of all parameters, left to right, for a given path.
548 pub type vtable_res<'tcx> = VecPerParamSpace<vtable_param_res<'tcx>>;
551 pub enum vtable_origin<'tcx> {
553 Statically known vtable. def_id gives the impl item
554 from whence comes the vtable, and tys are the type substs.
555 vtable_res is the vtable itself.
557 vtable_static(ast::DefId, subst::Substs<'tcx>, vtable_res<'tcx>),
560 Dynamic vtable, comes from a parameter that has a bound on it:
561 fn foo<T:quux,baz,bar>(a: T) -- a's vtable would have a
564 The first argument is the param index (identifying T in the example),
565 and the second is the bound number (identifying baz)
567 vtable_param(param_index, usize),
570 Vtable automatically generated for a closure. The def ID is the
571 ID of the closure expression.
573 vtable_closure(ast::DefId),
576 Asked to determine the vtable for ty_err. This is the value used
577 for the vtables of `Self` in a virtual call like `foo.bar()`
578 where `foo` is of object type. The same value is also used when
585 // For every explicit cast into an object type, maps from the cast
586 // expr to the associated trait ref.
587 pub type ObjectCastMap<'tcx> = RefCell<NodeMap<ty::PolyTraitRef<'tcx>>>;
589 /// A restriction that certain types must be the same size. The use of
590 /// `transmute` gives rise to these restrictions. These generally
591 /// cannot be checked until trans; therefore, each call to `transmute`
592 /// will push one or more such restriction into the
593 /// `transmute_restrictions` vector during `intrinsicck`. They are
594 /// then checked during `trans` by the fn `check_intrinsics`.
596 pub struct TransmuteRestriction<'tcx> {
597 /// The span whence the restriction comes.
600 /// The type being transmuted from.
601 pub original_from: Ty<'tcx>,
603 /// The type being transmuted to.
604 pub original_to: Ty<'tcx>,
606 /// The type being transmuted from, with all type parameters
607 /// substituted for an arbitrary representative. Not to be shown
609 pub substituted_from: Ty<'tcx>,
611 /// The type being transmuted to, with all type parameters
612 /// substituted for an arbitrary representative. Not to be shown
614 pub substituted_to: Ty<'tcx>,
616 /// NodeId of the transmute intrinsic.
621 pub struct CtxtArenas<'tcx> {
622 type_: TypedArena<TyS<'tcx>>,
623 substs: TypedArena<Substs<'tcx>>,
624 bare_fn: TypedArena<BareFnTy<'tcx>>,
625 region: TypedArena<Region>,
628 impl<'tcx> CtxtArenas<'tcx> {
629 pub fn new() -> CtxtArenas<'tcx> {
631 type_: TypedArena::new(),
632 substs: TypedArena::new(),
633 bare_fn: TypedArena::new(),
634 region: TypedArena::new(),
639 pub struct CommonTypes<'tcx> {
657 /// The data structure to keep track of all the information that typechecker
658 /// generates so that so that it can be reused and doesn't have to be redone
660 pub struct ctxt<'tcx> {
661 /// The arenas that types etc are allocated from.
662 arenas: &'tcx CtxtArenas<'tcx>,
664 /// Specifically use a speedy hash algorithm for this hash map, it's used
666 // FIXME(eddyb) use a FnvHashSet<InternedTy<'tcx>> when equivalent keys can
667 // queried from a HashSet.
668 interner: RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>,
670 // FIXME as above, use a hashset if equivalent elements can be queried.
671 substs_interner: RefCell<FnvHashMap<&'tcx Substs<'tcx>, &'tcx Substs<'tcx>>>,
672 bare_fn_interner: RefCell<FnvHashMap<&'tcx BareFnTy<'tcx>, &'tcx BareFnTy<'tcx>>>,
673 region_interner: RefCell<FnvHashMap<&'tcx Region, &'tcx Region>>,
675 /// Common types, pre-interned for your convenience.
676 pub types: CommonTypes<'tcx>,
681 pub named_region_map: resolve_lifetime::NamedRegionMap,
683 pub region_maps: middle::region::RegionMaps,
685 /// Stores the types for various nodes in the AST. Note that this table
686 /// is not guaranteed to be populated until after typeck. See
687 /// typeck::check::fn_ctxt for details.
688 pub node_types: RefCell<NodeMap<Ty<'tcx>>>,
690 /// Stores the type parameters which were substituted to obtain the type
691 /// of this node. This only applies to nodes that refer to entities
692 /// parameterized by type parameters, such as generic fns, types, or
694 pub item_substs: RefCell<NodeMap<ItemSubsts<'tcx>>>,
696 /// Maps from a trait item to the trait item "descriptor"
697 pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem<'tcx>>>,
699 /// Maps from a trait def-id to a list of the def-ids of its trait items
700 pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
702 /// A cache for the trait_items() routine
703 pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem<'tcx>>>>>,
705 pub impl_trait_cache: RefCell<DefIdMap<Option<Rc<ty::TraitRef<'tcx>>>>>,
707 pub impl_trait_refs: RefCell<NodeMap<Rc<TraitRef<'tcx>>>>,
708 pub trait_defs: RefCell<DefIdMap<Rc<TraitDef<'tcx>>>>,
710 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
711 /// associated predicates.
712 pub predicates: RefCell<DefIdMap<GenericPredicates<'tcx>>>,
714 /// Maps from the def-id of a trait to the list of
715 /// super-predicates. This is a subset of the full list of
716 /// predicates. We store these in a separate map because we must
717 /// evaluate them even during type conversion, often before the
718 /// full predicates are available (note that supertraits have
719 /// additional acyclicity requirements).
720 pub super_predicates: RefCell<DefIdMap<GenericPredicates<'tcx>>>,
722 /// Maps from node-id of a trait object cast (like `foo as
723 /// Box<Trait>`) to the trait reference.
724 pub object_cast_map: ObjectCastMap<'tcx>,
726 pub map: ast_map::Map<'tcx>,
727 pub freevars: RefCell<FreevarMap>,
728 pub tcache: RefCell<DefIdMap<TypeScheme<'tcx>>>,
729 pub rcache: RefCell<FnvHashMap<creader_cache_key, Ty<'tcx>>>,
730 pub short_names_cache: RefCell<FnvHashMap<Ty<'tcx>, String>>,
731 pub tc_cache: RefCell<FnvHashMap<Ty<'tcx>, TypeContents>>,
732 pub ast_ty_to_ty_cache: RefCell<NodeMap<Ty<'tcx>>>,
733 pub enum_var_cache: RefCell<DefIdMap<Rc<Vec<Rc<VariantInfo<'tcx>>>>>>,
734 pub ty_param_defs: RefCell<NodeMap<TypeParameterDef<'tcx>>>,
735 pub adjustments: RefCell<NodeMap<AutoAdjustment<'tcx>>>,
736 pub normalized_cache: RefCell<FnvHashMap<Ty<'tcx>, Ty<'tcx>>>,
737 pub lang_items: middle::lang_items::LanguageItems,
738 /// A mapping of fake provided method def_ids to the default implementation
739 pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
740 pub struct_fields: RefCell<DefIdMap<Rc<Vec<field_ty>>>>,
742 /// Maps from def-id of a type or region parameter to its
743 /// (inferred) variance.
744 pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
746 /// True if the variance has been computed yet; false otherwise.
747 pub variance_computed: Cell<bool>,
749 /// A mapping from the def ID of an enum or struct type to the def ID
750 /// of the method that implements its destructor. If the type is not
751 /// present in this map, it does not have a destructor. This map is
752 /// populated during the coherence phase of typechecking.
753 pub destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
755 /// A method will be in this list if and only if it is a destructor.
756 pub destructors: RefCell<DefIdSet>,
758 /// Maps a trait onto a list of impls of that trait.
759 pub trait_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
761 /// A set of traits that have a default impl
762 traits_with_default_impls: RefCell<DefIdMap<()>>,
764 /// Maps a DefId of a type to a list of its inherent impls.
765 /// Contains implementations of methods that are inherent to a type.
766 /// Methods in these implementations don't need to be exported.
767 pub inherent_impls: RefCell<DefIdMap<Rc<Vec<ast::DefId>>>>,
769 /// Maps a DefId of an impl to a list of its items.
770 /// Note that this contains all of the impls that we know about,
771 /// including ones in other crates. It's not clear that this is the best
773 pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
775 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
776 /// present in this set can be warned about.
777 pub used_unsafe: RefCell<NodeSet>,
779 /// Set of nodes which mark locals as mutable which end up getting used at
780 /// some point. Local variable definitions not in this set can be warned
782 pub used_mut_nodes: RefCell<NodeSet>,
784 /// The set of external nominal types whose implementations have been read.
785 /// This is used for lazy resolution of methods.
786 pub populated_external_types: RefCell<DefIdSet>,
788 /// The set of external traits whose implementations have been read. This
789 /// is used for lazy resolution of traits.
790 pub populated_external_traits: RefCell<DefIdSet>,
792 /// The set of external primitive inherent implementations that have been read.
793 pub populated_external_primitive_impls: RefCell<DefIdSet>,
796 pub upvar_capture_map: RefCell<UpvarCaptureMap>,
798 /// These two caches are used by const_eval when decoding external statics
799 /// and variants that are found.
800 pub extern_const_statics: RefCell<DefIdMap<ast::NodeId>>,
801 pub extern_const_variants: RefCell<DefIdMap<ast::NodeId>>,
803 pub method_map: MethodMap<'tcx>,
805 pub dependency_formats: RefCell<dependency_format::Dependencies>,
807 /// Records the type of each closure. The def ID is the ID of the
808 /// expression defining the closure.
809 pub closure_kinds: RefCell<DefIdMap<ClosureKind>>,
811 /// Records the type of each closure. The def ID is the ID of the
812 /// expression defining the closure.
813 pub closure_tys: RefCell<DefIdMap<ClosureTy<'tcx>>>,
815 pub node_lint_levels: RefCell<FnvHashMap<(ast::NodeId, lint::LintId),
818 /// The types that must be asserted to be the same size for `transmute`
819 /// to be valid. We gather up these restrictions in the intrinsicck pass
820 /// and check them in trans.
821 pub transmute_restrictions: RefCell<Vec<TransmuteRestriction<'tcx>>>,
823 /// Maps any item's def-id to its stability index.
824 pub stability: RefCell<stability::Index>,
826 /// Maps def IDs to true if and only if they're associated types.
827 pub associated_types: RefCell<DefIdMap<bool>>,
829 /// Caches the results of trait selection. This cache is used
830 /// for things that do not have to do with the parameters in scope.
831 pub selection_cache: traits::SelectionCache<'tcx>,
833 /// Caches the representation hints for struct definitions.
834 pub repr_hint_cache: RefCell<DefIdMap<Rc<Vec<attr::ReprAttr>>>>,
836 /// Caches whether types are known to impl Copy. Note that type
837 /// parameters are never placed into this cache, because their
838 /// results are dependent on the parameter environment.
839 pub type_impls_copy_cache: RefCell<HashMap<Ty<'tcx>,bool>>,
841 /// Caches whether types are known to impl Sized. Note that type
842 /// parameters are never placed into this cache, because their
843 /// results are dependent on the parameter environment.
844 pub type_impls_sized_cache: RefCell<HashMap<Ty<'tcx>,bool>>,
846 /// Caches whether traits are object safe
847 pub object_safety_cache: RefCell<DefIdMap<bool>>,
849 /// Maps Expr NodeId's to their constant qualification.
850 pub const_qualif_map: RefCell<NodeMap<check_const::ConstQualif>>,
853 // Flags that we track on types. These flags are propagated upwards
854 // through the type during type construction, so that we can quickly
855 // check whether the type has various kinds of types in it without
856 // recursing over the type itself.
858 flags TypeFlags: u32 {
859 const NO_TYPE_FLAGS = 0b0,
860 const HAS_PARAMS = 0b1,
861 const HAS_SELF = 0b10,
862 const HAS_TY_INFER = 0b100,
863 const HAS_RE_INFER = 0b1000,
864 const HAS_RE_LATE_BOUND = 0b10000,
865 const HAS_REGIONS = 0b100000,
866 const HAS_TY_ERR = 0b1000000,
867 const HAS_PROJECTION = 0b10000000,
868 const NEEDS_SUBST = HAS_PARAMS.bits | HAS_SELF.bits | HAS_REGIONS.bits,
872 macro_rules! sty_debug_print {
873 ($ctxt: expr, $($variant: ident),*) => {{
874 // curious inner module to allow variant names to be used as
886 pub fn go(tcx: &ty::ctxt) {
887 let mut total = DebugStat {
889 region_infer: 0, ty_infer: 0, both_infer: 0,
891 $(let mut $variant = total;)*
894 for (_, t) in &*tcx.interner.borrow() {
895 let variant = match t.sty {
896 ty::ty_bool | ty::ty_char | ty::ty_int(..) | ty::ty_uint(..) |
897 ty::ty_float(..) | ty::ty_str => continue,
898 ty::ty_err => /* unimportant */ continue,
899 $(ty::$variant(..) => &mut $variant,)*
901 let region = t.flags.intersects(ty::HAS_RE_INFER);
902 let ty = t.flags.intersects(ty::HAS_TY_INFER);
906 if region { total.region_infer += 1; variant.region_infer += 1 }
907 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
908 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
910 println!("Ty interner total ty region both");
911 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
912 {ty:4.1}% {region:5.1}% {both:4.1}%",
913 stringify!($variant),
914 uses = $variant.total,
915 usespc = $variant.total as f64 * 100.0 / total.total as f64,
916 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
917 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
918 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
920 println!(" total {uses:6} \
921 {ty:4.1}% {region:5.1}% {both:4.1}%",
923 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
924 region = total.region_infer as f64 * 100.0 / total.total as f64,
925 both = total.both_infer as f64 * 100.0 / total.total as f64)
933 impl<'tcx> ctxt<'tcx> {
934 pub fn print_debug_stats(&self) {
937 ty_enum, ty_uniq, ty_vec, ty_ptr, ty_rptr, ty_bare_fn, ty_trait,
938 ty_struct, ty_closure, ty_tup, ty_param, ty_infer, ty_projection);
940 println!("Substs interner: #{}", self.substs_interner.borrow().len());
941 println!("BareFnTy interner: #{}", self.bare_fn_interner.borrow().len());
942 println!("Region interner: #{}", self.region_interner.borrow().len());
947 pub struct TyS<'tcx> {
949 pub flags: TypeFlags,
951 // the maximal depth of any bound regions appearing in this type.
955 impl fmt::Debug for TypeFlags {
956 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
957 write!(f, "{}", self.bits)
961 impl<'tcx> PartialEq for TyS<'tcx> {
962 fn eq(&self, other: &TyS<'tcx>) -> bool {
963 // (self as *const _) == (other as *const _)
964 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
967 impl<'tcx> Eq for TyS<'tcx> {}
969 impl<'tcx> Hash for TyS<'tcx> {
970 fn hash<H: Hasher>(&self, s: &mut H) {
971 (self as *const TyS).hash(s)
975 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
977 /// An entry in the type interner.
978 pub struct InternedTy<'tcx> {
982 // NB: An InternedTy compares and hashes as a sty.
983 impl<'tcx> PartialEq for InternedTy<'tcx> {
984 fn eq(&self, other: &InternedTy<'tcx>) -> bool {
985 self.ty.sty == other.ty.sty
989 impl<'tcx> Eq for InternedTy<'tcx> {}
991 impl<'tcx> Hash for InternedTy<'tcx> {
992 fn hash<H: Hasher>(&self, s: &mut H) {
997 impl<'tcx> Borrow<sty<'tcx>> for InternedTy<'tcx> {
998 fn borrow<'a>(&'a self) -> &'a sty<'tcx> {
1003 pub fn type_has_params(ty: Ty) -> bool {
1004 ty.flags.intersects(HAS_PARAMS)
1006 pub fn type_has_self(ty: Ty) -> bool {
1007 ty.flags.intersects(HAS_SELF)
1009 pub fn type_has_ty_infer(ty: Ty) -> bool {
1010 ty.flags.intersects(HAS_TY_INFER)
1012 pub fn type_needs_infer(ty: Ty) -> bool {
1013 ty.flags.intersects(HAS_TY_INFER | HAS_RE_INFER)
1015 pub fn type_has_projection(ty: Ty) -> bool {
1016 ty.flags.intersects(HAS_PROJECTION)
1019 pub fn type_has_late_bound_regions(ty: Ty) -> bool {
1020 ty.flags.intersects(HAS_RE_LATE_BOUND)
1023 /// An "escaping region" is a bound region whose binder is not part of `t`.
1025 /// So, for example, consider a type like the following, which has two binders:
1027 /// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
1028 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
1029 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
1031 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
1032 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
1033 /// fn type*, that type has an escaping region: `'a`.
1035 /// Note that what I'm calling an "escaping region" is often just called a "free region". However,
1036 /// we already use the term "free region". It refers to the regions that we use to represent bound
1037 /// regions on a fn definition while we are typechecking its body.
1039 /// To clarify, conceptually there is no particular difference between an "escaping" region and a
1040 /// "free" region. However, there is a big difference in practice. Basically, when "entering" a
1041 /// binding level, one is generally required to do some sort of processing to a bound region, such
1042 /// as replacing it with a fresh/skolemized region, or making an entry in the environment to
1043 /// represent the scope to which it is attached, etc. An escaping region represents a bound region
1044 /// for which this processing has not yet been done.
1045 pub fn type_has_escaping_regions(ty: Ty) -> bool {
1046 type_escapes_depth(ty, 0)
1049 pub fn type_escapes_depth(ty: Ty, depth: u32) -> bool {
1050 ty.region_depth > depth
1053 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1054 pub struct BareFnTy<'tcx> {
1055 pub unsafety: ast::Unsafety,
1057 pub sig: PolyFnSig<'tcx>,
1060 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1061 pub struct ClosureTy<'tcx> {
1062 pub unsafety: ast::Unsafety,
1064 pub sig: PolyFnSig<'tcx>,
1067 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1068 pub enum FnOutput<'tcx> {
1069 FnConverging(Ty<'tcx>),
1073 impl<'tcx> FnOutput<'tcx> {
1074 pub fn diverges(&self) -> bool {
1075 *self == FnDiverging
1078 pub fn unwrap(self) -> Ty<'tcx> {
1080 ty::FnConverging(t) => t,
1081 ty::FnDiverging => unreachable!()
1086 pub type PolyFnOutput<'tcx> = Binder<FnOutput<'tcx>>;
1088 impl<'tcx> PolyFnOutput<'tcx> {
1089 pub fn diverges(&self) -> bool {
1094 /// Signature of a function type, which I have arbitrarily
1095 /// decided to use to refer to the input/output types.
1097 /// - `inputs` is the list of arguments and their modes.
1098 /// - `output` is the return type.
1099 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
1100 #[derive(Clone, PartialEq, Eq, Hash)]
1101 pub struct FnSig<'tcx> {
1102 pub inputs: Vec<Ty<'tcx>>,
1103 pub output: FnOutput<'tcx>,
1107 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1109 impl<'tcx> PolyFnSig<'tcx> {
1110 pub fn inputs(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
1111 self.map_bound_ref(|fn_sig| fn_sig.inputs.clone())
1113 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
1114 self.map_bound_ref(|fn_sig| fn_sig.inputs[index])
1116 pub fn output(&self) -> ty::Binder<FnOutput<'tcx>> {
1117 self.map_bound_ref(|fn_sig| fn_sig.output.clone())
1119 pub fn variadic(&self) -> bool {
1120 self.skip_binder().variadic
1124 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1125 pub struct ParamTy {
1126 pub space: subst::ParamSpace,
1128 pub name: ast::Name,
1131 /// A [De Bruijn index][dbi] is a standard means of representing
1132 /// regions (and perhaps later types) in a higher-ranked setting. In
1133 /// particular, imagine a type like this:
1135 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
1138 /// | +------------+ 1 | |
1140 /// +--------------------------------+ 2 |
1142 /// +------------------------------------------+ 1
1144 /// In this type, there are two binders (the outer fn and the inner
1145 /// fn). We need to be able to determine, for any given region, which
1146 /// fn type it is bound by, the inner or the outer one. There are
1147 /// various ways you can do this, but a De Bruijn index is one of the
1148 /// more convenient and has some nice properties. The basic idea is to
1149 /// count the number of binders, inside out. Some examples should help
1150 /// clarify what I mean.
1152 /// Let's start with the reference type `&'b isize` that is the first
1153 /// argument to the inner function. This region `'b` is assigned a De
1154 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
1155 /// fn). The region `'a` that appears in the second argument type (`&'a
1156 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
1157 /// second-innermost binder". (These indices are written on the arrays
1158 /// in the diagram).
1160 /// What is interesting is that De Bruijn index attached to a particular
1161 /// variable will vary depending on where it appears. For example,
1162 /// the final type `&'a char` also refers to the region `'a` declared on
1163 /// the outermost fn. But this time, this reference is not nested within
1164 /// any other binders (i.e., it is not an argument to the inner fn, but
1165 /// rather the outer one). Therefore, in this case, it is assigned a
1166 /// De Bruijn index of 1, because the innermost binder in that location
1167 /// is the outer fn.
1169 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1170 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
1171 pub struct DebruijnIndex {
1172 // We maintain the invariant that this is never 0. So 1 indicates
1173 // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
1177 /// Representation of regions:
1178 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
1180 // Region bound in a type or fn declaration which will be
1181 // substituted 'early' -- that is, at the same time when type
1182 // parameters are substituted.
1183 ReEarlyBound(/* param id */ ast::NodeId,
1188 // Region bound in a function scope, which will be substituted when the
1189 // function is called.
1190 ReLateBound(DebruijnIndex, BoundRegion),
1192 /// When checking a function body, the types of all arguments and so forth
1193 /// that refer to bound region parameters are modified to refer to free
1194 /// region parameters.
1197 /// A concrete region naming some statically determined extent
1198 /// (e.g. an expression or sequence of statements) within the
1199 /// current function.
1200 ReScope(region::CodeExtent),
1202 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1205 /// A region variable. Should not exist after typeck.
1206 ReInfer(InferRegion),
1208 /// Empty lifetime is for data that is never accessed.
1209 /// Bottom in the region lattice. We treat ReEmpty somewhat
1210 /// specially; at least right now, we do not generate instances of
1211 /// it during the GLB computations, but rather
1212 /// generate an error instead. This is to improve error messages.
1213 /// The only way to get an instance of ReEmpty is to have a region
1214 /// variable with no constraints.
1218 /// Upvars do not get their own node-id. Instead, we use the pair of
1219 /// the original var id (that is, the root variable that is referenced
1220 /// by the upvar) and the id of the closure expression.
1221 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1222 pub struct UpvarId {
1223 pub var_id: ast::NodeId,
1224 pub closure_expr_id: ast::NodeId,
1227 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
1228 pub enum BorrowKind {
1229 /// Data must be immutable and is aliasable.
1232 /// Data must be immutable but not aliasable. This kind of borrow
1233 /// cannot currently be expressed by the user and is used only in
1234 /// implicit closure bindings. It is needed when you the closure
1235 /// is borrowing or mutating a mutable referent, e.g.:
1237 /// let x: &mut isize = ...;
1238 /// let y = || *x += 5;
1240 /// If we were to try to translate this closure into a more explicit
1241 /// form, we'd encounter an error with the code as written:
1243 /// struct Env { x: & &mut isize }
1244 /// let x: &mut isize = ...;
1245 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
1246 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1248 /// This is then illegal because you cannot mutate a `&mut` found
1249 /// in an aliasable location. To solve, you'd have to translate with
1250 /// an `&mut` borrow:
1252 /// struct Env { x: & &mut isize }
1253 /// let x: &mut isize = ...;
1254 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
1255 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1257 /// Now the assignment to `**env.x` is legal, but creating a
1258 /// mutable pointer to `x` is not because `x` is not mutable. We
1259 /// could fix this by declaring `x` as `let mut x`. This is ok in
1260 /// user code, if awkward, but extra weird for closures, since the
1261 /// borrow is hidden.
1263 /// So we introduce a "unique imm" borrow -- the referent is
1264 /// immutable, but not aliasable. This solves the problem. For
1265 /// simplicity, we don't give users the way to express this
1266 /// borrow, it's just used when translating closures.
1269 /// Data is mutable and not aliasable.
1273 /// Information describing the capture of an upvar. This is computed
1274 /// during `typeck`, specifically by `regionck`.
1275 #[derive(PartialEq, Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1276 pub enum UpvarCapture {
1277 /// Upvar is captured by value. This is always true when the
1278 /// closure is labeled `move`, but can also be true in other cases
1279 /// depending on inference.
1282 /// Upvar is captured by reference.
1286 #[derive(PartialEq, Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1287 pub struct UpvarBorrow {
1288 /// The kind of borrow: by-ref upvars have access to shared
1289 /// immutable borrows, which are not part of the normal language
1291 pub kind: BorrowKind,
1293 /// Region of the resulting reference.
1294 pub region: ty::Region,
1297 pub type UpvarCaptureMap = FnvHashMap<UpvarId, UpvarCapture>;
1300 pub fn is_bound(&self) -> bool {
1302 ty::ReEarlyBound(..) => true,
1303 ty::ReLateBound(..) => true,
1308 pub fn escapes_depth(&self, depth: u32) -> bool {
1310 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1316 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1317 RustcEncodable, RustcDecodable, Debug, Copy)]
1318 /// A "free" region `fr` can be interpreted as "some region
1319 /// at least as big as the scope `fr.scope`".
1320 pub struct FreeRegion {
1321 pub scope: region::DestructionScopeData,
1322 pub bound_region: BoundRegion
1325 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1326 RustcEncodable, RustcDecodable, Debug, Copy)]
1327 pub enum BoundRegion {
1328 /// An anonymous region parameter for a given fn (&T)
1331 /// Named region parameters for functions (a in &'a T)
1333 /// The def-id is needed to distinguish free regions in
1334 /// the event of shadowing.
1335 BrNamed(ast::DefId, ast::Name),
1337 /// Fresh bound identifiers created during GLB computations.
1340 // Anonymous region for the implicit env pointer parameter
1345 // NB: If you change this, you'll probably want to change the corresponding
1346 // AST structure in libsyntax/ast.rs as well.
1347 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1348 pub enum sty<'tcx> {
1352 ty_uint(ast::UintTy),
1353 ty_float(ast::FloatTy),
1354 /// Substs here, possibly against intuition, *may* contain `ty_param`s.
1355 /// That is, even after substitution it is possible that there are type
1356 /// variables. This happens when the `ty_enum` corresponds to an enum
1357 /// definition and not a concrete use of it. To get the correct `ty_enum`
1358 /// from the tcx, use the `NodeId` from the `ast::Ty` and look it up in
1359 /// the `ast_ty_to_ty_cache`. This is probably true for `ty_struct` as
1361 ty_enum(DefId, &'tcx Substs<'tcx>),
1364 ty_vec(Ty<'tcx>, Option<usize>), // Second field is length.
1366 ty_rptr(&'tcx Region, mt<'tcx>),
1368 // If the def-id is Some(_), then this is the type of a specific
1369 // fn item. Otherwise, if None(_), it a fn pointer type.
1370 ty_bare_fn(Option<DefId>, &'tcx BareFnTy<'tcx>),
1372 ty_trait(Box<TyTrait<'tcx>>),
1373 ty_struct(DefId, &'tcx Substs<'tcx>),
1375 ty_closure(DefId, &'tcx Substs<'tcx>),
1377 ty_tup(Vec<Ty<'tcx>>),
1379 ty_projection(ProjectionTy<'tcx>),
1380 ty_param(ParamTy), // type parameter
1382 ty_infer(InferTy), // something used only during inference/typeck
1383 ty_err, // Also only used during inference/typeck, to represent
1384 // the type of an erroneous expression (helps cut down
1385 // on non-useful type error messages)
1388 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1389 pub struct TyTrait<'tcx> {
1390 pub principal: ty::PolyTraitRef<'tcx>,
1391 pub bounds: ExistentialBounds<'tcx>,
1394 impl<'tcx> TyTrait<'tcx> {
1395 pub fn principal_def_id(&self) -> ast::DefId {
1396 self.principal.0.def_id
1399 /// Object types don't have a self-type specified. Therefore, when
1400 /// we convert the principal trait-ref into a normal trait-ref,
1401 /// you must give *some* self-type. A common choice is `mk_err()`
1402 /// or some skolemized type.
1403 pub fn principal_trait_ref_with_self_ty(&self,
1406 -> ty::PolyTraitRef<'tcx>
1408 // otherwise the escaping regions would be captured by the binder
1409 assert!(!self_ty.has_escaping_regions());
1411 ty::Binder(Rc::new(ty::TraitRef {
1412 def_id: self.principal.0.def_id,
1413 substs: tcx.mk_substs(self.principal.0.substs.with_self_ty(self_ty)),
1417 pub fn projection_bounds_with_self_ty(&self,
1420 -> Vec<ty::PolyProjectionPredicate<'tcx>>
1422 // otherwise the escaping regions would be captured by the binders
1423 assert!(!self_ty.has_escaping_regions());
1425 self.bounds.projection_bounds.iter()
1426 .map(|in_poly_projection_predicate| {
1427 let in_projection_ty = &in_poly_projection_predicate.0.projection_ty;
1428 let substs = tcx.mk_substs(in_projection_ty.trait_ref.substs.with_self_ty(self_ty));
1430 Rc::new(ty::TraitRef::new(in_projection_ty.trait_ref.def_id,
1432 let projection_ty = ty::ProjectionTy {
1433 trait_ref: trait_ref,
1434 item_name: in_projection_ty.item_name
1436 ty::Binder(ty::ProjectionPredicate {
1437 projection_ty: projection_ty,
1438 ty: in_poly_projection_predicate.0.ty
1445 /// A complete reference to a trait. These take numerous guises in syntax,
1446 /// but perhaps the most recognizable form is in a where clause:
1450 /// This would be represented by a trait-reference where the def-id is the
1451 /// def-id for the trait `Foo` and the substs defines `T` as parameter 0 in the
1452 /// `SelfSpace` and `U` as parameter 0 in the `TypeSpace`.
1454 /// Trait references also appear in object types like `Foo<U>`, but in
1455 /// that case the `Self` parameter is absent from the substitutions.
1457 /// Note that a `TraitRef` introduces a level of region binding, to
1458 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
1459 /// U>` or higher-ranked object types.
1460 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1461 pub struct TraitRef<'tcx> {
1463 pub substs: &'tcx Substs<'tcx>,
1466 pub type PolyTraitRef<'tcx> = Binder<Rc<TraitRef<'tcx>>>;
1468 impl<'tcx> PolyTraitRef<'tcx> {
1469 pub fn self_ty(&self) -> Ty<'tcx> {
1473 pub fn def_id(&self) -> ast::DefId {
1477 pub fn substs(&self) -> &'tcx Substs<'tcx> {
1478 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
1482 pub fn input_types(&self) -> &[Ty<'tcx>] {
1483 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
1484 self.0.input_types()
1487 pub fn to_poly_trait_predicate(&self) -> PolyTraitPredicate<'tcx> {
1488 // Note that we preserve binding levels
1489 Binder(TraitPredicate { trait_ref: self.0.clone() })
1493 /// Binder is a binder for higher-ranked lifetimes. It is part of the
1494 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
1495 /// (which would be represented by the type `PolyTraitRef ==
1496 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
1497 /// erase, or otherwise "discharge" these bound regions, we change the
1498 /// type from `Binder<T>` to just `T` (see
1499 /// e.g. `liberate_late_bound_regions`).
1500 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1501 pub struct Binder<T>(pub T);
1504 /// Skips the binder and returns the "bound" value. This is a
1505 /// risky thing to do because it's easy to get confused about
1506 /// debruijn indices and the like. It is usually better to
1507 /// discharge the binder using `no_late_bound_regions` or
1508 /// `replace_late_bound_regions` or something like
1509 /// that. `skip_binder` is only valid when you are either
1510 /// extracting data that has nothing to do with bound regions, you
1511 /// are doing some sort of test that does not involve bound
1512 /// regions, or you are being very careful about your depth
1515 /// Some examples where `skip_binder` is reasonable:
1516 /// - extracting the def-id from a PolyTraitRef;
1517 /// - comparing the self type of a PolyTraitRef to see if it is equal to
1518 /// a type parameter `X`, since the type `X` does not reference any regions
1519 pub fn skip_binder(&self) -> &T {
1523 pub fn as_ref(&self) -> Binder<&T> {
1527 pub fn map_bound_ref<F,U>(&self, f: F) -> Binder<U>
1528 where F: FnOnce(&T) -> U
1530 self.as_ref().map_bound(f)
1533 pub fn map_bound<F,U>(self, f: F) -> Binder<U>
1534 where F: FnOnce(T) -> U
1536 ty::Binder(f(self.0))
1540 #[derive(Clone, Copy, PartialEq)]
1541 pub enum IntVarValue {
1542 IntType(ast::IntTy),
1543 UintType(ast::UintTy),
1546 #[derive(Clone, Copy, Debug)]
1547 pub enum terr_vstore_kind {
1554 #[derive(Clone, Copy, Debug)]
1555 pub struct expected_found<T> {
1560 // Data structures used in type unification
1561 #[derive(Clone, Copy, Debug)]
1562 pub enum type_err<'tcx> {
1564 terr_unsafety_mismatch(expected_found<ast::Unsafety>),
1565 terr_abi_mismatch(expected_found<abi::Abi>),
1567 terr_box_mutability,
1568 terr_ptr_mutability,
1569 terr_ref_mutability,
1570 terr_vec_mutability,
1571 terr_tuple_size(expected_found<usize>),
1572 terr_fixed_array_size(expected_found<usize>),
1573 terr_ty_param_size(expected_found<usize>),
1575 terr_regions_does_not_outlive(Region, Region),
1576 terr_regions_not_same(Region, Region),
1577 terr_regions_no_overlap(Region, Region),
1578 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
1579 terr_regions_overly_polymorphic(BoundRegion, Region),
1580 terr_sorts(expected_found<Ty<'tcx>>),
1581 terr_integer_as_char,
1582 terr_int_mismatch(expected_found<IntVarValue>),
1583 terr_float_mismatch(expected_found<ast::FloatTy>),
1584 terr_traits(expected_found<ast::DefId>),
1585 terr_builtin_bounds(expected_found<BuiltinBounds>),
1586 terr_variadic_mismatch(expected_found<bool>),
1588 terr_convergence_mismatch(expected_found<bool>),
1589 terr_projection_name_mismatched(expected_found<ast::Name>),
1590 terr_projection_bounds_length(expected_found<usize>),
1593 /// Bounds suitable for a named type parameter like `A` in `fn foo<A>`
1594 /// as well as the existential type parameter in an object type.
1595 #[derive(PartialEq, Eq, Hash, Clone, Debug)]
1596 pub struct ParamBounds<'tcx> {
1597 pub region_bounds: Vec<ty::Region>,
1598 pub builtin_bounds: BuiltinBounds,
1599 pub trait_bounds: Vec<PolyTraitRef<'tcx>>,
1600 pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
1603 /// Bounds suitable for an existentially quantified type parameter
1604 /// such as those that appear in object types or closure types. The
1605 /// major difference between this case and `ParamBounds` is that
1606 /// general purpose trait bounds are omitted and there must be
1607 /// *exactly one* region.
1608 #[derive(PartialEq, Eq, Hash, Clone, Debug)]
1609 pub struct ExistentialBounds<'tcx> {
1610 pub region_bound: ty::Region,
1611 pub builtin_bounds: BuiltinBounds,
1612 pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
1615 pub type BuiltinBounds = EnumSet<BuiltinBound>;
1617 #[derive(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
1620 pub enum BuiltinBound {
1627 pub fn empty_builtin_bounds() -> BuiltinBounds {
1631 pub fn all_builtin_bounds() -> BuiltinBounds {
1632 let mut set = EnumSet::new();
1633 set.insert(BoundSend);
1634 set.insert(BoundSized);
1635 set.insert(BoundSync);
1639 /// An existential bound that does not implement any traits.
1640 pub fn region_existential_bound<'tcx>(r: ty::Region) -> ExistentialBounds<'tcx> {
1641 ty::ExistentialBounds { region_bound: r,
1642 builtin_bounds: empty_builtin_bounds(),
1643 projection_bounds: Vec::new() }
1646 impl CLike for BuiltinBound {
1647 fn to_usize(&self) -> usize {
1650 fn from_usize(v: usize) -> BuiltinBound {
1651 unsafe { mem::transmute(v) }
1655 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1660 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1665 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1666 pub struct FloatVid {
1670 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1671 pub struct RegionVid {
1675 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1681 /// A `FreshTy` is one that is generated as a replacement for an
1682 /// unbound type variable. This is convenient for caching etc. See
1683 /// `middle::infer::freshen` for more details.
1686 // FIXME -- once integral fallback is impl'd, we should remove
1687 // this type. It's only needed to prevent spurious errors for
1688 // integers whose type winds up never being constrained.
1692 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
1693 pub enum UnconstrainedNumeric {
1700 #[derive(Clone, RustcEncodable, RustcDecodable, Eq, Hash, Debug, Copy)]
1701 pub enum InferRegion {
1703 ReSkolemized(u32, BoundRegion)
1706 impl cmp::PartialEq for InferRegion {
1707 fn eq(&self, other: &InferRegion) -> bool {
1708 match ((*self), *other) {
1709 (ReVar(rva), ReVar(rvb)) => {
1712 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
1718 fn ne(&self, other: &InferRegion) -> bool {
1719 !((*self) == (*other))
1723 impl fmt::Debug for TyVid {
1724 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
1725 write!(f, "_#{}t", self.index)
1729 impl fmt::Debug for IntVid {
1730 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1731 write!(f, "_#{}i", self.index)
1735 impl fmt::Debug for FloatVid {
1736 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1737 write!(f, "_#{}f", self.index)
1741 impl fmt::Debug for RegionVid {
1742 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1743 write!(f, "'_#{}r", self.index)
1747 impl<'tcx> fmt::Debug for FnSig<'tcx> {
1748 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1749 write!(f, "({:?}; variadic: {})->{:?}", self.inputs, self.variadic, self.output)
1753 impl fmt::Debug for InferTy {
1754 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1756 TyVar(ref v) => v.fmt(f),
1757 IntVar(ref v) => v.fmt(f),
1758 FloatVar(ref v) => v.fmt(f),
1759 FreshTy(v) => write!(f, "FreshTy({:?})", v),
1760 FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
1765 impl fmt::Debug for IntVarValue {
1766 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1768 IntType(ref v) => v.fmt(f),
1769 UintType(ref v) => v.fmt(f),
1774 /// Default region to use for the bound of objects that are
1775 /// supplied as the value for this type parameter. This is derived
1776 /// from `T:'a` annotations appearing in the type definition. If
1777 /// this is `None`, then the default is inherited from the
1778 /// surrounding context. See RFC #599 for details.
1779 #[derive(Copy, Clone, Debug)]
1780 pub enum ObjectLifetimeDefault {
1781 /// Require an explicit annotation. Occurs when multiple
1782 /// `T:'a` constraints are found.
1785 /// Use the given region as the default.
1789 #[derive(Clone, Debug)]
1790 pub struct TypeParameterDef<'tcx> {
1791 pub name: ast::Name,
1792 pub def_id: ast::DefId,
1793 pub space: subst::ParamSpace,
1795 pub default: Option<Ty<'tcx>>,
1796 pub object_lifetime_default: Option<ObjectLifetimeDefault>,
1799 #[derive(RustcEncodable, RustcDecodable, Clone, Debug)]
1800 pub struct RegionParameterDef {
1801 pub name: ast::Name,
1802 pub def_id: ast::DefId,
1803 pub space: subst::ParamSpace,
1805 pub bounds: Vec<ty::Region>,
1808 impl RegionParameterDef {
1809 pub fn to_early_bound_region(&self) -> ty::Region {
1810 ty::ReEarlyBound(self.def_id.node, self.space, self.index, self.name)
1812 pub fn to_bound_region(&self) -> ty::BoundRegion {
1813 ty::BoundRegion::BrNamed(self.def_id, self.name)
1817 /// Information about the formal type/lifetime parameters associated
1818 /// with an item or method. Analogous to ast::Generics.
1819 #[derive(Clone, Debug)]
1820 pub struct Generics<'tcx> {
1821 pub types: VecPerParamSpace<TypeParameterDef<'tcx>>,
1822 pub regions: VecPerParamSpace<RegionParameterDef>,
1825 impl<'tcx> Generics<'tcx> {
1826 pub fn empty() -> Generics<'tcx> {
1828 types: VecPerParamSpace::empty(),
1829 regions: VecPerParamSpace::empty(),
1833 pub fn is_empty(&self) -> bool {
1834 self.types.is_empty() && self.regions.is_empty()
1837 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
1838 !self.types.is_empty_in(space)
1841 pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
1842 !self.regions.is_empty_in(space)
1846 /// Bounds on generics.
1847 #[derive(Clone, Debug)]
1848 pub struct GenericPredicates<'tcx> {
1849 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
1852 impl<'tcx> GenericPredicates<'tcx> {
1853 pub fn empty() -> GenericPredicates<'tcx> {
1855 predicates: VecPerParamSpace::empty(),
1859 pub fn instantiate(&self, tcx: &ty::ctxt<'tcx>, substs: &Substs<'tcx>)
1860 -> InstantiatedPredicates<'tcx> {
1861 InstantiatedPredicates {
1862 predicates: self.predicates.subst(tcx, substs),
1866 pub fn instantiate_supertrait(&self,
1867 tcx: &ty::ctxt<'tcx>,
1868 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
1869 -> InstantiatedPredicates<'tcx>
1871 InstantiatedPredicates {
1872 predicates: self.predicates.map(|pred| pred.subst_supertrait(tcx, poly_trait_ref))
1877 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1878 pub enum Predicate<'tcx> {
1879 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
1880 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1881 /// would be the parameters in the `TypeSpace`.
1882 Trait(PolyTraitPredicate<'tcx>),
1884 /// where `T1 == T2`.
1885 Equate(PolyEquatePredicate<'tcx>),
1888 RegionOutlives(PolyRegionOutlivesPredicate),
1891 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1893 /// where <T as TraitRef>::Name == X, approximately.
1894 /// See `ProjectionPredicate` struct for details.
1895 Projection(PolyProjectionPredicate<'tcx>),
1898 impl<'tcx> Predicate<'tcx> {
1899 /// Performs a substituion suitable for going from a
1900 /// poly-trait-ref to supertraits that must hold if that
1901 /// poly-trait-ref holds. This is slightly different from a normal
1902 /// substitution in terms of what happens with bound regions. See
1903 /// lengthy comment below for details.
1904 pub fn subst_supertrait(&self,
1905 tcx: &ty::ctxt<'tcx>,
1906 trait_ref: &ty::PolyTraitRef<'tcx>)
1907 -> ty::Predicate<'tcx>
1909 // The interaction between HRTB and supertraits is not entirely
1910 // obvious. Let me walk you (and myself) through an example.
1912 // Let's start with an easy case. Consider two traits:
1914 // trait Foo<'a> : Bar<'a,'a> { }
1915 // trait Bar<'b,'c> { }
1917 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
1918 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
1919 // knew that `Foo<'x>` (for any 'x) then we also know that
1920 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1921 // normal substitution.
1923 // In terms of why this is sound, the idea is that whenever there
1924 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1925 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1926 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1929 // Another example to be careful of is this:
1931 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
1932 // trait Bar1<'b,'c> { }
1934 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
1935 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
1936 // reason is similar to the previous example: any impl of
1937 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
1938 // basically we would want to collapse the bound lifetimes from
1939 // the input (`trait_ref`) and the supertraits.
1941 // To achieve this in practice is fairly straightforward. Let's
1942 // consider the more complicated scenario:
1944 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
1945 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
1946 // where both `'x` and `'b` would have a DB index of 1.
1947 // The substitution from the input trait-ref is therefore going to be
1948 // `'a => 'x` (where `'x` has a DB index of 1).
1949 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1950 // early-bound parameter and `'b' is a late-bound parameter with a
1952 // - If we replace `'a` with `'x` from the input, it too will have
1953 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1954 // just as we wanted.
1956 // There is only one catch. If we just apply the substitution `'a
1957 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1958 // adjust the DB index because we substituting into a binder (it
1959 // tries to be so smart...) resulting in `for<'x> for<'b>
1960 // Bar1<'x,'b>` (we have no syntax for this, so use your
1961 // imagination). Basically the 'x will have DB index of 2 and 'b
1962 // will have DB index of 1. Not quite what we want. So we apply
1963 // the substitution to the *contents* of the trait reference,
1964 // rather than the trait reference itself (put another way, the
1965 // substitution code expects equal binding levels in the values
1966 // from the substitution and the value being substituted into, and
1967 // this trick achieves that).
1969 let substs = &trait_ref.0.substs;
1971 Predicate::Trait(ty::Binder(ref data)) =>
1972 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
1973 Predicate::Equate(ty::Binder(ref data)) =>
1974 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
1975 Predicate::RegionOutlives(ty::Binder(ref data)) =>
1976 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
1977 Predicate::TypeOutlives(ty::Binder(ref data)) =>
1978 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
1979 Predicate::Projection(ty::Binder(ref data)) =>
1980 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
1985 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1986 pub struct TraitPredicate<'tcx> {
1987 pub trait_ref: Rc<TraitRef<'tcx>>
1989 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1991 impl<'tcx> TraitPredicate<'tcx> {
1992 pub fn def_id(&self) -> ast::DefId {
1993 self.trait_ref.def_id
1996 pub fn input_types(&self) -> &[Ty<'tcx>] {
1997 self.trait_ref.substs.types.as_slice()
2000 pub fn self_ty(&self) -> Ty<'tcx> {
2001 self.trait_ref.self_ty()
2005 impl<'tcx> PolyTraitPredicate<'tcx> {
2006 pub fn def_id(&self) -> ast::DefId {
2011 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2012 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
2013 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
2015 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2016 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
2017 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
2018 pub type PolyRegionOutlivesPredicate = PolyOutlivesPredicate<ty::Region, ty::Region>;
2019 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region>;
2021 /// This kind of predicate has no *direct* correspondent in the
2022 /// syntax, but it roughly corresponds to the syntactic forms:
2024 /// 1. `T : TraitRef<..., Item=Type>`
2025 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
2027 /// In particular, form #1 is "desugared" to the combination of a
2028 /// normal trait predicate (`T : TraitRef<...>`) and one of these
2029 /// predicates. Form #2 is a broader form in that it also permits
2030 /// equality between arbitrary types. Processing an instance of Form
2031 /// #2 eventually yields one of these `ProjectionPredicate`
2032 /// instances to normalize the LHS.
2033 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2034 pub struct ProjectionPredicate<'tcx> {
2035 pub projection_ty: ProjectionTy<'tcx>,
2039 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
2041 impl<'tcx> PolyProjectionPredicate<'tcx> {
2042 pub fn item_name(&self) -> ast::Name {
2043 self.0.projection_ty.item_name // safe to skip the binder to access a name
2046 pub fn sort_key(&self) -> (ast::DefId, ast::Name) {
2047 self.0.projection_ty.sort_key()
2051 /// Represents the projection of an associated type. In explicit UFCS
2052 /// form this would be written `<T as Trait<..>>::N`.
2053 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2054 pub struct ProjectionTy<'tcx> {
2055 /// The trait reference `T as Trait<..>`.
2056 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
2058 /// The name `N` of the associated type.
2059 pub item_name: ast::Name,
2062 impl<'tcx> ProjectionTy<'tcx> {
2063 pub fn sort_key(&self) -> (ast::DefId, ast::Name) {
2064 (self.trait_ref.def_id, self.item_name)
2068 pub trait ToPolyTraitRef<'tcx> {
2069 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
2072 impl<'tcx> ToPolyTraitRef<'tcx> for Rc<TraitRef<'tcx>> {
2073 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2074 assert!(!self.has_escaping_regions());
2075 ty::Binder(self.clone())
2079 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
2080 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2081 self.map_bound_ref(|trait_pred| trait_pred.trait_ref.clone())
2085 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
2086 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2087 // Note: unlike with TraitRef::to_poly_trait_ref(),
2088 // self.0.trait_ref is permitted to have escaping regions.
2089 // This is because here `self` has a `Binder` and so does our
2090 // return value, so we are preserving the number of binding
2092 ty::Binder(self.0.projection_ty.trait_ref.clone())
2096 pub trait AsPredicate<'tcx> {
2097 fn as_predicate(&self) -> Predicate<'tcx>;
2100 impl<'tcx> AsPredicate<'tcx> for Rc<TraitRef<'tcx>> {
2101 fn as_predicate(&self) -> Predicate<'tcx> {
2102 // we're about to add a binder, so let's check that we don't
2103 // accidentally capture anything, or else that might be some
2104 // weird debruijn accounting.
2105 assert!(!self.has_escaping_regions());
2107 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
2108 trait_ref: self.clone()
2113 impl<'tcx> AsPredicate<'tcx> for PolyTraitRef<'tcx> {
2114 fn as_predicate(&self) -> Predicate<'tcx> {
2115 ty::Predicate::Trait(self.to_poly_trait_predicate())
2119 impl<'tcx> AsPredicate<'tcx> for PolyEquatePredicate<'tcx> {
2120 fn as_predicate(&self) -> Predicate<'tcx> {
2121 Predicate::Equate(self.clone())
2125 impl<'tcx> AsPredicate<'tcx> for PolyRegionOutlivesPredicate {
2126 fn as_predicate(&self) -> Predicate<'tcx> {
2127 Predicate::RegionOutlives(self.clone())
2131 impl<'tcx> AsPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
2132 fn as_predicate(&self) -> Predicate<'tcx> {
2133 Predicate::TypeOutlives(self.clone())
2137 impl<'tcx> AsPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
2138 fn as_predicate(&self) -> Predicate<'tcx> {
2139 Predicate::Projection(self.clone())
2143 impl<'tcx> Predicate<'tcx> {
2144 /// Iterates over the types in this predicate. Note that in all
2145 /// cases this is skipping over a binder, so late-bound regions
2146 /// with depth 0 are bound by the predicate.
2147 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
2148 let vec: Vec<_> = match *self {
2149 ty::Predicate::Trait(ref data) => {
2150 data.0.trait_ref.substs.types.as_slice().to_vec()
2152 ty::Predicate::Equate(ty::Binder(ref data)) => {
2153 vec![data.0, data.1]
2155 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
2158 ty::Predicate::RegionOutlives(..) => {
2161 ty::Predicate::Projection(ref data) => {
2162 let trait_inputs = data.0.projection_ty.trait_ref.substs.types.as_slice();
2165 .chain(Some(data.0.ty).into_iter())
2170 // The only reason to collect into a vector here is that I was
2171 // too lazy to make the full (somewhat complicated) iterator
2172 // type that would be needed here. But I wanted this fn to
2173 // return an iterator conceptually, rather than a `Vec`, so as
2174 // to be closer to `Ty::walk`.
2178 pub fn has_escaping_regions(&self) -> bool {
2180 Predicate::Trait(ref trait_ref) => trait_ref.has_escaping_regions(),
2181 Predicate::Equate(ref p) => p.has_escaping_regions(),
2182 Predicate::RegionOutlives(ref p) => p.has_escaping_regions(),
2183 Predicate::TypeOutlives(ref p) => p.has_escaping_regions(),
2184 Predicate::Projection(ref p) => p.has_escaping_regions(),
2188 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
2190 Predicate::Trait(ref t) => {
2191 Some(t.to_poly_trait_ref())
2193 Predicate::Projection(..) |
2194 Predicate::Equate(..) |
2195 Predicate::RegionOutlives(..) |
2196 Predicate::TypeOutlives(..) => {
2203 /// Represents the bounds declared on a particular set of type
2204 /// parameters. Should eventually be generalized into a flag list of
2205 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
2206 /// `GenericPredicates` by using the `instantiate` method. Note that this method
2207 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
2208 /// the `GenericPredicates` are expressed in terms of the bound type
2209 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
2210 /// represented a set of bounds for some particular instantiation,
2211 /// meaning that the generic parameters have been substituted with
2216 /// struct Foo<T,U:Bar<T>> { ... }
2218 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
2219 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
2220 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
2221 /// [usize:Bar<isize>]]`.
2222 #[derive(Clone, Debug)]
2223 pub struct InstantiatedPredicates<'tcx> {
2224 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
2227 impl<'tcx> InstantiatedPredicates<'tcx> {
2228 pub fn empty() -> InstantiatedPredicates<'tcx> {
2229 InstantiatedPredicates { predicates: VecPerParamSpace::empty() }
2232 pub fn has_escaping_regions(&self) -> bool {
2233 self.predicates.any(|p| p.has_escaping_regions())
2236 pub fn is_empty(&self) -> bool {
2237 self.predicates.is_empty()
2241 impl<'tcx> TraitRef<'tcx> {
2242 pub fn new(def_id: ast::DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
2243 TraitRef { def_id: def_id, substs: substs }
2246 pub fn self_ty(&self) -> Ty<'tcx> {
2247 self.substs.self_ty().unwrap()
2250 pub fn input_types(&self) -> &[Ty<'tcx>] {
2251 // Select only the "input types" from a trait-reference. For
2252 // now this is all the types that appear in the
2253 // trait-reference, but it should eventually exclude
2254 // associated types.
2255 self.substs.types.as_slice()
2259 /// When type checking, we use the `ParameterEnvironment` to track
2260 /// details about the type/lifetime parameters that are in scope.
2261 /// It primarily stores the bounds information.
2263 /// Note: This information might seem to be redundant with the data in
2264 /// `tcx.ty_param_defs`, but it is not. That table contains the
2265 /// parameter definitions from an "outside" perspective, but this
2266 /// struct will contain the bounds for a parameter as seen from inside
2267 /// the function body. Currently the only real distinction is that
2268 /// bound lifetime parameters are replaced with free ones, but in the
2269 /// future I hope to refine the representation of types so as to make
2270 /// more distinctions clearer.
2272 pub struct ParameterEnvironment<'a, 'tcx:'a> {
2273 pub tcx: &'a ctxt<'tcx>,
2275 /// See `construct_free_substs` for details.
2276 pub free_substs: Substs<'tcx>,
2278 /// Each type parameter has an implicit region bound that
2279 /// indicates it must outlive at least the function body (the user
2280 /// may specify stronger requirements). This field indicates the
2281 /// region of the callee.
2282 pub implicit_region_bound: ty::Region,
2284 /// Obligations that the caller must satisfy. This is basically
2285 /// the set of bounds on the in-scope type parameters, translated
2286 /// into Obligations.
2287 pub caller_bounds: Vec<ty::Predicate<'tcx>>,
2289 /// Caches the results of trait selection. This cache is used
2290 /// for things that have to do with the parameters in scope.
2291 pub selection_cache: traits::SelectionCache<'tcx>,
2294 impl<'a, 'tcx> ParameterEnvironment<'a, 'tcx> {
2295 pub fn with_caller_bounds(&self,
2296 caller_bounds: Vec<ty::Predicate<'tcx>>)
2297 -> ParameterEnvironment<'a,'tcx>
2299 ParameterEnvironment {
2301 free_substs: self.free_substs.clone(),
2302 implicit_region_bound: self.implicit_region_bound,
2303 caller_bounds: caller_bounds,
2304 selection_cache: traits::SelectionCache::new(),
2308 pub fn for_item(cx: &'a ctxt<'tcx>, id: NodeId) -> ParameterEnvironment<'a, 'tcx> {
2309 match cx.map.find(id) {
2310 Some(ast_map::NodeImplItem(ref impl_item)) => {
2311 match impl_item.node {
2312 ast::MethodImplItem(_, ref body) => {
2313 let method_def_id = ast_util::local_def(id);
2314 match ty::impl_or_trait_item(cx, method_def_id) {
2315 MethodTraitItem(ref method_ty) => {
2316 let method_generics = &method_ty.generics;
2317 let method_bounds = &method_ty.predicates;
2318 construct_parameter_environment(
2325 TypeTraitItem(_) => {
2327 .bug("ParameterEnvironment::for_item(): \
2328 can't create a parameter environment \
2329 for type trait items")
2333 ast::TypeImplItem(_) => {
2334 cx.sess.bug("ParameterEnvironment::for_item(): \
2335 can't create a parameter environment \
2336 for type impl items")
2338 ast::MacImplItem(_) => cx.sess.bug("unexpanded macro")
2341 Some(ast_map::NodeTraitItem(trait_item)) => {
2342 match trait_item.node {
2343 ast::MethodTraitItem(_, None) => {
2344 cx.sess.span_bug(trait_item.span,
2345 "ParameterEnvironment::for_item():
2346 can't create a parameter \
2347 environment for required trait \
2350 ast::MethodTraitItem(_, Some(ref body)) => {
2351 let method_def_id = ast_util::local_def(id);
2352 match ty::impl_or_trait_item(cx, method_def_id) {
2353 MethodTraitItem(ref method_ty) => {
2354 let method_generics = &method_ty.generics;
2355 let method_bounds = &method_ty.predicates;
2356 construct_parameter_environment(
2363 TypeTraitItem(_) => {
2365 .bug("ParameterEnvironment::for_item(): \
2366 can't create a parameter environment \
2367 for type trait items")
2371 ast::TypeTraitItem(..) => {
2372 cx.sess.bug("ParameterEnvironment::from_item(): \
2373 can't create a parameter environment \
2374 for type trait items")
2378 Some(ast_map::NodeItem(item)) => {
2380 ast::ItemFn(_, _, _, _, ref body) => {
2381 // We assume this is a function.
2382 let fn_def_id = ast_util::local_def(id);
2383 let fn_scheme = lookup_item_type(cx, fn_def_id);
2384 let fn_predicates = lookup_predicates(cx, fn_def_id);
2386 construct_parameter_environment(cx,
2388 &fn_scheme.generics,
2393 ast::ItemStruct(..) |
2395 ast::ItemConst(..) |
2396 ast::ItemStatic(..) => {
2397 let def_id = ast_util::local_def(id);
2398 let scheme = lookup_item_type(cx, def_id);
2399 let predicates = lookup_predicates(cx, def_id);
2400 construct_parameter_environment(cx,
2407 cx.sess.span_bug(item.span,
2408 "ParameterEnvironment::from_item():
2409 can't create a parameter \
2410 environment for this kind of item")
2414 Some(ast_map::NodeExpr(..)) => {
2415 // This is a convenience to allow closures to work.
2416 ParameterEnvironment::for_item(cx, cx.map.get_parent(id))
2419 cx.sess.bug(&format!("ParameterEnvironment::from_item(): \
2420 `{}` is not an item",
2421 cx.map.node_to_string(id)))
2427 /// A "type scheme", in ML terminology, is a type combined with some
2428 /// set of generic types that the type is, well, generic over. In Rust
2429 /// terms, it is the "type" of a fn item or struct -- this type will
2430 /// include various generic parameters that must be substituted when
2431 /// the item/struct is referenced. That is called converting the type
2432 /// scheme to a monotype.
2434 /// - `generics`: the set of type parameters and their bounds
2435 /// - `ty`: the base types, which may reference the parameters defined
2438 /// Note that TypeSchemes are also sometimes called "polytypes" (and
2439 /// in fact this struct used to carry that name, so you may find some
2440 /// stray references in a comment or something). We try to reserve the
2441 /// "poly" prefix to refer to higher-ranked things, as in
2444 /// Note that each item also comes with predicates, see
2445 /// `lookup_predicates`.
2446 #[derive(Clone, Debug)]
2447 pub struct TypeScheme<'tcx> {
2448 pub generics: Generics<'tcx>,
2452 /// As `TypeScheme` but for a trait ref.
2453 pub struct TraitDef<'tcx> {
2454 pub unsafety: ast::Unsafety,
2456 /// If `true`, then this trait had the `#[rustc_paren_sugar]`
2457 /// attribute, indicating that it should be used with `Foo()`
2458 /// sugar. This is a temporary thing -- eventually any trait wil
2459 /// be usable with the sugar (or without it).
2460 pub paren_sugar: bool,
2462 /// Generic type definitions. Note that `Self` is listed in here
2463 /// as having a single bound, the trait itself (e.g., in the trait
2464 /// `Eq`, there is a single bound `Self : Eq`). This is so that
2465 /// default methods get to assume that the `Self` parameters
2466 /// implements the trait.
2467 pub generics: Generics<'tcx>,
2469 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
2471 /// A list of the associated types defined in this trait. Useful
2472 /// for resolving `X::Foo` type markers.
2473 pub associated_type_names: Vec<ast::Name>,
2476 /// Records the substitutions used to translate the polytype for an
2477 /// item into the monotype of an item reference.
2479 pub struct ItemSubsts<'tcx> {
2480 pub substs: Substs<'tcx>,
2483 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
2484 pub enum ClosureKind {
2485 // Warning: Ordering is significant here! The ordering is chosen
2486 // because the trait Fn is a subtrait of FnMut and so in turn, and
2487 // hence we order it so that Fn < FnMut < FnOnce.
2494 pub fn trait_did(&self, cx: &ctxt) -> ast::DefId {
2495 let result = match *self {
2496 FnClosureKind => cx.lang_items.require(FnTraitLangItem),
2497 FnMutClosureKind => {
2498 cx.lang_items.require(FnMutTraitLangItem)
2500 FnOnceClosureKind => {
2501 cx.lang_items.require(FnOnceTraitLangItem)
2505 Ok(trait_did) => trait_did,
2506 Err(err) => cx.sess.fatal(&err[..]),
2510 /// True if this a type that impls this closure kind
2511 /// must also implement `other`.
2512 pub fn extends(self, other: ty::ClosureKind) -> bool {
2513 match (self, other) {
2514 (FnClosureKind, FnClosureKind) => true,
2515 (FnClosureKind, FnMutClosureKind) => true,
2516 (FnClosureKind, FnOnceClosureKind) => true,
2517 (FnMutClosureKind, FnMutClosureKind) => true,
2518 (FnMutClosureKind, FnOnceClosureKind) => true,
2519 (FnOnceClosureKind, FnOnceClosureKind) => true,
2525 pub trait ClosureTyper<'tcx> {
2526 fn tcx(&self) -> &ty::ctxt<'tcx> {
2527 self.param_env().tcx
2530 fn param_env<'a>(&'a self) -> &'a ty::ParameterEnvironment<'a, 'tcx>;
2532 /// Is this a `Fn`, `FnMut` or `FnOnce` closure? During typeck,
2533 /// returns `None` if the kind of this closure has not yet been
2535 fn closure_kind(&self,
2537 -> Option<ty::ClosureKind>;
2539 /// Returns the argument/return types of this closure.
2540 fn closure_type(&self,
2542 substs: &subst::Substs<'tcx>)
2543 -> ty::ClosureTy<'tcx>;
2545 /// Returns the set of all upvars and their transformed
2546 /// types. During typeck, maybe return `None` if the upvar types
2547 /// have not yet been inferred.
2548 fn closure_upvars(&self,
2550 substs: &Substs<'tcx>)
2551 -> Option<Vec<ClosureUpvar<'tcx>>>;
2554 impl<'tcx> CommonTypes<'tcx> {
2555 fn new(arena: &'tcx TypedArena<TyS<'tcx>>,
2556 interner: &mut FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>)
2557 -> CommonTypes<'tcx>
2560 bool: intern_ty(arena, interner, ty_bool),
2561 char: intern_ty(arena, interner, ty_char),
2562 err: intern_ty(arena, interner, ty_err),
2563 isize: intern_ty(arena, interner, ty_int(ast::TyIs)),
2564 i8: intern_ty(arena, interner, ty_int(ast::TyI8)),
2565 i16: intern_ty(arena, interner, ty_int(ast::TyI16)),
2566 i32: intern_ty(arena, interner, ty_int(ast::TyI32)),
2567 i64: intern_ty(arena, interner, ty_int(ast::TyI64)),
2568 usize: intern_ty(arena, interner, ty_uint(ast::TyUs)),
2569 u8: intern_ty(arena, interner, ty_uint(ast::TyU8)),
2570 u16: intern_ty(arena, interner, ty_uint(ast::TyU16)),
2571 u32: intern_ty(arena, interner, ty_uint(ast::TyU32)),
2572 u64: intern_ty(arena, interner, ty_uint(ast::TyU64)),
2573 f32: intern_ty(arena, interner, ty_float(ast::TyF32)),
2574 f64: intern_ty(arena, interner, ty_float(ast::TyF64)),
2579 pub fn mk_ctxt<'tcx>(s: Session,
2580 arenas: &'tcx CtxtArenas<'tcx>,
2582 named_region_map: resolve_lifetime::NamedRegionMap,
2583 map: ast_map::Map<'tcx>,
2584 freevars: RefCell<FreevarMap>,
2585 region_maps: middle::region::RegionMaps,
2586 lang_items: middle::lang_items::LanguageItems,
2587 stability: stability::Index) -> ctxt<'tcx>
2589 let mut interner = FnvHashMap();
2590 let common_types = CommonTypes::new(&arenas.type_, &mut interner);
2594 interner: RefCell::new(interner),
2595 substs_interner: RefCell::new(FnvHashMap()),
2596 bare_fn_interner: RefCell::new(FnvHashMap()),
2597 region_interner: RefCell::new(FnvHashMap()),
2598 types: common_types,
2599 named_region_map: named_region_map,
2600 item_variance_map: RefCell::new(DefIdMap()),
2601 variance_computed: Cell::new(false),
2604 region_maps: region_maps,
2605 node_types: RefCell::new(FnvHashMap()),
2606 item_substs: RefCell::new(NodeMap()),
2607 impl_trait_refs: RefCell::new(NodeMap()),
2608 trait_defs: RefCell::new(DefIdMap()),
2609 predicates: RefCell::new(DefIdMap()),
2610 super_predicates: RefCell::new(DefIdMap()),
2611 object_cast_map: RefCell::new(NodeMap()),
2614 tcache: RefCell::new(DefIdMap()),
2615 rcache: RefCell::new(FnvHashMap()),
2616 short_names_cache: RefCell::new(FnvHashMap()),
2617 tc_cache: RefCell::new(FnvHashMap()),
2618 ast_ty_to_ty_cache: RefCell::new(NodeMap()),
2619 enum_var_cache: RefCell::new(DefIdMap()),
2620 impl_or_trait_items: RefCell::new(DefIdMap()),
2621 trait_item_def_ids: RefCell::new(DefIdMap()),
2622 trait_items_cache: RefCell::new(DefIdMap()),
2623 impl_trait_cache: RefCell::new(DefIdMap()),
2624 ty_param_defs: RefCell::new(NodeMap()),
2625 adjustments: RefCell::new(NodeMap()),
2626 normalized_cache: RefCell::new(FnvHashMap()),
2627 lang_items: lang_items,
2628 provided_method_sources: RefCell::new(DefIdMap()),
2629 struct_fields: RefCell::new(DefIdMap()),
2630 destructor_for_type: RefCell::new(DefIdMap()),
2631 destructors: RefCell::new(DefIdSet()),
2632 trait_impls: RefCell::new(DefIdMap()),
2633 traits_with_default_impls: RefCell::new(DefIdMap()),
2634 inherent_impls: RefCell::new(DefIdMap()),
2635 impl_items: RefCell::new(DefIdMap()),
2636 used_unsafe: RefCell::new(NodeSet()),
2637 used_mut_nodes: RefCell::new(NodeSet()),
2638 populated_external_types: RefCell::new(DefIdSet()),
2639 populated_external_traits: RefCell::new(DefIdSet()),
2640 populated_external_primitive_impls: RefCell::new(DefIdSet()),
2641 upvar_capture_map: RefCell::new(FnvHashMap()),
2642 extern_const_statics: RefCell::new(DefIdMap()),
2643 extern_const_variants: RefCell::new(DefIdMap()),
2644 method_map: RefCell::new(FnvHashMap()),
2645 dependency_formats: RefCell::new(FnvHashMap()),
2646 closure_kinds: RefCell::new(DefIdMap()),
2647 closure_tys: RefCell::new(DefIdMap()),
2648 node_lint_levels: RefCell::new(FnvHashMap()),
2649 transmute_restrictions: RefCell::new(Vec::new()),
2650 stability: RefCell::new(stability),
2651 associated_types: RefCell::new(DefIdMap()),
2652 selection_cache: traits::SelectionCache::new(),
2653 repr_hint_cache: RefCell::new(DefIdMap()),
2654 type_impls_copy_cache: RefCell::new(HashMap::new()),
2655 type_impls_sized_cache: RefCell::new(HashMap::new()),
2656 object_safety_cache: RefCell::new(DefIdMap()),
2657 const_qualif_map: RefCell::new(NodeMap()),
2661 // Type constructors
2663 impl<'tcx> ctxt<'tcx> {
2664 pub fn mk_substs(&self, substs: Substs<'tcx>) -> &'tcx Substs<'tcx> {
2665 if let Some(substs) = self.substs_interner.borrow().get(&substs) {
2669 let substs = self.arenas.substs.alloc(substs);
2670 self.substs_interner.borrow_mut().insert(substs, substs);
2674 /// Create an unsafe fn ty based on a safe fn ty.
2675 pub fn safe_to_unsafe_fn_ty(&self, bare_fn: &BareFnTy<'tcx>) -> Ty<'tcx> {
2676 assert_eq!(bare_fn.unsafety, ast::Unsafety::Normal);
2677 let unsafe_fn_ty_a = self.mk_bare_fn(ty::BareFnTy {
2678 unsafety: ast::Unsafety::Unsafe,
2680 sig: bare_fn.sig.clone()
2682 ty::mk_bare_fn(self, None, unsafe_fn_ty_a)
2685 pub fn mk_bare_fn(&self, bare_fn: BareFnTy<'tcx>) -> &'tcx BareFnTy<'tcx> {
2686 if let Some(bare_fn) = self.bare_fn_interner.borrow().get(&bare_fn) {
2690 let bare_fn = self.arenas.bare_fn.alloc(bare_fn);
2691 self.bare_fn_interner.borrow_mut().insert(bare_fn, bare_fn);
2695 pub fn mk_region(&self, region: Region) -> &'tcx Region {
2696 if let Some(region) = self.region_interner.borrow().get(®ion) {
2700 let region = self.arenas.region.alloc(region);
2701 self.region_interner.borrow_mut().insert(region, region);
2705 pub fn closure_kind(&self, def_id: ast::DefId) -> ty::ClosureKind {
2706 *self.closure_kinds.borrow().get(&def_id).unwrap()
2709 pub fn closure_type(&self,
2711 substs: &subst::Substs<'tcx>)
2712 -> ty::ClosureTy<'tcx>
2714 self.closure_tys.borrow().get(&def_id).unwrap().subst(self, substs)
2717 pub fn type_parameter_def(&self,
2718 node_id: ast::NodeId)
2719 -> TypeParameterDef<'tcx>
2721 self.ty_param_defs.borrow().get(&node_id).unwrap().clone()
2724 pub fn pat_contains_ref_binding(&self, pat: &ast::Pat) -> bool {
2725 pat_util::pat_contains_ref_binding(&self.def_map, pat)
2728 pub fn arm_contains_ref_binding(&self, arm: &ast::Arm) -> bool {
2729 pat_util::arm_contains_ref_binding(&self.def_map, arm)
2733 // Interns a type/name combination, stores the resulting box in cx.interner,
2734 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
2735 pub fn mk_t<'tcx>(cx: &ctxt<'tcx>, st: sty<'tcx>) -> Ty<'tcx> {
2736 let mut interner = cx.interner.borrow_mut();
2737 intern_ty(&cx.arenas.type_, &mut *interner, st)
2740 fn intern_ty<'tcx>(type_arena: &'tcx TypedArena<TyS<'tcx>>,
2741 interner: &mut FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>,
2745 match interner.get(&st) {
2746 Some(ty) => return *ty,
2750 let flags = FlagComputation::for_sty(&st);
2753 () => type_arena.alloc(TyS { sty: st,
2755 region_depth: flags.depth, }),
2758 debug!("Interned type: {:?} Pointer: {:?}",
2759 ty, ty as *const TyS);
2761 interner.insert(InternedTy { ty: ty }, ty);
2766 struct FlagComputation {
2769 // maximum depth of any bound region that we have seen thus far
2773 impl FlagComputation {
2774 fn new() -> FlagComputation {
2775 FlagComputation { flags: NO_TYPE_FLAGS, depth: 0 }
2778 fn for_sty(st: &sty) -> FlagComputation {
2779 let mut result = FlagComputation::new();
2784 fn add_flags(&mut self, flags: TypeFlags) {
2785 self.flags = self.flags | flags;
2788 fn add_depth(&mut self, depth: u32) {
2789 if depth > self.depth {
2794 /// Adds the flags/depth from a set of types that appear within the current type, but within a
2796 fn add_bound_computation(&mut self, computation: &FlagComputation) {
2797 self.add_flags(computation.flags);
2799 // The types that contributed to `computation` occurred within
2800 // a region binder, so subtract one from the region depth
2801 // within when adding the depth to `self`.
2802 let depth = computation.depth;
2804 self.add_depth(depth - 1);
2808 fn add_sty(&mut self, st: &sty) {
2818 // You might think that we could just return ty_err for
2819 // any type containing ty_err as a component, and get
2820 // rid of the HAS_TY_ERR flag -- likewise for ty_bot (with
2821 // the exception of function types that return bot).
2822 // But doing so caused sporadic memory corruption, and
2823 // neither I (tjc) nor nmatsakis could figure out why,
2824 // so we're doing it this way.
2826 self.add_flags(HAS_TY_ERR)
2829 &ty_param(ref p) => {
2830 if p.space == subst::SelfSpace {
2831 self.add_flags(HAS_SELF);
2833 self.add_flags(HAS_PARAMS);
2837 &ty_closure(_, substs) => {
2838 self.add_substs(substs);
2842 self.add_flags(HAS_TY_INFER)
2845 &ty_enum(_, substs) | &ty_struct(_, substs) => {
2846 self.add_substs(substs);
2849 &ty_projection(ref data) => {
2850 self.add_flags(HAS_PROJECTION);
2851 self.add_projection_ty(data);
2854 &ty_trait(box TyTrait { ref principal, ref bounds }) => {
2855 let mut computation = FlagComputation::new();
2856 computation.add_substs(principal.0.substs);
2857 for projection_bound in &bounds.projection_bounds {
2858 let mut proj_computation = FlagComputation::new();
2859 proj_computation.add_projection_predicate(&projection_bound.0);
2860 computation.add_bound_computation(&proj_computation);
2862 self.add_bound_computation(&computation);
2864 self.add_bounds(bounds);
2867 &ty_uniq(tt) | &ty_vec(tt, _) => {
2875 &ty_rptr(r, ref m) => {
2876 self.add_region(*r);
2880 &ty_tup(ref ts) => {
2881 self.add_tys(&ts[..]);
2884 &ty_bare_fn(_, ref f) => {
2885 self.add_fn_sig(&f.sig);
2890 fn add_ty(&mut self, ty: Ty) {
2891 self.add_flags(ty.flags);
2892 self.add_depth(ty.region_depth);
2895 fn add_tys(&mut self, tys: &[Ty]) {
2901 fn add_fn_sig(&mut self, fn_sig: &PolyFnSig) {
2902 let mut computation = FlagComputation::new();
2904 computation.add_tys(&fn_sig.0.inputs);
2906 if let ty::FnConverging(output) = fn_sig.0.output {
2907 computation.add_ty(output);
2910 self.add_bound_computation(&computation);
2913 fn add_region(&mut self, r: Region) {
2914 self.add_flags(HAS_REGIONS);
2916 ty::ReInfer(_) => { self.add_flags(HAS_RE_INFER); }
2917 ty::ReLateBound(debruijn, _) => {
2918 self.add_flags(HAS_RE_LATE_BOUND);
2919 self.add_depth(debruijn.depth);
2925 fn add_projection_predicate(&mut self, projection_predicate: &ProjectionPredicate) {
2926 self.add_projection_ty(&projection_predicate.projection_ty);
2927 self.add_ty(projection_predicate.ty);
2930 fn add_projection_ty(&mut self, projection_ty: &ProjectionTy) {
2931 self.add_substs(projection_ty.trait_ref.substs);
2934 fn add_substs(&mut self, substs: &Substs) {
2935 self.add_tys(substs.types.as_slice());
2936 match substs.regions {
2937 subst::ErasedRegions => {}
2938 subst::NonerasedRegions(ref regions) => {
2939 for &r in regions.iter() {
2946 fn add_bounds(&mut self, bounds: &ExistentialBounds) {
2947 self.add_region(bounds.region_bound);
2951 pub fn mk_mach_int<'tcx>(tcx: &ctxt<'tcx>, tm: ast::IntTy) -> Ty<'tcx> {
2953 ast::TyIs => tcx.types.isize,
2954 ast::TyI8 => tcx.types.i8,
2955 ast::TyI16 => tcx.types.i16,
2956 ast::TyI32 => tcx.types.i32,
2957 ast::TyI64 => tcx.types.i64,
2961 pub fn mk_mach_uint<'tcx>(tcx: &ctxt<'tcx>, tm: ast::UintTy) -> Ty<'tcx> {
2963 ast::TyUs => tcx.types.usize,
2964 ast::TyU8 => tcx.types.u8,
2965 ast::TyU16 => tcx.types.u16,
2966 ast::TyU32 => tcx.types.u32,
2967 ast::TyU64 => tcx.types.u64,
2971 pub fn mk_mach_float<'tcx>(tcx: &ctxt<'tcx>, tm: ast::FloatTy) -> Ty<'tcx> {
2973 ast::TyF32 => tcx.types.f32,
2974 ast::TyF64 => tcx.types.f64,
2978 pub fn mk_str<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2982 pub fn mk_str_slice<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, m: ast::Mutability) -> Ty<'tcx> {
2985 ty: mk_t(cx, ty_str),
2990 pub fn mk_enum<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
2991 // take a copy of substs so that we own the vectors inside
2992 mk_t(cx, ty_enum(did, substs))
2995 pub fn mk_uniq<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { mk_t(cx, ty_uniq(ty)) }
2997 pub fn mk_ptr<'tcx>(cx: &ctxt<'tcx>, tm: mt<'tcx>) -> Ty<'tcx> { mk_t(cx, ty_ptr(tm)) }
2999 pub fn mk_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, tm: mt<'tcx>) -> Ty<'tcx> {
3000 mk_t(cx, ty_rptr(r, tm))
3003 pub fn mk_mut_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
3004 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
3006 pub fn mk_imm_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
3007 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
3010 pub fn mk_mut_ptr<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
3011 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
3014 pub fn mk_imm_ptr<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
3015 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
3018 pub fn mk_nil_ptr<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
3019 mk_ptr(cx, mt {ty: mk_nil(cx), mutbl: ast::MutImmutable})
3022 pub fn mk_vec<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>, sz: Option<usize>) -> Ty<'tcx> {
3023 mk_t(cx, ty_vec(ty, sz))
3026 pub fn mk_slice<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, tm: mt<'tcx>) -> Ty<'tcx> {
3029 ty: mk_vec(cx, tm.ty, None),
3034 pub fn mk_tup<'tcx>(cx: &ctxt<'tcx>, ts: Vec<Ty<'tcx>>) -> Ty<'tcx> {
3035 mk_t(cx, ty_tup(ts))
3038 pub fn mk_nil<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
3039 mk_tup(cx, Vec::new())
3042 pub fn mk_bool<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
3046 pub fn mk_bare_fn<'tcx>(cx: &ctxt<'tcx>,
3047 opt_def_id: Option<ast::DefId>,
3048 fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
3049 mk_t(cx, ty_bare_fn(opt_def_id, fty))
3052 pub fn mk_ctor_fn<'tcx>(cx: &ctxt<'tcx>,
3054 input_tys: &[Ty<'tcx>],
3055 output: Ty<'tcx>) -> Ty<'tcx> {
3056 let input_args = input_tys.iter().cloned().collect();
3059 cx.mk_bare_fn(BareFnTy {
3060 unsafety: ast::Unsafety::Normal,
3062 sig: ty::Binder(FnSig {
3064 output: ty::FnConverging(output),
3070 pub fn mk_trait<'tcx>(cx: &ctxt<'tcx>,
3071 principal: ty::PolyTraitRef<'tcx>,
3072 bounds: ExistentialBounds<'tcx>)
3075 assert!(bound_list_is_sorted(&bounds.projection_bounds));
3077 let inner = box TyTrait {
3078 principal: principal,
3081 mk_t(cx, ty_trait(inner))
3084 fn bound_list_is_sorted(bounds: &[ty::PolyProjectionPredicate]) -> bool {
3085 bounds.len() == 0 ||
3086 bounds[1..].iter().enumerate().all(
3087 |(index, bound)| bounds[index].sort_key() <= bound.sort_key())
3090 pub fn sort_bounds_list(bounds: &mut [ty::PolyProjectionPredicate]) {
3091 bounds.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()))
3094 pub fn mk_projection<'tcx>(cx: &ctxt<'tcx>,
3095 trait_ref: Rc<ty::TraitRef<'tcx>>,
3096 item_name: ast::Name)
3098 // take a copy of substs so that we own the vectors inside
3099 let inner = ProjectionTy { trait_ref: trait_ref, item_name: item_name };
3100 mk_t(cx, ty_projection(inner))
3103 pub fn mk_struct<'tcx>(cx: &ctxt<'tcx>, struct_id: ast::DefId,
3104 substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
3105 // take a copy of substs so that we own the vectors inside
3106 mk_t(cx, ty_struct(struct_id, substs))
3109 pub fn mk_closure<'tcx>(cx: &ctxt<'tcx>, closure_id: ast::DefId, substs: &'tcx Substs<'tcx>)
3111 mk_t(cx, ty_closure(closure_id, substs))
3114 pub fn mk_var<'tcx>(cx: &ctxt<'tcx>, v: TyVid) -> Ty<'tcx> {
3115 mk_infer(cx, TyVar(v))
3118 pub fn mk_int_var<'tcx>(cx: &ctxt<'tcx>, v: IntVid) -> Ty<'tcx> {
3119 mk_infer(cx, IntVar(v))
3122 pub fn mk_float_var<'tcx>(cx: &ctxt<'tcx>, v: FloatVid) -> Ty<'tcx> {
3123 mk_infer(cx, FloatVar(v))
3126 pub fn mk_infer<'tcx>(cx: &ctxt<'tcx>, it: InferTy) -> Ty<'tcx> {
3127 mk_t(cx, ty_infer(it))
3130 pub fn mk_param<'tcx>(cx: &ctxt<'tcx>,
3131 space: subst::ParamSpace,
3133 name: ast::Name) -> Ty<'tcx> {
3134 mk_t(cx, ty_param(ParamTy { space: space, idx: index, name: name }))
3137 pub fn mk_self_type<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
3138 mk_param(cx, subst::SelfSpace, 0, special_idents::type_self.name)
3141 pub fn mk_param_from_def<'tcx>(cx: &ctxt<'tcx>, def: &TypeParameterDef) -> Ty<'tcx> {
3142 mk_param(cx, def.space, def.index, def.name)
3145 impl<'tcx> TyS<'tcx> {
3146 /// Iterator that walks `self` and any types reachable from
3147 /// `self`, in depth-first order. Note that just walks the types
3148 /// that appear in `self`, it does not descend into the fields of
3149 /// structs or variants. For example:
3152 /// isize => { isize }
3153 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
3154 /// [isize] => { [isize], isize }
3156 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
3157 TypeWalker::new(self)
3160 /// Iterator that walks types reachable from `self`, in
3161 /// depth-first order. Note that this is a shallow walk. For
3166 /// Foo<Bar<isize>> => { Bar<isize>, isize }
3167 /// [isize] => { isize }
3169 pub fn walk_children(&'tcx self) -> TypeWalker<'tcx> {
3170 // Walks type reachable from `self` but not `self
3171 let mut walker = self.walk();
3172 let r = walker.next();
3173 assert_eq!(r, Some(self));
3177 pub fn as_opt_param_ty(&self) -> Option<ty::ParamTy> {
3179 ty::ty_param(ref d) => Some(d.clone()),
3184 pub fn is_param(&self, space: ParamSpace, index: u32) -> bool {
3186 ty::ty_param(ref data) => data.space == space && data.idx == index,
3192 pub fn walk_ty<'tcx, F>(ty_root: Ty<'tcx>, mut f: F)
3193 where F: FnMut(Ty<'tcx>),
3195 for ty in ty_root.walk() {
3200 /// Walks `ty` and any types appearing within `ty`, invoking the
3201 /// callback `f` on each type. If the callback returns false, then the
3202 /// children of the current type are ignored.
3204 /// Note: prefer `ty.walk()` where possible.
3205 pub fn maybe_walk_ty<'tcx,F>(ty_root: Ty<'tcx>, mut f: F)
3206 where F : FnMut(Ty<'tcx>) -> bool
3208 let mut walker = ty_root.walk();
3209 while let Some(ty) = walker.next() {
3211 walker.skip_current_subtree();
3216 // Folds types from the bottom up.
3217 pub fn fold_ty<'tcx, F>(cx: &ctxt<'tcx>, t0: Ty<'tcx>,
3220 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
3222 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
3227 pub fn new(space: subst::ParamSpace,
3231 ParamTy { space: space, idx: index, name: name }
3234 pub fn for_self() -> ParamTy {
3235 ParamTy::new(subst::SelfSpace, 0, special_idents::type_self.name)
3238 pub fn for_def(def: &TypeParameterDef) -> ParamTy {
3239 ParamTy::new(def.space, def.index, def.name)
3242 pub fn to_ty<'tcx>(self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx> {
3243 ty::mk_param(tcx, self.space, self.idx, self.name)
3246 pub fn is_self(&self) -> bool {
3247 self.space == subst::SelfSpace && self.idx == 0
3251 impl<'tcx> ItemSubsts<'tcx> {
3252 pub fn empty() -> ItemSubsts<'tcx> {
3253 ItemSubsts { substs: Substs::empty() }
3256 pub fn is_noop(&self) -> bool {
3257 self.substs.is_noop()
3261 impl<'tcx> ParamBounds<'tcx> {
3262 pub fn empty() -> ParamBounds<'tcx> {
3264 builtin_bounds: empty_builtin_bounds(),
3265 trait_bounds: Vec::new(),
3266 region_bounds: Vec::new(),
3267 projection_bounds: Vec::new(),
3274 pub fn type_is_nil(ty: Ty) -> bool {
3276 ty_tup(ref tys) => tys.is_empty(),
3281 pub fn type_is_error(ty: Ty) -> bool {
3282 ty.flags.intersects(HAS_TY_ERR)
3285 pub fn type_needs_subst(ty: Ty) -> bool {
3286 ty.flags.intersects(NEEDS_SUBST)
3289 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
3290 tref.substs.types.any(|&ty| type_is_error(ty))
3293 pub fn type_is_ty_var(ty: Ty) -> bool {
3295 ty_infer(TyVar(_)) => true,
3300 pub fn type_is_bool(ty: Ty) -> bool { ty.sty == ty_bool }
3302 pub fn type_is_self(ty: Ty) -> bool {
3304 ty_param(ref p) => p.space == subst::SelfSpace,
3309 fn type_is_slice(ty: Ty) -> bool {
3311 ty_ptr(mt) | ty_rptr(_, mt) => match mt.ty.sty {
3312 ty_vec(_, None) | ty_str => true,
3319 pub fn type_is_vec(ty: Ty) -> bool {
3322 ty_ptr(mt{ty, ..}) | ty_rptr(_, mt{ty, ..}) |
3323 ty_uniq(ty) => match ty.sty {
3324 ty_vec(_, None) => true,
3331 pub fn type_is_structural(ty: Ty) -> bool {
3333 ty_struct(..) | ty_tup(_) | ty_enum(..) |
3334 ty_vec(_, Some(_)) | ty_closure(..) => true,
3335 _ => type_is_slice(ty) | type_is_trait(ty)
3339 pub fn type_is_simd(cx: &ctxt, ty: Ty) -> bool {
3341 ty_struct(did, _) => lookup_simd(cx, did),
3346 pub fn sequence_element_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
3348 ty_vec(ty, _) => ty,
3349 ty_str => mk_mach_uint(cx, ast::TyU8),
3350 _ => cx.sess.bug(&format!("sequence_element_type called on non-sequence value: {}",
3351 ty_to_string(cx, ty))),
3355 pub fn simd_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
3357 ty_struct(did, substs) => {
3358 let fields = lookup_struct_fields(cx, did);
3359 lookup_field_type(cx, did, fields[0].id, substs)
3361 _ => panic!("simd_type called on invalid type")
3365 pub fn simd_size(cx: &ctxt, ty: Ty) -> usize {
3367 ty_struct(did, _) => {
3368 let fields = lookup_struct_fields(cx, did);
3371 _ => panic!("simd_size called on invalid type")
3375 pub fn type_is_region_ptr(ty: Ty) -> bool {
3377 ty_rptr(..) => true,
3382 pub fn type_is_unsafe_ptr(ty: Ty) -> bool {
3384 ty_ptr(_) => return true,
3389 pub fn type_is_unique(ty: Ty) -> bool {
3397 A scalar type is one that denotes an atomic datum, with no sub-components.
3398 (A ty_ptr is scalar because it represents a non-managed pointer, so its
3399 contents are abstract to rustc.)
3401 pub fn type_is_scalar(ty: Ty) -> bool {
3403 ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
3404 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
3405 ty_bare_fn(..) | ty_ptr(_) => true,
3410 /// Returns true if this type is a floating point type and false otherwise.
3411 pub fn type_is_floating_point(ty: Ty) -> bool {
3414 ty_infer(FloatVar(_)) =>
3422 /// Type contents is how the type checker reasons about kinds.
3423 /// They track what kinds of things are found within a type. You can
3424 /// think of them as kind of an "anti-kind". They track the kinds of values
3425 /// and thinks that are contained in types. Having a larger contents for
3426 /// a type tends to rule that type *out* from various kinds. For example,
3427 /// a type that contains a reference is not sendable.
3429 /// The reason we compute type contents and not kinds is that it is
3430 /// easier for me (nmatsakis) to think about what is contained within
3431 /// a type than to think about what is *not* contained within a type.
3432 #[derive(Clone, Copy)]
3433 pub struct TypeContents {
3437 macro_rules! def_type_content_sets {
3438 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
3439 #[allow(non_snake_case)]
3441 use middle::ty::TypeContents;
3443 #[allow(non_upper_case_globals)]
3444 pub const $name: TypeContents = TypeContents { bits: $bits };
3450 def_type_content_sets! {
3452 None = 0b0000_0000__0000_0000__0000,
3454 // Things that are interior to the value (first nibble):
3455 InteriorUnsized = 0b0000_0000__0000_0000__0001,
3456 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
3457 InteriorParam = 0b0000_0000__0000_0000__0100,
3458 // InteriorAll = 0b00000000__00000000__1111,
3460 // Things that are owned by the value (second and third nibbles):
3461 OwnsOwned = 0b0000_0000__0000_0001__0000,
3462 OwnsDtor = 0b0000_0000__0000_0010__0000,
3463 OwnsManaged /* see [1] below */ = 0b0000_0000__0000_0100__0000,
3464 OwnsAll = 0b0000_0000__1111_1111__0000,
3466 // Things that are reachable by the value in any way (fourth nibble):
3467 ReachesBorrowed = 0b0000_0010__0000_0000__0000,
3468 // ReachesManaged /* see [1] below */ = 0b0000_0100__0000_0000__0000,
3469 ReachesMutable = 0b0000_1000__0000_0000__0000,
3470 ReachesFfiUnsafe = 0b0010_0000__0000_0000__0000,
3471 ReachesAll = 0b0011_1111__0000_0000__0000,
3473 // Things that mean drop glue is necessary
3474 NeedsDrop = 0b0000_0000__0000_0111__0000,
3476 // Things that prevent values from being considered sized
3477 Nonsized = 0b0000_0000__0000_0000__0001,
3479 // Bits to set when a managed value is encountered
3481 // [1] Do not set the bits TC::OwnsManaged or
3482 // TC::ReachesManaged directly, instead reference
3483 // TC::Managed to set them both at once.
3484 Managed = 0b0000_0100__0000_0100__0000,
3487 All = 0b1111_1111__1111_1111__1111
3492 pub fn when(&self, cond: bool) -> TypeContents {
3493 if cond {*self} else {TC::None}
3496 pub fn intersects(&self, tc: TypeContents) -> bool {
3497 (self.bits & tc.bits) != 0
3500 pub fn owns_managed(&self) -> bool {
3501 self.intersects(TC::OwnsManaged)
3504 pub fn owns_owned(&self) -> bool {
3505 self.intersects(TC::OwnsOwned)
3508 pub fn is_sized(&self, _: &ctxt) -> bool {
3509 !self.intersects(TC::Nonsized)
3512 pub fn interior_param(&self) -> bool {
3513 self.intersects(TC::InteriorParam)
3516 pub fn interior_unsafe(&self) -> bool {
3517 self.intersects(TC::InteriorUnsafe)
3520 pub fn interior_unsized(&self) -> bool {
3521 self.intersects(TC::InteriorUnsized)
3524 pub fn needs_drop(&self, _: &ctxt) -> bool {
3525 self.intersects(TC::NeedsDrop)
3528 /// Includes only those bits that still apply when indirected through a `Box` pointer
3529 pub fn owned_pointer(&self) -> TypeContents {
3531 *self & (TC::OwnsAll | TC::ReachesAll))
3534 /// Includes only those bits that still apply when indirected through a reference (`&`)
3535 pub fn reference(&self, bits: TypeContents) -> TypeContents {
3537 *self & TC::ReachesAll)
3540 /// Includes only those bits that still apply when indirected through a managed pointer (`@`)
3541 pub fn managed_pointer(&self) -> TypeContents {
3543 *self & TC::ReachesAll)
3546 /// Includes only those bits that still apply when indirected through an unsafe pointer (`*`)
3547 pub fn unsafe_pointer(&self) -> TypeContents {
3548 *self & TC::ReachesAll
3551 pub fn union<T, F>(v: &[T], mut f: F) -> TypeContents where
3552 F: FnMut(&T) -> TypeContents,
3554 v.iter().fold(TC::None, |tc, ty| tc | f(ty))
3557 pub fn has_dtor(&self) -> bool {
3558 self.intersects(TC::OwnsDtor)
3562 impl ops::BitOr for TypeContents {
3563 type Output = TypeContents;
3565 fn bitor(self, other: TypeContents) -> TypeContents {
3566 TypeContents {bits: self.bits | other.bits}
3570 impl ops::BitAnd for TypeContents {
3571 type Output = TypeContents;
3573 fn bitand(self, other: TypeContents) -> TypeContents {
3574 TypeContents {bits: self.bits & other.bits}
3578 impl ops::Sub for TypeContents {
3579 type Output = TypeContents;
3581 fn sub(self, other: TypeContents) -> TypeContents {
3582 TypeContents {bits: self.bits & !other.bits}
3586 impl fmt::Debug for TypeContents {
3587 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3588 write!(f, "TypeContents({:b})", self.bits)
3592 pub fn type_interior_is_unsafe<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
3593 type_contents(cx, ty).interior_unsafe()
3596 pub fn type_contents<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> TypeContents {
3597 return memoized(&cx.tc_cache, ty, |ty| {
3598 tc_ty(cx, ty, &mut FnvHashMap())
3601 fn tc_ty<'tcx>(cx: &ctxt<'tcx>,
3603 cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
3605 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
3606 // private cache for this walk. This is needed in the case of cyclic
3609 // struct List { next: Box<Option<List>>, ... }
3611 // When computing the type contents of such a type, we wind up deeply
3612 // recursing as we go. So when we encounter the recursive reference
3613 // to List, we temporarily use TC::None as its contents. Later we'll
3614 // patch up the cache with the correct value, once we've computed it
3615 // (this is basically a co-inductive process, if that helps). So in
3616 // the end we'll compute TC::OwnsOwned, in this case.
3618 // The problem is, as we are doing the computation, we will also
3619 // compute an *intermediate* contents for, e.g., Option<List> of
3620 // TC::None. This is ok during the computation of List itself, but if
3621 // we stored this intermediate value into cx.tc_cache, then later
3622 // requests for the contents of Option<List> would also yield TC::None
3623 // which is incorrect. This value was computed based on the crutch
3624 // value for the type contents of list. The correct value is
3625 // TC::OwnsOwned. This manifested as issue #4821.
3626 match cache.get(&ty) {
3627 Some(tc) => { return *tc; }
3630 match cx.tc_cache.borrow().get(&ty) { // Must check both caches!
3631 Some(tc) => { return *tc; }
3634 cache.insert(ty, TC::None);
3636 let result = match ty.sty {
3637 // usize and isize are ffi-unsafe
3638 ty_uint(ast::TyUs) | ty_int(ast::TyIs) => {
3639 TC::ReachesFfiUnsafe
3642 // Scalar and unique types are sendable, and durable
3643 ty_infer(ty::FreshIntTy(_)) |
3644 ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
3645 ty_bare_fn(..) | ty::ty_char => {
3650 TC::ReachesFfiUnsafe | match typ.sty {
3651 ty_str => TC::OwnsOwned,
3652 _ => tc_ty(cx, typ, cache).owned_pointer(),
3656 ty_trait(box TyTrait { ref bounds, .. }) => {
3657 object_contents(bounds) | TC::ReachesFfiUnsafe | TC::Nonsized
3661 tc_ty(cx, mt.ty, cache).unsafe_pointer()
3664 ty_rptr(r, ref mt) => {
3665 TC::ReachesFfiUnsafe | match mt.ty.sty {
3666 ty_str => borrowed_contents(*r, ast::MutImmutable),
3667 ty_vec(..) => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(*r,
3669 _ => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(*r, mt.mutbl)),
3673 ty_vec(ty, Some(_)) => {
3674 tc_ty(cx, ty, cache)
3677 ty_vec(ty, None) => {
3678 tc_ty(cx, ty, cache) | TC::Nonsized
3680 ty_str => TC::Nonsized,
3682 ty_struct(did, substs) => {
3683 let flds = struct_fields(cx, did, substs);
3685 TypeContents::union(&flds[..],
3686 |f| tc_mt(cx, f.mt, cache));
3688 if !lookup_repr_hints(cx, did).contains(&attr::ReprExtern) {
3689 res = res | TC::ReachesFfiUnsafe;
3692 if ty::has_dtor(cx, did) {
3693 res = res | TC::OwnsDtor;
3695 apply_lang_items(cx, did, res)
3698 ty_closure(did, substs) => {
3699 // FIXME(#14449): `borrowed_contents` below assumes `&mut` closure.
3700 let param_env = ty::empty_parameter_environment(cx);
3701 let upvars = closure_upvars(¶m_env, did, substs).unwrap();
3702 TypeContents::union(&upvars, |f| tc_ty(cx, &f.ty, cache))
3705 ty_tup(ref tys) => {
3706 TypeContents::union(&tys[..],
3707 |ty| tc_ty(cx, *ty, cache))
3710 ty_enum(did, substs) => {
3711 let variants = substd_enum_variants(cx, did, substs);
3713 TypeContents::union(&variants[..], |variant| {
3714 TypeContents::union(&variant.args,
3716 tc_ty(cx, *arg_ty, cache)
3720 if ty::has_dtor(cx, did) {
3721 res = res | TC::OwnsDtor;
3724 if variants.len() != 0 {
3725 let repr_hints = lookup_repr_hints(cx, did);
3726 if repr_hints.len() > 1 {
3727 // this is an error later on, but this type isn't safe
3728 res = res | TC::ReachesFfiUnsafe;
3731 match repr_hints.get(0) {
3732 Some(h) => if !h.is_ffi_safe() {
3733 res = res | TC::ReachesFfiUnsafe;
3737 res = res | TC::ReachesFfiUnsafe;
3739 // We allow ReprAny enums if they are eligible for
3740 // the nullable pointer optimization and the
3741 // contained type is an `extern fn`
3743 if variants.len() == 2 {
3744 let mut data_idx = 0;
3746 if variants[0].args.len() == 0 {
3750 if variants[data_idx].args.len() == 1 {
3751 match variants[data_idx].args[0].sty {
3752 ty_bare_fn(..) => { res = res - TC::ReachesFfiUnsafe; }
3762 apply_lang_items(cx, did, res)
3772 cx.sess.bug("asked to compute contents of error type");
3776 cache.insert(ty, result);
3780 fn tc_mt<'tcx>(cx: &ctxt<'tcx>,
3782 cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
3784 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
3785 mc | tc_ty(cx, mt.ty, cache)
3788 fn apply_lang_items(cx: &ctxt, did: ast::DefId, tc: TypeContents)
3790 if Some(did) == cx.lang_items.managed_bound() {
3792 } else if Some(did) == cx.lang_items.unsafe_cell_type() {
3793 tc | TC::InteriorUnsafe
3799 /// Type contents due to containing a reference with the region `region` and borrow kind `bk`
3800 fn borrowed_contents(region: ty::Region,
3801 mutbl: ast::Mutability)
3803 let b = match mutbl {
3804 ast::MutMutable => TC::ReachesMutable,
3805 ast::MutImmutable => TC::None,
3807 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
3810 fn object_contents(bounds: &ExistentialBounds) -> TypeContents {
3811 // These are the type contents of the (opaque) interior. We
3812 // make no assumptions (other than that it cannot have an
3813 // in-scope type parameter within, which makes no sense).
3814 let mut tc = TC::All - TC::InteriorParam;
3815 for bound in &bounds.builtin_bounds {
3816 tc = tc - match bound {
3817 BoundSync | BoundSend | BoundCopy => TC::None,
3818 BoundSized => TC::Nonsized,
3825 fn type_impls_bound<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>,
3826 cache: &RefCell<HashMap<Ty<'tcx>,bool>>,
3828 bound: ty::BuiltinBound,
3832 assert!(!ty::type_needs_infer(ty));
3834 if !type_has_params(ty) && !type_has_self(ty) {
3835 match cache.borrow().get(&ty) {
3838 debug!("type_impls_bound({}, {:?}) = {:?} (cached)",
3839 ty.repr(param_env.tcx),
3847 let infcx = infer::new_infer_ctxt(param_env.tcx);
3849 let is_impld = traits::type_known_to_meet_builtin_bound(&infcx, param_env, ty, bound, span);
3851 debug!("type_impls_bound({}, {:?}) = {:?}",
3852 ty.repr(param_env.tcx),
3856 if !type_has_params(ty) && !type_has_self(ty) {
3857 let old_value = cache.borrow_mut().insert(ty, is_impld);
3858 assert!(old_value.is_none());
3864 pub fn type_moves_by_default<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>,
3869 let tcx = param_env.tcx;
3870 !type_impls_bound(param_env, &tcx.type_impls_copy_cache, ty, ty::BoundCopy, span)
3873 pub fn type_is_sized<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>,
3878 let tcx = param_env.tcx;
3879 type_impls_bound(param_env, &tcx.type_impls_sized_cache, ty, ty::BoundSized, span)
3882 pub fn is_ffi_safe<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
3883 !type_contents(cx, ty).intersects(TC::ReachesFfiUnsafe)
3886 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
3887 pub fn is_instantiable<'tcx>(cx: &ctxt<'tcx>, r_ty: Ty<'tcx>) -> bool {
3888 fn type_requires<'tcx>(cx: &ctxt<'tcx>, seen: &mut Vec<DefId>,
3889 r_ty: Ty<'tcx>, ty: Ty<'tcx>) -> bool {
3890 debug!("type_requires({:?}, {:?})?",
3891 ::util::ppaux::ty_to_string(cx, r_ty),
3892 ::util::ppaux::ty_to_string(cx, ty));
3894 let r = r_ty == ty || subtypes_require(cx, seen, r_ty, ty);
3896 debug!("type_requires({:?}, {:?})? {:?}",
3897 ::util::ppaux::ty_to_string(cx, r_ty),
3898 ::util::ppaux::ty_to_string(cx, ty),
3903 fn subtypes_require<'tcx>(cx: &ctxt<'tcx>, seen: &mut Vec<DefId>,
3904 r_ty: Ty<'tcx>, ty: Ty<'tcx>) -> bool {
3905 debug!("subtypes_require({:?}, {:?})?",
3906 ::util::ppaux::ty_to_string(cx, r_ty),
3907 ::util::ppaux::ty_to_string(cx, ty));
3909 let r = match ty.sty {
3910 // fixed length vectors need special treatment compared to
3911 // normal vectors, since they don't necessarily have the
3912 // possibility to have length zero.
3913 ty_vec(_, Some(0)) => false, // don't need no contents
3914 ty_vec(ty, Some(_)) => type_requires(cx, seen, r_ty, ty),
3925 ty_vec(_, None) => {
3929 type_requires(cx, seen, r_ty, typ)
3931 ty_rptr(_, ref mt) => {
3932 type_requires(cx, seen, r_ty, mt.ty)
3936 false // unsafe ptrs can always be NULL
3943 ty_struct(ref did, _) if seen.contains(did) => {
3947 ty_struct(did, substs) => {
3949 let fields = struct_fields(cx, did, substs);
3950 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
3951 seen.pop().unwrap();
3958 // this check is run on type definitions, so we don't expect to see
3959 // inference by-products or closure types
3960 cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
3964 ts.iter().any(|ty| type_requires(cx, seen, r_ty, *ty))
3967 ty_enum(ref did, _) if seen.contains(did) => {
3971 ty_enum(did, substs) => {
3973 let vs = enum_variants(cx, did);
3974 let r = !vs.is_empty() && vs.iter().all(|variant| {
3975 variant.args.iter().any(|aty| {
3976 let sty = aty.subst(cx, substs);
3977 type_requires(cx, seen, r_ty, sty)
3980 seen.pop().unwrap();
3985 debug!("subtypes_require({:?}, {:?})? {:?}",
3986 ::util::ppaux::ty_to_string(cx, r_ty),
3987 ::util::ppaux::ty_to_string(cx, ty),
3993 let mut seen = Vec::new();
3994 !subtypes_require(cx, &mut seen, r_ty, r_ty)
3997 /// Describes whether a type is representable. For types that are not
3998 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
3999 /// distinguish between types that are recursive with themselves and types that
4000 /// contain a different recursive type. These cases can therefore be treated
4001 /// differently when reporting errors.
4003 /// The ordering of the cases is significant. They are sorted so that cmp::max
4004 /// will keep the "more erroneous" of two values.
4005 #[derive(Copy, PartialOrd, Ord, Eq, PartialEq, Debug)]
4006 pub enum Representability {
4012 /// Check whether a type is representable. This means it cannot contain unboxed
4013 /// structural recursion. This check is needed for structs and enums.
4014 pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>)
4015 -> Representability {
4017 // Iterate until something non-representable is found
4018 fn find_nonrepresentable<'tcx, It: Iterator<Item=Ty<'tcx>>>(cx: &ctxt<'tcx>, sp: Span,
4019 seen: &mut Vec<Ty<'tcx>>,
4021 -> Representability {
4022 iter.fold(Representable,
4023 |r, ty| cmp::max(r, is_type_structurally_recursive(cx, sp, seen, ty)))
4026 fn are_inner_types_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
4027 seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
4028 -> Representability {
4031 find_nonrepresentable(cx, sp, seen, ts.iter().cloned())
4033 // Fixed-length vectors.
4034 // FIXME(#11924) Behavior undecided for zero-length vectors.
4035 ty_vec(ty, Some(_)) => {
4036 is_type_structurally_recursive(cx, sp, seen, ty)
4038 ty_struct(did, substs) => {
4039 let fields = struct_fields(cx, did, substs);
4040 find_nonrepresentable(cx, sp, seen, fields.iter().map(|f| f.mt.ty))
4042 ty_enum(did, substs) => {
4043 let vs = enum_variants(cx, did);
4044 let iter = vs.iter()
4045 .flat_map(|variant| { variant.args.iter() })
4046 .map(|aty| { aty.subst_spanned(cx, substs, Some(sp)) });
4048 find_nonrepresentable(cx, sp, seen, iter)
4051 // this check is run on type definitions, so we don't expect
4052 // to see closure types
4053 cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
4059 fn same_struct_or_enum_def_id(ty: Ty, did: DefId) -> bool {
4061 ty_struct(ty_did, _) | ty_enum(ty_did, _) => {
4068 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
4069 match (&a.sty, &b.sty) {
4070 (&ty_struct(did_a, ref substs_a), &ty_struct(did_b, ref substs_b)) |
4071 (&ty_enum(did_a, ref substs_a), &ty_enum(did_b, ref substs_b)) => {
4076 let types_a = substs_a.types.get_slice(subst::TypeSpace);
4077 let types_b = substs_b.types.get_slice(subst::TypeSpace);
4079 let mut pairs = types_a.iter().zip(types_b.iter());
4081 pairs.all(|(&a, &b)| same_type(a, b))
4089 // Does the type `ty` directly (without indirection through a pointer)
4090 // contain any types on stack `seen`?
4091 fn is_type_structurally_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
4092 seen: &mut Vec<Ty<'tcx>>,
4093 ty: Ty<'tcx>) -> Representability {
4094 debug!("is_type_structurally_recursive: {:?}",
4095 ::util::ppaux::ty_to_string(cx, ty));
4098 ty_struct(did, _) | ty_enum(did, _) => {
4100 // Iterate through stack of previously seen types.
4101 let mut iter = seen.iter();
4103 // The first item in `seen` is the type we are actually curious about.
4104 // We want to return SelfRecursive if this type contains itself.
4105 // It is important that we DON'T take generic parameters into account
4106 // for this check, so that Bar<T> in this example counts as SelfRecursive:
4109 // struct Bar<T> { x: Bar<Foo> }
4112 Some(&seen_type) => {
4113 if same_struct_or_enum_def_id(seen_type, did) {
4114 debug!("SelfRecursive: {:?} contains {:?}",
4115 ::util::ppaux::ty_to_string(cx, seen_type),
4116 ::util::ppaux::ty_to_string(cx, ty));
4117 return SelfRecursive;
4123 // We also need to know whether the first item contains other types that
4124 // are structurally recursive. If we don't catch this case, we will recurse
4125 // infinitely for some inputs.
4127 // It is important that we DO take generic parameters into account here,
4128 // so that code like this is considered SelfRecursive, not ContainsRecursive:
4130 // struct Foo { Option<Option<Foo>> }
4132 for &seen_type in iter {
4133 if same_type(ty, seen_type) {
4134 debug!("ContainsRecursive: {:?} contains {:?}",
4135 ::util::ppaux::ty_to_string(cx, seen_type),
4136 ::util::ppaux::ty_to_string(cx, ty));
4137 return ContainsRecursive;
4142 // For structs and enums, track all previously seen types by pushing them
4143 // onto the 'seen' stack.
4145 let out = are_inner_types_recursive(cx, sp, seen, ty);
4150 // No need to push in other cases.
4151 are_inner_types_recursive(cx, sp, seen, ty)
4156 debug!("is_type_representable: {:?}",
4157 ::util::ppaux::ty_to_string(cx, ty));
4159 // To avoid a stack overflow when checking an enum variant or struct that
4160 // contains a different, structurally recursive type, maintain a stack
4161 // of seen types and check recursion for each of them (issues #3008, #3779).
4162 let mut seen: Vec<Ty> = Vec::new();
4163 let r = is_type_structurally_recursive(cx, sp, &mut seen, ty);
4164 debug!("is_type_representable: {:?} is {:?}",
4165 ::util::ppaux::ty_to_string(cx, ty), r);
4169 pub fn type_is_trait(ty: Ty) -> bool {
4170 type_trait_info(ty).is_some()
4173 pub fn type_trait_info<'tcx>(ty: Ty<'tcx>) -> Option<&'tcx TyTrait<'tcx>> {
4175 ty_uniq(ty) | ty_rptr(_, mt { ty, ..}) | ty_ptr(mt { ty, ..}) => match ty.sty {
4176 ty_trait(ref t) => Some(&**t),
4179 ty_trait(ref t) => Some(&**t),
4184 pub fn type_is_integral(ty: Ty) -> bool {
4186 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
4191 pub fn type_is_fresh(ty: Ty) -> bool {
4193 ty_infer(FreshTy(_)) => true,
4194 ty_infer(FreshIntTy(_)) => true,
4199 pub fn type_is_uint(ty: Ty) -> bool {
4201 ty_infer(IntVar(_)) | ty_uint(ast::TyUs) => true,
4206 pub fn type_is_char(ty: Ty) -> bool {
4213 pub fn type_is_bare_fn(ty: Ty) -> bool {
4215 ty_bare_fn(..) => true,
4220 pub fn type_is_bare_fn_item(ty: Ty) -> bool {
4222 ty_bare_fn(Some(_), _) => true,
4227 pub fn type_is_fp(ty: Ty) -> bool {
4229 ty_infer(FloatVar(_)) | ty_float(_) => true,
4234 pub fn type_is_numeric(ty: Ty) -> bool {
4235 return type_is_integral(ty) || type_is_fp(ty);
4238 pub fn type_is_signed(ty: Ty) -> bool {
4245 pub fn type_is_machine(ty: Ty) -> bool {
4247 ty_int(ast::TyIs) | ty_uint(ast::TyUs) => false,
4248 ty_int(..) | ty_uint(..) | ty_float(..) => true,
4253 // Whether a type is enum like, that is an enum type with only nullary
4255 pub fn type_is_c_like_enum(cx: &ctxt, ty: Ty) -> bool {
4257 ty_enum(did, _) => {
4258 let variants = enum_variants(cx, did);
4259 if variants.len() == 0 {
4262 variants.iter().all(|v| v.args.len() == 0)
4269 // Returns the type and mutability of *ty.
4271 // The parameter `explicit` indicates if this is an *explicit* dereference.
4272 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
4273 pub fn deref<'tcx>(ty: Ty<'tcx>, explicit: bool) -> Option<mt<'tcx>> {
4278 mutbl: ast::MutImmutable,
4281 ty_rptr(_, mt) => Some(mt),
4282 ty_ptr(mt) if explicit => Some(mt),
4287 pub fn type_content<'tcx>(ty: Ty<'tcx>) -> Ty<'tcx> {
4290 ty_rptr(_, mt) |ty_ptr(mt) => mt.ty,
4295 // Returns the type of ty[i]
4296 pub fn index<'tcx>(ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
4298 ty_vec(ty, _) => Some(ty),
4303 // Returns the type of elements contained within an 'array-like' type.
4304 // This is exactly the same as the above, except it supports strings,
4305 // which can't actually be indexed.
4306 pub fn array_element_ty<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
4308 ty_vec(ty, _) => Some(ty),
4309 ty_str => Some(tcx.types.u8),
4314 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
4315 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
4316 pub fn positional_element_ty<'tcx>(cx: &ctxt<'tcx>,
4319 variant: Option<ast::DefId>) -> Option<Ty<'tcx>> {
4321 match (&ty.sty, variant) {
4322 (&ty_tup(ref v), None) => v.get(i).cloned(),
4325 (&ty_struct(def_id, substs), None) => lookup_struct_fields(cx, def_id)
4327 .map(|&t|lookup_item_type(cx, t.id).ty.subst(cx, substs)),
4329 (&ty_enum(def_id, substs), Some(variant_def_id)) => {
4330 let variant_info = enum_variant_with_id(cx, def_id, variant_def_id);
4331 variant_info.args.get(i).map(|t|t.subst(cx, substs))
4334 (&ty_enum(def_id, substs), None) => {
4335 assert!(enum_is_univariant(cx, def_id));
4336 let enum_variants = enum_variants(cx, def_id);
4337 let variant_info = &(*enum_variants)[0];
4338 variant_info.args.get(i).map(|t|t.subst(cx, substs))
4345 /// Returns the type of element at field `n` in struct or struct-like type `t`.
4346 /// For an enum `t`, `variant` must be some def id.
4347 pub fn named_element_ty<'tcx>(cx: &ctxt<'tcx>,
4350 variant: Option<ast::DefId>) -> Option<Ty<'tcx>> {
4352 match (&ty.sty, variant) {
4353 (&ty_struct(def_id, substs), None) => {
4354 let r = lookup_struct_fields(cx, def_id);
4355 r.iter().find(|f| f.name == n)
4356 .map(|&f| lookup_field_type(cx, def_id, f.id, substs))
4358 (&ty_enum(def_id, substs), Some(variant_def_id)) => {
4359 let variant_info = enum_variant_with_id(cx, def_id, variant_def_id);
4360 variant_info.arg_names.as_ref()
4361 .expect("must have struct enum variant if accessing a named fields")
4362 .iter().zip(variant_info.args.iter())
4363 .find(|&(ident, _)| ident.name == n)
4364 .map(|(_ident, arg_t)| arg_t.subst(cx, substs))
4370 pub fn impl_id_to_trait_ref<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId)
4371 -> Rc<ty::TraitRef<'tcx>> {
4372 match cx.impl_trait_refs.borrow().get(&id) {
4373 Some(ty) => ty.clone(),
4374 None => cx.sess.bug(
4375 &format!("impl_id_to_trait_ref: no trait ref for impl `{}`",
4376 cx.map.node_to_string(id)))
4380 pub fn node_id_to_type<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> Ty<'tcx> {
4381 match node_id_to_type_opt(cx, id) {
4383 None => cx.sess.bug(
4384 &format!("node_id_to_type: no type for node `{}`",
4385 cx.map.node_to_string(id)))
4389 pub fn node_id_to_type_opt<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> Option<Ty<'tcx>> {
4390 match cx.node_types.borrow().get(&id) {
4391 Some(&ty) => Some(ty),
4396 pub fn node_id_item_substs<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> ItemSubsts<'tcx> {
4397 match cx.item_substs.borrow().get(&id) {
4398 None => ItemSubsts::empty(),
4399 Some(ts) => ts.clone(),
4403 pub fn fn_is_variadic(fty: Ty) -> bool {
4405 ty_bare_fn(_, ref f) => f.sig.0.variadic,
4407 panic!("fn_is_variadic() called on non-fn type: {:?}", s)
4412 pub fn ty_fn_sig<'tcx>(fty: Ty<'tcx>) -> &'tcx PolyFnSig<'tcx> {
4414 ty_bare_fn(_, ref f) => &f.sig,
4416 panic!("ty_fn_sig() called on non-fn type: {:?}", s)
4421 /// Returns the ABI of the given function.
4422 pub fn ty_fn_abi(fty: Ty) -> abi::Abi {
4424 ty_bare_fn(_, ref f) => f.abi,
4425 _ => panic!("ty_fn_abi() called on non-fn type"),
4429 // Type accessors for substructures of types
4430 pub fn ty_fn_args<'tcx>(fty: Ty<'tcx>) -> ty::Binder<Vec<Ty<'tcx>>> {
4431 ty_fn_sig(fty).inputs()
4434 pub fn ty_fn_ret<'tcx>(fty: Ty<'tcx>) -> Binder<FnOutput<'tcx>> {
4436 ty_bare_fn(_, ref f) => f.sig.output(),
4438 panic!("ty_fn_ret() called on non-fn type: {:?}", s)
4443 pub fn is_fn_ty(fty: Ty) -> bool {
4445 ty_bare_fn(..) => true,
4450 pub fn ty_region(tcx: &ctxt,
4454 ty_rptr(r, _) => *r,
4458 &format!("ty_region() invoked on an inappropriate ty: {:?}",
4464 pub fn free_region_from_def(outlives_extent: region::DestructionScopeData,
4465 def: &RegionParameterDef)
4469 ty::ReFree(ty::FreeRegion { scope: outlives_extent,
4470 bound_region: ty::BrNamed(def.def_id,
4472 debug!("free_region_from_def returns {:?}", ret);
4476 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
4477 // doesn't provide type parameter substitutions.
4478 pub fn pat_ty<'tcx>(cx: &ctxt<'tcx>, pat: &ast::Pat) -> Ty<'tcx> {
4479 return node_id_to_type(cx, pat.id);
4481 pub fn pat_ty_opt<'tcx>(cx: &ctxt<'tcx>, pat: &ast::Pat) -> Option<Ty<'tcx>> {
4482 return node_id_to_type_opt(cx, pat.id);
4486 // Returns the type of an expression as a monotype.
4488 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
4489 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
4490 // auto-ref. The type returned by this function does not consider such
4491 // adjustments. See `expr_ty_adjusted()` instead.
4493 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
4494 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
4495 // instead of "fn(ty) -> T with T = isize".
4496 pub fn expr_ty<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Ty<'tcx> {
4497 return node_id_to_type(cx, expr.id);
4500 pub fn expr_ty_opt<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Option<Ty<'tcx>> {
4501 return node_id_to_type_opt(cx, expr.id);
4504 /// Returns the type of `expr`, considering any `AutoAdjustment`
4505 /// entry recorded for that expression.
4507 /// It would almost certainly be better to store the adjusted ty in with
4508 /// the `AutoAdjustment`, but I opted not to do this because it would
4509 /// require serializing and deserializing the type and, although that's not
4510 /// hard to do, I just hate that code so much I didn't want to touch it
4511 /// unless it was to fix it properly, which seemed a distraction from the
4512 /// task at hand! -nmatsakis
4513 pub fn expr_ty_adjusted<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Ty<'tcx> {
4514 adjust_ty(cx, expr.span, expr.id, expr_ty(cx, expr),
4515 cx.adjustments.borrow().get(&expr.id),
4516 |method_call| cx.method_map.borrow().get(&method_call).map(|method| method.ty))
4519 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
4520 match cx.map.find(id) {
4521 Some(ast_map::NodeExpr(e)) => {
4525 cx.sess.bug(&format!("Node id {} is not an expr: {:?}",
4530 cx.sess.bug(&format!("Node id {} is not present \
4531 in the node map", id));
4536 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
4537 match cx.map.find(id) {
4538 Some(ast_map::NodeLocal(pat)) => {
4540 ast::PatIdent(_, ref path1, _) => {
4541 token::get_ident(path1.node)
4545 &format!("Variable id {} maps to {:?}, not local",
4552 cx.sess.bug(&format!("Variable id {} maps to {:?}, not local",
4559 /// See `expr_ty_adjusted`
4560 pub fn adjust_ty<'tcx, F>(cx: &ctxt<'tcx>,
4562 expr_id: ast::NodeId,
4563 unadjusted_ty: Ty<'tcx>,
4564 adjustment: Option<&AutoAdjustment<'tcx>>,
4567 F: FnMut(MethodCall) -> Option<Ty<'tcx>>,
4569 if let ty_err = unadjusted_ty.sty {
4570 return unadjusted_ty;
4573 return match adjustment {
4574 Some(adjustment) => {
4576 AdjustReifyFnPointer(_) => {
4577 match unadjusted_ty.sty {
4578 ty::ty_bare_fn(Some(_), b) => {
4579 ty::mk_bare_fn(cx, None, b)
4583 &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
4590 AdjustUnsafeFnPointer => {
4591 match unadjusted_ty.sty {
4592 ty::ty_bare_fn(None, b) => cx.safe_to_unsafe_fn_ty(b),
4595 &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
4602 AdjustDerefRef(ref adj) => {
4603 let mut adjusted_ty = unadjusted_ty;
4605 if !ty::type_is_error(adjusted_ty) {
4606 for i in 0..adj.autoderefs {
4607 let method_call = MethodCall::autoderef(expr_id, i);
4608 match method_type(method_call) {
4609 Some(method_ty) => {
4610 // overloaded deref operators have all late-bound
4611 // regions fully instantiated and coverge
4613 ty::no_late_bound_regions(cx,
4614 &ty_fn_ret(method_ty)).unwrap();
4615 adjusted_ty = fn_ret.unwrap();
4619 match deref(adjusted_ty, true) {
4620 Some(mt) => { adjusted_ty = mt.ty; }
4624 &format!("the {}th autoderef failed: \
4627 ty_to_string(cx, adjusted_ty))
4634 adjust_ty_for_autoref(cx, span, adjusted_ty, adj.autoref.as_ref())
4638 None => unadjusted_ty
4642 pub fn adjust_ty_for_autoref<'tcx>(cx: &ctxt<'tcx>,
4645 autoref: Option<&AutoRef<'tcx>>)
4651 Some(&AutoPtr(r, m, ref a)) => {
4652 let adjusted_ty = match a {
4653 &Some(box ref a) => adjust_ty_for_autoref(cx, span, ty, Some(a)),
4656 mk_rptr(cx, cx.mk_region(r), mt {
4662 Some(&AutoUnsafe(m, ref a)) => {
4663 let adjusted_ty = match a {
4664 &Some(box ref a) => adjust_ty_for_autoref(cx, span, ty, Some(a)),
4667 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
4670 Some(&AutoUnsize(ref k)) => unsize_ty(cx, ty, k, span),
4672 Some(&AutoUnsizeUniq(ref k)) => ty::mk_uniq(cx, unsize_ty(cx, ty, k, span)),
4676 // Take a sized type and a sizing adjustment and produce an unsized version of
4678 pub fn unsize_ty<'tcx>(cx: &ctxt<'tcx>,
4680 kind: &UnsizeKind<'tcx>,
4684 &UnsizeLength(len) => match ty.sty {
4685 ty_vec(ty, Some(n)) => {
4687 mk_vec(cx, ty, None)
4689 _ => cx.sess.span_bug(span,
4690 &format!("UnsizeLength with bad sty: {:?}",
4691 ty_to_string(cx, ty)))
4693 &UnsizeStruct(box ref k, tp_index) => match ty.sty {
4694 ty_struct(did, substs) => {
4695 let ty_substs = substs.types.get_slice(subst::TypeSpace);
4696 let new_ty = unsize_ty(cx, ty_substs[tp_index], k, span);
4697 let mut unsized_substs = substs.clone();
4698 unsized_substs.types.get_mut_slice(subst::TypeSpace)[tp_index] = new_ty;
4699 mk_struct(cx, did, cx.mk_substs(unsized_substs))
4701 _ => cx.sess.span_bug(span,
4702 &format!("UnsizeStruct with bad sty: {:?}",
4703 ty_to_string(cx, ty)))
4705 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
4706 mk_trait(cx, principal.clone(), bounds.clone())
4708 &UnsizeUpcast(target_ty) => {
4714 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> def::Def {
4715 match tcx.def_map.borrow().get(&expr.id) {
4716 Some(def) => def.full_def(),
4718 tcx.sess.span_bug(expr.span, &format!(
4719 "no def-map entry for expr {}", expr.id));
4724 pub fn expr_is_lval(tcx: &ctxt, e: &ast::Expr) -> bool {
4725 match expr_kind(tcx, e) {
4727 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
4731 /// We categorize expressions into three kinds. The distinction between
4732 /// lvalue/rvalue is fundamental to the language. The distinction between the
4733 /// two kinds of rvalues is an artifact of trans which reflects how we will
4734 /// generate code for that kind of expression. See trans/expr.rs for more
4744 pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
4745 if tcx.method_map.borrow().contains_key(&MethodCall::expr(expr.id)) {
4746 // Overloaded operations are generally calls, and hence they are
4747 // generated via DPS, but there are a few exceptions:
4748 return match expr.node {
4749 // `a += b` has a unit result.
4750 ast::ExprAssignOp(..) => RvalueStmtExpr,
4752 // the deref method invoked for `*a` always yields an `&T`
4753 ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
4755 // the index method invoked for `a[i]` always yields an `&T`
4756 ast::ExprIndex(..) => LvalueExpr,
4758 // in the general case, result could be any type, use DPS
4764 ast::ExprPath(..) => {
4765 match resolve_expr(tcx, expr) {
4766 def::DefVariant(tid, vid, _) => {
4767 let variant_info = enum_variant_with_id(tcx, tid, vid);
4768 if variant_info.args.len() > 0 {
4777 def::DefStruct(_) => {
4778 match tcx.node_types.borrow().get(&expr.id) {
4779 Some(ty) => match ty.sty {
4780 ty_bare_fn(..) => RvalueDatumExpr,
4783 // See ExprCast below for why types might be missing.
4784 None => RvalueDatumExpr
4788 // Special case: A unit like struct's constructor must be called without () at the
4789 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
4790 // of unit structs this is should not be interpreted as function pointer but as
4791 // call to the constructor.
4792 def::DefFn(_, true) => RvalueDpsExpr,
4794 // Fn pointers are just scalar values.
4795 def::DefFn(..) | def::DefMethod(..) => RvalueDatumExpr,
4797 // Note: there is actually a good case to be made that
4798 // DefArg's, particularly those of immediate type, ought to
4799 // considered rvalues.
4800 def::DefStatic(..) |
4802 def::DefLocal(..) => LvalueExpr,
4804 def::DefConst(..) => RvalueDatumExpr,
4809 &format!("uncategorized def for expr {}: {:?}",
4816 ast::ExprUnary(ast::UnDeref, _) |
4817 ast::ExprField(..) |
4818 ast::ExprTupField(..) |
4819 ast::ExprIndex(..) => {
4824 ast::ExprMethodCall(..) |
4825 ast::ExprStruct(..) |
4826 ast::ExprRange(..) |
4829 ast::ExprMatch(..) |
4830 ast::ExprClosure(..) |
4831 ast::ExprBlock(..) |
4832 ast::ExprRepeat(..) |
4833 ast::ExprVec(..) => {
4837 ast::ExprIfLet(..) => {
4838 tcx.sess.span_bug(expr.span, "non-desugared ExprIfLet");
4840 ast::ExprWhileLet(..) => {
4841 tcx.sess.span_bug(expr.span, "non-desugared ExprWhileLet");
4844 ast::ExprForLoop(..) => {
4845 tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
4848 ast::ExprLit(ref lit) if lit_is_str(&**lit) => {
4852 ast::ExprBreak(..) |
4853 ast::ExprAgain(..) |
4855 ast::ExprWhile(..) |
4857 ast::ExprAssign(..) |
4858 ast::ExprInlineAsm(..) |
4859 ast::ExprAssignOp(..) => {
4863 ast::ExprLit(_) | // Note: LitStr is carved out above
4864 ast::ExprUnary(..) |
4865 ast::ExprBox(None, _) |
4866 ast::ExprAddrOf(..) |
4867 ast::ExprBinary(..) |
4868 ast::ExprCast(..) => {
4872 ast::ExprBox(Some(ref place), _) => {
4873 // Special case `Box<T>` for now:
4874 let def_id = match tcx.def_map.borrow().get(&place.id) {
4875 Some(def) => def.def_id(),
4876 None => panic!("no def for place"),
4878 if tcx.lang_items.exchange_heap() == Some(def_id) {
4885 ast::ExprParen(ref e) => expr_kind(tcx, &**e),
4887 ast::ExprMac(..) => {
4890 "macro expression remains after expansion");
4895 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
4897 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
4900 ast::StmtMac(..) => panic!("unexpanded macro in trans")
4904 pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
4907 for f in fields { if f.name == name { return i; } i += 1; }
4908 tcx.sess.bug(&format!(
4909 "no field named `{}` found in the list of fields `{:?}`",
4910 token::get_name(name),
4912 .map(|f| token::get_name(f.name).to_string())
4913 .collect::<Vec<String>>()));
4916 pub fn impl_or_trait_item_idx(id: ast::Name, trait_items: &[ImplOrTraitItem])
4918 trait_items.iter().position(|m| m.name() == id)
4921 pub fn ty_sort_string<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> String {
4923 ty_bool | ty_char | ty_int(_) |
4924 ty_uint(_) | ty_float(_) | ty_str => {
4925 ::util::ppaux::ty_to_string(cx, ty)
4927 ty_tup(ref tys) if tys.is_empty() => ::util::ppaux::ty_to_string(cx, ty),
4929 ty_enum(id, _) => format!("enum `{}`", item_path_str(cx, id)),
4930 ty_uniq(_) => "box".to_string(),
4931 ty_vec(_, Some(n)) => format!("array of {} elements", n),
4932 ty_vec(_, None) => "slice".to_string(),
4933 ty_ptr(_) => "*-ptr".to_string(),
4934 ty_rptr(_, _) => "&-ptr".to_string(),
4935 ty_bare_fn(Some(_), _) => format!("fn item"),
4936 ty_bare_fn(None, _) => "fn pointer".to_string(),
4937 ty_trait(ref inner) => {
4938 format!("trait {}", item_path_str(cx, inner.principal_def_id()))
4940 ty_struct(id, _) => {
4941 format!("struct `{}`", item_path_str(cx, id))
4943 ty_closure(..) => "closure".to_string(),
4944 ty_tup(_) => "tuple".to_string(),
4945 ty_infer(TyVar(_)) => "inferred type".to_string(),
4946 ty_infer(IntVar(_)) => "integral variable".to_string(),
4947 ty_infer(FloatVar(_)) => "floating-point variable".to_string(),
4948 ty_infer(FreshTy(_)) => "skolemized type".to_string(),
4949 ty_infer(FreshIntTy(_)) => "skolemized integral type".to_string(),
4950 ty_projection(_) => "associated type".to_string(),
4951 ty_param(ref p) => {
4952 if p.space == subst::SelfSpace {
4955 "type parameter".to_string()
4958 ty_err => "type error".to_string(),
4962 impl<'tcx> Repr<'tcx> for ty::type_err<'tcx> {
4963 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
4964 ty::type_err_to_str(tcx, self)
4968 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
4969 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
4970 /// afterwards to present additional details, particularly when it comes to lifetime-related
4972 pub fn type_err_to_str<'tcx>(cx: &ctxt<'tcx>, err: &type_err<'tcx>) -> String {
4974 terr_cyclic_ty => "cyclic type of infinite size".to_string(),
4975 terr_mismatch => "types differ".to_string(),
4976 terr_unsafety_mismatch(values) => {
4977 format!("expected {} fn, found {} fn",
4981 terr_abi_mismatch(values) => {
4982 format!("expected {} fn, found {} fn",
4986 terr_mutability => "values differ in mutability".to_string(),
4987 terr_box_mutability => {
4988 "boxed values differ in mutability".to_string()
4990 terr_vec_mutability => "vectors differ in mutability".to_string(),
4991 terr_ptr_mutability => "pointers differ in mutability".to_string(),
4992 terr_ref_mutability => "references differ in mutability".to_string(),
4993 terr_ty_param_size(values) => {
4994 format!("expected a type with {} type params, \
4995 found one with {} type params",
4999 terr_fixed_array_size(values) => {
5000 format!("expected an array with a fixed size of {} elements, \
5001 found one with {} elements",
5005 terr_tuple_size(values) => {
5006 format!("expected a tuple with {} elements, \
5007 found one with {} elements",
5012 "incorrect number of function parameters".to_string()
5014 terr_regions_does_not_outlive(..) => {
5015 "lifetime mismatch".to_string()
5017 terr_regions_not_same(..) => {
5018 "lifetimes are not the same".to_string()
5020 terr_regions_no_overlap(..) => {
5021 "lifetimes do not intersect".to_string()
5023 terr_regions_insufficiently_polymorphic(br, _) => {
5024 format!("expected bound lifetime parameter {}, \
5025 found concrete lifetime",
5026 bound_region_ptr_to_string(cx, br))
5028 terr_regions_overly_polymorphic(br, _) => {
5029 format!("expected concrete lifetime, \
5030 found bound lifetime parameter {}",
5031 bound_region_ptr_to_string(cx, br))
5033 terr_sorts(values) => {
5034 // A naive approach to making sure that we're not reporting silly errors such as:
5035 // (expected closure, found closure).
5036 let expected_str = ty_sort_string(cx, values.expected);
5037 let found_str = ty_sort_string(cx, values.found);
5038 if expected_str == found_str {
5039 format!("expected {}, found a different {}", expected_str, found_str)
5041 format!("expected {}, found {}", expected_str, found_str)
5044 terr_traits(values) => {
5045 format!("expected trait `{}`, found trait `{}`",
5046 item_path_str(cx, values.expected),
5047 item_path_str(cx, values.found))
5049 terr_builtin_bounds(values) => {
5050 if values.expected.is_empty() {
5051 format!("expected no bounds, found `{}`",
5052 values.found.user_string(cx))
5053 } else if values.found.is_empty() {
5054 format!("expected bounds `{}`, found no bounds",
5055 values.expected.user_string(cx))
5057 format!("expected bounds `{}`, found bounds `{}`",
5058 values.expected.user_string(cx),
5059 values.found.user_string(cx))
5062 terr_integer_as_char => {
5063 "expected an integral type, found `char`".to_string()
5065 terr_int_mismatch(ref values) => {
5066 format!("expected `{:?}`, found `{:?}`",
5070 terr_float_mismatch(ref values) => {
5071 format!("expected `{:?}`, found `{:?}`",
5075 terr_variadic_mismatch(ref values) => {
5076 format!("expected {} fn, found {} function",
5077 if values.expected { "variadic" } else { "non-variadic" },
5078 if values.found { "variadic" } else { "non-variadic" })
5080 terr_convergence_mismatch(ref values) => {
5081 format!("expected {} fn, found {} function",
5082 if values.expected { "converging" } else { "diverging" },
5083 if values.found { "converging" } else { "diverging" })
5085 terr_projection_name_mismatched(ref values) => {
5086 format!("expected {}, found {}",
5087 token::get_name(values.expected),
5088 token::get_name(values.found))
5090 terr_projection_bounds_length(ref values) => {
5091 format!("expected {} associated type bindings, found {}",
5098 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
5100 terr_regions_does_not_outlive(subregion, superregion) => {
5101 note_and_explain_region(cx, "", subregion, "...");
5102 note_and_explain_region(cx, "...does not necessarily outlive ",
5105 terr_regions_not_same(region1, region2) => {
5106 note_and_explain_region(cx, "", region1, "...");
5107 note_and_explain_region(cx, "...is not the same lifetime as ",
5110 terr_regions_no_overlap(region1, region2) => {
5111 note_and_explain_region(cx, "", region1, "...");
5112 note_and_explain_region(cx, "...does not overlap ",
5115 terr_regions_insufficiently_polymorphic(_, conc_region) => {
5116 note_and_explain_region(cx,
5117 "concrete lifetime that was found is ",
5120 terr_regions_overly_polymorphic(_, ty::ReInfer(ty::ReVar(_))) => {
5121 // don't bother to print out the message below for
5122 // inference variables, it's not very illuminating.
5124 terr_regions_overly_polymorphic(_, conc_region) => {
5125 note_and_explain_region(cx,
5126 "expected concrete lifetime is ",
5133 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
5134 cx.provided_method_sources.borrow().get(&id).cloned()
5137 pub fn provided_trait_methods<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5138 -> Vec<Rc<Method<'tcx>>> {
5140 if let ItemTrait(_, _, _, ref ms) = cx.map.expect_item(id.node).node {
5141 ms.iter().filter_map(|ti| {
5142 if let ast::MethodTraitItem(_, Some(_)) = ti.node {
5143 match impl_or_trait_item(cx, ast_util::local_def(ti.id)) {
5144 MethodTraitItem(m) => Some(m),
5145 TypeTraitItem(_) => {
5146 cx.sess.bug("provided_trait_methods(): \
5147 associated type found from \
5148 looking up ProvidedMethod?!")
5156 cx.sess.bug(&format!("provided_trait_methods: `{:?}` is not a trait", id))
5159 csearch::get_provided_trait_methods(cx, id)
5163 /// Helper for looking things up in the various maps that are populated during
5164 /// typeck::collect (e.g., `cx.impl_or_trait_items`, `cx.tcache`, etc). All of
5165 /// these share the pattern that if the id is local, it should have been loaded
5166 /// into the map by the `typeck::collect` phase. If the def-id is external,
5167 /// then we have to go consult the crate loading code (and cache the result for
5169 fn lookup_locally_or_in_crate_store<V, F>(descr: &str,
5171 map: &mut DefIdMap<V>,
5172 load_external: F) -> V where
5176 match map.get(&def_id).cloned() {
5177 Some(v) => { return v; }
5181 if def_id.krate == ast::LOCAL_CRATE {
5182 panic!("No def'n found for {:?} in tcx.{}", def_id, descr);
5184 let v = load_external();
5185 map.insert(def_id, v.clone());
5189 pub fn trait_item<'tcx>(cx: &ctxt<'tcx>, trait_did: ast::DefId, idx: usize)
5190 -> ImplOrTraitItem<'tcx> {
5191 let method_def_id = (*ty::trait_item_def_ids(cx, trait_did))[idx].def_id();
5192 impl_or_trait_item(cx, method_def_id)
5195 pub fn trait_items<'tcx>(cx: &ctxt<'tcx>, trait_did: ast::DefId)
5196 -> Rc<Vec<ImplOrTraitItem<'tcx>>> {
5197 let mut trait_items = cx.trait_items_cache.borrow_mut();
5198 match trait_items.get(&trait_did).cloned() {
5199 Some(trait_items) => trait_items,
5201 let def_ids = ty::trait_item_def_ids(cx, trait_did);
5202 let items: Rc<Vec<ImplOrTraitItem>> =
5203 Rc::new(def_ids.iter()
5204 .map(|d| impl_or_trait_item(cx, d.def_id()))
5206 trait_items.insert(trait_did, items.clone());
5212 pub fn trait_impl_polarity<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5213 -> Option<ast::ImplPolarity> {
5214 if id.krate == ast::LOCAL_CRATE {
5215 match cx.map.find(id.node) {
5216 Some(ast_map::NodeItem(item)) => {
5218 ast::ItemImpl(_, polarity, _, _, _, _) => Some(polarity),
5225 csearch::get_impl_polarity(cx, id)
5229 pub fn impl_or_trait_item<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5230 -> ImplOrTraitItem<'tcx> {
5231 lookup_locally_or_in_crate_store("impl_or_trait_items",
5233 &mut *cx.impl_or_trait_items
5236 csearch::get_impl_or_trait_item(cx, id)
5240 /// Returns true if the given ID refers to an associated type and false if it
5241 /// refers to anything else.
5242 pub fn is_associated_type(cx: &ctxt, id: ast::DefId) -> bool {
5243 memoized(&cx.associated_types, id, |id: ast::DefId| {
5244 if id.krate == ast::LOCAL_CRATE {
5245 match cx.impl_or_trait_items.borrow().get(&id) {
5248 TypeTraitItem(_) => true,
5249 MethodTraitItem(_) => false,
5255 csearch::is_associated_type(&cx.sess.cstore, id)
5260 /// Returns the parameter index that the given associated type corresponds to.
5261 pub fn associated_type_parameter_index(cx: &ctxt,
5262 trait_def: &TraitDef,
5263 associated_type_id: ast::DefId)
5265 for type_parameter_def in trait_def.generics.types.iter() {
5266 if type_parameter_def.def_id == associated_type_id {
5267 return type_parameter_def.index as usize
5270 cx.sess.bug("couldn't find associated type parameter index")
5273 pub fn trait_item_def_ids(cx: &ctxt, id: ast::DefId)
5274 -> Rc<Vec<ImplOrTraitItemId>> {
5275 lookup_locally_or_in_crate_store("trait_item_def_ids",
5277 &mut *cx.trait_item_def_ids.borrow_mut(),
5279 Rc::new(csearch::get_trait_item_def_ids(&cx.sess.cstore, id))
5283 pub fn impl_trait_ref<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5284 -> Option<Rc<TraitRef<'tcx>>> {
5285 memoized(&cx.impl_trait_cache, id, |id: ast::DefId| {
5286 if id.krate == ast::LOCAL_CRATE {
5287 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
5288 if let Some(ast_map::NodeItem(item)) = cx.map.find(id.node) {
5290 ast::ItemImpl(_, _, _, Some(_), _, _) |
5291 ast::ItemDefaultImpl(..) => {
5292 Some(ty::impl_id_to_trait_ref(cx, id.node))
5300 csearch::get_impl_trait(cx, id)
5305 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
5306 tcx.def_map.borrow().get(&tr.ref_id).expect("no def-map entry for trait").def_id()
5309 pub fn try_add_builtin_trait(
5311 trait_def_id: ast::DefId,
5312 builtin_bounds: &mut EnumSet<BuiltinBound>)
5315 //! Checks whether `trait_ref` refers to one of the builtin
5316 //! traits, like `Send`, and adds the corresponding
5317 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
5318 //! is a builtin trait.
5320 match tcx.lang_items.to_builtin_kind(trait_def_id) {
5321 Some(bound) => { builtin_bounds.insert(bound); true }
5326 pub fn ty_to_def_id(ty: Ty) -> Option<ast::DefId> {
5329 Some(tt.principal_def_id()),
5332 ty_closure(id, _) =>
5341 pub struct VariantInfo<'tcx> {
5342 pub args: Vec<Ty<'tcx>>,
5343 pub arg_names: Option<Vec<ast::Ident>>,
5344 pub ctor_ty: Option<Ty<'tcx>>,
5345 pub name: ast::Name,
5351 impl<'tcx> VariantInfo<'tcx> {
5353 /// Creates a new VariantInfo from the corresponding ast representation.
5355 /// Does not do any caching of the value in the type context.
5356 pub fn from_ast_variant(cx: &ctxt<'tcx>,
5357 ast_variant: &ast::Variant,
5358 discriminant: Disr) -> VariantInfo<'tcx> {
5359 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
5361 match ast_variant.node.kind {
5362 ast::TupleVariantKind(ref args) => {
5363 let arg_tys = if args.len() > 0 {
5364 // the regions in the argument types come from the
5365 // enum def'n, and hence will all be early bound
5366 ty::no_late_bound_regions(cx, &ty_fn_args(ctor_ty)).unwrap()
5371 return VariantInfo {
5374 ctor_ty: Some(ctor_ty),
5375 name: ast_variant.node.name.name,
5376 id: ast_util::local_def(ast_variant.node.id),
5377 disr_val: discriminant,
5378 vis: ast_variant.node.vis
5381 ast::StructVariantKind(ref struct_def) => {
5382 let fields: &[StructField] = &struct_def.fields;
5384 assert!(fields.len() > 0);
5386 let arg_tys = struct_def.fields.iter()
5387 .map(|field| node_id_to_type(cx, field.node.id)).collect();
5388 let arg_names = fields.iter().map(|field| {
5389 match field.node.kind {
5390 NamedField(ident, _) => ident,
5391 UnnamedField(..) => cx.sess.bug(
5392 "enum_variants: all fields in struct must have a name")
5396 return VariantInfo {
5398 arg_names: Some(arg_names),
5400 name: ast_variant.node.name.name,
5401 id: ast_util::local_def(ast_variant.node.id),
5402 disr_val: discriminant,
5403 vis: ast_variant.node.vis
5410 pub fn substd_enum_variants<'tcx>(cx: &ctxt<'tcx>,
5412 substs: &Substs<'tcx>)
5413 -> Vec<Rc<VariantInfo<'tcx>>> {
5414 enum_variants(cx, id).iter().map(|variant_info| {
5415 let substd_args = variant_info.args.iter()
5416 .map(|aty| aty.subst(cx, substs)).collect::<Vec<_>>();
5418 let substd_ctor_ty = variant_info.ctor_ty.subst(cx, substs);
5420 Rc::new(VariantInfo {
5422 ctor_ty: substd_ctor_ty,
5423 ..(**variant_info).clone()
5428 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
5429 with_path(cx, id, |path| ast_map::path_to_string(path)).to_string()
5435 TraitDtor(DefId, bool)
5439 pub fn is_present(&self) -> bool {
5441 TraitDtor(..) => true,
5446 pub fn has_drop_flag(&self) -> bool {
5449 &TraitDtor(_, flag) => flag
5454 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
5455 Otherwise return none. */
5456 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
5457 match cx.destructor_for_type.borrow().get(&struct_id) {
5458 Some(&method_def_id) => {
5459 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
5461 TraitDtor(method_def_id, flag)
5467 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
5468 cx.destructor_for_type.borrow().contains_key(&struct_id)
5471 pub fn with_path<T, F>(cx: &ctxt, id: ast::DefId, f: F) -> T where
5472 F: FnOnce(ast_map::PathElems) -> T,
5474 if id.krate == ast::LOCAL_CRATE {
5475 cx.map.with_path(id.node, f)
5477 f(csearch::get_item_path(cx, id).iter().cloned().chain(None))
5481 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
5482 enum_variants(cx, id).len() == 1
5485 pub fn type_is_empty(cx: &ctxt, ty: Ty) -> bool {
5487 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
5492 pub fn enum_variants<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5493 -> Rc<Vec<Rc<VariantInfo<'tcx>>>> {
5494 memoized(&cx.enum_var_cache, id, |id: ast::DefId| {
5495 if ast::LOCAL_CRATE != id.krate {
5496 Rc::new(csearch::get_enum_variants(cx, id))
5499 Although both this code and check_enum_variants in typeck/check
5500 call eval_const_expr, it should never get called twice for the same
5501 expr, since check_enum_variants also updates the enum_var_cache
5503 match cx.map.get(id.node) {
5504 ast_map::NodeItem(ref item) => {
5506 ast::ItemEnum(ref enum_definition, _) => {
5507 let mut last_discriminant: Option<Disr> = None;
5508 Rc::new(enum_definition.variants.iter().map(|variant| {
5510 let mut discriminant = INITIAL_DISCRIMINANT_VALUE;
5511 if let Some(ref e) = variant.node.disr_expr {
5512 // Preserve all values, and prefer signed.
5513 let ty = Some(cx.types.i64);
5514 match const_eval::eval_const_expr_partial(cx, &**e, ty) {
5515 Ok(const_eval::const_int(val)) => {
5516 discriminant = val as Disr;
5518 Ok(const_eval::const_uint(val)) => {
5519 discriminant = val as Disr;
5522 span_err!(cx.sess, e.span, E0304,
5523 "expected signed integer constant");
5526 span_err!(cx.sess, err.span, E0305,
5527 "constant evaluation error: {}",
5532 if let Some(val) = last_discriminant {
5533 if let Some(v) = val.checked_add(1) {
5538 &format!("Discriminant overflowed!"));
5541 discriminant = INITIAL_DISCRIMINANT_VALUE;
5545 last_discriminant = Some(discriminant);
5546 Rc::new(VariantInfo::from_ast_variant(cx, &**variant,
5551 cx.sess.bug("enum_variants: id not bound to an enum")
5555 _ => cx.sess.bug("enum_variants: id not bound to an enum")
5561 // Returns information about the enum variant with the given ID:
5562 pub fn enum_variant_with_id<'tcx>(cx: &ctxt<'tcx>,
5563 enum_id: ast::DefId,
5564 variant_id: ast::DefId)
5565 -> Rc<VariantInfo<'tcx>> {
5566 enum_variants(cx, enum_id).iter()
5567 .find(|variant| variant.id == variant_id)
5568 .expect("enum_variant_with_id(): no variant exists with that ID")
5573 // If the given item is in an external crate, looks up its type and adds it to
5574 // the type cache. Returns the type parameters and type.
5575 pub fn lookup_item_type<'tcx>(cx: &ctxt<'tcx>,
5577 -> TypeScheme<'tcx> {
5578 lookup_locally_or_in_crate_store(
5579 "tcache", did, &mut *cx.tcache.borrow_mut(),
5580 || csearch::get_type(cx, did))
5583 /// Given the did of a trait, returns its canonical trait ref.
5584 pub fn lookup_trait_def<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId)
5585 -> Rc<TraitDef<'tcx>> {
5586 memoized(&cx.trait_defs, did, |did: DefId| {
5587 assert!(did.krate != ast::LOCAL_CRATE);
5588 Rc::new(csearch::get_trait_def(cx, did))
5592 /// Given the did of an item, returns its full set of predicates.
5593 pub fn lookup_predicates<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId)
5594 -> GenericPredicates<'tcx>
5596 memoized(&cx.predicates, did, |did: DefId| {
5597 assert!(did.krate != ast::LOCAL_CRATE);
5598 csearch::get_predicates(cx, did)
5602 /// Given the did of a trait, returns its superpredicates.
5603 pub fn lookup_super_predicates<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId)
5604 -> GenericPredicates<'tcx>
5606 memoized(&cx.super_predicates, did, |did: DefId| {
5607 assert!(did.krate != ast::LOCAL_CRATE);
5608 csearch::get_super_predicates(cx, did)
5612 pub fn predicates<'tcx>(
5615 bounds: &ParamBounds<'tcx>)
5616 -> Vec<Predicate<'tcx>>
5618 let mut vec = Vec::new();
5620 for builtin_bound in &bounds.builtin_bounds {
5621 match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty) {
5622 Ok(trait_ref) => { vec.push(trait_ref.as_predicate()); }
5623 Err(ErrorReported) => { }
5627 for ®ion_bound in &bounds.region_bounds {
5628 // account for the binder being introduced below; no need to shift `param_ty`
5629 // because, at present at least, it can only refer to early-bound regions
5630 let region_bound = ty_fold::shift_region(region_bound, 1);
5631 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).as_predicate());
5634 for bound_trait_ref in &bounds.trait_bounds {
5635 vec.push(bound_trait_ref.as_predicate());
5638 for projection in &bounds.projection_bounds {
5639 vec.push(projection.as_predicate());
5645 /// Get the attributes of a definition.
5646 pub fn get_attrs<'tcx>(tcx: &'tcx ctxt, did: DefId)
5647 -> Cow<'tcx, [ast::Attribute]> {
5649 Cow::Borrowed(tcx.map.attrs(did.node))
5651 Cow::Owned(csearch::get_item_attrs(&tcx.sess.cstore, did))
5655 /// Determine whether an item is annotated with an attribute
5656 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
5657 get_attrs(tcx, did).iter().any(|item| item.check_name(attr))
5660 /// Determine whether an item is annotated with `#[repr(packed)]`
5661 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
5662 lookup_repr_hints(tcx, did).contains(&attr::ReprPacked)
5665 /// Determine whether an item is annotated with `#[simd]`
5666 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
5667 has_attr(tcx, did, "simd")
5670 /// Obtain the representation annotation for a struct definition.
5671 pub fn lookup_repr_hints(tcx: &ctxt, did: DefId) -> Rc<Vec<attr::ReprAttr>> {
5672 memoized(&tcx.repr_hint_cache, did, |did: DefId| {
5673 Rc::new(if did.krate == LOCAL_CRATE {
5674 get_attrs(tcx, did).iter().flat_map(|meta| {
5675 attr::find_repr_attrs(tcx.sess.diagnostic(), meta).into_iter()
5678 csearch::get_repr_attrs(&tcx.sess.cstore, did)
5683 // Look up a field ID, whether or not it's local
5684 // Takes a list of type substs in case the struct is generic
5685 pub fn lookup_field_type<'tcx>(tcx: &ctxt<'tcx>,
5688 substs: &Substs<'tcx>)
5690 let ty = if id.krate == ast::LOCAL_CRATE {
5691 node_id_to_type(tcx, id.node)
5693 let mut tcache = tcx.tcache.borrow_mut();
5694 tcache.entry(id).or_insert_with(|| csearch::get_field_type(tcx, struct_id, id)).ty
5696 ty.subst(tcx, substs)
5699 // Look up the list of field names and IDs for a given struct.
5700 // Panics if the id is not bound to a struct.
5701 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
5702 if did.krate == ast::LOCAL_CRATE {
5703 let struct_fields = cx.struct_fields.borrow();
5704 match struct_fields.get(&did) {
5705 Some(fields) => (**fields).clone(),
5708 &format!("ID not mapped to struct fields: {}",
5709 cx.map.node_to_string(did.node)));
5713 csearch::get_struct_fields(&cx.sess.cstore, did)
5717 pub fn is_tuple_struct(cx: &ctxt, did: ast::DefId) -> bool {
5718 let fields = lookup_struct_fields(cx, did);
5719 !fields.is_empty() && fields.iter().all(|f| f.name == token::special_names::unnamed_field)
5722 // Returns a list of fields corresponding to the struct's items. trans uses
5723 // this. Takes a list of substs with which to instantiate field types.
5724 pub fn struct_fields<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId, substs: &Substs<'tcx>)
5725 -> Vec<field<'tcx>> {
5726 lookup_struct_fields(cx, did).iter().map(|f| {
5730 ty: lookup_field_type(cx, did, f.id, substs),
5737 // Returns a list of fields corresponding to the tuple's items. trans uses
5739 pub fn tup_fields<'tcx>(v: &[Ty<'tcx>]) -> Vec<field<'tcx>> {
5740 v.iter().enumerate().map(|(i, &f)| {
5742 name: token::intern(&i.to_string()),
5751 #[derive(Copy, Clone)]
5752 pub struct ClosureUpvar<'tcx> {
5758 // Returns a list of `ClosureUpvar`s for each upvar.
5759 pub fn closure_upvars<'tcx>(typer: &mc::Typer<'tcx>,
5760 closure_id: ast::DefId,
5761 substs: &Substs<'tcx>)
5762 -> Option<Vec<ClosureUpvar<'tcx>>>
5764 // Presently an unboxed closure type cannot "escape" out of a
5765 // function, so we will only encounter ones that originated in the
5766 // local crate or were inlined into it along with some function.
5767 // This may change if abstract return types of some sort are
5769 assert!(closure_id.krate == ast::LOCAL_CRATE);
5770 let tcx = typer.tcx();
5771 match tcx.freevars.borrow().get(&closure_id.node) {
5772 None => Some(vec![]),
5773 Some(ref freevars) => {
5776 let freevar_def_id = freevar.def.def_id();
5777 let freevar_ty = match typer.node_ty(freevar_def_id.node) {
5779 Err(()) => { return None; }
5781 let freevar_ty = freevar_ty.subst(tcx, substs);
5783 let upvar_id = ty::UpvarId {
5784 var_id: freevar_def_id.node,
5785 closure_expr_id: closure_id.node
5788 typer.upvar_capture(upvar_id).map(|capture| {
5789 let freevar_ref_ty = match capture {
5790 UpvarCapture::ByValue => {
5793 UpvarCapture::ByRef(borrow) => {
5795 tcx.mk_region(borrow.region),
5798 mutbl: borrow.kind.to_mutbl_lossy(),
5815 // Returns the repeat count for a repeating vector expression.
5816 pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> usize {
5817 match const_eval::eval_const_expr_partial(tcx, count_expr, Some(tcx.types.usize)) {
5819 let found = match val {
5820 const_eval::const_uint(count) => return count as usize,
5821 const_eval::const_int(count) if count >= 0 => return count as usize,
5822 const_eval::const_int(_) => "negative integer",
5823 const_eval::const_float(_) => "float",
5824 const_eval::const_str(_) => "string",
5825 const_eval::const_bool(_) => "boolean",
5826 const_eval::const_binary(_) => "binary array",
5827 const_eval::Struct(..) => "struct",
5828 const_eval::Tuple(_) => "tuple"
5830 span_err!(tcx.sess, count_expr.span, E0306,
5831 "expected positive integer for repeat count, found {}",
5835 let found = match count_expr.node {
5836 ast::ExprPath(None, ast::Path {
5840 }) if segments.len() == 1 =>
5843 "non-constant expression"
5845 span_err!(tcx.sess, count_expr.span, E0307,
5846 "expected constant integer for repeat count, found {}",
5853 // Iterate over a type parameter's bounded traits and any supertraits
5854 // of those traits, ignoring kinds.
5855 // Here, the supertraits are the transitive closure of the supertrait
5856 // relation on the supertraits from each bounded trait's constraint
5858 pub fn each_bound_trait_and_supertraits<'tcx, F>(tcx: &ctxt<'tcx>,
5859 bounds: &[PolyTraitRef<'tcx>],
5862 F: FnMut(PolyTraitRef<'tcx>) -> bool,
5864 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
5865 if !f(bound_trait_ref) {
5872 /// Given a set of predicates that apply to an object type, returns
5873 /// the region bounds that the (erased) `Self` type must
5874 /// outlive. Precisely *because* the `Self` type is erased, the
5875 /// parameter `erased_self_ty` must be supplied to indicate what type
5876 /// has been used to represent `Self` in the predicates
5877 /// themselves. This should really be a unique type; `FreshTy(0)` is a
5880 /// Requires that trait definitions have been processed so that we can
5881 /// elaborate predicates and walk supertraits.
5882 pub fn required_region_bounds<'tcx>(tcx: &ctxt<'tcx>,
5883 erased_self_ty: Ty<'tcx>,
5884 predicates: Vec<ty::Predicate<'tcx>>)
5887 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
5888 erased_self_ty.repr(tcx),
5889 predicates.repr(tcx));
5891 assert!(!erased_self_ty.has_escaping_regions());
5893 traits::elaborate_predicates(tcx, predicates)
5894 .filter_map(|predicate| {
5896 ty::Predicate::Projection(..) |
5897 ty::Predicate::Trait(..) |
5898 ty::Predicate::Equate(..) |
5899 ty::Predicate::RegionOutlives(..) => {
5902 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
5903 // Search for a bound of the form `erased_self_ty
5904 // : 'a`, but be wary of something like `for<'a>
5905 // erased_self_ty : 'a` (we interpret a
5906 // higher-ranked bound like that as 'static,
5907 // though at present the code in `fulfill.rs`
5908 // considers such bounds to be unsatisfiable, so
5909 // it's kind of a moot point since you could never
5910 // construct such an object, but this seems
5911 // correct even if that code changes).
5912 if t == erased_self_ty && !r.has_escaping_regions() {
5913 if r.has_escaping_regions() {
5927 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> Rc<ItemVariances> {
5928 lookup_locally_or_in_crate_store(
5929 "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
5930 || Rc::new(csearch::get_item_variances(&tcx.sess.cstore, item_id)))
5933 pub fn trait_has_default_impl(tcx: &ctxt, trait_def_id: DefId) -> bool {
5934 populate_implementations_for_trait_if_necessary(tcx, trait_def_id);
5935 tcx.traits_with_default_impls.borrow().contains_key(&trait_def_id)
5938 /// Records a trait-to-implementation mapping.
5939 pub fn record_trait_has_default_impl(tcx: &ctxt, trait_def_id: DefId) {
5940 // We're using the latest implementation found as the reference one.
5941 // Duplicated implementations are caught and reported in the coherence
5943 tcx.traits_with_default_impls.borrow_mut().insert(trait_def_id, ());
5946 /// Records a trait-to-implementation mapping.
5947 pub fn record_trait_implementation(tcx: &ctxt,
5948 trait_def_id: DefId,
5949 impl_def_id: DefId) {
5951 match tcx.trait_impls.borrow().get(&trait_def_id) {
5952 Some(impls_for_trait) => {
5953 impls_for_trait.borrow_mut().push(impl_def_id);
5959 tcx.trait_impls.borrow_mut().insert(trait_def_id, Rc::new(RefCell::new(vec!(impl_def_id))));
5962 /// Load primitive inherent implementations if necessary
5963 pub fn populate_implementations_for_primitive_if_necessary(tcx: &ctxt, lang_def_id: ast::DefId) {
5964 if lang_def_id.krate == LOCAL_CRATE {
5967 if tcx.populated_external_primitive_impls.borrow().contains(&lang_def_id) {
5971 debug!("populate_implementations_for_primitive_if_necessary: searching for {:?}", lang_def_id);
5973 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, lang_def_id);
5975 // Store the implementation info.
5976 tcx.impl_items.borrow_mut().insert(lang_def_id, impl_items);
5978 tcx.populated_external_primitive_impls.borrow_mut().insert(lang_def_id);
5981 /// Populates the type context with all the implementations for the given type
5983 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
5984 type_id: ast::DefId) {
5985 if type_id.krate == LOCAL_CRATE {
5988 if tcx.populated_external_types.borrow().contains(&type_id) {
5992 debug!("populate_implementations_for_type_if_necessary: searching for {:?}", type_id);
5994 let mut inherent_impls = Vec::new();
5995 csearch::each_implementation_for_type(&tcx.sess.cstore, type_id, |impl_def_id| {
5996 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, impl_def_id);
5998 // Record the trait->implementation mappings, if applicable.
5999 let associated_traits = csearch::get_impl_trait(tcx, impl_def_id);
6000 if let Some(ref trait_ref) = associated_traits {
6001 record_trait_implementation(tcx, trait_ref.def_id, impl_def_id);
6004 // For any methods that use a default implementation, add them to
6005 // the map. This is a bit unfortunate.
6006 for impl_item_def_id in &impl_items {
6007 let method_def_id = impl_item_def_id.def_id();
6008 match impl_or_trait_item(tcx, method_def_id) {
6009 MethodTraitItem(method) => {
6010 if let Some(source) = method.provided_source {
6011 tcx.provided_method_sources
6013 .insert(method_def_id, source);
6016 TypeTraitItem(_) => {}
6020 // Store the implementation info.
6021 tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
6023 // If this is an inherent implementation, record it.
6024 if associated_traits.is_none() {
6025 inherent_impls.push(impl_def_id);
6029 tcx.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
6030 tcx.populated_external_types.borrow_mut().insert(type_id);
6033 /// Populates the type context with all the implementations for the given
6034 /// trait if necessary.
6035 pub fn populate_implementations_for_trait_if_necessary(
6037 trait_id: ast::DefId) {
6038 if trait_id.krate == LOCAL_CRATE {
6042 if tcx.populated_external_traits.borrow().contains(&trait_id) {
6046 if csearch::is_defaulted_trait(&tcx.sess.cstore, trait_id) {
6047 record_trait_has_default_impl(tcx, trait_id);
6050 csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id, |implementation_def_id| {
6051 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, implementation_def_id);
6053 // Record the trait->implementation mapping.
6054 record_trait_implementation(tcx, trait_id, implementation_def_id);
6056 // For any methods that use a default implementation, add them to
6057 // the map. This is a bit unfortunate.
6058 for impl_item_def_id in &impl_items {
6059 let method_def_id = impl_item_def_id.def_id();
6060 match impl_or_trait_item(tcx, method_def_id) {
6061 MethodTraitItem(method) => {
6062 if let Some(source) = method.provided_source {
6063 tcx.provided_method_sources
6065 .insert(method_def_id, source);
6068 TypeTraitItem(_) => {}
6072 // Store the implementation info.
6073 tcx.impl_items.borrow_mut().insert(implementation_def_id, impl_items);
6076 tcx.populated_external_traits.borrow_mut().insert(trait_id);
6079 /// Given the def_id of an impl, return the def_id of the trait it implements.
6080 /// If it implements no trait, return `None`.
6081 pub fn trait_id_of_impl(tcx: &ctxt,
6083 -> Option<ast::DefId> {
6084 ty::impl_trait_ref(tcx, def_id).map(|tr| tr.def_id)
6087 /// If the given def ID describes a method belonging to an impl, return the
6088 /// ID of the impl that the method belongs to. Otherwise, return `None`.
6089 pub fn impl_of_method(tcx: &ctxt, def_id: ast::DefId)
6090 -> Option<ast::DefId> {
6091 if def_id.krate != LOCAL_CRATE {
6092 return match csearch::get_impl_or_trait_item(tcx,
6093 def_id).container() {
6094 TraitContainer(_) => None,
6095 ImplContainer(def_id) => Some(def_id),
6098 match tcx.impl_or_trait_items.borrow().get(&def_id).cloned() {
6099 Some(trait_item) => {
6100 match trait_item.container() {
6101 TraitContainer(_) => None,
6102 ImplContainer(def_id) => Some(def_id),
6109 /// If the given def ID describes an item belonging to a trait (either a
6110 /// default method or an implementation of a trait method), return the ID of
6111 /// the trait that the method belongs to. Otherwise, return `None`.
6112 pub fn trait_of_item(tcx: &ctxt, def_id: ast::DefId) -> Option<ast::DefId> {
6113 if def_id.krate != LOCAL_CRATE {
6114 return csearch::get_trait_of_item(&tcx.sess.cstore, def_id, tcx);
6116 match tcx.impl_or_trait_items.borrow().get(&def_id).cloned() {
6117 Some(impl_or_trait_item) => {
6118 match impl_or_trait_item.container() {
6119 TraitContainer(def_id) => Some(def_id),
6120 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
6127 /// If the given def ID describes an item belonging to a trait, (either a
6128 /// default method or an implementation of a trait method), return the ID of
6129 /// the method inside trait definition (this means that if the given def ID
6130 /// is already that of the original trait method, then the return value is
6132 /// Otherwise, return `None`.
6133 pub fn trait_item_of_item(tcx: &ctxt, def_id: ast::DefId)
6134 -> Option<ImplOrTraitItemId> {
6135 let impl_item = match tcx.impl_or_trait_items.borrow().get(&def_id) {
6136 Some(m) => m.clone(),
6137 None => return None,
6139 let name = impl_item.name();
6140 match trait_of_item(tcx, def_id) {
6141 Some(trait_did) => {
6142 let trait_items = ty::trait_items(tcx, trait_did);
6144 .position(|m| m.name() == name)
6145 .map(|idx| ty::trait_item(tcx, trait_did, idx).id())
6151 /// Creates a hash of the type `Ty` which will be the same no matter what crate
6152 /// context it's calculated within. This is used by the `type_id` intrinsic.
6153 pub fn hash_crate_independent<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh) -> u64 {
6154 let mut state = SipHasher::new();
6155 helper(tcx, ty, svh, &mut state);
6156 return state.finish();
6158 fn helper<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh,
6159 state: &mut SipHasher) {
6160 macro_rules! byte { ($b:expr) => { ($b as u8).hash(state) } }
6161 macro_rules! hash { ($e:expr) => { $e.hash(state) } }
6163 let region = |state: &mut SipHasher, r: Region| {
6166 ReLateBound(db, BrAnon(i)) => {
6176 tcx.sess.bug("unexpected region found when hashing a type")
6180 let did = |state: &mut SipHasher, did: DefId| {
6181 let h = if ast_util::is_local(did) {
6184 tcx.sess.cstore.get_crate_hash(did.krate)
6186 h.as_str().hash(state);
6187 did.node.hash(state);
6189 let mt = |state: &mut SipHasher, mt: mt| {
6190 mt.mutbl.hash(state);
6192 let fn_sig = |state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| {
6193 let sig = anonymize_late_bound_regions(tcx, sig).0;
6194 for a in &sig.inputs { helper(tcx, *a, svh, state); }
6195 if let ty::FnConverging(output) = sig.output {
6196 helper(tcx, output, svh, state);
6199 maybe_walk_ty(ty, |ty| {
6201 ty_bool => byte!(2),
6202 ty_char => byte!(3),
6225 ty_vec(_, Some(n)) => {
6229 ty_vec(_, None) => {
6241 ty_bare_fn(opt_def_id, ref b) => {
6246 fn_sig(state, &b.sig);
6249 ty_trait(ref data) => {
6251 did(state, data.principal_def_id());
6254 let principal = anonymize_late_bound_regions(tcx, &data.principal).0;
6255 for subty in principal.substs.types.iter() {
6256 helper(tcx, *subty, svh, state);
6261 ty_struct(d, _) => {
6265 ty_tup(ref inner) => {
6273 hash!(token::get_name(p.name));
6275 ty_infer(_) => unreachable!(),
6276 ty_err => byte!(21),
6277 ty_closure(d, _) => {
6281 ty_projection(ref data) => {
6283 did(state, data.trait_ref.def_id);
6284 hash!(token::get_name(data.item_name));
6293 pub fn to_string(self) -> &'static str {
6296 Contravariant => "-",
6303 /// Construct a parameter environment suitable for static contexts or other contexts where there
6304 /// are no free type/lifetime parameters in scope.
6305 pub fn empty_parameter_environment<'a,'tcx>(cx: &'a ctxt<'tcx>) -> ParameterEnvironment<'a,'tcx> {
6306 ty::ParameterEnvironment { tcx: cx,
6307 free_substs: Substs::empty(),
6308 caller_bounds: Vec::new(),
6309 implicit_region_bound: ty::ReEmpty,
6310 selection_cache: traits::SelectionCache::new(), }
6313 /// Constructs and returns a substitution that can be applied to move from
6314 /// the "outer" view of a type or method to the "inner" view.
6315 /// In general, this means converting from bound parameters to
6316 /// free parameters. Since we currently represent bound/free type
6317 /// parameters in the same way, this only has an effect on regions.
6318 pub fn construct_free_substs<'a,'tcx>(
6319 tcx: &'a ctxt<'tcx>,
6320 generics: &Generics<'tcx>,
6321 free_id: ast::NodeId)
6325 let mut types = VecPerParamSpace::empty();
6326 push_types_from_defs(tcx, &mut types, generics.types.as_slice());
6328 let free_id_outlive = region::DestructionScopeData::new(free_id);
6330 // map bound 'a => free 'a
6331 let mut regions = VecPerParamSpace::empty();
6332 push_region_params(&mut regions, free_id_outlive, generics.regions.as_slice());
6336 regions: subst::NonerasedRegions(regions)
6339 fn push_region_params(regions: &mut VecPerParamSpace<ty::Region>,
6340 all_outlive_extent: region::DestructionScopeData,
6341 region_params: &[RegionParameterDef])
6343 for r in region_params {
6344 regions.push(r.space, ty::free_region_from_def(all_outlive_extent, r));
6348 fn push_types_from_defs<'tcx>(tcx: &ty::ctxt<'tcx>,
6349 types: &mut VecPerParamSpace<Ty<'tcx>>,
6350 defs: &[TypeParameterDef<'tcx>]) {
6352 debug!("construct_parameter_environment(): push_types_from_defs: def={:?}",
6354 let ty = ty::mk_param_from_def(tcx, def);
6355 types.push(def.space, ty);
6360 /// See `ParameterEnvironment` struct def'n for details
6361 pub fn construct_parameter_environment<'a,'tcx>(
6362 tcx: &'a ctxt<'tcx>,
6364 generics: &ty::Generics<'tcx>,
6365 generic_predicates: &ty::GenericPredicates<'tcx>,
6366 free_id: ast::NodeId)
6367 -> ParameterEnvironment<'a, 'tcx>
6370 // Construct the free substs.
6373 let free_substs = construct_free_substs(tcx, generics, free_id);
6374 let free_id_outlive = region::DestructionScopeData::new(free_id);
6377 // Compute the bounds on Self and the type parameters.
6380 let bounds = generic_predicates.instantiate(tcx, &free_substs);
6381 let bounds = liberate_late_bound_regions(tcx, free_id_outlive, &ty::Binder(bounds));
6382 let predicates = bounds.predicates.into_vec();
6385 // Compute region bounds. For now, these relations are stored in a
6386 // global table on the tcx, so just enter them there. I'm not
6387 // crazy about this scheme, but it's convenient, at least.
6390 record_region_bounds(tcx, &*predicates);
6392 debug!("construct_parameter_environment: free_id={:?} free_subst={:?} predicates={:?}",
6394 free_substs.repr(tcx),
6395 predicates.repr(tcx));
6398 // Finally, we have to normalize the bounds in the environment, in
6399 // case they contain any associated type projections. This process
6400 // can yield errors if the put in illegal associated types, like
6401 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
6402 // report these errors right here; this doesn't actually feel
6403 // right to me, because constructing the environment feels like a
6404 // kind of a "idempotent" action, but I'm not sure where would be
6405 // a better place. In practice, we construct environments for
6406 // every fn once during type checking, and we'll abort if there
6407 // are any errors at that point, so after type checking you can be
6408 // sure that this will succeed without errors anyway.
6411 let unnormalized_env = ty::ParameterEnvironment {
6413 free_substs: free_substs,
6414 implicit_region_bound: ty::ReScope(free_id_outlive.to_code_extent()),
6415 caller_bounds: predicates,
6416 selection_cache: traits::SelectionCache::new(),
6419 let cause = traits::ObligationCause::misc(span, free_id);
6420 return traits::normalize_param_env_or_error(unnormalized_env, cause);
6422 fn record_region_bounds<'tcx>(tcx: &ty::ctxt<'tcx>, predicates: &[ty::Predicate<'tcx>]) {
6423 debug!("record_region_bounds(predicates={:?})", predicates.repr(tcx));
6425 for predicate in predicates {
6427 Predicate::Projection(..) |
6428 Predicate::Trait(..) |
6429 Predicate::Equate(..) |
6430 Predicate::TypeOutlives(..) => {
6431 // No region bounds here
6433 Predicate::RegionOutlives(ty::Binder(ty::OutlivesPredicate(r_a, r_b))) => {
6435 (ty::ReFree(fr_a), ty::ReFree(fr_b)) => {
6436 // Record that `'a:'b`. Or, put another way, `'b <= 'a`.
6437 tcx.region_maps.relate_free_regions(fr_b, fr_a);
6440 // All named regions are instantiated with free regions.
6442 &format!("record_region_bounds: non free region: {} / {}",
6454 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
6456 ast::MutMutable => MutBorrow,
6457 ast::MutImmutable => ImmBorrow,
6461 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
6462 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
6463 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
6465 pub fn to_mutbl_lossy(self) -> ast::Mutability {
6467 MutBorrow => ast::MutMutable,
6468 ImmBorrow => ast::MutImmutable,
6470 // We have no type corresponding to a unique imm borrow, so
6471 // use `&mut`. It gives all the capabilities of an `&uniq`
6472 // and hence is a safe "over approximation".
6473 UniqueImmBorrow => ast::MutMutable,
6477 pub fn to_user_str(&self) -> &'static str {
6479 MutBorrow => "mutable",
6480 ImmBorrow => "immutable",
6481 UniqueImmBorrow => "uniquely immutable",
6486 impl<'tcx> ctxt<'tcx> {
6487 pub fn is_method_call(&self, expr_id: ast::NodeId) -> bool {
6488 self.method_map.borrow().contains_key(&MethodCall::expr(expr_id))
6491 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
6492 Some(self.upvar_capture_map.borrow().get(&upvar_id).unwrap().clone())
6496 impl<'a,'tcx> mc::Typer<'tcx> for ParameterEnvironment<'a,'tcx> {
6497 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<Ty<'tcx>> {
6498 Ok(ty::node_id_to_type(self.tcx, id))
6501 fn expr_ty_adjusted(&self, expr: &ast::Expr) -> mc::McResult<Ty<'tcx>> {
6502 Ok(ty::expr_ty_adjusted(self.tcx, expr))
6505 fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>> {
6506 self.tcx.method_map.borrow().get(&method_call).map(|method| method.ty)
6509 fn node_method_origin(&self, method_call: ty::MethodCall)
6510 -> Option<ty::MethodOrigin<'tcx>>
6512 self.tcx.method_map.borrow().get(&method_call).map(|method| method.origin.clone())
6515 fn adjustments(&self) -> &RefCell<NodeMap<ty::AutoAdjustment<'tcx>>> {
6516 &self.tcx.adjustments
6519 fn is_method_call(&self, id: ast::NodeId) -> bool {
6520 self.tcx.is_method_call(id)
6523 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent> {
6524 self.tcx.region_maps.temporary_scope(rvalue_id)
6527 fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
6528 self.tcx.upvar_capture(upvar_id)
6531 fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool {
6532 type_moves_by_default(self, span, ty)
6536 impl<'a,'tcx> ClosureTyper<'tcx> for ty::ParameterEnvironment<'a,'tcx> {
6537 fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> {
6541 fn closure_kind(&self,
6543 -> Option<ty::ClosureKind>
6545 Some(self.tcx.closure_kind(def_id))
6548 fn closure_type(&self,
6550 substs: &subst::Substs<'tcx>)
6551 -> ty::ClosureTy<'tcx>
6553 self.tcx.closure_type(def_id, substs)
6556 fn closure_upvars(&self,
6558 substs: &Substs<'tcx>)
6559 -> Option<Vec<ClosureUpvar<'tcx>>>
6561 closure_upvars(self, def_id, substs)
6566 /// The category of explicit self.
6567 #[derive(Clone, Copy, Eq, PartialEq, Debug)]
6568 pub enum ExplicitSelfCategory {
6569 StaticExplicitSelfCategory,
6570 ByValueExplicitSelfCategory,
6571 ByReferenceExplicitSelfCategory(Region, ast::Mutability),
6572 ByBoxExplicitSelfCategory,
6575 /// Pushes all the lifetimes in the given type onto the given list. A
6576 /// "lifetime in a type" is a lifetime specified by a reference or a lifetime
6577 /// in a list of type substitutions. This does *not* traverse into nominal
6578 /// types, nor does it resolve fictitious types.
6579 pub fn accumulate_lifetimes_in_type(accumulator: &mut Vec<ty::Region>,
6583 ty_rptr(region, _) => {
6584 accumulator.push(*region)
6586 ty_trait(ref t) => {
6587 accumulator.push_all(t.principal.0.substs.regions().as_slice());
6589 ty_enum(_, substs) |
6590 ty_struct(_, substs) => {
6591 accum_substs(accumulator, substs);
6593 ty_closure(_, substs) => {
6594 accum_substs(accumulator, substs);
6615 fn accum_substs(accumulator: &mut Vec<Region>, substs: &Substs) {
6616 match substs.regions {
6617 subst::ErasedRegions => {}
6618 subst::NonerasedRegions(ref regions) => {
6619 for region in regions.iter() {
6620 accumulator.push(*region)
6627 /// A free variable referred to in a function.
6628 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
6629 pub struct Freevar {
6630 /// The variable being accessed free.
6633 // First span where it is accessed (there can be multiple).
6637 pub type FreevarMap = NodeMap<Vec<Freevar>>;
6639 pub type CaptureModeMap = NodeMap<ast::CaptureClause>;
6641 // Trait method resolution
6642 pub type TraitMap = NodeMap<Vec<DefId>>;
6644 // Map from the NodeId of a glob import to a list of items which are actually
6646 pub type GlobMap = HashMap<NodeId, HashSet<Name>>;
6648 pub fn with_freevars<T, F>(tcx: &ty::ctxt, fid: ast::NodeId, f: F) -> T where
6649 F: FnOnce(&[Freevar]) -> T,
6651 match tcx.freevars.borrow().get(&fid) {
6653 Some(d) => f(&d[..])
6657 impl<'tcx> AutoAdjustment<'tcx> {
6658 pub fn is_identity(&self) -> bool {
6660 AdjustReifyFnPointer(..) => false,
6661 AdjustUnsafeFnPointer(..) => false,
6662 AdjustDerefRef(ref r) => r.is_identity(),
6667 impl<'tcx> AutoDerefRef<'tcx> {
6668 pub fn is_identity(&self) -> bool {
6669 self.autoderefs == 0 && self.autoref.is_none()
6673 /// Replace any late-bound regions bound in `value` with free variants attached to scope-id
6675 pub fn liberate_late_bound_regions<'tcx, T>(
6676 tcx: &ty::ctxt<'tcx>,
6677 all_outlive_scope: region::DestructionScopeData,
6680 where T : TypeFoldable<'tcx> + Repr<'tcx>
6682 replace_late_bound_regions(
6684 |br| ty::ReFree(ty::FreeRegion{scope: all_outlive_scope, bound_region: br})).0
6687 pub fn count_late_bound_regions<'tcx, T>(
6688 tcx: &ty::ctxt<'tcx>,
6691 where T : TypeFoldable<'tcx> + Repr<'tcx>
6693 let (_, skol_map) = replace_late_bound_regions(tcx, value, |_| ty::ReStatic);
6697 pub fn binds_late_bound_regions<'tcx, T>(
6698 tcx: &ty::ctxt<'tcx>,
6701 where T : TypeFoldable<'tcx> + Repr<'tcx>
6703 count_late_bound_regions(tcx, value) > 0
6706 /// Flattens two binding levels into one. So `for<'a> for<'b> Foo`
6707 /// becomes `for<'a,'b> Foo`.
6708 pub fn flatten_late_bound_regions<'tcx, T>(
6709 tcx: &ty::ctxt<'tcx>,
6710 bound2_value: &Binder<Binder<T>>)
6712 where T: TypeFoldable<'tcx> + Repr<'tcx>
6714 let bound0_value = bound2_value.skip_binder().skip_binder();
6715 let value = ty_fold::fold_regions(tcx, bound0_value, |region, current_depth| {
6717 ty::ReLateBound(debruijn, br) if debruijn.depth >= current_depth => {
6718 // should be true if no escaping regions from bound2_value
6719 assert!(debruijn.depth - current_depth <= 1);
6720 ty::ReLateBound(DebruijnIndex::new(current_depth), br)
6730 pub fn no_late_bound_regions<'tcx, T>(
6731 tcx: &ty::ctxt<'tcx>,
6734 where T : TypeFoldable<'tcx> + Repr<'tcx> + Clone
6736 if binds_late_bound_regions(tcx, value) {
6739 Some(value.0.clone())
6743 /// Replace any late-bound regions bound in `value` with `'static`. Useful in trans but also
6744 /// method lookup and a few other places where precise region relationships are not required.
6745 pub fn erase_late_bound_regions<'tcx, T>(
6746 tcx: &ty::ctxt<'tcx>,
6749 where T : TypeFoldable<'tcx> + Repr<'tcx>
6751 replace_late_bound_regions(tcx, value, |_| ty::ReStatic).0
6754 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
6755 /// assigned starting at 1 and increasing monotonically in the order traversed
6756 /// by the fold operation.
6758 /// The chief purpose of this function is to canonicalize regions so that two
6759 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
6760 /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
6761 /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
6762 pub fn anonymize_late_bound_regions<'tcx, T>(
6766 where T : TypeFoldable<'tcx> + Repr<'tcx>,
6768 let mut counter = 0;
6769 ty::Binder(replace_late_bound_regions(tcx, sig, |_| {
6771 ReLateBound(ty::DebruijnIndex::new(1), BrAnon(counter))
6775 /// Replaces the late-bound-regions in `value` that are bound by `value`.
6776 pub fn replace_late_bound_regions<'tcx, T, F>(
6777 tcx: &ty::ctxt<'tcx>,
6780 -> (T, FnvHashMap<ty::BoundRegion,ty::Region>)
6781 where T : TypeFoldable<'tcx> + Repr<'tcx>,
6782 F : FnMut(BoundRegion) -> ty::Region,
6784 debug!("replace_late_bound_regions({})", binder.repr(tcx));
6786 let mut map = FnvHashMap();
6788 // Note: fold the field `0`, not the binder, so that late-bound
6789 // regions bound by `binder` are considered free.
6790 let value = ty_fold::fold_regions(tcx, &binder.0, |region, current_depth| {
6791 debug!("region={}", region.repr(tcx));
6793 ty::ReLateBound(debruijn, br) if debruijn.depth == current_depth => {
6794 let region = *map.entry(br).or_insert_with(|| mapf(br));
6796 if let ty::ReLateBound(debruijn1, br) = region {
6797 // If the callback returns a late-bound region,
6798 // that region should always use depth 1. Then we
6799 // adjust it to the correct depth.
6800 assert_eq!(debruijn1.depth, 1);
6801 ty::ReLateBound(debruijn, br)
6812 debug!("resulting map: {:?} value: {:?}", map, value.repr(tcx));
6816 impl DebruijnIndex {
6817 pub fn new(depth: u32) -> DebruijnIndex {
6819 DebruijnIndex { depth: depth }
6822 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
6823 DebruijnIndex { depth: self.depth + amount }
6827 impl<'tcx> Repr<'tcx> for AutoAdjustment<'tcx> {
6828 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6830 AdjustReifyFnPointer(def_id) => {
6831 format!("AdjustReifyFnPointer({})", def_id.repr(tcx))
6833 AdjustUnsafeFnPointer => {
6834 format!("AdjustUnsafeFnPointer")
6836 AdjustDerefRef(ref data) => {
6843 impl<'tcx> Repr<'tcx> for UnsizeKind<'tcx> {
6844 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6846 UnsizeLength(n) => format!("UnsizeLength({})", n),
6847 UnsizeStruct(ref k, n) => format!("UnsizeStruct({},{})", k.repr(tcx), n),
6848 UnsizeVtable(ref a, ref b) => format!("UnsizeVtable({},{})", a.repr(tcx), b.repr(tcx)),
6849 UnsizeUpcast(ref a) => format!("UnsizeUpcast({})", a.repr(tcx)),
6854 impl<'tcx> Repr<'tcx> for AutoDerefRef<'tcx> {
6855 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6856 format!("AutoDerefRef({}, {})", self.autoderefs, self.autoref.repr(tcx))
6860 impl<'tcx> Repr<'tcx> for AutoRef<'tcx> {
6861 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6863 AutoPtr(a, b, ref c) => {
6864 format!("AutoPtr({},{:?},{})", a.repr(tcx), b, c.repr(tcx))
6866 AutoUnsize(ref a) => {
6867 format!("AutoUnsize({})", a.repr(tcx))
6869 AutoUnsizeUniq(ref a) => {
6870 format!("AutoUnsizeUniq({})", a.repr(tcx))
6872 AutoUnsafe(ref a, ref b) => {
6873 format!("AutoUnsafe({:?},{})", a, b.repr(tcx))
6879 impl<'tcx> Repr<'tcx> for TyTrait<'tcx> {
6880 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6881 format!("TyTrait({},{})",
6882 self.principal.repr(tcx),
6883 self.bounds.repr(tcx))
6887 impl<'tcx> Repr<'tcx> for ty::Predicate<'tcx> {
6888 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6890 Predicate::Trait(ref a) => a.repr(tcx),
6891 Predicate::Equate(ref pair) => pair.repr(tcx),
6892 Predicate::RegionOutlives(ref pair) => pair.repr(tcx),
6893 Predicate::TypeOutlives(ref pair) => pair.repr(tcx),
6894 Predicate::Projection(ref pair) => pair.repr(tcx),
6899 impl<'tcx> Repr<'tcx> for vtable_origin<'tcx> {
6900 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
6902 vtable_static(def_id, ref tys, ref vtable_res) => {
6903 format!("vtable_static({:?}:{}, {}, {})",
6905 ty::item_path_str(tcx, def_id),
6907 vtable_res.repr(tcx))
6910 vtable_param(x, y) => {
6911 format!("vtable_param({:?}, {})", x, y)
6914 vtable_closure(def_id) => {
6915 format!("vtable_closure({:?})", def_id)
6919 format!("vtable_error")
6925 pub fn make_substs_for_receiver_types<'tcx>(tcx: &ty::ctxt<'tcx>,
6926 trait_ref: &ty::TraitRef<'tcx>,
6927 method: &ty::Method<'tcx>)
6928 -> subst::Substs<'tcx>
6931 * Substitutes the values for the receiver's type parameters
6932 * that are found in method, leaving the method's type parameters
6936 let meth_tps: Vec<Ty> =
6937 method.generics.types.get_slice(subst::FnSpace)
6939 .map(|def| ty::mk_param_from_def(tcx, def))
6941 let meth_regions: Vec<ty::Region> =
6942 method.generics.regions.get_slice(subst::FnSpace)
6944 .map(|def| ty::ReEarlyBound(def.def_id.node, def.space,
6945 def.index, def.name))
6947 trait_ref.substs.clone().with_method(meth_tps, meth_regions)
6951 pub enum CopyImplementationError {
6952 FieldDoesNotImplementCopy(ast::Name),
6953 VariantDoesNotImplementCopy(ast::Name),
6958 pub fn can_type_implement_copy<'a,'tcx>(param_env: &ParameterEnvironment<'a, 'tcx>,
6960 self_type: Ty<'tcx>)
6961 -> Result<(),CopyImplementationError>
6963 let tcx = param_env.tcx;
6965 let did = match self_type.sty {
6966 ty::ty_struct(struct_did, substs) => {
6967 let fields = ty::struct_fields(tcx, struct_did, substs);
6968 for field in &fields {
6969 if type_moves_by_default(param_env, span, field.mt.ty) {
6970 return Err(FieldDoesNotImplementCopy(field.name))
6975 ty::ty_enum(enum_did, substs) => {
6976 let enum_variants = ty::enum_variants(tcx, enum_did);
6977 for variant in &*enum_variants {
6978 for variant_arg_type in &variant.args {
6979 let substd_arg_type =
6980 variant_arg_type.subst(tcx, substs);
6981 if type_moves_by_default(param_env, span, substd_arg_type) {
6982 return Err(VariantDoesNotImplementCopy(variant.name))
6988 _ => return Err(TypeIsStructural),
6991 if ty::has_dtor(tcx, did) {
6992 return Err(TypeHasDestructor)
6998 // FIXME(#20298) -- all of these types basically walk various
6999 // structures to test whether types/regions are reachable with various
7000 // properties. It should be possible to express them in terms of one
7001 // common "walker" trait or something.
7003 pub trait RegionEscape {
7004 fn has_escaping_regions(&self) -> bool {
7005 self.has_regions_escaping_depth(0)
7008 fn has_regions_escaping_depth(&self, depth: u32) -> bool;
7011 impl<'tcx> RegionEscape for Ty<'tcx> {
7012 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7013 ty::type_escapes_depth(*self, depth)
7017 impl<'tcx> RegionEscape for Substs<'tcx> {
7018 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7019 self.types.has_regions_escaping_depth(depth) ||
7020 self.regions.has_regions_escaping_depth(depth)
7024 impl<'tcx,T:RegionEscape> RegionEscape for VecPerParamSpace<T> {
7025 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7026 self.iter_enumerated().any(|(space, _, t)| {
7027 if space == subst::FnSpace {
7028 t.has_regions_escaping_depth(depth+1)
7030 t.has_regions_escaping_depth(depth)
7036 impl<'tcx> RegionEscape for TypeScheme<'tcx> {
7037 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7038 self.ty.has_regions_escaping_depth(depth)
7042 impl RegionEscape for Region {
7043 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7044 self.escapes_depth(depth)
7048 impl<'tcx> RegionEscape for GenericPredicates<'tcx> {
7049 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7050 self.predicates.has_regions_escaping_depth(depth)
7054 impl<'tcx> RegionEscape for Predicate<'tcx> {
7055 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7057 Predicate::Trait(ref data) => data.has_regions_escaping_depth(depth),
7058 Predicate::Equate(ref data) => data.has_regions_escaping_depth(depth),
7059 Predicate::RegionOutlives(ref data) => data.has_regions_escaping_depth(depth),
7060 Predicate::TypeOutlives(ref data) => data.has_regions_escaping_depth(depth),
7061 Predicate::Projection(ref data) => data.has_regions_escaping_depth(depth),
7066 impl<'tcx,P:RegionEscape> RegionEscape for traits::Obligation<'tcx,P> {
7067 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7068 self.predicate.has_regions_escaping_depth(depth)
7072 impl<'tcx> RegionEscape for TraitRef<'tcx> {
7073 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7074 self.substs.types.iter().any(|t| t.has_regions_escaping_depth(depth)) ||
7075 self.substs.regions.has_regions_escaping_depth(depth)
7079 impl<'tcx> RegionEscape for subst::RegionSubsts {
7080 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7082 subst::ErasedRegions => false,
7083 subst::NonerasedRegions(ref r) => {
7084 r.iter().any(|t| t.has_regions_escaping_depth(depth))
7090 impl<'tcx,T:RegionEscape> RegionEscape for Binder<T> {
7091 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7092 self.0.has_regions_escaping_depth(depth + 1)
7096 impl<'tcx> RegionEscape for EquatePredicate<'tcx> {
7097 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7098 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7102 impl<'tcx> RegionEscape for TraitPredicate<'tcx> {
7103 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7104 self.trait_ref.has_regions_escaping_depth(depth)
7108 impl<T:RegionEscape,U:RegionEscape> RegionEscape for OutlivesPredicate<T,U> {
7109 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7110 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7114 impl<'tcx> RegionEscape for ProjectionPredicate<'tcx> {
7115 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7116 self.projection_ty.has_regions_escaping_depth(depth) ||
7117 self.ty.has_regions_escaping_depth(depth)
7121 impl<'tcx> RegionEscape for ProjectionTy<'tcx> {
7122 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7123 self.trait_ref.has_regions_escaping_depth(depth)
7127 impl<'tcx> Repr<'tcx> for ty::ProjectionPredicate<'tcx> {
7128 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7129 format!("ProjectionPredicate({}, {})",
7130 self.projection_ty.repr(tcx),
7135 pub trait HasProjectionTypes {
7136 fn has_projection_types(&self) -> bool;
7139 impl<'tcx,T:HasProjectionTypes> HasProjectionTypes for Vec<T> {
7140 fn has_projection_types(&self) -> bool {
7141 self.iter().any(|p| p.has_projection_types())
7145 impl<'tcx,T:HasProjectionTypes> HasProjectionTypes for VecPerParamSpace<T> {
7146 fn has_projection_types(&self) -> bool {
7147 self.iter().any(|p| p.has_projection_types())
7151 impl<'tcx> HasProjectionTypes for ClosureTy<'tcx> {
7152 fn has_projection_types(&self) -> bool {
7153 self.sig.has_projection_types()
7157 impl<'tcx> HasProjectionTypes for ClosureUpvar<'tcx> {
7158 fn has_projection_types(&self) -> bool {
7159 self.ty.has_projection_types()
7163 impl<'tcx> HasProjectionTypes for ty::InstantiatedPredicates<'tcx> {
7164 fn has_projection_types(&self) -> bool {
7165 self.predicates.has_projection_types()
7169 impl<'tcx> HasProjectionTypes for Predicate<'tcx> {
7170 fn has_projection_types(&self) -> bool {
7172 Predicate::Trait(ref data) => data.has_projection_types(),
7173 Predicate::Equate(ref data) => data.has_projection_types(),
7174 Predicate::RegionOutlives(ref data) => data.has_projection_types(),
7175 Predicate::TypeOutlives(ref data) => data.has_projection_types(),
7176 Predicate::Projection(ref data) => data.has_projection_types(),
7181 impl<'tcx> HasProjectionTypes for TraitPredicate<'tcx> {
7182 fn has_projection_types(&self) -> bool {
7183 self.trait_ref.has_projection_types()
7187 impl<'tcx> HasProjectionTypes for EquatePredicate<'tcx> {
7188 fn has_projection_types(&self) -> bool {
7189 self.0.has_projection_types() || self.1.has_projection_types()
7193 impl HasProjectionTypes for Region {
7194 fn has_projection_types(&self) -> bool {
7199 impl<T:HasProjectionTypes,U:HasProjectionTypes> HasProjectionTypes for OutlivesPredicate<T,U> {
7200 fn has_projection_types(&self) -> bool {
7201 self.0.has_projection_types() || self.1.has_projection_types()
7205 impl<'tcx> HasProjectionTypes for ProjectionPredicate<'tcx> {
7206 fn has_projection_types(&self) -> bool {
7207 self.projection_ty.has_projection_types() || self.ty.has_projection_types()
7211 impl<'tcx> HasProjectionTypes for ProjectionTy<'tcx> {
7212 fn has_projection_types(&self) -> bool {
7213 self.trait_ref.has_projection_types()
7217 impl<'tcx> HasProjectionTypes for Ty<'tcx> {
7218 fn has_projection_types(&self) -> bool {
7219 ty::type_has_projection(*self)
7223 impl<'tcx> HasProjectionTypes for TraitRef<'tcx> {
7224 fn has_projection_types(&self) -> bool {
7225 self.substs.has_projection_types()
7229 impl<'tcx> HasProjectionTypes for subst::Substs<'tcx> {
7230 fn has_projection_types(&self) -> bool {
7231 self.types.iter().any(|t| t.has_projection_types())
7235 impl<'tcx,T> HasProjectionTypes for Option<T>
7236 where T : HasProjectionTypes
7238 fn has_projection_types(&self) -> bool {
7239 self.iter().any(|t| t.has_projection_types())
7243 impl<'tcx,T> HasProjectionTypes for Rc<T>
7244 where T : HasProjectionTypes
7246 fn has_projection_types(&self) -> bool {
7247 (**self).has_projection_types()
7251 impl<'tcx,T> HasProjectionTypes for Box<T>
7252 where T : HasProjectionTypes
7254 fn has_projection_types(&self) -> bool {
7255 (**self).has_projection_types()
7259 impl<T> HasProjectionTypes for Binder<T>
7260 where T : HasProjectionTypes
7262 fn has_projection_types(&self) -> bool {
7263 self.0.has_projection_types()
7267 impl<'tcx> HasProjectionTypes for FnOutput<'tcx> {
7268 fn has_projection_types(&self) -> bool {
7270 FnConverging(t) => t.has_projection_types(),
7271 FnDiverging => false,
7276 impl<'tcx> HasProjectionTypes for FnSig<'tcx> {
7277 fn has_projection_types(&self) -> bool {
7278 self.inputs.iter().any(|t| t.has_projection_types()) ||
7279 self.output.has_projection_types()
7283 impl<'tcx> HasProjectionTypes for field<'tcx> {
7284 fn has_projection_types(&self) -> bool {
7285 self.mt.ty.has_projection_types()
7289 impl<'tcx> HasProjectionTypes for BareFnTy<'tcx> {
7290 fn has_projection_types(&self) -> bool {
7291 self.sig.has_projection_types()
7295 pub trait ReferencesError {
7296 fn references_error(&self) -> bool;
7299 impl<T:ReferencesError> ReferencesError for Binder<T> {
7300 fn references_error(&self) -> bool {
7301 self.0.references_error()
7305 impl<T:ReferencesError> ReferencesError for Rc<T> {
7306 fn references_error(&self) -> bool {
7307 (&**self).references_error()
7311 impl<'tcx> ReferencesError for TraitPredicate<'tcx> {
7312 fn references_error(&self) -> bool {
7313 self.trait_ref.references_error()
7317 impl<'tcx> ReferencesError for ProjectionPredicate<'tcx> {
7318 fn references_error(&self) -> bool {
7319 self.projection_ty.trait_ref.references_error() || self.ty.references_error()
7323 impl<'tcx> ReferencesError for TraitRef<'tcx> {
7324 fn references_error(&self) -> bool {
7325 self.input_types().iter().any(|t| t.references_error())
7329 impl<'tcx> ReferencesError for Ty<'tcx> {
7330 fn references_error(&self) -> bool {
7331 type_is_error(*self)
7335 impl<'tcx> ReferencesError for Predicate<'tcx> {
7336 fn references_error(&self) -> bool {
7338 Predicate::Trait(ref data) => data.references_error(),
7339 Predicate::Equate(ref data) => data.references_error(),
7340 Predicate::RegionOutlives(ref data) => data.references_error(),
7341 Predicate::TypeOutlives(ref data) => data.references_error(),
7342 Predicate::Projection(ref data) => data.references_error(),
7347 impl<A,B> ReferencesError for OutlivesPredicate<A,B>
7348 where A : ReferencesError, B : ReferencesError
7350 fn references_error(&self) -> bool {
7351 self.0.references_error() || self.1.references_error()
7355 impl<'tcx> ReferencesError for EquatePredicate<'tcx>
7357 fn references_error(&self) -> bool {
7358 self.0.references_error() || self.1.references_error()
7362 impl ReferencesError for Region
7364 fn references_error(&self) -> bool {
7369 impl<'tcx> Repr<'tcx> for ClosureTy<'tcx> {
7370 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7371 format!("ClosureTy({},{},{})",
7378 impl<'tcx> Repr<'tcx> for ClosureUpvar<'tcx> {
7379 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7380 format!("ClosureUpvar({},{})",
7386 impl<'tcx> Repr<'tcx> for field<'tcx> {
7387 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7388 format!("field({},{})",
7389 self.name.repr(tcx),
7394 impl<'a, 'tcx> Repr<'tcx> for ParameterEnvironment<'a, 'tcx> {
7395 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7396 format!("ParameterEnvironment(\
7398 implicit_region_bound={}, \
7400 self.free_substs.repr(tcx),
7401 self.implicit_region_bound.repr(tcx),
7402 self.caller_bounds.repr(tcx))
7406 impl<'tcx> Repr<'tcx> for ObjectLifetimeDefault {
7407 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7409 ObjectLifetimeDefault::Ambiguous => format!("Ambiguous"),
7410 ObjectLifetimeDefault::Specific(ref r) => r.repr(tcx),