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::UnboxedClosureKind::*;
20 pub use self::ast_ty_to_ty_cache_entry::*;
21 pub use self::Variance::*;
22 pub use self::AutoAdjustment::*;
23 pub use self::Representability::*;
24 pub use self::UnsizeKind::*;
25 pub use self::AutoRef::*;
26 pub use self::ExprKind::*;
27 pub use self::DtorKind::*;
28 pub use self::ExplicitSelfCategory::*;
29 pub use self::FnOutput::*;
30 pub use self::Region::*;
31 pub use self::ImplOrTraitItemContainer::*;
32 pub use self::BorrowKind::*;
33 pub use self::ImplOrTraitItem::*;
34 pub use self::BoundRegion::*;
36 pub use self::IntVarValue::*;
37 pub use self::ExprAdjustment::*;
38 pub use self::vtable_origin::*;
39 pub use self::MethodOrigin::*;
40 pub use self::CopyImplementationError::*;
45 use metadata::csearch;
47 use middle::const_eval;
48 use middle::def::{self, DefMap, ExportMap};
49 use middle::dependency_format;
50 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem};
51 use middle::lang_items::{FnOnceTraitLangItem, TyDescStructLangItem};
52 use middle::mem_categorization as mc;
54 use middle::resolve_lifetime;
56 use middle::stability;
57 use middle::subst::{self, 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::{BorrowFrom, Cow};
71 use std::cell::{Cell, RefCell};
73 use std::fmt::{self, Show};
74 use std::hash::{Hash, Writer, SipHasher, Hasher};
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::{Onceness, StmtExpr, StmtSemi, StructField, UnnamedField};
85 use syntax::ast::{Visibility};
86 use syntax::ast_util::{self, is_local, lit_is_str, local_def, PostExpansionMethod};
87 use syntax::attr::{self, AttrMetaMethods};
88 use syntax::codemap::Span;
89 use syntax::parse::token::{self, InternedString, special_idents};
90 use syntax::{ast, ast_map};
94 pub const INITIAL_DISCRIMINANT_VALUE: Disr = 0;
98 /// The complete set of all analyses described in this module. This is
99 /// produced by the driver and fed to trans and later passes.
100 pub struct CrateAnalysis<'tcx> {
101 pub export_map: ExportMap,
102 pub exported_items: middle::privacy::ExportedItems,
103 pub public_items: middle::privacy::PublicItems,
104 pub ty_cx: ty::ctxt<'tcx>,
105 pub reachable: NodeSet,
107 pub glob_map: Option<GlobMap>,
110 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
111 pub struct field<'tcx> {
116 #[derive(Clone, Copy, Show)]
117 pub enum ImplOrTraitItemContainer {
118 TraitContainer(ast::DefId),
119 ImplContainer(ast::DefId),
122 impl ImplOrTraitItemContainer {
123 pub fn id(&self) -> ast::DefId {
125 TraitContainer(id) => id,
126 ImplContainer(id) => id,
131 #[derive(Clone, Show)]
132 pub enum ImplOrTraitItem<'tcx> {
133 MethodTraitItem(Rc<Method<'tcx>>),
134 TypeTraitItem(Rc<AssociatedType>),
137 impl<'tcx> ImplOrTraitItem<'tcx> {
138 fn id(&self) -> ImplOrTraitItemId {
140 MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
141 TypeTraitItem(ref associated_type) => {
142 TypeTraitItemId(associated_type.def_id)
147 pub fn def_id(&self) -> ast::DefId {
149 MethodTraitItem(ref method) => method.def_id,
150 TypeTraitItem(ref associated_type) => associated_type.def_id,
154 pub fn name(&self) -> ast::Name {
156 MethodTraitItem(ref method) => method.name,
157 TypeTraitItem(ref associated_type) => associated_type.name,
161 pub fn container(&self) -> ImplOrTraitItemContainer {
163 MethodTraitItem(ref method) => method.container,
164 TypeTraitItem(ref associated_type) => associated_type.container,
168 pub fn as_opt_method(&self) -> Option<Rc<Method<'tcx>>> {
170 MethodTraitItem(ref m) => Some((*m).clone()),
171 TypeTraitItem(_) => None
176 #[derive(Clone, Copy, Show)]
177 pub enum ImplOrTraitItemId {
178 MethodTraitItemId(ast::DefId),
179 TypeTraitItemId(ast::DefId),
182 impl ImplOrTraitItemId {
183 pub fn def_id(&self) -> ast::DefId {
185 MethodTraitItemId(def_id) => def_id,
186 TypeTraitItemId(def_id) => def_id,
191 #[derive(Clone, Show)]
192 pub struct Method<'tcx> {
194 pub generics: ty::Generics<'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>,
209 explicit_self: ExplicitSelfCategory,
210 vis: ast::Visibility,
212 container: ImplOrTraitItemContainer,
213 provided_source: Option<ast::DefId>)
219 explicit_self: explicit_self,
222 container: container,
223 provided_source: provided_source
227 pub fn container_id(&self) -> ast::DefId {
228 match self.container {
229 TraitContainer(id) => id,
230 ImplContainer(id) => id,
235 #[derive(Clone, Copy, Show)]
236 pub struct AssociatedType {
238 pub vis: ast::Visibility,
239 pub def_id: ast::DefId,
240 pub container: ImplOrTraitItemContainer,
243 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
244 pub struct mt<'tcx> {
246 pub mutbl: ast::Mutability,
249 #[derive(Clone, Copy, Show)]
250 pub struct field_ty {
253 pub vis: ast::Visibility,
254 pub origin: ast::DefId, // The DefId of the struct in which the field is declared.
257 // Contains information needed to resolve types and (in the future) look up
258 // the types of AST nodes.
259 #[derive(Copy, PartialEq, Eq, Hash)]
260 pub struct creader_cache_key {
267 pub enum ast_ty_to_ty_cache_entry<'tcx> {
268 atttce_unresolved, /* not resolved yet */
269 atttce_resolved(Ty<'tcx>) /* resolved to a type, irrespective of region */
272 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
273 pub struct ItemVariances {
274 pub types: VecPerParamSpace<Variance>,
275 pub regions: VecPerParamSpace<Variance>,
278 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Show, Copy)]
280 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
281 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
282 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
283 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
286 #[derive(Clone, Show)]
287 pub enum AutoAdjustment<'tcx> {
288 AdjustReifyFnPointer(ast::DefId), // go from a fn-item type to a fn-pointer type
289 AdjustDerefRef(AutoDerefRef<'tcx>)
292 #[derive(Clone, PartialEq, Show)]
293 pub enum UnsizeKind<'tcx> {
294 // [T, ..n] -> [T], the uint field is n.
296 // An unsize coercion applied to the tail field of a struct.
297 // The uint is the index of the type parameter which is unsized.
298 UnsizeStruct(Box<UnsizeKind<'tcx>>, uint),
299 UnsizeVtable(TyTrait<'tcx>, /* the self type of the trait */ Ty<'tcx>)
302 #[derive(Clone, Show)]
303 pub struct AutoDerefRef<'tcx> {
304 pub autoderefs: uint,
305 pub autoref: Option<AutoRef<'tcx>>
308 #[derive(Clone, PartialEq, Show)]
309 pub enum AutoRef<'tcx> {
310 /// Convert from T to &T
311 /// The third field allows us to wrap other AutoRef adjustments.
312 AutoPtr(Region, ast::Mutability, Option<Box<AutoRef<'tcx>>>),
314 /// Convert [T, ..n] to [T] (or similar, depending on the kind)
315 AutoUnsize(UnsizeKind<'tcx>),
317 /// Convert Box<[T, ..n]> to Box<[T]> or something similar in a Box.
318 /// With DST and Box a library type, this should be replaced by UnsizeStruct.
319 AutoUnsizeUniq(UnsizeKind<'tcx>),
321 /// Convert from T to *T
322 /// Value to thin pointer
323 /// The second field allows us to wrap other AutoRef adjustments.
324 AutoUnsafe(ast::Mutability, Option<Box<AutoRef<'tcx>>>),
327 // Ugly little helper function. The first bool in the returned tuple is true if
328 // there is an 'unsize to trait object' adjustment at the bottom of the
329 // adjustment. If that is surrounded by an AutoPtr, then we also return the
330 // region of the AutoPtr (in the third argument). The second bool is true if the
331 // adjustment is unique.
332 fn autoref_object_region(autoref: &AutoRef) -> (bool, bool, Option<Region>) {
333 fn unsize_kind_is_object(k: &UnsizeKind) -> bool {
335 &UnsizeVtable(..) => true,
336 &UnsizeStruct(box ref k, _) => unsize_kind_is_object(k),
342 &AutoUnsize(ref k) => (unsize_kind_is_object(k), false, None),
343 &AutoUnsizeUniq(ref k) => (unsize_kind_is_object(k), true, None),
344 &AutoPtr(adj_r, _, Some(box ref autoref)) => {
345 let (b, u, r) = autoref_object_region(autoref);
346 if r.is_some() || u {
352 &AutoUnsafe(_, Some(box ref autoref)) => autoref_object_region(autoref),
353 _ => (false, false, None)
357 // If the adjustment introduces a borrowed reference to a trait object, then
358 // returns the region of the borrowed reference.
359 pub fn adjusted_object_region(adj: &AutoAdjustment) -> Option<Region> {
361 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
362 let (b, _, r) = autoref_object_region(autoref);
373 // Returns true if there is a trait cast at the bottom of the adjustment.
374 pub fn adjust_is_object(adj: &AutoAdjustment) -> bool {
376 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
377 let (b, _, _) = autoref_object_region(autoref);
384 // If possible, returns the type expected from the given adjustment. This is not
385 // possible if the adjustment depends on the type of the adjusted expression.
386 pub fn type_of_adjust<'tcx>(cx: &ctxt<'tcx>, adj: &AutoAdjustment<'tcx>) -> Option<Ty<'tcx>> {
387 fn type_of_autoref<'tcx>(cx: &ctxt<'tcx>, autoref: &AutoRef<'tcx>) -> Option<Ty<'tcx>> {
389 &AutoUnsize(ref k) => match k {
390 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
391 Some(mk_trait(cx, principal.clone(), bounds.clone()))
395 &AutoUnsizeUniq(ref k) => match k {
396 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
397 Some(mk_uniq(cx, mk_trait(cx, principal.clone(), bounds.clone())))
401 &AutoPtr(r, m, Some(box ref autoref)) => {
402 match type_of_autoref(cx, autoref) {
403 Some(ty) => Some(mk_rptr(cx, cx.mk_region(r), mt {mutbl: m, ty: ty})),
407 &AutoUnsafe(m, Some(box ref autoref)) => {
408 match type_of_autoref(cx, autoref) {
409 Some(ty) => Some(mk_ptr(cx, mt {mutbl: m, ty: ty})),
418 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
419 type_of_autoref(cx, autoref)
425 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Show)]
426 pub struct param_index {
427 pub space: subst::ParamSpace,
431 #[derive(Clone, Show)]
432 pub enum MethodOrigin<'tcx> {
433 // fully statically resolved method
434 MethodStatic(ast::DefId),
436 // fully statically resolved unboxed closure invocation
437 MethodStaticUnboxedClosure(ast::DefId),
439 // method invoked on a type parameter with a bounded trait
440 MethodTypeParam(MethodParam<'tcx>),
442 // method invoked on a trait instance
443 MethodTraitObject(MethodObject<'tcx>),
447 // details for a method invoked with a receiver whose type is a type parameter
448 // with a bounded trait.
449 #[derive(Clone, Show)]
450 pub struct MethodParam<'tcx> {
451 // the precise trait reference that occurs as a bound -- this may
452 // be a supertrait of what the user actually typed. Note that it
453 // never contains bound regions; those regions should have been
454 // instantiated with fresh variables at this point.
455 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
457 // index of uint in the list of methods for the trait
458 pub method_num: uint,
461 // details for a method invoked with a receiver whose type is an object
462 #[derive(Clone, Show)]
463 pub struct MethodObject<'tcx> {
464 // the (super)trait containing the method to be invoked
465 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
467 // the actual base trait id of the object
468 pub object_trait_id: ast::DefId,
470 // index of the method to be invoked amongst the trait's methods
471 pub method_num: uint,
473 // index into the actual runtime vtable.
474 // the vtable is formed by concatenating together the method lists of
475 // the base object trait and all supertraits; this is the index into
477 pub real_index: uint,
481 pub struct MethodCallee<'tcx> {
482 pub origin: MethodOrigin<'tcx>,
484 pub substs: subst::Substs<'tcx>
487 /// With method calls, we store some extra information in
488 /// side tables (i.e method_map). We use
489 /// MethodCall as a key to index into these tables instead of
490 /// just directly using the expression's NodeId. The reason
491 /// for this being that we may apply adjustments (coercions)
492 /// with the resulting expression also needing to use the
493 /// side tables. The problem with this is that we don't
494 /// assign a separate NodeId to this new expression
495 /// and so it would clash with the base expression if both
496 /// needed to add to the side tables. Thus to disambiguate
497 /// we also keep track of whether there's an adjustment in
499 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
500 pub struct MethodCall {
501 pub expr_id: ast::NodeId,
502 pub adjustment: ExprAdjustment
505 #[derive(Clone, PartialEq, Eq, Hash, Show, RustcEncodable, RustcDecodable, Copy)]
506 pub enum ExprAdjustment {
513 pub fn expr(id: ast::NodeId) -> MethodCall {
516 adjustment: NoAdjustment
520 pub fn autoobject(id: ast::NodeId) -> MethodCall {
523 adjustment: AutoObject
527 pub fn autoderef(expr_id: ast::NodeId, autoderef: uint) -> MethodCall {
530 adjustment: AutoDeref(1 + autoderef)
535 // maps from an expression id that corresponds to a method call to the details
536 // of the method to be invoked
537 pub type MethodMap<'tcx> = RefCell<FnvHashMap<MethodCall, MethodCallee<'tcx>>>;
539 pub type vtable_param_res<'tcx> = Vec<vtable_origin<'tcx>>;
541 // Resolutions for bounds of all parameters, left to right, for a given path.
542 pub type vtable_res<'tcx> = VecPerParamSpace<vtable_param_res<'tcx>>;
545 pub enum vtable_origin<'tcx> {
547 Statically known vtable. def_id gives the impl item
548 from whence comes the vtable, and tys are the type substs.
549 vtable_res is the vtable itself.
551 vtable_static(ast::DefId, subst::Substs<'tcx>, vtable_res<'tcx>),
554 Dynamic vtable, comes from a parameter that has a bound on it:
555 fn foo<T:quux,baz,bar>(a: T) -- a's vtable would have a
558 The first argument is the param index (identifying T in the example),
559 and the second is the bound number (identifying baz)
561 vtable_param(param_index, uint),
564 Vtable automatically generated for an unboxed closure. The def ID is the
565 ID of the closure expression.
567 vtable_unboxed_closure(ast::DefId),
570 Asked to determine the vtable for ty_err. This is the value used
571 for the vtables of `Self` in a virtual call like `foo.bar()`
572 where `foo` is of object type. The same value is also used when
579 // For every explicit cast into an object type, maps from the cast
580 // expr to the associated trait ref.
581 pub type ObjectCastMap<'tcx> = RefCell<NodeMap<ty::PolyTraitRef<'tcx>>>;
583 /// A restriction that certain types must be the same size. The use of
584 /// `transmute` gives rise to these restrictions. These generally
585 /// cannot be checked until trans; therefore, each call to `transmute`
586 /// will push one or more such restriction into the
587 /// `transmute_restrictions` vector during `intrinsicck`. They are
588 /// then checked during `trans` by the fn `check_intrinsics`.
590 pub struct TransmuteRestriction<'tcx> {
591 /// The span whence the restriction comes.
594 /// The type being transmuted from.
595 pub original_from: Ty<'tcx>,
597 /// The type being transmuted to.
598 pub original_to: Ty<'tcx>,
600 /// The type being transmuted from, with all type parameters
601 /// substituted for an arbitrary representative. Not to be shown
603 pub substituted_from: Ty<'tcx>,
605 /// The type being transmuted to, with all type parameters
606 /// substituted for an arbitrary representative. Not to be shown
608 pub substituted_to: Ty<'tcx>,
610 /// NodeId of the transmute intrinsic.
615 pub struct CtxtArenas<'tcx> {
616 type_: TypedArena<TyS<'tcx>>,
617 substs: TypedArena<Substs<'tcx>>,
618 bare_fn: TypedArena<BareFnTy<'tcx>>,
619 region: TypedArena<Region>,
622 impl<'tcx> CtxtArenas<'tcx> {
623 pub fn new() -> CtxtArenas<'tcx> {
625 type_: TypedArena::new(),
626 substs: TypedArena::new(),
627 bare_fn: TypedArena::new(),
628 region: TypedArena::new(),
633 pub struct CommonTypes<'tcx> {
651 /// The data structure to keep track of all the information that typechecker
652 /// generates so that so that it can be reused and doesn't have to be redone
654 pub struct ctxt<'tcx> {
655 /// The arenas that types etc are allocated from.
656 arenas: &'tcx CtxtArenas<'tcx>,
658 /// Specifically use a speedy hash algorithm for this hash map, it's used
660 // FIXME(eddyb) use a FnvHashSet<InternedTy<'tcx>> when equivalent keys can
661 // queried from a HashSet.
662 interner: RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>,
664 // FIXME as above, use a hashset if equivalent elements can be queried.
665 substs_interner: RefCell<FnvHashMap<&'tcx Substs<'tcx>, &'tcx Substs<'tcx>>>,
666 bare_fn_interner: RefCell<FnvHashMap<&'tcx BareFnTy<'tcx>, &'tcx BareFnTy<'tcx>>>,
667 region_interner: RefCell<FnvHashMap<&'tcx Region, &'tcx Region>>,
669 /// Common types, pre-interned for your convenience.
670 pub types: CommonTypes<'tcx>,
675 pub named_region_map: resolve_lifetime::NamedRegionMap,
677 pub region_maps: middle::region::RegionMaps,
679 /// Stores the types for various nodes in the AST. Note that this table
680 /// is not guaranteed to be populated until after typeck. See
681 /// typeck::check::fn_ctxt for details.
682 pub node_types: RefCell<NodeMap<Ty<'tcx>>>,
684 /// Stores the type parameters which were substituted to obtain the type
685 /// of this node. This only applies to nodes that refer to entities
686 /// parameterized by type parameters, such as generic fns, types, or
688 pub item_substs: RefCell<NodeMap<ItemSubsts<'tcx>>>,
690 /// Maps from a trait item to the trait item "descriptor"
691 pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem<'tcx>>>,
693 /// Maps from a trait def-id to a list of the def-ids of its trait items
694 pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
696 /// A cache for the trait_items() routine
697 pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem<'tcx>>>>>,
699 pub impl_trait_cache: RefCell<DefIdMap<Option<Rc<ty::TraitRef<'tcx>>>>>,
701 pub trait_refs: RefCell<NodeMap<Rc<TraitRef<'tcx>>>>,
702 pub trait_defs: RefCell<DefIdMap<Rc<TraitDef<'tcx>>>>,
704 /// Maps from node-id of a trait object cast (like `foo as
705 /// Box<Trait>`) to the trait reference.
706 pub object_cast_map: ObjectCastMap<'tcx>,
708 pub map: ast_map::Map<'tcx>,
709 pub intrinsic_defs: RefCell<DefIdMap<Ty<'tcx>>>,
710 pub freevars: RefCell<FreevarMap>,
711 pub tcache: RefCell<DefIdMap<TypeScheme<'tcx>>>,
712 pub rcache: RefCell<FnvHashMap<creader_cache_key, Ty<'tcx>>>,
713 pub short_names_cache: RefCell<FnvHashMap<Ty<'tcx>, String>>,
714 pub tc_cache: RefCell<FnvHashMap<Ty<'tcx>, TypeContents>>,
715 pub ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry<'tcx>>>,
716 pub enum_var_cache: RefCell<DefIdMap<Rc<Vec<Rc<VariantInfo<'tcx>>>>>>,
717 pub ty_param_defs: RefCell<NodeMap<TypeParameterDef<'tcx>>>,
718 pub adjustments: RefCell<NodeMap<AutoAdjustment<'tcx>>>,
719 pub normalized_cache: RefCell<FnvHashMap<Ty<'tcx>, Ty<'tcx>>>,
720 pub lang_items: middle::lang_items::LanguageItems,
721 /// A mapping of fake provided method def_ids to the default implementation
722 pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
723 pub struct_fields: RefCell<DefIdMap<Rc<Vec<field_ty>>>>,
725 /// Maps from def-id of a type or region parameter to its
726 /// (inferred) variance.
727 pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
729 /// True if the variance has been computed yet; false otherwise.
730 pub variance_computed: Cell<bool>,
732 /// A mapping from the def ID of an enum or struct type to the def ID
733 /// of the method that implements its destructor. If the type is not
734 /// present in this map, it does not have a destructor. This map is
735 /// populated during the coherence phase of typechecking.
736 pub destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
738 /// A method will be in this list if and only if it is a destructor.
739 pub destructors: RefCell<DefIdSet>,
741 /// Maps a trait onto a list of impls of that trait.
742 pub trait_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
744 /// Maps a DefId of a type to a list of its inherent impls.
745 /// Contains implementations of methods that are inherent to a type.
746 /// Methods in these implementations don't need to be exported.
747 pub inherent_impls: RefCell<DefIdMap<Rc<Vec<ast::DefId>>>>,
749 /// Maps a DefId of an impl to a list of its items.
750 /// Note that this contains all of the impls that we know about,
751 /// including ones in other crates. It's not clear that this is the best
753 pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
755 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
756 /// present in this set can be warned about.
757 pub used_unsafe: RefCell<NodeSet>,
759 /// Set of nodes which mark locals as mutable which end up getting used at
760 /// some point. Local variable definitions not in this set can be warned
762 pub used_mut_nodes: RefCell<NodeSet>,
764 /// The set of external nominal types whose implementations have been read.
765 /// This is used for lazy resolution of methods.
766 pub populated_external_types: RefCell<DefIdSet>,
768 /// The set of external traits whose implementations have been read. This
769 /// is used for lazy resolution of traits.
770 pub populated_external_traits: RefCell<DefIdSet>,
773 pub upvar_borrow_map: RefCell<UpvarBorrowMap>,
775 /// These two caches are used by const_eval when decoding external statics
776 /// and variants that are found.
777 pub extern_const_statics: RefCell<DefIdMap<ast::NodeId>>,
778 pub extern_const_variants: RefCell<DefIdMap<ast::NodeId>>,
780 pub method_map: MethodMap<'tcx>,
782 pub dependency_formats: RefCell<dependency_format::Dependencies>,
784 /// Records the type of each unboxed closure. The def ID is the ID of the
785 /// expression defining the unboxed closure.
786 pub unboxed_closures: RefCell<DefIdMap<UnboxedClosure<'tcx>>>,
788 pub node_lint_levels: RefCell<FnvHashMap<(ast::NodeId, lint::LintId),
791 /// The types that must be asserted to be the same size for `transmute`
792 /// to be valid. We gather up these restrictions in the intrinsicck pass
793 /// and check them in trans.
794 pub transmute_restrictions: RefCell<Vec<TransmuteRestriction<'tcx>>>,
796 /// Maps any item's def-id to its stability index.
797 pub stability: RefCell<stability::Index>,
799 /// Maps closures to their capture clauses.
800 pub capture_modes: RefCell<CaptureModeMap>,
802 /// Maps def IDs to true if and only if they're associated types.
803 pub associated_types: RefCell<DefIdMap<bool>>,
805 /// Caches the results of trait selection. This cache is used
806 /// for things that do not have to do with the parameters in scope.
807 pub selection_cache: traits::SelectionCache<'tcx>,
809 /// Caches the representation hints for struct definitions.
810 pub repr_hint_cache: RefCell<DefIdMap<Rc<Vec<attr::ReprAttr>>>>,
812 /// Caches whether types are known to impl Copy. Note that type
813 /// parameters are never placed into this cache, because their
814 /// results are dependent on the parameter environment.
815 pub type_impls_copy_cache: RefCell<HashMap<Ty<'tcx>,bool>>,
817 /// Caches whether types are known to impl Sized. Note that type
818 /// parameters are never placed into this cache, because their
819 /// results are dependent on the parameter environment.
820 pub type_impls_sized_cache: RefCell<HashMap<Ty<'tcx>,bool>>,
822 /// Caches whether traits are object safe
823 pub object_safety_cache: RefCell<DefIdMap<bool>>,
826 // Flags that we track on types. These flags are propagated upwards
827 // through the type during type construction, so that we can quickly
828 // check whether the type has various kinds of types in it without
829 // recursing over the type itself.
831 flags TypeFlags: u32 {
832 const NO_TYPE_FLAGS = 0b0,
833 const HAS_PARAMS = 0b1,
834 const HAS_SELF = 0b10,
835 const HAS_TY_INFER = 0b100,
836 const HAS_RE_INFER = 0b1000,
837 const HAS_RE_LATE_BOUND = 0b10000,
838 const HAS_REGIONS = 0b100000,
839 const HAS_TY_ERR = 0b1000000,
840 const HAS_PROJECTION = 0b10000000,
841 const NEEDS_SUBST = HAS_PARAMS.bits | HAS_SELF.bits | HAS_REGIONS.bits,
845 macro_rules! sty_debug_print {
846 ($ctxt: expr, $($variant: ident),*) => {{
847 // curious inner module to allow variant names to be used as
859 pub fn go(tcx: &ty::ctxt) {
860 let mut total = DebugStat {
862 region_infer: 0, ty_infer: 0, both_infer: 0,
864 $(let mut $variant = total;)*
867 for (_, t) in tcx.interner.borrow().iter() {
868 let variant = match t.sty {
869 ty::ty_bool | ty::ty_char | ty::ty_int(..) | ty::ty_uint(..) |
870 ty::ty_float(..) | ty::ty_str => continue,
871 ty::ty_err => /* unimportant */ continue,
872 $(ty::$variant(..) => &mut $variant,)*
874 let region = t.flags.intersects(ty::HAS_RE_INFER);
875 let ty = t.flags.intersects(ty::HAS_TY_INFER);
879 if region { total.region_infer += 1; variant.region_infer += 1 }
880 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
881 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
883 println!("Ty interner total ty region both");
884 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
885 {ty:4.1}% {region:5.1}% {both:4.1}%",
886 stringify!($variant),
887 uses = $variant.total,
888 usespc = $variant.total as f64 * 100.0 / total.total as f64,
889 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
890 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
891 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
893 println!(" total {uses:6} \
894 {ty:4.1}% {region:5.1}% {both:4.1}%",
896 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
897 region = total.region_infer as f64 * 100.0 / total.total as f64,
898 both = total.both_infer as f64 * 100.0 / total.total as f64)
906 impl<'tcx> ctxt<'tcx> {
907 pub fn print_debug_stats(&self) {
910 ty_enum, ty_uniq, ty_vec, ty_ptr, ty_rptr, ty_bare_fn, ty_trait,
911 ty_struct, ty_unboxed_closure, ty_tup, ty_param, ty_open, ty_infer, ty_projection);
913 println!("Substs interner: #{}", self.substs_interner.borrow().len());
914 println!("BareFnTy interner: #{}", self.bare_fn_interner.borrow().len());
915 println!("Region interner: #{}", self.region_interner.borrow().len());
920 pub struct TyS<'tcx> {
922 pub flags: TypeFlags,
924 // the maximal depth of any bound regions appearing in this type.
928 impl fmt::Debug for TypeFlags {
929 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
930 write!(f, "{}", self.bits)
934 impl<'tcx> PartialEq for TyS<'tcx> {
935 fn eq(&self, other: &TyS<'tcx>) -> bool {
936 (self as *const _) == (other as *const _)
939 impl<'tcx> Eq for TyS<'tcx> {}
941 impl<'tcx, S: Writer + Hasher> Hash<S> for TyS<'tcx> {
942 fn hash(&self, s: &mut S) {
943 (self as *const _).hash(s)
947 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
949 /// An entry in the type interner.
950 pub struct InternedTy<'tcx> {
954 // NB: An InternedTy compares and hashes as a sty.
955 impl<'tcx> PartialEq for InternedTy<'tcx> {
956 fn eq(&self, other: &InternedTy<'tcx>) -> bool {
957 self.ty.sty == other.ty.sty
961 impl<'tcx> Eq for InternedTy<'tcx> {}
963 impl<'tcx, S: Writer + Hasher> Hash<S> for InternedTy<'tcx> {
964 fn hash(&self, s: &mut S) {
969 impl<'tcx> BorrowFrom<InternedTy<'tcx>> for sty<'tcx> {
970 fn borrow_from<'a>(ty: &'a InternedTy<'tcx>) -> &'a sty<'tcx> {
975 pub fn type_has_params(ty: Ty) -> bool {
976 ty.flags.intersects(HAS_PARAMS)
978 pub fn type_has_self(ty: Ty) -> bool {
979 ty.flags.intersects(HAS_SELF)
981 pub fn type_has_ty_infer(ty: Ty) -> bool {
982 ty.flags.intersects(HAS_TY_INFER)
984 pub fn type_needs_infer(ty: Ty) -> bool {
985 ty.flags.intersects(HAS_TY_INFER | HAS_RE_INFER)
987 pub fn type_has_projection(ty: Ty) -> bool {
988 ty.flags.intersects(HAS_PROJECTION)
991 pub fn type_has_late_bound_regions(ty: Ty) -> bool {
992 ty.flags.intersects(HAS_RE_LATE_BOUND)
995 /// An "escaping region" is a bound region whose binder is not part of `t`.
997 /// So, for example, consider a type like the following, which has two binders:
999 /// for<'a> fn(x: for<'b> fn(&'a int, &'b int))
1000 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
1001 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
1003 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
1004 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
1005 /// fn type*, that type has an escaping region: `'a`.
1007 /// Note that what I'm calling an "escaping region" is often just called a "free region". However,
1008 /// we already use the term "free region". It refers to the regions that we use to represent bound
1009 /// regions on a fn definition while we are typechecking its body.
1011 /// To clarify, conceptually there is no particular difference between an "escaping" region and a
1012 /// "free" region. However, there is a big difference in practice. Basically, when "entering" a
1013 /// binding level, one is generally required to do some sort of processing to a bound region, such
1014 /// as replacing it with a fresh/skolemized region, or making an entry in the environment to
1015 /// represent the scope to which it is attached, etc. An escaping region represents a bound region
1016 /// for which this processing has not yet been done.
1017 pub fn type_has_escaping_regions(ty: Ty) -> bool {
1018 type_escapes_depth(ty, 0)
1021 pub fn type_escapes_depth(ty: Ty, depth: u32) -> bool {
1022 ty.region_depth > depth
1025 #[derive(Clone, PartialEq, Eq, Hash, Show)]
1026 pub struct BareFnTy<'tcx> {
1027 pub unsafety: ast::Unsafety,
1029 pub sig: PolyFnSig<'tcx>,
1032 #[derive(Clone, PartialEq, Eq, Hash, Show)]
1033 pub struct ClosureTy<'tcx> {
1034 pub unsafety: ast::Unsafety,
1036 pub sig: PolyFnSig<'tcx>,
1039 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
1040 pub enum FnOutput<'tcx> {
1041 FnConverging(Ty<'tcx>),
1045 impl<'tcx> FnOutput<'tcx> {
1046 pub fn diverges(&self) -> bool {
1047 *self == FnDiverging
1050 pub fn unwrap(self) -> Ty<'tcx> {
1052 ty::FnConverging(t) => t,
1053 ty::FnDiverging => unreachable!()
1058 pub type PolyFnOutput<'tcx> = Binder<FnOutput<'tcx>>;
1060 impl<'tcx> PolyFnOutput<'tcx> {
1061 pub fn diverges(&self) -> bool {
1066 /// Signature of a function type, which I have arbitrarily
1067 /// decided to use to refer to the input/output types.
1069 /// - `inputs` is the list of arguments and their modes.
1070 /// - `output` is the return type.
1071 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
1072 #[derive(Clone, PartialEq, Eq, Hash)]
1073 pub struct FnSig<'tcx> {
1074 pub inputs: Vec<Ty<'tcx>>,
1075 pub output: FnOutput<'tcx>,
1079 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1081 impl<'tcx> PolyFnSig<'tcx> {
1082 pub fn inputs(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
1083 ty::Binder(self.0.inputs.clone())
1085 pub fn input(&self, index: uint) -> ty::Binder<Ty<'tcx>> {
1086 ty::Binder(self.0.inputs[index])
1088 pub fn output(&self) -> ty::Binder<FnOutput<'tcx>> {
1089 ty::Binder(self.0.output.clone())
1091 pub fn variadic(&self) -> bool {
1096 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
1097 pub struct ParamTy {
1098 pub space: subst::ParamSpace,
1100 pub name: ast::Name,
1103 /// A [De Bruijn index][dbi] is a standard means of representing
1104 /// regions (and perhaps later types) in a higher-ranked setting. In
1105 /// particular, imagine a type like this:
1107 /// for<'a> fn(for<'b> fn(&'b int, &'a int), &'a char)
1110 /// | +------------+ 1 | |
1112 /// +--------------------------------+ 2 |
1114 /// +------------------------------------------+ 1
1116 /// In this type, there are two binders (the outer fn and the inner
1117 /// fn). We need to be able to determine, for any given region, which
1118 /// fn type it is bound by, the inner or the outer one. There are
1119 /// various ways you can do this, but a De Bruijn index is one of the
1120 /// more convenient and has some nice properties. The basic idea is to
1121 /// count the number of binders, inside out. Some examples should help
1122 /// clarify what I mean.
1124 /// Let's start with the reference type `&'b int` that is the first
1125 /// argument to the inner function. This region `'b` is assigned a De
1126 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
1127 /// fn). The region `'a` that appears in the second argument type (`&'a
1128 /// int`) would then be assigned a De Bruijn index of 2, meaning "the
1129 /// second-innermost binder". (These indices are written on the arrays
1130 /// in the diagram).
1132 /// What is interesting is that De Bruijn index attached to a particular
1133 /// variable will vary depending on where it appears. For example,
1134 /// the final type `&'a char` also refers to the region `'a` declared on
1135 /// the outermost fn. But this time, this reference is not nested within
1136 /// any other binders (i.e., it is not an argument to the inner fn, but
1137 /// rather the outer one). Therefore, in this case, it is assigned a
1138 /// De Bruijn index of 1, because the innermost binder in that location
1139 /// is the outer fn.
1141 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1142 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show, Copy)]
1143 pub struct DebruijnIndex {
1144 // We maintain the invariant that this is never 0. So 1 indicates
1145 // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
1149 /// Representation of regions:
1150 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show, Copy)]
1152 // Region bound in a type or fn declaration which will be
1153 // substituted 'early' -- that is, at the same time when type
1154 // parameters are substituted.
1155 ReEarlyBound(/* param id */ ast::NodeId,
1160 // Region bound in a function scope, which will be substituted when the
1161 // function is called.
1162 ReLateBound(DebruijnIndex, BoundRegion),
1164 /// When checking a function body, the types of all arguments and so forth
1165 /// that refer to bound region parameters are modified to refer to free
1166 /// region parameters.
1169 /// A concrete region naming some expression within the current function.
1170 ReScope(region::CodeExtent),
1172 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1175 /// A region variable. Should not exist after typeck.
1176 ReInfer(InferRegion),
1178 /// Empty lifetime is for data that is never accessed.
1179 /// Bottom in the region lattice. We treat ReEmpty somewhat
1180 /// specially; at least right now, we do not generate instances of
1181 /// it during the GLB computations, but rather
1182 /// generate an error instead. This is to improve error messages.
1183 /// The only way to get an instance of ReEmpty is to have a region
1184 /// variable with no constraints.
1188 /// Upvars do not get their own node-id. Instead, we use the pair of
1189 /// the original var id (that is, the root variable that is referenced
1190 /// by the upvar) and the id of the closure expression.
1191 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
1192 pub struct UpvarId {
1193 pub var_id: ast::NodeId,
1194 pub closure_expr_id: ast::NodeId,
1197 #[derive(Clone, PartialEq, Eq, Hash, Show, RustcEncodable, RustcDecodable, Copy)]
1198 pub enum BorrowKind {
1199 /// Data must be immutable and is aliasable.
1202 /// Data must be immutable but not aliasable. This kind of borrow
1203 /// cannot currently be expressed by the user and is used only in
1204 /// implicit closure bindings. It is needed when you the closure
1205 /// is borrowing or mutating a mutable referent, e.g.:
1207 /// let x: &mut int = ...;
1208 /// let y = || *x += 5;
1210 /// If we were to try to translate this closure into a more explicit
1211 /// form, we'd encounter an error with the code as written:
1213 /// struct Env { x: & &mut int }
1214 /// let x: &mut int = ...;
1215 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
1216 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1218 /// This is then illegal because you cannot mutate a `&mut` found
1219 /// in an aliasable location. To solve, you'd have to translate with
1220 /// an `&mut` borrow:
1222 /// struct Env { x: & &mut int }
1223 /// let x: &mut int = ...;
1224 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
1225 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1227 /// Now the assignment to `**env.x` is legal, but creating a
1228 /// mutable pointer to `x` is not because `x` is not mutable. We
1229 /// could fix this by declaring `x` as `let mut x`. This is ok in
1230 /// user code, if awkward, but extra weird for closures, since the
1231 /// borrow is hidden.
1233 /// So we introduce a "unique imm" borrow -- the referent is
1234 /// immutable, but not aliasable. This solves the problem. For
1235 /// simplicity, we don't give users the way to express this
1236 /// borrow, it's just used when translating closures.
1239 /// Data is mutable and not aliasable.
1243 /// Information describing the borrowing of an upvar. This is computed
1244 /// during `typeck`, specifically by `regionck`. The general idea is
1245 /// that the compiler analyses treat closures like:
1247 /// let closure: &'e fn() = || {
1248 /// x = 1; // upvar x is assigned to
1249 /// use(y); // upvar y is read
1250 /// foo(&z); // upvar z is borrowed immutably
1253 /// as if they were "desugared" to something loosely like:
1255 /// struct Vars<'x,'y,'z> { x: &'x mut int,
1256 /// y: &'y const int,
1258 /// let closure: &'e fn() = {
1259 /// fn f(env: &Vars) {
1264 /// let env: &'e mut Vars<'x,'y,'z> = &mut Vars { x: &'x mut x,
1270 /// This is basically what happens at runtime. The closure is basically
1271 /// an existentially quantified version of the `(env, f)` pair.
1273 /// This data structure indicates the region and mutability of a single
1274 /// one of the `x...z` borrows.
1276 /// It may not be obvious why each borrowed variable gets its own
1277 /// lifetime (in the desugared version of the example, these are indicated
1278 /// by the lifetime parameters `'x`, `'y`, and `'z` in the `Vars` definition).
1279 /// Each such lifetime must encompass the lifetime `'e` of the closure itself,
1280 /// but need not be identical to it. The reason that this makes sense:
1282 /// - Callers are only permitted to invoke the closure, and hence to
1283 /// use the pointers, within the lifetime `'e`, so clearly `'e` must
1284 /// be a sublifetime of `'x...'z`.
1285 /// - The closure creator knows which upvars were borrowed by the closure
1286 /// and thus `x...z` will be reserved for `'x...'z` respectively.
1287 /// - Through mutation, the borrowed upvars can actually escape
1288 /// the closure, so sometimes it is necessary for them to be larger
1289 /// than the closure lifetime itself.
1290 #[derive(PartialEq, Clone, RustcEncodable, RustcDecodable, Show, Copy)]
1291 pub struct UpvarBorrow {
1292 pub kind: BorrowKind,
1293 pub region: ty::Region,
1296 pub type UpvarBorrowMap = FnvHashMap<UpvarId, UpvarBorrow>;
1299 pub fn is_bound(&self) -> bool {
1301 ty::ReEarlyBound(..) => true,
1302 ty::ReLateBound(..) => true,
1307 pub fn escapes_depth(&self, depth: u32) -> bool {
1309 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1315 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1316 RustcEncodable, RustcDecodable, Show, Copy)]
1317 /// A "free" region `fr` can be interpreted as "some region
1318 /// at least as big as the scope `fr.scope`".
1319 pub struct FreeRegion {
1320 pub scope: region::CodeExtent,
1321 pub bound_region: BoundRegion
1324 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1325 RustcEncodable, RustcDecodable, Show, Copy)]
1326 pub enum BoundRegion {
1327 /// An anonymous region parameter for a given fn (&T)
1330 /// Named region parameters for functions (a in &'a T)
1332 /// The def-id is needed to distinguish free regions in
1333 /// the event of shadowing.
1334 BrNamed(ast::DefId, ast::Name),
1336 /// Fresh bound identifiers created during GLB computations.
1339 // Anonymous region for the implicit env pointer parameter
1344 // NB: If you change this, you'll probably want to change the corresponding
1345 // AST structure in libsyntax/ast.rs as well.
1346 #[derive(Clone, PartialEq, Eq, Hash, Show)]
1347 pub enum sty<'tcx> {
1351 ty_uint(ast::UintTy),
1352 ty_float(ast::FloatTy),
1353 /// Substs here, possibly against intuition, *may* contain `ty_param`s.
1354 /// That is, even after substitution it is possible that there are type
1355 /// variables. This happens when the `ty_enum` corresponds to an enum
1356 /// definition and not a concrete use of it. To get the correct `ty_enum`
1357 /// from the tcx, use the `NodeId` from the `ast::Ty` and look it up in
1358 /// the `ast_ty_to_ty_cache`. This is probably true for `ty_struct` as
1360 ty_enum(DefId, &'tcx Substs<'tcx>),
1363 ty_vec(Ty<'tcx>, Option<uint>), // Second field is length.
1365 ty_rptr(&'tcx Region, mt<'tcx>),
1367 // If the def-id is Some(_), then this is the type of a specific
1368 // fn item. Otherwise, if None(_), it a fn pointer type.
1369 ty_bare_fn(Option<DefId>, &'tcx BareFnTy<'tcx>),
1371 ty_trait(Box<TyTrait<'tcx>>),
1372 ty_struct(DefId, &'tcx Substs<'tcx>),
1374 ty_unboxed_closure(DefId, &'tcx Region, &'tcx Substs<'tcx>),
1376 ty_tup(Vec<Ty<'tcx>>),
1378 ty_projection(ProjectionTy<'tcx>),
1379 ty_param(ParamTy), // type parameter
1381 ty_open(Ty<'tcx>), // A deref'ed fat pointer, i.e., a dynamically sized value
1382 // and its size. Only ever used in trans. It is not necessary
1383 // earlier since we don't need to distinguish a DST with its
1384 // size (e.g., in a deref) vs a DST with the size elsewhere (
1385 // e.g., in a field).
1387 ty_infer(InferTy), // something used only during inference/typeck
1388 ty_err, // Also only used during inference/typeck, to represent
1389 // the type of an erroneous expression (helps cut down
1390 // on non-useful type error messages)
1393 #[derive(Clone, PartialEq, Eq, Hash, Show)]
1394 pub struct TyTrait<'tcx> {
1395 pub principal: ty::PolyTraitRef<'tcx>,
1396 pub bounds: ExistentialBounds<'tcx>,
1399 impl<'tcx> TyTrait<'tcx> {
1400 pub fn principal_def_id(&self) -> ast::DefId {
1401 self.principal.0.def_id
1404 /// Object types don't have a self-type specified. Therefore, when
1405 /// we convert the principal trait-ref into a normal trait-ref,
1406 /// you must give *some* self-type. A common choice is `mk_err()`
1407 /// or some skolemized type.
1408 pub fn principal_trait_ref_with_self_ty(&self,
1411 -> ty::PolyTraitRef<'tcx>
1413 // otherwise the escaping regions would be captured by the binder
1414 assert!(!self_ty.has_escaping_regions());
1416 ty::Binder(Rc::new(ty::TraitRef {
1417 def_id: self.principal.0.def_id,
1418 substs: tcx.mk_substs(self.principal.0.substs.with_self_ty(self_ty)),
1422 pub fn projection_bounds_with_self_ty(&self,
1425 -> Vec<ty::PolyProjectionPredicate<'tcx>>
1427 // otherwise the escaping regions would be captured by the binders
1428 assert!(!self_ty.has_escaping_regions());
1430 self.bounds.projection_bounds.iter()
1431 .map(|in_poly_projection_predicate| {
1432 let in_projection_ty = &in_poly_projection_predicate.0.projection_ty;
1433 let substs = tcx.mk_substs(in_projection_ty.trait_ref.substs.with_self_ty(self_ty));
1435 Rc::new(ty::TraitRef::new(in_projection_ty.trait_ref.def_id,
1437 let projection_ty = ty::ProjectionTy {
1438 trait_ref: trait_ref,
1439 item_name: in_projection_ty.item_name
1441 ty::Binder(ty::ProjectionPredicate {
1442 projection_ty: projection_ty,
1443 ty: in_poly_projection_predicate.0.ty
1450 /// A complete reference to a trait. These take numerous guises in syntax,
1451 /// but perhaps the most recognizable form is in a where clause:
1455 /// This would be represented by a trait-reference where the def-id is the
1456 /// def-id for the trait `Foo` and the substs defines `T` as parameter 0 in the
1457 /// `SelfSpace` and `U` as parameter 0 in the `TypeSpace`.
1459 /// Trait references also appear in object types like `Foo<U>`, but in
1460 /// that case the `Self` parameter is absent from the substitutions.
1462 /// Note that a `TraitRef` introduces a level of region binding, to
1463 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
1464 /// U>` or higher-ranked object types.
1465 #[derive(Clone, PartialEq, Eq, Hash, Show)]
1466 pub struct TraitRef<'tcx> {
1468 pub substs: &'tcx Substs<'tcx>,
1471 pub type PolyTraitRef<'tcx> = Binder<Rc<TraitRef<'tcx>>>;
1473 impl<'tcx> PolyTraitRef<'tcx> {
1474 pub fn self_ty(&self) -> Ty<'tcx> {
1478 pub fn def_id(&self) -> ast::DefId {
1482 pub fn substs(&self) -> &'tcx Substs<'tcx> {
1483 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
1487 pub fn input_types(&self) -> &[Ty<'tcx>] {
1488 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
1489 self.0.input_types()
1492 pub fn to_poly_trait_predicate(&self) -> PolyTraitPredicate<'tcx> {
1493 // Note that we preserve binding levels
1494 Binder(TraitPredicate { trait_ref: self.0.clone() })
1498 /// Binder is a binder for higher-ranked lifetimes. It is part of the
1499 /// compiler's representation for things like `for<'a> Fn(&'a int)`
1500 /// (which would be represented by the type `PolyTraitRef ==
1501 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
1502 /// erase, or otherwise "discharge" these bound reons, we change the
1503 /// type from `Binder<T>` to just `T` (see
1504 /// e.g. `liberate_late_bound_regions`).
1505 #[derive(Clone, PartialEq, Eq, Hash, Show)]
1506 pub struct Binder<T>(pub T);
1508 #[derive(Clone, Copy, PartialEq)]
1509 pub enum IntVarValue {
1510 IntType(ast::IntTy),
1511 UintType(ast::UintTy),
1514 #[derive(Clone, Copy, Show)]
1515 pub enum terr_vstore_kind {
1522 #[derive(Clone, Copy, Show)]
1523 pub struct expected_found<T> {
1528 // Data structures used in type unification
1529 #[derive(Clone, Copy, Show)]
1530 pub enum type_err<'tcx> {
1532 terr_unsafety_mismatch(expected_found<ast::Unsafety>),
1533 terr_onceness_mismatch(expected_found<Onceness>),
1534 terr_abi_mismatch(expected_found<abi::Abi>),
1536 terr_box_mutability,
1537 terr_ptr_mutability,
1538 terr_ref_mutability,
1539 terr_vec_mutability,
1540 terr_tuple_size(expected_found<uint>),
1541 terr_fixed_array_size(expected_found<uint>),
1542 terr_ty_param_size(expected_found<uint>),
1544 terr_regions_does_not_outlive(Region, Region),
1545 terr_regions_not_same(Region, Region),
1546 terr_regions_no_overlap(Region, Region),
1547 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
1548 terr_regions_overly_polymorphic(BoundRegion, Region),
1549 terr_sorts(expected_found<Ty<'tcx>>),
1550 terr_integer_as_char,
1551 terr_int_mismatch(expected_found<IntVarValue>),
1552 terr_float_mismatch(expected_found<ast::FloatTy>),
1553 terr_traits(expected_found<ast::DefId>),
1554 terr_builtin_bounds(expected_found<BuiltinBounds>),
1555 terr_variadic_mismatch(expected_found<bool>),
1557 terr_convergence_mismatch(expected_found<bool>),
1558 terr_projection_name_mismatched(expected_found<ast::Name>),
1559 terr_projection_bounds_length(expected_found<uint>),
1562 /// Bounds suitable for a named type parameter like `A` in `fn foo<A>`
1563 /// as well as the existential type parameter in an object type.
1564 #[derive(PartialEq, Eq, Hash, Clone, Show)]
1565 pub struct ParamBounds<'tcx> {
1566 pub region_bounds: Vec<ty::Region>,
1567 pub builtin_bounds: BuiltinBounds,
1568 pub trait_bounds: Vec<PolyTraitRef<'tcx>>,
1569 pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
1572 /// Bounds suitable for an existentially quantified type parameter
1573 /// such as those that appear in object types or closure types. The
1574 /// major difference between this case and `ParamBounds` is that
1575 /// general purpose trait bounds are omitted and there must be
1576 /// *exactly one* region.
1577 #[derive(PartialEq, Eq, Hash, Clone, Show)]
1578 pub struct ExistentialBounds<'tcx> {
1579 pub region_bound: ty::Region,
1580 pub builtin_bounds: BuiltinBounds,
1581 pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
1584 pub type BuiltinBounds = EnumSet<BuiltinBound>;
1586 #[derive(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
1589 pub enum BuiltinBound {
1596 pub fn empty_builtin_bounds() -> BuiltinBounds {
1600 pub fn all_builtin_bounds() -> BuiltinBounds {
1601 let mut set = EnumSet::new();
1602 set.insert(BoundSend);
1603 set.insert(BoundSized);
1604 set.insert(BoundSync);
1608 /// An existential bound that does not implement any traits.
1609 pub fn region_existential_bound<'tcx>(r: ty::Region) -> ExistentialBounds<'tcx> {
1610 ty::ExistentialBounds { region_bound: r,
1611 builtin_bounds: empty_builtin_bounds(),
1612 projection_bounds: Vec::new() }
1615 impl CLike for BuiltinBound {
1616 fn to_uint(&self) -> uint {
1619 fn from_uint(v: uint) -> BuiltinBound {
1620 unsafe { mem::transmute(v) }
1624 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1629 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1634 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1635 pub struct FloatVid {
1639 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1640 pub struct RegionVid {
1644 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1650 /// A `FreshTy` is one that is generated as a replacement for an
1651 /// unbound type variable. This is convenient for caching etc. See
1652 /// `middle::infer::freshen` for more details.
1655 // FIXME -- once integral fallback is impl'd, we should remove
1656 // this type. It's only needed to prevent spurious errors for
1657 // integers whose type winds up never being constrained.
1661 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
1662 pub enum UnconstrainedNumeric {
1669 #[derive(Clone, RustcEncodable, RustcDecodable, Eq, Hash, Show, Copy)]
1670 pub enum InferRegion {
1672 ReSkolemized(u32, BoundRegion)
1675 impl cmp::PartialEq for InferRegion {
1676 fn eq(&self, other: &InferRegion) -> bool {
1677 match ((*self), *other) {
1678 (ReVar(rva), ReVar(rvb)) => {
1681 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
1687 fn ne(&self, other: &InferRegion) -> bool {
1688 !((*self) == (*other))
1692 impl fmt::Debug for TyVid {
1693 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
1694 write!(f, "_#{}t", self.index)
1698 impl fmt::Debug for IntVid {
1699 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1700 write!(f, "_#{}i", self.index)
1704 impl fmt::Debug for FloatVid {
1705 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1706 write!(f, "_#{}f", self.index)
1710 impl fmt::Debug for RegionVid {
1711 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1712 write!(f, "'_#{}r", self.index)
1716 impl<'tcx> fmt::Debug for FnSig<'tcx> {
1717 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1718 write!(f, "({:?}; variadic: {})->{:?}", self.inputs, self.variadic, self.output)
1722 impl fmt::Debug for InferTy {
1723 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1725 TyVar(ref v) => v.fmt(f),
1726 IntVar(ref v) => v.fmt(f),
1727 FloatVar(ref v) => v.fmt(f),
1728 FreshTy(v) => write!(f, "FreshTy({:?})", v),
1729 FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
1734 impl fmt::Debug for IntVarValue {
1735 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1737 IntType(ref v) => v.fmt(f),
1738 UintType(ref v) => v.fmt(f),
1743 #[derive(Clone, Show)]
1744 pub struct TypeParameterDef<'tcx> {
1745 pub name: ast::Name,
1746 pub def_id: ast::DefId,
1747 pub space: subst::ParamSpace,
1749 pub bounds: ParamBounds<'tcx>,
1750 pub default: Option<Ty<'tcx>>,
1753 #[derive(RustcEncodable, RustcDecodable, Clone, Show)]
1754 pub struct RegionParameterDef {
1755 pub name: ast::Name,
1756 pub def_id: ast::DefId,
1757 pub space: subst::ParamSpace,
1759 pub bounds: Vec<ty::Region>,
1762 impl RegionParameterDef {
1763 pub fn to_early_bound_region(&self) -> ty::Region {
1764 ty::ReEarlyBound(self.def_id.node, self.space, self.index, self.name)
1768 /// Information about the formal type/lifetime parameters associated
1769 /// with an item or method. Analogous to ast::Generics.
1770 #[derive(Clone, Show)]
1771 pub struct Generics<'tcx> {
1772 pub types: VecPerParamSpace<TypeParameterDef<'tcx>>,
1773 pub regions: VecPerParamSpace<RegionParameterDef>,
1774 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
1777 impl<'tcx> Generics<'tcx> {
1778 pub fn empty() -> Generics<'tcx> {
1780 types: VecPerParamSpace::empty(),
1781 regions: VecPerParamSpace::empty(),
1782 predicates: VecPerParamSpace::empty(),
1786 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
1787 !self.types.is_empty_in(space)
1790 pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
1791 !self.regions.is_empty_in(space)
1794 pub fn is_empty(&self) -> bool {
1795 self.types.is_empty() && self.regions.is_empty()
1798 pub fn to_bounds(&self, tcx: &ty::ctxt<'tcx>, substs: &Substs<'tcx>)
1799 -> GenericBounds<'tcx> {
1801 predicates: self.predicates.subst(tcx, substs),
1806 #[derive(Clone, PartialEq, Eq, Hash, Show)]
1807 pub enum Predicate<'tcx> {
1808 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
1809 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1810 /// would be the parameters in the `TypeSpace`.
1811 Trait(PolyTraitPredicate<'tcx>),
1813 /// where `T1 == T2`.
1814 Equate(PolyEquatePredicate<'tcx>),
1817 RegionOutlives(PolyRegionOutlivesPredicate),
1820 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1822 /// where <T as TraitRef>::Name == X, approximately.
1823 /// See `ProjectionPredicate` struct for details.
1824 Projection(PolyProjectionPredicate<'tcx>),
1827 #[derive(Clone, PartialEq, Eq, Hash, Show)]
1828 pub struct TraitPredicate<'tcx> {
1829 pub trait_ref: Rc<TraitRef<'tcx>>
1831 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1833 impl<'tcx> TraitPredicate<'tcx> {
1834 pub fn def_id(&self) -> ast::DefId {
1835 self.trait_ref.def_id
1838 pub fn input_types(&self) -> &[Ty<'tcx>] {
1839 self.trait_ref.substs.types.as_slice()
1842 pub fn self_ty(&self) -> Ty<'tcx> {
1843 self.trait_ref.self_ty()
1847 impl<'tcx> PolyTraitPredicate<'tcx> {
1848 pub fn def_id(&self) -> ast::DefId {
1853 #[derive(Clone, PartialEq, Eq, Hash, Show)]
1854 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
1855 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
1857 #[derive(Clone, PartialEq, Eq, Hash, Show)]
1858 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
1859 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
1860 pub type PolyRegionOutlivesPredicate = PolyOutlivesPredicate<ty::Region, ty::Region>;
1861 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region>;
1863 /// This kind of predicate has no *direct* correspondent in the
1864 /// syntax, but it roughly corresponds to the syntactic forms:
1866 /// 1. `T : TraitRef<..., Item=Type>`
1867 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1869 /// In particular, form #1 is "desugared" to the combination of a
1870 /// normal trait predicate (`T : TraitRef<...>`) and one of these
1871 /// predicates. Form #2 is a broader form in that it also permits
1872 /// equality between arbitrary types. Processing an instance of Form
1873 /// #2 eventually yields one of these `ProjectionPredicate`
1874 /// instances to normalize the LHS.
1875 #[derive(Clone, PartialEq, Eq, Hash, Show)]
1876 pub struct ProjectionPredicate<'tcx> {
1877 pub projection_ty: ProjectionTy<'tcx>,
1881 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1883 impl<'tcx> PolyProjectionPredicate<'tcx> {
1884 pub fn item_name(&self) -> ast::Name {
1885 self.0.projection_ty.item_name // safe to skip the binder to access a name
1888 pub fn sort_key(&self) -> (ast::DefId, ast::Name) {
1889 self.0.projection_ty.sort_key()
1893 /// Represents the projection of an associated type. In explicit UFCS
1894 /// form this would be written `<T as Trait<..>>::N`.
1895 #[derive(Clone, PartialEq, Eq, Hash, Show)]
1896 pub struct ProjectionTy<'tcx> {
1897 /// The trait reference `T as Trait<..>`.
1898 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
1900 /// The name `N` of the associated type.
1901 pub item_name: ast::Name,
1904 impl<'tcx> ProjectionTy<'tcx> {
1905 pub fn sort_key(&self) -> (ast::DefId, ast::Name) {
1906 (self.trait_ref.def_id, self.item_name)
1910 pub trait ToPolyTraitRef<'tcx> {
1911 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1914 impl<'tcx> ToPolyTraitRef<'tcx> for Rc<TraitRef<'tcx>> {
1915 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1916 assert!(!self.has_escaping_regions());
1917 ty::Binder(self.clone())
1921 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1922 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1923 // We are just preserving the binder levels here
1924 ty::Binder(self.0.trait_ref.clone())
1928 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
1929 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1930 // Note: unlike with TraitRef::to_poly_trait_ref(),
1931 // self.0.trait_ref is permitted to have escaping regions.
1932 // This is because here `self` has a `Binder` and so does our
1933 // return value, so we are preserving the number of binding
1935 ty::Binder(self.0.projection_ty.trait_ref.clone())
1939 pub trait AsPredicate<'tcx> {
1940 fn as_predicate(&self) -> Predicate<'tcx>;
1943 impl<'tcx> AsPredicate<'tcx> for Rc<TraitRef<'tcx>> {
1944 fn as_predicate(&self) -> Predicate<'tcx> {
1945 // we're about to add a binder, so let's check that we don't
1946 // accidentally capture anything, or else that might be some
1947 // weird debruijn accounting.
1948 assert!(!self.has_escaping_regions());
1950 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1951 trait_ref: self.clone()
1956 impl<'tcx> AsPredicate<'tcx> for PolyTraitRef<'tcx> {
1957 fn as_predicate(&self) -> Predicate<'tcx> {
1958 ty::Predicate::Trait(self.to_poly_trait_predicate())
1962 impl<'tcx> AsPredicate<'tcx> for PolyEquatePredicate<'tcx> {
1963 fn as_predicate(&self) -> Predicate<'tcx> {
1964 Predicate::Equate(self.clone())
1968 impl<'tcx> AsPredicate<'tcx> for PolyRegionOutlivesPredicate {
1969 fn as_predicate(&self) -> Predicate<'tcx> {
1970 Predicate::RegionOutlives(self.clone())
1974 impl<'tcx> AsPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1975 fn as_predicate(&self) -> Predicate<'tcx> {
1976 Predicate::TypeOutlives(self.clone())
1980 impl<'tcx> AsPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1981 fn as_predicate(&self) -> Predicate<'tcx> {
1982 Predicate::Projection(self.clone())
1986 impl<'tcx> Predicate<'tcx> {
1987 pub fn has_escaping_regions(&self) -> bool {
1989 Predicate::Trait(ref trait_ref) => trait_ref.has_escaping_regions(),
1990 Predicate::Equate(ref p) => p.has_escaping_regions(),
1991 Predicate::RegionOutlives(ref p) => p.has_escaping_regions(),
1992 Predicate::TypeOutlives(ref p) => p.has_escaping_regions(),
1993 Predicate::Projection(ref p) => p.has_escaping_regions(),
1997 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1999 Predicate::Trait(ref t) => {
2000 Some(t.to_poly_trait_ref())
2002 Predicate::Projection(..) |
2003 Predicate::Equate(..) |
2004 Predicate::RegionOutlives(..) |
2005 Predicate::TypeOutlives(..) => {
2012 /// Represents the bounds declared on a particular set of type
2013 /// parameters. Should eventually be generalized into a flag list of
2014 /// where clauses. You can obtain a `GenericBounds` list from a
2015 /// `Generics` by using the `to_bounds` method. Note that this method
2016 /// reflects an important semantic invariant of `GenericBounds`: while
2017 /// the bounds in a `Generics` are expressed in terms of the bound type
2018 /// parameters of the impl/trait/whatever, a `GenericBounds` instance
2019 /// represented a set of bounds for some particular instantiation,
2020 /// meaning that the generic parameters have been substituted with
2025 /// struct Foo<T,U:Bar<T>> { ... }
2027 /// Here, the `Generics` for `Foo` would contain a list of bounds like
2028 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
2029 /// like `Foo<int,uint>`, then the `GenericBounds` would be `[[],
2030 /// [uint:Bar<int>]]`.
2031 #[derive(Clone, Show)]
2032 pub struct GenericBounds<'tcx> {
2033 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
2036 impl<'tcx> GenericBounds<'tcx> {
2037 pub fn empty() -> GenericBounds<'tcx> {
2038 GenericBounds { predicates: VecPerParamSpace::empty() }
2041 pub fn has_escaping_regions(&self) -> bool {
2042 self.predicates.any(|p| p.has_escaping_regions())
2045 pub fn is_empty(&self) -> bool {
2046 self.predicates.is_empty()
2050 impl<'tcx> TraitRef<'tcx> {
2051 pub fn new(def_id: ast::DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
2052 TraitRef { def_id: def_id, substs: substs }
2055 pub fn self_ty(&self) -> Ty<'tcx> {
2056 self.substs.self_ty().unwrap()
2059 pub fn input_types(&self) -> &[Ty<'tcx>] {
2060 // Select only the "input types" from a trait-reference. For
2061 // now this is all the types that appear in the
2062 // trait-reference, but it should eventually exclude
2063 // associated types.
2064 self.substs.types.as_slice()
2068 /// When type checking, we use the `ParameterEnvironment` to track
2069 /// details about the type/lifetime parameters that are in scope.
2070 /// It primarily stores the bounds information.
2072 /// Note: This information might seem to be redundant with the data in
2073 /// `tcx.ty_param_defs`, but it is not. That table contains the
2074 /// parameter definitions from an "outside" perspective, but this
2075 /// struct will contain the bounds for a parameter as seen from inside
2076 /// the function body. Currently the only real distinction is that
2077 /// bound lifetime parameters are replaced with free ones, but in the
2078 /// future I hope to refine the representation of types so as to make
2079 /// more distinctions clearer.
2081 pub struct ParameterEnvironment<'a, 'tcx:'a> {
2082 pub tcx: &'a ctxt<'tcx>,
2084 /// A substitution that can be applied to move from
2085 /// the "outer" view of a type or method to the "inner" view.
2086 /// In general, this means converting from bound parameters to
2087 /// free parameters. Since we currently represent bound/free type
2088 /// parameters in the same way, this only has an effect on regions.
2089 pub free_substs: Substs<'tcx>,
2091 /// Each type parameter has an implicit region bound that
2092 /// indicates it must outlive at least the function body (the user
2093 /// may specify stronger requirements). This field indicates the
2094 /// region of the callee.
2095 pub implicit_region_bound: ty::Region,
2097 /// Obligations that the caller must satisfy. This is basically
2098 /// the set of bounds on the in-scope type parameters, translated
2099 /// into Obligations.
2100 pub caller_bounds: ty::GenericBounds<'tcx>,
2102 /// Caches the results of trait selection. This cache is used
2103 /// for things that have to do with the parameters in scope.
2104 pub selection_cache: traits::SelectionCache<'tcx>,
2107 impl<'a, 'tcx> ParameterEnvironment<'a, 'tcx> {
2108 pub fn for_item(cx: &'a ctxt<'tcx>, id: NodeId) -> ParameterEnvironment<'a, 'tcx> {
2109 match cx.map.find(id) {
2110 Some(ast_map::NodeImplItem(ref impl_item)) => {
2112 ast::MethodImplItem(ref method) => {
2113 let method_def_id = ast_util::local_def(id);
2114 match ty::impl_or_trait_item(cx, method_def_id) {
2115 MethodTraitItem(ref method_ty) => {
2116 let method_generics = &method_ty.generics;
2117 construct_parameter_environment(
2120 method.pe_body().id)
2122 TypeTraitItem(_) => {
2124 .bug("ParameterEnvironment::for_item(): \
2125 can't create a parameter environment \
2126 for type trait items")
2130 ast::TypeImplItem(_) => {
2131 cx.sess.bug("ParameterEnvironment::for_item(): \
2132 can't create a parameter environment \
2133 for type impl items")
2137 Some(ast_map::NodeTraitItem(trait_method)) => {
2138 match *trait_method {
2139 ast::RequiredMethod(ref required) => {
2140 cx.sess.span_bug(required.span,
2141 "ParameterEnvironment::for_item():
2142 can't create a parameter \
2143 environment for required trait \
2146 ast::ProvidedMethod(ref method) => {
2147 let method_def_id = ast_util::local_def(id);
2148 match ty::impl_or_trait_item(cx, method_def_id) {
2149 MethodTraitItem(ref method_ty) => {
2150 let method_generics = &method_ty.generics;
2151 construct_parameter_environment(
2154 method.pe_body().id)
2156 TypeTraitItem(_) => {
2158 .bug("ParameterEnvironment::for_item(): \
2159 can't create a parameter environment \
2160 for type trait items")
2164 ast::TypeTraitItem(_) => {
2165 cx.sess.bug("ParameterEnvironment::from_item(): \
2166 can't create a parameter environment \
2167 for type trait items")
2171 Some(ast_map::NodeItem(item)) => {
2173 ast::ItemFn(_, _, _, _, ref body) => {
2174 // We assume this is a function.
2175 let fn_def_id = ast_util::local_def(id);
2176 let fn_pty = ty::lookup_item_type(cx, fn_def_id);
2178 construct_parameter_environment(cx,
2183 ast::ItemStruct(..) |
2185 ast::ItemConst(..) |
2186 ast::ItemStatic(..) => {
2187 let def_id = ast_util::local_def(id);
2188 let pty = ty::lookup_item_type(cx, def_id);
2189 construct_parameter_environment(cx, &pty.generics, id)
2192 cx.sess.span_bug(item.span,
2193 "ParameterEnvironment::from_item():
2194 can't create a parameter \
2195 environment for this kind of item")
2199 Some(ast_map::NodeExpr(..)) => {
2200 // This is a convenience to allow closures to work.
2201 ParameterEnvironment::for_item(cx, cx.map.get_parent(id))
2204 cx.sess.bug(&format!("ParameterEnvironment::from_item(): \
2205 `{}` is not an item",
2206 cx.map.node_to_string(id))[])
2212 /// A "type scheme", in ML terminology, is a type combined with some
2213 /// set of generic types that the type is, well, generic over. In Rust
2214 /// terms, it is the "type" of a fn item or struct -- this type will
2215 /// include various generic parameters that must be substituted when
2216 /// the item/struct is referenced. That is called converting the type
2217 /// scheme to a monotype.
2219 /// - `generics`: the set of type parameters and their bounds
2220 /// - `ty`: the base types, which may reference the parameters defined
2223 /// Note that TypeSchemes are also sometimes called "polytypes" (and
2224 /// in fact this struct used to carry that name, so you may find some
2225 /// stray references in a comment or something). We try to reserve the
2226 /// "poly" prefix to refer to higher-ranked things, as in
2228 #[derive(Clone, Show)]
2229 pub struct TypeScheme<'tcx> {
2230 pub generics: Generics<'tcx>,
2234 /// As `TypeScheme` but for a trait ref.
2235 pub struct TraitDef<'tcx> {
2236 pub unsafety: ast::Unsafety,
2238 /// Generic type definitions. Note that `Self` is listed in here
2239 /// as having a single bound, the trait itself (e.g., in the trait
2240 /// `Eq`, there is a single bound `Self : Eq`). This is so that
2241 /// default methods get to assume that the `Self` parameters
2242 /// implements the trait.
2243 pub generics: Generics<'tcx>,
2245 /// The "supertrait" bounds.
2246 pub bounds: ParamBounds<'tcx>,
2248 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
2250 /// A list of the associated types defined in this trait. Useful
2251 /// for resolving `X::Foo` type markers.
2252 pub associated_type_names: Vec<ast::Name>,
2255 /// Records the substitutions used to translate the polytype for an
2256 /// item into the monotype of an item reference.
2258 pub struct ItemSubsts<'tcx> {
2259 pub substs: Substs<'tcx>,
2262 /// Records information about each unboxed closure.
2264 pub struct UnboxedClosure<'tcx> {
2265 /// The type of the unboxed closure.
2266 pub closure_type: ClosureTy<'tcx>,
2267 /// The kind of unboxed closure this is.
2268 pub kind: UnboxedClosureKind,
2271 #[derive(Clone, Copy, PartialEq, Eq, Show)]
2272 pub enum UnboxedClosureKind {
2273 FnUnboxedClosureKind,
2274 FnMutUnboxedClosureKind,
2275 FnOnceUnboxedClosureKind,
2278 impl UnboxedClosureKind {
2279 pub fn trait_did(&self, cx: &ctxt) -> ast::DefId {
2280 let result = match *self {
2281 FnUnboxedClosureKind => cx.lang_items.require(FnTraitLangItem),
2282 FnMutUnboxedClosureKind => {
2283 cx.lang_items.require(FnMutTraitLangItem)
2285 FnOnceUnboxedClosureKind => {
2286 cx.lang_items.require(FnOnceTraitLangItem)
2290 Ok(trait_did) => trait_did,
2291 Err(err) => cx.sess.fatal(&err[]),
2296 pub trait UnboxedClosureTyper<'tcx> {
2297 fn param_env<'a>(&'a self) -> &'a ty::ParameterEnvironment<'a, 'tcx>;
2299 fn unboxed_closure_kind(&self,
2301 -> ty::UnboxedClosureKind;
2303 fn unboxed_closure_type(&self,
2305 substs: &subst::Substs<'tcx>)
2306 -> ty::ClosureTy<'tcx>;
2308 // Returns `None` if the upvar types cannot yet be definitively determined.
2309 fn unboxed_closure_upvars(&self,
2311 substs: &Substs<'tcx>)
2312 -> Option<Vec<UnboxedClosureUpvar<'tcx>>>;
2315 impl<'tcx> CommonTypes<'tcx> {
2316 fn new(arena: &'tcx TypedArena<TyS<'tcx>>,
2317 interner: &mut FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>)
2318 -> CommonTypes<'tcx>
2321 bool: intern_ty(arena, interner, ty_bool),
2322 char: intern_ty(arena, interner, ty_char),
2323 err: intern_ty(arena, interner, ty_err),
2324 int: intern_ty(arena, interner, ty_int(ast::TyIs(false))),
2325 i8: intern_ty(arena, interner, ty_int(ast::TyI8)),
2326 i16: intern_ty(arena, interner, ty_int(ast::TyI16)),
2327 i32: intern_ty(arena, interner, ty_int(ast::TyI32)),
2328 i64: intern_ty(arena, interner, ty_int(ast::TyI64)),
2329 uint: intern_ty(arena, interner, ty_uint(ast::TyUs(false))),
2330 u8: intern_ty(arena, interner, ty_uint(ast::TyU8)),
2331 u16: intern_ty(arena, interner, ty_uint(ast::TyU16)),
2332 u32: intern_ty(arena, interner, ty_uint(ast::TyU32)),
2333 u64: intern_ty(arena, interner, ty_uint(ast::TyU64)),
2334 f32: intern_ty(arena, interner, ty_float(ast::TyF32)),
2335 f64: intern_ty(arena, interner, ty_float(ast::TyF64)),
2340 pub fn mk_ctxt<'tcx>(s: Session,
2341 arenas: &'tcx CtxtArenas<'tcx>,
2343 named_region_map: resolve_lifetime::NamedRegionMap,
2344 map: ast_map::Map<'tcx>,
2345 freevars: RefCell<FreevarMap>,
2346 capture_modes: RefCell<CaptureModeMap>,
2347 region_maps: middle::region::RegionMaps,
2348 lang_items: middle::lang_items::LanguageItems,
2349 stability: stability::Index) -> ctxt<'tcx>
2351 let mut interner = FnvHashMap();
2352 let common_types = CommonTypes::new(&arenas.type_, &mut interner);
2356 interner: RefCell::new(interner),
2357 substs_interner: RefCell::new(FnvHashMap()),
2358 bare_fn_interner: RefCell::new(FnvHashMap()),
2359 region_interner: RefCell::new(FnvHashMap()),
2360 types: common_types,
2361 named_region_map: named_region_map,
2362 item_variance_map: RefCell::new(DefIdMap()),
2363 variance_computed: Cell::new(false),
2366 region_maps: region_maps,
2367 node_types: RefCell::new(FnvHashMap()),
2368 item_substs: RefCell::new(NodeMap()),
2369 trait_refs: RefCell::new(NodeMap()),
2370 trait_defs: RefCell::new(DefIdMap()),
2371 object_cast_map: RefCell::new(NodeMap()),
2373 intrinsic_defs: RefCell::new(DefIdMap()),
2375 tcache: RefCell::new(DefIdMap()),
2376 rcache: RefCell::new(FnvHashMap()),
2377 short_names_cache: RefCell::new(FnvHashMap()),
2378 tc_cache: RefCell::new(FnvHashMap()),
2379 ast_ty_to_ty_cache: RefCell::new(NodeMap()),
2380 enum_var_cache: RefCell::new(DefIdMap()),
2381 impl_or_trait_items: RefCell::new(DefIdMap()),
2382 trait_item_def_ids: RefCell::new(DefIdMap()),
2383 trait_items_cache: RefCell::new(DefIdMap()),
2384 impl_trait_cache: RefCell::new(DefIdMap()),
2385 ty_param_defs: RefCell::new(NodeMap()),
2386 adjustments: RefCell::new(NodeMap()),
2387 normalized_cache: RefCell::new(FnvHashMap()),
2388 lang_items: lang_items,
2389 provided_method_sources: RefCell::new(DefIdMap()),
2390 struct_fields: RefCell::new(DefIdMap()),
2391 destructor_for_type: RefCell::new(DefIdMap()),
2392 destructors: RefCell::new(DefIdSet()),
2393 trait_impls: RefCell::new(DefIdMap()),
2394 inherent_impls: RefCell::new(DefIdMap()),
2395 impl_items: RefCell::new(DefIdMap()),
2396 used_unsafe: RefCell::new(NodeSet()),
2397 used_mut_nodes: RefCell::new(NodeSet()),
2398 populated_external_types: RefCell::new(DefIdSet()),
2399 populated_external_traits: RefCell::new(DefIdSet()),
2400 upvar_borrow_map: RefCell::new(FnvHashMap()),
2401 extern_const_statics: RefCell::new(DefIdMap()),
2402 extern_const_variants: RefCell::new(DefIdMap()),
2403 method_map: RefCell::new(FnvHashMap()),
2404 dependency_formats: RefCell::new(FnvHashMap()),
2405 unboxed_closures: RefCell::new(DefIdMap()),
2406 node_lint_levels: RefCell::new(FnvHashMap()),
2407 transmute_restrictions: RefCell::new(Vec::new()),
2408 stability: RefCell::new(stability),
2409 capture_modes: capture_modes,
2410 associated_types: RefCell::new(DefIdMap()),
2411 selection_cache: traits::SelectionCache::new(),
2412 repr_hint_cache: RefCell::new(DefIdMap()),
2413 type_impls_copy_cache: RefCell::new(HashMap::new()),
2414 type_impls_sized_cache: RefCell::new(HashMap::new()),
2415 object_safety_cache: RefCell::new(DefIdMap()),
2419 // Type constructors
2421 impl<'tcx> ctxt<'tcx> {
2422 pub fn mk_substs(&self, substs: Substs<'tcx>) -> &'tcx Substs<'tcx> {
2423 if let Some(substs) = self.substs_interner.borrow().get(&substs) {
2427 let substs = self.arenas.substs.alloc(substs);
2428 self.substs_interner.borrow_mut().insert(substs, substs);
2432 pub fn mk_bare_fn(&self, bare_fn: BareFnTy<'tcx>) -> &'tcx BareFnTy<'tcx> {
2433 if let Some(bare_fn) = self.bare_fn_interner.borrow().get(&bare_fn) {
2437 let bare_fn = self.arenas.bare_fn.alloc(bare_fn);
2438 self.bare_fn_interner.borrow_mut().insert(bare_fn, bare_fn);
2442 pub fn mk_region(&self, region: Region) -> &'tcx Region {
2443 if let Some(region) = self.region_interner.borrow().get(®ion) {
2447 let region = self.arenas.region.alloc(region);
2448 self.region_interner.borrow_mut().insert(region, region);
2452 pub fn unboxed_closure_kind(&self,
2454 -> ty::UnboxedClosureKind
2456 self.unboxed_closures.borrow()[def_id].kind
2459 pub fn unboxed_closure_type(&self,
2461 substs: &subst::Substs<'tcx>)
2462 -> ty::ClosureTy<'tcx>
2464 self.unboxed_closures.borrow()[def_id].closure_type.subst(self, substs)
2468 // Interns a type/name combination, stores the resulting box in cx.interner,
2469 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
2470 pub fn mk_t<'tcx>(cx: &ctxt<'tcx>, st: sty<'tcx>) -> Ty<'tcx> {
2471 let mut interner = cx.interner.borrow_mut();
2472 intern_ty(&cx.arenas.type_, &mut *interner, st)
2475 fn intern_ty<'tcx>(type_arena: &'tcx TypedArena<TyS<'tcx>>,
2476 interner: &mut FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>,
2480 match interner.get(&st) {
2481 Some(ty) => return *ty,
2485 let flags = FlagComputation::for_sty(&st);
2487 let ty = type_arena.alloc(TyS {
2490 region_depth: flags.depth,
2493 debug!("Interned type: {:?} Pointer: {:?}",
2494 ty, ty as *const _);
2496 interner.insert(InternedTy { ty: ty }, ty);
2501 struct FlagComputation {
2504 // maximum depth of any bound region that we have seen thus far
2508 impl FlagComputation {
2509 fn new() -> FlagComputation {
2510 FlagComputation { flags: NO_TYPE_FLAGS, depth: 0 }
2513 fn for_sty(st: &sty) -> FlagComputation {
2514 let mut result = FlagComputation::new();
2519 fn add_flags(&mut self, flags: TypeFlags) {
2520 self.flags = self.flags | flags;
2523 fn add_depth(&mut self, depth: u32) {
2524 if depth > self.depth {
2529 /// Adds the flags/depth from a set of types that appear within the current type, but within a
2531 fn add_bound_computation(&mut self, computation: &FlagComputation) {
2532 self.add_flags(computation.flags);
2534 // The types that contributed to `computation` occured within
2535 // a region binder, so subtract one from the region depth
2536 // within when adding the depth to `self`.
2537 let depth = computation.depth;
2539 self.add_depth(depth - 1);
2543 fn add_sty(&mut self, st: &sty) {
2553 // You might think that we could just return ty_err for
2554 // any type containing ty_err as a component, and get
2555 // rid of the HAS_TY_ERR flag -- likewise for ty_bot (with
2556 // the exception of function types that return bot).
2557 // But doing so caused sporadic memory corruption, and
2558 // neither I (tjc) nor nmatsakis could figure out why,
2559 // so we're doing it this way.
2561 self.add_flags(HAS_TY_ERR)
2564 &ty_param(ref p) => {
2565 if p.space == subst::SelfSpace {
2566 self.add_flags(HAS_SELF);
2568 self.add_flags(HAS_PARAMS);
2572 &ty_unboxed_closure(_, region, substs) => {
2573 self.add_region(*region);
2574 self.add_substs(substs);
2578 self.add_flags(HAS_TY_INFER)
2581 &ty_enum(_, substs) | &ty_struct(_, substs) => {
2582 self.add_substs(substs);
2585 &ty_projection(ref data) => {
2586 self.add_flags(HAS_PROJECTION);
2587 self.add_projection_ty(data);
2590 &ty_trait(box TyTrait { ref principal, ref bounds }) => {
2591 let mut computation = FlagComputation::new();
2592 computation.add_substs(principal.0.substs);
2593 for projection_bound in bounds.projection_bounds.iter() {
2594 let mut proj_computation = FlagComputation::new();
2595 proj_computation.add_projection_predicate(&projection_bound.0);
2596 computation.add_bound_computation(&proj_computation);
2598 self.add_bound_computation(&computation);
2600 self.add_bounds(bounds);
2603 &ty_uniq(tt) | &ty_vec(tt, _) | &ty_open(tt) => {
2611 &ty_rptr(r, ref m) => {
2612 self.add_region(*r);
2616 &ty_tup(ref ts) => {
2617 self.add_tys(&ts[]);
2620 &ty_bare_fn(_, ref f) => {
2621 self.add_fn_sig(&f.sig);
2626 fn add_ty(&mut self, ty: Ty) {
2627 self.add_flags(ty.flags);
2628 self.add_depth(ty.region_depth);
2631 fn add_tys(&mut self, tys: &[Ty]) {
2632 for &ty in tys.iter() {
2637 fn add_fn_sig(&mut self, fn_sig: &PolyFnSig) {
2638 let mut computation = FlagComputation::new();
2640 computation.add_tys(&fn_sig.0.inputs[]);
2642 if let ty::FnConverging(output) = fn_sig.0.output {
2643 computation.add_ty(output);
2646 self.add_bound_computation(&computation);
2649 fn add_region(&mut self, r: Region) {
2650 self.add_flags(HAS_REGIONS);
2652 ty::ReInfer(_) => { self.add_flags(HAS_RE_INFER); }
2653 ty::ReLateBound(debruijn, _) => {
2654 self.add_flags(HAS_RE_LATE_BOUND);
2655 self.add_depth(debruijn.depth);
2661 fn add_projection_predicate(&mut self, projection_predicate: &ProjectionPredicate) {
2662 self.add_projection_ty(&projection_predicate.projection_ty);
2663 self.add_ty(projection_predicate.ty);
2666 fn add_projection_ty(&mut self, projection_ty: &ProjectionTy) {
2667 self.add_substs(projection_ty.trait_ref.substs);
2670 fn add_substs(&mut self, substs: &Substs) {
2671 self.add_tys(substs.types.as_slice());
2672 match substs.regions {
2673 subst::ErasedRegions => {}
2674 subst::NonerasedRegions(ref regions) => {
2675 for &r in regions.iter() {
2682 fn add_bounds(&mut self, bounds: &ExistentialBounds) {
2683 self.add_region(bounds.region_bound);
2687 pub fn mk_mach_int<'tcx>(tcx: &ctxt<'tcx>, tm: ast::IntTy) -> Ty<'tcx> {
2689 ast::TyIs(_) => tcx.types.int,
2690 ast::TyI8 => tcx.types.i8,
2691 ast::TyI16 => tcx.types.i16,
2692 ast::TyI32 => tcx.types.i32,
2693 ast::TyI64 => tcx.types.i64,
2697 pub fn mk_mach_uint<'tcx>(tcx: &ctxt<'tcx>, tm: ast::UintTy) -> Ty<'tcx> {
2699 ast::TyUs(_) => tcx.types.uint,
2700 ast::TyU8 => tcx.types.u8,
2701 ast::TyU16 => tcx.types.u16,
2702 ast::TyU32 => tcx.types.u32,
2703 ast::TyU64 => tcx.types.u64,
2707 pub fn mk_mach_float<'tcx>(tcx: &ctxt<'tcx>, tm: ast::FloatTy) -> Ty<'tcx> {
2709 ast::TyF32 => tcx.types.f32,
2710 ast::TyF64 => tcx.types.f64,
2714 pub fn mk_str<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2718 pub fn mk_str_slice<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, m: ast::Mutability) -> Ty<'tcx> {
2721 ty: mk_t(cx, ty_str),
2726 pub fn mk_enum<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
2727 // take a copy of substs so that we own the vectors inside
2728 mk_t(cx, ty_enum(did, substs))
2731 pub fn mk_uniq<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { mk_t(cx, ty_uniq(ty)) }
2733 pub fn mk_ptr<'tcx>(cx: &ctxt<'tcx>, tm: mt<'tcx>) -> Ty<'tcx> { mk_t(cx, ty_ptr(tm)) }
2735 pub fn mk_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, tm: mt<'tcx>) -> Ty<'tcx> {
2736 mk_t(cx, ty_rptr(r, tm))
2739 pub fn mk_mut_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
2740 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
2742 pub fn mk_imm_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
2743 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
2746 pub fn mk_mut_ptr<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2747 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
2750 pub fn mk_imm_ptr<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2751 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
2754 pub fn mk_nil_ptr<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2755 mk_ptr(cx, mt {ty: mk_nil(cx), mutbl: ast::MutImmutable})
2758 pub fn mk_vec<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>, sz: Option<uint>) -> Ty<'tcx> {
2759 mk_t(cx, ty_vec(ty, sz))
2762 pub fn mk_slice<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, tm: mt<'tcx>) -> Ty<'tcx> {
2765 ty: mk_vec(cx, tm.ty, None),
2770 pub fn mk_tup<'tcx>(cx: &ctxt<'tcx>, ts: Vec<Ty<'tcx>>) -> Ty<'tcx> {
2771 mk_t(cx, ty_tup(ts))
2774 pub fn mk_nil<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2775 mk_tup(cx, Vec::new())
2778 pub fn mk_bare_fn<'tcx>(cx: &ctxt<'tcx>,
2779 opt_def_id: Option<ast::DefId>,
2780 fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
2781 mk_t(cx, ty_bare_fn(opt_def_id, fty))
2784 pub fn mk_ctor_fn<'tcx>(cx: &ctxt<'tcx>,
2786 input_tys: &[Ty<'tcx>],
2787 output: Ty<'tcx>) -> Ty<'tcx> {
2788 let input_args = input_tys.iter().map(|ty| *ty).collect();
2791 cx.mk_bare_fn(BareFnTy {
2792 unsafety: ast::Unsafety::Normal,
2794 sig: ty::Binder(FnSig {
2796 output: ty::FnConverging(output),
2802 pub fn mk_trait<'tcx>(cx: &ctxt<'tcx>,
2803 principal: ty::PolyTraitRef<'tcx>,
2804 bounds: ExistentialBounds<'tcx>)
2807 assert!(bound_list_is_sorted(bounds.projection_bounds.as_slice()));
2809 let inner = box TyTrait {
2810 principal: principal,
2813 mk_t(cx, ty_trait(inner))
2816 fn bound_list_is_sorted(bounds: &[ty::PolyProjectionPredicate]) -> bool {
2817 bounds.len() == 0 ||
2818 bounds[1..].iter().enumerate().all(
2819 |(index, bound)| bounds[index].sort_key() <= bound.sort_key())
2822 pub fn sort_bounds_list(bounds: &mut [ty::PolyProjectionPredicate]) {
2823 bounds.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()))
2826 pub fn mk_projection<'tcx>(cx: &ctxt<'tcx>,
2827 trait_ref: Rc<ty::TraitRef<'tcx>>,
2828 item_name: ast::Name)
2830 // take a copy of substs so that we own the vectors inside
2831 let inner = ProjectionTy { trait_ref: trait_ref, item_name: item_name };
2832 mk_t(cx, ty_projection(inner))
2835 pub fn mk_struct<'tcx>(cx: &ctxt<'tcx>, struct_id: ast::DefId,
2836 substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
2837 // take a copy of substs so that we own the vectors inside
2838 mk_t(cx, ty_struct(struct_id, substs))
2841 pub fn mk_unboxed_closure<'tcx>(cx: &ctxt<'tcx>, closure_id: ast::DefId,
2842 region: &'tcx Region, substs: &'tcx Substs<'tcx>)
2844 mk_t(cx, ty_unboxed_closure(closure_id, region, substs))
2847 pub fn mk_var<'tcx>(cx: &ctxt<'tcx>, v: TyVid) -> Ty<'tcx> {
2848 mk_infer(cx, TyVar(v))
2851 pub fn mk_int_var<'tcx>(cx: &ctxt<'tcx>, v: IntVid) -> Ty<'tcx> {
2852 mk_infer(cx, IntVar(v))
2855 pub fn mk_float_var<'tcx>(cx: &ctxt<'tcx>, v: FloatVid) -> Ty<'tcx> {
2856 mk_infer(cx, FloatVar(v))
2859 pub fn mk_infer<'tcx>(cx: &ctxt<'tcx>, it: InferTy) -> Ty<'tcx> {
2860 mk_t(cx, ty_infer(it))
2863 pub fn mk_param<'tcx>(cx: &ctxt<'tcx>,
2864 space: subst::ParamSpace,
2866 name: ast::Name) -> Ty<'tcx> {
2867 mk_t(cx, ty_param(ParamTy { space: space, idx: index, name: name }))
2870 pub fn mk_self_type<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2871 mk_param(cx, subst::SelfSpace, 0, special_idents::type_self.name)
2874 pub fn mk_param_from_def<'tcx>(cx: &ctxt<'tcx>, def: &TypeParameterDef) -> Ty<'tcx> {
2875 mk_param(cx, def.space, def.index, def.name)
2878 pub fn mk_open<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { mk_t(cx, ty_open(ty)) }
2880 impl<'tcx> TyS<'tcx> {
2881 /// Iterator that walks `self` and any types reachable from
2882 /// `self`, in depth-first order. Note that just walks the types
2883 /// that appear in `self`, it does not descend into the fields of
2884 /// structs or variants. For example:
2888 /// Foo<Bar<int>> => { Foo<Bar<int>>, Bar<int>, int }
2889 /// [int] => { [int], int }
2891 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2892 TypeWalker::new(self)
2895 /// Iterator that walks types reachable from `self`, in
2896 /// depth-first order. Note that this is a shallow walk. For
2901 /// Foo<Bar<int>> => { Bar<int>, int }
2902 /// [int] => { int }
2904 pub fn walk_children(&'tcx self) -> TypeWalker<'tcx> {
2905 // Walks type reachable from `self` but not `self
2906 let mut walker = self.walk();
2907 let r = walker.next();
2908 assert_eq!(r, Some(self));
2913 pub fn walk_ty<'tcx, F>(ty_root: Ty<'tcx>, mut f: F)
2914 where F: FnMut(Ty<'tcx>),
2916 for ty in ty_root.walk() {
2921 /// Walks `ty` and any types appearing within `ty`, invoking the
2922 /// callback `f` on each type. If the callback returns false, then the
2923 /// children of the current type are ignored.
2925 /// Note: prefer `ty.walk()` where possible.
2926 pub fn maybe_walk_ty<'tcx,F>(ty_root: Ty<'tcx>, mut f: F)
2927 where F : FnMut(Ty<'tcx>) -> bool
2929 let mut walker = ty_root.walk();
2930 while let Some(ty) = walker.next() {
2932 walker.skip_current_subtree();
2937 // Folds types from the bottom up.
2938 pub fn fold_ty<'tcx, F>(cx: &ctxt<'tcx>, t0: Ty<'tcx>,
2941 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
2943 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
2948 pub fn new(space: subst::ParamSpace,
2952 ParamTy { space: space, idx: index, name: name }
2955 pub fn for_self() -> ParamTy {
2956 ParamTy::new(subst::SelfSpace, 0, special_idents::type_self.name)
2959 pub fn for_def(def: &TypeParameterDef) -> ParamTy {
2960 ParamTy::new(def.space, def.index, def.name)
2963 pub fn to_ty<'tcx>(self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx> {
2964 ty::mk_param(tcx, self.space, self.idx, self.name)
2967 pub fn is_self(&self) -> bool {
2968 self.space == subst::SelfSpace && self.idx == 0
2972 impl<'tcx> ItemSubsts<'tcx> {
2973 pub fn empty() -> ItemSubsts<'tcx> {
2974 ItemSubsts { substs: Substs::empty() }
2977 pub fn is_noop(&self) -> bool {
2978 self.substs.is_noop()
2982 impl<'tcx> ParamBounds<'tcx> {
2983 pub fn empty() -> ParamBounds<'tcx> {
2985 builtin_bounds: empty_builtin_bounds(),
2986 trait_bounds: Vec::new(),
2987 region_bounds: Vec::new(),
2988 projection_bounds: Vec::new(),
2995 pub fn type_is_nil(ty: Ty) -> bool {
2997 ty_tup(ref tys) => tys.is_empty(),
3002 pub fn type_is_error(ty: Ty) -> bool {
3003 ty.flags.intersects(HAS_TY_ERR)
3006 pub fn type_needs_subst(ty: Ty) -> bool {
3007 ty.flags.intersects(NEEDS_SUBST)
3010 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
3011 tref.substs.types.any(|&ty| type_is_error(ty))
3014 pub fn type_is_ty_var(ty: Ty) -> bool {
3016 ty_infer(TyVar(_)) => true,
3021 pub fn type_is_bool(ty: Ty) -> bool { ty.sty == ty_bool }
3023 pub fn type_is_self(ty: Ty) -> bool {
3025 ty_param(ref p) => p.space == subst::SelfSpace,
3030 fn type_is_slice(ty: Ty) -> bool {
3032 ty_ptr(mt) | ty_rptr(_, mt) => match mt.ty.sty {
3033 ty_vec(_, None) | ty_str => true,
3040 pub fn type_is_vec(ty: Ty) -> bool {
3043 ty_ptr(mt{ty, ..}) | ty_rptr(_, mt{ty, ..}) |
3044 ty_uniq(ty) => match ty.sty {
3045 ty_vec(_, None) => true,
3052 pub fn type_is_structural(ty: Ty) -> bool {
3054 ty_struct(..) | ty_tup(_) | ty_enum(..) |
3055 ty_vec(_, Some(_)) | ty_unboxed_closure(..) => true,
3056 _ => type_is_slice(ty) | type_is_trait(ty)
3060 pub fn type_is_simd(cx: &ctxt, ty: Ty) -> bool {
3062 ty_struct(did, _) => lookup_simd(cx, did),
3067 pub fn sequence_element_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
3069 ty_vec(ty, _) => ty,
3070 ty_str => mk_mach_uint(cx, ast::TyU8),
3071 ty_open(ty) => sequence_element_type(cx, ty),
3072 _ => cx.sess.bug(&format!("sequence_element_type called on non-sequence value: {}",
3073 ty_to_string(cx, ty))[]),
3077 pub fn simd_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
3079 ty_struct(did, substs) => {
3080 let fields = lookup_struct_fields(cx, did);
3081 lookup_field_type(cx, did, fields[0].id, substs)
3083 _ => panic!("simd_type called on invalid type")
3087 pub fn simd_size(cx: &ctxt, ty: Ty) -> uint {
3089 ty_struct(did, _) => {
3090 let fields = lookup_struct_fields(cx, did);
3093 _ => panic!("simd_size called on invalid type")
3097 pub fn type_is_region_ptr(ty: Ty) -> bool {
3099 ty_rptr(..) => true,
3104 pub fn type_is_unsafe_ptr(ty: Ty) -> bool {
3106 ty_ptr(_) => return true,
3111 pub fn type_is_unique(ty: Ty) -> bool {
3113 ty_uniq(_) => match ty.sty {
3114 ty_trait(..) => false,
3122 A scalar type is one that denotes an atomic datum, with no sub-components.
3123 (A ty_ptr is scalar because it represents a non-managed pointer, so its
3124 contents are abstract to rustc.)
3126 pub fn type_is_scalar(ty: Ty) -> bool {
3128 ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
3129 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
3130 ty_bare_fn(..) | ty_ptr(_) => true,
3131 ty_tup(ref tys) if tys.is_empty() => true,
3136 /// Returns true if this type is a floating point type and false otherwise.
3137 pub fn type_is_floating_point(ty: Ty) -> bool {
3139 ty_float(_) => true,
3144 /// Type contents is how the type checker reasons about kinds.
3145 /// They track what kinds of things are found within a type. You can
3146 /// think of them as kind of an "anti-kind". They track the kinds of values
3147 /// and thinks that are contained in types. Having a larger contents for
3148 /// a type tends to rule that type *out* from various kinds. For example,
3149 /// a type that contains a reference is not sendable.
3151 /// The reason we compute type contents and not kinds is that it is
3152 /// easier for me (nmatsakis) to think about what is contained within
3153 /// a type than to think about what is *not* contained within a type.
3154 #[derive(Clone, Copy)]
3155 pub struct TypeContents {
3159 macro_rules! def_type_content_sets {
3160 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
3161 #[allow(non_snake_case)]
3163 use middle::ty::TypeContents;
3165 #[allow(non_upper_case_globals)]
3166 pub const $name: TypeContents = TypeContents { bits: $bits };
3172 def_type_content_sets! {
3174 None = 0b0000_0000__0000_0000__0000,
3176 // Things that are interior to the value (first nibble):
3177 InteriorUnsized = 0b0000_0000__0000_0000__0001,
3178 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
3179 InteriorParam = 0b0000_0000__0000_0000__0100,
3180 // InteriorAll = 0b00000000__00000000__1111,
3182 // Things that are owned by the value (second and third nibbles):
3183 OwnsOwned = 0b0000_0000__0000_0001__0000,
3184 OwnsDtor = 0b0000_0000__0000_0010__0000,
3185 OwnsManaged /* see [1] below */ = 0b0000_0000__0000_0100__0000,
3186 OwnsAll = 0b0000_0000__1111_1111__0000,
3188 // Things that are reachable by the value in any way (fourth nibble):
3189 ReachesBorrowed = 0b0000_0010__0000_0000__0000,
3190 // ReachesManaged /* see [1] below */ = 0b0000_0100__0000_0000__0000,
3191 ReachesMutable = 0b0000_1000__0000_0000__0000,
3192 ReachesFfiUnsafe = 0b0010_0000__0000_0000__0000,
3193 ReachesAll = 0b0011_1111__0000_0000__0000,
3195 // Things that mean drop glue is necessary
3196 NeedsDrop = 0b0000_0000__0000_0111__0000,
3198 // Things that prevent values from being considered sized
3199 Nonsized = 0b0000_0000__0000_0000__0001,
3201 // Bits to set when a managed value is encountered
3203 // [1] Do not set the bits TC::OwnsManaged or
3204 // TC::ReachesManaged directly, instead reference
3205 // TC::Managed to set them both at once.
3206 Managed = 0b0000_0100__0000_0100__0000,
3209 All = 0b1111_1111__1111_1111__1111
3214 pub fn when(&self, cond: bool) -> TypeContents {
3215 if cond {*self} else {TC::None}
3218 pub fn intersects(&self, tc: TypeContents) -> bool {
3219 (self.bits & tc.bits) != 0
3222 pub fn owns_managed(&self) -> bool {
3223 self.intersects(TC::OwnsManaged)
3226 pub fn owns_owned(&self) -> bool {
3227 self.intersects(TC::OwnsOwned)
3230 pub fn is_sized(&self, _: &ctxt) -> bool {
3231 !self.intersects(TC::Nonsized)
3234 pub fn interior_param(&self) -> bool {
3235 self.intersects(TC::InteriorParam)
3238 pub fn interior_unsafe(&self) -> bool {
3239 self.intersects(TC::InteriorUnsafe)
3242 pub fn interior_unsized(&self) -> bool {
3243 self.intersects(TC::InteriorUnsized)
3246 pub fn needs_drop(&self, _: &ctxt) -> bool {
3247 self.intersects(TC::NeedsDrop)
3250 /// Includes only those bits that still apply when indirected through a `Box` pointer
3251 pub fn owned_pointer(&self) -> TypeContents {
3253 *self & (TC::OwnsAll | TC::ReachesAll))
3256 /// Includes only those bits that still apply when indirected through a reference (`&`)
3257 pub fn reference(&self, bits: TypeContents) -> TypeContents {
3259 *self & TC::ReachesAll)
3262 /// Includes only those bits that still apply when indirected through a managed pointer (`@`)
3263 pub fn managed_pointer(&self) -> TypeContents {
3265 *self & TC::ReachesAll)
3268 /// Includes only those bits that still apply when indirected through an unsafe pointer (`*`)
3269 pub fn unsafe_pointer(&self) -> TypeContents {
3270 *self & TC::ReachesAll
3273 pub fn union<T, F>(v: &[T], mut f: F) -> TypeContents where
3274 F: FnMut(&T) -> TypeContents,
3276 v.iter().fold(TC::None, |tc, ty| tc | f(ty))
3279 pub fn has_dtor(&self) -> bool {
3280 self.intersects(TC::OwnsDtor)
3284 impl ops::BitOr for TypeContents {
3285 type Output = TypeContents;
3287 fn bitor(self, other: TypeContents) -> TypeContents {
3288 TypeContents {bits: self.bits | other.bits}
3292 impl ops::BitAnd for TypeContents {
3293 type Output = TypeContents;
3295 fn bitand(self, other: TypeContents) -> TypeContents {
3296 TypeContents {bits: self.bits & other.bits}
3300 impl ops::Sub for TypeContents {
3301 type Output = TypeContents;
3303 fn sub(self, other: TypeContents) -> TypeContents {
3304 TypeContents {bits: self.bits & !other.bits}
3308 impl fmt::Debug for TypeContents {
3309 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3310 write!(f, "TypeContents({:b})", self.bits)
3314 pub fn type_interior_is_unsafe<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
3315 type_contents(cx, ty).interior_unsafe()
3318 pub fn type_contents<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> TypeContents {
3319 return memoized(&cx.tc_cache, ty, |ty| {
3320 tc_ty(cx, ty, &mut FnvHashMap())
3323 fn tc_ty<'tcx>(cx: &ctxt<'tcx>,
3325 cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
3327 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
3328 // private cache for this walk. This is needed in the case of cyclic
3331 // struct List { next: Box<Option<List>>, ... }
3333 // When computing the type contents of such a type, we wind up deeply
3334 // recursing as we go. So when we encounter the recursive reference
3335 // to List, we temporarily use TC::None as its contents. Later we'll
3336 // patch up the cache with the correct value, once we've computed it
3337 // (this is basically a co-inductive process, if that helps). So in
3338 // the end we'll compute TC::OwnsOwned, in this case.
3340 // The problem is, as we are doing the computation, we will also
3341 // compute an *intermediate* contents for, e.g., Option<List> of
3342 // TC::None. This is ok during the computation of List itself, but if
3343 // we stored this intermediate value into cx.tc_cache, then later
3344 // requests for the contents of Option<List> would also yield TC::None
3345 // which is incorrect. This value was computed based on the crutch
3346 // value for the type contents of list. The correct value is
3347 // TC::OwnsOwned. This manifested as issue #4821.
3348 match cache.get(&ty) {
3349 Some(tc) => { return *tc; }
3352 match cx.tc_cache.borrow().get(&ty) { // Must check both caches!
3353 Some(tc) => { return *tc; }
3356 cache.insert(ty, TC::None);
3358 let result = match ty.sty {
3359 // uint and int are ffi-unsafe
3360 ty_uint(ast::TyUs(_)) | ty_int(ast::TyIs(_)) => {
3361 TC::ReachesFfiUnsafe
3364 // Scalar and unique types are sendable, and durable
3365 ty_infer(ty::FreshIntTy(_)) |
3366 ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
3367 ty_bare_fn(..) | ty::ty_char => {
3372 TC::ReachesFfiUnsafe | match typ.sty {
3373 ty_str => TC::OwnsOwned,
3374 _ => tc_ty(cx, typ, cache).owned_pointer(),
3378 ty_trait(box TyTrait { ref bounds, .. }) => {
3379 object_contents(bounds) | TC::ReachesFfiUnsafe | TC::Nonsized
3383 tc_ty(cx, mt.ty, cache).unsafe_pointer()
3386 ty_rptr(r, ref mt) => {
3387 TC::ReachesFfiUnsafe | match mt.ty.sty {
3388 ty_str => borrowed_contents(*r, ast::MutImmutable),
3389 ty_vec(..) => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(*r,
3391 _ => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(*r, mt.mutbl)),
3395 ty_vec(ty, Some(_)) => {
3396 tc_ty(cx, ty, cache)
3399 ty_vec(ty, None) => {
3400 tc_ty(cx, ty, cache) | TC::Nonsized
3402 ty_str => TC::Nonsized,
3404 ty_struct(did, substs) => {
3405 let flds = struct_fields(cx, did, substs);
3407 TypeContents::union(&flds[],
3408 |f| tc_mt(cx, f.mt, cache));
3410 if !lookup_repr_hints(cx, did).contains(&attr::ReprExtern) {
3411 res = res | TC::ReachesFfiUnsafe;
3414 if ty::has_dtor(cx, did) {
3415 res = res | TC::OwnsDtor;
3417 apply_lang_items(cx, did, res)
3420 ty_unboxed_closure(did, r, substs) => {
3421 // FIXME(#14449): `borrowed_contents` below assumes `&mut`
3423 let param_env = ty::empty_parameter_environment(cx);
3424 let upvars = unboxed_closure_upvars(¶m_env, did, substs).unwrap();
3425 TypeContents::union(upvars.as_slice(),
3426 |f| tc_ty(cx, f.ty, cache))
3427 | borrowed_contents(*r, MutMutable)
3430 ty_tup(ref tys) => {
3431 TypeContents::union(&tys[],
3432 |ty| tc_ty(cx, *ty, cache))
3435 ty_enum(did, substs) => {
3436 let variants = substd_enum_variants(cx, did, substs);
3438 TypeContents::union(&variants[], |variant| {
3439 TypeContents::union(&variant.args[],
3441 tc_ty(cx, *arg_ty, cache)
3445 if ty::has_dtor(cx, did) {
3446 res = res | TC::OwnsDtor;
3449 if variants.len() != 0 {
3450 let repr_hints = lookup_repr_hints(cx, did);
3451 if repr_hints.len() > 1 {
3452 // this is an error later on, but this type isn't safe
3453 res = res | TC::ReachesFfiUnsafe;
3456 match repr_hints.get(0) {
3457 Some(h) => if !h.is_ffi_safe() {
3458 res = res | TC::ReachesFfiUnsafe;
3462 res = res | TC::ReachesFfiUnsafe;
3464 // We allow ReprAny enums if they are eligible for
3465 // the nullable pointer optimization and the
3466 // contained type is an `extern fn`
3468 if variants.len() == 2 {
3469 let mut data_idx = 0;
3471 if variants[0].args.len() == 0 {
3475 if variants[data_idx].args.len() == 1 {
3476 match variants[data_idx].args[0].sty {
3477 ty_bare_fn(..) => { res = res - TC::ReachesFfiUnsafe; }
3487 apply_lang_items(cx, did, res)
3496 let result = tc_ty(cx, ty, cache);
3497 assert!(!result.is_sized(cx));
3498 result.unsafe_pointer() | TC::Nonsized
3503 cx.sess.bug("asked to compute contents of error type");
3507 cache.insert(ty, result);
3511 fn tc_mt<'tcx>(cx: &ctxt<'tcx>,
3513 cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
3515 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
3516 mc | tc_ty(cx, mt.ty, cache)
3519 fn apply_lang_items(cx: &ctxt, did: ast::DefId, tc: TypeContents)
3521 if Some(did) == cx.lang_items.managed_bound() {
3523 } else if Some(did) == cx.lang_items.unsafe_type() {
3524 tc | TC::InteriorUnsafe
3530 /// Type contents due to containing a reference with the region `region` and borrow kind `bk`
3531 fn borrowed_contents(region: ty::Region,
3532 mutbl: ast::Mutability)
3534 let b = match mutbl {
3535 ast::MutMutable => TC::ReachesMutable,
3536 ast::MutImmutable => TC::None,
3538 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
3541 fn object_contents(bounds: &ExistentialBounds) -> TypeContents {
3542 // These are the type contents of the (opaque) interior. We
3543 // make no assumptions (other than that it cannot have an
3544 // in-scope type parameter within, which makes no sense).
3545 let mut tc = TC::All - TC::InteriorParam;
3546 for bound in bounds.builtin_bounds.iter() {
3547 tc = tc - match bound {
3548 BoundSync | BoundSend | BoundCopy => TC::None,
3549 BoundSized => TC::Nonsized,
3556 fn type_impls_bound<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>,
3557 cache: &RefCell<HashMap<Ty<'tcx>,bool>>,
3559 bound: ty::BuiltinBound,
3563 assert!(!ty::type_needs_infer(ty));
3565 if !type_has_params(ty) && !type_has_self(ty) {
3566 match cache.borrow().get(&ty) {
3569 debug!("type_impls_bound({}, {:?}) = {:?} (cached)",
3570 ty.repr(param_env.tcx),
3578 let infcx = infer::new_infer_ctxt(param_env.tcx);
3580 let is_impld = traits::type_known_to_meet_builtin_bound(&infcx, param_env, ty, bound, span);
3582 debug!("type_impls_bound({}, {:?}) = {:?}",
3583 ty.repr(param_env.tcx),
3587 if !type_has_params(ty) && !type_has_self(ty) {
3588 let old_value = cache.borrow_mut().insert(ty, is_impld);
3589 assert!(old_value.is_none());
3595 pub fn type_moves_by_default<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>,
3600 let tcx = param_env.tcx;
3601 !type_impls_bound(param_env, &tcx.type_impls_copy_cache, ty, ty::BoundCopy, span)
3604 pub fn type_is_sized<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>,
3609 let tcx = param_env.tcx;
3610 type_impls_bound(param_env, &tcx.type_impls_sized_cache, ty, ty::BoundSized, span)
3613 pub fn is_ffi_safe<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
3614 !type_contents(cx, ty).intersects(TC::ReachesFfiUnsafe)
3617 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
3618 pub fn is_instantiable<'tcx>(cx: &ctxt<'tcx>, r_ty: Ty<'tcx>) -> bool {
3619 fn type_requires<'tcx>(cx: &ctxt<'tcx>, seen: &mut Vec<DefId>,
3620 r_ty: Ty<'tcx>, ty: Ty<'tcx>) -> bool {
3621 debug!("type_requires({:?}, {:?})?",
3622 ::util::ppaux::ty_to_string(cx, r_ty),
3623 ::util::ppaux::ty_to_string(cx, ty));
3625 let r = r_ty == ty || subtypes_require(cx, seen, r_ty, ty);
3627 debug!("type_requires({:?}, {:?})? {:?}",
3628 ::util::ppaux::ty_to_string(cx, r_ty),
3629 ::util::ppaux::ty_to_string(cx, ty),
3634 fn subtypes_require<'tcx>(cx: &ctxt<'tcx>, seen: &mut Vec<DefId>,
3635 r_ty: Ty<'tcx>, ty: Ty<'tcx>) -> bool {
3636 debug!("subtypes_require({:?}, {:?})?",
3637 ::util::ppaux::ty_to_string(cx, r_ty),
3638 ::util::ppaux::ty_to_string(cx, ty));
3640 let r = match ty.sty {
3641 // fixed length vectors need special treatment compared to
3642 // normal vectors, since they don't necessarily have the
3643 // possibility to have length zero.
3644 ty_vec(_, Some(0)) => false, // don't need no contents
3645 ty_vec(ty, Some(_)) => type_requires(cx, seen, r_ty, ty),
3656 ty_vec(_, None) => {
3659 ty_uniq(typ) | ty_open(typ) => {
3660 type_requires(cx, seen, r_ty, typ)
3662 ty_rptr(_, ref mt) => {
3663 type_requires(cx, seen, r_ty, mt.ty)
3667 false // unsafe ptrs can always be NULL
3674 ty_struct(ref did, _) if seen.contains(did) => {
3678 ty_struct(did, substs) => {
3680 let fields = struct_fields(cx, did, substs);
3681 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
3682 seen.pop().unwrap();
3688 ty_unboxed_closure(..) => {
3689 // this check is run on type definitions, so we don't expect to see
3690 // inference by-products or unboxed closure types
3691 cx.sess.bug(format!("requires check invoked on inapplicable type: {:?}",
3696 ts.iter().any(|ty| type_requires(cx, seen, r_ty, *ty))
3699 ty_enum(ref did, _) if seen.contains(did) => {
3703 ty_enum(did, substs) => {
3705 let vs = enum_variants(cx, did);
3706 let r = !vs.is_empty() && vs.iter().all(|variant| {
3707 variant.args.iter().any(|aty| {
3708 let sty = aty.subst(cx, substs);
3709 type_requires(cx, seen, r_ty, sty)
3712 seen.pop().unwrap();
3717 debug!("subtypes_require({:?}, {:?})? {:?}",
3718 ::util::ppaux::ty_to_string(cx, r_ty),
3719 ::util::ppaux::ty_to_string(cx, ty),
3725 let mut seen = Vec::new();
3726 !subtypes_require(cx, &mut seen, r_ty, r_ty)
3729 /// Describes whether a type is representable. For types that are not
3730 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
3731 /// distinguish between types that are recursive with themselves and types that
3732 /// contain a different recursive type. These cases can therefore be treated
3733 /// differently when reporting errors.
3735 /// The ordering of the cases is significant. They are sorted so that cmp::max
3736 /// will keep the "more erroneous" of two values.
3737 #[derive(Copy, PartialOrd, Ord, Eq, PartialEq, Show)]
3738 pub enum Representability {
3744 /// Check whether a type is representable. This means it cannot contain unboxed
3745 /// structural recursion. This check is needed for structs and enums.
3746 pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>)
3747 -> Representability {
3749 // Iterate until something non-representable is found
3750 fn find_nonrepresentable<'tcx, It: Iterator<Item=Ty<'tcx>>>(cx: &ctxt<'tcx>, sp: Span,
3751 seen: &mut Vec<Ty<'tcx>>,
3753 -> Representability {
3754 iter.fold(Representable,
3755 |r, ty| cmp::max(r, is_type_structurally_recursive(cx, sp, seen, ty)))
3758 fn are_inner_types_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
3759 seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
3760 -> Representability {
3763 find_nonrepresentable(cx, sp, seen, ts.iter().map(|ty| *ty))
3765 // Fixed-length vectors.
3766 // FIXME(#11924) Behavior undecided for zero-length vectors.
3767 ty_vec(ty, Some(_)) => {
3768 is_type_structurally_recursive(cx, sp, seen, ty)
3770 ty_struct(did, substs) => {
3771 let fields = struct_fields(cx, did, substs);
3772 find_nonrepresentable(cx, sp, seen, fields.iter().map(|f| f.mt.ty))
3774 ty_enum(did, substs) => {
3775 let vs = enum_variants(cx, did);
3776 let iter = vs.iter()
3777 .flat_map(|variant| { variant.args.iter() })
3778 .map(|aty| { aty.subst_spanned(cx, substs, Some(sp)) });
3780 find_nonrepresentable(cx, sp, seen, iter)
3782 ty_unboxed_closure(..) => {
3783 // this check is run on type definitions, so we don't expect to see
3784 // unboxed closure types
3785 cx.sess.bug(format!("requires check invoked on inapplicable type: {:?}",
3792 fn same_struct_or_enum_def_id(ty: Ty, did: DefId) -> bool {
3794 ty_struct(ty_did, _) | ty_enum(ty_did, _) => {
3801 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
3802 match (&a.sty, &b.sty) {
3803 (&ty_struct(did_a, ref substs_a), &ty_struct(did_b, ref substs_b)) |
3804 (&ty_enum(did_a, ref substs_a), &ty_enum(did_b, ref substs_b)) => {
3809 let types_a = substs_a.types.get_slice(subst::TypeSpace);
3810 let types_b = substs_b.types.get_slice(subst::TypeSpace);
3812 let pairs = types_a.iter().zip(types_b.iter());
3814 pairs.all(|(&a, &b)| same_type(a, b))
3822 // Does the type `ty` directly (without indirection through a pointer)
3823 // contain any types on stack `seen`?
3824 fn is_type_structurally_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
3825 seen: &mut Vec<Ty<'tcx>>,
3826 ty: Ty<'tcx>) -> Representability {
3827 debug!("is_type_structurally_recursive: {:?}",
3828 ::util::ppaux::ty_to_string(cx, ty));
3831 ty_struct(did, _) | ty_enum(did, _) => {
3833 // Iterate through stack of previously seen types.
3834 let mut iter = seen.iter();
3836 // The first item in `seen` is the type we are actually curious about.
3837 // We want to return SelfRecursive if this type contains itself.
3838 // It is important that we DON'T take generic parameters into account
3839 // for this check, so that Bar<T> in this example counts as SelfRecursive:
3842 // struct Bar<T> { x: Bar<Foo> }
3845 Some(&seen_type) => {
3846 if same_struct_or_enum_def_id(seen_type, did) {
3847 debug!("SelfRecursive: {:?} contains {:?}",
3848 ::util::ppaux::ty_to_string(cx, seen_type),
3849 ::util::ppaux::ty_to_string(cx, ty));
3850 return SelfRecursive;
3856 // We also need to know whether the first item contains other types that
3857 // are structurally recursive. If we don't catch this case, we will recurse
3858 // infinitely for some inputs.
3860 // It is important that we DO take generic parameters into account here,
3861 // so that code like this is considered SelfRecursive, not ContainsRecursive:
3863 // struct Foo { Option<Option<Foo>> }
3865 for &seen_type in iter {
3866 if same_type(ty, seen_type) {
3867 debug!("ContainsRecursive: {:?} contains {:?}",
3868 ::util::ppaux::ty_to_string(cx, seen_type),
3869 ::util::ppaux::ty_to_string(cx, ty));
3870 return ContainsRecursive;
3875 // For structs and enums, track all previously seen types by pushing them
3876 // onto the 'seen' stack.
3878 let out = are_inner_types_recursive(cx, sp, seen, ty);
3883 // No need to push in other cases.
3884 are_inner_types_recursive(cx, sp, seen, ty)
3889 debug!("is_type_representable: {:?}",
3890 ::util::ppaux::ty_to_string(cx, ty));
3892 // To avoid a stack overflow when checking an enum variant or struct that
3893 // contains a different, structurally recursive type, maintain a stack
3894 // of seen types and check recursion for each of them (issues #3008, #3779).
3895 let mut seen: Vec<Ty> = Vec::new();
3896 let r = is_type_structurally_recursive(cx, sp, &mut seen, ty);
3897 debug!("is_type_representable: {:?} is {:?}",
3898 ::util::ppaux::ty_to_string(cx, ty), r);
3902 pub fn type_is_trait(ty: Ty) -> bool {
3903 type_trait_info(ty).is_some()
3906 pub fn type_trait_info<'tcx>(ty: Ty<'tcx>) -> Option<&'tcx TyTrait<'tcx>> {
3908 ty_uniq(ty) | ty_rptr(_, mt { ty, ..}) | ty_ptr(mt { ty, ..}) => match ty.sty {
3909 ty_trait(ref t) => Some(&**t),
3912 ty_trait(ref t) => Some(&**t),
3917 pub fn type_is_integral(ty: Ty) -> bool {
3919 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
3924 pub fn type_is_fresh(ty: Ty) -> bool {
3926 ty_infer(FreshTy(_)) => true,
3927 ty_infer(FreshIntTy(_)) => true,
3932 pub fn type_is_uint(ty: Ty) -> bool {
3934 ty_infer(IntVar(_)) | ty_uint(ast::TyUs(_)) => true,
3939 pub fn type_is_char(ty: Ty) -> bool {
3946 pub fn type_is_bare_fn(ty: Ty) -> bool {
3948 ty_bare_fn(..) => true,
3953 pub fn type_is_bare_fn_item(ty: Ty) -> bool {
3955 ty_bare_fn(Some(_), _) => true,
3960 pub fn type_is_fp(ty: Ty) -> bool {
3962 ty_infer(FloatVar(_)) | ty_float(_) => true,
3967 pub fn type_is_numeric(ty: Ty) -> bool {
3968 return type_is_integral(ty) || type_is_fp(ty);
3971 pub fn type_is_signed(ty: Ty) -> bool {
3978 pub fn type_is_machine(ty: Ty) -> bool {
3980 ty_int(ast::TyIs(_)) | ty_uint(ast::TyUs(_)) => false,
3981 ty_int(..) | ty_uint(..) | ty_float(..) => true,
3986 // Whether a type is enum like, that is an enum type with only nullary
3988 pub fn type_is_c_like_enum(cx: &ctxt, ty: Ty) -> bool {
3990 ty_enum(did, _) => {
3991 let variants = enum_variants(cx, did);
3992 if variants.len() == 0 {
3995 variants.iter().all(|v| v.args.len() == 0)
4002 // Returns the type and mutability of *ty.
4004 // The parameter `explicit` indicates if this is an *explicit* dereference.
4005 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
4006 pub fn deref<'tcx>(ty: Ty<'tcx>, explicit: bool) -> Option<mt<'tcx>> {
4011 mutbl: ast::MutImmutable,
4014 ty_rptr(_, mt) => Some(mt),
4015 ty_ptr(mt) if explicit => Some(mt),
4020 pub fn close_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
4022 ty_open(ty) => mk_rptr(cx, cx.mk_region(ReStatic), mt {ty: ty, mutbl:ast::MutImmutable}),
4023 _ => cx.sess.bug(&format!("Trying to close a non-open type {}",
4024 ty_to_string(cx, ty))[])
4028 pub fn type_content<'tcx>(ty: Ty<'tcx>) -> Ty<'tcx> {
4031 ty_rptr(_, mt) |ty_ptr(mt) => mt.ty,
4036 // Extract the unsized type in an open type (or just return ty if it is not open).
4037 pub fn unopen_type<'tcx>(ty: Ty<'tcx>) -> Ty<'tcx> {
4044 // Returns the type of ty[i]
4045 pub fn index<'tcx>(ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
4047 ty_vec(ty, _) => Some(ty),
4052 // Returns the type of elements contained within an 'array-like' type.
4053 // This is exactly the same as the above, except it supports strings,
4054 // which can't actually be indexed.
4055 pub fn array_element_ty<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
4057 ty_vec(ty, _) => Some(ty),
4058 ty_str => Some(tcx.types.u8),
4063 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
4064 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
4065 pub fn positional_element_ty<'tcx>(cx: &ctxt<'tcx>,
4068 variant: Option<ast::DefId>) -> Option<Ty<'tcx>> {
4070 match (&ty.sty, variant) {
4071 (&ty_tup(ref v), None) => v.get(i).map(|&t| t),
4074 (&ty_struct(def_id, substs), None) => lookup_struct_fields(cx, def_id)
4076 .map(|&t|lookup_item_type(cx, t.id).ty.subst(cx, substs)),
4078 (&ty_enum(def_id, substs), Some(variant_def_id)) => {
4079 let variant_info = enum_variant_with_id(cx, def_id, variant_def_id);
4080 variant_info.args.get(i).map(|t|t.subst(cx, substs))
4083 (&ty_enum(def_id, substs), None) => {
4084 assert!(enum_is_univariant(cx, def_id));
4085 let enum_variants = enum_variants(cx, def_id);
4086 let variant_info = &(*enum_variants)[0];
4087 variant_info.args.get(i).map(|t|t.subst(cx, substs))
4094 /// Returns the type of element at field `n` in struct or struct-like type `t`.
4095 /// For an enum `t`, `variant` must be some def id.
4096 pub fn named_element_ty<'tcx>(cx: &ctxt<'tcx>,
4099 variant: Option<ast::DefId>) -> Option<Ty<'tcx>> {
4101 match (&ty.sty, variant) {
4102 (&ty_struct(def_id, substs), None) => {
4103 let r = lookup_struct_fields(cx, def_id);
4104 r.iter().find(|f| f.name == n)
4105 .map(|&f| lookup_field_type(cx, def_id, f.id, substs))
4107 (&ty_enum(def_id, substs), Some(variant_def_id)) => {
4108 let variant_info = enum_variant_with_id(cx, def_id, variant_def_id);
4109 variant_info.arg_names.as_ref()
4110 .expect("must have struct enum variant if accessing a named fields")
4111 .iter().zip(variant_info.args.iter())
4112 .find(|&(ident, _)| ident.name == n)
4113 .map(|(_ident, arg_t)| arg_t.subst(cx, substs))
4119 pub fn node_id_to_trait_ref<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId)
4120 -> Rc<ty::TraitRef<'tcx>> {
4121 match cx.trait_refs.borrow().get(&id) {
4122 Some(ty) => ty.clone(),
4123 None => cx.sess.bug(
4124 &format!("node_id_to_trait_ref: no trait ref for node `{}`",
4125 cx.map.node_to_string(id))[])
4129 pub fn node_id_to_type<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> Ty<'tcx> {
4130 match node_id_to_type_opt(cx, id) {
4132 None => cx.sess.bug(
4133 &format!("node_id_to_type: no type for node `{}`",
4134 cx.map.node_to_string(id))[])
4138 pub fn node_id_to_type_opt<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> Option<Ty<'tcx>> {
4139 match cx.node_types.borrow().get(&id) {
4140 Some(&ty) => Some(ty),
4145 pub fn node_id_item_substs<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> ItemSubsts<'tcx> {
4146 match cx.item_substs.borrow().get(&id) {
4147 None => ItemSubsts::empty(),
4148 Some(ts) => ts.clone(),
4152 pub fn fn_is_variadic(fty: Ty) -> bool {
4154 ty_bare_fn(_, ref f) => f.sig.0.variadic,
4156 panic!("fn_is_variadic() called on non-fn type: {:?}", s)
4161 pub fn ty_fn_sig<'tcx>(fty: Ty<'tcx>) -> &'tcx PolyFnSig<'tcx> {
4163 ty_bare_fn(_, ref f) => &f.sig,
4165 panic!("ty_fn_sig() called on non-fn type: {:?}", s)
4170 /// Returns the ABI of the given function.
4171 pub fn ty_fn_abi(fty: Ty) -> abi::Abi {
4173 ty_bare_fn(_, ref f) => f.abi,
4174 _ => panic!("ty_fn_abi() called on non-fn type"),
4178 // Type accessors for substructures of types
4179 pub fn ty_fn_args<'tcx>(fty: Ty<'tcx>) -> ty::Binder<Vec<Ty<'tcx>>> {
4180 ty_fn_sig(fty).inputs()
4183 pub fn ty_fn_ret<'tcx>(fty: Ty<'tcx>) -> Binder<FnOutput<'tcx>> {
4185 ty_bare_fn(_, ref f) => f.sig.output(),
4187 panic!("ty_fn_ret() called on non-fn type: {:?}", s)
4192 pub fn is_fn_ty(fty: Ty) -> bool {
4194 ty_bare_fn(..) => true,
4199 pub fn ty_region(tcx: &ctxt,
4203 ty_rptr(r, _) => *r,
4207 &format!("ty_region() invoked on an inappropriate ty: {:?}",
4213 pub fn free_region_from_def(free_id: ast::NodeId, def: &RegionParameterDef)
4216 ty::ReFree(ty::FreeRegion { scope: region::CodeExtent::from_node_id(free_id),
4217 bound_region: ty::BrNamed(def.def_id,
4221 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
4222 // doesn't provide type parameter substitutions.
4223 pub fn pat_ty<'tcx>(cx: &ctxt<'tcx>, pat: &ast::Pat) -> Ty<'tcx> {
4224 return node_id_to_type(cx, pat.id);
4228 // Returns the type of an expression as a monotype.
4230 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
4231 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
4232 // auto-ref. The type returned by this function does not consider such
4233 // adjustments. See `expr_ty_adjusted()` instead.
4235 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
4236 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
4237 // instead of "fn(ty) -> T with T = int".
4238 pub fn expr_ty<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Ty<'tcx> {
4239 return node_id_to_type(cx, expr.id);
4242 pub fn expr_ty_opt<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Option<Ty<'tcx>> {
4243 return node_id_to_type_opt(cx, expr.id);
4246 /// Returns the type of `expr`, considering any `AutoAdjustment`
4247 /// entry recorded for that expression.
4249 /// It would almost certainly be better to store the adjusted ty in with
4250 /// the `AutoAdjustment`, but I opted not to do this because it would
4251 /// require serializing and deserializing the type and, although that's not
4252 /// hard to do, I just hate that code so much I didn't want to touch it
4253 /// unless it was to fix it properly, which seemed a distraction from the
4254 /// task at hand! -nmatsakis
4255 pub fn expr_ty_adjusted<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Ty<'tcx> {
4256 adjust_ty(cx, expr.span, expr.id, expr_ty(cx, expr),
4257 cx.adjustments.borrow().get(&expr.id),
4258 |method_call| cx.method_map.borrow().get(&method_call).map(|method| method.ty))
4261 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
4262 match cx.map.find(id) {
4263 Some(ast_map::NodeExpr(e)) => {
4267 cx.sess.bug(&format!("Node id {} is not an expr: {:?}",
4272 cx.sess.bug(&format!("Node id {} is not present \
4273 in the node map", id)[]);
4278 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
4279 match cx.map.find(id) {
4280 Some(ast_map::NodeLocal(pat)) => {
4282 ast::PatIdent(_, ref path1, _) => {
4283 token::get_ident(path1.node)
4287 &format!("Variable id {} maps to {:?}, not local",
4294 cx.sess.bug(&format!("Variable id {} maps to {:?}, not local",
4301 /// See `expr_ty_adjusted`
4302 pub fn adjust_ty<'tcx, F>(cx: &ctxt<'tcx>,
4304 expr_id: ast::NodeId,
4305 unadjusted_ty: Ty<'tcx>,
4306 adjustment: Option<&AutoAdjustment<'tcx>>,
4309 F: FnMut(MethodCall) -> Option<Ty<'tcx>>,
4311 if let ty_err = unadjusted_ty.sty {
4312 return unadjusted_ty;
4315 return match adjustment {
4316 Some(adjustment) => {
4318 AdjustReifyFnPointer(_) => {
4319 match unadjusted_ty.sty {
4320 ty::ty_bare_fn(Some(_), b) => {
4321 ty::mk_bare_fn(cx, None, b)
4325 &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
4332 AdjustDerefRef(ref adj) => {
4333 let mut adjusted_ty = unadjusted_ty;
4335 if !ty::type_is_error(adjusted_ty) {
4336 for i in range(0, adj.autoderefs) {
4337 let method_call = MethodCall::autoderef(expr_id, i);
4338 match method_type(method_call) {
4339 Some(method_ty) => {
4340 // overloaded deref operators have all late-bound
4341 // regions fully instantiated and coverge
4343 ty::assert_no_late_bound_regions(cx,
4344 &ty_fn_ret(method_ty));
4345 adjusted_ty = fn_ret.unwrap();
4349 match deref(adjusted_ty, true) {
4350 Some(mt) => { adjusted_ty = mt.ty; }
4354 &format!("the {}th autoderef failed: \
4357 ty_to_string(cx, adjusted_ty))
4364 adjust_ty_for_autoref(cx, span, adjusted_ty, adj.autoref.as_ref())
4368 None => unadjusted_ty
4372 pub fn adjust_ty_for_autoref<'tcx>(cx: &ctxt<'tcx>,
4375 autoref: Option<&AutoRef<'tcx>>)
4381 Some(&AutoPtr(r, m, ref a)) => {
4382 let adjusted_ty = match a {
4383 &Some(box ref a) => adjust_ty_for_autoref(cx, span, ty, Some(a)),
4386 mk_rptr(cx, cx.mk_region(r), mt {
4392 Some(&AutoUnsafe(m, ref a)) => {
4393 let adjusted_ty = match a {
4394 &Some(box ref a) => adjust_ty_for_autoref(cx, span, ty, Some(a)),
4397 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
4400 Some(&AutoUnsize(ref k)) => unsize_ty(cx, ty, k, span),
4402 Some(&AutoUnsizeUniq(ref k)) => ty::mk_uniq(cx, unsize_ty(cx, ty, k, span)),
4406 // Take a sized type and a sizing adjustment and produce an unsized version of
4408 pub fn unsize_ty<'tcx>(cx: &ctxt<'tcx>,
4410 kind: &UnsizeKind<'tcx>,
4414 &UnsizeLength(len) => match ty.sty {
4415 ty_vec(ty, Some(n)) => {
4417 mk_vec(cx, ty, None)
4419 _ => cx.sess.span_bug(span,
4420 &format!("UnsizeLength with bad sty: {:?}",
4421 ty_to_string(cx, ty))[])
4423 &UnsizeStruct(box ref k, tp_index) => match ty.sty {
4424 ty_struct(did, substs) => {
4425 let ty_substs = substs.types.get_slice(subst::TypeSpace);
4426 let new_ty = unsize_ty(cx, ty_substs[tp_index], k, span);
4427 let mut unsized_substs = substs.clone();
4428 unsized_substs.types.get_mut_slice(subst::TypeSpace)[tp_index] = new_ty;
4429 mk_struct(cx, did, cx.mk_substs(unsized_substs))
4431 _ => cx.sess.span_bug(span,
4432 &format!("UnsizeStruct with bad sty: {:?}",
4433 ty_to_string(cx, ty))[])
4435 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
4436 mk_trait(cx, principal.clone(), bounds.clone())
4441 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> def::Def {
4442 match tcx.def_map.borrow().get(&expr.id) {
4445 tcx.sess.span_bug(expr.span, &format!(
4446 "no def-map entry for expr {}", expr.id)[]);
4451 pub fn expr_is_lval(tcx: &ctxt, e: &ast::Expr) -> bool {
4452 match expr_kind(tcx, e) {
4454 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
4458 /// We categorize expressions into three kinds. The distinction between
4459 /// lvalue/rvalue is fundamental to the language. The distinction between the
4460 /// two kinds of rvalues is an artifact of trans which reflects how we will
4461 /// generate code for that kind of expression. See trans/expr.rs for more
4471 pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
4472 if tcx.method_map.borrow().contains_key(&MethodCall::expr(expr.id)) {
4473 // Overloaded operations are generally calls, and hence they are
4474 // generated via DPS, but there are a few exceptions:
4475 return match expr.node {
4476 // `a += b` has a unit result.
4477 ast::ExprAssignOp(..) => RvalueStmtExpr,
4479 // the deref method invoked for `*a` always yields an `&T`
4480 ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
4482 // the index method invoked for `a[i]` always yields an `&T`
4483 ast::ExprIndex(..) => LvalueExpr,
4485 // `for` loops are statements
4486 ast::ExprForLoop(..) => RvalueStmtExpr,
4488 // in the general case, result could be any type, use DPS
4494 ast::ExprPath(_) | ast::ExprQPath(_) => {
4495 match resolve_expr(tcx, expr) {
4496 def::DefVariant(tid, vid, _) => {
4497 let variant_info = enum_variant_with_id(tcx, tid, vid);
4498 if variant_info.args.len() > 0u {
4507 def::DefStruct(_) => {
4508 match tcx.node_types.borrow().get(&expr.id) {
4509 Some(ty) => match ty.sty {
4510 ty_bare_fn(..) => RvalueDatumExpr,
4513 // See ExprCast below for why types might be missing.
4514 None => RvalueDatumExpr
4518 // Special case: A unit like struct's constructor must be called without () at the
4519 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
4520 // of unit structs this is should not be interpreted as function pointer but as
4521 // call to the constructor.
4522 def::DefFn(_, true) => RvalueDpsExpr,
4524 // Fn pointers are just scalar values.
4525 def::DefFn(..) | def::DefStaticMethod(..) | def::DefMethod(..) => RvalueDatumExpr,
4527 // Note: there is actually a good case to be made that
4528 // DefArg's, particularly those of immediate type, ought to
4529 // considered rvalues.
4530 def::DefStatic(..) |
4532 def::DefLocal(..) => LvalueExpr,
4534 def::DefConst(..) => RvalueDatumExpr,
4539 &format!("uncategorized def for expr {}: {:?}",
4546 ast::ExprUnary(ast::UnDeref, _) |
4547 ast::ExprField(..) |
4548 ast::ExprTupField(..) |
4549 ast::ExprIndex(..) => {
4554 ast::ExprMethodCall(..) |
4555 ast::ExprStruct(..) |
4556 ast::ExprRange(..) |
4559 ast::ExprMatch(..) |
4560 ast::ExprClosure(..) |
4561 ast::ExprBlock(..) |
4562 ast::ExprRepeat(..) |
4563 ast::ExprVec(..) => {
4567 ast::ExprIfLet(..) => {
4568 tcx.sess.span_bug(expr.span, "non-desugared ExprIfLet");
4570 ast::ExprWhileLet(..) => {
4571 tcx.sess.span_bug(expr.span, "non-desugared ExprWhileLet");
4574 ast::ExprLit(ref lit) if lit_is_str(&**lit) => {
4578 ast::ExprCast(..) => {
4579 match tcx.node_types.borrow().get(&expr.id) {
4581 if type_is_trait(ty) {
4588 // Technically, it should not happen that the expr is not
4589 // present within the table. However, it DOES happen
4590 // during type check, because the final types from the
4591 // expressions are not yet recorded in the tcx. At that
4592 // time, though, we are only interested in knowing lvalue
4593 // vs rvalue. It would be better to base this decision on
4594 // the AST type in cast node---but (at the time of this
4595 // writing) it's not easy to distinguish casts to traits
4596 // from other casts based on the AST. This should be
4597 // easier in the future, when casts to traits
4598 // would like @Foo, Box<Foo>, or &Foo.
4604 ast::ExprBreak(..) |
4605 ast::ExprAgain(..) |
4607 ast::ExprWhile(..) |
4609 ast::ExprAssign(..) |
4610 ast::ExprInlineAsm(..) |
4611 ast::ExprAssignOp(..) |
4612 ast::ExprForLoop(..) => {
4616 ast::ExprLit(_) | // Note: LitStr is carved out above
4617 ast::ExprUnary(..) |
4618 ast::ExprBox(None, _) |
4619 ast::ExprAddrOf(..) |
4620 ast::ExprBinary(..) => {
4624 ast::ExprBox(Some(ref place), _) => {
4625 // Special case `Box<T>` for now:
4626 let definition = match tcx.def_map.borrow().get(&place.id) {
4628 None => panic!("no def for place"),
4630 let def_id = definition.def_id();
4631 if tcx.lang_items.exchange_heap() == Some(def_id) {
4638 ast::ExprParen(ref e) => expr_kind(tcx, &**e),
4640 ast::ExprMac(..) => {
4643 "macro expression remains after expansion");
4648 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
4650 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
4653 ast::StmtMac(..) => panic!("unexpanded macro in trans")
4657 pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
4660 for f in fields.iter() { if f.name == name { return i; } i += 1u; }
4661 tcx.sess.bug(&format!(
4662 "no field named `{}` found in the list of fields `{:?}`",
4663 token::get_name(name),
4665 .map(|f| token::get_name(f.name).get().to_string())
4666 .collect::<Vec<String>>())[]);
4669 pub fn impl_or_trait_item_idx(id: ast::Name, trait_items: &[ImplOrTraitItem])
4671 trait_items.iter().position(|m| m.name() == id)
4674 pub fn ty_sort_string<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> String {
4676 ty_bool | ty_char | ty_int(_) |
4677 ty_uint(_) | ty_float(_) | ty_str => {
4678 ::util::ppaux::ty_to_string(cx, ty)
4680 ty_tup(ref tys) if tys.is_empty() => ::util::ppaux::ty_to_string(cx, ty),
4682 ty_enum(id, _) => format!("enum `{}`", item_path_str(cx, id)),
4683 ty_uniq(_) => "box".to_string(),
4684 ty_vec(_, Some(n)) => format!("array of {} elements", n),
4685 ty_vec(_, None) => "slice".to_string(),
4686 ty_ptr(_) => "*-ptr".to_string(),
4687 ty_rptr(_, _) => "&-ptr".to_string(),
4688 ty_bare_fn(Some(_), _) => format!("fn item"),
4689 ty_bare_fn(None, _) => "fn pointer".to_string(),
4690 ty_trait(ref inner) => {
4691 format!("trait {}", item_path_str(cx, inner.principal_def_id()))
4693 ty_struct(id, _) => {
4694 format!("struct `{}`", item_path_str(cx, id))
4696 ty_unboxed_closure(..) => "closure".to_string(),
4697 ty_tup(_) => "tuple".to_string(),
4698 ty_infer(TyVar(_)) => "inferred type".to_string(),
4699 ty_infer(IntVar(_)) => "integral variable".to_string(),
4700 ty_infer(FloatVar(_)) => "floating-point variable".to_string(),
4701 ty_infer(FreshTy(_)) => "skolemized type".to_string(),
4702 ty_infer(FreshIntTy(_)) => "skolemized integral type".to_string(),
4703 ty_projection(_) => "associated type".to_string(),
4704 ty_param(ref p) => {
4705 if p.space == subst::SelfSpace {
4708 "type parameter".to_string()
4711 ty_err => "type error".to_string(),
4712 ty_open(_) => "opened DST".to_string(),
4716 impl<'tcx> Repr<'tcx> for ty::type_err<'tcx> {
4717 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
4718 ty::type_err_to_str(tcx, self)
4722 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
4723 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
4724 /// afterwards to present additional details, particularly when it comes to lifetime-related
4726 pub fn type_err_to_str<'tcx>(cx: &ctxt<'tcx>, err: &type_err<'tcx>) -> String {
4728 terr_cyclic_ty => "cyclic type of infinite size".to_string(),
4729 terr_mismatch => "types differ".to_string(),
4730 terr_unsafety_mismatch(values) => {
4731 format!("expected {} fn, found {} fn",
4735 terr_abi_mismatch(values) => {
4736 format!("expected {} fn, found {} fn",
4740 terr_onceness_mismatch(values) => {
4741 format!("expected {} fn, found {} fn",
4745 terr_mutability => "values differ in mutability".to_string(),
4746 terr_box_mutability => {
4747 "boxed values differ in mutability".to_string()
4749 terr_vec_mutability => "vectors differ in mutability".to_string(),
4750 terr_ptr_mutability => "pointers differ in mutability".to_string(),
4751 terr_ref_mutability => "references differ in mutability".to_string(),
4752 terr_ty_param_size(values) => {
4753 format!("expected a type with {} type params, \
4754 found one with {} type params",
4758 terr_fixed_array_size(values) => {
4759 format!("expected an array with a fixed size of {} elements, \
4760 found one with {} elements",
4764 terr_tuple_size(values) => {
4765 format!("expected a tuple with {} elements, \
4766 found one with {} elements",
4771 "incorrect number of function parameters".to_string()
4773 terr_regions_does_not_outlive(..) => {
4774 "lifetime mismatch".to_string()
4776 terr_regions_not_same(..) => {
4777 "lifetimes are not the same".to_string()
4779 terr_regions_no_overlap(..) => {
4780 "lifetimes do not intersect".to_string()
4782 terr_regions_insufficiently_polymorphic(br, _) => {
4783 format!("expected bound lifetime parameter {}, \
4784 found concrete lifetime",
4785 bound_region_ptr_to_string(cx, br))
4787 terr_regions_overly_polymorphic(br, _) => {
4788 format!("expected concrete lifetime, \
4789 found bound lifetime parameter {}",
4790 bound_region_ptr_to_string(cx, br))
4792 terr_sorts(values) => {
4793 // A naive approach to making sure that we're not reporting silly errors such as:
4794 // (expected closure, found closure).
4795 let expected_str = ty_sort_string(cx, values.expected);
4796 let found_str = ty_sort_string(cx, values.found);
4797 if expected_str == found_str {
4798 format!("expected {}, found a different {}", expected_str, found_str)
4800 format!("expected {}, found {}", expected_str, found_str)
4803 terr_traits(values) => {
4804 format!("expected trait `{}`, found trait `{}`",
4805 item_path_str(cx, values.expected),
4806 item_path_str(cx, values.found))
4808 terr_builtin_bounds(values) => {
4809 if values.expected.is_empty() {
4810 format!("expected no bounds, found `{}`",
4811 values.found.user_string(cx))
4812 } else if values.found.is_empty() {
4813 format!("expected bounds `{}`, found no bounds",
4814 values.expected.user_string(cx))
4816 format!("expected bounds `{}`, found bounds `{}`",
4817 values.expected.user_string(cx),
4818 values.found.user_string(cx))
4821 terr_integer_as_char => {
4822 "expected an integral type, found `char`".to_string()
4824 terr_int_mismatch(ref values) => {
4825 format!("expected `{:?}`, found `{:?}`",
4829 terr_float_mismatch(ref values) => {
4830 format!("expected `{:?}`, found `{:?}`",
4834 terr_variadic_mismatch(ref values) => {
4835 format!("expected {} fn, found {} function",
4836 if values.expected { "variadic" } else { "non-variadic" },
4837 if values.found { "variadic" } else { "non-variadic" })
4839 terr_convergence_mismatch(ref values) => {
4840 format!("expected {} fn, found {} function",
4841 if values.expected { "converging" } else { "diverging" },
4842 if values.found { "converging" } else { "diverging" })
4844 terr_projection_name_mismatched(ref values) => {
4845 format!("expected {}, found {}",
4846 token::get_name(values.expected),
4847 token::get_name(values.found))
4849 terr_projection_bounds_length(ref values) => {
4850 format!("expected {} associated type bindings, found {}",
4857 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
4859 terr_regions_does_not_outlive(subregion, superregion) => {
4860 note_and_explain_region(cx, "", subregion, "...");
4861 note_and_explain_region(cx, "...does not necessarily outlive ",
4864 terr_regions_not_same(region1, region2) => {
4865 note_and_explain_region(cx, "", region1, "...");
4866 note_and_explain_region(cx, "...is not the same lifetime as ",
4869 terr_regions_no_overlap(region1, region2) => {
4870 note_and_explain_region(cx, "", region1, "...");
4871 note_and_explain_region(cx, "...does not overlap ",
4874 terr_regions_insufficiently_polymorphic(_, conc_region) => {
4875 note_and_explain_region(cx,
4876 "concrete lifetime that was found is ",
4879 terr_regions_overly_polymorphic(_, ty::ReInfer(ty::ReVar(_))) => {
4880 // don't bother to print out the message below for
4881 // inference variables, it's not very illuminating.
4883 terr_regions_overly_polymorphic(_, conc_region) => {
4884 note_and_explain_region(cx,
4885 "expected concrete lifetime is ",
4892 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
4893 cx.provided_method_sources.borrow().get(&id).map(|x| *x)
4896 pub fn provided_trait_methods<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
4897 -> Vec<Rc<Method<'tcx>>> {
4899 match cx.map.find(id.node) {
4900 Some(ast_map::NodeItem(item)) => {
4902 ItemTrait(_, _, _, ref ms) => {
4904 ast_util::split_trait_methods(&ms[]);
4907 match impl_or_trait_item(
4909 ast_util::local_def(m.id)) {
4910 MethodTraitItem(m) => m,
4911 TypeTraitItem(_) => {
4912 cx.sess.bug("provided_trait_methods(): \
4913 split_trait_methods() put \
4914 associated types in the \
4915 provided method bucket?!")
4921 cx.sess.bug(&format!("provided_trait_methods: `{:?}` is \
4928 cx.sess.bug(&format!("provided_trait_methods: `{:?}` is not a \
4934 csearch::get_provided_trait_methods(cx, id)
4938 /// Helper for looking things up in the various maps that are populated during
4939 /// typeck::collect (e.g., `cx.impl_or_trait_items`, `cx.tcache`, etc). All of
4940 /// these share the pattern that if the id is local, it should have been loaded
4941 /// into the map by the `typeck::collect` phase. If the def-id is external,
4942 /// then we have to go consult the crate loading code (and cache the result for
4944 fn lookup_locally_or_in_crate_store<V, F>(descr: &str,
4946 map: &mut DefIdMap<V>,
4947 load_external: F) -> V where
4951 match map.get(&def_id).cloned() {
4952 Some(v) => { return v; }
4956 if def_id.krate == ast::LOCAL_CRATE {
4957 panic!("No def'n found for {:?} in tcx.{}", def_id, descr);
4959 let v = load_external();
4960 map.insert(def_id, v.clone());
4964 pub fn trait_item<'tcx>(cx: &ctxt<'tcx>, trait_did: ast::DefId, idx: uint)
4965 -> ImplOrTraitItem<'tcx> {
4966 let method_def_id = (*ty::trait_item_def_ids(cx, trait_did))[idx].def_id();
4967 impl_or_trait_item(cx, method_def_id)
4970 pub fn trait_items<'tcx>(cx: &ctxt<'tcx>, trait_did: ast::DefId)
4971 -> Rc<Vec<ImplOrTraitItem<'tcx>>> {
4972 let mut trait_items = cx.trait_items_cache.borrow_mut();
4973 match trait_items.get(&trait_did).cloned() {
4974 Some(trait_items) => trait_items,
4976 let def_ids = ty::trait_item_def_ids(cx, trait_did);
4977 let items: Rc<Vec<ImplOrTraitItem>> =
4978 Rc::new(def_ids.iter()
4979 .map(|d| impl_or_trait_item(cx, d.def_id()))
4981 trait_items.insert(trait_did, items.clone());
4987 pub fn trait_impl_polarity<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
4988 -> Option<ast::ImplPolarity> {
4989 if id.krate == ast::LOCAL_CRATE {
4990 match cx.map.find(id.node) {
4991 Some(ast_map::NodeItem(item)) => {
4993 ast::ItemImpl(_, polarity, _, _, _, _) => Some(polarity),
5000 csearch::get_impl_polarity(cx, id)
5004 pub fn impl_or_trait_item<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5005 -> ImplOrTraitItem<'tcx> {
5006 lookup_locally_or_in_crate_store("impl_or_trait_items",
5008 &mut *cx.impl_or_trait_items
5011 csearch::get_impl_or_trait_item(cx, id)
5015 /// Returns true if the given ID refers to an associated type and false if it
5016 /// refers to anything else.
5017 pub fn is_associated_type(cx: &ctxt, id: ast::DefId) -> bool {
5018 memoized(&cx.associated_types, id, |id: ast::DefId| {
5019 if id.krate == ast::LOCAL_CRATE {
5020 match cx.impl_or_trait_items.borrow().get(&id) {
5023 TypeTraitItem(_) => true,
5024 MethodTraitItem(_) => false,
5030 csearch::is_associated_type(&cx.sess.cstore, id)
5035 /// Returns the parameter index that the given associated type corresponds to.
5036 pub fn associated_type_parameter_index(cx: &ctxt,
5037 trait_def: &TraitDef,
5038 associated_type_id: ast::DefId)
5040 for type_parameter_def in trait_def.generics.types.iter() {
5041 if type_parameter_def.def_id == associated_type_id {
5042 return type_parameter_def.index as uint
5045 cx.sess.bug("couldn't find associated type parameter index")
5048 pub fn trait_item_def_ids(cx: &ctxt, id: ast::DefId)
5049 -> Rc<Vec<ImplOrTraitItemId>> {
5050 lookup_locally_or_in_crate_store("trait_item_def_ids",
5052 &mut *cx.trait_item_def_ids.borrow_mut(),
5054 Rc::new(csearch::get_trait_item_def_ids(&cx.sess.cstore, id))
5058 pub fn impl_trait_ref<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5059 -> Option<Rc<TraitRef<'tcx>>> {
5060 memoized(&cx.impl_trait_cache, id, |id: ast::DefId| {
5061 if id.krate == ast::LOCAL_CRATE {
5062 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
5063 match cx.map.find(id.node) {
5064 Some(ast_map::NodeItem(item)) => {
5066 ast::ItemImpl(_, _, _, ref opt_trait, _, _) => {
5069 let trait_ref = ty::node_id_to_trait_ref(cx, t.ref_id);
5081 csearch::get_impl_trait(cx, id)
5086 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
5087 let def = *tcx.def_map.borrow()
5089 .expect("no def-map entry for trait");
5093 pub fn try_add_builtin_trait(
5095 trait_def_id: ast::DefId,
5096 builtin_bounds: &mut EnumSet<BuiltinBound>)
5099 //! Checks whether `trait_ref` refers to one of the builtin
5100 //! traits, like `Send`, and adds the corresponding
5101 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
5102 //! is a builtin trait.
5104 match tcx.lang_items.to_builtin_kind(trait_def_id) {
5105 Some(bound) => { builtin_bounds.insert(bound); true }
5110 pub fn ty_to_def_id(ty: Ty) -> Option<ast::DefId> {
5113 Some(tt.principal_def_id()),
5116 ty_unboxed_closure(id, _, _) =>
5125 pub struct VariantInfo<'tcx> {
5126 pub args: Vec<Ty<'tcx>>,
5127 pub arg_names: Option<Vec<ast::Ident>>,
5128 pub ctor_ty: Option<Ty<'tcx>>,
5129 pub name: ast::Name,
5135 impl<'tcx> VariantInfo<'tcx> {
5137 /// Creates a new VariantInfo from the corresponding ast representation.
5139 /// Does not do any caching of the value in the type context.
5140 pub fn from_ast_variant(cx: &ctxt<'tcx>,
5141 ast_variant: &ast::Variant,
5142 discriminant: Disr) -> VariantInfo<'tcx> {
5143 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
5145 match ast_variant.node.kind {
5146 ast::TupleVariantKind(ref args) => {
5147 let arg_tys = if args.len() > 0 {
5148 // the regions in the argument types come from the
5149 // enum def'n, and hence will all be early bound
5150 ty::assert_no_late_bound_regions(cx, &ty_fn_args(ctor_ty))
5155 return VariantInfo {
5158 ctor_ty: Some(ctor_ty),
5159 name: ast_variant.node.name.name,
5160 id: ast_util::local_def(ast_variant.node.id),
5161 disr_val: discriminant,
5162 vis: ast_variant.node.vis
5165 ast::StructVariantKind(ref struct_def) => {
5166 let fields: &[StructField] = &struct_def.fields[];
5168 assert!(fields.len() > 0);
5170 let arg_tys = struct_def.fields.iter()
5171 .map(|field| node_id_to_type(cx, field.node.id)).collect();
5172 let arg_names = fields.iter().map(|field| {
5173 match field.node.kind {
5174 NamedField(ident, _) => ident,
5175 UnnamedField(..) => cx.sess.bug(
5176 "enum_variants: all fields in struct must have a name")
5180 return VariantInfo {
5182 arg_names: Some(arg_names),
5184 name: ast_variant.node.name.name,
5185 id: ast_util::local_def(ast_variant.node.id),
5186 disr_val: discriminant,
5187 vis: ast_variant.node.vis
5194 pub fn substd_enum_variants<'tcx>(cx: &ctxt<'tcx>,
5196 substs: &Substs<'tcx>)
5197 -> Vec<Rc<VariantInfo<'tcx>>> {
5198 enum_variants(cx, id).iter().map(|variant_info| {
5199 let substd_args = variant_info.args.iter()
5200 .map(|aty| aty.subst(cx, substs)).collect::<Vec<_>>();
5202 let substd_ctor_ty = variant_info.ctor_ty.subst(cx, substs);
5204 Rc::new(VariantInfo {
5206 ctor_ty: substd_ctor_ty,
5207 ..(**variant_info).clone()
5212 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
5213 with_path(cx, id, |path| ast_map::path_to_string(path)).to_string()
5219 TraitDtor(DefId, bool)
5223 pub fn is_present(&self) -> bool {
5225 TraitDtor(..) => true,
5230 pub fn has_drop_flag(&self) -> bool {
5233 &TraitDtor(_, flag) => flag
5238 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
5239 Otherwise return none. */
5240 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
5241 match cx.destructor_for_type.borrow().get(&struct_id) {
5242 Some(&method_def_id) => {
5243 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
5245 TraitDtor(method_def_id, flag)
5251 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
5252 cx.destructor_for_type.borrow().contains_key(&struct_id)
5255 pub fn with_path<T, F>(cx: &ctxt, id: ast::DefId, f: F) -> T where
5256 F: FnOnce(ast_map::PathElems) -> T,
5258 if id.krate == ast::LOCAL_CRATE {
5259 cx.map.with_path(id.node, f)
5261 f(ast_map::Values(csearch::get_item_path(cx, id).iter()).chain(None))
5265 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
5266 enum_variants(cx, id).len() == 1
5269 pub fn type_is_empty(cx: &ctxt, ty: Ty) -> bool {
5271 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
5276 pub fn enum_variants<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5277 -> Rc<Vec<Rc<VariantInfo<'tcx>>>> {
5278 memoized(&cx.enum_var_cache, id, |id: ast::DefId| {
5279 if ast::LOCAL_CRATE != id.krate {
5280 Rc::new(csearch::get_enum_variants(cx, id))
5283 Although both this code and check_enum_variants in typeck/check
5284 call eval_const_expr, it should never get called twice for the same
5285 expr, since check_enum_variants also updates the enum_var_cache
5287 match cx.map.get(id.node) {
5288 ast_map::NodeItem(ref item) => {
5290 ast::ItemEnum(ref enum_definition, _) => {
5291 let mut last_discriminant: Option<Disr> = None;
5292 Rc::new(enum_definition.variants.iter().map(|variant| {
5294 let mut discriminant = match last_discriminant {
5295 Some(val) => val + 1,
5296 None => INITIAL_DISCRIMINANT_VALUE
5299 match variant.node.disr_expr {
5301 match const_eval::eval_const_expr_partial(cx, &**e) {
5302 Ok(const_eval::const_int(val)) => {
5303 discriminant = val as Disr
5305 Ok(const_eval::const_uint(val)) => {
5306 discriminant = val as Disr
5309 span_err!(cx.sess, e.span, E0304,
5310 "expected signed integer constant");
5313 span_err!(cx.sess, e.span, E0305,
5314 "expected constant: {}",
5321 last_discriminant = Some(discriminant);
5322 Rc::new(VariantInfo::from_ast_variant(cx, &**variant,
5327 cx.sess.bug("enum_variants: id not bound to an enum")
5331 _ => cx.sess.bug("enum_variants: id not bound to an enum")
5337 // Returns information about the enum variant with the given ID:
5338 pub fn enum_variant_with_id<'tcx>(cx: &ctxt<'tcx>,
5339 enum_id: ast::DefId,
5340 variant_id: ast::DefId)
5341 -> Rc<VariantInfo<'tcx>> {
5342 enum_variants(cx, enum_id).iter()
5343 .find(|variant| variant.id == variant_id)
5344 .expect("enum_variant_with_id(): no variant exists with that ID")
5349 // If the given item is in an external crate, looks up its type and adds it to
5350 // the type cache. Returns the type parameters and type.
5351 pub fn lookup_item_type<'tcx>(cx: &ctxt<'tcx>,
5353 -> TypeScheme<'tcx> {
5354 lookup_locally_or_in_crate_store(
5355 "tcache", did, &mut *cx.tcache.borrow_mut(),
5356 || csearch::get_type(cx, did))
5359 /// Given the did of a trait, returns its canonical trait ref.
5360 pub fn lookup_trait_def<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId)
5361 -> Rc<ty::TraitDef<'tcx>> {
5362 memoized(&cx.trait_defs, did, |did: DefId| {
5363 assert!(did.krate != ast::LOCAL_CRATE);
5364 Rc::new(csearch::get_trait_def(cx, did))
5368 /// Given a reference to a trait, returns the "superbounds" declared
5369 /// on the trait, with appropriate substitutions applied. Basically,
5370 /// this applies a filter to the where clauses on the trait, returning
5371 /// those that have the form:
5373 /// Self : SuperTrait<...>
5375 pub fn predicates_for_trait_ref<'tcx>(tcx: &ctxt<'tcx>,
5376 trait_ref: &PolyTraitRef<'tcx>)
5377 -> Vec<ty::Predicate<'tcx>>
5379 let trait_def = lookup_trait_def(tcx, trait_ref.def_id());
5381 debug!("bounds_for_trait_ref(trait_def={:?}, trait_ref={:?})",
5382 trait_def.repr(tcx), trait_ref.repr(tcx));
5384 // The interaction between HRTB and supertraits is not entirely
5385 // obvious. Let me walk you (and myself) through an example.
5387 // Let's start with an easy case. Consider two traits:
5389 // trait Foo<'a> : Bar<'a,'a> { }
5390 // trait Bar<'b,'c> { }
5392 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
5393 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
5394 // knew that `Foo<'x>` (for any 'x) then we also know that
5395 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
5396 // normal substitution.
5398 // In terms of why this is sound, the idea is that whenever there
5399 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
5400 // holds. So if there is an impl of `T:Foo<'a>` that applies to
5401 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
5404 // Another example to be careful of is this:
5406 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
5407 // trait Bar1<'b,'c> { }
5409 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
5410 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
5411 // reason is similar to the previous example: any impl of
5412 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
5413 // basically we would want to collapse the bound lifetimes from
5414 // the input (`trait_ref`) and the supertraits.
5416 // To achieve this in practice is fairly straightforward. Let's
5417 // consider the more complicated scenario:
5419 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
5420 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
5421 // where both `'x` and `'b` would have a DB index of 1.
5422 // The substitution from the input trait-ref is therefore going to be
5423 // `'a => 'x` (where `'x` has a DB index of 1).
5424 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
5425 // early-bound parameter and `'b' is a late-bound parameter with a
5427 // - If we replace `'a` with `'x` from the input, it too will have
5428 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
5429 // just as we wanted.
5431 // There is only one catch. If we just apply the substitution `'a
5432 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
5433 // adjust the DB index because we substituting into a binder (it
5434 // tries to be so smart...) resulting in `for<'x> for<'b>
5435 // Bar1<'x,'b>` (we have no syntax for this, so use your
5436 // imagination). Basically the 'x will have DB index of 2 and 'b
5437 // will have DB index of 1. Not quite what we want. So we apply
5438 // the substitution to the *contents* of the trait reference,
5439 // rather than the trait reference itself (put another way, the
5440 // substitution code expects equal binding levels in the values
5441 // from the substitution and the value being substituted into, and
5442 // this trick achieves that).
5444 // Carefully avoid the binder introduced by each trait-ref by
5445 // substituting over the substs, not the trait-refs themselves,
5446 // thus achieving the "collapse" described in the big comment
5448 let trait_bounds: Vec<_> =
5449 trait_def.bounds.trait_bounds
5451 .map(|poly_trait_ref| ty::Binder(poly_trait_ref.0.subst(tcx, trait_ref.substs())))
5454 let projection_bounds: Vec<_> =
5455 trait_def.bounds.projection_bounds
5457 .map(|poly_proj| ty::Binder(poly_proj.0.subst(tcx, trait_ref.substs())))
5460 debug!("bounds_for_trait_ref: trait_bounds={} projection_bounds={}",
5461 trait_bounds.repr(tcx),
5462 projection_bounds.repr(tcx));
5464 // The region bounds and builtin bounds do not currently introduce
5465 // binders so we can just substitute in a straightforward way here.
5467 trait_def.bounds.region_bounds.subst(tcx, trait_ref.substs());
5468 let builtin_bounds =
5469 trait_def.bounds.builtin_bounds.subst(tcx, trait_ref.substs());
5471 let bounds = ty::ParamBounds {
5472 trait_bounds: trait_bounds,
5473 region_bounds: region_bounds,
5474 builtin_bounds: builtin_bounds,
5475 projection_bounds: projection_bounds,
5478 predicates(tcx, trait_ref.self_ty(), &bounds)
5481 pub fn predicates<'tcx>(
5484 bounds: &ParamBounds<'tcx>)
5485 -> Vec<Predicate<'tcx>>
5487 let mut vec = Vec::new();
5489 for builtin_bound in bounds.builtin_bounds.iter() {
5490 match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty) {
5491 Ok(trait_ref) => { vec.push(trait_ref.as_predicate()); }
5492 Err(ErrorReported) => { }
5496 for ®ion_bound in bounds.region_bounds.iter() {
5497 // account for the binder being introduced below; no need to shift `param_ty`
5498 // because, at present at least, it can only refer to early-bound regions
5499 let region_bound = ty_fold::shift_region(region_bound, 1);
5500 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).as_predicate());
5503 for bound_trait_ref in bounds.trait_bounds.iter() {
5504 vec.push(bound_trait_ref.as_predicate());
5507 for projection in bounds.projection_bounds.iter() {
5508 vec.push(projection.as_predicate());
5514 /// Get the attributes of a definition.
5515 pub fn get_attrs<'tcx>(tcx: &'tcx ctxt, did: DefId)
5516 -> CowVec<'tcx, ast::Attribute> {
5518 let item = tcx.map.expect_item(did.node);
5519 Cow::Borrowed(&item.attrs[])
5521 Cow::Owned(csearch::get_item_attrs(&tcx.sess.cstore, did))
5525 /// Determine whether an item is annotated with an attribute
5526 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
5527 get_attrs(tcx, did).iter().any(|item| item.check_name(attr))
5530 /// Determine whether an item is annotated with `#[repr(packed)]`
5531 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
5532 lookup_repr_hints(tcx, did).contains(&attr::ReprPacked)
5535 /// Determine whether an item is annotated with `#[simd]`
5536 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
5537 has_attr(tcx, did, "simd")
5540 /// Obtain the representation annotation for a struct definition.
5541 pub fn lookup_repr_hints(tcx: &ctxt, did: DefId) -> Rc<Vec<attr::ReprAttr>> {
5542 memoized(&tcx.repr_hint_cache, did, |did: DefId| {
5543 Rc::new(if did.krate == LOCAL_CRATE {
5544 get_attrs(tcx, did).iter().flat_map(|meta| {
5545 attr::find_repr_attrs(tcx.sess.diagnostic(), meta).into_iter()
5548 csearch::get_repr_attrs(&tcx.sess.cstore, did)
5553 // Look up a field ID, whether or not it's local
5554 // Takes a list of type substs in case the struct is generic
5555 pub fn lookup_field_type<'tcx>(tcx: &ctxt<'tcx>,
5558 substs: &Substs<'tcx>)
5560 let ty = if id.krate == ast::LOCAL_CRATE {
5561 node_id_to_type(tcx, id.node)
5563 let mut tcache = tcx.tcache.borrow_mut();
5564 let pty = tcache.entry(id).get().unwrap_or_else(
5565 |vacant_entry| vacant_entry.insert(csearch::get_field_type(tcx, struct_id, id)));
5568 ty.subst(tcx, substs)
5571 // Look up the list of field names and IDs for a given struct.
5572 // Panics if the id is not bound to a struct.
5573 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
5574 if did.krate == ast::LOCAL_CRATE {
5575 let struct_fields = cx.struct_fields.borrow();
5576 match struct_fields.get(&did) {
5577 Some(fields) => (**fields).clone(),
5580 &format!("ID not mapped to struct fields: {}",
5581 cx.map.node_to_string(did.node))[]);
5585 csearch::get_struct_fields(&cx.sess.cstore, did)
5589 pub fn is_tuple_struct(cx: &ctxt, did: ast::DefId) -> bool {
5590 let fields = lookup_struct_fields(cx, did);
5591 !fields.is_empty() && fields.iter().all(|f| f.name == token::special_names::unnamed_field)
5594 // Returns a list of fields corresponding to the struct's items. trans uses
5595 // this. Takes a list of substs with which to instantiate field types.
5596 pub fn struct_fields<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId, substs: &Substs<'tcx>)
5597 -> Vec<field<'tcx>> {
5598 lookup_struct_fields(cx, did).iter().map(|f| {
5602 ty: lookup_field_type(cx, did, f.id, substs),
5609 // Returns a list of fields corresponding to the tuple's items. trans uses
5611 pub fn tup_fields<'tcx>(v: &[Ty<'tcx>]) -> Vec<field<'tcx>> {
5612 v.iter().enumerate().map(|(i, &f)| {
5614 name: token::intern(&i.to_string()[]),
5623 #[derive(Copy, Clone)]
5624 pub struct UnboxedClosureUpvar<'tcx> {
5630 // Returns a list of `UnboxedClosureUpvar`s for each upvar.
5631 pub fn unboxed_closure_upvars<'tcx>(typer: &mc::Typer<'tcx>,
5632 closure_id: ast::DefId,
5633 substs: &Substs<'tcx>)
5634 -> Option<Vec<UnboxedClosureUpvar<'tcx>>>
5636 // Presently an unboxed closure type cannot "escape" out of a
5637 // function, so we will only encounter ones that originated in the
5638 // local crate or were inlined into it along with some function.
5639 // This may change if abstract return types of some sort are
5641 assert!(closure_id.krate == ast::LOCAL_CRATE);
5642 let tcx = typer.tcx();
5643 let capture_mode = tcx.capture_modes.borrow()[closure_id.node].clone();
5644 match tcx.freevars.borrow().get(&closure_id.node) {
5645 None => Some(vec![]),
5646 Some(ref freevars) => {
5649 let freevar_def_id = freevar.def.def_id();
5650 let freevar_ty = match typer.node_ty(freevar_def_id.node) {
5652 Err(()) => { return None; }
5654 let freevar_ty = freevar_ty.subst(tcx, substs);
5656 match capture_mode {
5657 ast::CaptureByValue => {
5658 Some(UnboxedClosureUpvar { def: freevar.def,
5663 ast::CaptureByRef => {
5664 let upvar_id = ty::UpvarId {
5665 var_id: freevar_def_id.node,
5666 closure_expr_id: closure_id.node
5670 let freevar_ref_ty = match typer.upvar_borrow(upvar_id) {
5673 tcx.mk_region(borrow.region),
5676 mutbl: borrow.kind.to_mutbl_lossy(),
5680 // FIXME(#16640) we should really return None here;
5681 // but that requires better inference integration,
5682 // for now gin up something.
5686 Some(UnboxedClosureUpvar {
5699 pub fn is_binopable<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>, op: ast::BinOp) -> bool {
5700 #![allow(non_upper_case_globals)]
5701 static tycat_other: int = 0;
5702 static tycat_bool: int = 1;
5703 static tycat_char: int = 2;
5704 static tycat_int: int = 3;
5705 static tycat_float: int = 4;
5706 static tycat_raw_ptr: int = 6;
5708 static opcat_add: int = 0;
5709 static opcat_sub: int = 1;
5710 static opcat_mult: int = 2;
5711 static opcat_shift: int = 3;
5712 static opcat_rel: int = 4;
5713 static opcat_eq: int = 5;
5714 static opcat_bit: int = 6;
5715 static opcat_logic: int = 7;
5716 static opcat_mod: int = 8;
5718 fn opcat(op: ast::BinOp) -> int {
5720 ast::BiAdd => opcat_add,
5721 ast::BiSub => opcat_sub,
5722 ast::BiMul => opcat_mult,
5723 ast::BiDiv => opcat_mult,
5724 ast::BiRem => opcat_mod,
5725 ast::BiAnd => opcat_logic,
5726 ast::BiOr => opcat_logic,
5727 ast::BiBitXor => opcat_bit,
5728 ast::BiBitAnd => opcat_bit,
5729 ast::BiBitOr => opcat_bit,
5730 ast::BiShl => opcat_shift,
5731 ast::BiShr => opcat_shift,
5732 ast::BiEq => opcat_eq,
5733 ast::BiNe => opcat_eq,
5734 ast::BiLt => opcat_rel,
5735 ast::BiLe => opcat_rel,
5736 ast::BiGe => opcat_rel,
5737 ast::BiGt => opcat_rel
5741 fn tycat<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> int {
5742 if type_is_simd(cx, ty) {
5743 return tycat(cx, simd_type(cx, ty))
5746 ty_char => tycat_char,
5747 ty_bool => tycat_bool,
5748 ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
5749 ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
5750 ty_ptr(_) => tycat_raw_ptr,
5755 static t: bool = true;
5756 static f: bool = false;
5759 // +, -, *, shift, rel, ==, bit, logic, mod
5760 /*other*/ [f, f, f, f, f, f, f, f, f],
5761 /*bool*/ [f, f, f, f, t, t, t, t, f],
5762 /*char*/ [f, f, f, f, t, t, f, f, f],
5763 /*int*/ [t, t, t, t, t, t, t, f, t],
5764 /*float*/ [t, t, t, f, t, t, f, f, f],
5765 /*bot*/ [t, t, t, t, t, t, t, t, t],
5766 /*raw ptr*/ [f, f, f, f, t, t, f, f, f]];
5768 return tbl[tycat(cx, ty) as uint ][opcat(op) as uint];
5771 // Returns the repeat count for a repeating vector expression.
5772 pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> uint {
5773 match const_eval::eval_const_expr_partial(tcx, count_expr) {
5775 let found = match val {
5776 const_eval::const_uint(count) => return count as uint,
5777 const_eval::const_int(count) if count >= 0 => return count as uint,
5778 const_eval::const_int(_) =>
5780 const_eval::const_float(_) =>
5782 const_eval::const_str(_) =>
5784 const_eval::const_bool(_) =>
5786 const_eval::const_binary(_) =>
5789 span_err!(tcx.sess, count_expr.span, E0306,
5790 "expected positive integer for repeat count, found {}",
5794 let found = match count_expr.node {
5795 ast::ExprPath(ast::Path {
5799 }) if segments.len() == 1 =>
5802 "non-constant expression"
5804 span_err!(tcx.sess, count_expr.span, E0307,
5805 "expected constant integer for repeat count, found {}",
5812 // Iterate over a type parameter's bounded traits and any supertraits
5813 // of those traits, ignoring kinds.
5814 // Here, the supertraits are the transitive closure of the supertrait
5815 // relation on the supertraits from each bounded trait's constraint
5817 pub fn each_bound_trait_and_supertraits<'tcx, F>(tcx: &ctxt<'tcx>,
5818 bounds: &[PolyTraitRef<'tcx>],
5821 F: FnMut(PolyTraitRef<'tcx>) -> bool,
5823 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
5824 if !f(bound_trait_ref) {
5831 pub fn object_region_bounds<'tcx>(
5833 opt_principal: Option<&PolyTraitRef<'tcx>>, // None for closures
5834 others: BuiltinBounds)
5837 // Since we don't actually *know* the self type for an object,
5838 // this "open(err)" serves as a kind of dummy standin -- basically
5839 // a skolemized type.
5840 let open_ty = ty::mk_infer(tcx, FreshTy(0));
5842 let opt_trait_ref = opt_principal.map_or(Vec::new(), |principal| {
5843 // Note that we preserve the overall binding levels here.
5844 assert!(!open_ty.has_escaping_regions());
5845 let substs = tcx.mk_substs(principal.0.substs.with_self_ty(open_ty));
5846 vec!(ty::Binder(Rc::new(ty::TraitRef::new(principal.0.def_id, substs))))
5849 let param_bounds = ty::ParamBounds {
5850 region_bounds: Vec::new(),
5851 builtin_bounds: others,
5852 trait_bounds: opt_trait_ref,
5853 projection_bounds: Vec::new(), // not relevant to computing region bounds
5856 let predicates = ty::predicates(tcx, open_ty, ¶m_bounds);
5857 ty::required_region_bounds(tcx, open_ty, predicates)
5860 /// Given a set of predicates that apply to an object type, returns
5861 /// the region bounds that the (erased) `Self` type must
5862 /// outlive. Precisely *because* the `Self` type is erased, the
5863 /// parameter `erased_self_ty` must be supplied to indicate what type
5864 /// has been used to represent `Self` in the predicates
5865 /// themselves. This should really be a unique type; `FreshTy(0)` is a
5866 /// popular choice (see `object_region_bounds` above).
5868 /// Requires that trait definitions have been processed so that we can
5869 /// elaborate predicates and walk supertraits.
5870 pub fn required_region_bounds<'tcx>(tcx: &ctxt<'tcx>,
5871 erased_self_ty: Ty<'tcx>,
5872 predicates: Vec<ty::Predicate<'tcx>>)
5875 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
5876 erased_self_ty.repr(tcx),
5877 predicates.repr(tcx));
5879 assert!(!erased_self_ty.has_escaping_regions());
5881 traits::elaborate_predicates(tcx, predicates)
5882 .filter_map(|predicate| {
5884 ty::Predicate::Projection(..) |
5885 ty::Predicate::Trait(..) |
5886 ty::Predicate::Equate(..) |
5887 ty::Predicate::RegionOutlives(..) => {
5890 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
5891 // Search for a bound of the form `erased_self_ty
5892 // : 'a`, but be wary of something like `for<'a>
5893 // erased_self_ty : 'a` (we interpret a
5894 // higher-ranked bound like that as 'static,
5895 // though at present the code in `fulfill.rs`
5896 // considers such bounds to be unsatisfiable, so
5897 // it's kind of a moot point since you could never
5898 // construct such an object, but this seems
5899 // correct even if that code changes).
5900 if t == erased_self_ty && !r.has_escaping_regions() {
5901 if r.has_escaping_regions() {
5915 pub fn get_tydesc_ty<'tcx>(tcx: &ctxt<'tcx>) -> Result<Ty<'tcx>, String> {
5916 tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
5917 tcx.intrinsic_defs.borrow().get(&tydesc_lang_item).cloned()
5918 .expect("Failed to resolve TyDesc")
5922 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> Rc<ItemVariances> {
5923 lookup_locally_or_in_crate_store(
5924 "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
5925 || Rc::new(csearch::get_item_variances(&tcx.sess.cstore, item_id)))
5928 /// Records a trait-to-implementation mapping.
5929 pub fn record_trait_implementation(tcx: &ctxt,
5930 trait_def_id: DefId,
5931 impl_def_id: DefId) {
5933 match tcx.trait_impls.borrow().get(&trait_def_id) {
5934 Some(impls_for_trait) => {
5935 impls_for_trait.borrow_mut().push(impl_def_id);
5941 tcx.trait_impls.borrow_mut().insert(trait_def_id, Rc::new(RefCell::new(vec!(impl_def_id))));
5944 /// Populates the type context with all the implementations for the given type
5946 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
5947 type_id: ast::DefId) {
5948 if type_id.krate == LOCAL_CRATE {
5951 if tcx.populated_external_types.borrow().contains(&type_id) {
5955 debug!("populate_implementations_for_type_if_necessary: searching for {:?}", type_id);
5957 let mut inherent_impls = Vec::new();
5958 csearch::each_implementation_for_type(&tcx.sess.cstore, type_id,
5960 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, impl_def_id);
5962 // Record the trait->implementation mappings, if applicable.
5963 let associated_traits = csearch::get_impl_trait(tcx, impl_def_id);
5964 for trait_ref in associated_traits.iter() {
5965 record_trait_implementation(tcx, trait_ref.def_id, impl_def_id);
5968 // For any methods that use a default implementation, add them to
5969 // the map. This is a bit unfortunate.
5970 for impl_item_def_id in impl_items.iter() {
5971 let method_def_id = impl_item_def_id.def_id();
5972 match impl_or_trait_item(tcx, method_def_id) {
5973 MethodTraitItem(method) => {
5974 for &source in method.provided_source.iter() {
5975 tcx.provided_method_sources
5977 .insert(method_def_id, source);
5980 TypeTraitItem(_) => {}
5984 // Store the implementation info.
5985 tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
5987 // If this is an inherent implementation, record it.
5988 if associated_traits.is_none() {
5989 inherent_impls.push(impl_def_id);
5993 tcx.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
5994 tcx.populated_external_types.borrow_mut().insert(type_id);
5997 /// Populates the type context with all the implementations for the given
5998 /// trait if necessary.
5999 pub fn populate_implementations_for_trait_if_necessary(
6001 trait_id: ast::DefId) {
6002 if trait_id.krate == LOCAL_CRATE {
6005 if tcx.populated_external_traits.borrow().contains(&trait_id) {
6009 csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id,
6010 |implementation_def_id| {
6011 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, implementation_def_id);
6013 // Record the trait->implementation mapping.
6014 record_trait_implementation(tcx, trait_id, implementation_def_id);
6016 // For any methods that use a default implementation, add them to
6017 // the map. This is a bit unfortunate.
6018 for impl_item_def_id in impl_items.iter() {
6019 let method_def_id = impl_item_def_id.def_id();
6020 match impl_or_trait_item(tcx, method_def_id) {
6021 MethodTraitItem(method) => {
6022 for &source in method.provided_source.iter() {
6023 tcx.provided_method_sources
6025 .insert(method_def_id, source);
6028 TypeTraitItem(_) => {}
6032 // Store the implementation info.
6033 tcx.impl_items.borrow_mut().insert(implementation_def_id, impl_items);
6036 tcx.populated_external_traits.borrow_mut().insert(trait_id);
6039 /// Given the def_id of an impl, return the def_id of the trait it implements.
6040 /// If it implements no trait, return `None`.
6041 pub fn trait_id_of_impl(tcx: &ctxt,
6043 -> Option<ast::DefId> {
6044 ty::impl_trait_ref(tcx, def_id).map(|tr| tr.def_id)
6047 /// If the given def ID describes a method belonging to an impl, return the
6048 /// ID of the impl that the method belongs to. Otherwise, return `None`.
6049 pub fn impl_of_method(tcx: &ctxt, def_id: ast::DefId)
6050 -> Option<ast::DefId> {
6051 if def_id.krate != LOCAL_CRATE {
6052 return match csearch::get_impl_or_trait_item(tcx,
6053 def_id).container() {
6054 TraitContainer(_) => None,
6055 ImplContainer(def_id) => Some(def_id),
6058 match tcx.impl_or_trait_items.borrow().get(&def_id).cloned() {
6059 Some(trait_item) => {
6060 match trait_item.container() {
6061 TraitContainer(_) => None,
6062 ImplContainer(def_id) => Some(def_id),
6069 /// If the given def ID describes an item belonging to a trait (either a
6070 /// default method or an implementation of a trait method), return the ID of
6071 /// the trait that the method belongs to. Otherwise, return `None`.
6072 pub fn trait_of_item(tcx: &ctxt, def_id: ast::DefId) -> Option<ast::DefId> {
6073 if def_id.krate != LOCAL_CRATE {
6074 return csearch::get_trait_of_item(&tcx.sess.cstore, def_id, tcx);
6076 match tcx.impl_or_trait_items.borrow().get(&def_id).cloned() {
6077 Some(impl_or_trait_item) => {
6078 match impl_or_trait_item.container() {
6079 TraitContainer(def_id) => Some(def_id),
6080 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
6087 /// If the given def ID describes an item belonging to a trait, (either a
6088 /// default method or an implementation of a trait method), return the ID of
6089 /// the method inside trait definition (this means that if the given def ID
6090 /// is already that of the original trait method, then the return value is
6092 /// Otherwise, return `None`.
6093 pub fn trait_item_of_item(tcx: &ctxt, def_id: ast::DefId)
6094 -> Option<ImplOrTraitItemId> {
6095 let impl_item = match tcx.impl_or_trait_items.borrow().get(&def_id) {
6096 Some(m) => m.clone(),
6097 None => return None,
6099 let name = impl_item.name();
6100 match trait_of_item(tcx, def_id) {
6101 Some(trait_did) => {
6102 let trait_items = ty::trait_items(tcx, trait_did);
6104 .position(|m| m.name() == name)
6105 .map(|idx| ty::trait_item(tcx, trait_did, idx).id())
6111 /// Creates a hash of the type `Ty` which will be the same no matter what crate
6112 /// context it's calculated within. This is used by the `type_id` intrinsic.
6113 pub fn hash_crate_independent<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh) -> u64 {
6114 let mut state = SipHasher::new();
6115 helper(tcx, ty, svh, &mut state);
6116 return state.finish();
6118 fn helper<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh,
6119 state: &mut SipHasher) {
6120 macro_rules! byte { ($b:expr) => { ($b as u8).hash(state) } }
6121 macro_rules! hash { ($e:expr) => { $e.hash(state) } }
6123 let region = |&: state: &mut SipHasher, r: Region| {
6126 ReLateBound(db, BrAnon(i)) => {
6136 tcx.sess.bug("unexpected region found when hashing a type")
6140 let did = |&: state: &mut SipHasher, did: DefId| {
6141 let h = if ast_util::is_local(did) {
6144 tcx.sess.cstore.get_crate_hash(did.krate)
6146 h.as_str().hash(state);
6147 did.node.hash(state);
6149 let mt = |&: state: &mut SipHasher, mt: mt| {
6150 mt.mutbl.hash(state);
6152 let fn_sig = |&: state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| {
6153 let sig = anonymize_late_bound_regions(tcx, sig).0;
6154 for a in sig.inputs.iter() { helper(tcx, *a, svh, state); }
6155 if let ty::FnConverging(output) = sig.output {
6156 helper(tcx, output, svh, state);
6159 maybe_walk_ty(ty, |ty| {
6161 ty_bool => byte!(2),
6162 ty_char => byte!(3),
6185 ty_vec(_, Some(n)) => {
6189 ty_vec(_, None) => {
6201 ty_bare_fn(opt_def_id, ref b) => {
6206 fn_sig(state, &b.sig);
6209 ty_trait(ref data) => {
6211 did(state, data.principal_def_id());
6214 let principal = anonymize_late_bound_regions(tcx, &data.principal).0;
6215 for subty in principal.substs.types.iter() {
6216 helper(tcx, *subty, svh, state);
6221 ty_struct(d, _) => {
6225 ty_tup(ref inner) => {
6233 hash!(token::get_name(p.name));
6235 ty_open(_) => byte!(22),
6236 ty_infer(_) => unreachable!(),
6237 ty_err => byte!(23),
6238 ty_unboxed_closure(d, r, _) => {
6243 ty_projection(ref data) => {
6245 did(state, data.trait_ref.def_id);
6246 hash!(token::get_name(data.item_name));
6255 pub fn to_string(self) -> &'static str {
6258 Contravariant => "-",
6265 /// Construct a parameter environment suitable for static contexts or other contexts where there
6266 /// are no free type/lifetime parameters in scope.
6267 pub fn empty_parameter_environment<'a,'tcx>(cx: &'a ctxt<'tcx>) -> ParameterEnvironment<'a,'tcx> {
6268 ty::ParameterEnvironment { tcx: cx,
6269 free_substs: Substs::empty(),
6270 caller_bounds: GenericBounds::empty(),
6271 implicit_region_bound: ty::ReEmpty,
6272 selection_cache: traits::SelectionCache::new(), }
6275 /// See `ParameterEnvironment` struct def'n for details
6276 pub fn construct_parameter_environment<'a,'tcx>(
6277 tcx: &'a ctxt<'tcx>,
6278 generics: &ty::Generics<'tcx>,
6279 free_id: ast::NodeId)
6280 -> ParameterEnvironment<'a, 'tcx>
6284 // Construct the free substs.
6288 let mut types = VecPerParamSpace::empty();
6289 push_types_from_defs(tcx, &mut types, generics.types.as_slice());
6291 // map bound 'a => free 'a
6292 let mut regions = VecPerParamSpace::empty();
6293 push_region_params(&mut regions, free_id, generics.regions.as_slice());
6295 let free_substs = Substs {
6297 regions: subst::NonerasedRegions(regions)
6300 let free_id_scope = region::CodeExtent::from_node_id(free_id);
6303 // Compute the bounds on Self and the type parameters.
6306 let bounds = generics.to_bounds(tcx, &free_substs);
6307 let bounds = liberate_late_bound_regions(tcx, free_id_scope, &ty::Binder(bounds));
6310 // Compute region bounds. For now, these relations are stored in a
6311 // global table on the tcx, so just enter them there. I'm not
6312 // crazy about this scheme, but it's convenient, at least.
6315 record_region_bounds(tcx, &bounds);
6317 debug!("construct_parameter_environment: free_id={:?} free_subst={:?} bounds={:?}",
6319 free_substs.repr(tcx),
6322 return ty::ParameterEnvironment {
6324 free_substs: free_substs,
6325 implicit_region_bound: ty::ReScope(free_id_scope),
6326 caller_bounds: bounds,
6327 selection_cache: traits::SelectionCache::new(),
6330 fn push_region_params(regions: &mut VecPerParamSpace<ty::Region>,
6331 free_id: ast::NodeId,
6332 region_params: &[RegionParameterDef])
6334 for r in region_params.iter() {
6335 regions.push(r.space, ty::free_region_from_def(free_id, r));
6339 fn push_types_from_defs<'tcx>(tcx: &ty::ctxt<'tcx>,
6340 types: &mut VecPerParamSpace<Ty<'tcx>>,
6341 defs: &[TypeParameterDef<'tcx>]) {
6342 for def in defs.iter() {
6343 debug!("construct_parameter_environment(): push_types_from_defs: def={:?}",
6345 let ty = ty::mk_param_from_def(tcx, def);
6346 types.push(def.space, ty);
6350 fn record_region_bounds<'tcx>(tcx: &ty::ctxt<'tcx>, bounds: &GenericBounds<'tcx>) {
6351 debug!("record_region_bounds(bounds={:?})", bounds.repr(tcx));
6353 for predicate in bounds.predicates.iter() {
6355 Predicate::Projection(..) |
6356 Predicate::Trait(..) |
6357 Predicate::Equate(..) |
6358 Predicate::TypeOutlives(..) => {
6359 // No region bounds here
6361 Predicate::RegionOutlives(ty::Binder(ty::OutlivesPredicate(r_a, r_b))) => {
6363 (ty::ReFree(fr_a), ty::ReFree(fr_b)) => {
6364 // Record that `'a:'b`. Or, put another way, `'b <= 'a`.
6365 tcx.region_maps.relate_free_regions(fr_b, fr_a);
6368 // All named regions are instantiated with free regions.
6370 format!("record_region_bounds: non free region: {} / {}",
6372 r_b.repr(tcx)).as_slice());
6382 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
6384 ast::MutMutable => MutBorrow,
6385 ast::MutImmutable => ImmBorrow,
6389 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
6390 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
6391 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
6393 pub fn to_mutbl_lossy(self) -> ast::Mutability {
6395 MutBorrow => ast::MutMutable,
6396 ImmBorrow => ast::MutImmutable,
6398 // We have no type corresponding to a unique imm borrow, so
6399 // use `&mut`. It gives all the capabilities of an `&uniq`
6400 // and hence is a safe "over approximation".
6401 UniqueImmBorrow => ast::MutMutable,
6405 pub fn to_user_str(&self) -> &'static str {
6407 MutBorrow => "mutable",
6408 ImmBorrow => "immutable",
6409 UniqueImmBorrow => "uniquely immutable",
6414 impl<'tcx> ctxt<'tcx> {
6415 pub fn capture_mode(&self, closure_expr_id: ast::NodeId)
6416 -> ast::CaptureClause {
6417 self.capture_modes.borrow()[closure_expr_id].clone()
6420 pub fn is_method_call(&self, expr_id: ast::NodeId) -> bool {
6421 self.method_map.borrow().contains_key(&MethodCall::expr(expr_id))
6425 impl<'a,'tcx> mc::Typer<'tcx> for ParameterEnvironment<'a,'tcx> {
6426 fn tcx(&self) -> &ty::ctxt<'tcx> {
6430 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<Ty<'tcx>> {
6431 Ok(ty::node_id_to_type(self.tcx, id))
6434 fn expr_ty_adjusted(&self, expr: &ast::Expr) -> mc::McResult<Ty<'tcx>> {
6435 Ok(ty::expr_ty_adjusted(self.tcx, expr))
6438 fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>> {
6439 self.tcx.method_map.borrow().get(&method_call).map(|method| method.ty)
6442 fn node_method_origin(&self, method_call: ty::MethodCall)
6443 -> Option<ty::MethodOrigin<'tcx>>
6445 self.tcx.method_map.borrow().get(&method_call).map(|method| method.origin.clone())
6448 fn adjustments(&self) -> &RefCell<NodeMap<ty::AutoAdjustment<'tcx>>> {
6449 &self.tcx.adjustments
6452 fn is_method_call(&self, id: ast::NodeId) -> bool {
6453 self.tcx.is_method_call(id)
6456 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent> {
6457 self.tcx.region_maps.temporary_scope(rvalue_id)
6460 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarBorrow> {
6461 Some(self.tcx.upvar_borrow_map.borrow()[upvar_id].clone())
6464 fn capture_mode(&self, closure_expr_id: ast::NodeId)
6465 -> ast::CaptureClause {
6466 self.tcx.capture_mode(closure_expr_id)
6469 fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool {
6470 type_moves_by_default(self, span, ty)
6474 impl<'a,'tcx> UnboxedClosureTyper<'tcx> for ty::ParameterEnvironment<'a,'tcx> {
6475 fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> {
6479 fn unboxed_closure_kind(&self,
6481 -> ty::UnboxedClosureKind
6483 self.tcx.unboxed_closure_kind(def_id)
6486 fn unboxed_closure_type(&self,
6488 substs: &subst::Substs<'tcx>)
6489 -> ty::ClosureTy<'tcx>
6491 self.tcx.unboxed_closure_type(def_id, substs)
6494 fn unboxed_closure_upvars(&self,
6496 substs: &Substs<'tcx>)
6497 -> Option<Vec<UnboxedClosureUpvar<'tcx>>>
6499 unboxed_closure_upvars(self, def_id, substs)
6504 /// The category of explicit self.
6505 #[derive(Clone, Copy, Eq, PartialEq, Show)]
6506 pub enum ExplicitSelfCategory {
6507 StaticExplicitSelfCategory,
6508 ByValueExplicitSelfCategory,
6509 ByReferenceExplicitSelfCategory(Region, ast::Mutability),
6510 ByBoxExplicitSelfCategory,
6513 /// Pushes all the lifetimes in the given type onto the given list. A
6514 /// "lifetime in a type" is a lifetime specified by a reference or a lifetime
6515 /// in a list of type substitutions. This does *not* traverse into nominal
6516 /// types, nor does it resolve fictitious types.
6517 pub fn accumulate_lifetimes_in_type(accumulator: &mut Vec<ty::Region>,
6521 ty_rptr(region, _) => {
6522 accumulator.push(*region)
6524 ty_trait(ref t) => {
6525 accumulator.push_all(t.principal.0.substs.regions().as_slice());
6527 ty_enum(_, substs) |
6528 ty_struct(_, substs) => {
6529 accum_substs(accumulator, substs);
6531 ty_unboxed_closure(_, region, substs) => {
6532 accumulator.push(*region);
6533 accum_substs(accumulator, substs);
6555 fn accum_substs(accumulator: &mut Vec<Region>, substs: &Substs) {
6556 match substs.regions {
6557 subst::ErasedRegions => {}
6558 subst::NonerasedRegions(ref regions) => {
6559 for region in regions.iter() {
6560 accumulator.push(*region)
6567 /// A free variable referred to in a function.
6568 #[derive(Copy, RustcEncodable, RustcDecodable)]
6569 pub struct Freevar {
6570 /// The variable being accessed free.
6573 // First span where it is accessed (there can be multiple).
6577 pub type FreevarMap = NodeMap<Vec<Freevar>>;
6579 pub type CaptureModeMap = NodeMap<ast::CaptureClause>;
6581 // Trait method resolution
6582 pub type TraitMap = NodeMap<Vec<DefId>>;
6584 // Map from the NodeId of a glob import to a list of items which are actually
6586 pub type GlobMap = HashMap<NodeId, HashSet<Name>>;
6588 pub fn with_freevars<T, F>(tcx: &ty::ctxt, fid: ast::NodeId, f: F) -> T where
6589 F: FnOnce(&[Freevar]) -> T,
6591 match tcx.freevars.borrow().get(&fid) {
6597 impl<'tcx> AutoAdjustment<'tcx> {
6598 pub fn is_identity(&self) -> bool {
6600 AdjustReifyFnPointer(..) => false,
6601 AdjustDerefRef(ref r) => r.is_identity(),
6606 impl<'tcx> AutoDerefRef<'tcx> {
6607 pub fn is_identity(&self) -> bool {
6608 self.autoderefs == 0 && self.autoref.is_none()
6612 /// Replace any late-bound regions bound in `value` with free variants attached to scope-id
6614 pub fn liberate_late_bound_regions<'tcx, T>(
6615 tcx: &ty::ctxt<'tcx>,
6616 scope: region::CodeExtent,
6619 where T : TypeFoldable<'tcx> + Repr<'tcx>
6621 replace_late_bound_regions(
6623 |br| ty::ReFree(ty::FreeRegion{scope: scope, bound_region: br})).0
6626 pub fn count_late_bound_regions<'tcx, T>(
6627 tcx: &ty::ctxt<'tcx>,
6630 where T : TypeFoldable<'tcx> + Repr<'tcx>
6632 let (_, skol_map) = replace_late_bound_regions(tcx, value, |_| ty::ReStatic);
6636 pub fn binds_late_bound_regions<'tcx, T>(
6637 tcx: &ty::ctxt<'tcx>,
6640 where T : TypeFoldable<'tcx> + Repr<'tcx>
6642 count_late_bound_regions(tcx, value) > 0
6645 pub fn assert_no_late_bound_regions<'tcx, T>(
6646 tcx: &ty::ctxt<'tcx>,
6649 where T : TypeFoldable<'tcx> + Repr<'tcx> + Clone
6651 assert!(!binds_late_bound_regions(tcx, value));
6655 /// Replace any late-bound regions bound in `value` with `'static`. Useful in trans but also
6656 /// method lookup and a few other places where precise region relationships are not required.
6657 pub fn erase_late_bound_regions<'tcx, T>(
6658 tcx: &ty::ctxt<'tcx>,
6661 where T : TypeFoldable<'tcx> + Repr<'tcx>
6663 replace_late_bound_regions(tcx, value, |_| ty::ReStatic).0
6666 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
6667 /// assigned starting at 1 and increasing monotonically in the order traversed
6668 /// by the fold operation.
6670 /// The chief purpose of this function is to canonicalize regions so that two
6671 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
6672 /// structurally identical. For example, `for<'a, 'b> fn(&'a int, &'b int)` and
6673 /// `for<'a, 'b> fn(&'b int, &'a int)` will become identical after anonymization.
6674 pub fn anonymize_late_bound_regions<'tcx, T>(
6678 where T : TypeFoldable<'tcx> + Repr<'tcx>,
6680 let mut counter = 0;
6681 ty::Binder(replace_late_bound_regions(tcx, sig, |_| {
6683 ReLateBound(ty::DebruijnIndex::new(1), BrAnon(counter))
6687 /// Replaces the late-bound-regions in `value` that are bound by `value`.
6688 pub fn replace_late_bound_regions<'tcx, T, F>(
6689 tcx: &ty::ctxt<'tcx>,
6692 -> (T, FnvHashMap<ty::BoundRegion,ty::Region>)
6693 where T : TypeFoldable<'tcx> + Repr<'tcx>,
6694 F : FnMut(BoundRegion) -> ty::Region,
6696 debug!("replace_late_bound_regions({})", binder.repr(tcx));
6698 let mut map = FnvHashMap();
6700 // Note: fold the field `0`, not the binder, so that late-bound
6701 // regions bound by `binder` are considered free.
6702 let value = ty_fold::fold_regions(tcx, &binder.0, |region, current_depth| {
6703 debug!("region={}", region.repr(tcx));
6705 ty::ReLateBound(debruijn, br) if debruijn.depth == current_depth => {
6707 * map.entry(br).get().unwrap_or_else(
6708 |vacant_entry| vacant_entry.insert(mapf(br)));
6710 if let ty::ReLateBound(debruijn1, br) = region {
6711 // If the callback returns a late-bound region,
6712 // that region should always use depth 1. Then we
6713 // adjust it to the correct depth.
6714 assert_eq!(debruijn1.depth, 1);
6715 ty::ReLateBound(debruijn, br)
6726 debug!("resulting map: {:?} value: {:?}", map, value.repr(tcx));
6730 impl DebruijnIndex {
6731 pub fn new(depth: u32) -> DebruijnIndex {
6733 DebruijnIndex { depth: depth }
6736 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
6737 DebruijnIndex { depth: self.depth + amount }
6741 impl<'tcx> Repr<'tcx> for AutoAdjustment<'tcx> {
6742 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6744 AdjustReifyFnPointer(def_id) => {
6745 format!("AdjustReifyFnPointer({})", def_id.repr(tcx))
6747 AdjustDerefRef(ref data) => {
6754 impl<'tcx> Repr<'tcx> for UnsizeKind<'tcx> {
6755 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6757 UnsizeLength(n) => format!("UnsizeLength({})", n),
6758 UnsizeStruct(ref k, n) => format!("UnsizeStruct({},{})", k.repr(tcx), n),
6759 UnsizeVtable(ref a, ref b) => format!("UnsizeVtable({},{})", a.repr(tcx), b.repr(tcx)),
6764 impl<'tcx> Repr<'tcx> for AutoDerefRef<'tcx> {
6765 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6766 format!("AutoDerefRef({}, {})", self.autoderefs, self.autoref.repr(tcx))
6770 impl<'tcx> Repr<'tcx> for AutoRef<'tcx> {
6771 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6773 AutoPtr(a, b, ref c) => {
6774 format!("AutoPtr({},{:?},{})", a.repr(tcx), b, c.repr(tcx))
6776 AutoUnsize(ref a) => {
6777 format!("AutoUnsize({})", a.repr(tcx))
6779 AutoUnsizeUniq(ref a) => {
6780 format!("AutoUnsizeUniq({})", a.repr(tcx))
6782 AutoUnsafe(ref a, ref b) => {
6783 format!("AutoUnsafe({:?},{})", a, b.repr(tcx))
6789 impl<'tcx> Repr<'tcx> for TyTrait<'tcx> {
6790 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6791 format!("TyTrait({},{})",
6792 self.principal.repr(tcx),
6793 self.bounds.repr(tcx))
6797 impl<'tcx> Repr<'tcx> for ty::Predicate<'tcx> {
6798 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6800 Predicate::Trait(ref a) => a.repr(tcx),
6801 Predicate::Equate(ref pair) => pair.repr(tcx),
6802 Predicate::RegionOutlives(ref pair) => pair.repr(tcx),
6803 Predicate::TypeOutlives(ref pair) => pair.repr(tcx),
6804 Predicate::Projection(ref pair) => pair.repr(tcx),
6809 impl<'tcx> Repr<'tcx> for vtable_origin<'tcx> {
6810 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
6812 vtable_static(def_id, ref tys, ref vtable_res) => {
6813 format!("vtable_static({:?}:{}, {}, {})",
6815 ty::item_path_str(tcx, def_id),
6817 vtable_res.repr(tcx))
6820 vtable_param(x, y) => {
6821 format!("vtable_param({:?}, {})", x, y)
6824 vtable_unboxed_closure(def_id) => {
6825 format!("vtable_unboxed_closure({:?})", def_id)
6829 format!("vtable_error")
6835 pub fn make_substs_for_receiver_types<'tcx>(tcx: &ty::ctxt<'tcx>,
6836 trait_ref: &ty::TraitRef<'tcx>,
6837 method: &ty::Method<'tcx>)
6838 -> subst::Substs<'tcx>
6841 * Substitutes the values for the receiver's type parameters
6842 * that are found in method, leaving the method's type parameters
6846 let meth_tps: Vec<Ty> =
6847 method.generics.types.get_slice(subst::FnSpace)
6849 .map(|def| ty::mk_param_from_def(tcx, def))
6851 let meth_regions: Vec<ty::Region> =
6852 method.generics.regions.get_slice(subst::FnSpace)
6854 .map(|def| ty::ReEarlyBound(def.def_id.node, def.space,
6855 def.index, def.name))
6857 trait_ref.substs.clone().with_method(meth_tps, meth_regions)
6861 pub enum CopyImplementationError {
6862 FieldDoesNotImplementCopy(ast::Name),
6863 VariantDoesNotImplementCopy(ast::Name),
6868 pub fn can_type_implement_copy<'a,'tcx>(param_env: &ParameterEnvironment<'a, 'tcx>,
6870 self_type: Ty<'tcx>)
6871 -> Result<(),CopyImplementationError>
6873 let tcx = param_env.tcx;
6875 let did = match self_type.sty {
6876 ty::ty_struct(struct_did, substs) => {
6877 let fields = ty::struct_fields(tcx, struct_did, substs);
6878 for field in fields.iter() {
6879 if type_moves_by_default(param_env, span, field.mt.ty) {
6880 return Err(FieldDoesNotImplementCopy(field.name))
6885 ty::ty_enum(enum_did, substs) => {
6886 let enum_variants = ty::enum_variants(tcx, enum_did);
6887 for variant in enum_variants.iter() {
6888 for variant_arg_type in variant.args.iter() {
6889 let substd_arg_type =
6890 variant_arg_type.subst(tcx, substs);
6891 if type_moves_by_default(param_env, span, substd_arg_type) {
6892 return Err(VariantDoesNotImplementCopy(variant.name))
6898 _ => return Err(TypeIsStructural),
6901 if ty::has_dtor(tcx, did) {
6902 return Err(TypeHasDestructor)
6908 // FIXME(#20298) -- all of these types basically walk various
6909 // structures to test whether types/regions are reachable with various
6910 // properties. It should be possible to express them in terms of one
6911 // common "walker" trait or something.
6913 pub trait RegionEscape {
6914 fn has_escaping_regions(&self) -> bool {
6915 self.has_regions_escaping_depth(0)
6918 fn has_regions_escaping_depth(&self, depth: u32) -> bool;
6921 impl<'tcx> RegionEscape for Ty<'tcx> {
6922 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
6923 ty::type_escapes_depth(*self, depth)
6927 impl<'tcx> RegionEscape for Substs<'tcx> {
6928 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
6929 self.types.has_regions_escaping_depth(depth) ||
6930 self.regions.has_regions_escaping_depth(depth)
6934 impl<'tcx,T:RegionEscape> RegionEscape for VecPerParamSpace<T> {
6935 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
6936 self.iter_enumerated().any(|(space, _, t)| {
6937 if space == subst::FnSpace {
6938 t.has_regions_escaping_depth(depth+1)
6940 t.has_regions_escaping_depth(depth)
6946 impl<'tcx> RegionEscape for TypeScheme<'tcx> {
6947 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
6948 self.ty.has_regions_escaping_depth(depth) ||
6949 self.generics.has_regions_escaping_depth(depth)
6953 impl RegionEscape for Region {
6954 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
6955 self.escapes_depth(depth)
6959 impl<'tcx> RegionEscape for Generics<'tcx> {
6960 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
6961 self.predicates.has_regions_escaping_depth(depth)
6965 impl<'tcx> RegionEscape for Predicate<'tcx> {
6966 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
6968 Predicate::Trait(ref data) => data.has_regions_escaping_depth(depth),
6969 Predicate::Equate(ref data) => data.has_regions_escaping_depth(depth),
6970 Predicate::RegionOutlives(ref data) => data.has_regions_escaping_depth(depth),
6971 Predicate::TypeOutlives(ref data) => data.has_regions_escaping_depth(depth),
6972 Predicate::Projection(ref data) => data.has_regions_escaping_depth(depth),
6977 impl<'tcx> RegionEscape for TraitRef<'tcx> {
6978 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
6979 self.substs.types.iter().any(|t| t.has_regions_escaping_depth(depth)) ||
6980 self.substs.regions.has_regions_escaping_depth(depth)
6984 impl<'tcx> RegionEscape for subst::RegionSubsts {
6985 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
6987 subst::ErasedRegions => false,
6988 subst::NonerasedRegions(ref r) => {
6989 r.iter().any(|t| t.has_regions_escaping_depth(depth))
6995 impl<'tcx,T:RegionEscape> RegionEscape for Binder<T> {
6996 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
6997 self.0.has_regions_escaping_depth(depth + 1)
7001 impl<'tcx> RegionEscape for EquatePredicate<'tcx> {
7002 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7003 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7007 impl<'tcx> RegionEscape for TraitPredicate<'tcx> {
7008 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7009 self.trait_ref.has_regions_escaping_depth(depth)
7013 impl<T:RegionEscape,U:RegionEscape> RegionEscape for OutlivesPredicate<T,U> {
7014 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7015 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7019 impl<'tcx> RegionEscape for ProjectionPredicate<'tcx> {
7020 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7021 self.projection_ty.has_regions_escaping_depth(depth) ||
7022 self.ty.has_regions_escaping_depth(depth)
7026 impl<'tcx> RegionEscape for ProjectionTy<'tcx> {
7027 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7028 self.trait_ref.has_regions_escaping_depth(depth)
7032 impl<'tcx> Repr<'tcx> for ty::ProjectionPredicate<'tcx> {
7033 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7034 format!("ProjectionPredicate({}, {})",
7035 self.projection_ty.repr(tcx),
7040 pub trait HasProjectionTypes {
7041 fn has_projection_types(&self) -> bool;
7044 impl<'tcx,T:HasProjectionTypes> HasProjectionTypes for Vec<T> {
7045 fn has_projection_types(&self) -> bool {
7046 self.iter().any(|p| p.has_projection_types())
7050 impl<'tcx,T:HasProjectionTypes> HasProjectionTypes for VecPerParamSpace<T> {
7051 fn has_projection_types(&self) -> bool {
7052 self.iter().any(|p| p.has_projection_types())
7056 impl<'tcx> HasProjectionTypes for ClosureTy<'tcx> {
7057 fn has_projection_types(&self) -> bool {
7058 self.sig.has_projection_types()
7062 impl<'tcx> HasProjectionTypes for UnboxedClosureUpvar<'tcx> {
7063 fn has_projection_types(&self) -> bool {
7064 self.ty.has_projection_types()
7068 impl<'tcx> HasProjectionTypes for ty::GenericBounds<'tcx> {
7069 fn has_projection_types(&self) -> bool {
7070 self.predicates.has_projection_types()
7074 impl<'tcx> HasProjectionTypes for Predicate<'tcx> {
7075 fn has_projection_types(&self) -> bool {
7077 Predicate::Trait(ref data) => data.has_projection_types(),
7078 Predicate::Equate(ref data) => data.has_projection_types(),
7079 Predicate::RegionOutlives(ref data) => data.has_projection_types(),
7080 Predicate::TypeOutlives(ref data) => data.has_projection_types(),
7081 Predicate::Projection(ref data) => data.has_projection_types(),
7086 impl<'tcx> HasProjectionTypes for TraitPredicate<'tcx> {
7087 fn has_projection_types(&self) -> bool {
7088 self.trait_ref.has_projection_types()
7092 impl<'tcx> HasProjectionTypes for EquatePredicate<'tcx> {
7093 fn has_projection_types(&self) -> bool {
7094 self.0.has_projection_types() || self.1.has_projection_types()
7098 impl HasProjectionTypes for Region {
7099 fn has_projection_types(&self) -> bool {
7104 impl<T:HasProjectionTypes,U:HasProjectionTypes> HasProjectionTypes for OutlivesPredicate<T,U> {
7105 fn has_projection_types(&self) -> bool {
7106 self.0.has_projection_types() || self.1.has_projection_types()
7110 impl<'tcx> HasProjectionTypes for ProjectionPredicate<'tcx> {
7111 fn has_projection_types(&self) -> bool {
7112 self.projection_ty.has_projection_types() || self.ty.has_projection_types()
7116 impl<'tcx> HasProjectionTypes for ProjectionTy<'tcx> {
7117 fn has_projection_types(&self) -> bool {
7118 self.trait_ref.has_projection_types()
7122 impl<'tcx> HasProjectionTypes for Ty<'tcx> {
7123 fn has_projection_types(&self) -> bool {
7124 ty::type_has_projection(*self)
7128 impl<'tcx> HasProjectionTypes for TraitRef<'tcx> {
7129 fn has_projection_types(&self) -> bool {
7130 self.substs.has_projection_types()
7134 impl<'tcx> HasProjectionTypes for subst::Substs<'tcx> {
7135 fn has_projection_types(&self) -> bool {
7136 self.types.iter().any(|t| t.has_projection_types())
7140 impl<'tcx,T> HasProjectionTypes for Option<T>
7141 where T : HasProjectionTypes
7143 fn has_projection_types(&self) -> bool {
7144 self.iter().any(|t| t.has_projection_types())
7148 impl<'tcx,T> HasProjectionTypes for Rc<T>
7149 where T : HasProjectionTypes
7151 fn has_projection_types(&self) -> bool {
7152 (**self).has_projection_types()
7156 impl<'tcx,T> HasProjectionTypes for Box<T>
7157 where T : HasProjectionTypes
7159 fn has_projection_types(&self) -> bool {
7160 (**self).has_projection_types()
7164 impl<T> HasProjectionTypes for Binder<T>
7165 where T : HasProjectionTypes
7167 fn has_projection_types(&self) -> bool {
7168 self.0.has_projection_types()
7172 impl<'tcx> HasProjectionTypes for FnOutput<'tcx> {
7173 fn has_projection_types(&self) -> bool {
7175 FnConverging(t) => t.has_projection_types(),
7176 FnDiverging => false,
7181 impl<'tcx> HasProjectionTypes for FnSig<'tcx> {
7182 fn has_projection_types(&self) -> bool {
7183 self.inputs.iter().any(|t| t.has_projection_types()) ||
7184 self.output.has_projection_types()
7188 impl<'tcx> HasProjectionTypes for field<'tcx> {
7189 fn has_projection_types(&self) -> bool {
7190 self.mt.ty.has_projection_types()
7194 impl<'tcx> HasProjectionTypes for BareFnTy<'tcx> {
7195 fn has_projection_types(&self) -> bool {
7196 self.sig.has_projection_types()
7200 pub trait ReferencesError {
7201 fn references_error(&self) -> bool;
7204 impl<T:ReferencesError> ReferencesError for Binder<T> {
7205 fn references_error(&self) -> bool {
7206 self.0.references_error()
7210 impl<T:ReferencesError> ReferencesError for Rc<T> {
7211 fn references_error(&self) -> bool {
7212 (&**self).references_error()
7216 impl<'tcx> ReferencesError for TraitPredicate<'tcx> {
7217 fn references_error(&self) -> bool {
7218 self.trait_ref.references_error()
7222 impl<'tcx> ReferencesError for ProjectionPredicate<'tcx> {
7223 fn references_error(&self) -> bool {
7224 self.projection_ty.trait_ref.references_error() || self.ty.references_error()
7228 impl<'tcx> ReferencesError for TraitRef<'tcx> {
7229 fn references_error(&self) -> bool {
7230 self.input_types().iter().any(|t| t.references_error())
7234 impl<'tcx> ReferencesError for Ty<'tcx> {
7235 fn references_error(&self) -> bool {
7236 type_is_error(*self)
7240 impl<'tcx> ReferencesError for Predicate<'tcx> {
7241 fn references_error(&self) -> bool {
7243 Predicate::Trait(ref data) => data.references_error(),
7244 Predicate::Equate(ref data) => data.references_error(),
7245 Predicate::RegionOutlives(ref data) => data.references_error(),
7246 Predicate::TypeOutlives(ref data) => data.references_error(),
7247 Predicate::Projection(ref data) => data.references_error(),
7252 impl<A,B> ReferencesError for OutlivesPredicate<A,B>
7253 where A : ReferencesError, B : ReferencesError
7255 fn references_error(&self) -> bool {
7256 self.0.references_error() || self.1.references_error()
7260 impl<'tcx> ReferencesError for EquatePredicate<'tcx>
7262 fn references_error(&self) -> bool {
7263 self.0.references_error() || self.1.references_error()
7267 impl ReferencesError for Region
7269 fn references_error(&self) -> bool {
7274 impl<'tcx> Repr<'tcx> for ClosureTy<'tcx> {
7275 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7276 format!("ClosureTy({},{},{})",
7283 impl<'tcx> Repr<'tcx> for UnboxedClosureUpvar<'tcx> {
7284 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7285 format!("UnboxedClosureUpvar({},{})",
7291 impl<'tcx> Repr<'tcx> for field<'tcx> {
7292 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7293 format!("field({},{})",
7294 self.name.repr(tcx),
7299 impl<'a, 'tcx> Repr<'tcx> for ParameterEnvironment<'a, 'tcx> {
7300 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7301 format!("ParameterEnvironment(\
7303 implicit_region_bound={}, \
7305 self.free_substs.repr(tcx),
7306 self.implicit_region_bound.repr(tcx),
7307 self.caller_bounds.repr(tcx))