1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #[allow(non_camel_case_types)];
15 use metadata::csearch;
17 use middle::const_eval;
18 use middle::lang_items::{ExchangeHeapLangItem, OpaqueStructLangItem};
19 use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem};
22 use middle::resolve_lifetime;
24 use middle::subst::Subst;
27 use middle::ty_fold::TypeFolder;
29 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_str};
30 use util::ppaux::{trait_store_to_str, ty_to_str, vstore_to_str};
31 use util::ppaux::{Repr, UserString};
32 use util::common::{indenter};
35 use std::cell::{Cell, RefCell};
39 use std::hash::{Hash, sip};
43 use collections::{HashMap, HashSet};
45 use syntax::ast_util::{is_local, lit_is_str};
48 use syntax::attr::AttrMetaMethods;
49 use syntax::codemap::Span;
50 use syntax::parse::token;
51 use syntax::parse::token::InternedString;
52 use syntax::{ast, ast_map};
53 use syntax::opt_vec::OptVec;
55 use syntax::abi::AbiSet;
57 use collections::enum_set::{EnumSet, CLike};
61 pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0;
72 pub enum MethodContainer {
73 TraitContainer(ast::DefId),
74 ImplContainer(ast::DefId),
80 generics: ty::Generics,
82 explicit_self: ast::ExplicitSelf_,
85 container: MethodContainer,
87 // If this method is provided, we need to know where it came from
88 provided_source: Option<ast::DefId>
92 pub fn new(ident: ast::Ident,
93 generics: ty::Generics,
95 explicit_self: ast::ExplicitSelf_,
98 container: MethodContainer,
99 provided_source: Option<ast::DefId>)
105 explicit_self: explicit_self,
108 container: container,
109 provided_source: provided_source
113 pub fn container_id(&self) -> ast::DefId {
114 match self.container {
115 TraitContainer(id) => id,
116 ImplContainer(id) => id,
127 #[deriving(Clone, Eq, Hash)]
130 mutbl: ast::Mutability,
133 #[deriving(Clone, Eq, Encodable, Decodable, Hash, Show)]
140 #[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)]
141 pub enum TraitStore {
142 UniqTraitStore, // ~Trait
143 RegionTraitStore(Region), // &Trait
146 pub struct field_ty {
149 vis: ast::Visibility,
152 // Contains information needed to resolve types and (in the future) look up
153 // the types of AST nodes.
154 #[deriving(Eq, Hash)]
155 pub struct creader_cache_key {
161 type creader_cache = RefCell<HashMap<creader_cache_key, t>>;
167 // NB: Do not replace this with #[deriving(Eq)]. The automatically-derived
168 // implementation will not recurse through sty and you will get stack
170 impl cmp::Eq for intern_key {
171 fn eq(&self, other: &intern_key) -> bool {
173 *self.sty == *other.sty
176 fn ne(&self, other: &intern_key) -> bool {
181 impl Hash for intern_key {
182 fn hash(&self, s: &mut sip::SipState) {
189 pub enum ast_ty_to_ty_cache_entry {
190 atttce_unresolved, /* not resolved yet */
191 atttce_resolved(t) /* resolved to a type, irrespective of region */
194 #[deriving(Clone, Eq, Decodable, Encodable)]
195 pub struct ItemVariances {
196 self_param: Option<Variance>,
197 type_params: OptVec<Variance>,
198 region_params: OptVec<Variance>
201 #[deriving(Clone, Eq, Decodable, Encodable, Show)]
203 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
204 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
205 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
206 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
209 pub enum AutoAdjustment {
210 AutoAddEnv(ty::Region, ast::Sigil),
211 AutoDerefRef(AutoDerefRef),
212 AutoObject(ast::Sigil, Option<ty::Region>,
215 ast::DefId, /* Trait ID */
216 ty::substs /* Trait substitutions */)
219 #[deriving(Decodable, Encodable)]
220 pub struct AutoDerefRef {
222 autoref: Option<AutoRef>
225 #[deriving(Decodable, Encodable)]
227 /// Convert from T to &T
228 AutoPtr(Region, ast::Mutability),
230 /// Convert from ~[]/&[] to &[] (or str)
231 AutoBorrowVec(Region, ast::Mutability),
233 /// Convert from ~[]/&[] to &&[] (or str)
234 AutoBorrowVecRef(Region, ast::Mutability),
236 /// Convert from @fn()/~fn()/|| to ||
237 AutoBorrowFn(Region),
239 /// Convert from T to *T
240 AutoUnsafe(ast::Mutability),
242 /// Convert from ~Trait/&Trait to &Trait
243 AutoBorrowObj(Region, ast::Mutability),
246 pub type ctxt = @ctxt_;
248 /// The data structure to keep track of all the information that typechecker
249 /// generates so that so that it can be reused and doesn't have to be redone
252 diag: @syntax::diagnostic::SpanHandler,
253 interner: RefCell<HashMap<intern_key, ~t_box_>>,
255 cstore: @metadata::cstore::CStore,
256 sess: session::Session,
257 def_map: resolve::DefMap,
259 named_region_map: @RefCell<resolve_lifetime::NamedRegionMap>,
261 region_maps: middle::region::RegionMaps,
263 // Stores the types for various nodes in the AST. Note that this table
264 // is not guaranteed to be populated until after typeck. See
265 // typeck::check::fn_ctxt for details.
266 node_types: node_type_table,
268 // Stores the type parameters which were substituted to obtain the type
269 // of this node. This only applies to nodes that refer to entities
270 // parameterized by type parameters, such as generic fns, types, or
272 node_type_substs: RefCell<HashMap<NodeId, ~[t]>>,
274 // Maps from a method to the method "descriptor"
275 methods: RefCell<HashMap<DefId, @Method>>,
277 // Maps from a trait def-id to a list of the def-ids of its methods
278 trait_method_def_ids: RefCell<HashMap<DefId, @~[DefId]>>,
280 // A cache for the trait_methods() routine
281 trait_methods_cache: RefCell<HashMap<DefId, @~[@Method]>>,
283 impl_trait_cache: RefCell<HashMap<ast::DefId, Option<@ty::TraitRef>>>,
285 trait_refs: RefCell<HashMap<NodeId, @TraitRef>>,
286 trait_defs: RefCell<HashMap<DefId, @TraitDef>>,
289 intrinsic_defs: RefCell<HashMap<ast::DefId, t>>,
290 freevars: RefCell<freevars::freevar_map>,
292 rcache: creader_cache,
293 short_names_cache: RefCell<HashMap<t, ~str>>,
294 needs_unwind_cleanup_cache: RefCell<HashMap<t, bool>>,
295 tc_cache: RefCell<HashMap<uint, TypeContents>>,
296 ast_ty_to_ty_cache: RefCell<HashMap<NodeId, ast_ty_to_ty_cache_entry>>,
297 enum_var_cache: RefCell<HashMap<DefId, @~[@VariantInfo]>>,
298 ty_param_defs: RefCell<HashMap<ast::NodeId, TypeParameterDef>>,
299 adjustments: RefCell<HashMap<ast::NodeId, @AutoAdjustment>>,
300 normalized_cache: RefCell<HashMap<t, t>>,
301 lang_items: @middle::lang_items::LanguageItems,
302 // A mapping of fake provided method def_ids to the default implementation
303 provided_method_sources: RefCell<HashMap<ast::DefId, ast::DefId>>,
304 supertraits: RefCell<HashMap<ast::DefId, @~[@TraitRef]>>,
306 // Maps from def-id of a type or region parameter to its
307 // (inferred) variance.
308 item_variance_map: RefCell<HashMap<ast::DefId, @ItemVariances>>,
310 // A mapping from the def ID of an enum or struct type to the def ID
311 // of the method that implements its destructor. If the type is not
312 // present in this map, it does not have a destructor. This map is
313 // populated during the coherence phase of typechecking.
314 destructor_for_type: RefCell<HashMap<ast::DefId, ast::DefId>>,
316 // A method will be in this list if and only if it is a destructor.
317 destructors: RefCell<HashSet<ast::DefId>>,
319 // Maps a trait onto a list of impls of that trait.
320 trait_impls: RefCell<HashMap<ast::DefId, @RefCell<~[@Impl]>>>,
322 // Maps a def_id of a type to a list of its inherent impls.
323 // Contains implementations of methods that are inherent to a type.
324 // Methods in these implementations don't need to be exported.
325 inherent_impls: RefCell<HashMap<ast::DefId, @RefCell<~[@Impl]>>>,
327 // Maps a def_id of an impl to an Impl structure.
328 // Note that this contains all of the impls that we know about,
329 // including ones in other crates. It's not clear that this is the best
331 impls: RefCell<HashMap<ast::DefId, @Impl>>,
333 // Set of used unsafe nodes (functions or blocks). Unsafe nodes not
334 // present in this set can be warned about.
335 used_unsafe: RefCell<HashSet<ast::NodeId>>,
337 // Set of nodes which mark locals as mutable which end up getting used at
338 // some point. Local variable definitions not in this set can be warned
340 used_mut_nodes: RefCell<HashSet<ast::NodeId>>,
342 // vtable resolution information for impl declarations
343 impl_vtables: typeck::impl_vtable_map,
345 // The set of external nominal types whose implementations have been read.
346 // This is used for lazy resolution of methods.
347 populated_external_types: RefCell<HashSet<ast::DefId>>,
349 // The set of external traits whose implementations have been read. This
350 // is used for lazy resolution of traits.
351 populated_external_traits: RefCell<HashSet<ast::DefId>>,
354 upvar_borrow_map: RefCell<UpvarBorrowMap>,
356 // These two caches are used by const_eval when decoding external statics
357 // and variants that are found.
358 extern_const_statics: RefCell<HashMap<ast::DefId, Option<@ast::Expr>>>,
359 extern_const_variants: RefCell<HashMap<ast::DefId, Option<@ast::Expr>>>,
370 // a meta-flag: subst may be required if the type has parameters, a self
371 // type, or references bound regions
372 needs_subst = 1 | 2 | 8
375 pub type t_box = &'static t_box_;
383 // To reduce refcounting cost, we're representing types as unsafe pointers
384 // throughout the compiler. These are simply casted t_box values. Use ty::get
385 // to cast them back to a box. (Without the cast, compiler performance suffers
386 // ~15%.) This does mean that a t value relies on the ctxt to keep its box
387 // alive, and using ty::get is unsafe when the ctxt is no longer alive.
390 #[deriving(Clone, Eq, Hash)]
391 pub struct t { priv inner: *t_opaque }
393 impl fmt::Show for t {
394 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
395 f.buf.write_str("*t_opaque")
399 pub fn get(t: t) -> t_box {
401 let t2: t_box = cast::transmute(t);
406 pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
407 (tb.flags & (flag as uint)) != 0u
409 pub fn type_has_params(t: t) -> bool {
410 tbox_has_flag(get(t), has_params)
412 pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
413 pub fn type_needs_infer(t: t) -> bool {
414 tbox_has_flag(get(t), needs_infer)
416 pub fn type_has_regions(t: t) -> bool {
417 tbox_has_flag(get(t), has_regions)
419 pub fn type_id(t: t) -> uint { get(t).id }
421 #[deriving(Clone, Eq, Hash)]
422 pub struct BareFnTy {
428 #[deriving(Clone, Eq, Hash)]
429 pub struct ClosureTy {
432 onceness: ast::Onceness,
434 bounds: BuiltinBounds,
439 * Signature of a function type, which I have arbitrarily
440 * decided to use to refer to the input/output types.
442 * - `binder_id` is the node id where this fn type appeared;
443 * it is used to identify all the bound regions appearing
444 * in the input/output types that are bound by this fn type
445 * (vs some enclosing or enclosed fn type)
446 * - `inputs` is the list of arguments and their modes.
447 * - `output` is the return type.
448 * - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
450 #[deriving(Clone, Eq, Hash)]
452 binder_id: ast::NodeId,
458 #[deriving(Clone, Eq, Hash)]
459 pub struct param_ty {
464 /// Representation of regions:
465 #[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)]
467 // Region bound in a type or fn declaration which will be
468 // substituted 'early' -- that is, at the same time when type
469 // parameters are substituted.
470 ReEarlyBound(/* param id */ ast::NodeId, /*index*/ uint, ast::Name),
472 // Region bound in a function scope, which will be substituted when the
473 // function is called. The first argument must be the `binder_id` of
474 // some enclosing function signature.
475 ReLateBound(/* binder_id */ ast::NodeId, BoundRegion),
477 /// When checking a function body, the types of all arguments and so forth
478 /// that refer to bound region parameters are modified to refer to free
479 /// region parameters.
482 /// A concrete region naming some expression within the current function.
485 /// Static data that has an "infinite" lifetime. Top in the region lattice.
488 /// A region variable. Should not exist after typeck.
489 ReInfer(InferRegion),
491 /// Empty lifetime is for data that is never accessed.
492 /// Bottom in the region lattice. We treat ReEmpty somewhat
493 /// specially; at least right now, we do not generate instances of
494 /// it during the GLB computations, but rather
495 /// generate an error instead. This is to improve error messages.
496 /// The only way to get an instance of ReEmpty is to have a region
497 /// variable with no constraints.
502 * Upvars do not get their own node-id. Instead, we use the pair of
503 * the original var id (that is, the root variable that is referenced
504 * by the upvar) and the id of the closure expression.
506 #[deriving(Clone, Eq, Hash)]
509 closure_expr_id: ast::NodeId,
512 #[deriving(Clone, Eq, Hash)]
513 pub enum BorrowKind {
514 /// Data must be immutable and is aliasable.
517 /// Data must be immutable but not aliasable. This kind of borrow
518 /// cannot currently be expressed by the user and is used only in
519 /// implicit closure bindings. It is needed when you the closure
520 /// is borrowing or mutating a mutable referent, e.g.:
522 /// let x: &mut int = ...;
523 /// let y = || *x += 5;
525 /// If we were to try to translate this closure into a more explicit
526 /// form, we'd encounter an error with the code as written:
528 /// struct Env { x: & &mut int }
529 /// let x: &mut int = ...;
530 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
531 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
533 /// This is then illegal because you cannot mutate a `&mut` found
534 /// in an aliasable location. To solve, you'd have to translate with
535 /// an `&mut` borrow:
537 /// struct Env { x: & &mut int }
538 /// let x: &mut int = ...;
539 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
540 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
542 /// Now the assignment to `**env.x` is legal, but creating a
543 /// mutable pointer to `x` is not because `x` is not mutable. We
544 /// could fix this by declaring `x` as `let mut x`. This is ok in
545 /// user code, if awkward, but extra weird for closures, since the
546 /// borrow is hidden.
548 /// So we introduce a "unique imm" borrow -- the referent is
549 /// immutable, but not aliasable. This solves the problem. For
550 /// simplicity, we don't give users the way to express this
551 /// borrow, it's just used when translating closures.
554 /// Data is mutable and not aliasable.
559 * Information describing the borrowing of an upvar. This is computed
560 * during `typeck`, specifically by `regionck`. The general idea is
561 * that the compiler analyses treat closures like:
563 * let closure: &'e fn() = || {
564 * x = 1; // upvar x is assigned to
565 * use(y); // upvar y is read
566 * foo(&z); // upvar z is borrowed immutably
569 * as if they were "desugared" to something loosely like:
571 * struct Vars<'x,'y,'z> { x: &'x mut int,
574 * let closure: &'e fn() = {
580 * let env: &'e mut Vars<'x,'y,'z> = &mut Vars { x: &'x mut x,
586 * This is basically what happens at runtime. The closure is basically
587 * an existentially quantified version of the `(env, f)` pair.
589 * This data structure indicates the region and mutability of a single
590 * one of the `x...z` borrows.
592 * It may not be obvious why each borrowed variable gets its own
593 * lifetime (in the desugared version of the example, these are indicated
594 * by the lifetime parameters `'x`, `'y`, and `'z` in the `Vars` definition).
595 * Each such lifetime must encompass the lifetime `'e` of the closure itself,
596 * but need not be identical to it. The reason that this makes sense:
598 * - Callers are only permitted to invoke the closure, and hence to
599 * use the pointers, within the lifetime `'e`, so clearly `'e` must
600 * be a sublifetime of `'x...'z`.
601 * - The closure creator knows which upvars were borrowed by the closure
602 * and thus `x...z` will be reserved for `'x...'z` respectively.
603 * - Through mutation, the borrowed upvars can actually escape the
604 * the closure, so sometimes it is necessary for them to be larger
605 * than the closure lifetime itself.
607 #[deriving(Eq, Clone)]
608 pub struct UpvarBorrow {
613 pub type UpvarBorrowMap = HashMap<UpvarId, UpvarBorrow>;
616 pub fn is_bound(&self) -> bool {
618 &ty::ReEarlyBound(..) => true,
619 &ty::ReLateBound(..) => true,
625 #[deriving(Clone, Eq, TotalOrd, TotalEq, Hash, Encodable, Decodable, Show)]
626 pub struct FreeRegion {
628 bound_region: BoundRegion
631 #[deriving(Clone, Eq, TotalEq, TotalOrd, Hash, Encodable, Decodable, Show)]
632 pub enum BoundRegion {
633 /// An anonymous region parameter for a given fn (&T)
636 /// Named region parameters for functions (a in &'a T)
638 /// The def-id is needed to distinguish free regions in
639 /// the event of shadowing.
640 BrNamed(ast::DefId, ast::Name),
642 /// Fresh bound identifiers created during GLB computations.
647 * Represents the values to use when substituting lifetime parameters.
648 * If the value is `ErasedRegions`, then this subst is occurring during
649 * trans, and all region parameters will be replaced with `ty::ReStatic`. */
650 #[deriving(Clone, Eq, Hash)]
651 pub enum RegionSubsts {
653 NonerasedRegions(OptVec<ty::Region>)
657 * The type substs represents the kinds of things that can be substituted to
658 * convert a polytype into a monotype. Note however that substituting bound
659 * regions other than `self` is done through a different mechanism:
661 * - `tps` represents the type parameters in scope. They are indexed
662 * according to the order in which they were declared.
664 * - `self_r` indicates the region parameter `self` that is present on nominal
665 * types (enums, structs) declared as having a region parameter. `self_r`
666 * should always be none for types that are not region-parameterized and
667 * Some(_) for types that are. The only bound region parameter that should
668 * appear within a region-parameterized type is `self`.
670 * - `self_ty` is the type to which `self` should be remapped, if any. The
671 * `self` type is rather funny in that it can only appear on traits and is
672 * always substituted away to the implementing type for a trait. */
673 #[deriving(Clone, Eq, Hash)]
675 self_ty: Option<ty::t>,
677 regions: RegionSubsts,
685 macro_rules! def_prim_ty(
686 ($name:ident, $sty:expr, $id:expr) => (
687 pub static $name: t_box_ = t_box_ {
695 def_prim_ty!(TY_NIL, super::ty_nil, 0)
696 def_prim_ty!(TY_BOOL, super::ty_bool, 1)
697 def_prim_ty!(TY_CHAR, super::ty_char, 2)
698 def_prim_ty!(TY_INT, super::ty_int(ast::TyI), 3)
699 def_prim_ty!(TY_I8, super::ty_int(ast::TyI8), 4)
700 def_prim_ty!(TY_I16, super::ty_int(ast::TyI16), 5)
701 def_prim_ty!(TY_I32, super::ty_int(ast::TyI32), 6)
702 def_prim_ty!(TY_I64, super::ty_int(ast::TyI64), 7)
703 def_prim_ty!(TY_UINT, super::ty_uint(ast::TyU), 8)
704 def_prim_ty!(TY_U8, super::ty_uint(ast::TyU8), 9)
705 def_prim_ty!(TY_U16, super::ty_uint(ast::TyU16), 10)
706 def_prim_ty!(TY_U32, super::ty_uint(ast::TyU32), 11)
707 def_prim_ty!(TY_U64, super::ty_uint(ast::TyU64), 12)
708 def_prim_ty!(TY_F32, super::ty_float(ast::TyF32), 14)
709 def_prim_ty!(TY_F64, super::ty_float(ast::TyF64), 15)
711 pub static TY_BOT: t_box_ = t_box_ {
714 flags: super::has_ty_bot as uint,
717 pub static TY_ERR: t_box_ = t_box_ {
720 flags: super::has_ty_err as uint,
723 pub static LAST_PRIMITIVE_ID: uint = 18;
726 // NB: If you change this, you'll probably want to change the corresponding
727 // AST structure in libsyntax/ast.rs as well.
728 #[deriving(Clone, Eq, Hash)]
735 ty_uint(ast::UintTy),
736 ty_float(ast::FloatTy),
738 ty_enum(DefId, substs),
744 ty_bare_fn(BareFnTy),
745 ty_closure(ClosureTy),
746 ty_trait(DefId, substs, TraitStore, ast::Mutability, BuiltinBounds),
747 ty_struct(DefId, substs),
750 ty_param(param_ty), // type parameter
751 ty_self(DefId), /* special, implicit `self` type parameter;
752 * def_id is the id of the trait */
754 ty_infer(InferTy), // something used only during inference/typeck
755 ty_err, // Also only used during inference/typeck, to represent
756 // the type of an erroneous expression (helps cut down
757 // on non-useful type error messages)
759 // "Fake" types, used for trans purposes
763 #[deriving(Eq, Hash)]
764 pub struct TraitRef {
769 #[deriving(Clone, Eq)]
770 pub enum IntVarValue {
772 UintType(ast::UintTy),
775 #[deriving(Clone, Show)]
776 pub enum terr_vstore_kind {
783 #[deriving(Clone, Show)]
784 pub struct expected_found<T> {
789 // Data structures used in type unification
790 #[deriving(Clone, Show)]
793 terr_purity_mismatch(expected_found<Purity>),
794 terr_onceness_mismatch(expected_found<Onceness>),
795 terr_abi_mismatch(expected_found<AbiSet>),
797 terr_sigil_mismatch(expected_found<ast::Sigil>),
802 terr_tuple_size(expected_found<uint>),
803 terr_ty_param_size(expected_found<uint>),
804 terr_record_size(expected_found<uint>),
805 terr_record_mutability,
806 terr_record_fields(expected_found<Ident>),
808 terr_regions_does_not_outlive(Region, Region),
809 terr_regions_not_same(Region, Region),
810 terr_regions_no_overlap(Region, Region),
811 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
812 terr_regions_overly_polymorphic(BoundRegion, Region),
813 terr_vstores_differ(terr_vstore_kind, expected_found<vstore>),
814 terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
815 terr_in_field(@type_err, ast::Ident),
816 terr_sorts(expected_found<t>),
817 terr_integer_as_char,
818 terr_int_mismatch(expected_found<IntVarValue>),
819 terr_float_mismatch(expected_found<ast::FloatTy>),
820 terr_traits(expected_found<ast::DefId>),
821 terr_builtin_bounds(expected_found<BuiltinBounds>),
822 terr_variadic_mismatch(expected_found<bool>)
825 #[deriving(Eq, Hash)]
826 pub struct ParamBounds {
827 builtin_bounds: BuiltinBounds,
828 trait_bounds: ~[@TraitRef]
831 pub type BuiltinBounds = EnumSet<BuiltinBound>;
833 #[deriving(Clone, Encodable, Eq, Decodable, Hash, Show)]
835 pub enum BuiltinBound {
843 pub fn EmptyBuiltinBounds() -> BuiltinBounds {
847 pub fn AllBuiltinBounds() -> BuiltinBounds {
848 let mut set = EnumSet::empty();
849 set.add(BoundStatic);
851 set.add(BoundFreeze);
856 impl CLike for BuiltinBound {
857 fn to_uint(&self) -> uint {
860 fn from_uint(v: uint) -> BuiltinBound {
861 unsafe { cast::transmute(v) }
865 #[deriving(Clone, Eq, Hash)]
866 pub struct TyVid(uint);
868 #[deriving(Clone, Eq, Hash)]
869 pub struct IntVid(uint);
871 #[deriving(Clone, Eq, Hash)]
872 pub struct FloatVid(uint);
874 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
875 pub struct RegionVid {
879 #[deriving(Clone, Eq, Hash)]
886 #[deriving(Clone, Encodable, Decodable, Hash, Show)]
887 pub enum InferRegion {
889 ReSkolemized(uint, BoundRegion)
892 impl cmp::Eq for InferRegion {
893 fn eq(&self, other: &InferRegion) -> bool {
894 match ((*self), *other) {
895 (ReVar(rva), ReVar(rvb)) => {
898 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
904 fn ne(&self, other: &InferRegion) -> bool {
905 !((*self) == (*other))
910 fn to_uint(&self) -> uint;
914 fn to_uint(&self) -> uint { let TyVid(v) = *self; v }
917 impl fmt::Show for TyVid {
918 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
919 write!(f.buf, "<generic \\#{}>", self.to_uint())
923 impl Vid for IntVid {
924 fn to_uint(&self) -> uint { let IntVid(v) = *self; v }
927 impl fmt::Show for IntVid {
928 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
929 write!(f.buf, "<generic integer \\#{}>", self.to_uint())
933 impl Vid for FloatVid {
934 fn to_uint(&self) -> uint { let FloatVid(v) = *self; v }
937 impl fmt::Show for FloatVid {
938 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
939 write!(f.buf, "<generic float \\#{}>", self.to_uint())
943 impl Vid for RegionVid {
944 fn to_uint(&self) -> uint { self.id }
947 impl fmt::Show for RegionVid {
948 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
953 impl fmt::Show for FnSig {
954 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
955 // grr, without tcx not much we can do.
956 write!(f.buf, "(...)")
960 impl fmt::Show for InferTy {
961 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
963 TyVar(ref v) => v.fmt(f),
964 IntVar(ref v) => v.fmt(f),
965 FloatVar(ref v) => v.fmt(f),
970 impl fmt::Show for IntVarValue {
971 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
973 IntType(ref v) => v.fmt(f),
974 UintType(ref v) => v.fmt(f),
980 pub struct TypeParameterDef {
983 bounds: @ParamBounds,
984 default: Option<ty::t>
987 #[deriving(Encodable, Decodable, Clone)]
988 pub struct RegionParameterDef {
993 /// Information about the type/lifetime parameters associated with an item.
994 /// Analogous to ast::Generics.
996 pub struct Generics {
997 /// List of type parameters declared on the item.
998 type_param_defs: Rc<~[TypeParameterDef]>,
1000 /// List of region parameters declared on the item.
1001 region_param_defs: Rc<~[RegionParameterDef]>,
1005 pub fn has_type_params(&self) -> bool {
1006 !self.type_param_defs.borrow().is_empty()
1008 pub fn type_param_defs<'a>(&'a self) -> &'a [TypeParameterDef] {
1009 self.type_param_defs.borrow().as_slice()
1011 pub fn region_param_defs<'a>(&'a self) -> &'a [RegionParameterDef] {
1012 self.region_param_defs.borrow().as_slice()
1016 /// When type checking, we use the `ParameterEnvironment` to track
1017 /// details about the type/lifetime parameters that are in scope.
1018 /// It primarily stores the bounds information.
1020 /// Note: This information might seem to be redundant with the data in
1021 /// `tcx.ty_param_defs`, but it is not. That table contains the
1022 /// parameter definitions from an "outside" perspective, but this
1023 /// struct will contain the bounds for a parameter as seen from inside
1024 /// the function body. Currently the only real distinction is that
1025 /// bound lifetime parameters are replaced with free ones, but in the
1026 /// future I hope to refine the representation of types so as to make
1027 /// more distinctions clearer.
1028 pub struct ParameterEnvironment {
1029 /// A substitution that can be applied to move from
1030 /// the "outer" view of a type or method to the "inner" view.
1031 /// In general, this means converting from bound parameters to
1032 /// free parameters. Since we currently represent bound/free type
1033 /// parameters in the same way, this only has an affect on regions.
1034 free_substs: ty::substs,
1036 /// Bound on the Self parameter
1037 self_param_bound: Option<@TraitRef>,
1039 /// Bounds on each numbered type parameter
1040 type_param_bounds: ~[ParamBounds],
1045 /// - `bounds`: The list of bounds for each type parameter. The length of the
1046 /// list also tells you how many type parameters there are.
1048 /// - `rp`: true if the type is region-parameterized. Types can have at
1049 /// most one region parameter, always called `&self`.
1051 /// - `ty`: the base type. May have reference to the (unsubstituted) bound
1052 /// region `&self` or to (unsubstituted) ty_param types
1054 pub struct ty_param_bounds_and_ty {
1059 /// As `ty_param_bounds_and_ty` but for a trait ref.
1060 pub struct TraitDef {
1062 bounds: BuiltinBounds,
1063 trait_ref: @ty::TraitRef,
1066 pub struct ty_param_substs_and_ty {
1071 type type_cache = RefCell<HashMap<ast::DefId, ty_param_bounds_and_ty>>;
1073 pub type node_type_table = RefCell<HashMap<uint,t>>;
1075 pub fn mk_ctxt(s: session::Session,
1076 dm: resolve::DefMap,
1077 named_region_map: @RefCell<resolve_lifetime::NamedRegionMap>,
1079 freevars: freevars::freevar_map,
1080 region_maps: middle::region::RegionMaps,
1081 lang_items: @middle::lang_items::LanguageItems)
1085 named_region_map: named_region_map,
1086 item_variance_map: RefCell::new(HashMap::new()),
1087 diag: s.diagnostic(),
1088 interner: RefCell::new(HashMap::new()),
1089 next_id: Cell::new(primitives::LAST_PRIMITIVE_ID),
1093 region_maps: region_maps,
1094 node_types: RefCell::new(HashMap::new()),
1095 node_type_substs: RefCell::new(HashMap::new()),
1096 trait_refs: RefCell::new(HashMap::new()),
1097 trait_defs: RefCell::new(HashMap::new()),
1099 intrinsic_defs: RefCell::new(HashMap::new()),
1100 freevars: RefCell::new(freevars),
1101 tcache: RefCell::new(HashMap::new()),
1102 rcache: RefCell::new(HashMap::new()),
1103 short_names_cache: RefCell::new(HashMap::new()),
1104 needs_unwind_cleanup_cache: RefCell::new(HashMap::new()),
1105 tc_cache: RefCell::new(HashMap::new()),
1106 ast_ty_to_ty_cache: RefCell::new(HashMap::new()),
1107 enum_var_cache: RefCell::new(HashMap::new()),
1108 methods: RefCell::new(HashMap::new()),
1109 trait_method_def_ids: RefCell::new(HashMap::new()),
1110 trait_methods_cache: RefCell::new(HashMap::new()),
1111 impl_trait_cache: RefCell::new(HashMap::new()),
1112 ty_param_defs: RefCell::new(HashMap::new()),
1113 adjustments: RefCell::new(HashMap::new()),
1114 normalized_cache: RefCell::new(HashMap::new()),
1115 lang_items: lang_items,
1116 provided_method_sources: RefCell::new(HashMap::new()),
1117 supertraits: RefCell::new(HashMap::new()),
1118 destructor_for_type: RefCell::new(HashMap::new()),
1119 destructors: RefCell::new(HashSet::new()),
1120 trait_impls: RefCell::new(HashMap::new()),
1121 inherent_impls: RefCell::new(HashMap::new()),
1122 impls: RefCell::new(HashMap::new()),
1123 used_unsafe: RefCell::new(HashSet::new()),
1124 used_mut_nodes: RefCell::new(HashSet::new()),
1125 impl_vtables: RefCell::new(HashMap::new()),
1126 populated_external_types: RefCell::new(HashSet::new()),
1127 populated_external_traits: RefCell::new(HashSet::new()),
1128 upvar_borrow_map: RefCell::new(HashMap::new()),
1129 extern_const_statics: RefCell::new(HashMap::new()),
1130 extern_const_variants: RefCell::new(HashMap::new()),
1134 // Type constructors
1136 // Interns a type/name combination, stores the resulting box in cx.interner,
1137 // and returns the box as cast to an unsafe ptr (see comments for t above).
1138 pub fn mk_t(cx: ctxt, st: sty) -> t {
1139 // Check for primitive types.
1141 ty_nil => return mk_nil(),
1142 ty_err => return mk_err(),
1143 ty_bool => return mk_bool(),
1144 ty_int(i) => return mk_mach_int(i),
1145 ty_uint(u) => return mk_mach_uint(u),
1146 ty_float(f) => return mk_mach_float(f),
1147 ty_char => return mk_char(),
1148 ty_bot => return mk_bot(),
1152 let key = intern_key { sty: &st };
1155 let mut interner = cx.interner.borrow_mut();
1156 match interner.get().find(&key) {
1157 Some(t) => unsafe { return cast::transmute(&t.sty); },
1163 fn rflags(r: Region) -> uint {
1164 (has_regions as uint) | {
1166 ty::ReInfer(_) => needs_infer as uint,
1171 fn sflags(substs: &substs) -> uint {
1173 for tt in substs.tps.iter() { f |= get(*tt).flags; }
1174 match substs.regions {
1176 NonerasedRegions(ref regions) => {
1177 for r in regions.iter() {
1185 &ty_str(vstore_slice(r)) => {
1188 &ty_vec(ref mt, vstore_slice(r)) => {
1190 flags |= get(mt.ty).flags;
1192 &ty_nil | &ty_bool | &ty_char | &ty_int(_) | &ty_float(_) | &ty_uint(_) |
1194 // You might think that we could just return ty_err for
1195 // any type containing ty_err as a component, and get
1196 // rid of the has_ty_err flag -- likewise for ty_bot (with
1197 // the exception of function types that return bot).
1198 // But doing so caused sporadic memory corruption, and
1199 // neither I (tjc) nor nmatsakis could figure out why,
1200 // so we're doing it this way.
1201 &ty_bot => flags |= has_ty_bot as uint,
1202 &ty_err => flags |= has_ty_err as uint,
1203 &ty_param(_) => flags |= has_params as uint,
1204 &ty_infer(_) => flags |= needs_infer as uint,
1205 &ty_self(_) => flags |= has_self as uint,
1206 &ty_enum(_, ref substs) | &ty_struct(_, ref substs) |
1207 &ty_trait(_, ref substs, _, _, _) => {
1208 flags |= sflags(substs);
1210 ty_trait(_, _, RegionTraitStore(r), _, _) => {
1216 &ty_box(tt) | &ty_uniq(tt) => {
1217 flags |= get(tt).flags
1219 &ty_vec(ref m, _) | &ty_ptr(ref m) |
1220 &ty_unboxed_vec(ref m) => {
1221 flags |= get(m.ty).flags;
1223 &ty_rptr(r, ref m) => {
1225 flags |= get(m.ty).flags;
1227 &ty_tup(ref ts) => for tt in ts.iter() { flags |= get(*tt).flags; },
1228 &ty_bare_fn(ref f) => {
1229 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1230 flags |= get(f.sig.output).flags;
1231 // T -> _|_ is *not* _|_ !
1232 flags &= !(has_ty_bot as uint);
1234 &ty_closure(ref f) => {
1235 flags |= rflags(f.region);
1236 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1237 flags |= get(f.sig.output).flags;
1238 // T -> _|_ is *not* _|_ !
1239 flags &= !(has_ty_bot as uint);
1245 id: cx.next_id.get(),
1249 let sty_ptr = &t.sty as *sty;
1251 let key = intern_key {
1255 let mut interner = cx.interner.borrow_mut();
1256 interner.get().insert(key, t);
1258 cx.next_id.set(cx.next_id.get() + 1);
1261 cast::transmute::<*sty, t>(sty_ptr)
1266 pub fn mk_prim_t(primitive: &'static t_box_) -> t {
1268 cast::transmute::<&'static t_box_, t>(primitive)
1273 pub fn mk_nil() -> t { mk_prim_t(&primitives::TY_NIL) }
1276 pub fn mk_err() -> t { mk_prim_t(&primitives::TY_ERR) }
1279 pub fn mk_bot() -> t { mk_prim_t(&primitives::TY_BOT) }
1282 pub fn mk_bool() -> t { mk_prim_t(&primitives::TY_BOOL) }
1285 pub fn mk_int() -> t { mk_prim_t(&primitives::TY_INT) }
1288 pub fn mk_i8() -> t { mk_prim_t(&primitives::TY_I8) }
1291 pub fn mk_i16() -> t { mk_prim_t(&primitives::TY_I16) }
1294 pub fn mk_i32() -> t { mk_prim_t(&primitives::TY_I32) }
1297 pub fn mk_i64() -> t { mk_prim_t(&primitives::TY_I64) }
1300 pub fn mk_f32() -> t { mk_prim_t(&primitives::TY_F32) }
1303 pub fn mk_f64() -> t { mk_prim_t(&primitives::TY_F64) }
1306 pub fn mk_uint() -> t { mk_prim_t(&primitives::TY_UINT) }
1309 pub fn mk_u8() -> t { mk_prim_t(&primitives::TY_U8) }
1312 pub fn mk_u16() -> t { mk_prim_t(&primitives::TY_U16) }
1315 pub fn mk_u32() -> t { mk_prim_t(&primitives::TY_U32) }
1318 pub fn mk_u64() -> t { mk_prim_t(&primitives::TY_U64) }
1320 pub fn mk_mach_int(tm: ast::IntTy) -> t {
1322 ast::TyI => mk_int(),
1323 ast::TyI8 => mk_i8(),
1324 ast::TyI16 => mk_i16(),
1325 ast::TyI32 => mk_i32(),
1326 ast::TyI64 => mk_i64(),
1330 pub fn mk_mach_uint(tm: ast::UintTy) -> t {
1332 ast::TyU => mk_uint(),
1333 ast::TyU8 => mk_u8(),
1334 ast::TyU16 => mk_u16(),
1335 ast::TyU32 => mk_u32(),
1336 ast::TyU64 => mk_u64(),
1340 pub fn mk_mach_float(tm: ast::FloatTy) -> t {
1342 ast::TyF32 => mk_f32(),
1343 ast::TyF64 => mk_f64(),
1348 pub fn mk_char() -> t { mk_prim_t(&primitives::TY_CHAR) }
1350 pub fn mk_str(cx: ctxt, t: vstore) -> t {
1354 pub fn mk_enum(cx: ctxt, did: ast::DefId, substs: substs) -> t {
1355 // take a copy of substs so that we own the vectors inside
1356 mk_t(cx, ty_enum(did, substs))
1359 pub fn mk_box(cx: ctxt, ty: t) -> t { mk_t(cx, ty_box(ty)) }
1361 pub fn mk_uniq(cx: ctxt, ty: t) -> t { mk_t(cx, ty_uniq(ty)) }
1363 pub fn mk_ptr(cx: ctxt, tm: mt) -> t { mk_t(cx, ty_ptr(tm)) }
1365 pub fn mk_rptr(cx: ctxt, r: Region, tm: mt) -> t { mk_t(cx, ty_rptr(r, tm)) }
1367 pub fn mk_mut_rptr(cx: ctxt, r: Region, ty: t) -> t {
1368 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
1370 pub fn mk_imm_rptr(cx: ctxt, r: Region, ty: t) -> t {
1371 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
1374 pub fn mk_mut_ptr(cx: ctxt, ty: t) -> t {
1375 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
1378 pub fn mk_imm_ptr(cx: ctxt, ty: t) -> t {
1379 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
1382 pub fn mk_nil_ptr(cx: ctxt) -> t {
1383 mk_ptr(cx, mt {ty: mk_nil(), mutbl: ast::MutImmutable})
1386 pub fn mk_vec(cx: ctxt, tm: mt, t: vstore) -> t {
1387 mk_t(cx, ty_vec(tm, t))
1390 pub fn mk_unboxed_vec(cx: ctxt, tm: mt) -> t {
1391 mk_t(cx, ty_unboxed_vec(tm))
1393 pub fn mk_mut_unboxed_vec(cx: ctxt, ty: t) -> t {
1394 mk_t(cx, ty_unboxed_vec(mt {ty: ty, mutbl: ast::MutImmutable}))
1397 pub fn mk_tup(cx: ctxt, ts: ~[t]) -> t { mk_t(cx, ty_tup(ts)) }
1399 pub fn mk_closure(cx: ctxt, fty: ClosureTy) -> t {
1400 mk_t(cx, ty_closure(fty))
1403 pub fn mk_bare_fn(cx: ctxt, fty: BareFnTy) -> t {
1404 mk_t(cx, ty_bare_fn(fty))
1407 pub fn mk_ctor_fn(cx: ctxt,
1408 binder_id: ast::NodeId,
1409 input_tys: &[ty::t],
1410 output: ty::t) -> t {
1411 let input_args = input_tys.map(|t| *t);
1414 purity: ast::ImpureFn,
1415 abis: AbiSet::Rust(),
1417 binder_id: binder_id,
1426 pub fn mk_trait(cx: ctxt,
1430 mutability: ast::Mutability,
1431 bounds: BuiltinBounds)
1433 // take a copy of substs so that we own the vectors inside
1434 mk_t(cx, ty_trait(did, substs, store, mutability, bounds))
1437 pub fn mk_struct(cx: ctxt, struct_id: ast::DefId, substs: substs) -> t {
1438 // take a copy of substs so that we own the vectors inside
1439 mk_t(cx, ty_struct(struct_id, substs))
1442 pub fn mk_var(cx: ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) }
1444 pub fn mk_int_var(cx: ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) }
1446 pub fn mk_float_var(cx: ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) }
1448 pub fn mk_infer(cx: ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) }
1450 pub fn mk_self(cx: ctxt, did: ast::DefId) -> t { mk_t(cx, ty_self(did)) }
1452 pub fn mk_param(cx: ctxt, n: uint, k: DefId) -> t {
1453 mk_t(cx, ty_param(param_ty { idx: n, def_id: k }))
1456 pub fn walk_ty(ty: t, f: |t|) {
1457 maybe_walk_ty(ty, |t| { f(t); true });
1460 pub fn maybe_walk_ty(ty: t, f: |t| -> bool) {
1465 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) |
1466 ty_str(_) | ty_self(_) |
1467 ty_infer(_) | ty_param(_) | ty_err => {}
1468 ty_box(ty) | ty_uniq(ty) => maybe_walk_ty(ty, f),
1469 ty_vec(ref tm, _) | ty_unboxed_vec(ref tm) | ty_ptr(ref tm) |
1470 ty_rptr(_, ref tm) => {
1471 maybe_walk_ty(tm.ty, f);
1473 ty_enum(_, ref substs) | ty_struct(_, ref substs) |
1474 ty_trait(_, ref substs, _, _, _) => {
1475 for subty in (*substs).tps.iter() { maybe_walk_ty(*subty, |x| f(x)); }
1477 ty_tup(ref ts) => { for tt in ts.iter() { maybe_walk_ty(*tt, |x| f(x)); } }
1478 ty_bare_fn(ref ft) => {
1479 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1480 maybe_walk_ty(ft.sig.output, f);
1482 ty_closure(ref ft) => {
1483 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1484 maybe_walk_ty(ft.sig.output, f);
1489 // Folds types from the bottom up.
1490 pub fn fold_ty(cx: ctxt, t0: t, fldop: |t| -> t) -> t {
1491 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
1495 pub fn walk_regions_and_ty(cx: ctxt, ty: t, fldr: |r: Region|, fldt: |t: t|)
1497 ty_fold::RegionFolder::general(cx,
1499 |t| { fldt(t); t }).fold_ty(ty)
1502 pub fn fold_regions(cx: ctxt, ty: t, fldr: |r: Region| -> Region) -> t {
1503 ty_fold::RegionFolder::regions(cx, fldr).fold_ty(ty)
1506 // Substitute *only* type parameters. Used in trans where regions are erased.
1507 pub fn subst_tps(tcx: ctxt, tps: &[t], self_ty_opt: Option<t>, typ: t) -> t {
1508 let mut subst = TpsSubst { tcx: tcx, self_ty_opt: self_ty_opt, tps: tps };
1509 return subst.fold_ty(typ);
1511 struct TpsSubst<'a> {
1513 self_ty_opt: Option<t>,
1517 impl<'a> TypeFolder for TpsSubst<'a> {
1518 fn tcx(&self) -> ty::ctxt { self.tcx }
1520 fn fold_ty(&mut self, t: ty::t) -> ty::t {
1521 if self.tps.len() == 0u && self.self_ty_opt.is_none() {
1525 let tb = ty::get(t);
1526 if self.self_ty_opt.is_none() && !tbox_has_flag(tb, has_params) {
1530 match ty::get(t).sty {
1536 match self.self_ty_opt {
1537 None => self.tcx.sess.bug("ty_self unexpected here"),
1538 Some(self_ty) => self_ty
1543 ty_fold::super_fold_ty(self, t)
1550 pub fn substs_is_noop(substs: &substs) -> bool {
1551 let regions_is_noop = match substs.regions {
1552 ErasedRegions => false, // may be used to canonicalize
1553 NonerasedRegions(ref regions) => regions.is_empty()
1556 substs.tps.len() == 0u &&
1558 substs.self_ty.is_none()
1561 pub fn substs_to_str(cx: ctxt, substs: &substs) -> ~str {
1565 pub fn subst(cx: ctxt,
1569 typ.subst(cx, substs)
1574 pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil }
1576 pub fn type_is_bot(ty: t) -> bool {
1577 (get(ty).flags & (has_ty_bot as uint)) != 0
1580 pub fn type_is_error(ty: t) -> bool {
1581 (get(ty).flags & (has_ty_err as uint)) != 0
1584 pub fn type_needs_subst(ty: t) -> bool {
1585 tbox_has_flag(get(ty), needs_subst)
1588 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
1589 tref.substs.self_ty.iter().any(|&t| type_is_error(t)) ||
1590 tref.substs.tps.iter().any(|&t| type_is_error(t))
1593 pub fn type_is_ty_var(ty: t) -> bool {
1595 ty_infer(TyVar(_)) => true,
1600 pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool }
1602 pub fn type_is_self(ty: t) -> bool {
1604 ty_self(..) => true,
1609 pub fn type_is_structural(ty: t) -> bool {
1611 ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) | ty_trait(..) |
1612 ty_vec(_, vstore_fixed(_)) | ty_str(vstore_fixed(_)) |
1613 ty_vec(_, vstore_slice(_)) | ty_str(vstore_slice(_))
1619 pub fn type_is_sequence(ty: t) -> bool {
1621 ty_str(_) | ty_vec(_, _) => true,
1626 pub fn type_is_simd(cx: ctxt, ty: t) -> bool {
1628 ty_struct(did, _) => lookup_simd(cx, did),
1633 pub fn type_is_str(ty: t) -> bool {
1640 pub fn sequence_element_type(cx: ctxt, ty: t) -> t {
1642 ty_str(_) => return mk_mach_uint(ast::TyU8),
1643 ty_vec(mt, _) | ty_unboxed_vec(mt) => return mt.ty,
1644 _ => cx.sess.bug("sequence_element_type called on non-sequence value"),
1648 pub fn simd_type(cx: ctxt, ty: t) -> t {
1650 ty_struct(did, ref substs) => {
1651 let fields = lookup_struct_fields(cx, did);
1652 lookup_field_type(cx, did, fields[0].id, substs)
1654 _ => fail!("simd_type called on invalid type")
1658 pub fn simd_size(cx: ctxt, ty: t) -> uint {
1660 ty_struct(did, _) => {
1661 let fields = lookup_struct_fields(cx, did);
1664 _ => fail!("simd_size called on invalid type")
1668 pub fn get_element_type(ty: t, i: uint) -> t {
1670 ty_tup(ref ts) => return ts[i],
1671 _ => fail!("get_element_type called on invalid type")
1675 pub fn type_is_box(ty: t) -> bool {
1677 ty_box(_) => return true,
1682 pub fn type_is_boxed(ty: t) -> bool {
1689 pub fn type_is_region_ptr(ty: t) -> bool {
1691 ty_rptr(_, _) => true,
1696 pub fn type_is_slice(ty: t) -> bool {
1698 ty_vec(_, vstore_slice(_)) | ty_str(vstore_slice(_)) => true,
1703 pub fn type_is_unique_box(ty: t) -> bool {
1705 ty_uniq(_) => return true,
1710 pub fn type_is_unsafe_ptr(ty: t) -> bool {
1712 ty_ptr(_) => return true,
1717 pub fn type_is_vec(ty: t) -> bool {
1718 return match get(ty).sty {
1719 ty_vec(_, _) | ty_unboxed_vec(_) => true,
1725 pub fn type_is_unique(ty: t) -> bool {
1727 ty_uniq(_) | ty_vec(_, vstore_uniq) | ty_str(vstore_uniq) => true,
1733 A scalar type is one that denotes an atomic datum, with no sub-components.
1734 (A ty_ptr is scalar because it represents a non-managed pointer, so its
1735 contents are abstract to rustc.)
1737 pub fn type_is_scalar(ty: t) -> bool {
1739 ty_nil | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
1740 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
1741 ty_bare_fn(..) | ty_ptr(_) => true,
1746 pub fn type_needs_drop(cx: ctxt, ty: t) -> bool {
1747 type_contents(cx, ty).needs_drop(cx)
1750 // Some things don't need cleanups during unwinding because the
1751 // task can free them all at once later. Currently only things
1752 // that only contain scalars and shared boxes can avoid unwind
1754 pub fn type_needs_unwind_cleanup(cx: ctxt, ty: t) -> bool {
1756 let needs_unwind_cleanup_cache = cx.needs_unwind_cleanup_cache
1758 match needs_unwind_cleanup_cache.get().find(&ty) {
1759 Some(&result) => return result,
1764 let mut tycache = HashSet::new();
1765 let needs_unwind_cleanup =
1766 type_needs_unwind_cleanup_(cx, ty, &mut tycache, false);
1767 let mut needs_unwind_cleanup_cache = cx.needs_unwind_cleanup_cache
1769 needs_unwind_cleanup_cache.get().insert(ty, needs_unwind_cleanup);
1770 return needs_unwind_cleanup;
1773 fn type_needs_unwind_cleanup_(cx: ctxt, ty: t,
1774 tycache: &mut HashSet<t>,
1775 encountered_box: bool) -> bool {
1777 // Prevent infinite recursion
1778 if !tycache.insert(ty) {
1782 let mut encountered_box = encountered_box;
1783 let mut needs_unwind_cleanup = false;
1784 maybe_walk_ty(ty, |ty| {
1785 let old_encountered_box = encountered_box;
1786 let result = match get(ty).sty {
1788 encountered_box = true;
1791 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
1792 ty_tup(_) | ty_ptr(_) => {
1795 ty_enum(did, ref substs) => {
1796 for v in (*enum_variants(cx, did)).iter() {
1797 for aty in v.args.iter() {
1798 let t = subst(cx, substs, *aty);
1799 needs_unwind_cleanup |=
1800 type_needs_unwind_cleanup_(cx, t, tycache,
1804 !needs_unwind_cleanup
1807 ty_str(vstore_uniq) |
1808 ty_vec(_, vstore_uniq) => {
1809 // Once we're inside a box, the annihilator will find
1810 // it and destroy it.
1811 if !encountered_box {
1812 needs_unwind_cleanup = true;
1819 needs_unwind_cleanup = true;
1824 encountered_box = old_encountered_box;
1828 return needs_unwind_cleanup;
1832 * Type contents is how the type checker reasons about kinds.
1833 * They track what kinds of things are found within a type. You can
1834 * think of them as kind of an "anti-kind". They track the kinds of values
1835 * and thinks that are contained in types. Having a larger contents for
1836 * a type tends to rule that type *out* from various kinds. For example,
1837 * a type that contains a reference is not sendable.
1839 * The reason we compute type contents and not kinds is that it is
1840 * easier for me (nmatsakis) to think about what is contained within
1841 * a type than to think about what is *not* contained within a type.
1843 pub struct TypeContents {
1847 macro_rules! def_type_content_sets(
1848 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
1850 use middle::ty::TypeContents;
1851 $(pub static $name: TypeContents = TypeContents { bits: $bits };)+
1856 def_type_content_sets!(
1858 None = 0b0000__00000000__0000,
1860 // Things that are interior to the value (first nibble):
1861 InteriorUnsized = 0b0000__00000000__0001,
1862 // InteriorAll = 0b0000__00000000__1111,
1864 // Things that are owned by the value (second and third nibbles):
1865 OwnsOwned = 0b0000__00000001__0000,
1866 OwnsDtor = 0b0000__00000010__0000,
1867 OwnsManaged /* see [1] below */ = 0b0000__00000100__0000,
1868 OwnsAffine = 0b0000__00001000__0000,
1869 OwnsAll = 0b0000__11111111__0000,
1871 // Things that are reachable by the value in any way (fourth nibble):
1872 ReachesNonsendAnnot = 0b0001__00000000__0000,
1873 ReachesBorrowed = 0b0010__00000000__0000,
1874 // ReachesManaged /* see [1] below */ = 0b0100__00000000__0000,
1875 ReachesMutable = 0b1000__00000000__0000,
1876 ReachesAll = 0b1111__00000000__0000,
1878 // Things that cause values to *move* rather than *copy*
1879 Moves = 0b0000__00001011__0000,
1881 // Things that mean drop glue is necessary
1882 NeedsDrop = 0b0000__00000111__0000,
1884 // Things that prevent values from being sent
1886 // Note: For checking whether something is sendable, it'd
1887 // be sufficient to have ReachesManaged. However, we include
1888 // both ReachesManaged and OwnsManaged so that when
1889 // a parameter has a bound T:Send, we are able to deduce
1890 // that it neither reaches nor owns a managed pointer.
1891 Nonsendable = 0b0111__00000100__0000,
1893 // Things that prevent values from being considered freezable
1894 Nonfreezable = 0b1000__00000000__0000,
1896 // Things that prevent values from being considered 'static
1897 Nonstatic = 0b0010__00000000__0000,
1899 // Things that prevent values from being considered sized
1900 Nonsized = 0b0000__00000000__0001,
1902 // Things that make values considered not POD (would be same
1903 // as `Moves`, but for the fact that managed data `@` is
1904 // not considered POD)
1905 Nonpod = 0b0000__00001111__0000,
1907 // Bits to set when a managed value is encountered
1909 // [1] Do not set the bits TC::OwnsManaged or
1910 // TC::ReachesManaged directly, instead reference
1911 // TC::Managed to set them both at once.
1912 Managed = 0b0100__00000100__0000,
1915 All = 0b1111__11111111__1111
1920 pub fn meets_bounds(&self, cx: ctxt, bbs: BuiltinBounds) -> bool {
1921 bbs.iter().all(|bb| self.meets_bound(cx, bb))
1924 pub fn meets_bound(&self, cx: ctxt, bb: BuiltinBound) -> bool {
1926 BoundStatic => self.is_static(cx),
1927 BoundFreeze => self.is_freezable(cx),
1928 BoundSend => self.is_sendable(cx),
1929 BoundSized => self.is_sized(cx),
1930 BoundPod => self.is_pod(cx),
1934 pub fn when(&self, cond: bool) -> TypeContents {
1935 if cond {*self} else {TC::None}
1938 pub fn intersects(&self, tc: TypeContents) -> bool {
1939 (self.bits & tc.bits) != 0
1942 pub fn is_static(&self, _: ctxt) -> bool {
1943 !self.intersects(TC::Nonstatic)
1946 pub fn is_sendable(&self, _: ctxt) -> bool {
1947 !self.intersects(TC::Nonsendable)
1950 pub fn owns_managed(&self) -> bool {
1951 self.intersects(TC::OwnsManaged)
1954 pub fn owns_owned(&self) -> bool {
1955 self.intersects(TC::OwnsOwned)
1958 pub fn is_freezable(&self, _: ctxt) -> bool {
1959 !self.intersects(TC::Nonfreezable)
1962 pub fn is_sized(&self, _: ctxt) -> bool {
1963 !self.intersects(TC::Nonsized)
1966 pub fn is_pod(&self, _: ctxt) -> bool {
1967 !self.intersects(TC::Nonpod)
1970 pub fn moves_by_default(&self, _: ctxt) -> bool {
1971 self.intersects(TC::Moves)
1974 pub fn needs_drop(&self, _: ctxt) -> bool {
1975 self.intersects(TC::NeedsDrop)
1978 pub fn owned_pointer(&self) -> TypeContents {
1980 * Includes only those bits that still apply
1981 * when indirected through a `~` pointer
1984 *self & (TC::OwnsAll | TC::ReachesAll))
1987 pub fn reference(&self, bits: TypeContents) -> TypeContents {
1989 * Includes only those bits that still apply
1990 * when indirected through a reference (`&`)
1993 *self & TC::ReachesAll)
1996 pub fn managed_pointer(&self) -> TypeContents {
1998 * Includes only those bits that still apply
1999 * when indirected through a managed pointer (`@`)
2002 *self & TC::ReachesAll)
2005 pub fn unsafe_pointer(&self) -> TypeContents {
2007 * Includes only those bits that still apply
2008 * when indirected through an unsafe pointer (`*`)
2010 *self & TC::ReachesAll
2013 pub fn union<T>(v: &[T], f: |&T| -> TypeContents) -> TypeContents {
2014 v.iter().fold(TC::None, |tc, t| tc | f(t))
2017 pub fn inverse(&self) -> TypeContents {
2018 TypeContents { bits: !self.bits }
2021 pub fn has_dtor(&self) -> bool {
2022 self.intersects(TC::OwnsDtor)
2026 impl ops::BitOr<TypeContents,TypeContents> for TypeContents {
2027 fn bitor(&self, other: &TypeContents) -> TypeContents {
2028 TypeContents {bits: self.bits | other.bits}
2032 impl ops::BitAnd<TypeContents,TypeContents> for TypeContents {
2033 fn bitand(&self, other: &TypeContents) -> TypeContents {
2034 TypeContents {bits: self.bits & other.bits}
2038 impl ops::Sub<TypeContents,TypeContents> for TypeContents {
2039 fn sub(&self, other: &TypeContents) -> TypeContents {
2040 TypeContents {bits: self.bits & !other.bits}
2044 impl fmt::Show for TypeContents {
2045 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2046 write!(f.buf, "TypeContents({:t})", self.bits)
2050 pub fn type_has_dtor(cx: ctxt, t: ty::t) -> bool {
2051 type_contents(cx, t).has_dtor()
2054 pub fn type_is_static(cx: ctxt, t: ty::t) -> bool {
2055 type_contents(cx, t).is_static(cx)
2058 pub fn type_is_sendable(cx: ctxt, t: ty::t) -> bool {
2059 type_contents(cx, t).is_sendable(cx)
2062 pub fn type_is_freezable(cx: ctxt, t: ty::t) -> bool {
2063 type_contents(cx, t).is_freezable(cx)
2066 pub fn type_contents(cx: ctxt, ty: t) -> TypeContents {
2067 let ty_id = type_id(ty);
2070 let tc_cache = cx.tc_cache.borrow();
2071 match tc_cache.get().find(&ty_id) {
2072 Some(tc) => { return *tc; }
2077 let mut cache = HashMap::new();
2078 let result = tc_ty(cx, ty, &mut cache);
2080 let mut tc_cache = cx.tc_cache.borrow_mut();
2081 tc_cache.get().insert(ty_id, result);
2086 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2088 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
2089 // private cache for this walk. This is needed in the case of cyclic
2092 // struct List { next: ~Option<List>, ... }
2094 // When computing the type contents of such a type, we wind up deeply
2095 // recursing as we go. So when we encounter the recursive reference
2096 // to List, we temporarily use TC::None as its contents. Later we'll
2097 // patch up the cache with the correct value, once we've computed it
2098 // (this is basically a co-inductive process, if that helps). So in
2099 // the end we'll compute TC::OwnsOwned, in this case.
2101 // The problem is, as we are doing the computation, we will also
2102 // compute an *intermediate* contents for, e.g., Option<List> of
2103 // TC::None. This is ok during the computation of List itself, but if
2104 // we stored this intermediate value into cx.tc_cache, then later
2105 // requests for the contents of Option<List> would also yield TC::None
2106 // which is incorrect. This value was computed based on the crutch
2107 // value for the type contents of list. The correct value is
2108 // TC::OwnsOwned. This manifested as issue #4821.
2109 let ty_id = type_id(ty);
2110 match cache.find(&ty_id) {
2111 Some(tc) => { return *tc; }
2115 let tc_cache = cx.tc_cache.borrow();
2116 match tc_cache.get().find(&ty_id) { // Must check both caches!
2117 Some(tc) => { return *tc; }
2121 cache.insert(ty_id, TC::None);
2123 let result = match get(ty).sty {
2124 // Scalar and unique types are sendable, freezable, and durable
2125 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2126 ty_bare_fn(_) | ty::ty_char => {
2130 ty_str(vstore_uniq) => {
2134 ty_closure(ref c) => {
2135 closure_contents(cx, c)
2139 tc_ty(cx, typ, cache).managed_pointer()
2143 tc_ty(cx, typ, cache).owned_pointer()
2146 ty_trait(_, _, store, mutbl, bounds) => {
2147 object_contents(cx, store, mutbl, bounds)
2151 tc_ty(cx, mt.ty, cache).unsafe_pointer()
2154 ty_rptr(r, ref mt) => {
2155 tc_ty(cx, mt.ty, cache).reference(
2156 borrowed_contents(r, mt.mutbl))
2159 ty_vec(mt, vstore_uniq) => {
2160 tc_mt(cx, mt, cache).owned_pointer()
2163 ty_vec(ref mt, vstore_slice(r)) => {
2164 tc_ty(cx, mt.ty, cache).reference(
2165 borrowed_contents(r, mt.mutbl))
2168 ty_vec(mt, vstore_fixed(_)) => {
2169 tc_mt(cx, mt, cache)
2172 ty_str(vstore_slice(r)) => {
2173 borrowed_contents(r, ast::MutImmutable)
2176 ty_str(vstore_fixed(_)) => {
2180 ty_struct(did, ref substs) => {
2181 let flds = struct_fields(cx, did, substs);
2183 TypeContents::union(flds, |f| tc_mt(cx, f.mt, cache));
2184 if ty::has_dtor(cx, did) {
2185 res = res | TC::OwnsDtor;
2187 apply_lang_items(cx, did, res)
2190 ty_tup(ref tys) => {
2191 TypeContents::union(*tys, |ty| tc_ty(cx, *ty, cache))
2194 ty_enum(did, ref substs) => {
2195 let variants = substd_enum_variants(cx, did, substs);
2197 TypeContents::union(variants, |variant| {
2198 TypeContents::union(variant.args, |arg_ty| {
2199 tc_ty(cx, *arg_ty, cache)
2202 apply_lang_items(cx, did, res)
2206 // We only ever ask for the kind of types that are defined in
2207 // the current crate; therefore, the only type parameters that
2208 // could be in scope are those defined in the current crate.
2209 // If this assertion failures, it is likely because of a
2210 // failure in the cross-crate inlining code to translate a
2212 assert_eq!(p.def_id.krate, ast::LOCAL_CRATE);
2214 let ty_param_defs = cx.ty_param_defs.borrow();
2215 let tp_def = ty_param_defs.get().get(&p.def_id.node);
2216 kind_bounds_to_contents(cx,
2217 tp_def.bounds.builtin_bounds,
2218 tp_def.bounds.trait_bounds)
2221 ty_self(def_id) => {
2222 // FIXME(#4678)---self should just be a ty param
2224 // Self may be bounded if the associated trait has builtin kinds
2225 // for supertraits. If so we can use those bounds.
2226 let trait_def = lookup_trait_def(cx, def_id);
2227 let traits = [trait_def.trait_ref];
2228 kind_bounds_to_contents(cx, trait_def.bounds, traits)
2232 // This occurs during coherence, but shouldn't occur at other
2236 ty_unboxed_vec(mt) => TC::InteriorUnsized | tc_mt(cx, mt, cache),
2239 cx.sess.bug("asked to compute contents of error type");
2243 cache.insert(ty_id, result);
2249 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2251 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
2252 mc | tc_ty(cx, mt.ty, cache)
2255 fn apply_lang_items(cx: ctxt,
2259 if Some(did) == cx.lang_items.no_freeze_bound() {
2260 tc | TC::ReachesMutable
2261 } else if Some(did) == cx.lang_items.no_send_bound() {
2262 tc | TC::ReachesNonsendAnnot
2263 } else if Some(did) == cx.lang_items.managed_bound() {
2265 } else if Some(did) == cx.lang_items.no_pod_bound() {
2272 fn borrowed_contents(region: ty::Region,
2273 mutbl: ast::Mutability)
2276 * Type contents due to containing a reference
2277 * with the region `region` and borrow kind `bk`
2280 let b = match mutbl {
2281 ast::MutMutable => TC::ReachesMutable | TC::OwnsAffine,
2282 ast::MutImmutable => TC::None,
2284 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
2287 fn closure_contents(cx: ctxt, cty: &ClosureTy) -> TypeContents {
2288 // Closure contents are just like trait contents, but with potentially
2290 let st = match cty.sigil {
2291 ast::BorrowedSigil =>
2292 object_contents(cx, RegionTraitStore(cty.region), MutMutable, cty.bounds),
2294 object_contents(cx, UniqTraitStore, MutImmutable, cty.bounds),
2295 ast::ManagedSigil => unreachable!()
2298 // FIXME(#3569): This borrowed_contents call should be taken care of in
2299 // object_contents, after ~Traits and @Traits can have region bounds too.
2300 // This one here is redundant for &fns but important for ~fns and @fns.
2301 let rt = borrowed_contents(cty.region, ast::MutImmutable);
2303 // This also prohibits "@once fn" from being copied, which allows it to
2304 // be called. Neither way really makes much sense.
2305 let ot = match cty.onceness {
2306 ast::Once => TC::OwnsAffine,
2307 ast::Many => TC::None,
2313 fn object_contents(cx: ctxt,
2315 mutbl: ast::Mutability,
2316 bounds: BuiltinBounds)
2318 // These are the type contents of the (opaque) interior
2319 let contents = TC::ReachesMutable.when(mutbl == ast::MutMutable) |
2320 kind_bounds_to_contents(cx, bounds, []);
2324 contents.owned_pointer()
2326 RegionTraitStore(r) => {
2327 contents.reference(borrowed_contents(r, mutbl))
2332 fn kind_bounds_to_contents(cx: ctxt,
2333 bounds: BuiltinBounds,
2334 traits: &[@TraitRef])
2336 let _i = indenter();
2337 let mut tc = TC::All;
2338 each_inherited_builtin_bound(cx, bounds, traits, |bound| {
2339 tc = tc - match bound {
2340 BoundStatic => TC::Nonstatic,
2341 BoundSend => TC::Nonsendable,
2342 BoundFreeze => TC::Nonfreezable,
2343 BoundSized => TC::Nonsized,
2344 BoundPod => TC::Nonpod,
2349 // Iterates over all builtin bounds on the type parameter def, including
2350 // those inherited from traits with builtin-kind-supertraits.
2351 fn each_inherited_builtin_bound(cx: ctxt,
2352 bounds: BuiltinBounds,
2353 traits: &[@TraitRef],
2354 f: |BuiltinBound|) {
2355 for bound in bounds.iter() {
2359 each_bound_trait_and_supertraits(cx, traits, |trait_ref| {
2360 let trait_def = lookup_trait_def(cx, trait_ref.def_id);
2361 for bound in trait_def.bounds.iter() {
2370 pub fn type_moves_by_default(cx: ctxt, ty: t) -> bool {
2371 type_contents(cx, ty).moves_by_default(cx)
2374 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
2375 pub fn is_instantiable(cx: ctxt, r_ty: t) -> bool {
2376 fn type_requires(cx: ctxt, seen: &mut ~[DefId],
2377 r_ty: t, ty: t) -> bool {
2378 debug!("type_requires({}, {})?",
2379 ::util::ppaux::ty_to_str(cx, r_ty),
2380 ::util::ppaux::ty_to_str(cx, ty));
2383 get(r_ty).sty == get(ty).sty ||
2384 subtypes_require(cx, seen, r_ty, ty)
2387 debug!("type_requires({}, {})? {}",
2388 ::util::ppaux::ty_to_str(cx, r_ty),
2389 ::util::ppaux::ty_to_str(cx, ty),
2394 fn subtypes_require(cx: ctxt, seen: &mut ~[DefId],
2395 r_ty: t, ty: t) -> bool {
2396 debug!("subtypes_require({}, {})?",
2397 ::util::ppaux::ty_to_str(cx, r_ty),
2398 ::util::ppaux::ty_to_str(cx, ty));
2400 let r = match get(ty).sty {
2401 // fixed length vectors need special treatment compared to
2402 // normal vectors, since they don't necessarily have the
2403 // possibilty to have length zero.
2404 ty_vec(_, vstore_fixed(0)) => false, // don't need no contents
2405 ty_vec(mt, vstore_fixed(_)) => type_requires(cx, seen, r_ty, mt.ty),
2422 ty_unboxed_vec(_) => {
2425 ty_box(typ) | ty_uniq(typ) => {
2426 type_requires(cx, seen, r_ty, typ)
2428 ty_rptr(_, ref mt) => {
2429 type_requires(cx, seen, r_ty, mt.ty)
2433 false // unsafe ptrs can always be NULL
2436 ty_trait(_, _, _, _, _) => {
2440 ty_struct(ref did, _) if seen.contains(did) => {
2444 ty_struct(did, ref substs) => {
2446 let fields = struct_fields(cx, did, substs);
2447 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
2448 seen.pop().unwrap();
2453 ts.iter().any(|t| type_requires(cx, seen, r_ty, *t))
2456 ty_enum(ref did, _) if seen.contains(did) => {
2460 ty_enum(did, ref substs) => {
2462 let vs = enum_variants(cx, did);
2463 let r = !vs.is_empty() && vs.iter().all(|variant| {
2464 variant.args.iter().any(|aty| {
2465 let sty = subst(cx, substs, *aty);
2466 type_requires(cx, seen, r_ty, sty)
2469 seen.pop().unwrap();
2474 debug!("subtypes_require({}, {})? {}",
2475 ::util::ppaux::ty_to_str(cx, r_ty),
2476 ::util::ppaux::ty_to_str(cx, ty),
2483 !subtypes_require(cx, &mut seen, r_ty, r_ty)
2486 /// Describes whether a type is representable. For types that are not
2487 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
2488 /// distinguish between types that are recursive with themselves and types that
2489 /// contain a different recursive type. These cases can therefore be treated
2490 /// differently when reporting errors.
2492 pub enum Representability {
2498 /// Check whether a type is representable. This means it cannot contain unboxed
2499 /// structural recursion. This check is needed for structs and enums.
2500 pub fn is_type_representable(cx: ctxt, ty: t) -> Representability {
2502 // Iterate until something non-representable is found
2503 fn find_nonrepresentable<It: Iterator<t>>(cx: ctxt, seen: &mut ~[DefId],
2504 mut iter: It) -> Representability {
2506 let r = type_structurally_recursive(cx, seen, ty);
2507 if r != Representable {
2514 // Does the type `ty` directly (without indirection through a pointer)
2515 // contain any types on stack `seen`?
2516 fn type_structurally_recursive(cx: ctxt, seen: &mut ~[DefId],
2517 ty: t) -> Representability {
2518 debug!("type_structurally_recursive: {}",
2519 ::util::ppaux::ty_to_str(cx, ty));
2521 // Compare current type to previously seen types
2524 ty_enum(did, _) => {
2525 for (i, &seen_did) in seen.iter().enumerate() {
2526 if did == seen_did {
2527 return if i == 0 { SelfRecursive }
2528 else { ContainsRecursive }
2535 // Check inner types
2539 find_nonrepresentable(cx, seen, ts.iter().map(|t| *t))
2541 // Fixed-length vectors.
2542 // FIXME(#11924) Behavior undecided for zero-length vectors.
2543 ty_vec(mt, vstore_fixed(_)) => {
2544 type_structurally_recursive(cx, seen, mt.ty)
2547 // Push struct and enum def-ids onto `seen` before recursing.
2548 ty_struct(did, ref substs) => {
2550 let fields = struct_fields(cx, did, substs);
2551 let r = find_nonrepresentable(cx, seen,
2552 fields.iter().map(|f| f.mt.ty));
2556 ty_enum(did, ref substs) => {
2558 let vs = enum_variants(cx, did);
2560 let mut r = Representable;
2561 for variant in vs.iter() {
2562 let iter = variant.args.iter().map(|aty| subst(cx, substs, *aty));
2563 r = find_nonrepresentable(cx, seen, iter);
2565 if r != Representable { break }
2576 debug!("is_type_representable: {}",
2577 ::util::ppaux::ty_to_str(cx, ty));
2579 // To avoid a stack overflow when checking an enum variant or struct that
2580 // contains a different, structurally recursive type, maintain a stack
2581 // of seen types and check recursion for each of them (issues #3008, #3779).
2582 let mut seen: ~[DefId] = ~[];
2583 type_structurally_recursive(cx, &mut seen, ty)
2586 pub fn type_is_trait(ty: t) -> bool {
2588 ty_trait(..) => true,
2593 pub fn type_is_integral(ty: t) -> bool {
2595 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
2600 pub fn type_is_char(ty: t) -> bool {
2607 pub fn type_is_bare_fn(ty: t) -> bool {
2609 ty_bare_fn(..) => true,
2614 pub fn type_is_fp(ty: t) -> bool {
2616 ty_infer(FloatVar(_)) | ty_float(_) => true,
2621 pub fn type_is_numeric(ty: t) -> bool {
2622 return type_is_integral(ty) || type_is_fp(ty);
2625 pub fn type_is_signed(ty: t) -> bool {
2632 pub fn type_is_machine(ty: t) -> bool {
2634 ty_int(ast::TyI) | ty_uint(ast::TyU) => false,
2635 ty_int(..) | ty_uint(..) | ty_float(..) => true,
2640 pub fn type_is_enum(ty: t) -> bool {
2642 ty_enum(_, _) => return true,
2647 // Is the type's representation size known at compile time?
2648 pub fn type_is_sized(cx: ctxt, ty: ty::t) -> bool {
2650 // FIXME(#6308) add trait, vec, str, etc here.
2652 let ty_param_defs = cx.ty_param_defs.borrow();
2653 let param_def = ty_param_defs.get().get(&p.def_id.node);
2654 if param_def.bounds.builtin_bounds.contains_elem(BoundSized) {
2663 // Whether a type is enum like, that is an enum type with only nullary
2665 pub fn type_is_c_like_enum(cx: ctxt, ty: t) -> bool {
2667 ty_enum(did, _) => {
2668 let variants = enum_variants(cx, did);
2669 if variants.len() == 0 {
2672 variants.iter().all(|v| v.args.len() == 0)
2679 pub fn type_param(ty: t) -> Option<uint> {
2681 ty_param(p) => return Some(p.idx),
2682 _ => {/* fall through */ }
2687 // Returns the type and mutability of *t.
2689 // The parameter `explicit` indicates if this is an *explicit* dereference.
2690 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
2691 pub fn deref(t: t, explicit: bool) -> Option<mt> {
2692 deref_sty(&get(t).sty, explicit)
2695 pub fn deref_sty(sty: &sty, explicit: bool) -> Option<mt> {
2697 ty_box(typ) | ty_uniq(typ) => {
2700 mutbl: ast::MutImmutable,
2708 ty_ptr(mt) if explicit => {
2716 pub fn type_autoderef(t: t) -> t {
2719 match deref(t, false) {
2721 Some(mt) => t = mt.ty
2726 // Returns the type and mutability of t[i]
2727 pub fn index(t: t) -> Option<mt> {
2728 index_sty(&get(t).sty)
2731 pub fn index_sty(sty: &sty) -> Option<mt> {
2733 ty_vec(mt, _) => Some(mt),
2734 ty_str(_) => Some(mt {ty: mk_u8(), mutbl: ast::MutImmutable}),
2739 pub fn node_id_to_trait_ref(cx: ctxt, id: ast::NodeId) -> @ty::TraitRef {
2740 let trait_refs = cx.trait_refs.borrow();
2741 match trait_refs.get().find(&id) {
2743 None => cx.sess.bug(
2744 format!("node_id_to_trait_ref: no trait ref for node `{}`",
2745 cx.map.node_to_str(id)))
2749 pub fn try_node_id_to_type(cx: ctxt, id: ast::NodeId) -> Option<t> {
2750 let node_types = cx.node_types.borrow();
2751 node_types.get().find_copy(&(id as uint))
2754 pub fn node_id_to_type(cx: ctxt, id: ast::NodeId) -> t {
2755 match try_node_id_to_type(cx, id) {
2757 None => cx.sess.bug(
2758 format!("node_id_to_type: no type for node `{}`",
2759 cx.map.node_to_str(id)))
2763 pub fn node_id_to_type_opt(cx: ctxt, id: ast::NodeId) -> Option<t> {
2764 let node_types = cx.node_types.borrow();
2765 debug!("id: {:?}, node_types: {:?}", id, node_types);
2766 match node_types.get().find(&(id as uint)) {
2767 Some(&t) => Some(t),
2772 // FIXME(pcwalton): Makes a copy, bleh. Probably better to not do that.
2773 pub fn node_id_to_type_params(cx: ctxt, id: ast::NodeId) -> ~[t] {
2774 let node_type_substs = cx.node_type_substs.borrow();
2775 match node_type_substs.get().find(&id) {
2777 Some(ts) => return (*ts).clone(),
2781 fn node_id_has_type_params(cx: ctxt, id: ast::NodeId) -> bool {
2782 let node_type_substs = cx.node_type_substs.borrow();
2783 node_type_substs.get().contains_key(&id)
2786 pub fn fn_is_variadic(fty: t) -> bool {
2787 match get(fty).sty {
2788 ty_bare_fn(ref f) => f.sig.variadic,
2789 ty_closure(ref f) => f.sig.variadic,
2791 fail!("fn_is_variadic() called on non-fn type: {:?}", s)
2796 pub fn ty_fn_sig(fty: t) -> FnSig {
2797 match get(fty).sty {
2798 ty_bare_fn(ref f) => f.sig.clone(),
2799 ty_closure(ref f) => f.sig.clone(),
2801 fail!("ty_fn_sig() called on non-fn type: {:?}", s)
2806 // Type accessors for substructures of types
2807 pub fn ty_fn_args(fty: t) -> ~[t] {
2808 match get(fty).sty {
2809 ty_bare_fn(ref f) => f.sig.inputs.clone(),
2810 ty_closure(ref f) => f.sig.inputs.clone(),
2812 fail!("ty_fn_args() called on non-fn type: {:?}", s)
2817 pub fn ty_closure_sigil(fty: t) -> Sigil {
2818 match get(fty).sty {
2819 ty_closure(ref f) => f.sigil,
2821 fail!("ty_closure_sigil() called on non-closure type: {:?}", s)
2826 pub fn ty_fn_purity(fty: t) -> ast::Purity {
2827 match get(fty).sty {
2828 ty_bare_fn(ref f) => f.purity,
2829 ty_closure(ref f) => f.purity,
2831 fail!("ty_fn_purity() called on non-fn type: {:?}", s)
2836 pub fn ty_fn_ret(fty: t) -> t {
2837 match get(fty).sty {
2838 ty_bare_fn(ref f) => f.sig.output,
2839 ty_closure(ref f) => f.sig.output,
2841 fail!("ty_fn_ret() called on non-fn type: {:?}", s)
2846 pub fn is_fn_ty(fty: t) -> bool {
2847 match get(fty).sty {
2848 ty_bare_fn(_) => true,
2849 ty_closure(_) => true,
2854 pub fn ty_vstore(ty: t) -> vstore {
2856 ty_vec(_, vstore) => vstore,
2857 ty_str(vstore) => vstore,
2858 ref s => fail!("ty_vstore() called on invalid sty: {:?}", s)
2862 pub fn ty_region(tcx: ctxt,
2867 ty_vec(_, vstore_slice(r)) => r,
2868 ty_str(vstore_slice(r)) => r,
2872 format!("ty_region() invoked on in appropriate ty: {:?}", s));
2877 pub fn replace_fn_sig(cx: ctxt, fsty: &sty, new_sig: FnSig) -> t {
2879 ty_bare_fn(ref f) => mk_bare_fn(cx, BareFnTy {sig: new_sig, ..*f}),
2880 ty_closure(ref f) => mk_closure(cx, ClosureTy {sig: new_sig, ..*f}),
2883 format!("ty_fn_sig() called on non-fn type: {:?}", s));
2888 pub fn replace_closure_return_type(tcx: ctxt, fn_type: t, ret_type: t) -> t {
2891 * Returns a new function type based on `fn_type` but returning a value of
2892 * type `ret_type` instead. */
2894 match ty::get(fn_type).sty {
2895 ty::ty_closure(ref fty) => {
2896 ty::mk_closure(tcx, ClosureTy {
2897 sig: FnSig {output: ret_type, ..fty.sig.clone()},
2902 tcx.sess.bug(format!(
2903 "replace_fn_ret() invoked with non-fn-type: {}",
2904 ty_to_str(tcx, fn_type)));
2909 // Returns a vec of all the input and output types of fty.
2910 pub fn tys_in_fn_sig(sig: &FnSig) -> ~[t] {
2911 vec::append_one(sig.inputs.map(|a| *a), sig.output)
2914 // Type accessors for AST nodes
2915 pub fn block_ty(cx: ctxt, b: &ast::Block) -> t {
2916 return node_id_to_type(cx, b.id);
2920 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
2921 // doesn't provide type parameter substitutions.
2922 pub fn pat_ty(cx: ctxt, pat: &ast::Pat) -> t {
2923 return node_id_to_type(cx, pat.id);
2927 // Returns the type of an expression as a monotype.
2929 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
2930 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
2931 // auto-ref. The type returned by this function does not consider such
2932 // adjustments. See `expr_ty_adjusted()` instead.
2934 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
2935 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
2936 // instead of "fn(t) -> T with T = int". If this isn't what you want, see
2937 // expr_ty_params_and_ty() below.
2938 pub fn expr_ty(cx: ctxt, expr: &ast::Expr) -> t {
2939 return node_id_to_type(cx, expr.id);
2942 pub fn expr_ty_opt(cx: ctxt, expr: &ast::Expr) -> Option<t> {
2943 return node_id_to_type_opt(cx, expr.id);
2946 pub fn expr_ty_adjusted(cx: ctxt, expr: &ast::Expr) -> t {
2949 * Returns the type of `expr`, considering any `AutoAdjustment`
2950 * entry recorded for that expression.
2952 * It would almost certainly be better to store the adjusted ty in with
2953 * the `AutoAdjustment`, but I opted not to do this because it would
2954 * require serializing and deserializing the type and, although that's not
2955 * hard to do, I just hate that code so much I didn't want to touch it
2956 * unless it was to fix it properly, which seemed a distraction from the
2957 * task at hand! -nmatsakis
2960 let unadjusted_ty = expr_ty(cx, expr);
2962 let adjustments = cx.adjustments.borrow();
2963 adjustments.get().find_copy(&expr.id)
2965 adjust_ty(cx, expr.span, unadjusted_ty, adjustment)
2968 pub fn expr_span(cx: ctxt, id: NodeId) -> Span {
2969 match cx.map.find(id) {
2970 Some(ast_map::NodeExpr(e)) => {
2974 cx.sess.bug(format!("Node id {} is not an expr: {:?}",
2978 cx.sess.bug(format!("Node id {} is not present \
2979 in the node map", id));
2984 pub fn local_var_name_str(cx: ctxt, id: NodeId) -> InternedString {
2985 match cx.map.find(id) {
2986 Some(ast_map::NodeLocal(pat)) => {
2988 ast::PatIdent(_, ref path, _) => {
2989 token::get_ident(ast_util::path_to_ident(path))
2993 format!("Variable id {} maps to {:?}, not local",
3000 format!("Variable id {} maps to {:?}, not local",
3006 pub fn adjust_ty(cx: ctxt,
3008 unadjusted_ty: ty::t,
3009 adjustment: Option<@AutoAdjustment>)
3011 /*! See `expr_ty_adjusted` */
3013 return match adjustment {
3014 None => unadjusted_ty,
3016 Some(adjustment) => {
3018 AutoAddEnv(r, s) => {
3019 match ty::get(unadjusted_ty).sty {
3020 ty::ty_bare_fn(ref b) => {
3023 ty::ClosureTy {purity: b.purity,
3025 onceness: ast::Many,
3027 bounds: ty::AllBuiltinBounds(),
3028 sig: b.sig.clone()})
3032 format!("add_env adjustment on non-bare-fn: \
3039 AutoDerefRef(ref adj) => {
3040 let mut adjusted_ty = unadjusted_ty;
3042 if !ty::type_is_error(adjusted_ty) {
3043 for i in range(0, adj.autoderefs) {
3044 match ty::deref(adjusted_ty, true) {
3045 Some(mt) => { adjusted_ty = mt.ty; }
3049 format!("the {}th autoderef failed: \
3052 ty_to_str(cx, adjusted_ty)));
3059 None => adjusted_ty,
3060 Some(ref autoref) => {
3069 AutoBorrowVec(r, m) => {
3070 borrow_vec(cx, span, r, m, adjusted_ty)
3073 AutoBorrowVecRef(r, m) => {
3074 adjusted_ty = borrow_vec(cx,
3081 mutbl: ast::MutImmutable
3085 AutoBorrowFn(r) => {
3086 borrow_fn(cx, span, r, adjusted_ty)
3090 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
3093 AutoBorrowObj(r, m) => {
3094 borrow_obj(cx, span, r, m, adjusted_ty)
3101 AutoObject(ref sigil, ref region, m, b, def_id, ref substs) => {
3102 trait_adjustment_to_ty(cx,
3114 fn borrow_vec(cx: ctxt, span: Span,
3115 r: Region, m: ast::Mutability,
3116 ty: ty::t) -> ty::t {
3119 ty::mk_vec(cx, mt {ty: mt.ty, mutbl: m}, vstore_slice(r))
3123 ty::mk_str(cx, vstore_slice(r))
3129 format!("borrow-vec associated with bad sty: {:?}",
3135 fn borrow_fn(cx: ctxt, span: Span, r: Region, ty: ty::t) -> ty::t {
3137 ty_closure(ref fty) => {
3138 ty::mk_closure(cx, ClosureTy {
3139 sigil: BorrowedSigil,
3148 format!("borrow-fn associated with bad sty: {:?}",
3154 fn borrow_obj(cx: ctxt, span: Span, r: Region,
3155 m: ast::Mutability, ty: ty::t) -> ty::t {
3157 ty_trait(trt_did, ref trt_substs, _, _, b) => {
3158 ty::mk_trait(cx, trt_did, trt_substs.clone(),
3159 RegionTraitStore(r), m, b)
3164 format!("borrow-trait-obj associated with bad sty: {:?}",
3171 pub fn trait_adjustment_to_ty(cx: ctxt, sigil: &ast::Sigil, region: &Option<Region>,
3172 def_id: ast::DefId, substs: &substs, m: ast::Mutability,
3173 bounds: BuiltinBounds) -> t {
3175 let trait_store = match *sigil {
3176 BorrowedSigil => RegionTraitStore(region.expect("expected valid region")),
3177 OwnedSigil => UniqTraitStore,
3178 ManagedSigil => unreachable!()
3181 mk_trait(cx, def_id, substs.clone(), trait_store, m, bounds)
3185 pub fn map_region(&self, f: |Region| -> Region) -> AutoRef {
3187 ty::AutoPtr(r, m) => ty::AutoPtr(f(r), m),
3188 ty::AutoBorrowVec(r, m) => ty::AutoBorrowVec(f(r), m),
3189 ty::AutoBorrowVecRef(r, m) => ty::AutoBorrowVecRef(f(r), m),
3190 ty::AutoBorrowFn(r) => ty::AutoBorrowFn(f(r)),
3191 ty::AutoUnsafe(m) => ty::AutoUnsafe(m),
3192 ty::AutoBorrowObj(r, m) => ty::AutoBorrowObj(f(r), m),
3197 pub struct ParamsTy {
3202 pub fn expr_ty_params_and_ty(cx: ctxt,
3206 params: node_id_to_type_params(cx, expr.id),
3207 ty: node_id_to_type(cx, expr.id)
3211 pub fn expr_has_ty_params(cx: ctxt, expr: &ast::Expr) -> bool {
3212 return node_id_has_type_params(cx, expr.id);
3215 pub fn method_call_type_param_defs(tcx: ctxt, origin: typeck::MethodOrigin)
3216 -> Rc<~[TypeParameterDef]> {
3218 typeck::MethodStatic(did) => {
3219 // n.b.: When we encode impl methods, the bounds
3220 // that we encode include both the impl bounds
3221 // and then the method bounds themselves...
3222 ty::lookup_item_type(tcx, did).generics.type_param_defs
3224 typeck::MethodParam(typeck::MethodParam {
3226 method_num: n_mth, ..}) |
3227 typeck::MethodObject(typeck::MethodObject {
3229 method_num: n_mth, ..}) => {
3230 // ...trait methods bounds, in contrast, include only the
3231 // method bounds, so we must preprend the tps from the
3232 // trait itself. This ought to be harmonized.
3233 let trait_type_param_defs =
3234 lookup_trait_def(tcx, trt_id).generics.type_param_defs();
3235 Rc::new(vec::append(
3236 trait_type_param_defs.to_owned(),
3237 ty::trait_method(tcx,
3239 n_mth).generics.type_param_defs()))
3244 pub fn resolve_expr(tcx: ctxt, expr: &ast::Expr) -> ast::Def {
3245 let def_map = tcx.def_map.borrow();
3246 match def_map.get().find(&expr.id) {
3249 tcx.sess.span_bug(expr.span, format!(
3250 "no def-map entry for expr {:?}", expr.id));
3255 pub fn expr_is_lval(tcx: ctxt,
3256 method_map: typeck::MethodMap,
3257 e: &ast::Expr) -> bool {
3258 match expr_kind(tcx, method_map, e) {
3260 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
3264 /// We categorize expressions into three kinds. The distinction between
3265 /// lvalue/rvalue is fundamental to the language. The distinction between the
3266 /// two kinds of rvalues is an artifact of trans which reflects how we will
3267 /// generate code for that kind of expression. See trans/expr.rs for more
3276 pub fn expr_kind(tcx: ctxt,
3277 method_map: typeck::MethodMap,
3278 expr: &ast::Expr) -> ExprKind {
3280 let method_map = method_map.borrow();
3281 if method_map.get().contains_key(&expr.id) {
3282 // Overloaded operations are generally calls, and hence they are
3283 // generated via DPS. However, assign_op (e.g., `x += y`) is an
3284 // exception, as its result is always unit.
3285 return match expr.node {
3286 ast::ExprAssignOp(..) => RvalueStmtExpr,
3293 ast::ExprPath(..) => {
3294 match resolve_expr(tcx, expr) {
3295 ast::DefVariant(tid, vid, _) => {
3296 let variant_info = enum_variant_with_id(tcx, tid, vid);
3297 if variant_info.args.len() > 0u {
3306 ast::DefStruct(_) => {
3307 match get(expr_ty(tcx, expr)).sty {
3308 ty_bare_fn(..) => RvalueDatumExpr,
3313 // Fn pointers are just scalar values.
3314 ast::DefFn(..) | ast::DefStaticMethod(..) => RvalueDatumExpr,
3316 // Note: there is actually a good case to be made that
3317 // DefArg's, particularly those of immediate type, ought to
3318 // considered rvalues.
3319 ast::DefStatic(..) |
3320 ast::DefBinding(..) |
3323 ast::DefLocal(..) => LvalueExpr,
3326 tcx.sess.span_bug(expr.span, format!(
3327 "uncategorized def for expr {:?}: {:?}",
3333 ast::ExprUnary(ast::UnDeref, _) |
3334 ast::ExprField(..) |
3335 ast::ExprIndex(..) => {
3340 ast::ExprMethodCall(..) |
3341 ast::ExprStruct(..) |
3344 ast::ExprMatch(..) |
3345 ast::ExprFnBlock(..) |
3347 ast::ExprBlock(..) |
3348 ast::ExprRepeat(..) |
3349 ast::ExprVstore(_, ast::ExprVstoreSlice) |
3350 ast::ExprVstore(_, ast::ExprVstoreMutSlice) |
3351 ast::ExprVec(..) => {
3355 ast::ExprLit(lit) if lit_is_str(lit) => {
3359 ast::ExprCast(..) => {
3360 let node_types = tcx.node_types.borrow();
3361 match node_types.get().find(&(expr.id as uint)) {
3363 if type_is_trait(t) {
3370 // Technically, it should not happen that the expr is not
3371 // present within the table. However, it DOES happen
3372 // during type check, because the final types from the
3373 // expressions are not yet recorded in the tcx. At that
3374 // time, though, we are only interested in knowing lvalue
3375 // vs rvalue. It would be better to base this decision on
3376 // the AST type in cast node---but (at the time of this
3377 // writing) it's not easy to distinguish casts to traits
3378 // from other casts based on the AST. This should be
3379 // easier in the future, when casts to traits would like
3380 // like @Foo, ~Foo, or &Foo.
3386 ast::ExprBreak(..) |
3387 ast::ExprAgain(..) |
3389 ast::ExprWhile(..) |
3391 ast::ExprAssign(..) |
3392 ast::ExprInlineAsm(..) |
3393 ast::ExprAssignOp(..) => {
3397 ast::ExprForLoop(..) => fail!("non-desugared expr_for_loop"),
3400 ast::ExprLit(_) | // Note: LitStr is carved out above
3401 ast::ExprUnary(..) |
3402 ast::ExprAddrOf(..) |
3403 ast::ExprBinary(..) |
3404 ast::ExprVstore(_, ast::ExprVstoreUniq) => {
3408 ast::ExprBox(place, _) => {
3409 // Special case `~T` for now:
3410 let def_map = tcx.def_map.borrow();
3411 let definition = match def_map.get().find(&place.id) {
3413 None => fail!("no def for place"),
3415 let def_id = ast_util::def_id_of_def(definition);
3416 match tcx.lang_items.items[ExchangeHeapLangItem as uint] {
3417 Some(item_def_id) if def_id == item_def_id => RvalueDatumExpr,
3418 Some(_) | None => RvalueDpsExpr,
3422 ast::ExprParen(e) => expr_kind(tcx, method_map, e),
3424 ast::ExprMac(..) => {
3427 "macro expression remains after expansion");
3432 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
3434 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
3437 ast::StmtMac(..) => fail!("unexpanded macro in trans")
3441 pub fn field_idx(name: ast::Name, fields: &[field]) -> Option<uint> {
3443 for f in fields.iter() { if f.ident.name == name { return Some(i); } i += 1u; }
3447 pub fn field_idx_strict(tcx: ty::ctxt, name: ast::Name, fields: &[field])
3450 for f in fields.iter() { if f.ident.name == name { return i; } i += 1u; }
3451 tcx.sess.bug(format!(
3452 "no field named `{}` found in the list of fields `{:?}`",
3453 token::get_name(name),
3454 fields.map(|f| token::get_ident(f.ident).get().to_str())));
3457 pub fn method_idx(id: ast::Ident, meths: &[@Method]) -> Option<uint> {
3458 meths.iter().position(|m| m.ident == id)
3461 /// Returns a vector containing the indices of all type parameters that appear
3462 /// in `ty`. The vector may contain duplicates. Probably should be converted
3463 /// to a bitset or some other representation.
3464 pub fn param_tys_in_type(ty: t) -> ~[param_ty] {
3477 pub fn occurs_check(tcx: ctxt, sp: Span, vid: TyVid, rt: t) {
3478 // Returns a vec of all the type variables occurring in `ty`. It may
3479 // contain duplicates. (Integral type vars aren't counted.)
3480 fn vars_in_type(ty: t) -> ~[TyVid] {
3484 ty_infer(TyVar(v)) => rslt.push(v),
3492 if !type_needs_infer(rt) { return; }
3495 if vars_in_type(rt).contains(&vid) {
3496 // Maybe this should be span_err -- however, there's an
3497 // assertion later on that the type doesn't contain
3498 // variables, so in this case we have to be sure to die.
3500 (sp, ~"type inference failed because I \
3501 could not find a type\n that's both of the form "
3502 + ::util::ppaux::ty_to_str(tcx, mk_var(tcx, vid)) +
3503 " and of the form " + ::util::ppaux::ty_to_str(tcx, rt) +
3504 " - such a type would have to be infinitely large.");
3508 pub fn ty_sort_str(cx: ctxt, t: t) -> ~str {
3510 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) |
3511 ty_uint(_) | ty_float(_) | ty_str(_) => {
3512 ::util::ppaux::ty_to_str(cx, t)
3515 ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
3516 ty_box(_) => ~"@-ptr",
3517 ty_uniq(_) => ~"~-ptr",
3518 ty_vec(_, _) => ~"vector",
3519 ty_unboxed_vec(_) => ~"unboxed vector",
3520 ty_ptr(_) => ~"*-ptr",
3521 ty_rptr(_, _) => ~"&-ptr",
3522 ty_bare_fn(_) => ~"extern fn",
3523 ty_closure(_) => ~"fn",
3524 ty_trait(id, _, _, _, _) => format!("trait {}", item_path_str(cx, id)),
3525 ty_struct(id, _) => format!("struct {}", item_path_str(cx, id)),
3526 ty_tup(_) => ~"tuple",
3527 ty_infer(TyVar(_)) => ~"inferred type",
3528 ty_infer(IntVar(_)) => ~"integral variable",
3529 ty_infer(FloatVar(_)) => ~"floating-point variable",
3530 ty_param(_) => ~"type parameter",
3531 ty_self(_) => ~"self",
3532 ty_err => ~"type error"
3536 pub fn type_err_to_str(cx: ctxt, err: &type_err) -> ~str {
3539 * Explains the source of a type err in a short,
3540 * human readable way. This is meant to be placed in
3541 * parentheses after some larger message. You should
3542 * also invoke `note_and_explain_type_err()` afterwards
3543 * to present additional details, particularly when
3544 * it comes to lifetime-related errors. */
3546 fn terr_vstore_kind_to_str(k: terr_vstore_kind) -> ~str {
3551 terr_trait => ~"trait"
3556 terr_mismatch => ~"types differ",
3557 terr_purity_mismatch(values) => {
3558 format!("expected {} fn but found {} fn",
3559 values.expected.to_str(), values.found.to_str())
3561 terr_abi_mismatch(values) => {
3562 format!("expected {} fn but found {} fn",
3563 values.expected.to_str(), values.found.to_str())
3565 terr_onceness_mismatch(values) => {
3566 format!("expected {} fn but found {} fn",
3567 values.expected.to_str(), values.found.to_str())
3569 terr_sigil_mismatch(values) => {
3570 format!("expected {} closure, found {} closure",
3571 values.expected.to_str(),
3572 values.found.to_str())
3574 terr_mutability => ~"values differ in mutability",
3575 terr_box_mutability => ~"boxed values differ in mutability",
3576 terr_vec_mutability => ~"vectors differ in mutability",
3577 terr_ptr_mutability => ~"pointers differ in mutability",
3578 terr_ref_mutability => ~"references differ in mutability",
3579 terr_ty_param_size(values) => {
3580 format!("expected a type with {} type params \
3581 but found one with {} type params",
3582 values.expected, values.found)
3584 terr_tuple_size(values) => {
3585 format!("expected a tuple with {} elements \
3586 but found one with {} elements",
3587 values.expected, values.found)
3589 terr_record_size(values) => {
3590 format!("expected a record with {} fields \
3591 but found one with {} fields",
3592 values.expected, values.found)
3594 terr_record_mutability => {
3595 ~"record elements differ in mutability"
3597 terr_record_fields(values) => {
3598 format!("expected a record with field `{}` but found one with field \
3600 token::get_ident(values.expected),
3601 token::get_ident(values.found))
3603 terr_arg_count => ~"incorrect number of function parameters",
3604 terr_regions_does_not_outlive(..) => {
3605 format!("lifetime mismatch")
3607 terr_regions_not_same(..) => {
3608 format!("lifetimes are not the same")
3610 terr_regions_no_overlap(..) => {
3611 format!("lifetimes do not intersect")
3613 terr_regions_insufficiently_polymorphic(br, _) => {
3614 format!("expected bound lifetime parameter {}, \
3615 but found concrete lifetime",
3616 bound_region_ptr_to_str(cx, br))
3618 terr_regions_overly_polymorphic(br, _) => {
3619 format!("expected concrete lifetime, \
3620 but found bound lifetime parameter {}",
3621 bound_region_ptr_to_str(cx, br))
3623 terr_vstores_differ(k, ref values) => {
3624 format!("{} storage differs: expected `{}` but found `{}`",
3625 terr_vstore_kind_to_str(k),
3626 vstore_to_str(cx, (*values).expected),
3627 vstore_to_str(cx, (*values).found))
3629 terr_trait_stores_differ(_, ref values) => {
3630 format!("trait storage differs: expected `{}` but found `{}`",
3631 trait_store_to_str(cx, (*values).expected),
3632 trait_store_to_str(cx, (*values).found))
3634 terr_in_field(err, fname) => {
3635 format!("in field `{}`, {}", token::get_ident(fname),
3636 type_err_to_str(cx, err))
3638 terr_sorts(values) => {
3639 format!("expected {} but found {}",
3640 ty_sort_str(cx, values.expected),
3641 ty_sort_str(cx, values.found))
3643 terr_traits(values) => {
3644 format!("expected trait `{}` but found trait `{}`",
3645 item_path_str(cx, values.expected),
3646 item_path_str(cx, values.found))
3648 terr_builtin_bounds(values) => {
3649 if values.expected.is_empty() {
3650 format!("expected no bounds but found `{}`",
3651 values.found.user_string(cx))
3652 } else if values.found.is_empty() {
3653 format!("expected bounds `{}` but found no bounds",
3654 values.expected.user_string(cx))
3656 format!("expected bounds `{}` but found bounds `{}`",
3657 values.expected.user_string(cx),
3658 values.found.user_string(cx))
3661 terr_integer_as_char => {
3662 format!("expected an integral type but found `char`")
3664 terr_int_mismatch(ref values) => {
3665 format!("expected `{}` but found `{}`",
3666 values.expected.to_str(),
3667 values.found.to_str())
3669 terr_float_mismatch(ref values) => {
3670 format!("expected `{}` but found `{}`",
3671 values.expected.to_str(),
3672 values.found.to_str())
3674 terr_variadic_mismatch(ref values) => {
3675 format!("expected {} fn but found {} function",
3676 if values.expected { "variadic" } else { "non-variadic" },
3677 if values.found { "variadic" } else { "non-variadic" })
3682 pub fn note_and_explain_type_err(cx: ctxt, err: &type_err) {
3684 terr_regions_does_not_outlive(subregion, superregion) => {
3685 note_and_explain_region(cx, "", subregion, "...");
3686 note_and_explain_region(cx, "...does not necessarily outlive ",
3689 terr_regions_not_same(region1, region2) => {
3690 note_and_explain_region(cx, "", region1, "...");
3691 note_and_explain_region(cx, "...is not the same lifetime as ",
3694 terr_regions_no_overlap(region1, region2) => {
3695 note_and_explain_region(cx, "", region1, "...");
3696 note_and_explain_region(cx, "...does not overlap ",
3699 terr_regions_insufficiently_polymorphic(_, conc_region) => {
3700 note_and_explain_region(cx,
3701 "concrete lifetime that was found is ",
3704 terr_regions_overly_polymorphic(_, conc_region) => {
3705 note_and_explain_region(cx,
3706 "expected concrete lifetime is ",
3713 pub fn def_has_ty_params(def: ast::Def) -> bool {
3715 ast::DefFn(_, _) | ast::DefVariant(_, _, _) | ast::DefStruct(_)
3721 pub fn provided_source(cx: ctxt, id: ast::DefId) -> Option<ast::DefId> {
3722 let provided_method_sources = cx.provided_method_sources.borrow();
3723 provided_method_sources.get().find(&id).map(|x| *x)
3726 pub fn provided_trait_methods(cx: ctxt, id: ast::DefId) -> ~[@Method] {
3729 match cx.map.find(id.node) {
3730 Some(ast_map::NodeItem(item)) => {
3732 ItemTrait(_, _, ref ms) => {
3733 let (_, p) = ast_util::split_trait_methods(*ms);
3734 p.map(|m| method(cx, ast_util::local_def(m.id)))
3737 cx.sess.bug(format!("provided_trait_methods: \
3738 `{:?}` is not a trait",
3744 cx.sess.bug(format!("provided_trait_methods: `{:?}` is not \
3751 csearch::get_provided_trait_methods(cx, id)
3755 pub fn trait_supertraits(cx: ctxt, id: ast::DefId) -> @~[@TraitRef] {
3758 let supertraits = cx.supertraits.borrow();
3759 match supertraits.get().find(&id) {
3760 Some(&trait_refs) => { return trait_refs; }
3761 None => {} // Continue.
3765 // Not in the cache. It had better be in the metadata, which means it
3766 // shouldn't be local.
3767 assert!(!is_local(id));
3769 // Get the supertraits out of the metadata and create the
3770 // TraitRef for each.
3771 let result = @csearch::get_supertraits(cx, id);
3772 let mut supertraits = cx.supertraits.borrow_mut();
3773 supertraits.get().insert(id, result);
3777 pub fn trait_ref_supertraits(cx: ctxt, trait_ref: &ty::TraitRef) -> ~[@TraitRef] {
3778 let supertrait_refs = trait_supertraits(cx, trait_ref.def_id);
3779 supertrait_refs.map(
3780 |supertrait_ref| supertrait_ref.subst(cx, &trait_ref.substs))
3783 fn lookup_locally_or_in_crate_store<V:Clone>(
3786 map: &mut HashMap<ast::DefId, V>,
3787 load_external: || -> V) -> V {
3789 * Helper for looking things up in the various maps
3790 * that are populated during typeck::collect (e.g.,
3791 * `cx.methods`, `cx.tcache`, etc). All of these share
3792 * the pattern that if the id is local, it should have
3793 * been loaded into the map by the `typeck::collect` phase.
3794 * If the def-id is external, then we have to go consult
3795 * the crate loading code (and cache the result for the future).
3798 match map.find_copy(&def_id) {
3799 Some(v) => { return v; }
3803 if def_id.krate == ast::LOCAL_CRATE {
3804 fail!("No def'n found for {:?} in tcx.{}", def_id, descr);
3806 let v = load_external();
3807 map.insert(def_id, v.clone());
3811 pub fn trait_method(cx: ctxt, trait_did: ast::DefId, idx: uint) -> @Method {
3812 let method_def_id = ty::trait_method_def_ids(cx, trait_did)[idx];
3813 ty::method(cx, method_def_id)
3817 pub fn trait_methods(cx: ctxt, trait_did: ast::DefId) -> @~[@Method] {
3818 let mut trait_methods_cache = cx.trait_methods_cache.borrow_mut();
3819 match trait_methods_cache.get().find(&trait_did) {
3820 Some(&methods) => methods,
3822 let def_ids = ty::trait_method_def_ids(cx, trait_did);
3823 let methods = @def_ids.map(|d| ty::method(cx, *d));
3824 trait_methods_cache.get().insert(trait_did, methods);
3830 pub fn method(cx: ctxt, id: ast::DefId) -> @Method {
3831 let mut methods = cx.methods.borrow_mut();
3832 lookup_locally_or_in_crate_store("methods", id, methods.get(), || {
3833 @csearch::get_method(cx, id)
3837 pub fn trait_method_def_ids(cx: ctxt, id: ast::DefId) -> @~[DefId] {
3838 let mut trait_method_def_ids = cx.trait_method_def_ids.borrow_mut();
3839 lookup_locally_or_in_crate_store("trait_method_def_ids",
3841 trait_method_def_ids.get(),
3843 @csearch::get_trait_method_def_ids(cx.cstore, id)
3847 pub fn impl_trait_ref(cx: ctxt, id: ast::DefId) -> Option<@TraitRef> {
3849 let mut impl_trait_cache = cx.impl_trait_cache.borrow_mut();
3850 match impl_trait_cache.get().find(&id) {
3851 Some(&ret) => { return ret; }
3856 let ret = if id.krate == ast::LOCAL_CRATE {
3857 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
3858 match cx.map.find(id.node) {
3859 Some(ast_map::NodeItem(item)) => {
3861 ast::ItemImpl(_, ref opt_trait, _, _) => {
3864 Some(ty::node_id_to_trait_ref(cx, t.ref_id))
3875 csearch::get_impl_trait(cx, id)
3878 let mut impl_trait_cache = cx.impl_trait_cache.borrow_mut();
3879 impl_trait_cache.get().insert(id, ret);
3883 pub fn trait_ref_to_def_id(tcx: ctxt, tr: &ast::TraitRef) -> ast::DefId {
3884 let def_map = tcx.def_map.borrow();
3885 let def = def_map.get()
3887 .expect("no def-map entry for trait");
3888 ast_util::def_id_of_def(*def)
3891 pub fn try_add_builtin_trait(tcx: ctxt,
3892 trait_def_id: ast::DefId,
3893 builtin_bounds: &mut BuiltinBounds) -> bool {
3894 //! Checks whether `trait_ref` refers to one of the builtin
3895 //! traits, like `Send`, and adds the corresponding
3896 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
3897 //! is a builtin trait.
3899 match tcx.lang_items.to_builtin_kind(trait_def_id) {
3900 Some(bound) => { builtin_bounds.add(bound); true }
3905 pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> {
3907 ty_trait(id, _, _, _, _) | ty_struct(id, _) | ty_enum(id, _) => Some(id),
3914 pub struct VariantInfo {
3916 arg_names: Option<~[ast::Ident]>,
3926 /// Creates a new VariantInfo from the corresponding ast representation.
3928 /// Does not do any caching of the value in the type context.
3929 pub fn from_ast_variant(cx: ctxt,
3930 ast_variant: &ast::Variant,
3931 discriminant: Disr) -> VariantInfo {
3932 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
3934 match ast_variant.node.kind {
3935 ast::TupleVariantKind(ref args) => {
3936 let arg_tys = if args.len() > 0 { ty_fn_args(ctor_ty).map(|a| *a) } else { ~[] };
3938 return VariantInfo {
3942 name: ast_variant.node.name,
3943 id: ast_util::local_def(ast_variant.node.id),
3944 disr_val: discriminant,
3945 vis: ast_variant.node.vis
3948 ast::StructVariantKind(ref struct_def) => {
3950 let fields: &[StructField] = struct_def.fields;
3952 assert!(fields.len() > 0);
3954 let arg_tys = ty_fn_args(ctor_ty).map(|a| *a);
3955 let arg_names = fields.map(|field| {
3956 match field.node.kind {
3957 NamedField(ident, _) => ident,
3958 UnnamedField => cx.sess.bug(
3959 "enum_variants: all fields in struct must have a name")
3963 return VariantInfo {
3965 arg_names: Some(arg_names),
3967 name: ast_variant.node.name,
3968 id: ast_util::local_def(ast_variant.node.id),
3969 disr_val: discriminant,
3970 vis: ast_variant.node.vis
3977 pub fn substd_enum_variants(cx: ctxt,
3980 -> ~[@VariantInfo] {
3981 enum_variants(cx, id).iter().map(|variant_info| {
3982 let substd_args = variant_info.args.iter()
3983 .map(|aty| subst(cx, substs, *aty)).collect();
3985 let substd_ctor_ty = subst(cx, substs, variant_info.ctor_ty);
3989 ctor_ty: substd_ctor_ty,
3990 ..(**variant_info).clone()
3995 pub fn item_path_str(cx: ctxt, id: ast::DefId) -> ~str {
3996 with_path(cx, id, |path| ast_map::path_to_str(path))
4001 TraitDtor(DefId, bool)
4005 pub fn is_not_present(&self) -> bool {
4012 pub fn is_present(&self) -> bool {
4013 !self.is_not_present()
4016 pub fn has_drop_flag(&self) -> bool {
4019 &TraitDtor(_, flag) => flag
4024 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
4025 Otherwise return none. */
4026 pub fn ty_dtor(cx: ctxt, struct_id: DefId) -> DtorKind {
4027 let destructor_for_type = cx.destructor_for_type.borrow();
4028 match destructor_for_type.get().find(&struct_id) {
4029 Some(&method_def_id) => {
4030 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
4032 TraitDtor(method_def_id, flag)
4038 pub fn has_dtor(cx: ctxt, struct_id: DefId) -> bool {
4039 ty_dtor(cx, struct_id).is_present()
4042 pub fn with_path<T>(cx: ctxt, id: ast::DefId, f: |ast_map::PathElems| -> T) -> T {
4043 if id.krate == ast::LOCAL_CRATE {
4044 cx.map.with_path(id.node, f)
4046 f(ast_map::Values(csearch::get_item_path(cx, id).iter()).chain(None))
4050 pub fn enum_is_univariant(cx: ctxt, id: ast::DefId) -> bool {
4051 enum_variants(cx, id).len() == 1
4054 pub fn type_is_empty(cx: ctxt, t: t) -> bool {
4055 match ty::get(t).sty {
4056 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
4061 pub fn enum_variants(cx: ctxt, id: ast::DefId) -> @~[@VariantInfo] {
4063 let enum_var_cache = cx.enum_var_cache.borrow();
4064 match enum_var_cache.get().find(&id) {
4065 Some(&variants) => return variants,
4066 _ => { /* fallthrough */ }
4070 let result = if ast::LOCAL_CRATE != id.krate {
4071 @csearch::get_enum_variants(cx, id)
4074 Although both this code and check_enum_variants in typeck/check
4075 call eval_const_expr, it should never get called twice for the same
4076 expr, since check_enum_variants also updates the enum_var_cache
4079 match cx.map.get(id.node) {
4080 ast_map::NodeItem(item) => {
4082 ast::ItemEnum(ref enum_definition, _) => {
4083 let mut last_discriminant: Option<Disr> = None;
4084 @enum_definition.variants.iter().map(|&variant| {
4086 let mut discriminant = match last_discriminant {
4087 Some(val) => val + 1,
4088 None => INITIAL_DISCRIMINANT_VALUE
4091 match variant.node.disr_expr {
4092 Some(e) => match const_eval::eval_const_expr_partial(&cx, e) {
4093 Ok(const_eval::const_int(val)) => {
4094 discriminant = val as Disr
4096 Ok(const_eval::const_uint(val)) => {
4097 discriminant = val as Disr
4102 "expected signed integer \
4117 @VariantInfo::from_ast_variant(cx,
4120 last_discriminant = Some(discriminant);
4126 cx.sess.bug("enum_variants: id not bound to an enum")
4130 _ => cx.sess.bug("enum_variants: id not bound to an enum")
4136 let mut enum_var_cache = cx.enum_var_cache.borrow_mut();
4137 enum_var_cache.get().insert(id, result);
4143 // Returns information about the enum variant with the given ID:
4144 pub fn enum_variant_with_id(cx: ctxt,
4145 enum_id: ast::DefId,
4146 variant_id: ast::DefId)
4148 let variants = enum_variants(cx, enum_id);
4150 while i < variants.len() {
4151 let variant = variants[i];
4152 if variant.id == variant_id { return variant; }
4155 cx.sess.bug("enum_variant_with_id(): no variant exists with that ID");
4159 // If the given item is in an external crate, looks up its type and adds it to
4160 // the type cache. Returns the type parameters and type.
4161 pub fn lookup_item_type(cx: ctxt,
4163 -> ty_param_bounds_and_ty {
4164 let mut tcache = cx.tcache.borrow_mut();
4165 lookup_locally_or_in_crate_store(
4166 "tcache", did, tcache.get(),
4167 || csearch::get_type(cx, did))
4170 pub fn lookup_impl_vtables(cx: ctxt,
4172 -> typeck::impl_res {
4173 let mut impl_vtables = cx.impl_vtables.borrow_mut();
4174 lookup_locally_or_in_crate_store(
4175 "impl_vtables", did, impl_vtables.get(),
4176 || csearch::get_impl_vtables(cx, did) )
4179 /// Given the did of a trait, returns its canonical trait ref.
4180 pub fn lookup_trait_def(cx: ctxt, did: ast::DefId) -> @ty::TraitDef {
4181 let mut trait_defs = cx.trait_defs.borrow_mut();
4182 match trait_defs.get().find(&did) {
4183 Some(&trait_def) => {
4184 // The item is in this crate. The caller should have added it to the
4185 // type cache already
4189 assert!(did.krate != ast::LOCAL_CRATE);
4190 let trait_def = @csearch::get_trait_def(cx, did);
4191 trait_defs.get().insert(did, trait_def);
4197 /// Iterate over meta_items of a definition.
4198 // (This should really be an iterator, but that would require csearch and
4199 // decoder to use iterators instead of higher-order functions.)
4200 pub fn each_attr(tcx: ctxt, did: DefId, f: |@MetaItem| -> bool) -> bool {
4202 let item = tcx.map.expect_item(did.node);
4203 item.attrs.iter().advance(|attr| f(attr.node.value))
4205 let mut cont = true;
4206 csearch::get_item_attrs(tcx.cstore, did, |meta_items| {
4208 cont = meta_items.iter().advance(|ptrptr| f(*ptrptr));
4215 /// Determine whether an item is annotated with an attribute
4216 pub fn has_attr(tcx: ctxt, did: DefId, attr: &str) -> bool {
4217 let mut found = false;
4218 each_attr(tcx, did, |item| {
4219 if item.name().equiv(&attr) {
4229 /// Determine whether an item is annotated with `#[packed]`
4230 pub fn lookup_packed(tcx: ctxt, did: DefId) -> bool {
4231 has_attr(tcx, did, "packed")
4234 /// Determine whether an item is annotated with `#[simd]`
4235 pub fn lookup_simd(tcx: ctxt, did: DefId) -> bool {
4236 has_attr(tcx, did, "simd")
4239 // Obtain the the representation annotation for a definition.
4240 pub fn lookup_repr_hint(tcx: ctxt, did: DefId) -> attr::ReprAttr {
4241 let mut acc = attr::ReprAny;
4242 ty::each_attr(tcx, did, |meta| {
4243 acc = attr::find_repr_attr(tcx.sess.diagnostic(), meta, acc);
4249 // Look up a field ID, whether or not it's local
4250 // Takes a list of type substs in case the struct is generic
4251 pub fn lookup_field_type(tcx: ctxt,
4256 let t = if id.krate == ast::LOCAL_CRATE {
4257 node_id_to_type(tcx, id.node)
4260 let mut tcache = tcx.tcache.borrow_mut();
4261 match tcache.get().find(&id) {
4262 Some(&ty_param_bounds_and_ty {ty, ..}) => ty,
4264 let tpt = csearch::get_field_type(tcx, struct_id, id);
4265 tcache.get().insert(id, tpt.clone());
4271 subst(tcx, substs, t)
4274 // Look up the list of field names and IDs for a given struct
4275 // Fails if the id is not bound to a struct.
4276 pub fn lookup_struct_fields(cx: ctxt, did: ast::DefId) -> ~[field_ty] {
4277 if did.krate == ast::LOCAL_CRATE {
4279 match cx.map.find(did.node) {
4280 Some(ast_map::NodeItem(i)) => {
4282 ast::ItemStruct(struct_def, _) => {
4283 struct_field_tys(struct_def.fields)
4285 _ => cx.sess.bug("struct ID bound to non-struct")
4288 Some(ast_map::NodeVariant(ref variant)) => {
4289 match (*variant).node.kind {
4290 ast::StructVariantKind(struct_def) => {
4291 struct_field_tys(struct_def.fields)
4294 cx.sess.bug("struct ID bound to enum variant that isn't \
4301 format!("struct ID not bound to an item: {}",
4302 cx.map.node_to_str(did.node)));
4307 return csearch::get_struct_fields(cx.sess.cstore, did);
4311 pub fn lookup_struct_field(cx: ctxt,
4313 field_id: ast::DefId)
4315 let r = lookup_struct_fields(cx, parent);
4316 match r.iter().find(
4317 |f| f.id.node == field_id.node) {
4319 None => cx.sess.bug("struct ID not found in parent's fields")
4323 fn struct_field_tys(fields: &[StructField]) -> ~[field_ty] {
4324 fields.map(|field| {
4325 match field.node.kind {
4326 NamedField(ident, visibility) => {
4329 id: ast_util::local_def(field.node.id),
4335 name: syntax::parse::token::special_idents::unnamed_field.name,
4336 id: ast_util::local_def(field.node.id),
4344 // Returns a list of fields corresponding to the struct's items. trans uses
4345 // this. Takes a list of substs with which to instantiate field types.
4346 pub fn struct_fields(cx: ctxt, did: ast::DefId, substs: &substs)
4348 lookup_struct_fields(cx, did).map(|f| {
4350 // FIXME #6993: change type of field to Name and get rid of new()
4351 ident: ast::Ident::new(f.name),
4353 ty: lookup_field_type(cx, did, f.id, substs),
4360 pub fn is_binopable(cx: ctxt, ty: t, op: ast::BinOp) -> bool {
4361 static tycat_other: int = 0;
4362 static tycat_bool: int = 1;
4363 static tycat_char: int = 2;
4364 static tycat_int: int = 3;
4365 static tycat_float: int = 4;
4366 static tycat_bot: int = 5;
4367 static tycat_raw_ptr: int = 6;
4369 static opcat_add: int = 0;
4370 static opcat_sub: int = 1;
4371 static opcat_mult: int = 2;
4372 static opcat_shift: int = 3;
4373 static opcat_rel: int = 4;
4374 static opcat_eq: int = 5;
4375 static opcat_bit: int = 6;
4376 static opcat_logic: int = 7;
4378 fn opcat(op: ast::BinOp) -> int {
4380 ast::BiAdd => opcat_add,
4381 ast::BiSub => opcat_sub,
4382 ast::BiMul => opcat_mult,
4383 ast::BiDiv => opcat_mult,
4384 ast::BiRem => opcat_mult,
4385 ast::BiAnd => opcat_logic,
4386 ast::BiOr => opcat_logic,
4387 ast::BiBitXor => opcat_bit,
4388 ast::BiBitAnd => opcat_bit,
4389 ast::BiBitOr => opcat_bit,
4390 ast::BiShl => opcat_shift,
4391 ast::BiShr => opcat_shift,
4392 ast::BiEq => opcat_eq,
4393 ast::BiNe => opcat_eq,
4394 ast::BiLt => opcat_rel,
4395 ast::BiLe => opcat_rel,
4396 ast::BiGe => opcat_rel,
4397 ast::BiGt => opcat_rel
4401 fn tycat(cx: ctxt, ty: t) -> int {
4402 if type_is_simd(cx, ty) {
4403 return tycat(cx, simd_type(cx, ty))
4406 ty_char => tycat_char,
4407 ty_bool => tycat_bool,
4408 ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
4409 ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
4410 ty_bot => tycat_bot,
4411 ty_ptr(_) => tycat_raw_ptr,
4416 static t: bool = true;
4417 static f: bool = false;
4420 // +, -, *, shift, rel, ==, bit, logic
4421 /*other*/ [f, f, f, f, f, f, f, f],
4422 /*bool*/ [f, f, f, f, t, t, t, t],
4423 /*char*/ [f, f, f, f, t, t, f, f],
4424 /*int*/ [t, t, t, t, t, t, t, f],
4425 /*float*/ [t, t, t, f, t, t, f, f],
4426 /*bot*/ [t, t, t, t, t, t, t, t],
4427 /*raw ptr*/ [f, f, f, f, t, t, f, f]];
4429 return tbl[tycat(cx, ty)][opcat(op)];
4432 pub fn ty_params_to_tys(tcx: ty::ctxt, generics: &ast::Generics) -> ~[t] {
4433 vec::from_fn(generics.ty_params.len(), |i| {
4434 let id = generics.ty_params.get(i).id;
4435 ty::mk_param(tcx, i, ast_util::local_def(id))
4439 /// Returns an equivalent type with all the typedefs and self regions removed.
4440 pub fn normalize_ty(cx: ctxt, t: t) -> t {
4441 let u = TypeNormalizer(cx).fold_ty(t);
4444 struct TypeNormalizer(ctxt);
4446 impl TypeFolder for TypeNormalizer {
4447 fn tcx(&self) -> ty::ctxt { let TypeNormalizer(c) = *self; c }
4449 fn fold_ty(&mut self, t: ty::t) -> ty::t {
4450 let normalized_opt = {
4451 let normalized_cache = self.tcx().normalized_cache.borrow();
4452 normalized_cache.get().find_copy(&t)
4454 match normalized_opt {
4459 let t_norm = ty_fold::super_fold_ty(self, t);
4460 let mut normalized_cache = self.tcx()
4463 normalized_cache.get().insert(t, t_norm);
4469 fn fold_vstore(&mut self, vstore: vstore) -> vstore {
4471 vstore_fixed(..) | vstore_uniq => vstore,
4472 vstore_slice(_) => vstore_slice(ReStatic)
4476 fn fold_region(&mut self, _: ty::Region) -> ty::Region {
4480 fn fold_substs(&mut self,
4483 substs { regions: ErasedRegions,
4484 self_ty: ty_fold::fold_opt_ty(self, substs.self_ty),
4485 tps: ty_fold::fold_ty_vec(self, substs.tps) }
4488 fn fold_sig(&mut self,
4491 // The binder-id is only relevant to bound regions, which
4492 // are erased at trans time.
4493 ty::FnSig { binder_id: ast::DUMMY_NODE_ID,
4494 inputs: ty_fold::fold_ty_vec(self, sig.inputs),
4495 output: self.fold_ty(sig.output),
4496 variadic: sig.variadic }
4501 pub trait ExprTyProvider {
4502 fn expr_ty(&self, ex: &ast::Expr) -> t;
4503 fn ty_ctxt(&self) -> ctxt;
4506 impl ExprTyProvider for ctxt {
4507 fn expr_ty(&self, ex: &ast::Expr) -> t {
4511 fn ty_ctxt(&self) -> ctxt {
4516 // Returns the repeat count for a repeating vector expression.
4517 pub fn eval_repeat_count<T: ExprTyProvider>(tcx: &T, count_expr: &ast::Expr) -> uint {
4518 match const_eval::eval_const_expr_partial(tcx, count_expr) {
4519 Ok(ref const_val) => match *const_val {
4520 const_eval::const_int(count) => if count < 0 {
4521 tcx.ty_ctxt().sess.span_err(count_expr.span,
4522 "expected positive integer for \
4523 repeat count but found negative integer");
4526 return count as uint
4528 const_eval::const_uint(count) => return count as uint,
4529 const_eval::const_float(count) => {
4530 tcx.ty_ctxt().sess.span_err(count_expr.span,
4531 "expected positive integer for \
4532 repeat count but found float");
4533 return count as uint;
4535 const_eval::const_str(_) => {
4536 tcx.ty_ctxt().sess.span_err(count_expr.span,
4537 "expected positive integer for \
4538 repeat count but found string");
4541 const_eval::const_bool(_) => {
4542 tcx.ty_ctxt().sess.span_err(count_expr.span,
4543 "expected positive integer for \
4544 repeat count but found boolean");
4547 const_eval::const_binary(_) => {
4548 tcx.ty_ctxt().sess.span_err(count_expr.span,
4549 "expected positive integer for \
4550 repeat count but found binary array");
4555 tcx.ty_ctxt().sess.span_err(count_expr.span,
4556 "expected constant integer for repeat count \
4557 but found variable");
4563 // Determine what purity to check a nested function under
4564 pub fn determine_inherited_purity(parent: (ast::Purity, ast::NodeId),
4565 child: (ast::Purity, ast::NodeId),
4566 child_sigil: ast::Sigil)
4567 -> (ast::Purity, ast::NodeId) {
4568 // If the closure is a stack closure and hasn't had some non-standard
4569 // purity inferred for it, then check it under its parent's purity.
4570 // Otherwise, use its own
4572 ast::BorrowedSigil if child.val0() == ast::ImpureFn => parent,
4577 // Iterate over a type parameter's bounded traits and any supertraits
4578 // of those traits, ignoring kinds.
4579 // Here, the supertraits are the transitive closure of the supertrait
4580 // relation on the supertraits from each bounded trait's constraint
4582 pub fn each_bound_trait_and_supertraits(tcx: ctxt,
4583 bounds: &[@TraitRef],
4584 f: |@TraitRef| -> bool)
4586 for &bound_trait_ref in bounds.iter() {
4587 let mut supertrait_set = HashMap::new();
4588 let mut trait_refs = ~[];
4591 // Seed the worklist with the trait from the bound
4592 supertrait_set.insert(bound_trait_ref.def_id, ());
4593 trait_refs.push(bound_trait_ref);
4595 // Add the given trait ty to the hash map
4596 while i < trait_refs.len() {
4597 debug!("each_bound_trait_and_supertraits(i={:?}, trait_ref={})",
4598 i, trait_refs[i].repr(tcx));
4600 if !f(trait_refs[i]) {
4604 // Add supertraits to supertrait_set
4605 let supertrait_refs = trait_ref_supertraits(tcx, trait_refs[i]);
4606 for &supertrait_ref in supertrait_refs.iter() {
4607 debug!("each_bound_trait_and_supertraits(supertrait_ref={})",
4608 supertrait_ref.repr(tcx));
4610 let d_id = supertrait_ref.def_id;
4611 if !supertrait_set.contains_key(&d_id) {
4612 // FIXME(#5527) Could have same trait multiple times
4613 supertrait_set.insert(d_id, ());
4614 trait_refs.push(supertrait_ref);
4624 pub fn count_traits_and_supertraits(tcx: ctxt,
4625 type_param_defs: &[TypeParameterDef]) -> uint {
4627 for type_param_def in type_param_defs.iter() {
4628 each_bound_trait_and_supertraits(
4629 tcx, type_param_def.bounds.trait_bounds, |_| {
4637 pub fn get_tydesc_ty(tcx: ctxt) -> Result<t, ~str> {
4638 tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
4639 let intrinsic_defs = tcx.intrinsic_defs.borrow();
4640 intrinsic_defs.get().find_copy(&tydesc_lang_item)
4641 .expect("Failed to resolve TyDesc")
4645 pub fn get_opaque_ty(tcx: ctxt) -> Result<t, ~str> {
4646 tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| {
4647 let intrinsic_defs = tcx.intrinsic_defs.borrow();
4648 intrinsic_defs.get().find_copy(&opaque_lang_item)
4649 .expect("Failed to resolve Opaque")
4653 pub fn visitor_object_ty(tcx: ctxt,
4654 region: ty::Region) -> Result<(@TraitRef, t), ~str> {
4655 let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) {
4657 Err(s) => { return Err(s); }
4659 let substs = substs {
4660 regions: ty::NonerasedRegions(opt_vec::Empty),
4664 let trait_ref = @TraitRef { def_id: trait_lang_item, substs: substs };
4668 trait_ref.substs.clone(),
4669 RegionTraitStore(region),
4671 EmptyBuiltinBounds())))
4674 pub fn item_variances(tcx: ctxt, item_id: ast::DefId) -> @ItemVariances {
4675 let mut item_variance_map = tcx.item_variance_map.borrow_mut();
4676 lookup_locally_or_in_crate_store(
4677 "item_variance_map", item_id, item_variance_map.get(),
4678 || @csearch::get_item_variances(tcx.cstore, item_id))
4681 /// Records a trait-to-implementation mapping.
4682 fn record_trait_implementation(tcx: ctxt,
4683 trait_def_id: DefId,
4684 implementation: @Impl) {
4685 let implementation_list;
4686 let mut trait_impls = tcx.trait_impls.borrow_mut();
4687 match trait_impls.get().find(&trait_def_id) {
4689 implementation_list = @RefCell::new(~[]);
4690 trait_impls.get().insert(trait_def_id, implementation_list);
4692 Some(&existing_implementation_list) => {
4693 implementation_list = existing_implementation_list
4697 let mut implementation_list = implementation_list.borrow_mut();
4698 implementation_list.get().push(implementation);
4701 /// Populates the type context with all the implementations for the given type
4703 pub fn populate_implementations_for_type_if_necessary(tcx: ctxt,
4704 type_id: ast::DefId) {
4705 if type_id.krate == LOCAL_CRATE {
4709 let populated_external_types = tcx.populated_external_types.borrow();
4710 if populated_external_types.get().contains(&type_id) {
4715 csearch::each_implementation_for_type(tcx.sess.cstore, type_id,
4716 |implementation_def_id| {
4717 let implementation = @csearch::get_impl(tcx, implementation_def_id);
4719 // Record the trait->implementation mappings, if applicable.
4720 let associated_traits = csearch::get_impl_trait(tcx,
4721 implementation.did);
4722 for trait_ref in associated_traits.iter() {
4723 record_trait_implementation(tcx,
4728 // For any methods that use a default implementation, add them to
4729 // the map. This is a bit unfortunate.
4730 for method in implementation.methods.iter() {
4731 for source in method.provided_source.iter() {
4732 let mut provided_method_sources =
4733 tcx.provided_method_sources.borrow_mut();
4734 provided_method_sources.get().insert(method.def_id, *source);
4738 // If this is an inherent implementation, record it.
4739 if associated_traits.is_none() {
4740 let implementation_list;
4741 let mut inherent_impls = tcx.inherent_impls.borrow_mut();
4742 match inherent_impls.get().find(&type_id) {
4744 implementation_list = @RefCell::new(~[]);
4745 inherent_impls.get().insert(type_id, implementation_list);
4747 Some(&existing_implementation_list) => {
4748 implementation_list = existing_implementation_list;
4752 let mut implementation_list =
4753 implementation_list.borrow_mut();
4754 implementation_list.get().push(implementation);
4758 // Store the implementation info.
4759 let mut impls = tcx.impls.borrow_mut();
4760 impls.get().insert(implementation_def_id, implementation);
4763 let mut populated_external_types = tcx.populated_external_types
4765 populated_external_types.get().insert(type_id);
4768 /// Populates the type context with all the implementations for the given
4769 /// trait if necessary.
4770 pub fn populate_implementations_for_trait_if_necessary(
4772 trait_id: ast::DefId) {
4773 if trait_id.krate == LOCAL_CRATE {
4777 let populated_external_traits = tcx.populated_external_traits
4779 if populated_external_traits.get().contains(&trait_id) {
4784 csearch::each_implementation_for_trait(tcx.sess.cstore, trait_id,
4785 |implementation_def_id| {
4786 let implementation = @csearch::get_impl(tcx, implementation_def_id);
4788 // Record the trait->implementation mapping.
4789 record_trait_implementation(tcx, trait_id, implementation);
4791 // For any methods that use a default implementation, add them to
4792 // the map. This is a bit unfortunate.
4793 for method in implementation.methods.iter() {
4794 for source in method.provided_source.iter() {
4795 let mut provided_method_sources =
4796 tcx.provided_method_sources.borrow_mut();
4797 provided_method_sources.get().insert(method.def_id, *source);
4801 // Store the implementation info.
4802 let mut impls = tcx.impls.borrow_mut();
4803 impls.get().insert(implementation_def_id, implementation);
4806 let mut populated_external_traits = tcx.populated_external_traits
4808 populated_external_traits.get().insert(trait_id);
4811 /// Given the def_id of an impl, return the def_id of the trait it implements.
4812 /// If it implements no trait, return `None`.
4813 pub fn trait_id_of_impl(tcx: ctxt,
4814 def_id: ast::DefId) -> Option<ast::DefId> {
4815 let node = match tcx.map.find(def_id.node) {
4820 ast_map::NodeItem(item) => {
4822 ast::ItemImpl(_, Some(ref trait_ref), _, _) => {
4823 Some(node_id_to_trait_ref(tcx, trait_ref.ref_id).def_id)
4832 /// If the given def ID describes a method belonging to a trait (either a
4833 /// default method or an implementation of a trait method), return the ID of
4834 /// the trait that the method belongs to. Otherwise, return `None`.
4835 pub fn trait_of_method(tcx: ctxt, def_id: ast::DefId)
4836 -> Option<ast::DefId> {
4837 if def_id.krate != LOCAL_CRATE {
4838 return csearch::get_trait_of_method(tcx.cstore, def_id, tcx);
4842 let methods = tcx.methods.borrow();
4843 method = methods.get().find(&def_id).map(|method| *method);
4847 match method.container {
4848 TraitContainer(def_id) => Some(def_id),
4849 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
4856 /// If the given def ID describes a method belonging to a trait, (either a
4857 /// default method or an implementation of a trait method), return the ID of
4858 /// the method inside trait definition (this means that if the given def ID
4859 /// is already that of the original trait method, then the return value is
4861 /// Otherwise, return `None`.
4862 pub fn trait_method_of_method(tcx: ctxt,
4863 def_id: ast::DefId) -> Option<ast::DefId> {
4866 let methods = tcx.methods.borrow();
4867 match methods.get().find(&def_id) {
4868 Some(m) => method = *m,
4869 None => return None,
4872 let name = method.ident.name;
4873 match trait_of_method(tcx, def_id) {
4874 Some(trait_did) => {
4875 let trait_methods = ty::trait_methods(tcx, trait_did);
4876 trait_methods.iter()
4877 .position(|m| m.ident.name == name)
4878 .map(|idx| ty::trait_method(tcx, trait_did, idx).def_id)
4884 /// Creates a hash of the type `t` which will be the same no matter what crate
4885 /// context it's calculated within. This is used by the `type_id` intrinsic.
4886 pub fn hash_crate_independent(tcx: ctxt, t: t, svh: &Svh) -> u64 {
4887 let mut state = sip::SipState::new();
4888 macro_rules! byte( ($b:expr) => { ($b as u8).hash(&mut state) } );
4889 macro_rules! hash( ($e:expr) => { $e.hash(&mut state) } );
4891 let region = |_state: &mut sip::SipState, r: Region| {
4901 tcx.sess.bug("non-static region found when hashing a type")
4905 let vstore = |state: &mut sip::SipState, v: vstore| {
4907 vstore_fixed(_) => 0u8.hash(state),
4908 vstore_uniq => 1u8.hash(state),
4909 vstore_slice(r) => {
4915 let did = |state: &mut sip::SipState, did: DefId| {
4916 let h = if ast_util::is_local(did) {
4919 tcx.sess.cstore.get_crate_hash(did.krate)
4921 h.as_str().hash(state);
4922 did.node.hash(state);
4924 let mt = |state: &mut sip::SipState, mt: mt| {
4925 mt.mutbl.hash(state);
4927 ty::walk_ty(t, |t| {
4928 match ty::get(t).sty {
4931 ty_bool => byte!(2),
4932 ty_char => byte!(3),
4962 vstore(&mut state, v);
4970 region(&mut state, r);
4973 ty_bare_fn(ref b) => {
4978 ty_closure(ref c) => {
4984 region(&mut state, c.region);
4986 ty_trait(d, _, store, m, bounds) => {
4990 UniqTraitStore => byte!(0),
4991 RegionTraitStore(r) => {
4993 region(&mut state, r);
4999 ty_struct(d, _) => {
5003 ty_tup(ref inner) => {
5010 did(&mut state, p.def_id);
5016 ty_infer(_) => unreachable!(),
5017 ty_err => byte!(23),
5018 ty_unboxed_vec(m) => {
5029 pub fn to_str(self) -> &'static str {
5032 Contravariant => "-",
5039 pub fn construct_parameter_environment(
5041 self_bound: Option<@TraitRef>,
5042 item_type_params: &[TypeParameterDef],
5043 method_type_params: &[TypeParameterDef],
5044 item_region_params: &[RegionParameterDef],
5045 free_id: ast::NodeId)
5046 -> ParameterEnvironment
5048 /*! See `ParameterEnvironment` struct def'n for details */
5051 // Construct the free substs.
5055 let self_ty = self_bound.map(|t| ty::mk_self(tcx, t.def_id));
5058 let num_item_type_params = item_type_params.len();
5059 let num_method_type_params = method_type_params.len();
5060 let num_type_params = num_item_type_params + num_method_type_params;
5061 let type_params = vec::from_fn(num_type_params, |i| {
5062 let def_id = if i < num_item_type_params {
5063 item_type_params[i].def_id
5065 method_type_params[i - num_item_type_params].def_id
5068 ty::mk_param(tcx, i, def_id)
5071 // map bound 'a => free 'a
5072 let region_params = item_region_params.iter().
5073 map(|r| ty::ReFree(ty::FreeRegion {
5075 bound_region: ty::BrNamed(r.def_id, r.ident)})).
5078 let free_substs = substs {
5081 regions: ty::NonerasedRegions(region_params)
5085 // Compute the bounds on Self and the type parameters.
5088 let self_bound_substd = self_bound.map(|b| b.subst(tcx, &free_substs));
5089 let type_param_bounds_substd = vec::from_fn(num_type_params, |i| {
5090 if i < num_item_type_params {
5091 (*item_type_params[i].bounds).subst(tcx, &free_substs)
5093 let j = i - num_item_type_params;
5094 (*method_type_params[j].bounds).subst(tcx, &free_substs)
5098 ty::ParameterEnvironment {
5099 free_substs: free_substs,
5100 self_param_bound: self_bound_substd,
5101 type_param_bounds: type_param_bounds_substd,
5106 pub fn empty() -> substs {
5110 regions: NonerasedRegions(opt_vec::Empty)
5116 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
5118 ast::MutMutable => MutBorrow,
5119 ast::MutImmutable => ImmBorrow,
5123 pub fn to_user_str(&self) -> &'static str {
5125 MutBorrow => "mutable",
5126 ImmBorrow => "immutable",
5127 UniqueImmBorrow => "uniquely immutable",
5131 pub fn to_short_str(&self) -> &'static str {
5135 UniqueImmBorrow => "own",