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 mc = middle::mem_categorization;
18 use middle::const_eval;
20 use middle::dependency_format;
21 use middle::lang_items::OpaqueStructLangItem;
22 use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem};
25 use middle::resolve_lifetime;
27 use middle::subst::{Subst, Substs, VecPerParamSpace};
28 use middle::stability;
31 use middle::typeck::MethodCall;
33 use middle::ty_fold::{TypeFoldable,TypeFolder};
35 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_str};
36 use util::ppaux::{trait_store_to_str, ty_to_str};
37 use util::ppaux::{Repr, UserString};
38 use util::common::{indenter};
39 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet, FnvHashMap};
41 use std::cell::{Cell, RefCell};
45 use std::hash::{Hash, sip, Writer};
47 use std::iter::AdditiveIterator;
51 use std::collections::{HashMap, HashSet};
54 use syntax::ast_util::{is_local, lit_is_str};
57 use syntax::attr::AttrMetaMethods;
58 use syntax::codemap::Span;
59 use syntax::parse::token;
60 use syntax::parse::token::InternedString;
61 use syntax::{ast, ast_map};
62 use syntax::util::small_vector::SmallVector;
63 use std::collections::enum_set::{EnumSet, CLike};
67 pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0;
71 #[deriving(PartialEq, Eq, Hash)]
73 pub ident: ast::Ident,
78 pub enum MethodContainer {
79 TraitContainer(ast::DefId),
80 ImplContainer(ast::DefId),
85 pub ident: ast::Ident,
86 pub generics: ty::Generics,
88 pub explicit_self: ast::ExplicitSelf_,
89 pub vis: ast::Visibility,
90 pub def_id: ast::DefId,
91 pub container: MethodContainer,
93 // If this method is provided, we need to know where it came from
94 pub provided_source: Option<ast::DefId>
98 pub fn new(ident: ast::Ident,
99 generics: ty::Generics,
101 explicit_self: ast::ExplicitSelf_,
102 vis: ast::Visibility,
104 container: MethodContainer,
105 provided_source: Option<ast::DefId>)
111 explicit_self: explicit_self,
114 container: container,
115 provided_source: provided_source
119 pub fn container_id(&self) -> ast::DefId {
120 match self.container {
121 TraitContainer(id) => id,
122 ImplContainer(id) => id,
127 #[deriving(Clone, PartialEq, Eq, Hash)]
130 pub mutbl: ast::Mutability,
133 #[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
134 pub enum TraitStore {
137 /// &Trait and &mut Trait
138 RegionTraitStore(Region, ast::Mutability),
142 pub struct field_ty {
145 pub vis: ast::Visibility,
146 pub origin: ast::DefId, // The DefId of the struct in which the field is declared.
149 // Contains information needed to resolve types and (in the future) look up
150 // the types of AST nodes.
151 #[deriving(PartialEq, Eq, Hash)]
152 pub struct creader_cache_key {
158 pub type creader_cache = RefCell<HashMap<creader_cache_key, t>>;
160 pub struct intern_key {
164 // NB: Do not replace this with #[deriving(PartialEq)]. The automatically-derived
165 // implementation will not recurse through sty and you will get stack
167 impl cmp::PartialEq for intern_key {
168 fn eq(&self, other: &intern_key) -> bool {
170 *self.sty == *other.sty
173 fn ne(&self, other: &intern_key) -> bool {
178 impl Eq for intern_key {}
180 impl<W:Writer> Hash<W> for intern_key {
181 fn hash(&self, s: &mut W) {
182 unsafe { (*self.sty).hash(s) }
186 pub enum ast_ty_to_ty_cache_entry {
187 atttce_unresolved, /* not resolved yet */
188 atttce_resolved(t) /* resolved to a type, irrespective of region */
191 #[deriving(Clone, PartialEq, Decodable, Encodable)]
192 pub struct ItemVariances {
193 pub types: VecPerParamSpace<Variance>,
194 pub regions: VecPerParamSpace<Variance>,
197 #[deriving(Clone, PartialEq, Decodable, Encodable, Show)]
199 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
200 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
201 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
202 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
206 pub enum AutoAdjustment {
207 AutoAddEnv(ty::TraitStore),
208 AutoDerefRef(AutoDerefRef),
209 AutoObject(ty::TraitStore,
211 ast::DefId, /* Trait ID */
212 subst::Substs /* Trait substitutions */)
215 #[deriving(Clone, Decodable, Encodable)]
216 pub struct AutoDerefRef {
217 pub autoderefs: uint,
218 pub autoref: Option<AutoRef>
221 #[deriving(Clone, Decodable, Encodable, PartialEq, Show)]
223 /// Convert from T to &T
224 AutoPtr(Region, ast::Mutability),
226 /// Convert from ~[]/&[] to &[] or str
227 AutoBorrowVec(Region, ast::Mutability),
229 /// Convert from ~[]/&[] to &&[] or str
230 AutoBorrowVecRef(Region, ast::Mutability),
232 /// Convert from T to *T
233 AutoUnsafe(ast::Mutability),
235 /// Convert from Box<Trait>/&Trait to &Trait
236 AutoBorrowObj(Region, ast::Mutability),
239 /// A restriction that certain types must be the same size. The use of
240 /// `transmute` gives rise to these restrictions.
241 pub struct TransmuteRestriction {
242 /// The span from whence the restriction comes.
244 /// The type being transmuted from.
246 /// The type being transmuted to.
250 /// The data structure to keep track of all the information that typechecker
251 /// generates so that so that it can be reused and doesn't have to be redone
254 /// Specifically use a speedy hash algorithm for this hash map, it's used
256 pub interner: RefCell<FnvHashMap<intern_key, Box<t_box_>>>,
257 pub next_id: Cell<uint>,
259 pub def_map: resolve::DefMap,
261 pub named_region_map: resolve_lifetime::NamedRegionMap,
263 pub region_maps: middle::region::RegionMaps,
265 /// Stores the types for various nodes in the AST. Note that this table
266 /// is not guaranteed to be populated until after typeck. See
267 /// typeck::check::fn_ctxt for details.
268 pub node_types: node_type_table,
270 /// Stores the type parameters which were substituted to obtain the type
271 /// of this node. This only applies to nodes that refer to entities
272 /// param<eterized by type parameters, such as generic fns, types, or
274 pub item_substs: RefCell<NodeMap<ItemSubsts>>,
276 /// Maps from a method to the method "descriptor"
277 pub methods: RefCell<DefIdMap<Rc<Method>>>,
279 /// Maps from a trait def-id to a list of the def-ids of its methods
280 pub trait_method_def_ids: RefCell<DefIdMap<Rc<Vec<DefId>>>>,
282 /// A cache for the trait_methods() routine
283 pub trait_methods_cache: RefCell<DefIdMap<Rc<Vec<Rc<Method>>>>>,
285 pub impl_trait_cache: RefCell<DefIdMap<Option<Rc<ty::TraitRef>>>>,
287 pub trait_refs: RefCell<NodeMap<Rc<TraitRef>>>,
288 pub trait_defs: RefCell<DefIdMap<Rc<TraitDef>>>,
290 pub map: ast_map::Map,
291 pub intrinsic_defs: RefCell<DefIdMap<t>>,
292 pub freevars: RefCell<freevars::freevar_map>,
293 pub tcache: type_cache,
294 pub rcache: creader_cache,
295 pub short_names_cache: RefCell<HashMap<t, String>>,
296 pub needs_unwind_cleanup_cache: RefCell<HashMap<t, bool>>,
297 pub tc_cache: RefCell<HashMap<uint, TypeContents>>,
298 pub ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry>>,
299 pub enum_var_cache: RefCell<DefIdMap<Rc<Vec<Rc<VariantInfo>>>>>,
300 pub ty_param_defs: RefCell<NodeMap<TypeParameterDef>>,
301 pub adjustments: RefCell<NodeMap<AutoAdjustment>>,
302 pub normalized_cache: RefCell<HashMap<t, t>>,
303 pub lang_items: middle::lang_items::LanguageItems,
304 /// A mapping of fake provided method def_ids to the default implementation
305 pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
306 pub supertraits: RefCell<DefIdMap<Rc<Vec<Rc<TraitRef>>>>>,
307 pub superstructs: RefCell<DefIdMap<Option<ast::DefId>>>,
308 pub struct_fields: RefCell<DefIdMap<Rc<Vec<field_ty>>>>,
310 /// Maps from def-id of a type or region parameter to its
311 /// (inferred) variance.
312 pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
314 /// A mapping from the def ID of an enum or struct type to the def ID
315 /// of the method that implements its destructor. If the type is not
316 /// present in this map, it does not have a destructor. This map is
317 /// populated during the coherence phase of typechecking.
318 pub destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
320 /// A method will be in this list if and only if it is a destructor.
321 pub destructors: RefCell<DefIdSet>,
323 /// Maps a trait onto a list of impls of that trait.
324 pub trait_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
326 /// Maps a DefId of a type to a list of its inherent impls.
327 /// Contains implementations of methods that are inherent to a type.
328 /// Methods in these implementations don't need to be exported.
329 pub inherent_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
331 /// Maps a DefId of an impl to a list of its methods.
332 /// Note that this contains all of the impls that we know about,
333 /// including ones in other crates. It's not clear that this is the best
335 pub impl_methods: RefCell<DefIdMap<Vec<ast::DefId>>>,
337 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
338 /// present in this set can be warned about.
339 pub used_unsafe: RefCell<NodeSet>,
341 /// Set of nodes which mark locals as mutable which end up getting used at
342 /// some point. Local variable definitions not in this set can be warned
344 pub used_mut_nodes: RefCell<NodeSet>,
346 /// vtable resolution information for impl declarations
347 pub impl_vtables: typeck::impl_vtable_map,
349 /// The set of external nominal types whose implementations have been read.
350 /// This is used for lazy resolution of methods.
351 pub populated_external_types: RefCell<DefIdSet>,
353 /// The set of external traits whose implementations have been read. This
354 /// is used for lazy resolution of traits.
355 pub populated_external_traits: RefCell<DefIdSet>,
358 pub upvar_borrow_map: RefCell<UpvarBorrowMap>,
360 /// These two caches are used by const_eval when decoding external statics
361 /// and variants that are found.
362 pub extern_const_statics: RefCell<DefIdMap<Option<Gc<ast::Expr>>>>,
363 pub extern_const_variants: RefCell<DefIdMap<Option<Gc<ast::Expr>>>>,
365 pub method_map: typeck::MethodMap,
366 pub vtable_map: typeck::vtable_map,
368 pub dependency_formats: RefCell<dependency_format::Dependencies>,
370 pub node_lint_levels: RefCell<HashMap<(ast::NodeId, lint::LintId),
373 /// The types that must be asserted to be the same size for `transmute`
374 /// to be valid. We gather up these restrictions in the intrinsicck pass
375 /// and check them in trans.
376 pub transmute_restrictions: RefCell<Vec<TransmuteRestriction>>,
378 /// Maps any item's def-id to its stability index.
379 pub stability: RefCell<stability::Index>,
390 // a meta-pub flag: subst may be required if the type has parameters, a self
391 // type, or references bound regions
392 needs_subst = 1 | 2 | 8
395 pub type t_box = &'static t_box_;
403 // To reduce refcounting cost, we're representing types as unsafe pointers
404 // throughout the compiler. These are simply casted t_box values. Use ty::get
405 // to cast them back to a box. (Without the cast, compiler performance suffers
406 // ~15%.) This does mean that a t value relies on the ctxt to keep its box
407 // alive, and using ty::get is unsafe when the ctxt is no longer alive.
410 #[allow(raw_pointer_deriving)]
411 #[deriving(Clone, PartialEq, Eq, Hash)]
412 pub struct t { inner: *const t_opaque }
414 impl fmt::Show for t {
415 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
420 pub fn get(t: t) -> t_box {
422 let t2: t_box = mem::transmute(t);
427 pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
428 (tb.flags & (flag as uint)) != 0u
430 pub fn type_has_params(t: t) -> bool {
431 tbox_has_flag(get(t), has_params)
433 pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
434 pub fn type_needs_infer(t: t) -> bool {
435 tbox_has_flag(get(t), needs_infer)
437 pub fn type_id(t: t) -> uint { get(t).id }
439 #[deriving(Clone, PartialEq, Eq, Hash)]
440 pub struct BareFnTy {
441 pub fn_style: ast::FnStyle,
446 #[deriving(Clone, PartialEq, Eq, Hash)]
447 pub struct ClosureTy {
448 pub fn_style: ast::FnStyle,
449 pub onceness: ast::Onceness,
450 pub store: TraitStore,
451 pub bounds: BuiltinBounds,
456 * Signature of a function type, which I have arbitrarily
457 * decided to use to refer to the input/output types.
459 * - `binder_id` is the node id where this fn type appeared;
460 * it is used to identify all the bound regions appearing
461 * in the input/output types that are bound by this fn type
462 * (vs some enclosing or enclosed fn type)
463 * - `inputs` is the list of arguments and their modes.
464 * - `output` is the return type.
465 * - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
467 #[deriving(Clone, PartialEq, Eq, Hash)]
469 pub binder_id: ast::NodeId,
475 #[deriving(Clone, PartialEq, Eq, Hash)]
477 pub space: subst::ParamSpace,
482 /// Representation of regions:
483 #[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
485 // Region bound in a type or fn declaration which will be
486 // substituted 'early' -- that is, at the same time when type
487 // parameters are substituted.
488 ReEarlyBound(/* param id */ ast::NodeId,
493 // Region bound in a function scope, which will be substituted when the
494 // function is called. The first argument must be the `binder_id` of
495 // some enclosing function signature.
496 ReLateBound(/* binder_id */ ast::NodeId, BoundRegion),
498 /// When checking a function body, the types of all arguments and so forth
499 /// that refer to bound region parameters are modified to refer to free
500 /// region parameters.
503 /// A concrete region naming some expression within the current function.
506 /// Static data that has an "infinite" lifetime. Top in the region lattice.
509 /// A region variable. Should not exist after typeck.
510 ReInfer(InferRegion),
512 /// Empty lifetime is for data that is never accessed.
513 /// Bottom in the region lattice. We treat ReEmpty somewhat
514 /// specially; at least right now, we do not generate instances of
515 /// it during the GLB computations, but rather
516 /// generate an error instead. This is to improve error messages.
517 /// The only way to get an instance of ReEmpty is to have a region
518 /// variable with no constraints.
523 * Upvars do not get their own node-id. Instead, we use the pair of
524 * the original var id (that is, the root variable that is referenced
525 * by the upvar) and the id of the closure expression.
527 #[deriving(Clone, PartialEq, Eq, Hash)]
529 pub var_id: ast::NodeId,
530 pub closure_expr_id: ast::NodeId,
533 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
534 pub enum BorrowKind {
535 /// Data must be immutable and is aliasable.
538 /// Data must be immutable but not aliasable. This kind of borrow
539 /// cannot currently be expressed by the user and is used only in
540 /// implicit closure bindings. It is needed when you the closure
541 /// is borrowing or mutating a mutable referent, e.g.:
543 /// let x: &mut int = ...;
544 /// let y = || *x += 5;
546 /// If we were to try to translate this closure into a more explicit
547 /// form, we'd encounter an error with the code as written:
549 /// struct Env { x: & &mut int }
550 /// let x: &mut int = ...;
551 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
552 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
554 /// This is then illegal because you cannot mutate a `&mut` found
555 /// in an aliasable location. To solve, you'd have to translate with
556 /// an `&mut` borrow:
558 /// struct Env { x: & &mut int }
559 /// let x: &mut int = ...;
560 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
561 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
563 /// Now the assignment to `**env.x` is legal, but creating a
564 /// mutable pointer to `x` is not because `x` is not mutable. We
565 /// could fix this by declaring `x` as `let mut x`. This is ok in
566 /// user code, if awkward, but extra weird for closures, since the
567 /// borrow is hidden.
569 /// So we introduce a "unique imm" borrow -- the referent is
570 /// immutable, but not aliasable. This solves the problem. For
571 /// simplicity, we don't give users the way to express this
572 /// borrow, it's just used when translating closures.
575 /// Data is mutable and not aliasable.
580 * Information describing the borrowing of an upvar. This is computed
581 * during `typeck`, specifically by `regionck`. The general idea is
582 * that the compiler analyses treat closures like:
584 * let closure: &'e fn() = || {
585 * x = 1; // upvar x is assigned to
586 * use(y); // upvar y is read
587 * foo(&z); // upvar z is borrowed immutably
590 * as if they were "desugared" to something loosely like:
592 * struct Vars<'x,'y,'z> { x: &'x mut int,
595 * let closure: &'e fn() = {
601 * let env: &'e mut Vars<'x,'y,'z> = &mut Vars { x: &'x mut x,
607 * This is basically what happens at runtime. The closure is basically
608 * an existentially quantified version of the `(env, f)` pair.
610 * This data structure indicates the region and mutability of a single
611 * one of the `x...z` borrows.
613 * It may not be obvious why each borrowed variable gets its own
614 * lifetime (in the desugared version of the example, these are indicated
615 * by the lifetime parameters `'x`, `'y`, and `'z` in the `Vars` definition).
616 * Each such lifetime must encompass the lifetime `'e` of the closure itself,
617 * but need not be identical to it. The reason that this makes sense:
619 * - Callers are only permitted to invoke the closure, and hence to
620 * use the pointers, within the lifetime `'e`, so clearly `'e` must
621 * be a sublifetime of `'x...'z`.
622 * - The closure creator knows which upvars were borrowed by the closure
623 * and thus `x...z` will be reserved for `'x...'z` respectively.
624 * - Through mutation, the borrowed upvars can actually escape
625 * the closure, so sometimes it is necessary for them to be larger
626 * than the closure lifetime itself.
628 #[deriving(PartialEq, Clone)]
629 pub struct UpvarBorrow {
630 pub kind: BorrowKind,
631 pub region: ty::Region,
634 pub type UpvarBorrowMap = HashMap<UpvarId, UpvarBorrow>;
637 pub fn is_bound(&self) -> bool {
639 &ty::ReEarlyBound(..) => true,
640 &ty::ReLateBound(..) => true,
646 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
647 pub struct FreeRegion {
648 pub scope_id: NodeId,
649 pub bound_region: BoundRegion
652 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
653 pub enum BoundRegion {
654 /// An anonymous region parameter for a given fn (&T)
657 /// Named region parameters for functions (a in &'a T)
659 /// The def-id is needed to distinguish free regions in
660 /// the event of shadowing.
661 BrNamed(ast::DefId, ast::Name),
663 /// Fresh bound identifiers created during GLB computations.
672 macro_rules! def_prim_ty(
673 ($name:ident, $sty:expr, $id:expr) => (
674 pub static $name: t_box_ = t_box_ {
682 def_prim_ty!(TY_NIL, super::ty_nil, 0)
683 def_prim_ty!(TY_BOOL, super::ty_bool, 1)
684 def_prim_ty!(TY_CHAR, super::ty_char, 2)
685 def_prim_ty!(TY_INT, super::ty_int(ast::TyI), 3)
686 def_prim_ty!(TY_I8, super::ty_int(ast::TyI8), 4)
687 def_prim_ty!(TY_I16, super::ty_int(ast::TyI16), 5)
688 def_prim_ty!(TY_I32, super::ty_int(ast::TyI32), 6)
689 def_prim_ty!(TY_I64, super::ty_int(ast::TyI64), 7)
690 def_prim_ty!(TY_UINT, super::ty_uint(ast::TyU), 8)
691 def_prim_ty!(TY_U8, super::ty_uint(ast::TyU8), 9)
692 def_prim_ty!(TY_U16, super::ty_uint(ast::TyU16), 10)
693 def_prim_ty!(TY_U32, super::ty_uint(ast::TyU32), 11)
694 def_prim_ty!(TY_U64, super::ty_uint(ast::TyU64), 12)
695 def_prim_ty!(TY_F32, super::ty_float(ast::TyF32), 14)
696 def_prim_ty!(TY_F64, super::ty_float(ast::TyF64), 15)
698 pub static TY_BOT: t_box_ = t_box_ {
701 flags: super::has_ty_bot as uint,
704 pub static TY_ERR: t_box_ = t_box_ {
707 flags: super::has_ty_err as uint,
710 pub static LAST_PRIMITIVE_ID: uint = 18;
713 // NB: If you change this, you'll probably want to change the corresponding
714 // AST structure in libsyntax/ast.rs as well.
715 #[deriving(Clone, PartialEq, Eq, Hash)]
722 ty_uint(ast::UintTy),
723 ty_float(ast::FloatTy),
724 ty_enum(DefId, Substs),
728 ty_vec(mt, Option<uint>), // Second field is length.
731 ty_bare_fn(BareFnTy),
732 ty_closure(Box<ClosureTy>),
733 ty_trait(Box<TyTrait>),
734 ty_struct(DefId, Substs),
737 ty_param(ParamTy), // type parameter
738 ty_infer(InferTy), // something used only during inference/typeck
739 ty_err, // Also only used during inference/typeck, to represent
740 // the type of an erroneous expression (helps cut down
741 // on non-useful type error messages)
744 #[deriving(Clone, PartialEq, Eq, Hash)]
748 pub bounds: BuiltinBounds
751 #[deriving(PartialEq, Eq, Hash)]
752 pub struct TraitRef {
757 #[deriving(Clone, PartialEq)]
758 pub enum IntVarValue {
760 UintType(ast::UintTy),
763 #[deriving(Clone, Show)]
764 pub enum terr_vstore_kind {
771 #[deriving(Clone, Show)]
772 pub struct expected_found<T> {
777 // Data structures used in type unification
778 #[deriving(Clone, Show)]
781 terr_fn_style_mismatch(expected_found<FnStyle>),
782 terr_onceness_mismatch(expected_found<Onceness>),
783 terr_abi_mismatch(expected_found<abi::Abi>),
785 terr_sigil_mismatch(expected_found<TraitStore>),
790 terr_tuple_size(expected_found<uint>),
791 terr_ty_param_size(expected_found<uint>),
792 terr_record_size(expected_found<uint>),
793 terr_record_mutability,
794 terr_record_fields(expected_found<Ident>),
796 terr_regions_does_not_outlive(Region, Region),
797 terr_regions_not_same(Region, Region),
798 terr_regions_no_overlap(Region, Region),
799 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
800 terr_regions_overly_polymorphic(BoundRegion, Region),
801 terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
802 terr_sorts(expected_found<t>),
803 terr_integer_as_char,
804 terr_int_mismatch(expected_found<IntVarValue>),
805 terr_float_mismatch(expected_found<ast::FloatTy>),
806 terr_traits(expected_found<ast::DefId>),
807 terr_builtin_bounds(expected_found<BuiltinBounds>),
808 terr_variadic_mismatch(expected_found<bool>)
811 #[deriving(PartialEq, Eq, Hash)]
812 pub struct ParamBounds {
813 pub builtin_bounds: BuiltinBounds,
814 pub trait_bounds: Vec<Rc<TraitRef>>
817 pub type BuiltinBounds = EnumSet<BuiltinBound>;
819 #[deriving(Clone, Encodable, PartialEq, Eq, Decodable, Hash, Show)]
821 pub enum BuiltinBound {
829 pub fn empty_builtin_bounds() -> BuiltinBounds {
833 pub fn all_builtin_bounds() -> BuiltinBounds {
834 let mut set = EnumSet::empty();
835 set.add(BoundStatic);
842 impl CLike for BuiltinBound {
843 fn to_uint(&self) -> uint {
846 fn from_uint(v: uint) -> BuiltinBound {
847 unsafe { mem::transmute(v) }
851 #[deriving(Clone, PartialEq, Eq, Hash)]
856 #[deriving(Clone, PartialEq, Eq, Hash)]
861 #[deriving(Clone, PartialEq, Eq, Hash)]
862 pub struct FloatVid {
866 #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)]
867 pub struct RegionVid {
871 #[deriving(Clone, PartialEq, Eq, Hash)]
878 #[deriving(Clone, Encodable, Decodable, Eq, Hash, Show)]
879 pub enum InferRegion {
881 ReSkolemized(uint, BoundRegion)
884 impl cmp::PartialEq for InferRegion {
885 fn eq(&self, other: &InferRegion) -> bool {
886 match ((*self), *other) {
887 (ReVar(rva), ReVar(rvb)) => {
890 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
896 fn ne(&self, other: &InferRegion) -> bool {
897 !((*self) == (*other))
901 impl fmt::Show for TyVid {
902 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
903 write!(f, "<generic #{}>", self.index)
907 impl fmt::Show for IntVid {
908 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
909 write!(f, "<generic integer #{}>", self.index)
913 impl fmt::Show for FloatVid {
914 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
915 write!(f, "<generic float #{}>", self.index)
919 impl fmt::Show for RegionVid {
920 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
921 write!(f, "'<generic lifetime #{}>", self.index)
925 impl fmt::Show for FnSig {
926 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
927 // grr, without tcx not much we can do.
932 impl fmt::Show for InferTy {
933 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
935 TyVar(ref v) => v.fmt(f),
936 IntVar(ref v) => v.fmt(f),
937 FloatVar(ref v) => v.fmt(f),
942 impl fmt::Show for IntVarValue {
943 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
945 IntType(ref v) => v.fmt(f),
946 UintType(ref v) => v.fmt(f),
952 pub struct TypeParameterDef {
953 pub ident: ast::Ident,
954 pub def_id: ast::DefId,
955 pub space: subst::ParamSpace,
957 pub bounds: Rc<ParamBounds>,
958 pub default: Option<ty::t>
961 #[deriving(Encodable, Decodable, Clone)]
962 pub struct RegionParameterDef {
964 pub def_id: ast::DefId,
965 pub space: subst::ParamSpace,
969 /// Information about the type/lifetime parameters associated with an
970 /// item or method. Analogous to ast::Generics.
972 pub struct Generics {
973 pub types: VecPerParamSpace<TypeParameterDef>,
974 pub regions: VecPerParamSpace<RegionParameterDef>,
978 pub fn empty() -> Generics {
979 Generics { types: VecPerParamSpace::empty(),
980 regions: VecPerParamSpace::empty() }
983 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
984 !self.types.get_vec(space).is_empty()
988 /// When type checking, we use the `ParameterEnvironment` to track
989 /// details about the type/lifetime parameters that are in scope.
990 /// It primarily stores the bounds information.
992 /// Note: This information might seem to be redundant with the data in
993 /// `tcx.ty_param_defs`, but it is not. That table contains the
994 /// parameter definitions from an "outside" perspective, but this
995 /// struct will contain the bounds for a parameter as seen from inside
996 /// the function body. Currently the only real distinction is that
997 /// bound lifetime parameters are replaced with free ones, but in the
998 /// future I hope to refine the representation of types so as to make
999 /// more distinctions clearer.
1000 pub struct ParameterEnvironment {
1001 /// A substitution that can be applied to move from
1002 /// the "outer" view of a type or method to the "inner" view.
1003 /// In general, this means converting from bound parameters to
1004 /// free parameters. Since we currently represent bound/free type
1005 /// parameters in the same way, this only has an affect on regions.
1006 pub free_substs: Substs,
1008 /// Bounds on the various type parameters
1009 pub bounds: VecPerParamSpace<ParamBounds>,
1014 /// - `generics`: the set of type parameters and their bounds
1015 /// - `ty`: the base types, which may reference the parameters defined
1018 pub struct Polytype {
1019 pub generics: Generics,
1023 /// As `Polytype` but for a trait ref.
1024 pub struct TraitDef {
1025 pub generics: Generics,
1026 pub bounds: BuiltinBounds,
1027 pub trait_ref: Rc<ty::TraitRef>,
1030 /// Records the substitutions used to translate the polytype for an
1031 /// item into the monotype of an item reference.
1033 pub struct ItemSubsts {
1037 pub type type_cache = RefCell<DefIdMap<Polytype>>;
1039 pub type node_type_table = RefCell<HashMap<uint,t>>;
1041 pub fn mk_ctxt(s: Session,
1042 dm: resolve::DefMap,
1043 named_region_map: resolve_lifetime::NamedRegionMap,
1045 freevars: freevars::freevar_map,
1046 region_maps: middle::region::RegionMaps,
1047 lang_items: middle::lang_items::LanguageItems,
1048 stability: stability::Index)
1051 named_region_map: named_region_map,
1052 item_variance_map: RefCell::new(DefIdMap::new()),
1053 interner: RefCell::new(FnvHashMap::new()),
1054 next_id: Cell::new(primitives::LAST_PRIMITIVE_ID),
1057 region_maps: region_maps,
1058 node_types: RefCell::new(HashMap::new()),
1059 item_substs: RefCell::new(NodeMap::new()),
1060 trait_refs: RefCell::new(NodeMap::new()),
1061 trait_defs: RefCell::new(DefIdMap::new()),
1063 intrinsic_defs: RefCell::new(DefIdMap::new()),
1064 freevars: RefCell::new(freevars),
1065 tcache: RefCell::new(DefIdMap::new()),
1066 rcache: RefCell::new(HashMap::new()),
1067 short_names_cache: RefCell::new(HashMap::new()),
1068 needs_unwind_cleanup_cache: RefCell::new(HashMap::new()),
1069 tc_cache: RefCell::new(HashMap::new()),
1070 ast_ty_to_ty_cache: RefCell::new(NodeMap::new()),
1071 enum_var_cache: RefCell::new(DefIdMap::new()),
1072 methods: RefCell::new(DefIdMap::new()),
1073 trait_method_def_ids: RefCell::new(DefIdMap::new()),
1074 trait_methods_cache: RefCell::new(DefIdMap::new()),
1075 impl_trait_cache: RefCell::new(DefIdMap::new()),
1076 ty_param_defs: RefCell::new(NodeMap::new()),
1077 adjustments: RefCell::new(NodeMap::new()),
1078 normalized_cache: RefCell::new(HashMap::new()),
1079 lang_items: lang_items,
1080 provided_method_sources: RefCell::new(DefIdMap::new()),
1081 supertraits: RefCell::new(DefIdMap::new()),
1082 superstructs: RefCell::new(DefIdMap::new()),
1083 struct_fields: RefCell::new(DefIdMap::new()),
1084 destructor_for_type: RefCell::new(DefIdMap::new()),
1085 destructors: RefCell::new(DefIdSet::new()),
1086 trait_impls: RefCell::new(DefIdMap::new()),
1087 inherent_impls: RefCell::new(DefIdMap::new()),
1088 impl_methods: RefCell::new(DefIdMap::new()),
1089 used_unsafe: RefCell::new(NodeSet::new()),
1090 used_mut_nodes: RefCell::new(NodeSet::new()),
1091 impl_vtables: RefCell::new(DefIdMap::new()),
1092 populated_external_types: RefCell::new(DefIdSet::new()),
1093 populated_external_traits: RefCell::new(DefIdSet::new()),
1094 upvar_borrow_map: RefCell::new(HashMap::new()),
1095 extern_const_statics: RefCell::new(DefIdMap::new()),
1096 extern_const_variants: RefCell::new(DefIdMap::new()),
1097 method_map: RefCell::new(FnvHashMap::new()),
1098 vtable_map: RefCell::new(FnvHashMap::new()),
1099 dependency_formats: RefCell::new(HashMap::new()),
1100 node_lint_levels: RefCell::new(HashMap::new()),
1101 transmute_restrictions: RefCell::new(Vec::new()),
1102 stability: RefCell::new(stability)
1106 // Type constructors
1108 // Interns a type/name combination, stores the resulting box in cx.interner,
1109 // and returns the box as cast to an unsafe ptr (see comments for t above).
1110 pub fn mk_t(cx: &ctxt, st: sty) -> t {
1111 // Check for primitive types.
1113 ty_nil => return mk_nil(),
1114 ty_err => return mk_err(),
1115 ty_bool => return mk_bool(),
1116 ty_int(i) => return mk_mach_int(i),
1117 ty_uint(u) => return mk_mach_uint(u),
1118 ty_float(f) => return mk_mach_float(f),
1119 ty_char => return mk_char(),
1120 ty_bot => return mk_bot(),
1124 let key = intern_key { sty: &st };
1126 match cx.interner.borrow().find(&key) {
1127 Some(t) => unsafe { return mem::transmute(&t.sty); },
1132 fn rflags(r: Region) -> uint {
1133 (has_regions as uint) | {
1135 ty::ReInfer(_) => needs_infer as uint,
1140 fn sflags(substs: &Substs) -> uint {
1142 let mut i = substs.types.iter();
1144 f |= get(*tt).flags;
1146 match substs.regions {
1147 subst::ErasedRegions => {}
1148 subst::NonerasedRegions(ref regions) => {
1149 for r in regions.iter() {
1157 &ty_nil | &ty_bool | &ty_char | &ty_int(_) | &ty_float(_) | &ty_uint(_) |
1159 // You might think that we could just return ty_err for
1160 // any type containing ty_err as a component, and get
1161 // rid of the has_ty_err flag -- likewise for ty_bot (with
1162 // the exception of function types that return bot).
1163 // But doing so caused sporadic memory corruption, and
1164 // neither I (tjc) nor nmatsakis could figure out why,
1165 // so we're doing it this way.
1166 &ty_bot => flags |= has_ty_bot as uint,
1167 &ty_err => flags |= has_ty_err as uint,
1168 &ty_param(ref p) => {
1169 if p.space == subst::SelfSpace {
1170 flags |= has_self as uint;
1172 flags |= has_params as uint;
1175 &ty_infer(_) => flags |= needs_infer as uint,
1176 &ty_enum(_, ref substs) | &ty_struct(_, ref substs) => {
1177 flags |= sflags(substs);
1179 &ty_trait(box ty::TyTrait { ref substs, .. }) => {
1180 flags |= sflags(substs);
1182 &ty_box(tt) | &ty_uniq(tt) => {
1183 flags |= get(tt).flags
1185 &ty_ptr(ref m) | &ty_vec(ref m, _) => {
1186 flags |= get(m.ty).flags;
1188 &ty_rptr(r, ref m) => {
1190 flags |= get(m.ty).flags;
1192 &ty_tup(ref ts) => for tt in ts.iter() { flags |= get(*tt).flags; },
1193 &ty_bare_fn(ref f) => {
1194 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1195 flags |= get(f.sig.output).flags;
1196 // T -> _|_ is *not* _|_ !
1197 flags &= !(has_ty_bot as uint);
1199 &ty_closure(ref f) => {
1201 RegionTraitStore(r, _) => {
1206 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1207 flags |= get(f.sig.output).flags;
1208 // T -> _|_ is *not* _|_ !
1209 flags &= !(has_ty_bot as uint);
1213 let t = box t_box_ {
1215 id: cx.next_id.get(),
1219 let sty_ptr = &t.sty as *const sty;
1221 let key = intern_key {
1225 cx.interner.borrow_mut().insert(key, t);
1227 cx.next_id.set(cx.next_id.get() + 1);
1230 mem::transmute::<*const sty, t>(sty_ptr)
1235 pub fn mk_prim_t(primitive: &'static t_box_) -> t {
1237 mem::transmute::<&'static t_box_, t>(primitive)
1242 pub fn mk_nil() -> t { mk_prim_t(&primitives::TY_NIL) }
1245 pub fn mk_err() -> t { mk_prim_t(&primitives::TY_ERR) }
1248 pub fn mk_bot() -> t { mk_prim_t(&primitives::TY_BOT) }
1251 pub fn mk_bool() -> t { mk_prim_t(&primitives::TY_BOOL) }
1254 pub fn mk_int() -> t { mk_prim_t(&primitives::TY_INT) }
1257 pub fn mk_i8() -> t { mk_prim_t(&primitives::TY_I8) }
1260 pub fn mk_i16() -> t { mk_prim_t(&primitives::TY_I16) }
1263 pub fn mk_i32() -> t { mk_prim_t(&primitives::TY_I32) }
1266 pub fn mk_i64() -> t { mk_prim_t(&primitives::TY_I64) }
1269 pub fn mk_f32() -> t { mk_prim_t(&primitives::TY_F32) }
1272 pub fn mk_f64() -> t { mk_prim_t(&primitives::TY_F64) }
1275 pub fn mk_uint() -> t { mk_prim_t(&primitives::TY_UINT) }
1278 pub fn mk_u8() -> t { mk_prim_t(&primitives::TY_U8) }
1281 pub fn mk_u16() -> t { mk_prim_t(&primitives::TY_U16) }
1284 pub fn mk_u32() -> t { mk_prim_t(&primitives::TY_U32) }
1287 pub fn mk_u64() -> t { mk_prim_t(&primitives::TY_U64) }
1289 pub fn mk_mach_int(tm: ast::IntTy) -> t {
1291 ast::TyI => mk_int(),
1292 ast::TyI8 => mk_i8(),
1293 ast::TyI16 => mk_i16(),
1294 ast::TyI32 => mk_i32(),
1295 ast::TyI64 => mk_i64(),
1299 pub fn mk_mach_uint(tm: ast::UintTy) -> t {
1301 ast::TyU => mk_uint(),
1302 ast::TyU8 => mk_u8(),
1303 ast::TyU16 => mk_u16(),
1304 ast::TyU32 => mk_u32(),
1305 ast::TyU64 => mk_u64(),
1309 pub fn mk_mach_float(tm: ast::FloatTy) -> t {
1311 ast::TyF32 => mk_f32(),
1312 ast::TyF64 => mk_f64(),
1317 pub fn mk_char() -> t { mk_prim_t(&primitives::TY_CHAR) }
1319 pub fn mk_str(cx: &ctxt) -> t {
1323 pub fn mk_str_slice(cx: &ctxt, r: Region, m: ast::Mutability) -> t {
1326 ty: mk_t(cx, ty_str),
1331 pub fn mk_enum(cx: &ctxt, did: ast::DefId, substs: Substs) -> t {
1332 // take a copy of substs so that we own the vectors inside
1333 mk_t(cx, ty_enum(did, substs))
1336 pub fn mk_box(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_box(ty)) }
1338 pub fn mk_uniq(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_uniq(ty)) }
1340 pub fn mk_ptr(cx: &ctxt, tm: mt) -> t { mk_t(cx, ty_ptr(tm)) }
1342 pub fn mk_rptr(cx: &ctxt, r: Region, tm: mt) -> t { mk_t(cx, ty_rptr(r, tm)) }
1344 pub fn mk_mut_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1345 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
1347 pub fn mk_imm_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1348 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
1351 pub fn mk_mut_ptr(cx: &ctxt, ty: t) -> t {
1352 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
1355 pub fn mk_imm_ptr(cx: &ctxt, ty: t) -> t {
1356 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
1359 pub fn mk_nil_ptr(cx: &ctxt) -> t {
1360 mk_ptr(cx, mt {ty: mk_nil(), mutbl: ast::MutImmutable})
1363 pub fn mk_vec(cx: &ctxt, tm: mt, sz: Option<uint>) -> t {
1364 mk_t(cx, ty_vec(tm, sz))
1367 pub fn mk_slice(cx: &ctxt, r: Region, tm: mt) -> t {
1370 ty: mk_vec(cx, tm, None),
1375 pub fn mk_tup(cx: &ctxt, ts: Vec<t>) -> t { mk_t(cx, ty_tup(ts)) }
1377 pub fn mk_closure(cx: &ctxt, fty: ClosureTy) -> t {
1378 mk_t(cx, ty_closure(box fty))
1381 pub fn mk_bare_fn(cx: &ctxt, fty: BareFnTy) -> t {
1382 mk_t(cx, ty_bare_fn(fty))
1385 pub fn mk_ctor_fn(cx: &ctxt,
1386 binder_id: ast::NodeId,
1387 input_tys: &[ty::t],
1388 output: ty::t) -> t {
1389 let input_args = input_tys.iter().map(|t| *t).collect();
1392 fn_style: ast::NormalFn,
1395 binder_id: binder_id,
1404 pub fn mk_trait(cx: &ctxt,
1407 bounds: BuiltinBounds)
1409 // take a copy of substs so that we own the vectors inside
1410 let inner = box TyTrait {
1415 mk_t(cx, ty_trait(inner))
1418 pub fn mk_struct(cx: &ctxt, struct_id: ast::DefId, substs: Substs) -> t {
1419 // take a copy of substs so that we own the vectors inside
1420 mk_t(cx, ty_struct(struct_id, substs))
1423 pub fn mk_var(cx: &ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) }
1425 pub fn mk_int_var(cx: &ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) }
1427 pub fn mk_float_var(cx: &ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) }
1429 pub fn mk_infer(cx: &ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) }
1431 pub fn mk_param(cx: &ctxt, space: subst::ParamSpace, n: uint, k: DefId) -> t {
1432 mk_t(cx, ty_param(ParamTy { space: space, idx: n, def_id: k }))
1435 pub fn mk_self_type(cx: &ctxt, did: ast::DefId) -> t {
1436 mk_param(cx, subst::SelfSpace, 0, did)
1439 pub fn mk_param_from_def(cx: &ctxt, def: &TypeParameterDef) -> t {
1440 mk_param(cx, def.space, def.index, def.def_id)
1443 pub fn walk_ty(ty: t, f: |t|) {
1444 maybe_walk_ty(ty, |t| { f(t); true });
1447 pub fn maybe_walk_ty(ty: t, f: |t| -> bool) {
1452 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) |
1453 ty_str | ty_infer(_) | ty_param(_) | ty_err => {
1455 ty_box(ty) | ty_uniq(ty) => maybe_walk_ty(ty, f),
1456 ty_ptr(ref tm) | ty_rptr(_, ref tm) | ty_vec(ref tm, _) => {
1457 maybe_walk_ty(tm.ty, f);
1459 ty_enum(_, ref substs) | ty_struct(_, ref substs) |
1460 ty_trait(box TyTrait { ref substs, .. }) => {
1461 for subty in (*substs).types.iter() {
1462 maybe_walk_ty(*subty, |x| f(x));
1465 ty_tup(ref ts) => { for tt in ts.iter() { maybe_walk_ty(*tt, |x| f(x)); } }
1466 ty_bare_fn(ref ft) => {
1467 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1468 maybe_walk_ty(ft.sig.output, f);
1470 ty_closure(ref ft) => {
1471 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1472 maybe_walk_ty(ft.sig.output, f);
1477 // Folds types from the bottom up.
1478 pub fn fold_ty(cx: &ctxt, t0: t, fldop: |t| -> t) -> t {
1479 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
1483 pub fn walk_regions_and_ty(cx: &ctxt, ty: t, fldr: |r: Region|, fldt: |t: t|)
1485 ty_fold::RegionFolder::general(cx,
1487 |t| { fldt(t); t }).fold_ty(ty)
1491 pub fn empty() -> ItemSubsts {
1492 ItemSubsts { substs: Substs::empty() }
1495 pub fn is_noop(&self) -> bool {
1496 self.substs.is_noop()
1502 pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil }
1504 pub fn type_is_bot(ty: t) -> bool {
1505 (get(ty).flags & (has_ty_bot as uint)) != 0
1508 pub fn type_is_error(ty: t) -> bool {
1509 (get(ty).flags & (has_ty_err as uint)) != 0
1512 pub fn type_needs_subst(ty: t) -> bool {
1513 tbox_has_flag(get(ty), needs_subst)
1516 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
1517 tref.substs.types.any(|&t| type_is_error(t))
1520 pub fn type_is_ty_var(ty: t) -> bool {
1522 ty_infer(TyVar(_)) => true,
1527 pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool }
1529 pub fn type_is_self(ty: t) -> bool {
1531 ty_param(ref p) => p.space == subst::SelfSpace,
1536 fn type_is_slice(ty:t) -> bool {
1538 ty_rptr(_, mt) => match get(mt.ty).sty {
1539 ty_vec(_, None) | ty_str => true,
1546 pub fn type_is_structural(ty: t) -> bool {
1548 ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) |
1549 ty_vec(_, Some(_)) => true,
1550 _ => type_is_slice(ty) | type_is_trait(ty)
1554 pub fn type_is_simd(cx: &ctxt, ty: t) -> bool {
1556 ty_struct(did, _) => lookup_simd(cx, did),
1561 pub fn sequence_element_type(cx: &ctxt, ty: t) -> t {
1563 ty_vec(mt, Some(_)) => mt.ty,
1564 ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) |
1565 ty_box(t) | ty_uniq(t) => match get(t).sty {
1566 ty_vec(mt, None) => mt.ty,
1567 ty_str => mk_mach_uint(ast::TyU8),
1568 _ => cx.sess.bug("sequence_element_type called on non-sequence value"),
1570 _ => cx.sess.bug("sequence_element_type called on non-sequence value"),
1574 pub fn simd_type(cx: &ctxt, ty: t) -> t {
1576 ty_struct(did, ref substs) => {
1577 let fields = lookup_struct_fields(cx, did);
1578 lookup_field_type(cx, did, fields.get(0).id, substs)
1580 _ => fail!("simd_type called on invalid type")
1584 pub fn simd_size(cx: &ctxt, ty: t) -> uint {
1586 ty_struct(did, _) => {
1587 let fields = lookup_struct_fields(cx, did);
1590 _ => fail!("simd_size called on invalid type")
1594 pub fn type_is_boxed(ty: t) -> bool {
1601 pub fn type_is_region_ptr(ty: t) -> bool {
1603 ty_rptr(_, mt) => match get(mt.ty).sty {
1604 // FIXME(nrc, DST) slices weren't regarded as rptrs, so we preserve this
1605 // odd behaviour for now. (But ~[] were unique. I have no idea why).
1606 ty_vec(_, None) | ty_str | ty_trait(..) => false,
1613 pub fn type_is_unsafe_ptr(ty: t) -> bool {
1615 ty_ptr(_) => return true,
1620 pub fn type_is_unique(ty: t) -> bool {
1622 ty_uniq(_) => match get(ty).sty {
1623 ty_trait(..) => false,
1631 A scalar type is one that denotes an atomic datum, with no sub-components.
1632 (A ty_ptr is scalar because it represents a non-managed pointer, so its
1633 contents are abstract to rustc.)
1635 pub fn type_is_scalar(ty: t) -> bool {
1637 ty_nil | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
1638 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
1639 ty_bare_fn(..) | ty_ptr(_) => true,
1644 /// Returns true if this type is a floating point type and false otherwise.
1645 pub fn type_is_floating_point(ty: t) -> bool {
1647 ty_float(_) => true,
1652 pub fn type_needs_drop(cx: &ctxt, ty: t) -> bool {
1653 type_contents(cx, ty).needs_drop(cx)
1656 // Some things don't need cleanups during unwinding because the
1657 // task can free them all at once later. Currently only things
1658 // that only contain scalars and shared boxes can avoid unwind
1660 pub fn type_needs_unwind_cleanup(cx: &ctxt, ty: t) -> bool {
1661 match cx.needs_unwind_cleanup_cache.borrow().find(&ty) {
1662 Some(&result) => return result,
1666 let mut tycache = HashSet::new();
1667 let needs_unwind_cleanup =
1668 type_needs_unwind_cleanup_(cx, ty, &mut tycache, false);
1669 cx.needs_unwind_cleanup_cache.borrow_mut().insert(ty, needs_unwind_cleanup);
1670 return needs_unwind_cleanup;
1673 fn type_needs_unwind_cleanup_(cx: &ctxt, ty: t,
1674 tycache: &mut HashSet<t>,
1675 encountered_box: bool) -> bool {
1677 // Prevent infinite recursion
1678 if !tycache.insert(ty) {
1682 let mut encountered_box = encountered_box;
1683 let mut needs_unwind_cleanup = false;
1684 maybe_walk_ty(ty, |ty| {
1685 let old_encountered_box = encountered_box;
1686 let result = match get(ty).sty {
1688 encountered_box = true;
1691 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
1692 ty_tup(_) | ty_ptr(_) => {
1695 ty_enum(did, ref substs) => {
1696 for v in (*enum_variants(cx, did)).iter() {
1697 for aty in v.args.iter() {
1698 let t = aty.subst(cx, substs);
1699 needs_unwind_cleanup |=
1700 type_needs_unwind_cleanup_(cx, t, tycache,
1704 !needs_unwind_cleanup
1707 // Once we're inside a box, the annihilator will find
1708 // it and destroy it.
1709 if !encountered_box {
1710 needs_unwind_cleanup = true;
1717 needs_unwind_cleanup = true;
1722 encountered_box = old_encountered_box;
1726 return needs_unwind_cleanup;
1730 * Type contents is how the type checker reasons about kinds.
1731 * They track what kinds of things are found within a type. You can
1732 * think of them as kind of an "anti-kind". They track the kinds of values
1733 * and thinks that are contained in types. Having a larger contents for
1734 * a type tends to rule that type *out* from various kinds. For example,
1735 * a type that contains a reference is not sendable.
1737 * The reason we compute type contents and not kinds is that it is
1738 * easier for me (nmatsakis) to think about what is contained within
1739 * a type than to think about what is *not* contained within a type.
1741 pub struct TypeContents {
1745 macro_rules! def_type_content_sets(
1746 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
1748 use middle::ty::TypeContents;
1749 $(pub static $name: TypeContents = TypeContents { bits: $bits };)+
1754 def_type_content_sets!(
1756 None = 0b0000_0000__0000_0000__0000,
1758 // Things that are interior to the value (first nibble):
1759 InteriorUnsized = 0b0000_0000__0000_0000__0001,
1760 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
1761 // InteriorAll = 0b00000000__00000000__1111,
1763 // Things that are owned by the value (second and third nibbles):
1764 OwnsOwned = 0b0000_0000__0000_0001__0000,
1765 OwnsDtor = 0b0000_0000__0000_0010__0000,
1766 OwnsManaged /* see [1] below */ = 0b0000_0000__0000_0100__0000,
1767 OwnsAffine = 0b0000_0000__0000_1000__0000,
1768 OwnsAll = 0b0000_0000__1111_1111__0000,
1770 // Things that are reachable by the value in any way (fourth nibble):
1771 ReachesNonsendAnnot = 0b0000_0001__0000_0000__0000,
1772 ReachesBorrowed = 0b0000_0010__0000_0000__0000,
1773 // ReachesManaged /* see [1] below */ = 0b0000_0100__0000_0000__0000,
1774 ReachesMutable = 0b0000_1000__0000_0000__0000,
1775 ReachesNoShare = 0b0001_0000__0000_0000__0000,
1776 ReachesAll = 0b0001_1111__0000_0000__0000,
1778 // Things that cause values to *move* rather than *copy*
1779 Moves = 0b0000_0000__0000_1011__0000,
1781 // Things that mean drop glue is necessary
1782 NeedsDrop = 0b0000_0000__0000_0111__0000,
1784 // Things that prevent values from being sent
1786 // Note: For checking whether something is sendable, it'd
1787 // be sufficient to have ReachesManaged. However, we include
1788 // both ReachesManaged and OwnsManaged so that when
1789 // a parameter has a bound T:Send, we are able to deduce
1790 // that it neither reaches nor owns a managed pointer.
1791 Nonsendable = 0b0000_0111__0000_0100__0000,
1793 // Things that prevent values from being considered 'static
1794 Nonstatic = 0b0000_0010__0000_0000__0000,
1796 // Things that prevent values from being considered sized
1797 Nonsized = 0b0000_0000__0000_0000__0001,
1799 // Things that prevent values from being shared
1800 Nonsharable = 0b0001_0000__0000_0000__0000,
1802 // Things that make values considered not POD (would be same
1803 // as `Moves`, but for the fact that managed data `@` is
1804 // not considered POD)
1805 Noncopy = 0b0000_0000__0000_1111__0000,
1807 // Bits to set when a managed value is encountered
1809 // [1] Do not set the bits TC::OwnsManaged or
1810 // TC::ReachesManaged directly, instead reference
1811 // TC::Managed to set them both at once.
1812 Managed = 0b0000_0100__0000_0100__0000,
1815 All = 0b1111_1111__1111_1111__1111
1820 pub fn meets_bound(&self, cx: &ctxt, bb: BuiltinBound) -> bool {
1822 BoundStatic => self.is_static(cx),
1823 BoundSend => self.is_sendable(cx),
1824 BoundSized => self.is_sized(cx),
1825 BoundCopy => self.is_copy(cx),
1826 BoundShare => self.is_sharable(cx),
1830 pub fn when(&self, cond: bool) -> TypeContents {
1831 if cond {*self} else {TC::None}
1834 pub fn intersects(&self, tc: TypeContents) -> bool {
1835 (self.bits & tc.bits) != 0
1838 pub fn is_static(&self, _: &ctxt) -> bool {
1839 !self.intersects(TC::Nonstatic)
1842 pub fn is_sendable(&self, _: &ctxt) -> bool {
1843 !self.intersects(TC::Nonsendable)
1846 pub fn is_sharable(&self, _: &ctxt) -> bool {
1847 !self.intersects(TC::Nonsharable)
1850 pub fn owns_managed(&self) -> bool {
1851 self.intersects(TC::OwnsManaged)
1854 pub fn owns_owned(&self) -> bool {
1855 self.intersects(TC::OwnsOwned)
1858 pub fn is_sized(&self, _: &ctxt) -> bool {
1859 !self.intersects(TC::Nonsized)
1862 pub fn is_copy(&self, _: &ctxt) -> bool {
1863 !self.intersects(TC::Noncopy)
1866 pub fn interior_unsafe(&self) -> bool {
1867 self.intersects(TC::InteriorUnsafe)
1870 pub fn interior_unsized(&self) -> bool {
1871 self.intersects(TC::InteriorUnsized)
1874 pub fn moves_by_default(&self, _: &ctxt) -> bool {
1875 self.intersects(TC::Moves)
1878 pub fn needs_drop(&self, _: &ctxt) -> bool {
1879 self.intersects(TC::NeedsDrop)
1882 pub fn owned_pointer(&self) -> TypeContents {
1884 * Includes only those bits that still apply
1885 * when indirected through a `Box` pointer
1888 *self & (TC::OwnsAll | TC::ReachesAll))
1891 pub fn reference(&self, bits: TypeContents) -> TypeContents {
1893 * Includes only those bits that still apply
1894 * when indirected through a reference (`&`)
1897 *self & TC::ReachesAll)
1900 pub fn managed_pointer(&self) -> TypeContents {
1902 * Includes only those bits that still apply
1903 * when indirected through a managed pointer (`@`)
1906 *self & TC::ReachesAll)
1909 pub fn unsafe_pointer(&self) -> TypeContents {
1911 * Includes only those bits that still apply
1912 * when indirected through an unsafe pointer (`*`)
1914 *self & TC::ReachesAll
1917 pub fn union<T>(v: &[T], f: |&T| -> TypeContents) -> TypeContents {
1918 v.iter().fold(TC::None, |tc, t| tc | f(t))
1921 pub fn has_dtor(&self) -> bool {
1922 self.intersects(TC::OwnsDtor)
1926 impl ops::BitOr<TypeContents,TypeContents> for TypeContents {
1927 fn bitor(&self, other: &TypeContents) -> TypeContents {
1928 TypeContents {bits: self.bits | other.bits}
1932 impl ops::BitAnd<TypeContents,TypeContents> for TypeContents {
1933 fn bitand(&self, other: &TypeContents) -> TypeContents {
1934 TypeContents {bits: self.bits & other.bits}
1938 impl ops::Sub<TypeContents,TypeContents> for TypeContents {
1939 fn sub(&self, other: &TypeContents) -> TypeContents {
1940 TypeContents {bits: self.bits & !other.bits}
1944 impl fmt::Show for TypeContents {
1945 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1946 write!(f, "TypeContents({:t})", self.bits)
1950 pub fn type_is_static(cx: &ctxt, t: ty::t) -> bool {
1951 type_contents(cx, t).is_static(cx)
1954 pub fn type_is_sendable(cx: &ctxt, t: ty::t) -> bool {
1955 type_contents(cx, t).is_sendable(cx)
1958 pub fn type_interior_is_unsafe(cx: &ctxt, t: ty::t) -> bool {
1959 type_contents(cx, t).interior_unsafe()
1962 pub fn type_contents(cx: &ctxt, ty: t) -> TypeContents {
1963 let ty_id = type_id(ty);
1965 match cx.tc_cache.borrow().find(&ty_id) {
1966 Some(tc) => { return *tc; }
1970 let mut cache = HashMap::new();
1971 let result = tc_ty(cx, ty, &mut cache);
1973 cx.tc_cache.borrow_mut().insert(ty_id, result);
1978 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
1980 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
1981 // private cache for this walk. This is needed in the case of cyclic
1984 // struct List { next: Box<Option<List>>, ... }
1986 // When computing the type contents of such a type, we wind up deeply
1987 // recursing as we go. So when we encounter the recursive reference
1988 // to List, we temporarily use TC::None as its contents. Later we'll
1989 // patch up the cache with the correct value, once we've computed it
1990 // (this is basically a co-inductive process, if that helps). So in
1991 // the end we'll compute TC::OwnsOwned, in this case.
1993 // The problem is, as we are doing the computation, we will also
1994 // compute an *intermediate* contents for, e.g., Option<List> of
1995 // TC::None. This is ok during the computation of List itself, but if
1996 // we stored this intermediate value into cx.tc_cache, then later
1997 // requests for the contents of Option<List> would also yield TC::None
1998 // which is incorrect. This value was computed based on the crutch
1999 // value for the type contents of list. The correct value is
2000 // TC::OwnsOwned. This manifested as issue #4821.
2001 let ty_id = type_id(ty);
2002 match cache.find(&ty_id) {
2003 Some(tc) => { return *tc; }
2006 match cx.tc_cache.borrow().find(&ty_id) { // Must check both caches!
2007 Some(tc) => { return *tc; }
2010 cache.insert(ty_id, TC::None);
2012 let result = match get(ty).sty {
2013 // Scalar and unique types are sendable, and durable
2014 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2015 ty_bare_fn(_) | ty::ty_char | ty_str => {
2019 ty_closure(ref c) => {
2020 closure_contents(cx, *c)
2024 tc_ty(cx, typ, cache).managed_pointer()
2028 match get(typ).sty {
2029 ty_str => TC::OwnsOwned,
2030 _ => tc_ty(cx, typ, cache).owned_pointer(),
2034 ty_trait(box ty::TyTrait { bounds, .. }) => {
2035 object_contents(cx, bounds)
2039 tc_ty(cx, mt.ty, cache).unsafe_pointer()
2042 ty_rptr(r, ref mt) => {
2043 match get(mt.ty).sty {
2044 ty_str => borrowed_contents(r, ast::MutImmutable),
2045 _ => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(r, mt.mutbl)),
2050 tc_mt(cx, mt, cache)
2053 ty_struct(did, ref substs) => {
2054 let flds = struct_fields(cx, did, substs);
2056 TypeContents::union(flds.as_slice(),
2057 |f| tc_mt(cx, f.mt, cache));
2058 if ty::has_dtor(cx, did) {
2059 res = res | TC::OwnsDtor;
2061 apply_lang_items(cx, did, res)
2064 ty_tup(ref tys) => {
2065 TypeContents::union(tys.as_slice(),
2066 |ty| tc_ty(cx, *ty, cache))
2069 ty_enum(did, ref substs) => {
2070 let variants = substd_enum_variants(cx, did, substs);
2072 TypeContents::union(variants.as_slice(), |variant| {
2073 TypeContents::union(variant.args.as_slice(),
2075 tc_ty(cx, *arg_ty, cache)
2078 apply_lang_items(cx, did, res)
2082 // We only ever ask for the kind of types that are defined in
2083 // the current crate; therefore, the only type parameters that
2084 // could be in scope are those defined in the current crate.
2085 // If this assertion failures, it is likely because of a
2086 // failure in the cross-crate inlining code to translate a
2088 assert_eq!(p.def_id.krate, ast::LOCAL_CRATE);
2090 let ty_param_defs = cx.ty_param_defs.borrow();
2091 let tp_def = ty_param_defs.get(&p.def_id.node);
2092 kind_bounds_to_contents(cx,
2093 tp_def.bounds.builtin_bounds,
2094 tp_def.bounds.trait_bounds.as_slice())
2098 // This occurs during coherence, but shouldn't occur at other
2104 cx.sess.bug("asked to compute contents of error type");
2108 cache.insert(ty_id, result);
2114 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2116 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
2117 mc | tc_ty(cx, mt.ty, cache)
2120 fn apply_lang_items(cx: &ctxt,
2124 if Some(did) == cx.lang_items.no_send_bound() {
2125 tc | TC::ReachesNonsendAnnot
2126 } else if Some(did) == cx.lang_items.managed_bound() {
2128 } else if Some(did) == cx.lang_items.no_copy_bound() {
2130 } else if Some(did) == cx.lang_items.no_share_bound() {
2131 tc | TC::ReachesNoShare
2132 } else if Some(did) == cx.lang_items.unsafe_type() {
2133 // FIXME(#13231): This shouldn't be needed after
2134 // opt-in built-in bounds are implemented.
2135 (tc | TC::InteriorUnsafe) - TC::Nonsharable
2141 fn borrowed_contents(region: ty::Region,
2142 mutbl: ast::Mutability)
2145 * Type contents due to containing a reference
2146 * with the region `region` and borrow kind `bk`
2149 let b = match mutbl {
2150 ast::MutMutable => TC::ReachesMutable | TC::OwnsAffine,
2151 ast::MutImmutable => TC::None,
2153 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
2156 fn closure_contents(cx: &ctxt, cty: &ClosureTy) -> TypeContents {
2157 // Closure contents are just like trait contents, but with potentially
2159 let st = object_contents(cx, cty.bounds);
2161 let st = match cty.store {
2165 RegionTraitStore(r, mutbl) => {
2166 st.reference(borrowed_contents(r, mutbl))
2170 // This also prohibits "@once fn" from being copied, which allows it to
2171 // be called. Neither way really makes much sense.
2172 let ot = match cty.onceness {
2173 ast::Once => TC::OwnsAffine,
2174 ast::Many => TC::None,
2180 fn object_contents(cx: &ctxt,
2181 bounds: BuiltinBounds)
2183 // These are the type contents of the (opaque) interior
2184 kind_bounds_to_contents(cx, bounds, [])
2187 fn kind_bounds_to_contents(cx: &ctxt,
2188 bounds: BuiltinBounds,
2189 traits: &[Rc<TraitRef>])
2191 let _i = indenter();
2192 let mut tc = TC::All;
2193 each_inherited_builtin_bound(cx, bounds, traits, |bound| {
2194 tc = tc - match bound {
2195 BoundStatic => TC::Nonstatic,
2196 BoundSend => TC::Nonsendable,
2197 BoundSized => TC::Nonsized,
2198 BoundCopy => TC::Noncopy,
2199 BoundShare => TC::Nonsharable,
2204 // Iterates over all builtin bounds on the type parameter def, including
2205 // those inherited from traits with builtin-kind-supertraits.
2206 fn each_inherited_builtin_bound(cx: &ctxt,
2207 bounds: BuiltinBounds,
2208 traits: &[Rc<TraitRef>],
2209 f: |BuiltinBound|) {
2210 for bound in bounds.iter() {
2214 each_bound_trait_and_supertraits(cx, traits, |trait_ref| {
2215 let trait_def = lookup_trait_def(cx, trait_ref.def_id);
2216 for bound in trait_def.bounds.iter() {
2225 pub fn type_moves_by_default(cx: &ctxt, ty: t) -> bool {
2226 type_contents(cx, ty).moves_by_default(cx)
2229 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
2230 pub fn is_instantiable(cx: &ctxt, r_ty: t) -> bool {
2231 fn type_requires(cx: &ctxt, seen: &mut Vec<DefId>,
2232 r_ty: t, ty: t) -> bool {
2233 debug!("type_requires({}, {})?",
2234 ::util::ppaux::ty_to_str(cx, r_ty),
2235 ::util::ppaux::ty_to_str(cx, ty));
2238 get(r_ty).sty == get(ty).sty ||
2239 subtypes_require(cx, seen, r_ty, ty)
2242 debug!("type_requires({}, {})? {}",
2243 ::util::ppaux::ty_to_str(cx, r_ty),
2244 ::util::ppaux::ty_to_str(cx, ty),
2249 fn subtypes_require(cx: &ctxt, seen: &mut Vec<DefId>,
2250 r_ty: t, ty: t) -> bool {
2251 debug!("subtypes_require({}, {})?",
2252 ::util::ppaux::ty_to_str(cx, r_ty),
2253 ::util::ppaux::ty_to_str(cx, ty));
2255 let r = match get(ty).sty {
2256 // fixed length vectors need special treatment compared to
2257 // normal vectors, since they don't necessarily have the
2258 // possibility to have length zero.
2259 ty_vec(_, Some(0)) => false, // don't need no contents
2260 ty_vec(mt, Some(_)) => type_requires(cx, seen, r_ty, mt.ty),
2275 ty_vec(_, None) => {
2278 ty_box(typ) | ty_uniq(typ) => {
2279 type_requires(cx, seen, r_ty, typ)
2281 ty_rptr(_, ref mt) => {
2282 type_requires(cx, seen, r_ty, mt.ty)
2286 false // unsafe ptrs can always be NULL
2293 ty_struct(ref did, _) if seen.contains(did) => {
2297 ty_struct(did, ref substs) => {
2299 let fields = struct_fields(cx, did, substs);
2300 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
2301 seen.pop().unwrap();
2306 ts.iter().any(|t| type_requires(cx, seen, r_ty, *t))
2309 ty_enum(ref did, _) if seen.contains(did) => {
2313 ty_enum(did, ref substs) => {
2315 let vs = enum_variants(cx, did);
2316 let r = !vs.is_empty() && vs.iter().all(|variant| {
2317 variant.args.iter().any(|aty| {
2318 let sty = aty.subst(cx, substs);
2319 type_requires(cx, seen, r_ty, sty)
2322 seen.pop().unwrap();
2327 debug!("subtypes_require({}, {})? {}",
2328 ::util::ppaux::ty_to_str(cx, r_ty),
2329 ::util::ppaux::ty_to_str(cx, ty),
2335 let mut seen = Vec::new();
2336 !subtypes_require(cx, &mut seen, r_ty, r_ty)
2339 /// Describes whether a type is representable. For types that are not
2340 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
2341 /// distinguish between types that are recursive with themselves and types that
2342 /// contain a different recursive type. These cases can therefore be treated
2343 /// differently when reporting errors.
2344 #[deriving(PartialEq)]
2345 pub enum Representability {
2351 /// Check whether a type is representable. This means it cannot contain unboxed
2352 /// structural recursion. This check is needed for structs and enums.
2353 pub fn is_type_representable(cx: &ctxt, sp: Span, ty: t) -> Representability {
2355 // Iterate until something non-representable is found
2356 fn find_nonrepresentable<It: Iterator<t>>(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2357 mut iter: It) -> Representability {
2359 let r = type_structurally_recursive(cx, sp, seen, ty);
2360 if r != Representable {
2367 // Does the type `ty` directly (without indirection through a pointer)
2368 // contain any types on stack `seen`?
2369 fn type_structurally_recursive(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2370 ty: t) -> Representability {
2371 debug!("type_structurally_recursive: {}",
2372 ::util::ppaux::ty_to_str(cx, ty));
2374 // Compare current type to previously seen types
2377 ty_enum(did, _) => {
2378 for (i, &seen_did) in seen.iter().enumerate() {
2379 if did == seen_did {
2380 return if i == 0 { SelfRecursive }
2381 else { ContainsRecursive }
2388 // Check inner types
2392 find_nonrepresentable(cx, sp, seen, ts.iter().map(|t| *t))
2394 // Fixed-length vectors.
2395 // FIXME(#11924) Behavior undecided for zero-length vectors.
2396 ty_vec(mt, Some(_)) => {
2397 type_structurally_recursive(cx, sp, seen, mt.ty)
2400 // Push struct and enum def-ids onto `seen` before recursing.
2401 ty_struct(did, ref substs) => {
2403 let fields = struct_fields(cx, did, substs);
2404 let r = find_nonrepresentable(cx, sp, seen,
2405 fields.iter().map(|f| f.mt.ty));
2409 ty_enum(did, ref substs) => {
2411 let vs = enum_variants(cx, did);
2413 let mut r = Representable;
2414 for variant in vs.iter() {
2415 let iter = variant.args.iter().map(|aty| {
2416 aty.subst_spanned(cx, substs, Some(sp))
2418 r = find_nonrepresentable(cx, sp, seen, iter);
2420 if r != Representable { break }
2431 debug!("is_type_representable: {}",
2432 ::util::ppaux::ty_to_str(cx, ty));
2434 // To avoid a stack overflow when checking an enum variant or struct that
2435 // contains a different, structurally recursive type, maintain a stack
2436 // of seen types and check recursion for each of them (issues #3008, #3779).
2437 let mut seen: Vec<DefId> = Vec::new();
2438 type_structurally_recursive(cx, sp, &mut seen, ty)
2441 pub fn type_is_trait(ty: t) -> bool {
2443 ty_uniq(ty) | ty_rptr(_, mt { ty, ..}) => match get(ty).sty {
2444 ty_trait(..) => true,
2447 ty_trait(..) => true,
2452 pub fn type_is_integral(ty: t) -> bool {
2454 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
2459 pub fn type_is_uint(ty: t) -> bool {
2461 ty_infer(IntVar(_)) | ty_uint(ast::TyU) => true,
2466 pub fn type_is_char(ty: t) -> bool {
2473 pub fn type_is_bare_fn(ty: t) -> bool {
2475 ty_bare_fn(..) => true,
2480 pub fn type_is_fp(ty: t) -> bool {
2482 ty_infer(FloatVar(_)) | ty_float(_) => true,
2487 pub fn type_is_numeric(ty: t) -> bool {
2488 return type_is_integral(ty) || type_is_fp(ty);
2491 pub fn type_is_signed(ty: t) -> bool {
2498 pub fn type_is_machine(ty: t) -> bool {
2500 ty_int(ast::TyI) | ty_uint(ast::TyU) => false,
2501 ty_int(..) | ty_uint(..) | ty_float(..) => true,
2506 // Is the type's representation size known at compile time?
2507 #[allow(dead_code)] // leaving in for DST
2508 pub fn type_is_sized(cx: &ctxt, ty: ty::t) -> bool {
2509 type_contents(cx, ty).is_sized(cx)
2512 // Whether a type is enum like, that is an enum type with only nullary
2514 pub fn type_is_c_like_enum(cx: &ctxt, ty: t) -> bool {
2516 ty_enum(did, _) => {
2517 let variants = enum_variants(cx, did);
2518 if variants.len() == 0 {
2521 variants.iter().all(|v| v.args.len() == 0)
2528 // Returns the type and mutability of *t.
2530 // The parameter `explicit` indicates if this is an *explicit* dereference.
2531 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
2532 pub fn deref(t: t, explicit: bool) -> Option<mt> {
2534 ty_box(typ) | ty_uniq(typ) => match get(typ).sty {
2535 // Don't deref ~[] etc., might need to generalise this to all DST.
2536 ty_vec(_, None) | ty_str | ty_trait(..) => None,
2539 mutbl: ast::MutImmutable,
2542 ty_rptr(_, mt) => match get(mt.ty).sty {
2543 // Don't deref &[], might need to generalise this to all DST.
2544 ty_vec(_, None) | ty_str | ty_trait(..) => None,
2547 ty_ptr(mt) if explicit => Some(mt),
2552 // Returns the type of t[i]
2553 pub fn index(t: t) -> Option<mt> {
2555 ty_vec(mt, Some(_)) => Some(mt),
2556 ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) |
2557 ty_box(t) | ty_uniq(t) => match get(t).sty {
2558 ty_vec(mt, None) => Some(mt),
2565 // Returns the type of elements contained within an 'array-like' type.
2566 // This is exactly the same as the above, except it supports strings,
2567 // which can't actually be indexed.
2568 pub fn array_element_ty(t: t) -> Option<mt> {
2570 ty_vec(mt, Some(_)) => Some(mt),
2571 ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) |
2572 ty_box(t) | ty_uniq(t) => match get(t).sty {
2573 ty_vec(mt, None) => Some(mt),
2574 ty_str => Some(mt {ty: mk_u8(), mutbl: ast::MutImmutable}),
2581 pub fn node_id_to_trait_ref(cx: &ctxt, id: ast::NodeId) -> Rc<ty::TraitRef> {
2582 match cx.trait_refs.borrow().find(&id) {
2583 Some(t) => t.clone(),
2584 None => cx.sess.bug(
2585 format!("node_id_to_trait_ref: no trait ref for node `{}`",
2586 cx.map.node_to_str(id)).as_slice())
2590 pub fn try_node_id_to_type(cx: &ctxt, id: ast::NodeId) -> Option<t> {
2591 cx.node_types.borrow().find_copy(&(id as uint))
2594 pub fn node_id_to_type(cx: &ctxt, id: ast::NodeId) -> t {
2595 match try_node_id_to_type(cx, id) {
2597 None => cx.sess.bug(
2598 format!("node_id_to_type: no type for node `{}`",
2599 cx.map.node_to_str(id)).as_slice())
2603 pub fn node_id_to_type_opt(cx: &ctxt, id: ast::NodeId) -> Option<t> {
2604 match cx.node_types.borrow().find(&(id as uint)) {
2605 Some(&t) => Some(t),
2610 pub fn node_id_item_substs(cx: &ctxt, id: ast::NodeId) -> ItemSubsts {
2611 match cx.item_substs.borrow().find(&id) {
2612 None => ItemSubsts::empty(),
2613 Some(ts) => ts.clone(),
2617 pub fn fn_is_variadic(fty: t) -> bool {
2618 match get(fty).sty {
2619 ty_bare_fn(ref f) => f.sig.variadic,
2620 ty_closure(ref f) => f.sig.variadic,
2622 fail!("fn_is_variadic() called on non-fn type: {:?}", s)
2627 pub fn ty_fn_sig(fty: t) -> FnSig {
2628 match get(fty).sty {
2629 ty_bare_fn(ref f) => f.sig.clone(),
2630 ty_closure(ref f) => f.sig.clone(),
2632 fail!("ty_fn_sig() called on non-fn type: {:?}", s)
2637 // Type accessors for substructures of types
2638 pub fn ty_fn_args(fty: t) -> Vec<t> {
2639 match get(fty).sty {
2640 ty_bare_fn(ref f) => f.sig.inputs.clone(),
2641 ty_closure(ref f) => f.sig.inputs.clone(),
2643 fail!("ty_fn_args() called on non-fn type: {:?}", s)
2648 pub fn ty_closure_store(fty: t) -> TraitStore {
2649 match get(fty).sty {
2650 ty_closure(ref f) => f.store,
2652 fail!("ty_closure_store() called on non-closure type: {:?}", s)
2657 pub fn ty_fn_ret(fty: t) -> t {
2658 match get(fty).sty {
2659 ty_bare_fn(ref f) => f.sig.output,
2660 ty_closure(ref f) => f.sig.output,
2662 fail!("ty_fn_ret() called on non-fn type: {:?}", s)
2667 pub fn is_fn_ty(fty: t) -> bool {
2668 match get(fty).sty {
2669 ty_bare_fn(_) => true,
2670 ty_closure(_) => true,
2675 pub fn ty_region(tcx: &ctxt,
2683 format!("ty_region() invoked on in appropriate ty: {:?}",
2689 pub fn free_region_from_def(free_id: ast::NodeId, def: &RegionParameterDef)
2692 ty::ReFree(ty::FreeRegion { scope_id: free_id,
2693 bound_region: ty::BrNamed(def.def_id,
2697 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
2698 // doesn't provide type parameter substitutions.
2699 pub fn pat_ty(cx: &ctxt, pat: &ast::Pat) -> t {
2700 return node_id_to_type(cx, pat.id);
2704 // Returns the type of an expression as a monotype.
2706 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
2707 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
2708 // auto-ref. The type returned by this function does not consider such
2709 // adjustments. See `expr_ty_adjusted()` instead.
2711 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
2712 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
2713 // instead of "fn(t) -> T with T = int".
2714 pub fn expr_ty(cx: &ctxt, expr: &ast::Expr) -> t {
2715 return node_id_to_type(cx, expr.id);
2718 pub fn expr_ty_opt(cx: &ctxt, expr: &ast::Expr) -> Option<t> {
2719 return node_id_to_type_opt(cx, expr.id);
2722 pub fn expr_ty_adjusted(cx: &ctxt, expr: &ast::Expr) -> t {
2725 * Returns the type of `expr`, considering any `AutoAdjustment`
2726 * entry recorded for that expression.
2728 * It would almost certainly be better to store the adjusted ty in with
2729 * the `AutoAdjustment`, but I opted not to do this because it would
2730 * require serializing and deserializing the type and, although that's not
2731 * hard to do, I just hate that code so much I didn't want to touch it
2732 * unless it was to fix it properly, which seemed a distraction from the
2733 * task at hand! -nmatsakis
2736 adjust_ty(cx, expr.span, expr.id, expr_ty(cx, expr),
2737 cx.adjustments.borrow().find(&expr.id),
2738 |method_call| cx.method_map.borrow().find(&method_call).map(|method| method.ty))
2741 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
2742 match cx.map.find(id) {
2743 Some(ast_map::NodeExpr(e)) => {
2747 cx.sess.bug(format!("Node id {} is not an expr: {:?}",
2752 cx.sess.bug(format!("Node id {} is not present \
2753 in the node map", id).as_slice());
2758 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
2759 match cx.map.find(id) {
2760 Some(ast_map::NodeLocal(pat)) => {
2762 ast::PatIdent(_, ref path, _) => {
2763 token::get_ident(ast_util::path_to_ident(path))
2767 format!("Variable id {} maps to {:?}, not local",
2774 cx.sess.bug(format!("Variable id {} maps to {:?}, not local",
2781 pub fn adjust_ty(cx: &ctxt,
2783 expr_id: ast::NodeId,
2784 unadjusted_ty: ty::t,
2785 adjustment: Option<&AutoAdjustment>,
2786 method_type: |typeck::MethodCall| -> Option<ty::t>)
2788 /*! See `expr_ty_adjusted` */
2790 return match adjustment {
2791 Some(adjustment) => {
2793 AutoAddEnv(store) => {
2794 match ty::get(unadjusted_ty).sty {
2795 ty::ty_bare_fn(ref b) => {
2798 ty::ClosureTy {fn_style: b.fn_style,
2799 onceness: ast::Many,
2801 bounds: ty::all_builtin_bounds(),
2802 sig: b.sig.clone()})
2806 format!("add_env adjustment on non-bare-fn: \
2813 AutoDerefRef(ref adj) => {
2814 let mut adjusted_ty = unadjusted_ty;
2816 if !ty::type_is_error(adjusted_ty) {
2817 for i in range(0, adj.autoderefs) {
2818 let method_call = typeck::MethodCall::autoderef(expr_id, i);
2819 match method_type(method_call) {
2820 Some(method_ty) => {
2821 adjusted_ty = ty_fn_ret(method_ty);
2825 match deref(adjusted_ty, true) {
2826 Some(mt) => { adjusted_ty = mt.ty; }
2830 format!("the {}th autoderef failed: \
2833 ty_to_str(cx, adjusted_ty))
2841 None => adjusted_ty,
2842 Some(ref autoref) => {
2851 AutoBorrowVec(r, m) => {
2852 borrow_vec(cx, span, r, m, adjusted_ty)
2855 AutoBorrowVecRef(r, m) => {
2856 adjusted_ty = borrow_vec(cx,
2863 mutbl: ast::MutImmutable
2868 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
2871 AutoBorrowObj(r, m) => {
2872 borrow_obj(cx, span, r, m, adjusted_ty)
2879 AutoObject(store, bounds, def_id, ref substs) => {
2881 let tr = mk_trait(cx, def_id, substs.clone(), bounds);
2886 RegionTraitStore(r, m) => {
2896 None => unadjusted_ty
2899 fn borrow_vec(cx: &ctxt,
2903 ty: ty::t) -> ty::t {
2905 ty_uniq(t) | ty_ptr(mt{ty: t, ..}) |
2906 ty_rptr(_, mt{ty: t, ..}) => match get(t).sty {
2907 ty::ty_vec(mt, None) => ty::mk_slice(cx, r, ty::mt {ty: mt.ty, mutbl: m}),
2908 ty::ty_str => ty::mk_str_slice(cx, r, m),
2912 format!("borrow-vec associated with bad sty: {:?}",
2913 get(ty).sty).as_slice());
2916 ty_vec(mt, Some(_)) => ty::mk_slice(cx, r, ty::mt {ty: mt.ty, mutbl: m}),
2921 format!("borrow-vec associated with bad sty: {:?}",
2927 fn borrow_obj(cx: &ctxt, span: Span, r: Region,
2928 m: ast::Mutability, ty: ty::t) -> ty::t {
2930 ty_uniq(t) | ty_rptr(_, mt{ty: t, ..}) => match get(t).sty {
2931 ty_trait(box ty::TyTrait {def_id, ref substs, bounds, .. }) => {
2933 ty: ty::mk_trait(cx, def_id, substs.clone(), bounds),
2940 format!("borrow-trait-obj associated with bad sty: {:?}",
2941 get(ty).sty).as_slice());
2947 format!("borrow-trait-obj associated with bad sty: {:?}",
2955 pub fn map_region(&self, f: |Region| -> Region) -> AutoRef {
2957 ty::AutoPtr(r, m) => ty::AutoPtr(f(r), m),
2958 ty::AutoBorrowVec(r, m) => ty::AutoBorrowVec(f(r), m),
2959 ty::AutoBorrowVecRef(r, m) => ty::AutoBorrowVecRef(f(r), m),
2960 ty::AutoUnsafe(m) => ty::AutoUnsafe(m),
2961 ty::AutoBorrowObj(r, m) => ty::AutoBorrowObj(f(r), m),
2966 pub fn method_call_type_param_defs(tcx: &ctxt, origin: typeck::MethodOrigin)
2967 -> VecPerParamSpace<TypeParameterDef> {
2969 typeck::MethodStatic(did) => {
2970 ty::lookup_item_type(tcx, did).generics.types.clone()
2972 typeck::MethodParam(typeck::MethodParam{trait_id: trt_id,
2973 method_num: n_mth, ..}) |
2974 typeck::MethodObject(typeck::MethodObject{trait_id: trt_id,
2975 method_num: n_mth, ..}) => {
2976 ty::trait_method(tcx, trt_id, n_mth).generics.types.clone()
2981 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> def::Def {
2982 match tcx.def_map.borrow().find(&expr.id) {
2985 tcx.sess.span_bug(expr.span, format!(
2986 "no def-map entry for expr {:?}", expr.id).as_slice());
2991 pub fn expr_is_lval(tcx: &ctxt, e: &ast::Expr) -> bool {
2992 match expr_kind(tcx, e) {
2994 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
2998 /// We categorize expressions into three kinds. The distinction between
2999 /// lvalue/rvalue is fundamental to the language. The distinction between the
3000 /// two kinds of rvalues is an artifact of trans which reflects how we will
3001 /// generate code for that kind of expression. See trans/expr.rs for more
3010 pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
3011 if tcx.method_map.borrow().contains_key(&typeck::MethodCall::expr(expr.id)) {
3012 // Overloaded operations are generally calls, and hence they are
3013 // generated via DPS, but there are two exceptions:
3014 return match expr.node {
3015 // `a += b` has a unit result.
3016 ast::ExprAssignOp(..) => RvalueStmtExpr,
3018 // the deref method invoked for `*a` always yields an `&T`
3019 ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
3021 // in the general case, result could be any type, use DPS
3027 ast::ExprPath(..) => {
3028 match resolve_expr(tcx, expr) {
3029 def::DefVariant(tid, vid, _) => {
3030 let variant_info = enum_variant_with_id(tcx, tid, vid);
3031 if variant_info.args.len() > 0u {
3040 def::DefStruct(_) => {
3041 match get(expr_ty(tcx, expr)).sty {
3042 ty_bare_fn(..) => RvalueDatumExpr,
3047 // Fn pointers are just scalar values.
3048 def::DefFn(..) | def::DefStaticMethod(..) => RvalueDatumExpr,
3050 // Note: there is actually a good case to be made that
3051 // DefArg's, particularly those of immediate type, ought to
3052 // considered rvalues.
3053 def::DefStatic(..) |
3054 def::DefBinding(..) |
3057 def::DefLocal(..) => LvalueExpr,
3062 format!("uncategorized def for expr {:?}: {:?}",
3069 ast::ExprUnary(ast::UnDeref, _) |
3070 ast::ExprField(..) |
3071 ast::ExprIndex(..) => {
3076 ast::ExprMethodCall(..) |
3077 ast::ExprStruct(..) |
3080 ast::ExprMatch(..) |
3081 ast::ExprFnBlock(..) |
3083 ast::ExprBlock(..) |
3084 ast::ExprRepeat(..) |
3085 ast::ExprVstore(_, ast::ExprVstoreSlice) |
3086 ast::ExprVstore(_, ast::ExprVstoreMutSlice) |
3087 ast::ExprVec(..) => {
3091 ast::ExprLit(lit) if lit_is_str(lit) => {
3095 ast::ExprCast(..) => {
3096 match tcx.node_types.borrow().find(&(expr.id as uint)) {
3098 if type_is_trait(t) {
3105 // Technically, it should not happen that the expr is not
3106 // present within the table. However, it DOES happen
3107 // during type check, because the final types from the
3108 // expressions are not yet recorded in the tcx. At that
3109 // time, though, we are only interested in knowing lvalue
3110 // vs rvalue. It would be better to base this decision on
3111 // the AST type in cast node---but (at the time of this
3112 // writing) it's not easy to distinguish casts to traits
3113 // from other casts based on the AST. This should be
3114 // easier in the future, when casts to traits
3115 // would like @Foo, Box<Foo>, or &Foo.
3121 ast::ExprBreak(..) |
3122 ast::ExprAgain(..) |
3124 ast::ExprWhile(..) |
3126 ast::ExprAssign(..) |
3127 ast::ExprInlineAsm(..) |
3128 ast::ExprAssignOp(..) => {
3132 ast::ExprForLoop(..) => fail!("non-desugared expr_for_loop"),
3134 ast::ExprLit(_) | // Note: LitStr is carved out above
3135 ast::ExprUnary(..) |
3136 ast::ExprAddrOf(..) |
3137 ast::ExprBinary(..) |
3138 ast::ExprVstore(_, ast::ExprVstoreUniq) => {
3142 ast::ExprBox(place, _) => {
3143 // Special case `Box<T>`/`Gc<T>` for now:
3144 let definition = match tcx.def_map.borrow().find(&place.id) {
3146 None => fail!("no def for place"),
3148 let def_id = definition.def_id();
3149 if tcx.lang_items.exchange_heap() == Some(def_id) ||
3150 tcx.lang_items.managed_heap() == Some(def_id) {
3157 ast::ExprParen(ref e) => expr_kind(tcx, &**e),
3159 ast::ExprMac(..) => {
3162 "macro expression remains after expansion");
3167 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
3169 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
3172 ast::StmtMac(..) => fail!("unexpanded macro in trans")
3176 pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
3179 for f in fields.iter() { if f.ident.name == name { return i; } i += 1u; }
3180 tcx.sess.bug(format!(
3181 "no field named `{}` found in the list of fields `{:?}`",
3182 token::get_name(name),
3184 .map(|f| token::get_ident(f.ident).get().to_string())
3185 .collect::<Vec<String>>()).as_slice());
3188 pub fn method_idx(id: ast::Ident, meths: &[Rc<Method>]) -> Option<uint> {
3189 meths.iter().position(|m| m.ident == id)
3192 /// Returns a vector containing the indices of all type parameters that appear
3193 /// in `ty`. The vector may contain duplicates. Probably should be converted
3194 /// to a bitset or some other representation.
3195 pub fn param_tys_in_type(ty: t) -> Vec<ParamTy> {
3196 let mut rslt = Vec::new();
3208 pub fn ty_sort_str(cx: &ctxt, t: t) -> String {
3210 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) |
3211 ty_uint(_) | ty_float(_) | ty_str => {
3212 ::util::ppaux::ty_to_str(cx, t)
3215 ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
3216 ty_box(_) => "Gc-ptr".to_string(),
3217 ty_uniq(_) => "box".to_string(),
3218 ty_vec(_, _) => "vector".to_string(),
3219 ty_ptr(_) => "*-ptr".to_string(),
3220 ty_rptr(_, _) => "&-ptr".to_string(),
3221 ty_bare_fn(_) => "extern fn".to_string(),
3222 ty_closure(_) => "fn".to_string(),
3223 ty_trait(ref inner) => {
3224 format!("trait {}", item_path_str(cx, inner.def_id))
3226 ty_struct(id, _) => {
3227 format!("struct {}", item_path_str(cx, id))
3229 ty_tup(_) => "tuple".to_string(),
3230 ty_infer(TyVar(_)) => "inferred type".to_string(),
3231 ty_infer(IntVar(_)) => "integral variable".to_string(),
3232 ty_infer(FloatVar(_)) => "floating-point variable".to_string(),
3233 ty_param(ref p) => {
3234 if p.space == subst::SelfSpace {
3237 "type parameter".to_string()
3240 ty_err => "type error".to_string(),
3244 pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> String {
3247 * Explains the source of a type err in a short,
3248 * human readable way. This is meant to be placed in
3249 * parentheses after some larger message. You should
3250 * also invoke `note_and_explain_type_err()` afterwards
3251 * to present additional details, particularly when
3252 * it comes to lifetime-related errors. */
3254 fn tstore_to_closure(s: &TraitStore) -> String {
3256 &UniqTraitStore => "proc".to_string(),
3257 &RegionTraitStore(..) => "closure".to_string()
3262 terr_mismatch => "types differ".to_string(),
3263 terr_fn_style_mismatch(values) => {
3264 format!("expected {} fn but found {} fn",
3265 values.expected.to_str(),
3266 values.found.to_str())
3268 terr_abi_mismatch(values) => {
3269 format!("expected {} fn but found {} fn",
3270 values.expected.to_str(),
3271 values.found.to_str())
3273 terr_onceness_mismatch(values) => {
3274 format!("expected {} fn but found {} fn",
3275 values.expected.to_str(),
3276 values.found.to_str())
3278 terr_sigil_mismatch(values) => {
3279 format!("expected {}, found {}",
3280 tstore_to_closure(&values.expected),
3281 tstore_to_closure(&values.found))
3283 terr_mutability => "values differ in mutability".to_string(),
3284 terr_box_mutability => {
3285 "boxed values differ in mutability".to_string()
3287 terr_vec_mutability => "vectors differ in mutability".to_string(),
3288 terr_ptr_mutability => "pointers differ in mutability".to_string(),
3289 terr_ref_mutability => "references differ in mutability".to_string(),
3290 terr_ty_param_size(values) => {
3291 format!("expected a type with {} type params \
3292 but found one with {} type params",
3296 terr_tuple_size(values) => {
3297 format!("expected a tuple with {} elements \
3298 but found one with {} elements",
3302 terr_record_size(values) => {
3303 format!("expected a record with {} fields \
3304 but found one with {} fields",
3308 terr_record_mutability => {
3309 "record elements differ in mutability".to_string()
3311 terr_record_fields(values) => {
3312 format!("expected a record with field `{}` but found one \
3314 token::get_ident(values.expected),
3315 token::get_ident(values.found))
3318 "incorrect number of function parameters".to_string()
3320 terr_regions_does_not_outlive(..) => {
3321 "lifetime mismatch".to_string()
3323 terr_regions_not_same(..) => {
3324 "lifetimes are not the same".to_string()
3326 terr_regions_no_overlap(..) => {
3327 "lifetimes do not intersect".to_string()
3329 terr_regions_insufficiently_polymorphic(br, _) => {
3330 format!("expected bound lifetime parameter {}, \
3331 but found concrete lifetime",
3332 bound_region_ptr_to_str(cx, br))
3334 terr_regions_overly_polymorphic(br, _) => {
3335 format!("expected concrete lifetime, \
3336 but found bound lifetime parameter {}",
3337 bound_region_ptr_to_str(cx, br))
3339 terr_trait_stores_differ(_, ref values) => {
3340 format!("trait storage differs: expected `{}` but found `{}`",
3341 trait_store_to_str(cx, (*values).expected),
3342 trait_store_to_str(cx, (*values).found))
3344 terr_sorts(values) => {
3345 format!("expected {} but found {}",
3346 ty_sort_str(cx, values.expected),
3347 ty_sort_str(cx, values.found))
3349 terr_traits(values) => {
3350 format!("expected trait `{}` but found trait `{}`",
3351 item_path_str(cx, values.expected),
3352 item_path_str(cx, values.found))
3354 terr_builtin_bounds(values) => {
3355 if values.expected.is_empty() {
3356 format!("expected no bounds but found `{}`",
3357 values.found.user_string(cx))
3358 } else if values.found.is_empty() {
3359 format!("expected bounds `{}` but found no bounds",
3360 values.expected.user_string(cx))
3362 format!("expected bounds `{}` but found bounds `{}`",
3363 values.expected.user_string(cx),
3364 values.found.user_string(cx))
3367 terr_integer_as_char => {
3368 "expected an integral type but found `char`".to_string()
3370 terr_int_mismatch(ref values) => {
3371 format!("expected `{}` but found `{}`",
3372 values.expected.to_str(),
3373 values.found.to_str())
3375 terr_float_mismatch(ref values) => {
3376 format!("expected `{}` but found `{}`",
3377 values.expected.to_str(),
3378 values.found.to_str())
3380 terr_variadic_mismatch(ref values) => {
3381 format!("expected {} fn but found {} function",
3382 if values.expected { "variadic" } else { "non-variadic" },
3383 if values.found { "variadic" } else { "non-variadic" })
3388 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
3390 terr_regions_does_not_outlive(subregion, superregion) => {
3391 note_and_explain_region(cx, "", subregion, "...");
3392 note_and_explain_region(cx, "...does not necessarily outlive ",
3395 terr_regions_not_same(region1, region2) => {
3396 note_and_explain_region(cx, "", region1, "...");
3397 note_and_explain_region(cx, "...is not the same lifetime as ",
3400 terr_regions_no_overlap(region1, region2) => {
3401 note_and_explain_region(cx, "", region1, "...");
3402 note_and_explain_region(cx, "...does not overlap ",
3405 terr_regions_insufficiently_polymorphic(_, conc_region) => {
3406 note_and_explain_region(cx,
3407 "concrete lifetime that was found is ",
3410 terr_regions_overly_polymorphic(_, conc_region) => {
3411 note_and_explain_region(cx,
3412 "expected concrete lifetime is ",
3419 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
3420 cx.provided_method_sources.borrow().find(&id).map(|x| *x)
3423 pub fn provided_trait_methods(cx: &ctxt, id: ast::DefId) -> Vec<Rc<Method>> {
3425 match cx.map.find(id.node) {
3426 Some(ast_map::NodeItem(item)) => {
3428 ItemTrait(_, _, _, ref ms) => {
3429 let (_, p) = ast_util::split_trait_methods(ms.as_slice());
3430 p.iter().map(|m| method(cx, ast_util::local_def(m.id))).collect()
3433 cx.sess.bug(format!("provided_trait_methods: `{}` is \
3440 cx.sess.bug(format!("provided_trait_methods: `{}` is not a \
3446 csearch::get_provided_trait_methods(cx, id)
3450 pub fn trait_supertraits(cx: &ctxt, id: ast::DefId) -> Rc<Vec<Rc<TraitRef>>> {
3452 match cx.supertraits.borrow().find(&id) {
3453 Some(trait_refs) => { return trait_refs.clone(); }
3454 None => {} // Continue.
3457 // Not in the cache. It had better be in the metadata, which means it
3458 // shouldn't be local.
3459 assert!(!is_local(id));
3461 // Get the supertraits out of the metadata and create the
3462 // TraitRef for each.
3463 let result = Rc::new(csearch::get_supertraits(cx, id));
3464 cx.supertraits.borrow_mut().insert(id, result.clone());
3468 pub fn trait_ref_supertraits(cx: &ctxt, trait_ref: &ty::TraitRef) -> Vec<Rc<TraitRef>> {
3469 let supertrait_refs = trait_supertraits(cx, trait_ref.def_id);
3470 supertrait_refs.iter().map(
3471 |supertrait_ref| supertrait_ref.subst(cx, &trait_ref.substs)).collect()
3474 fn lookup_locally_or_in_crate_store<V:Clone>(
3477 map: &mut DefIdMap<V>,
3478 load_external: || -> V) -> V {
3480 * Helper for looking things up in the various maps
3481 * that are populated during typeck::collect (e.g.,
3482 * `cx.methods`, `cx.tcache`, etc). All of these share
3483 * the pattern that if the id is local, it should have
3484 * been loaded into the map by the `typeck::collect` phase.
3485 * If the def-id is external, then we have to go consult
3486 * the crate loading code (and cache the result for the future).
3489 match map.find_copy(&def_id) {
3490 Some(v) => { return v; }
3494 if def_id.krate == ast::LOCAL_CRATE {
3495 fail!("No def'n found for {:?} in tcx.{}", def_id, descr);
3497 let v = load_external();
3498 map.insert(def_id, v.clone());
3502 pub fn trait_method(cx: &ctxt, trait_did: ast::DefId, idx: uint) -> Rc<Method> {
3503 let method_def_id = *ty::trait_method_def_ids(cx, trait_did).get(idx);
3504 ty::method(cx, method_def_id)
3508 pub fn trait_methods(cx: &ctxt, trait_did: ast::DefId) -> Rc<Vec<Rc<Method>>> {
3509 let mut trait_methods = cx.trait_methods_cache.borrow_mut();
3510 match trait_methods.find_copy(&trait_did) {
3511 Some(methods) => methods,
3513 let def_ids = ty::trait_method_def_ids(cx, trait_did);
3514 let methods: Rc<Vec<Rc<Method>>> = Rc::new(def_ids.iter().map(|d| {
3517 trait_methods.insert(trait_did, methods.clone());
3523 pub fn method(cx: &ctxt, id: ast::DefId) -> Rc<Method> {
3524 lookup_locally_or_in_crate_store("methods", id,
3525 &mut *cx.methods.borrow_mut(), || {
3526 Rc::new(csearch::get_method(cx, id))
3530 pub fn trait_method_def_ids(cx: &ctxt, id: ast::DefId) -> Rc<Vec<DefId>> {
3531 lookup_locally_or_in_crate_store("trait_method_def_ids",
3533 &mut *cx.trait_method_def_ids.borrow_mut(),
3535 Rc::new(csearch::get_trait_method_def_ids(&cx.sess.cstore, id))
3539 pub fn impl_trait_ref(cx: &ctxt, id: ast::DefId) -> Option<Rc<TraitRef>> {
3540 match cx.impl_trait_cache.borrow().find(&id) {
3541 Some(ret) => { return ret.clone(); }
3545 let ret = if id.krate == ast::LOCAL_CRATE {
3546 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
3547 match cx.map.find(id.node) {
3548 Some(ast_map::NodeItem(item)) => {
3550 ast::ItemImpl(_, ref opt_trait, _, _) => {
3553 Some(ty::node_id_to_trait_ref(cx, t.ref_id))
3564 csearch::get_impl_trait(cx, id)
3567 cx.impl_trait_cache.borrow_mut().insert(id, ret.clone());
3571 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
3572 let def = *tcx.def_map.borrow()
3574 .expect("no def-map entry for trait");
3578 pub fn try_add_builtin_trait(tcx: &ctxt,
3579 trait_def_id: ast::DefId,
3580 builtin_bounds: &mut BuiltinBounds) -> bool {
3581 //! Checks whether `trait_ref` refers to one of the builtin
3582 //! traits, like `Send`, and adds the corresponding
3583 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
3584 //! is a builtin trait.
3586 match tcx.lang_items.to_builtin_kind(trait_def_id) {
3587 Some(bound) => { builtin_bounds.add(bound); true }
3592 pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> {
3594 ty_trait(box TyTrait { def_id: id, .. }) |
3596 ty_enum(id, _) => Some(id),
3603 pub struct VariantInfo {
3605 pub arg_names: Option<Vec<ast::Ident> >,
3607 pub name: ast::Ident,
3615 /// Creates a new VariantInfo from the corresponding ast representation.
3617 /// Does not do any caching of the value in the type context.
3618 pub fn from_ast_variant(cx: &ctxt,
3619 ast_variant: &ast::Variant,
3620 discriminant: Disr) -> VariantInfo {
3621 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
3623 match ast_variant.node.kind {
3624 ast::TupleVariantKind(ref args) => {
3625 let arg_tys = if args.len() > 0 {
3626 ty_fn_args(ctor_ty).iter().map(|a| *a).collect()
3631 return VariantInfo {
3635 name: ast_variant.node.name,
3636 id: ast_util::local_def(ast_variant.node.id),
3637 disr_val: discriminant,
3638 vis: ast_variant.node.vis
3641 ast::StructVariantKind(ref struct_def) => {
3643 let fields: &[StructField] = struct_def.fields.as_slice();
3645 assert!(fields.len() > 0);
3647 let arg_tys = ty_fn_args(ctor_ty).iter().map(|a| *a).collect();
3648 let arg_names = fields.iter().map(|field| {
3649 match field.node.kind {
3650 NamedField(ident, _) => ident,
3651 UnnamedField(..) => cx.sess.bug(
3652 "enum_variants: all fields in struct must have a name")
3656 return VariantInfo {
3658 arg_names: Some(arg_names),
3660 name: ast_variant.node.name,
3661 id: ast_util::local_def(ast_variant.node.id),
3662 disr_val: discriminant,
3663 vis: ast_variant.node.vis
3670 pub fn substd_enum_variants(cx: &ctxt,
3673 -> Vec<Rc<VariantInfo>> {
3674 enum_variants(cx, id).iter().map(|variant_info| {
3675 let substd_args = variant_info.args.iter()
3676 .map(|aty| aty.subst(cx, substs)).collect();
3678 let substd_ctor_ty = variant_info.ctor_ty.subst(cx, substs);
3680 Rc::new(VariantInfo {
3682 ctor_ty: substd_ctor_ty,
3683 ..(**variant_info).clone()
3688 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
3689 with_path(cx, id, |path| ast_map::path_to_str(path)).to_string()
3694 TraitDtor(DefId, bool)
3698 pub fn is_not_present(&self) -> bool {
3705 pub fn is_present(&self) -> bool {
3706 !self.is_not_present()
3709 pub fn has_drop_flag(&self) -> bool {
3712 &TraitDtor(_, flag) => flag
3717 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
3718 Otherwise return none. */
3719 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
3720 match cx.destructor_for_type.borrow().find(&struct_id) {
3721 Some(&method_def_id) => {
3722 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
3724 TraitDtor(method_def_id, flag)
3730 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
3731 ty_dtor(cx, struct_id).is_present()
3734 pub fn with_path<T>(cx: &ctxt, id: ast::DefId, f: |ast_map::PathElems| -> T) -> T {
3735 if id.krate == ast::LOCAL_CRATE {
3736 cx.map.with_path(id.node, f)
3738 f(ast_map::Values(csearch::get_item_path(cx, id).iter()).chain(None))
3742 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
3743 enum_variants(cx, id).len() == 1
3746 pub fn type_is_empty(cx: &ctxt, t: t) -> bool {
3747 match ty::get(t).sty {
3748 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
3753 pub fn enum_variants(cx: &ctxt, id: ast::DefId) -> Rc<Vec<Rc<VariantInfo>>> {
3754 match cx.enum_var_cache.borrow().find(&id) {
3755 Some(variants) => return variants.clone(),
3756 _ => { /* fallthrough */ }
3759 let result = if ast::LOCAL_CRATE != id.krate {
3760 Rc::new(csearch::get_enum_variants(cx, id))
3763 Although both this code and check_enum_variants in typeck/check
3764 call eval_const_expr, it should never get called twice for the same
3765 expr, since check_enum_variants also updates the enum_var_cache
3767 match cx.map.get(id.node) {
3768 ast_map::NodeItem(item) => {
3770 ast::ItemEnum(ref enum_definition, _) => {
3771 let mut last_discriminant: Option<Disr> = None;
3772 Rc::new(enum_definition.variants.iter().map(|&variant| {
3774 let mut discriminant = match last_discriminant {
3775 Some(val) => val + 1,
3776 None => INITIAL_DISCRIMINANT_VALUE
3779 match variant.node.disr_expr {
3780 Some(ref e) => match const_eval::eval_const_expr_partial(cx, &**e) {
3781 Ok(const_eval::const_int(val)) => {
3782 discriminant = val as Disr
3784 Ok(const_eval::const_uint(val)) => {
3785 discriminant = val as Disr
3790 "expected signed integer constant");
3795 format!("expected constant: {}",
3802 last_discriminant = Some(discriminant);
3803 Rc::new(VariantInfo::from_ast_variant(cx, &*variant,
3808 cx.sess.bug("enum_variants: id not bound to an enum")
3812 _ => cx.sess.bug("enum_variants: id not bound to an enum")
3816 cx.enum_var_cache.borrow_mut().insert(id, result.clone());
3821 // Returns information about the enum variant with the given ID:
3822 pub fn enum_variant_with_id(cx: &ctxt,
3823 enum_id: ast::DefId,
3824 variant_id: ast::DefId)
3825 -> Rc<VariantInfo> {
3826 enum_variants(cx, enum_id).iter()
3827 .find(|variant| variant.id == variant_id)
3828 .expect("enum_variant_with_id(): no variant exists with that ID")
3833 // If the given item is in an external crate, looks up its type and adds it to
3834 // the type cache. Returns the type parameters and type.
3835 pub fn lookup_item_type(cx: &ctxt,
3838 lookup_locally_or_in_crate_store(
3839 "tcache", did, &mut *cx.tcache.borrow_mut(),
3840 || csearch::get_type(cx, did))
3843 pub fn lookup_impl_vtables(cx: &ctxt,
3845 -> typeck::vtable_res {
3846 lookup_locally_or_in_crate_store(
3847 "impl_vtables", did, &mut *cx.impl_vtables.borrow_mut(),
3848 || csearch::get_impl_vtables(cx, did) )
3851 /// Given the did of a trait, returns its canonical trait ref.
3852 pub fn lookup_trait_def(cx: &ctxt, did: ast::DefId) -> Rc<ty::TraitDef> {
3853 let mut trait_defs = cx.trait_defs.borrow_mut();
3854 match trait_defs.find_copy(&did) {
3855 Some(trait_def) => {
3856 // The item is in this crate. The caller should have added it to the
3857 // type cache already
3861 assert!(did.krate != ast::LOCAL_CRATE);
3862 let trait_def = Rc::new(csearch::get_trait_def(cx, did));
3863 trait_defs.insert(did, trait_def.clone());
3869 /// Iterate over attributes of a definition.
3870 // (This should really be an iterator, but that would require csearch and
3871 // decoder to use iterators instead of higher-order functions.)
3872 pub fn each_attr(tcx: &ctxt, did: DefId, f: |&ast::Attribute| -> bool) -> bool {
3874 let item = tcx.map.expect_item(did.node);
3875 item.attrs.iter().advance(|attr| f(attr))
3877 info!("getting foreign attrs");
3878 let mut cont = true;
3879 csearch::get_item_attrs(&tcx.sess.cstore, did, |attrs| {
3881 cont = attrs.iter().advance(|attr| f(attr));
3889 /// Determine whether an item is annotated with an attribute
3890 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
3891 let mut found = false;
3892 each_attr(tcx, did, |item| {
3893 if item.check_name(attr) {
3903 /// Determine whether an item is annotated with `#[packed]`
3904 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
3905 has_attr(tcx, did, "packed")
3908 /// Determine whether an item is annotated with `#[simd]`
3909 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
3910 has_attr(tcx, did, "simd")
3913 // Obtain the representation annotation for a definition.
3914 pub fn lookup_repr_hint(tcx: &ctxt, did: DefId) -> attr::ReprAttr {
3915 let mut acc = attr::ReprAny;
3916 ty::each_attr(tcx, did, |meta| {
3917 acc = attr::find_repr_attr(tcx.sess.diagnostic(), meta, acc);
3923 // Look up a field ID, whether or not it's local
3924 // Takes a list of type substs in case the struct is generic
3925 pub fn lookup_field_type(tcx: &ctxt,
3930 let t = if id.krate == ast::LOCAL_CRATE {
3931 node_id_to_type(tcx, id.node)
3933 let mut tcache = tcx.tcache.borrow_mut();
3934 match tcache.find(&id) {
3935 Some(&Polytype {ty, ..}) => ty,
3937 let tpt = csearch::get_field_type(tcx, struct_id, id);
3938 tcache.insert(id, tpt.clone());
3943 t.subst(tcx, substs)
3946 // Lookup all ancestor structs of a struct indicated by did. That is the reflexive,
3947 // transitive closure of doing a single lookup in cx.superstructs.
3948 fn each_super_struct(cx: &ctxt, mut did: ast::DefId, f: |ast::DefId|) {
3949 let superstructs = cx.superstructs.borrow();
3953 match superstructs.find(&did) {
3954 Some(&Some(def_id)) => {
3957 Some(&None) => break,
3960 format!("ID not mapped to super-struct: {}",
3961 cx.map.node_to_str(did.node)).as_slice());
3967 // Look up the list of field names and IDs for a given struct.
3968 // Fails if the id is not bound to a struct.
3969 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
3970 if did.krate == ast::LOCAL_CRATE {
3971 // We store the fields which are syntactically in each struct in cx. So
3972 // we have to walk the inheritance chain of the struct to get all the
3973 // structs (explicit and inherited) for a struct. If this is expensive
3974 // we could cache the whole list of fields here.
3975 let struct_fields = cx.struct_fields.borrow();
3976 let mut results: SmallVector<&[field_ty]> = SmallVector::zero();
3977 each_super_struct(cx, did, |s| {
3978 match struct_fields.find(&s) {
3979 Some(fields) => results.push(fields.as_slice()),
3982 format!("ID not mapped to struct fields: {}",
3983 cx.map.node_to_str(did.node)).as_slice());
3988 let len = results.as_slice().iter().map(|x| x.len()).sum();
3989 let mut result: Vec<field_ty> = Vec::with_capacity(len);
3990 result.extend(results.as_slice().iter().flat_map(|rs| rs.iter().map(|&f| f)));
3991 assert!(result.len() == len);
3994 csearch::get_struct_fields(&cx.sess.cstore, did)
3998 pub fn lookup_struct_field(cx: &ctxt,
4000 field_id: ast::DefId)
4002 let r = lookup_struct_fields(cx, parent);
4003 match r.iter().find(|f| f.id.node == field_id.node) {
4005 None => cx.sess.bug("struct ID not found in parent's fields")
4009 // Returns a list of fields corresponding to the struct's items. trans uses
4010 // this. Takes a list of substs with which to instantiate field types.
4011 pub fn struct_fields(cx: &ctxt, did: ast::DefId, substs: &Substs)
4013 lookup_struct_fields(cx, did).iter().map(|f| {
4015 // FIXME #6993: change type of field to Name and get rid of new()
4016 ident: ast::Ident::new(f.name),
4018 ty: lookup_field_type(cx, did, f.id, substs),
4025 pub fn is_binopable(cx: &ctxt, ty: t, op: ast::BinOp) -> bool {
4026 static tycat_other: int = 0;
4027 static tycat_bool: int = 1;
4028 static tycat_char: int = 2;
4029 static tycat_int: int = 3;
4030 static tycat_float: int = 4;
4031 static tycat_bot: int = 5;
4032 static tycat_raw_ptr: int = 6;
4034 static opcat_add: int = 0;
4035 static opcat_sub: int = 1;
4036 static opcat_mult: int = 2;
4037 static opcat_shift: int = 3;
4038 static opcat_rel: int = 4;
4039 static opcat_eq: int = 5;
4040 static opcat_bit: int = 6;
4041 static opcat_logic: int = 7;
4042 static opcat_mod: int = 8;
4044 fn opcat(op: ast::BinOp) -> int {
4046 ast::BiAdd => opcat_add,
4047 ast::BiSub => opcat_sub,
4048 ast::BiMul => opcat_mult,
4049 ast::BiDiv => opcat_mult,
4050 ast::BiRem => opcat_mod,
4051 ast::BiAnd => opcat_logic,
4052 ast::BiOr => opcat_logic,
4053 ast::BiBitXor => opcat_bit,
4054 ast::BiBitAnd => opcat_bit,
4055 ast::BiBitOr => opcat_bit,
4056 ast::BiShl => opcat_shift,
4057 ast::BiShr => opcat_shift,
4058 ast::BiEq => opcat_eq,
4059 ast::BiNe => opcat_eq,
4060 ast::BiLt => opcat_rel,
4061 ast::BiLe => opcat_rel,
4062 ast::BiGe => opcat_rel,
4063 ast::BiGt => opcat_rel
4067 fn tycat(cx: &ctxt, ty: t) -> int {
4068 if type_is_simd(cx, ty) {
4069 return tycat(cx, simd_type(cx, ty))
4072 ty_char => tycat_char,
4073 ty_bool => tycat_bool,
4074 ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
4075 ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
4076 ty_bot => tycat_bot,
4077 ty_ptr(_) => tycat_raw_ptr,
4082 static t: bool = true;
4083 static f: bool = false;
4086 // +, -, *, shift, rel, ==, bit, logic, mod
4087 /*other*/ [f, f, f, f, f, f, f, f, f],
4088 /*bool*/ [f, f, f, f, t, t, t, t, f],
4089 /*char*/ [f, f, f, f, t, t, f, f, f],
4090 /*int*/ [t, t, t, t, t, t, t, f, t],
4091 /*float*/ [t, t, t, f, t, t, f, f, f],
4092 /*bot*/ [t, t, t, t, t, t, t, t, t],
4093 /*raw ptr*/ [f, f, f, f, t, t, f, f, f]];
4095 return tbl[tycat(cx, ty) as uint ][opcat(op) as uint];
4098 /// Returns an equivalent type with all the typedefs and self regions removed.
4099 pub fn normalize_ty(cx: &ctxt, t: t) -> t {
4100 let u = TypeNormalizer(cx).fold_ty(t);
4103 struct TypeNormalizer<'a>(&'a ctxt);
4105 impl<'a> TypeFolder for TypeNormalizer<'a> {
4106 fn tcx<'a>(&'a self) -> &'a ctxt { let TypeNormalizer(c) = *self; c }
4108 fn fold_ty(&mut self, t: ty::t) -> ty::t {
4109 match self.tcx().normalized_cache.borrow().find_copy(&t) {
4114 let t_norm = ty_fold::super_fold_ty(self, t);
4115 self.tcx().normalized_cache.borrow_mut().insert(t, t_norm);
4119 fn fold_region(&mut self, _: ty::Region) -> ty::Region {
4123 fn fold_substs(&mut self,
4124 substs: &subst::Substs)
4126 subst::Substs { regions: subst::ErasedRegions,
4127 types: substs.types.fold_with(self) }
4130 fn fold_sig(&mut self,
4133 // The binder-id is only relevant to bound regions, which
4134 // are erased at trans time.
4136 binder_id: ast::DUMMY_NODE_ID,
4137 inputs: sig.inputs.fold_with(self),
4138 output: sig.output.fold_with(self),
4139 variadic: sig.variadic,
4145 pub trait ExprTyProvider {
4146 fn expr_ty(&self, ex: &ast::Expr) -> t;
4147 fn ty_ctxt<'a>(&'a self) -> &'a ctxt;
4150 impl ExprTyProvider for ctxt {
4151 fn expr_ty(&self, ex: &ast::Expr) -> t {
4155 fn ty_ctxt<'a>(&'a self) -> &'a ctxt {
4160 // Returns the repeat count for a repeating vector expression.
4161 pub fn eval_repeat_count<T: ExprTyProvider>(tcx: &T, count_expr: &ast::Expr) -> uint {
4162 match const_eval::eval_const_expr_partial(tcx, count_expr) {
4163 Ok(ref const_val) => match *const_val {
4164 const_eval::const_int(count) => if count < 0 {
4165 tcx.ty_ctxt().sess.span_err(count_expr.span,
4166 "expected positive integer for \
4167 repeat count but found negative integer");
4170 return count as uint
4172 const_eval::const_uint(count) => return count as uint,
4173 const_eval::const_float(count) => {
4174 tcx.ty_ctxt().sess.span_err(count_expr.span,
4175 "expected positive integer for \
4176 repeat count but found float");
4177 return count as uint;
4179 const_eval::const_str(_) => {
4180 tcx.ty_ctxt().sess.span_err(count_expr.span,
4181 "expected positive integer for \
4182 repeat count but found string");
4185 const_eval::const_bool(_) => {
4186 tcx.ty_ctxt().sess.span_err(count_expr.span,
4187 "expected positive integer for \
4188 repeat count but found boolean");
4191 const_eval::const_binary(_) => {
4192 tcx.ty_ctxt().sess.span_err(count_expr.span,
4193 "expected positive integer for \
4194 repeat count but found binary array");
4197 const_eval::const_nil => {
4198 tcx.ty_ctxt().sess.span_err(count_expr.span,
4199 "expected positive integer for \
4200 repeat count but found ()");
4205 tcx.ty_ctxt().sess.span_err(count_expr.span,
4206 "expected constant integer for repeat count \
4207 but found variable");
4213 // Iterate over a type parameter's bounded traits and any supertraits
4214 // of those traits, ignoring kinds.
4215 // Here, the supertraits are the transitive closure of the supertrait
4216 // relation on the supertraits from each bounded trait's constraint
4218 pub fn each_bound_trait_and_supertraits(tcx: &ctxt,
4219 bounds: &[Rc<TraitRef>],
4220 f: |Rc<TraitRef>| -> bool)
4222 for bound_trait_ref in bounds.iter() {
4223 let mut supertrait_set = HashMap::new();
4224 let mut trait_refs = Vec::new();
4227 // Seed the worklist with the trait from the bound
4228 supertrait_set.insert(bound_trait_ref.def_id, ());
4229 trait_refs.push(bound_trait_ref.clone());
4231 // Add the given trait ty to the hash map
4232 while i < trait_refs.len() {
4233 debug!("each_bound_trait_and_supertraits(i={:?}, trait_ref={})",
4234 i, trait_refs.get(i).repr(tcx));
4236 if !f(trait_refs.get(i).clone()) {
4240 // Add supertraits to supertrait_set
4241 let supertrait_refs = trait_ref_supertraits(tcx,
4242 &**trait_refs.get(i));
4243 for supertrait_ref in supertrait_refs.iter() {
4244 debug!("each_bound_trait_and_supertraits(supertrait_ref={})",
4245 supertrait_ref.repr(tcx));
4247 let d_id = supertrait_ref.def_id;
4248 if !supertrait_set.contains_key(&d_id) {
4249 // FIXME(#5527) Could have same trait multiple times
4250 supertrait_set.insert(d_id, ());
4251 trait_refs.push(supertrait_ref.clone());
4261 pub fn get_tydesc_ty(tcx: &ctxt) -> Result<t, String> {
4262 tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
4263 tcx.intrinsic_defs.borrow().find_copy(&tydesc_lang_item)
4264 .expect("Failed to resolve TyDesc")
4268 pub fn get_opaque_ty(tcx: &ctxt) -> Result<t, String> {
4269 tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| {
4270 tcx.intrinsic_defs.borrow().find_copy(&opaque_lang_item)
4271 .expect("Failed to resolve Opaque")
4275 pub fn visitor_object_ty(tcx: &ctxt,
4276 region: ty::Region) -> Result<(Rc<TraitRef>, t), String> {
4277 let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) {
4279 Err(s) => { return Err(s); }
4281 let substs = Substs::empty();
4282 let trait_ref = Rc::new(TraitRef { def_id: trait_lang_item, substs: substs });
4283 Ok((trait_ref.clone(),
4284 mk_rptr(tcx, region, mt {mutbl: ast::MutMutable,
4287 trait_ref.substs.clone(),
4288 empty_builtin_bounds()) })))
4291 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> Rc<ItemVariances> {
4292 lookup_locally_or_in_crate_store(
4293 "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
4294 || Rc::new(csearch::get_item_variances(&tcx.sess.cstore, item_id)))
4297 /// Records a trait-to-implementation mapping.
4298 pub fn record_trait_implementation(tcx: &ctxt,
4299 trait_def_id: DefId,
4300 impl_def_id: DefId) {
4301 match tcx.trait_impls.borrow().find(&trait_def_id) {
4302 Some(impls_for_trait) => {
4303 impls_for_trait.borrow_mut().push(impl_def_id);
4308 tcx.trait_impls.borrow_mut().insert(trait_def_id, Rc::new(RefCell::new(vec!(impl_def_id))));
4311 /// Populates the type context with all the implementations for the given type
4313 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
4314 type_id: ast::DefId) {
4315 if type_id.krate == LOCAL_CRATE {
4318 if tcx.populated_external_types.borrow().contains(&type_id) {
4322 csearch::each_implementation_for_type(&tcx.sess.cstore, type_id,
4324 let methods = csearch::get_impl_methods(&tcx.sess.cstore, impl_def_id);
4326 // Record the trait->implementation mappings, if applicable.
4327 let associated_traits = csearch::get_impl_trait(tcx, impl_def_id);
4328 for trait_ref in associated_traits.iter() {
4329 record_trait_implementation(tcx, trait_ref.def_id, impl_def_id);
4332 // For any methods that use a default implementation, add them to
4333 // the map. This is a bit unfortunate.
4334 for &method_def_id in methods.iter() {
4335 for &source in ty::method(tcx, method_def_id).provided_source.iter() {
4336 tcx.provided_method_sources.borrow_mut().insert(method_def_id, source);
4340 // Store the implementation info.
4341 tcx.impl_methods.borrow_mut().insert(impl_def_id, methods);
4343 // If this is an inherent implementation, record it.
4344 if associated_traits.is_none() {
4345 match tcx.inherent_impls.borrow().find(&type_id) {
4346 Some(implementation_list) => {
4347 implementation_list.borrow_mut().push(impl_def_id);
4352 tcx.inherent_impls.borrow_mut().insert(type_id,
4353 Rc::new(RefCell::new(vec!(impl_def_id))));
4357 tcx.populated_external_types.borrow_mut().insert(type_id);
4360 /// Populates the type context with all the implementations for the given
4361 /// trait if necessary.
4362 pub fn populate_implementations_for_trait_if_necessary(
4364 trait_id: ast::DefId) {
4365 if trait_id.krate == LOCAL_CRATE {
4368 if tcx.populated_external_traits.borrow().contains(&trait_id) {
4372 csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id,
4373 |implementation_def_id| {
4374 let methods = csearch::get_impl_methods(&tcx.sess.cstore, implementation_def_id);
4376 // Record the trait->implementation mapping.
4377 record_trait_implementation(tcx, trait_id, implementation_def_id);
4379 // For any methods that use a default implementation, add them to
4380 // the map. This is a bit unfortunate.
4381 for &method_def_id in methods.iter() {
4382 for &source in ty::method(tcx, method_def_id).provided_source.iter() {
4383 tcx.provided_method_sources.borrow_mut().insert(method_def_id, source);
4387 // Store the implementation info.
4388 tcx.impl_methods.borrow_mut().insert(implementation_def_id, methods);
4391 tcx.populated_external_traits.borrow_mut().insert(trait_id);
4394 /// Given the def_id of an impl, return the def_id of the trait it implements.
4395 /// If it implements no trait, return `None`.
4396 pub fn trait_id_of_impl(tcx: &ctxt,
4397 def_id: ast::DefId) -> Option<ast::DefId> {
4398 let node = match tcx.map.find(def_id.node) {
4403 ast_map::NodeItem(item) => {
4405 ast::ItemImpl(_, Some(ref trait_ref), _, _) => {
4406 Some(node_id_to_trait_ref(tcx, trait_ref.ref_id).def_id)
4415 /// If the given def ID describes a method belonging to an impl, return the
4416 /// ID of the impl that the method belongs to. Otherwise, return `None`.
4417 pub fn impl_of_method(tcx: &ctxt, def_id: ast::DefId)
4418 -> Option<ast::DefId> {
4419 if def_id.krate != LOCAL_CRATE {
4420 return match csearch::get_method(tcx, def_id).container {
4421 TraitContainer(_) => None,
4422 ImplContainer(def_id) => Some(def_id),
4425 match tcx.methods.borrow().find_copy(&def_id) {
4427 match method.container {
4428 TraitContainer(_) => None,
4429 ImplContainer(def_id) => Some(def_id),
4436 /// If the given def ID describes a method belonging to a trait (either a
4437 /// default method or an implementation of a trait method), return the ID of
4438 /// the trait that the method belongs to. Otherwise, return `None`.
4439 pub fn trait_of_method(tcx: &ctxt, def_id: ast::DefId)
4440 -> Option<ast::DefId> {
4441 if def_id.krate != LOCAL_CRATE {
4442 return csearch::get_trait_of_method(&tcx.sess.cstore, def_id, tcx);
4444 match tcx.methods.borrow().find_copy(&def_id) {
4446 match method.container {
4447 TraitContainer(def_id) => Some(def_id),
4448 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
4455 /// If the given def ID describes a method belonging to a trait, (either a
4456 /// default method or an implementation of a trait method), return the ID of
4457 /// the method inside trait definition (this means that if the given def ID
4458 /// is already that of the original trait method, then the return value is
4460 /// Otherwise, return `None`.
4461 pub fn trait_method_of_method(tcx: &ctxt,
4462 def_id: ast::DefId) -> Option<ast::DefId> {
4463 let method = match tcx.methods.borrow().find(&def_id) {
4464 Some(m) => m.clone(),
4465 None => return None,
4467 let name = method.ident.name;
4468 match trait_of_method(tcx, def_id) {
4469 Some(trait_did) => {
4470 let trait_methods = ty::trait_methods(tcx, trait_did);
4471 trait_methods.iter()
4472 .position(|m| m.ident.name == name)
4473 .map(|idx| ty::trait_method(tcx, trait_did, idx).def_id)
4479 /// Creates a hash of the type `t` which will be the same no matter what crate
4480 /// context it's calculated within. This is used by the `type_id` intrinsic.
4481 pub fn hash_crate_independent(tcx: &ctxt, t: t, svh: &Svh) -> u64 {
4482 let mut state = sip::SipState::new();
4483 macro_rules! byte( ($b:expr) => { ($b as u8).hash(&mut state) } );
4484 macro_rules! hash( ($e:expr) => { $e.hash(&mut state) } );
4486 let region = |_state: &mut sip::SipState, r: Region| {
4496 tcx.sess.bug("non-static region found when hashing a type")
4500 let did = |state: &mut sip::SipState, did: DefId| {
4501 let h = if ast_util::is_local(did) {
4504 tcx.sess.cstore.get_crate_hash(did.krate)
4506 h.as_str().hash(state);
4507 did.node.hash(state);
4509 let mt = |state: &mut sip::SipState, mt: mt| {
4510 mt.mutbl.hash(state);
4512 ty::walk_ty(t, |t| {
4513 match ty::get(t).sty {
4516 ty_bool => byte!(2),
4517 ty_char => byte!(3),
4543 ty_vec(m, Some(n)) => {
4547 1u8.hash(&mut state);
4549 ty_vec(m, None) => {
4552 0u8.hash(&mut state);
4560 region(&mut state, r);
4563 ty_bare_fn(ref b) => {
4568 ty_closure(ref c) => {
4574 UniqTraitStore => byte!(0),
4575 RegionTraitStore(r, m) => {
4577 region(&mut state, r);
4578 assert_eq!(m, ast::MutMutable);
4582 ty_trait(box ty::TyTrait { def_id: d, bounds, .. }) => {
4587 ty_struct(d, _) => {
4591 ty_tup(ref inner) => {
4598 did(&mut state, p.def_id);
4600 ty_infer(_) => unreachable!(),
4601 ty_err => byte!(23),
4609 pub fn to_str(self) -> &'static str {
4612 Contravariant => "-",
4619 pub fn construct_parameter_environment(
4621 generics: &ty::Generics,
4622 free_id: ast::NodeId)
4623 -> ParameterEnvironment
4625 /*! See `ParameterEnvironment` struct def'n for details */
4628 // Construct the free substs.
4632 let mut types = VecPerParamSpace::empty();
4633 for &space in subst::ParamSpace::all().iter() {
4634 push_types_from_defs(tcx, &mut types, space,
4635 generics.types.get_vec(space));
4638 // map bound 'a => free 'a
4639 let mut regions = VecPerParamSpace::empty();
4640 for &space in subst::ParamSpace::all().iter() {
4641 push_region_params(&mut regions, space, free_id,
4642 generics.regions.get_vec(space));
4645 let free_substs = Substs {
4647 regions: subst::NonerasedRegions(regions)
4651 // Compute the bounds on Self and the type parameters.
4654 let mut bounds = VecPerParamSpace::empty();
4655 for &space in subst::ParamSpace::all().iter() {
4656 push_bounds_from_defs(tcx, &mut bounds, space, &free_substs,
4657 generics.types.get_vec(space));
4660 debug!("construct_parameter_environment: free_id={} \
4664 free_substs.repr(tcx),
4667 return ty::ParameterEnvironment {
4668 free_substs: free_substs,
4672 fn push_region_params(regions: &mut VecPerParamSpace<ty::Region>,
4673 space: subst::ParamSpace,
4674 free_id: ast::NodeId,
4675 region_params: &Vec<RegionParameterDef>)
4677 for r in region_params.iter() {
4678 regions.push(space, ty::free_region_from_def(free_id, r));
4682 fn push_types_from_defs(tcx: &ty::ctxt,
4683 types: &mut subst::VecPerParamSpace<ty::t>,
4684 space: subst::ParamSpace,
4685 defs: &Vec<TypeParameterDef>) {
4686 for (i, def) in defs.iter().enumerate() {
4687 let ty = ty::mk_param(tcx, space, i, def.def_id);
4688 types.push(space, ty);
4692 fn push_bounds_from_defs(tcx: &ty::ctxt,
4693 bounds: &mut subst::VecPerParamSpace<ParamBounds>,
4694 space: subst::ParamSpace,
4695 free_substs: &subst::Substs,
4696 defs: &Vec<TypeParameterDef>) {
4697 for def in defs.iter() {
4698 let b = (*def.bounds).subst(tcx, free_substs);
4699 bounds.push(space, b);
4705 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
4707 ast::MutMutable => MutBorrow,
4708 ast::MutImmutable => ImmBorrow,
4712 pub fn to_user_str(&self) -> &'static str {
4714 MutBorrow => "mutable",
4715 ImmBorrow => "immutable",
4716 UniqueImmBorrow => "uniquely immutable",
4721 impl mc::Typer for ty::ctxt {
4722 fn tcx<'a>(&'a self) -> &'a ty::ctxt {
4726 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<ty::t> {
4727 Ok(ty::node_id_to_type(self, id))
4730 fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t> {
4731 self.method_map.borrow().find(&method_call).map(|method| method.ty)
4734 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment>> {
4738 fn is_method_call(&self, id: ast::NodeId) -> bool {
4739 self.method_map.borrow().contains_key(&typeck::MethodCall::expr(id))
4742 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<ast::NodeId> {
4743 self.region_maps.temporary_scope(rvalue_id)
4746 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow {
4747 self.upvar_borrow_map.borrow().get_copy(&upvar_id)