1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #[allow(non_camel_case_types)];
15 use metadata::csearch;
17 use middle::const_eval;
18 use middle::lang_items::{ExchangeHeapLangItem, OpaqueStructLangItem};
19 use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem};
22 use middle::resolve_lifetime;
24 use middle::subst::Subst;
27 use middle::ty_fold::TypeFolder;
29 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_str};
30 use util::ppaux::{trait_store_to_str, ty_to_str, vstore_to_str};
31 use util::ppaux::{Repr, UserString};
32 use util::common::{indenter};
33 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet};
36 use std::cell::{Cell, RefCell};
40 use std::hash::{Hash, sip};
44 use collections::{HashMap, HashSet};
46 use syntax::ast_util::{is_local, lit_is_str};
49 use syntax::attr::AttrMetaMethods;
50 use syntax::codemap::Span;
51 use syntax::parse::token;
52 use syntax::parse::token::InternedString;
53 use syntax::{ast, ast_map};
54 use syntax::opt_vec::OptVec;
56 use syntax::abi::AbiSet;
58 use collections::enum_set::{EnumSet, CLike};
62 pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0;
73 pub enum MethodContainer {
74 TraitContainer(ast::DefId),
75 ImplContainer(ast::DefId),
81 generics: ty::Generics,
83 explicit_self: ast::ExplicitSelf_,
86 container: MethodContainer,
88 // If this method is provided, we need to know where it came from
89 provided_source: Option<ast::DefId>
93 pub fn new(ident: ast::Ident,
94 generics: ty::Generics,
96 explicit_self: ast::ExplicitSelf_,
99 container: MethodContainer,
100 provided_source: Option<ast::DefId>)
106 explicit_self: explicit_self,
109 container: container,
110 provided_source: provided_source
114 pub fn container_id(&self) -> ast::DefId {
115 match self.container {
116 TraitContainer(id) => id,
117 ImplContainer(id) => id,
128 #[deriving(Clone, Eq, Hash)]
131 mutbl: ast::Mutability,
134 #[deriving(Clone, Eq, Encodable, Decodable, Hash, Show)]
141 #[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)]
142 pub enum TraitStore {
143 UniqTraitStore, // ~Trait
144 RegionTraitStore(Region), // &Trait
147 pub struct field_ty {
150 vis: ast::Visibility,
153 // Contains information needed to resolve types and (in the future) look up
154 // the types of AST nodes.
155 #[deriving(Eq, Hash)]
156 pub struct creader_cache_key {
162 pub type creader_cache = RefCell<HashMap<creader_cache_key, t>>;
164 pub struct intern_key {
168 // NB: Do not replace this with #[deriving(Eq)]. The automatically-derived
169 // implementation will not recurse through sty and you will get stack
171 impl cmp::Eq for intern_key {
172 fn eq(&self, other: &intern_key) -> bool {
174 *self.sty == *other.sty
177 fn ne(&self, other: &intern_key) -> bool {
183 impl Hash for intern_key {
184 fn hash(&self, s: &mut sip::SipState) {
185 unsafe { (*self.sty).hash(s) }
189 impl<W:Writer> Hash<W> for intern_key {
190 fn hash(&self, s: &mut W) {
191 unsafe { (*self.sty).hash(s) }
195 pub enum ast_ty_to_ty_cache_entry {
196 atttce_unresolved, /* not resolved yet */
197 atttce_resolved(t) /* resolved to a type, irrespective of region */
200 #[deriving(Clone, Eq, Decodable, Encodable)]
201 pub struct ItemVariances {
202 self_param: Option<Variance>,
203 type_params: OptVec<Variance>,
204 region_params: OptVec<Variance>
207 #[deriving(Clone, Eq, Decodable, Encodable, Show)]
209 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
210 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
211 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
212 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
215 pub enum AutoAdjustment {
216 AutoAddEnv(ty::Region, ast::Sigil),
217 AutoDerefRef(AutoDerefRef),
218 AutoObject(ast::Sigil, Option<ty::Region>,
221 ast::DefId, /* Trait ID */
222 ty::substs /* Trait substitutions */)
225 #[deriving(Decodable, Encodable)]
226 pub struct AutoDerefRef {
228 autoref: Option<AutoRef>
231 #[deriving(Decodable, Encodable)]
233 /// Convert from T to &T
234 AutoPtr(Region, ast::Mutability),
236 /// Convert from ~[]/&[] to &[] (or str)
237 AutoBorrowVec(Region, ast::Mutability),
239 /// Convert from ~[]/&[] to &&[] (or str)
240 AutoBorrowVecRef(Region, ast::Mutability),
242 /// Convert from @fn()/~fn()/|| to ||
243 AutoBorrowFn(Region),
245 /// Convert from T to *T
246 AutoUnsafe(ast::Mutability),
248 /// Convert from ~Trait/&Trait to &Trait
249 AutoBorrowObj(Region, ast::Mutability),
252 pub type ctxt = @ctxt_;
254 /// The data structure to keep track of all the information that typechecker
255 /// generates so that so that it can be reused and doesn't have to be redone
258 diag: @syntax::diagnostic::SpanHandler,
259 // Specifically use a speedy hash algorithm for this hash map, it's used
262 interner: RefCell<HashMap<intern_key, ~t_box_>>,
264 interner: RefCell<HashMap<intern_key, ~t_box_, ::util::nodemap::FnvHasher>>,
266 cstore: @metadata::cstore::CStore,
267 sess: session::Session,
268 def_map: resolve::DefMap,
270 named_region_map: @RefCell<resolve_lifetime::NamedRegionMap>,
272 region_maps: middle::region::RegionMaps,
274 // Stores the types for various nodes in the AST. Note that this table
275 // is not guaranteed to be populated until after typeck. See
276 // typeck::check::fn_ctxt for details.
277 node_types: node_type_table,
279 // Stores the type parameters which were substituted to obtain the type
280 // of this node. This only applies to nodes that refer to entities
281 // parameterized by type parameters, such as generic fns, types, or
283 node_type_substs: RefCell<NodeMap<~[t]>>,
285 // Maps from a method to the method "descriptor"
286 methods: RefCell<DefIdMap<@Method>>,
288 // Maps from a trait def-id to a list of the def-ids of its methods
289 trait_method_def_ids: RefCell<DefIdMap<@~[DefId]>>,
291 // A cache for the trait_methods() routine
292 trait_methods_cache: RefCell<DefIdMap<@~[@Method]>>,
294 impl_trait_cache: RefCell<DefIdMap<Option<@ty::TraitRef>>>,
296 trait_refs: RefCell<NodeMap<@TraitRef>>,
297 trait_defs: RefCell<DefIdMap<@TraitDef>>,
300 intrinsic_defs: RefCell<DefIdMap<t>>,
301 freevars: RefCell<freevars::freevar_map>,
303 rcache: creader_cache,
304 short_names_cache: RefCell<HashMap<t, ~str>>,
305 needs_unwind_cleanup_cache: RefCell<HashMap<t, bool>>,
306 tc_cache: RefCell<HashMap<uint, TypeContents>>,
307 ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry>>,
308 enum_var_cache: RefCell<DefIdMap<@~[@VariantInfo]>>,
309 ty_param_defs: RefCell<NodeMap<TypeParameterDef>>,
310 adjustments: RefCell<NodeMap<@AutoAdjustment>>,
311 normalized_cache: RefCell<HashMap<t, t>>,
312 lang_items: @middle::lang_items::LanguageItems,
313 // A mapping of fake provided method def_ids to the default implementation
314 provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
315 supertraits: RefCell<DefIdMap<@~[@TraitRef]>>,
317 // Maps from def-id of a type or region parameter to its
318 // (inferred) variance.
319 item_variance_map: RefCell<DefIdMap<@ItemVariances>>,
321 // A mapping from the def ID of an enum or struct type to the def ID
322 // of the method that implements its destructor. If the type is not
323 // present in this map, it does not have a destructor. This map is
324 // populated during the coherence phase of typechecking.
325 destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
327 // A method will be in this list if and only if it is a destructor.
328 destructors: RefCell<DefIdSet>,
330 // Maps a trait onto a list of impls of that trait.
331 trait_impls: RefCell<DefIdMap<@RefCell<~[@Impl]>>>,
333 // Maps a def_id of a type to a list of its inherent impls.
334 // Contains implementations of methods that are inherent to a type.
335 // Methods in these implementations don't need to be exported.
336 inherent_impls: RefCell<DefIdMap<@RefCell<~[@Impl]>>>,
338 // Maps a def_id of an impl to an Impl structure.
339 // Note that this contains all of the impls that we know about,
340 // including ones in other crates. It's not clear that this is the best
342 impls: RefCell<DefIdMap<@Impl>>,
344 // Set of used unsafe nodes (functions or blocks). Unsafe nodes not
345 // present in this set can be warned about.
346 used_unsafe: RefCell<NodeSet>,
348 // Set of nodes which mark locals as mutable which end up getting used at
349 // some point. Local variable definitions not in this set can be warned
351 used_mut_nodes: RefCell<NodeSet>,
353 // vtable resolution information for impl declarations
354 impl_vtables: typeck::impl_vtable_map,
356 // The set of external nominal types whose implementations have been read.
357 // This is used for lazy resolution of methods.
358 populated_external_types: RefCell<DefIdSet>,
360 // The set of external traits whose implementations have been read. This
361 // is used for lazy resolution of traits.
362 populated_external_traits: RefCell<DefIdSet>,
365 upvar_borrow_map: RefCell<UpvarBorrowMap>,
367 // These two caches are used by const_eval when decoding external statics
368 // and variants that are found.
369 extern_const_statics: RefCell<DefIdMap<Option<@ast::Expr>>>,
370 extern_const_variants: RefCell<DefIdMap<Option<@ast::Expr>>>,
381 // a meta-flag: subst may be required if the type has parameters, a self
382 // type, or references bound regions
383 needs_subst = 1 | 2 | 8
386 pub type t_box = &'static t_box_;
394 // To reduce refcounting cost, we're representing types as unsafe pointers
395 // throughout the compiler. These are simply casted t_box values. Use ty::get
396 // to cast them back to a box. (Without the cast, compiler performance suffers
397 // ~15%.) This does mean that a t value relies on the ctxt to keep its box
398 // alive, and using ty::get is unsafe when the ctxt is no longer alive.
401 #[deriving(Clone, Eq, Hash)]
402 pub struct t { priv inner: *t_opaque }
404 impl fmt::Show for t {
405 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
406 f.buf.write_str("*t_opaque")
410 pub fn get(t: t) -> t_box {
412 let t2: t_box = cast::transmute(t);
417 pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
418 (tb.flags & (flag as uint)) != 0u
420 pub fn type_has_params(t: t) -> bool {
421 tbox_has_flag(get(t), has_params)
423 pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
424 pub fn type_needs_infer(t: t) -> bool {
425 tbox_has_flag(get(t), needs_infer)
427 pub fn type_has_regions(t: t) -> bool {
428 tbox_has_flag(get(t), has_regions)
430 pub fn type_id(t: t) -> uint { get(t).id }
432 #[deriving(Clone, Eq, Hash)]
433 pub struct BareFnTy {
439 #[deriving(Clone, Eq, Hash)]
440 pub struct ClosureTy {
443 onceness: ast::Onceness,
445 bounds: BuiltinBounds,
450 * Signature of a function type, which I have arbitrarily
451 * decided to use to refer to the input/output types.
453 * - `binder_id` is the node id where this fn type appeared;
454 * it is used to identify all the bound regions appearing
455 * in the input/output types that are bound by this fn type
456 * (vs some enclosing or enclosed fn type)
457 * - `inputs` is the list of arguments and their modes.
458 * - `output` is the return type.
459 * - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
461 #[deriving(Clone, Eq, Hash)]
463 binder_id: ast::NodeId,
469 #[deriving(Clone, Eq, Hash)]
470 pub struct param_ty {
475 /// Representation of regions:
476 #[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)]
478 // Region bound in a type or fn declaration which will be
479 // substituted 'early' -- that is, at the same time when type
480 // parameters are substituted.
481 ReEarlyBound(/* param id */ ast::NodeId, /*index*/ uint, ast::Name),
483 // Region bound in a function scope, which will be substituted when the
484 // function is called. The first argument must be the `binder_id` of
485 // some enclosing function signature.
486 ReLateBound(/* binder_id */ ast::NodeId, BoundRegion),
488 /// When checking a function body, the types of all arguments and so forth
489 /// that refer to bound region parameters are modified to refer to free
490 /// region parameters.
493 /// A concrete region naming some expression within the current function.
496 /// Static data that has an "infinite" lifetime. Top in the region lattice.
499 /// A region variable. Should not exist after typeck.
500 ReInfer(InferRegion),
502 /// Empty lifetime is for data that is never accessed.
503 /// Bottom in the region lattice. We treat ReEmpty somewhat
504 /// specially; at least right now, we do not generate instances of
505 /// it during the GLB computations, but rather
506 /// generate an error instead. This is to improve error messages.
507 /// The only way to get an instance of ReEmpty is to have a region
508 /// variable with no constraints.
513 * Upvars do not get their own node-id. Instead, we use the pair of
514 * the original var id (that is, the root variable that is referenced
515 * by the upvar) and the id of the closure expression.
517 #[deriving(Clone, Eq, Hash)]
520 closure_expr_id: ast::NodeId,
523 #[deriving(Clone, Eq, Hash)]
524 pub enum BorrowKind {
525 /// Data must be immutable and is aliasable.
528 /// Data must be immutable but not aliasable. This kind of borrow
529 /// cannot currently be expressed by the user and is used only in
530 /// implicit closure bindings. It is needed when you the closure
531 /// is borrowing or mutating a mutable referent, e.g.:
533 /// let x: &mut int = ...;
534 /// let y = || *x += 5;
536 /// If we were to try to translate this closure into a more explicit
537 /// form, we'd encounter an error with the code as written:
539 /// struct Env { x: & &mut int }
540 /// let x: &mut int = ...;
541 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
542 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
544 /// This is then illegal because you cannot mutate a `&mut` found
545 /// in an aliasable location. To solve, you'd have to translate with
546 /// an `&mut` borrow:
548 /// struct Env { x: & &mut int }
549 /// let x: &mut int = ...;
550 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
551 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
553 /// Now the assignment to `**env.x` is legal, but creating a
554 /// mutable pointer to `x` is not because `x` is not mutable. We
555 /// could fix this by declaring `x` as `let mut x`. This is ok in
556 /// user code, if awkward, but extra weird for closures, since the
557 /// borrow is hidden.
559 /// So we introduce a "unique imm" borrow -- the referent is
560 /// immutable, but not aliasable. This solves the problem. For
561 /// simplicity, we don't give users the way to express this
562 /// borrow, it's just used when translating closures.
565 /// Data is mutable and not aliasable.
570 * Information describing the borrowing of an upvar. This is computed
571 * during `typeck`, specifically by `regionck`. The general idea is
572 * that the compiler analyses treat closures like:
574 * let closure: &'e fn() = || {
575 * x = 1; // upvar x is assigned to
576 * use(y); // upvar y is read
577 * foo(&z); // upvar z is borrowed immutably
580 * as if they were "desugared" to something loosely like:
582 * struct Vars<'x,'y,'z> { x: &'x mut int,
585 * let closure: &'e fn() = {
591 * let env: &'e mut Vars<'x,'y,'z> = &mut Vars { x: &'x mut x,
597 * This is basically what happens at runtime. The closure is basically
598 * an existentially quantified version of the `(env, f)` pair.
600 * This data structure indicates the region and mutability of a single
601 * one of the `x...z` borrows.
603 * It may not be obvious why each borrowed variable gets its own
604 * lifetime (in the desugared version of the example, these are indicated
605 * by the lifetime parameters `'x`, `'y`, and `'z` in the `Vars` definition).
606 * Each such lifetime must encompass the lifetime `'e` of the closure itself,
607 * but need not be identical to it. The reason that this makes sense:
609 * - Callers are only permitted to invoke the closure, and hence to
610 * use the pointers, within the lifetime `'e`, so clearly `'e` must
611 * be a sublifetime of `'x...'z`.
612 * - The closure creator knows which upvars were borrowed by the closure
613 * and thus `x...z` will be reserved for `'x...'z` respectively.
614 * - Through mutation, the borrowed upvars can actually escape
615 * the closure, so sometimes it is necessary for them to be larger
616 * than the closure lifetime itself.
618 #[deriving(Eq, Clone)]
619 pub struct UpvarBorrow {
624 pub type UpvarBorrowMap = HashMap<UpvarId, UpvarBorrow>;
627 pub fn is_bound(&self) -> bool {
629 &ty::ReEarlyBound(..) => true,
630 &ty::ReLateBound(..) => true,
636 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd, Hash, Encodable, Decodable, Show)]
637 pub struct FreeRegion {
639 bound_region: BoundRegion
642 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd, Hash, Encodable, Decodable, Show)]
643 pub enum BoundRegion {
644 /// An anonymous region parameter for a given fn (&T)
647 /// Named region parameters for functions (a in &'a T)
649 /// The def-id is needed to distinguish free regions in
650 /// the event of shadowing.
651 BrNamed(ast::DefId, ast::Name),
653 /// Fresh bound identifiers created during GLB computations.
658 * Represents the values to use when substituting lifetime parameters.
659 * If the value is `ErasedRegions`, then this subst is occurring during
660 * trans, and all region parameters will be replaced with `ty::ReStatic`. */
661 #[deriving(Clone, Eq, Hash)]
662 pub enum RegionSubsts {
664 NonerasedRegions(OptVec<ty::Region>)
668 * The type substs represents the kinds of things that can be substituted to
669 * convert a polytype into a monotype. Note however that substituting bound
670 * regions other than `self` is done through a different mechanism:
672 * - `tps` represents the type parameters in scope. They are indexed
673 * according to the order in which they were declared.
675 * - `self_r` indicates the region parameter `self` that is present on nominal
676 * types (enums, structs) declared as having a region parameter. `self_r`
677 * should always be none for types that are not region-parameterized and
678 * Some(_) for types that are. The only bound region parameter that should
679 * appear within a region-parameterized type is `self`.
681 * - `self_ty` is the type to which `self` should be remapped, if any. The
682 * `self` type is rather funny in that it can only appear on traits and is
683 * always substituted away to the implementing type for a trait. */
684 #[deriving(Clone, Eq, Hash)]
686 self_ty: Option<ty::t>,
688 regions: RegionSubsts,
696 macro_rules! def_prim_ty(
697 ($name:ident, $sty:expr, $id:expr) => (
698 pub static $name: t_box_ = t_box_ {
706 def_prim_ty!(TY_NIL, super::ty_nil, 0)
707 def_prim_ty!(TY_BOOL, super::ty_bool, 1)
708 def_prim_ty!(TY_CHAR, super::ty_char, 2)
709 def_prim_ty!(TY_INT, super::ty_int(ast::TyI), 3)
710 def_prim_ty!(TY_I8, super::ty_int(ast::TyI8), 4)
711 def_prim_ty!(TY_I16, super::ty_int(ast::TyI16), 5)
712 def_prim_ty!(TY_I32, super::ty_int(ast::TyI32), 6)
713 def_prim_ty!(TY_I64, super::ty_int(ast::TyI64), 7)
714 def_prim_ty!(TY_UINT, super::ty_uint(ast::TyU), 8)
715 def_prim_ty!(TY_U8, super::ty_uint(ast::TyU8), 9)
716 def_prim_ty!(TY_U16, super::ty_uint(ast::TyU16), 10)
717 def_prim_ty!(TY_U32, super::ty_uint(ast::TyU32), 11)
718 def_prim_ty!(TY_U64, super::ty_uint(ast::TyU64), 12)
719 def_prim_ty!(TY_F32, super::ty_float(ast::TyF32), 14)
720 def_prim_ty!(TY_F64, super::ty_float(ast::TyF64), 15)
722 pub static TY_BOT: t_box_ = t_box_ {
725 flags: super::has_ty_bot as uint,
728 pub static TY_ERR: t_box_ = t_box_ {
731 flags: super::has_ty_err as uint,
734 pub static LAST_PRIMITIVE_ID: uint = 18;
737 // NB: If you change this, you'll probably want to change the corresponding
738 // AST structure in libsyntax/ast.rs as well.
739 #[deriving(Clone, Eq, Hash)]
746 ty_uint(ast::UintTy),
747 ty_float(ast::FloatTy),
749 ty_enum(DefId, substs),
755 ty_bare_fn(BareFnTy),
756 ty_closure(ClosureTy),
757 ty_trait(DefId, substs, TraitStore, ast::Mutability, BuiltinBounds),
758 ty_struct(DefId, substs),
761 ty_param(param_ty), // type parameter
762 ty_self(DefId), /* special, implicit `self` type parameter;
763 * def_id is the id of the trait */
765 ty_infer(InferTy), // something used only during inference/typeck
766 ty_err, // Also only used during inference/typeck, to represent
767 // the type of an erroneous expression (helps cut down
768 // on non-useful type error messages)
770 // "Fake" types, used for trans purposes
774 #[deriving(Eq, Hash)]
775 pub struct TraitRef {
780 #[deriving(Clone, Eq)]
781 pub enum IntVarValue {
783 UintType(ast::UintTy),
786 #[deriving(Clone, Show)]
787 pub enum terr_vstore_kind {
794 #[deriving(Clone, Show)]
795 pub struct expected_found<T> {
800 // Data structures used in type unification
801 #[deriving(Clone, Show)]
804 terr_purity_mismatch(expected_found<Purity>),
805 terr_onceness_mismatch(expected_found<Onceness>),
806 terr_abi_mismatch(expected_found<AbiSet>),
808 terr_sigil_mismatch(expected_found<ast::Sigil>),
813 terr_tuple_size(expected_found<uint>),
814 terr_ty_param_size(expected_found<uint>),
815 terr_record_size(expected_found<uint>),
816 terr_record_mutability,
817 terr_record_fields(expected_found<Ident>),
819 terr_regions_does_not_outlive(Region, Region),
820 terr_regions_not_same(Region, Region),
821 terr_regions_no_overlap(Region, Region),
822 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
823 terr_regions_overly_polymorphic(BoundRegion, Region),
824 terr_vstores_differ(terr_vstore_kind, expected_found<vstore>),
825 terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
826 terr_in_field(@type_err, ast::Ident),
827 terr_sorts(expected_found<t>),
828 terr_integer_as_char,
829 terr_int_mismatch(expected_found<IntVarValue>),
830 terr_float_mismatch(expected_found<ast::FloatTy>),
831 terr_traits(expected_found<ast::DefId>),
832 terr_builtin_bounds(expected_found<BuiltinBounds>),
833 terr_variadic_mismatch(expected_found<bool>)
836 #[deriving(Eq, Hash)]
837 pub struct ParamBounds {
838 builtin_bounds: BuiltinBounds,
839 trait_bounds: ~[@TraitRef]
842 pub type BuiltinBounds = EnumSet<BuiltinBound>;
844 #[deriving(Clone, Encodable, Eq, Decodable, Hash, Show)]
846 pub enum BuiltinBound {
854 pub fn EmptyBuiltinBounds() -> BuiltinBounds {
858 pub fn AllBuiltinBounds() -> BuiltinBounds {
859 let mut set = EnumSet::empty();
860 set.add(BoundStatic);
862 set.add(BoundFreeze);
867 impl CLike for BuiltinBound {
868 fn to_uint(&self) -> uint {
871 fn from_uint(v: uint) -> BuiltinBound {
872 unsafe { cast::transmute(v) }
876 #[deriving(Clone, Eq, Hash)]
877 pub struct TyVid(uint);
879 #[deriving(Clone, Eq, Hash)]
880 pub struct IntVid(uint);
882 #[deriving(Clone, Eq, Hash)]
883 pub struct FloatVid(uint);
885 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
886 pub struct RegionVid {
890 #[deriving(Clone, Eq, Hash)]
897 #[deriving(Clone, Encodable, Decodable, Hash, Show)]
898 pub enum InferRegion {
900 ReSkolemized(uint, BoundRegion)
903 impl cmp::Eq for InferRegion {
904 fn eq(&self, other: &InferRegion) -> bool {
905 match ((*self), *other) {
906 (ReVar(rva), ReVar(rvb)) => {
909 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
915 fn ne(&self, other: &InferRegion) -> bool {
916 !((*self) == (*other))
921 fn to_uint(&self) -> uint;
925 fn to_uint(&self) -> uint { let TyVid(v) = *self; v }
928 impl fmt::Show for TyVid {
929 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
930 write!(f.buf, "<generic \\#{}>", self.to_uint())
934 impl Vid for IntVid {
935 fn to_uint(&self) -> uint { let IntVid(v) = *self; v }
938 impl fmt::Show for IntVid {
939 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
940 write!(f.buf, "<generic integer \\#{}>", self.to_uint())
944 impl Vid for FloatVid {
945 fn to_uint(&self) -> uint { let FloatVid(v) = *self; v }
948 impl fmt::Show for FloatVid {
949 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
950 write!(f.buf, "<generic float \\#{}>", self.to_uint())
954 impl Vid for RegionVid {
955 fn to_uint(&self) -> uint { self.id }
958 impl fmt::Show for RegionVid {
959 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
964 impl fmt::Show for FnSig {
965 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
966 // grr, without tcx not much we can do.
967 write!(f.buf, "(...)")
971 impl fmt::Show for InferTy {
972 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
974 TyVar(ref v) => v.fmt(f),
975 IntVar(ref v) => v.fmt(f),
976 FloatVar(ref v) => v.fmt(f),
981 impl fmt::Show for IntVarValue {
982 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
984 IntType(ref v) => v.fmt(f),
985 UintType(ref v) => v.fmt(f),
991 pub struct TypeParameterDef {
994 bounds: @ParamBounds,
995 default: Option<ty::t>
998 #[deriving(Encodable, Decodable, Clone)]
999 pub struct RegionParameterDef {
1004 /// Information about the type/lifetime parameters associated with an item.
1005 /// Analogous to ast::Generics.
1007 pub struct Generics {
1008 /// List of type parameters declared on the item.
1009 type_param_defs: Rc<~[TypeParameterDef]>,
1011 /// List of region parameters declared on the item.
1012 region_param_defs: Rc<~[RegionParameterDef]>,
1016 pub fn has_type_params(&self) -> bool {
1017 !self.type_param_defs.borrow().is_empty()
1019 pub fn type_param_defs<'a>(&'a self) -> &'a [TypeParameterDef] {
1020 self.type_param_defs.borrow().as_slice()
1022 pub fn region_param_defs<'a>(&'a self) -> &'a [RegionParameterDef] {
1023 self.region_param_defs.borrow().as_slice()
1027 /// When type checking, we use the `ParameterEnvironment` to track
1028 /// details about the type/lifetime parameters that are in scope.
1029 /// It primarily stores the bounds information.
1031 /// Note: This information might seem to be redundant with the data in
1032 /// `tcx.ty_param_defs`, but it is not. That table contains the
1033 /// parameter definitions from an "outside" perspective, but this
1034 /// struct will contain the bounds for a parameter as seen from inside
1035 /// the function body. Currently the only real distinction is that
1036 /// bound lifetime parameters are replaced with free ones, but in the
1037 /// future I hope to refine the representation of types so as to make
1038 /// more distinctions clearer.
1039 pub struct ParameterEnvironment {
1040 /// A substitution that can be applied to move from
1041 /// the "outer" view of a type or method to the "inner" view.
1042 /// In general, this means converting from bound parameters to
1043 /// free parameters. Since we currently represent bound/free type
1044 /// parameters in the same way, this only has an affect on regions.
1045 free_substs: ty::substs,
1047 /// Bound on the Self parameter
1048 self_param_bound: Option<@TraitRef>,
1050 /// Bounds on each numbered type parameter
1051 type_param_bounds: ~[ParamBounds],
1056 /// - `bounds`: The list of bounds for each type parameter. The length of the
1057 /// list also tells you how many type parameters there are.
1059 /// - `rp`: true if the type is region-parameterized. Types can have at
1060 /// most one region parameter, always called `&self`.
1062 /// - `ty`: the base type. May have reference to the (unsubstituted) bound
1063 /// region `&self` or to (unsubstituted) ty_param types
1065 pub struct ty_param_bounds_and_ty {
1070 /// As `ty_param_bounds_and_ty` but for a trait ref.
1071 pub struct TraitDef {
1073 bounds: BuiltinBounds,
1074 trait_ref: @ty::TraitRef,
1077 pub struct ty_param_substs_and_ty {
1082 pub type type_cache = RefCell<DefIdMap<ty_param_bounds_and_ty>>;
1084 pub type node_type_table = RefCell<HashMap<uint,t>>;
1086 pub fn mk_ctxt(s: session::Session,
1087 dm: resolve::DefMap,
1088 named_region_map: @RefCell<resolve_lifetime::NamedRegionMap>,
1090 freevars: freevars::freevar_map,
1091 region_maps: middle::region::RegionMaps,
1092 lang_items: @middle::lang_items::LanguageItems)
1095 fn hasher() -> HashMap<intern_key, ~t_box_> {
1099 fn hasher() -> HashMap<intern_key, ~t_box_, ::util::nodemap::FnvHasher> {
1100 HashMap::with_hasher(::util::nodemap::FnvHasher)
1103 named_region_map: named_region_map,
1104 item_variance_map: RefCell::new(DefIdMap::new()),
1105 diag: s.diagnostic(),
1106 interner: RefCell::new(hasher()),
1107 next_id: Cell::new(primitives::LAST_PRIMITIVE_ID),
1111 region_maps: region_maps,
1112 node_types: RefCell::new(HashMap::new()),
1113 node_type_substs: RefCell::new(NodeMap::new()),
1114 trait_refs: RefCell::new(NodeMap::new()),
1115 trait_defs: RefCell::new(DefIdMap::new()),
1117 intrinsic_defs: RefCell::new(DefIdMap::new()),
1118 freevars: RefCell::new(freevars),
1119 tcache: RefCell::new(DefIdMap::new()),
1120 rcache: RefCell::new(HashMap::new()),
1121 short_names_cache: RefCell::new(HashMap::new()),
1122 needs_unwind_cleanup_cache: RefCell::new(HashMap::new()),
1123 tc_cache: RefCell::new(HashMap::new()),
1124 ast_ty_to_ty_cache: RefCell::new(NodeMap::new()),
1125 enum_var_cache: RefCell::new(DefIdMap::new()),
1126 methods: RefCell::new(DefIdMap::new()),
1127 trait_method_def_ids: RefCell::new(DefIdMap::new()),
1128 trait_methods_cache: RefCell::new(DefIdMap::new()),
1129 impl_trait_cache: RefCell::new(DefIdMap::new()),
1130 ty_param_defs: RefCell::new(NodeMap::new()),
1131 adjustments: RefCell::new(NodeMap::new()),
1132 normalized_cache: RefCell::new(HashMap::new()),
1133 lang_items: lang_items,
1134 provided_method_sources: RefCell::new(DefIdMap::new()),
1135 supertraits: RefCell::new(DefIdMap::new()),
1136 destructor_for_type: RefCell::new(DefIdMap::new()),
1137 destructors: RefCell::new(DefIdSet::new()),
1138 trait_impls: RefCell::new(DefIdMap::new()),
1139 inherent_impls: RefCell::new(DefIdMap::new()),
1140 impls: RefCell::new(DefIdMap::new()),
1141 used_unsafe: RefCell::new(NodeSet::new()),
1142 used_mut_nodes: RefCell::new(NodeSet::new()),
1143 impl_vtables: RefCell::new(DefIdMap::new()),
1144 populated_external_types: RefCell::new(DefIdSet::new()),
1145 populated_external_traits: RefCell::new(DefIdSet::new()),
1146 upvar_borrow_map: RefCell::new(HashMap::new()),
1147 extern_const_statics: RefCell::new(DefIdMap::new()),
1148 extern_const_variants: RefCell::new(DefIdMap::new()),
1152 // Type constructors
1154 // Interns a type/name combination, stores the resulting box in cx.interner,
1155 // and returns the box as cast to an unsafe ptr (see comments for t above).
1156 pub fn mk_t(cx: ctxt, st: sty) -> t {
1157 // Check for primitive types.
1159 ty_nil => return mk_nil(),
1160 ty_err => return mk_err(),
1161 ty_bool => return mk_bool(),
1162 ty_int(i) => return mk_mach_int(i),
1163 ty_uint(u) => return mk_mach_uint(u),
1164 ty_float(f) => return mk_mach_float(f),
1165 ty_char => return mk_char(),
1166 ty_bot => return mk_bot(),
1170 let key = intern_key { sty: &st };
1173 let mut interner = cx.interner.borrow_mut();
1174 match interner.get().find(&key) {
1175 Some(t) => unsafe { return cast::transmute(&t.sty); },
1181 fn rflags(r: Region) -> uint {
1182 (has_regions as uint) | {
1184 ty::ReInfer(_) => needs_infer as uint,
1189 fn sflags(substs: &substs) -> uint {
1191 for tt in substs.tps.iter() { f |= get(*tt).flags; }
1192 match substs.regions {
1194 NonerasedRegions(ref regions) => {
1195 for r in regions.iter() {
1203 &ty_str(vstore_slice(r)) => {
1206 &ty_vec(ref mt, vstore_slice(r)) => {
1208 flags |= get(mt.ty).flags;
1210 &ty_nil | &ty_bool | &ty_char | &ty_int(_) | &ty_float(_) | &ty_uint(_) |
1212 // You might think that we could just return ty_err for
1213 // any type containing ty_err as a component, and get
1214 // rid of the has_ty_err flag -- likewise for ty_bot (with
1215 // the exception of function types that return bot).
1216 // But doing so caused sporadic memory corruption, and
1217 // neither I (tjc) nor nmatsakis could figure out why,
1218 // so we're doing it this way.
1219 &ty_bot => flags |= has_ty_bot as uint,
1220 &ty_err => flags |= has_ty_err as uint,
1221 &ty_param(_) => flags |= has_params as uint,
1222 &ty_infer(_) => flags |= needs_infer as uint,
1223 &ty_self(_) => flags |= has_self as uint,
1224 &ty_enum(_, ref substs) | &ty_struct(_, ref substs) |
1225 &ty_trait(_, ref substs, _, _, _) => {
1226 flags |= sflags(substs);
1228 ty_trait(_, _, RegionTraitStore(r), _, _) => {
1234 &ty_box(tt) | &ty_uniq(tt) => {
1235 flags |= get(tt).flags
1237 &ty_vec(ref m, _) | &ty_ptr(ref m) |
1238 &ty_unboxed_vec(ref m) => {
1239 flags |= get(m.ty).flags;
1241 &ty_rptr(r, ref m) => {
1243 flags |= get(m.ty).flags;
1245 &ty_tup(ref ts) => for tt in ts.iter() { flags |= get(*tt).flags; },
1246 &ty_bare_fn(ref f) => {
1247 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1248 flags |= get(f.sig.output).flags;
1249 // T -> _|_ is *not* _|_ !
1250 flags &= !(has_ty_bot as uint);
1252 &ty_closure(ref f) => {
1253 flags |= rflags(f.region);
1254 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1255 flags |= get(f.sig.output).flags;
1256 // T -> _|_ is *not* _|_ !
1257 flags &= !(has_ty_bot as uint);
1263 id: cx.next_id.get(),
1267 let sty_ptr = &t.sty as *sty;
1269 let key = intern_key {
1273 let mut interner = cx.interner.borrow_mut();
1274 interner.get().insert(key, t);
1276 cx.next_id.set(cx.next_id.get() + 1);
1279 cast::transmute::<*sty, t>(sty_ptr)
1284 pub fn mk_prim_t(primitive: &'static t_box_) -> t {
1286 cast::transmute::<&'static t_box_, t>(primitive)
1291 pub fn mk_nil() -> t { mk_prim_t(&primitives::TY_NIL) }
1294 pub fn mk_err() -> t { mk_prim_t(&primitives::TY_ERR) }
1297 pub fn mk_bot() -> t { mk_prim_t(&primitives::TY_BOT) }
1300 pub fn mk_bool() -> t { mk_prim_t(&primitives::TY_BOOL) }
1303 pub fn mk_int() -> t { mk_prim_t(&primitives::TY_INT) }
1306 pub fn mk_i8() -> t { mk_prim_t(&primitives::TY_I8) }
1309 pub fn mk_i16() -> t { mk_prim_t(&primitives::TY_I16) }
1312 pub fn mk_i32() -> t { mk_prim_t(&primitives::TY_I32) }
1315 pub fn mk_i64() -> t { mk_prim_t(&primitives::TY_I64) }
1318 pub fn mk_f32() -> t { mk_prim_t(&primitives::TY_F32) }
1321 pub fn mk_f64() -> t { mk_prim_t(&primitives::TY_F64) }
1324 pub fn mk_uint() -> t { mk_prim_t(&primitives::TY_UINT) }
1327 pub fn mk_u8() -> t { mk_prim_t(&primitives::TY_U8) }
1330 pub fn mk_u16() -> t { mk_prim_t(&primitives::TY_U16) }
1333 pub fn mk_u32() -> t { mk_prim_t(&primitives::TY_U32) }
1336 pub fn mk_u64() -> t { mk_prim_t(&primitives::TY_U64) }
1338 pub fn mk_mach_int(tm: ast::IntTy) -> t {
1340 ast::TyI => mk_int(),
1341 ast::TyI8 => mk_i8(),
1342 ast::TyI16 => mk_i16(),
1343 ast::TyI32 => mk_i32(),
1344 ast::TyI64 => mk_i64(),
1348 pub fn mk_mach_uint(tm: ast::UintTy) -> t {
1350 ast::TyU => mk_uint(),
1351 ast::TyU8 => mk_u8(),
1352 ast::TyU16 => mk_u16(),
1353 ast::TyU32 => mk_u32(),
1354 ast::TyU64 => mk_u64(),
1358 pub fn mk_mach_float(tm: ast::FloatTy) -> t {
1360 ast::TyF32 => mk_f32(),
1361 ast::TyF64 => mk_f64(),
1366 pub fn mk_char() -> t { mk_prim_t(&primitives::TY_CHAR) }
1368 pub fn mk_str(cx: ctxt, t: vstore) -> t {
1372 pub fn mk_enum(cx: ctxt, did: ast::DefId, substs: substs) -> t {
1373 // take a copy of substs so that we own the vectors inside
1374 mk_t(cx, ty_enum(did, substs))
1377 pub fn mk_box(cx: ctxt, ty: t) -> t { mk_t(cx, ty_box(ty)) }
1379 pub fn mk_uniq(cx: ctxt, ty: t) -> t { mk_t(cx, ty_uniq(ty)) }
1381 pub fn mk_ptr(cx: ctxt, tm: mt) -> t { mk_t(cx, ty_ptr(tm)) }
1383 pub fn mk_rptr(cx: ctxt, r: Region, tm: mt) -> t { mk_t(cx, ty_rptr(r, tm)) }
1385 pub fn mk_mut_rptr(cx: ctxt, r: Region, ty: t) -> t {
1386 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
1388 pub fn mk_imm_rptr(cx: ctxt, r: Region, ty: t) -> t {
1389 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
1392 pub fn mk_mut_ptr(cx: ctxt, ty: t) -> t {
1393 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
1396 pub fn mk_imm_ptr(cx: ctxt, ty: t) -> t {
1397 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
1400 pub fn mk_nil_ptr(cx: ctxt) -> t {
1401 mk_ptr(cx, mt {ty: mk_nil(), mutbl: ast::MutImmutable})
1404 pub fn mk_vec(cx: ctxt, tm: mt, t: vstore) -> t {
1405 mk_t(cx, ty_vec(tm, t))
1408 pub fn mk_unboxed_vec(cx: ctxt, tm: mt) -> t {
1409 mk_t(cx, ty_unboxed_vec(tm))
1411 pub fn mk_mut_unboxed_vec(cx: ctxt, ty: t) -> t {
1412 mk_t(cx, ty_unboxed_vec(mt {ty: ty, mutbl: ast::MutImmutable}))
1415 pub fn mk_tup(cx: ctxt, ts: ~[t]) -> t { mk_t(cx, ty_tup(ts)) }
1417 pub fn mk_closure(cx: ctxt, fty: ClosureTy) -> t {
1418 mk_t(cx, ty_closure(fty))
1421 pub fn mk_bare_fn(cx: ctxt, fty: BareFnTy) -> t {
1422 mk_t(cx, ty_bare_fn(fty))
1425 pub fn mk_ctor_fn(cx: ctxt,
1426 binder_id: ast::NodeId,
1427 input_tys: &[ty::t],
1428 output: ty::t) -> t {
1429 let input_args = input_tys.map(|t| *t);
1432 purity: ast::ImpureFn,
1433 abis: AbiSet::Rust(),
1435 binder_id: binder_id,
1444 pub fn mk_trait(cx: ctxt,
1448 mutability: ast::Mutability,
1449 bounds: BuiltinBounds)
1451 // take a copy of substs so that we own the vectors inside
1452 mk_t(cx, ty_trait(did, substs, store, mutability, bounds))
1455 pub fn mk_struct(cx: ctxt, struct_id: ast::DefId, substs: substs) -> t {
1456 // take a copy of substs so that we own the vectors inside
1457 mk_t(cx, ty_struct(struct_id, substs))
1460 pub fn mk_var(cx: ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) }
1462 pub fn mk_int_var(cx: ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) }
1464 pub fn mk_float_var(cx: ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) }
1466 pub fn mk_infer(cx: ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) }
1468 pub fn mk_self(cx: ctxt, did: ast::DefId) -> t { mk_t(cx, ty_self(did)) }
1470 pub fn mk_param(cx: ctxt, n: uint, k: DefId) -> t {
1471 mk_t(cx, ty_param(param_ty { idx: n, def_id: k }))
1474 pub fn walk_ty(ty: t, f: |t|) {
1475 maybe_walk_ty(ty, |t| { f(t); true });
1478 pub fn maybe_walk_ty(ty: t, f: |t| -> bool) {
1483 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) |
1484 ty_str(_) | ty_self(_) |
1485 ty_infer(_) | ty_param(_) | ty_err => {}
1486 ty_box(ty) | ty_uniq(ty) => maybe_walk_ty(ty, f),
1487 ty_vec(ref tm, _) | ty_unboxed_vec(ref tm) | ty_ptr(ref tm) |
1488 ty_rptr(_, ref tm) => {
1489 maybe_walk_ty(tm.ty, f);
1491 ty_enum(_, ref substs) | ty_struct(_, ref substs) |
1492 ty_trait(_, ref substs, _, _, _) => {
1493 for subty in (*substs).tps.iter() { maybe_walk_ty(*subty, |x| f(x)); }
1495 ty_tup(ref ts) => { for tt in ts.iter() { maybe_walk_ty(*tt, |x| f(x)); } }
1496 ty_bare_fn(ref ft) => {
1497 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1498 maybe_walk_ty(ft.sig.output, f);
1500 ty_closure(ref ft) => {
1501 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1502 maybe_walk_ty(ft.sig.output, f);
1507 // Folds types from the bottom up.
1508 pub fn fold_ty(cx: ctxt, t0: t, fldop: |t| -> t) -> t {
1509 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
1513 pub fn walk_regions_and_ty(cx: ctxt, ty: t, fldr: |r: Region|, fldt: |t: t|)
1515 ty_fold::RegionFolder::general(cx,
1517 |t| { fldt(t); t }).fold_ty(ty)
1520 pub fn fold_regions(cx: ctxt, ty: t, fldr: |r: Region| -> Region) -> t {
1521 ty_fold::RegionFolder::regions(cx, fldr).fold_ty(ty)
1524 // Substitute *only* type parameters. Used in trans where regions are erased.
1525 pub fn subst_tps(tcx: ctxt, tps: &[t], self_ty_opt: Option<t>, typ: t) -> t {
1526 let mut subst = TpsSubst { tcx: tcx, self_ty_opt: self_ty_opt, tps: tps };
1527 return subst.fold_ty(typ);
1529 struct TpsSubst<'a> {
1531 self_ty_opt: Option<t>,
1535 impl<'a> TypeFolder for TpsSubst<'a> {
1536 fn tcx(&self) -> ty::ctxt { self.tcx }
1538 fn fold_ty(&mut self, t: ty::t) -> ty::t {
1539 if self.tps.len() == 0u && self.self_ty_opt.is_none() {
1543 let tb = ty::get(t);
1544 if self.self_ty_opt.is_none() && !tbox_has_flag(tb, has_params) {
1548 match ty::get(t).sty {
1554 match self.self_ty_opt {
1555 None => self.tcx.sess.bug("ty_self unexpected here"),
1556 Some(self_ty) => self_ty
1561 ty_fold::super_fold_ty(self, t)
1568 pub fn substs_is_noop(substs: &substs) -> bool {
1569 let regions_is_noop = match substs.regions {
1570 ErasedRegions => false, // may be used to canonicalize
1571 NonerasedRegions(ref regions) => regions.is_empty()
1574 substs.tps.len() == 0u &&
1576 substs.self_ty.is_none()
1579 pub fn substs_to_str(cx: ctxt, substs: &substs) -> ~str {
1583 pub fn subst(cx: ctxt,
1587 typ.subst(cx, substs)
1592 pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil }
1594 pub fn type_is_bot(ty: t) -> bool {
1595 (get(ty).flags & (has_ty_bot as uint)) != 0
1598 pub fn type_is_error(ty: t) -> bool {
1599 (get(ty).flags & (has_ty_err as uint)) != 0
1602 pub fn type_needs_subst(ty: t) -> bool {
1603 tbox_has_flag(get(ty), needs_subst)
1606 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
1607 tref.substs.self_ty.iter().any(|&t| type_is_error(t)) ||
1608 tref.substs.tps.iter().any(|&t| type_is_error(t))
1611 pub fn type_is_ty_var(ty: t) -> bool {
1613 ty_infer(TyVar(_)) => true,
1618 pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool }
1620 pub fn type_is_self(ty: t) -> bool {
1622 ty_self(..) => true,
1627 pub fn type_is_structural(ty: t) -> bool {
1629 ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) | ty_trait(..) |
1630 ty_vec(_, vstore_fixed(_)) | ty_str(vstore_fixed(_)) |
1631 ty_vec(_, vstore_slice(_)) | ty_str(vstore_slice(_))
1637 pub fn type_is_sequence(ty: t) -> bool {
1639 ty_str(_) | ty_vec(_, _) => true,
1644 pub fn type_is_simd(cx: ctxt, ty: t) -> bool {
1646 ty_struct(did, _) => lookup_simd(cx, did),
1651 pub fn type_is_str(ty: t) -> bool {
1658 pub fn sequence_element_type(cx: ctxt, ty: t) -> t {
1660 ty_str(_) => return mk_mach_uint(ast::TyU8),
1661 ty_vec(mt, _) | ty_unboxed_vec(mt) => return mt.ty,
1662 _ => cx.sess.bug("sequence_element_type called on non-sequence value"),
1666 pub fn simd_type(cx: ctxt, ty: t) -> t {
1668 ty_struct(did, ref substs) => {
1669 let fields = lookup_struct_fields(cx, did);
1670 lookup_field_type(cx, did, fields[0].id, substs)
1672 _ => fail!("simd_type called on invalid type")
1676 pub fn simd_size(cx: ctxt, ty: t) -> uint {
1678 ty_struct(did, _) => {
1679 let fields = lookup_struct_fields(cx, did);
1682 _ => fail!("simd_size called on invalid type")
1686 pub fn get_element_type(ty: t, i: uint) -> t {
1688 ty_tup(ref ts) => return ts[i],
1689 _ => fail!("get_element_type called on invalid type")
1693 pub fn type_is_box(ty: t) -> bool {
1695 ty_box(_) => return true,
1700 pub fn type_is_boxed(ty: t) -> bool {
1707 pub fn type_is_region_ptr(ty: t) -> bool {
1709 ty_rptr(_, _) => true,
1714 pub fn type_is_slice(ty: t) -> bool {
1716 ty_vec(_, vstore_slice(_)) | ty_str(vstore_slice(_)) => true,
1721 pub fn type_is_unique_box(ty: t) -> bool {
1723 ty_uniq(_) => return true,
1728 pub fn type_is_unsafe_ptr(ty: t) -> bool {
1730 ty_ptr(_) => return true,
1735 pub fn type_is_vec(ty: t) -> bool {
1736 return match get(ty).sty {
1737 ty_vec(_, _) | ty_unboxed_vec(_) => true,
1743 pub fn type_is_unique(ty: t) -> bool {
1745 ty_uniq(_) | ty_vec(_, vstore_uniq) | ty_str(vstore_uniq) => true,
1751 A scalar type is one that denotes an atomic datum, with no sub-components.
1752 (A ty_ptr is scalar because it represents a non-managed pointer, so its
1753 contents are abstract to rustc.)
1755 pub fn type_is_scalar(ty: t) -> bool {
1757 ty_nil | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
1758 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
1759 ty_bare_fn(..) | ty_ptr(_) => true,
1764 pub fn type_needs_drop(cx: ctxt, ty: t) -> bool {
1765 type_contents(cx, ty).needs_drop(cx)
1768 // Some things don't need cleanups during unwinding because the
1769 // task can free them all at once later. Currently only things
1770 // that only contain scalars and shared boxes can avoid unwind
1772 pub fn type_needs_unwind_cleanup(cx: ctxt, ty: t) -> bool {
1774 let needs_unwind_cleanup_cache = cx.needs_unwind_cleanup_cache
1776 match needs_unwind_cleanup_cache.get().find(&ty) {
1777 Some(&result) => return result,
1782 let mut tycache = HashSet::new();
1783 let needs_unwind_cleanup =
1784 type_needs_unwind_cleanup_(cx, ty, &mut tycache, false);
1785 let mut needs_unwind_cleanup_cache = cx.needs_unwind_cleanup_cache
1787 needs_unwind_cleanup_cache.get().insert(ty, needs_unwind_cleanup);
1788 return needs_unwind_cleanup;
1791 fn type_needs_unwind_cleanup_(cx: ctxt, ty: t,
1792 tycache: &mut HashSet<t>,
1793 encountered_box: bool) -> bool {
1795 // Prevent infinite recursion
1796 if !tycache.insert(ty) {
1800 let mut encountered_box = encountered_box;
1801 let mut needs_unwind_cleanup = false;
1802 maybe_walk_ty(ty, |ty| {
1803 let old_encountered_box = encountered_box;
1804 let result = match get(ty).sty {
1806 encountered_box = true;
1809 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
1810 ty_tup(_) | ty_ptr(_) => {
1813 ty_enum(did, ref substs) => {
1814 for v in (*enum_variants(cx, did)).iter() {
1815 for aty in v.args.iter() {
1816 let t = subst(cx, substs, *aty);
1817 needs_unwind_cleanup |=
1818 type_needs_unwind_cleanup_(cx, t, tycache,
1822 !needs_unwind_cleanup
1825 ty_str(vstore_uniq) |
1826 ty_vec(_, vstore_uniq) => {
1827 // Once we're inside a box, the annihilator will find
1828 // it and destroy it.
1829 if !encountered_box {
1830 needs_unwind_cleanup = true;
1837 needs_unwind_cleanup = true;
1842 encountered_box = old_encountered_box;
1846 return needs_unwind_cleanup;
1850 * Type contents is how the type checker reasons about kinds.
1851 * They track what kinds of things are found within a type. You can
1852 * think of them as kind of an "anti-kind". They track the kinds of values
1853 * and thinks that are contained in types. Having a larger contents for
1854 * a type tends to rule that type *out* from various kinds. For example,
1855 * a type that contains a reference is not sendable.
1857 * The reason we compute type contents and not kinds is that it is
1858 * easier for me (nmatsakis) to think about what is contained within
1859 * a type than to think about what is *not* contained within a type.
1861 pub struct TypeContents {
1865 macro_rules! def_type_content_sets(
1866 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
1868 use middle::ty::TypeContents;
1869 $(pub static $name: TypeContents = TypeContents { bits: $bits };)+
1874 def_type_content_sets!(
1876 None = 0b0000__00000000__0000,
1878 // Things that are interior to the value (first nibble):
1879 InteriorUnsized = 0b0000__00000000__0001,
1880 // InteriorAll = 0b0000__00000000__1111,
1882 // Things that are owned by the value (second and third nibbles):
1883 OwnsOwned = 0b0000__00000001__0000,
1884 OwnsDtor = 0b0000__00000010__0000,
1885 OwnsManaged /* see [1] below */ = 0b0000__00000100__0000,
1886 OwnsAffine = 0b0000__00001000__0000,
1887 OwnsAll = 0b0000__11111111__0000,
1889 // Things that are reachable by the value in any way (fourth nibble):
1890 ReachesNonsendAnnot = 0b0001__00000000__0000,
1891 ReachesBorrowed = 0b0010__00000000__0000,
1892 // ReachesManaged /* see [1] below */ = 0b0100__00000000__0000,
1893 ReachesMutable = 0b1000__00000000__0000,
1894 ReachesAll = 0b1111__00000000__0000,
1896 // Things that cause values to *move* rather than *copy*
1897 Moves = 0b0000__00001011__0000,
1899 // Things that mean drop glue is necessary
1900 NeedsDrop = 0b0000__00000111__0000,
1902 // Things that prevent values from being sent
1904 // Note: For checking whether something is sendable, it'd
1905 // be sufficient to have ReachesManaged. However, we include
1906 // both ReachesManaged and OwnsManaged so that when
1907 // a parameter has a bound T:Send, we are able to deduce
1908 // that it neither reaches nor owns a managed pointer.
1909 Nonsendable = 0b0111__00000100__0000,
1911 // Things that prevent values from being considered freezable
1912 Nonfreezable = 0b1000__00000000__0000,
1914 // Things that prevent values from being considered 'static
1915 Nonstatic = 0b0010__00000000__0000,
1917 // Things that prevent values from being considered sized
1918 Nonsized = 0b0000__00000000__0001,
1920 // Things that make values considered not POD (would be same
1921 // as `Moves`, but for the fact that managed data `@` is
1922 // not considered POD)
1923 Nonpod = 0b0000__00001111__0000,
1925 // Bits to set when a managed value is encountered
1927 // [1] Do not set the bits TC::OwnsManaged or
1928 // TC::ReachesManaged directly, instead reference
1929 // TC::Managed to set them both at once.
1930 Managed = 0b0100__00000100__0000,
1933 All = 0b1111__11111111__1111
1938 pub fn meets_bounds(&self, cx: ctxt, bbs: BuiltinBounds) -> bool {
1939 bbs.iter().all(|bb| self.meets_bound(cx, bb))
1942 pub fn meets_bound(&self, cx: ctxt, bb: BuiltinBound) -> bool {
1944 BoundStatic => self.is_static(cx),
1945 BoundFreeze => self.is_freezable(cx),
1946 BoundSend => self.is_sendable(cx),
1947 BoundSized => self.is_sized(cx),
1948 BoundPod => self.is_pod(cx),
1952 pub fn when(&self, cond: bool) -> TypeContents {
1953 if cond {*self} else {TC::None}
1956 pub fn intersects(&self, tc: TypeContents) -> bool {
1957 (self.bits & tc.bits) != 0
1960 pub fn is_static(&self, _: ctxt) -> bool {
1961 !self.intersects(TC::Nonstatic)
1964 pub fn is_sendable(&self, _: ctxt) -> bool {
1965 !self.intersects(TC::Nonsendable)
1968 pub fn owns_managed(&self) -> bool {
1969 self.intersects(TC::OwnsManaged)
1972 pub fn owns_owned(&self) -> bool {
1973 self.intersects(TC::OwnsOwned)
1976 pub fn is_freezable(&self, _: ctxt) -> bool {
1977 !self.intersects(TC::Nonfreezable)
1980 pub fn is_sized(&self, _: ctxt) -> bool {
1981 !self.intersects(TC::Nonsized)
1984 pub fn is_pod(&self, _: ctxt) -> bool {
1985 !self.intersects(TC::Nonpod)
1988 pub fn moves_by_default(&self, _: ctxt) -> bool {
1989 self.intersects(TC::Moves)
1992 pub fn needs_drop(&self, _: ctxt) -> bool {
1993 self.intersects(TC::NeedsDrop)
1996 pub fn owned_pointer(&self) -> TypeContents {
1998 * Includes only those bits that still apply
1999 * when indirected through a `~` pointer
2002 *self & (TC::OwnsAll | TC::ReachesAll))
2005 pub fn reference(&self, bits: TypeContents) -> TypeContents {
2007 * Includes only those bits that still apply
2008 * when indirected through a reference (`&`)
2011 *self & TC::ReachesAll)
2014 pub fn managed_pointer(&self) -> TypeContents {
2016 * Includes only those bits that still apply
2017 * when indirected through a managed pointer (`@`)
2020 *self & TC::ReachesAll)
2023 pub fn unsafe_pointer(&self) -> TypeContents {
2025 * Includes only those bits that still apply
2026 * when indirected through an unsafe pointer (`*`)
2028 *self & TC::ReachesAll
2031 pub fn union<T>(v: &[T], f: |&T| -> TypeContents) -> TypeContents {
2032 v.iter().fold(TC::None, |tc, t| tc | f(t))
2035 pub fn inverse(&self) -> TypeContents {
2036 TypeContents { bits: !self.bits }
2039 pub fn has_dtor(&self) -> bool {
2040 self.intersects(TC::OwnsDtor)
2044 impl ops::BitOr<TypeContents,TypeContents> for TypeContents {
2045 fn bitor(&self, other: &TypeContents) -> TypeContents {
2046 TypeContents {bits: self.bits | other.bits}
2050 impl ops::BitAnd<TypeContents,TypeContents> for TypeContents {
2051 fn bitand(&self, other: &TypeContents) -> TypeContents {
2052 TypeContents {bits: self.bits & other.bits}
2056 impl ops::Sub<TypeContents,TypeContents> for TypeContents {
2057 fn sub(&self, other: &TypeContents) -> TypeContents {
2058 TypeContents {bits: self.bits & !other.bits}
2062 impl fmt::Show for TypeContents {
2063 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2064 write!(f.buf, "TypeContents({:t})", self.bits)
2068 pub fn type_has_dtor(cx: ctxt, t: ty::t) -> bool {
2069 type_contents(cx, t).has_dtor()
2072 pub fn type_is_static(cx: ctxt, t: ty::t) -> bool {
2073 type_contents(cx, t).is_static(cx)
2076 pub fn type_is_sendable(cx: ctxt, t: ty::t) -> bool {
2077 type_contents(cx, t).is_sendable(cx)
2080 pub fn type_is_freezable(cx: ctxt, t: ty::t) -> bool {
2081 type_contents(cx, t).is_freezable(cx)
2084 pub fn type_contents(cx: ctxt, ty: t) -> TypeContents {
2085 let ty_id = type_id(ty);
2088 let tc_cache = cx.tc_cache.borrow();
2089 match tc_cache.get().find(&ty_id) {
2090 Some(tc) => { return *tc; }
2095 let mut cache = HashMap::new();
2096 let result = tc_ty(cx, ty, &mut cache);
2098 let mut tc_cache = cx.tc_cache.borrow_mut();
2099 tc_cache.get().insert(ty_id, result);
2104 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2106 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
2107 // private cache for this walk. This is needed in the case of cyclic
2110 // struct List { next: ~Option<List>, ... }
2112 // When computing the type contents of such a type, we wind up deeply
2113 // recursing as we go. So when we encounter the recursive reference
2114 // to List, we temporarily use TC::None as its contents. Later we'll
2115 // patch up the cache with the correct value, once we've computed it
2116 // (this is basically a co-inductive process, if that helps). So in
2117 // the end we'll compute TC::OwnsOwned, in this case.
2119 // The problem is, as we are doing the computation, we will also
2120 // compute an *intermediate* contents for, e.g., Option<List> of
2121 // TC::None. This is ok during the computation of List itself, but if
2122 // we stored this intermediate value into cx.tc_cache, then later
2123 // requests for the contents of Option<List> would also yield TC::None
2124 // which is incorrect. This value was computed based on the crutch
2125 // value for the type contents of list. The correct value is
2126 // TC::OwnsOwned. This manifested as issue #4821.
2127 let ty_id = type_id(ty);
2128 match cache.find(&ty_id) {
2129 Some(tc) => { return *tc; }
2133 let tc_cache = cx.tc_cache.borrow();
2134 match tc_cache.get().find(&ty_id) { // Must check both caches!
2135 Some(tc) => { return *tc; }
2139 cache.insert(ty_id, TC::None);
2141 let result = match get(ty).sty {
2142 // Scalar and unique types are sendable, freezable, and durable
2143 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2144 ty_bare_fn(_) | ty::ty_char => {
2148 ty_str(vstore_uniq) => {
2152 ty_closure(ref c) => {
2153 closure_contents(cx, c)
2157 tc_ty(cx, typ, cache).managed_pointer()
2161 tc_ty(cx, typ, cache).owned_pointer()
2164 ty_trait(_, _, store, mutbl, bounds) => {
2165 object_contents(cx, store, mutbl, bounds)
2169 tc_ty(cx, mt.ty, cache).unsafe_pointer()
2172 ty_rptr(r, ref mt) => {
2173 tc_ty(cx, mt.ty, cache).reference(
2174 borrowed_contents(r, mt.mutbl))
2177 ty_vec(mt, vstore_uniq) => {
2178 tc_mt(cx, mt, cache).owned_pointer()
2181 ty_vec(ref mt, vstore_slice(r)) => {
2182 tc_ty(cx, mt.ty, cache).reference(
2183 borrowed_contents(r, mt.mutbl))
2186 ty_vec(mt, vstore_fixed(_)) => {
2187 tc_mt(cx, mt, cache)
2190 ty_str(vstore_slice(r)) => {
2191 borrowed_contents(r, ast::MutImmutable)
2194 ty_str(vstore_fixed(_)) => {
2198 ty_struct(did, ref substs) => {
2199 let flds = struct_fields(cx, did, substs);
2201 TypeContents::union(flds, |f| tc_mt(cx, f.mt, cache));
2202 if ty::has_dtor(cx, did) {
2203 res = res | TC::OwnsDtor;
2205 apply_lang_items(cx, did, res)
2208 ty_tup(ref tys) => {
2209 TypeContents::union(*tys, |ty| tc_ty(cx, *ty, cache))
2212 ty_enum(did, ref substs) => {
2213 let variants = substd_enum_variants(cx, did, substs);
2215 TypeContents::union(variants, |variant| {
2216 TypeContents::union(variant.args, |arg_ty| {
2217 tc_ty(cx, *arg_ty, cache)
2220 apply_lang_items(cx, did, res)
2224 // We only ever ask for the kind of types that are defined in
2225 // the current crate; therefore, the only type parameters that
2226 // could be in scope are those defined in the current crate.
2227 // If this assertion failures, it is likely because of a
2228 // failure in the cross-crate inlining code to translate a
2230 assert_eq!(p.def_id.krate, ast::LOCAL_CRATE);
2232 let ty_param_defs = cx.ty_param_defs.borrow();
2233 let tp_def = ty_param_defs.get().get(&p.def_id.node);
2234 kind_bounds_to_contents(cx,
2235 tp_def.bounds.builtin_bounds,
2236 tp_def.bounds.trait_bounds)
2239 ty_self(def_id) => {
2240 // FIXME(#4678)---self should just be a ty param
2242 // Self may be bounded if the associated trait has builtin kinds
2243 // for supertraits. If so we can use those bounds.
2244 let trait_def = lookup_trait_def(cx, def_id);
2245 let traits = [trait_def.trait_ref];
2246 kind_bounds_to_contents(cx, trait_def.bounds, traits)
2250 // This occurs during coherence, but shouldn't occur at other
2254 ty_unboxed_vec(mt) => TC::InteriorUnsized | tc_mt(cx, mt, cache),
2257 cx.sess.bug("asked to compute contents of error type");
2261 cache.insert(ty_id, result);
2267 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2269 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
2270 mc | tc_ty(cx, mt.ty, cache)
2273 fn apply_lang_items(cx: ctxt,
2277 if Some(did) == cx.lang_items.no_freeze_bound() {
2278 tc | TC::ReachesMutable
2279 } else if Some(did) == cx.lang_items.no_send_bound() {
2280 tc | TC::ReachesNonsendAnnot
2281 } else if Some(did) == cx.lang_items.managed_bound() {
2283 } else if Some(did) == cx.lang_items.no_pod_bound() {
2290 fn borrowed_contents(region: ty::Region,
2291 mutbl: ast::Mutability)
2294 * Type contents due to containing a reference
2295 * with the region `region` and borrow kind `bk`
2298 let b = match mutbl {
2299 ast::MutMutable => TC::ReachesMutable | TC::OwnsAffine,
2300 ast::MutImmutable => TC::None,
2302 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
2305 fn closure_contents(cx: ctxt, cty: &ClosureTy) -> TypeContents {
2306 // Closure contents are just like trait contents, but with potentially
2308 let st = match cty.sigil {
2309 ast::BorrowedSigil =>
2310 object_contents(cx, RegionTraitStore(cty.region), MutMutable, cty.bounds),
2312 object_contents(cx, UniqTraitStore, MutImmutable, cty.bounds),
2313 ast::ManagedSigil => unreachable!()
2316 // FIXME(#3569): This borrowed_contents call should be taken care of in
2317 // object_contents, after ~Traits and @Traits can have region bounds too.
2318 // This one here is redundant for &fns but important for ~fns and @fns.
2319 let rt = borrowed_contents(cty.region, ast::MutImmutable);
2321 // This also prohibits "@once fn" from being copied, which allows it to
2322 // be called. Neither way really makes much sense.
2323 let ot = match cty.onceness {
2324 ast::Once => TC::OwnsAffine,
2325 ast::Many => TC::None,
2331 fn object_contents(cx: ctxt,
2333 mutbl: ast::Mutability,
2334 bounds: BuiltinBounds)
2336 // These are the type contents of the (opaque) interior
2337 let contents = TC::ReachesMutable.when(mutbl == ast::MutMutable) |
2338 kind_bounds_to_contents(cx, bounds, []);
2342 contents.owned_pointer()
2344 RegionTraitStore(r) => {
2345 contents.reference(borrowed_contents(r, mutbl))
2350 fn kind_bounds_to_contents(cx: ctxt,
2351 bounds: BuiltinBounds,
2352 traits: &[@TraitRef])
2354 let _i = indenter();
2355 let mut tc = TC::All;
2356 each_inherited_builtin_bound(cx, bounds, traits, |bound| {
2357 tc = tc - match bound {
2358 BoundStatic => TC::Nonstatic,
2359 BoundSend => TC::Nonsendable,
2360 BoundFreeze => TC::Nonfreezable,
2361 BoundSized => TC::Nonsized,
2362 BoundPod => TC::Nonpod,
2367 // Iterates over all builtin bounds on the type parameter def, including
2368 // those inherited from traits with builtin-kind-supertraits.
2369 fn each_inherited_builtin_bound(cx: ctxt,
2370 bounds: BuiltinBounds,
2371 traits: &[@TraitRef],
2372 f: |BuiltinBound|) {
2373 for bound in bounds.iter() {
2377 each_bound_trait_and_supertraits(cx, traits, |trait_ref| {
2378 let trait_def = lookup_trait_def(cx, trait_ref.def_id);
2379 for bound in trait_def.bounds.iter() {
2388 pub fn type_moves_by_default(cx: ctxt, ty: t) -> bool {
2389 type_contents(cx, ty).moves_by_default(cx)
2392 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
2393 pub fn is_instantiable(cx: ctxt, r_ty: t) -> bool {
2394 fn type_requires(cx: ctxt, seen: &mut ~[DefId],
2395 r_ty: t, ty: t) -> bool {
2396 debug!("type_requires({}, {})?",
2397 ::util::ppaux::ty_to_str(cx, r_ty),
2398 ::util::ppaux::ty_to_str(cx, ty));
2401 get(r_ty).sty == get(ty).sty ||
2402 subtypes_require(cx, seen, r_ty, ty)
2405 debug!("type_requires({}, {})? {}",
2406 ::util::ppaux::ty_to_str(cx, r_ty),
2407 ::util::ppaux::ty_to_str(cx, ty),
2412 fn subtypes_require(cx: ctxt, seen: &mut ~[DefId],
2413 r_ty: t, ty: t) -> bool {
2414 debug!("subtypes_require({}, {})?",
2415 ::util::ppaux::ty_to_str(cx, r_ty),
2416 ::util::ppaux::ty_to_str(cx, ty));
2418 let r = match get(ty).sty {
2419 // fixed length vectors need special treatment compared to
2420 // normal vectors, since they don't necessarily have the
2421 // possibilty to have length zero.
2422 ty_vec(_, vstore_fixed(0)) => false, // don't need no contents
2423 ty_vec(mt, vstore_fixed(_)) => type_requires(cx, seen, r_ty, mt.ty),
2440 ty_unboxed_vec(_) => {
2443 ty_box(typ) | ty_uniq(typ) => {
2444 type_requires(cx, seen, r_ty, typ)
2446 ty_rptr(_, ref mt) => {
2447 type_requires(cx, seen, r_ty, mt.ty)
2451 false // unsafe ptrs can always be NULL
2454 ty_trait(_, _, _, _, _) => {
2458 ty_struct(ref did, _) if seen.contains(did) => {
2462 ty_struct(did, ref substs) => {
2464 let fields = struct_fields(cx, did, substs);
2465 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
2466 seen.pop().unwrap();
2471 ts.iter().any(|t| type_requires(cx, seen, r_ty, *t))
2474 ty_enum(ref did, _) if seen.contains(did) => {
2478 ty_enum(did, ref substs) => {
2480 let vs = enum_variants(cx, did);
2481 let r = !vs.is_empty() && vs.iter().all(|variant| {
2482 variant.args.iter().any(|aty| {
2483 let sty = subst(cx, substs, *aty);
2484 type_requires(cx, seen, r_ty, sty)
2487 seen.pop().unwrap();
2492 debug!("subtypes_require({}, {})? {}",
2493 ::util::ppaux::ty_to_str(cx, r_ty),
2494 ::util::ppaux::ty_to_str(cx, ty),
2501 !subtypes_require(cx, &mut seen, r_ty, r_ty)
2504 /// Describes whether a type is representable. For types that are not
2505 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
2506 /// distinguish between types that are recursive with themselves and types that
2507 /// contain a different recursive type. These cases can therefore be treated
2508 /// differently when reporting errors.
2510 pub enum Representability {
2516 /// Check whether a type is representable. This means it cannot contain unboxed
2517 /// structural recursion. This check is needed for structs and enums.
2518 pub fn is_type_representable(cx: ctxt, ty: t) -> Representability {
2520 // Iterate until something non-representable is found
2521 fn find_nonrepresentable<It: Iterator<t>>(cx: ctxt, seen: &mut ~[DefId],
2522 mut iter: It) -> Representability {
2524 let r = type_structurally_recursive(cx, seen, ty);
2525 if r != Representable {
2532 // Does the type `ty` directly (without indirection through a pointer)
2533 // contain any types on stack `seen`?
2534 fn type_structurally_recursive(cx: ctxt, seen: &mut ~[DefId],
2535 ty: t) -> Representability {
2536 debug!("type_structurally_recursive: {}",
2537 ::util::ppaux::ty_to_str(cx, ty));
2539 // Compare current type to previously seen types
2542 ty_enum(did, _) => {
2543 for (i, &seen_did) in seen.iter().enumerate() {
2544 if did == seen_did {
2545 return if i == 0 { SelfRecursive }
2546 else { ContainsRecursive }
2553 // Check inner types
2557 find_nonrepresentable(cx, seen, ts.iter().map(|t| *t))
2559 // Fixed-length vectors.
2560 // FIXME(#11924) Behavior undecided for zero-length vectors.
2561 ty_vec(mt, vstore_fixed(_)) => {
2562 type_structurally_recursive(cx, seen, mt.ty)
2565 // Push struct and enum def-ids onto `seen` before recursing.
2566 ty_struct(did, ref substs) => {
2568 let fields = struct_fields(cx, did, substs);
2569 let r = find_nonrepresentable(cx, seen,
2570 fields.iter().map(|f| f.mt.ty));
2574 ty_enum(did, ref substs) => {
2576 let vs = enum_variants(cx, did);
2578 let mut r = Representable;
2579 for variant in vs.iter() {
2580 let iter = variant.args.iter().map(|aty| subst(cx, substs, *aty));
2581 r = find_nonrepresentable(cx, seen, iter);
2583 if r != Representable { break }
2594 debug!("is_type_representable: {}",
2595 ::util::ppaux::ty_to_str(cx, ty));
2597 // To avoid a stack overflow when checking an enum variant or struct that
2598 // contains a different, structurally recursive type, maintain a stack
2599 // of seen types and check recursion for each of them (issues #3008, #3779).
2600 let mut seen: ~[DefId] = ~[];
2601 type_structurally_recursive(cx, &mut seen, ty)
2604 pub fn type_is_trait(ty: t) -> bool {
2606 ty_trait(..) => true,
2611 pub fn type_is_integral(ty: t) -> bool {
2613 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
2618 pub fn type_is_char(ty: t) -> bool {
2625 pub fn type_is_bare_fn(ty: t) -> bool {
2627 ty_bare_fn(..) => true,
2632 pub fn type_is_fp(ty: t) -> bool {
2634 ty_infer(FloatVar(_)) | ty_float(_) => true,
2639 pub fn type_is_numeric(ty: t) -> bool {
2640 return type_is_integral(ty) || type_is_fp(ty);
2643 pub fn type_is_signed(ty: t) -> bool {
2650 pub fn type_is_machine(ty: t) -> bool {
2652 ty_int(ast::TyI) | ty_uint(ast::TyU) => false,
2653 ty_int(..) | ty_uint(..) | ty_float(..) => true,
2658 pub fn type_is_enum(ty: t) -> bool {
2660 ty_enum(_, _) => return true,
2665 // Is the type's representation size known at compile time?
2666 pub fn type_is_sized(cx: ctxt, ty: ty::t) -> bool {
2668 // FIXME(#6308) add trait, vec, str, etc here.
2670 let ty_param_defs = cx.ty_param_defs.borrow();
2671 let param_def = ty_param_defs.get().get(&p.def_id.node);
2672 if param_def.bounds.builtin_bounds.contains_elem(BoundSized) {
2681 // Whether a type is enum like, that is an enum type with only nullary
2683 pub fn type_is_c_like_enum(cx: ctxt, ty: t) -> bool {
2685 ty_enum(did, _) => {
2686 let variants = enum_variants(cx, did);
2687 if variants.len() == 0 {
2690 variants.iter().all(|v| v.args.len() == 0)
2697 pub fn type_param(ty: t) -> Option<uint> {
2699 ty_param(p) => return Some(p.idx),
2700 _ => {/* fall through */ }
2705 // Returns the type and mutability of *t.
2707 // The parameter `explicit` indicates if this is an *explicit* dereference.
2708 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
2709 pub fn deref(t: t, explicit: bool) -> Option<mt> {
2710 deref_sty(&get(t).sty, explicit)
2713 pub fn deref_sty(sty: &sty, explicit: bool) -> Option<mt> {
2715 ty_box(typ) | ty_uniq(typ) => {
2718 mutbl: ast::MutImmutable,
2726 ty_ptr(mt) if explicit => {
2734 pub fn type_autoderef(t: t) -> t {
2737 match deref(t, false) {
2739 Some(mt) => t = mt.ty
2744 // Returns the type and mutability of t[i]
2745 pub fn index(t: t) -> Option<mt> {
2746 index_sty(&get(t).sty)
2749 pub fn index_sty(sty: &sty) -> Option<mt> {
2751 ty_vec(mt, _) => Some(mt),
2752 ty_str(_) => Some(mt {ty: mk_u8(), mutbl: ast::MutImmutable}),
2757 pub fn node_id_to_trait_ref(cx: ctxt, id: ast::NodeId) -> @ty::TraitRef {
2758 let trait_refs = cx.trait_refs.borrow();
2759 match trait_refs.get().find(&id) {
2761 None => cx.sess.bug(
2762 format!("node_id_to_trait_ref: no trait ref for node `{}`",
2763 cx.map.node_to_str(id)))
2767 pub fn try_node_id_to_type(cx: ctxt, id: ast::NodeId) -> Option<t> {
2768 let node_types = cx.node_types.borrow();
2769 node_types.get().find_copy(&(id as uint))
2772 pub fn node_id_to_type(cx: ctxt, id: ast::NodeId) -> t {
2773 match try_node_id_to_type(cx, id) {
2775 None => cx.sess.bug(
2776 format!("node_id_to_type: no type for node `{}`",
2777 cx.map.node_to_str(id)))
2781 pub fn node_id_to_type_opt(cx: ctxt, id: ast::NodeId) -> Option<t> {
2782 let node_types = cx.node_types.borrow();
2783 debug!("id: {:?}, node_types: {:?}", id, node_types);
2784 match node_types.get().find(&(id as uint)) {
2785 Some(&t) => Some(t),
2790 // FIXME(pcwalton): Makes a copy, bleh. Probably better to not do that.
2791 pub fn node_id_to_type_params(cx: ctxt, id: ast::NodeId) -> ~[t] {
2792 let node_type_substs = cx.node_type_substs.borrow();
2793 match node_type_substs.get().find(&id) {
2795 Some(ts) => return (*ts).clone(),
2799 fn node_id_has_type_params(cx: ctxt, id: ast::NodeId) -> bool {
2800 let node_type_substs = cx.node_type_substs.borrow();
2801 node_type_substs.get().contains_key(&id)
2804 pub fn fn_is_variadic(fty: t) -> bool {
2805 match get(fty).sty {
2806 ty_bare_fn(ref f) => f.sig.variadic,
2807 ty_closure(ref f) => f.sig.variadic,
2809 fail!("fn_is_variadic() called on non-fn type: {:?}", s)
2814 pub fn ty_fn_sig(fty: t) -> FnSig {
2815 match get(fty).sty {
2816 ty_bare_fn(ref f) => f.sig.clone(),
2817 ty_closure(ref f) => f.sig.clone(),
2819 fail!("ty_fn_sig() called on non-fn type: {:?}", s)
2824 // Type accessors for substructures of types
2825 pub fn ty_fn_args(fty: t) -> ~[t] {
2826 match get(fty).sty {
2827 ty_bare_fn(ref f) => f.sig.inputs.clone(),
2828 ty_closure(ref f) => f.sig.inputs.clone(),
2830 fail!("ty_fn_args() called on non-fn type: {:?}", s)
2835 pub fn ty_closure_sigil(fty: t) -> Sigil {
2836 match get(fty).sty {
2837 ty_closure(ref f) => f.sigil,
2839 fail!("ty_closure_sigil() called on non-closure type: {:?}", s)
2844 pub fn ty_fn_purity(fty: t) -> ast::Purity {
2845 match get(fty).sty {
2846 ty_bare_fn(ref f) => f.purity,
2847 ty_closure(ref f) => f.purity,
2849 fail!("ty_fn_purity() called on non-fn type: {:?}", s)
2854 pub fn ty_fn_ret(fty: t) -> t {
2855 match get(fty).sty {
2856 ty_bare_fn(ref f) => f.sig.output,
2857 ty_closure(ref f) => f.sig.output,
2859 fail!("ty_fn_ret() called on non-fn type: {:?}", s)
2864 pub fn is_fn_ty(fty: t) -> bool {
2865 match get(fty).sty {
2866 ty_bare_fn(_) => true,
2867 ty_closure(_) => true,
2872 pub fn ty_vstore(ty: t) -> vstore {
2874 ty_vec(_, vstore) => vstore,
2875 ty_str(vstore) => vstore,
2876 ref s => fail!("ty_vstore() called on invalid sty: {:?}", s)
2880 pub fn ty_region(tcx: ctxt,
2885 ty_vec(_, vstore_slice(r)) => r,
2886 ty_str(vstore_slice(r)) => r,
2890 format!("ty_region() invoked on in appropriate ty: {:?}", s));
2895 pub fn replace_fn_sig(cx: ctxt, fsty: &sty, new_sig: FnSig) -> t {
2897 ty_bare_fn(ref f) => mk_bare_fn(cx, BareFnTy {sig: new_sig, ..*f}),
2898 ty_closure(ref f) => mk_closure(cx, ClosureTy {sig: new_sig, ..*f}),
2901 format!("ty_fn_sig() called on non-fn type: {:?}", s));
2906 pub fn replace_closure_return_type(tcx: ctxt, fn_type: t, ret_type: t) -> t {
2909 * Returns a new function type based on `fn_type` but returning a value of
2910 * type `ret_type` instead. */
2912 match ty::get(fn_type).sty {
2913 ty::ty_closure(ref fty) => {
2914 ty::mk_closure(tcx, ClosureTy {
2915 sig: FnSig {output: ret_type, ..fty.sig.clone()},
2920 tcx.sess.bug(format!(
2921 "replace_fn_ret() invoked with non-fn-type: {}",
2922 ty_to_str(tcx, fn_type)));
2927 // Returns a vec of all the input and output types of fty.
2928 pub fn tys_in_fn_sig(sig: &FnSig) -> ~[t] {
2929 vec::append_one(sig.inputs.map(|a| *a), sig.output)
2932 // Type accessors for AST nodes
2933 pub fn block_ty(cx: ctxt, b: &ast::Block) -> t {
2934 return node_id_to_type(cx, b.id);
2938 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
2939 // doesn't provide type parameter substitutions.
2940 pub fn pat_ty(cx: ctxt, pat: &ast::Pat) -> t {
2941 return node_id_to_type(cx, pat.id);
2945 // Returns the type of an expression as a monotype.
2947 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
2948 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
2949 // auto-ref. The type returned by this function does not consider such
2950 // adjustments. See `expr_ty_adjusted()` instead.
2952 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
2953 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
2954 // instead of "fn(t) -> T with T = int". If this isn't what you want, see
2955 // expr_ty_params_and_ty() below.
2956 pub fn expr_ty(cx: ctxt, expr: &ast::Expr) -> t {
2957 return node_id_to_type(cx, expr.id);
2960 pub fn expr_ty_opt(cx: ctxt, expr: &ast::Expr) -> Option<t> {
2961 return node_id_to_type_opt(cx, expr.id);
2964 pub fn expr_ty_adjusted(cx: ctxt, expr: &ast::Expr) -> t {
2967 * Returns the type of `expr`, considering any `AutoAdjustment`
2968 * entry recorded for that expression.
2970 * It would almost certainly be better to store the adjusted ty in with
2971 * the `AutoAdjustment`, but I opted not to do this because it would
2972 * require serializing and deserializing the type and, although that's not
2973 * hard to do, I just hate that code so much I didn't want to touch it
2974 * unless it was to fix it properly, which seemed a distraction from the
2975 * task at hand! -nmatsakis
2978 let unadjusted_ty = expr_ty(cx, expr);
2980 let adjustments = cx.adjustments.borrow();
2981 adjustments.get().find_copy(&expr.id)
2983 adjust_ty(cx, expr.span, unadjusted_ty, adjustment)
2986 pub fn expr_span(cx: ctxt, id: NodeId) -> Span {
2987 match cx.map.find(id) {
2988 Some(ast_map::NodeExpr(e)) => {
2992 cx.sess.bug(format!("Node id {} is not an expr: {:?}",
2996 cx.sess.bug(format!("Node id {} is not present \
2997 in the node map", id));
3002 pub fn local_var_name_str(cx: ctxt, id: NodeId) -> InternedString {
3003 match cx.map.find(id) {
3004 Some(ast_map::NodeLocal(pat)) => {
3006 ast::PatIdent(_, ref path, _) => {
3007 token::get_ident(ast_util::path_to_ident(path))
3011 format!("Variable id {} maps to {:?}, not local",
3018 format!("Variable id {} maps to {:?}, not local",
3024 pub fn adjust_ty(cx: ctxt,
3026 unadjusted_ty: ty::t,
3027 adjustment: Option<@AutoAdjustment>)
3029 /*! See `expr_ty_adjusted` */
3031 return match adjustment {
3032 None => unadjusted_ty,
3034 Some(adjustment) => {
3036 AutoAddEnv(r, s) => {
3037 match ty::get(unadjusted_ty).sty {
3038 ty::ty_bare_fn(ref b) => {
3041 ty::ClosureTy {purity: b.purity,
3043 onceness: ast::Many,
3045 bounds: ty::AllBuiltinBounds(),
3046 sig: b.sig.clone()})
3050 format!("add_env adjustment on non-bare-fn: \
3057 AutoDerefRef(ref adj) => {
3058 let mut adjusted_ty = unadjusted_ty;
3060 if !ty::type_is_error(adjusted_ty) {
3061 for i in range(0, adj.autoderefs) {
3062 match ty::deref(adjusted_ty, true) {
3063 Some(mt) => { adjusted_ty = mt.ty; }
3067 format!("the {}th autoderef failed: \
3070 ty_to_str(cx, adjusted_ty)));
3077 None => adjusted_ty,
3078 Some(ref autoref) => {
3087 AutoBorrowVec(r, m) => {
3088 borrow_vec(cx, span, r, m, adjusted_ty)
3091 AutoBorrowVecRef(r, m) => {
3092 adjusted_ty = borrow_vec(cx,
3099 mutbl: ast::MutImmutable
3103 AutoBorrowFn(r) => {
3104 borrow_fn(cx, span, r, adjusted_ty)
3108 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
3111 AutoBorrowObj(r, m) => {
3112 borrow_obj(cx, span, r, m, adjusted_ty)
3119 AutoObject(ref sigil, ref region, m, b, def_id, ref substs) => {
3120 trait_adjustment_to_ty(cx,
3132 fn borrow_vec(cx: ctxt, span: Span,
3133 r: Region, m: ast::Mutability,
3134 ty: ty::t) -> ty::t {
3137 ty::mk_vec(cx, mt {ty: mt.ty, mutbl: m}, vstore_slice(r))
3141 ty::mk_str(cx, vstore_slice(r))
3147 format!("borrow-vec associated with bad sty: {:?}",
3153 fn borrow_fn(cx: ctxt, span: Span, r: Region, ty: ty::t) -> ty::t {
3155 ty_closure(ref fty) => {
3156 ty::mk_closure(cx, ClosureTy {
3157 sigil: BorrowedSigil,
3166 format!("borrow-fn associated with bad sty: {:?}",
3172 fn borrow_obj(cx: ctxt, span: Span, r: Region,
3173 m: ast::Mutability, ty: ty::t) -> ty::t {
3175 ty_trait(trt_did, ref trt_substs, _, _, b) => {
3176 ty::mk_trait(cx, trt_did, trt_substs.clone(),
3177 RegionTraitStore(r), m, b)
3182 format!("borrow-trait-obj associated with bad sty: {:?}",
3189 pub fn trait_adjustment_to_ty(cx: ctxt, sigil: &ast::Sigil, region: &Option<Region>,
3190 def_id: ast::DefId, substs: &substs, m: ast::Mutability,
3191 bounds: BuiltinBounds) -> t {
3193 let trait_store = match *sigil {
3194 BorrowedSigil => RegionTraitStore(region.expect("expected valid region")),
3195 OwnedSigil => UniqTraitStore,
3196 ManagedSigil => unreachable!()
3199 mk_trait(cx, def_id, substs.clone(), trait_store, m, bounds)
3203 pub fn map_region(&self, f: |Region| -> Region) -> AutoRef {
3205 ty::AutoPtr(r, m) => ty::AutoPtr(f(r), m),
3206 ty::AutoBorrowVec(r, m) => ty::AutoBorrowVec(f(r), m),
3207 ty::AutoBorrowVecRef(r, m) => ty::AutoBorrowVecRef(f(r), m),
3208 ty::AutoBorrowFn(r) => ty::AutoBorrowFn(f(r)),
3209 ty::AutoUnsafe(m) => ty::AutoUnsafe(m),
3210 ty::AutoBorrowObj(r, m) => ty::AutoBorrowObj(f(r), m),
3215 pub struct ParamsTy {
3220 pub fn expr_ty_params_and_ty(cx: ctxt,
3224 params: node_id_to_type_params(cx, expr.id),
3225 ty: node_id_to_type(cx, expr.id)
3229 pub fn expr_has_ty_params(cx: ctxt, expr: &ast::Expr) -> bool {
3230 return node_id_has_type_params(cx, expr.id);
3233 pub fn method_call_type_param_defs(tcx: ctxt, origin: typeck::MethodOrigin)
3234 -> Rc<~[TypeParameterDef]> {
3236 typeck::MethodStatic(did) => {
3237 // n.b.: When we encode impl methods, the bounds
3238 // that we encode include both the impl bounds
3239 // and then the method bounds themselves...
3240 ty::lookup_item_type(tcx, did).generics.type_param_defs
3242 typeck::MethodParam(typeck::MethodParam {
3244 method_num: n_mth, ..}) |
3245 typeck::MethodObject(typeck::MethodObject {
3247 method_num: n_mth, ..}) => {
3248 // ...trait methods bounds, in contrast, include only the
3249 // method bounds, so we must preprend the tps from the
3250 // trait itself. This ought to be harmonized.
3251 let trait_type_param_defs =
3252 lookup_trait_def(tcx, trt_id).generics.type_param_defs();
3253 Rc::new(vec::append(
3254 trait_type_param_defs.to_owned(),
3255 ty::trait_method(tcx,
3257 n_mth).generics.type_param_defs()))
3262 pub fn resolve_expr(tcx: ctxt, expr: &ast::Expr) -> ast::Def {
3263 let def_map = tcx.def_map.borrow();
3264 match def_map.get().find(&expr.id) {
3267 tcx.sess.span_bug(expr.span, format!(
3268 "no def-map entry for expr {:?}", expr.id));
3273 pub fn expr_is_lval(tcx: ctxt,
3274 method_map: typeck::MethodMap,
3275 e: &ast::Expr) -> bool {
3276 match expr_kind(tcx, method_map, e) {
3278 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
3282 /// We categorize expressions into three kinds. The distinction between
3283 /// lvalue/rvalue is fundamental to the language. The distinction between the
3284 /// two kinds of rvalues is an artifact of trans which reflects how we will
3285 /// generate code for that kind of expression. See trans/expr.rs for more
3294 pub fn expr_kind(tcx: ctxt,
3295 method_map: typeck::MethodMap,
3296 expr: &ast::Expr) -> ExprKind {
3298 let method_map = method_map.borrow();
3299 if method_map.get().contains_key(&expr.id) {
3300 // Overloaded operations are generally calls, and hence they are
3301 // generated via DPS. However, assign_op (e.g., `x += y`) is an
3302 // exception, as its result is always unit.
3303 return match expr.node {
3304 ast::ExprAssignOp(..) => RvalueStmtExpr,
3305 ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
3312 ast::ExprPath(..) => {
3313 match resolve_expr(tcx, expr) {
3314 ast::DefVariant(tid, vid, _) => {
3315 let variant_info = enum_variant_with_id(tcx, tid, vid);
3316 if variant_info.args.len() > 0u {
3325 ast::DefStruct(_) => {
3326 match get(expr_ty(tcx, expr)).sty {
3327 ty_bare_fn(..) => RvalueDatumExpr,
3332 // Fn pointers are just scalar values.
3333 ast::DefFn(..) | ast::DefStaticMethod(..) => RvalueDatumExpr,
3335 // Note: there is actually a good case to be made that
3336 // DefArg's, particularly those of immediate type, ought to
3337 // considered rvalues.
3338 ast::DefStatic(..) |
3339 ast::DefBinding(..) |
3342 ast::DefLocal(..) => LvalueExpr,
3345 tcx.sess.span_bug(expr.span, format!(
3346 "uncategorized def for expr {:?}: {:?}",
3352 ast::ExprUnary(ast::UnDeref, _) |
3353 ast::ExprField(..) |
3354 ast::ExprIndex(..) => {
3359 ast::ExprMethodCall(..) |
3360 ast::ExprStruct(..) |
3363 ast::ExprMatch(..) |
3364 ast::ExprFnBlock(..) |
3366 ast::ExprBlock(..) |
3367 ast::ExprRepeat(..) |
3368 ast::ExprVstore(_, ast::ExprVstoreSlice) |
3369 ast::ExprVstore(_, ast::ExprVstoreMutSlice) |
3370 ast::ExprVec(..) => {
3374 ast::ExprLit(lit) if lit_is_str(lit) => {
3378 ast::ExprCast(..) => {
3379 let node_types = tcx.node_types.borrow();
3380 match node_types.get().find(&(expr.id as uint)) {
3382 if type_is_trait(t) {
3389 // Technically, it should not happen that the expr is not
3390 // present within the table. However, it DOES happen
3391 // during type check, because the final types from the
3392 // expressions are not yet recorded in the tcx. At that
3393 // time, though, we are only interested in knowing lvalue
3394 // vs rvalue. It would be better to base this decision on
3395 // the AST type in cast node---but (at the time of this
3396 // writing) it's not easy to distinguish casts to traits
3397 // from other casts based on the AST. This should be
3398 // easier in the future, when casts to traits
3399 // would like @Foo, ~Foo, or &Foo.
3405 ast::ExprBreak(..) |
3406 ast::ExprAgain(..) |
3408 ast::ExprWhile(..) |
3410 ast::ExprAssign(..) |
3411 ast::ExprInlineAsm(..) |
3412 ast::ExprAssignOp(..) => {
3416 ast::ExprForLoop(..) => fail!("non-desugared expr_for_loop"),
3419 ast::ExprLit(_) | // Note: LitStr is carved out above
3420 ast::ExprUnary(..) |
3421 ast::ExprAddrOf(..) |
3422 ast::ExprBinary(..) |
3423 ast::ExprVstore(_, ast::ExprVstoreUniq) => {
3427 ast::ExprBox(place, _) => {
3428 // Special case `~T` for now:
3429 let def_map = tcx.def_map.borrow();
3430 let definition = match def_map.get().find(&place.id) {
3432 None => fail!("no def for place"),
3434 let def_id = ast_util::def_id_of_def(definition);
3435 match tcx.lang_items.items[ExchangeHeapLangItem as uint] {
3436 Some(item_def_id) if def_id == item_def_id => RvalueDatumExpr,
3437 Some(_) | None => RvalueDpsExpr,
3441 ast::ExprParen(e) => expr_kind(tcx, method_map, e),
3443 ast::ExprMac(..) => {
3446 "macro expression remains after expansion");
3451 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
3453 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
3456 ast::StmtMac(..) => fail!("unexpanded macro in trans")
3460 pub fn field_idx(name: ast::Name, fields: &[field]) -> Option<uint> {
3462 for f in fields.iter() { if f.ident.name == name { return Some(i); } i += 1u; }
3466 pub fn field_idx_strict(tcx: ty::ctxt, name: ast::Name, fields: &[field])
3469 for f in fields.iter() { if f.ident.name == name { return i; } i += 1u; }
3470 tcx.sess.bug(format!(
3471 "no field named `{}` found in the list of fields `{:?}`",
3472 token::get_name(name),
3473 fields.map(|f| token::get_ident(f.ident).get().to_str())));
3476 pub fn method_idx(id: ast::Ident, meths: &[@Method]) -> Option<uint> {
3477 meths.iter().position(|m| m.ident == id)
3480 /// Returns a vector containing the indices of all type parameters that appear
3481 /// in `ty`. The vector may contain duplicates. Probably should be converted
3482 /// to a bitset or some other representation.
3483 pub fn param_tys_in_type(ty: t) -> ~[param_ty] {
3496 pub fn occurs_check(tcx: ctxt, sp: Span, vid: TyVid, rt: t) {
3497 // Returns a vec of all the type variables occurring in `ty`. It may
3498 // contain duplicates. (Integral type vars aren't counted.)
3499 fn vars_in_type(ty: t) -> ~[TyVid] {
3503 ty_infer(TyVar(v)) => rslt.push(v),
3511 if !type_needs_infer(rt) { return; }
3514 if vars_in_type(rt).contains(&vid) {
3515 // Maybe this should be span_err -- however, there's an
3516 // assertion later on that the type doesn't contain
3517 // variables, so in this case we have to be sure to die.
3519 (sp, ~"type inference failed because I \
3520 could not find a type\n that's both of the form "
3521 + ::util::ppaux::ty_to_str(tcx, mk_var(tcx, vid)) +
3522 " and of the form " + ::util::ppaux::ty_to_str(tcx, rt) +
3523 " - such a type would have to be infinitely large.");
3527 pub fn ty_sort_str(cx: ctxt, t: t) -> ~str {
3529 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) |
3530 ty_uint(_) | ty_float(_) | ty_str(_) => {
3531 ::util::ppaux::ty_to_str(cx, t)
3534 ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
3535 ty_box(_) => ~"@-ptr",
3536 ty_uniq(_) => ~"~-ptr",
3537 ty_vec(_, _) => ~"vector",
3538 ty_unboxed_vec(_) => ~"unboxed vector",
3539 ty_ptr(_) => ~"*-ptr",
3540 ty_rptr(_, _) => ~"&-ptr",
3541 ty_bare_fn(_) => ~"extern fn",
3542 ty_closure(_) => ~"fn",
3543 ty_trait(id, _, _, _, _) => format!("trait {}", item_path_str(cx, id)),
3544 ty_struct(id, _) => format!("struct {}", item_path_str(cx, id)),
3545 ty_tup(_) => ~"tuple",
3546 ty_infer(TyVar(_)) => ~"inferred type",
3547 ty_infer(IntVar(_)) => ~"integral variable",
3548 ty_infer(FloatVar(_)) => ~"floating-point variable",
3549 ty_param(_) => ~"type parameter",
3550 ty_self(_) => ~"self",
3551 ty_err => ~"type error"
3555 pub fn type_err_to_str(cx: ctxt, err: &type_err) -> ~str {
3558 * Explains the source of a type err in a short,
3559 * human readable way. This is meant to be placed in
3560 * parentheses after some larger message. You should
3561 * also invoke `note_and_explain_type_err()` afterwards
3562 * to present additional details, particularly when
3563 * it comes to lifetime-related errors. */
3565 fn terr_vstore_kind_to_str(k: terr_vstore_kind) -> ~str {
3570 terr_trait => ~"trait"
3575 terr_mismatch => ~"types differ",
3576 terr_purity_mismatch(values) => {
3577 format!("expected {} fn but found {} fn",
3578 values.expected.to_str(), values.found.to_str())
3580 terr_abi_mismatch(values) => {
3581 format!("expected {} fn but found {} fn",
3582 values.expected.to_str(), values.found.to_str())
3584 terr_onceness_mismatch(values) => {
3585 format!("expected {} fn but found {} fn",
3586 values.expected.to_str(), values.found.to_str())
3588 terr_sigil_mismatch(values) => {
3589 format!("expected {} closure, found {} closure",
3590 values.expected.to_str(),
3591 values.found.to_str())
3593 terr_mutability => ~"values differ in mutability",
3594 terr_box_mutability => ~"boxed values differ in mutability",
3595 terr_vec_mutability => ~"vectors differ in mutability",
3596 terr_ptr_mutability => ~"pointers differ in mutability",
3597 terr_ref_mutability => ~"references differ in mutability",
3598 terr_ty_param_size(values) => {
3599 format!("expected a type with {} type params \
3600 but found one with {} type params",
3601 values.expected, values.found)
3603 terr_tuple_size(values) => {
3604 format!("expected a tuple with {} elements \
3605 but found one with {} elements",
3606 values.expected, values.found)
3608 terr_record_size(values) => {
3609 format!("expected a record with {} fields \
3610 but found one with {} fields",
3611 values.expected, values.found)
3613 terr_record_mutability => {
3614 ~"record elements differ in mutability"
3616 terr_record_fields(values) => {
3617 format!("expected a record with field `{}` but found one with field \
3619 token::get_ident(values.expected),
3620 token::get_ident(values.found))
3622 terr_arg_count => ~"incorrect number of function parameters",
3623 terr_regions_does_not_outlive(..) => {
3624 format!("lifetime mismatch")
3626 terr_regions_not_same(..) => {
3627 format!("lifetimes are not the same")
3629 terr_regions_no_overlap(..) => {
3630 format!("lifetimes do not intersect")
3632 terr_regions_insufficiently_polymorphic(br, _) => {
3633 format!("expected bound lifetime parameter {}, \
3634 but found concrete lifetime",
3635 bound_region_ptr_to_str(cx, br))
3637 terr_regions_overly_polymorphic(br, _) => {
3638 format!("expected concrete lifetime, \
3639 but found bound lifetime parameter {}",
3640 bound_region_ptr_to_str(cx, br))
3642 terr_vstores_differ(k, ref values) => {
3643 format!("{} storage differs: expected `{}` but found `{}`",
3644 terr_vstore_kind_to_str(k),
3645 vstore_to_str(cx, (*values).expected),
3646 vstore_to_str(cx, (*values).found))
3648 terr_trait_stores_differ(_, ref values) => {
3649 format!("trait storage differs: expected `{}` but found `{}`",
3650 trait_store_to_str(cx, (*values).expected),
3651 trait_store_to_str(cx, (*values).found))
3653 terr_in_field(err, fname) => {
3654 format!("in field `{}`, {}", token::get_ident(fname),
3655 type_err_to_str(cx, err))
3657 terr_sorts(values) => {
3658 format!("expected {} but found {}",
3659 ty_sort_str(cx, values.expected),
3660 ty_sort_str(cx, values.found))
3662 terr_traits(values) => {
3663 format!("expected trait `{}` but found trait `{}`",
3664 item_path_str(cx, values.expected),
3665 item_path_str(cx, values.found))
3667 terr_builtin_bounds(values) => {
3668 if values.expected.is_empty() {
3669 format!("expected no bounds but found `{}`",
3670 values.found.user_string(cx))
3671 } else if values.found.is_empty() {
3672 format!("expected bounds `{}` but found no bounds",
3673 values.expected.user_string(cx))
3675 format!("expected bounds `{}` but found bounds `{}`",
3676 values.expected.user_string(cx),
3677 values.found.user_string(cx))
3680 terr_integer_as_char => {
3681 format!("expected an integral type but found `char`")
3683 terr_int_mismatch(ref values) => {
3684 format!("expected `{}` but found `{}`",
3685 values.expected.to_str(),
3686 values.found.to_str())
3688 terr_float_mismatch(ref values) => {
3689 format!("expected `{}` but found `{}`",
3690 values.expected.to_str(),
3691 values.found.to_str())
3693 terr_variadic_mismatch(ref values) => {
3694 format!("expected {} fn but found {} function",
3695 if values.expected { "variadic" } else { "non-variadic" },
3696 if values.found { "variadic" } else { "non-variadic" })
3701 pub fn note_and_explain_type_err(cx: ctxt, err: &type_err) {
3703 terr_regions_does_not_outlive(subregion, superregion) => {
3704 note_and_explain_region(cx, "", subregion, "...");
3705 note_and_explain_region(cx, "...does not necessarily outlive ",
3708 terr_regions_not_same(region1, region2) => {
3709 note_and_explain_region(cx, "", region1, "...");
3710 note_and_explain_region(cx, "...is not the same lifetime as ",
3713 terr_regions_no_overlap(region1, region2) => {
3714 note_and_explain_region(cx, "", region1, "...");
3715 note_and_explain_region(cx, "...does not overlap ",
3718 terr_regions_insufficiently_polymorphic(_, conc_region) => {
3719 note_and_explain_region(cx,
3720 "concrete lifetime that was found is ",
3723 terr_regions_overly_polymorphic(_, conc_region) => {
3724 note_and_explain_region(cx,
3725 "expected concrete lifetime is ",
3732 pub fn def_has_ty_params(def: ast::Def) -> bool {
3734 ast::DefFn(_, _) | ast::DefVariant(_, _, _) | ast::DefStruct(_)
3740 pub fn provided_source(cx: ctxt, id: ast::DefId) -> Option<ast::DefId> {
3741 let provided_method_sources = cx.provided_method_sources.borrow();
3742 provided_method_sources.get().find(&id).map(|x| *x)
3745 pub fn provided_trait_methods(cx: ctxt, id: ast::DefId) -> ~[@Method] {
3748 match cx.map.find(id.node) {
3749 Some(ast_map::NodeItem(item)) => {
3751 ItemTrait(_, _, ref ms) => {
3753 ast_util::split_trait_methods(ms.as_slice());
3755 .map(|m| method(cx, ast_util::local_def(m.id)))
3759 cx.sess.bug(format!("provided_trait_methods: \
3760 `{:?}` is not a trait",
3766 cx.sess.bug(format!("provided_trait_methods: `{:?}` is not \
3773 csearch::get_provided_trait_methods(cx, id)
3777 pub fn trait_supertraits(cx: ctxt, id: ast::DefId) -> @~[@TraitRef] {
3780 let supertraits = cx.supertraits.borrow();
3781 match supertraits.get().find(&id) {
3782 Some(&trait_refs) => { return trait_refs; }
3783 None => {} // Continue.
3787 // Not in the cache. It had better be in the metadata, which means it
3788 // shouldn't be local.
3789 assert!(!is_local(id));
3791 // Get the supertraits out of the metadata and create the
3792 // TraitRef for each.
3793 let result = @csearch::get_supertraits(cx, id);
3794 let mut supertraits = cx.supertraits.borrow_mut();
3795 supertraits.get().insert(id, result);
3799 pub fn trait_ref_supertraits(cx: ctxt, trait_ref: &ty::TraitRef) -> ~[@TraitRef] {
3800 let supertrait_refs = trait_supertraits(cx, trait_ref.def_id);
3801 supertrait_refs.map(
3802 |supertrait_ref| supertrait_ref.subst(cx, &trait_ref.substs))
3805 fn lookup_locally_or_in_crate_store<V:Clone>(
3808 map: &mut DefIdMap<V>,
3809 load_external: || -> V) -> V {
3811 * Helper for looking things up in the various maps
3812 * that are populated during typeck::collect (e.g.,
3813 * `cx.methods`, `cx.tcache`, etc). All of these share
3814 * the pattern that if the id is local, it should have
3815 * been loaded into the map by the `typeck::collect` phase.
3816 * If the def-id is external, then we have to go consult
3817 * the crate loading code (and cache the result for the future).
3820 match map.find_copy(&def_id) {
3821 Some(v) => { return v; }
3825 if def_id.krate == ast::LOCAL_CRATE {
3826 fail!("No def'n found for {:?} in tcx.{}", def_id, descr);
3828 let v = load_external();
3829 map.insert(def_id, v.clone());
3833 pub fn trait_method(cx: ctxt, trait_did: ast::DefId, idx: uint) -> @Method {
3834 let method_def_id = ty::trait_method_def_ids(cx, trait_did)[idx];
3835 ty::method(cx, method_def_id)
3839 pub fn trait_methods(cx: ctxt, trait_did: ast::DefId) -> @~[@Method] {
3840 let mut trait_methods_cache = cx.trait_methods_cache.borrow_mut();
3841 match trait_methods_cache.get().find(&trait_did) {
3842 Some(&methods) => methods,
3844 let def_ids = ty::trait_method_def_ids(cx, trait_did);
3845 let methods = @def_ids.map(|d| ty::method(cx, *d));
3846 trait_methods_cache.get().insert(trait_did, methods);
3852 pub fn method(cx: ctxt, id: ast::DefId) -> @Method {
3853 let mut methods = cx.methods.borrow_mut();
3854 lookup_locally_or_in_crate_store("methods", id, methods.get(), || {
3855 @csearch::get_method(cx, id)
3859 pub fn trait_method_def_ids(cx: ctxt, id: ast::DefId) -> @~[DefId] {
3860 let mut trait_method_def_ids = cx.trait_method_def_ids.borrow_mut();
3861 lookup_locally_or_in_crate_store("trait_method_def_ids",
3863 trait_method_def_ids.get(),
3865 @csearch::get_trait_method_def_ids(cx.cstore, id)
3869 pub fn impl_trait_ref(cx: ctxt, id: ast::DefId) -> Option<@TraitRef> {
3871 let mut impl_trait_cache = cx.impl_trait_cache.borrow_mut();
3872 match impl_trait_cache.get().find(&id) {
3873 Some(&ret) => { return ret; }
3878 let ret = if id.krate == ast::LOCAL_CRATE {
3879 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
3880 match cx.map.find(id.node) {
3881 Some(ast_map::NodeItem(item)) => {
3883 ast::ItemImpl(_, ref opt_trait, _, _) => {
3886 Some(ty::node_id_to_trait_ref(cx, t.ref_id))
3897 csearch::get_impl_trait(cx, id)
3900 let mut impl_trait_cache = cx.impl_trait_cache.borrow_mut();
3901 impl_trait_cache.get().insert(id, ret);
3905 pub fn trait_ref_to_def_id(tcx: ctxt, tr: &ast::TraitRef) -> ast::DefId {
3906 let def_map = tcx.def_map.borrow();
3907 let def = def_map.get()
3909 .expect("no def-map entry for trait");
3910 ast_util::def_id_of_def(*def)
3913 pub fn try_add_builtin_trait(tcx: ctxt,
3914 trait_def_id: ast::DefId,
3915 builtin_bounds: &mut BuiltinBounds) -> bool {
3916 //! Checks whether `trait_ref` refers to one of the builtin
3917 //! traits, like `Send`, and adds the corresponding
3918 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
3919 //! is a builtin trait.
3921 match tcx.lang_items.to_builtin_kind(trait_def_id) {
3922 Some(bound) => { builtin_bounds.add(bound); true }
3927 pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> {
3929 ty_trait(id, _, _, _, _) | ty_struct(id, _) | ty_enum(id, _) => Some(id),
3936 pub struct VariantInfo {
3938 arg_names: Option<~[ast::Ident]>,
3948 /// Creates a new VariantInfo from the corresponding ast representation.
3950 /// Does not do any caching of the value in the type context.
3951 pub fn from_ast_variant(cx: ctxt,
3952 ast_variant: &ast::Variant,
3953 discriminant: Disr) -> VariantInfo {
3954 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
3956 match ast_variant.node.kind {
3957 ast::TupleVariantKind(ref args) => {
3958 let arg_tys = if args.len() > 0 { ty_fn_args(ctor_ty).map(|a| *a) } else { ~[] };
3960 return VariantInfo {
3964 name: ast_variant.node.name,
3965 id: ast_util::local_def(ast_variant.node.id),
3966 disr_val: discriminant,
3967 vis: ast_variant.node.vis
3970 ast::StructVariantKind(ref struct_def) => {
3972 let fields: &[StructField] = struct_def.fields.as_slice();
3974 assert!(fields.len() > 0);
3976 let arg_tys = ty_fn_args(ctor_ty).map(|a| *a);
3977 let arg_names = fields.map(|field| {
3978 match field.node.kind {
3979 NamedField(ident, _) => ident,
3980 UnnamedField => cx.sess.bug(
3981 "enum_variants: all fields in struct must have a name")
3985 return VariantInfo {
3987 arg_names: Some(arg_names),
3989 name: ast_variant.node.name,
3990 id: ast_util::local_def(ast_variant.node.id),
3991 disr_val: discriminant,
3992 vis: ast_variant.node.vis
3999 pub fn substd_enum_variants(cx: ctxt,
4002 -> ~[@VariantInfo] {
4003 enum_variants(cx, id).iter().map(|variant_info| {
4004 let substd_args = variant_info.args.iter()
4005 .map(|aty| subst(cx, substs, *aty)).collect();
4007 let substd_ctor_ty = subst(cx, substs, variant_info.ctor_ty);
4011 ctor_ty: substd_ctor_ty,
4012 ..(**variant_info).clone()
4017 pub fn item_path_str(cx: ctxt, id: ast::DefId) -> ~str {
4018 with_path(cx, id, |path| ast_map::path_to_str(path))
4023 TraitDtor(DefId, bool)
4027 pub fn is_not_present(&self) -> bool {
4034 pub fn is_present(&self) -> bool {
4035 !self.is_not_present()
4038 pub fn has_drop_flag(&self) -> bool {
4041 &TraitDtor(_, flag) => flag
4046 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
4047 Otherwise return none. */
4048 pub fn ty_dtor(cx: ctxt, struct_id: DefId) -> DtorKind {
4049 let destructor_for_type = cx.destructor_for_type.borrow();
4050 match destructor_for_type.get().find(&struct_id) {
4051 Some(&method_def_id) => {
4052 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
4054 TraitDtor(method_def_id, flag)
4060 pub fn has_dtor(cx: ctxt, struct_id: DefId) -> bool {
4061 ty_dtor(cx, struct_id).is_present()
4064 pub fn with_path<T>(cx: ctxt, id: ast::DefId, f: |ast_map::PathElems| -> T) -> T {
4065 if id.krate == ast::LOCAL_CRATE {
4066 cx.map.with_path(id.node, f)
4068 f(ast_map::Values(csearch::get_item_path(cx, id).iter()).chain(None))
4072 pub fn enum_is_univariant(cx: ctxt, id: ast::DefId) -> bool {
4073 enum_variants(cx, id).len() == 1
4076 pub fn type_is_empty(cx: ctxt, t: t) -> bool {
4077 match ty::get(t).sty {
4078 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
4083 pub fn enum_variants(cx: ctxt, id: ast::DefId) -> @~[@VariantInfo] {
4085 let enum_var_cache = cx.enum_var_cache.borrow();
4086 match enum_var_cache.get().find(&id) {
4087 Some(&variants) => return variants,
4088 _ => { /* fallthrough */ }
4092 let result = if ast::LOCAL_CRATE != id.krate {
4093 @csearch::get_enum_variants(cx, id)
4096 Although both this code and check_enum_variants in typeck/check
4097 call eval_const_expr, it should never get called twice for the same
4098 expr, since check_enum_variants also updates the enum_var_cache
4101 match cx.map.get(id.node) {
4102 ast_map::NodeItem(item) => {
4104 ast::ItemEnum(ref enum_definition, _) => {
4105 let mut last_discriminant: Option<Disr> = None;
4106 @enum_definition.variants.iter().map(|&variant| {
4108 let mut discriminant = match last_discriminant {
4109 Some(val) => val + 1,
4110 None => INITIAL_DISCRIMINANT_VALUE
4113 match variant.node.disr_expr {
4114 Some(e) => match const_eval::eval_const_expr_partial(&cx, e) {
4115 Ok(const_eval::const_int(val)) => {
4116 discriminant = val as Disr
4118 Ok(const_eval::const_uint(val)) => {
4119 discriminant = val as Disr
4124 "expected signed integer \
4139 @VariantInfo::from_ast_variant(cx,
4142 last_discriminant = Some(discriminant);
4148 cx.sess.bug("enum_variants: id not bound to an enum")
4152 _ => cx.sess.bug("enum_variants: id not bound to an enum")
4158 let mut enum_var_cache = cx.enum_var_cache.borrow_mut();
4159 enum_var_cache.get().insert(id, result);
4165 // Returns information about the enum variant with the given ID:
4166 pub fn enum_variant_with_id(cx: ctxt,
4167 enum_id: ast::DefId,
4168 variant_id: ast::DefId)
4170 let variants = enum_variants(cx, enum_id);
4172 while i < variants.len() {
4173 let variant = variants[i];
4174 if variant.id == variant_id { return variant; }
4177 cx.sess.bug("enum_variant_with_id(): no variant exists with that ID");
4181 // If the given item is in an external crate, looks up its type and adds it to
4182 // the type cache. Returns the type parameters and type.
4183 pub fn lookup_item_type(cx: ctxt,
4185 -> ty_param_bounds_and_ty {
4186 let mut tcache = cx.tcache.borrow_mut();
4187 lookup_locally_or_in_crate_store(
4188 "tcache", did, tcache.get(),
4189 || csearch::get_type(cx, did))
4192 pub fn lookup_impl_vtables(cx: ctxt,
4194 -> typeck::impl_res {
4195 let mut impl_vtables = cx.impl_vtables.borrow_mut();
4196 lookup_locally_or_in_crate_store(
4197 "impl_vtables", did, impl_vtables.get(),
4198 || csearch::get_impl_vtables(cx, did) )
4201 /// Given the did of a trait, returns its canonical trait ref.
4202 pub fn lookup_trait_def(cx: ctxt, did: ast::DefId) -> @ty::TraitDef {
4203 let mut trait_defs = cx.trait_defs.borrow_mut();
4204 match trait_defs.get().find(&did) {
4205 Some(&trait_def) => {
4206 // The item is in this crate. The caller should have added it to the
4207 // type cache already
4211 assert!(did.krate != ast::LOCAL_CRATE);
4212 let trait_def = @csearch::get_trait_def(cx, did);
4213 trait_defs.get().insert(did, trait_def);
4219 /// Iterate over meta_items of a definition.
4220 // (This should really be an iterator, but that would require csearch and
4221 // decoder to use iterators instead of higher-order functions.)
4222 pub fn each_attr(tcx: ctxt, did: DefId, f: |@MetaItem| -> bool) -> bool {
4224 let item = tcx.map.expect_item(did.node);
4225 item.attrs.iter().advance(|attr| f(attr.node.value))
4227 let mut cont = true;
4228 csearch::get_item_attrs(tcx.cstore, did, |meta_items| {
4230 cont = meta_items.iter().advance(|ptrptr| f(*ptrptr));
4237 /// Determine whether an item is annotated with an attribute
4238 pub fn has_attr(tcx: ctxt, did: DefId, attr: &str) -> bool {
4239 let mut found = false;
4240 each_attr(tcx, did, |item| {
4241 if item.name().equiv(&attr) {
4251 /// Determine whether an item is annotated with `#[packed]`
4252 pub fn lookup_packed(tcx: ctxt, did: DefId) -> bool {
4253 has_attr(tcx, did, "packed")
4256 /// Determine whether an item is annotated with `#[simd]`
4257 pub fn lookup_simd(tcx: ctxt, did: DefId) -> bool {
4258 has_attr(tcx, did, "simd")
4261 // Obtain the representation annotation for a definition.
4262 pub fn lookup_repr_hint(tcx: ctxt, did: DefId) -> attr::ReprAttr {
4263 let mut acc = attr::ReprAny;
4264 ty::each_attr(tcx, did, |meta| {
4265 acc = attr::find_repr_attr(tcx.sess.diagnostic(), meta, acc);
4271 // Look up a field ID, whether or not it's local
4272 // Takes a list of type substs in case the struct is generic
4273 pub fn lookup_field_type(tcx: ctxt,
4278 let t = if id.krate == ast::LOCAL_CRATE {
4279 node_id_to_type(tcx, id.node)
4282 let mut tcache = tcx.tcache.borrow_mut();
4283 match tcache.get().find(&id) {
4284 Some(&ty_param_bounds_and_ty {ty, ..}) => ty,
4286 let tpt = csearch::get_field_type(tcx, struct_id, id);
4287 tcache.get().insert(id, tpt.clone());
4293 subst(tcx, substs, t)
4296 // Look up the list of field names and IDs for a given struct
4297 // Fails if the id is not bound to a struct.
4298 pub fn lookup_struct_fields(cx: ctxt, did: ast::DefId) -> ~[field_ty] {
4299 if did.krate == ast::LOCAL_CRATE {
4301 match cx.map.find(did.node) {
4302 Some(ast_map::NodeItem(i)) => {
4304 ast::ItemStruct(struct_def, _) => {
4305 struct_field_tys(struct_def.fields.as_slice())
4307 _ => cx.sess.bug("struct ID bound to non-struct")
4310 Some(ast_map::NodeVariant(ref variant)) => {
4311 match (*variant).node.kind {
4312 ast::StructVariantKind(struct_def) => {
4313 struct_field_tys(struct_def.fields.as_slice())
4316 cx.sess.bug("struct ID bound to enum variant that isn't \
4323 format!("struct ID not bound to an item: {}",
4324 cx.map.node_to_str(did.node)));
4329 return csearch::get_struct_fields(cx.sess.cstore, did);
4333 pub fn lookup_struct_field(cx: ctxt,
4335 field_id: ast::DefId)
4337 let r = lookup_struct_fields(cx, parent);
4338 match r.iter().find(
4339 |f| f.id.node == field_id.node) {
4341 None => cx.sess.bug("struct ID not found in parent's fields")
4345 fn struct_field_tys(fields: &[StructField]) -> ~[field_ty] {
4346 fields.map(|field| {
4347 match field.node.kind {
4348 NamedField(ident, visibility) => {
4351 id: ast_util::local_def(field.node.id),
4357 name: syntax::parse::token::special_idents::unnamed_field.name,
4358 id: ast_util::local_def(field.node.id),
4366 // Returns a list of fields corresponding to the struct's items. trans uses
4367 // this. Takes a list of substs with which to instantiate field types.
4368 pub fn struct_fields(cx: ctxt, did: ast::DefId, substs: &substs)
4370 lookup_struct_fields(cx, did).map(|f| {
4372 // FIXME #6993: change type of field to Name and get rid of new()
4373 ident: ast::Ident::new(f.name),
4375 ty: lookup_field_type(cx, did, f.id, substs),
4382 pub fn is_binopable(cx: ctxt, ty: t, op: ast::BinOp) -> bool {
4383 static tycat_other: int = 0;
4384 static tycat_bool: int = 1;
4385 static tycat_char: int = 2;
4386 static tycat_int: int = 3;
4387 static tycat_float: int = 4;
4388 static tycat_bot: int = 5;
4389 static tycat_raw_ptr: int = 6;
4391 static opcat_add: int = 0;
4392 static opcat_sub: int = 1;
4393 static opcat_mult: int = 2;
4394 static opcat_shift: int = 3;
4395 static opcat_rel: int = 4;
4396 static opcat_eq: int = 5;
4397 static opcat_bit: int = 6;
4398 static opcat_logic: int = 7;
4400 fn opcat(op: ast::BinOp) -> int {
4402 ast::BiAdd => opcat_add,
4403 ast::BiSub => opcat_sub,
4404 ast::BiMul => opcat_mult,
4405 ast::BiDiv => opcat_mult,
4406 ast::BiRem => opcat_mult,
4407 ast::BiAnd => opcat_logic,
4408 ast::BiOr => opcat_logic,
4409 ast::BiBitXor => opcat_bit,
4410 ast::BiBitAnd => opcat_bit,
4411 ast::BiBitOr => opcat_bit,
4412 ast::BiShl => opcat_shift,
4413 ast::BiShr => opcat_shift,
4414 ast::BiEq => opcat_eq,
4415 ast::BiNe => opcat_eq,
4416 ast::BiLt => opcat_rel,
4417 ast::BiLe => opcat_rel,
4418 ast::BiGe => opcat_rel,
4419 ast::BiGt => opcat_rel
4423 fn tycat(cx: ctxt, ty: t) -> int {
4424 if type_is_simd(cx, ty) {
4425 return tycat(cx, simd_type(cx, ty))
4428 ty_char => tycat_char,
4429 ty_bool => tycat_bool,
4430 ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
4431 ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
4432 ty_bot => tycat_bot,
4433 ty_ptr(_) => tycat_raw_ptr,
4438 static t: bool = true;
4439 static f: bool = false;
4442 // +, -, *, shift, rel, ==, bit, logic
4443 /*other*/ [f, f, f, f, f, f, f, f],
4444 /*bool*/ [f, f, f, f, t, t, t, t],
4445 /*char*/ [f, f, f, f, t, t, f, f],
4446 /*int*/ [t, t, t, t, t, t, t, f],
4447 /*float*/ [t, t, t, f, t, t, f, f],
4448 /*bot*/ [t, t, t, t, t, t, t, t],
4449 /*raw ptr*/ [f, f, f, f, t, t, f, f]];
4451 return tbl[tycat(cx, ty)][opcat(op)];
4454 pub fn ty_params_to_tys(tcx: ty::ctxt, generics: &ast::Generics) -> ~[t] {
4455 vec::from_fn(generics.ty_params.len(), |i| {
4456 let id = generics.ty_params.get(i).id;
4457 ty::mk_param(tcx, i, ast_util::local_def(id))
4461 /// Returns an equivalent type with all the typedefs and self regions removed.
4462 pub fn normalize_ty(cx: ctxt, t: t) -> t {
4463 let u = TypeNormalizer(cx).fold_ty(t);
4466 struct TypeNormalizer(ctxt);
4468 impl TypeFolder for TypeNormalizer {
4469 fn tcx(&self) -> ty::ctxt { let TypeNormalizer(c) = *self; c }
4471 fn fold_ty(&mut self, t: ty::t) -> ty::t {
4472 let normalized_opt = {
4473 let normalized_cache = self.tcx().normalized_cache.borrow();
4474 normalized_cache.get().find_copy(&t)
4476 match normalized_opt {
4481 let t_norm = ty_fold::super_fold_ty(self, t);
4482 let mut normalized_cache = self.tcx()
4485 normalized_cache.get().insert(t, t_norm);
4491 fn fold_vstore(&mut self, vstore: vstore) -> vstore {
4493 vstore_fixed(..) | vstore_uniq => vstore,
4494 vstore_slice(_) => vstore_slice(ReStatic)
4498 fn fold_region(&mut self, _: ty::Region) -> ty::Region {
4502 fn fold_substs(&mut self,
4505 substs { regions: ErasedRegions,
4506 self_ty: ty_fold::fold_opt_ty(self, substs.self_ty),
4507 tps: ty_fold::fold_ty_vec(self, substs.tps) }
4510 fn fold_sig(&mut self,
4513 // The binder-id is only relevant to bound regions, which
4514 // are erased at trans time.
4515 ty::FnSig { binder_id: ast::DUMMY_NODE_ID,
4516 inputs: ty_fold::fold_ty_vec(self, sig.inputs),
4517 output: self.fold_ty(sig.output),
4518 variadic: sig.variadic }
4523 pub trait ExprTyProvider {
4524 fn expr_ty(&self, ex: &ast::Expr) -> t;
4525 fn ty_ctxt(&self) -> ctxt;
4528 impl ExprTyProvider for ctxt {
4529 fn expr_ty(&self, ex: &ast::Expr) -> t {
4533 fn ty_ctxt(&self) -> ctxt {
4538 // Returns the repeat count for a repeating vector expression.
4539 pub fn eval_repeat_count<T: ExprTyProvider>(tcx: &T, count_expr: &ast::Expr) -> uint {
4540 match const_eval::eval_const_expr_partial(tcx, count_expr) {
4541 Ok(ref const_val) => match *const_val {
4542 const_eval::const_int(count) => if count < 0 {
4543 tcx.ty_ctxt().sess.span_err(count_expr.span,
4544 "expected positive integer for \
4545 repeat count but found negative integer");
4548 return count as uint
4550 const_eval::const_uint(count) => return count as uint,
4551 const_eval::const_float(count) => {
4552 tcx.ty_ctxt().sess.span_err(count_expr.span,
4553 "expected positive integer for \
4554 repeat count but found float");
4555 return count as uint;
4557 const_eval::const_str(_) => {
4558 tcx.ty_ctxt().sess.span_err(count_expr.span,
4559 "expected positive integer for \
4560 repeat count but found string");
4563 const_eval::const_bool(_) => {
4564 tcx.ty_ctxt().sess.span_err(count_expr.span,
4565 "expected positive integer for \
4566 repeat count but found boolean");
4569 const_eval::const_binary(_) => {
4570 tcx.ty_ctxt().sess.span_err(count_expr.span,
4571 "expected positive integer for \
4572 repeat count but found binary array");
4577 tcx.ty_ctxt().sess.span_err(count_expr.span,
4578 "expected constant integer for repeat count \
4579 but found variable");
4585 // Determine what purity to check a nested function under
4586 pub fn determine_inherited_purity(parent: (ast::Purity, ast::NodeId),
4587 child: (ast::Purity, ast::NodeId),
4588 child_sigil: ast::Sigil)
4589 -> (ast::Purity, ast::NodeId) {
4590 // If the closure is a stack closure and hasn't had some non-standard
4591 // purity inferred for it, then check it under its parent's purity.
4592 // Otherwise, use its own
4594 ast::BorrowedSigil if child.val0() == ast::ImpureFn => parent,
4599 // Iterate over a type parameter's bounded traits and any supertraits
4600 // of those traits, ignoring kinds.
4601 // Here, the supertraits are the transitive closure of the supertrait
4602 // relation on the supertraits from each bounded trait's constraint
4604 pub fn each_bound_trait_and_supertraits(tcx: ctxt,
4605 bounds: &[@TraitRef],
4606 f: |@TraitRef| -> bool)
4608 for &bound_trait_ref in bounds.iter() {
4609 let mut supertrait_set = HashMap::new();
4610 let mut trait_refs = ~[];
4613 // Seed the worklist with the trait from the bound
4614 supertrait_set.insert(bound_trait_ref.def_id, ());
4615 trait_refs.push(bound_trait_ref);
4617 // Add the given trait ty to the hash map
4618 while i < trait_refs.len() {
4619 debug!("each_bound_trait_and_supertraits(i={:?}, trait_ref={})",
4620 i, trait_refs[i].repr(tcx));
4622 if !f(trait_refs[i]) {
4626 // Add supertraits to supertrait_set
4627 let supertrait_refs = trait_ref_supertraits(tcx, trait_refs[i]);
4628 for &supertrait_ref in supertrait_refs.iter() {
4629 debug!("each_bound_trait_and_supertraits(supertrait_ref={})",
4630 supertrait_ref.repr(tcx));
4632 let d_id = supertrait_ref.def_id;
4633 if !supertrait_set.contains_key(&d_id) {
4634 // FIXME(#5527) Could have same trait multiple times
4635 supertrait_set.insert(d_id, ());
4636 trait_refs.push(supertrait_ref);
4646 pub fn count_traits_and_supertraits(tcx: ctxt,
4647 type_param_defs: &[TypeParameterDef]) -> uint {
4649 for type_param_def in type_param_defs.iter() {
4650 each_bound_trait_and_supertraits(
4651 tcx, type_param_def.bounds.trait_bounds, |_| {
4659 pub fn get_tydesc_ty(tcx: ctxt) -> Result<t, ~str> {
4660 tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
4661 let intrinsic_defs = tcx.intrinsic_defs.borrow();
4662 intrinsic_defs.get().find_copy(&tydesc_lang_item)
4663 .expect("Failed to resolve TyDesc")
4667 pub fn get_opaque_ty(tcx: ctxt) -> Result<t, ~str> {
4668 tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| {
4669 let intrinsic_defs = tcx.intrinsic_defs.borrow();
4670 intrinsic_defs.get().find_copy(&opaque_lang_item)
4671 .expect("Failed to resolve Opaque")
4675 pub fn visitor_object_ty(tcx: ctxt,
4676 region: ty::Region) -> Result<(@TraitRef, t), ~str> {
4677 let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) {
4679 Err(s) => { return Err(s); }
4681 let substs = substs {
4682 regions: ty::NonerasedRegions(opt_vec::Empty),
4686 let trait_ref = @TraitRef { def_id: trait_lang_item, substs: substs };
4690 trait_ref.substs.clone(),
4691 RegionTraitStore(region),
4693 EmptyBuiltinBounds())))
4696 pub fn item_variances(tcx: ctxt, item_id: ast::DefId) -> @ItemVariances {
4697 let mut item_variance_map = tcx.item_variance_map.borrow_mut();
4698 lookup_locally_or_in_crate_store(
4699 "item_variance_map", item_id, item_variance_map.get(),
4700 || @csearch::get_item_variances(tcx.cstore, item_id))
4703 /// Records a trait-to-implementation mapping.
4704 fn record_trait_implementation(tcx: ctxt,
4705 trait_def_id: DefId,
4706 implementation: @Impl) {
4707 let implementation_list;
4708 let mut trait_impls = tcx.trait_impls.borrow_mut();
4709 match trait_impls.get().find(&trait_def_id) {
4711 implementation_list = @RefCell::new(~[]);
4712 trait_impls.get().insert(trait_def_id, implementation_list);
4714 Some(&existing_implementation_list) => {
4715 implementation_list = existing_implementation_list
4719 let mut implementation_list = implementation_list.borrow_mut();
4720 implementation_list.get().push(implementation);
4723 /// Populates the type context with all the implementations for the given type
4725 pub fn populate_implementations_for_type_if_necessary(tcx: ctxt,
4726 type_id: ast::DefId) {
4727 if type_id.krate == LOCAL_CRATE {
4731 let populated_external_types = tcx.populated_external_types.borrow();
4732 if populated_external_types.get().contains(&type_id) {
4737 csearch::each_implementation_for_type(tcx.sess.cstore, type_id,
4738 |implementation_def_id| {
4739 let implementation = @csearch::get_impl(tcx, implementation_def_id);
4741 // Record the trait->implementation mappings, if applicable.
4742 let associated_traits = csearch::get_impl_trait(tcx,
4743 implementation.did);
4744 for trait_ref in associated_traits.iter() {
4745 record_trait_implementation(tcx,
4750 // For any methods that use a default implementation, add them to
4751 // the map. This is a bit unfortunate.
4752 for method in implementation.methods.iter() {
4753 for source in method.provided_source.iter() {
4754 let mut provided_method_sources =
4755 tcx.provided_method_sources.borrow_mut();
4756 provided_method_sources.get().insert(method.def_id, *source);
4760 // If this is an inherent implementation, record it.
4761 if associated_traits.is_none() {
4762 let implementation_list;
4763 let mut inherent_impls = tcx.inherent_impls.borrow_mut();
4764 match inherent_impls.get().find(&type_id) {
4766 implementation_list = @RefCell::new(~[]);
4767 inherent_impls.get().insert(type_id, implementation_list);
4769 Some(&existing_implementation_list) => {
4770 implementation_list = existing_implementation_list;
4774 let mut implementation_list =
4775 implementation_list.borrow_mut();
4776 implementation_list.get().push(implementation);
4780 // Store the implementation info.
4781 let mut impls = tcx.impls.borrow_mut();
4782 impls.get().insert(implementation_def_id, implementation);
4785 let mut populated_external_types = tcx.populated_external_types
4787 populated_external_types.get().insert(type_id);
4790 /// Populates the type context with all the implementations for the given
4791 /// trait if necessary.
4792 pub fn populate_implementations_for_trait_if_necessary(
4794 trait_id: ast::DefId) {
4795 if trait_id.krate == LOCAL_CRATE {
4799 let populated_external_traits = tcx.populated_external_traits
4801 if populated_external_traits.get().contains(&trait_id) {
4806 csearch::each_implementation_for_trait(tcx.sess.cstore, trait_id,
4807 |implementation_def_id| {
4808 let implementation = @csearch::get_impl(tcx, implementation_def_id);
4810 // Record the trait->implementation mapping.
4811 record_trait_implementation(tcx, trait_id, implementation);
4813 // For any methods that use a default implementation, add them to
4814 // the map. This is a bit unfortunate.
4815 for method in implementation.methods.iter() {
4816 for source in method.provided_source.iter() {
4817 let mut provided_method_sources =
4818 tcx.provided_method_sources.borrow_mut();
4819 provided_method_sources.get().insert(method.def_id, *source);
4823 // Store the implementation info.
4824 let mut impls = tcx.impls.borrow_mut();
4825 impls.get().insert(implementation_def_id, implementation);
4828 let mut populated_external_traits = tcx.populated_external_traits
4830 populated_external_traits.get().insert(trait_id);
4833 /// Given the def_id of an impl, return the def_id of the trait it implements.
4834 /// If it implements no trait, return `None`.
4835 pub fn trait_id_of_impl(tcx: ctxt,
4836 def_id: ast::DefId) -> Option<ast::DefId> {
4837 let node = match tcx.map.find(def_id.node) {
4842 ast_map::NodeItem(item) => {
4844 ast::ItemImpl(_, Some(ref trait_ref), _, _) => {
4845 Some(node_id_to_trait_ref(tcx, trait_ref.ref_id).def_id)
4854 /// If the given def ID describes a method belonging to a trait (either a
4855 /// default method or an implementation of a trait method), return the ID of
4856 /// the trait that the method belongs to. Otherwise, return `None`.
4857 pub fn trait_of_method(tcx: ctxt, def_id: ast::DefId)
4858 -> Option<ast::DefId> {
4859 if def_id.krate != LOCAL_CRATE {
4860 return csearch::get_trait_of_method(tcx.cstore, def_id, tcx);
4864 let methods = tcx.methods.borrow();
4865 method = methods.get().find(&def_id).map(|method| *method);
4869 match method.container {
4870 TraitContainer(def_id) => Some(def_id),
4871 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
4878 /// If the given def ID describes a method belonging to a trait, (either a
4879 /// default method or an implementation of a trait method), return the ID of
4880 /// the method inside trait definition (this means that if the given def ID
4881 /// is already that of the original trait method, then the return value is
4883 /// Otherwise, return `None`.
4884 pub fn trait_method_of_method(tcx: ctxt,
4885 def_id: ast::DefId) -> Option<ast::DefId> {
4888 let methods = tcx.methods.borrow();
4889 match methods.get().find(&def_id) {
4890 Some(m) => method = *m,
4891 None => return None,
4894 let name = method.ident.name;
4895 match trait_of_method(tcx, def_id) {
4896 Some(trait_did) => {
4897 let trait_methods = ty::trait_methods(tcx, trait_did);
4898 trait_methods.iter()
4899 .position(|m| m.ident.name == name)
4900 .map(|idx| ty::trait_method(tcx, trait_did, idx).def_id)
4906 /// Creates a hash of the type `t` which will be the same no matter what crate
4907 /// context it's calculated within. This is used by the `type_id` intrinsic.
4908 pub fn hash_crate_independent(tcx: ctxt, t: t, svh: &Svh) -> u64 {
4909 let mut state = sip::SipState::new();
4910 macro_rules! byte( ($b:expr) => { ($b as u8).hash(&mut state) } );
4911 macro_rules! hash( ($e:expr) => { $e.hash(&mut state) } );
4913 let region = |_state: &mut sip::SipState, r: Region| {
4923 tcx.sess.bug("non-static region found when hashing a type")
4927 let vstore = |state: &mut sip::SipState, v: vstore| {
4929 vstore_fixed(_) => 0u8.hash(state),
4930 vstore_uniq => 1u8.hash(state),
4931 vstore_slice(r) => {
4937 let did = |state: &mut sip::SipState, did: DefId| {
4938 let h = if ast_util::is_local(did) {
4941 tcx.sess.cstore.get_crate_hash(did.krate)
4943 h.as_str().hash(state);
4944 did.node.hash(state);
4946 let mt = |state: &mut sip::SipState, mt: mt| {
4947 mt.mutbl.hash(state);
4949 ty::walk_ty(t, |t| {
4950 match ty::get(t).sty {
4953 ty_bool => byte!(2),
4954 ty_char => byte!(3),
4984 vstore(&mut state, v);
4992 region(&mut state, r);
4995 ty_bare_fn(ref b) => {
5000 ty_closure(ref c) => {
5006 region(&mut state, c.region);
5008 ty_trait(d, _, store, m, bounds) => {
5012 UniqTraitStore => byte!(0),
5013 RegionTraitStore(r) => {
5015 region(&mut state, r);
5021 ty_struct(d, _) => {
5025 ty_tup(ref inner) => {
5032 did(&mut state, p.def_id);
5038 ty_infer(_) => unreachable!(),
5039 ty_err => byte!(23),
5040 ty_unboxed_vec(m) => {
5051 pub fn to_str(self) -> &'static str {
5054 Contravariant => "-",
5061 pub fn construct_parameter_environment(
5063 self_bound: Option<@TraitRef>,
5064 item_type_params: &[TypeParameterDef],
5065 method_type_params: &[TypeParameterDef],
5066 item_region_params: &[RegionParameterDef],
5067 free_id: ast::NodeId)
5068 -> ParameterEnvironment
5070 /*! See `ParameterEnvironment` struct def'n for details */
5073 // Construct the free substs.
5077 let self_ty = self_bound.map(|t| ty::mk_self(tcx, t.def_id));
5080 let num_item_type_params = item_type_params.len();
5081 let num_method_type_params = method_type_params.len();
5082 let num_type_params = num_item_type_params + num_method_type_params;
5083 let type_params = vec::from_fn(num_type_params, |i| {
5084 let def_id = if i < num_item_type_params {
5085 item_type_params[i].def_id
5087 method_type_params[i - num_item_type_params].def_id
5090 ty::mk_param(tcx, i, def_id)
5093 // map bound 'a => free 'a
5094 let region_params = item_region_params.iter().
5095 map(|r| ty::ReFree(ty::FreeRegion {
5097 bound_region: ty::BrNamed(r.def_id, r.ident)})).
5100 let free_substs = substs {
5103 regions: ty::NonerasedRegions(region_params)
5107 // Compute the bounds on Self and the type parameters.
5110 let self_bound_substd = self_bound.map(|b| b.subst(tcx, &free_substs));
5111 let type_param_bounds_substd = vec::from_fn(num_type_params, |i| {
5112 if i < num_item_type_params {
5113 (*item_type_params[i].bounds).subst(tcx, &free_substs)
5115 let j = i - num_item_type_params;
5116 (*method_type_params[j].bounds).subst(tcx, &free_substs)
5120 ty::ParameterEnvironment {
5121 free_substs: free_substs,
5122 self_param_bound: self_bound_substd,
5123 type_param_bounds: type_param_bounds_substd,
5128 pub fn empty() -> substs {
5132 regions: NonerasedRegions(opt_vec::Empty)
5138 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
5140 ast::MutMutable => MutBorrow,
5141 ast::MutImmutable => ImmBorrow,
5145 pub fn to_user_str(&self) -> &'static str {
5147 MutBorrow => "mutable",
5148 ImmBorrow => "immutable",
5149 UniqueImmBorrow => "uniquely immutable",
5153 pub fn to_short_str(&self) -> &'static str {
5157 UniqueImmBorrow => "own",