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.
12 use metadata::csearch;
14 use middle::const_eval;
15 use middle::lang_items::{ExchangeHeapLangItem, OpaqueStructLangItem};
16 use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem};
19 use middle::resolve_lifetime;
21 use middle::subst::Subst;
24 use middle::ty_fold::TypeFolder;
26 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_str};
27 use util::ppaux::{trait_store_to_str, ty_to_str, vstore_to_str};
28 use util::ppaux::{Repr, UserString};
29 use util::common::{indenter};
32 use std::cell::{Cell, RefCell};
34 use std::hashmap::{HashMap, HashSet};
36 use std::ptr::to_unsafe_ptr;
38 use std::to_str::ToStr;
41 use syntax::ast_util::{is_local, lit_is_str};
44 use syntax::attr::AttrMetaMethods;
45 use syntax::codemap::Span;
46 use syntax::parse::token;
47 use syntax::{ast, ast_map};
48 use syntax::opt_vec::OptVec;
50 use syntax::abi::AbiSet;
52 use extra::enum_set::{EnumSet, CLike};
56 pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0;
60 #[deriving(Eq, IterBytes)]
67 pub enum MethodContainer {
68 TraitContainer(ast::DefId),
69 ImplContainer(ast::DefId),
75 generics: ty::Generics,
77 explicit_self: ast::ExplicitSelf_,
80 container: MethodContainer,
82 // If this method is provided, we need to know where it came from
83 provided_source: Option<ast::DefId>
87 pub fn new(ident: ast::Ident,
88 generics: ty::Generics,
90 explicit_self: ast::ExplicitSelf_,
93 container: MethodContainer,
94 provided_source: Option<ast::DefId>)
100 explicit_self: explicit_self,
103 container: container,
104 provided_source: provided_source
108 pub fn container_id(&self) -> ast::DefId {
109 match self.container {
110 TraitContainer(id) => id,
111 ImplContainer(id) => id,
122 #[deriving(Clone, Eq, IterBytes)]
125 mutbl: ast::Mutability,
128 #[deriving(Clone, Eq, Encodable, Decodable, IterBytes, ToStr)]
136 #[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)]
137 pub enum TraitStore {
138 BoxTraitStore, // @Trait
139 UniqTraitStore, // ~Trait
140 RegionTraitStore(Region), // &Trait
143 pub struct field_ty {
146 vis: ast::Visibility,
149 // Contains information needed to resolve types and (in the future) look up
150 // the types of AST nodes.
151 #[deriving(Eq,IterBytes)]
152 pub struct creader_cache_key {
158 type creader_cache = RefCell<HashMap<creader_cache_key, t>>;
164 // NB: Do not replace this with #[deriving(Eq)]. The automatically-derived
165 // implementation will not recurse through sty and you will get stack
167 impl cmp::Eq for intern_key {
168 fn eq(&self, other: &intern_key) -> bool {
170 *self.sty == *other.sty
173 fn ne(&self, other: &intern_key) -> bool {
178 // NB: Do not replace this with #[deriving(IterBytes)], as above. (Figured
179 // this out the hard way.)
180 impl to_bytes::IterBytes for intern_key {
181 fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
183 (*self.sty).iter_bytes(lsb0, f)
188 pub enum ast_ty_to_ty_cache_entry {
189 atttce_unresolved, /* not resolved yet */
190 atttce_resolved(t) /* resolved to a type, irrespective of region */
193 #[deriving(Clone, Eq, Decodable, Encodable)]
194 pub struct ItemVariances {
195 self_param: Option<Variance>,
196 type_params: OptVec<Variance>,
197 region_params: OptVec<Variance>
200 #[deriving(Clone, Eq, Decodable, Encodable)]
202 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
203 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
204 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
205 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
208 pub enum AutoAdjustment {
209 AutoAddEnv(ty::Region, ast::Sigil),
210 AutoDerefRef(AutoDerefRef),
211 AutoObject(ast::Sigil, Option<ty::Region>,
214 ast::DefId, /* Trait ID */
215 ty::substs /* Trait substitutions */)
218 #[deriving(Decodable, Encodable)]
219 pub struct AutoDerefRef {
221 autoref: Option<AutoRef>
224 #[deriving(Decodable, Encodable)]
226 /// Convert from T to &T
227 AutoPtr(Region, ast::Mutability),
229 /// Convert from @[]/~[]/&[] to &[] (or str)
230 AutoBorrowVec(Region, ast::Mutability),
232 /// Convert from @[]/~[]/&[] to &&[] (or str)
233 AutoBorrowVecRef(Region, ast::Mutability),
235 /// Convert from @fn()/~fn()/|| to ||
236 AutoBorrowFn(Region),
238 /// Convert from T to *T
239 AutoUnsafe(ast::Mutability),
241 /// Convert from @Trait/~Trait/&Trait to &Trait
242 AutoBorrowObj(Region, ast::Mutability),
245 pub type ctxt = @ctxt_;
247 /// The data structure to keep track of all the information that typechecker
248 /// generates so that so that it can be reused and doesn't have to be redone
251 diag: @syntax::diagnostic::SpanHandler,
252 interner: RefCell<HashMap<intern_key, ~t_box_>>,
254 cstore: @metadata::cstore::CStore,
255 sess: session::Session,
256 def_map: resolve::DefMap,
258 named_region_map: @RefCell<resolve_lifetime::NamedRegionMap>,
260 region_maps: middle::region::RegionMaps,
262 // Stores the types for various nodes in the AST. Note that this table
263 // is not guaranteed to be populated until after typeck. See
264 // typeck::check::fn_ctxt for details.
265 node_types: node_type_table,
267 // Stores the type parameters which were substituted to obtain the type
268 // of this node. This only applies to nodes that refer to entities
269 // parameterized by type parameters, such as generic fns, types, or
271 node_type_substs: RefCell<HashMap<NodeId, ~[t]>>,
273 // Maps from a method to the method "descriptor"
274 methods: RefCell<HashMap<DefId, @Method>>,
276 // Maps from a trait def-id to a list of the def-ids of its methods
277 trait_method_def_ids: RefCell<HashMap<DefId, @~[DefId]>>,
279 // A cache for the trait_methods() routine
280 trait_methods_cache: RefCell<HashMap<DefId, @~[@Method]>>,
282 impl_trait_cache: RefCell<HashMap<ast::DefId, Option<@ty::TraitRef>>>,
284 trait_refs: RefCell<HashMap<NodeId, @TraitRef>>,
285 trait_defs: RefCell<HashMap<DefId, @TraitDef>>,
287 /// Despite its name, `items` does not only map NodeId to an item but
288 /// also to expr/stmt/local/arg/etc
290 intrinsic_defs: RefCell<HashMap<ast::DefId, t>>,
291 freevars: RefCell<freevars::freevar_map>,
293 rcache: creader_cache,
294 short_names_cache: RefCell<HashMap<t, ~str>>,
295 needs_unwind_cleanup_cache: RefCell<HashMap<t, bool>>,
296 tc_cache: RefCell<HashMap<uint, TypeContents>>,
297 ast_ty_to_ty_cache: RefCell<HashMap<NodeId, ast_ty_to_ty_cache_entry>>,
298 enum_var_cache: RefCell<HashMap<DefId, @~[@VariantInfo]>>,
299 ty_param_defs: RefCell<HashMap<ast::NodeId, TypeParameterDef>>,
300 adjustments: RefCell<HashMap<ast::NodeId, @AutoAdjustment>>,
301 normalized_cache: RefCell<HashMap<t, t>>,
302 lang_items: @middle::lang_items::LanguageItems,
303 // A mapping of fake provided method def_ids to the default implementation
304 provided_method_sources: RefCell<HashMap<ast::DefId, ast::DefId>>,
305 supertraits: RefCell<HashMap<ast::DefId, @~[@TraitRef]>>,
307 // Maps from def-id of a type or region parameter to its
308 // (inferred) variance.
309 item_variance_map: RefCell<HashMap<ast::DefId, @ItemVariances>>,
311 // A mapping from the def ID of an enum or struct type to the def ID
312 // of the method that implements its destructor. If the type is not
313 // present in this map, it does not have a destructor. This map is
314 // populated during the coherence phase of typechecking.
315 destructor_for_type: RefCell<HashMap<ast::DefId, ast::DefId>>,
317 // A method will be in this list if and only if it is a destructor.
318 destructors: RefCell<HashSet<ast::DefId>>,
320 // Maps a trait onto a list of impls of that trait.
321 trait_impls: RefCell<HashMap<ast::DefId, @RefCell<~[@Impl]>>>,
323 // Maps a def_id of a type to a list of its inherent impls.
324 // Contains implementations of methods that are inherent to a type.
325 // Methods in these implementations don't need to be exported.
326 inherent_impls: RefCell<HashMap<ast::DefId, @RefCell<~[@Impl]>>>,
328 // Maps a def_id of an impl to an Impl structure.
329 // Note that this contains all of the impls that we know about,
330 // including ones in other crates. It's not clear that this is the best
332 impls: RefCell<HashMap<ast::DefId, @Impl>>,
334 // Set of used unsafe nodes (functions or blocks). Unsafe nodes not
335 // present in this set can be warned about.
336 used_unsafe: RefCell<HashSet<ast::NodeId>>,
338 // Set of nodes which mark locals as mutable which end up getting used at
339 // some point. Local variable definitions not in this set can be warned
341 used_mut_nodes: RefCell<HashSet<ast::NodeId>>,
343 // vtable resolution information for impl declarations
344 impl_vtables: typeck::impl_vtable_map,
346 // The set of external nominal types whose implementations have been read.
347 // This is used for lazy resolution of methods.
348 populated_external_types: RefCell<HashSet<ast::DefId>>,
350 // The set of external traits whose implementations have been read. This
351 // is used for lazy resolution of traits.
352 populated_external_traits: RefCell<HashSet<ast::DefId>>,
354 // These two caches are used by const_eval when decoding external statics
355 // and variants that are found.
356 extern_const_statics: RefCell<HashMap<ast::DefId, Option<@ast::Expr>>>,
357 extern_const_variants: RefCell<HashMap<ast::DefId, Option<@ast::Expr>>>,
368 // a meta-flag: subst may be required if the type has parameters, a self
369 // type, or references bound regions
370 needs_subst = 1 | 2 | 8
373 pub type t_box = &'static t_box_;
381 // To reduce refcounting cost, we're representing types as unsafe pointers
382 // throughout the compiler. These are simply casted t_box values. Use ty::get
383 // to cast them back to a box. (Without the cast, compiler performance suffers
384 // ~15%.) This does mean that a t value relies on the ctxt to keep its box
385 // alive, and using ty::get is unsafe when the ctxt is no longer alive.
387 pub type t = *t_opaque;
390 fn to_str(&self) -> ~str {
395 pub fn get(t: t) -> t_box {
397 let t2: t_box = cast::transmute(t);
402 pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
403 (tb.flags & (flag as uint)) != 0u
405 pub fn type_has_params(t: t) -> bool {
406 tbox_has_flag(get(t), has_params)
408 pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
409 pub fn type_needs_infer(t: t) -> bool {
410 tbox_has_flag(get(t), needs_infer)
412 pub fn type_has_regions(t: t) -> bool {
413 tbox_has_flag(get(t), has_regions)
415 pub fn type_id(t: t) -> uint { get(t).id }
417 #[deriving(Clone, Eq, IterBytes)]
418 pub struct BareFnTy {
424 #[deriving(Clone, Eq, IterBytes)]
425 pub struct ClosureTy {
428 onceness: ast::Onceness,
430 bounds: BuiltinBounds,
435 * Signature of a function type, which I have arbitrarily
436 * decided to use to refer to the input/output types.
438 * - `binder_id` is the node id where this fn type appeared;
439 * it is used to identify all the bound regions appearing
440 * in the input/output types that are bound by this fn type
441 * (vs some enclosing or enclosed fn type)
442 * - `inputs` is the list of arguments and their modes.
443 * - `output` is the return type.
444 * - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
446 #[deriving(Clone, Eq, IterBytes)]
448 binder_id: ast::NodeId,
454 #[deriving(Clone, Eq, IterBytes)]
455 pub struct param_ty {
460 /// Representation of regions:
461 #[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)]
463 // Region bound in a type or fn declaration which will be
464 // substituted 'early' -- that is, at the same time when type
465 // parameters are substituted.
466 ReEarlyBound(/* param id */ ast::NodeId, /*index*/ uint, ast::Ident),
468 // Region bound in a function scope, which will be substituted when the
469 // function is called. The first argument must be the `binder_id` of
470 // some enclosing function signature.
471 ReLateBound(/* binder_id */ ast::NodeId, BoundRegion),
473 /// When checking a function body, the types of all arguments and so forth
474 /// that refer to bound region parameters are modified to refer to free
475 /// region parameters.
478 /// A concrete region naming some expression within the current function.
481 /// Static data that has an "infinite" lifetime. Top in the region lattice.
484 /// A region variable. Should not exist after typeck.
485 ReInfer(InferRegion),
487 /// Empty lifetime is for data that is never accessed.
488 /// Bottom in the region lattice. We treat ReEmpty somewhat
489 /// specially; at least right now, we do not generate instances of
490 /// it during the GLB computations, but rather
491 /// generate an error instead. This is to improve error messages.
492 /// The only way to get an instance of ReEmpty is to have a region
493 /// variable with no constraints.
498 pub fn is_bound(&self) -> bool {
500 &ty::ReEarlyBound(..) => true,
501 &ty::ReLateBound(..) => true,
507 #[deriving(Clone, Eq, TotalOrd, TotalEq, IterBytes, Encodable, Decodable, ToStr)]
508 pub struct FreeRegion {
510 bound_region: BoundRegion
513 #[deriving(Clone, Eq, TotalEq, TotalOrd, IterBytes, Encodable, Decodable, ToStr)]
514 pub enum BoundRegion {
515 /// An anonymous region parameter for a given fn (&T)
518 /// Named region parameters for functions (a in &'a T)
520 /// The def-id is needed to distinguish free regions in
521 /// the event of shadowing.
522 BrNamed(ast::DefId, ast::Ident),
524 /// Fresh bound identifiers created during GLB computations.
529 * Represents the values to use when substituting lifetime parameters.
530 * If the value is `ErasedRegions`, then this subst is occurring during
531 * trans, and all region parameters will be replaced with `ty::ReStatic`. */
532 #[deriving(Clone, Eq, IterBytes)]
533 pub enum RegionSubsts {
535 NonerasedRegions(OptVec<ty::Region>)
539 * The type substs represents the kinds of things that can be substituted to
540 * convert a polytype into a monotype. Note however that substituting bound
541 * regions other than `self` is done through a different mechanism:
543 * - `tps` represents the type parameters in scope. They are indexed
544 * according to the order in which they were declared.
546 * - `self_r` indicates the region parameter `self` that is present on nominal
547 * types (enums, structs) declared as having a region parameter. `self_r`
548 * should always be none for types that are not region-parameterized and
549 * Some(_) for types that are. The only bound region parameter that should
550 * appear within a region-parameterized type is `self`.
552 * - `self_ty` is the type to which `self` should be remapped, if any. The
553 * `self` type is rather funny in that it can only appear on traits and is
554 * always substituted away to the implementing type for a trait. */
555 #[deriving(Clone, Eq, IterBytes)]
557 self_ty: Option<ty::t>,
559 regions: RegionSubsts,
567 macro_rules! def_prim_ty(
568 ($name:ident, $sty:expr, $id:expr) => (
569 pub static $name: t_box_ = t_box_ {
577 def_prim_ty!(TY_NIL, super::ty_nil, 0)
578 def_prim_ty!(TY_BOOL, super::ty_bool, 1)
579 def_prim_ty!(TY_CHAR, super::ty_char, 2)
580 def_prim_ty!(TY_INT, super::ty_int(ast::TyI), 3)
581 def_prim_ty!(TY_I8, super::ty_int(ast::TyI8), 4)
582 def_prim_ty!(TY_I16, super::ty_int(ast::TyI16), 5)
583 def_prim_ty!(TY_I32, super::ty_int(ast::TyI32), 6)
584 def_prim_ty!(TY_I64, super::ty_int(ast::TyI64), 7)
585 def_prim_ty!(TY_UINT, super::ty_uint(ast::TyU), 8)
586 def_prim_ty!(TY_U8, super::ty_uint(ast::TyU8), 9)
587 def_prim_ty!(TY_U16, super::ty_uint(ast::TyU16), 10)
588 def_prim_ty!(TY_U32, super::ty_uint(ast::TyU32), 11)
589 def_prim_ty!(TY_U64, super::ty_uint(ast::TyU64), 12)
590 def_prim_ty!(TY_F32, super::ty_float(ast::TyF32), 14)
591 def_prim_ty!(TY_F64, super::ty_float(ast::TyF64), 15)
593 pub static TY_BOT: t_box_ = t_box_ {
596 flags: super::has_ty_bot as uint,
599 pub static TY_ERR: t_box_ = t_box_ {
602 flags: super::has_ty_err as uint,
605 pub static LAST_PRIMITIVE_ID: uint = 18;
608 // NB: If you change this, you'll probably want to change the corresponding
609 // AST structure in libsyntax/ast.rs as well.
610 #[deriving(Clone, Eq, IterBytes)]
617 ty_uint(ast::UintTy),
618 ty_float(ast::FloatTy),
620 ty_enum(DefId, substs),
626 ty_bare_fn(BareFnTy),
627 ty_closure(ClosureTy),
628 ty_trait(DefId, substs, TraitStore, ast::Mutability, BuiltinBounds),
629 ty_struct(DefId, substs),
632 ty_param(param_ty), // type parameter
633 ty_self(DefId), /* special, implicit `self` type parameter;
634 * def_id is the id of the trait */
636 ty_infer(InferTy), // something used only during inference/typeck
637 ty_err, // Also only used during inference/typeck, to represent
638 // the type of an erroneous expression (helps cut down
639 // on non-useful type error messages)
641 // "Fake" types, used for trans purposes
642 ty_type, // type_desc*
646 #[deriving(Eq, IterBytes)]
647 pub struct TraitRef {
652 #[deriving(Clone, Eq)]
653 pub enum IntVarValue {
655 UintType(ast::UintTy),
658 #[deriving(Clone, ToStr)]
659 pub enum terr_vstore_kind {
666 #[deriving(Clone, ToStr)]
667 pub struct expected_found<T> {
672 // Data structures used in type unification
673 #[deriving(Clone, ToStr)]
676 terr_purity_mismatch(expected_found<Purity>),
677 terr_onceness_mismatch(expected_found<Onceness>),
678 terr_abi_mismatch(expected_found<AbiSet>),
680 terr_sigil_mismatch(expected_found<ast::Sigil>),
685 terr_tuple_size(expected_found<uint>),
686 terr_ty_param_size(expected_found<uint>),
687 terr_record_size(expected_found<uint>),
688 terr_record_mutability,
689 terr_record_fields(expected_found<Ident>),
691 terr_regions_does_not_outlive(Region, Region),
692 terr_regions_not_same(Region, Region),
693 terr_regions_no_overlap(Region, Region),
694 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
695 terr_regions_overly_polymorphic(BoundRegion, Region),
696 terr_vstores_differ(terr_vstore_kind, expected_found<vstore>),
697 terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
698 terr_in_field(@type_err, ast::Ident),
699 terr_sorts(expected_found<t>),
700 terr_integer_as_char,
701 terr_int_mismatch(expected_found<IntVarValue>),
702 terr_float_mismatch(expected_found<ast::FloatTy>),
703 terr_traits(expected_found<ast::DefId>),
704 terr_builtin_bounds(expected_found<BuiltinBounds>),
705 terr_variadic_mismatch(expected_found<bool>)
708 #[deriving(Eq, IterBytes)]
709 pub struct ParamBounds {
710 builtin_bounds: BuiltinBounds,
711 trait_bounds: ~[@TraitRef]
714 pub type BuiltinBounds = EnumSet<BuiltinBound>;
716 #[deriving(Clone, Encodable, Eq, Decodable, IterBytes, ToStr)]
718 pub enum BuiltinBound {
726 pub fn EmptyBuiltinBounds() -> BuiltinBounds {
730 pub fn AllBuiltinBounds() -> BuiltinBounds {
731 let mut set = EnumSet::empty();
732 set.add(BoundStatic);
734 set.add(BoundFreeze);
739 impl CLike for BuiltinBound {
740 fn to_uint(&self) -> uint {
743 fn from_uint(v: uint) -> BuiltinBound {
744 unsafe { cast::transmute(v) }
748 #[deriving(Clone, Eq, IterBytes)]
749 pub struct TyVid(uint);
751 #[deriving(Clone, Eq, IterBytes)]
752 pub struct IntVid(uint);
754 #[deriving(Clone, Eq, IterBytes)]
755 pub struct FloatVid(uint);
757 #[deriving(Clone, Eq, Encodable, Decodable, IterBytes)]
758 pub struct RegionVid {
762 #[deriving(Clone, Eq, IterBytes)]
769 #[deriving(Clone, Encodable, Decodable, IterBytes, ToStr)]
770 pub enum InferRegion {
772 ReSkolemized(uint, BoundRegion)
775 impl cmp::Eq for InferRegion {
776 fn eq(&self, other: &InferRegion) -> bool {
777 match ((*self), *other) {
778 (ReVar(rva), ReVar(rvb)) => {
781 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
787 fn ne(&self, other: &InferRegion) -> bool {
788 !((*self) == (*other))
793 fn to_uint(&self) -> uint;
797 fn to_uint(&self) -> uint { let TyVid(v) = *self; v }
800 impl ToStr for TyVid {
801 fn to_str(&self) -> ~str { format!("<generic \\#{}>", self.to_uint()) }
804 impl Vid for IntVid {
805 fn to_uint(&self) -> uint { let IntVid(v) = *self; v }
808 impl ToStr for IntVid {
809 fn to_str(&self) -> ~str { format!("<generic integer \\#{}>", self.to_uint()) }
812 impl Vid for FloatVid {
813 fn to_uint(&self) -> uint { let FloatVid(v) = *self; v }
816 impl ToStr for FloatVid {
817 fn to_str(&self) -> ~str { format!("<generic float \\#{}>", self.to_uint()) }
820 impl Vid for RegionVid {
821 fn to_uint(&self) -> uint { self.id }
824 impl ToStr for RegionVid {
825 fn to_str(&self) -> ~str { format!("{:?}", self.id) }
828 impl ToStr for FnSig {
829 fn to_str(&self) -> ~str {
830 // grr, without tcx not much we can do.
835 impl ToStr for InferTy {
836 fn to_str(&self) -> ~str {
838 TyVar(ref v) => v.to_str(),
839 IntVar(ref v) => v.to_str(),
840 FloatVar(ref v) => v.to_str()
845 impl ToStr for IntVarValue {
846 fn to_str(&self) -> ~str {
848 IntType(ref v) => v.to_str(),
849 UintType(ref v) => v.to_str(),
855 pub struct TypeParameterDef {
858 bounds: @ParamBounds,
859 default: Option<ty::t>
862 #[deriving(Encodable, Decodable, Clone)]
863 pub struct RegionParameterDef {
868 /// Information about the type/lifetime parameters associated with an item.
869 /// Analogous to ast::Generics.
871 pub struct Generics {
872 /// List of type parameters declared on the item.
873 type_param_defs: @~[TypeParameterDef],
875 /// List of region parameters declared on the item.
876 region_param_defs: @[RegionParameterDef],
880 pub fn has_type_params(&self) -> bool {
881 !self.type_param_defs.is_empty()
885 /// When type checking, we use the `ParameterEnvironment` to track
886 /// details about the type/lifetime parameters that are in scope.
887 /// It primarily stores the bounds information.
889 /// Note: This information might seem to be redundant with the data in
890 /// `tcx.ty_param_defs`, but it is not. That table contains the
891 /// parameter definitions from an "outside" perspective, but this
892 /// struct will contain the bounds for a parameter as seen from inside
893 /// the function body. Currently the only real distinction is that
894 /// bound lifetime parameters are replaced with free ones, but in the
895 /// future I hope to refine the representation of types so as to make
896 /// more distinctions clearer.
897 pub struct ParameterEnvironment {
898 /// A substitution that can be applied to move from
899 /// the "outer" view of a type or method to the "inner" view.
900 /// In general, this means converting from bound parameters to
901 /// free parameters. Since we currently represent bound/free type
902 /// parameters in the same way, this only has an affect on regions.
903 free_substs: ty::substs,
905 /// Bound on the Self parameter
906 self_param_bound: Option<@TraitRef>,
908 /// Bounds on each numbered type parameter
909 type_param_bounds: ~[ParamBounds],
914 /// - `bounds`: The list of bounds for each type parameter. The length of the
915 /// list also tells you how many type parameters there are.
917 /// - `rp`: true if the type is region-parameterized. Types can have at
918 /// most one region parameter, always called `&self`.
920 /// - `ty`: the base type. May have reference to the (unsubstituted) bound
921 /// region `&self` or to (unsubstituted) ty_param types
923 pub struct ty_param_bounds_and_ty {
928 /// As `ty_param_bounds_and_ty` but for a trait ref.
929 pub struct TraitDef {
931 bounds: BuiltinBounds,
932 trait_ref: @ty::TraitRef,
935 pub struct ty_param_substs_and_ty {
940 type type_cache = RefCell<HashMap<ast::DefId, ty_param_bounds_and_ty>>;
942 pub type node_type_table = RefCell<HashMap<uint,t>>;
944 pub fn mk_ctxt(s: session::Session,
946 named_region_map: @RefCell<resolve_lifetime::NamedRegionMap>,
948 freevars: freevars::freevar_map,
949 region_maps: middle::region::RegionMaps,
950 lang_items: @middle::lang_items::LanguageItems)
953 named_region_map: named_region_map,
954 item_variance_map: RefCell::new(HashMap::new()),
955 diag: s.diagnostic(),
956 interner: RefCell::new(HashMap::new()),
957 next_id: Cell::new(primitives::LAST_PRIMITIVE_ID),
961 region_maps: region_maps,
962 node_types: RefCell::new(HashMap::new()),
963 node_type_substs: RefCell::new(HashMap::new()),
964 trait_refs: RefCell::new(HashMap::new()),
965 trait_defs: RefCell::new(HashMap::new()),
967 intrinsic_defs: RefCell::new(HashMap::new()),
968 freevars: RefCell::new(freevars),
969 tcache: RefCell::new(HashMap::new()),
970 rcache: RefCell::new(HashMap::new()),
971 short_names_cache: RefCell::new(HashMap::new()),
972 needs_unwind_cleanup_cache: RefCell::new(HashMap::new()),
973 tc_cache: RefCell::new(HashMap::new()),
974 ast_ty_to_ty_cache: RefCell::new(HashMap::new()),
975 enum_var_cache: RefCell::new(HashMap::new()),
976 methods: RefCell::new(HashMap::new()),
977 trait_method_def_ids: RefCell::new(HashMap::new()),
978 trait_methods_cache: RefCell::new(HashMap::new()),
979 impl_trait_cache: RefCell::new(HashMap::new()),
980 ty_param_defs: RefCell::new(HashMap::new()),
981 adjustments: RefCell::new(HashMap::new()),
982 normalized_cache: RefCell::new(HashMap::new()),
983 lang_items: lang_items,
984 provided_method_sources: RefCell::new(HashMap::new()),
985 supertraits: RefCell::new(HashMap::new()),
986 destructor_for_type: RefCell::new(HashMap::new()),
987 destructors: RefCell::new(HashSet::new()),
988 trait_impls: RefCell::new(HashMap::new()),
989 inherent_impls: RefCell::new(HashMap::new()),
990 impls: RefCell::new(HashMap::new()),
991 used_unsafe: RefCell::new(HashSet::new()),
992 used_mut_nodes: RefCell::new(HashSet::new()),
993 impl_vtables: RefCell::new(HashMap::new()),
994 populated_external_types: RefCell::new(HashSet::new()),
995 populated_external_traits: RefCell::new(HashSet::new()),
997 extern_const_statics: RefCell::new(HashMap::new()),
998 extern_const_variants: RefCell::new(HashMap::new()),
1002 // Type constructors
1004 // Interns a type/name combination, stores the resulting box in cx.interner,
1005 // and returns the box as cast to an unsafe ptr (see comments for t above).
1006 pub fn mk_t(cx: ctxt, st: sty) -> t {
1007 // Check for primitive types.
1009 ty_nil => return mk_nil(),
1010 ty_err => return mk_err(),
1011 ty_bool => return mk_bool(),
1012 ty_int(i) => return mk_mach_int(i),
1013 ty_uint(u) => return mk_mach_uint(u),
1014 ty_float(f) => return mk_mach_float(f),
1015 ty_char => return mk_char(),
1016 ty_bot => return mk_bot(),
1020 let key = intern_key { sty: to_unsafe_ptr(&st) };
1023 let mut interner = cx.interner.borrow_mut();
1024 match interner.get().find(&key) {
1025 Some(t) => unsafe { return cast::transmute(&t.sty); },
1031 fn rflags(r: Region) -> uint {
1032 (has_regions as uint) | {
1034 ty::ReInfer(_) => needs_infer as uint,
1039 fn sflags(substs: &substs) -> uint {
1041 for tt in substs.tps.iter() { f |= get(*tt).flags; }
1042 match substs.regions {
1044 NonerasedRegions(ref regions) => {
1045 for r in regions.iter() {
1053 &ty_str(vstore_slice(r)) => {
1056 &ty_vec(ref mt, vstore_slice(r)) => {
1058 flags |= get(mt.ty).flags;
1060 &ty_nil | &ty_bool | &ty_char | &ty_int(_) | &ty_float(_) | &ty_uint(_) |
1061 &ty_str(_) | &ty_type => {}
1062 // You might think that we could just return ty_err for
1063 // any type containing ty_err as a component, and get
1064 // rid of the has_ty_err flag -- likewise for ty_bot (with
1065 // the exception of function types that return bot).
1066 // But doing so caused sporadic memory corruption, and
1067 // neither I (tjc) nor nmatsakis could figure out why,
1068 // so we're doing it this way.
1069 &ty_bot => flags |= has_ty_bot as uint,
1070 &ty_err => flags |= has_ty_err as uint,
1071 &ty_param(_) => flags |= has_params as uint,
1072 &ty_infer(_) => flags |= needs_infer as uint,
1073 &ty_self(_) => flags |= has_self as uint,
1074 &ty_enum(_, ref substs) | &ty_struct(_, ref substs) |
1075 &ty_trait(_, ref substs, _, _, _) => {
1076 flags |= sflags(substs);
1078 ty_trait(_, _, RegionTraitStore(r), _, _) => {
1084 &ty_box(tt) | &ty_uniq(tt) => {
1085 flags |= get(tt).flags
1087 &ty_vec(ref m, _) | &ty_ptr(ref m) |
1088 &ty_unboxed_vec(ref m) => {
1089 flags |= get(m.ty).flags;
1091 &ty_rptr(r, ref m) => {
1093 flags |= get(m.ty).flags;
1095 &ty_tup(ref ts) => for tt in ts.iter() { flags |= get(*tt).flags; },
1096 &ty_bare_fn(ref f) => {
1097 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1098 flags |= get(f.sig.output).flags;
1099 // T -> _|_ is *not* _|_ !
1100 flags &= !(has_ty_bot as uint);
1102 &ty_closure(ref f) => {
1103 flags |= rflags(f.region);
1104 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1105 flags |= get(f.sig.output).flags;
1106 // T -> _|_ is *not* _|_ !
1107 flags &= !(has_ty_bot as uint);
1113 id: cx.next_id.get(),
1117 let sty_ptr = to_unsafe_ptr(&t.sty);
1119 let key = intern_key {
1123 let mut interner = cx.interner.borrow_mut();
1124 interner.get().insert(key, t);
1126 cx.next_id.set(cx.next_id.get() + 1);
1129 cast::transmute::<*sty, t>(sty_ptr)
1134 pub fn mk_prim_t(primitive: &'static t_box_) -> t {
1136 cast::transmute::<&'static t_box_, t>(primitive)
1141 pub fn mk_nil() -> t { mk_prim_t(&primitives::TY_NIL) }
1144 pub fn mk_err() -> t { mk_prim_t(&primitives::TY_ERR) }
1147 pub fn mk_bot() -> t { mk_prim_t(&primitives::TY_BOT) }
1150 pub fn mk_bool() -> t { mk_prim_t(&primitives::TY_BOOL) }
1153 pub fn mk_int() -> t { mk_prim_t(&primitives::TY_INT) }
1156 pub fn mk_i8() -> t { mk_prim_t(&primitives::TY_I8) }
1159 pub fn mk_i16() -> t { mk_prim_t(&primitives::TY_I16) }
1162 pub fn mk_i32() -> t { mk_prim_t(&primitives::TY_I32) }
1165 pub fn mk_i64() -> t { mk_prim_t(&primitives::TY_I64) }
1168 pub fn mk_f32() -> t { mk_prim_t(&primitives::TY_F32) }
1171 pub fn mk_f64() -> t { mk_prim_t(&primitives::TY_F64) }
1174 pub fn mk_uint() -> t { mk_prim_t(&primitives::TY_UINT) }
1177 pub fn mk_u8() -> t { mk_prim_t(&primitives::TY_U8) }
1180 pub fn mk_u16() -> t { mk_prim_t(&primitives::TY_U16) }
1183 pub fn mk_u32() -> t { mk_prim_t(&primitives::TY_U32) }
1186 pub fn mk_u64() -> t { mk_prim_t(&primitives::TY_U64) }
1188 pub fn mk_mach_int(tm: ast::IntTy) -> t {
1190 ast::TyI => mk_int(),
1191 ast::TyI8 => mk_i8(),
1192 ast::TyI16 => mk_i16(),
1193 ast::TyI32 => mk_i32(),
1194 ast::TyI64 => mk_i64(),
1198 pub fn mk_mach_uint(tm: ast::UintTy) -> t {
1200 ast::TyU => mk_uint(),
1201 ast::TyU8 => mk_u8(),
1202 ast::TyU16 => mk_u16(),
1203 ast::TyU32 => mk_u32(),
1204 ast::TyU64 => mk_u64(),
1208 pub fn mk_mach_float(tm: ast::FloatTy) -> t {
1210 ast::TyF32 => mk_f32(),
1211 ast::TyF64 => mk_f64(),
1216 pub fn mk_char() -> t { mk_prim_t(&primitives::TY_CHAR) }
1218 pub fn mk_str(cx: ctxt, t: vstore) -> t {
1222 pub fn mk_enum(cx: ctxt, did: ast::DefId, substs: substs) -> t {
1223 // take a copy of substs so that we own the vectors inside
1224 mk_t(cx, ty_enum(did, substs))
1227 pub fn mk_box(cx: ctxt, ty: t) -> t { mk_t(cx, ty_box(ty)) }
1229 pub fn mk_uniq(cx: ctxt, ty: t) -> t { mk_t(cx, ty_uniq(ty)) }
1231 pub fn mk_ptr(cx: ctxt, tm: mt) -> t { mk_t(cx, ty_ptr(tm)) }
1233 pub fn mk_rptr(cx: ctxt, r: Region, tm: mt) -> t { mk_t(cx, ty_rptr(r, tm)) }
1235 pub fn mk_mut_rptr(cx: ctxt, r: Region, ty: t) -> t {
1236 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
1238 pub fn mk_imm_rptr(cx: ctxt, r: Region, ty: t) -> t {
1239 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
1242 pub fn mk_mut_ptr(cx: ctxt, ty: t) -> t {
1243 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
1246 pub fn mk_imm_ptr(cx: ctxt, ty: t) -> t {
1247 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
1250 pub fn mk_nil_ptr(cx: ctxt) -> t {
1251 mk_ptr(cx, mt {ty: mk_nil(), mutbl: ast::MutImmutable})
1254 pub fn mk_vec(cx: ctxt, tm: mt, t: vstore) -> t {
1255 mk_t(cx, ty_vec(tm, t))
1258 pub fn mk_unboxed_vec(cx: ctxt, tm: mt) -> t {
1259 mk_t(cx, ty_unboxed_vec(tm))
1261 pub fn mk_mut_unboxed_vec(cx: ctxt, ty: t) -> t {
1262 mk_t(cx, ty_unboxed_vec(mt {ty: ty, mutbl: ast::MutImmutable}))
1265 pub fn mk_tup(cx: ctxt, ts: ~[t]) -> t { mk_t(cx, ty_tup(ts)) }
1267 pub fn mk_closure(cx: ctxt, fty: ClosureTy) -> t {
1268 mk_t(cx, ty_closure(fty))
1271 pub fn mk_bare_fn(cx: ctxt, fty: BareFnTy) -> t {
1272 mk_t(cx, ty_bare_fn(fty))
1275 pub fn mk_ctor_fn(cx: ctxt,
1276 binder_id: ast::NodeId,
1277 input_tys: &[ty::t],
1278 output: ty::t) -> t {
1279 let input_args = input_tys.map(|t| *t);
1282 purity: ast::ImpureFn,
1283 abis: AbiSet::Rust(),
1285 binder_id: binder_id,
1294 pub fn mk_trait(cx: ctxt,
1298 mutability: ast::Mutability,
1299 bounds: BuiltinBounds)
1301 // take a copy of substs so that we own the vectors inside
1302 mk_t(cx, ty_trait(did, substs, store, mutability, bounds))
1305 pub fn mk_struct(cx: ctxt, struct_id: ast::DefId, substs: substs) -> t {
1306 // take a copy of substs so that we own the vectors inside
1307 mk_t(cx, ty_struct(struct_id, substs))
1310 pub fn mk_var(cx: ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) }
1312 pub fn mk_int_var(cx: ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) }
1314 pub fn mk_float_var(cx: ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) }
1316 pub fn mk_infer(cx: ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) }
1318 pub fn mk_self(cx: ctxt, did: ast::DefId) -> t { mk_t(cx, ty_self(did)) }
1320 pub fn mk_param(cx: ctxt, n: uint, k: DefId) -> t {
1321 mk_t(cx, ty_param(param_ty { idx: n, def_id: k }))
1324 pub fn mk_type(cx: ctxt) -> t { mk_t(cx, ty_type) }
1326 pub fn walk_ty(ty: t, f: |t|) {
1327 maybe_walk_ty(ty, |t| { f(t); true });
1330 pub fn maybe_walk_ty(ty: t, f: |t| -> bool) {
1335 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) |
1336 ty_str(_) | ty_type | ty_self(_) |
1337 ty_infer(_) | ty_param(_) | ty_err => {}
1338 ty_box(ty) | ty_uniq(ty) => maybe_walk_ty(ty, f),
1339 ty_vec(ref tm, _) | ty_unboxed_vec(ref tm) | ty_ptr(ref tm) |
1340 ty_rptr(_, ref tm) => {
1341 maybe_walk_ty(tm.ty, f);
1343 ty_enum(_, ref substs) | ty_struct(_, ref substs) |
1344 ty_trait(_, ref substs, _, _, _) => {
1345 for subty in (*substs).tps.iter() { maybe_walk_ty(*subty, |x| f(x)); }
1347 ty_tup(ref ts) => { for tt in ts.iter() { maybe_walk_ty(*tt, |x| f(x)); } }
1348 ty_bare_fn(ref ft) => {
1349 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1350 maybe_walk_ty(ft.sig.output, f);
1352 ty_closure(ref ft) => {
1353 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1354 maybe_walk_ty(ft.sig.output, f);
1359 // Folds types from the bottom up.
1360 pub fn fold_ty(cx: ctxt, t0: t, fldop: |t| -> t) -> t {
1361 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
1365 pub fn walk_regions_and_ty(cx: ctxt, ty: t, fldr: |r: Region|, fldt: |t: t|)
1367 ty_fold::RegionFolder::general(cx,
1369 |t| { fldt(t); t }).fold_ty(ty)
1372 pub fn fold_regions(cx: ctxt, ty: t, fldr: |r: Region| -> Region) -> t {
1373 ty_fold::RegionFolder::regions(cx, fldr).fold_ty(ty)
1376 // Substitute *only* type parameters. Used in trans where regions are erased.
1377 pub fn subst_tps(tcx: ctxt, tps: &[t], self_ty_opt: Option<t>, typ: t) -> t {
1378 let mut subst = TpsSubst { tcx: tcx, self_ty_opt: self_ty_opt, tps: tps };
1379 return subst.fold_ty(typ);
1381 struct TpsSubst<'a> {
1383 self_ty_opt: Option<t>,
1387 impl<'a> TypeFolder for TpsSubst<'a> {
1388 fn tcx(&self) -> ty::ctxt { self.tcx }
1390 fn fold_ty(&mut self, t: ty::t) -> ty::t {
1391 if self.tps.len() == 0u && self.self_ty_opt.is_none() {
1395 let tb = ty::get(t);
1396 if self.self_ty_opt.is_none() && !tbox_has_flag(tb, has_params) {
1400 match ty::get(t).sty {
1406 match self.self_ty_opt {
1407 None => self.tcx.sess.bug("ty_self unexpected here"),
1408 Some(self_ty) => self_ty
1413 ty_fold::super_fold_ty(self, t)
1420 pub fn substs_is_noop(substs: &substs) -> bool {
1421 let regions_is_noop = match substs.regions {
1422 ErasedRegions => false, // may be used to canonicalize
1423 NonerasedRegions(ref regions) => regions.is_empty()
1426 substs.tps.len() == 0u &&
1428 substs.self_ty.is_none()
1431 pub fn substs_to_str(cx: ctxt, substs: &substs) -> ~str {
1435 pub fn subst(cx: ctxt,
1439 typ.subst(cx, substs)
1444 pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil }
1446 pub fn type_is_bot(ty: t) -> bool {
1447 (get(ty).flags & (has_ty_bot as uint)) != 0
1450 pub fn type_is_error(ty: t) -> bool {
1451 (get(ty).flags & (has_ty_err as uint)) != 0
1454 pub fn type_needs_subst(ty: t) -> bool {
1455 tbox_has_flag(get(ty), needs_subst)
1458 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
1459 tref.substs.self_ty.iter().any(|&t| type_is_error(t)) ||
1460 tref.substs.tps.iter().any(|&t| type_is_error(t))
1463 pub fn type_is_ty_var(ty: t) -> bool {
1465 ty_infer(TyVar(_)) => true,
1470 pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool }
1472 pub fn type_is_self(ty: t) -> bool {
1474 ty_self(..) => true,
1479 pub fn type_is_structural(ty: t) -> bool {
1481 ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) | ty_trait(..) |
1482 ty_vec(_, vstore_fixed(_)) | ty_str(vstore_fixed(_)) |
1483 ty_vec(_, vstore_slice(_)) | ty_str(vstore_slice(_))
1489 pub fn type_is_sequence(ty: t) -> bool {
1491 ty_str(_) | ty_vec(_, _) => true,
1496 pub fn type_is_simd(cx: ctxt, ty: t) -> bool {
1498 ty_struct(did, _) => lookup_simd(cx, did),
1503 pub fn type_is_str(ty: t) -> bool {
1510 pub fn sequence_element_type(cx: ctxt, ty: t) -> t {
1512 ty_str(_) => return mk_mach_uint(ast::TyU8),
1513 ty_vec(mt, _) | ty_unboxed_vec(mt) => return mt.ty,
1514 _ => cx.sess.bug("sequence_element_type called on non-sequence value"),
1518 pub fn simd_type(cx: ctxt, ty: t) -> t {
1520 ty_struct(did, ref substs) => {
1521 let fields = lookup_struct_fields(cx, did);
1522 lookup_field_type(cx, did, fields[0].id, substs)
1524 _ => fail!("simd_type called on invalid type")
1528 pub fn simd_size(cx: ctxt, ty: t) -> uint {
1530 ty_struct(did, _) => {
1531 let fields = lookup_struct_fields(cx, did);
1534 _ => fail!("simd_size called on invalid type")
1538 pub fn get_element_type(ty: t, i: uint) -> t {
1540 ty_tup(ref ts) => return ts[i],
1541 _ => fail!("get_element_type called on invalid type")
1545 pub fn type_is_box(ty: t) -> bool {
1547 ty_box(_) => return true,
1552 pub fn type_is_boxed(ty: t) -> bool {
1554 ty_box(_) | ty_vec(_, vstore_box) | ty_str(vstore_box) => true,
1559 pub fn type_is_region_ptr(ty: t) -> bool {
1561 ty_rptr(_, _) => true,
1566 pub fn type_is_slice(ty: t) -> bool {
1568 ty_vec(_, vstore_slice(_)) | ty_str(vstore_slice(_)) => true,
1573 pub fn type_is_unique_box(ty: t) -> bool {
1575 ty_uniq(_) => return true,
1580 pub fn type_is_unsafe_ptr(ty: t) -> bool {
1582 ty_ptr(_) => return true,
1587 pub fn type_is_vec(ty: t) -> bool {
1588 return match get(ty).sty {
1589 ty_vec(_, _) | ty_unboxed_vec(_) => true,
1595 pub fn type_is_unique(ty: t) -> bool {
1597 ty_uniq(_) | ty_vec(_, vstore_uniq) | ty_str(vstore_uniq) => true,
1603 A scalar type is one that denotes an atomic datum, with no sub-components.
1604 (A ty_ptr is scalar because it represents a non-managed pointer, so its
1605 contents are abstract to rustc.)
1607 pub fn type_is_scalar(ty: t) -> bool {
1609 ty_nil | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
1610 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) | ty_type |
1611 ty_bare_fn(..) | ty_ptr(_) => true,
1616 pub fn type_needs_drop(cx: ctxt, ty: t) -> bool {
1617 type_contents(cx, ty).needs_drop(cx)
1620 // Some things don't need cleanups during unwinding because the
1621 // task can free them all at once later. Currently only things
1622 // that only contain scalars and shared boxes can avoid unwind
1624 pub fn type_needs_unwind_cleanup(cx: ctxt, ty: t) -> bool {
1626 let needs_unwind_cleanup_cache = cx.needs_unwind_cleanup_cache
1628 match needs_unwind_cleanup_cache.get().find(&ty) {
1629 Some(&result) => return result,
1634 let mut tycache = HashSet::new();
1635 let needs_unwind_cleanup =
1636 type_needs_unwind_cleanup_(cx, ty, &mut tycache, false);
1637 let mut needs_unwind_cleanup_cache = cx.needs_unwind_cleanup_cache
1639 needs_unwind_cleanup_cache.get().insert(ty, needs_unwind_cleanup);
1640 return needs_unwind_cleanup;
1643 fn type_needs_unwind_cleanup_(cx: ctxt, ty: t,
1644 tycache: &mut HashSet<t>,
1645 encountered_box: bool) -> bool {
1647 // Prevent infinite recursion
1648 if !tycache.insert(ty) {
1652 let mut encountered_box = encountered_box;
1653 let mut needs_unwind_cleanup = false;
1654 maybe_walk_ty(ty, |ty| {
1655 let old_encountered_box = encountered_box;
1656 let result = match get(ty).sty {
1658 encountered_box = true;
1661 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
1662 ty_tup(_) | ty_ptr(_) => {
1665 ty_enum(did, ref substs) => {
1666 for v in (*enum_variants(cx, did)).iter() {
1667 for aty in v.args.iter() {
1668 let t = subst(cx, substs, *aty);
1669 needs_unwind_cleanup |=
1670 type_needs_unwind_cleanup_(cx, t, tycache,
1674 !needs_unwind_cleanup
1677 ty_str(vstore_uniq) |
1678 ty_str(vstore_box) |
1679 ty_vec(_, vstore_uniq) |
1680 ty_vec(_, vstore_box)
1682 // Once we're inside a box, the annihilator will find
1683 // it and destroy it.
1684 if !encountered_box {
1685 needs_unwind_cleanup = true;
1692 needs_unwind_cleanup = true;
1697 encountered_box = old_encountered_box;
1701 return needs_unwind_cleanup;
1705 * Type contents is how the type checker reasons about kinds.
1706 * They track what kinds of things are found within a type. You can
1707 * think of them as kind of an "anti-kind". They track the kinds of values
1708 * and thinks that are contained in types. Having a larger contents for
1709 * a type tends to rule that type *out* from various kinds. For example,
1710 * a type that contains a reference is not sendable.
1712 * The reason we compute type contents and not kinds is that it is
1713 * easier for me (nmatsakis) to think about what is contained within
1714 * a type than to think about what is *not* contained within a type.
1716 pub struct TypeContents {
1720 macro_rules! def_type_content_sets(
1721 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
1723 use middle::ty::TypeContents;
1724 $(pub static $name: TypeContents = TypeContents { bits: $bits };)+
1729 def_type_content_sets!(
1731 None = 0b0000__00000000__0000,
1733 // Things that are interior to the value (first nibble):
1734 InteriorUnsized = 0b0000__00000000__0001,
1735 // InteriorAll = 0b0000__00000000__1111,
1737 // Things that are owned by the value (second and third nibbles):
1738 OwnsOwned = 0b0000__00000001__0000,
1739 OwnsDtor = 0b0000__00000010__0000,
1740 OwnsManaged /* see [1] below */ = 0b0000__00000100__0000,
1741 OwnsAffine = 0b0000__00001000__0000,
1742 OwnsAll = 0b0000__11111111__0000,
1744 // Things that are reachable by the value in any way (fourth nibble):
1745 ReachesNonsendAnnot = 0b0001__00000000__0000,
1746 ReachesBorrowed = 0b0010__00000000__0000,
1747 // ReachesManaged /* see [1] below */ = 0b0100__00000000__0000,
1748 ReachesMutable = 0b1000__00000000__0000,
1749 ReachesAll = 0b1111__00000000__0000,
1751 // Things that cause values to *move* rather than *copy*
1752 Moves = 0b0000__00001011__0000,
1754 // Things that mean drop glue is necessary
1755 NeedsDrop = 0b0000__00000111__0000,
1757 // Things that prevent values from being sent
1759 // Note: For checking whether something is sendable, it'd
1760 // be sufficient to have ReachesManaged. However, we include
1761 // both ReachesManaged and OwnsManaged so that when
1762 // a parameter has a bound T:Send, we are able to deduce
1763 // that it neither reaches nor owns a managed pointer.
1764 Nonsendable = 0b0111__00000100__0000,
1766 // Things that prevent values from being considered freezable
1767 Nonfreezable = 0b1000__00000000__0000,
1769 // Things that prevent values from being considered 'static
1770 Nonstatic = 0b0010__00000000__0000,
1772 // Things that prevent values from being considered sized
1773 Nonsized = 0b0000__00000000__0001,
1775 // Things that make values considered not POD (would be same
1776 // as `Moves`, but for the fact that managed data `@` is
1777 // not considered POD)
1778 Nonpod = 0b0000__00001111__0000,
1780 // Bits to set when a managed value is encountered
1782 // [1] Do not set the bits TC::OwnsManaged or
1783 // TC::ReachesManaged directly, instead reference
1784 // TC::Managed to set them both at once.
1785 Managed = 0b0100__00000100__0000,
1788 All = 0b1111__11111111__1111
1793 pub fn meets_bounds(&self, cx: ctxt, bbs: BuiltinBounds) -> bool {
1794 bbs.iter().all(|bb| self.meets_bound(cx, bb))
1797 pub fn meets_bound(&self, cx: ctxt, bb: BuiltinBound) -> bool {
1799 BoundStatic => self.is_static(cx),
1800 BoundFreeze => self.is_freezable(cx),
1801 BoundSend => self.is_sendable(cx),
1802 BoundSized => self.is_sized(cx),
1803 BoundPod => self.is_pod(cx),
1807 pub fn when(&self, cond: bool) -> TypeContents {
1808 if cond {*self} else {TC::None}
1811 pub fn intersects(&self, tc: TypeContents) -> bool {
1812 (self.bits & tc.bits) != 0
1815 pub fn is_static(&self, _: ctxt) -> bool {
1816 !self.intersects(TC::Nonstatic)
1819 pub fn is_sendable(&self, _: ctxt) -> bool {
1820 !self.intersects(TC::Nonsendable)
1823 pub fn owns_managed(&self) -> bool {
1824 self.intersects(TC::OwnsManaged)
1827 pub fn is_freezable(&self, _: ctxt) -> bool {
1828 !self.intersects(TC::Nonfreezable)
1831 pub fn is_sized(&self, _: ctxt) -> bool {
1832 !self.intersects(TC::Nonsized)
1835 pub fn is_pod(&self, _: ctxt) -> bool {
1836 !self.intersects(TC::Nonpod)
1839 pub fn moves_by_default(&self, _: ctxt) -> bool {
1840 self.intersects(TC::Moves)
1843 pub fn needs_drop(&self, _: ctxt) -> bool {
1844 self.intersects(TC::NeedsDrop)
1847 pub fn owned_pointer(&self) -> TypeContents {
1849 * Includes only those bits that still apply
1850 * when indirected through a `~` pointer
1853 *self & (TC::OwnsAll | TC::ReachesAll))
1856 pub fn reference(&self, bits: TypeContents) -> TypeContents {
1858 * Includes only those bits that still apply
1859 * when indirected through a reference (`&`)
1862 *self & TC::ReachesAll)
1865 pub fn managed_pointer(&self) -> TypeContents {
1867 * Includes only those bits that still apply
1868 * when indirected through a managed pointer (`@`)
1871 *self & TC::ReachesAll)
1874 pub fn unsafe_pointer(&self) -> TypeContents {
1876 * Includes only those bits that still apply
1877 * when indirected through an unsafe pointer (`*`)
1879 *self & TC::ReachesAll
1882 pub fn union<T>(v: &[T], f: |&T| -> TypeContents) -> TypeContents {
1883 v.iter().fold(TC::None, |tc, t| tc | f(t))
1886 pub fn inverse(&self) -> TypeContents {
1887 TypeContents { bits: !self.bits }
1891 impl ops::BitOr<TypeContents,TypeContents> for TypeContents {
1892 fn bitor(&self, other: &TypeContents) -> TypeContents {
1893 TypeContents {bits: self.bits | other.bits}
1897 impl ops::BitAnd<TypeContents,TypeContents> for TypeContents {
1898 fn bitand(&self, other: &TypeContents) -> TypeContents {
1899 TypeContents {bits: self.bits & other.bits}
1903 impl ops::Sub<TypeContents,TypeContents> for TypeContents {
1904 fn sub(&self, other: &TypeContents) -> TypeContents {
1905 TypeContents {bits: self.bits & !other.bits}
1909 impl ToStr for TypeContents {
1910 fn to_str(&self) -> ~str {
1911 format!("TypeContents({})", self.bits.to_str_radix(2))
1915 pub fn type_is_static(cx: ctxt, t: ty::t) -> bool {
1916 type_contents(cx, t).is_static(cx)
1919 pub fn type_is_sendable(cx: ctxt, t: ty::t) -> bool {
1920 type_contents(cx, t).is_sendable(cx)
1923 pub fn type_is_freezable(cx: ctxt, t: ty::t) -> bool {
1924 type_contents(cx, t).is_freezable(cx)
1927 pub fn type_contents(cx: ctxt, ty: t) -> TypeContents {
1928 let ty_id = type_id(ty);
1931 let tc_cache = cx.tc_cache.borrow();
1932 match tc_cache.get().find(&ty_id) {
1933 Some(tc) => { return *tc; }
1938 let mut cache = HashMap::new();
1939 let result = tc_ty(cx, ty, &mut cache);
1941 let mut tc_cache = cx.tc_cache.borrow_mut();
1942 tc_cache.get().insert(ty_id, result);
1947 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
1949 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
1950 // private cache for this walk. This is needed in the case of cyclic
1953 // struct List { next: ~Option<List>, ... }
1955 // When computing the type contents of such a type, we wind up deeply
1956 // recursing as we go. So when we encounter the recursive reference
1957 // to List, we temporarily use TC::None as its contents. Later we'll
1958 // patch up the cache with the correct value, once we've computed it
1959 // (this is basically a co-inductive process, if that helps). So in
1960 // the end we'll compute TC::OwnsOwned, in this case.
1962 // The problem is, as we are doing the computation, we will also
1963 // compute an *intermediate* contents for, e.g., Option<List> of
1964 // TC::None. This is ok during the computation of List itself, but if
1965 // we stored this intermediate value into cx.tc_cache, then later
1966 // requests for the contents of Option<List> would also yield TC::None
1967 // which is incorrect. This value was computed based on the crutch
1968 // value for the type contents of list. The correct value is
1969 // TC::OwnsOwned. This manifested as issue #4821.
1970 let ty_id = type_id(ty);
1971 match cache.find(&ty_id) {
1972 Some(tc) => { return *tc; }
1976 let tc_cache = cx.tc_cache.borrow();
1977 match tc_cache.get().find(&ty_id) { // Must check both caches!
1978 Some(tc) => { return *tc; }
1982 cache.insert(ty_id, TC::None);
1984 let result = match get(ty).sty {
1985 // Scalar and unique types are sendable, freezable, and durable
1986 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
1987 ty_bare_fn(_) | ty::ty_char => {
1991 ty_str(vstore_uniq) => {
1995 ty_closure(ref c) => {
1996 closure_contents(cx, c)
2000 tc_ty(cx, typ, cache).managed_pointer()
2004 tc_ty(cx, typ, cache).owned_pointer()
2007 ty_trait(_, _, store, mutbl, bounds) => {
2008 object_contents(cx, store, mutbl, bounds)
2012 tc_ty(cx, mt.ty, cache).unsafe_pointer()
2015 ty_rptr(r, ref mt) => {
2016 tc_ty(cx, mt.ty, cache).reference(
2017 borrowed_contents(r, mt.mutbl))
2020 ty_vec(mt, vstore_uniq) => {
2021 tc_mt(cx, mt, cache).owned_pointer()
2024 ty_vec(mt, vstore_box) => {
2025 tc_mt(cx, mt, cache).managed_pointer()
2028 ty_vec(ref mt, vstore_slice(r)) => {
2029 tc_ty(cx, mt.ty, cache).reference(
2030 borrowed_contents(r, mt.mutbl))
2033 ty_vec(mt, vstore_fixed(_)) => {
2034 tc_mt(cx, mt, cache)
2037 ty_str(vstore_box) => {
2041 ty_str(vstore_slice(r)) => {
2042 borrowed_contents(r, ast::MutImmutable)
2045 ty_str(vstore_fixed(_)) => {
2049 ty_struct(did, ref substs) => {
2050 let flds = struct_fields(cx, did, substs);
2052 TypeContents::union(flds, |f| tc_mt(cx, f.mt, cache));
2053 if ty::has_dtor(cx, did) {
2054 res = res | TC::OwnsDtor;
2056 apply_lang_items(cx, did, res)
2059 ty_tup(ref tys) => {
2060 TypeContents::union(*tys, |ty| tc_ty(cx, *ty, cache))
2063 ty_enum(did, ref substs) => {
2064 let variants = substd_enum_variants(cx, did, substs);
2066 TypeContents::union(variants, |variant| {
2067 TypeContents::union(variant.args, |arg_ty| {
2068 tc_ty(cx, *arg_ty, cache)
2071 apply_lang_items(cx, did, res)
2075 // We only ever ask for the kind of types that are defined in
2076 // the current crate; therefore, the only type parameters that
2077 // could be in scope are those defined in the current crate.
2078 // If this assertion failures, it is likely because of a
2079 // failure in the cross-crate inlining code to translate a
2081 assert_eq!(p.def_id.crate, ast::LOCAL_CRATE);
2083 let ty_param_defs = cx.ty_param_defs.borrow();
2084 let tp_def = ty_param_defs.get().get(&p.def_id.node);
2085 kind_bounds_to_contents(cx,
2086 tp_def.bounds.builtin_bounds,
2087 tp_def.bounds.trait_bounds)
2090 ty_self(def_id) => {
2091 // FIXME(#4678)---self should just be a ty param
2093 // Self may be bounded if the associated trait has builtin kinds
2094 // for supertraits. If so we can use those bounds.
2095 let trait_def = lookup_trait_def(cx, def_id);
2096 let traits = [trait_def.trait_ref];
2097 kind_bounds_to_contents(cx, trait_def.bounds, traits)
2101 // This occurs during coherence, but shouldn't occur at other
2105 ty_unboxed_vec(mt) => TC::InteriorUnsized | tc_mt(cx, mt, cache),
2107 ty_type => TC::None,
2110 cx.sess.bug("Asked to compute contents of error type");
2114 cache.insert(ty_id, result);
2120 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2122 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
2123 mc | tc_ty(cx, mt.ty, cache)
2126 fn apply_lang_items(cx: ctxt,
2130 if Some(did) == cx.lang_items.no_freeze_bound() {
2131 tc | TC::ReachesMutable
2132 } else if Some(did) == cx.lang_items.no_send_bound() {
2133 tc | TC::ReachesNonsendAnnot
2134 } else if Some(did) == cx.lang_items.managed_bound() {
2136 } else if Some(did) == cx.lang_items.no_pod_bound() {
2143 fn borrowed_contents(region: ty::Region,
2144 mutbl: ast::Mutability)
2147 * Type contents due to containing a reference
2148 * with the region `region` and borrow kind `bk`
2151 let b = match mutbl {
2152 ast::MutMutable => TC::ReachesMutable | TC::OwnsAffine,
2153 ast::MutImmutable => TC::None,
2155 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
2158 fn closure_contents(cx: ctxt, cty: &ClosureTy) -> TypeContents {
2159 // Closure contents are just like trait contents, but with potentially
2161 let st = match cty.sigil {
2162 ast::BorrowedSigil =>
2163 object_contents(cx, RegionTraitStore(cty.region), MutMutable, cty.bounds),
2164 ast::ManagedSigil =>
2165 object_contents(cx, BoxTraitStore, MutImmutable, cty.bounds),
2167 object_contents(cx, UniqTraitStore, MutImmutable, cty.bounds),
2170 // FIXME(#3569): This borrowed_contents call should be taken care of in
2171 // object_contents, after ~Traits and @Traits can have region bounds too.
2172 // This one here is redundant for &fns but important for ~fns and @fns.
2173 let rt = borrowed_contents(cty.region, ast::MutImmutable);
2175 // This also prohibits "@once fn" from being copied, which allows it to
2176 // be called. Neither way really makes much sense.
2177 let ot = match cty.onceness {
2178 ast::Once => TC::OwnsAffine,
2179 ast::Many => TC::None,
2185 fn object_contents(cx: ctxt,
2187 mutbl: ast::Mutability,
2188 bounds: BuiltinBounds)
2190 // These are the type contents of the (opaque) interior
2191 let contents = (TC::ReachesMutable.when(mutbl == ast::MutMutable) |
2192 kind_bounds_to_contents(cx, bounds, []));
2196 contents.owned_pointer()
2199 contents.managed_pointer()
2201 RegionTraitStore(r) => {
2202 contents.reference(borrowed_contents(r, mutbl))
2207 fn kind_bounds_to_contents(cx: ctxt,
2208 bounds: BuiltinBounds,
2209 traits: &[@TraitRef])
2211 let _i = indenter();
2212 let mut tc = TC::All;
2213 each_inherited_builtin_bound(cx, bounds, traits, |bound| {
2214 tc = tc - match bound {
2215 BoundStatic => TC::Nonstatic,
2216 BoundSend => TC::Nonsendable,
2217 BoundFreeze => TC::Nonfreezable,
2218 BoundSized => TC::Nonsized,
2219 BoundPod => TC::Nonpod,
2224 // Iterates over all builtin bounds on the type parameter def, including
2225 // those inherited from traits with builtin-kind-supertraits.
2226 fn each_inherited_builtin_bound(cx: ctxt,
2227 bounds: BuiltinBounds,
2228 traits: &[@TraitRef],
2229 f: |BuiltinBound|) {
2230 for bound in bounds.iter() {
2234 each_bound_trait_and_supertraits(cx, traits, |trait_ref| {
2235 let trait_def = lookup_trait_def(cx, trait_ref.def_id);
2236 for bound in trait_def.bounds.iter() {
2245 pub fn type_moves_by_default(cx: ctxt, ty: t) -> bool {
2246 type_contents(cx, ty).moves_by_default(cx)
2249 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
2250 pub fn is_instantiable(cx: ctxt, r_ty: t) -> bool {
2251 fn type_requires(cx: ctxt, seen: &mut ~[DefId],
2252 r_ty: t, ty: t) -> bool {
2253 debug!("type_requires({}, {})?",
2254 ::util::ppaux::ty_to_str(cx, r_ty),
2255 ::util::ppaux::ty_to_str(cx, ty));
2258 get(r_ty).sty == get(ty).sty ||
2259 subtypes_require(cx, seen, r_ty, ty)
2262 debug!("type_requires({}, {})? {}",
2263 ::util::ppaux::ty_to_str(cx, r_ty),
2264 ::util::ppaux::ty_to_str(cx, ty),
2269 fn subtypes_require(cx: ctxt, seen: &mut ~[DefId],
2270 r_ty: t, ty: t) -> bool {
2271 debug!("subtypes_require({}, {})?",
2272 ::util::ppaux::ty_to_str(cx, r_ty),
2273 ::util::ppaux::ty_to_str(cx, ty));
2275 let r = match get(ty).sty {
2276 // fixed length vectors need special treatment compared to
2277 // normal vectors, since they don't necessarily have the
2278 // possibilty to have length zero.
2279 ty_vec(_, vstore_fixed(0)) => false, // don't need no contents
2280 ty_vec(mt, vstore_fixed(_)) => type_requires(cx, seen, r_ty, mt.ty),
2298 ty_unboxed_vec(_) => {
2301 ty_box(typ) | ty_uniq(typ) => {
2302 type_requires(cx, seen, r_ty, typ)
2304 ty_rptr(_, ref mt) => {
2305 type_requires(cx, seen, r_ty, mt.ty)
2309 false // unsafe ptrs can always be NULL
2312 ty_trait(_, _, _, _, _) => {
2316 ty_struct(ref did, _) if seen.contains(did) => {
2320 ty_struct(did, ref substs) => {
2322 let fields = struct_fields(cx, did, substs);
2323 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
2324 seen.pop().unwrap();
2329 ts.iter().any(|t| type_requires(cx, seen, r_ty, *t))
2332 ty_enum(ref did, _) if seen.contains(did) => {
2336 ty_enum(did, ref substs) => {
2338 let vs = enum_variants(cx, did);
2339 let r = !vs.is_empty() && vs.iter().all(|variant| {
2340 variant.args.iter().any(|aty| {
2341 let sty = subst(cx, substs, *aty);
2342 type_requires(cx, seen, r_ty, sty)
2345 seen.pop().unwrap();
2350 debug!("subtypes_require({}, {})? {}",
2351 ::util::ppaux::ty_to_str(cx, r_ty),
2352 ::util::ppaux::ty_to_str(cx, ty),
2359 !subtypes_require(cx, &mut seen, r_ty, r_ty)
2362 /// Describes whether a type is representable. For types that are not
2363 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
2364 /// distinguish between types that are recursive with themselves and types that
2365 /// contain a different recursive type. These cases can therefore be treated
2366 /// differently when reporting errors.
2368 pub enum Representability {
2374 /// Check whether a type is representable. This means it cannot contain unboxed
2375 /// structural recursion. This check is needed for structs and enums.
2376 pub fn is_type_representable(cx: ctxt, ty: t) -> Representability {
2378 // Iterate until something non-representable is found
2379 fn find_nonrepresentable<It: Iterator<t>>(cx: ctxt, seen: &mut ~[DefId],
2380 mut iter: It) -> Representability {
2382 let r = type_structurally_recursive(cx, seen, ty);
2383 if r != Representable {
2390 // Does the type `ty` directly (without indirection through a pointer)
2391 // contain any types on stack `seen`?
2392 fn type_structurally_recursive(cx: ctxt, seen: &mut ~[DefId],
2393 ty: t) -> Representability {
2394 debug!("type_structurally_recursive: {}",
2395 ::util::ppaux::ty_to_str(cx, ty));
2397 // Compare current type to previously seen types
2400 ty_enum(did, _) => {
2401 for (i, &seen_did) in seen.iter().enumerate() {
2402 if did == seen_did {
2403 return if i == 0 { SelfRecursive }
2404 else { ContainsRecursive }
2411 // Check inner types
2415 find_nonrepresentable(cx, seen, ts.iter().map(|t| *t))
2417 // Fixed-length vectors.
2418 // FIXME(#11924) Behavior undecided for zero-length vectors.
2419 ty_vec(mt, vstore_fixed(_)) => {
2420 type_structurally_recursive(cx, seen, mt.ty)
2423 // Push struct and enum def-ids onto `seen` before recursing.
2424 ty_struct(did, ref substs) => {
2426 let fields = struct_fields(cx, did, substs);
2427 let r = find_nonrepresentable(cx, seen,
2428 fields.iter().map(|f| f.mt.ty));
2432 ty_enum(did, ref substs) => {
2434 let vs = enum_variants(cx, did);
2436 let mut r = Representable;
2437 for variant in vs.iter() {
2438 let iter = variant.args.iter().map(|aty| subst(cx, substs, *aty));
2439 r = find_nonrepresentable(cx, seen, iter);
2441 if r != Representable { break }
2452 debug!("is_type_representable: {}",
2453 ::util::ppaux::ty_to_str(cx, ty));
2455 // To avoid a stack overflow when checking an enum variant or struct that
2456 // contains a different, structurally recursive type, maintain a stack
2457 // of seen types and check recursion for each of them (issues #3008, #3779).
2458 let mut seen: ~[DefId] = ~[];
2459 type_structurally_recursive(cx, &mut seen, ty)
2462 pub fn type_is_trait(ty: t) -> bool {
2464 ty_trait(..) => true,
2469 pub fn type_is_integral(ty: t) -> bool {
2471 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
2476 pub fn type_is_char(ty: t) -> bool {
2483 pub fn type_is_bare_fn(ty: t) -> bool {
2485 ty_bare_fn(..) => true,
2490 pub fn type_is_fp(ty: t) -> bool {
2492 ty_infer(FloatVar(_)) | ty_float(_) => true,
2497 pub fn type_is_numeric(ty: t) -> bool {
2498 return type_is_integral(ty) || type_is_fp(ty);
2501 pub fn type_is_signed(ty: t) -> bool {
2508 pub fn type_is_machine(ty: t) -> bool {
2510 ty_int(ast::TyI) | ty_uint(ast::TyU) => false,
2511 ty_int(..) | ty_uint(..) | ty_float(..) => true,
2516 // Whether a type is Plain Old Data -- meaning it does not contain pointers
2517 // that the cycle collector might care about.
2518 pub fn type_is_pod(cx: ctxt, ty: t) -> bool {
2519 let mut result = true;
2522 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
2523 ty_type | ty_ptr(_) | ty_bare_fn(_) => result = true,
2525 ty_box(_) | ty_uniq(_) | ty_closure(_) |
2526 ty_str(vstore_uniq) | ty_str(vstore_box) |
2527 ty_vec(_, vstore_uniq) | ty_vec(_, vstore_box) |
2528 ty_trait(_, _, _, _, _) | ty_rptr(_,_) => result = false,
2530 ty_enum(did, ref substs) => {
2531 let variants = enum_variants(cx, did);
2532 for variant in (*variants).iter() {
2533 // FIXME(pcwalton): This is an inefficient way to do this. Don't
2534 // synthesize a tuple!
2536 // Perform any type parameter substitutions.
2537 let tup_ty = mk_tup(cx, variant.args.clone());
2538 let tup_ty = subst(cx, substs, tup_ty);
2539 if !type_is_pod(cx, tup_ty) { result = false; }
2542 ty_tup(ref elts) => {
2543 for elt in elts.iter() { if !type_is_pod(cx, *elt) { result = false; } }
2545 ty_str(vstore_fixed(_)) => result = true,
2546 ty_vec(ref mt, vstore_fixed(_)) | ty_unboxed_vec(ref mt) => {
2547 result = type_is_pod(cx, mt.ty);
2549 ty_param(_) => result = false,
2550 ty_struct(did, ref substs) => {
2551 let fields = lookup_struct_fields(cx, did);
2552 result = fields.iter().all(|f| {
2553 let fty = ty::lookup_item_type(cx, f.id);
2554 let sty = subst(cx, substs, fty.ty);
2555 type_is_pod(cx, sty)
2559 ty_str(vstore_slice(..)) | ty_vec(_, vstore_slice(..)) => {
2563 ty_infer(..) | ty_self(..) | ty_err => {
2564 cx.sess.bug("non concrete type in type_is_pod");
2571 pub fn type_is_enum(ty: t) -> bool {
2573 ty_enum(_, _) => return true,
2578 // Is the type's representation size known at compile time?
2579 pub fn type_is_sized(cx: ctxt, ty: ty::t) -> bool {
2581 // FIXME(#6308) add trait, vec, str, etc here.
2583 let ty_param_defs = cx.ty_param_defs.borrow();
2584 let param_def = ty_param_defs.get().get(&p.def_id.node);
2585 if param_def.bounds.builtin_bounds.contains_elem(BoundSized) {
2594 // Whether a type is enum like, that is an enum type with only nullary
2596 pub fn type_is_c_like_enum(cx: ctxt, ty: t) -> bool {
2598 ty_enum(did, _) => {
2599 let variants = enum_variants(cx, did);
2600 if variants.len() == 0 {
2603 variants.iter().all(|v| v.args.len() == 0)
2610 pub fn type_param(ty: t) -> Option<uint> {
2612 ty_param(p) => return Some(p.idx),
2613 _ => {/* fall through */ }
2618 // Returns the type and mutability of *t.
2620 // The parameter `explicit` indicates if this is an *explicit* dereference.
2621 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
2622 pub fn deref(t: t, explicit: bool) -> Option<mt> {
2623 deref_sty(&get(t).sty, explicit)
2626 pub fn deref_sty(sty: &sty, explicit: bool) -> Option<mt> {
2628 ty_box(typ) | ty_uniq(typ) => {
2631 mutbl: ast::MutImmutable,
2639 ty_ptr(mt) if explicit => {
2647 pub fn type_autoderef(t: t) -> t {
2650 match deref(t, false) {
2652 Some(mt) => t = mt.ty
2657 // Returns the type and mutability of t[i]
2658 pub fn index(t: t) -> Option<mt> {
2659 index_sty(&get(t).sty)
2662 pub fn index_sty(sty: &sty) -> Option<mt> {
2664 ty_vec(mt, _) => Some(mt),
2665 ty_str(_) => Some(mt {ty: mk_u8(), mutbl: ast::MutImmutable}),
2670 pub fn node_id_to_trait_ref(cx: ctxt, id: ast::NodeId) -> @ty::TraitRef {
2671 let trait_refs = cx.trait_refs.borrow();
2672 match trait_refs.get().find(&id) {
2674 None => cx.sess.bug(
2675 format!("node_id_to_trait_ref: no trait ref for node `{}`",
2676 ast_map::node_id_to_str(cx.items, id,
2677 token::get_ident_interner())))
2681 pub fn node_id_to_type(cx: ctxt, id: ast::NodeId) -> t {
2682 match node_id_to_type_opt(cx, id) {
2684 None => cx.sess.bug(
2685 format!("node_id_to_type: no type for node `{}`",
2686 ast_map::node_id_to_str(cx.items, id,
2687 token::get_ident_interner())))
2691 pub fn node_id_to_type_opt(cx: ctxt, id: ast::NodeId) -> Option<t> {
2692 let node_types = cx.node_types.borrow();
2693 debug!("id: {:?}, node_types: {:?}", id, node_types);
2694 match node_types.get().find(&(id as uint)) {
2695 Some(&t) => Some(t),
2700 // FIXME(pcwalton): Makes a copy, bleh. Probably better to not do that.
2701 pub fn node_id_to_type_params(cx: ctxt, id: ast::NodeId) -> ~[t] {
2702 let node_type_substs = cx.node_type_substs.borrow();
2703 match node_type_substs.get().find(&id) {
2705 Some(ts) => return (*ts).clone(),
2709 fn node_id_has_type_params(cx: ctxt, id: ast::NodeId) -> bool {
2710 let node_type_substs = cx.node_type_substs.borrow();
2711 node_type_substs.get().contains_key(&id)
2714 pub fn fn_is_variadic(fty: t) -> bool {
2715 match get(fty).sty {
2716 ty_bare_fn(ref f) => f.sig.variadic,
2717 ty_closure(ref f) => f.sig.variadic,
2719 fail!("fn_is_variadic() called on non-fn type: {:?}", s)
2724 pub fn ty_fn_sig(fty: t) -> FnSig {
2725 match get(fty).sty {
2726 ty_bare_fn(ref f) => f.sig.clone(),
2727 ty_closure(ref f) => f.sig.clone(),
2729 fail!("ty_fn_sig() called on non-fn type: {:?}", s)
2734 // Type accessors for substructures of types
2735 pub fn ty_fn_args(fty: t) -> ~[t] {
2736 match get(fty).sty {
2737 ty_bare_fn(ref f) => f.sig.inputs.clone(),
2738 ty_closure(ref f) => f.sig.inputs.clone(),
2740 fail!("ty_fn_args() called on non-fn type: {:?}", s)
2745 pub fn ty_closure_sigil(fty: t) -> Sigil {
2746 match get(fty).sty {
2747 ty_closure(ref f) => f.sigil,
2749 fail!("ty_closure_sigil() called on non-closure type: {:?}", s)
2754 pub fn ty_fn_purity(fty: t) -> ast::Purity {
2755 match get(fty).sty {
2756 ty_bare_fn(ref f) => f.purity,
2757 ty_closure(ref f) => f.purity,
2759 fail!("ty_fn_purity() called on non-fn type: {:?}", s)
2764 pub fn ty_fn_ret(fty: t) -> t {
2765 match get(fty).sty {
2766 ty_bare_fn(ref f) => f.sig.output,
2767 ty_closure(ref f) => f.sig.output,
2769 fail!("ty_fn_ret() called on non-fn type: {:?}", s)
2774 pub fn is_fn_ty(fty: t) -> bool {
2775 match get(fty).sty {
2776 ty_bare_fn(_) => true,
2777 ty_closure(_) => true,
2782 pub fn ty_vstore(ty: t) -> vstore {
2784 ty_vec(_, vstore) => vstore,
2785 ty_str(vstore) => vstore,
2786 ref s => fail!("ty_vstore() called on invalid sty: {:?}", s)
2790 pub fn ty_region(tcx: ctxt,
2795 ty_vec(_, vstore_slice(r)) => r,
2796 ty_str(vstore_slice(r)) => r,
2800 format!("ty_region() invoked on in appropriate ty: {:?}", s));
2805 pub fn replace_fn_sig(cx: ctxt, fsty: &sty, new_sig: FnSig) -> t {
2807 ty_bare_fn(ref f) => mk_bare_fn(cx, BareFnTy {sig: new_sig, ..*f}),
2808 ty_closure(ref f) => mk_closure(cx, ClosureTy {sig: new_sig, ..*f}),
2811 format!("ty_fn_sig() called on non-fn type: {:?}", s));
2816 pub fn replace_closure_return_type(tcx: ctxt, fn_type: t, ret_type: t) -> t {
2819 * Returns a new function type based on `fn_type` but returning a value of
2820 * type `ret_type` instead. */
2822 match ty::get(fn_type).sty {
2823 ty::ty_closure(ref fty) => {
2824 ty::mk_closure(tcx, ClosureTy {
2825 sig: FnSig {output: ret_type, ..fty.sig.clone()},
2830 tcx.sess.bug(format!(
2831 "replace_fn_ret() invoked with non-fn-type: {}",
2832 ty_to_str(tcx, fn_type)));
2837 // Returns a vec of all the input and output types of fty.
2838 pub fn tys_in_fn_sig(sig: &FnSig) -> ~[t] {
2839 vec::append_one(sig.inputs.map(|a| *a), sig.output)
2842 // Type accessors for AST nodes
2843 pub fn block_ty(cx: ctxt, b: &ast::Block) -> t {
2844 return node_id_to_type(cx, b.id);
2848 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
2849 // doesn't provide type parameter substitutions.
2850 pub fn pat_ty(cx: ctxt, pat: &ast::Pat) -> t {
2851 return node_id_to_type(cx, pat.id);
2855 // Returns the type of an expression as a monotype.
2857 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
2858 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
2859 // auto-ref. The type returned by this function does not consider such
2860 // adjustments. See `expr_ty_adjusted()` instead.
2862 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
2863 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
2864 // instead of "fn(t) -> T with T = int". If this isn't what you want, see
2865 // expr_ty_params_and_ty() below.
2866 pub fn expr_ty(cx: ctxt, expr: &ast::Expr) -> t {
2867 return node_id_to_type(cx, expr.id);
2870 pub fn expr_ty_opt(cx: ctxt, expr: &ast::Expr) -> Option<t> {
2871 return node_id_to_type_opt(cx, expr.id);
2874 pub fn expr_ty_adjusted(cx: ctxt, expr: &ast::Expr) -> t {
2877 * Returns the type of `expr`, considering any `AutoAdjustment`
2878 * entry recorded for that expression.
2880 * It would almost certainly be better to store the adjusted ty in with
2881 * the `AutoAdjustment`, but I opted not to do this because it would
2882 * require serializing and deserializing the type and, although that's not
2883 * hard to do, I just hate that code so much I didn't want to touch it
2884 * unless it was to fix it properly, which seemed a distraction from the
2885 * task at hand! -nmatsakis
2888 let unadjusted_ty = expr_ty(cx, expr);
2890 let adjustments = cx.adjustments.borrow();
2891 adjustments.get().find_copy(&expr.id)
2893 adjust_ty(cx, expr.span, unadjusted_ty, adjustment)
2896 pub fn adjust_ty(cx: ctxt,
2898 unadjusted_ty: ty::t,
2899 adjustment: Option<@AutoAdjustment>)
2901 /*! See `expr_ty_adjusted` */
2903 return match adjustment {
2904 None => unadjusted_ty,
2906 Some(adjustment) => {
2908 AutoAddEnv(r, s) => {
2909 match ty::get(unadjusted_ty).sty {
2910 ty::ty_bare_fn(ref b) => {
2913 ty::ClosureTy {purity: b.purity,
2915 onceness: ast::Many,
2917 bounds: ty::AllBuiltinBounds(),
2918 sig: b.sig.clone()})
2922 format!("add_env adjustment on non-bare-fn: \
2929 AutoDerefRef(ref adj) => {
2930 let mut adjusted_ty = unadjusted_ty;
2932 if !ty::type_is_error(adjusted_ty) {
2933 for i in range(0, adj.autoderefs) {
2934 match ty::deref(adjusted_ty, true) {
2935 Some(mt) => { adjusted_ty = mt.ty; }
2939 format!("The {}th autoderef failed: \
2942 ty_to_str(cx, adjusted_ty)));
2949 None => adjusted_ty,
2950 Some(ref autoref) => {
2959 AutoBorrowVec(r, m) => {
2960 borrow_vec(cx, span, r, m, adjusted_ty)
2963 AutoBorrowVecRef(r, m) => {
2964 adjusted_ty = borrow_vec(cx,
2971 mutbl: ast::MutImmutable
2975 AutoBorrowFn(r) => {
2976 borrow_fn(cx, span, r, adjusted_ty)
2980 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
2983 AutoBorrowObj(r, m) => {
2984 borrow_obj(cx, span, r, m, adjusted_ty)
2991 AutoObject(ref sigil, ref region, m, b, def_id, ref substs) => {
2992 trait_adjustment_to_ty(cx,
3004 fn borrow_vec(cx: ctxt, span: Span,
3005 r: Region, m: ast::Mutability,
3006 ty: ty::t) -> ty::t {
3009 ty::mk_vec(cx, mt {ty: mt.ty, mutbl: m}, vstore_slice(r))
3013 ty::mk_str(cx, vstore_slice(r))
3019 format!("borrow-vec associated with bad sty: {:?}",
3025 fn borrow_fn(cx: ctxt, span: Span, r: Region, ty: ty::t) -> ty::t {
3027 ty_closure(ref fty) => {
3028 ty::mk_closure(cx, ClosureTy {
3029 sigil: BorrowedSigil,
3038 format!("borrow-fn associated with bad sty: {:?}",
3044 fn borrow_obj(cx: ctxt, span: Span, r: Region,
3045 m: ast::Mutability, ty: ty::t) -> ty::t {
3047 ty_trait(trt_did, ref trt_substs, _, _, b) => {
3048 ty::mk_trait(cx, trt_did, trt_substs.clone(),
3049 RegionTraitStore(r), m, b)
3054 format!("borrow-trait-obj associated with bad sty: {:?}",
3061 pub fn trait_adjustment_to_ty(cx: ctxt, sigil: &ast::Sigil, region: &Option<Region>,
3062 def_id: ast::DefId, substs: &substs, m: ast::Mutability,
3063 bounds: BuiltinBounds) -> t {
3065 let trait_store = match *sigil {
3066 BorrowedSigil => RegionTraitStore(region.expect("expected valid region")),
3067 OwnedSigil => UniqTraitStore,
3068 ManagedSigil => BoxTraitStore
3071 mk_trait(cx, def_id, substs.clone(), trait_store, m, bounds)
3075 pub fn map_region(&self, f: |Region| -> Region) -> AutoRef {
3077 ty::AutoPtr(r, m) => ty::AutoPtr(f(r), m),
3078 ty::AutoBorrowVec(r, m) => ty::AutoBorrowVec(f(r), m),
3079 ty::AutoBorrowVecRef(r, m) => ty::AutoBorrowVecRef(f(r), m),
3080 ty::AutoBorrowFn(r) => ty::AutoBorrowFn(f(r)),
3081 ty::AutoUnsafe(m) => ty::AutoUnsafe(m),
3082 ty::AutoBorrowObj(r, m) => ty::AutoBorrowObj(f(r), m),
3087 pub struct ParamsTy {
3092 pub fn expr_ty_params_and_ty(cx: ctxt,
3096 params: node_id_to_type_params(cx, expr.id),
3097 ty: node_id_to_type(cx, expr.id)
3101 pub fn expr_has_ty_params(cx: ctxt, expr: &ast::Expr) -> bool {
3102 return node_id_has_type_params(cx, expr.id);
3105 pub fn method_call_type_param_defs(tcx: ctxt,
3106 method_map: typeck::method_map,
3108 -> Option<@~[TypeParameterDef]> {
3109 let method_map = method_map.borrow();
3110 method_map.get().find(&id).map(|method| {
3111 match method.origin {
3112 typeck::method_static(did) => {
3113 // n.b.: When we encode impl methods, the bounds
3114 // that we encode include both the impl bounds
3115 // and then the method bounds themselves...
3116 ty::lookup_item_type(tcx, did).generics.type_param_defs
3118 typeck::method_param(typeck::method_param {
3120 method_num: n_mth, ..}) |
3121 typeck::method_object(typeck::method_object {
3123 method_num: n_mth, ..}) => {
3124 // ...trait methods bounds, in contrast, include only the
3125 // method bounds, so we must preprend the tps from the
3126 // trait itself. This ought to be harmonized.
3127 let trait_type_param_defs =
3128 lookup_trait_def(tcx, trt_id).generics.type_param_defs;
3130 (*trait_type_param_defs).clone(),
3131 *ty::trait_method(tcx,
3133 n_mth).generics.type_param_defs)
3139 pub fn resolve_expr(tcx: ctxt, expr: &ast::Expr) -> ast::Def {
3140 let def_map = tcx.def_map.borrow();
3141 match def_map.get().find(&expr.id) {
3144 tcx.sess.span_bug(expr.span, format!(
3145 "No def-map entry for expr {:?}", expr.id));
3150 pub fn expr_is_lval(tcx: ctxt,
3151 method_map: typeck::method_map,
3152 e: &ast::Expr) -> bool {
3153 match expr_kind(tcx, method_map, e) {
3155 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
3159 /// We categorize expressions into three kinds. The distinction between
3160 /// lvalue/rvalue is fundamental to the language. The distinction between the
3161 /// two kinds of rvalues is an artifact of trans which reflects how we will
3162 /// generate code for that kind of expression. See trans/expr.rs for more
3171 pub fn expr_kind(tcx: ctxt,
3172 method_map: typeck::method_map,
3173 expr: &ast::Expr) -> ExprKind {
3175 let method_map = method_map.borrow();
3176 if method_map.get().contains_key(&expr.id) {
3177 // Overloaded operations are generally calls, and hence they are
3178 // generated via DPS. However, assign_op (e.g., `x += y`) is an
3179 // exception, as its result is always unit.
3180 return match expr.node {
3181 ast::ExprAssignOp(..) => RvalueStmtExpr,
3188 ast::ExprPath(..) => {
3189 match resolve_expr(tcx, expr) {
3190 ast::DefVariant(tid, vid, _) => {
3191 let variant_info = enum_variant_with_id(tcx, tid, vid);
3192 if variant_info.args.len() > 0u {
3201 ast::DefStruct(_) => {
3202 match get(expr_ty(tcx, expr)).sty {
3203 ty_bare_fn(..) => RvalueDatumExpr,
3208 // Fn pointers are just scalar values.
3209 ast::DefFn(..) | ast::DefStaticMethod(..) => RvalueDatumExpr,
3211 // Note: there is actually a good case to be made that
3212 // DefArg's, particularly those of immediate type, ought to
3213 // considered rvalues.
3214 ast::DefStatic(..) |
3215 ast::DefBinding(..) |
3218 ast::DefLocal(..) => LvalueExpr,
3221 tcx.sess.span_bug(expr.span, format!(
3222 "Uncategorized def for expr {:?}: {:?}",
3228 ast::ExprUnary(_, ast::UnDeref, _) |
3229 ast::ExprField(..) |
3230 ast::ExprIndex(..) => {
3235 ast::ExprMethodCall(..) |
3236 ast::ExprStruct(..) |
3239 ast::ExprMatch(..) |
3240 ast::ExprFnBlock(..) |
3242 ast::ExprBlock(..) |
3243 ast::ExprRepeat(..) |
3244 ast::ExprVstore(_, ast::ExprVstoreSlice) |
3245 ast::ExprVstore(_, ast::ExprVstoreMutSlice) |
3246 ast::ExprVec(..) => {
3250 ast::ExprLit(lit) if lit_is_str(lit) => {
3254 ast::ExprCast(..) => {
3255 let node_types = tcx.node_types.borrow();
3256 match node_types.get().find(&(expr.id as uint)) {
3258 if type_is_trait(t) {
3265 // Technically, it should not happen that the expr is not
3266 // present within the table. However, it DOES happen
3267 // during type check, because the final types from the
3268 // expressions are not yet recorded in the tcx. At that
3269 // time, though, we are only interested in knowing lvalue
3270 // vs rvalue. It would be better to base this decision on
3271 // the AST type in cast node---but (at the time of this
3272 // writing) it's not easy to distinguish casts to traits
3273 // from other casts based on the AST. This should be
3274 // easier in the future, when casts to traits would like
3275 // like @Foo, ~Foo, or &Foo.
3281 ast::ExprBreak(..) |
3282 ast::ExprAgain(..) |
3284 ast::ExprWhile(..) |
3286 ast::ExprAssign(..) |
3287 ast::ExprInlineAsm(..) |
3288 ast::ExprAssignOp(..) => {
3292 ast::ExprForLoop(..) => fail!("non-desugared expr_for_loop"),
3295 ast::ExprLit(_) | // Note: LitStr is carved out above
3296 ast::ExprUnary(..) |
3297 ast::ExprAddrOf(..) |
3298 ast::ExprBinary(..) |
3299 ast::ExprVstore(_, ast::ExprVstoreBox) |
3300 ast::ExprVstore(_, ast::ExprVstoreUniq) => {
3304 ast::ExprBox(place, _) => {
3305 // Special case `~T` for now:
3306 let def_map = tcx.def_map.borrow();
3307 let definition = match def_map.get().find(&place.id) {
3309 None => fail!("no def for place"),
3311 let def_id = ast_util::def_id_of_def(definition);
3312 match tcx.lang_items.items[ExchangeHeapLangItem as uint] {
3313 Some(item_def_id) if def_id == item_def_id => RvalueDatumExpr,
3314 Some(_) | None => RvalueDpsExpr,
3318 ast::ExprParen(e) => expr_kind(tcx, method_map, e),
3320 ast::ExprMac(..) => {
3323 "macro expression remains after expansion");
3328 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
3330 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
3333 ast::StmtMac(..) => fail!("unexpanded macro in trans")
3337 pub fn field_idx(name: ast::Name, fields: &[field]) -> Option<uint> {
3339 for f in fields.iter() { if f.ident.name == name { return Some(i); } i += 1u; }
3343 pub fn field_idx_strict(tcx: ty::ctxt, name: ast::Name, fields: &[field])
3346 for f in fields.iter() { if f.ident.name == name { return i; } i += 1u; }
3347 let string = token::get_ident(name);
3348 tcx.sess.bug(format!(
3349 "No field named `{}` found in the list of fields `{:?}`",
3351 fields.map(|f| tcx.sess.str_of(f.ident))));
3354 pub fn method_idx(id: ast::Ident, meths: &[@Method]) -> Option<uint> {
3355 meths.iter().position(|m| m.ident == id)
3358 /// Returns a vector containing the indices of all type parameters that appear
3359 /// in `ty`. The vector may contain duplicates. Probably should be converted
3360 /// to a bitset or some other representation.
3361 pub fn param_tys_in_type(ty: t) -> ~[param_ty] {
3374 pub fn occurs_check(tcx: ctxt, sp: Span, vid: TyVid, rt: t) {
3375 // Returns a vec of all the type variables occurring in `ty`. It may
3376 // contain duplicates. (Integral type vars aren't counted.)
3377 fn vars_in_type(ty: t) -> ~[TyVid] {
3381 ty_infer(TyVar(v)) => rslt.push(v),
3389 if !type_needs_infer(rt) { return; }
3392 if vars_in_type(rt).contains(&vid) {
3393 // Maybe this should be span_err -- however, there's an
3394 // assertion later on that the type doesn't contain
3395 // variables, so in this case we have to be sure to die.
3397 (sp, ~"type inference failed because I \
3398 could not find a type\n that's both of the form "
3399 + ::util::ppaux::ty_to_str(tcx, mk_var(tcx, vid)) +
3400 " and of the form " + ::util::ppaux::ty_to_str(tcx, rt) +
3401 " - such a type would have to be infinitely large.");
3405 pub fn ty_sort_str(cx: ctxt, t: t) -> ~str {
3407 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) |
3408 ty_uint(_) | ty_float(_) | ty_str(_) | ty_type => {
3409 ::util::ppaux::ty_to_str(cx, t)
3412 ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
3413 ty_box(_) => ~"@-ptr",
3414 ty_uniq(_) => ~"~-ptr",
3415 ty_vec(_, _) => ~"vector",
3416 ty_unboxed_vec(_) => ~"unboxed vector",
3417 ty_ptr(_) => ~"*-ptr",
3418 ty_rptr(_, _) => ~"&-ptr",
3419 ty_bare_fn(_) => ~"extern fn",
3420 ty_closure(_) => ~"fn",
3421 ty_trait(id, _, _, _, _) => format!("trait {}", item_path_str(cx, id)),
3422 ty_struct(id, _) => format!("struct {}", item_path_str(cx, id)),
3423 ty_tup(_) => ~"tuple",
3424 ty_infer(TyVar(_)) => ~"inferred type",
3425 ty_infer(IntVar(_)) => ~"integral variable",
3426 ty_infer(FloatVar(_)) => ~"floating-point variable",
3427 ty_param(_) => ~"type parameter",
3428 ty_self(_) => ~"self",
3429 ty_err => ~"type error"
3433 pub fn type_err_to_str(cx: ctxt, err: &type_err) -> ~str {
3436 * Explains the source of a type err in a short,
3437 * human readable way. This is meant to be placed in
3438 * parentheses after some larger message. You should
3439 * also invoke `note_and_explain_type_err()` afterwards
3440 * to present additional details, particularly when
3441 * it comes to lifetime-related errors. */
3443 fn terr_vstore_kind_to_str(k: terr_vstore_kind) -> ~str {
3448 terr_trait => ~"trait"
3453 terr_mismatch => ~"types differ",
3454 terr_purity_mismatch(values) => {
3455 format!("expected {} fn but found {} fn",
3456 values.expected.to_str(), values.found.to_str())
3458 terr_abi_mismatch(values) => {
3459 format!("expected {} fn but found {} fn",
3460 values.expected.to_str(), values.found.to_str())
3462 terr_onceness_mismatch(values) => {
3463 format!("expected {} fn but found {} fn",
3464 values.expected.to_str(), values.found.to_str())
3466 terr_sigil_mismatch(values) => {
3467 format!("expected {} closure, found {} closure",
3468 values.expected.to_str(),
3469 values.found.to_str())
3471 terr_mutability => ~"values differ in mutability",
3472 terr_box_mutability => ~"boxed values differ in mutability",
3473 terr_vec_mutability => ~"vectors differ in mutability",
3474 terr_ptr_mutability => ~"pointers differ in mutability",
3475 terr_ref_mutability => ~"references differ in mutability",
3476 terr_ty_param_size(values) => {
3477 format!("expected a type with {} type params \
3478 but found one with {} type params",
3479 values.expected, values.found)
3481 terr_tuple_size(values) => {
3482 format!("expected a tuple with {} elements \
3483 but found one with {} elements",
3484 values.expected, values.found)
3486 terr_record_size(values) => {
3487 format!("expected a record with {} fields \
3488 but found one with {} fields",
3489 values.expected, values.found)
3491 terr_record_mutability => {
3492 ~"record elements differ in mutability"
3494 terr_record_fields(values) => {
3495 format!("expected a record with field `{}` but found one with field \
3497 cx.sess.str_of(values.expected),
3498 cx.sess.str_of(values.found))
3500 terr_arg_count => ~"incorrect number of function parameters",
3501 terr_regions_does_not_outlive(..) => {
3502 format!("lifetime mismatch")
3504 terr_regions_not_same(..) => {
3505 format!("lifetimes are not the same")
3507 terr_regions_no_overlap(..) => {
3508 format!("lifetimes do not intersect")
3510 terr_regions_insufficiently_polymorphic(br, _) => {
3511 format!("expected bound lifetime parameter {}, \
3512 but found concrete lifetime",
3513 bound_region_ptr_to_str(cx, br))
3515 terr_regions_overly_polymorphic(br, _) => {
3516 format!("expected concrete lifetime, \
3517 but found bound lifetime parameter {}",
3518 bound_region_ptr_to_str(cx, br))
3520 terr_vstores_differ(k, ref values) => {
3521 format!("{} storage differs: expected `{}` but found `{}`",
3522 terr_vstore_kind_to_str(k),
3523 vstore_to_str(cx, (*values).expected),
3524 vstore_to_str(cx, (*values).found))
3526 terr_trait_stores_differ(_, ref values) => {
3527 format!("trait storage differs: expected `{}` but found `{}`",
3528 trait_store_to_str(cx, (*values).expected),
3529 trait_store_to_str(cx, (*values).found))
3531 terr_in_field(err, fname) => {
3532 format!("in field `{}`, {}", cx.sess.str_of(fname),
3533 type_err_to_str(cx, err))
3535 terr_sorts(values) => {
3536 format!("expected {} but found {}",
3537 ty_sort_str(cx, values.expected),
3538 ty_sort_str(cx, values.found))
3540 terr_traits(values) => {
3541 format!("expected trait `{}` but found trait `{}`",
3542 item_path_str(cx, values.expected),
3543 item_path_str(cx, values.found))
3545 terr_builtin_bounds(values) => {
3546 if values.expected.is_empty() {
3547 format!("expected no bounds but found `{}`",
3548 values.found.user_string(cx))
3549 } else if values.found.is_empty() {
3550 format!("expected bounds `{}` but found no bounds",
3551 values.expected.user_string(cx))
3553 format!("expected bounds `{}` but found bounds `{}`",
3554 values.expected.user_string(cx),
3555 values.found.user_string(cx))
3558 terr_integer_as_char => {
3559 format!("expected an integral type but found char")
3561 terr_int_mismatch(ref values) => {
3562 format!("expected {} but found {}",
3563 values.expected.to_str(),
3564 values.found.to_str())
3566 terr_float_mismatch(ref values) => {
3567 format!("expected {} but found {}",
3568 values.expected.to_str(),
3569 values.found.to_str())
3571 terr_variadic_mismatch(ref values) => {
3572 format!("expected {} fn but found {} function",
3573 if values.expected { "variadic" } else { "non-variadic" },
3574 if values.found { "variadic" } else { "non-variadic" })
3579 pub fn note_and_explain_type_err(cx: ctxt, err: &type_err) {
3581 terr_regions_does_not_outlive(subregion, superregion) => {
3582 note_and_explain_region(cx, "", subregion, "...");
3583 note_and_explain_region(cx, "...does not necessarily outlive ",
3586 terr_regions_not_same(region1, region2) => {
3587 note_and_explain_region(cx, "", region1, "...");
3588 note_and_explain_region(cx, "...is not the same lifetime as ",
3591 terr_regions_no_overlap(region1, region2) => {
3592 note_and_explain_region(cx, "", region1, "...");
3593 note_and_explain_region(cx, "...does not overlap ",
3596 terr_regions_insufficiently_polymorphic(_, conc_region) => {
3597 note_and_explain_region(cx,
3598 "concrete lifetime that was found is ",
3601 terr_regions_overly_polymorphic(_, conc_region) => {
3602 note_and_explain_region(cx,
3603 "expected concrete lifetime is ",
3610 pub fn def_has_ty_params(def: ast::Def) -> bool {
3612 ast::DefFn(_, _) | ast::DefVariant(_, _, _) | ast::DefStruct(_)
3618 pub fn provided_source(cx: ctxt, id: ast::DefId) -> Option<ast::DefId> {
3619 let provided_method_sources = cx.provided_method_sources.borrow();
3620 provided_method_sources.get().find(&id).map(|x| *x)
3623 pub fn provided_trait_methods(cx: ctxt, id: ast::DefId) -> ~[@Method] {
3626 match cx.items.find(id.node) {
3627 Some(ast_map::NodeItem(item, _)) => {
3629 ItemTrait(_, _, ref ms) => {
3630 let (_, p) = ast_util::split_trait_methods(*ms);
3631 p.map(|m| method(cx, ast_util::local_def(m.id)))
3634 cx.sess.bug(format!("provided_trait_methods: \
3635 {:?} is not a trait",
3641 cx.sess.bug(format!("provided_trait_methods: {:?} is not \
3648 csearch::get_provided_trait_methods(cx, id)
3652 pub fn trait_supertraits(cx: ctxt, id: ast::DefId) -> @~[@TraitRef] {
3655 let supertraits = cx.supertraits.borrow();
3656 match supertraits.get().find(&id) {
3657 Some(&trait_refs) => { return trait_refs; }
3658 None => {} // Continue.
3662 // Not in the cache. It had better be in the metadata, which means it
3663 // shouldn't be local.
3664 assert!(!is_local(id));
3666 // Get the supertraits out of the metadata and create the
3667 // TraitRef for each.
3668 let result = @csearch::get_supertraits(cx, id);
3669 let mut supertraits = cx.supertraits.borrow_mut();
3670 supertraits.get().insert(id, result);
3674 pub fn trait_ref_supertraits(cx: ctxt, trait_ref: &ty::TraitRef) -> ~[@TraitRef] {
3675 let supertrait_refs = trait_supertraits(cx, trait_ref.def_id);
3676 supertrait_refs.map(
3677 |supertrait_ref| supertrait_ref.subst(cx, &trait_ref.substs))
3680 fn lookup_locally_or_in_crate_store<V:Clone>(
3683 map: &mut HashMap<ast::DefId, V>,
3684 load_external: || -> V) -> V {
3686 * Helper for looking things up in the various maps
3687 * that are populated during typeck::collect (e.g.,
3688 * `cx.methods`, `cx.tcache`, etc). All of these share
3689 * the pattern that if the id is local, it should have
3690 * been loaded into the map by the `typeck::collect` phase.
3691 * If the def-id is external, then we have to go consult
3692 * the crate loading code (and cache the result for the future).
3695 match map.find_copy(&def_id) {
3696 Some(v) => { return v; }
3700 if def_id.crate == ast::LOCAL_CRATE {
3701 fail!("No def'n found for {:?} in tcx.{}", def_id, descr);
3703 let v = load_external();
3704 map.insert(def_id, v.clone());
3708 pub fn trait_method(cx: ctxt, trait_did: ast::DefId, idx: uint) -> @Method {
3709 let method_def_id = ty::trait_method_def_ids(cx, trait_did)[idx];
3710 ty::method(cx, method_def_id)
3714 pub fn trait_methods(cx: ctxt, trait_did: ast::DefId) -> @~[@Method] {
3715 let mut trait_methods_cache = cx.trait_methods_cache.borrow_mut();
3716 match trait_methods_cache.get().find(&trait_did) {
3717 Some(&methods) => methods,
3719 let def_ids = ty::trait_method_def_ids(cx, trait_did);
3720 let methods = @def_ids.map(|d| ty::method(cx, *d));
3721 trait_methods_cache.get().insert(trait_did, methods);
3727 pub fn method(cx: ctxt, id: ast::DefId) -> @Method {
3728 let mut methods = cx.methods.borrow_mut();
3729 lookup_locally_or_in_crate_store("methods", id, methods.get(), || {
3730 @csearch::get_method(cx, id)
3734 pub fn trait_method_def_ids(cx: ctxt, id: ast::DefId) -> @~[DefId] {
3735 let mut trait_method_def_ids = cx.trait_method_def_ids.borrow_mut();
3736 lookup_locally_or_in_crate_store("trait_method_def_ids",
3738 trait_method_def_ids.get(),
3740 @csearch::get_trait_method_def_ids(cx.cstore, id)
3744 pub fn impl_trait_ref(cx: ctxt, id: ast::DefId) -> Option<@TraitRef> {
3746 let mut impl_trait_cache = cx.impl_trait_cache.borrow_mut();
3747 match impl_trait_cache.get().find(&id) {
3748 Some(&ret) => { return ret; }
3753 let ret = if id.crate == ast::LOCAL_CRATE {
3754 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
3756 match cx.items.find(id.node) {
3757 Some(ast_map::NodeItem(item, _)) => {
3759 ast::ItemImpl(_, ref opt_trait, _, _) => {
3762 Some(ty::node_id_to_trait_ref(cx,
3775 csearch::get_impl_trait(cx, id)
3778 let mut impl_trait_cache = cx.impl_trait_cache.borrow_mut();
3779 impl_trait_cache.get().insert(id, ret);
3783 pub fn trait_ref_to_def_id(tcx: ctxt, tr: &ast::TraitRef) -> ast::DefId {
3784 let def_map = tcx.def_map.borrow();
3785 let def = def_map.get()
3787 .expect("no def-map entry for trait");
3788 ast_util::def_id_of_def(*def)
3791 pub fn try_add_builtin_trait(tcx: ctxt,
3792 trait_def_id: ast::DefId,
3793 builtin_bounds: &mut BuiltinBounds) -> bool {
3794 //! Checks whether `trait_ref` refers to one of the builtin
3795 //! traits, like `Send`, and adds the corresponding
3796 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
3797 //! is a builtin trait.
3799 match tcx.lang_items.to_builtin_kind(trait_def_id) {
3800 Some(bound) => { builtin_bounds.add(bound); true }
3805 pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> {
3807 ty_trait(id, _, _, _, _) | ty_struct(id, _) | ty_enum(id, _) => Some(id),
3814 pub struct VariantInfo {
3816 arg_names: Option<~[ast::Ident]>,
3826 /// Creates a new VariantInfo from the corresponding ast representation.
3828 /// Does not do any caching of the value in the type context.
3829 pub fn from_ast_variant(cx: ctxt,
3830 ast_variant: &ast::Variant,
3831 discriminant: Disr) -> VariantInfo {
3832 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
3834 match ast_variant.node.kind {
3835 ast::TupleVariantKind(ref args) => {
3836 let arg_tys = if args.len() > 0 { ty_fn_args(ctor_ty).map(|a| *a) } else { ~[] };
3838 return VariantInfo {
3842 name: ast_variant.node.name,
3843 id: ast_util::local_def(ast_variant.node.id),
3844 disr_val: discriminant,
3845 vis: ast_variant.node.vis
3848 ast::StructVariantKind(ref struct_def) => {
3850 let fields: &[StructField] = struct_def.fields;
3852 assert!(fields.len() > 0);
3854 let arg_tys = ty_fn_args(ctor_ty).map(|a| *a);
3855 let arg_names = fields.map(|field| {
3856 match field.node.kind {
3857 NamedField(ident, _) => ident,
3858 UnnamedField => cx.sess.bug(
3859 "enum_variants: all fields in struct must have a name")
3863 return VariantInfo {
3865 arg_names: Some(arg_names),
3867 name: ast_variant.node.name,
3868 id: ast_util::local_def(ast_variant.node.id),
3869 disr_val: discriminant,
3870 vis: ast_variant.node.vis
3877 pub fn substd_enum_variants(cx: ctxt,
3880 -> ~[@VariantInfo] {
3881 enum_variants(cx, id).iter().map(|variant_info| {
3882 let substd_args = variant_info.args.iter()
3883 .map(|aty| subst(cx, substs, *aty)).collect();
3885 let substd_ctor_ty = subst(cx, substs, variant_info.ctor_ty);
3889 ctor_ty: substd_ctor_ty,
3890 ..(**variant_info).clone()
3895 pub fn item_path_str(cx: ctxt, id: ast::DefId) -> ~str {
3896 ast_map::path_to_str(item_path(cx, id), token::get_ident_interner())
3901 TraitDtor(DefId, bool)
3905 pub fn is_not_present(&self) -> bool {
3912 pub fn is_present(&self) -> bool {
3913 !self.is_not_present()
3916 pub fn has_drop_flag(&self) -> bool {
3919 &TraitDtor(_, flag) => flag
3924 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
3925 Otherwise return none. */
3926 pub fn ty_dtor(cx: ctxt, struct_id: DefId) -> DtorKind {
3927 let destructor_for_type = cx.destructor_for_type.borrow();
3928 match destructor_for_type.get().find(&struct_id) {
3929 Some(&method_def_id) => {
3930 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
3932 TraitDtor(method_def_id, flag)
3938 pub fn has_dtor(cx: ctxt, struct_id: DefId) -> bool {
3939 ty_dtor(cx, struct_id).is_present()
3942 pub fn item_path(cx: ctxt, id: ast::DefId) -> ast_map::Path {
3943 if id.crate != ast::LOCAL_CRATE {
3944 return csearch::get_item_path(cx, id)
3947 // FIXME (#5521): uncomment this code and don't have a catch-all at the
3948 // end of the match statement. Favor explicitly listing
3950 // let node = cx.items.get(&id.node);
3952 match cx.items.get(id.node) {
3953 ast_map::NodeItem(item, path) => {
3954 let item_elt = match item.node {
3955 ItemMod(_) | ItemForeignMod(_) => {
3956 ast_map::PathMod(item.ident)
3958 _ => ast_map::PathName(item.ident)
3960 vec::append_one((*path).clone(), item_elt)
3963 ast_map::NodeForeignItem(nitem, _, _, path) => {
3964 vec::append_one((*path).clone(),
3965 ast_map::PathName(nitem.ident))
3968 ast_map::NodeMethod(method, _, path) => {
3969 vec::append_one((*path).clone(),
3970 ast_map::PathName(method.ident))
3972 ast_map::NodeTraitMethod(trait_method, _, path) => {
3973 let method = ast_util::trait_method_to_ty_method(&*trait_method);
3974 vec::append_one((*path).clone(),
3975 ast_map::PathName(method.ident))
3978 ast_map::NodeVariant(ref variant, _, path) => {
3979 vec::append_one(path.init().to_owned(),
3980 ast_map::PathName((*variant).node.name))
3983 ast_map::NodeStructCtor(_, item, path) => {
3984 vec::append_one((*path).clone(), ast_map::PathName(item.ident))
3988 cx.sess.bug(format!("cannot find item_path for node {:?}", node));
3993 pub fn enum_is_univariant(cx: ctxt, id: ast::DefId) -> bool {
3994 enum_variants(cx, id).len() == 1
3997 pub fn type_is_empty(cx: ctxt, t: t) -> bool {
3998 match ty::get(t).sty {
3999 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
4004 pub fn enum_variants(cx: ctxt, id: ast::DefId) -> @~[@VariantInfo] {
4006 let enum_var_cache = cx.enum_var_cache.borrow();
4007 match enum_var_cache.get().find(&id) {
4008 Some(&variants) => return variants,
4009 _ => { /* fallthrough */ }
4013 let result = if ast::LOCAL_CRATE != id.crate {
4014 @csearch::get_enum_variants(cx, id)
4017 Although both this code and check_enum_variants in typeck/check
4018 call eval_const_expr, it should never get called twice for the same
4019 expr, since check_enum_variants also updates the enum_var_cache
4022 match cx.items.get(id.node) {
4023 ast_map::NodeItem(item, _) => {
4025 ast::ItemEnum(ref enum_definition, _) => {
4026 let mut last_discriminant: Option<Disr> = None;
4027 @enum_definition.variants.iter().map(|&variant| {
4029 let mut discriminant = match last_discriminant {
4030 Some(val) => val + 1,
4031 None => INITIAL_DISCRIMINANT_VALUE
4034 match variant.node.disr_expr {
4035 Some(e) => match const_eval::eval_const_expr_partial(&cx, e) {
4036 Ok(const_eval::const_int(val)) => {
4037 discriminant = val as Disr
4039 Ok(const_eval::const_uint(val)) => {
4040 discriminant = val as Disr
4045 "expected signed integer \
4060 @VariantInfo::from_ast_variant(cx,
4063 last_discriminant = Some(discriminant);
4069 cx.sess.bug("enum_variants: id not bound to an enum")
4073 _ => cx.sess.bug("enum_variants: id not bound to an enum")
4079 let mut enum_var_cache = cx.enum_var_cache.borrow_mut();
4080 enum_var_cache.get().insert(id, result);
4086 // Returns information about the enum variant with the given ID:
4087 pub fn enum_variant_with_id(cx: ctxt,
4088 enum_id: ast::DefId,
4089 variant_id: ast::DefId)
4091 let variants = enum_variants(cx, enum_id);
4093 while i < variants.len() {
4094 let variant = variants[i];
4095 if variant.id == variant_id { return variant; }
4098 cx.sess.bug("enum_variant_with_id(): no variant exists with that ID");
4102 // If the given item is in an external crate, looks up its type and adds it to
4103 // the type cache. Returns the type parameters and type.
4104 pub fn lookup_item_type(cx: ctxt,
4106 -> ty_param_bounds_and_ty {
4107 let mut tcache = cx.tcache.borrow_mut();
4108 lookup_locally_or_in_crate_store(
4109 "tcache", did, tcache.get(),
4110 || csearch::get_type(cx, did))
4113 pub fn lookup_impl_vtables(cx: ctxt,
4115 -> typeck::impl_res {
4116 let mut impl_vtables = cx.impl_vtables.borrow_mut();
4117 lookup_locally_or_in_crate_store(
4118 "impl_vtables", did, impl_vtables.get(),
4119 || csearch::get_impl_vtables(cx, did) )
4122 /// Given the did of a trait, returns its canonical trait ref.
4123 pub fn lookup_trait_def(cx: ctxt, did: ast::DefId) -> @ty::TraitDef {
4124 let mut trait_defs = cx.trait_defs.borrow_mut();
4125 match trait_defs.get().find(&did) {
4126 Some(&trait_def) => {
4127 // The item is in this crate. The caller should have added it to the
4128 // type cache already
4132 assert!(did.crate != ast::LOCAL_CRATE);
4133 let trait_def = @csearch::get_trait_def(cx, did);
4134 trait_defs.get().insert(did, trait_def);
4140 /// Iterate over meta_items of a definition.
4141 // (This should really be an iterator, but that would require csearch and
4142 // decoder to use iterators instead of higher-order functions.)
4143 pub fn each_attr(tcx: ctxt, did: DefId, f: |@MetaItem| -> bool) -> bool {
4146 match tcx.items.find(did.node) {
4147 Some(ast_map::NodeItem(item, _)) => {
4148 item.attrs.iter().advance(|attr| f(attr.node.value))
4150 _ => tcx.sess.bug(format!("has_attr: {:?} is not an item",
4155 let mut cont = true;
4156 csearch::get_item_attrs(tcx.cstore, did, |meta_items| {
4158 cont = meta_items.iter().advance(|ptrptr| f(*ptrptr));
4165 /// Determine whether an item is annotated with an attribute
4166 pub fn has_attr(tcx: ctxt, did: DefId, attr: &str) -> bool {
4167 let mut found = false;
4168 each_attr(tcx, did, |item| {
4169 if item.name().equiv(&attr) {
4179 /// Determine whether an item is annotated with `#[packed]`
4180 pub fn lookup_packed(tcx: ctxt, did: DefId) -> bool {
4181 has_attr(tcx, did, "packed")
4184 /// Determine whether an item is annotated with `#[simd]`
4185 pub fn lookup_simd(tcx: ctxt, did: DefId) -> bool {
4186 has_attr(tcx, did, "simd")
4189 // Obtain the the representation annotation for a definition.
4190 pub fn lookup_repr_hint(tcx: ctxt, did: DefId) -> attr::ReprAttr {
4191 let mut acc = attr::ReprAny;
4192 ty::each_attr(tcx, did, |meta| {
4193 acc = attr::find_repr_attr(tcx.sess.diagnostic(), meta, acc);
4199 // Look up a field ID, whether or not it's local
4200 // Takes a list of type substs in case the struct is generic
4201 pub fn lookup_field_type(tcx: ctxt,
4206 let t = if id.crate == ast::LOCAL_CRATE {
4207 node_id_to_type(tcx, id.node)
4210 let mut tcache = tcx.tcache.borrow_mut();
4211 match tcache.get().find(&id) {
4212 Some(&ty_param_bounds_and_ty {ty, ..}) => ty,
4214 let tpt = csearch::get_field_type(tcx, struct_id, id);
4215 tcache.get().insert(id, tpt);
4221 subst(tcx, substs, t)
4224 // Look up the list of field names and IDs for a given struct
4225 // Fails if the id is not bound to a struct.
4226 pub fn lookup_struct_fields(cx: ctxt, did: ast::DefId) -> ~[field_ty] {
4227 if did.crate == ast::LOCAL_CRATE {
4229 match cx.items.find(did.node) {
4230 Some(ast_map::NodeItem(i,_)) => {
4232 ast::ItemStruct(struct_def, _) => {
4233 struct_field_tys(struct_def.fields)
4235 _ => cx.sess.bug("struct ID bound to non-struct")
4238 Some(ast_map::NodeVariant(ref variant, _, _)) => {
4239 match (*variant).node.kind {
4240 ast::StructVariantKind(struct_def) => {
4241 struct_field_tys(struct_def.fields)
4244 cx.sess.bug("struct ID bound to enum variant that isn't \
4251 format!("struct ID not bound to an item: {}",
4252 ast_map::node_id_to_str(cx.items, did.node,
4253 token::get_ident_interner())));
4258 return csearch::get_struct_fields(cx.sess.cstore, did);
4262 pub fn lookup_struct_field(cx: ctxt,
4264 field_id: ast::DefId)
4266 let r = lookup_struct_fields(cx, parent);
4267 match r.iter().find(
4268 |f| f.id.node == field_id.node) {
4270 None => cx.sess.bug("struct ID not found in parent's fields")
4274 fn struct_field_tys(fields: &[StructField]) -> ~[field_ty] {
4275 fields.map(|field| {
4276 match field.node.kind {
4277 NamedField(ident, visibility) => {
4280 id: ast_util::local_def(field.node.id),
4287 syntax::parse::token::special_idents::unnamed_field.name,
4288 id: ast_util::local_def(field.node.id),
4296 // Returns a list of fields corresponding to the struct's items. trans uses
4297 // this. Takes a list of substs with which to instantiate field types.
4298 pub fn struct_fields(cx: ctxt, did: ast::DefId, substs: &substs)
4300 lookup_struct_fields(cx, did).map(|f| {
4302 // FIXME #6993: change type of field to Name and get rid of new()
4303 ident: ast::Ident::new(f.name),
4305 ty: lookup_field_type(cx, did, f.id, substs),
4312 pub fn is_binopable(cx: ctxt, ty: t, op: ast::BinOp) -> bool {
4313 static tycat_other: int = 0;
4314 static tycat_bool: int = 1;
4315 static tycat_char: int = 2;
4316 static tycat_int: int = 3;
4317 static tycat_float: int = 4;
4318 static tycat_bot: int = 5;
4319 static tycat_raw_ptr: int = 6;
4321 static opcat_add: int = 0;
4322 static opcat_sub: int = 1;
4323 static opcat_mult: int = 2;
4324 static opcat_shift: int = 3;
4325 static opcat_rel: int = 4;
4326 static opcat_eq: int = 5;
4327 static opcat_bit: int = 6;
4328 static opcat_logic: int = 7;
4330 fn opcat(op: ast::BinOp) -> int {
4332 ast::BiAdd => opcat_add,
4333 ast::BiSub => opcat_sub,
4334 ast::BiMul => opcat_mult,
4335 ast::BiDiv => opcat_mult,
4336 ast::BiRem => opcat_mult,
4337 ast::BiAnd => opcat_logic,
4338 ast::BiOr => opcat_logic,
4339 ast::BiBitXor => opcat_bit,
4340 ast::BiBitAnd => opcat_bit,
4341 ast::BiBitOr => opcat_bit,
4342 ast::BiShl => opcat_shift,
4343 ast::BiShr => opcat_shift,
4344 ast::BiEq => opcat_eq,
4345 ast::BiNe => opcat_eq,
4346 ast::BiLt => opcat_rel,
4347 ast::BiLe => opcat_rel,
4348 ast::BiGe => opcat_rel,
4349 ast::BiGt => opcat_rel
4353 fn tycat(cx: ctxt, ty: t) -> int {
4354 if type_is_simd(cx, ty) {
4355 return tycat(cx, simd_type(cx, ty))
4358 ty_char => tycat_char,
4359 ty_bool => tycat_bool,
4360 ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
4361 ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
4362 ty_bot => tycat_bot,
4363 ty_ptr(_) => tycat_raw_ptr,
4368 static t: bool = true;
4369 static f: bool = false;
4372 // +, -, *, shift, rel, ==, bit, logic
4373 /*other*/ [f, f, f, f, f, f, f, f],
4374 /*bool*/ [f, f, f, f, t, t, t, t],
4375 /*char*/ [f, f, f, f, t, t, f, f],
4376 /*int*/ [t, t, t, t, t, t, t, f],
4377 /*float*/ [t, t, t, f, t, t, f, f],
4378 /*bot*/ [t, t, t, t, t, t, t, t],
4379 /*raw ptr*/ [f, f, f, f, t, t, f, f]];
4381 return tbl[tycat(cx, ty)][opcat(op)];
4384 pub fn ty_params_to_tys(tcx: ty::ctxt, generics: &ast::Generics) -> ~[t] {
4385 vec::from_fn(generics.ty_params.len(), |i| {
4386 let id = generics.ty_params.get(i).id;
4387 ty::mk_param(tcx, i, ast_util::local_def(id))
4391 /// Returns an equivalent type with all the typedefs and self regions removed.
4392 pub fn normalize_ty(cx: ctxt, t: t) -> t {
4393 let u = TypeNormalizer(cx).fold_ty(t);
4396 struct TypeNormalizer(ctxt);
4398 impl TypeFolder for TypeNormalizer {
4399 fn tcx(&self) -> ty::ctxt { let TypeNormalizer(c) = *self; c }
4401 fn fold_ty(&mut self, t: ty::t) -> ty::t {
4402 let normalized_opt = {
4403 let normalized_cache = self.tcx().normalized_cache.borrow();
4404 normalized_cache.get().find_copy(&t)
4406 match normalized_opt {
4411 let t_norm = ty_fold::super_fold_ty(self, t);
4412 let mut normalized_cache = self.tcx()
4415 normalized_cache.get().insert(t, t_norm);
4421 fn fold_vstore(&mut self, vstore: vstore) -> vstore {
4423 vstore_fixed(..) | vstore_uniq | vstore_box => vstore,
4424 vstore_slice(_) => vstore_slice(ReStatic)
4428 fn fold_region(&mut self, _: ty::Region) -> ty::Region {
4432 fn fold_substs(&mut self,
4435 substs { regions: ErasedRegions,
4436 self_ty: ty_fold::fold_opt_ty(self, substs.self_ty),
4437 tps: ty_fold::fold_ty_vec(self, substs.tps) }
4440 fn fold_sig(&mut self,
4443 // The binder-id is only relevant to bound regions, which
4444 // are erased at trans time.
4445 ty::FnSig { binder_id: ast::DUMMY_NODE_ID,
4446 inputs: ty_fold::fold_ty_vec(self, sig.inputs),
4447 output: self.fold_ty(sig.output),
4448 variadic: sig.variadic }
4453 pub trait ExprTyProvider {
4454 fn expr_ty(&self, ex: &ast::Expr) -> t;
4455 fn ty_ctxt(&self) -> ctxt;
4458 impl ExprTyProvider for ctxt {
4459 fn expr_ty(&self, ex: &ast::Expr) -> t {
4463 fn ty_ctxt(&self) -> ctxt {
4468 // Returns the repeat count for a repeating vector expression.
4469 pub fn eval_repeat_count<T: ExprTyProvider>(tcx: &T, count_expr: &ast::Expr) -> uint {
4470 match const_eval::eval_const_expr_partial(tcx, count_expr) {
4471 Ok(ref const_val) => match *const_val {
4472 const_eval::const_int(count) => if count < 0 {
4473 tcx.ty_ctxt().sess.span_err(count_expr.span,
4474 "expected positive integer for \
4475 repeat count but found negative integer");
4478 return count as uint
4480 const_eval::const_uint(count) => return count as uint,
4481 const_eval::const_float(count) => {
4482 tcx.ty_ctxt().sess.span_err(count_expr.span,
4483 "expected positive integer for \
4484 repeat count but found float");
4485 return count as uint;
4487 const_eval::const_str(_) => {
4488 tcx.ty_ctxt().sess.span_err(count_expr.span,
4489 "expected positive integer for \
4490 repeat count but found string");
4493 const_eval::const_bool(_) => {
4494 tcx.ty_ctxt().sess.span_err(count_expr.span,
4495 "expected positive integer for \
4496 repeat count but found boolean");
4499 const_eval::const_binary(_) => {
4500 tcx.ty_ctxt().sess.span_err(count_expr.span,
4501 "expected positive integer for \
4502 repeat count but found binary array");
4507 tcx.ty_ctxt().sess.span_err(count_expr.span,
4508 "expected constant integer for repeat count \
4509 but found variable");
4515 // Determine what purity to check a nested function under
4516 pub fn determine_inherited_purity(parent: (ast::Purity, ast::NodeId),
4517 child: (ast::Purity, ast::NodeId),
4518 child_sigil: ast::Sigil)
4519 -> (ast::Purity, ast::NodeId) {
4520 // If the closure is a stack closure and hasn't had some non-standard
4521 // purity inferred for it, then check it under its parent's purity.
4522 // Otherwise, use its own
4524 ast::BorrowedSigil if child.first() == ast::ImpureFn => parent,
4529 // Iterate over a type parameter's bounded traits and any supertraits
4530 // of those traits, ignoring kinds.
4531 // Here, the supertraits are the transitive closure of the supertrait
4532 // relation on the supertraits from each bounded trait's constraint
4534 pub fn each_bound_trait_and_supertraits(tcx: ctxt,
4535 bounds: &[@TraitRef],
4536 f: |@TraitRef| -> bool)
4538 for &bound_trait_ref in bounds.iter() {
4539 let mut supertrait_set = HashMap::new();
4540 let mut trait_refs = ~[];
4543 // Seed the worklist with the trait from the bound
4544 supertrait_set.insert(bound_trait_ref.def_id, ());
4545 trait_refs.push(bound_trait_ref);
4547 // Add the given trait ty to the hash map
4548 while i < trait_refs.len() {
4549 debug!("each_bound_trait_and_supertraits(i={:?}, trait_ref={})",
4550 i, trait_refs[i].repr(tcx));
4552 if !f(trait_refs[i]) {
4556 // Add supertraits to supertrait_set
4557 let supertrait_refs = trait_ref_supertraits(tcx, trait_refs[i]);
4558 for &supertrait_ref in supertrait_refs.iter() {
4559 debug!("each_bound_trait_and_supertraits(supertrait_ref={})",
4560 supertrait_ref.repr(tcx));
4562 let d_id = supertrait_ref.def_id;
4563 if !supertrait_set.contains_key(&d_id) {
4564 // FIXME(#5527) Could have same trait multiple times
4565 supertrait_set.insert(d_id, ());
4566 trait_refs.push(supertrait_ref);
4576 pub fn count_traits_and_supertraits(tcx: ctxt,
4577 type_param_defs: &[TypeParameterDef]) -> uint {
4579 for type_param_def in type_param_defs.iter() {
4580 each_bound_trait_and_supertraits(
4581 tcx, type_param_def.bounds.trait_bounds, |_| {
4589 pub fn get_tydesc_ty(tcx: ctxt) -> Result<t, ~str> {
4590 tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
4591 let intrinsic_defs = tcx.intrinsic_defs.borrow();
4592 intrinsic_defs.get().find_copy(&tydesc_lang_item)
4593 .expect("Failed to resolve TyDesc")
4597 pub fn get_opaque_ty(tcx: ctxt) -> Result<t, ~str> {
4598 tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| {
4599 let intrinsic_defs = tcx.intrinsic_defs.borrow();
4600 intrinsic_defs.get().find_copy(&opaque_lang_item)
4601 .expect("Failed to resolve Opaque")
4605 pub fn visitor_object_ty(tcx: ctxt,
4606 region: ty::Region) -> Result<(@TraitRef, t), ~str> {
4607 let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) {
4609 Err(s) => { return Err(s); }
4611 let substs = substs {
4612 regions: ty::NonerasedRegions(opt_vec::Empty),
4616 let trait_ref = @TraitRef { def_id: trait_lang_item, substs: substs };
4620 trait_ref.substs.clone(),
4621 RegionTraitStore(region),
4623 EmptyBuiltinBounds())))
4626 pub fn item_variances(tcx: ctxt, item_id: ast::DefId) -> @ItemVariances {
4627 let mut item_variance_map = tcx.item_variance_map.borrow_mut();
4628 lookup_locally_or_in_crate_store(
4629 "item_variance_map", item_id, item_variance_map.get(),
4630 || @csearch::get_item_variances(tcx.cstore, item_id))
4633 /// Records a trait-to-implementation mapping.
4634 fn record_trait_implementation(tcx: ctxt,
4635 trait_def_id: DefId,
4636 implementation: @Impl) {
4637 let implementation_list;
4638 let mut trait_impls = tcx.trait_impls.borrow_mut();
4639 match trait_impls.get().find(&trait_def_id) {
4641 implementation_list = @RefCell::new(~[]);
4642 trait_impls.get().insert(trait_def_id, implementation_list);
4644 Some(&existing_implementation_list) => {
4645 implementation_list = existing_implementation_list
4649 let mut implementation_list = implementation_list.borrow_mut();
4650 implementation_list.get().push(implementation);
4653 /// Populates the type context with all the implementations for the given type
4655 pub fn populate_implementations_for_type_if_necessary(tcx: ctxt,
4656 type_id: ast::DefId) {
4657 if type_id.crate == LOCAL_CRATE {
4661 let populated_external_types = tcx.populated_external_types.borrow();
4662 if populated_external_types.get().contains(&type_id) {
4667 csearch::each_implementation_for_type(tcx.sess.cstore, type_id,
4668 |implementation_def_id| {
4669 let implementation = @csearch::get_impl(tcx, implementation_def_id);
4671 // Record the trait->implementation mappings, if applicable.
4672 let associated_traits = csearch::get_impl_trait(tcx,
4673 implementation.did);
4674 for trait_ref in associated_traits.iter() {
4675 record_trait_implementation(tcx,
4680 // For any methods that use a default implementation, add them to
4681 // the map. This is a bit unfortunate.
4682 for method in implementation.methods.iter() {
4683 for source in method.provided_source.iter() {
4684 let mut provided_method_sources =
4685 tcx.provided_method_sources.borrow_mut();
4686 provided_method_sources.get().insert(method.def_id, *source);
4690 // If this is an inherent implementation, record it.
4691 if associated_traits.is_none() {
4692 let implementation_list;
4693 let mut inherent_impls = tcx.inherent_impls.borrow_mut();
4694 match inherent_impls.get().find(&type_id) {
4696 implementation_list = @RefCell::new(~[]);
4697 inherent_impls.get().insert(type_id, implementation_list);
4699 Some(&existing_implementation_list) => {
4700 implementation_list = existing_implementation_list;
4704 let mut implementation_list =
4705 implementation_list.borrow_mut();
4706 implementation_list.get().push(implementation);
4710 // Store the implementation info.
4711 let mut impls = tcx.impls.borrow_mut();
4712 impls.get().insert(implementation_def_id, implementation);
4715 let mut populated_external_types = tcx.populated_external_types
4717 populated_external_types.get().insert(type_id);
4720 /// Populates the type context with all the implementations for the given
4721 /// trait if necessary.
4722 pub fn populate_implementations_for_trait_if_necessary(
4724 trait_id: ast::DefId) {
4725 if trait_id.crate == LOCAL_CRATE {
4729 let populated_external_traits = tcx.populated_external_traits
4731 if populated_external_traits.get().contains(&trait_id) {
4736 csearch::each_implementation_for_trait(tcx.sess.cstore, trait_id,
4737 |implementation_def_id| {
4738 let implementation = @csearch::get_impl(tcx, implementation_def_id);
4740 // Record the trait->implementation mapping.
4741 record_trait_implementation(tcx, trait_id, implementation);
4743 // For any methods that use a default implementation, add them to
4744 // the map. This is a bit unfortunate.
4745 for method in implementation.methods.iter() {
4746 for source in method.provided_source.iter() {
4747 let mut provided_method_sources =
4748 tcx.provided_method_sources.borrow_mut();
4749 provided_method_sources.get().insert(method.def_id, *source);
4753 // Store the implementation info.
4754 let mut impls = tcx.impls.borrow_mut();
4755 impls.get().insert(implementation_def_id, implementation);
4758 let mut populated_external_traits = tcx.populated_external_traits
4760 populated_external_traits.get().insert(trait_id);
4763 /// Given the def_id of an impl, return the def_id of the trait it implements.
4764 /// If it implements no trait, return `None`.
4765 pub fn trait_id_of_impl(tcx: ctxt,
4766 def_id: ast::DefId) -> Option<ast::DefId> {
4767 let node = match tcx.items.find(def_id.node) {
4772 ast_map::NodeItem(item, _) => {
4774 ast::ItemImpl(_, Some(ref trait_ref), _, _) => {
4775 Some(node_id_to_trait_ref(tcx, trait_ref.ref_id).def_id)
4784 /// If the given def ID describes a method belonging to a trait (either a
4785 /// default method or an implementation of a trait method), return the ID of
4786 /// the trait that the method belongs to. Otherwise, return `None`.
4787 pub fn trait_of_method(tcx: ctxt, def_id: ast::DefId)
4788 -> Option<ast::DefId> {
4789 if def_id.crate != LOCAL_CRATE {
4790 return csearch::get_trait_of_method(tcx.cstore, def_id, tcx);
4794 let methods = tcx.methods.borrow();
4795 method = methods.get().find(&def_id).map(|method| *method);
4799 match method.container {
4800 TraitContainer(def_id) => Some(def_id),
4801 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
4808 /// If the given def ID describes a method belonging to a trait, (either a
4809 /// default method or an implementation of a trait method), return the ID of
4810 /// the method inside trait definition (this means that if the given def ID
4811 /// is already that of the original trait method, then the return value is
4813 /// Otherwise, return `None`.
4814 pub fn trait_method_of_method(tcx: ctxt,
4815 def_id: ast::DefId) -> Option<ast::DefId> {
4818 let methods = tcx.methods.borrow();
4819 match methods.get().find(&def_id) {
4820 Some(m) => method = *m,
4821 None => return None,
4824 let name = method.ident.name;
4825 match trait_of_method(tcx, def_id) {
4826 Some(trait_did) => {
4827 let trait_methods = ty::trait_methods(tcx, trait_did);
4828 trait_methods.iter()
4829 .position(|m| m.ident.name == name)
4830 .map(|idx| ty::trait_method(tcx, trait_did, idx).def_id)
4836 /// Creates a hash of the type `t` which will be the same no matter what crate
4837 /// context it's calculated within. This is used by the `type_id` intrinsic.
4838 pub fn hash_crate_independent(tcx: ctxt, t: t, local_hash: ~str) -> u64 {
4839 use std::hash::{SipState, Streaming};
4841 let mut hash = SipState::new(0, 0);
4842 let region = |_hash: &mut SipState, r: Region| {
4852 tcx.sess.bug("non-static region found when hashing a type")
4856 let vstore = |hash: &mut SipState, v: vstore| {
4858 vstore_fixed(_) => hash.input([0]),
4859 vstore_uniq => hash.input([1]),
4860 vstore_box => hash.input([2]),
4861 vstore_slice(r) => {
4867 let did = |hash: &mut SipState, did: DefId| {
4868 let h = if ast_util::is_local(did) {
4871 tcx.sess.cstore.get_crate_hash(did.crate)
4873 hash.input(h.as_bytes());
4874 iter(hash, &did.node);
4876 let mt = |hash: &mut SipState, mt: mt| {
4877 iter(hash, &mt.mutbl);
4879 fn iter<T: IterBytes>(hash: &mut SipState, t: &T) {
4880 t.iter_bytes(true, |bytes| { hash.input(bytes); true });
4882 ty::walk_ty(t, |t| {
4883 match ty::get(t).sty {
4884 ty_nil => hash.input([0]),
4885 ty_bot => hash.input([1]),
4886 ty_bool => hash.input([2]),
4887 ty_char => hash.input([3]),
4890 iter(&mut hash, &i);
4894 iter(&mut hash, &u);
4898 iter(&mut hash, &f);
4902 vstore(&mut hash, v);
4917 vstore(&mut hash, v);
4925 region(&mut hash, r);
4928 ty_bare_fn(ref b) => {
4930 iter(&mut hash, &b.purity);
4931 iter(&mut hash, &b.abis);
4933 ty_closure(ref c) => {
4935 iter(&mut hash, &c.purity);
4936 iter(&mut hash, &c.sigil);
4937 iter(&mut hash, &c.onceness);
4938 iter(&mut hash, &c.bounds);
4939 region(&mut hash, c.region);
4941 ty_trait(d, _, store, m, bounds) => {
4945 BoxTraitStore => hash.input([0]),
4946 UniqTraitStore => hash.input([1]),
4947 RegionTraitStore(r) => {
4949 region(&mut hash, r);
4952 iter(&mut hash, &m);
4953 iter(&mut hash, &bounds);
4955 ty_struct(d, _) => {
4959 ty_tup(ref inner) => {
4961 iter(&mut hash, &inner.len());
4965 iter(&mut hash, &p.idx);
4966 did(&mut hash, p.def_id);
4972 ty_infer(_) => unreachable!(),
4973 ty_err => hash.input([23]),
4974 ty_type => hash.input([24]),
4975 ty_unboxed_vec(m) => {
4986 pub fn to_str(self) -> &'static str {
4989 Contravariant => "-",
4996 pub fn construct_parameter_environment(
4998 self_bound: Option<@TraitRef>,
4999 item_type_params: &[TypeParameterDef],
5000 method_type_params: &[TypeParameterDef],
5001 item_region_params: &[RegionParameterDef],
5002 free_id: ast::NodeId)
5003 -> ParameterEnvironment
5005 /*! See `ParameterEnvironment` struct def'n for details */
5008 // Construct the free substs.
5012 let self_ty = self_bound.map(|t| ty::mk_self(tcx, t.def_id));
5015 let num_item_type_params = item_type_params.len();
5016 let num_method_type_params = method_type_params.len();
5017 let num_type_params = num_item_type_params + num_method_type_params;
5018 let type_params = vec::from_fn(num_type_params, |i| {
5019 let def_id = if i < num_item_type_params {
5020 item_type_params[i].def_id
5022 method_type_params[i - num_item_type_params].def_id
5025 ty::mk_param(tcx, i, def_id)
5028 // map bound 'a => free 'a
5029 let region_params = item_region_params.iter().
5030 map(|r| ty::ReFree(ty::FreeRegion {
5032 bound_region: ty::BrNamed(r.def_id, r.ident)})).
5035 let free_substs = substs {
5038 regions: ty::NonerasedRegions(region_params)
5042 // Compute the bounds on Self and the type parameters.
5045 let self_bound_substd = self_bound.map(|b| b.subst(tcx, &free_substs));
5046 let type_param_bounds_substd = vec::from_fn(num_type_params, |i| {
5047 if i < num_item_type_params {
5048 (*item_type_params[i].bounds).subst(tcx, &free_substs)
5050 let j = i - num_item_type_params;
5051 (*method_type_params[j].bounds).subst(tcx, &free_substs)
5055 ty::ParameterEnvironment {
5056 free_substs: free_substs,
5057 self_param_bound: self_bound_substd,
5058 type_param_bounds: type_param_bounds_substd,
5063 pub fn empty() -> substs {
5067 regions: NonerasedRegions(opt_vec::Empty)