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)]
14 use driver::session::Session;
15 use metadata::csearch;
16 use middle::const_eval;
17 use middle::lang_items::{ExchangeHeapLangItem, OpaqueStructLangItem};
18 use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem};
21 use middle::resolve_lifetime;
23 use middle::subst::Subst;
25 use middle::typeck::{MethodCall, MethodCallee, MethodMap};
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};
33 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet, FnvHashMap};
36 use std::cell::{Cell, RefCell};
40 use std::hash::{Hash, sip};
44 use collections::{HashMap, HashSet};
46 use syntax::ast_util::{is_local, lit_is_str};
49 use syntax::attr::AttrMetaMethods;
50 use syntax::codemap::Span;
51 use syntax::parse::token;
52 use syntax::parse::token::InternedString;
53 use syntax::{ast, ast_map};
54 use syntax::owned_slice::OwnedSlice;
55 use syntax::abi::AbiSet;
57 use collections::enum_set::{EnumSet, CLike};
61 pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0;
65 #[deriving(Eq, TotalEq, Hash)]
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,
124 methods: Vec<@Method> }
126 #[deriving(Clone, Eq, TotalEq, Hash)]
129 mutbl: ast::Mutability,
132 #[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash, Show)]
139 #[deriving(Clone, Eq, TotalEq, Hash, Encodable, Decodable, Show)]
140 pub enum TraitStore {
141 UniqTraitStore, // ~Trait
142 RegionTraitStore(Region), // &Trait
145 pub struct field_ty {
148 vis: ast::Visibility,
151 // Contains information needed to resolve types and (in the future) look up
152 // the types of AST nodes.
153 #[deriving(Eq, TotalEq, Hash)]
154 pub struct creader_cache_key {
160 pub type creader_cache = RefCell<HashMap<creader_cache_key, t>>;
162 pub struct intern_key {
166 // NB: Do not replace this with #[deriving(Eq)]. The automatically-derived
167 // implementation will not recurse through sty and you will get stack
169 impl cmp::Eq for intern_key {
170 fn eq(&self, other: &intern_key) -> bool {
172 *self.sty == *other.sty
175 fn ne(&self, other: &intern_key) -> bool {
180 impl TotalEq for intern_key {}
182 impl<W:Writer> Hash<W> for intern_key {
183 fn hash(&self, s: &mut W) {
184 unsafe { (*self.sty).hash(s) }
188 pub enum ast_ty_to_ty_cache_entry {
189 atttce_unresolved, /* not resolved yet */
190 atttce_resolved(t) /* resolved to a type, irrespective of region */
193 #[deriving(Clone, Eq, Decodable, Encodable)]
194 pub struct ItemVariances {
195 self_param: Option<Variance>,
196 type_params: OwnedSlice<Variance>,
197 region_params: OwnedSlice<Variance>
200 #[deriving(Clone, Eq, Decodable, Encodable, Show)]
202 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
203 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
204 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
205 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
208 pub enum AutoAdjustment {
209 AutoAddEnv(ty::Region, ast::Sigil),
210 AutoDerefRef(AutoDerefRef),
211 AutoObject(ast::Sigil, Option<ty::Region>,
214 ast::DefId, /* Trait ID */
215 ty::substs /* Trait substitutions */)
218 #[deriving(Decodable, Encodable)]
219 pub struct AutoDerefRef {
221 autoref: Option<AutoRef>
224 #[deriving(Decodable, Encodable, Eq, Show)]
226 /// Convert from T to &T
227 AutoPtr(Region, ast::Mutability),
229 /// Convert from ~[]/&[] to &[] (or str)
230 AutoBorrowVec(Region, ast::Mutability),
232 /// Convert from ~[]/&[] to &&[] (or str)
233 AutoBorrowVecRef(Region, ast::Mutability),
235 /// Convert from @fn()/~fn()/|| to ||
236 AutoBorrowFn(Region),
238 /// Convert from T to *T
239 AutoUnsafe(ast::Mutability),
241 /// Convert from ~Trait/&Trait to &Trait
242 AutoBorrowObj(Region, ast::Mutability),
245 /// The data structure to keep track of all the information that typechecker
246 /// generates so that so that it can be reused and doesn't have to be redone
249 // Specifically use a speedy hash algorithm for this hash map, it's used
251 interner: RefCell<FnvHashMap<intern_key, ~t_box_>>,
254 def_map: resolve::DefMap,
256 named_region_map: resolve_lifetime::NamedRegionMap,
258 region_maps: middle::region::RegionMaps,
260 // Stores the types for various nodes in the AST. Note that this table
261 // is not guaranteed to be populated until after typeck. See
262 // typeck::check::fn_ctxt for details.
263 node_types: node_type_table,
265 // Stores the type parameters which were substituted to obtain the type
266 // of this node. This only applies to nodes that refer to entities
267 // parameterized by type parameters, such as generic fns, types, or
269 node_type_substs: RefCell<NodeMap<Vec<t>>>,
271 // Maps from a method to the method "descriptor"
272 methods: RefCell<DefIdMap<@Method>>,
274 // Maps from a trait def-id to a list of the def-ids of its methods
275 trait_method_def_ids: RefCell<DefIdMap<@Vec<DefId> >>,
277 // A cache for the trait_methods() routine
278 trait_methods_cache: RefCell<DefIdMap<@Vec<@Method> >>,
280 impl_trait_cache: RefCell<DefIdMap<Option<@ty::TraitRef>>>,
282 trait_refs: RefCell<NodeMap<@TraitRef>>,
283 trait_defs: RefCell<DefIdMap<@TraitDef>>,
286 intrinsic_defs: RefCell<DefIdMap<t>>,
287 freevars: RefCell<freevars::freevar_map>,
289 rcache: creader_cache,
290 short_names_cache: RefCell<HashMap<t, ~str>>,
291 needs_unwind_cleanup_cache: RefCell<HashMap<t, bool>>,
292 tc_cache: RefCell<HashMap<uint, TypeContents>>,
293 ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry>>,
294 enum_var_cache: RefCell<DefIdMap<@Vec<@VariantInfo> >>,
295 ty_param_defs: RefCell<NodeMap<TypeParameterDef>>,
296 adjustments: RefCell<NodeMap<@AutoAdjustment>>,
297 normalized_cache: RefCell<HashMap<t, t>>,
298 lang_items: @middle::lang_items::LanguageItems,
299 // A mapping of fake provided method def_ids to the default implementation
300 provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
301 supertraits: RefCell<DefIdMap<@Vec<@TraitRef> >>,
303 // Maps from def-id of a type or region parameter to its
304 // (inferred) variance.
305 item_variance_map: RefCell<DefIdMap<@ItemVariances>>,
307 // A mapping from the def ID of an enum or struct type to the def ID
308 // of the method that implements its destructor. If the type is not
309 // present in this map, it does not have a destructor. This map is
310 // populated during the coherence phase of typechecking.
311 destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
313 // A method will be in this list if and only if it is a destructor.
314 destructors: RefCell<DefIdSet>,
316 // Maps a trait onto a list of impls of that trait.
317 trait_impls: RefCell<DefIdMap<@RefCell<Vec<@Impl> >>>,
319 // Maps a def_id of a type to a list of its inherent impls.
320 // Contains implementations of methods that are inherent to a type.
321 // Methods in these implementations don't need to be exported.
322 inherent_impls: RefCell<DefIdMap<@RefCell<Vec<@Impl> >>>,
324 // Maps a def_id of an impl to an Impl structure.
325 // Note that this contains all of the impls that we know about,
326 // including ones in other crates. It's not clear that this is the best
328 impls: RefCell<DefIdMap<@Impl>>,
330 // Set of used unsafe nodes (functions or blocks). Unsafe nodes not
331 // present in this set can be warned about.
332 used_unsafe: RefCell<NodeSet>,
334 // Set of nodes which mark locals as mutable which end up getting used at
335 // some point. Local variable definitions not in this set can be warned
337 used_mut_nodes: RefCell<NodeSet>,
339 // vtable resolution information for impl declarations
340 impl_vtables: typeck::impl_vtable_map,
342 // The set of external nominal types whose implementations have been read.
343 // This is used for lazy resolution of methods.
344 populated_external_types: RefCell<DefIdSet>,
346 // The set of external traits whose implementations have been read. This
347 // is used for lazy resolution of traits.
348 populated_external_traits: RefCell<DefIdSet>,
351 upvar_borrow_map: RefCell<UpvarBorrowMap>,
353 // These two caches are used by const_eval when decoding external statics
354 // and variants that are found.
355 extern_const_statics: RefCell<DefIdMap<Option<@ast::Expr>>>,
356 extern_const_variants: RefCell<DefIdMap<Option<@ast::Expr>>>,
367 // a meta-flag: subst may be required if the type has parameters, a self
368 // type, or references bound regions
369 needs_subst = 1 | 2 | 8
372 pub type t_box = &'static t_box_;
380 // To reduce refcounting cost, we're representing types as unsafe pointers
381 // throughout the compiler. These are simply casted t_box values. Use ty::get
382 // to cast them back to a box. (Without the cast, compiler performance suffers
383 // ~15%.) This does mean that a t value relies on the ctxt to keep its box
384 // alive, and using ty::get is unsafe when the ctxt is no longer alive.
387 #[allow(raw_pointer_deriving)]
388 #[deriving(Clone, Eq, TotalEq, Hash)]
389 pub struct t { priv inner: *t_opaque }
391 impl fmt::Show for t {
392 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
393 f.buf.write_str("*t_opaque")
397 pub fn get(t: t) -> t_box {
399 let t2: t_box = cast::transmute(t);
404 pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
405 (tb.flags & (flag as uint)) != 0u
407 pub fn type_has_params(t: t) -> bool {
408 tbox_has_flag(get(t), has_params)
410 pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
411 pub fn type_needs_infer(t: t) -> bool {
412 tbox_has_flag(get(t), needs_infer)
414 pub fn type_has_regions(t: t) -> bool {
415 tbox_has_flag(get(t), has_regions)
417 pub fn type_id(t: t) -> uint { get(t).id }
419 #[deriving(Clone, Eq, TotalEq, Hash)]
420 pub struct BareFnTy {
426 #[deriving(Clone, Eq, TotalEq, Hash)]
427 pub struct ClosureTy {
430 onceness: ast::Onceness,
432 bounds: BuiltinBounds,
437 * Signature of a function type, which I have arbitrarily
438 * decided to use to refer to the input/output types.
440 * - `binder_id` is the node id where this fn type appeared;
441 * it is used to identify all the bound regions appearing
442 * in the input/output types that are bound by this fn type
443 * (vs some enclosing or enclosed fn type)
444 * - `inputs` is the list of arguments and their modes.
445 * - `output` is the return type.
446 * - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
448 #[deriving(Clone, Eq, TotalEq, Hash)]
450 binder_id: ast::NodeId,
456 #[deriving(Clone, Eq, TotalEq, Hash)]
457 pub struct param_ty {
462 /// Representation of regions:
463 #[deriving(Clone, Eq, TotalEq, Hash, Encodable, Decodable, Show)]
465 // Region bound in a type or fn declaration which will be
466 // substituted 'early' -- that is, at the same time when type
467 // parameters are substituted.
468 ReEarlyBound(/* param id */ ast::NodeId, /*index*/ uint, ast::Name),
470 // Region bound in a function scope, which will be substituted when the
471 // function is called. The first argument must be the `binder_id` of
472 // some enclosing function signature.
473 ReLateBound(/* binder_id */ ast::NodeId, BoundRegion),
475 /// When checking a function body, the types of all arguments and so forth
476 /// that refer to bound region parameters are modified to refer to free
477 /// region parameters.
480 /// A concrete region naming some expression within the current function.
483 /// Static data that has an "infinite" lifetime. Top in the region lattice.
486 /// A region variable. Should not exist after typeck.
487 ReInfer(InferRegion),
489 /// Empty lifetime is for data that is never accessed.
490 /// Bottom in the region lattice. We treat ReEmpty somewhat
491 /// specially; at least right now, we do not generate instances of
492 /// it during the GLB computations, but rather
493 /// generate an error instead. This is to improve error messages.
494 /// The only way to get an instance of ReEmpty is to have a region
495 /// variable with no constraints.
500 * Upvars do not get their own node-id. Instead, we use the pair of
501 * the original var id (that is, the root variable that is referenced
502 * by the upvar) and the id of the closure expression.
504 #[deriving(Clone, Eq, TotalEq, Hash)]
507 closure_expr_id: ast::NodeId,
510 #[deriving(Clone, Eq, TotalEq, Hash)]
511 pub enum BorrowKind {
512 /// Data must be immutable and is aliasable.
515 /// Data must be immutable but not aliasable. This kind of borrow
516 /// cannot currently be expressed by the user and is used only in
517 /// implicit closure bindings. It is needed when you the closure
518 /// is borrowing or mutating a mutable referent, e.g.:
520 /// let x: &mut int = ...;
521 /// let y = || *x += 5;
523 /// If we were to try to translate this closure into a more explicit
524 /// form, we'd encounter an error with the code as written:
526 /// struct Env { x: & &mut int }
527 /// let x: &mut int = ...;
528 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
529 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
531 /// This is then illegal because you cannot mutate a `&mut` found
532 /// in an aliasable location. To solve, you'd have to translate with
533 /// an `&mut` borrow:
535 /// struct Env { x: & &mut int }
536 /// let x: &mut int = ...;
537 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
538 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
540 /// Now the assignment to `**env.x` is legal, but creating a
541 /// mutable pointer to `x` is not because `x` is not mutable. We
542 /// could fix this by declaring `x` as `let mut x`. This is ok in
543 /// user code, if awkward, but extra weird for closures, since the
544 /// borrow is hidden.
546 /// So we introduce a "unique imm" borrow -- the referent is
547 /// immutable, but not aliasable. This solves the problem. For
548 /// simplicity, we don't give users the way to express this
549 /// borrow, it's just used when translating closures.
552 /// Data is mutable and not aliasable.
557 * Information describing the borrowing of an upvar. This is computed
558 * during `typeck`, specifically by `regionck`. The general idea is
559 * that the compiler analyses treat closures like:
561 * let closure: &'e fn() = || {
562 * x = 1; // upvar x is assigned to
563 * use(y); // upvar y is read
564 * foo(&z); // upvar z is borrowed immutably
567 * as if they were "desugared" to something loosely like:
569 * struct Vars<'x,'y,'z> { x: &'x mut int,
572 * let closure: &'e fn() = {
578 * let env: &'e mut Vars<'x,'y,'z> = &mut Vars { x: &'x mut x,
584 * This is basically what happens at runtime. The closure is basically
585 * an existentially quantified version of the `(env, f)` pair.
587 * This data structure indicates the region and mutability of a single
588 * one of the `x...z` borrows.
590 * It may not be obvious why each borrowed variable gets its own
591 * lifetime (in the desugared version of the example, these are indicated
592 * by the lifetime parameters `'x`, `'y`, and `'z` in the `Vars` definition).
593 * Each such lifetime must encompass the lifetime `'e` of the closure itself,
594 * but need not be identical to it. The reason that this makes sense:
596 * - Callers are only permitted to invoke the closure, and hence to
597 * use the pointers, within the lifetime `'e`, so clearly `'e` must
598 * be a sublifetime of `'x...'z`.
599 * - The closure creator knows which upvars were borrowed by the closure
600 * and thus `x...z` will be reserved for `'x...'z` respectively.
601 * - Through mutation, the borrowed upvars can actually escape
602 * the closure, so sometimes it is necessary for them to be larger
603 * than the closure lifetime itself.
605 #[deriving(Eq, Clone)]
606 pub struct UpvarBorrow {
611 pub type UpvarBorrowMap = HashMap<UpvarId, UpvarBorrow>;
614 pub fn is_bound(&self) -> bool {
616 &ty::ReEarlyBound(..) => true,
617 &ty::ReLateBound(..) => true,
623 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd, Hash, Encodable, Decodable, Show)]
624 pub struct FreeRegion {
626 bound_region: BoundRegion
629 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd, Hash, Encodable, Decodable, Show)]
630 pub enum BoundRegion {
631 /// An anonymous region parameter for a given fn (&T)
634 /// Named region parameters for functions (a in &'a T)
636 /// The def-id is needed to distinguish free regions in
637 /// the event of shadowing.
638 BrNamed(ast::DefId, ast::Name),
640 /// Fresh bound identifiers created during GLB computations.
645 * Represents the values to use when substituting lifetime parameters.
646 * If the value is `ErasedRegions`, then this subst is occurring during
647 * trans, and all region parameters will be replaced with `ty::ReStatic`. */
648 #[deriving(Clone, Eq, TotalEq, Hash)]
649 pub enum RegionSubsts {
651 NonerasedRegions(OwnedSlice<ty::Region>)
655 * The type substs represents the kinds of things that can be substituted to
656 * convert a polytype into a monotype. Note however that substituting bound
657 * regions other than `self` is done through a different mechanism:
659 * - `tps` represents the type parameters in scope. They are indexed
660 * according to the order in which they were declared.
662 * - `self_r` indicates the region parameter `self` that is present on nominal
663 * types (enums, structs) declared as having a region parameter. `self_r`
664 * should always be none for types that are not region-parameterized and
665 * Some(_) for types that are. The only bound region parameter that should
666 * appear within a region-parameterized type is `self`.
668 * - `self_ty` is the type to which `self` should be remapped, if any. The
669 * `self` type is rather funny in that it can only appear on traits and is
670 * always substituted away to the implementing type for a trait. */
671 #[deriving(Clone, Eq, TotalEq, Hash)]
673 self_ty: Option<ty::t>,
675 regions: RegionSubsts,
683 macro_rules! def_prim_ty(
684 ($name:ident, $sty:expr, $id:expr) => (
685 pub static $name: t_box_ = t_box_ {
693 def_prim_ty!(TY_NIL, super::ty_nil, 0)
694 def_prim_ty!(TY_BOOL, super::ty_bool, 1)
695 def_prim_ty!(TY_CHAR, super::ty_char, 2)
696 def_prim_ty!(TY_INT, super::ty_int(ast::TyI), 3)
697 def_prim_ty!(TY_I8, super::ty_int(ast::TyI8), 4)
698 def_prim_ty!(TY_I16, super::ty_int(ast::TyI16), 5)
699 def_prim_ty!(TY_I32, super::ty_int(ast::TyI32), 6)
700 def_prim_ty!(TY_I64, super::ty_int(ast::TyI64), 7)
701 def_prim_ty!(TY_UINT, super::ty_uint(ast::TyU), 8)
702 def_prim_ty!(TY_U8, super::ty_uint(ast::TyU8), 9)
703 def_prim_ty!(TY_U16, super::ty_uint(ast::TyU16), 10)
704 def_prim_ty!(TY_U32, super::ty_uint(ast::TyU32), 11)
705 def_prim_ty!(TY_U64, super::ty_uint(ast::TyU64), 12)
706 def_prim_ty!(TY_F32, super::ty_float(ast::TyF32), 14)
707 def_prim_ty!(TY_F64, super::ty_float(ast::TyF64), 15)
709 pub static TY_BOT: t_box_ = t_box_ {
712 flags: super::has_ty_bot as uint,
715 pub static TY_ERR: t_box_ = t_box_ {
718 flags: super::has_ty_err as uint,
721 pub static LAST_PRIMITIVE_ID: uint = 18;
724 // NB: If you change this, you'll probably want to change the corresponding
725 // AST structure in libsyntax/ast.rs as well.
726 #[deriving(Clone, Eq, TotalEq, Hash)]
733 ty_uint(ast::UintTy),
734 ty_float(ast::FloatTy),
736 ty_enum(DefId, substs),
742 ty_bare_fn(BareFnTy),
743 ty_closure(~ClosureTy),
745 ty_struct(DefId, substs),
748 ty_param(param_ty), // type parameter
749 ty_self(DefId), /* special, implicit `self` type parameter;
750 * def_id is the id of the trait */
752 ty_infer(InferTy), // something used only during inference/typeck
753 ty_err, // Also only used during inference/typeck, to represent
754 // the type of an erroneous expression (helps cut down
755 // on non-useful type error messages)
757 // "Fake" types, used for trans purposes
761 #[deriving(Clone, Eq, TotalEq, Hash)]
766 mutability: ast::Mutability,
767 bounds: BuiltinBounds
770 #[deriving(Eq, TotalEq, Hash)]
771 pub struct TraitRef {
776 #[deriving(Clone, Eq)]
777 pub enum IntVarValue {
779 UintType(ast::UintTy),
782 #[deriving(Clone, Show)]
783 pub enum terr_vstore_kind {
790 #[deriving(Clone, Show)]
791 pub struct expected_found<T> {
796 // Data structures used in type unification
797 #[deriving(Clone, Show)]
800 terr_purity_mismatch(expected_found<Purity>),
801 terr_onceness_mismatch(expected_found<Onceness>),
802 terr_abi_mismatch(expected_found<AbiSet>),
804 terr_sigil_mismatch(expected_found<ast::Sigil>),
809 terr_tuple_size(expected_found<uint>),
810 terr_ty_param_size(expected_found<uint>),
811 terr_record_size(expected_found<uint>),
812 terr_record_mutability,
813 terr_record_fields(expected_found<Ident>),
815 terr_regions_does_not_outlive(Region, Region),
816 terr_regions_not_same(Region, Region),
817 terr_regions_no_overlap(Region, Region),
818 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
819 terr_regions_overly_polymorphic(BoundRegion, Region),
820 terr_vstores_differ(terr_vstore_kind, expected_found<vstore>),
821 terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
822 terr_in_field(@type_err, ast::Ident),
823 terr_sorts(expected_found<t>),
824 terr_integer_as_char,
825 terr_int_mismatch(expected_found<IntVarValue>),
826 terr_float_mismatch(expected_found<ast::FloatTy>),
827 terr_traits(expected_found<ast::DefId>),
828 terr_builtin_bounds(expected_found<BuiltinBounds>),
829 terr_variadic_mismatch(expected_found<bool>)
832 #[deriving(Eq, TotalEq, Hash)]
833 pub struct ParamBounds {
834 builtin_bounds: BuiltinBounds,
835 trait_bounds: Vec<@TraitRef> }
837 pub type BuiltinBounds = EnumSet<BuiltinBound>;
839 #[deriving(Clone, Encodable, Eq, TotalEq, Decodable, Hash, Show)]
841 pub enum BuiltinBound {
849 pub fn EmptyBuiltinBounds() -> BuiltinBounds {
853 pub fn AllBuiltinBounds() -> BuiltinBounds {
854 let mut set = EnumSet::empty();
855 set.add(BoundStatic);
862 impl CLike for BuiltinBound {
863 fn to_uint(&self) -> uint {
866 fn from_uint(v: uint) -> BuiltinBound {
867 unsafe { cast::transmute(v) }
871 #[deriving(Clone, Eq, TotalEq, Hash)]
872 pub struct TyVid(uint);
874 #[deriving(Clone, Eq, TotalEq, Hash)]
875 pub struct IntVid(uint);
877 #[deriving(Clone, Eq, TotalEq, Hash)]
878 pub struct FloatVid(uint);
880 #[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
881 pub struct RegionVid {
885 #[deriving(Clone, Eq, TotalEq, Hash)]
892 #[deriving(Clone, Encodable, Decodable, TotalEq, Hash, Show)]
893 pub enum InferRegion {
895 ReSkolemized(uint, BoundRegion)
898 impl cmp::Eq for InferRegion {
899 fn eq(&self, other: &InferRegion) -> bool {
900 match ((*self), *other) {
901 (ReVar(rva), ReVar(rvb)) => {
904 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
910 fn ne(&self, other: &InferRegion) -> bool {
911 !((*self) == (*other))
916 fn to_uint(&self) -> uint;
920 fn to_uint(&self) -> uint { let TyVid(v) = *self; v }
923 impl fmt::Show for TyVid {
924 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
925 write!(f.buf, "<generic \\#{}>", self.to_uint())
929 impl Vid for IntVid {
930 fn to_uint(&self) -> uint { let IntVid(v) = *self; v }
933 impl fmt::Show for IntVid {
934 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
935 write!(f.buf, "<generic integer \\#{}>", self.to_uint())
939 impl Vid for FloatVid {
940 fn to_uint(&self) -> uint { let FloatVid(v) = *self; v }
943 impl fmt::Show for FloatVid {
944 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
945 write!(f.buf, "<generic float \\#{}>", self.to_uint())
949 impl Vid for RegionVid {
950 fn to_uint(&self) -> uint { self.id }
953 impl fmt::Show for RegionVid {
954 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
959 impl fmt::Show for FnSig {
960 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
961 // grr, without tcx not much we can do.
962 write!(f.buf, "(...)")
966 impl fmt::Show for InferTy {
967 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
969 TyVar(ref v) => v.fmt(f),
970 IntVar(ref v) => v.fmt(f),
971 FloatVar(ref v) => v.fmt(f),
976 impl fmt::Show for IntVarValue {
977 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
979 IntType(ref v) => v.fmt(f),
980 UintType(ref v) => v.fmt(f),
986 pub struct TypeParameterDef {
989 bounds: @ParamBounds,
990 default: Option<ty::t>
993 #[deriving(Encodable, Decodable, Clone)]
994 pub struct RegionParameterDef {
999 /// Information about the type/lifetime parameters associated with an item.
1000 /// Analogous to ast::Generics.
1002 pub struct Generics {
1003 /// List of type parameters declared on the item.
1004 type_param_defs: Rc<Vec<TypeParameterDef> >,
1006 /// List of region parameters declared on the item.
1007 /// For a fn or method, only includes *early-bound* lifetimes.
1008 region_param_defs: Rc<Vec<RegionParameterDef> >,
1012 pub fn has_type_params(&self) -> bool {
1013 !self.type_param_defs.is_empty()
1015 pub fn type_param_defs<'a>(&'a self) -> &'a [TypeParameterDef] {
1016 self.type_param_defs.as_slice()
1018 pub fn region_param_defs<'a>(&'a self) -> &'a [RegionParameterDef] {
1019 self.region_param_defs.as_slice()
1023 /// When type checking, we use the `ParameterEnvironment` to track
1024 /// details about the type/lifetime parameters that are in scope.
1025 /// It primarily stores the bounds information.
1027 /// Note: This information might seem to be redundant with the data in
1028 /// `tcx.ty_param_defs`, but it is not. That table contains the
1029 /// parameter definitions from an "outside" perspective, but this
1030 /// struct will contain the bounds for a parameter as seen from inside
1031 /// the function body. Currently the only real distinction is that
1032 /// bound lifetime parameters are replaced with free ones, but in the
1033 /// future I hope to refine the representation of types so as to make
1034 /// more distinctions clearer.
1035 pub struct ParameterEnvironment {
1036 /// A substitution that can be applied to move from
1037 /// the "outer" view of a type or method to the "inner" view.
1038 /// In general, this means converting from bound parameters to
1039 /// free parameters. Since we currently represent bound/free type
1040 /// parameters in the same way, this only has an affect on regions.
1041 free_substs: ty::substs,
1043 /// Bound on the Self parameter
1044 self_param_bound: Option<@TraitRef>,
1046 /// Bounds on each numbered type parameter
1047 type_param_bounds: Vec<ParamBounds> ,
1052 /// - `bounds`: The list of bounds for each type parameter. The length of the
1053 /// list also tells you how many type parameters there are.
1055 /// - `rp`: true if the type is region-parameterized. Types can have at
1056 /// most one region parameter, always called `&self`.
1058 /// - `ty`: the base type. May have reference to the (unsubstituted) bound
1059 /// region `&self` or to (unsubstituted) ty_param types
1061 pub struct ty_param_bounds_and_ty {
1066 /// As `ty_param_bounds_and_ty` but for a trait ref.
1067 pub struct TraitDef {
1069 bounds: BuiltinBounds,
1070 trait_ref: @ty::TraitRef,
1073 pub struct ty_param_substs_and_ty {
1078 pub type type_cache = RefCell<DefIdMap<ty_param_bounds_and_ty>>;
1080 pub type node_type_table = RefCell<HashMap<uint,t>>;
1082 pub fn mk_ctxt(s: Session,
1083 dm: resolve::DefMap,
1084 named_region_map: resolve_lifetime::NamedRegionMap,
1086 freevars: freevars::freevar_map,
1087 region_maps: middle::region::RegionMaps,
1088 lang_items: @middle::lang_items::LanguageItems)
1091 named_region_map: named_region_map,
1092 item_variance_map: RefCell::new(DefIdMap::new()),
1093 interner: RefCell::new(FnvHashMap::new()),
1094 next_id: Cell::new(primitives::LAST_PRIMITIVE_ID),
1097 region_maps: region_maps,
1098 node_types: RefCell::new(HashMap::new()),
1099 node_type_substs: RefCell::new(NodeMap::new()),
1100 trait_refs: RefCell::new(NodeMap::new()),
1101 trait_defs: RefCell::new(DefIdMap::new()),
1103 intrinsic_defs: RefCell::new(DefIdMap::new()),
1104 freevars: RefCell::new(freevars),
1105 tcache: RefCell::new(DefIdMap::new()),
1106 rcache: RefCell::new(HashMap::new()),
1107 short_names_cache: RefCell::new(HashMap::new()),
1108 needs_unwind_cleanup_cache: RefCell::new(HashMap::new()),
1109 tc_cache: RefCell::new(HashMap::new()),
1110 ast_ty_to_ty_cache: RefCell::new(NodeMap::new()),
1111 enum_var_cache: RefCell::new(DefIdMap::new()),
1112 methods: RefCell::new(DefIdMap::new()),
1113 trait_method_def_ids: RefCell::new(DefIdMap::new()),
1114 trait_methods_cache: RefCell::new(DefIdMap::new()),
1115 impl_trait_cache: RefCell::new(DefIdMap::new()),
1116 ty_param_defs: RefCell::new(NodeMap::new()),
1117 adjustments: RefCell::new(NodeMap::new()),
1118 normalized_cache: RefCell::new(HashMap::new()),
1119 lang_items: lang_items,
1120 provided_method_sources: RefCell::new(DefIdMap::new()),
1121 supertraits: RefCell::new(DefIdMap::new()),
1122 destructor_for_type: RefCell::new(DefIdMap::new()),
1123 destructors: RefCell::new(DefIdSet::new()),
1124 trait_impls: RefCell::new(DefIdMap::new()),
1125 inherent_impls: RefCell::new(DefIdMap::new()),
1126 impls: RefCell::new(DefIdMap::new()),
1127 used_unsafe: RefCell::new(NodeSet::new()),
1128 used_mut_nodes: RefCell::new(NodeSet::new()),
1129 impl_vtables: RefCell::new(DefIdMap::new()),
1130 populated_external_types: RefCell::new(DefIdSet::new()),
1131 populated_external_traits: RefCell::new(DefIdSet::new()),
1132 upvar_borrow_map: RefCell::new(HashMap::new()),
1133 extern_const_statics: RefCell::new(DefIdMap::new()),
1134 extern_const_variants: RefCell::new(DefIdMap::new()),
1138 // Type constructors
1140 // Interns a type/name combination, stores the resulting box in cx.interner,
1141 // and returns the box as cast to an unsafe ptr (see comments for t above).
1142 pub fn mk_t(cx: &ctxt, st: sty) -> t {
1143 // Check for primitive types.
1145 ty_nil => return mk_nil(),
1146 ty_err => return mk_err(),
1147 ty_bool => return mk_bool(),
1148 ty_int(i) => return mk_mach_int(i),
1149 ty_uint(u) => return mk_mach_uint(u),
1150 ty_float(f) => return mk_mach_float(f),
1151 ty_char => return mk_char(),
1152 ty_bot => return mk_bot(),
1156 let key = intern_key { sty: &st };
1158 match cx.interner.borrow().find(&key) {
1159 Some(t) => unsafe { return cast::transmute(&t.sty); },
1164 fn rflags(r: Region) -> uint {
1165 (has_regions as uint) | {
1167 ty::ReInfer(_) => needs_infer as uint,
1172 fn sflags(substs: &substs) -> uint {
1174 for tt in substs.tps.iter() { f |= get(*tt).flags; }
1175 match substs.regions {
1177 NonerasedRegions(ref regions) => {
1178 for r in regions.iter() {
1186 &ty_str(vstore_slice(r)) => {
1189 &ty_vec(ref mt, vstore_slice(r)) => {
1191 flags |= get(mt.ty).flags;
1193 &ty_nil | &ty_bool | &ty_char | &ty_int(_) | &ty_float(_) | &ty_uint(_) |
1195 // You might think that we could just return ty_err for
1196 // any type containing ty_err as a component, and get
1197 // rid of the has_ty_err flag -- likewise for ty_bot (with
1198 // the exception of function types that return bot).
1199 // But doing so caused sporadic memory corruption, and
1200 // neither I (tjc) nor nmatsakis could figure out why,
1201 // so we're doing it this way.
1202 &ty_bot => flags |= has_ty_bot as uint,
1203 &ty_err => flags |= has_ty_err as uint,
1204 &ty_param(_) => flags |= has_params as uint,
1205 &ty_infer(_) => flags |= needs_infer as uint,
1206 &ty_self(_) => flags |= has_self as uint,
1207 &ty_enum(_, ref substs) | &ty_struct(_, ref substs) |
1208 &ty_trait(~ty::TyTrait { ref substs, .. }) => {
1209 flags |= sflags(substs);
1211 ty_trait(~ty::TyTrait { store: RegionTraitStore(r), .. }) => {
1217 &ty_box(tt) | &ty_uniq(tt) => {
1218 flags |= get(tt).flags
1220 &ty_vec(ref m, _) | &ty_ptr(ref m) |
1221 &ty_unboxed_vec(ref m) => {
1222 flags |= get(m.ty).flags;
1224 &ty_rptr(r, ref m) => {
1226 flags |= get(m.ty).flags;
1228 &ty_tup(ref ts) => for tt in ts.iter() { flags |= get(*tt).flags; },
1229 &ty_bare_fn(ref f) => {
1230 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1231 flags |= get(f.sig.output).flags;
1232 // T -> _|_ is *not* _|_ !
1233 flags &= !(has_ty_bot as uint);
1235 &ty_closure(ref f) => {
1236 flags |= rflags(f.region);
1237 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1238 flags |= get(f.sig.output).flags;
1239 // T -> _|_ is *not* _|_ !
1240 flags &= !(has_ty_bot as uint);
1246 id: cx.next_id.get(),
1250 let sty_ptr = &t.sty as *sty;
1252 let key = intern_key {
1256 cx.interner.borrow_mut().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: Vec<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,
1418 inputs: Vec::from_slice(input_args),
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 let inner = ~TyTrait {
1438 mutability: mutability,
1441 mk_t(cx, ty_trait(inner))
1444 pub fn mk_struct(cx: &ctxt, struct_id: ast::DefId, substs: substs) -> t {
1445 // take a copy of substs so that we own the vectors inside
1446 mk_t(cx, ty_struct(struct_id, substs))
1449 pub fn mk_var(cx: &ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) }
1451 pub fn mk_int_var(cx: &ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) }
1453 pub fn mk_float_var(cx: &ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) }
1455 pub fn mk_infer(cx: &ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) }
1457 pub fn mk_self(cx: &ctxt, did: ast::DefId) -> t { mk_t(cx, ty_self(did)) }
1459 pub fn mk_param(cx: &ctxt, n: uint, k: DefId) -> t {
1460 mk_t(cx, ty_param(param_ty { idx: n, def_id: k }))
1463 pub fn walk_ty(ty: t, f: |t|) {
1464 maybe_walk_ty(ty, |t| { f(t); true });
1467 pub fn maybe_walk_ty(ty: t, f: |t| -> bool) {
1472 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) |
1473 ty_str(_) | ty_self(_) |
1474 ty_infer(_) | ty_param(_) | ty_err => {}
1475 ty_box(ty) | ty_uniq(ty) => maybe_walk_ty(ty, f),
1476 ty_vec(ref tm, _) | ty_unboxed_vec(ref tm) | ty_ptr(ref tm) |
1477 ty_rptr(_, ref tm) => {
1478 maybe_walk_ty(tm.ty, f);
1480 ty_enum(_, ref substs) | ty_struct(_, ref substs) |
1481 ty_trait(~TyTrait { ref substs, .. }) => {
1482 for subty in (*substs).tps.iter() { maybe_walk_ty(*subty, |x| f(x)); }
1484 ty_tup(ref ts) => { for tt in ts.iter() { maybe_walk_ty(*tt, |x| f(x)); } }
1485 ty_bare_fn(ref ft) => {
1486 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1487 maybe_walk_ty(ft.sig.output, f);
1489 ty_closure(ref ft) => {
1490 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1491 maybe_walk_ty(ft.sig.output, f);
1496 // Folds types from the bottom up.
1497 pub fn fold_ty(cx: &ctxt, t0: t, fldop: |t| -> t) -> t {
1498 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
1502 pub fn walk_regions_and_ty(cx: &ctxt, ty: t, fldr: |r: Region|, fldt: |t: t|)
1504 ty_fold::RegionFolder::general(cx,
1506 |t| { fldt(t); t }).fold_ty(ty)
1509 pub fn fold_regions(cx: &ctxt, ty: t, fldr: |r: Region| -> Region) -> t {
1510 ty_fold::RegionFolder::regions(cx, fldr).fold_ty(ty)
1513 // Substitute *only* type parameters. Used in trans where regions are erased.
1514 pub fn subst_tps(tcx: &ctxt, tps: &[t], self_ty_opt: Option<t>, typ: t) -> t {
1515 let mut subst = TpsSubst { tcx: tcx, self_ty_opt: self_ty_opt, tps: tps };
1516 return subst.fold_ty(typ);
1518 struct TpsSubst<'a> {
1520 self_ty_opt: Option<t>,
1524 impl<'a> TypeFolder for TpsSubst<'a> {
1525 fn tcx<'a>(&'a self) -> &'a ctxt { self.tcx }
1527 fn fold_ty(&mut self, t: ty::t) -> ty::t {
1528 if self.tps.len() == 0u && self.self_ty_opt.is_none() {
1532 let tb = ty::get(t);
1533 if self.self_ty_opt.is_none() && !tbox_has_flag(tb, has_params) {
1537 match ty::get(t).sty {
1543 match self.self_ty_opt {
1544 None => self.tcx.sess.bug("ty_self unexpected here"),
1545 Some(self_ty) => self_ty
1550 ty_fold::super_fold_ty(self, t)
1557 pub fn substs_is_noop(substs: &substs) -> bool {
1558 let regions_is_noop = match substs.regions {
1559 ErasedRegions => false, // may be used to canonicalize
1560 NonerasedRegions(ref regions) => regions.is_empty()
1563 substs.tps.len() == 0u &&
1565 substs.self_ty.is_none()
1568 pub fn substs_to_str(cx: &ctxt, substs: &substs) -> ~str {
1572 pub fn subst(cx: &ctxt,
1576 typ.subst(cx, substs)
1581 pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil }
1583 pub fn type_is_bot(ty: t) -> bool {
1584 (get(ty).flags & (has_ty_bot as uint)) != 0
1587 pub fn type_is_error(ty: t) -> bool {
1588 (get(ty).flags & (has_ty_err as uint)) != 0
1591 pub fn type_needs_subst(ty: t) -> bool {
1592 tbox_has_flag(get(ty), needs_subst)
1595 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
1596 tref.substs.self_ty.iter().any(|&t| type_is_error(t)) ||
1597 tref.substs.tps.iter().any(|&t| type_is_error(t))
1600 pub fn type_is_ty_var(ty: t) -> bool {
1602 ty_infer(TyVar(_)) => true,
1607 pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool }
1609 pub fn type_is_self(ty: t) -> bool {
1611 ty_self(..) => true,
1616 pub fn type_is_structural(ty: t) -> bool {
1618 ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) | ty_trait(..) |
1619 ty_vec(_, vstore_fixed(_)) | ty_str(vstore_fixed(_)) |
1620 ty_vec(_, vstore_slice(_)) | ty_str(vstore_slice(_))
1626 pub fn type_is_sequence(ty: t) -> bool {
1628 ty_str(_) | ty_vec(_, _) => true,
1633 pub fn type_is_simd(cx: &ctxt, ty: t) -> bool {
1635 ty_struct(did, _) => lookup_simd(cx, did),
1640 pub fn type_is_str(ty: t) -> bool {
1647 pub fn sequence_element_type(cx: &ctxt, ty: t) -> t {
1649 ty_str(_) => return mk_mach_uint(ast::TyU8),
1650 ty_vec(mt, _) | ty_unboxed_vec(mt) => return mt.ty,
1651 _ => cx.sess.bug("sequence_element_type called on non-sequence value"),
1655 pub fn simd_type(cx: &ctxt, ty: t) -> t {
1657 ty_struct(did, ref substs) => {
1658 let fields = lookup_struct_fields(cx, did);
1659 lookup_field_type(cx, did, fields.get(0).id, substs)
1661 _ => fail!("simd_type called on invalid type")
1665 pub fn simd_size(cx: &ctxt, ty: t) -> uint {
1667 ty_struct(did, _) => {
1668 let fields = lookup_struct_fields(cx, did);
1671 _ => fail!("simd_size called on invalid type")
1675 pub fn get_element_type(ty: t, i: uint) -> t {
1677 ty_tup(ref ts) => return *ts.get(i),
1678 _ => fail!("get_element_type called on invalid type")
1682 pub fn type_is_box(ty: t) -> bool {
1684 ty_box(_) => return true,
1689 pub fn type_is_boxed(ty: t) -> bool {
1696 pub fn type_is_region_ptr(ty: t) -> bool {
1698 ty_rptr(_, _) => true,
1703 pub fn type_is_slice(ty: t) -> bool {
1705 ty_vec(_, vstore_slice(_)) | ty_str(vstore_slice(_)) => true,
1710 pub fn type_is_unique_box(ty: t) -> bool {
1712 ty_uniq(_) => return true,
1717 pub fn type_is_unsafe_ptr(ty: t) -> bool {
1719 ty_ptr(_) => return true,
1724 pub fn type_is_vec(ty: t) -> bool {
1725 return match get(ty).sty {
1726 ty_vec(_, _) | ty_unboxed_vec(_) => true,
1732 pub fn type_is_unique(ty: t) -> bool {
1734 ty_uniq(_) | ty_vec(_, vstore_uniq) | ty_str(vstore_uniq) => true,
1740 A scalar type is one that denotes an atomic datum, with no sub-components.
1741 (A ty_ptr is scalar because it represents a non-managed pointer, so its
1742 contents are abstract to rustc.)
1744 pub fn type_is_scalar(ty: t) -> bool {
1746 ty_nil | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
1747 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
1748 ty_bare_fn(..) | ty_ptr(_) => true,
1753 pub fn type_needs_drop(cx: &ctxt, ty: t) -> bool {
1754 type_contents(cx, ty).needs_drop(cx)
1757 // Some things don't need cleanups during unwinding because the
1758 // task can free them all at once later. Currently only things
1759 // that only contain scalars and shared boxes can avoid unwind
1761 pub fn type_needs_unwind_cleanup(cx: &ctxt, ty: t) -> bool {
1762 match cx.needs_unwind_cleanup_cache.borrow().find(&ty) {
1763 Some(&result) => return result,
1767 let mut tycache = HashSet::new();
1768 let needs_unwind_cleanup =
1769 type_needs_unwind_cleanup_(cx, ty, &mut tycache, false);
1770 cx.needs_unwind_cleanup_cache.borrow_mut().insert(ty, needs_unwind_cleanup);
1771 return needs_unwind_cleanup;
1774 fn type_needs_unwind_cleanup_(cx: &ctxt, ty: t,
1775 tycache: &mut HashSet<t>,
1776 encountered_box: bool) -> bool {
1778 // Prevent infinite recursion
1779 if !tycache.insert(ty) {
1783 let mut encountered_box = encountered_box;
1784 let mut needs_unwind_cleanup = false;
1785 maybe_walk_ty(ty, |ty| {
1786 let old_encountered_box = encountered_box;
1787 let result = match get(ty).sty {
1789 encountered_box = true;
1792 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
1793 ty_tup(_) | ty_ptr(_) => {
1796 ty_enum(did, ref substs) => {
1797 for v in (*enum_variants(cx, did)).iter() {
1798 for aty in v.args.iter() {
1799 let t = subst(cx, substs, *aty);
1800 needs_unwind_cleanup |=
1801 type_needs_unwind_cleanup_(cx, t, tycache,
1805 !needs_unwind_cleanup
1808 ty_str(vstore_uniq) |
1809 ty_vec(_, vstore_uniq) => {
1810 // Once we're inside a box, the annihilator will find
1811 // it and destroy it.
1812 if !encountered_box {
1813 needs_unwind_cleanup = true;
1820 needs_unwind_cleanup = true;
1825 encountered_box = old_encountered_box;
1829 return needs_unwind_cleanup;
1833 * Type contents is how the type checker reasons about kinds.
1834 * They track what kinds of things are found within a type. You can
1835 * think of them as kind of an "anti-kind". They track the kinds of values
1836 * and thinks that are contained in types. Having a larger contents for
1837 * a type tends to rule that type *out* from various kinds. For example,
1838 * a type that contains a reference is not sendable.
1840 * The reason we compute type contents and not kinds is that it is
1841 * easier for me (nmatsakis) to think about what is contained within
1842 * a type than to think about what is *not* contained within a type.
1844 pub struct TypeContents {
1848 macro_rules! def_type_content_sets(
1849 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
1851 use middle::ty::TypeContents;
1852 $(pub static $name: TypeContents = TypeContents { bits: $bits };)+
1857 def_type_content_sets!(
1859 None = 0b0000_0000__0000_0000__0000,
1861 // Things that are interior to the value (first nibble):
1862 InteriorUnsized = 0b0000_0000__0000_0000__0001,
1863 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
1864 // InteriorAll = 0b00000000__00000000__1111,
1866 // Things that are owned by the value (second and third nibbles):
1867 OwnsOwned = 0b0000_0000__0000_0001__0000,
1868 OwnsDtor = 0b0000_0000__0000_0010__0000,
1869 OwnsManaged /* see [1] below */ = 0b0000_0000__0000_0100__0000,
1870 OwnsAffine = 0b0000_0000__0000_1000__0000,
1871 OwnsAll = 0b0000_0000__1111_1111__0000,
1873 // Things that are reachable by the value in any way (fourth nibble):
1874 ReachesNonsendAnnot = 0b0000_0001__0000_0000__0000,
1875 ReachesBorrowed = 0b0000_0010__0000_0000__0000,
1876 // ReachesManaged /* see [1] below */ = 0b0000_0100__0000_0000__0000,
1877 ReachesMutable = 0b0000_1000__0000_0000__0000,
1878 ReachesNoShare = 0b0001_0000__0000_0000__0000,
1879 ReachesAll = 0b0001_1111__0000_0000__0000,
1881 // Things that cause values to *move* rather than *copy*
1882 Moves = 0b0000_0000__0000_1011__0000,
1884 // Things that mean drop glue is necessary
1885 NeedsDrop = 0b0000_0000__0000_0111__0000,
1887 // Things that prevent values from being sent
1889 // Note: For checking whether something is sendable, it'd
1890 // be sufficient to have ReachesManaged. However, we include
1891 // both ReachesManaged and OwnsManaged so that when
1892 // a parameter has a bound T:Send, we are able to deduce
1893 // that it neither reaches nor owns a managed pointer.
1894 Nonsendable = 0b0000_0111__0000_0100__0000,
1896 // Things that prevent values from being considered 'static
1897 Nonstatic = 0b0000_0010__0000_0000__0000,
1899 // Things that prevent values from being considered sized
1900 Nonsized = 0b0000_0000__0000_0000__0001,
1902 // Things that prevent values from being shared
1903 Nonsharable = 0b0001_0000__0000_0000__0000,
1905 // Things that make values considered not POD (would be same
1906 // as `Moves`, but for the fact that managed data `@` is
1907 // not considered POD)
1908 Noncopy = 0b0000_0000__0000_1111__0000,
1910 // Bits to set when a managed value is encountered
1912 // [1] Do not set the bits TC::OwnsManaged or
1913 // TC::ReachesManaged directly, instead reference
1914 // TC::Managed to set them both at once.
1915 Managed = 0b0000_0100__0000_0100__0000,
1918 All = 0b1111_1111__1111_1111__1111
1923 pub fn meets_bounds(&self, cx: &ctxt, bbs: BuiltinBounds) -> bool {
1924 bbs.iter().all(|bb| self.meets_bound(cx, bb))
1927 pub fn meets_bound(&self, cx: &ctxt, bb: BuiltinBound) -> bool {
1929 BoundStatic => self.is_static(cx),
1930 BoundSend => self.is_sendable(cx),
1931 BoundSized => self.is_sized(cx),
1932 BoundCopy => self.is_copy(cx),
1933 BoundShare => self.is_sharable(cx),
1937 pub fn when(&self, cond: bool) -> TypeContents {
1938 if cond {*self} else {TC::None}
1941 pub fn intersects(&self, tc: TypeContents) -> bool {
1942 (self.bits & tc.bits) != 0
1945 pub fn is_static(&self, _: &ctxt) -> bool {
1946 !self.intersects(TC::Nonstatic)
1949 pub fn is_sendable(&self, _: &ctxt) -> bool {
1950 !self.intersects(TC::Nonsendable)
1953 pub fn is_sharable(&self, _: &ctxt) -> bool {
1954 !self.intersects(TC::Nonsharable)
1957 pub fn owns_managed(&self) -> bool {
1958 self.intersects(TC::OwnsManaged)
1961 pub fn owns_owned(&self) -> bool {
1962 self.intersects(TC::OwnsOwned)
1965 pub fn is_sized(&self, _: &ctxt) -> bool {
1966 !self.intersects(TC::Nonsized)
1969 pub fn is_copy(&self, _: &ctxt) -> bool {
1970 !self.intersects(TC::Noncopy)
1973 pub fn interior_unsafe(&self) -> bool {
1974 self.intersects(TC::InteriorUnsafe)
1977 pub fn moves_by_default(&self, _: &ctxt) -> bool {
1978 self.intersects(TC::Moves)
1981 pub fn needs_drop(&self, _: &ctxt) -> bool {
1982 self.intersects(TC::NeedsDrop)
1985 pub fn owned_pointer(&self) -> TypeContents {
1987 * Includes only those bits that still apply
1988 * when indirected through a `~` pointer
1991 *self & (TC::OwnsAll | TC::ReachesAll))
1994 pub fn reference(&self, bits: TypeContents) -> TypeContents {
1996 * Includes only those bits that still apply
1997 * when indirected through a reference (`&`)
2000 *self & TC::ReachesAll)
2003 pub fn managed_pointer(&self) -> TypeContents {
2005 * Includes only those bits that still apply
2006 * when indirected through a managed pointer (`@`)
2009 *self & TC::ReachesAll)
2012 pub fn unsafe_pointer(&self) -> TypeContents {
2014 * Includes only those bits that still apply
2015 * when indirected through an unsafe pointer (`*`)
2017 *self & TC::ReachesAll
2020 pub fn union<T>(v: &[T], f: |&T| -> TypeContents) -> TypeContents {
2021 v.iter().fold(TC::None, |tc, t| tc | f(t))
2024 pub fn inverse(&self) -> TypeContents {
2025 TypeContents { bits: !self.bits }
2028 pub fn has_dtor(&self) -> bool {
2029 self.intersects(TC::OwnsDtor)
2033 impl ops::BitOr<TypeContents,TypeContents> for TypeContents {
2034 fn bitor(&self, other: &TypeContents) -> TypeContents {
2035 TypeContents {bits: self.bits | other.bits}
2039 impl ops::BitAnd<TypeContents,TypeContents> for TypeContents {
2040 fn bitand(&self, other: &TypeContents) -> TypeContents {
2041 TypeContents {bits: self.bits & other.bits}
2045 impl ops::Sub<TypeContents,TypeContents> for TypeContents {
2046 fn sub(&self, other: &TypeContents) -> TypeContents {
2047 TypeContents {bits: self.bits & !other.bits}
2051 impl fmt::Show for TypeContents {
2052 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2053 write!(f.buf, "TypeContents({:t})", self.bits)
2057 pub fn type_has_dtor(cx: &ctxt, t: ty::t) -> bool {
2058 type_contents(cx, t).has_dtor()
2061 pub fn type_is_static(cx: &ctxt, t: ty::t) -> bool {
2062 type_contents(cx, t).is_static(cx)
2065 pub fn type_is_sendable(cx: &ctxt, t: ty::t) -> bool {
2066 type_contents(cx, t).is_sendable(cx)
2069 pub fn type_interior_is_unsafe(cx: &ctxt, t: ty::t) -> bool {
2070 type_contents(cx, t).interior_unsafe()
2073 pub fn type_contents(cx: &ctxt, ty: t) -> TypeContents {
2074 let ty_id = type_id(ty);
2076 match cx.tc_cache.borrow().find(&ty_id) {
2077 Some(tc) => { return *tc; }
2081 let mut cache = HashMap::new();
2082 let result = tc_ty(cx, ty, &mut cache);
2084 cx.tc_cache.borrow_mut().insert(ty_id, result);
2089 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2091 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
2092 // private cache for this walk. This is needed in the case of cyclic
2095 // struct List { next: ~Option<List>, ... }
2097 // When computing the type contents of such a type, we wind up deeply
2098 // recursing as we go. So when we encounter the recursive reference
2099 // to List, we temporarily use TC::None as its contents. Later we'll
2100 // patch up the cache with the correct value, once we've computed it
2101 // (this is basically a co-inductive process, if that helps). So in
2102 // the end we'll compute TC::OwnsOwned, in this case.
2104 // The problem is, as we are doing the computation, we will also
2105 // compute an *intermediate* contents for, e.g., Option<List> of
2106 // TC::None. This is ok during the computation of List itself, but if
2107 // we stored this intermediate value into cx.tc_cache, then later
2108 // requests for the contents of Option<List> would also yield TC::None
2109 // which is incorrect. This value was computed based on the crutch
2110 // value for the type contents of list. The correct value is
2111 // TC::OwnsOwned. This manifested as issue #4821.
2112 let ty_id = type_id(ty);
2113 match cache.find(&ty_id) {
2114 Some(tc) => { return *tc; }
2117 match cx.tc_cache.borrow().find(&ty_id) { // Must check both caches!
2118 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, 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(~ty::TyTrait { store, mutability, bounds, .. }) => {
2147 object_contents(cx, store, mutability, 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.as_slice(),
2184 |f| tc_mt(cx, f.mt, cache));
2185 if ty::has_dtor(cx, did) {
2186 res = res | TC::OwnsDtor;
2188 apply_lang_items(cx, did, res)
2191 ty_tup(ref tys) => {
2192 TypeContents::union(tys.as_slice(),
2193 |ty| tc_ty(cx, *ty, cache))
2196 ty_enum(did, ref substs) => {
2197 let variants = substd_enum_variants(cx, did, substs);
2199 TypeContents::union(variants.as_slice(), |variant| {
2200 TypeContents::union(variant.args.as_slice(),
2202 tc_ty(cx, *arg_ty, cache)
2205 apply_lang_items(cx, did, res)
2209 // We only ever ask for the kind of types that are defined in
2210 // the current crate; therefore, the only type parameters that
2211 // could be in scope are those defined in the current crate.
2212 // If this assertion failures, it is likely because of a
2213 // failure in the cross-crate inlining code to translate a
2215 assert_eq!(p.def_id.krate, ast::LOCAL_CRATE);
2217 let ty_param_defs = cx.ty_param_defs.borrow();
2218 let tp_def = ty_param_defs.get(&p.def_id.node);
2219 kind_bounds_to_contents(cx,
2220 tp_def.bounds.builtin_bounds,
2221 tp_def.bounds.trait_bounds.as_slice())
2224 ty_self(def_id) => {
2225 // FIXME(#4678)---self should just be a ty param
2227 // Self may be bounded if the associated trait has builtin kinds
2228 // for supertraits. If so we can use those bounds.
2229 let trait_def = lookup_trait_def(cx, def_id);
2230 let traits = [trait_def.trait_ref];
2231 kind_bounds_to_contents(cx, trait_def.bounds, traits)
2235 // This occurs during coherence, but shouldn't occur at other
2239 ty_unboxed_vec(mt) => TC::InteriorUnsized | tc_mt(cx, mt, cache),
2242 cx.sess.bug("asked to compute contents of error type");
2246 cache.insert(ty_id, result);
2252 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2254 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
2255 mc | tc_ty(cx, mt.ty, cache)
2258 fn apply_lang_items(cx: &ctxt,
2262 if Some(did) == cx.lang_items.no_send_bound() {
2263 tc | TC::ReachesNonsendAnnot
2264 } else if Some(did) == cx.lang_items.managed_bound() {
2266 } else if Some(did) == cx.lang_items.no_copy_bound() {
2268 } else if Some(did) == cx.lang_items.no_share_bound() {
2269 tc | TC::ReachesNoShare
2270 } else if Some(did) == cx.lang_items.unsafe_type() {
2271 tc | TC::InteriorUnsafe
2277 fn borrowed_contents(region: ty::Region,
2278 mutbl: ast::Mutability)
2281 * Type contents due to containing a reference
2282 * with the region `region` and borrow kind `bk`
2285 let b = match mutbl {
2286 ast::MutMutable => TC::ReachesMutable | TC::OwnsAffine,
2287 ast::MutImmutable => TC::None,
2289 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
2292 fn closure_contents(cx: &ctxt, cty: &ClosureTy) -> TypeContents {
2293 // Closure contents are just like trait contents, but with potentially
2295 let st = match cty.sigil {
2296 ast::BorrowedSigil =>
2297 object_contents(cx, RegionTraitStore(cty.region), MutMutable, cty.bounds),
2299 object_contents(cx, UniqTraitStore, MutImmutable, cty.bounds),
2300 ast::ManagedSigil => unreachable!()
2303 // FIXME(#3569): This borrowed_contents call should be taken care of in
2304 // object_contents, after ~Traits and @Traits can have region bounds too.
2305 // This one here is redundant for &fns but important for ~fns and @fns.
2306 let rt = borrowed_contents(cty.region, ast::MutImmutable);
2308 // This also prohibits "@once fn" from being copied, which allows it to
2309 // be called. Neither way really makes much sense.
2310 let ot = match cty.onceness {
2311 ast::Once => TC::OwnsAffine,
2312 ast::Many => TC::None,
2318 fn object_contents(cx: &ctxt,
2320 mutbl: ast::Mutability,
2321 bounds: BuiltinBounds)
2323 // These are the type contents of the (opaque) interior
2324 let contents = TC::ReachesMutable.when(mutbl == ast::MutMutable) |
2325 kind_bounds_to_contents(cx, bounds, []);
2329 contents.owned_pointer()
2331 RegionTraitStore(r) => {
2332 contents.reference(borrowed_contents(r, mutbl))
2337 fn kind_bounds_to_contents(cx: &ctxt,
2338 bounds: BuiltinBounds,
2339 traits: &[@TraitRef])
2341 let _i = indenter();
2342 let mut tc = TC::All;
2343 each_inherited_builtin_bound(cx, bounds, traits, |bound| {
2344 tc = tc - match bound {
2345 BoundStatic => TC::Nonstatic,
2346 BoundSend => TC::Nonsendable,
2347 BoundSized => TC::Nonsized,
2348 BoundCopy => TC::Noncopy,
2349 BoundShare => TC::Nonsharable,
2354 // Iterates over all builtin bounds on the type parameter def, including
2355 // those inherited from traits with builtin-kind-supertraits.
2356 fn each_inherited_builtin_bound(cx: &ctxt,
2357 bounds: BuiltinBounds,
2358 traits: &[@TraitRef],
2359 f: |BuiltinBound|) {
2360 for bound in bounds.iter() {
2364 each_bound_trait_and_supertraits(cx, traits, |trait_ref| {
2365 let trait_def = lookup_trait_def(cx, trait_ref.def_id);
2366 for bound in trait_def.bounds.iter() {
2375 pub fn type_moves_by_default(cx: &ctxt, ty: t) -> bool {
2376 type_contents(cx, ty).moves_by_default(cx)
2379 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
2380 pub fn is_instantiable(cx: &ctxt, r_ty: t) -> bool {
2381 fn type_requires(cx: &ctxt, seen: &mut Vec<DefId>,
2382 r_ty: t, ty: t) -> bool {
2383 debug!("type_requires({}, {})?",
2384 ::util::ppaux::ty_to_str(cx, r_ty),
2385 ::util::ppaux::ty_to_str(cx, ty));
2388 get(r_ty).sty == get(ty).sty ||
2389 subtypes_require(cx, seen, r_ty, ty)
2392 debug!("type_requires({}, {})? {}",
2393 ::util::ppaux::ty_to_str(cx, r_ty),
2394 ::util::ppaux::ty_to_str(cx, ty),
2399 fn subtypes_require(cx: &ctxt, seen: &mut Vec<DefId>,
2400 r_ty: t, ty: t) -> bool {
2401 debug!("subtypes_require({}, {})?",
2402 ::util::ppaux::ty_to_str(cx, r_ty),
2403 ::util::ppaux::ty_to_str(cx, ty));
2405 let r = match get(ty).sty {
2406 // fixed length vectors need special treatment compared to
2407 // normal vectors, since they don't necessarily have the
2408 // possibilty to have length zero.
2409 ty_vec(_, vstore_fixed(0)) => false, // don't need no contents
2410 ty_vec(mt, vstore_fixed(_)) => type_requires(cx, seen, r_ty, mt.ty),
2427 ty_unboxed_vec(_) => {
2430 ty_box(typ) | ty_uniq(typ) => {
2431 type_requires(cx, seen, r_ty, typ)
2433 ty_rptr(_, ref mt) => {
2434 type_requires(cx, seen, r_ty, mt.ty)
2438 false // unsafe ptrs can always be NULL
2445 ty_struct(ref did, _) if seen.contains(did) => {
2449 ty_struct(did, ref substs) => {
2451 let fields = struct_fields(cx, did, substs);
2452 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
2453 seen.pop().unwrap();
2458 ts.iter().any(|t| type_requires(cx, seen, r_ty, *t))
2461 ty_enum(ref did, _) if seen.contains(did) => {
2465 ty_enum(did, ref substs) => {
2467 let vs = enum_variants(cx, did);
2468 let r = !vs.is_empty() && vs.iter().all(|variant| {
2469 variant.args.iter().any(|aty| {
2470 let sty = subst(cx, substs, *aty);
2471 type_requires(cx, seen, r_ty, sty)
2474 seen.pop().unwrap();
2479 debug!("subtypes_require({}, {})? {}",
2480 ::util::ppaux::ty_to_str(cx, r_ty),
2481 ::util::ppaux::ty_to_str(cx, ty),
2487 let mut seen = Vec::new();
2488 !subtypes_require(cx, &mut seen, r_ty, r_ty)
2491 /// Describes whether a type is representable. For types that are not
2492 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
2493 /// distinguish between types that are recursive with themselves and types that
2494 /// contain a different recursive type. These cases can therefore be treated
2495 /// differently when reporting errors.
2497 pub enum Representability {
2503 /// Check whether a type is representable. This means it cannot contain unboxed
2504 /// structural recursion. This check is needed for structs and enums.
2505 pub fn is_type_representable(cx: &ctxt, ty: t) -> Representability {
2507 // Iterate until something non-representable is found
2508 fn find_nonrepresentable<It: Iterator<t>>(cx: &ctxt, seen: &mut Vec<DefId>,
2509 mut iter: It) -> Representability {
2511 let r = type_structurally_recursive(cx, seen, ty);
2512 if r != Representable {
2519 // Does the type `ty` directly (without indirection through a pointer)
2520 // contain any types on stack `seen`?
2521 fn type_structurally_recursive(cx: &ctxt, seen: &mut Vec<DefId>,
2522 ty: t) -> Representability {
2523 debug!("type_structurally_recursive: {}",
2524 ::util::ppaux::ty_to_str(cx, ty));
2526 // Compare current type to previously seen types
2529 ty_enum(did, _) => {
2530 for (i, &seen_did) in seen.iter().enumerate() {
2531 if did == seen_did {
2532 return if i == 0 { SelfRecursive }
2533 else { ContainsRecursive }
2540 // Check inner types
2544 find_nonrepresentable(cx, seen, ts.iter().map(|t| *t))
2546 // Fixed-length vectors.
2547 // FIXME(#11924) Behavior undecided for zero-length vectors.
2548 ty_vec(mt, vstore_fixed(_)) => {
2549 type_structurally_recursive(cx, seen, mt.ty)
2552 // Push struct and enum def-ids onto `seen` before recursing.
2553 ty_struct(did, ref substs) => {
2555 let fields = struct_fields(cx, did, substs);
2556 let r = find_nonrepresentable(cx, seen,
2557 fields.iter().map(|f| f.mt.ty));
2561 ty_enum(did, ref substs) => {
2563 let vs = enum_variants(cx, did);
2565 let mut r = Representable;
2566 for variant in vs.iter() {
2567 let iter = variant.args.iter().map(|aty| subst(cx, substs, *aty));
2568 r = find_nonrepresentable(cx, seen, iter);
2570 if r != Representable { break }
2581 debug!("is_type_representable: {}",
2582 ::util::ppaux::ty_to_str(cx, ty));
2584 // To avoid a stack overflow when checking an enum variant or struct that
2585 // contains a different, structurally recursive type, maintain a stack
2586 // of seen types and check recursion for each of them (issues #3008, #3779).
2587 let mut seen: Vec<DefId> = Vec::new();
2588 type_structurally_recursive(cx, &mut seen, ty)
2591 pub fn type_is_trait(ty: t) -> bool {
2593 ty_trait(..) => true,
2598 pub fn type_is_integral(ty: t) -> bool {
2600 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
2605 pub fn type_is_char(ty: t) -> bool {
2612 pub fn type_is_bare_fn(ty: t) -> bool {
2614 ty_bare_fn(..) => true,
2619 pub fn type_is_fp(ty: t) -> bool {
2621 ty_infer(FloatVar(_)) | ty_float(_) => true,
2626 pub fn type_is_numeric(ty: t) -> bool {
2627 return type_is_integral(ty) || type_is_fp(ty);
2630 pub fn type_is_signed(ty: t) -> bool {
2637 pub fn type_is_machine(ty: t) -> bool {
2639 ty_int(ast::TyI) | ty_uint(ast::TyU) => false,
2640 ty_int(..) | ty_uint(..) | ty_float(..) => true,
2645 pub fn type_is_enum(ty: t) -> bool {
2647 ty_enum(_, _) => return true,
2652 // Is the type's representation size known at compile time?
2653 pub fn type_is_sized(cx: &ctxt, ty: ty::t) -> bool {
2655 // FIXME(#6308) add trait, vec, str, etc here.
2657 let ty_param_defs = cx.ty_param_defs.borrow();
2658 let param_def = ty_param_defs.get(&p.def_id.node);
2659 if param_def.bounds.builtin_bounds.contains_elem(BoundSized) {
2668 // Whether a type is enum like, that is an enum type with only nullary
2670 pub fn type_is_c_like_enum(cx: &ctxt, ty: t) -> bool {
2672 ty_enum(did, _) => {
2673 let variants = enum_variants(cx, did);
2674 if variants.len() == 0 {
2677 variants.iter().all(|v| v.args.len() == 0)
2684 pub fn type_param(ty: t) -> Option<uint> {
2686 ty_param(p) => return Some(p.idx),
2687 _ => {/* fall through */ }
2692 // Returns the type and mutability of *t.
2694 // The parameter `explicit` indicates if this is an *explicit* dereference.
2695 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
2696 pub fn deref(t: t, explicit: bool) -> Option<mt> {
2698 ty_box(typ) | ty_uniq(typ) => Some(mt {
2700 mutbl: ast::MutImmutable,
2702 ty_rptr(_, mt) => Some(mt),
2703 ty_ptr(mt) if explicit => Some(mt),
2708 // Returns the type and mutability of t[i]
2709 pub fn index(t: t) -> Option<mt> {
2711 ty_vec(mt, _) => Some(mt),
2712 ty_str(_) => Some(mt {ty: mk_u8(), mutbl: ast::MutImmutable}),
2717 pub fn node_id_to_trait_ref(cx: &ctxt, id: ast::NodeId) -> @ty::TraitRef {
2718 match cx.trait_refs.borrow().find(&id) {
2720 None => cx.sess.bug(
2721 format!("node_id_to_trait_ref: no trait ref for node `{}`",
2722 cx.map.node_to_str(id)))
2726 pub fn try_node_id_to_type(cx: &ctxt, id: ast::NodeId) -> Option<t> {
2727 cx.node_types.borrow().find_copy(&(id as uint))
2730 pub fn node_id_to_type(cx: &ctxt, id: ast::NodeId) -> t {
2731 match try_node_id_to_type(cx, id) {
2733 None => cx.sess.bug(
2734 format!("node_id_to_type: no type for node `{}`",
2735 cx.map.node_to_str(id)))
2739 pub fn node_id_to_type_opt(cx: &ctxt, id: ast::NodeId) -> Option<t> {
2740 match cx.node_types.borrow().find(&(id as uint)) {
2741 Some(&t) => Some(t),
2746 // FIXME(pcwalton): Makes a copy, bleh. Probably better to not do that.
2747 pub fn node_id_to_type_params(cx: &ctxt, id: ast::NodeId) -> Vec<t> {
2748 match cx.node_type_substs.borrow().find(&id) {
2749 None => return Vec::new(),
2750 Some(ts) => return (*ts).clone(),
2754 fn node_id_has_type_params(cx: &ctxt, id: ast::NodeId) -> bool {
2755 cx.node_type_substs.borrow().contains_key(&id)
2758 pub fn fn_is_variadic(fty: t) -> bool {
2759 match get(fty).sty {
2760 ty_bare_fn(ref f) => f.sig.variadic,
2761 ty_closure(ref f) => f.sig.variadic,
2763 fail!("fn_is_variadic() called on non-fn type: {:?}", s)
2768 pub fn ty_fn_sig(fty: t) -> FnSig {
2769 match get(fty).sty {
2770 ty_bare_fn(ref f) => f.sig.clone(),
2771 ty_closure(ref f) => f.sig.clone(),
2773 fail!("ty_fn_sig() called on non-fn type: {:?}", s)
2778 // Type accessors for substructures of types
2779 pub fn ty_fn_args(fty: t) -> Vec<t> {
2780 match get(fty).sty {
2781 ty_bare_fn(ref f) => f.sig.inputs.clone(),
2782 ty_closure(ref f) => f.sig.inputs.clone(),
2784 fail!("ty_fn_args() called on non-fn type: {:?}", s)
2789 pub fn ty_closure_sigil(fty: t) -> Sigil {
2790 match get(fty).sty {
2791 ty_closure(ref f) => f.sigil,
2793 fail!("ty_closure_sigil() called on non-closure type: {:?}", s)
2798 pub fn ty_fn_purity(fty: t) -> ast::Purity {
2799 match get(fty).sty {
2800 ty_bare_fn(ref f) => f.purity,
2801 ty_closure(ref f) => f.purity,
2803 fail!("ty_fn_purity() called on non-fn type: {:?}", s)
2808 pub fn ty_fn_ret(fty: t) -> t {
2809 match get(fty).sty {
2810 ty_bare_fn(ref f) => f.sig.output,
2811 ty_closure(ref f) => f.sig.output,
2813 fail!("ty_fn_ret() called on non-fn type: {:?}", s)
2818 pub fn is_fn_ty(fty: t) -> bool {
2819 match get(fty).sty {
2820 ty_bare_fn(_) => true,
2821 ty_closure(_) => true,
2826 pub fn ty_vstore(ty: t) -> vstore {
2828 ty_vec(_, vstore) => vstore,
2829 ty_str(vstore) => vstore,
2830 ref s => fail!("ty_vstore() called on invalid sty: {:?}", s)
2834 pub fn ty_region(tcx: &ctxt,
2839 ty_vec(_, vstore_slice(r)) => r,
2840 ty_str(vstore_slice(r)) => r,
2844 format!("ty_region() invoked on in appropriate ty: {:?}", s));
2849 pub fn replace_fn_sig(cx: &ctxt, fsty: &sty, new_sig: FnSig) -> t {
2851 ty_bare_fn(ref f) => mk_bare_fn(cx, BareFnTy {sig: new_sig, ..*f}),
2852 ty_closure(ref f) => mk_closure(cx, ClosureTy {sig: new_sig, ..**f}),
2855 format!("ty_fn_sig() called on non-fn type: {:?}", s));
2860 pub fn replace_closure_return_type(tcx: &ctxt, fn_type: t, ret_type: t) -> t {
2863 * Returns a new function type based on `fn_type` but returning a value of
2864 * type `ret_type` instead. */
2866 match ty::get(fn_type).sty {
2867 ty::ty_closure(ref fty) => {
2868 ty::mk_closure(tcx, ClosureTy {
2869 sig: FnSig {output: ret_type, ..fty.sig.clone()},
2874 tcx.sess.bug(format!(
2875 "replace_fn_ret() invoked with non-fn-type: {}",
2876 ty_to_str(tcx, fn_type)));
2881 // Returns a vec of all the input and output types of fty.
2882 pub fn tys_in_fn_sig(sig: &FnSig) -> Vec<t> {
2883 vec::append_one(sig.inputs.map(|a| *a), sig.output)
2886 // Type accessors for AST nodes
2887 pub fn block_ty(cx: &ctxt, b: &ast::Block) -> t {
2888 return node_id_to_type(cx, b.id);
2892 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
2893 // doesn't provide type parameter substitutions.
2894 pub fn pat_ty(cx: &ctxt, pat: &ast::Pat) -> t {
2895 return node_id_to_type(cx, pat.id);
2899 // Returns the type of an expression as a monotype.
2901 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
2902 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
2903 // auto-ref. The type returned by this function does not consider such
2904 // adjustments. See `expr_ty_adjusted()` instead.
2906 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
2907 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
2908 // instead of "fn(t) -> T with T = int". If this isn't what you want, see
2909 // expr_ty_params_and_ty() below.
2910 pub fn expr_ty(cx: &ctxt, expr: &ast::Expr) -> t {
2911 return node_id_to_type(cx, expr.id);
2914 pub fn expr_ty_opt(cx: &ctxt, expr: &ast::Expr) -> Option<t> {
2915 return node_id_to_type_opt(cx, expr.id);
2918 pub fn expr_ty_adjusted(cx: &ctxt,
2920 method_map: &FnvHashMap<MethodCall, MethodCallee>)
2924 * Returns the type of `expr`, considering any `AutoAdjustment`
2925 * entry recorded for that expression.
2927 * It would almost certainly be better to store the adjusted ty in with
2928 * the `AutoAdjustment`, but I opted not to do this because it would
2929 * require serializing and deserializing the type and, although that's not
2930 * hard to do, I just hate that code so much I didn't want to touch it
2931 * unless it was to fix it properly, which seemed a distraction from the
2932 * task at hand! -nmatsakis
2935 let unadjusted_ty = expr_ty(cx, expr);
2936 let adjustment = cx.adjustments.borrow().find_copy(&expr.id);
2937 adjust_ty(cx, expr.span, expr.id, unadjusted_ty, adjustment, |method_call| {
2938 method_map.find(&method_call).map(|method| method.ty)
2942 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
2943 match cx.map.find(id) {
2944 Some(ast_map::NodeExpr(e)) => {
2948 cx.sess.bug(format!("Node id {} is not an expr: {:?}",
2952 cx.sess.bug(format!("Node id {} is not present \
2953 in the node map", id));
2958 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
2959 match cx.map.find(id) {
2960 Some(ast_map::NodeLocal(pat)) => {
2962 ast::PatIdent(_, ref path, _) => {
2963 token::get_ident(ast_util::path_to_ident(path))
2967 format!("Variable id {} maps to {:?}, not local",
2974 format!("Variable id {} maps to {:?}, not local",
2980 pub fn adjust_ty(cx: &ctxt,
2982 expr_id: ast::NodeId,
2983 unadjusted_ty: ty::t,
2984 adjustment: Option<@AutoAdjustment>,
2985 method_type: |MethodCall| -> Option<ty::t>)
2987 /*! See `expr_ty_adjusted` */
2989 return match adjustment {
2990 Some(adjustment) => {
2992 AutoAddEnv(r, s) => {
2993 match ty::get(unadjusted_ty).sty {
2994 ty::ty_bare_fn(ref b) => {
2997 ty::ClosureTy {purity: b.purity,
2999 onceness: ast::Many,
3001 bounds: ty::AllBuiltinBounds(),
3002 sig: b.sig.clone()})
3006 format!("add_env adjustment on non-bare-fn: \
3013 AutoDerefRef(ref adj) => {
3014 let mut adjusted_ty = unadjusted_ty;
3016 if !ty::type_is_error(adjusted_ty) {
3017 for i in range(0, adj.autoderefs) {
3018 match method_type(MethodCall::autoderef(expr_id, i as u32)) {
3019 Some(method_ty) => {
3020 adjusted_ty = ty_fn_ret(method_ty);
3024 match deref(adjusted_ty, true) {
3025 Some(mt) => { adjusted_ty = mt.ty; }
3029 format!("the {}th autoderef failed: \
3032 ty_to_str(cx, adjusted_ty)));
3039 None => adjusted_ty,
3040 Some(ref autoref) => {
3049 AutoBorrowVec(r, m) => {
3050 borrow_vec(cx, span, r, m, adjusted_ty)
3053 AutoBorrowVecRef(r, m) => {
3054 adjusted_ty = borrow_vec(cx,
3061 mutbl: ast::MutImmutable
3065 AutoBorrowFn(r) => {
3066 borrow_fn(cx, span, r, adjusted_ty)
3070 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
3073 AutoBorrowObj(r, m) => {
3074 borrow_obj(cx, span, r, m, adjusted_ty)
3081 AutoObject(ref sigil, ref region, m, b, def_id, ref substs) => {
3082 trait_adjustment_to_ty(cx,
3092 None => unadjusted_ty
3095 fn borrow_vec(cx: &ctxt, span: Span,
3096 r: Region, m: ast::Mutability,
3097 ty: ty::t) -> ty::t {
3100 ty::mk_vec(cx, mt {ty: mt.ty, mutbl: m}, vstore_slice(r))
3104 ty::mk_str(cx, vstore_slice(r))
3110 format!("borrow-vec associated with bad sty: {:?}",
3116 fn borrow_fn(cx: &ctxt, span: Span, r: Region, ty: ty::t) -> ty::t {
3118 ty_closure(ref fty) => {
3119 ty::mk_closure(cx, ClosureTy {
3120 sigil: BorrowedSigil,
3129 format!("borrow-fn associated with bad sty: {:?}",
3135 fn borrow_obj(cx: &ctxt, span: Span, r: Region,
3136 m: ast::Mutability, ty: ty::t) -> ty::t {
3138 ty_trait(~ty::TyTrait {def_id, ref substs, bounds, .. }) => {
3139 ty::mk_trait(cx, def_id, substs.clone(),
3140 RegionTraitStore(r), m, bounds)
3145 format!("borrow-trait-obj associated with bad sty: {:?}",
3152 pub fn trait_adjustment_to_ty(cx: &ctxt, sigil: &ast::Sigil, region: &Option<Region>,
3153 def_id: ast::DefId, substs: &substs, m: ast::Mutability,
3154 bounds: BuiltinBounds) -> t {
3156 let trait_store = match *sigil {
3157 BorrowedSigil => RegionTraitStore(region.expect("expected valid region")),
3158 OwnedSigil => UniqTraitStore,
3159 ManagedSigil => unreachable!()
3162 mk_trait(cx, def_id, substs.clone(), trait_store, m, bounds)
3166 pub fn map_region(&self, f: |Region| -> Region) -> AutoRef {
3168 ty::AutoPtr(r, m) => ty::AutoPtr(f(r), m),
3169 ty::AutoBorrowVec(r, m) => ty::AutoBorrowVec(f(r), m),
3170 ty::AutoBorrowVecRef(r, m) => ty::AutoBorrowVecRef(f(r), m),
3171 ty::AutoBorrowFn(r) => ty::AutoBorrowFn(f(r)),
3172 ty::AutoUnsafe(m) => ty::AutoUnsafe(m),
3173 ty::AutoBorrowObj(r, m) => ty::AutoBorrowObj(f(r), m),
3178 pub struct ParamsTy {
3183 pub fn expr_ty_params_and_ty(cx: &ctxt,
3187 params: node_id_to_type_params(cx, expr.id),
3188 ty: node_id_to_type(cx, expr.id)
3192 pub fn expr_has_ty_params(cx: &ctxt, expr: &ast::Expr) -> bool {
3193 return node_id_has_type_params(cx, expr.id);
3196 pub fn method_call_type_param_defs(tcx: &ctxt, origin: typeck::MethodOrigin)
3197 -> Rc<Vec<TypeParameterDef>> {
3199 typeck::MethodStatic(did) => {
3200 // n.b.: When we encode impl methods, the bounds
3201 // that we encode include both the impl bounds
3202 // and then the method bounds themselves...
3203 ty::lookup_item_type(tcx, did).generics.type_param_defs
3205 typeck::MethodParam(typeck::MethodParam {
3207 method_num: n_mth, ..}) |
3208 typeck::MethodObject(typeck::MethodObject {
3210 method_num: n_mth, ..}) => {
3211 // ...trait methods bounds, in contrast, include only the
3212 // method bounds, so we must preprend the tps from the
3213 // trait itself. This ought to be harmonized.
3214 let trait_type_param_defs =
3215 lookup_trait_def(tcx, trt_id).generics.type_param_defs();
3216 Rc::new(vec::append(
3217 Vec::from_slice(trait_type_param_defs),
3218 ty::trait_method(tcx,
3220 n_mth).generics.type_param_defs()))
3225 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> ast::Def {
3226 match tcx.def_map.borrow().find(&expr.id) {
3229 tcx.sess.span_bug(expr.span, format!(
3230 "no def-map entry for expr {:?}", expr.id));
3235 pub fn expr_is_lval(tcx: &ctxt,
3236 method_map: MethodMap,
3237 e: &ast::Expr) -> bool {
3238 match expr_kind(tcx, method_map, e) {
3240 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
3244 /// We categorize expressions into three kinds. The distinction between
3245 /// lvalue/rvalue is fundamental to the language. The distinction between the
3246 /// two kinds of rvalues is an artifact of trans which reflects how we will
3247 /// generate code for that kind of expression. See trans/expr.rs for more
3256 pub fn expr_kind(tcx: &ctxt,
3257 method_map: MethodMap,
3258 expr: &ast::Expr) -> ExprKind {
3259 if method_map.borrow().contains_key(&MethodCall::expr(expr.id)) {
3260 // Overloaded operations are generally calls, and hence they are
3261 // generated via DPS, but there are two exceptions:
3262 return match expr.node {
3263 // `a += b` has a unit result.
3264 ast::ExprAssignOp(..) => RvalueStmtExpr,
3266 // the deref method invoked for `*a` always yields an `&T`
3267 ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
3269 // in the general case, result could be any type, use DPS
3275 ast::ExprPath(..) => {
3276 match resolve_expr(tcx, expr) {
3277 ast::DefVariant(tid, vid, _) => {
3278 let variant_info = enum_variant_with_id(tcx, tid, vid);
3279 if variant_info.args.len() > 0u {
3288 ast::DefStruct(_) => {
3289 match get(expr_ty(tcx, expr)).sty {
3290 ty_bare_fn(..) => RvalueDatumExpr,
3295 // Fn pointers are just scalar values.
3296 ast::DefFn(..) | ast::DefStaticMethod(..) => RvalueDatumExpr,
3298 // Note: there is actually a good case to be made that
3299 // DefArg's, particularly those of immediate type, ought to
3300 // considered rvalues.
3301 ast::DefStatic(..) |
3302 ast::DefBinding(..) |
3305 ast::DefLocal(..) => LvalueExpr,
3308 tcx.sess.span_bug(expr.span, format!(
3309 "uncategorized def for expr {:?}: {:?}",
3315 ast::ExprUnary(ast::UnDeref, _) |
3316 ast::ExprField(..) |
3317 ast::ExprIndex(..) => {
3322 ast::ExprMethodCall(..) |
3323 ast::ExprStruct(..) |
3326 ast::ExprMatch(..) |
3327 ast::ExprFnBlock(..) |
3329 ast::ExprBlock(..) |
3330 ast::ExprRepeat(..) |
3331 ast::ExprVstore(_, ast::ExprVstoreSlice) |
3332 ast::ExprVstore(_, ast::ExprVstoreMutSlice) |
3333 ast::ExprVec(..) => {
3337 ast::ExprLit(lit) if lit_is_str(lit) => {
3341 ast::ExprCast(..) => {
3342 match tcx.node_types.borrow().find(&(expr.id as uint)) {
3344 if type_is_trait(t) {
3351 // Technically, it should not happen that the expr is not
3352 // present within the table. However, it DOES happen
3353 // during type check, because the final types from the
3354 // expressions are not yet recorded in the tcx. At that
3355 // time, though, we are only interested in knowing lvalue
3356 // vs rvalue. It would be better to base this decision on
3357 // the AST type in cast node---but (at the time of this
3358 // writing) it's not easy to distinguish casts to traits
3359 // from other casts based on the AST. This should be
3360 // easier in the future, when casts to traits
3361 // would like @Foo, ~Foo, or &Foo.
3367 ast::ExprBreak(..) |
3368 ast::ExprAgain(..) |
3370 ast::ExprWhile(..) |
3372 ast::ExprAssign(..) |
3373 ast::ExprInlineAsm(..) |
3374 ast::ExprAssignOp(..) => {
3378 ast::ExprForLoop(..) => fail!("non-desugared expr_for_loop"),
3380 ast::ExprLit(_) | // Note: LitStr is carved out above
3381 ast::ExprUnary(..) |
3382 ast::ExprAddrOf(..) |
3383 ast::ExprBinary(..) |
3384 ast::ExprVstore(_, ast::ExprVstoreUniq) => {
3388 ast::ExprBox(place, _) => {
3389 // Special case `~T` for now:
3390 let definition = match tcx.def_map.borrow().find(&place.id) {
3392 None => fail!("no def for place"),
3394 let def_id = ast_util::def_id_of_def(definition);
3395 match tcx.lang_items.items.get(ExchangeHeapLangItem as uint) {
3396 &Some(item_def_id) if def_id == item_def_id => {
3399 &Some(_) | &None => RvalueDpsExpr,
3403 ast::ExprParen(e) => expr_kind(tcx, method_map, e),
3405 ast::ExprMac(..) => {
3408 "macro expression remains after expansion");
3413 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
3415 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
3418 ast::StmtMac(..) => fail!("unexpanded macro in trans")
3422 pub fn field_idx(name: ast::Name, fields: &[field]) -> Option<uint> {
3424 for f in fields.iter() { if f.ident.name == name { return Some(i); } i += 1u; }
3428 pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
3431 for f in fields.iter() { if f.ident.name == name { return i; } i += 1u; }
3432 tcx.sess.bug(format!(
3433 "no field named `{}` found in the list of fields `{:?}`",
3434 token::get_name(name),
3435 fields.map(|f| token::get_ident(f.ident).get().to_str())));
3438 pub fn method_idx(id: ast::Ident, meths: &[@Method]) -> Option<uint> {
3439 meths.iter().position(|m| m.ident == id)
3442 /// Returns a vector containing the indices of all type parameters that appear
3443 /// in `ty`. The vector may contain duplicates. Probably should be converted
3444 /// to a bitset or some other representation.
3445 pub fn param_tys_in_type(ty: t) -> Vec<param_ty> {
3446 let mut rslt = Vec::new();
3458 pub fn ty_sort_str(cx: &ctxt, t: t) -> ~str {
3460 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) |
3461 ty_uint(_) | ty_float(_) | ty_str(_) => {
3462 ::util::ppaux::ty_to_str(cx, t)
3465 ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
3466 ty_box(_) => ~"@-ptr",
3467 ty_uniq(_) => ~"~-ptr",
3468 ty_vec(_, _) => ~"vector",
3469 ty_unboxed_vec(_) => ~"unboxed vector",
3470 ty_ptr(_) => ~"*-ptr",
3471 ty_rptr(_, _) => ~"&-ptr",
3472 ty_bare_fn(_) => ~"extern fn",
3473 ty_closure(_) => ~"fn",
3474 ty_trait(ref inner) => format!("trait {}", item_path_str(cx, inner.def_id)),
3475 ty_struct(id, _) => format!("struct {}", item_path_str(cx, id)),
3476 ty_tup(_) => ~"tuple",
3477 ty_infer(TyVar(_)) => ~"inferred type",
3478 ty_infer(IntVar(_)) => ~"integral variable",
3479 ty_infer(FloatVar(_)) => ~"floating-point variable",
3480 ty_param(_) => ~"type parameter",
3481 ty_self(_) => ~"self",
3482 ty_err => ~"type error"
3486 pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> ~str {
3489 * Explains the source of a type err in a short,
3490 * human readable way. This is meant to be placed in
3491 * parentheses after some larger message. You should
3492 * also invoke `note_and_explain_type_err()` afterwards
3493 * to present additional details, particularly when
3494 * it comes to lifetime-related errors. */
3496 fn terr_vstore_kind_to_str(k: terr_vstore_kind) -> ~str {
3501 terr_trait => ~"trait"
3506 terr_mismatch => ~"types differ",
3507 terr_purity_mismatch(values) => {
3508 format!("expected {} fn but found {} fn",
3509 values.expected.to_str(), values.found.to_str())
3511 terr_abi_mismatch(values) => {
3512 format!("expected {} fn but found {} fn",
3513 values.expected.to_str(), values.found.to_str())
3515 terr_onceness_mismatch(values) => {
3516 format!("expected {} fn but found {} fn",
3517 values.expected.to_str(), values.found.to_str())
3519 terr_sigil_mismatch(values) => {
3520 format!("expected {} closure, found {} closure",
3521 values.expected.to_str(),
3522 values.found.to_str())
3524 terr_mutability => ~"values differ in mutability",
3525 terr_box_mutability => ~"boxed values differ in mutability",
3526 terr_vec_mutability => ~"vectors differ in mutability",
3527 terr_ptr_mutability => ~"pointers differ in mutability",
3528 terr_ref_mutability => ~"references differ in mutability",
3529 terr_ty_param_size(values) => {
3530 format!("expected a type with {} type params \
3531 but found one with {} type params",
3532 values.expected, values.found)
3534 terr_tuple_size(values) => {
3535 format!("expected a tuple with {} elements \
3536 but found one with {} elements",
3537 values.expected, values.found)
3539 terr_record_size(values) => {
3540 format!("expected a record with {} fields \
3541 but found one with {} fields",
3542 values.expected, values.found)
3544 terr_record_mutability => {
3545 ~"record elements differ in mutability"
3547 terr_record_fields(values) => {
3548 format!("expected a record with field `{}` but found one with field \
3550 token::get_ident(values.expected),
3551 token::get_ident(values.found))
3553 terr_arg_count => ~"incorrect number of function parameters",
3554 terr_regions_does_not_outlive(..) => {
3555 format!("lifetime mismatch")
3557 terr_regions_not_same(..) => {
3558 format!("lifetimes are not the same")
3560 terr_regions_no_overlap(..) => {
3561 format!("lifetimes do not intersect")
3563 terr_regions_insufficiently_polymorphic(br, _) => {
3564 format!("expected bound lifetime parameter {}, \
3565 but found concrete lifetime",
3566 bound_region_ptr_to_str(cx, br))
3568 terr_regions_overly_polymorphic(br, _) => {
3569 format!("expected concrete lifetime, \
3570 but found bound lifetime parameter {}",
3571 bound_region_ptr_to_str(cx, br))
3573 terr_vstores_differ(k, ref values) => {
3574 format!("{} storage differs: expected `{}` but found `{}`",
3575 terr_vstore_kind_to_str(k),
3576 vstore_to_str(cx, (*values).expected),
3577 vstore_to_str(cx, (*values).found))
3579 terr_trait_stores_differ(_, ref values) => {
3580 format!("trait storage differs: expected `{}` but found `{}`",
3581 trait_store_to_str(cx, (*values).expected),
3582 trait_store_to_str(cx, (*values).found))
3584 terr_in_field(err, fname) => {
3585 format!("in field `{}`, {}", token::get_ident(fname),
3586 type_err_to_str(cx, err))
3588 terr_sorts(values) => {
3589 format!("expected {} but found {}",
3590 ty_sort_str(cx, values.expected),
3591 ty_sort_str(cx, values.found))
3593 terr_traits(values) => {
3594 format!("expected trait `{}` but found trait `{}`",
3595 item_path_str(cx, values.expected),
3596 item_path_str(cx, values.found))
3598 terr_builtin_bounds(values) => {
3599 if values.expected.is_empty() {
3600 format!("expected no bounds but found `{}`",
3601 values.found.user_string(cx))
3602 } else if values.found.is_empty() {
3603 format!("expected bounds `{}` but found no bounds",
3604 values.expected.user_string(cx))
3606 format!("expected bounds `{}` but found bounds `{}`",
3607 values.expected.user_string(cx),
3608 values.found.user_string(cx))
3611 terr_integer_as_char => {
3612 format!("expected an integral type but found `char`")
3614 terr_int_mismatch(ref values) => {
3615 format!("expected `{}` but found `{}`",
3616 values.expected.to_str(),
3617 values.found.to_str())
3619 terr_float_mismatch(ref values) => {
3620 format!("expected `{}` but found `{}`",
3621 values.expected.to_str(),
3622 values.found.to_str())
3624 terr_variadic_mismatch(ref values) => {
3625 format!("expected {} fn but found {} function",
3626 if values.expected { "variadic" } else { "non-variadic" },
3627 if values.found { "variadic" } else { "non-variadic" })
3632 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
3634 terr_regions_does_not_outlive(subregion, superregion) => {
3635 note_and_explain_region(cx, "", subregion, "...");
3636 note_and_explain_region(cx, "...does not necessarily outlive ",
3639 terr_regions_not_same(region1, region2) => {
3640 note_and_explain_region(cx, "", region1, "...");
3641 note_and_explain_region(cx, "...is not the same lifetime as ",
3644 terr_regions_no_overlap(region1, region2) => {
3645 note_and_explain_region(cx, "", region1, "...");
3646 note_and_explain_region(cx, "...does not overlap ",
3649 terr_regions_insufficiently_polymorphic(_, conc_region) => {
3650 note_and_explain_region(cx,
3651 "concrete lifetime that was found is ",
3654 terr_regions_overly_polymorphic(_, conc_region) => {
3655 note_and_explain_region(cx,
3656 "expected concrete lifetime is ",
3663 pub fn def_has_ty_params(def: ast::Def) -> bool {
3665 ast::DefFn(_, _) | ast::DefVariant(_, _, _) | ast::DefStruct(_)
3671 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
3672 cx.provided_method_sources.borrow().find(&id).map(|x| *x)
3675 pub fn provided_trait_methods(cx: &ctxt, id: ast::DefId) -> Vec<@Method> {
3678 match cx.map.find(id.node) {
3679 Some(ast_map::NodeItem(item)) => {
3681 ItemTrait(_, _, ref ms) => {
3683 ast_util::split_trait_methods(ms.as_slice());
3685 .map(|m| method(cx, ast_util::local_def(m.id)))
3689 cx.sess.bug(format!("provided_trait_methods: \
3690 `{:?}` is not a trait",
3696 cx.sess.bug(format!("provided_trait_methods: `{:?}` is not \
3703 csearch::get_provided_trait_methods(cx, id)
3707 pub fn trait_supertraits(cx: &ctxt, id: ast::DefId) -> @Vec<@TraitRef> {
3709 match cx.supertraits.borrow().find(&id) {
3710 Some(&trait_refs) => { return trait_refs; }
3711 None => {} // Continue.
3714 // Not in the cache. It had better be in the metadata, which means it
3715 // shouldn't be local.
3716 assert!(!is_local(id));
3718 // Get the supertraits out of the metadata and create the
3719 // TraitRef for each.
3720 let result = @csearch::get_supertraits(cx, id);
3721 cx.supertraits.borrow_mut().insert(id, result);
3725 pub fn trait_ref_supertraits(cx: &ctxt, trait_ref: &ty::TraitRef) -> Vec<@TraitRef> {
3726 let supertrait_refs = trait_supertraits(cx, trait_ref.def_id);
3727 supertrait_refs.map(
3728 |supertrait_ref| supertrait_ref.subst(cx, &trait_ref.substs))
3731 fn lookup_locally_or_in_crate_store<V:Clone>(
3734 map: &mut DefIdMap<V>,
3735 load_external: || -> V) -> V {
3737 * Helper for looking things up in the various maps
3738 * that are populated during typeck::collect (e.g.,
3739 * `cx.methods`, `cx.tcache`, etc). All of these share
3740 * the pattern that if the id is local, it should have
3741 * been loaded into the map by the `typeck::collect` phase.
3742 * If the def-id is external, then we have to go consult
3743 * the crate loading code (and cache the result for the future).
3746 match map.find_copy(&def_id) {
3747 Some(v) => { return v; }
3751 if def_id.krate == ast::LOCAL_CRATE {
3752 fail!("No def'n found for {:?} in tcx.{}", def_id, descr);
3754 let v = load_external();
3755 map.insert(def_id, v.clone());
3759 pub fn trait_method(cx: &ctxt, trait_did: ast::DefId, idx: uint) -> @Method {
3760 let method_def_id = *ty::trait_method_def_ids(cx, trait_did).get(idx);
3761 ty::method(cx, method_def_id)
3765 pub fn trait_methods(cx: &ctxt, trait_did: ast::DefId) -> @Vec<@Method> {
3766 let mut trait_methods = cx.trait_methods_cache.borrow_mut();
3767 match trait_methods.find(&trait_did) {
3768 Some(&methods) => methods,
3770 let def_ids = ty::trait_method_def_ids(cx, trait_did);
3771 let methods = @def_ids.map(|d| ty::method(cx, *d));
3772 trait_methods.insert(trait_did, methods);
3778 pub fn method(cx: &ctxt, id: ast::DefId) -> @Method {
3779 lookup_locally_or_in_crate_store("methods", id,
3780 &mut *cx.methods.borrow_mut(), || {
3781 @csearch::get_method(cx, id)
3785 pub fn trait_method_def_ids(cx: &ctxt, id: ast::DefId) -> @Vec<DefId> {
3786 lookup_locally_or_in_crate_store("trait_method_def_ids",
3788 &mut *cx.trait_method_def_ids.borrow_mut(),
3790 @csearch::get_trait_method_def_ids(&cx.sess.cstore, id)
3794 pub fn impl_trait_ref(cx: &ctxt, id: ast::DefId) -> Option<@TraitRef> {
3795 match cx.impl_trait_cache.borrow().find(&id) {
3796 Some(&ret) => { return ret; }
3800 let ret = if id.krate == ast::LOCAL_CRATE {
3801 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
3802 match cx.map.find(id.node) {
3803 Some(ast_map::NodeItem(item)) => {
3805 ast::ItemImpl(_, ref opt_trait, _, _) => {
3808 Some(ty::node_id_to_trait_ref(cx, t.ref_id))
3819 csearch::get_impl_trait(cx, id)
3822 cx.impl_trait_cache.borrow_mut().insert(id, ret);
3826 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
3827 let def = *tcx.def_map.borrow()
3829 .expect("no def-map entry for trait");
3830 ast_util::def_id_of_def(def)
3833 pub fn try_add_builtin_trait(tcx: &ctxt,
3834 trait_def_id: ast::DefId,
3835 builtin_bounds: &mut BuiltinBounds) -> bool {
3836 //! Checks whether `trait_ref` refers to one of the builtin
3837 //! traits, like `Send`, and adds the corresponding
3838 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
3839 //! is a builtin trait.
3841 match tcx.lang_items.to_builtin_kind(trait_def_id) {
3842 Some(bound) => { builtin_bounds.add(bound); true }
3847 pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> {
3849 ty_trait(~TyTrait { def_id: id, .. }) | ty_struct(id, _) | ty_enum(id, _) => Some(id),
3856 pub struct VariantInfo {
3858 arg_names: Option<Vec<ast::Ident> >,
3868 /// Creates a new VariantInfo from the corresponding ast representation.
3870 /// Does not do any caching of the value in the type context.
3871 pub fn from_ast_variant(cx: &ctxt,
3872 ast_variant: &ast::Variant,
3873 discriminant: Disr) -> VariantInfo {
3874 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
3876 match ast_variant.node.kind {
3877 ast::TupleVariantKind(ref args) => {
3878 let arg_tys = if args.len() > 0 {
3879 ty_fn_args(ctor_ty).map(|a| *a)
3884 return VariantInfo {
3888 name: ast_variant.node.name,
3889 id: ast_util::local_def(ast_variant.node.id),
3890 disr_val: discriminant,
3891 vis: ast_variant.node.vis
3894 ast::StructVariantKind(ref struct_def) => {
3896 let fields: &[StructField] = struct_def.fields.as_slice();
3898 assert!(fields.len() > 0);
3900 let arg_tys = ty_fn_args(ctor_ty).map(|a| *a);
3901 let arg_names = fields.iter().map(|field| {
3902 match field.node.kind {
3903 NamedField(ident, _) => ident,
3904 UnnamedField(..) => cx.sess.bug(
3905 "enum_variants: all fields in struct must have a name")
3909 return VariantInfo {
3911 arg_names: Some(arg_names),
3913 name: ast_variant.node.name,
3914 id: ast_util::local_def(ast_variant.node.id),
3915 disr_val: discriminant,
3916 vis: ast_variant.node.vis
3923 pub fn substd_enum_variants(cx: &ctxt,
3926 -> Vec<@VariantInfo> {
3927 enum_variants(cx, id).iter().map(|variant_info| {
3928 let substd_args = variant_info.args.iter()
3929 .map(|aty| subst(cx, substs, *aty)).collect();
3931 let substd_ctor_ty = subst(cx, substs, variant_info.ctor_ty);
3935 ctor_ty: substd_ctor_ty,
3936 ..(**variant_info).clone()
3941 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> ~str {
3942 with_path(cx, id, |path| ast_map::path_to_str(path))
3947 TraitDtor(DefId, bool)
3951 pub fn is_not_present(&self) -> bool {
3958 pub fn is_present(&self) -> bool {
3959 !self.is_not_present()
3962 pub fn has_drop_flag(&self) -> bool {
3965 &TraitDtor(_, flag) => flag
3970 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
3971 Otherwise return none. */
3972 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
3973 match cx.destructor_for_type.borrow().find(&struct_id) {
3974 Some(&method_def_id) => {
3975 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
3977 TraitDtor(method_def_id, flag)
3983 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
3984 ty_dtor(cx, struct_id).is_present()
3987 pub fn with_path<T>(cx: &ctxt, id: ast::DefId, f: |ast_map::PathElems| -> T) -> T {
3988 if id.krate == ast::LOCAL_CRATE {
3989 cx.map.with_path(id.node, f)
3991 f(ast_map::Values(csearch::get_item_path(cx, id).iter()).chain(None))
3995 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
3996 enum_variants(cx, id).len() == 1
3999 pub fn type_is_empty(cx: &ctxt, t: t) -> bool {
4000 match ty::get(t).sty {
4001 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
4006 pub fn enum_variants(cx: &ctxt, id: ast::DefId) -> @Vec<@VariantInfo> {
4007 match cx.enum_var_cache.borrow().find(&id) {
4008 Some(&variants) => return variants,
4009 _ => { /* fallthrough */ }
4012 let result = if ast::LOCAL_CRATE != id.krate {
4013 @csearch::get_enum_variants(cx, id)
4016 Although both this code and check_enum_variants in typeck/check
4017 call eval_const_expr, it should never get called twice for the same
4018 expr, since check_enum_variants also updates the enum_var_cache
4021 match cx.map.get(id.node) {
4022 ast_map::NodeItem(item) => {
4024 ast::ItemEnum(ref enum_definition, _) => {
4025 let mut last_discriminant: Option<Disr> = None;
4026 @enum_definition.variants.iter().map(|&variant| {
4028 let mut discriminant = match last_discriminant {
4029 Some(val) => val + 1,
4030 None => INITIAL_DISCRIMINANT_VALUE
4033 match variant.node.disr_expr {
4034 Some(e) => match const_eval::eval_const_expr_partial(cx, e) {
4035 Ok(const_eval::const_int(val)) => {
4036 discriminant = val as Disr
4038 Ok(const_eval::const_uint(val)) => {
4039 discriminant = val as Disr
4044 "expected signed integer \
4059 @VariantInfo::from_ast_variant(cx,
4062 last_discriminant = Some(discriminant);
4068 cx.sess.bug("enum_variants: id not bound to an enum")
4072 _ => cx.sess.bug("enum_variants: id not bound to an enum")
4077 cx.enum_var_cache.borrow_mut().insert(id, result);
4082 // Returns information about the enum variant with the given ID:
4083 pub fn enum_variant_with_id(cx: &ctxt,
4084 enum_id: ast::DefId,
4085 variant_id: ast::DefId)
4087 let variants = enum_variants(cx, enum_id);
4089 while i < variants.len() {
4090 let variant = *variants.get(i);
4091 if variant.id == variant_id {
4096 cx.sess.bug("enum_variant_with_id(): no variant exists with that ID");
4100 // If the given item is in an external crate, looks up its type and adds it to
4101 // the type cache. Returns the type parameters and type.
4102 pub fn lookup_item_type(cx: &ctxt,
4104 -> ty_param_bounds_and_ty {
4105 lookup_locally_or_in_crate_store(
4106 "tcache", did, &mut *cx.tcache.borrow_mut(),
4107 || csearch::get_type(cx, did))
4110 pub fn lookup_impl_vtables(cx: &ctxt,
4112 -> typeck::impl_res {
4113 lookup_locally_or_in_crate_store(
4114 "impl_vtables", did, &mut *cx.impl_vtables.borrow_mut(),
4115 || csearch::get_impl_vtables(cx, did) )
4118 /// Given the did of a trait, returns its canonical trait ref.
4119 pub fn lookup_trait_def(cx: &ctxt, did: ast::DefId) -> @ty::TraitDef {
4120 let mut trait_defs = cx.trait_defs.borrow_mut();
4121 match trait_defs.find(&did) {
4122 Some(&trait_def) => {
4123 // The item is in this crate. The caller should have added it to the
4124 // type cache already
4128 assert!(did.krate != ast::LOCAL_CRATE);
4129 let trait_def = @csearch::get_trait_def(cx, did);
4130 trait_defs.insert(did, trait_def);
4136 /// Iterate over meta_items of a definition.
4137 // (This should really be an iterator, but that would require csearch and
4138 // decoder to use iterators instead of higher-order functions.)
4139 pub fn each_attr(tcx: &ctxt, did: DefId, f: |@MetaItem| -> bool) -> bool {
4141 let item = tcx.map.expect_item(did.node);
4142 item.attrs.iter().advance(|attr| f(attr.node.value))
4144 let mut cont = true;
4145 csearch::get_item_attrs(&tcx.sess.cstore, did, |meta_items| {
4147 cont = meta_items.iter().advance(|ptrptr| f(*ptrptr));
4154 /// Determine whether an item is annotated with an attribute
4155 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
4156 let mut found = false;
4157 each_attr(tcx, did, |item| {
4158 if item.name().equiv(&attr) {
4168 /// Determine whether an item is annotated with `#[packed]`
4169 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
4170 has_attr(tcx, did, "packed")
4173 /// Determine whether an item is annotated with `#[simd]`
4174 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
4175 has_attr(tcx, did, "simd")
4178 // Obtain the representation annotation for a definition.
4179 pub fn lookup_repr_hint(tcx: &ctxt, did: DefId) -> attr::ReprAttr {
4180 let mut acc = attr::ReprAny;
4181 ty::each_attr(tcx, did, |meta| {
4182 acc = attr::find_repr_attr(tcx.sess.diagnostic(), meta, acc);
4188 // Look up a field ID, whether or not it's local
4189 // Takes a list of type substs in case the struct is generic
4190 pub fn lookup_field_type(tcx: &ctxt,
4195 let t = if id.krate == ast::LOCAL_CRATE {
4196 node_id_to_type(tcx, id.node)
4198 let mut tcache = tcx.tcache.borrow_mut();
4199 match tcache.find(&id) {
4200 Some(&ty_param_bounds_and_ty {ty, ..}) => ty,
4202 let tpt = csearch::get_field_type(tcx, struct_id, id);
4203 tcache.insert(id, tpt.clone());
4208 subst(tcx, substs, t)
4211 // Look up the list of field names and IDs for a given struct
4212 // Fails if the id is not bound to a struct.
4213 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
4214 if did.krate == ast::LOCAL_CRATE {
4215 match cx.map.find(did.node) {
4216 Some(ast_map::NodeItem(i)) => {
4218 ast::ItemStruct(struct_def, _) => {
4219 struct_field_tys(struct_def.fields.as_slice())
4221 _ => cx.sess.bug("struct ID bound to non-struct")
4224 Some(ast_map::NodeVariant(ref variant)) => {
4225 match (*variant).node.kind {
4226 ast::StructVariantKind(struct_def) => {
4227 struct_field_tys(struct_def.fields.as_slice())
4230 cx.sess.bug("struct ID bound to enum variant that \
4237 format!("struct ID not bound to an item: {}",
4238 cx.map.node_to_str(did.node)));
4242 csearch::get_struct_fields(&cx.sess.cstore, did)
4246 pub fn lookup_struct_field(cx: &ctxt,
4248 field_id: ast::DefId)
4250 let r = lookup_struct_fields(cx, parent);
4251 match r.iter().find(
4252 |f| f.id.node == field_id.node) {
4254 None => cx.sess.bug("struct ID not found in parent's fields")
4258 fn struct_field_tys(fields: &[StructField]) -> Vec<field_ty> {
4259 fields.iter().map(|field| {
4260 match field.node.kind {
4261 NamedField(ident, visibility) => {
4264 id: ast_util::local_def(field.node.id),
4268 UnnamedField(visibility) => {
4270 name: syntax::parse::token::special_idents::unnamed_field.name,
4271 id: ast_util::local_def(field.node.id),
4279 // Returns a list of fields corresponding to the struct's items. trans uses
4280 // this. Takes a list of substs with which to instantiate field types.
4281 pub fn struct_fields(cx: &ctxt, did: ast::DefId, substs: &substs)
4283 lookup_struct_fields(cx, did).map(|f| {
4285 // FIXME #6993: change type of field to Name and get rid of new()
4286 ident: ast::Ident::new(f.name),
4288 ty: lookup_field_type(cx, did, f.id, substs),
4295 pub fn is_binopable(cx: &ctxt, ty: t, op: ast::BinOp) -> bool {
4296 static tycat_other: int = 0;
4297 static tycat_bool: int = 1;
4298 static tycat_char: int = 2;
4299 static tycat_int: int = 3;
4300 static tycat_float: int = 4;
4301 static tycat_bot: int = 5;
4302 static tycat_raw_ptr: int = 6;
4304 static opcat_add: int = 0;
4305 static opcat_sub: int = 1;
4306 static opcat_mult: int = 2;
4307 static opcat_shift: int = 3;
4308 static opcat_rel: int = 4;
4309 static opcat_eq: int = 5;
4310 static opcat_bit: int = 6;
4311 static opcat_logic: int = 7;
4313 fn opcat(op: ast::BinOp) -> int {
4315 ast::BiAdd => opcat_add,
4316 ast::BiSub => opcat_sub,
4317 ast::BiMul => opcat_mult,
4318 ast::BiDiv => opcat_mult,
4319 ast::BiRem => opcat_mult,
4320 ast::BiAnd => opcat_logic,
4321 ast::BiOr => opcat_logic,
4322 ast::BiBitXor => opcat_bit,
4323 ast::BiBitAnd => opcat_bit,
4324 ast::BiBitOr => opcat_bit,
4325 ast::BiShl => opcat_shift,
4326 ast::BiShr => opcat_shift,
4327 ast::BiEq => opcat_eq,
4328 ast::BiNe => opcat_eq,
4329 ast::BiLt => opcat_rel,
4330 ast::BiLe => opcat_rel,
4331 ast::BiGe => opcat_rel,
4332 ast::BiGt => opcat_rel
4336 fn tycat(cx: &ctxt, ty: t) -> int {
4337 if type_is_simd(cx, ty) {
4338 return tycat(cx, simd_type(cx, ty))
4341 ty_char => tycat_char,
4342 ty_bool => tycat_bool,
4343 ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
4344 ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
4345 ty_bot => tycat_bot,
4346 ty_ptr(_) => tycat_raw_ptr,
4351 static t: bool = true;
4352 static f: bool = false;
4355 // +, -, *, shift, rel, ==, bit, logic
4356 /*other*/ [f, f, f, f, f, f, f, f],
4357 /*bool*/ [f, f, f, f, t, t, t, t],
4358 /*char*/ [f, f, f, f, t, t, f, f],
4359 /*int*/ [t, t, t, t, t, t, t, f],
4360 /*float*/ [t, t, t, f, t, t, f, f],
4361 /*bot*/ [t, t, t, t, t, t, t, t],
4362 /*raw ptr*/ [f, f, f, f, t, t, f, f]];
4364 return tbl[tycat(cx, ty)][opcat(op)];
4367 pub fn ty_params_to_tys(tcx: &ctxt, generics: &ast::Generics) -> Vec<t> {
4368 Vec::from_fn(generics.ty_params.len(), |i| {
4369 let id = generics.ty_params.get(i).id;
4370 ty::mk_param(tcx, i, ast_util::local_def(id))
4374 /// Returns an equivalent type with all the typedefs and self regions removed.
4375 pub fn normalize_ty(cx: &ctxt, t: t) -> t {
4376 let u = TypeNormalizer(cx).fold_ty(t);
4379 struct TypeNormalizer<'a>(&'a ctxt);
4381 impl<'a> TypeFolder for TypeNormalizer<'a> {
4382 fn tcx<'a>(&'a self) -> &'a ctxt { let TypeNormalizer(c) = *self; c }
4384 fn fold_ty(&mut self, t: ty::t) -> ty::t {
4385 match self.tcx().normalized_cache.borrow().find_copy(&t) {
4390 let t_norm = ty_fold::super_fold_ty(self, t);
4391 self.tcx().normalized_cache.borrow_mut().insert(t, t_norm);
4395 fn fold_vstore(&mut self, vstore: vstore) -> vstore {
4397 vstore_fixed(..) | vstore_uniq => vstore,
4398 vstore_slice(_) => vstore_slice(ReStatic)
4402 fn fold_region(&mut self, _: ty::Region) -> ty::Region {
4406 fn fold_substs(&mut self,
4409 substs { regions: ErasedRegions,
4410 self_ty: ty_fold::fold_opt_ty(self, substs.self_ty),
4411 tps: ty_fold::fold_ty_vec(self, substs.tps.as_slice()) }
4414 fn fold_sig(&mut self,
4417 // The binder-id is only relevant to bound regions, which
4418 // are erased at trans time.
4420 binder_id: ast::DUMMY_NODE_ID,
4421 inputs: ty_fold::fold_ty_vec(self, sig.inputs.as_slice()),
4422 output: self.fold_ty(sig.output),
4423 variadic: sig.variadic,
4429 pub trait ExprTyProvider {
4430 fn expr_ty(&self, ex: &ast::Expr) -> t;
4431 fn ty_ctxt<'a>(&'a self) -> &'a ctxt;
4434 impl ExprTyProvider for ctxt {
4435 fn expr_ty(&self, ex: &ast::Expr) -> t {
4439 fn ty_ctxt<'a>(&'a self) -> &'a ctxt {
4444 // Returns the repeat count for a repeating vector expression.
4445 pub fn eval_repeat_count<T: ExprTyProvider>(tcx: &T, count_expr: &ast::Expr) -> uint {
4446 match const_eval::eval_const_expr_partial(tcx, count_expr) {
4447 Ok(ref const_val) => match *const_val {
4448 const_eval::const_int(count) => if count < 0 {
4449 tcx.ty_ctxt().sess.span_err(count_expr.span,
4450 "expected positive integer for \
4451 repeat count but found negative integer");
4454 return count as uint
4456 const_eval::const_uint(count) => return count as uint,
4457 const_eval::const_float(count) => {
4458 tcx.ty_ctxt().sess.span_err(count_expr.span,
4459 "expected positive integer for \
4460 repeat count but found float");
4461 return count as uint;
4463 const_eval::const_str(_) => {
4464 tcx.ty_ctxt().sess.span_err(count_expr.span,
4465 "expected positive integer for \
4466 repeat count but found string");
4469 const_eval::const_bool(_) => {
4470 tcx.ty_ctxt().sess.span_err(count_expr.span,
4471 "expected positive integer for \
4472 repeat count but found boolean");
4475 const_eval::const_binary(_) => {
4476 tcx.ty_ctxt().sess.span_err(count_expr.span,
4477 "expected positive integer for \
4478 repeat count but found binary array");
4483 tcx.ty_ctxt().sess.span_err(count_expr.span,
4484 "expected constant integer for repeat count \
4485 but found variable");
4491 // Determine what purity to check a nested function under
4492 pub fn determine_inherited_purity(parent: (ast::Purity, ast::NodeId),
4493 child: (ast::Purity, ast::NodeId),
4494 child_sigil: ast::Sigil)
4495 -> (ast::Purity, ast::NodeId) {
4496 // If the closure is a stack closure and hasn't had some non-standard
4497 // purity inferred for it, then check it under its parent's purity.
4498 // Otherwise, use its own
4500 ast::BorrowedSigil if child.val0() == ast::ImpureFn => parent,
4505 // Iterate over a type parameter's bounded traits and any supertraits
4506 // of those traits, ignoring kinds.
4507 // Here, the supertraits are the transitive closure of the supertrait
4508 // relation on the supertraits from each bounded trait's constraint
4510 pub fn each_bound_trait_and_supertraits(tcx: &ctxt,
4511 bounds: &[@TraitRef],
4512 f: |@TraitRef| -> bool)
4514 for &bound_trait_ref in bounds.iter() {
4515 let mut supertrait_set = HashMap::new();
4516 let mut trait_refs = Vec::new();
4519 // Seed the worklist with the trait from the bound
4520 supertrait_set.insert(bound_trait_ref.def_id, ());
4521 trait_refs.push(bound_trait_ref);
4523 // Add the given trait ty to the hash map
4524 while i < trait_refs.len() {
4525 debug!("each_bound_trait_and_supertraits(i={:?}, trait_ref={})",
4526 i, trait_refs.get(i).repr(tcx));
4528 if !f(*trait_refs.get(i)) {
4532 // Add supertraits to supertrait_set
4533 let supertrait_refs = trait_ref_supertraits(tcx,
4534 *trait_refs.get(i));
4535 for &supertrait_ref in supertrait_refs.iter() {
4536 debug!("each_bound_trait_and_supertraits(supertrait_ref={})",
4537 supertrait_ref.repr(tcx));
4539 let d_id = supertrait_ref.def_id;
4540 if !supertrait_set.contains_key(&d_id) {
4541 // FIXME(#5527) Could have same trait multiple times
4542 supertrait_set.insert(d_id, ());
4543 trait_refs.push(supertrait_ref);
4553 pub fn count_traits_and_supertraits(tcx: &ctxt,
4554 type_param_defs: &[TypeParameterDef]) -> uint {
4556 for type_param_def in type_param_defs.iter() {
4557 each_bound_trait_and_supertraits(
4558 tcx, type_param_def.bounds.trait_bounds.as_slice(), |_| {
4566 pub fn get_tydesc_ty(tcx: &ctxt) -> Result<t, ~str> {
4567 tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
4568 tcx.intrinsic_defs.borrow().find_copy(&tydesc_lang_item)
4569 .expect("Failed to resolve TyDesc")
4573 pub fn get_opaque_ty(tcx: &ctxt) -> Result<t, ~str> {
4574 tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| {
4575 tcx.intrinsic_defs.borrow().find_copy(&opaque_lang_item)
4576 .expect("Failed to resolve Opaque")
4580 pub fn visitor_object_ty(tcx: &ctxt,
4581 region: ty::Region) -> Result<(@TraitRef, t), ~str> {
4582 let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) {
4584 Err(s) => { return Err(s); }
4586 let substs = substs {
4587 regions: ty::NonerasedRegions(OwnedSlice::empty()),
4591 let trait_ref = @TraitRef { def_id: trait_lang_item, substs: substs };
4595 trait_ref.substs.clone(),
4596 RegionTraitStore(region),
4598 EmptyBuiltinBounds())))
4601 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> @ItemVariances {
4602 lookup_locally_or_in_crate_store(
4603 "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
4604 || @csearch::get_item_variances(&tcx.sess.cstore, item_id))
4607 /// Records a trait-to-implementation mapping.
4608 fn record_trait_implementation(tcx: &ctxt,
4609 trait_def_id: DefId,
4610 implementation: @Impl) {
4611 let implementation_list;
4612 let mut trait_impls = tcx.trait_impls.borrow_mut();
4613 match trait_impls.find(&trait_def_id) {
4615 implementation_list = @RefCell::new(Vec::new());
4616 trait_impls.insert(trait_def_id, implementation_list);
4618 Some(&existing_implementation_list) => {
4619 implementation_list = existing_implementation_list
4623 implementation_list.borrow_mut().push(implementation);
4626 /// Populates the type context with all the implementations for the given type
4628 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
4629 type_id: ast::DefId) {
4630 if type_id.krate == LOCAL_CRATE {
4633 if tcx.populated_external_types.borrow().contains(&type_id) {
4637 csearch::each_implementation_for_type(&tcx.sess.cstore, type_id,
4638 |implementation_def_id| {
4639 let implementation = @csearch::get_impl(tcx, implementation_def_id);
4641 // Record the trait->implementation mappings, if applicable.
4642 let associated_traits = csearch::get_impl_trait(tcx,
4643 implementation.did);
4644 for trait_ref in associated_traits.iter() {
4645 record_trait_implementation(tcx,
4650 // For any methods that use a default implementation, add them to
4651 // the map. This is a bit unfortunate.
4652 for method in implementation.methods.iter() {
4653 for source in method.provided_source.iter() {
4654 tcx.provided_method_sources.borrow_mut()
4655 .insert(method.def_id, *source);
4659 // If this is an inherent implementation, record it.
4660 if associated_traits.is_none() {
4661 let implementation_list;
4662 let mut inherent_impls = tcx.inherent_impls.borrow_mut();
4663 match inherent_impls.find(&type_id) {
4665 implementation_list = @RefCell::new(Vec::new());
4666 inherent_impls.insert(type_id, implementation_list);
4668 Some(&existing_implementation_list) => {
4669 implementation_list = existing_implementation_list;
4672 implementation_list.borrow_mut().push(implementation);
4675 // Store the implementation info.
4676 tcx.impls.borrow_mut().insert(implementation_def_id, implementation);
4679 tcx.populated_external_types.borrow_mut().insert(type_id);
4682 /// Populates the type context with all the implementations for the given
4683 /// trait if necessary.
4684 pub fn populate_implementations_for_trait_if_necessary(
4686 trait_id: ast::DefId) {
4687 if trait_id.krate == LOCAL_CRATE {
4690 if tcx.populated_external_traits.borrow().contains(&trait_id) {
4694 csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id,
4695 |implementation_def_id| {
4696 let implementation = @csearch::get_impl(tcx, implementation_def_id);
4698 // Record the trait->implementation mapping.
4699 record_trait_implementation(tcx, trait_id, implementation);
4701 // For any methods that use a default implementation, add them to
4702 // the map. This is a bit unfortunate.
4703 for method in implementation.methods.iter() {
4704 for source in method.provided_source.iter() {
4705 tcx.provided_method_sources.borrow_mut()
4706 .insert(method.def_id, *source);
4710 // Store the implementation info.
4711 tcx.impls.borrow_mut().insert(implementation_def_id, implementation);
4714 tcx.populated_external_traits.borrow_mut().insert(trait_id);
4717 /// Given the def_id of an impl, return the def_id of the trait it implements.
4718 /// If it implements no trait, return `None`.
4719 pub fn trait_id_of_impl(tcx: &ctxt,
4720 def_id: ast::DefId) -> Option<ast::DefId> {
4721 let node = match tcx.map.find(def_id.node) {
4726 ast_map::NodeItem(item) => {
4728 ast::ItemImpl(_, Some(ref trait_ref), _, _) => {
4729 Some(node_id_to_trait_ref(tcx, trait_ref.ref_id).def_id)
4738 /// If the given def ID describes a method belonging to a trait (either a
4739 /// default method or an implementation of a trait method), return the ID of
4740 /// the trait that the method belongs to. Otherwise, return `None`.
4741 pub fn trait_of_method(tcx: &ctxt, def_id: ast::DefId)
4742 -> Option<ast::DefId> {
4743 if def_id.krate != LOCAL_CRATE {
4744 return csearch::get_trait_of_method(&tcx.sess.cstore, def_id, tcx);
4746 match tcx.methods.borrow().find(&def_id).map(|m| *m) {
4748 match method.container {
4749 TraitContainer(def_id) => Some(def_id),
4750 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
4757 /// If the given def ID describes a method belonging to a trait, (either a
4758 /// default method or an implementation of a trait method), return the ID of
4759 /// the method inside trait definition (this means that if the given def ID
4760 /// is already that of the original trait method, then the return value is
4762 /// Otherwise, return `None`.
4763 pub fn trait_method_of_method(tcx: &ctxt,
4764 def_id: ast::DefId) -> Option<ast::DefId> {
4765 let method = match tcx.methods.borrow().find(&def_id) {
4767 None => return None,
4769 let name = method.ident.name;
4770 match trait_of_method(tcx, def_id) {
4771 Some(trait_did) => {
4772 let trait_methods = ty::trait_methods(tcx, trait_did);
4773 trait_methods.iter()
4774 .position(|m| m.ident.name == name)
4775 .map(|idx| ty::trait_method(tcx, trait_did, idx).def_id)
4781 /// Creates a hash of the type `t` which will be the same no matter what crate
4782 /// context it's calculated within. This is used by the `type_id` intrinsic.
4783 pub fn hash_crate_independent(tcx: &ctxt, t: t, svh: &Svh) -> u64 {
4784 let mut state = sip::SipState::new();
4785 macro_rules! byte( ($b:expr) => { ($b as u8).hash(&mut state) } );
4786 macro_rules! hash( ($e:expr) => { $e.hash(&mut state) } );
4788 let region = |_state: &mut sip::SipState, r: Region| {
4798 tcx.sess.bug("non-static region found when hashing a type")
4802 let vstore = |state: &mut sip::SipState, v: vstore| {
4804 vstore_fixed(_) => 0u8.hash(state),
4805 vstore_uniq => 1u8.hash(state),
4806 vstore_slice(r) => {
4812 let did = |state: &mut sip::SipState, did: DefId| {
4813 let h = if ast_util::is_local(did) {
4816 tcx.sess.cstore.get_crate_hash(did.krate)
4818 h.as_str().hash(state);
4819 did.node.hash(state);
4821 let mt = |state: &mut sip::SipState, mt: mt| {
4822 mt.mutbl.hash(state);
4824 ty::walk_ty(t, |t| {
4825 match ty::get(t).sty {
4828 ty_bool => byte!(2),
4829 ty_char => byte!(3),
4859 vstore(&mut state, v);
4867 region(&mut state, r);
4870 ty_bare_fn(ref b) => {
4875 ty_closure(ref c) => {
4881 region(&mut state, c.region);
4883 ty_trait(~ty::TyTrait { def_id: d, store, mutability: m, bounds, .. }) => {
4887 UniqTraitStore => byte!(0),
4888 RegionTraitStore(r) => {
4890 region(&mut state, r);
4896 ty_struct(d, _) => {
4900 ty_tup(ref inner) => {
4907 did(&mut state, p.def_id);
4913 ty_infer(_) => unreachable!(),
4914 ty_err => byte!(23),
4915 ty_unboxed_vec(m) => {
4926 pub fn to_str(self) -> &'static str {
4929 Contravariant => "-",
4936 pub fn construct_parameter_environment(
4938 self_bound: Option<@TraitRef>,
4939 item_type_params: &[TypeParameterDef],
4940 method_type_params: &[TypeParameterDef],
4941 item_region_params: &[RegionParameterDef],
4942 method_region_params: &[RegionParameterDef],
4943 free_id: ast::NodeId)
4944 -> ParameterEnvironment
4946 /*! See `ParameterEnvironment` struct def'n for details */
4949 // Construct the free substs.
4953 let self_ty = self_bound.map(|t| ty::mk_self(tcx, t.def_id));
4956 let num_item_type_params = item_type_params.len();
4957 let num_method_type_params = method_type_params.len();
4958 let num_type_params = num_item_type_params + num_method_type_params;
4959 let type_params = Vec::from_fn(num_type_params, |i| {
4960 let def_id = if i < num_item_type_params {
4961 item_type_params[i].def_id
4963 method_type_params[i - num_item_type_params].def_id
4966 ty::mk_param(tcx, i, def_id)
4969 // map bound 'a => free 'a
4970 let region_params = {
4971 fn push_region_params(mut accum: Vec<ty::Region>,
4972 free_id: ast::NodeId,
4973 region_params: &[RegionParameterDef])
4974 -> Vec<ty::Region> {
4975 for r in region_params.iter() {
4977 ty::ReFree(ty::FreeRegion {
4979 bound_region: ty::BrNamed(r.def_id, r.name)}));
4984 let t = push_region_params(vec!(), free_id, item_region_params);
4985 push_region_params(t, free_id, method_region_params)
4988 let free_substs = substs {
4991 regions: ty::NonerasedRegions(OwnedSlice::from_vec(region_params))
4995 // Compute the bounds on Self and the type parameters.
4998 let self_bound_substd = self_bound.map(|b| b.subst(tcx, &free_substs));
4999 let type_param_bounds_substd = Vec::from_fn(num_type_params, |i| {
5000 if i < num_item_type_params {
5001 (*item_type_params[i].bounds).subst(tcx, &free_substs)
5003 let j = i - num_item_type_params;
5004 (*method_type_params[j].bounds).subst(tcx, &free_substs)
5008 debug!("construct_parameter_environment: free_id={} \
5010 self_param_bound={} \
5011 type_param_bound={}",
5013 free_substs.repr(tcx),
5014 self_bound_substd.repr(tcx),
5015 type_param_bounds_substd.repr(tcx));
5017 ty::ParameterEnvironment {
5018 free_substs: free_substs,
5019 self_param_bound: self_bound_substd,
5020 type_param_bounds: type_param_bounds_substd,
5025 pub fn empty() -> substs {
5029 regions: NonerasedRegions(OwnedSlice::empty())
5035 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
5037 ast::MutMutable => MutBorrow,
5038 ast::MutImmutable => ImmBorrow,
5042 pub fn to_user_str(&self) -> &'static str {
5044 MutBorrow => "mutable",
5045 ImmBorrow => "immutable",
5046 UniqueImmBorrow => "uniquely immutable",
5050 pub fn to_short_str(&self) -> &'static str {
5054 UniqueImmBorrow => "own",