1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(non_camel_case_types)]
13 pub use self::terr_vstore_kind::*;
14 pub use self::type_err::*;
15 pub use self::BuiltinBound::*;
16 pub use self::InferTy::*;
17 pub use self::InferRegion::*;
18 pub use self::ImplOrTraitItemId::*;
19 pub use self::ClosureKind::*;
20 pub use self::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::check_const;
48 use middle::const_eval;
49 use middle::def::{self, DefMap, ExportMap};
50 use middle::dependency_format;
51 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem};
52 use middle::lang_items::{FnOnceTraitLangItem, TyDescStructLangItem};
53 use middle::mem_categorization as mc;
55 use middle::resolve_lifetime;
57 use middle::stability;
58 use middle::subst::{self, Subst, Substs, VecPerParamSpace};
61 use middle::ty_fold::{self, TypeFoldable, TypeFolder};
62 use middle::ty_walk::TypeWalker;
63 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_string};
64 use util::ppaux::ty_to_string;
65 use util::ppaux::{Repr, UserString};
66 use util::common::{memoized, ErrorReported};
67 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet};
68 use util::nodemap::{FnvHashMap};
70 use arena::TypedArena;
71 use std::borrow::{Borrow, Cow};
72 use std::cell::{Cell, RefCell};
75 use std::hash::{Hash, SipHasher, Hasher};
76 #[cfg(stage0)] use std::hash::Writer;
80 use std::vec::{CowVec, IntoIter};
81 use collections::enum_set::{EnumSet, CLike};
82 use std::collections::{HashMap, HashSet};
84 use syntax::ast::{CrateNum, DefId, Ident, ItemTrait, LOCAL_CRATE};
85 use syntax::ast::{MutImmutable, MutMutable, Name, NamedField, NodeId};
86 use syntax::ast::{StmtExpr, StmtSemi, StructField, UnnamedField, Visibility};
87 use syntax::ast_util::{self, is_local, lit_is_str, local_def, PostExpansionMethod};
88 use syntax::attr::{self, AttrMetaMethods};
89 use syntax::codemap::Span;
90 use syntax::parse::token::{self, InternedString, special_idents};
91 use syntax::{ast, ast_map};
95 pub const INITIAL_DISCRIMINANT_VALUE: Disr = 0;
99 /// The complete set of all analyses described in this module. This is
100 /// produced by the driver and fed to trans and later passes.
101 pub struct CrateAnalysis<'tcx> {
102 pub export_map: ExportMap,
103 pub exported_items: middle::privacy::ExportedItems,
104 pub public_items: middle::privacy::PublicItems,
105 pub ty_cx: ty::ctxt<'tcx>,
106 pub reachable: NodeSet,
108 pub glob_map: Option<GlobMap>,
111 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
112 pub struct field<'tcx> {
117 #[derive(Clone, Copy, Debug)]
118 pub enum ImplOrTraitItemContainer {
119 TraitContainer(ast::DefId),
120 ImplContainer(ast::DefId),
123 impl ImplOrTraitItemContainer {
124 pub fn id(&self) -> ast::DefId {
126 TraitContainer(id) => id,
127 ImplContainer(id) => id,
132 #[derive(Clone, Debug)]
133 pub enum ImplOrTraitItem<'tcx> {
134 MethodTraitItem(Rc<Method<'tcx>>),
135 TypeTraitItem(Rc<AssociatedType>),
138 impl<'tcx> ImplOrTraitItem<'tcx> {
139 fn id(&self) -> ImplOrTraitItemId {
141 MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
142 TypeTraitItem(ref associated_type) => {
143 TypeTraitItemId(associated_type.def_id)
148 pub fn def_id(&self) -> ast::DefId {
150 MethodTraitItem(ref method) => method.def_id,
151 TypeTraitItem(ref associated_type) => associated_type.def_id,
155 pub fn name(&self) -> ast::Name {
157 MethodTraitItem(ref method) => method.name,
158 TypeTraitItem(ref associated_type) => associated_type.name,
162 pub fn container(&self) -> ImplOrTraitItemContainer {
164 MethodTraitItem(ref method) => method.container,
165 TypeTraitItem(ref associated_type) => associated_type.container,
169 pub fn as_opt_method(&self) -> Option<Rc<Method<'tcx>>> {
171 MethodTraitItem(ref m) => Some((*m).clone()),
172 TypeTraitItem(_) => None
177 #[derive(Clone, Copy, Debug)]
178 pub enum ImplOrTraitItemId {
179 MethodTraitItemId(ast::DefId),
180 TypeTraitItemId(ast::DefId),
183 impl ImplOrTraitItemId {
184 pub fn def_id(&self) -> ast::DefId {
186 MethodTraitItemId(def_id) => def_id,
187 TypeTraitItemId(def_id) => def_id,
192 #[derive(Clone, Debug)]
193 pub struct Method<'tcx> {
195 pub generics: Generics<'tcx>,
196 pub predicates: GenericPredicates<'tcx>,
197 pub fty: BareFnTy<'tcx>,
198 pub explicit_self: ExplicitSelfCategory,
199 pub vis: ast::Visibility,
200 pub def_id: ast::DefId,
201 pub container: ImplOrTraitItemContainer,
203 // If this method is provided, we need to know where it came from
204 pub provided_source: Option<ast::DefId>
207 impl<'tcx> Method<'tcx> {
208 pub fn new(name: ast::Name,
209 generics: ty::Generics<'tcx>,
210 predicates: GenericPredicates<'tcx>,
212 explicit_self: ExplicitSelfCategory,
213 vis: ast::Visibility,
215 container: ImplOrTraitItemContainer,
216 provided_source: Option<ast::DefId>)
221 predicates: predicates,
223 explicit_self: explicit_self,
226 container: container,
227 provided_source: provided_source
231 pub fn container_id(&self) -> ast::DefId {
232 match self.container {
233 TraitContainer(id) => id,
234 ImplContainer(id) => id,
239 #[derive(Clone, Copy, Debug)]
240 pub struct AssociatedType {
242 pub vis: ast::Visibility,
243 pub def_id: ast::DefId,
244 pub container: ImplOrTraitItemContainer,
247 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
248 pub struct mt<'tcx> {
250 pub mutbl: ast::Mutability,
253 #[derive(Clone, Copy, Debug)]
254 pub struct field_ty {
257 pub vis: ast::Visibility,
258 pub origin: ast::DefId, // The DefId of the struct in which the field is declared.
261 // Contains information needed to resolve types and (in the future) look up
262 // the types of AST nodes.
263 #[derive(Copy, PartialEq, Eq, Hash)]
264 pub struct creader_cache_key {
271 pub enum ast_ty_to_ty_cache_entry<'tcx> {
272 atttce_unresolved, /* not resolved yet */
273 atttce_resolved(Ty<'tcx>) /* resolved to a type, irrespective of region */
276 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
277 pub struct ItemVariances {
278 pub types: VecPerParamSpace<Variance>,
279 pub regions: VecPerParamSpace<Variance>,
282 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug, Copy)]
284 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
285 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
286 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
287 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
290 #[derive(Clone, Debug)]
291 pub enum AutoAdjustment<'tcx> {
292 AdjustReifyFnPointer(ast::DefId), // go from a fn-item type to a fn-pointer type
293 AdjustDerefRef(AutoDerefRef<'tcx>)
296 #[derive(Clone, PartialEq, Debug)]
297 pub enum UnsizeKind<'tcx> {
298 // [T, ..n] -> [T], the uint field is n.
300 // An unsize coercion applied to the tail field of a struct.
301 // The uint is the index of the type parameter which is unsized.
302 UnsizeStruct(Box<UnsizeKind<'tcx>>, uint),
303 UnsizeVtable(TyTrait<'tcx>, /* the self type of the trait */ Ty<'tcx>)
306 #[derive(Clone, Debug)]
307 pub struct AutoDerefRef<'tcx> {
308 pub autoderefs: uint,
309 pub autoref: Option<AutoRef<'tcx>>
312 #[derive(Clone, PartialEq, Debug)]
313 pub enum AutoRef<'tcx> {
314 /// Convert from T to &T
315 /// The third field allows us to wrap other AutoRef adjustments.
316 AutoPtr(Region, ast::Mutability, Option<Box<AutoRef<'tcx>>>),
318 /// Convert [T, ..n] to [T] (or similar, depending on the kind)
319 AutoUnsize(UnsizeKind<'tcx>),
321 /// Convert Box<[T, ..n]> to Box<[T]> or something similar in a Box.
322 /// With DST and Box a library type, this should be replaced by UnsizeStruct.
323 AutoUnsizeUniq(UnsizeKind<'tcx>),
325 /// Convert from T to *T
326 /// Value to thin pointer
327 /// The second field allows us to wrap other AutoRef adjustments.
328 AutoUnsafe(ast::Mutability, Option<Box<AutoRef<'tcx>>>),
331 // Ugly little helper function. The first bool in the returned tuple is true if
332 // there is an 'unsize to trait object' adjustment at the bottom of the
333 // adjustment. If that is surrounded by an AutoPtr, then we also return the
334 // region of the AutoPtr (in the third argument). The second bool is true if the
335 // adjustment is unique.
336 fn autoref_object_region(autoref: &AutoRef) -> (bool, bool, Option<Region>) {
337 fn unsize_kind_is_object(k: &UnsizeKind) -> bool {
339 &UnsizeVtable(..) => true,
340 &UnsizeStruct(box ref k, _) => unsize_kind_is_object(k),
346 &AutoUnsize(ref k) => (unsize_kind_is_object(k), false, None),
347 &AutoUnsizeUniq(ref k) => (unsize_kind_is_object(k), true, None),
348 &AutoPtr(adj_r, _, Some(box ref autoref)) => {
349 let (b, u, r) = autoref_object_region(autoref);
350 if r.is_some() || u {
356 &AutoUnsafe(_, Some(box ref autoref)) => autoref_object_region(autoref),
357 _ => (false, false, None)
361 // If the adjustment introduces a borrowed reference to a trait object, then
362 // returns the region of the borrowed reference.
363 pub fn adjusted_object_region(adj: &AutoAdjustment) -> Option<Region> {
365 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
366 let (b, _, r) = autoref_object_region(autoref);
377 // Returns true if there is a trait cast at the bottom of the adjustment.
378 pub fn adjust_is_object(adj: &AutoAdjustment) -> bool {
380 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
381 let (b, _, _) = autoref_object_region(autoref);
388 // If possible, returns the type expected from the given adjustment. This is not
389 // possible if the adjustment depends on the type of the adjusted expression.
390 pub fn type_of_adjust<'tcx>(cx: &ctxt<'tcx>, adj: &AutoAdjustment<'tcx>) -> Option<Ty<'tcx>> {
391 fn type_of_autoref<'tcx>(cx: &ctxt<'tcx>, autoref: &AutoRef<'tcx>) -> Option<Ty<'tcx>> {
393 &AutoUnsize(ref k) => match k {
394 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
395 Some(mk_trait(cx, principal.clone(), bounds.clone()))
399 &AutoUnsizeUniq(ref k) => match k {
400 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
401 Some(mk_uniq(cx, mk_trait(cx, principal.clone(), bounds.clone())))
405 &AutoPtr(r, m, Some(box ref autoref)) => {
406 match type_of_autoref(cx, autoref) {
407 Some(ty) => Some(mk_rptr(cx, cx.mk_region(r), mt {mutbl: m, ty: ty})),
411 &AutoUnsafe(m, Some(box ref autoref)) => {
412 match type_of_autoref(cx, autoref) {
413 Some(ty) => Some(mk_ptr(cx, mt {mutbl: m, ty: ty})),
422 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
423 type_of_autoref(cx, autoref)
429 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Debug)]
430 pub struct param_index {
431 pub space: subst::ParamSpace,
435 #[derive(Clone, Debug)]
436 pub enum MethodOrigin<'tcx> {
437 // fully statically resolved method
438 MethodStatic(ast::DefId),
440 // fully statically resolved closure invocation
441 MethodStaticClosure(ast::DefId),
443 // method invoked on a type parameter with a bounded trait
444 MethodTypeParam(MethodParam<'tcx>),
446 // method invoked on a trait instance
447 MethodTraitObject(MethodObject<'tcx>),
451 // details for a method invoked with a receiver whose type is a type parameter
452 // with a bounded trait.
453 #[derive(Clone, Debug)]
454 pub struct MethodParam<'tcx> {
455 // the precise trait reference that occurs as a bound -- this may
456 // be a supertrait of what the user actually typed. Note that it
457 // never contains bound regions; those regions should have been
458 // instantiated with fresh variables at this point.
459 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
461 // index of uint in the list of trait items. Note that this is NOT
462 // the index into the vtable, because the list of trait items
463 // includes associated types.
464 pub method_num: uint,
466 /// The impl for the trait from which the method comes. This
467 /// should only be used for certain linting/heuristic purposes
468 /// since there is no guarantee that this is Some in every
469 /// situation that it could/should be.
470 pub impl_def_id: Option<ast::DefId>,
473 // details for a method invoked with a receiver whose type is an object
474 #[derive(Clone, Debug)]
475 pub struct MethodObject<'tcx> {
476 // the (super)trait containing the method to be invoked
477 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
479 // the actual base trait id of the object
480 pub object_trait_id: ast::DefId,
482 // index of the method to be invoked amongst the trait's items
483 pub method_num: uint,
485 // index into the actual runtime vtable.
486 // the vtable is formed by concatenating together the method lists of
487 // the base object trait and all supertraits; this is the index into
489 pub vtable_index: uint,
493 pub struct MethodCallee<'tcx> {
494 pub origin: MethodOrigin<'tcx>,
496 pub substs: subst::Substs<'tcx>
499 /// With method calls, we store some extra information in
500 /// side tables (i.e method_map). We use
501 /// MethodCall as a key to index into these tables instead of
502 /// just directly using the expression's NodeId. The reason
503 /// for this being that we may apply adjustments (coercions)
504 /// with the resulting expression also needing to use the
505 /// side tables. The problem with this is that we don't
506 /// assign a separate NodeId to this new expression
507 /// and so it would clash with the base expression if both
508 /// needed to add to the side tables. Thus to disambiguate
509 /// we also keep track of whether there's an adjustment in
511 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
512 pub struct MethodCall {
513 pub expr_id: ast::NodeId,
514 pub adjustment: ExprAdjustment
517 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
518 pub enum ExprAdjustment {
525 pub fn expr(id: ast::NodeId) -> MethodCall {
528 adjustment: NoAdjustment
532 pub fn autoobject(id: ast::NodeId) -> MethodCall {
535 adjustment: AutoObject
539 pub fn autoderef(expr_id: ast::NodeId, autoderef: uint) -> MethodCall {
542 adjustment: AutoDeref(1 + autoderef)
547 // maps from an expression id that corresponds to a method call to the details
548 // of the method to be invoked
549 pub type MethodMap<'tcx> = RefCell<FnvHashMap<MethodCall, MethodCallee<'tcx>>>;
551 pub type vtable_param_res<'tcx> = Vec<vtable_origin<'tcx>>;
553 // Resolutions for bounds of all parameters, left to right, for a given path.
554 pub type vtable_res<'tcx> = VecPerParamSpace<vtable_param_res<'tcx>>;
557 pub enum vtable_origin<'tcx> {
559 Statically known vtable. def_id gives the impl item
560 from whence comes the vtable, and tys are the type substs.
561 vtable_res is the vtable itself.
563 vtable_static(ast::DefId, subst::Substs<'tcx>, vtable_res<'tcx>),
566 Dynamic vtable, comes from a parameter that has a bound on it:
567 fn foo<T:quux,baz,bar>(a: T) -- a's vtable would have a
570 The first argument is the param index (identifying T in the example),
571 and the second is the bound number (identifying baz)
573 vtable_param(param_index, uint),
576 Vtable automatically generated for a closure. The def ID is the
577 ID of the closure expression.
579 vtable_closure(ast::DefId),
582 Asked to determine the vtable for ty_err. This is the value used
583 for the vtables of `Self` in a virtual call like `foo.bar()`
584 where `foo` is of object type. The same value is also used when
591 // For every explicit cast into an object type, maps from the cast
592 // expr to the associated trait ref.
593 pub type ObjectCastMap<'tcx> = RefCell<NodeMap<ty::PolyTraitRef<'tcx>>>;
595 /// A restriction that certain types must be the same size. The use of
596 /// `transmute` gives rise to these restrictions. These generally
597 /// cannot be checked until trans; therefore, each call to `transmute`
598 /// will push one or more such restriction into the
599 /// `transmute_restrictions` vector during `intrinsicck`. They are
600 /// then checked during `trans` by the fn `check_intrinsics`.
602 pub struct TransmuteRestriction<'tcx> {
603 /// The span whence the restriction comes.
606 /// The type being transmuted from.
607 pub original_from: Ty<'tcx>,
609 /// The type being transmuted to.
610 pub original_to: Ty<'tcx>,
612 /// The type being transmuted from, with all type parameters
613 /// substituted for an arbitrary representative. Not to be shown
615 pub substituted_from: Ty<'tcx>,
617 /// The type being transmuted to, with all type parameters
618 /// substituted for an arbitrary representative. Not to be shown
620 pub substituted_to: Ty<'tcx>,
622 /// NodeId of the transmute intrinsic.
627 pub struct CtxtArenas<'tcx> {
628 type_: TypedArena<TyS<'tcx>>,
629 substs: TypedArena<Substs<'tcx>>,
630 bare_fn: TypedArena<BareFnTy<'tcx>>,
631 region: TypedArena<Region>,
634 impl<'tcx> CtxtArenas<'tcx> {
635 pub fn new() -> CtxtArenas<'tcx> {
637 type_: TypedArena::new(),
638 substs: TypedArena::new(),
639 bare_fn: TypedArena::new(),
640 region: TypedArena::new(),
645 pub struct CommonTypes<'tcx> {
663 /// The data structure to keep track of all the information that typechecker
664 /// generates so that so that it can be reused and doesn't have to be redone
666 pub struct ctxt<'tcx> {
667 /// The arenas that types etc are allocated from.
668 arenas: &'tcx CtxtArenas<'tcx>,
670 /// Specifically use a speedy hash algorithm for this hash map, it's used
672 // FIXME(eddyb) use a FnvHashSet<InternedTy<'tcx>> when equivalent keys can
673 // queried from a HashSet.
674 interner: RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>,
676 // FIXME as above, use a hashset if equivalent elements can be queried.
677 substs_interner: RefCell<FnvHashMap<&'tcx Substs<'tcx>, &'tcx Substs<'tcx>>>,
678 bare_fn_interner: RefCell<FnvHashMap<&'tcx BareFnTy<'tcx>, &'tcx BareFnTy<'tcx>>>,
679 region_interner: RefCell<FnvHashMap<&'tcx Region, &'tcx Region>>,
681 /// Common types, pre-interned for your convenience.
682 pub types: CommonTypes<'tcx>,
687 pub named_region_map: resolve_lifetime::NamedRegionMap,
689 pub region_maps: middle::region::RegionMaps,
691 /// Stores the types for various nodes in the AST. Note that this table
692 /// is not guaranteed to be populated until after typeck. See
693 /// typeck::check::fn_ctxt for details.
694 pub node_types: RefCell<NodeMap<Ty<'tcx>>>,
696 /// Stores the type parameters which were substituted to obtain the type
697 /// of this node. This only applies to nodes that refer to entities
698 /// parameterized by type parameters, such as generic fns, types, or
700 pub item_substs: RefCell<NodeMap<ItemSubsts<'tcx>>>,
702 /// Maps from a trait item to the trait item "descriptor"
703 pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem<'tcx>>>,
705 /// Maps from a trait def-id to a list of the def-ids of its trait items
706 pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
708 /// A cache for the trait_items() routine
709 pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem<'tcx>>>>>,
711 pub impl_trait_cache: RefCell<DefIdMap<Option<Rc<ty::TraitRef<'tcx>>>>>,
713 pub trait_refs: RefCell<NodeMap<Rc<TraitRef<'tcx>>>>,
714 pub trait_defs: RefCell<DefIdMap<Rc<TraitDef<'tcx>>>>,
716 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
717 /// associated predicates.
718 pub predicates: RefCell<DefIdMap<GenericPredicates<'tcx>>>,
720 /// Maps from node-id of a trait object cast (like `foo as
721 /// Box<Trait>`) to the trait reference.
722 pub object_cast_map: ObjectCastMap<'tcx>,
724 pub map: ast_map::Map<'tcx>,
725 pub intrinsic_defs: RefCell<DefIdMap<Ty<'tcx>>>,
726 pub freevars: RefCell<FreevarMap>,
727 pub tcache: RefCell<DefIdMap<TypeScheme<'tcx>>>,
728 pub rcache: RefCell<FnvHashMap<creader_cache_key, Ty<'tcx>>>,
729 pub short_names_cache: RefCell<FnvHashMap<Ty<'tcx>, String>>,
730 pub tc_cache: RefCell<FnvHashMap<Ty<'tcx>, TypeContents>>,
731 pub ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry<'tcx>>>,
732 pub enum_var_cache: RefCell<DefIdMap<Rc<Vec<Rc<VariantInfo<'tcx>>>>>>,
733 pub ty_param_defs: RefCell<NodeMap<TypeParameterDef<'tcx>>>,
734 pub adjustments: RefCell<NodeMap<AutoAdjustment<'tcx>>>,
735 pub normalized_cache: RefCell<FnvHashMap<Ty<'tcx>, Ty<'tcx>>>,
736 pub lang_items: middle::lang_items::LanguageItems,
737 /// A mapping of fake provided method def_ids to the default implementation
738 pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
739 pub struct_fields: RefCell<DefIdMap<Rc<Vec<field_ty>>>>,
741 /// Maps from def-id of a type or region parameter to its
742 /// (inferred) variance.
743 pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
745 /// True if the variance has been computed yet; false otherwise.
746 pub variance_computed: Cell<bool>,
748 /// A mapping from the def ID of an enum or struct type to the def ID
749 /// of the method that implements its destructor. If the type is not
750 /// present in this map, it does not have a destructor. This map is
751 /// populated during the coherence phase of typechecking.
752 pub destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
754 /// A method will be in this list if and only if it is a destructor.
755 pub destructors: RefCell<DefIdSet>,
757 /// Maps a trait onto a list of impls of that trait.
758 pub trait_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
760 /// Maps a DefId of a type to a list of its inherent impls.
761 /// Contains implementations of methods that are inherent to a type.
762 /// Methods in these implementations don't need to be exported.
763 pub inherent_impls: RefCell<DefIdMap<Rc<Vec<ast::DefId>>>>,
765 /// Maps a DefId of an impl to a list of its items.
766 /// Note that this contains all of the impls that we know about,
767 /// including ones in other crates. It's not clear that this is the best
769 pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
771 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
772 /// present in this set can be warned about.
773 pub used_unsafe: RefCell<NodeSet>,
775 /// Set of nodes which mark locals as mutable which end up getting used at
776 /// some point. Local variable definitions not in this set can be warned
778 pub used_mut_nodes: RefCell<NodeSet>,
780 /// The set of external nominal types whose implementations have been read.
781 /// This is used for lazy resolution of methods.
782 pub populated_external_types: RefCell<DefIdSet>,
784 /// The set of external traits whose implementations have been read. This
785 /// is used for lazy resolution of traits.
786 pub populated_external_traits: RefCell<DefIdSet>,
789 pub upvar_capture_map: RefCell<UpvarCaptureMap>,
791 /// These two caches are used by const_eval when decoding external statics
792 /// and variants that are found.
793 pub extern_const_statics: RefCell<DefIdMap<ast::NodeId>>,
794 pub extern_const_variants: RefCell<DefIdMap<ast::NodeId>>,
796 pub method_map: MethodMap<'tcx>,
798 pub dependency_formats: RefCell<dependency_format::Dependencies>,
800 /// Records the type of each closure. The def ID is the ID of the
801 /// expression defining the closure.
802 pub closure_kinds: RefCell<DefIdMap<ClosureKind>>,
804 /// Records the type of each closure. The def ID is the ID of the
805 /// expression defining the closure.
806 pub closure_tys: RefCell<DefIdMap<ClosureTy<'tcx>>>,
808 pub node_lint_levels: RefCell<FnvHashMap<(ast::NodeId, lint::LintId),
811 /// The types that must be asserted to be the same size for `transmute`
812 /// to be valid. We gather up these restrictions in the intrinsicck pass
813 /// and check them in trans.
814 pub transmute_restrictions: RefCell<Vec<TransmuteRestriction<'tcx>>>,
816 /// Maps any item's def-id to its stability index.
817 pub stability: RefCell<stability::Index>,
819 /// Maps def IDs to true if and only if they're associated types.
820 pub associated_types: RefCell<DefIdMap<bool>>,
822 /// Caches the results of trait selection. This cache is used
823 /// for things that do not have to do with the parameters in scope.
824 pub selection_cache: traits::SelectionCache<'tcx>,
826 /// Caches the representation hints for struct definitions.
827 pub repr_hint_cache: RefCell<DefIdMap<Rc<Vec<attr::ReprAttr>>>>,
829 /// Caches whether types are known to impl Copy. Note that type
830 /// parameters are never placed into this cache, because their
831 /// results are dependent on the parameter environment.
832 pub type_impls_copy_cache: RefCell<HashMap<Ty<'tcx>,bool>>,
834 /// Caches whether types are known to impl Sized. Note that type
835 /// parameters are never placed into this cache, because their
836 /// results are dependent on the parameter environment.
837 pub type_impls_sized_cache: RefCell<HashMap<Ty<'tcx>,bool>>,
839 /// Caches whether traits are object safe
840 pub object_safety_cache: RefCell<DefIdMap<bool>>,
842 /// Maps Expr NodeId's to their constant qualification.
843 pub const_qualif_map: RefCell<NodeMap<check_const::ConstQualif>>,
846 // Flags that we track on types. These flags are propagated upwards
847 // through the type during type construction, so that we can quickly
848 // check whether the type has various kinds of types in it without
849 // recursing over the type itself.
851 flags TypeFlags: u32 {
852 const NO_TYPE_FLAGS = 0b0,
853 const HAS_PARAMS = 0b1,
854 const HAS_SELF = 0b10,
855 const HAS_TY_INFER = 0b100,
856 const HAS_RE_INFER = 0b1000,
857 const HAS_RE_LATE_BOUND = 0b10000,
858 const HAS_REGIONS = 0b100000,
859 const HAS_TY_ERR = 0b1000000,
860 const HAS_PROJECTION = 0b10000000,
861 const NEEDS_SUBST = HAS_PARAMS.bits | HAS_SELF.bits | HAS_REGIONS.bits,
865 macro_rules! sty_debug_print {
866 ($ctxt: expr, $($variant: ident),*) => {{
867 // curious inner module to allow variant names to be used as
879 pub fn go(tcx: &ty::ctxt) {
880 let mut total = DebugStat {
882 region_infer: 0, ty_infer: 0, both_infer: 0,
884 $(let mut $variant = total;)*
887 for (_, t) in &*tcx.interner.borrow() {
888 let variant = match t.sty {
889 ty::ty_bool | ty::ty_char | ty::ty_int(..) | ty::ty_uint(..) |
890 ty::ty_float(..) | ty::ty_str => continue,
891 ty::ty_err => /* unimportant */ continue,
892 $(ty::$variant(..) => &mut $variant,)*
894 let region = t.flags.intersects(ty::HAS_RE_INFER);
895 let ty = t.flags.intersects(ty::HAS_TY_INFER);
899 if region { total.region_infer += 1; variant.region_infer += 1 }
900 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
901 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
903 println!("Ty interner total ty region both");
904 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
905 {ty:4.1}% {region:5.1}% {both:4.1}%",
906 stringify!($variant),
907 uses = $variant.total,
908 usespc = $variant.total as f64 * 100.0 / total.total as f64,
909 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
910 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
911 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
913 println!(" total {uses:6} \
914 {ty:4.1}% {region:5.1}% {both:4.1}%",
916 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
917 region = total.region_infer as f64 * 100.0 / total.total as f64,
918 both = total.both_infer as f64 * 100.0 / total.total as f64)
926 impl<'tcx> ctxt<'tcx> {
927 pub fn print_debug_stats(&self) {
930 ty_enum, ty_uniq, ty_vec, ty_ptr, ty_rptr, ty_bare_fn, ty_trait,
931 ty_struct, ty_closure, ty_tup, ty_param, ty_open, ty_infer, ty_projection);
933 println!("Substs interner: #{}", self.substs_interner.borrow().len());
934 println!("BareFnTy interner: #{}", self.bare_fn_interner.borrow().len());
935 println!("Region interner: #{}", self.region_interner.borrow().len());
940 pub struct TyS<'tcx> {
942 pub flags: TypeFlags,
944 // the maximal depth of any bound regions appearing in this type.
948 impl fmt::Debug for TypeFlags {
949 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
950 write!(f, "{}", self.bits)
954 impl<'tcx> PartialEq for TyS<'tcx> {
955 fn eq(&self, other: &TyS<'tcx>) -> bool {
956 // (self as *const _) == (other as *const _)
957 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
960 impl<'tcx> Eq for TyS<'tcx> {}
963 impl<'tcx, S: Writer + Hasher> Hash<S> for TyS<'tcx> {
964 fn hash(&self, s: &mut S) {
965 (self as *const _).hash(s)
969 impl<'tcx> Hash for TyS<'tcx> {
970 fn hash<H: Hasher>(&self, s: &mut H) {
971 (self as *const _).hash(s)
975 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
977 /// An entry in the type interner.
978 pub struct InternedTy<'tcx> {
982 // NB: An InternedTy compares and hashes as a sty.
983 impl<'tcx> PartialEq for InternedTy<'tcx> {
984 fn eq(&self, other: &InternedTy<'tcx>) -> bool {
985 self.ty.sty == other.ty.sty
989 impl<'tcx> Eq for InternedTy<'tcx> {}
992 impl<'tcx, S: Writer + Hasher> Hash<S> for InternedTy<'tcx> {
993 fn hash(&self, s: &mut S) {
998 impl<'tcx> Hash for InternedTy<'tcx> {
999 fn hash<H: Hasher>(&self, s: &mut H) {
1004 impl<'tcx> Borrow<sty<'tcx>> for InternedTy<'tcx> {
1005 fn borrow<'a>(&'a self) -> &'a sty<'tcx> {
1010 pub fn type_has_params(ty: Ty) -> bool {
1011 ty.flags.intersects(HAS_PARAMS)
1013 pub fn type_has_self(ty: Ty) -> bool {
1014 ty.flags.intersects(HAS_SELF)
1016 pub fn type_has_ty_infer(ty: Ty) -> bool {
1017 ty.flags.intersects(HAS_TY_INFER)
1019 pub fn type_needs_infer(ty: Ty) -> bool {
1020 ty.flags.intersects(HAS_TY_INFER | HAS_RE_INFER)
1022 pub fn type_has_projection(ty: Ty) -> bool {
1023 ty.flags.intersects(HAS_PROJECTION)
1026 pub fn type_has_late_bound_regions(ty: Ty) -> bool {
1027 ty.flags.intersects(HAS_RE_LATE_BOUND)
1030 /// An "escaping region" is a bound region whose binder is not part of `t`.
1032 /// So, for example, consider a type like the following, which has two binders:
1034 /// for<'a> fn(x: for<'b> fn(&'a int, &'b int))
1035 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
1036 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
1038 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
1039 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
1040 /// fn type*, that type has an escaping region: `'a`.
1042 /// Note that what I'm calling an "escaping region" is often just called a "free region". However,
1043 /// we already use the term "free region". It refers to the regions that we use to represent bound
1044 /// regions on a fn definition while we are typechecking its body.
1046 /// To clarify, conceptually there is no particular difference between an "escaping" region and a
1047 /// "free" region. However, there is a big difference in practice. Basically, when "entering" a
1048 /// binding level, one is generally required to do some sort of processing to a bound region, such
1049 /// as replacing it with a fresh/skolemized region, or making an entry in the environment to
1050 /// represent the scope to which it is attached, etc. An escaping region represents a bound region
1051 /// for which this processing has not yet been done.
1052 pub fn type_has_escaping_regions(ty: Ty) -> bool {
1053 type_escapes_depth(ty, 0)
1056 pub fn type_escapes_depth(ty: Ty, depth: u32) -> bool {
1057 ty.region_depth > depth
1060 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1061 pub struct BareFnTy<'tcx> {
1062 pub unsafety: ast::Unsafety,
1064 pub sig: PolyFnSig<'tcx>,
1067 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1068 pub struct ClosureTy<'tcx> {
1069 pub unsafety: ast::Unsafety,
1071 pub sig: PolyFnSig<'tcx>,
1074 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1075 pub enum FnOutput<'tcx> {
1076 FnConverging(Ty<'tcx>),
1080 impl<'tcx> FnOutput<'tcx> {
1081 pub fn diverges(&self) -> bool {
1082 *self == FnDiverging
1085 pub fn unwrap(self) -> Ty<'tcx> {
1087 ty::FnConverging(t) => t,
1088 ty::FnDiverging => unreachable!()
1093 pub type PolyFnOutput<'tcx> = Binder<FnOutput<'tcx>>;
1095 impl<'tcx> PolyFnOutput<'tcx> {
1096 pub fn diverges(&self) -> bool {
1101 /// Signature of a function type, which I have arbitrarily
1102 /// decided to use to refer to the input/output types.
1104 /// - `inputs` is the list of arguments and their modes.
1105 /// - `output` is the return type.
1106 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
1107 #[derive(Clone, PartialEq, Eq, Hash)]
1108 pub struct FnSig<'tcx> {
1109 pub inputs: Vec<Ty<'tcx>>,
1110 pub output: FnOutput<'tcx>,
1114 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1116 impl<'tcx> PolyFnSig<'tcx> {
1117 pub fn inputs(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
1118 ty::Binder(self.0.inputs.clone())
1120 pub fn input(&self, index: uint) -> ty::Binder<Ty<'tcx>> {
1121 ty::Binder(self.0.inputs[index])
1123 pub fn output(&self) -> ty::Binder<FnOutput<'tcx>> {
1124 ty::Binder(self.0.output.clone())
1126 pub fn variadic(&self) -> bool {
1131 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1132 pub struct ParamTy {
1133 pub space: subst::ParamSpace,
1135 pub name: ast::Name,
1138 /// A [De Bruijn index][dbi] is a standard means of representing
1139 /// regions (and perhaps later types) in a higher-ranked setting. In
1140 /// particular, imagine a type like this:
1142 /// for<'a> fn(for<'b> fn(&'b int, &'a int), &'a char)
1145 /// | +------------+ 1 | |
1147 /// +--------------------------------+ 2 |
1149 /// +------------------------------------------+ 1
1151 /// In this type, there are two binders (the outer fn and the inner
1152 /// fn). We need to be able to determine, for any given region, which
1153 /// fn type it is bound by, the inner or the outer one. There are
1154 /// various ways you can do this, but a De Bruijn index is one of the
1155 /// more convenient and has some nice properties. The basic idea is to
1156 /// count the number of binders, inside out. Some examples should help
1157 /// clarify what I mean.
1159 /// Let's start with the reference type `&'b int` that is the first
1160 /// argument to the inner function. This region `'b` is assigned a De
1161 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
1162 /// fn). The region `'a` that appears in the second argument type (`&'a
1163 /// int`) would then be assigned a De Bruijn index of 2, meaning "the
1164 /// second-innermost binder". (These indices are written on the arrays
1165 /// in the diagram).
1167 /// What is interesting is that De Bruijn index attached to a particular
1168 /// variable will vary depending on where it appears. For example,
1169 /// the final type `&'a char` also refers to the region `'a` declared on
1170 /// the outermost fn. But this time, this reference is not nested within
1171 /// any other binders (i.e., it is not an argument to the inner fn, but
1172 /// rather the outer one). Therefore, in this case, it is assigned a
1173 /// De Bruijn index of 1, because the innermost binder in that location
1174 /// is the outer fn.
1176 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1177 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
1178 pub struct DebruijnIndex {
1179 // We maintain the invariant that this is never 0. So 1 indicates
1180 // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
1184 /// Representation of regions:
1185 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
1187 // Region bound in a type or fn declaration which will be
1188 // substituted 'early' -- that is, at the same time when type
1189 // parameters are substituted.
1190 ReEarlyBound(/* param id */ ast::NodeId,
1195 // Region bound in a function scope, which will be substituted when the
1196 // function is called.
1197 ReLateBound(DebruijnIndex, BoundRegion),
1199 /// When checking a function body, the types of all arguments and so forth
1200 /// that refer to bound region parameters are modified to refer to free
1201 /// region parameters.
1204 /// A concrete region naming some statically determined extent
1205 /// (e.g. an expression or sequence of statements) within the
1206 /// current function.
1207 ReScope(region::CodeExtent),
1209 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1212 /// A region variable. Should not exist after typeck.
1213 ReInfer(InferRegion),
1215 /// Empty lifetime is for data that is never accessed.
1216 /// Bottom in the region lattice. We treat ReEmpty somewhat
1217 /// specially; at least right now, we do not generate instances of
1218 /// it during the GLB computations, but rather
1219 /// generate an error instead. This is to improve error messages.
1220 /// The only way to get an instance of ReEmpty is to have a region
1221 /// variable with no constraints.
1225 /// Upvars do not get their own node-id. Instead, we use the pair of
1226 /// the original var id (that is, the root variable that is referenced
1227 /// by the upvar) and the id of the closure expression.
1228 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1229 pub struct UpvarId {
1230 pub var_id: ast::NodeId,
1231 pub closure_expr_id: ast::NodeId,
1234 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
1235 pub enum BorrowKind {
1236 /// Data must be immutable and is aliasable.
1239 /// Data must be immutable but not aliasable. This kind of borrow
1240 /// cannot currently be expressed by the user and is used only in
1241 /// implicit closure bindings. It is needed when you the closure
1242 /// is borrowing or mutating a mutable referent, e.g.:
1244 /// let x: &mut int = ...;
1245 /// let y = || *x += 5;
1247 /// If we were to try to translate this closure into a more explicit
1248 /// form, we'd encounter an error with the code as written:
1250 /// struct Env { x: & &mut int }
1251 /// let x: &mut int = ...;
1252 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
1253 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1255 /// This is then illegal because you cannot mutate a `&mut` found
1256 /// in an aliasable location. To solve, you'd have to translate with
1257 /// an `&mut` borrow:
1259 /// struct Env { x: & &mut int }
1260 /// let x: &mut int = ...;
1261 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
1262 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1264 /// Now the assignment to `**env.x` is legal, but creating a
1265 /// mutable pointer to `x` is not because `x` is not mutable. We
1266 /// could fix this by declaring `x` as `let mut x`. This is ok in
1267 /// user code, if awkward, but extra weird for closures, since the
1268 /// borrow is hidden.
1270 /// So we introduce a "unique imm" borrow -- the referent is
1271 /// immutable, but not aliasable. This solves the problem. For
1272 /// simplicity, we don't give users the way to express this
1273 /// borrow, it's just used when translating closures.
1276 /// Data is mutable and not aliasable.
1280 /// Information describing the capture of an upvar. This is computed
1281 /// during `typeck`, specifically by `regionck`.
1282 #[derive(PartialEq, Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1283 pub enum UpvarCapture {
1284 /// Upvar is captured by value. This is always true when the
1285 /// closure is labeled `move`, but can also be true in other cases
1286 /// depending on inference.
1289 /// Upvar is captured by reference.
1293 #[derive(PartialEq, Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1294 pub struct UpvarBorrow {
1295 /// The kind of borrow: by-ref upvars have access to shared
1296 /// immutable borrows, which are not part of the normal language
1298 pub kind: BorrowKind,
1300 /// Region of the resulting reference.
1301 pub region: ty::Region,
1304 pub type UpvarCaptureMap = FnvHashMap<UpvarId, UpvarCapture>;
1307 pub fn is_bound(&self) -> bool {
1309 ty::ReEarlyBound(..) => true,
1310 ty::ReLateBound(..) => true,
1315 pub fn escapes_depth(&self, depth: u32) -> bool {
1317 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1323 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1324 RustcEncodable, RustcDecodable, Debug, Copy)]
1325 /// A "free" region `fr` can be interpreted as "some region
1326 /// at least as big as the scope `fr.scope`".
1327 pub struct FreeRegion {
1328 pub scope: region::DestructionScopeData,
1329 pub bound_region: BoundRegion
1332 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1333 RustcEncodable, RustcDecodable, Debug, Copy)]
1334 pub enum BoundRegion {
1335 /// An anonymous region parameter for a given fn (&T)
1338 /// Named region parameters for functions (a in &'a T)
1340 /// The def-id is needed to distinguish free regions in
1341 /// the event of shadowing.
1342 BrNamed(ast::DefId, ast::Name),
1344 /// Fresh bound identifiers created during GLB computations.
1347 // Anonymous region for the implicit env pointer parameter
1352 // NB: If you change this, you'll probably want to change the corresponding
1353 // AST structure in libsyntax/ast.rs as well.
1354 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1355 pub enum sty<'tcx> {
1359 ty_uint(ast::UintTy),
1360 ty_float(ast::FloatTy),
1361 /// Substs here, possibly against intuition, *may* contain `ty_param`s.
1362 /// That is, even after substitution it is possible that there are type
1363 /// variables. This happens when the `ty_enum` corresponds to an enum
1364 /// definition and not a concrete use of it. To get the correct `ty_enum`
1365 /// from the tcx, use the `NodeId` from the `ast::Ty` and look it up in
1366 /// the `ast_ty_to_ty_cache`. This is probably true for `ty_struct` as
1368 ty_enum(DefId, &'tcx Substs<'tcx>),
1371 ty_vec(Ty<'tcx>, Option<uint>), // Second field is length.
1373 ty_rptr(&'tcx Region, mt<'tcx>),
1375 // If the def-id is Some(_), then this is the type of a specific
1376 // fn item. Otherwise, if None(_), it a fn pointer type.
1377 ty_bare_fn(Option<DefId>, &'tcx BareFnTy<'tcx>),
1379 ty_trait(Box<TyTrait<'tcx>>),
1380 ty_struct(DefId, &'tcx Substs<'tcx>),
1382 ty_closure(DefId, &'tcx Region, &'tcx Substs<'tcx>),
1384 ty_tup(Vec<Ty<'tcx>>),
1386 ty_projection(ProjectionTy<'tcx>),
1387 ty_param(ParamTy), // type parameter
1389 ty_open(Ty<'tcx>), // A deref'ed fat pointer, i.e., a dynamically sized value
1390 // and its size. Only ever used in trans. It is not necessary
1391 // earlier since we don't need to distinguish a DST with its
1392 // size (e.g., in a deref) vs a DST with the size elsewhere (
1393 // e.g., in a field).
1395 ty_infer(InferTy), // something used only during inference/typeck
1396 ty_err, // Also only used during inference/typeck, to represent
1397 // the type of an erroneous expression (helps cut down
1398 // on non-useful type error messages)
1401 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1402 pub struct TyTrait<'tcx> {
1403 pub principal: ty::PolyTraitRef<'tcx>,
1404 pub bounds: ExistentialBounds<'tcx>,
1407 impl<'tcx> TyTrait<'tcx> {
1408 pub fn principal_def_id(&self) -> ast::DefId {
1409 self.principal.0.def_id
1412 /// Object types don't have a self-type specified. Therefore, when
1413 /// we convert the principal trait-ref into a normal trait-ref,
1414 /// you must give *some* self-type. A common choice is `mk_err()`
1415 /// or some skolemized type.
1416 pub fn principal_trait_ref_with_self_ty(&self,
1419 -> ty::PolyTraitRef<'tcx>
1421 // otherwise the escaping regions would be captured by the binder
1422 assert!(!self_ty.has_escaping_regions());
1424 ty::Binder(Rc::new(ty::TraitRef {
1425 def_id: self.principal.0.def_id,
1426 substs: tcx.mk_substs(self.principal.0.substs.with_self_ty(self_ty)),
1430 pub fn projection_bounds_with_self_ty(&self,
1433 -> Vec<ty::PolyProjectionPredicate<'tcx>>
1435 // otherwise the escaping regions would be captured by the binders
1436 assert!(!self_ty.has_escaping_regions());
1438 self.bounds.projection_bounds.iter()
1439 .map(|in_poly_projection_predicate| {
1440 let in_projection_ty = &in_poly_projection_predicate.0.projection_ty;
1441 let substs = tcx.mk_substs(in_projection_ty.trait_ref.substs.with_self_ty(self_ty));
1443 Rc::new(ty::TraitRef::new(in_projection_ty.trait_ref.def_id,
1445 let projection_ty = ty::ProjectionTy {
1446 trait_ref: trait_ref,
1447 item_name: in_projection_ty.item_name
1449 ty::Binder(ty::ProjectionPredicate {
1450 projection_ty: projection_ty,
1451 ty: in_poly_projection_predicate.0.ty
1458 /// A complete reference to a trait. These take numerous guises in syntax,
1459 /// but perhaps the most recognizable form is in a where clause:
1463 /// This would be represented by a trait-reference where the def-id is the
1464 /// def-id for the trait `Foo` and the substs defines `T` as parameter 0 in the
1465 /// `SelfSpace` and `U` as parameter 0 in the `TypeSpace`.
1467 /// Trait references also appear in object types like `Foo<U>`, but in
1468 /// that case the `Self` parameter is absent from the substitutions.
1470 /// Note that a `TraitRef` introduces a level of region binding, to
1471 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
1472 /// U>` or higher-ranked object types.
1473 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1474 pub struct TraitRef<'tcx> {
1476 pub substs: &'tcx Substs<'tcx>,
1479 pub type PolyTraitRef<'tcx> = Binder<Rc<TraitRef<'tcx>>>;
1481 impl<'tcx> PolyTraitRef<'tcx> {
1482 pub fn self_ty(&self) -> Ty<'tcx> {
1486 pub fn def_id(&self) -> ast::DefId {
1490 pub fn substs(&self) -> &'tcx Substs<'tcx> {
1491 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
1495 pub fn input_types(&self) -> &[Ty<'tcx>] {
1496 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
1497 self.0.input_types()
1500 pub fn to_poly_trait_predicate(&self) -> PolyTraitPredicate<'tcx> {
1501 // Note that we preserve binding levels
1502 Binder(TraitPredicate { trait_ref: self.0.clone() })
1506 /// Binder is a binder for higher-ranked lifetimes. It is part of the
1507 /// compiler's representation for things like `for<'a> Fn(&'a int)`
1508 /// (which would be represented by the type `PolyTraitRef ==
1509 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
1510 /// erase, or otherwise "discharge" these bound regions, we change the
1511 /// type from `Binder<T>` to just `T` (see
1512 /// e.g. `liberate_late_bound_regions`).
1513 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1514 pub struct Binder<T>(pub T);
1516 #[derive(Clone, Copy, PartialEq)]
1517 pub enum IntVarValue {
1518 IntType(ast::IntTy),
1519 UintType(ast::UintTy),
1522 #[derive(Clone, Copy, Debug)]
1523 pub enum terr_vstore_kind {
1530 #[derive(Clone, Copy, Debug)]
1531 pub struct expected_found<T> {
1536 // Data structures used in type unification
1537 #[derive(Clone, Copy, Debug)]
1538 pub enum type_err<'tcx> {
1540 terr_unsafety_mismatch(expected_found<ast::Unsafety>),
1541 terr_abi_mismatch(expected_found<abi::Abi>),
1543 terr_box_mutability,
1544 terr_ptr_mutability,
1545 terr_ref_mutability,
1546 terr_vec_mutability,
1547 terr_tuple_size(expected_found<uint>),
1548 terr_fixed_array_size(expected_found<uint>),
1549 terr_ty_param_size(expected_found<uint>),
1551 terr_regions_does_not_outlive(Region, Region),
1552 terr_regions_not_same(Region, Region),
1553 terr_regions_no_overlap(Region, Region),
1554 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
1555 terr_regions_overly_polymorphic(BoundRegion, Region),
1556 terr_sorts(expected_found<Ty<'tcx>>),
1557 terr_integer_as_char,
1558 terr_int_mismatch(expected_found<IntVarValue>),
1559 terr_float_mismatch(expected_found<ast::FloatTy>),
1560 terr_traits(expected_found<ast::DefId>),
1561 terr_builtin_bounds(expected_found<BuiltinBounds>),
1562 terr_variadic_mismatch(expected_found<bool>),
1564 terr_convergence_mismatch(expected_found<bool>),
1565 terr_projection_name_mismatched(expected_found<ast::Name>),
1566 terr_projection_bounds_length(expected_found<uint>),
1569 /// Bounds suitable for a named type parameter like `A` in `fn foo<A>`
1570 /// as well as the existential type parameter in an object type.
1571 #[derive(PartialEq, Eq, Hash, Clone, Debug)]
1572 pub struct ParamBounds<'tcx> {
1573 pub region_bounds: Vec<ty::Region>,
1574 pub builtin_bounds: BuiltinBounds,
1575 pub trait_bounds: Vec<PolyTraitRef<'tcx>>,
1576 pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
1579 /// Bounds suitable for an existentially quantified type parameter
1580 /// such as those that appear in object types or closure types. The
1581 /// major difference between this case and `ParamBounds` is that
1582 /// general purpose trait bounds are omitted and there must be
1583 /// *exactly one* region.
1584 #[derive(PartialEq, Eq, Hash, Clone, Debug)]
1585 pub struct ExistentialBounds<'tcx> {
1586 pub region_bound: ty::Region,
1587 pub builtin_bounds: BuiltinBounds,
1588 pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
1591 pub type BuiltinBounds = EnumSet<BuiltinBound>;
1593 #[derive(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
1596 pub enum BuiltinBound {
1603 pub fn empty_builtin_bounds() -> BuiltinBounds {
1607 pub fn all_builtin_bounds() -> BuiltinBounds {
1608 let mut set = EnumSet::new();
1609 set.insert(BoundSend);
1610 set.insert(BoundSized);
1611 set.insert(BoundSync);
1615 /// An existential bound that does not implement any traits.
1616 pub fn region_existential_bound<'tcx>(r: ty::Region) -> ExistentialBounds<'tcx> {
1617 ty::ExistentialBounds { region_bound: r,
1618 builtin_bounds: empty_builtin_bounds(),
1619 projection_bounds: Vec::new() }
1622 impl CLike for BuiltinBound {
1623 fn to_usize(&self) -> uint {
1626 fn from_usize(v: uint) -> BuiltinBound {
1627 unsafe { mem::transmute(v) }
1631 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1636 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1641 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1642 pub struct FloatVid {
1646 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1647 pub struct RegionVid {
1651 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1657 /// A `FreshTy` is one that is generated as a replacement for an
1658 /// unbound type variable. This is convenient for caching etc. See
1659 /// `middle::infer::freshen` for more details.
1662 // FIXME -- once integral fallback is impl'd, we should remove
1663 // this type. It's only needed to prevent spurious errors for
1664 // integers whose type winds up never being constrained.
1668 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
1669 pub enum UnconstrainedNumeric {
1676 #[derive(Clone, RustcEncodable, RustcDecodable, Eq, Hash, Debug, Copy)]
1677 pub enum InferRegion {
1679 ReSkolemized(u32, BoundRegion)
1682 impl cmp::PartialEq for InferRegion {
1683 fn eq(&self, other: &InferRegion) -> bool {
1684 match ((*self), *other) {
1685 (ReVar(rva), ReVar(rvb)) => {
1688 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
1694 fn ne(&self, other: &InferRegion) -> bool {
1695 !((*self) == (*other))
1699 impl fmt::Debug for TyVid {
1700 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
1701 write!(f, "_#{}t", self.index)
1705 impl fmt::Debug for IntVid {
1706 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1707 write!(f, "_#{}i", self.index)
1711 impl fmt::Debug for FloatVid {
1712 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1713 write!(f, "_#{}f", self.index)
1717 impl fmt::Debug for RegionVid {
1718 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1719 write!(f, "'_#{}r", self.index)
1723 impl<'tcx> fmt::Debug for FnSig<'tcx> {
1724 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1725 write!(f, "({:?}; variadic: {})->{:?}", self.inputs, self.variadic, self.output)
1729 impl fmt::Debug for InferTy {
1730 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1732 TyVar(ref v) => v.fmt(f),
1733 IntVar(ref v) => v.fmt(f),
1734 FloatVar(ref v) => v.fmt(f),
1735 FreshTy(v) => write!(f, "FreshTy({:?})", v),
1736 FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
1741 impl fmt::Debug for IntVarValue {
1742 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1744 IntType(ref v) => v.fmt(f),
1745 UintType(ref v) => v.fmt(f),
1750 /// Default region to use for the bound of objects that are
1751 /// supplied as the value for this type parameter. This is derived
1752 /// from `T:'a` annotations appearing in the type definition. If
1753 /// this is `None`, then the default is inherited from the
1754 /// surrounding context. See RFC #599 for details.
1755 #[derive(Copy, Clone, Debug)]
1756 pub enum ObjectLifetimeDefault {
1757 /// Require an explicit annotation. Occurs when multiple
1758 /// `T:'a` constraints are found.
1761 /// Use the given region as the default.
1765 #[derive(Clone, Debug)]
1766 pub struct TypeParameterDef<'tcx> {
1767 pub name: ast::Name,
1768 pub def_id: ast::DefId,
1769 pub space: subst::ParamSpace,
1771 pub bounds: ParamBounds<'tcx>,
1772 pub default: Option<Ty<'tcx>>,
1773 pub object_lifetime_default: Option<ObjectLifetimeDefault>,
1776 #[derive(RustcEncodable, RustcDecodable, Clone, Debug)]
1777 pub struct RegionParameterDef {
1778 pub name: ast::Name,
1779 pub def_id: ast::DefId,
1780 pub space: subst::ParamSpace,
1782 pub bounds: Vec<ty::Region>,
1785 impl RegionParameterDef {
1786 pub fn to_early_bound_region(&self) -> ty::Region {
1787 ty::ReEarlyBound(self.def_id.node, self.space, self.index, self.name)
1791 /// Information about the formal type/lifetime parameters associated
1792 /// with an item or method. Analogous to ast::Generics.
1793 #[derive(Clone, Debug)]
1794 pub struct Generics<'tcx> {
1795 pub types: VecPerParamSpace<TypeParameterDef<'tcx>>,
1796 pub regions: VecPerParamSpace<RegionParameterDef>,
1799 impl<'tcx> Generics<'tcx> {
1800 pub fn empty() -> Generics<'tcx> {
1802 types: VecPerParamSpace::empty(),
1803 regions: VecPerParamSpace::empty(),
1807 pub fn is_empty(&self) -> bool {
1808 self.types.is_empty() && self.regions.is_empty()
1811 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
1812 !self.types.is_empty_in(space)
1815 pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
1816 !self.regions.is_empty_in(space)
1820 /// Bounds on generics.
1821 #[derive(Clone, Debug)]
1822 pub struct GenericPredicates<'tcx> {
1823 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
1826 impl<'tcx> GenericPredicates<'tcx> {
1827 pub fn empty() -> GenericPredicates<'tcx> {
1829 predicates: VecPerParamSpace::empty(),
1833 pub fn instantiate(&self, tcx: &ty::ctxt<'tcx>, substs: &Substs<'tcx>)
1834 -> InstantiatedPredicates<'tcx> {
1835 InstantiatedPredicates {
1836 predicates: self.predicates.subst(tcx, substs),
1841 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1842 pub enum Predicate<'tcx> {
1843 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
1844 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1845 /// would be the parameters in the `TypeSpace`.
1846 Trait(PolyTraitPredicate<'tcx>),
1848 /// where `T1 == T2`.
1849 Equate(PolyEquatePredicate<'tcx>),
1852 RegionOutlives(PolyRegionOutlivesPredicate),
1855 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1857 /// where <T as TraitRef>::Name == X, approximately.
1858 /// See `ProjectionPredicate` struct for details.
1859 Projection(PolyProjectionPredicate<'tcx>),
1862 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1863 pub struct TraitPredicate<'tcx> {
1864 pub trait_ref: Rc<TraitRef<'tcx>>
1866 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1868 impl<'tcx> TraitPredicate<'tcx> {
1869 pub fn def_id(&self) -> ast::DefId {
1870 self.trait_ref.def_id
1873 pub fn input_types(&self) -> &[Ty<'tcx>] {
1874 self.trait_ref.substs.types.as_slice()
1877 pub fn self_ty(&self) -> Ty<'tcx> {
1878 self.trait_ref.self_ty()
1882 impl<'tcx> PolyTraitPredicate<'tcx> {
1883 pub fn def_id(&self) -> ast::DefId {
1888 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1889 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
1890 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
1892 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1893 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
1894 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
1895 pub type PolyRegionOutlivesPredicate = PolyOutlivesPredicate<ty::Region, ty::Region>;
1896 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region>;
1898 /// This kind of predicate has no *direct* correspondent in the
1899 /// syntax, but it roughly corresponds to the syntactic forms:
1901 /// 1. `T : TraitRef<..., Item=Type>`
1902 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1904 /// In particular, form #1 is "desugared" to the combination of a
1905 /// normal trait predicate (`T : TraitRef<...>`) and one of these
1906 /// predicates. Form #2 is a broader form in that it also permits
1907 /// equality between arbitrary types. Processing an instance of Form
1908 /// #2 eventually yields one of these `ProjectionPredicate`
1909 /// instances to normalize the LHS.
1910 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1911 pub struct ProjectionPredicate<'tcx> {
1912 pub projection_ty: ProjectionTy<'tcx>,
1916 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1918 impl<'tcx> PolyProjectionPredicate<'tcx> {
1919 pub fn item_name(&self) -> ast::Name {
1920 self.0.projection_ty.item_name // safe to skip the binder to access a name
1923 pub fn sort_key(&self) -> (ast::DefId, ast::Name) {
1924 self.0.projection_ty.sort_key()
1928 /// Represents the projection of an associated type. In explicit UFCS
1929 /// form this would be written `<T as Trait<..>>::N`.
1930 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1931 pub struct ProjectionTy<'tcx> {
1932 /// The trait reference `T as Trait<..>`.
1933 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
1935 /// The name `N` of the associated type.
1936 pub item_name: ast::Name,
1939 impl<'tcx> ProjectionTy<'tcx> {
1940 pub fn sort_key(&self) -> (ast::DefId, ast::Name) {
1941 (self.trait_ref.def_id, self.item_name)
1945 pub trait ToPolyTraitRef<'tcx> {
1946 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1949 impl<'tcx> ToPolyTraitRef<'tcx> for Rc<TraitRef<'tcx>> {
1950 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1951 assert!(!self.has_escaping_regions());
1952 ty::Binder(self.clone())
1956 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1957 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1958 // We are just preserving the binder levels here
1959 ty::Binder(self.0.trait_ref.clone())
1963 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
1964 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1965 // Note: unlike with TraitRef::to_poly_trait_ref(),
1966 // self.0.trait_ref is permitted to have escaping regions.
1967 // This is because here `self` has a `Binder` and so does our
1968 // return value, so we are preserving the number of binding
1970 ty::Binder(self.0.projection_ty.trait_ref.clone())
1974 pub trait AsPredicate<'tcx> {
1975 fn as_predicate(&self) -> Predicate<'tcx>;
1978 impl<'tcx> AsPredicate<'tcx> for Rc<TraitRef<'tcx>> {
1979 fn as_predicate(&self) -> Predicate<'tcx> {
1980 // we're about to add a binder, so let's check that we don't
1981 // accidentally capture anything, or else that might be some
1982 // weird debruijn accounting.
1983 assert!(!self.has_escaping_regions());
1985 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1986 trait_ref: self.clone()
1991 impl<'tcx> AsPredicate<'tcx> for PolyTraitRef<'tcx> {
1992 fn as_predicate(&self) -> Predicate<'tcx> {
1993 ty::Predicate::Trait(self.to_poly_trait_predicate())
1997 impl<'tcx> AsPredicate<'tcx> for PolyEquatePredicate<'tcx> {
1998 fn as_predicate(&self) -> Predicate<'tcx> {
1999 Predicate::Equate(self.clone())
2003 impl<'tcx> AsPredicate<'tcx> for PolyRegionOutlivesPredicate {
2004 fn as_predicate(&self) -> Predicate<'tcx> {
2005 Predicate::RegionOutlives(self.clone())
2009 impl<'tcx> AsPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
2010 fn as_predicate(&self) -> Predicate<'tcx> {
2011 Predicate::TypeOutlives(self.clone())
2015 impl<'tcx> AsPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
2016 fn as_predicate(&self) -> Predicate<'tcx> {
2017 Predicate::Projection(self.clone())
2021 impl<'tcx> Predicate<'tcx> {
2022 /// Iterates over the types in this predicate. Note that in all
2023 /// cases this is skipping over a binder, so late-bound regions
2024 /// with depth 0 are bound by the predicate.
2025 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
2026 let vec: Vec<_> = match *self {
2027 ty::Predicate::Trait(ref data) => {
2028 data.0.trait_ref.substs.types.as_slice().to_vec()
2030 ty::Predicate::Equate(ty::Binder(ref data)) => {
2031 vec![data.0, data.1]
2033 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
2036 ty::Predicate::RegionOutlives(..) => {
2039 ty::Predicate::Projection(ref data) => {
2040 let trait_inputs = data.0.projection_ty.trait_ref.substs.types.as_slice();
2043 .chain(Some(data.0.ty).into_iter())
2048 // The only reason to collect into a vector here is that I was
2049 // too lazy to make the full (somewhat complicated) iterator
2050 // type that would be needed here. But I wanted this fn to
2051 // return an iterator conceptually, rather than a `Vec`, so as
2052 // to be closer to `Ty::walk`.
2056 pub fn has_escaping_regions(&self) -> bool {
2058 Predicate::Trait(ref trait_ref) => trait_ref.has_escaping_regions(),
2059 Predicate::Equate(ref p) => p.has_escaping_regions(),
2060 Predicate::RegionOutlives(ref p) => p.has_escaping_regions(),
2061 Predicate::TypeOutlives(ref p) => p.has_escaping_regions(),
2062 Predicate::Projection(ref p) => p.has_escaping_regions(),
2066 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
2068 Predicate::Trait(ref t) => {
2069 Some(t.to_poly_trait_ref())
2071 Predicate::Projection(..) |
2072 Predicate::Equate(..) |
2073 Predicate::RegionOutlives(..) |
2074 Predicate::TypeOutlives(..) => {
2081 /// Represents the bounds declared on a particular set of type
2082 /// parameters. Should eventually be generalized into a flag list of
2083 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
2084 /// `GenericPredicates` by using the `instantiate` method. Note that this method
2085 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
2086 /// the `GenericPredicates` are expressed in terms of the bound type
2087 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
2088 /// represented a set of bounds for some particular instantiation,
2089 /// meaning that the generic parameters have been substituted with
2094 /// struct Foo<T,U:Bar<T>> { ... }
2096 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
2097 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
2098 /// like `Foo<int,uint>`, then the `InstantiatedPredicates` would be `[[],
2099 /// [uint:Bar<int>]]`.
2100 #[derive(Clone, Debug)]
2101 pub struct InstantiatedPredicates<'tcx> {
2102 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
2105 impl<'tcx> InstantiatedPredicates<'tcx> {
2106 pub fn empty() -> InstantiatedPredicates<'tcx> {
2107 InstantiatedPredicates { predicates: VecPerParamSpace::empty() }
2110 pub fn has_escaping_regions(&self) -> bool {
2111 self.predicates.any(|p| p.has_escaping_regions())
2114 pub fn is_empty(&self) -> bool {
2115 self.predicates.is_empty()
2119 impl<'tcx> TraitRef<'tcx> {
2120 pub fn new(def_id: ast::DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
2121 TraitRef { def_id: def_id, substs: substs }
2124 pub fn self_ty(&self) -> Ty<'tcx> {
2125 self.substs.self_ty().unwrap()
2128 pub fn input_types(&self) -> &[Ty<'tcx>] {
2129 // Select only the "input types" from a trait-reference. For
2130 // now this is all the types that appear in the
2131 // trait-reference, but it should eventually exclude
2132 // associated types.
2133 self.substs.types.as_slice()
2137 /// When type checking, we use the `ParameterEnvironment` to track
2138 /// details about the type/lifetime parameters that are in scope.
2139 /// It primarily stores the bounds information.
2141 /// Note: This information might seem to be redundant with the data in
2142 /// `tcx.ty_param_defs`, but it is not. That table contains the
2143 /// parameter definitions from an "outside" perspective, but this
2144 /// struct will contain the bounds for a parameter as seen from inside
2145 /// the function body. Currently the only real distinction is that
2146 /// bound lifetime parameters are replaced with free ones, but in the
2147 /// future I hope to refine the representation of types so as to make
2148 /// more distinctions clearer.
2150 pub struct ParameterEnvironment<'a, 'tcx:'a> {
2151 pub tcx: &'a ctxt<'tcx>,
2153 /// See `construct_free_substs` for details.
2154 pub free_substs: Substs<'tcx>,
2156 /// Each type parameter has an implicit region bound that
2157 /// indicates it must outlive at least the function body (the user
2158 /// may specify stronger requirements). This field indicates the
2159 /// region of the callee.
2160 pub implicit_region_bound: ty::Region,
2162 /// Obligations that the caller must satisfy. This is basically
2163 /// the set of bounds on the in-scope type parameters, translated
2164 /// into Obligations.
2165 pub caller_bounds: Vec<ty::Predicate<'tcx>>,
2167 /// Caches the results of trait selection. This cache is used
2168 /// for things that have to do with the parameters in scope.
2169 pub selection_cache: traits::SelectionCache<'tcx>,
2172 impl<'a, 'tcx> ParameterEnvironment<'a, 'tcx> {
2173 pub fn with_caller_bounds(&self,
2174 caller_bounds: Vec<ty::Predicate<'tcx>>)
2175 -> ParameterEnvironment<'a,'tcx>
2177 ParameterEnvironment {
2179 free_substs: self.free_substs.clone(),
2180 implicit_region_bound: self.implicit_region_bound,
2181 caller_bounds: caller_bounds,
2182 selection_cache: traits::SelectionCache::new(),
2186 pub fn for_item(cx: &'a ctxt<'tcx>, id: NodeId) -> ParameterEnvironment<'a, 'tcx> {
2187 match cx.map.find(id) {
2188 Some(ast_map::NodeImplItem(ref impl_item)) => {
2190 ast::MethodImplItem(ref method) => {
2191 let method_def_id = ast_util::local_def(id);
2192 match ty::impl_or_trait_item(cx, method_def_id) {
2193 MethodTraitItem(ref method_ty) => {
2194 let method_generics = &method_ty.generics;
2195 let method_bounds = &method_ty.predicates;
2196 construct_parameter_environment(
2201 method.pe_body().id)
2203 TypeTraitItem(_) => {
2205 .bug("ParameterEnvironment::for_item(): \
2206 can't create a parameter environment \
2207 for type trait items")
2211 ast::TypeImplItem(_) => {
2212 cx.sess.bug("ParameterEnvironment::for_item(): \
2213 can't create a parameter environment \
2214 for type impl items")
2218 Some(ast_map::NodeTraitItem(trait_method)) => {
2219 match *trait_method {
2220 ast::RequiredMethod(ref required) => {
2221 cx.sess.span_bug(required.span,
2222 "ParameterEnvironment::for_item():
2223 can't create a parameter \
2224 environment for required trait \
2227 ast::ProvidedMethod(ref method) => {
2228 let method_def_id = ast_util::local_def(id);
2229 match ty::impl_or_trait_item(cx, method_def_id) {
2230 MethodTraitItem(ref method_ty) => {
2231 let method_generics = &method_ty.generics;
2232 let method_bounds = &method_ty.predicates;
2233 construct_parameter_environment(
2238 method.pe_body().id)
2240 TypeTraitItem(_) => {
2242 .bug("ParameterEnvironment::for_item(): \
2243 can't create a parameter environment \
2244 for type trait items")
2248 ast::TypeTraitItem(_) => {
2249 cx.sess.bug("ParameterEnvironment::from_item(): \
2250 can't create a parameter environment \
2251 for type trait items")
2255 Some(ast_map::NodeItem(item)) => {
2257 ast::ItemFn(_, _, _, _, ref body) => {
2258 // We assume this is a function.
2259 let fn_def_id = ast_util::local_def(id);
2260 let fn_scheme = lookup_item_type(cx, fn_def_id);
2261 let fn_predicates = lookup_predicates(cx, fn_def_id);
2263 construct_parameter_environment(cx,
2265 &fn_scheme.generics,
2270 ast::ItemStruct(..) |
2272 ast::ItemConst(..) |
2273 ast::ItemStatic(..) => {
2274 let def_id = ast_util::local_def(id);
2275 let scheme = lookup_item_type(cx, def_id);
2276 let predicates = lookup_predicates(cx, def_id);
2277 construct_parameter_environment(cx,
2284 cx.sess.span_bug(item.span,
2285 "ParameterEnvironment::from_item():
2286 can't create a parameter \
2287 environment for this kind of item")
2291 Some(ast_map::NodeExpr(..)) => {
2292 // This is a convenience to allow closures to work.
2293 ParameterEnvironment::for_item(cx, cx.map.get_parent(id))
2296 cx.sess.bug(&format!("ParameterEnvironment::from_item(): \
2297 `{}` is not an item",
2298 cx.map.node_to_string(id))[])
2304 /// A "type scheme", in ML terminology, is a type combined with some
2305 /// set of generic types that the type is, well, generic over. In Rust
2306 /// terms, it is the "type" of a fn item or struct -- this type will
2307 /// include various generic parameters that must be substituted when
2308 /// the item/struct is referenced. That is called converting the type
2309 /// scheme to a monotype.
2311 /// - `generics`: the set of type parameters and their bounds
2312 /// - `ty`: the base types, which may reference the parameters defined
2315 /// Note that TypeSchemes are also sometimes called "polytypes" (and
2316 /// in fact this struct used to carry that name, so you may find some
2317 /// stray references in a comment or something). We try to reserve the
2318 /// "poly" prefix to refer to higher-ranked things, as in
2321 /// Note that each item also comes with predicates, see
2322 /// `lookup_predicates`.
2323 #[derive(Clone, Debug)]
2324 pub struct TypeScheme<'tcx> {
2325 pub generics: Generics<'tcx>,
2329 /// As `TypeScheme` but for a trait ref.
2330 pub struct TraitDef<'tcx> {
2331 pub unsafety: ast::Unsafety,
2333 /// If `true`, then this trait had the `#[rustc_paren_sugar]`
2334 /// attribute, indicating that it should be used with `Foo()`
2335 /// sugar. This is a temporary thing -- eventually any trait wil
2336 /// be usable with the sugar (or without it).
2337 pub paren_sugar: bool,
2339 /// Generic type definitions. Note that `Self` is listed in here
2340 /// as having a single bound, the trait itself (e.g., in the trait
2341 /// `Eq`, there is a single bound `Self : Eq`). This is so that
2342 /// default methods get to assume that the `Self` parameters
2343 /// implements the trait.
2344 pub generics: Generics<'tcx>,
2346 /// The "supertrait" bounds.
2347 pub bounds: ParamBounds<'tcx>,
2349 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
2351 /// A list of the associated types defined in this trait. Useful
2352 /// for resolving `X::Foo` type markers.
2353 pub associated_type_names: Vec<ast::Name>,
2356 /// Records the substitutions used to translate the polytype for an
2357 /// item into the monotype of an item reference.
2359 pub struct ItemSubsts<'tcx> {
2360 pub substs: Substs<'tcx>,
2363 #[derive(Clone, Copy, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
2364 pub enum ClosureKind {
2371 pub fn trait_did(&self, cx: &ctxt) -> ast::DefId {
2372 let result = match *self {
2373 FnClosureKind => cx.lang_items.require(FnTraitLangItem),
2374 FnMutClosureKind => {
2375 cx.lang_items.require(FnMutTraitLangItem)
2377 FnOnceClosureKind => {
2378 cx.lang_items.require(FnOnceTraitLangItem)
2382 Ok(trait_did) => trait_did,
2383 Err(err) => cx.sess.fatal(&err[..]),
2388 pub trait ClosureTyper<'tcx> {
2389 fn tcx(&self) -> &ty::ctxt<'tcx> {
2390 self.param_env().tcx
2393 fn param_env<'a>(&'a self) -> &'a ty::ParameterEnvironment<'a, 'tcx>;
2395 /// Is this a `Fn`, `FnMut` or `FnOnce` closure? During typeck,
2396 /// returns `None` if the kind of this closure has not yet been
2398 fn closure_kind(&self,
2400 -> Option<ty::ClosureKind>;
2402 /// Returns the argument/return types of this closure.
2403 fn closure_type(&self,
2405 substs: &subst::Substs<'tcx>)
2406 -> ty::ClosureTy<'tcx>;
2408 /// Returns the set of all upvars and their transformed
2409 /// types. During typeck, maybe return `None` if the upvar types
2410 /// have not yet been inferred.
2411 fn closure_upvars(&self,
2413 substs: &Substs<'tcx>)
2414 -> Option<Vec<ClosureUpvar<'tcx>>>;
2417 impl<'tcx> CommonTypes<'tcx> {
2418 fn new(arena: &'tcx TypedArena<TyS<'tcx>>,
2419 interner: &mut FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>)
2420 -> CommonTypes<'tcx>
2423 bool: intern_ty(arena, interner, ty_bool),
2424 char: intern_ty(arena, interner, ty_char),
2425 err: intern_ty(arena, interner, ty_err),
2426 int: intern_ty(arena, interner, ty_int(ast::TyIs(false))),
2427 i8: intern_ty(arena, interner, ty_int(ast::TyI8)),
2428 i16: intern_ty(arena, interner, ty_int(ast::TyI16)),
2429 i32: intern_ty(arena, interner, ty_int(ast::TyI32)),
2430 i64: intern_ty(arena, interner, ty_int(ast::TyI64)),
2431 uint: intern_ty(arena, interner, ty_uint(ast::TyUs(false))),
2432 u8: intern_ty(arena, interner, ty_uint(ast::TyU8)),
2433 u16: intern_ty(arena, interner, ty_uint(ast::TyU16)),
2434 u32: intern_ty(arena, interner, ty_uint(ast::TyU32)),
2435 u64: intern_ty(arena, interner, ty_uint(ast::TyU64)),
2436 f32: intern_ty(arena, interner, ty_float(ast::TyF32)),
2437 f64: intern_ty(arena, interner, ty_float(ast::TyF64)),
2442 pub fn mk_ctxt<'tcx>(s: Session,
2443 arenas: &'tcx CtxtArenas<'tcx>,
2445 named_region_map: resolve_lifetime::NamedRegionMap,
2446 map: ast_map::Map<'tcx>,
2447 freevars: RefCell<FreevarMap>,
2448 region_maps: middle::region::RegionMaps,
2449 lang_items: middle::lang_items::LanguageItems,
2450 stability: stability::Index) -> ctxt<'tcx>
2452 let mut interner = FnvHashMap();
2453 let common_types = CommonTypes::new(&arenas.type_, &mut interner);
2457 interner: RefCell::new(interner),
2458 substs_interner: RefCell::new(FnvHashMap()),
2459 bare_fn_interner: RefCell::new(FnvHashMap()),
2460 region_interner: RefCell::new(FnvHashMap()),
2461 types: common_types,
2462 named_region_map: named_region_map,
2463 item_variance_map: RefCell::new(DefIdMap()),
2464 variance_computed: Cell::new(false),
2467 region_maps: region_maps,
2468 node_types: RefCell::new(FnvHashMap()),
2469 item_substs: RefCell::new(NodeMap()),
2470 trait_refs: RefCell::new(NodeMap()),
2471 trait_defs: RefCell::new(DefIdMap()),
2472 predicates: RefCell::new(DefIdMap()),
2473 object_cast_map: RefCell::new(NodeMap()),
2475 intrinsic_defs: RefCell::new(DefIdMap()),
2477 tcache: RefCell::new(DefIdMap()),
2478 rcache: RefCell::new(FnvHashMap()),
2479 short_names_cache: RefCell::new(FnvHashMap()),
2480 tc_cache: RefCell::new(FnvHashMap()),
2481 ast_ty_to_ty_cache: RefCell::new(NodeMap()),
2482 enum_var_cache: RefCell::new(DefIdMap()),
2483 impl_or_trait_items: RefCell::new(DefIdMap()),
2484 trait_item_def_ids: RefCell::new(DefIdMap()),
2485 trait_items_cache: RefCell::new(DefIdMap()),
2486 impl_trait_cache: RefCell::new(DefIdMap()),
2487 ty_param_defs: RefCell::new(NodeMap()),
2488 adjustments: RefCell::new(NodeMap()),
2489 normalized_cache: RefCell::new(FnvHashMap()),
2490 lang_items: lang_items,
2491 provided_method_sources: RefCell::new(DefIdMap()),
2492 struct_fields: RefCell::new(DefIdMap()),
2493 destructor_for_type: RefCell::new(DefIdMap()),
2494 destructors: RefCell::new(DefIdSet()),
2495 trait_impls: RefCell::new(DefIdMap()),
2496 inherent_impls: RefCell::new(DefIdMap()),
2497 impl_items: RefCell::new(DefIdMap()),
2498 used_unsafe: RefCell::new(NodeSet()),
2499 used_mut_nodes: RefCell::new(NodeSet()),
2500 populated_external_types: RefCell::new(DefIdSet()),
2501 populated_external_traits: RefCell::new(DefIdSet()),
2502 upvar_capture_map: RefCell::new(FnvHashMap()),
2503 extern_const_statics: RefCell::new(DefIdMap()),
2504 extern_const_variants: RefCell::new(DefIdMap()),
2505 method_map: RefCell::new(FnvHashMap()),
2506 dependency_formats: RefCell::new(FnvHashMap()),
2507 closure_kinds: RefCell::new(DefIdMap()),
2508 closure_tys: RefCell::new(DefIdMap()),
2509 node_lint_levels: RefCell::new(FnvHashMap()),
2510 transmute_restrictions: RefCell::new(Vec::new()),
2511 stability: RefCell::new(stability),
2512 associated_types: RefCell::new(DefIdMap()),
2513 selection_cache: traits::SelectionCache::new(),
2514 repr_hint_cache: RefCell::new(DefIdMap()),
2515 type_impls_copy_cache: RefCell::new(HashMap::new()),
2516 type_impls_sized_cache: RefCell::new(HashMap::new()),
2517 object_safety_cache: RefCell::new(DefIdMap()),
2518 const_qualif_map: RefCell::new(NodeMap()),
2522 // Type constructors
2524 impl<'tcx> ctxt<'tcx> {
2525 pub fn mk_substs(&self, substs: Substs<'tcx>) -> &'tcx Substs<'tcx> {
2526 if let Some(substs) = self.substs_interner.borrow().get(&substs) {
2530 let substs = self.arenas.substs.alloc(substs);
2531 self.substs_interner.borrow_mut().insert(substs, substs);
2535 pub fn mk_bare_fn(&self, bare_fn: BareFnTy<'tcx>) -> &'tcx BareFnTy<'tcx> {
2536 if let Some(bare_fn) = self.bare_fn_interner.borrow().get(&bare_fn) {
2540 let bare_fn = self.arenas.bare_fn.alloc(bare_fn);
2541 self.bare_fn_interner.borrow_mut().insert(bare_fn, bare_fn);
2545 pub fn mk_region(&self, region: Region) -> &'tcx Region {
2546 if let Some(region) = self.region_interner.borrow().get(®ion) {
2550 let region = self.arenas.region.alloc(region);
2551 self.region_interner.borrow_mut().insert(region, region);
2555 pub fn closure_kind(&self, def_id: ast::DefId) -> ty::ClosureKind {
2556 self.closure_kinds.borrow()[def_id]
2559 pub fn closure_type(&self,
2561 substs: &subst::Substs<'tcx>)
2562 -> ty::ClosureTy<'tcx>
2564 self.closure_tys.borrow()[def_id].subst(self, substs)
2568 // Interns a type/name combination, stores the resulting box in cx.interner,
2569 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
2570 pub fn mk_t<'tcx>(cx: &ctxt<'tcx>, st: sty<'tcx>) -> Ty<'tcx> {
2571 let mut interner = cx.interner.borrow_mut();
2572 intern_ty(&cx.arenas.type_, &mut *interner, st)
2575 fn intern_ty<'tcx>(type_arena: &'tcx TypedArena<TyS<'tcx>>,
2576 interner: &mut FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>,
2580 match interner.get(&st) {
2581 Some(ty) => return *ty,
2585 let flags = FlagComputation::for_sty(&st);
2588 () => type_arena.alloc(TyS { sty: st,
2590 region_depth: flags.depth, }),
2593 debug!("Interned type: {:?} Pointer: {:?}",
2594 ty, ty as *const _);
2596 interner.insert(InternedTy { ty: ty }, ty);
2601 struct FlagComputation {
2604 // maximum depth of any bound region that we have seen thus far
2608 impl FlagComputation {
2609 fn new() -> FlagComputation {
2610 FlagComputation { flags: NO_TYPE_FLAGS, depth: 0 }
2613 fn for_sty(st: &sty) -> FlagComputation {
2614 let mut result = FlagComputation::new();
2619 fn add_flags(&mut self, flags: TypeFlags) {
2620 self.flags = self.flags | flags;
2623 fn add_depth(&mut self, depth: u32) {
2624 if depth > self.depth {
2629 /// Adds the flags/depth from a set of types that appear within the current type, but within a
2631 fn add_bound_computation(&mut self, computation: &FlagComputation) {
2632 self.add_flags(computation.flags);
2634 // The types that contributed to `computation` occurred within
2635 // a region binder, so subtract one from the region depth
2636 // within when adding the depth to `self`.
2637 let depth = computation.depth;
2639 self.add_depth(depth - 1);
2643 fn add_sty(&mut self, st: &sty) {
2653 // You might think that we could just return ty_err for
2654 // any type containing ty_err as a component, and get
2655 // rid of the HAS_TY_ERR flag -- likewise for ty_bot (with
2656 // the exception of function types that return bot).
2657 // But doing so caused sporadic memory corruption, and
2658 // neither I (tjc) nor nmatsakis could figure out why,
2659 // so we're doing it this way.
2661 self.add_flags(HAS_TY_ERR)
2664 &ty_param(ref p) => {
2665 if p.space == subst::SelfSpace {
2666 self.add_flags(HAS_SELF);
2668 self.add_flags(HAS_PARAMS);
2672 &ty_closure(_, region, substs) => {
2673 self.add_region(*region);
2674 self.add_substs(substs);
2678 self.add_flags(HAS_TY_INFER)
2681 &ty_enum(_, substs) | &ty_struct(_, substs) => {
2682 self.add_substs(substs);
2685 &ty_projection(ref data) => {
2686 self.add_flags(HAS_PROJECTION);
2687 self.add_projection_ty(data);
2690 &ty_trait(box TyTrait { ref principal, ref bounds }) => {
2691 let mut computation = FlagComputation::new();
2692 computation.add_substs(principal.0.substs);
2693 for projection_bound in &bounds.projection_bounds {
2694 let mut proj_computation = FlagComputation::new();
2695 proj_computation.add_projection_predicate(&projection_bound.0);
2696 computation.add_bound_computation(&proj_computation);
2698 self.add_bound_computation(&computation);
2700 self.add_bounds(bounds);
2703 &ty_uniq(tt) | &ty_vec(tt, _) | &ty_open(tt) => {
2711 &ty_rptr(r, ref m) => {
2712 self.add_region(*r);
2716 &ty_tup(ref ts) => {
2717 self.add_tys(&ts[..]);
2720 &ty_bare_fn(_, ref f) => {
2721 self.add_fn_sig(&f.sig);
2726 fn add_ty(&mut self, ty: Ty) {
2727 self.add_flags(ty.flags);
2728 self.add_depth(ty.region_depth);
2731 fn add_tys(&mut self, tys: &[Ty]) {
2737 fn add_fn_sig(&mut self, fn_sig: &PolyFnSig) {
2738 let mut computation = FlagComputation::new();
2740 computation.add_tys(&fn_sig.0.inputs[]);
2742 if let ty::FnConverging(output) = fn_sig.0.output {
2743 computation.add_ty(output);
2746 self.add_bound_computation(&computation);
2749 fn add_region(&mut self, r: Region) {
2750 self.add_flags(HAS_REGIONS);
2752 ty::ReInfer(_) => { self.add_flags(HAS_RE_INFER); }
2753 ty::ReLateBound(debruijn, _) => {
2754 self.add_flags(HAS_RE_LATE_BOUND);
2755 self.add_depth(debruijn.depth);
2761 fn add_projection_predicate(&mut self, projection_predicate: &ProjectionPredicate) {
2762 self.add_projection_ty(&projection_predicate.projection_ty);
2763 self.add_ty(projection_predicate.ty);
2766 fn add_projection_ty(&mut self, projection_ty: &ProjectionTy) {
2767 self.add_substs(projection_ty.trait_ref.substs);
2770 fn add_substs(&mut self, substs: &Substs) {
2771 self.add_tys(substs.types.as_slice());
2772 match substs.regions {
2773 subst::ErasedRegions => {}
2774 subst::NonerasedRegions(ref regions) => {
2775 for &r in regions.iter() {
2782 fn add_bounds(&mut self, bounds: &ExistentialBounds) {
2783 self.add_region(bounds.region_bound);
2787 pub fn mk_mach_int<'tcx>(tcx: &ctxt<'tcx>, tm: ast::IntTy) -> Ty<'tcx> {
2789 ast::TyIs(_) => tcx.types.int,
2790 ast::TyI8 => tcx.types.i8,
2791 ast::TyI16 => tcx.types.i16,
2792 ast::TyI32 => tcx.types.i32,
2793 ast::TyI64 => tcx.types.i64,
2797 pub fn mk_mach_uint<'tcx>(tcx: &ctxt<'tcx>, tm: ast::UintTy) -> Ty<'tcx> {
2799 ast::TyUs(_) => tcx.types.uint,
2800 ast::TyU8 => tcx.types.u8,
2801 ast::TyU16 => tcx.types.u16,
2802 ast::TyU32 => tcx.types.u32,
2803 ast::TyU64 => tcx.types.u64,
2807 pub fn mk_mach_float<'tcx>(tcx: &ctxt<'tcx>, tm: ast::FloatTy) -> Ty<'tcx> {
2809 ast::TyF32 => tcx.types.f32,
2810 ast::TyF64 => tcx.types.f64,
2814 pub fn mk_str<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2818 pub fn mk_str_slice<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, m: ast::Mutability) -> Ty<'tcx> {
2821 ty: mk_t(cx, ty_str),
2826 pub fn mk_enum<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
2827 // take a copy of substs so that we own the vectors inside
2828 mk_t(cx, ty_enum(did, substs))
2831 pub fn mk_uniq<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { mk_t(cx, ty_uniq(ty)) }
2833 pub fn mk_ptr<'tcx>(cx: &ctxt<'tcx>, tm: mt<'tcx>) -> Ty<'tcx> { mk_t(cx, ty_ptr(tm)) }
2835 pub fn mk_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, tm: mt<'tcx>) -> Ty<'tcx> {
2836 mk_t(cx, ty_rptr(r, tm))
2839 pub fn mk_mut_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
2840 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
2842 pub fn mk_imm_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
2843 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
2846 pub fn mk_mut_ptr<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2847 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
2850 pub fn mk_imm_ptr<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2851 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
2854 pub fn mk_nil_ptr<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2855 mk_ptr(cx, mt {ty: mk_nil(cx), mutbl: ast::MutImmutable})
2858 pub fn mk_vec<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>, sz: Option<uint>) -> Ty<'tcx> {
2859 mk_t(cx, ty_vec(ty, sz))
2862 pub fn mk_slice<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, tm: mt<'tcx>) -> Ty<'tcx> {
2865 ty: mk_vec(cx, tm.ty, None),
2870 pub fn mk_tup<'tcx>(cx: &ctxt<'tcx>, ts: Vec<Ty<'tcx>>) -> Ty<'tcx> {
2871 mk_t(cx, ty_tup(ts))
2874 pub fn mk_nil<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2875 mk_tup(cx, Vec::new())
2878 pub fn mk_bare_fn<'tcx>(cx: &ctxt<'tcx>,
2879 opt_def_id: Option<ast::DefId>,
2880 fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
2881 mk_t(cx, ty_bare_fn(opt_def_id, fty))
2884 pub fn mk_ctor_fn<'tcx>(cx: &ctxt<'tcx>,
2886 input_tys: &[Ty<'tcx>],
2887 output: Ty<'tcx>) -> Ty<'tcx> {
2888 let input_args = input_tys.iter().cloned().collect();
2891 cx.mk_bare_fn(BareFnTy {
2892 unsafety: ast::Unsafety::Normal,
2894 sig: ty::Binder(FnSig {
2896 output: ty::FnConverging(output),
2902 pub fn mk_trait<'tcx>(cx: &ctxt<'tcx>,
2903 principal: ty::PolyTraitRef<'tcx>,
2904 bounds: ExistentialBounds<'tcx>)
2907 assert!(bound_list_is_sorted(&bounds.projection_bounds));
2909 let inner = box TyTrait {
2910 principal: principal,
2913 mk_t(cx, ty_trait(inner))
2916 fn bound_list_is_sorted(bounds: &[ty::PolyProjectionPredicate]) -> bool {
2917 bounds.len() == 0 ||
2918 bounds[1..].iter().enumerate().all(
2919 |(index, bound)| bounds[index].sort_key() <= bound.sort_key())
2922 pub fn sort_bounds_list(bounds: &mut [ty::PolyProjectionPredicate]) {
2923 bounds.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()))
2926 pub fn mk_projection<'tcx>(cx: &ctxt<'tcx>,
2927 trait_ref: Rc<ty::TraitRef<'tcx>>,
2928 item_name: ast::Name)
2930 // take a copy of substs so that we own the vectors inside
2931 let inner = ProjectionTy { trait_ref: trait_ref, item_name: item_name };
2932 mk_t(cx, ty_projection(inner))
2935 pub fn mk_struct<'tcx>(cx: &ctxt<'tcx>, struct_id: ast::DefId,
2936 substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
2937 // take a copy of substs so that we own the vectors inside
2938 mk_t(cx, ty_struct(struct_id, substs))
2941 pub fn mk_closure<'tcx>(cx: &ctxt<'tcx>, closure_id: ast::DefId,
2942 region: &'tcx Region, substs: &'tcx Substs<'tcx>)
2944 mk_t(cx, ty_closure(closure_id, region, substs))
2947 pub fn mk_var<'tcx>(cx: &ctxt<'tcx>, v: TyVid) -> Ty<'tcx> {
2948 mk_infer(cx, TyVar(v))
2951 pub fn mk_int_var<'tcx>(cx: &ctxt<'tcx>, v: IntVid) -> Ty<'tcx> {
2952 mk_infer(cx, IntVar(v))
2955 pub fn mk_float_var<'tcx>(cx: &ctxt<'tcx>, v: FloatVid) -> Ty<'tcx> {
2956 mk_infer(cx, FloatVar(v))
2959 pub fn mk_infer<'tcx>(cx: &ctxt<'tcx>, it: InferTy) -> Ty<'tcx> {
2960 mk_t(cx, ty_infer(it))
2963 pub fn mk_param<'tcx>(cx: &ctxt<'tcx>,
2964 space: subst::ParamSpace,
2966 name: ast::Name) -> Ty<'tcx> {
2967 mk_t(cx, ty_param(ParamTy { space: space, idx: index, name: name }))
2970 pub fn mk_self_type<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2971 mk_param(cx, subst::SelfSpace, 0, special_idents::type_self.name)
2974 pub fn mk_param_from_def<'tcx>(cx: &ctxt<'tcx>, def: &TypeParameterDef) -> Ty<'tcx> {
2975 mk_param(cx, def.space, def.index, def.name)
2978 pub fn mk_open<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { mk_t(cx, ty_open(ty)) }
2980 impl<'tcx> TyS<'tcx> {
2981 /// Iterator that walks `self` and any types reachable from
2982 /// `self`, in depth-first order. Note that just walks the types
2983 /// that appear in `self`, it does not descend into the fields of
2984 /// structs or variants. For example:
2988 /// Foo<Bar<int>> => { Foo<Bar<int>>, Bar<int>, int }
2989 /// [int] => { [int], int }
2991 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2992 TypeWalker::new(self)
2995 /// Iterator that walks types reachable from `self`, in
2996 /// depth-first order. Note that this is a shallow walk. For
3001 /// Foo<Bar<int>> => { Bar<int>, int }
3002 /// [int] => { int }
3004 pub fn walk_children(&'tcx self) -> TypeWalker<'tcx> {
3005 // Walks type reachable from `self` but not `self
3006 let mut walker = self.walk();
3007 let r = walker.next();
3008 assert_eq!(r, Some(self));
3012 pub fn as_opt_param_ty(&self) -> Option<ty::ParamTy> {
3014 ty::ty_param(ref d) => Some(d.clone()),
3020 pub fn walk_ty<'tcx, F>(ty_root: Ty<'tcx>, mut f: F)
3021 where F: FnMut(Ty<'tcx>),
3023 for ty in ty_root.walk() {
3028 /// Walks `ty` and any types appearing within `ty`, invoking the
3029 /// callback `f` on each type. If the callback returns false, then the
3030 /// children of the current type are ignored.
3032 /// Note: prefer `ty.walk()` where possible.
3033 pub fn maybe_walk_ty<'tcx,F>(ty_root: Ty<'tcx>, mut f: F)
3034 where F : FnMut(Ty<'tcx>) -> bool
3036 let mut walker = ty_root.walk();
3037 while let Some(ty) = walker.next() {
3039 walker.skip_current_subtree();
3044 // Folds types from the bottom up.
3045 pub fn fold_ty<'tcx, F>(cx: &ctxt<'tcx>, t0: Ty<'tcx>,
3048 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
3050 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
3055 pub fn new(space: subst::ParamSpace,
3059 ParamTy { space: space, idx: index, name: name }
3062 pub fn for_self() -> ParamTy {
3063 ParamTy::new(subst::SelfSpace, 0, special_idents::type_self.name)
3066 pub fn for_def(def: &TypeParameterDef) -> ParamTy {
3067 ParamTy::new(def.space, def.index, def.name)
3070 pub fn to_ty<'tcx>(self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx> {
3071 ty::mk_param(tcx, self.space, self.idx, self.name)
3074 pub fn is_self(&self) -> bool {
3075 self.space == subst::SelfSpace && self.idx == 0
3079 impl<'tcx> ItemSubsts<'tcx> {
3080 pub fn empty() -> ItemSubsts<'tcx> {
3081 ItemSubsts { substs: Substs::empty() }
3084 pub fn is_noop(&self) -> bool {
3085 self.substs.is_noop()
3089 impl<'tcx> ParamBounds<'tcx> {
3090 pub fn empty() -> ParamBounds<'tcx> {
3092 builtin_bounds: empty_builtin_bounds(),
3093 trait_bounds: Vec::new(),
3094 region_bounds: Vec::new(),
3095 projection_bounds: Vec::new(),
3102 pub fn type_is_nil(ty: Ty) -> bool {
3104 ty_tup(ref tys) => tys.is_empty(),
3109 pub fn type_is_error(ty: Ty) -> bool {
3110 ty.flags.intersects(HAS_TY_ERR)
3113 pub fn type_needs_subst(ty: Ty) -> bool {
3114 ty.flags.intersects(NEEDS_SUBST)
3117 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
3118 tref.substs.types.any(|&ty| type_is_error(ty))
3121 pub fn type_is_ty_var(ty: Ty) -> bool {
3123 ty_infer(TyVar(_)) => true,
3128 pub fn type_is_bool(ty: Ty) -> bool { ty.sty == ty_bool }
3130 pub fn type_is_self(ty: Ty) -> bool {
3132 ty_param(ref p) => p.space == subst::SelfSpace,
3137 fn type_is_slice(ty: Ty) -> bool {
3139 ty_ptr(mt) | ty_rptr(_, mt) => match mt.ty.sty {
3140 ty_vec(_, None) | ty_str => true,
3147 pub fn type_is_vec(ty: Ty) -> bool {
3150 ty_ptr(mt{ty, ..}) | ty_rptr(_, mt{ty, ..}) |
3151 ty_uniq(ty) => match ty.sty {
3152 ty_vec(_, None) => true,
3159 pub fn type_is_structural(ty: Ty) -> bool {
3161 ty_struct(..) | ty_tup(_) | ty_enum(..) |
3162 ty_vec(_, Some(_)) | ty_closure(..) => true,
3163 _ => type_is_slice(ty) | type_is_trait(ty)
3167 pub fn type_is_simd(cx: &ctxt, ty: Ty) -> bool {
3169 ty_struct(did, _) => lookup_simd(cx, did),
3174 pub fn sequence_element_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
3176 ty_vec(ty, _) => ty,
3177 ty_str => mk_mach_uint(cx, ast::TyU8),
3178 ty_open(ty) => sequence_element_type(cx, ty),
3179 _ => cx.sess.bug(&format!("sequence_element_type called on non-sequence value: {}",
3180 ty_to_string(cx, ty))[]),
3184 pub fn simd_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
3186 ty_struct(did, substs) => {
3187 let fields = lookup_struct_fields(cx, did);
3188 lookup_field_type(cx, did, fields[0].id, substs)
3190 _ => panic!("simd_type called on invalid type")
3194 pub fn simd_size(cx: &ctxt, ty: Ty) -> uint {
3196 ty_struct(did, _) => {
3197 let fields = lookup_struct_fields(cx, did);
3200 _ => panic!("simd_size called on invalid type")
3204 pub fn type_is_region_ptr(ty: Ty) -> bool {
3206 ty_rptr(..) => true,
3211 pub fn type_is_unsafe_ptr(ty: Ty) -> bool {
3213 ty_ptr(_) => return true,
3218 pub fn type_is_unique(ty: Ty) -> bool {
3226 A scalar type is one that denotes an atomic datum, with no sub-components.
3227 (A ty_ptr is scalar because it represents a non-managed pointer, so its
3228 contents are abstract to rustc.)
3230 pub fn type_is_scalar(ty: Ty) -> bool {
3232 ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
3233 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
3234 ty_bare_fn(..) | ty_ptr(_) => true,
3239 /// Returns true if this type is a floating point type and false otherwise.
3240 pub fn type_is_floating_point(ty: Ty) -> bool {
3242 ty_float(_) => true,
3247 /// Type contents is how the type checker reasons about kinds.
3248 /// They track what kinds of things are found within a type. You can
3249 /// think of them as kind of an "anti-kind". They track the kinds of values
3250 /// and thinks that are contained in types. Having a larger contents for
3251 /// a type tends to rule that type *out* from various kinds. For example,
3252 /// a type that contains a reference is not sendable.
3254 /// The reason we compute type contents and not kinds is that it is
3255 /// easier for me (nmatsakis) to think about what is contained within
3256 /// a type than to think about what is *not* contained within a type.
3257 #[derive(Clone, Copy)]
3258 pub struct TypeContents {
3262 macro_rules! def_type_content_sets {
3263 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
3264 #[allow(non_snake_case)]
3266 use middle::ty::TypeContents;
3268 #[allow(non_upper_case_globals)]
3269 pub const $name: TypeContents = TypeContents { bits: $bits };
3275 def_type_content_sets! {
3277 None = 0b0000_0000__0000_0000__0000,
3279 // Things that are interior to the value (first nibble):
3280 InteriorUnsized = 0b0000_0000__0000_0000__0001,
3281 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
3282 InteriorParam = 0b0000_0000__0000_0000__0100,
3283 // InteriorAll = 0b00000000__00000000__1111,
3285 // Things that are owned by the value (second and third nibbles):
3286 OwnsOwned = 0b0000_0000__0000_0001__0000,
3287 OwnsDtor = 0b0000_0000__0000_0010__0000,
3288 OwnsManaged /* see [1] below */ = 0b0000_0000__0000_0100__0000,
3289 OwnsAll = 0b0000_0000__1111_1111__0000,
3291 // Things that are reachable by the value in any way (fourth nibble):
3292 ReachesBorrowed = 0b0000_0010__0000_0000__0000,
3293 // ReachesManaged /* see [1] below */ = 0b0000_0100__0000_0000__0000,
3294 ReachesMutable = 0b0000_1000__0000_0000__0000,
3295 ReachesFfiUnsafe = 0b0010_0000__0000_0000__0000,
3296 ReachesAll = 0b0011_1111__0000_0000__0000,
3298 // Things that mean drop glue is necessary
3299 NeedsDrop = 0b0000_0000__0000_0111__0000,
3301 // Things that prevent values from being considered sized
3302 Nonsized = 0b0000_0000__0000_0000__0001,
3304 // Bits to set when a managed value is encountered
3306 // [1] Do not set the bits TC::OwnsManaged or
3307 // TC::ReachesManaged directly, instead reference
3308 // TC::Managed to set them both at once.
3309 Managed = 0b0000_0100__0000_0100__0000,
3312 All = 0b1111_1111__1111_1111__1111
3317 pub fn when(&self, cond: bool) -> TypeContents {
3318 if cond {*self} else {TC::None}
3321 pub fn intersects(&self, tc: TypeContents) -> bool {
3322 (self.bits & tc.bits) != 0
3325 pub fn owns_managed(&self) -> bool {
3326 self.intersects(TC::OwnsManaged)
3329 pub fn owns_owned(&self) -> bool {
3330 self.intersects(TC::OwnsOwned)
3333 pub fn is_sized(&self, _: &ctxt) -> bool {
3334 !self.intersects(TC::Nonsized)
3337 pub fn interior_param(&self) -> bool {
3338 self.intersects(TC::InteriorParam)
3341 pub fn interior_unsafe(&self) -> bool {
3342 self.intersects(TC::InteriorUnsafe)
3345 pub fn interior_unsized(&self) -> bool {
3346 self.intersects(TC::InteriorUnsized)
3349 pub fn needs_drop(&self, _: &ctxt) -> bool {
3350 self.intersects(TC::NeedsDrop)
3353 /// Includes only those bits that still apply when indirected through a `Box` pointer
3354 pub fn owned_pointer(&self) -> TypeContents {
3356 *self & (TC::OwnsAll | TC::ReachesAll))
3359 /// Includes only those bits that still apply when indirected through a reference (`&`)
3360 pub fn reference(&self, bits: TypeContents) -> TypeContents {
3362 *self & TC::ReachesAll)
3365 /// Includes only those bits that still apply when indirected through a managed pointer (`@`)
3366 pub fn managed_pointer(&self) -> TypeContents {
3368 *self & TC::ReachesAll)
3371 /// Includes only those bits that still apply when indirected through an unsafe pointer (`*`)
3372 pub fn unsafe_pointer(&self) -> TypeContents {
3373 *self & TC::ReachesAll
3376 pub fn union<T, F>(v: &[T], mut f: F) -> TypeContents where
3377 F: FnMut(&T) -> TypeContents,
3379 v.iter().fold(TC::None, |tc, ty| tc | f(ty))
3382 pub fn has_dtor(&self) -> bool {
3383 self.intersects(TC::OwnsDtor)
3387 impl ops::BitOr for TypeContents {
3388 type Output = TypeContents;
3390 fn bitor(self, other: TypeContents) -> TypeContents {
3391 TypeContents {bits: self.bits | other.bits}
3395 impl ops::BitAnd for TypeContents {
3396 type Output = TypeContents;
3398 fn bitand(self, other: TypeContents) -> TypeContents {
3399 TypeContents {bits: self.bits & other.bits}
3403 impl ops::Sub for TypeContents {
3404 type Output = TypeContents;
3406 fn sub(self, other: TypeContents) -> TypeContents {
3407 TypeContents {bits: self.bits & !other.bits}
3411 impl fmt::Debug for TypeContents {
3412 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3413 write!(f, "TypeContents({:b})", self.bits)
3417 pub fn type_interior_is_unsafe<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
3418 type_contents(cx, ty).interior_unsafe()
3421 pub fn type_contents<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> TypeContents {
3422 return memoized(&cx.tc_cache, ty, |ty| {
3423 tc_ty(cx, ty, &mut FnvHashMap())
3426 fn tc_ty<'tcx>(cx: &ctxt<'tcx>,
3428 cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
3430 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
3431 // private cache for this walk. This is needed in the case of cyclic
3434 // struct List { next: Box<Option<List>>, ... }
3436 // When computing the type contents of such a type, we wind up deeply
3437 // recursing as we go. So when we encounter the recursive reference
3438 // to List, we temporarily use TC::None as its contents. Later we'll
3439 // patch up the cache with the correct value, once we've computed it
3440 // (this is basically a co-inductive process, if that helps). So in
3441 // the end we'll compute TC::OwnsOwned, in this case.
3443 // The problem is, as we are doing the computation, we will also
3444 // compute an *intermediate* contents for, e.g., Option<List> of
3445 // TC::None. This is ok during the computation of List itself, but if
3446 // we stored this intermediate value into cx.tc_cache, then later
3447 // requests for the contents of Option<List> would also yield TC::None
3448 // which is incorrect. This value was computed based on the crutch
3449 // value for the type contents of list. The correct value is
3450 // TC::OwnsOwned. This manifested as issue #4821.
3451 match cache.get(&ty) {
3452 Some(tc) => { return *tc; }
3455 match cx.tc_cache.borrow().get(&ty) { // Must check both caches!
3456 Some(tc) => { return *tc; }
3459 cache.insert(ty, TC::None);
3461 let result = match ty.sty {
3462 // uint and int are ffi-unsafe
3463 ty_uint(ast::TyUs(_)) | ty_int(ast::TyIs(_)) => {
3464 TC::ReachesFfiUnsafe
3467 // Scalar and unique types are sendable, and durable
3468 ty_infer(ty::FreshIntTy(_)) |
3469 ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
3470 ty_bare_fn(..) | ty::ty_char => {
3475 TC::ReachesFfiUnsafe | match typ.sty {
3476 ty_str => TC::OwnsOwned,
3477 _ => tc_ty(cx, typ, cache).owned_pointer(),
3481 ty_trait(box TyTrait { ref bounds, .. }) => {
3482 object_contents(bounds) | TC::ReachesFfiUnsafe | TC::Nonsized
3486 tc_ty(cx, mt.ty, cache).unsafe_pointer()
3489 ty_rptr(r, ref mt) => {
3490 TC::ReachesFfiUnsafe | match mt.ty.sty {
3491 ty_str => borrowed_contents(*r, ast::MutImmutable),
3492 ty_vec(..) => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(*r,
3494 _ => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(*r, mt.mutbl)),
3498 ty_vec(ty, Some(_)) => {
3499 tc_ty(cx, ty, cache)
3502 ty_vec(ty, None) => {
3503 tc_ty(cx, ty, cache) | TC::Nonsized
3505 ty_str => TC::Nonsized,
3507 ty_struct(did, substs) => {
3508 let flds = struct_fields(cx, did, substs);
3510 TypeContents::union(&flds[..],
3511 |f| tc_mt(cx, f.mt, cache));
3513 if !lookup_repr_hints(cx, did).contains(&attr::ReprExtern) {
3514 res = res | TC::ReachesFfiUnsafe;
3517 if ty::has_dtor(cx, did) {
3518 res = res | TC::OwnsDtor;
3520 apply_lang_items(cx, did, res)
3523 ty_closure(did, r, substs) => {
3524 // FIXME(#14449): `borrowed_contents` below assumes `&mut` closure.
3525 let param_env = ty::empty_parameter_environment(cx);
3526 let upvars = closure_upvars(¶m_env, did, substs).unwrap();
3527 TypeContents::union(&upvars,
3528 |f| tc_ty(cx, &f.ty, cache))
3529 | borrowed_contents(*r, MutMutable)
3532 ty_tup(ref tys) => {
3533 TypeContents::union(&tys[..],
3534 |ty| tc_ty(cx, *ty, cache))
3537 ty_enum(did, substs) => {
3538 let variants = substd_enum_variants(cx, did, substs);
3540 TypeContents::union(&variants[..], |variant| {
3541 TypeContents::union(&variant.args[],
3543 tc_ty(cx, *arg_ty, cache)
3547 if ty::has_dtor(cx, did) {
3548 res = res | TC::OwnsDtor;
3551 if variants.len() != 0 {
3552 let repr_hints = lookup_repr_hints(cx, did);
3553 if repr_hints.len() > 1 {
3554 // this is an error later on, but this type isn't safe
3555 res = res | TC::ReachesFfiUnsafe;
3558 match repr_hints.get(0) {
3559 Some(h) => if !h.is_ffi_safe() {
3560 res = res | TC::ReachesFfiUnsafe;
3564 res = res | TC::ReachesFfiUnsafe;
3566 // We allow ReprAny enums if they are eligible for
3567 // the nullable pointer optimization and the
3568 // contained type is an `extern fn`
3570 if variants.len() == 2 {
3571 let mut data_idx = 0;
3573 if variants[0].args.len() == 0 {
3577 if variants[data_idx].args.len() == 1 {
3578 match variants[data_idx].args[0].sty {
3579 ty_bare_fn(..) => { res = res - TC::ReachesFfiUnsafe; }
3589 apply_lang_items(cx, did, res)
3598 let result = tc_ty(cx, ty, cache);
3599 assert!(!result.is_sized(cx));
3600 result.unsafe_pointer() | TC::Nonsized
3605 cx.sess.bug("asked to compute contents of error type");
3609 cache.insert(ty, result);
3613 fn tc_mt<'tcx>(cx: &ctxt<'tcx>,
3615 cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
3617 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
3618 mc | tc_ty(cx, mt.ty, cache)
3621 fn apply_lang_items(cx: &ctxt, did: ast::DefId, tc: TypeContents)
3623 if Some(did) == cx.lang_items.managed_bound() {
3625 } else if Some(did) == cx.lang_items.unsafe_cell_type() {
3626 tc | TC::InteriorUnsafe
3632 /// Type contents due to containing a reference with the region `region` and borrow kind `bk`
3633 fn borrowed_contents(region: ty::Region,
3634 mutbl: ast::Mutability)
3636 let b = match mutbl {
3637 ast::MutMutable => TC::ReachesMutable,
3638 ast::MutImmutable => TC::None,
3640 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
3643 fn object_contents(bounds: &ExistentialBounds) -> TypeContents {
3644 // These are the type contents of the (opaque) interior. We
3645 // make no assumptions (other than that it cannot have an
3646 // in-scope type parameter within, which makes no sense).
3647 let mut tc = TC::All - TC::InteriorParam;
3648 for bound in &bounds.builtin_bounds {
3649 tc = tc - match bound {
3650 BoundSync | BoundSend | BoundCopy => TC::None,
3651 BoundSized => TC::Nonsized,
3658 fn type_impls_bound<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>,
3659 cache: &RefCell<HashMap<Ty<'tcx>,bool>>,
3661 bound: ty::BuiltinBound,
3665 assert!(!ty::type_needs_infer(ty));
3667 if !type_has_params(ty) && !type_has_self(ty) {
3668 match cache.borrow().get(&ty) {
3671 debug!("type_impls_bound({}, {:?}) = {:?} (cached)",
3672 ty.repr(param_env.tcx),
3680 let infcx = infer::new_infer_ctxt(param_env.tcx);
3682 let is_impld = traits::type_known_to_meet_builtin_bound(&infcx, param_env, ty, bound, span);
3684 debug!("type_impls_bound({}, {:?}) = {:?}",
3685 ty.repr(param_env.tcx),
3689 if !type_has_params(ty) && !type_has_self(ty) {
3690 let old_value = cache.borrow_mut().insert(ty, is_impld);
3691 assert!(old_value.is_none());
3697 pub fn type_moves_by_default<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>,
3702 let tcx = param_env.tcx;
3703 !type_impls_bound(param_env, &tcx.type_impls_copy_cache, ty, ty::BoundCopy, span)
3706 pub fn type_is_sized<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>,
3711 let tcx = param_env.tcx;
3712 type_impls_bound(param_env, &tcx.type_impls_sized_cache, ty, ty::BoundSized, span)
3715 pub fn is_ffi_safe<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
3716 !type_contents(cx, ty).intersects(TC::ReachesFfiUnsafe)
3719 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
3720 pub fn is_instantiable<'tcx>(cx: &ctxt<'tcx>, r_ty: Ty<'tcx>) -> bool {
3721 fn type_requires<'tcx>(cx: &ctxt<'tcx>, seen: &mut Vec<DefId>,
3722 r_ty: Ty<'tcx>, ty: Ty<'tcx>) -> bool {
3723 debug!("type_requires({:?}, {:?})?",
3724 ::util::ppaux::ty_to_string(cx, r_ty),
3725 ::util::ppaux::ty_to_string(cx, ty));
3727 let r = r_ty == ty || subtypes_require(cx, seen, r_ty, ty);
3729 debug!("type_requires({:?}, {:?})? {:?}",
3730 ::util::ppaux::ty_to_string(cx, r_ty),
3731 ::util::ppaux::ty_to_string(cx, ty),
3736 fn subtypes_require<'tcx>(cx: &ctxt<'tcx>, seen: &mut Vec<DefId>,
3737 r_ty: Ty<'tcx>, ty: Ty<'tcx>) -> bool {
3738 debug!("subtypes_require({:?}, {:?})?",
3739 ::util::ppaux::ty_to_string(cx, r_ty),
3740 ::util::ppaux::ty_to_string(cx, ty));
3742 let r = match ty.sty {
3743 // fixed length vectors need special treatment compared to
3744 // normal vectors, since they don't necessarily have the
3745 // possibility to have length zero.
3746 ty_vec(_, Some(0)) => false, // don't need no contents
3747 ty_vec(ty, Some(_)) => type_requires(cx, seen, r_ty, ty),
3758 ty_vec(_, None) => {
3761 ty_uniq(typ) | ty_open(typ) => {
3762 type_requires(cx, seen, r_ty, typ)
3764 ty_rptr(_, ref mt) => {
3765 type_requires(cx, seen, r_ty, mt.ty)
3769 false // unsafe ptrs can always be NULL
3776 ty_struct(ref did, _) if seen.contains(did) => {
3780 ty_struct(did, substs) => {
3782 let fields = struct_fields(cx, did, substs);
3783 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
3784 seen.pop().unwrap();
3791 // this check is run on type definitions, so we don't expect to see
3792 // inference by-products or closure types
3793 cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
3797 ts.iter().any(|ty| type_requires(cx, seen, r_ty, *ty))
3800 ty_enum(ref did, _) if seen.contains(did) => {
3804 ty_enum(did, substs) => {
3806 let vs = enum_variants(cx, did);
3807 let r = !vs.is_empty() && vs.iter().all(|variant| {
3808 variant.args.iter().any(|aty| {
3809 let sty = aty.subst(cx, substs);
3810 type_requires(cx, seen, r_ty, sty)
3813 seen.pop().unwrap();
3818 debug!("subtypes_require({:?}, {:?})? {:?}",
3819 ::util::ppaux::ty_to_string(cx, r_ty),
3820 ::util::ppaux::ty_to_string(cx, ty),
3826 let mut seen = Vec::new();
3827 !subtypes_require(cx, &mut seen, r_ty, r_ty)
3830 /// Describes whether a type is representable. For types that are not
3831 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
3832 /// distinguish between types that are recursive with themselves and types that
3833 /// contain a different recursive type. These cases can therefore be treated
3834 /// differently when reporting errors.
3836 /// The ordering of the cases is significant. They are sorted so that cmp::max
3837 /// will keep the "more erroneous" of two values.
3838 #[derive(Copy, PartialOrd, Ord, Eq, PartialEq, Debug)]
3839 pub enum Representability {
3845 /// Check whether a type is representable. This means it cannot contain unboxed
3846 /// structural recursion. This check is needed for structs and enums.
3847 pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>)
3848 -> Representability {
3850 // Iterate until something non-representable is found
3851 fn find_nonrepresentable<'tcx, It: Iterator<Item=Ty<'tcx>>>(cx: &ctxt<'tcx>, sp: Span,
3852 seen: &mut Vec<Ty<'tcx>>,
3854 -> Representability {
3855 iter.fold(Representable,
3856 |r, ty| cmp::max(r, is_type_structurally_recursive(cx, sp, seen, ty)))
3859 fn are_inner_types_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
3860 seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
3861 -> Representability {
3864 find_nonrepresentable(cx, sp, seen, ts.iter().cloned())
3866 // Fixed-length vectors.
3867 // FIXME(#11924) Behavior undecided for zero-length vectors.
3868 ty_vec(ty, Some(_)) => {
3869 is_type_structurally_recursive(cx, sp, seen, ty)
3871 ty_struct(did, substs) => {
3872 let fields = struct_fields(cx, did, substs);
3873 find_nonrepresentable(cx, sp, seen, fields.iter().map(|f| f.mt.ty))
3875 ty_enum(did, substs) => {
3876 let vs = enum_variants(cx, did);
3877 let iter = vs.iter()
3878 .flat_map(|variant| { variant.args.iter() })
3879 .map(|aty| { aty.subst_spanned(cx, substs, Some(sp)) });
3881 find_nonrepresentable(cx, sp, seen, iter)
3884 // this check is run on type definitions, so we don't expect
3885 // to see closure types
3886 cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
3892 fn same_struct_or_enum_def_id(ty: Ty, did: DefId) -> bool {
3894 ty_struct(ty_did, _) | ty_enum(ty_did, _) => {
3901 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
3902 match (&a.sty, &b.sty) {
3903 (&ty_struct(did_a, ref substs_a), &ty_struct(did_b, ref substs_b)) |
3904 (&ty_enum(did_a, ref substs_a), &ty_enum(did_b, ref substs_b)) => {
3909 let types_a = substs_a.types.get_slice(subst::TypeSpace);
3910 let types_b = substs_b.types.get_slice(subst::TypeSpace);
3912 let pairs = types_a.iter().zip(types_b.iter());
3914 pairs.all(|(&a, &b)| same_type(a, b))
3922 // Does the type `ty` directly (without indirection through a pointer)
3923 // contain any types on stack `seen`?
3924 fn is_type_structurally_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
3925 seen: &mut Vec<Ty<'tcx>>,
3926 ty: Ty<'tcx>) -> Representability {
3927 debug!("is_type_structurally_recursive: {:?}",
3928 ::util::ppaux::ty_to_string(cx, ty));
3931 ty_struct(did, _) | ty_enum(did, _) => {
3933 // Iterate through stack of previously seen types.
3934 let mut iter = seen.iter();
3936 // The first item in `seen` is the type we are actually curious about.
3937 // We want to return SelfRecursive if this type contains itself.
3938 // It is important that we DON'T take generic parameters into account
3939 // for this check, so that Bar<T> in this example counts as SelfRecursive:
3942 // struct Bar<T> { x: Bar<Foo> }
3945 Some(&seen_type) => {
3946 if same_struct_or_enum_def_id(seen_type, did) {
3947 debug!("SelfRecursive: {:?} contains {:?}",
3948 ::util::ppaux::ty_to_string(cx, seen_type),
3949 ::util::ppaux::ty_to_string(cx, ty));
3950 return SelfRecursive;
3956 // We also need to know whether the first item contains other types that
3957 // are structurally recursive. If we don't catch this case, we will recurse
3958 // infinitely for some inputs.
3960 // It is important that we DO take generic parameters into account here,
3961 // so that code like this is considered SelfRecursive, not ContainsRecursive:
3963 // struct Foo { Option<Option<Foo>> }
3965 for &seen_type in iter {
3966 if same_type(ty, seen_type) {
3967 debug!("ContainsRecursive: {:?} contains {:?}",
3968 ::util::ppaux::ty_to_string(cx, seen_type),
3969 ::util::ppaux::ty_to_string(cx, ty));
3970 return ContainsRecursive;
3975 // For structs and enums, track all previously seen types by pushing them
3976 // onto the 'seen' stack.
3978 let out = are_inner_types_recursive(cx, sp, seen, ty);
3983 // No need to push in other cases.
3984 are_inner_types_recursive(cx, sp, seen, ty)
3989 debug!("is_type_representable: {:?}",
3990 ::util::ppaux::ty_to_string(cx, ty));
3992 // To avoid a stack overflow when checking an enum variant or struct that
3993 // contains a different, structurally recursive type, maintain a stack
3994 // of seen types and check recursion for each of them (issues #3008, #3779).
3995 let mut seen: Vec<Ty> = Vec::new();
3996 let r = is_type_structurally_recursive(cx, sp, &mut seen, ty);
3997 debug!("is_type_representable: {:?} is {:?}",
3998 ::util::ppaux::ty_to_string(cx, ty), r);
4002 pub fn type_is_trait(ty: Ty) -> bool {
4003 type_trait_info(ty).is_some()
4006 pub fn type_trait_info<'tcx>(ty: Ty<'tcx>) -> Option<&'tcx TyTrait<'tcx>> {
4008 ty_uniq(ty) | ty_rptr(_, mt { ty, ..}) | ty_ptr(mt { ty, ..}) => match ty.sty {
4009 ty_trait(ref t) => Some(&**t),
4012 ty_trait(ref t) => Some(&**t),
4017 pub fn type_is_integral(ty: Ty) -> bool {
4019 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
4024 pub fn type_is_fresh(ty: Ty) -> bool {
4026 ty_infer(FreshTy(_)) => true,
4027 ty_infer(FreshIntTy(_)) => true,
4032 pub fn type_is_uint(ty: Ty) -> bool {
4034 ty_infer(IntVar(_)) | ty_uint(ast::TyUs(_)) => true,
4039 pub fn type_is_char(ty: Ty) -> bool {
4046 pub fn type_is_bare_fn(ty: Ty) -> bool {
4048 ty_bare_fn(..) => true,
4053 pub fn type_is_bare_fn_item(ty: Ty) -> bool {
4055 ty_bare_fn(Some(_), _) => true,
4060 pub fn type_is_fp(ty: Ty) -> bool {
4062 ty_infer(FloatVar(_)) | ty_float(_) => true,
4067 pub fn type_is_numeric(ty: Ty) -> bool {
4068 return type_is_integral(ty) || type_is_fp(ty);
4071 pub fn type_is_signed(ty: Ty) -> bool {
4078 pub fn type_is_machine(ty: Ty) -> bool {
4080 ty_int(ast::TyIs(_)) | ty_uint(ast::TyUs(_)) => false,
4081 ty_int(..) | ty_uint(..) | ty_float(..) => true,
4086 // Whether a type is enum like, that is an enum type with only nullary
4088 pub fn type_is_c_like_enum(cx: &ctxt, ty: Ty) -> bool {
4090 ty_enum(did, _) => {
4091 let variants = enum_variants(cx, did);
4092 if variants.len() == 0 {
4095 variants.iter().all(|v| v.args.len() == 0)
4102 // Returns the type and mutability of *ty.
4104 // The parameter `explicit` indicates if this is an *explicit* dereference.
4105 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
4106 pub fn deref<'tcx>(ty: Ty<'tcx>, explicit: bool) -> Option<mt<'tcx>> {
4111 mutbl: ast::MutImmutable,
4114 ty_rptr(_, mt) => Some(mt),
4115 ty_ptr(mt) if explicit => Some(mt),
4120 pub fn close_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
4122 ty_open(ty) => mk_rptr(cx, cx.mk_region(ReStatic), mt {ty: ty, mutbl:ast::MutImmutable}),
4123 _ => cx.sess.bug(&format!("Trying to close a non-open type {}",
4124 ty_to_string(cx, ty))[])
4128 pub fn type_content<'tcx>(ty: Ty<'tcx>) -> Ty<'tcx> {
4131 ty_rptr(_, mt) |ty_ptr(mt) => mt.ty,
4136 // Extract the unsized type in an open type (or just return ty if it is not open).
4137 pub fn unopen_type<'tcx>(ty: Ty<'tcx>) -> Ty<'tcx> {
4144 // Returns the type of ty[i]
4145 pub fn index<'tcx>(ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
4147 ty_vec(ty, _) => Some(ty),
4152 // Returns the type of elements contained within an 'array-like' type.
4153 // This is exactly the same as the above, except it supports strings,
4154 // which can't actually be indexed.
4155 pub fn array_element_ty<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
4157 ty_vec(ty, _) => Some(ty),
4158 ty_str => Some(tcx.types.u8),
4163 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
4164 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
4165 pub fn positional_element_ty<'tcx>(cx: &ctxt<'tcx>,
4168 variant: Option<ast::DefId>) -> Option<Ty<'tcx>> {
4170 match (&ty.sty, variant) {
4171 (&ty_tup(ref v), None) => v.get(i).cloned(),
4174 (&ty_struct(def_id, substs), None) => lookup_struct_fields(cx, def_id)
4176 .map(|&t|lookup_item_type(cx, t.id).ty.subst(cx, substs)),
4178 (&ty_enum(def_id, substs), Some(variant_def_id)) => {
4179 let variant_info = enum_variant_with_id(cx, def_id, variant_def_id);
4180 variant_info.args.get(i).map(|t|t.subst(cx, substs))
4183 (&ty_enum(def_id, substs), None) => {
4184 assert!(enum_is_univariant(cx, def_id));
4185 let enum_variants = enum_variants(cx, def_id);
4186 let variant_info = &(*enum_variants)[0];
4187 variant_info.args.get(i).map(|t|t.subst(cx, substs))
4194 /// Returns the type of element at field `n` in struct or struct-like type `t`.
4195 /// For an enum `t`, `variant` must be some def id.
4196 pub fn named_element_ty<'tcx>(cx: &ctxt<'tcx>,
4199 variant: Option<ast::DefId>) -> Option<Ty<'tcx>> {
4201 match (&ty.sty, variant) {
4202 (&ty_struct(def_id, substs), None) => {
4203 let r = lookup_struct_fields(cx, def_id);
4204 r.iter().find(|f| f.name == n)
4205 .map(|&f| lookup_field_type(cx, def_id, f.id, substs))
4207 (&ty_enum(def_id, substs), Some(variant_def_id)) => {
4208 let variant_info = enum_variant_with_id(cx, def_id, variant_def_id);
4209 variant_info.arg_names.as_ref()
4210 .expect("must have struct enum variant if accessing a named fields")
4211 .iter().zip(variant_info.args.iter())
4212 .find(|&(ident, _)| ident.name == n)
4213 .map(|(_ident, arg_t)| arg_t.subst(cx, substs))
4219 pub fn node_id_to_trait_ref<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId)
4220 -> Rc<ty::TraitRef<'tcx>> {
4221 match cx.trait_refs.borrow().get(&id) {
4222 Some(ty) => ty.clone(),
4223 None => cx.sess.bug(
4224 &format!("node_id_to_trait_ref: no trait ref for node `{}`",
4225 cx.map.node_to_string(id))[])
4229 pub fn node_id_to_type<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> Ty<'tcx> {
4230 match node_id_to_type_opt(cx, id) {
4232 None => cx.sess.bug(
4233 &format!("node_id_to_type: no type for node `{}`",
4234 cx.map.node_to_string(id))[])
4238 pub fn node_id_to_type_opt<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> Option<Ty<'tcx>> {
4239 match cx.node_types.borrow().get(&id) {
4240 Some(&ty) => Some(ty),
4245 pub fn node_id_item_substs<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> ItemSubsts<'tcx> {
4246 match cx.item_substs.borrow().get(&id) {
4247 None => ItemSubsts::empty(),
4248 Some(ts) => ts.clone(),
4252 pub fn fn_is_variadic(fty: Ty) -> bool {
4254 ty_bare_fn(_, ref f) => f.sig.0.variadic,
4256 panic!("fn_is_variadic() called on non-fn type: {:?}", s)
4261 pub fn ty_fn_sig<'tcx>(fty: Ty<'tcx>) -> &'tcx PolyFnSig<'tcx> {
4263 ty_bare_fn(_, ref f) => &f.sig,
4265 panic!("ty_fn_sig() called on non-fn type: {:?}", s)
4270 /// Returns the ABI of the given function.
4271 pub fn ty_fn_abi(fty: Ty) -> abi::Abi {
4273 ty_bare_fn(_, ref f) => f.abi,
4274 _ => panic!("ty_fn_abi() called on non-fn type"),
4278 // Type accessors for substructures of types
4279 pub fn ty_fn_args<'tcx>(fty: Ty<'tcx>) -> ty::Binder<Vec<Ty<'tcx>>> {
4280 ty_fn_sig(fty).inputs()
4283 pub fn ty_fn_ret<'tcx>(fty: Ty<'tcx>) -> Binder<FnOutput<'tcx>> {
4285 ty_bare_fn(_, ref f) => f.sig.output(),
4287 panic!("ty_fn_ret() called on non-fn type: {:?}", s)
4292 pub fn is_fn_ty(fty: Ty) -> bool {
4294 ty_bare_fn(..) => true,
4299 pub fn ty_region(tcx: &ctxt,
4303 ty_rptr(r, _) => *r,
4307 &format!("ty_region() invoked on an inappropriate ty: {:?}",
4313 pub fn free_region_from_def(outlives_extent: region::DestructionScopeData,
4314 def: &RegionParameterDef)
4318 ty::ReFree(ty::FreeRegion { scope: outlives_extent,
4319 bound_region: ty::BrNamed(def.def_id,
4321 debug!("free_region_from_def returns {:?}", ret);
4325 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
4326 // doesn't provide type parameter substitutions.
4327 pub fn pat_ty<'tcx>(cx: &ctxt<'tcx>, pat: &ast::Pat) -> Ty<'tcx> {
4328 return node_id_to_type(cx, pat.id);
4332 // Returns the type of an expression as a monotype.
4334 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
4335 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
4336 // auto-ref. The type returned by this function does not consider such
4337 // adjustments. See `expr_ty_adjusted()` instead.
4339 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
4340 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
4341 // instead of "fn(ty) -> T with T = int".
4342 pub fn expr_ty<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Ty<'tcx> {
4343 return node_id_to_type(cx, expr.id);
4346 pub fn expr_ty_opt<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Option<Ty<'tcx>> {
4347 return node_id_to_type_opt(cx, expr.id);
4350 /// Returns the type of `expr`, considering any `AutoAdjustment`
4351 /// entry recorded for that expression.
4353 /// It would almost certainly be better to store the adjusted ty in with
4354 /// the `AutoAdjustment`, but I opted not to do this because it would
4355 /// require serializing and deserializing the type and, although that's not
4356 /// hard to do, I just hate that code so much I didn't want to touch it
4357 /// unless it was to fix it properly, which seemed a distraction from the
4358 /// task at hand! -nmatsakis
4359 pub fn expr_ty_adjusted<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Ty<'tcx> {
4360 adjust_ty(cx, expr.span, expr.id, expr_ty(cx, expr),
4361 cx.adjustments.borrow().get(&expr.id),
4362 |method_call| cx.method_map.borrow().get(&method_call).map(|method| method.ty))
4365 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
4366 match cx.map.find(id) {
4367 Some(ast_map::NodeExpr(e)) => {
4371 cx.sess.bug(&format!("Node id {} is not an expr: {:?}",
4376 cx.sess.bug(&format!("Node id {} is not present \
4377 in the node map", id)[]);
4382 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
4383 match cx.map.find(id) {
4384 Some(ast_map::NodeLocal(pat)) => {
4386 ast::PatIdent(_, ref path1, _) => {
4387 token::get_ident(path1.node)
4391 &format!("Variable id {} maps to {:?}, not local",
4398 cx.sess.bug(&format!("Variable id {} maps to {:?}, not local",
4405 /// See `expr_ty_adjusted`
4406 pub fn adjust_ty<'tcx, F>(cx: &ctxt<'tcx>,
4408 expr_id: ast::NodeId,
4409 unadjusted_ty: Ty<'tcx>,
4410 adjustment: Option<&AutoAdjustment<'tcx>>,
4413 F: FnMut(MethodCall) -> Option<Ty<'tcx>>,
4415 if let ty_err = unadjusted_ty.sty {
4416 return unadjusted_ty;
4419 return match adjustment {
4420 Some(adjustment) => {
4422 AdjustReifyFnPointer(_) => {
4423 match unadjusted_ty.sty {
4424 ty::ty_bare_fn(Some(_), b) => {
4425 ty::mk_bare_fn(cx, None, b)
4429 &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
4436 AdjustDerefRef(ref adj) => {
4437 let mut adjusted_ty = unadjusted_ty;
4439 if !ty::type_is_error(adjusted_ty) {
4440 for i in 0..adj.autoderefs {
4441 let method_call = MethodCall::autoderef(expr_id, i);
4442 match method_type(method_call) {
4443 Some(method_ty) => {
4444 // overloaded deref operators have all late-bound
4445 // regions fully instantiated and coverge
4447 ty::no_late_bound_regions(cx,
4448 &ty_fn_ret(method_ty)).unwrap();
4449 adjusted_ty = fn_ret.unwrap();
4453 match deref(adjusted_ty, true) {
4454 Some(mt) => { adjusted_ty = mt.ty; }
4458 &format!("the {}th autoderef failed: \
4461 ty_to_string(cx, adjusted_ty))
4468 adjust_ty_for_autoref(cx, span, adjusted_ty, adj.autoref.as_ref())
4472 None => unadjusted_ty
4476 pub fn adjust_ty_for_autoref<'tcx>(cx: &ctxt<'tcx>,
4479 autoref: Option<&AutoRef<'tcx>>)
4485 Some(&AutoPtr(r, m, ref a)) => {
4486 let adjusted_ty = match a {
4487 &Some(box ref a) => adjust_ty_for_autoref(cx, span, ty, Some(a)),
4490 mk_rptr(cx, cx.mk_region(r), mt {
4496 Some(&AutoUnsafe(m, ref a)) => {
4497 let adjusted_ty = match a {
4498 &Some(box ref a) => adjust_ty_for_autoref(cx, span, ty, Some(a)),
4501 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
4504 Some(&AutoUnsize(ref k)) => unsize_ty(cx, ty, k, span),
4506 Some(&AutoUnsizeUniq(ref k)) => ty::mk_uniq(cx, unsize_ty(cx, ty, k, span)),
4510 // Take a sized type and a sizing adjustment and produce an unsized version of
4512 pub fn unsize_ty<'tcx>(cx: &ctxt<'tcx>,
4514 kind: &UnsizeKind<'tcx>,
4518 &UnsizeLength(len) => match ty.sty {
4519 ty_vec(ty, Some(n)) => {
4521 mk_vec(cx, ty, None)
4523 _ => cx.sess.span_bug(span,
4524 &format!("UnsizeLength with bad sty: {:?}",
4525 ty_to_string(cx, ty))[])
4527 &UnsizeStruct(box ref k, tp_index) => match ty.sty {
4528 ty_struct(did, substs) => {
4529 let ty_substs = substs.types.get_slice(subst::TypeSpace);
4530 let new_ty = unsize_ty(cx, ty_substs[tp_index], k, span);
4531 let mut unsized_substs = substs.clone();
4532 unsized_substs.types.get_mut_slice(subst::TypeSpace)[tp_index] = new_ty;
4533 mk_struct(cx, did, cx.mk_substs(unsized_substs))
4535 _ => cx.sess.span_bug(span,
4536 &format!("UnsizeStruct with bad sty: {:?}",
4537 ty_to_string(cx, ty))[])
4539 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
4540 mk_trait(cx, principal.clone(), bounds.clone())
4545 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> def::Def {
4546 match tcx.def_map.borrow().get(&expr.id) {
4549 tcx.sess.span_bug(expr.span, &format!(
4550 "no def-map entry for expr {}", expr.id)[]);
4555 pub fn expr_is_lval(tcx: &ctxt, e: &ast::Expr) -> bool {
4556 match expr_kind(tcx, e) {
4558 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
4562 /// We categorize expressions into three kinds. The distinction between
4563 /// lvalue/rvalue is fundamental to the language. The distinction between the
4564 /// two kinds of rvalues is an artifact of trans which reflects how we will
4565 /// generate code for that kind of expression. See trans/expr.rs for more
4575 pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
4576 if tcx.method_map.borrow().contains_key(&MethodCall::expr(expr.id)) {
4577 // Overloaded operations are generally calls, and hence they are
4578 // generated via DPS, but there are a few exceptions:
4579 return match expr.node {
4580 // `a += b` has a unit result.
4581 ast::ExprAssignOp(..) => RvalueStmtExpr,
4583 // the deref method invoked for `*a` always yields an `&T`
4584 ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
4586 // the index method invoked for `a[i]` always yields an `&T`
4587 ast::ExprIndex(..) => LvalueExpr,
4589 // in the general case, result could be any type, use DPS
4595 ast::ExprPath(_) | ast::ExprQPath(_) => {
4596 match resolve_expr(tcx, expr) {
4597 def::DefVariant(tid, vid, _) => {
4598 let variant_info = enum_variant_with_id(tcx, tid, vid);
4599 if variant_info.args.len() > 0 {
4608 def::DefStruct(_) => {
4609 match tcx.node_types.borrow().get(&expr.id) {
4610 Some(ty) => match ty.sty {
4611 ty_bare_fn(..) => RvalueDatumExpr,
4614 // See ExprCast below for why types might be missing.
4615 None => RvalueDatumExpr
4619 // Special case: A unit like struct's constructor must be called without () at the
4620 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
4621 // of unit structs this is should not be interpreted as function pointer but as
4622 // call to the constructor.
4623 def::DefFn(_, true) => RvalueDpsExpr,
4625 // Fn pointers are just scalar values.
4626 def::DefFn(..) | def::DefStaticMethod(..) | def::DefMethod(..) => RvalueDatumExpr,
4628 // Note: there is actually a good case to be made that
4629 // DefArg's, particularly those of immediate type, ought to
4630 // considered rvalues.
4631 def::DefStatic(..) |
4633 def::DefLocal(..) => LvalueExpr,
4635 def::DefConst(..) => RvalueDatumExpr,
4640 &format!("uncategorized def for expr {}: {:?}",
4647 ast::ExprUnary(ast::UnDeref, _) |
4648 ast::ExprField(..) |
4649 ast::ExprTupField(..) |
4650 ast::ExprIndex(..) => {
4655 ast::ExprMethodCall(..) |
4656 ast::ExprStruct(..) |
4657 ast::ExprRange(..) |
4660 ast::ExprMatch(..) |
4661 ast::ExprClosure(..) |
4662 ast::ExprBlock(..) |
4663 ast::ExprRepeat(..) |
4664 ast::ExprVec(..) => {
4668 ast::ExprIfLet(..) => {
4669 tcx.sess.span_bug(expr.span, "non-desugared ExprIfLet");
4671 ast::ExprWhileLet(..) => {
4672 tcx.sess.span_bug(expr.span, "non-desugared ExprWhileLet");
4675 ast::ExprForLoop(..) => {
4676 tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
4679 ast::ExprLit(ref lit) if lit_is_str(&**lit) => {
4683 ast::ExprCast(..) => {
4684 match tcx.node_types.borrow().get(&expr.id) {
4686 if type_is_trait(ty) {
4693 // Technically, it should not happen that the expr is not
4694 // present within the table. However, it DOES happen
4695 // during type check, because the final types from the
4696 // expressions are not yet recorded in the tcx. At that
4697 // time, though, we are only interested in knowing lvalue
4698 // vs rvalue. It would be better to base this decision on
4699 // the AST type in cast node---but (at the time of this
4700 // writing) it's not easy to distinguish casts to traits
4701 // from other casts based on the AST. This should be
4702 // easier in the future, when casts to traits
4703 // would like @Foo, Box<Foo>, or &Foo.
4709 ast::ExprBreak(..) |
4710 ast::ExprAgain(..) |
4712 ast::ExprWhile(..) |
4714 ast::ExprAssign(..) |
4715 ast::ExprInlineAsm(..) |
4716 ast::ExprAssignOp(..) => {
4720 ast::ExprLit(_) | // Note: LitStr is carved out above
4721 ast::ExprUnary(..) |
4722 ast::ExprBox(None, _) |
4723 ast::ExprAddrOf(..) |
4724 ast::ExprBinary(..) => {
4728 ast::ExprBox(Some(ref place), _) => {
4729 // Special case `Box<T>` for now:
4730 let definition = match tcx.def_map.borrow().get(&place.id) {
4732 None => panic!("no def for place"),
4734 let def_id = definition.def_id();
4735 if tcx.lang_items.exchange_heap() == Some(def_id) {
4742 ast::ExprParen(ref e) => expr_kind(tcx, &**e),
4744 ast::ExprMac(..) => {
4747 "macro expression remains after expansion");
4752 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
4754 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
4757 ast::StmtMac(..) => panic!("unexpanded macro in trans")
4761 pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
4764 for f in fields { if f.name == name { return i; } i += 1; }
4765 tcx.sess.bug(&format!(
4766 "no field named `{}` found in the list of fields `{:?}`",
4767 token::get_name(name),
4769 .map(|f| token::get_name(f.name).to_string())
4770 .collect::<Vec<String>>())[]);
4773 pub fn impl_or_trait_item_idx(id: ast::Name, trait_items: &[ImplOrTraitItem])
4775 trait_items.iter().position(|m| m.name() == id)
4778 pub fn ty_sort_string<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> String {
4780 ty_bool | ty_char | ty_int(_) |
4781 ty_uint(_) | ty_float(_) | ty_str => {
4782 ::util::ppaux::ty_to_string(cx, ty)
4784 ty_tup(ref tys) if tys.is_empty() => ::util::ppaux::ty_to_string(cx, ty),
4786 ty_enum(id, _) => format!("enum `{}`", item_path_str(cx, id)),
4787 ty_uniq(_) => "box".to_string(),
4788 ty_vec(_, Some(n)) => format!("array of {} elements", n),
4789 ty_vec(_, None) => "slice".to_string(),
4790 ty_ptr(_) => "*-ptr".to_string(),
4791 ty_rptr(_, _) => "&-ptr".to_string(),
4792 ty_bare_fn(Some(_), _) => format!("fn item"),
4793 ty_bare_fn(None, _) => "fn pointer".to_string(),
4794 ty_trait(ref inner) => {
4795 format!("trait {}", item_path_str(cx, inner.principal_def_id()))
4797 ty_struct(id, _) => {
4798 format!("struct `{}`", item_path_str(cx, id))
4800 ty_closure(..) => "closure".to_string(),
4801 ty_tup(_) => "tuple".to_string(),
4802 ty_infer(TyVar(_)) => "inferred type".to_string(),
4803 ty_infer(IntVar(_)) => "integral variable".to_string(),
4804 ty_infer(FloatVar(_)) => "floating-point variable".to_string(),
4805 ty_infer(FreshTy(_)) => "skolemized type".to_string(),
4806 ty_infer(FreshIntTy(_)) => "skolemized integral type".to_string(),
4807 ty_projection(_) => "associated type".to_string(),
4808 ty_param(ref p) => {
4809 if p.space == subst::SelfSpace {
4812 "type parameter".to_string()
4815 ty_err => "type error".to_string(),
4816 ty_open(_) => "opened DST".to_string(),
4820 impl<'tcx> Repr<'tcx> for ty::type_err<'tcx> {
4821 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
4822 ty::type_err_to_str(tcx, self)
4826 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
4827 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
4828 /// afterwards to present additional details, particularly when it comes to lifetime-related
4830 pub fn type_err_to_str<'tcx>(cx: &ctxt<'tcx>, err: &type_err<'tcx>) -> String {
4832 terr_cyclic_ty => "cyclic type of infinite size".to_string(),
4833 terr_mismatch => "types differ".to_string(),
4834 terr_unsafety_mismatch(values) => {
4835 format!("expected {} fn, found {} fn",
4839 terr_abi_mismatch(values) => {
4840 format!("expected {} fn, found {} fn",
4844 terr_mutability => "values differ in mutability".to_string(),
4845 terr_box_mutability => {
4846 "boxed values differ in mutability".to_string()
4848 terr_vec_mutability => "vectors differ in mutability".to_string(),
4849 terr_ptr_mutability => "pointers differ in mutability".to_string(),
4850 terr_ref_mutability => "references differ in mutability".to_string(),
4851 terr_ty_param_size(values) => {
4852 format!("expected a type with {} type params, \
4853 found one with {} type params",
4857 terr_fixed_array_size(values) => {
4858 format!("expected an array with a fixed size of {} elements, \
4859 found one with {} elements",
4863 terr_tuple_size(values) => {
4864 format!("expected a tuple with {} elements, \
4865 found one with {} elements",
4870 "incorrect number of function parameters".to_string()
4872 terr_regions_does_not_outlive(..) => {
4873 "lifetime mismatch".to_string()
4875 terr_regions_not_same(..) => {
4876 "lifetimes are not the same".to_string()
4878 terr_regions_no_overlap(..) => {
4879 "lifetimes do not intersect".to_string()
4881 terr_regions_insufficiently_polymorphic(br, _) => {
4882 format!("expected bound lifetime parameter {}, \
4883 found concrete lifetime",
4884 bound_region_ptr_to_string(cx, br))
4886 terr_regions_overly_polymorphic(br, _) => {
4887 format!("expected concrete lifetime, \
4888 found bound lifetime parameter {}",
4889 bound_region_ptr_to_string(cx, br))
4891 terr_sorts(values) => {
4892 // A naive approach to making sure that we're not reporting silly errors such as:
4893 // (expected closure, found closure).
4894 let expected_str = ty_sort_string(cx, values.expected);
4895 let found_str = ty_sort_string(cx, values.found);
4896 if expected_str == found_str {
4897 format!("expected {}, found a different {}", expected_str, found_str)
4899 format!("expected {}, found {}", expected_str, found_str)
4902 terr_traits(values) => {
4903 format!("expected trait `{}`, found trait `{}`",
4904 item_path_str(cx, values.expected),
4905 item_path_str(cx, values.found))
4907 terr_builtin_bounds(values) => {
4908 if values.expected.is_empty() {
4909 format!("expected no bounds, found `{}`",
4910 values.found.user_string(cx))
4911 } else if values.found.is_empty() {
4912 format!("expected bounds `{}`, found no bounds",
4913 values.expected.user_string(cx))
4915 format!("expected bounds `{}`, found bounds `{}`",
4916 values.expected.user_string(cx),
4917 values.found.user_string(cx))
4920 terr_integer_as_char => {
4921 "expected an integral type, found `char`".to_string()
4923 terr_int_mismatch(ref values) => {
4924 format!("expected `{:?}`, found `{:?}`",
4928 terr_float_mismatch(ref values) => {
4929 format!("expected `{:?}`, found `{:?}`",
4933 terr_variadic_mismatch(ref values) => {
4934 format!("expected {} fn, found {} function",
4935 if values.expected { "variadic" } else { "non-variadic" },
4936 if values.found { "variadic" } else { "non-variadic" })
4938 terr_convergence_mismatch(ref values) => {
4939 format!("expected {} fn, found {} function",
4940 if values.expected { "converging" } else { "diverging" },
4941 if values.found { "converging" } else { "diverging" })
4943 terr_projection_name_mismatched(ref values) => {
4944 format!("expected {}, found {}",
4945 token::get_name(values.expected),
4946 token::get_name(values.found))
4948 terr_projection_bounds_length(ref values) => {
4949 format!("expected {} associated type bindings, found {}",
4956 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
4958 terr_regions_does_not_outlive(subregion, superregion) => {
4959 note_and_explain_region(cx, "", subregion, "...");
4960 note_and_explain_region(cx, "...does not necessarily outlive ",
4963 terr_regions_not_same(region1, region2) => {
4964 note_and_explain_region(cx, "", region1, "...");
4965 note_and_explain_region(cx, "...is not the same lifetime as ",
4968 terr_regions_no_overlap(region1, region2) => {
4969 note_and_explain_region(cx, "", region1, "...");
4970 note_and_explain_region(cx, "...does not overlap ",
4973 terr_regions_insufficiently_polymorphic(_, conc_region) => {
4974 note_and_explain_region(cx,
4975 "concrete lifetime that was found is ",
4978 terr_regions_overly_polymorphic(_, ty::ReInfer(ty::ReVar(_))) => {
4979 // don't bother to print out the message below for
4980 // inference variables, it's not very illuminating.
4982 terr_regions_overly_polymorphic(_, conc_region) => {
4983 note_and_explain_region(cx,
4984 "expected concrete lifetime is ",
4991 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
4992 cx.provided_method_sources.borrow().get(&id).cloned()
4995 pub fn provided_trait_methods<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
4996 -> Vec<Rc<Method<'tcx>>> {
4998 match cx.map.find(id.node) {
4999 Some(ast_map::NodeItem(item)) => {
5001 ItemTrait(_, _, _, ref ms) => {
5003 ast_util::split_trait_methods(&ms[..]);
5006 match impl_or_trait_item(
5008 ast_util::local_def(m.id)) {
5009 MethodTraitItem(m) => m,
5010 TypeTraitItem(_) => {
5011 cx.sess.bug("provided_trait_methods(): \
5012 split_trait_methods() put \
5013 associated types in the \
5014 provided method bucket?!")
5020 cx.sess.bug(&format!("provided_trait_methods: `{:?}` is \
5027 cx.sess.bug(&format!("provided_trait_methods: `{:?}` is not a \
5033 csearch::get_provided_trait_methods(cx, id)
5037 /// Helper for looking things up in the various maps that are populated during
5038 /// typeck::collect (e.g., `cx.impl_or_trait_items`, `cx.tcache`, etc). All of
5039 /// these share the pattern that if the id is local, it should have been loaded
5040 /// into the map by the `typeck::collect` phase. If the def-id is external,
5041 /// then we have to go consult the crate loading code (and cache the result for
5043 fn lookup_locally_or_in_crate_store<V, F>(descr: &str,
5045 map: &mut DefIdMap<V>,
5046 load_external: F) -> V where
5050 match map.get(&def_id).cloned() {
5051 Some(v) => { return v; }
5055 if def_id.krate == ast::LOCAL_CRATE {
5056 panic!("No def'n found for {:?} in tcx.{}", def_id, descr);
5058 let v = load_external();
5059 map.insert(def_id, v.clone());
5063 pub fn trait_item<'tcx>(cx: &ctxt<'tcx>, trait_did: ast::DefId, idx: uint)
5064 -> ImplOrTraitItem<'tcx> {
5065 let method_def_id = (*ty::trait_item_def_ids(cx, trait_did))[idx].def_id();
5066 impl_or_trait_item(cx, method_def_id)
5069 pub fn trait_items<'tcx>(cx: &ctxt<'tcx>, trait_did: ast::DefId)
5070 -> Rc<Vec<ImplOrTraitItem<'tcx>>> {
5071 let mut trait_items = cx.trait_items_cache.borrow_mut();
5072 match trait_items.get(&trait_did).cloned() {
5073 Some(trait_items) => trait_items,
5075 let def_ids = ty::trait_item_def_ids(cx, trait_did);
5076 let items: Rc<Vec<ImplOrTraitItem>> =
5077 Rc::new(def_ids.iter()
5078 .map(|d| impl_or_trait_item(cx, d.def_id()))
5080 trait_items.insert(trait_did, items.clone());
5086 pub fn trait_impl_polarity<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5087 -> Option<ast::ImplPolarity> {
5088 if id.krate == ast::LOCAL_CRATE {
5089 match cx.map.find(id.node) {
5090 Some(ast_map::NodeItem(item)) => {
5092 ast::ItemImpl(_, polarity, _, _, _, _) => Some(polarity),
5099 csearch::get_impl_polarity(cx, id)
5103 pub fn impl_or_trait_item<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5104 -> ImplOrTraitItem<'tcx> {
5105 lookup_locally_or_in_crate_store("impl_or_trait_items",
5107 &mut *cx.impl_or_trait_items
5110 csearch::get_impl_or_trait_item(cx, id)
5114 /// Returns true if the given ID refers to an associated type and false if it
5115 /// refers to anything else.
5116 pub fn is_associated_type(cx: &ctxt, id: ast::DefId) -> bool {
5117 memoized(&cx.associated_types, id, |id: ast::DefId| {
5118 if id.krate == ast::LOCAL_CRATE {
5119 match cx.impl_or_trait_items.borrow().get(&id) {
5122 TypeTraitItem(_) => true,
5123 MethodTraitItem(_) => false,
5129 csearch::is_associated_type(&cx.sess.cstore, id)
5134 /// Returns the parameter index that the given associated type corresponds to.
5135 pub fn associated_type_parameter_index(cx: &ctxt,
5136 trait_def: &TraitDef,
5137 associated_type_id: ast::DefId)
5139 for type_parameter_def in trait_def.generics.types.iter() {
5140 if type_parameter_def.def_id == associated_type_id {
5141 return type_parameter_def.index as uint
5144 cx.sess.bug("couldn't find associated type parameter index")
5147 pub fn trait_item_def_ids(cx: &ctxt, id: ast::DefId)
5148 -> Rc<Vec<ImplOrTraitItemId>> {
5149 lookup_locally_or_in_crate_store("trait_item_def_ids",
5151 &mut *cx.trait_item_def_ids.borrow_mut(),
5153 Rc::new(csearch::get_trait_item_def_ids(&cx.sess.cstore, id))
5157 pub fn impl_trait_ref<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5158 -> Option<Rc<TraitRef<'tcx>>> {
5159 memoized(&cx.impl_trait_cache, id, |id: ast::DefId| {
5160 if id.krate == ast::LOCAL_CRATE {
5161 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
5162 match cx.map.find(id.node) {
5163 Some(ast_map::NodeItem(item)) => {
5165 ast::ItemImpl(_, _, _, ref opt_trait, _, _) => {
5168 let trait_ref = ty::node_id_to_trait_ref(cx, t.ref_id);
5180 csearch::get_impl_trait(cx, id)
5185 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
5186 let def = *tcx.def_map.borrow()
5188 .expect("no def-map entry for trait");
5192 pub fn try_add_builtin_trait(
5194 trait_def_id: ast::DefId,
5195 builtin_bounds: &mut EnumSet<BuiltinBound>)
5198 //! Checks whether `trait_ref` refers to one of the builtin
5199 //! traits, like `Send`, and adds the corresponding
5200 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
5201 //! is a builtin trait.
5203 match tcx.lang_items.to_builtin_kind(trait_def_id) {
5204 Some(bound) => { builtin_bounds.insert(bound); true }
5209 pub fn ty_to_def_id(ty: Ty) -> Option<ast::DefId> {
5212 Some(tt.principal_def_id()),
5215 ty_closure(id, _, _) =>
5224 pub struct VariantInfo<'tcx> {
5225 pub args: Vec<Ty<'tcx>>,
5226 pub arg_names: Option<Vec<ast::Ident>>,
5227 pub ctor_ty: Option<Ty<'tcx>>,
5228 pub name: ast::Name,
5234 impl<'tcx> VariantInfo<'tcx> {
5236 /// Creates a new VariantInfo from the corresponding ast representation.
5238 /// Does not do any caching of the value in the type context.
5239 pub fn from_ast_variant(cx: &ctxt<'tcx>,
5240 ast_variant: &ast::Variant,
5241 discriminant: Disr) -> VariantInfo<'tcx> {
5242 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
5244 match ast_variant.node.kind {
5245 ast::TupleVariantKind(ref args) => {
5246 let arg_tys = if args.len() > 0 {
5247 // the regions in the argument types come from the
5248 // enum def'n, and hence will all be early bound
5249 ty::no_late_bound_regions(cx, &ty_fn_args(ctor_ty)).unwrap()
5254 return VariantInfo {
5257 ctor_ty: Some(ctor_ty),
5258 name: ast_variant.node.name.name,
5259 id: ast_util::local_def(ast_variant.node.id),
5260 disr_val: discriminant,
5261 vis: ast_variant.node.vis
5264 ast::StructVariantKind(ref struct_def) => {
5265 let fields: &[StructField] = &struct_def.fields[];
5267 assert!(fields.len() > 0);
5269 let arg_tys = struct_def.fields.iter()
5270 .map(|field| node_id_to_type(cx, field.node.id)).collect();
5271 let arg_names = fields.iter().map(|field| {
5272 match field.node.kind {
5273 NamedField(ident, _) => ident,
5274 UnnamedField(..) => cx.sess.bug(
5275 "enum_variants: all fields in struct must have a name")
5279 return VariantInfo {
5281 arg_names: Some(arg_names),
5283 name: ast_variant.node.name.name,
5284 id: ast_util::local_def(ast_variant.node.id),
5285 disr_val: discriminant,
5286 vis: ast_variant.node.vis
5293 pub fn substd_enum_variants<'tcx>(cx: &ctxt<'tcx>,
5295 substs: &Substs<'tcx>)
5296 -> Vec<Rc<VariantInfo<'tcx>>> {
5297 enum_variants(cx, id).iter().map(|variant_info| {
5298 let substd_args = variant_info.args.iter()
5299 .map(|aty| aty.subst(cx, substs)).collect::<Vec<_>>();
5301 let substd_ctor_ty = variant_info.ctor_ty.subst(cx, substs);
5303 Rc::new(VariantInfo {
5305 ctor_ty: substd_ctor_ty,
5306 ..(**variant_info).clone()
5311 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
5312 with_path(cx, id, |path| ast_map::path_to_string(path)).to_string()
5318 TraitDtor(DefId, bool)
5322 pub fn is_present(&self) -> bool {
5324 TraitDtor(..) => true,
5329 pub fn has_drop_flag(&self) -> bool {
5332 &TraitDtor(_, flag) => flag
5337 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
5338 Otherwise return none. */
5339 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
5340 match cx.destructor_for_type.borrow().get(&struct_id) {
5341 Some(&method_def_id) => {
5342 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
5344 TraitDtor(method_def_id, flag)
5350 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
5351 cx.destructor_for_type.borrow().contains_key(&struct_id)
5354 pub fn with_path<T, F>(cx: &ctxt, id: ast::DefId, f: F) -> T where
5355 F: FnOnce(ast_map::PathElems) -> T,
5357 if id.krate == ast::LOCAL_CRATE {
5358 cx.map.with_path(id.node, f)
5360 f(csearch::get_item_path(cx, id).iter().cloned().chain(None))
5364 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
5365 enum_variants(cx, id).len() == 1
5368 pub fn type_is_empty(cx: &ctxt, ty: Ty) -> bool {
5370 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
5375 pub fn enum_variants<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5376 -> Rc<Vec<Rc<VariantInfo<'tcx>>>> {
5377 memoized(&cx.enum_var_cache, id, |id: ast::DefId| {
5378 if ast::LOCAL_CRATE != id.krate {
5379 Rc::new(csearch::get_enum_variants(cx, id))
5382 Although both this code and check_enum_variants in typeck/check
5383 call eval_const_expr, it should never get called twice for the same
5384 expr, since check_enum_variants also updates the enum_var_cache
5386 match cx.map.get(id.node) {
5387 ast_map::NodeItem(ref item) => {
5389 ast::ItemEnum(ref enum_definition, _) => {
5390 let mut last_discriminant: Option<Disr> = None;
5391 Rc::new(enum_definition.variants.iter().map(|variant| {
5393 let mut discriminant = match last_discriminant {
5394 Some(val) => val + 1,
5395 None => INITIAL_DISCRIMINANT_VALUE
5398 if let Some(ref e) = variant.node.disr_expr {
5399 // Preserve all values, and prefer signed.
5400 let ty = Some(cx.types.i64);
5401 match const_eval::eval_const_expr_partial(cx, &**e, ty) {
5402 Ok(const_eval::const_int(val)) => {
5403 discriminant = val as Disr;
5405 Ok(const_eval::const_uint(val)) => {
5406 discriminant = val as Disr;
5409 span_err!(cx.sess, e.span, E0304,
5410 "expected signed integer constant");
5413 span_err!(cx.sess, e.span, E0305,
5414 "expected constant: {}", err);
5419 last_discriminant = Some(discriminant);
5420 Rc::new(VariantInfo::from_ast_variant(cx, &**variant,
5425 cx.sess.bug("enum_variants: id not bound to an enum")
5429 _ => cx.sess.bug("enum_variants: id not bound to an enum")
5435 // Returns information about the enum variant with the given ID:
5436 pub fn enum_variant_with_id<'tcx>(cx: &ctxt<'tcx>,
5437 enum_id: ast::DefId,
5438 variant_id: ast::DefId)
5439 -> Rc<VariantInfo<'tcx>> {
5440 enum_variants(cx, enum_id).iter()
5441 .find(|variant| variant.id == variant_id)
5442 .expect("enum_variant_with_id(): no variant exists with that ID")
5447 // If the given item is in an external crate, looks up its type and adds it to
5448 // the type cache. Returns the type parameters and type.
5449 pub fn lookup_item_type<'tcx>(cx: &ctxt<'tcx>,
5451 -> TypeScheme<'tcx> {
5452 lookup_locally_or_in_crate_store(
5453 "tcache", did, &mut *cx.tcache.borrow_mut(),
5454 || csearch::get_type(cx, did))
5457 /// Given the did of a trait, returns its canonical trait ref.
5458 pub fn lookup_trait_def<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId)
5459 -> Rc<TraitDef<'tcx>> {
5460 memoized(&cx.trait_defs, did, |did: DefId| {
5461 assert!(did.krate != ast::LOCAL_CRATE);
5462 Rc::new(csearch::get_trait_def(cx, did))
5466 /// Given the did of a trait, returns its full set of predicates.
5467 pub fn lookup_predicates<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId)
5468 -> GenericPredicates<'tcx>
5470 memoized(&cx.predicates, did, |did: DefId| {
5471 assert!(did.krate != ast::LOCAL_CRATE);
5472 csearch::get_predicates(cx, did)
5476 /// Given a reference to a trait, returns the "superbounds" declared
5477 /// on the trait, with appropriate substitutions applied. Basically,
5478 /// this applies a filter to the where clauses on the trait, returning
5479 /// those that have the form:
5481 /// Self : SuperTrait<...>
5483 pub fn predicates_for_trait_ref<'tcx>(tcx: &ctxt<'tcx>,
5484 trait_ref: &PolyTraitRef<'tcx>)
5485 -> Vec<ty::Predicate<'tcx>>
5487 let trait_def = lookup_trait_def(tcx, trait_ref.def_id());
5489 debug!("bounds_for_trait_ref(trait_def={:?}, trait_ref={:?})",
5490 trait_def.repr(tcx), trait_ref.repr(tcx));
5492 // The interaction between HRTB and supertraits is not entirely
5493 // obvious. Let me walk you (and myself) through an example.
5495 // Let's start with an easy case. Consider two traits:
5497 // trait Foo<'a> : Bar<'a,'a> { }
5498 // trait Bar<'b,'c> { }
5500 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
5501 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
5502 // knew that `Foo<'x>` (for any 'x) then we also know that
5503 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
5504 // normal substitution.
5506 // In terms of why this is sound, the idea is that whenever there
5507 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
5508 // holds. So if there is an impl of `T:Foo<'a>` that applies to
5509 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
5512 // Another example to be careful of is this:
5514 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
5515 // trait Bar1<'b,'c> { }
5517 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
5518 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
5519 // reason is similar to the previous example: any impl of
5520 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
5521 // basically we would want to collapse the bound lifetimes from
5522 // the input (`trait_ref`) and the supertraits.
5524 // To achieve this in practice is fairly straightforward. Let's
5525 // consider the more complicated scenario:
5527 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
5528 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
5529 // where both `'x` and `'b` would have a DB index of 1.
5530 // The substitution from the input trait-ref is therefore going to be
5531 // `'a => 'x` (where `'x` has a DB index of 1).
5532 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
5533 // early-bound parameter and `'b' is a late-bound parameter with a
5535 // - If we replace `'a` with `'x` from the input, it too will have
5536 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
5537 // just as we wanted.
5539 // There is only one catch. If we just apply the substitution `'a
5540 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
5541 // adjust the DB index because we substituting into a binder (it
5542 // tries to be so smart...) resulting in `for<'x> for<'b>
5543 // Bar1<'x,'b>` (we have no syntax for this, so use your
5544 // imagination). Basically the 'x will have DB index of 2 and 'b
5545 // will have DB index of 1. Not quite what we want. So we apply
5546 // the substitution to the *contents* of the trait reference,
5547 // rather than the trait reference itself (put another way, the
5548 // substitution code expects equal binding levels in the values
5549 // from the substitution and the value being substituted into, and
5550 // this trick achieves that).
5552 // Carefully avoid the binder introduced by each trait-ref by
5553 // substituting over the substs, not the trait-refs themselves,
5554 // thus achieving the "collapse" described in the big comment
5556 let trait_bounds: Vec<_> =
5557 trait_def.bounds.trait_bounds
5559 .map(|poly_trait_ref| ty::Binder(poly_trait_ref.0.subst(tcx, trait_ref.substs())))
5562 let projection_bounds: Vec<_> =
5563 trait_def.bounds.projection_bounds
5565 .map(|poly_proj| ty::Binder(poly_proj.0.subst(tcx, trait_ref.substs())))
5568 debug!("bounds_for_trait_ref: trait_bounds={} projection_bounds={}",
5569 trait_bounds.repr(tcx),
5570 projection_bounds.repr(tcx));
5572 // The region bounds and builtin bounds do not currently introduce
5573 // binders so we can just substitute in a straightforward way here.
5575 trait_def.bounds.region_bounds.subst(tcx, trait_ref.substs());
5576 let builtin_bounds =
5577 trait_def.bounds.builtin_bounds.subst(tcx, trait_ref.substs());
5579 let bounds = ty::ParamBounds {
5580 trait_bounds: trait_bounds,
5581 region_bounds: region_bounds,
5582 builtin_bounds: builtin_bounds,
5583 projection_bounds: projection_bounds,
5586 predicates(tcx, trait_ref.self_ty(), &bounds)
5589 pub fn predicates<'tcx>(
5592 bounds: &ParamBounds<'tcx>)
5593 -> Vec<Predicate<'tcx>>
5595 let mut vec = Vec::new();
5597 for builtin_bound in &bounds.builtin_bounds {
5598 match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty) {
5599 Ok(trait_ref) => { vec.push(trait_ref.as_predicate()); }
5600 Err(ErrorReported) => { }
5604 for ®ion_bound in &bounds.region_bounds {
5605 // account for the binder being introduced below; no need to shift `param_ty`
5606 // because, at present at least, it can only refer to early-bound regions
5607 let region_bound = ty_fold::shift_region(region_bound, 1);
5608 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).as_predicate());
5611 for bound_trait_ref in &bounds.trait_bounds {
5612 vec.push(bound_trait_ref.as_predicate());
5615 for projection in &bounds.projection_bounds {
5616 vec.push(projection.as_predicate());
5622 /// Get the attributes of a definition.
5623 pub fn get_attrs<'tcx>(tcx: &'tcx ctxt, did: DefId)
5624 -> CowVec<'tcx, ast::Attribute> {
5626 let item = tcx.map.expect_item(did.node);
5627 Cow::Borrowed(&item.attrs[])
5629 Cow::Owned(csearch::get_item_attrs(&tcx.sess.cstore, did))
5633 /// Determine whether an item is annotated with an attribute
5634 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
5635 get_attrs(tcx, did).iter().any(|item| item.check_name(attr))
5638 /// Determine whether an item is annotated with `#[repr(packed)]`
5639 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
5640 lookup_repr_hints(tcx, did).contains(&attr::ReprPacked)
5643 /// Determine whether an item is annotated with `#[simd]`
5644 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
5645 has_attr(tcx, did, "simd")
5648 /// Obtain the representation annotation for a struct definition.
5649 pub fn lookup_repr_hints(tcx: &ctxt, did: DefId) -> Rc<Vec<attr::ReprAttr>> {
5650 memoized(&tcx.repr_hint_cache, did, |did: DefId| {
5651 Rc::new(if did.krate == LOCAL_CRATE {
5652 get_attrs(tcx, did).iter().flat_map(|meta| {
5653 attr::find_repr_attrs(tcx.sess.diagnostic(), meta).into_iter()
5656 csearch::get_repr_attrs(&tcx.sess.cstore, did)
5661 // Look up a field ID, whether or not it's local
5662 // Takes a list of type substs in case the struct is generic
5663 pub fn lookup_field_type<'tcx>(tcx: &ctxt<'tcx>,
5666 substs: &Substs<'tcx>)
5668 let ty = if id.krate == ast::LOCAL_CRATE {
5669 node_id_to_type(tcx, id.node)
5671 let mut tcache = tcx.tcache.borrow_mut();
5672 let pty = tcache.entry(id).get().unwrap_or_else(
5673 |vacant_entry| vacant_entry.insert(csearch::get_field_type(tcx, struct_id, id)));
5676 ty.subst(tcx, substs)
5679 // Look up the list of field names and IDs for a given struct.
5680 // Panics if the id is not bound to a struct.
5681 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
5682 if did.krate == ast::LOCAL_CRATE {
5683 let struct_fields = cx.struct_fields.borrow();
5684 match struct_fields.get(&did) {
5685 Some(fields) => (**fields).clone(),
5688 &format!("ID not mapped to struct fields: {}",
5689 cx.map.node_to_string(did.node))[]);
5693 csearch::get_struct_fields(&cx.sess.cstore, did)
5697 pub fn is_tuple_struct(cx: &ctxt, did: ast::DefId) -> bool {
5698 let fields = lookup_struct_fields(cx, did);
5699 !fields.is_empty() && fields.iter().all(|f| f.name == token::special_names::unnamed_field)
5702 // Returns a list of fields corresponding to the struct's items. trans uses
5703 // this. Takes a list of substs with which to instantiate field types.
5704 pub fn struct_fields<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId, substs: &Substs<'tcx>)
5705 -> Vec<field<'tcx>> {
5706 lookup_struct_fields(cx, did).iter().map(|f| {
5710 ty: lookup_field_type(cx, did, f.id, substs),
5717 // Returns a list of fields corresponding to the tuple's items. trans uses
5719 pub fn tup_fields<'tcx>(v: &[Ty<'tcx>]) -> Vec<field<'tcx>> {
5720 v.iter().enumerate().map(|(i, &f)| {
5722 name: token::intern(&i.to_string()[]),
5731 #[derive(Copy, Clone)]
5732 pub struct ClosureUpvar<'tcx> {
5738 // Returns a list of `ClosureUpvar`s for each upvar.
5739 pub fn closure_upvars<'tcx>(typer: &mc::Typer<'tcx>,
5740 closure_id: ast::DefId,
5741 substs: &Substs<'tcx>)
5742 -> Option<Vec<ClosureUpvar<'tcx>>>
5744 // Presently an unboxed closure type cannot "escape" out of a
5745 // function, so we will only encounter ones that originated in the
5746 // local crate or were inlined into it along with some function.
5747 // This may change if abstract return types of some sort are
5749 assert!(closure_id.krate == ast::LOCAL_CRATE);
5750 let tcx = typer.tcx();
5751 match tcx.freevars.borrow().get(&closure_id.node) {
5752 None => Some(vec![]),
5753 Some(ref freevars) => {
5756 let freevar_def_id = freevar.def.def_id();
5757 let freevar_ty = match typer.node_ty(freevar_def_id.node) {
5759 Err(()) => { return None; }
5761 let freevar_ty = freevar_ty.subst(tcx, substs);
5763 let upvar_id = ty::UpvarId {
5764 var_id: freevar_def_id.node,
5765 closure_expr_id: closure_id.node
5768 typer.upvar_capture(upvar_id).map(|capture| {
5769 let freevar_ref_ty = match capture {
5770 UpvarCapture::ByValue => {
5773 UpvarCapture::ByRef(borrow) => {
5775 tcx.mk_region(borrow.region),
5778 mutbl: borrow.kind.to_mutbl_lossy(),
5795 pub fn is_binopable<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>, op: ast::BinOp) -> bool {
5796 #![allow(non_upper_case_globals)]
5797 static tycat_other: int = 0;
5798 static tycat_bool: int = 1;
5799 static tycat_char: int = 2;
5800 static tycat_int: int = 3;
5801 static tycat_float: int = 4;
5802 static tycat_raw_ptr: int = 6;
5804 static opcat_add: int = 0;
5805 static opcat_sub: int = 1;
5806 static opcat_mult: int = 2;
5807 static opcat_shift: int = 3;
5808 static opcat_rel: int = 4;
5809 static opcat_eq: int = 5;
5810 static opcat_bit: int = 6;
5811 static opcat_logic: int = 7;
5812 static opcat_mod: int = 8;
5814 fn opcat(op: ast::BinOp) -> int {
5816 ast::BiAdd => opcat_add,
5817 ast::BiSub => opcat_sub,
5818 ast::BiMul => opcat_mult,
5819 ast::BiDiv => opcat_mult,
5820 ast::BiRem => opcat_mod,
5821 ast::BiAnd => opcat_logic,
5822 ast::BiOr => opcat_logic,
5823 ast::BiBitXor => opcat_bit,
5824 ast::BiBitAnd => opcat_bit,
5825 ast::BiBitOr => opcat_bit,
5826 ast::BiShl => opcat_shift,
5827 ast::BiShr => opcat_shift,
5828 ast::BiEq => opcat_eq,
5829 ast::BiNe => opcat_eq,
5830 ast::BiLt => opcat_rel,
5831 ast::BiLe => opcat_rel,
5832 ast::BiGe => opcat_rel,
5833 ast::BiGt => opcat_rel
5837 fn tycat<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> int {
5838 if type_is_simd(cx, ty) {
5839 return tycat(cx, simd_type(cx, ty))
5842 ty_char => tycat_char,
5843 ty_bool => tycat_bool,
5844 ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
5845 ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
5846 ty_ptr(_) => tycat_raw_ptr,
5851 static t: bool = true;
5852 static f: bool = false;
5855 // +, -, *, shift, rel, ==, bit, logic, mod
5856 /*other*/ [f, f, f, f, f, f, f, f, f],
5857 /*bool*/ [f, f, f, f, t, t, t, t, f],
5858 /*char*/ [f, f, f, f, t, t, f, f, f],
5859 /*int*/ [t, t, t, t, t, t, t, f, t],
5860 /*float*/ [t, t, t, f, t, t, f, f, f],
5861 /*bot*/ [t, t, t, t, t, t, t, t, t],
5862 /*raw ptr*/ [f, f, f, f, t, t, f, f, f]];
5864 return tbl[tycat(cx, ty) as uint ][opcat(op) as uint];
5867 // Returns the repeat count for a repeating vector expression.
5868 pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> uint {
5869 match const_eval::eval_const_expr_partial(tcx, count_expr, Some(tcx.types.uint)) {
5871 let found = match val {
5872 const_eval::const_uint(count) => return count as uint,
5873 const_eval::const_int(count) if count >= 0 => return count as uint,
5874 const_eval::const_int(_) =>
5876 const_eval::const_float(_) =>
5878 const_eval::const_str(_) =>
5880 const_eval::const_bool(_) =>
5882 const_eval::const_binary(_) =>
5885 span_err!(tcx.sess, count_expr.span, E0306,
5886 "expected positive integer for repeat count, found {}",
5890 let found = match count_expr.node {
5891 ast::ExprPath(ast::Path {
5895 }) if segments.len() == 1 =>
5898 "non-constant expression"
5900 span_err!(tcx.sess, count_expr.span, E0307,
5901 "expected constant integer for repeat count, found {}",
5908 // Iterate over a type parameter's bounded traits and any supertraits
5909 // of those traits, ignoring kinds.
5910 // Here, the supertraits are the transitive closure of the supertrait
5911 // relation on the supertraits from each bounded trait's constraint
5913 pub fn each_bound_trait_and_supertraits<'tcx, F>(tcx: &ctxt<'tcx>,
5914 bounds: &[PolyTraitRef<'tcx>],
5917 F: FnMut(PolyTraitRef<'tcx>) -> bool,
5919 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
5920 if !f(bound_trait_ref) {
5927 /// Given a set of predicates that apply to an object type, returns
5928 /// the region bounds that the (erased) `Self` type must
5929 /// outlive. Precisely *because* the `Self` type is erased, the
5930 /// parameter `erased_self_ty` must be supplied to indicate what type
5931 /// has been used to represent `Self` in the predicates
5932 /// themselves. This should really be a unique type; `FreshTy(0)` is a
5935 /// Requires that trait definitions have been processed so that we can
5936 /// elaborate predicates and walk supertraits.
5937 pub fn required_region_bounds<'tcx>(tcx: &ctxt<'tcx>,
5938 erased_self_ty: Ty<'tcx>,
5939 predicates: Vec<ty::Predicate<'tcx>>)
5942 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
5943 erased_self_ty.repr(tcx),
5944 predicates.repr(tcx));
5946 assert!(!erased_self_ty.has_escaping_regions());
5948 traits::elaborate_predicates(tcx, predicates)
5949 .filter_map(|predicate| {
5951 ty::Predicate::Projection(..) |
5952 ty::Predicate::Trait(..) |
5953 ty::Predicate::Equate(..) |
5954 ty::Predicate::RegionOutlives(..) => {
5957 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
5958 // Search for a bound of the form `erased_self_ty
5959 // : 'a`, but be wary of something like `for<'a>
5960 // erased_self_ty : 'a` (we interpret a
5961 // higher-ranked bound like that as 'static,
5962 // though at present the code in `fulfill.rs`
5963 // considers such bounds to be unsatisfiable, so
5964 // it's kind of a moot point since you could never
5965 // construct such an object, but this seems
5966 // correct even if that code changes).
5967 if t == erased_self_ty && !r.has_escaping_regions() {
5968 if r.has_escaping_regions() {
5982 pub fn get_tydesc_ty<'tcx>(tcx: &ctxt<'tcx>) -> Result<Ty<'tcx>, String> {
5983 tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
5984 tcx.intrinsic_defs.borrow().get(&tydesc_lang_item).cloned()
5985 .expect("Failed to resolve TyDesc")
5989 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> Rc<ItemVariances> {
5990 lookup_locally_or_in_crate_store(
5991 "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
5992 || Rc::new(csearch::get_item_variances(&tcx.sess.cstore, item_id)))
5995 /// Records a trait-to-implementation mapping.
5996 pub fn record_trait_implementation(tcx: &ctxt,
5997 trait_def_id: DefId,
5998 impl_def_id: DefId) {
6000 match tcx.trait_impls.borrow().get(&trait_def_id) {
6001 Some(impls_for_trait) => {
6002 impls_for_trait.borrow_mut().push(impl_def_id);
6008 tcx.trait_impls.borrow_mut().insert(trait_def_id, Rc::new(RefCell::new(vec!(impl_def_id))));
6011 /// Populates the type context with all the implementations for the given type
6013 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
6014 type_id: ast::DefId) {
6015 if type_id.krate == LOCAL_CRATE {
6018 if tcx.populated_external_types.borrow().contains(&type_id) {
6022 debug!("populate_implementations_for_type_if_necessary: searching for {:?}", type_id);
6024 let mut inherent_impls = Vec::new();
6025 csearch::each_implementation_for_type(&tcx.sess.cstore, type_id,
6027 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, impl_def_id);
6029 // Record the trait->implementation mappings, if applicable.
6030 let associated_traits = csearch::get_impl_trait(tcx, impl_def_id);
6031 if let Some(ref trait_ref) = associated_traits {
6032 record_trait_implementation(tcx, trait_ref.def_id, impl_def_id);
6035 // For any methods that use a default implementation, add them to
6036 // the map. This is a bit unfortunate.
6037 for impl_item_def_id in &impl_items {
6038 let method_def_id = impl_item_def_id.def_id();
6039 match impl_or_trait_item(tcx, method_def_id) {
6040 MethodTraitItem(method) => {
6041 if let Some(source) = method.provided_source {
6042 tcx.provided_method_sources
6044 .insert(method_def_id, source);
6047 TypeTraitItem(_) => {}
6051 // Store the implementation info.
6052 tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
6054 // If this is an inherent implementation, record it.
6055 if associated_traits.is_none() {
6056 inherent_impls.push(impl_def_id);
6060 tcx.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
6061 tcx.populated_external_types.borrow_mut().insert(type_id);
6064 /// Populates the type context with all the implementations for the given
6065 /// trait if necessary.
6066 pub fn populate_implementations_for_trait_if_necessary(
6068 trait_id: ast::DefId) {
6069 if trait_id.krate == LOCAL_CRATE {
6072 if tcx.populated_external_traits.borrow().contains(&trait_id) {
6076 csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id,
6077 |implementation_def_id| {
6078 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, implementation_def_id);
6080 // Record the trait->implementation mapping.
6081 record_trait_implementation(tcx, trait_id, implementation_def_id);
6083 // For any methods that use a default implementation, add them to
6084 // the map. This is a bit unfortunate.
6085 for impl_item_def_id in &impl_items {
6086 let method_def_id = impl_item_def_id.def_id();
6087 match impl_or_trait_item(tcx, method_def_id) {
6088 MethodTraitItem(method) => {
6089 if let Some(source) = method.provided_source {
6090 tcx.provided_method_sources
6092 .insert(method_def_id, source);
6095 TypeTraitItem(_) => {}
6099 // Store the implementation info.
6100 tcx.impl_items.borrow_mut().insert(implementation_def_id, impl_items);
6103 tcx.populated_external_traits.borrow_mut().insert(trait_id);
6106 /// Given the def_id of an impl, return the def_id of the trait it implements.
6107 /// If it implements no trait, return `None`.
6108 pub fn trait_id_of_impl(tcx: &ctxt,
6110 -> Option<ast::DefId> {
6111 ty::impl_trait_ref(tcx, def_id).map(|tr| tr.def_id)
6114 /// If the given def ID describes a method belonging to an impl, return the
6115 /// ID of the impl that the method belongs to. Otherwise, return `None`.
6116 pub fn impl_of_method(tcx: &ctxt, def_id: ast::DefId)
6117 -> Option<ast::DefId> {
6118 if def_id.krate != LOCAL_CRATE {
6119 return match csearch::get_impl_or_trait_item(tcx,
6120 def_id).container() {
6121 TraitContainer(_) => None,
6122 ImplContainer(def_id) => Some(def_id),
6125 match tcx.impl_or_trait_items.borrow().get(&def_id).cloned() {
6126 Some(trait_item) => {
6127 match trait_item.container() {
6128 TraitContainer(_) => None,
6129 ImplContainer(def_id) => Some(def_id),
6136 /// If the given def ID describes an item belonging to a trait (either a
6137 /// default method or an implementation of a trait method), return the ID of
6138 /// the trait that the method belongs to. Otherwise, return `None`.
6139 pub fn trait_of_item(tcx: &ctxt, def_id: ast::DefId) -> Option<ast::DefId> {
6140 if def_id.krate != LOCAL_CRATE {
6141 return csearch::get_trait_of_item(&tcx.sess.cstore, def_id, tcx);
6143 match tcx.impl_or_trait_items.borrow().get(&def_id).cloned() {
6144 Some(impl_or_trait_item) => {
6145 match impl_or_trait_item.container() {
6146 TraitContainer(def_id) => Some(def_id),
6147 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
6154 /// If the given def ID describes an item belonging to a trait, (either a
6155 /// default method or an implementation of a trait method), return the ID of
6156 /// the method inside trait definition (this means that if the given def ID
6157 /// is already that of the original trait method, then the return value is
6159 /// Otherwise, return `None`.
6160 pub fn trait_item_of_item(tcx: &ctxt, def_id: ast::DefId)
6161 -> Option<ImplOrTraitItemId> {
6162 let impl_item = match tcx.impl_or_trait_items.borrow().get(&def_id) {
6163 Some(m) => m.clone(),
6164 None => return None,
6166 let name = impl_item.name();
6167 match trait_of_item(tcx, def_id) {
6168 Some(trait_did) => {
6169 let trait_items = ty::trait_items(tcx, trait_did);
6171 .position(|m| m.name() == name)
6172 .map(|idx| ty::trait_item(tcx, trait_did, idx).id())
6178 /// Creates a hash of the type `Ty` which will be the same no matter what crate
6179 /// context it's calculated within. This is used by the `type_id` intrinsic.
6180 pub fn hash_crate_independent<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh) -> u64 {
6181 let mut state = SipHasher::new();
6182 helper(tcx, ty, svh, &mut state);
6183 return state.finish();
6185 fn helper<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh,
6186 state: &mut SipHasher) {
6187 macro_rules! byte { ($b:expr) => { ($b as u8).hash(state) } }
6188 macro_rules! hash { ($e:expr) => { $e.hash(state) } }
6190 let region = |state: &mut SipHasher, r: Region| {
6193 ReLateBound(db, BrAnon(i)) => {
6203 tcx.sess.bug("unexpected region found when hashing a type")
6207 let did = |state: &mut SipHasher, did: DefId| {
6208 let h = if ast_util::is_local(did) {
6211 tcx.sess.cstore.get_crate_hash(did.krate)
6213 h.as_str().hash(state);
6214 did.node.hash(state);
6216 let mt = |state: &mut SipHasher, mt: mt| {
6217 mt.mutbl.hash(state);
6219 let fn_sig = |state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| {
6220 let sig = anonymize_late_bound_regions(tcx, sig).0;
6221 for a in &sig.inputs { helper(tcx, *a, svh, state); }
6222 if let ty::FnConverging(output) = sig.output {
6223 helper(tcx, output, svh, state);
6226 maybe_walk_ty(ty, |ty| {
6228 ty_bool => byte!(2),
6229 ty_char => byte!(3),
6252 ty_vec(_, Some(n)) => {
6256 ty_vec(_, None) => {
6268 ty_bare_fn(opt_def_id, ref b) => {
6273 fn_sig(state, &b.sig);
6276 ty_trait(ref data) => {
6278 did(state, data.principal_def_id());
6281 let principal = anonymize_late_bound_regions(tcx, &data.principal).0;
6282 for subty in principal.substs.types.iter() {
6283 helper(tcx, *subty, svh, state);
6288 ty_struct(d, _) => {
6292 ty_tup(ref inner) => {
6300 hash!(token::get_name(p.name));
6302 ty_open(_) => byte!(22),
6303 ty_infer(_) => unreachable!(),
6304 ty_err => byte!(23),
6305 ty_closure(d, r, _) => {
6310 ty_projection(ref data) => {
6312 did(state, data.trait_ref.def_id);
6313 hash!(token::get_name(data.item_name));
6322 pub fn to_string(self) -> &'static str {
6325 Contravariant => "-",
6332 /// Construct a parameter environment suitable for static contexts or other contexts where there
6333 /// are no free type/lifetime parameters in scope.
6334 pub fn empty_parameter_environment<'a,'tcx>(cx: &'a ctxt<'tcx>) -> ParameterEnvironment<'a,'tcx> {
6335 ty::ParameterEnvironment { tcx: cx,
6336 free_substs: Substs::empty(),
6337 caller_bounds: Vec::new(),
6338 implicit_region_bound: ty::ReEmpty,
6339 selection_cache: traits::SelectionCache::new(), }
6342 /// Constructs and returns a substitution that can be applied to move from
6343 /// the "outer" view of a type or method to the "inner" view.
6344 /// In general, this means converting from bound parameters to
6345 /// free parameters. Since we currently represent bound/free type
6346 /// parameters in the same way, this only has an effect on regions.
6347 pub fn construct_free_substs<'a,'tcx>(
6348 tcx: &'a ctxt<'tcx>,
6349 generics: &Generics<'tcx>,
6350 free_id: ast::NodeId)
6354 let mut types = VecPerParamSpace::empty();
6355 push_types_from_defs(tcx, &mut types, generics.types.as_slice());
6357 let free_id_outlive = region::DestructionScopeData::new(free_id);
6359 // map bound 'a => free 'a
6360 let mut regions = VecPerParamSpace::empty();
6361 push_region_params(&mut regions, free_id_outlive, generics.regions.as_slice());
6365 regions: subst::NonerasedRegions(regions)
6368 fn push_region_params(regions: &mut VecPerParamSpace<ty::Region>,
6369 all_outlive_extent: region::DestructionScopeData,
6370 region_params: &[RegionParameterDef])
6372 for r in region_params {
6373 regions.push(r.space, ty::free_region_from_def(all_outlive_extent, r));
6377 fn push_types_from_defs<'tcx>(tcx: &ty::ctxt<'tcx>,
6378 types: &mut VecPerParamSpace<Ty<'tcx>>,
6379 defs: &[TypeParameterDef<'tcx>]) {
6381 debug!("construct_parameter_environment(): push_types_from_defs: def={:?}",
6383 let ty = ty::mk_param_from_def(tcx, def);
6384 types.push(def.space, ty);
6389 /// See `ParameterEnvironment` struct def'n for details
6390 pub fn construct_parameter_environment<'a,'tcx>(
6391 tcx: &'a ctxt<'tcx>,
6393 generics: &ty::Generics<'tcx>,
6394 generic_predicates: &ty::GenericPredicates<'tcx>,
6395 free_id: ast::NodeId)
6396 -> ParameterEnvironment<'a, 'tcx>
6399 // Construct the free substs.
6402 let free_substs = construct_free_substs(tcx, generics, free_id);
6403 let free_id_outlive = region::DestructionScopeData::new(free_id);
6406 // Compute the bounds on Self and the type parameters.
6409 let bounds = generic_predicates.instantiate(tcx, &free_substs);
6410 let bounds = liberate_late_bound_regions(tcx, free_id_outlive, &ty::Binder(bounds));
6411 let predicates = bounds.predicates.into_vec();
6414 // Compute region bounds. For now, these relations are stored in a
6415 // global table on the tcx, so just enter them there. I'm not
6416 // crazy about this scheme, but it's convenient, at least.
6419 record_region_bounds(tcx, &*predicates);
6421 debug!("construct_parameter_environment: free_id={:?} free_subst={:?} predicates={:?}",
6423 free_substs.repr(tcx),
6424 predicates.repr(tcx));
6427 // Finally, we have to normalize the bounds in the environment, in
6428 // case they contain any associated type projections. This process
6429 // can yield errors if the put in illegal associated types, like
6430 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
6431 // report these errors right here; this doesn't actually feel
6432 // right to me, because constructing the environment feels like a
6433 // kind of a "idempotent" action, but I'm not sure where would be
6434 // a better place. In practice, we construct environments for
6435 // every fn once during type checking, and we'll abort if there
6436 // are any errors at that point, so after type checking you can be
6437 // sure that this will succeed without errors anyway.
6440 let unnormalized_env = ty::ParameterEnvironment {
6442 free_substs: free_substs,
6443 implicit_region_bound: ty::ReScope(free_id_outlive.to_code_extent()),
6444 caller_bounds: predicates,
6445 selection_cache: traits::SelectionCache::new(),
6448 let cause = traits::ObligationCause::misc(span, free_id);
6449 return traits::normalize_param_env_or_error(unnormalized_env, cause);
6451 fn record_region_bounds<'tcx>(tcx: &ty::ctxt<'tcx>, predicates: &[ty::Predicate<'tcx>]) {
6452 debug!("record_region_bounds(predicates={:?})", predicates.repr(tcx));
6454 for predicate in predicates {
6456 Predicate::Projection(..) |
6457 Predicate::Trait(..) |
6458 Predicate::Equate(..) |
6459 Predicate::TypeOutlives(..) => {
6460 // No region bounds here
6462 Predicate::RegionOutlives(ty::Binder(ty::OutlivesPredicate(r_a, r_b))) => {
6464 (ty::ReFree(fr_a), ty::ReFree(fr_b)) => {
6465 // Record that `'a:'b`. Or, put another way, `'b <= 'a`.
6466 tcx.region_maps.relate_free_regions(fr_b, fr_a);
6469 // All named regions are instantiated with free regions.
6471 &format!("record_region_bounds: non free region: {} / {}",
6483 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
6485 ast::MutMutable => MutBorrow,
6486 ast::MutImmutable => ImmBorrow,
6490 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
6491 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
6492 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
6494 pub fn to_mutbl_lossy(self) -> ast::Mutability {
6496 MutBorrow => ast::MutMutable,
6497 ImmBorrow => ast::MutImmutable,
6499 // We have no type corresponding to a unique imm borrow, so
6500 // use `&mut`. It gives all the capabilities of an `&uniq`
6501 // and hence is a safe "over approximation".
6502 UniqueImmBorrow => ast::MutMutable,
6506 pub fn to_user_str(&self) -> &'static str {
6508 MutBorrow => "mutable",
6509 ImmBorrow => "immutable",
6510 UniqueImmBorrow => "uniquely immutable",
6515 impl<'tcx> ctxt<'tcx> {
6516 pub fn is_method_call(&self, expr_id: ast::NodeId) -> bool {
6517 self.method_map.borrow().contains_key(&MethodCall::expr(expr_id))
6520 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
6521 Some(self.upvar_capture_map.borrow()[upvar_id].clone())
6525 impl<'a,'tcx> mc::Typer<'tcx> for ParameterEnvironment<'a,'tcx> {
6526 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<Ty<'tcx>> {
6527 Ok(ty::node_id_to_type(self.tcx, id))
6530 fn expr_ty_adjusted(&self, expr: &ast::Expr) -> mc::McResult<Ty<'tcx>> {
6531 Ok(ty::expr_ty_adjusted(self.tcx, expr))
6534 fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>> {
6535 self.tcx.method_map.borrow().get(&method_call).map(|method| method.ty)
6538 fn node_method_origin(&self, method_call: ty::MethodCall)
6539 -> Option<ty::MethodOrigin<'tcx>>
6541 self.tcx.method_map.borrow().get(&method_call).map(|method| method.origin.clone())
6544 fn adjustments(&self) -> &RefCell<NodeMap<ty::AutoAdjustment<'tcx>>> {
6545 &self.tcx.adjustments
6548 fn is_method_call(&self, id: ast::NodeId) -> bool {
6549 self.tcx.is_method_call(id)
6552 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent> {
6553 self.tcx.region_maps.temporary_scope(rvalue_id)
6556 fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
6557 self.tcx.upvar_capture(upvar_id)
6560 fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool {
6561 type_moves_by_default(self, span, ty)
6565 impl<'a,'tcx> ClosureTyper<'tcx> for ty::ParameterEnvironment<'a,'tcx> {
6566 fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> {
6570 fn closure_kind(&self,
6572 -> Option<ty::ClosureKind>
6574 Some(self.tcx.closure_kind(def_id))
6577 fn closure_type(&self,
6579 substs: &subst::Substs<'tcx>)
6580 -> ty::ClosureTy<'tcx>
6582 self.tcx.closure_type(def_id, substs)
6585 fn closure_upvars(&self,
6587 substs: &Substs<'tcx>)
6588 -> Option<Vec<ClosureUpvar<'tcx>>>
6590 closure_upvars(self, def_id, substs)
6595 /// The category of explicit self.
6596 #[derive(Clone, Copy, Eq, PartialEq, Debug)]
6597 pub enum ExplicitSelfCategory {
6598 StaticExplicitSelfCategory,
6599 ByValueExplicitSelfCategory,
6600 ByReferenceExplicitSelfCategory(Region, ast::Mutability),
6601 ByBoxExplicitSelfCategory,
6604 /// Pushes all the lifetimes in the given type onto the given list. A
6605 /// "lifetime in a type" is a lifetime specified by a reference or a lifetime
6606 /// in a list of type substitutions. This does *not* traverse into nominal
6607 /// types, nor does it resolve fictitious types.
6608 pub fn accumulate_lifetimes_in_type(accumulator: &mut Vec<ty::Region>,
6612 ty_rptr(region, _) => {
6613 accumulator.push(*region)
6615 ty_trait(ref t) => {
6616 accumulator.push_all(t.principal.0.substs.regions().as_slice());
6618 ty_enum(_, substs) |
6619 ty_struct(_, substs) => {
6620 accum_substs(accumulator, substs);
6622 ty_closure(_, region, substs) => {
6623 accumulator.push(*region);
6624 accum_substs(accumulator, substs);
6646 fn accum_substs(accumulator: &mut Vec<Region>, substs: &Substs) {
6647 match substs.regions {
6648 subst::ErasedRegions => {}
6649 subst::NonerasedRegions(ref regions) => {
6650 for region in regions.iter() {
6651 accumulator.push(*region)
6658 /// A free variable referred to in a function.
6659 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
6660 pub struct Freevar {
6661 /// The variable being accessed free.
6664 // First span where it is accessed (there can be multiple).
6668 pub type FreevarMap = NodeMap<Vec<Freevar>>;
6670 pub type CaptureModeMap = NodeMap<ast::CaptureClause>;
6672 // Trait method resolution
6673 pub type TraitMap = NodeMap<Vec<DefId>>;
6675 // Map from the NodeId of a glob import to a list of items which are actually
6677 pub type GlobMap = HashMap<NodeId, HashSet<Name>>;
6679 pub fn with_freevars<T, F>(tcx: &ty::ctxt, fid: ast::NodeId, f: F) -> T where
6680 F: FnOnce(&[Freevar]) -> T,
6682 match tcx.freevars.borrow().get(&fid) {
6684 Some(d) => f(&d[..])
6688 impl<'tcx> AutoAdjustment<'tcx> {
6689 pub fn is_identity(&self) -> bool {
6691 AdjustReifyFnPointer(..) => false,
6692 AdjustDerefRef(ref r) => r.is_identity(),
6697 impl<'tcx> AutoDerefRef<'tcx> {
6698 pub fn is_identity(&self) -> bool {
6699 self.autoderefs == 0 && self.autoref.is_none()
6703 /// Replace any late-bound regions bound in `value` with free variants attached to scope-id
6705 pub fn liberate_late_bound_regions<'tcx, T>(
6706 tcx: &ty::ctxt<'tcx>,
6707 all_outlive_scope: region::DestructionScopeData,
6710 where T : TypeFoldable<'tcx> + Repr<'tcx>
6712 replace_late_bound_regions(
6714 |br| ty::ReFree(ty::FreeRegion{scope: all_outlive_scope, bound_region: br})).0
6717 pub fn count_late_bound_regions<'tcx, T>(
6718 tcx: &ty::ctxt<'tcx>,
6721 where T : TypeFoldable<'tcx> + Repr<'tcx>
6723 let (_, skol_map) = replace_late_bound_regions(tcx, value, |_| ty::ReStatic);
6727 pub fn binds_late_bound_regions<'tcx, T>(
6728 tcx: &ty::ctxt<'tcx>,
6731 where T : TypeFoldable<'tcx> + Repr<'tcx>
6733 count_late_bound_regions(tcx, value) > 0
6736 pub fn no_late_bound_regions<'tcx, T>(
6737 tcx: &ty::ctxt<'tcx>,
6740 where T : TypeFoldable<'tcx> + Repr<'tcx> + Clone
6742 if binds_late_bound_regions(tcx, value) {
6745 Some(value.0.clone())
6749 /// Replace any late-bound regions bound in `value` with `'static`. Useful in trans but also
6750 /// method lookup and a few other places where precise region relationships are not required.
6751 pub fn erase_late_bound_regions<'tcx, T>(
6752 tcx: &ty::ctxt<'tcx>,
6755 where T : TypeFoldable<'tcx> + Repr<'tcx>
6757 replace_late_bound_regions(tcx, value, |_| ty::ReStatic).0
6760 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
6761 /// assigned starting at 1 and increasing monotonically in the order traversed
6762 /// by the fold operation.
6764 /// The chief purpose of this function is to canonicalize regions so that two
6765 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
6766 /// structurally identical. For example, `for<'a, 'b> fn(&'a int, &'b int)` and
6767 /// `for<'a, 'b> fn(&'b int, &'a int)` will become identical after anonymization.
6768 pub fn anonymize_late_bound_regions<'tcx, T>(
6772 where T : TypeFoldable<'tcx> + Repr<'tcx>,
6774 let mut counter = 0;
6775 ty::Binder(replace_late_bound_regions(tcx, sig, |_| {
6777 ReLateBound(ty::DebruijnIndex::new(1), BrAnon(counter))
6781 /// Replaces the late-bound-regions in `value` that are bound by `value`.
6782 pub fn replace_late_bound_regions<'tcx, T, F>(
6783 tcx: &ty::ctxt<'tcx>,
6786 -> (T, FnvHashMap<ty::BoundRegion,ty::Region>)
6787 where T : TypeFoldable<'tcx> + Repr<'tcx>,
6788 F : FnMut(BoundRegion) -> ty::Region,
6790 debug!("replace_late_bound_regions({})", binder.repr(tcx));
6792 let mut map = FnvHashMap();
6794 // Note: fold the field `0`, not the binder, so that late-bound
6795 // regions bound by `binder` are considered free.
6796 let value = ty_fold::fold_regions(tcx, &binder.0, |region, current_depth| {
6797 debug!("region={}", region.repr(tcx));
6799 ty::ReLateBound(debruijn, br) if debruijn.depth == current_depth => {
6801 * map.entry(br).get().unwrap_or_else(
6802 |vacant_entry| vacant_entry.insert(mapf(br)));
6804 if let ty::ReLateBound(debruijn1, br) = region {
6805 // If the callback returns a late-bound region,
6806 // that region should always use depth 1. Then we
6807 // adjust it to the correct depth.
6808 assert_eq!(debruijn1.depth, 1);
6809 ty::ReLateBound(debruijn, br)
6820 debug!("resulting map: {:?} value: {:?}", map, value.repr(tcx));
6824 impl DebruijnIndex {
6825 pub fn new(depth: u32) -> DebruijnIndex {
6827 DebruijnIndex { depth: depth }
6830 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
6831 DebruijnIndex { depth: self.depth + amount }
6835 impl<'tcx> Repr<'tcx> for AutoAdjustment<'tcx> {
6836 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6838 AdjustReifyFnPointer(def_id) => {
6839 format!("AdjustReifyFnPointer({})", def_id.repr(tcx))
6841 AdjustDerefRef(ref data) => {
6848 impl<'tcx> Repr<'tcx> for UnsizeKind<'tcx> {
6849 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6851 UnsizeLength(n) => format!("UnsizeLength({})", n),
6852 UnsizeStruct(ref k, n) => format!("UnsizeStruct({},{})", k.repr(tcx), n),
6853 UnsizeVtable(ref a, ref b) => format!("UnsizeVtable({},{})", a.repr(tcx), b.repr(tcx)),
6858 impl<'tcx> Repr<'tcx> for AutoDerefRef<'tcx> {
6859 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6860 format!("AutoDerefRef({}, {})", self.autoderefs, self.autoref.repr(tcx))
6864 impl<'tcx> Repr<'tcx> for AutoRef<'tcx> {
6865 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6867 AutoPtr(a, b, ref c) => {
6868 format!("AutoPtr({},{:?},{})", a.repr(tcx), b, c.repr(tcx))
6870 AutoUnsize(ref a) => {
6871 format!("AutoUnsize({})", a.repr(tcx))
6873 AutoUnsizeUniq(ref a) => {
6874 format!("AutoUnsizeUniq({})", a.repr(tcx))
6876 AutoUnsafe(ref a, ref b) => {
6877 format!("AutoUnsafe({:?},{})", a, b.repr(tcx))
6883 impl<'tcx> Repr<'tcx> for TyTrait<'tcx> {
6884 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6885 format!("TyTrait({},{})",
6886 self.principal.repr(tcx),
6887 self.bounds.repr(tcx))
6891 impl<'tcx> Repr<'tcx> for ty::Predicate<'tcx> {
6892 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6894 Predicate::Trait(ref a) => a.repr(tcx),
6895 Predicate::Equate(ref pair) => pair.repr(tcx),
6896 Predicate::RegionOutlives(ref pair) => pair.repr(tcx),
6897 Predicate::TypeOutlives(ref pair) => pair.repr(tcx),
6898 Predicate::Projection(ref pair) => pair.repr(tcx),
6903 impl<'tcx> Repr<'tcx> for vtable_origin<'tcx> {
6904 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
6906 vtable_static(def_id, ref tys, ref vtable_res) => {
6907 format!("vtable_static({:?}:{}, {}, {})",
6909 ty::item_path_str(tcx, def_id),
6911 vtable_res.repr(tcx))
6914 vtable_param(x, y) => {
6915 format!("vtable_param({:?}, {})", x, y)
6918 vtable_closure(def_id) => {
6919 format!("vtable_closure({:?})", def_id)
6923 format!("vtable_error")
6929 pub fn make_substs_for_receiver_types<'tcx>(tcx: &ty::ctxt<'tcx>,
6930 trait_ref: &ty::TraitRef<'tcx>,
6931 method: &ty::Method<'tcx>)
6932 -> subst::Substs<'tcx>
6935 * Substitutes the values for the receiver's type parameters
6936 * that are found in method, leaving the method's type parameters
6940 let meth_tps: Vec<Ty> =
6941 method.generics.types.get_slice(subst::FnSpace)
6943 .map(|def| ty::mk_param_from_def(tcx, def))
6945 let meth_regions: Vec<ty::Region> =
6946 method.generics.regions.get_slice(subst::FnSpace)
6948 .map(|def| ty::ReEarlyBound(def.def_id.node, def.space,
6949 def.index, def.name))
6951 trait_ref.substs.clone().with_method(meth_tps, meth_regions)
6955 pub enum CopyImplementationError {
6956 FieldDoesNotImplementCopy(ast::Name),
6957 VariantDoesNotImplementCopy(ast::Name),
6962 pub fn can_type_implement_copy<'a,'tcx>(param_env: &ParameterEnvironment<'a, 'tcx>,
6964 self_type: Ty<'tcx>)
6965 -> Result<(),CopyImplementationError>
6967 let tcx = param_env.tcx;
6969 let did = match self_type.sty {
6970 ty::ty_struct(struct_did, substs) => {
6971 let fields = ty::struct_fields(tcx, struct_did, substs);
6972 for field in &fields {
6973 if type_moves_by_default(param_env, span, field.mt.ty) {
6974 return Err(FieldDoesNotImplementCopy(field.name))
6979 ty::ty_enum(enum_did, substs) => {
6980 let enum_variants = ty::enum_variants(tcx, enum_did);
6981 for variant in &*enum_variants {
6982 for variant_arg_type in &variant.args {
6983 let substd_arg_type =
6984 variant_arg_type.subst(tcx, substs);
6985 if type_moves_by_default(param_env, span, substd_arg_type) {
6986 return Err(VariantDoesNotImplementCopy(variant.name))
6992 _ => return Err(TypeIsStructural),
6995 if ty::has_dtor(tcx, did) {
6996 return Err(TypeHasDestructor)
7002 // FIXME(#20298) -- all of these types basically walk various
7003 // structures to test whether types/regions are reachable with various
7004 // properties. It should be possible to express them in terms of one
7005 // common "walker" trait or something.
7007 pub trait RegionEscape {
7008 fn has_escaping_regions(&self) -> bool {
7009 self.has_regions_escaping_depth(0)
7012 fn has_regions_escaping_depth(&self, depth: u32) -> bool;
7015 impl<'tcx> RegionEscape for Ty<'tcx> {
7016 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7017 ty::type_escapes_depth(*self, depth)
7021 impl<'tcx> RegionEscape for Substs<'tcx> {
7022 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7023 self.types.has_regions_escaping_depth(depth) ||
7024 self.regions.has_regions_escaping_depth(depth)
7028 impl<'tcx,T:RegionEscape> RegionEscape for VecPerParamSpace<T> {
7029 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7030 self.iter_enumerated().any(|(space, _, t)| {
7031 if space == subst::FnSpace {
7032 t.has_regions_escaping_depth(depth+1)
7034 t.has_regions_escaping_depth(depth)
7040 impl<'tcx> RegionEscape for TypeScheme<'tcx> {
7041 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7042 self.ty.has_regions_escaping_depth(depth)
7046 impl RegionEscape for Region {
7047 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7048 self.escapes_depth(depth)
7052 impl<'tcx> RegionEscape for GenericPredicates<'tcx> {
7053 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7054 self.predicates.has_regions_escaping_depth(depth)
7058 impl<'tcx> RegionEscape for Predicate<'tcx> {
7059 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7061 Predicate::Trait(ref data) => data.has_regions_escaping_depth(depth),
7062 Predicate::Equate(ref data) => data.has_regions_escaping_depth(depth),
7063 Predicate::RegionOutlives(ref data) => data.has_regions_escaping_depth(depth),
7064 Predicate::TypeOutlives(ref data) => data.has_regions_escaping_depth(depth),
7065 Predicate::Projection(ref data) => data.has_regions_escaping_depth(depth),
7070 impl<'tcx> RegionEscape for TraitRef<'tcx> {
7071 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7072 self.substs.types.iter().any(|t| t.has_regions_escaping_depth(depth)) ||
7073 self.substs.regions.has_regions_escaping_depth(depth)
7077 impl<'tcx> RegionEscape for subst::RegionSubsts {
7078 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7080 subst::ErasedRegions => false,
7081 subst::NonerasedRegions(ref r) => {
7082 r.iter().any(|t| t.has_regions_escaping_depth(depth))
7088 impl<'tcx,T:RegionEscape> RegionEscape for Binder<T> {
7089 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7090 self.0.has_regions_escaping_depth(depth + 1)
7094 impl<'tcx> RegionEscape for EquatePredicate<'tcx> {
7095 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7096 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7100 impl<'tcx> RegionEscape for TraitPredicate<'tcx> {
7101 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7102 self.trait_ref.has_regions_escaping_depth(depth)
7106 impl<T:RegionEscape,U:RegionEscape> RegionEscape for OutlivesPredicate<T,U> {
7107 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7108 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7112 impl<'tcx> RegionEscape for ProjectionPredicate<'tcx> {
7113 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7114 self.projection_ty.has_regions_escaping_depth(depth) ||
7115 self.ty.has_regions_escaping_depth(depth)
7119 impl<'tcx> RegionEscape for ProjectionTy<'tcx> {
7120 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7121 self.trait_ref.has_regions_escaping_depth(depth)
7125 impl<'tcx> Repr<'tcx> for ty::ProjectionPredicate<'tcx> {
7126 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7127 format!("ProjectionPredicate({}, {})",
7128 self.projection_ty.repr(tcx),
7133 pub trait HasProjectionTypes {
7134 fn has_projection_types(&self) -> bool;
7137 impl<'tcx,T:HasProjectionTypes> HasProjectionTypes for Vec<T> {
7138 fn has_projection_types(&self) -> bool {
7139 self.iter().any(|p| p.has_projection_types())
7143 impl<'tcx,T:HasProjectionTypes> HasProjectionTypes for VecPerParamSpace<T> {
7144 fn has_projection_types(&self) -> bool {
7145 self.iter().any(|p| p.has_projection_types())
7149 impl<'tcx> HasProjectionTypes for ClosureTy<'tcx> {
7150 fn has_projection_types(&self) -> bool {
7151 self.sig.has_projection_types()
7155 impl<'tcx> HasProjectionTypes for ClosureUpvar<'tcx> {
7156 fn has_projection_types(&self) -> bool {
7157 self.ty.has_projection_types()
7161 impl<'tcx> HasProjectionTypes for ty::InstantiatedPredicates<'tcx> {
7162 fn has_projection_types(&self) -> bool {
7163 self.predicates.has_projection_types()
7167 impl<'tcx> HasProjectionTypes for Predicate<'tcx> {
7168 fn has_projection_types(&self) -> bool {
7170 Predicate::Trait(ref data) => data.has_projection_types(),
7171 Predicate::Equate(ref data) => data.has_projection_types(),
7172 Predicate::RegionOutlives(ref data) => data.has_projection_types(),
7173 Predicate::TypeOutlives(ref data) => data.has_projection_types(),
7174 Predicate::Projection(ref data) => data.has_projection_types(),
7179 impl<'tcx> HasProjectionTypes for TraitPredicate<'tcx> {
7180 fn has_projection_types(&self) -> bool {
7181 self.trait_ref.has_projection_types()
7185 impl<'tcx> HasProjectionTypes for EquatePredicate<'tcx> {
7186 fn has_projection_types(&self) -> bool {
7187 self.0.has_projection_types() || self.1.has_projection_types()
7191 impl HasProjectionTypes for Region {
7192 fn has_projection_types(&self) -> bool {
7197 impl<T:HasProjectionTypes,U:HasProjectionTypes> HasProjectionTypes for OutlivesPredicate<T,U> {
7198 fn has_projection_types(&self) -> bool {
7199 self.0.has_projection_types() || self.1.has_projection_types()
7203 impl<'tcx> HasProjectionTypes for ProjectionPredicate<'tcx> {
7204 fn has_projection_types(&self) -> bool {
7205 self.projection_ty.has_projection_types() || self.ty.has_projection_types()
7209 impl<'tcx> HasProjectionTypes for ProjectionTy<'tcx> {
7210 fn has_projection_types(&self) -> bool {
7211 self.trait_ref.has_projection_types()
7215 impl<'tcx> HasProjectionTypes for Ty<'tcx> {
7216 fn has_projection_types(&self) -> bool {
7217 ty::type_has_projection(*self)
7221 impl<'tcx> HasProjectionTypes for TraitRef<'tcx> {
7222 fn has_projection_types(&self) -> bool {
7223 self.substs.has_projection_types()
7227 impl<'tcx> HasProjectionTypes for subst::Substs<'tcx> {
7228 fn has_projection_types(&self) -> bool {
7229 self.types.iter().any(|t| t.has_projection_types())
7233 impl<'tcx,T> HasProjectionTypes for Option<T>
7234 where T : HasProjectionTypes
7236 fn has_projection_types(&self) -> bool {
7237 self.iter().any(|t| t.has_projection_types())
7241 impl<'tcx,T> HasProjectionTypes for Rc<T>
7242 where T : HasProjectionTypes
7244 fn has_projection_types(&self) -> bool {
7245 (**self).has_projection_types()
7249 impl<'tcx,T> HasProjectionTypes for Box<T>
7250 where T : HasProjectionTypes
7252 fn has_projection_types(&self) -> bool {
7253 (**self).has_projection_types()
7257 impl<T> HasProjectionTypes for Binder<T>
7258 where T : HasProjectionTypes
7260 fn has_projection_types(&self) -> bool {
7261 self.0.has_projection_types()
7265 impl<'tcx> HasProjectionTypes for FnOutput<'tcx> {
7266 fn has_projection_types(&self) -> bool {
7268 FnConverging(t) => t.has_projection_types(),
7269 FnDiverging => false,
7274 impl<'tcx> HasProjectionTypes for FnSig<'tcx> {
7275 fn has_projection_types(&self) -> bool {
7276 self.inputs.iter().any(|t| t.has_projection_types()) ||
7277 self.output.has_projection_types()
7281 impl<'tcx> HasProjectionTypes for field<'tcx> {
7282 fn has_projection_types(&self) -> bool {
7283 self.mt.ty.has_projection_types()
7287 impl<'tcx> HasProjectionTypes for BareFnTy<'tcx> {
7288 fn has_projection_types(&self) -> bool {
7289 self.sig.has_projection_types()
7293 pub trait ReferencesError {
7294 fn references_error(&self) -> bool;
7297 impl<T:ReferencesError> ReferencesError for Binder<T> {
7298 fn references_error(&self) -> bool {
7299 self.0.references_error()
7303 impl<T:ReferencesError> ReferencesError for Rc<T> {
7304 fn references_error(&self) -> bool {
7305 (&**self).references_error()
7309 impl<'tcx> ReferencesError for TraitPredicate<'tcx> {
7310 fn references_error(&self) -> bool {
7311 self.trait_ref.references_error()
7315 impl<'tcx> ReferencesError for ProjectionPredicate<'tcx> {
7316 fn references_error(&self) -> bool {
7317 self.projection_ty.trait_ref.references_error() || self.ty.references_error()
7321 impl<'tcx> ReferencesError for TraitRef<'tcx> {
7322 fn references_error(&self) -> bool {
7323 self.input_types().iter().any(|t| t.references_error())
7327 impl<'tcx> ReferencesError for Ty<'tcx> {
7328 fn references_error(&self) -> bool {
7329 type_is_error(*self)
7333 impl<'tcx> ReferencesError for Predicate<'tcx> {
7334 fn references_error(&self) -> bool {
7336 Predicate::Trait(ref data) => data.references_error(),
7337 Predicate::Equate(ref data) => data.references_error(),
7338 Predicate::RegionOutlives(ref data) => data.references_error(),
7339 Predicate::TypeOutlives(ref data) => data.references_error(),
7340 Predicate::Projection(ref data) => data.references_error(),
7345 impl<A,B> ReferencesError for OutlivesPredicate<A,B>
7346 where A : ReferencesError, B : ReferencesError
7348 fn references_error(&self) -> bool {
7349 self.0.references_error() || self.1.references_error()
7353 impl<'tcx> ReferencesError for EquatePredicate<'tcx>
7355 fn references_error(&self) -> bool {
7356 self.0.references_error() || self.1.references_error()
7360 impl ReferencesError for Region
7362 fn references_error(&self) -> bool {
7367 impl<'tcx> Repr<'tcx> for ClosureTy<'tcx> {
7368 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7369 format!("ClosureTy({},{},{})",
7376 impl<'tcx> Repr<'tcx> for ClosureUpvar<'tcx> {
7377 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7378 format!("ClosureUpvar({},{})",
7384 impl<'tcx> Repr<'tcx> for field<'tcx> {
7385 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7386 format!("field({},{})",
7387 self.name.repr(tcx),
7392 impl<'a, 'tcx> Repr<'tcx> for ParameterEnvironment<'a, 'tcx> {
7393 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7394 format!("ParameterEnvironment(\
7396 implicit_region_bound={}, \
7398 self.free_substs.repr(tcx),
7399 self.implicit_region_bound.repr(tcx),
7400 self.caller_bounds.repr(tcx))
7404 impl<'tcx> Repr<'tcx> for ObjectLifetimeDefault {
7405 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7407 ObjectLifetimeDefault::Ambiguous => format!("Ambiguous"),
7408 ObjectLifetimeDefault::Specific(ref r) => r.repr(tcx),