1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(non_camel_case_types)]
14 use driver::session::Session;
15 use metadata::csearch;
16 use middle::const_eval;
17 use middle::lang_items::{ExchangeHeapLangItem, OpaqueStructLangItem};
18 use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem};
21 use middle::resolve_lifetime;
23 use middle::subst::Subst;
25 use middle::typeck::{MethodCall, MethodCallee, MethodMap};
27 use middle::ty_fold::TypeFolder;
29 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_str};
30 use util::ppaux::{trait_store_to_str, ty_to_str, vstore_to_str};
31 use util::ppaux::{Repr, UserString};
32 use util::common::{indenter};
33 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet, FnvHashMap};
36 use std::cell::{Cell, RefCell};
40 use std::hash::{Hash, sip};
43 use collections::{HashMap, HashSet};
45 use syntax::ast_util::{is_local, lit_is_str};
48 use syntax::attr::AttrMetaMethods;
49 use syntax::codemap::Span;
50 use syntax::parse::token;
51 use syntax::parse::token::InternedString;
52 use syntax::{ast, ast_map};
53 use syntax::owned_slice::OwnedSlice;
54 use syntax::abi::AbiSet;
56 use collections::enum_set::{EnumSet, CLike};
60 pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0;
64 #[deriving(Eq, TotalEq, Hash)]
66 pub ident: ast::Ident,
71 pub enum MethodContainer {
72 TraitContainer(ast::DefId),
73 ImplContainer(ast::DefId),
78 pub ident: ast::Ident,
79 pub generics: ty::Generics,
81 pub explicit_self: ast::ExplicitSelf_,
82 pub vis: ast::Visibility,
83 pub def_id: ast::DefId,
84 pub container: MethodContainer,
86 // If this method is provided, we need to know where it came from
87 pub provided_source: Option<ast::DefId>
91 pub fn new(ident: ast::Ident,
92 generics: ty::Generics,
94 explicit_self: ast::ExplicitSelf_,
97 container: MethodContainer,
98 provided_source: Option<ast::DefId>)
104 explicit_self: explicit_self,
107 container: container,
108 provided_source: provided_source
112 pub fn container_id(&self) -> ast::DefId {
113 match self.container {
114 TraitContainer(id) => id,
115 ImplContainer(id) => id,
123 pub methods: Vec<@Method>,
126 #[deriving(Clone, Eq, TotalEq, Hash)]
129 pub mutbl: ast::Mutability,
132 #[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash, Show)]
139 #[deriving(Clone, Eq, TotalEq, Hash, Encodable, Decodable, Show)]
140 pub enum TraitStore {
141 UniqTraitStore, // ~Trait
142 RegionTraitStore(Region), // &Trait
145 pub struct field_ty {
148 pub vis: ast::Visibility,
151 // Contains information needed to resolve types and (in the future) look up
152 // the types of AST nodes.
153 #[deriving(Eq, TotalEq, Hash)]
154 pub struct creader_cache_key {
160 pub type creader_cache = RefCell<HashMap<creader_cache_key, t>>;
162 pub struct intern_key {
166 // NB: Do not replace this with #[deriving(Eq)]. The automatically-derived
167 // implementation will not recurse through sty and you will get stack
169 impl cmp::Eq for intern_key {
170 fn eq(&self, other: &intern_key) -> bool {
172 *self.sty == *other.sty
175 fn ne(&self, other: &intern_key) -> bool {
180 impl TotalEq for intern_key {}
182 impl<W:Writer> Hash<W> for intern_key {
183 fn hash(&self, s: &mut W) {
184 unsafe { (*self.sty).hash(s) }
188 pub enum ast_ty_to_ty_cache_entry {
189 atttce_unresolved, /* not resolved yet */
190 atttce_resolved(t) /* resolved to a type, irrespective of region */
193 #[deriving(Clone, Eq, Decodable, Encodable)]
194 pub struct ItemVariances {
195 pub self_param: Option<Variance>,
196 pub type_params: OwnedSlice<Variance>,
197 pub region_params: OwnedSlice<Variance>
200 #[deriving(Clone, Eq, Decodable, Encodable, Show)]
202 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
203 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
204 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
205 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
208 pub enum AutoAdjustment {
209 AutoAddEnv(ty::Region, ast::Sigil),
210 AutoDerefRef(AutoDerefRef),
211 AutoObject(ast::Sigil, Option<ty::Region>,
214 ast::DefId, /* Trait ID */
215 ty::substs /* Trait substitutions */)
218 #[deriving(Decodable, Encodable)]
219 pub struct AutoDerefRef {
220 pub autoderefs: uint,
221 pub autoref: Option<AutoRef>
224 #[deriving(Decodable, Encodable, Eq, Show)]
226 /// Convert from T to &T
227 AutoPtr(Region, ast::Mutability),
229 /// Convert from ~[]/&[] to &[] (or str)
230 AutoBorrowVec(Region, ast::Mutability),
232 /// Convert from ~[]/&[] to &&[] (or str)
233 AutoBorrowVecRef(Region, ast::Mutability),
235 /// Convert from @fn()/~fn()/|| to ||
236 AutoBorrowFn(Region),
238 /// Convert from T to *T
239 AutoUnsafe(ast::Mutability),
241 /// Convert from ~Trait/&Trait to &Trait
242 AutoBorrowObj(Region, ast::Mutability),
245 /// The data structure to keep track of all the information that typechecker
246 /// generates so that so that it can be reused and doesn't have to be redone
249 // Specifically use a speedy hash algorithm for this hash map, it's used
251 pub interner: RefCell<FnvHashMap<intern_key, ~t_box_>>,
252 pub next_id: Cell<uint>,
254 pub def_map: resolve::DefMap,
256 pub named_region_map: resolve_lifetime::NamedRegionMap,
258 pub region_maps: middle::region::RegionMaps,
260 // Stores the types for various nodes in the AST. Note that this table
261 // is not guaranteed to be populated until after typeck. See
262 // typeck::check::fn_ctxt for details.
263 pub node_types: node_type_table,
265 // Stores the type parameters which were substituted to obtain the type
266 // of this node. This only applies to nodes that refer to entities
267 // parameterized by type parameters, such as generic fns, types, or
269 pub node_type_substs: RefCell<NodeMap<Vec<t>>>,
271 // Maps from a method to the method "descriptor"
272 pub methods: RefCell<DefIdMap<@Method>>,
274 // Maps from a trait def-id to a list of the def-ids of its methods
275 pub trait_method_def_ids: RefCell<DefIdMap<@Vec<DefId> >>,
277 // A cache for the trait_methods() routine
278 pub trait_methods_cache: RefCell<DefIdMap<@Vec<@Method> >>,
280 pub impl_trait_cache: RefCell<DefIdMap<Option<@ty::TraitRef>>>,
282 pub trait_refs: RefCell<NodeMap<@TraitRef>>,
283 pub trait_defs: RefCell<DefIdMap<@TraitDef>>,
285 pub map: ast_map::Map,
286 pub intrinsic_defs: RefCell<DefIdMap<t>>,
287 pub freevars: RefCell<freevars::freevar_map>,
288 pub tcache: type_cache,
289 pub rcache: creader_cache,
290 pub short_names_cache: RefCell<HashMap<t, ~str>>,
291 pub needs_unwind_cleanup_cache: RefCell<HashMap<t, bool>>,
292 pub tc_cache: RefCell<HashMap<uint, TypeContents>>,
293 pub ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry>>,
294 pub enum_var_cache: RefCell<DefIdMap<@Vec<@VariantInfo> >>,
295 pub ty_param_defs: RefCell<NodeMap<TypeParameterDef>>,
296 pub adjustments: RefCell<NodeMap<@AutoAdjustment>>,
297 pub normalized_cache: RefCell<HashMap<t, t>>,
298 pub lang_items: @middle::lang_items::LanguageItems,
299 // A mapping of fake provided method def_ids to the default implementation
300 pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
301 pub supertraits: RefCell<DefIdMap<@Vec<@TraitRef> >>,
303 // Maps from def-id of a type or region parameter to its
304 // (inferred) variance.
305 pub item_variance_map: RefCell<DefIdMap<@ItemVariances>>,
307 // A mapping from the def ID of an enum or struct type to the def ID
308 // of the method that implements its destructor. If the type is not
309 // present in this map, it does not have a destructor. This map is
310 // populated during the coherence phase of typechecking.
311 pub destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
313 // A method will be in this list if and only if it is a destructor.
314 pub destructors: RefCell<DefIdSet>,
316 // Maps a trait onto a list of impls of that trait.
317 pub trait_impls: RefCell<DefIdMap<@RefCell<Vec<@Impl> >>>,
319 // Maps a def_id of a type to a list of its inherent impls.
320 // Contains implementations of methods that are inherent to a type.
321 // Methods in these implementations don't need to be exported.
322 pub inherent_impls: RefCell<DefIdMap<@RefCell<Vec<@Impl> >>>,
324 // Maps a def_id of an impl to an Impl structure.
325 // Note that this contains all of the impls that we know about,
326 // including ones in other crates. It's not clear that this is the best
328 pub impls: RefCell<DefIdMap<@Impl>>,
330 // Set of used unsafe nodes (functions or blocks). Unsafe nodes not
331 // present in this set can be warned about.
332 pub used_unsafe: RefCell<NodeSet>,
334 // Set of nodes which mark locals as mutable which end up getting used at
335 // some point. Local variable definitions not in this set can be warned
337 pub used_mut_nodes: RefCell<NodeSet>,
339 // vtable resolution information for impl declarations
340 pub impl_vtables: typeck::impl_vtable_map,
342 // The set of external nominal types whose implementations have been read.
343 // This is used for lazy resolution of methods.
344 pub populated_external_types: RefCell<DefIdSet>,
346 // The set of external traits whose implementations have been read. This
347 // is used for lazy resolution of traits.
348 pub populated_external_traits: RefCell<DefIdSet>,
351 pub upvar_borrow_map: RefCell<UpvarBorrowMap>,
353 // These two caches are used by const_eval when decoding external statics
354 // and variants that are found.
355 pub extern_const_statics: RefCell<DefIdMap<Option<@ast::Expr>>>,
356 pub extern_const_variants: RefCell<DefIdMap<Option<@ast::Expr>>>,
367 // a meta-pub flag: subst may be required if the type has parameters, a self
368 // type, or references bound regions
369 needs_subst = 1 | 2 | 8
372 pub type t_box = &'static t_box_;
380 // To reduce refcounting cost, we're representing types as unsafe pointers
381 // throughout the compiler. These are simply casted t_box values. Use ty::get
382 // to cast them back to a box. (Without the cast, compiler performance suffers
383 // ~15%.) This does mean that a t value relies on the ctxt to keep its box
384 // alive, and using ty::get is unsafe when the ctxt is no longer alive.
387 #[allow(raw_pointer_deriving)]
388 #[deriving(Clone, Eq, TotalEq, Hash)]
389 pub struct t { inner: *t_opaque }
391 impl fmt::Show for t {
392 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
393 f.buf.write_str("*t_opaque")
397 pub fn get(t: t) -> t_box {
399 let t2: t_box = cast::transmute(t);
404 pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
405 (tb.flags & (flag as uint)) != 0u
407 pub fn type_has_params(t: t) -> bool {
408 tbox_has_flag(get(t), has_params)
410 pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
411 pub fn type_needs_infer(t: t) -> bool {
412 tbox_has_flag(get(t), needs_infer)
414 pub fn type_has_regions(t: t) -> bool {
415 tbox_has_flag(get(t), has_regions)
417 pub fn type_id(t: t) -> uint { get(t).id }
419 #[deriving(Clone, Eq, TotalEq, Hash)]
420 pub struct BareFnTy {
421 pub purity: ast::Purity,
426 #[deriving(Clone, Eq, TotalEq, Hash)]
427 pub struct ClosureTy {
428 pub purity: ast::Purity,
429 pub sigil: ast::Sigil,
430 pub onceness: ast::Onceness,
432 pub bounds: BuiltinBounds,
437 * Signature of a function type, which I have arbitrarily
438 * decided to use to refer to the input/output types.
440 * - `binder_id` is the node id where this fn type appeared;
441 * it is used to identify all the bound regions appearing
442 * in the input/output types that are bound by this fn type
443 * (vs some enclosing or enclosed fn type)
444 * - `inputs` is the list of arguments and their modes.
445 * - `output` is the return type.
446 * - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
448 #[deriving(Clone, Eq, TotalEq, Hash)]
450 pub binder_id: ast::NodeId,
456 #[deriving(Clone, Eq, TotalEq, Hash)]
457 pub struct param_ty {
462 /// Representation of regions:
463 #[deriving(Clone, Eq, TotalEq, Hash, Encodable, Decodable, Show)]
465 // Region bound in a type or fn declaration which will be
466 // substituted 'early' -- that is, at the same time when type
467 // parameters are substituted.
468 ReEarlyBound(/* param id */ ast::NodeId, /*index*/ uint, ast::Name),
470 // Region bound in a function scope, which will be substituted when the
471 // function is called. The first argument must be the `binder_id` of
472 // some enclosing function signature.
473 ReLateBound(/* binder_id */ ast::NodeId, BoundRegion),
475 /// When checking a function body, the types of all arguments and so forth
476 /// that refer to bound region parameters are modified to refer to free
477 /// region parameters.
480 /// A concrete region naming some expression within the current function.
483 /// Static data that has an "infinite" lifetime. Top in the region lattice.
486 /// A region variable. Should not exist after typeck.
487 ReInfer(InferRegion),
489 /// Empty lifetime is for data that is never accessed.
490 /// Bottom in the region lattice. We treat ReEmpty somewhat
491 /// specially; at least right now, we do not generate instances of
492 /// it during the GLB computations, but rather
493 /// generate an error instead. This is to improve error messages.
494 /// The only way to get an instance of ReEmpty is to have a region
495 /// variable with no constraints.
500 * Upvars do not get their own node-id. Instead, we use the pair of
501 * the original var id (that is, the root variable that is referenced
502 * by the upvar) and the id of the closure expression.
504 #[deriving(Clone, Eq, TotalEq, Hash)]
506 pub var_id: ast::NodeId,
507 pub closure_expr_id: ast::NodeId,
510 #[deriving(Clone, Eq, TotalEq, Hash)]
511 pub enum BorrowKind {
512 /// Data must be immutable and is aliasable.
515 /// Data must be immutable but not aliasable. This kind of borrow
516 /// cannot currently be expressed by the user and is used only in
517 /// implicit closure bindings. It is needed when you the closure
518 /// is borrowing or mutating a mutable referent, e.g.:
520 /// let x: &mut int = ...;
521 /// let y = || *x += 5;
523 /// If we were to try to translate this closure into a more explicit
524 /// form, we'd encounter an error with the code as written:
526 /// struct Env { x: & &mut int }
527 /// let x: &mut int = ...;
528 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
529 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
531 /// This is then illegal because you cannot mutate a `&mut` found
532 /// in an aliasable location. To solve, you'd have to translate with
533 /// an `&mut` borrow:
535 /// struct Env { x: & &mut int }
536 /// let x: &mut int = ...;
537 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
538 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
540 /// Now the assignment to `**env.x` is legal, but creating a
541 /// mutable pointer to `x` is not because `x` is not mutable. We
542 /// could fix this by declaring `x` as `let mut x`. This is ok in
543 /// user code, if awkward, but extra weird for closures, since the
544 /// borrow is hidden.
546 /// So we introduce a "unique imm" borrow -- the referent is
547 /// immutable, but not aliasable. This solves the problem. For
548 /// simplicity, we don't give users the way to express this
549 /// borrow, it's just used when translating closures.
552 /// Data is mutable and not aliasable.
557 * Information describing the borrowing of an upvar. This is computed
558 * during `typeck`, specifically by `regionck`. The general idea is
559 * that the compiler analyses treat closures like:
561 * let closure: &'e fn() = || {
562 * x = 1; // upvar x is assigned to
563 * use(y); // upvar y is read
564 * foo(&z); // upvar z is borrowed immutably
567 * as if they were "desugared" to something loosely like:
569 * struct Vars<'x,'y,'z> { x: &'x mut int,
572 * let closure: &'e fn() = {
578 * let env: &'e mut Vars<'x,'y,'z> = &mut Vars { x: &'x mut x,
584 * This is basically what happens at runtime. The closure is basically
585 * an existentially quantified version of the `(env, f)` pair.
587 * This data structure indicates the region and mutability of a single
588 * one of the `x...z` borrows.
590 * It may not be obvious why each borrowed variable gets its own
591 * lifetime (in the desugared version of the example, these are indicated
592 * by the lifetime parameters `'x`, `'y`, and `'z` in the `Vars` definition).
593 * Each such lifetime must encompass the lifetime `'e` of the closure itself,
594 * but need not be identical to it. The reason that this makes sense:
596 * - Callers are only permitted to invoke the closure, and hence to
597 * use the pointers, within the lifetime `'e`, so clearly `'e` must
598 * be a sublifetime of `'x...'z`.
599 * - The closure creator knows which upvars were borrowed by the closure
600 * and thus `x...z` will be reserved for `'x...'z` respectively.
601 * - Through mutation, the borrowed upvars can actually escape
602 * the closure, so sometimes it is necessary for them to be larger
603 * than the closure lifetime itself.
605 #[deriving(Eq, Clone)]
606 pub struct UpvarBorrow {
607 pub kind: BorrowKind,
608 pub region: ty::Region,
611 pub type UpvarBorrowMap = HashMap<UpvarId, UpvarBorrow>;
614 pub fn is_bound(&self) -> bool {
616 &ty::ReEarlyBound(..) => true,
617 &ty::ReLateBound(..) => true,
623 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd, Hash, Encodable, Decodable, Show)]
624 pub struct FreeRegion {
625 pub scope_id: NodeId,
626 pub bound_region: BoundRegion
629 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd, Hash, Encodable, Decodable, Show)]
630 pub enum BoundRegion {
631 /// An anonymous region parameter for a given fn (&T)
634 /// Named region parameters for functions (a in &'a T)
636 /// The def-id is needed to distinguish free regions in
637 /// the event of shadowing.
638 BrNamed(ast::DefId, ast::Name),
640 /// Fresh bound identifiers created during GLB computations.
645 * Represents the values to use when substituting lifetime parameters.
646 * If the value is `ErasedRegions`, then this subst is occurring during
647 * trans, and all region parameters will be replaced with `ty::ReStatic`. */
648 #[deriving(Clone, Eq, TotalEq, Hash)]
649 pub enum RegionSubsts {
651 NonerasedRegions(OwnedSlice<ty::Region>)
655 * The type substs represents the kinds of things that can be substituted to
656 * convert a polytype into a monotype. Note however that substituting bound
657 * regions other than `self` is done through a different mechanism:
659 * - `tps` represents the type parameters in scope. They are indexed
660 * according to the order in which they were declared.
662 * - `self_r` indicates the region parameter `self` that is present on nominal
663 * types (enums, structs) declared as having a region parameter. `self_r`
664 * should always be none for types that are not region-parameterized and
665 * Some(_) for types that are. The only bound region parameter that should
666 * appear within a region-parameterized type is `self`.
668 * - `self_ty` is the type to which `self` should be remapped, if any. The
669 * `self` type is rather funny in that it can only appear on traits and is
670 * always substituted away to the implementing type for a trait. */
671 #[deriving(Clone, Eq, TotalEq, Hash)]
673 pub self_ty: Option<ty::t>,
675 pub regions: RegionSubsts,
683 macro_rules! def_prim_ty(
684 ($name:ident, $sty:expr, $id:expr) => (
685 pub static $name: t_box_ = t_box_ {
693 def_prim_ty!(TY_NIL, super::ty_nil, 0)
694 def_prim_ty!(TY_BOOL, super::ty_bool, 1)
695 def_prim_ty!(TY_CHAR, super::ty_char, 2)
696 def_prim_ty!(TY_INT, super::ty_int(ast::TyI), 3)
697 def_prim_ty!(TY_I8, super::ty_int(ast::TyI8), 4)
698 def_prim_ty!(TY_I16, super::ty_int(ast::TyI16), 5)
699 def_prim_ty!(TY_I32, super::ty_int(ast::TyI32), 6)
700 def_prim_ty!(TY_I64, super::ty_int(ast::TyI64), 7)
701 def_prim_ty!(TY_UINT, super::ty_uint(ast::TyU), 8)
702 def_prim_ty!(TY_U8, super::ty_uint(ast::TyU8), 9)
703 def_prim_ty!(TY_U16, super::ty_uint(ast::TyU16), 10)
704 def_prim_ty!(TY_U32, super::ty_uint(ast::TyU32), 11)
705 def_prim_ty!(TY_U64, super::ty_uint(ast::TyU64), 12)
706 def_prim_ty!(TY_F32, super::ty_float(ast::TyF32), 14)
707 def_prim_ty!(TY_F64, super::ty_float(ast::TyF64), 15)
709 pub static TY_BOT: t_box_ = t_box_ {
712 flags: super::has_ty_bot as uint,
715 pub static TY_ERR: t_box_ = t_box_ {
718 flags: super::has_ty_err as uint,
721 pub static LAST_PRIMITIVE_ID: uint = 18;
724 // NB: If you change this, you'll probably want to change the corresponding
725 // AST structure in libsyntax/ast.rs as well.
726 #[deriving(Clone, Eq, TotalEq, Hash)]
733 ty_uint(ast::UintTy),
734 ty_float(ast::FloatTy),
736 ty_enum(DefId, substs),
742 ty_bare_fn(BareFnTy),
743 ty_closure(~ClosureTy),
745 ty_struct(DefId, substs),
748 ty_param(param_ty), // type parameter
749 ty_self(DefId), /* special, implicit `self` type parameter;
750 * def_id is the id of the trait */
752 ty_infer(InferTy), // something used only during inference/typeck
753 ty_err, // Also only used during inference/typeck, to represent
754 // the type of an erroneous expression (helps cut down
755 // on non-useful type error messages)
757 // "Fake" types, used for trans purposes
761 #[deriving(Clone, Eq, TotalEq, Hash)]
765 pub store: TraitStore,
766 pub mutability: ast::Mutability,
767 pub bounds: BuiltinBounds
770 #[deriving(Eq, TotalEq, Hash)]
771 pub struct TraitRef {
776 #[deriving(Clone, Eq)]
777 pub enum IntVarValue {
779 UintType(ast::UintTy),
782 #[deriving(Clone, Show)]
783 pub enum terr_vstore_kind {
790 #[deriving(Clone, Show)]
791 pub struct expected_found<T> {
796 // Data structures used in type unification
797 #[deriving(Clone, Show)]
800 terr_purity_mismatch(expected_found<Purity>),
801 terr_onceness_mismatch(expected_found<Onceness>),
802 terr_abi_mismatch(expected_found<AbiSet>),
804 terr_sigil_mismatch(expected_found<ast::Sigil>),
809 terr_tuple_size(expected_found<uint>),
810 terr_ty_param_size(expected_found<uint>),
811 terr_record_size(expected_found<uint>),
812 terr_record_mutability,
813 terr_record_fields(expected_found<Ident>),
815 terr_regions_does_not_outlive(Region, Region),
816 terr_regions_not_same(Region, Region),
817 terr_regions_no_overlap(Region, Region),
818 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
819 terr_regions_overly_polymorphic(BoundRegion, Region),
820 terr_vstores_differ(terr_vstore_kind, expected_found<vstore>),
821 terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
822 terr_in_field(@type_err, ast::Ident),
823 terr_sorts(expected_found<t>),
824 terr_integer_as_char,
825 terr_int_mismatch(expected_found<IntVarValue>),
826 terr_float_mismatch(expected_found<ast::FloatTy>),
827 terr_traits(expected_found<ast::DefId>),
828 terr_builtin_bounds(expected_found<BuiltinBounds>),
829 terr_variadic_mismatch(expected_found<bool>)
832 #[deriving(Eq, TotalEq, Hash)]
833 pub struct ParamBounds {
834 pub builtin_bounds: BuiltinBounds,
835 pub trait_bounds: Vec<@TraitRef> }
837 pub type BuiltinBounds = EnumSet<BuiltinBound>;
839 #[deriving(Clone, Encodable, Eq, TotalEq, Decodable, Hash, Show)]
841 pub enum BuiltinBound {
849 pub fn EmptyBuiltinBounds() -> BuiltinBounds {
853 pub fn AllBuiltinBounds() -> BuiltinBounds {
854 let mut set = EnumSet::empty();
855 set.add(BoundStatic);
862 impl CLike for BuiltinBound {
863 fn to_uint(&self) -> uint {
866 fn from_uint(v: uint) -> BuiltinBound {
867 unsafe { cast::transmute(v) }
871 #[deriving(Clone, Eq, TotalEq, Hash)]
872 pub struct TyVid(uint);
874 #[deriving(Clone, Eq, TotalEq, Hash)]
875 pub struct IntVid(uint);
877 #[deriving(Clone, Eq, TotalEq, Hash)]
878 pub struct FloatVid(uint);
880 #[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
881 pub struct RegionVid {
885 #[deriving(Clone, Eq, TotalEq, Hash)]
892 #[deriving(Clone, Encodable, Decodable, TotalEq, Hash, Show)]
893 pub enum InferRegion {
895 ReSkolemized(uint, BoundRegion)
898 impl cmp::Eq for InferRegion {
899 fn eq(&self, other: &InferRegion) -> bool {
900 match ((*self), *other) {
901 (ReVar(rva), ReVar(rvb)) => {
904 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
910 fn ne(&self, other: &InferRegion) -> bool {
911 !((*self) == (*other))
916 fn to_uint(&self) -> uint;
920 fn to_uint(&self) -> uint { let TyVid(v) = *self; v }
923 impl fmt::Show for TyVid {
924 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
925 write!(f.buf, "<generic \\#{}>", self.to_uint())
929 impl Vid for IntVid {
930 fn to_uint(&self) -> uint { let IntVid(v) = *self; v }
933 impl fmt::Show for IntVid {
934 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
935 write!(f.buf, "<generic integer \\#{}>", self.to_uint())
939 impl Vid for FloatVid {
940 fn to_uint(&self) -> uint { let FloatVid(v) = *self; v }
943 impl fmt::Show for FloatVid {
944 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
945 write!(f.buf, "<generic float \\#{}>", self.to_uint())
949 impl Vid for RegionVid {
950 fn to_uint(&self) -> uint { self.id }
953 impl fmt::Show for RegionVid {
954 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
959 impl fmt::Show for FnSig {
960 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
961 // grr, without tcx not much we can do.
962 write!(f.buf, "(...)")
966 impl fmt::Show for InferTy {
967 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
969 TyVar(ref v) => v.fmt(f),
970 IntVar(ref v) => v.fmt(f),
971 FloatVar(ref v) => v.fmt(f),
976 impl fmt::Show for IntVarValue {
977 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
979 IntType(ref v) => v.fmt(f),
980 UintType(ref v) => v.fmt(f),
986 pub struct TypeParameterDef {
987 pub ident: ast::Ident,
988 pub def_id: ast::DefId,
989 pub bounds: @ParamBounds,
990 pub default: Option<ty::t>
993 #[deriving(Encodable, Decodable, Clone)]
994 pub struct RegionParameterDef {
996 pub def_id: ast::DefId,
999 /// Information about the type/lifetime parameters associated with an item.
1000 /// Analogous to ast::Generics.
1002 pub struct Generics {
1003 /// List of type parameters declared on the item.
1004 pub type_param_defs: Rc<Vec<TypeParameterDef>>,
1006 /// List of region parameters declared on the item.
1007 /// For a fn or method, only includes *early-bound* lifetimes.
1008 pub region_param_defs: Rc<Vec<RegionParameterDef>>,
1012 pub fn has_type_params(&self) -> bool {
1013 !self.type_param_defs.is_empty()
1015 pub fn type_param_defs<'a>(&'a self) -> &'a [TypeParameterDef] {
1016 self.type_param_defs.as_slice()
1018 pub fn region_param_defs<'a>(&'a self) -> &'a [RegionParameterDef] {
1019 self.region_param_defs.as_slice()
1023 /// When type checking, we use the `ParameterEnvironment` to track
1024 /// details about the type/lifetime parameters that are in scope.
1025 /// It primarily stores the bounds information.
1027 /// Note: This information might seem to be redundant with the data in
1028 /// `tcx.ty_param_defs`, but it is not. That table contains the
1029 /// parameter definitions from an "outside" perspective, but this
1030 /// struct will contain the bounds for a parameter as seen from inside
1031 /// the function body. Currently the only real distinction is that
1032 /// bound lifetime parameters are replaced with free ones, but in the
1033 /// future I hope to refine the representation of types so as to make
1034 /// more distinctions clearer.
1035 pub struct ParameterEnvironment {
1036 /// A substitution that can be applied to move from
1037 /// the "outer" view of a type or method to the "inner" view.
1038 /// In general, this means converting from bound parameters to
1039 /// free parameters. Since we currently represent bound/free type
1040 /// parameters in the same way, this only has an affect on regions.
1041 pub free_substs: ty::substs,
1043 /// Bound on the Self parameter
1044 pub self_param_bound: Option<@TraitRef>,
1046 /// Bounds on each numbered type parameter
1047 pub type_param_bounds: Vec<ParamBounds> ,
1052 /// - `bounds`: The list of bounds for each type parameter. The length of the
1053 /// list also tells you how many type parameters there are.
1055 /// - `rp`: true if the type is region-parameterized. Types can have at
1056 /// most one region parameter, always called `&self`.
1058 /// - `ty`: the base type. May have reference to the (unsubstituted) bound
1059 /// region `&self` or to (unsubstituted) ty_param types
1061 pub struct ty_param_bounds_and_ty {
1062 pub generics: Generics,
1066 /// As `ty_param_bounds_and_ty` but for a trait ref.
1067 pub struct TraitDef {
1068 pub generics: Generics,
1069 pub bounds: BuiltinBounds,
1070 pub trait_ref: @ty::TraitRef,
1073 pub struct ty_param_substs_and_ty {
1074 pub substs: ty::substs,
1078 pub type type_cache = RefCell<DefIdMap<ty_param_bounds_and_ty>>;
1080 pub type node_type_table = RefCell<HashMap<uint,t>>;
1082 pub fn mk_ctxt(s: Session,
1083 dm: resolve::DefMap,
1084 named_region_map: resolve_lifetime::NamedRegionMap,
1086 freevars: freevars::freevar_map,
1087 region_maps: middle::region::RegionMaps,
1088 lang_items: @middle::lang_items::LanguageItems)
1091 named_region_map: named_region_map,
1092 item_variance_map: RefCell::new(DefIdMap::new()),
1093 interner: RefCell::new(FnvHashMap::new()),
1094 next_id: Cell::new(primitives::LAST_PRIMITIVE_ID),
1097 region_maps: region_maps,
1098 node_types: RefCell::new(HashMap::new()),
1099 node_type_substs: RefCell::new(NodeMap::new()),
1100 trait_refs: RefCell::new(NodeMap::new()),
1101 trait_defs: RefCell::new(DefIdMap::new()),
1103 intrinsic_defs: RefCell::new(DefIdMap::new()),
1104 freevars: RefCell::new(freevars),
1105 tcache: RefCell::new(DefIdMap::new()),
1106 rcache: RefCell::new(HashMap::new()),
1107 short_names_cache: RefCell::new(HashMap::new()),
1108 needs_unwind_cleanup_cache: RefCell::new(HashMap::new()),
1109 tc_cache: RefCell::new(HashMap::new()),
1110 ast_ty_to_ty_cache: RefCell::new(NodeMap::new()),
1111 enum_var_cache: RefCell::new(DefIdMap::new()),
1112 methods: RefCell::new(DefIdMap::new()),
1113 trait_method_def_ids: RefCell::new(DefIdMap::new()),
1114 trait_methods_cache: RefCell::new(DefIdMap::new()),
1115 impl_trait_cache: RefCell::new(DefIdMap::new()),
1116 ty_param_defs: RefCell::new(NodeMap::new()),
1117 adjustments: RefCell::new(NodeMap::new()),
1118 normalized_cache: RefCell::new(HashMap::new()),
1119 lang_items: lang_items,
1120 provided_method_sources: RefCell::new(DefIdMap::new()),
1121 supertraits: RefCell::new(DefIdMap::new()),
1122 destructor_for_type: RefCell::new(DefIdMap::new()),
1123 destructors: RefCell::new(DefIdSet::new()),
1124 trait_impls: RefCell::new(DefIdMap::new()),
1125 inherent_impls: RefCell::new(DefIdMap::new()),
1126 impls: RefCell::new(DefIdMap::new()),
1127 used_unsafe: RefCell::new(NodeSet::new()),
1128 used_mut_nodes: RefCell::new(NodeSet::new()),
1129 impl_vtables: RefCell::new(DefIdMap::new()),
1130 populated_external_types: RefCell::new(DefIdSet::new()),
1131 populated_external_traits: RefCell::new(DefIdSet::new()),
1132 upvar_borrow_map: RefCell::new(HashMap::new()),
1133 extern_const_statics: RefCell::new(DefIdMap::new()),
1134 extern_const_variants: RefCell::new(DefIdMap::new()),
1138 // Type constructors
1140 // Interns a type/name combination, stores the resulting box in cx.interner,
1141 // and returns the box as cast to an unsafe ptr (see comments for t above).
1142 pub fn mk_t(cx: &ctxt, st: sty) -> t {
1143 // Check for primitive types.
1145 ty_nil => return mk_nil(),
1146 ty_err => return mk_err(),
1147 ty_bool => return mk_bool(),
1148 ty_int(i) => return mk_mach_int(i),
1149 ty_uint(u) => return mk_mach_uint(u),
1150 ty_float(f) => return mk_mach_float(f),
1151 ty_char => return mk_char(),
1152 ty_bot => return mk_bot(),
1156 let key = intern_key { sty: &st };
1158 match cx.interner.borrow().find(&key) {
1159 Some(t) => unsafe { return cast::transmute(&t.sty); },
1164 fn rflags(r: Region) -> uint {
1165 (has_regions as uint) | {
1167 ty::ReInfer(_) => needs_infer as uint,
1172 fn sflags(substs: &substs) -> uint {
1174 for tt in substs.tps.iter() { f |= get(*tt).flags; }
1175 match substs.regions {
1177 NonerasedRegions(ref regions) => {
1178 for r in regions.iter() {
1186 &ty_str(vstore_slice(r)) => {
1189 &ty_vec(ref mt, vstore_slice(r)) => {
1191 flags |= get(mt.ty).flags;
1193 &ty_nil | &ty_bool | &ty_char | &ty_int(_) | &ty_float(_) | &ty_uint(_) |
1195 // You might think that we could just return ty_err for
1196 // any type containing ty_err as a component, and get
1197 // rid of the has_ty_err flag -- likewise for ty_bot (with
1198 // the exception of function types that return bot).
1199 // But doing so caused sporadic memory corruption, and
1200 // neither I (tjc) nor nmatsakis could figure out why,
1201 // so we're doing it this way.
1202 &ty_bot => flags |= has_ty_bot as uint,
1203 &ty_err => flags |= has_ty_err as uint,
1204 &ty_param(_) => flags |= has_params as uint,
1205 &ty_infer(_) => flags |= needs_infer as uint,
1206 &ty_self(_) => flags |= has_self as uint,
1207 &ty_enum(_, ref substs) | &ty_struct(_, ref substs) |
1208 &ty_trait(~ty::TyTrait { ref substs, .. }) => {
1209 flags |= sflags(substs);
1211 ty_trait(~ty::TyTrait { store: RegionTraitStore(r), .. }) => {
1217 &ty_box(tt) | &ty_uniq(tt) => {
1218 flags |= get(tt).flags
1220 &ty_vec(ref m, _) | &ty_ptr(ref m) |
1221 &ty_unboxed_vec(ref m) => {
1222 flags |= get(m.ty).flags;
1224 &ty_rptr(r, ref m) => {
1226 flags |= get(m.ty).flags;
1228 &ty_tup(ref ts) => for tt in ts.iter() { flags |= get(*tt).flags; },
1229 &ty_bare_fn(ref f) => {
1230 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1231 flags |= get(f.sig.output).flags;
1232 // T -> _|_ is *not* _|_ !
1233 flags &= !(has_ty_bot as uint);
1235 &ty_closure(ref f) => {
1236 flags |= rflags(f.region);
1237 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1238 flags |= get(f.sig.output).flags;
1239 // T -> _|_ is *not* _|_ !
1240 flags &= !(has_ty_bot as uint);
1246 id: cx.next_id.get(),
1250 let sty_ptr = &t.sty as *sty;
1252 let key = intern_key {
1256 cx.interner.borrow_mut().insert(key, t);
1258 cx.next_id.set(cx.next_id.get() + 1);
1261 cast::transmute::<*sty, t>(sty_ptr)
1266 pub fn mk_prim_t(primitive: &'static t_box_) -> t {
1268 cast::transmute::<&'static t_box_, t>(primitive)
1273 pub fn mk_nil() -> t { mk_prim_t(&primitives::TY_NIL) }
1276 pub fn mk_err() -> t { mk_prim_t(&primitives::TY_ERR) }
1279 pub fn mk_bot() -> t { mk_prim_t(&primitives::TY_BOT) }
1282 pub fn mk_bool() -> t { mk_prim_t(&primitives::TY_BOOL) }
1285 pub fn mk_int() -> t { mk_prim_t(&primitives::TY_INT) }
1288 pub fn mk_i8() -> t { mk_prim_t(&primitives::TY_I8) }
1291 pub fn mk_i16() -> t { mk_prim_t(&primitives::TY_I16) }
1294 pub fn mk_i32() -> t { mk_prim_t(&primitives::TY_I32) }
1297 pub fn mk_i64() -> t { mk_prim_t(&primitives::TY_I64) }
1300 pub fn mk_f32() -> t { mk_prim_t(&primitives::TY_F32) }
1303 pub fn mk_f64() -> t { mk_prim_t(&primitives::TY_F64) }
1306 pub fn mk_uint() -> t { mk_prim_t(&primitives::TY_UINT) }
1309 pub fn mk_u8() -> t { mk_prim_t(&primitives::TY_U8) }
1312 pub fn mk_u16() -> t { mk_prim_t(&primitives::TY_U16) }
1315 pub fn mk_u32() -> t { mk_prim_t(&primitives::TY_U32) }
1318 pub fn mk_u64() -> t { mk_prim_t(&primitives::TY_U64) }
1320 pub fn mk_mach_int(tm: ast::IntTy) -> t {
1322 ast::TyI => mk_int(),
1323 ast::TyI8 => mk_i8(),
1324 ast::TyI16 => mk_i16(),
1325 ast::TyI32 => mk_i32(),
1326 ast::TyI64 => mk_i64(),
1330 pub fn mk_mach_uint(tm: ast::UintTy) -> t {
1332 ast::TyU => mk_uint(),
1333 ast::TyU8 => mk_u8(),
1334 ast::TyU16 => mk_u16(),
1335 ast::TyU32 => mk_u32(),
1336 ast::TyU64 => mk_u64(),
1340 pub fn mk_mach_float(tm: ast::FloatTy) -> t {
1342 ast::TyF32 => mk_f32(),
1343 ast::TyF64 => mk_f64(),
1348 pub fn mk_char() -> t { mk_prim_t(&primitives::TY_CHAR) }
1350 pub fn mk_str(cx: &ctxt, t: vstore) -> t {
1354 pub fn mk_enum(cx: &ctxt, did: ast::DefId, substs: substs) -> t {
1355 // take a copy of substs so that we own the vectors inside
1356 mk_t(cx, ty_enum(did, substs))
1359 pub fn mk_box(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_box(ty)) }
1361 pub fn mk_uniq(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_uniq(ty)) }
1363 pub fn mk_ptr(cx: &ctxt, tm: mt) -> t { mk_t(cx, ty_ptr(tm)) }
1365 pub fn mk_rptr(cx: &ctxt, r: Region, tm: mt) -> t { mk_t(cx, ty_rptr(r, tm)) }
1367 pub fn mk_mut_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1368 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
1370 pub fn mk_imm_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1371 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
1374 pub fn mk_mut_ptr(cx: &ctxt, ty: t) -> t {
1375 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
1378 pub fn mk_imm_ptr(cx: &ctxt, ty: t) -> t {
1379 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
1382 pub fn mk_nil_ptr(cx: &ctxt) -> t {
1383 mk_ptr(cx, mt {ty: mk_nil(), mutbl: ast::MutImmutable})
1386 pub fn mk_vec(cx: &ctxt, tm: mt, t: vstore) -> t {
1387 mk_t(cx, ty_vec(tm, t))
1390 pub fn mk_unboxed_vec(cx: &ctxt, tm: mt) -> t {
1391 mk_t(cx, ty_unboxed_vec(tm))
1393 pub fn mk_mut_unboxed_vec(cx: &ctxt, ty: t) -> t {
1394 mk_t(cx, ty_unboxed_vec(mt {ty: ty, mutbl: ast::MutImmutable}))
1397 pub fn mk_tup(cx: &ctxt, ts: Vec<t>) -> t { mk_t(cx, ty_tup(ts)) }
1399 pub fn mk_closure(cx: &ctxt, fty: ClosureTy) -> t {
1400 mk_t(cx, ty_closure(~fty))
1403 pub fn mk_bare_fn(cx: &ctxt, fty: BareFnTy) -> t {
1404 mk_t(cx, ty_bare_fn(fty))
1407 pub fn mk_ctor_fn(cx: &ctxt,
1408 binder_id: ast::NodeId,
1409 input_tys: &[ty::t],
1410 output: ty::t) -> t {
1411 let input_args = input_tys.iter().map(|t| *t).collect();
1414 purity: ast::ImpureFn,
1415 abis: AbiSet::Rust(),
1417 binder_id: binder_id,
1426 pub fn mk_trait(cx: &ctxt,
1430 mutability: ast::Mutability,
1431 bounds: BuiltinBounds)
1433 // take a copy of substs so that we own the vectors inside
1434 let inner = ~TyTrait {
1438 mutability: mutability,
1441 mk_t(cx, ty_trait(inner))
1444 pub fn mk_struct(cx: &ctxt, struct_id: ast::DefId, substs: substs) -> t {
1445 // take a copy of substs so that we own the vectors inside
1446 mk_t(cx, ty_struct(struct_id, substs))
1449 pub fn mk_var(cx: &ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) }
1451 pub fn mk_int_var(cx: &ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) }
1453 pub fn mk_float_var(cx: &ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) }
1455 pub fn mk_infer(cx: &ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) }
1457 pub fn mk_self(cx: &ctxt, did: ast::DefId) -> t { mk_t(cx, ty_self(did)) }
1459 pub fn mk_param(cx: &ctxt, n: uint, k: DefId) -> t {
1460 mk_t(cx, ty_param(param_ty { idx: n, def_id: k }))
1463 pub fn walk_ty(ty: t, f: |t|) {
1464 maybe_walk_ty(ty, |t| { f(t); true });
1467 pub fn maybe_walk_ty(ty: t, f: |t| -> bool) {
1472 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) |
1473 ty_str(_) | ty_self(_) |
1474 ty_infer(_) | ty_param(_) | ty_err => {}
1475 ty_box(ty) | ty_uniq(ty) => maybe_walk_ty(ty, f),
1476 ty_vec(ref tm, _) | ty_unboxed_vec(ref tm) | ty_ptr(ref tm) |
1477 ty_rptr(_, ref tm) => {
1478 maybe_walk_ty(tm.ty, f);
1480 ty_enum(_, ref substs) | ty_struct(_, ref substs) |
1481 ty_trait(~TyTrait { ref substs, .. }) => {
1482 for subty in (*substs).tps.iter() { maybe_walk_ty(*subty, |x| f(x)); }
1484 ty_tup(ref ts) => { for tt in ts.iter() { maybe_walk_ty(*tt, |x| f(x)); } }
1485 ty_bare_fn(ref ft) => {
1486 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1487 maybe_walk_ty(ft.sig.output, f);
1489 ty_closure(ref ft) => {
1490 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1491 maybe_walk_ty(ft.sig.output, f);
1496 // Folds types from the bottom up.
1497 pub fn fold_ty(cx: &ctxt, t0: t, fldop: |t| -> t) -> t {
1498 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
1502 pub fn walk_regions_and_ty(cx: &ctxt, ty: t, fldr: |r: Region|, fldt: |t: t|)
1504 ty_fold::RegionFolder::general(cx,
1506 |t| { fldt(t); t }).fold_ty(ty)
1509 pub fn fold_regions(cx: &ctxt, ty: t, fldr: |r: Region| -> Region) -> t {
1510 ty_fold::RegionFolder::regions(cx, fldr).fold_ty(ty)
1513 // Substitute *only* type parameters. Used in trans where regions are erased.
1514 pub fn subst_tps(tcx: &ctxt, tps: &[t], self_ty_opt: Option<t>, typ: t) -> t {
1515 let mut subst = TpsSubst { tcx: tcx, self_ty_opt: self_ty_opt, tps: tps };
1516 return subst.fold_ty(typ);
1518 struct TpsSubst<'a> {
1520 self_ty_opt: Option<t>,
1524 impl<'a> TypeFolder for TpsSubst<'a> {
1525 fn tcx<'a>(&'a self) -> &'a ctxt { self.tcx }
1527 fn fold_ty(&mut self, t: ty::t) -> ty::t {
1528 if self.tps.len() == 0u && self.self_ty_opt.is_none() {
1532 let tb = ty::get(t);
1533 if self.self_ty_opt.is_none() && !tbox_has_flag(tb, has_params) {
1537 match ty::get(t).sty {
1543 match self.self_ty_opt {
1544 None => self.tcx.sess.bug("ty_self unexpected here"),
1545 Some(self_ty) => self_ty
1550 ty_fold::super_fold_ty(self, t)
1557 pub fn substs_is_noop(substs: &substs) -> bool {
1558 let regions_is_noop = match substs.regions {
1559 ErasedRegions => false, // may be used to canonicalize
1560 NonerasedRegions(ref regions) => regions.is_empty()
1563 substs.tps.len() == 0u &&
1565 substs.self_ty.is_none()
1568 pub fn substs_to_str(cx: &ctxt, substs: &substs) -> ~str {
1572 pub fn subst(cx: &ctxt,
1576 typ.subst(cx, substs)
1581 pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil }
1583 pub fn type_is_bot(ty: t) -> bool {
1584 (get(ty).flags & (has_ty_bot as uint)) != 0
1587 pub fn type_is_error(ty: t) -> bool {
1588 (get(ty).flags & (has_ty_err as uint)) != 0
1591 pub fn type_needs_subst(ty: t) -> bool {
1592 tbox_has_flag(get(ty), needs_subst)
1595 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
1596 tref.substs.self_ty.iter().any(|&t| type_is_error(t)) ||
1597 tref.substs.tps.iter().any(|&t| type_is_error(t))
1600 pub fn type_is_ty_var(ty: t) -> bool {
1602 ty_infer(TyVar(_)) => true,
1607 pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool }
1609 pub fn type_is_self(ty: t) -> bool {
1611 ty_self(..) => true,
1616 pub fn type_is_structural(ty: t) -> bool {
1618 ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) | ty_trait(..) |
1619 ty_vec(_, vstore_fixed(_)) | ty_str(vstore_fixed(_)) |
1620 ty_vec(_, vstore_slice(_)) | ty_str(vstore_slice(_))
1626 pub fn type_is_sequence(ty: t) -> bool {
1628 ty_str(_) | ty_vec(_, _) => true,
1633 pub fn type_is_simd(cx: &ctxt, ty: t) -> bool {
1635 ty_struct(did, _) => lookup_simd(cx, did),
1640 pub fn type_is_str(ty: t) -> bool {
1647 pub fn sequence_element_type(cx: &ctxt, ty: t) -> t {
1649 ty_str(_) => return mk_mach_uint(ast::TyU8),
1650 ty_vec(mt, _) | ty_unboxed_vec(mt) => return mt.ty,
1651 _ => cx.sess.bug("sequence_element_type called on non-sequence value"),
1655 pub fn simd_type(cx: &ctxt, ty: t) -> t {
1657 ty_struct(did, ref substs) => {
1658 let fields = lookup_struct_fields(cx, did);
1659 lookup_field_type(cx, did, fields.get(0).id, substs)
1661 _ => fail!("simd_type called on invalid type")
1665 pub fn simd_size(cx: &ctxt, ty: t) -> uint {
1667 ty_struct(did, _) => {
1668 let fields = lookup_struct_fields(cx, did);
1671 _ => fail!("simd_size called on invalid type")
1675 pub fn get_element_type(ty: t, i: uint) -> t {
1677 ty_tup(ref ts) => return *ts.get(i),
1678 _ => fail!("get_element_type called on invalid type")
1682 pub fn type_is_box(ty: t) -> bool {
1684 ty_box(_) => return true,
1689 pub fn type_is_boxed(ty: t) -> bool {
1696 pub fn type_is_region_ptr(ty: t) -> bool {
1698 ty_rptr(_, _) => true,
1703 pub fn type_is_slice(ty: t) -> bool {
1705 ty_vec(_, vstore_slice(_)) | ty_str(vstore_slice(_)) => true,
1710 pub fn type_is_unique_box(ty: t) -> bool {
1712 ty_uniq(_) => return true,
1717 pub fn type_is_unsafe_ptr(ty: t) -> bool {
1719 ty_ptr(_) => return true,
1724 pub fn type_is_vec(ty: t) -> bool {
1725 return match get(ty).sty {
1726 ty_vec(_, _) | ty_unboxed_vec(_) => true,
1732 pub fn type_is_unique(ty: t) -> bool {
1734 ty_uniq(_) | ty_vec(_, vstore_uniq) | ty_str(vstore_uniq) => true,
1740 A scalar type is one that denotes an atomic datum, with no sub-components.
1741 (A ty_ptr is scalar because it represents a non-managed pointer, so its
1742 contents are abstract to rustc.)
1744 pub fn type_is_scalar(ty: t) -> bool {
1746 ty_nil | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
1747 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
1748 ty_bare_fn(..) | ty_ptr(_) => true,
1753 pub fn type_needs_drop(cx: &ctxt, ty: t) -> bool {
1754 type_contents(cx, ty).needs_drop(cx)
1757 // Some things don't need cleanups during unwinding because the
1758 // task can free them all at once later. Currently only things
1759 // that only contain scalars and shared boxes can avoid unwind
1761 pub fn type_needs_unwind_cleanup(cx: &ctxt, ty: t) -> bool {
1762 match cx.needs_unwind_cleanup_cache.borrow().find(&ty) {
1763 Some(&result) => return result,
1767 let mut tycache = HashSet::new();
1768 let needs_unwind_cleanup =
1769 type_needs_unwind_cleanup_(cx, ty, &mut tycache, false);
1770 cx.needs_unwind_cleanup_cache.borrow_mut().insert(ty, needs_unwind_cleanup);
1771 return needs_unwind_cleanup;
1774 fn type_needs_unwind_cleanup_(cx: &ctxt, ty: t,
1775 tycache: &mut HashSet<t>,
1776 encountered_box: bool) -> bool {
1778 // Prevent infinite recursion
1779 if !tycache.insert(ty) {
1783 let mut encountered_box = encountered_box;
1784 let mut needs_unwind_cleanup = false;
1785 maybe_walk_ty(ty, |ty| {
1786 let old_encountered_box = encountered_box;
1787 let result = match get(ty).sty {
1789 encountered_box = true;
1792 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
1793 ty_tup(_) | ty_ptr(_) => {
1796 ty_enum(did, ref substs) => {
1797 for v in (*enum_variants(cx, did)).iter() {
1798 for aty in v.args.iter() {
1799 let t = subst(cx, substs, *aty);
1800 needs_unwind_cleanup |=
1801 type_needs_unwind_cleanup_(cx, t, tycache,
1805 !needs_unwind_cleanup
1808 ty_str(vstore_uniq) |
1809 ty_vec(_, vstore_uniq) => {
1810 // Once we're inside a box, the annihilator will find
1811 // it and destroy it.
1812 if !encountered_box {
1813 needs_unwind_cleanup = true;
1820 needs_unwind_cleanup = true;
1825 encountered_box = old_encountered_box;
1829 return needs_unwind_cleanup;
1833 * Type contents is how the type checker reasons about kinds.
1834 * They track what kinds of things are found within a type. You can
1835 * think of them as kind of an "anti-kind". They track the kinds of values
1836 * and thinks that are contained in types. Having a larger contents for
1837 * a type tends to rule that type *out* from various kinds. For example,
1838 * a type that contains a reference is not sendable.
1840 * The reason we compute type contents and not kinds is that it is
1841 * easier for me (nmatsakis) to think about what is contained within
1842 * a type than to think about what is *not* contained within a type.
1844 pub struct TypeContents {
1848 macro_rules! def_type_content_sets(
1849 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
1851 use middle::ty::TypeContents;
1852 $(pub static $name: TypeContents = TypeContents { bits: $bits };)+
1857 def_type_content_sets!(
1859 None = 0b0000_0000__0000_0000__0000,
1861 // Things that are interior to the value (first nibble):
1862 InteriorUnsized = 0b0000_0000__0000_0000__0001,
1863 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
1864 // InteriorAll = 0b00000000__00000000__1111,
1866 // Things that are owned by the value (second and third nibbles):
1867 OwnsOwned = 0b0000_0000__0000_0001__0000,
1868 OwnsDtor = 0b0000_0000__0000_0010__0000,
1869 OwnsManaged /* see [1] below */ = 0b0000_0000__0000_0100__0000,
1870 OwnsAffine = 0b0000_0000__0000_1000__0000,
1871 OwnsAll = 0b0000_0000__1111_1111__0000,
1873 // Things that are reachable by the value in any way (fourth nibble):
1874 ReachesNonsendAnnot = 0b0000_0001__0000_0000__0000,
1875 ReachesBorrowed = 0b0000_0010__0000_0000__0000,
1876 // ReachesManaged /* see [1] below */ = 0b0000_0100__0000_0000__0000,
1877 ReachesMutable = 0b0000_1000__0000_0000__0000,
1878 ReachesNoShare = 0b0001_0000__0000_0000__0000,
1879 ReachesAll = 0b0001_1111__0000_0000__0000,
1881 // Things that cause values to *move* rather than *copy*
1882 Moves = 0b0000_0000__0000_1011__0000,
1884 // Things that mean drop glue is necessary
1885 NeedsDrop = 0b0000_0000__0000_0111__0000,
1887 // Things that prevent values from being sent
1889 // Note: For checking whether something is sendable, it'd
1890 // be sufficient to have ReachesManaged. However, we include
1891 // both ReachesManaged and OwnsManaged so that when
1892 // a parameter has a bound T:Send, we are able to deduce
1893 // that it neither reaches nor owns a managed pointer.
1894 Nonsendable = 0b0000_0111__0000_0100__0000,
1896 // Things that prevent values from being considered 'static
1897 Nonstatic = 0b0000_0010__0000_0000__0000,
1899 // Things that prevent values from being considered sized
1900 Nonsized = 0b0000_0000__0000_0000__0001,
1902 // Things that prevent values from being shared
1903 Nonsharable = 0b0001_0000__0000_0000__0000,
1905 // Things that make values considered not POD (would be same
1906 // as `Moves`, but for the fact that managed data `@` is
1907 // not considered POD)
1908 Noncopy = 0b0000_0000__0000_1111__0000,
1910 // Bits to set when a managed value is encountered
1912 // [1] Do not set the bits TC::OwnsManaged or
1913 // TC::ReachesManaged directly, instead reference
1914 // TC::Managed to set them both at once.
1915 Managed = 0b0000_0100__0000_0100__0000,
1918 All = 0b1111_1111__1111_1111__1111
1923 pub fn meets_bounds(&self, cx: &ctxt, bbs: BuiltinBounds) -> bool {
1924 bbs.iter().all(|bb| self.meets_bound(cx, bb))
1927 pub fn meets_bound(&self, cx: &ctxt, bb: BuiltinBound) -> bool {
1929 BoundStatic => self.is_static(cx),
1930 BoundSend => self.is_sendable(cx),
1931 BoundSized => self.is_sized(cx),
1932 BoundCopy => self.is_copy(cx),
1933 BoundShare => self.is_sharable(cx),
1937 pub fn when(&self, cond: bool) -> TypeContents {
1938 if cond {*self} else {TC::None}
1941 pub fn intersects(&self, tc: TypeContents) -> bool {
1942 (self.bits & tc.bits) != 0
1945 pub fn is_static(&self, _: &ctxt) -> bool {
1946 !self.intersects(TC::Nonstatic)
1949 pub fn is_sendable(&self, _: &ctxt) -> bool {
1950 !self.intersects(TC::Nonsendable)
1953 pub fn is_sharable(&self, _: &ctxt) -> bool {
1954 !self.intersects(TC::Nonsharable)
1957 pub fn owns_managed(&self) -> bool {
1958 self.intersects(TC::OwnsManaged)
1961 pub fn owns_owned(&self) -> bool {
1962 self.intersects(TC::OwnsOwned)
1965 pub fn is_sized(&self, _: &ctxt) -> bool {
1966 !self.intersects(TC::Nonsized)
1969 pub fn is_copy(&self, _: &ctxt) -> bool {
1970 !self.intersects(TC::Noncopy)
1973 pub fn interior_unsafe(&self) -> bool {
1974 self.intersects(TC::InteriorUnsafe)
1977 pub fn moves_by_default(&self, _: &ctxt) -> bool {
1978 self.intersects(TC::Moves)
1981 pub fn needs_drop(&self, _: &ctxt) -> bool {
1982 self.intersects(TC::NeedsDrop)
1985 pub fn owned_pointer(&self) -> TypeContents {
1987 * Includes only those bits that still apply
1988 * when indirected through a `~` pointer
1991 *self & (TC::OwnsAll | TC::ReachesAll))
1994 pub fn reference(&self, bits: TypeContents) -> TypeContents {
1996 * Includes only those bits that still apply
1997 * when indirected through a reference (`&`)
2000 *self & TC::ReachesAll)
2003 pub fn managed_pointer(&self) -> TypeContents {
2005 * Includes only those bits that still apply
2006 * when indirected through a managed pointer (`@`)
2009 *self & TC::ReachesAll)
2012 pub fn unsafe_pointer(&self) -> TypeContents {
2014 * Includes only those bits that still apply
2015 * when indirected through an unsafe pointer (`*`)
2017 *self & TC::ReachesAll
2020 pub fn union<T>(v: &[T], f: |&T| -> TypeContents) -> TypeContents {
2021 v.iter().fold(TC::None, |tc, t| tc | f(t))
2024 pub fn inverse(&self) -> TypeContents {
2025 TypeContents { bits: !self.bits }
2028 pub fn has_dtor(&self) -> bool {
2029 self.intersects(TC::OwnsDtor)
2033 impl ops::BitOr<TypeContents,TypeContents> for TypeContents {
2034 fn bitor(&self, other: &TypeContents) -> TypeContents {
2035 TypeContents {bits: self.bits | other.bits}
2039 impl ops::BitAnd<TypeContents,TypeContents> for TypeContents {
2040 fn bitand(&self, other: &TypeContents) -> TypeContents {
2041 TypeContents {bits: self.bits & other.bits}
2045 impl ops::Sub<TypeContents,TypeContents> for TypeContents {
2046 fn sub(&self, other: &TypeContents) -> TypeContents {
2047 TypeContents {bits: self.bits & !other.bits}
2051 impl fmt::Show for TypeContents {
2052 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2053 write!(f.buf, "TypeContents({:t})", self.bits)
2057 pub fn type_has_dtor(cx: &ctxt, t: ty::t) -> bool {
2058 type_contents(cx, t).has_dtor()
2061 pub fn type_is_static(cx: &ctxt, t: ty::t) -> bool {
2062 type_contents(cx, t).is_static(cx)
2065 pub fn type_is_sendable(cx: &ctxt, t: ty::t) -> bool {
2066 type_contents(cx, t).is_sendable(cx)
2069 pub fn type_interior_is_unsafe(cx: &ctxt, t: ty::t) -> bool {
2070 type_contents(cx, t).interior_unsafe()
2073 pub fn type_contents(cx: &ctxt, ty: t) -> TypeContents {
2074 let ty_id = type_id(ty);
2076 match cx.tc_cache.borrow().find(&ty_id) {
2077 Some(tc) => { return *tc; }
2081 let mut cache = HashMap::new();
2082 let result = tc_ty(cx, ty, &mut cache);
2084 cx.tc_cache.borrow_mut().insert(ty_id, result);
2089 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2091 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
2092 // private cache for this walk. This is needed in the case of cyclic
2095 // struct List { next: ~Option<List>, ... }
2097 // When computing the type contents of such a type, we wind up deeply
2098 // recursing as we go. So when we encounter the recursive reference
2099 // to List, we temporarily use TC::None as its contents. Later we'll
2100 // patch up the cache with the correct value, once we've computed it
2101 // (this is basically a co-inductive process, if that helps). So in
2102 // the end we'll compute TC::OwnsOwned, in this case.
2104 // The problem is, as we are doing the computation, we will also
2105 // compute an *intermediate* contents for, e.g., Option<List> of
2106 // TC::None. This is ok during the computation of List itself, but if
2107 // we stored this intermediate value into cx.tc_cache, then later
2108 // requests for the contents of Option<List> would also yield TC::None
2109 // which is incorrect. This value was computed based on the crutch
2110 // value for the type contents of list. The correct value is
2111 // TC::OwnsOwned. This manifested as issue #4821.
2112 let ty_id = type_id(ty);
2113 match cache.find(&ty_id) {
2114 Some(tc) => { return *tc; }
2117 match cx.tc_cache.borrow().find(&ty_id) { // Must check both caches!
2118 Some(tc) => { return *tc; }
2121 cache.insert(ty_id, TC::None);
2123 let result = match get(ty).sty {
2124 // Scalar and unique types are sendable, and durable
2125 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2126 ty_bare_fn(_) | ty::ty_char => {
2130 ty_str(vstore_uniq) => {
2134 ty_closure(ref c) => {
2135 closure_contents(cx, *c)
2139 tc_ty(cx, typ, cache).managed_pointer()
2143 tc_ty(cx, typ, cache).owned_pointer()
2146 ty_trait(~ty::TyTrait { store, mutability, bounds, .. }) => {
2147 object_contents(cx, store, mutability, bounds)
2151 tc_ty(cx, mt.ty, cache).unsafe_pointer()
2154 ty_rptr(r, ref mt) => {
2155 tc_ty(cx, mt.ty, cache).reference(
2156 borrowed_contents(r, mt.mutbl))
2159 ty_vec(mt, vstore_uniq) => {
2160 tc_mt(cx, mt, cache).owned_pointer()
2163 ty_vec(ref mt, vstore_slice(r)) => {
2164 tc_ty(cx, mt.ty, cache).reference(
2165 borrowed_contents(r, mt.mutbl))
2168 ty_vec(mt, vstore_fixed(_)) => {
2169 tc_mt(cx, mt, cache)
2172 ty_str(vstore_slice(r)) => {
2173 borrowed_contents(r, ast::MutImmutable)
2176 ty_str(vstore_fixed(_)) => {
2180 ty_struct(did, ref substs) => {
2181 let flds = struct_fields(cx, did, substs);
2183 TypeContents::union(flds.as_slice(),
2184 |f| tc_mt(cx, f.mt, cache));
2185 if ty::has_dtor(cx, did) {
2186 res = res | TC::OwnsDtor;
2188 apply_lang_items(cx, did, res)
2191 ty_tup(ref tys) => {
2192 TypeContents::union(tys.as_slice(),
2193 |ty| tc_ty(cx, *ty, cache))
2196 ty_enum(did, ref substs) => {
2197 let variants = substd_enum_variants(cx, did, substs);
2199 TypeContents::union(variants.as_slice(), |variant| {
2200 TypeContents::union(variant.args.as_slice(),
2202 tc_ty(cx, *arg_ty, cache)
2205 apply_lang_items(cx, did, res)
2209 // We only ever ask for the kind of types that are defined in
2210 // the current crate; therefore, the only type parameters that
2211 // could be in scope are those defined in the current crate.
2212 // If this assertion failures, it is likely because of a
2213 // failure in the cross-crate inlining code to translate a
2215 assert_eq!(p.def_id.krate, ast::LOCAL_CRATE);
2217 let ty_param_defs = cx.ty_param_defs.borrow();
2218 let tp_def = ty_param_defs.get(&p.def_id.node);
2219 kind_bounds_to_contents(cx,
2220 tp_def.bounds.builtin_bounds,
2221 tp_def.bounds.trait_bounds.as_slice())
2224 ty_self(def_id) => {
2225 // FIXME(#4678)---self should just be a ty param
2227 // Self may be bounded if the associated trait has builtin kinds
2228 // for supertraits. If so we can use those bounds.
2229 let trait_def = lookup_trait_def(cx, def_id);
2230 let traits = [trait_def.trait_ref];
2231 kind_bounds_to_contents(cx, trait_def.bounds, traits)
2235 // This occurs during coherence, but shouldn't occur at other
2239 ty_unboxed_vec(mt) => TC::InteriorUnsized | tc_mt(cx, mt, cache),
2242 cx.sess.bug("asked to compute contents of error type");
2246 cache.insert(ty_id, result);
2252 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2254 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
2255 mc | tc_ty(cx, mt.ty, cache)
2258 fn apply_lang_items(cx: &ctxt,
2262 if Some(did) == cx.lang_items.no_send_bound() {
2263 tc | TC::ReachesNonsendAnnot
2264 } else if Some(did) == cx.lang_items.managed_bound() {
2266 } else if Some(did) == cx.lang_items.no_copy_bound() {
2268 } else if Some(did) == cx.lang_items.no_share_bound() {
2269 tc | TC::ReachesNoShare
2270 } else if Some(did) == cx.lang_items.unsafe_type() {
2271 tc | TC::InteriorUnsafe
2277 fn borrowed_contents(region: ty::Region,
2278 mutbl: ast::Mutability)
2281 * Type contents due to containing a reference
2282 * with the region `region` and borrow kind `bk`
2285 let b = match mutbl {
2286 ast::MutMutable => TC::ReachesMutable | TC::OwnsAffine,
2287 ast::MutImmutable => TC::None,
2289 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
2292 fn closure_contents(cx: &ctxt, cty: &ClosureTy) -> TypeContents {
2293 // Closure contents are just like trait contents, but with potentially
2295 let st = match cty.sigil {
2296 ast::BorrowedSigil =>
2297 object_contents(cx, RegionTraitStore(cty.region), MutMutable, cty.bounds),
2299 object_contents(cx, UniqTraitStore, MutImmutable, cty.bounds),
2300 ast::ManagedSigil => unreachable!()
2303 // FIXME(#3569): This borrowed_contents call should be taken care of in
2304 // object_contents, after ~Traits and @Traits can have region bounds too.
2305 // This one here is redundant for &fns but important for ~fns and @fns.
2306 let rt = borrowed_contents(cty.region, ast::MutImmutable);
2308 // This also prohibits "@once fn" from being copied, which allows it to
2309 // be called. Neither way really makes much sense.
2310 let ot = match cty.onceness {
2311 ast::Once => TC::OwnsAffine,
2312 ast::Many => TC::None,
2318 fn object_contents(cx: &ctxt,
2320 mutbl: ast::Mutability,
2321 bounds: BuiltinBounds)
2323 // These are the type contents of the (opaque) interior
2324 let contents = TC::ReachesMutable.when(mutbl == ast::MutMutable) |
2325 kind_bounds_to_contents(cx, bounds, []);
2329 contents.owned_pointer()
2331 RegionTraitStore(r) => {
2332 contents.reference(borrowed_contents(r, mutbl))
2337 fn kind_bounds_to_contents(cx: &ctxt,
2338 bounds: BuiltinBounds,
2339 traits: &[@TraitRef])
2341 let _i = indenter();
2342 let mut tc = TC::All;
2343 each_inherited_builtin_bound(cx, bounds, traits, |bound| {
2344 tc = tc - match bound {
2345 BoundStatic => TC::Nonstatic,
2346 BoundSend => TC::Nonsendable,
2347 BoundSized => TC::Nonsized,
2348 BoundCopy => TC::Noncopy,
2349 BoundShare => TC::Nonsharable,
2354 // Iterates over all builtin bounds on the type parameter def, including
2355 // those inherited from traits with builtin-kind-supertraits.
2356 fn each_inherited_builtin_bound(cx: &ctxt,
2357 bounds: BuiltinBounds,
2358 traits: &[@TraitRef],
2359 f: |BuiltinBound|) {
2360 for bound in bounds.iter() {
2364 each_bound_trait_and_supertraits(cx, traits, |trait_ref| {
2365 let trait_def = lookup_trait_def(cx, trait_ref.def_id);
2366 for bound in trait_def.bounds.iter() {
2375 pub fn type_moves_by_default(cx: &ctxt, ty: t) -> bool {
2376 type_contents(cx, ty).moves_by_default(cx)
2379 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
2380 pub fn is_instantiable(cx: &ctxt, r_ty: t) -> bool {
2381 fn type_requires(cx: &ctxt, seen: &mut Vec<DefId>,
2382 r_ty: t, ty: t) -> bool {
2383 debug!("type_requires({}, {})?",
2384 ::util::ppaux::ty_to_str(cx, r_ty),
2385 ::util::ppaux::ty_to_str(cx, ty));
2388 get(r_ty).sty == get(ty).sty ||
2389 subtypes_require(cx, seen, r_ty, ty)
2392 debug!("type_requires({}, {})? {}",
2393 ::util::ppaux::ty_to_str(cx, r_ty),
2394 ::util::ppaux::ty_to_str(cx, ty),
2399 fn subtypes_require(cx: &ctxt, seen: &mut Vec<DefId>,
2400 r_ty: t, ty: t) -> bool {
2401 debug!("subtypes_require({}, {})?",
2402 ::util::ppaux::ty_to_str(cx, r_ty),
2403 ::util::ppaux::ty_to_str(cx, ty));
2405 let r = match get(ty).sty {
2406 // fixed length vectors need special treatment compared to
2407 // normal vectors, since they don't necessarily have the
2408 // possibilty to have length zero.
2409 ty_vec(_, vstore_fixed(0)) => false, // don't need no contents
2410 ty_vec(mt, vstore_fixed(_)) => type_requires(cx, seen, r_ty, mt.ty),
2427 ty_unboxed_vec(_) => {
2430 ty_box(typ) | ty_uniq(typ) => {
2431 type_requires(cx, seen, r_ty, typ)
2433 ty_rptr(_, ref mt) => {
2434 type_requires(cx, seen, r_ty, mt.ty)
2438 false // unsafe ptrs can always be NULL
2445 ty_struct(ref did, _) if seen.contains(did) => {
2449 ty_struct(did, ref substs) => {
2451 let fields = struct_fields(cx, did, substs);
2452 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
2453 seen.pop().unwrap();
2458 ts.iter().any(|t| type_requires(cx, seen, r_ty, *t))
2461 ty_enum(ref did, _) if seen.contains(did) => {
2465 ty_enum(did, ref substs) => {
2467 let vs = enum_variants(cx, did);
2468 let r = !vs.is_empty() && vs.iter().all(|variant| {
2469 variant.args.iter().any(|aty| {
2470 let sty = subst(cx, substs, *aty);
2471 type_requires(cx, seen, r_ty, sty)
2474 seen.pop().unwrap();
2479 debug!("subtypes_require({}, {})? {}",
2480 ::util::ppaux::ty_to_str(cx, r_ty),
2481 ::util::ppaux::ty_to_str(cx, ty),
2487 let mut seen = Vec::new();
2488 !subtypes_require(cx, &mut seen, r_ty, r_ty)
2491 /// Describes whether a type is representable. For types that are not
2492 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
2493 /// distinguish between types that are recursive with themselves and types that
2494 /// contain a different recursive type. These cases can therefore be treated
2495 /// differently when reporting errors.
2497 pub enum Representability {
2503 /// Check whether a type is representable. This means it cannot contain unboxed
2504 /// structural recursion. This check is needed for structs and enums.
2505 pub fn is_type_representable(cx: &ctxt, ty: t) -> Representability {
2507 // Iterate until something non-representable is found
2508 fn find_nonrepresentable<It: Iterator<t>>(cx: &ctxt, seen: &mut Vec<DefId>,
2509 mut iter: It) -> Representability {
2511 let r = type_structurally_recursive(cx, seen, ty);
2512 if r != Representable {
2519 // Does the type `ty` directly (without indirection through a pointer)
2520 // contain any types on stack `seen`?
2521 fn type_structurally_recursive(cx: &ctxt, seen: &mut Vec<DefId>,
2522 ty: t) -> Representability {
2523 debug!("type_structurally_recursive: {}",
2524 ::util::ppaux::ty_to_str(cx, ty));
2526 // Compare current type to previously seen types
2529 ty_enum(did, _) => {
2530 for (i, &seen_did) in seen.iter().enumerate() {
2531 if did == seen_did {
2532 return if i == 0 { SelfRecursive }
2533 else { ContainsRecursive }
2540 // Check inner types
2544 find_nonrepresentable(cx, seen, ts.iter().map(|t| *t))
2546 // Fixed-length vectors.
2547 // FIXME(#11924) Behavior undecided for zero-length vectors.
2548 ty_vec(mt, vstore_fixed(_)) => {
2549 type_structurally_recursive(cx, seen, mt.ty)
2552 // Push struct and enum def-ids onto `seen` before recursing.
2553 ty_struct(did, ref substs) => {
2555 let fields = struct_fields(cx, did, substs);
2556 let r = find_nonrepresentable(cx, seen,
2557 fields.iter().map(|f| f.mt.ty));
2561 ty_enum(did, ref substs) => {
2563 let vs = enum_variants(cx, did);
2565 let mut r = Representable;
2566 for variant in vs.iter() {
2567 let iter = variant.args.iter().map(|aty| subst(cx, substs, *aty));
2568 r = find_nonrepresentable(cx, seen, iter);
2570 if r != Representable { break }
2581 debug!("is_type_representable: {}",
2582 ::util::ppaux::ty_to_str(cx, ty));
2584 // To avoid a stack overflow when checking an enum variant or struct that
2585 // contains a different, structurally recursive type, maintain a stack
2586 // of seen types and check recursion for each of them (issues #3008, #3779).
2587 let mut seen: Vec<DefId> = Vec::new();
2588 type_structurally_recursive(cx, &mut seen, ty)
2591 pub fn type_is_trait(ty: t) -> bool {
2593 ty_trait(..) => true,
2598 pub fn type_is_integral(ty: t) -> bool {
2600 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
2605 pub fn type_is_uint(ty: t) -> bool {
2607 ty_infer(IntVar(_)) | ty_uint(ast::TyU) => true,
2612 pub fn type_is_char(ty: t) -> bool {
2619 pub fn type_is_bare_fn(ty: t) -> bool {
2621 ty_bare_fn(..) => true,
2626 pub fn type_is_fp(ty: t) -> bool {
2628 ty_infer(FloatVar(_)) | ty_float(_) => true,
2633 pub fn type_is_numeric(ty: t) -> bool {
2634 return type_is_integral(ty) || type_is_fp(ty);
2637 pub fn type_is_signed(ty: t) -> bool {
2644 pub fn type_is_machine(ty: t) -> bool {
2646 ty_int(ast::TyI) | ty_uint(ast::TyU) => false,
2647 ty_int(..) | ty_uint(..) | ty_float(..) => true,
2652 pub fn type_is_enum(ty: t) -> bool {
2654 ty_enum(_, _) => return true,
2659 // Is the type's representation size known at compile time?
2660 pub fn type_is_sized(cx: &ctxt, ty: ty::t) -> bool {
2662 // FIXME(#6308) add trait, vec, str, etc here.
2664 let ty_param_defs = cx.ty_param_defs.borrow();
2665 let param_def = ty_param_defs.get(&p.def_id.node);
2666 if param_def.bounds.builtin_bounds.contains_elem(BoundSized) {
2675 // Whether a type is enum like, that is an enum type with only nullary
2677 pub fn type_is_c_like_enum(cx: &ctxt, ty: t) -> bool {
2679 ty_enum(did, _) => {
2680 let variants = enum_variants(cx, did);
2681 if variants.len() == 0 {
2684 variants.iter().all(|v| v.args.len() == 0)
2691 pub fn type_param(ty: t) -> Option<uint> {
2693 ty_param(p) => return Some(p.idx),
2694 _ => {/* fall through */ }
2699 // Returns the type and mutability of *t.
2701 // The parameter `explicit` indicates if this is an *explicit* dereference.
2702 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
2703 pub fn deref(t: t, explicit: bool) -> Option<mt> {
2705 ty_box(typ) | ty_uniq(typ) => Some(mt {
2707 mutbl: ast::MutImmutable,
2709 ty_rptr(_, mt) => Some(mt),
2710 ty_ptr(mt) if explicit => Some(mt),
2715 // Returns the type and mutability of t[i]
2716 pub fn index(t: t) -> Option<mt> {
2718 ty_vec(mt, _) => Some(mt),
2719 ty_str(_) => Some(mt {ty: mk_u8(), mutbl: ast::MutImmutable}),
2724 pub fn node_id_to_trait_ref(cx: &ctxt, id: ast::NodeId) -> @ty::TraitRef {
2725 match cx.trait_refs.borrow().find(&id) {
2727 None => cx.sess.bug(
2728 format!("node_id_to_trait_ref: no trait ref for node `{}`",
2729 cx.map.node_to_str(id)))
2733 pub fn try_node_id_to_type(cx: &ctxt, id: ast::NodeId) -> Option<t> {
2734 cx.node_types.borrow().find_copy(&(id as uint))
2737 pub fn node_id_to_type(cx: &ctxt, id: ast::NodeId) -> t {
2738 match try_node_id_to_type(cx, id) {
2740 None => cx.sess.bug(
2741 format!("node_id_to_type: no type for node `{}`",
2742 cx.map.node_to_str(id)))
2746 pub fn node_id_to_type_opt(cx: &ctxt, id: ast::NodeId) -> Option<t> {
2747 match cx.node_types.borrow().find(&(id as uint)) {
2748 Some(&t) => Some(t),
2753 // FIXME(pcwalton): Makes a copy, bleh. Probably better to not do that.
2754 pub fn node_id_to_type_params(cx: &ctxt, id: ast::NodeId) -> Vec<t> {
2755 match cx.node_type_substs.borrow().find(&id) {
2756 None => return Vec::new(),
2757 Some(ts) => return (*ts).clone(),
2761 fn node_id_has_type_params(cx: &ctxt, id: ast::NodeId) -> bool {
2762 cx.node_type_substs.borrow().contains_key(&id)
2765 pub fn fn_is_variadic(fty: t) -> bool {
2766 match get(fty).sty {
2767 ty_bare_fn(ref f) => f.sig.variadic,
2768 ty_closure(ref f) => f.sig.variadic,
2770 fail!("fn_is_variadic() called on non-fn type: {:?}", s)
2775 pub fn ty_fn_sig(fty: t) -> FnSig {
2776 match get(fty).sty {
2777 ty_bare_fn(ref f) => f.sig.clone(),
2778 ty_closure(ref f) => f.sig.clone(),
2780 fail!("ty_fn_sig() called on non-fn type: {:?}", s)
2785 // Type accessors for substructures of types
2786 pub fn ty_fn_args(fty: t) -> Vec<t> {
2787 match get(fty).sty {
2788 ty_bare_fn(ref f) => f.sig.inputs.clone(),
2789 ty_closure(ref f) => f.sig.inputs.clone(),
2791 fail!("ty_fn_args() called on non-fn type: {:?}", s)
2796 pub fn ty_closure_sigil(fty: t) -> Sigil {
2797 match get(fty).sty {
2798 ty_closure(ref f) => f.sigil,
2800 fail!("ty_closure_sigil() called on non-closure type: {:?}", s)
2805 pub fn ty_fn_purity(fty: t) -> ast::Purity {
2806 match get(fty).sty {
2807 ty_bare_fn(ref f) => f.purity,
2808 ty_closure(ref f) => f.purity,
2810 fail!("ty_fn_purity() called on non-fn type: {:?}", s)
2815 pub fn ty_fn_ret(fty: t) -> t {
2816 match get(fty).sty {
2817 ty_bare_fn(ref f) => f.sig.output,
2818 ty_closure(ref f) => f.sig.output,
2820 fail!("ty_fn_ret() called on non-fn type: {:?}", s)
2825 pub fn is_fn_ty(fty: t) -> bool {
2826 match get(fty).sty {
2827 ty_bare_fn(_) => true,
2828 ty_closure(_) => true,
2833 pub fn ty_vstore(ty: t) -> vstore {
2835 ty_vec(_, vstore) => vstore,
2836 ty_str(vstore) => vstore,
2837 ref s => fail!("ty_vstore() called on invalid sty: {:?}", s)
2841 pub fn ty_region(tcx: &ctxt,
2846 ty_vec(_, vstore_slice(r)) => r,
2847 ty_str(vstore_slice(r)) => r,
2851 format!("ty_region() invoked on in appropriate ty: {:?}", s));
2856 pub fn replace_fn_sig(cx: &ctxt, fsty: &sty, new_sig: FnSig) -> t {
2858 ty_bare_fn(ref f) => mk_bare_fn(cx, BareFnTy {sig: new_sig, ..*f}),
2859 ty_closure(ref f) => mk_closure(cx, ClosureTy {sig: new_sig, ..**f}),
2862 format!("ty_fn_sig() called on non-fn type: {:?}", s));
2867 pub fn replace_closure_return_type(tcx: &ctxt, fn_type: t, ret_type: t) -> t {
2870 * Returns a new function type based on `fn_type` but returning a value of
2871 * type `ret_type` instead. */
2873 match ty::get(fn_type).sty {
2874 ty::ty_closure(ref fty) => {
2875 ty::mk_closure(tcx, ClosureTy {
2876 sig: FnSig {output: ret_type, ..fty.sig.clone()},
2881 tcx.sess.bug(format!(
2882 "replace_fn_ret() invoked with non-fn-type: {}",
2883 ty_to_str(tcx, fn_type)));
2888 // Returns a vec of all the input and output types of fty.
2889 pub fn tys_in_fn_sig(sig: &FnSig) -> Vec<t> {
2890 sig.inputs.iter().map(|a| *a).collect::<Vec<_>>().append_one(sig.output)
2893 // Type accessors for AST nodes
2894 pub fn block_ty(cx: &ctxt, b: &ast::Block) -> t {
2895 return node_id_to_type(cx, b.id);
2899 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
2900 // doesn't provide type parameter substitutions.
2901 pub fn pat_ty(cx: &ctxt, pat: &ast::Pat) -> t {
2902 return node_id_to_type(cx, pat.id);
2906 // Returns the type of an expression as a monotype.
2908 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
2909 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
2910 // auto-ref. The type returned by this function does not consider such
2911 // adjustments. See `expr_ty_adjusted()` instead.
2913 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
2914 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
2915 // instead of "fn(t) -> T with T = int". If this isn't what you want, see
2916 // expr_ty_params_and_ty() below.
2917 pub fn expr_ty(cx: &ctxt, expr: &ast::Expr) -> t {
2918 return node_id_to_type(cx, expr.id);
2921 pub fn expr_ty_opt(cx: &ctxt, expr: &ast::Expr) -> Option<t> {
2922 return node_id_to_type_opt(cx, expr.id);
2925 pub fn expr_ty_adjusted(cx: &ctxt,
2927 method_map: &FnvHashMap<MethodCall, MethodCallee>)
2931 * Returns the type of `expr`, considering any `AutoAdjustment`
2932 * entry recorded for that expression.
2934 * It would almost certainly be better to store the adjusted ty in with
2935 * the `AutoAdjustment`, but I opted not to do this because it would
2936 * require serializing and deserializing the type and, although that's not
2937 * hard to do, I just hate that code so much I didn't want to touch it
2938 * unless it was to fix it properly, which seemed a distraction from the
2939 * task at hand! -nmatsakis
2942 let unadjusted_ty = expr_ty(cx, expr);
2943 let adjustment = cx.adjustments.borrow().find_copy(&expr.id);
2944 adjust_ty(cx, expr.span, expr.id, unadjusted_ty, adjustment, |method_call| {
2945 method_map.find(&method_call).map(|method| method.ty)
2949 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
2950 match cx.map.find(id) {
2951 Some(ast_map::NodeExpr(e)) => {
2955 cx.sess.bug(format!("Node id {} is not an expr: {:?}",
2959 cx.sess.bug(format!("Node id {} is not present \
2960 in the node map", id));
2965 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
2966 match cx.map.find(id) {
2967 Some(ast_map::NodeLocal(pat)) => {
2969 ast::PatIdent(_, ref path, _) => {
2970 token::get_ident(ast_util::path_to_ident(path))
2974 format!("Variable id {} maps to {:?}, not local",
2981 format!("Variable id {} maps to {:?}, not local",
2987 pub fn adjust_ty(cx: &ctxt,
2989 expr_id: ast::NodeId,
2990 unadjusted_ty: ty::t,
2991 adjustment: Option<@AutoAdjustment>,
2992 method_type: |MethodCall| -> Option<ty::t>)
2994 /*! See `expr_ty_adjusted` */
2996 return match adjustment {
2997 Some(adjustment) => {
2999 AutoAddEnv(r, s) => {
3000 match ty::get(unadjusted_ty).sty {
3001 ty::ty_bare_fn(ref b) => {
3004 ty::ClosureTy {purity: b.purity,
3006 onceness: ast::Many,
3008 bounds: ty::AllBuiltinBounds(),
3009 sig: b.sig.clone()})
3013 format!("add_env adjustment on non-bare-fn: \
3020 AutoDerefRef(ref adj) => {
3021 let mut adjusted_ty = unadjusted_ty;
3023 if !ty::type_is_error(adjusted_ty) {
3024 for i in range(0, adj.autoderefs) {
3025 match method_type(MethodCall::autoderef(expr_id, i as u32)) {
3026 Some(method_ty) => {
3027 adjusted_ty = ty_fn_ret(method_ty);
3031 match deref(adjusted_ty, true) {
3032 Some(mt) => { adjusted_ty = mt.ty; }
3036 format!("the {}th autoderef failed: \
3039 ty_to_str(cx, adjusted_ty)));
3046 None => adjusted_ty,
3047 Some(ref autoref) => {
3056 AutoBorrowVec(r, m) => {
3057 borrow_vec(cx, span, r, m, adjusted_ty)
3060 AutoBorrowVecRef(r, m) => {
3061 adjusted_ty = borrow_vec(cx,
3068 mutbl: ast::MutImmutable
3072 AutoBorrowFn(r) => {
3073 borrow_fn(cx, span, r, adjusted_ty)
3077 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
3080 AutoBorrowObj(r, m) => {
3081 borrow_obj(cx, span, r, m, adjusted_ty)
3088 AutoObject(ref sigil, ref region, m, b, def_id, ref substs) => {
3089 trait_adjustment_to_ty(cx,
3099 None => unadjusted_ty
3102 fn borrow_vec(cx: &ctxt, span: Span,
3103 r: Region, m: ast::Mutability,
3104 ty: ty::t) -> ty::t {
3107 ty::mk_vec(cx, mt {ty: mt.ty, mutbl: m}, vstore_slice(r))
3111 ty::mk_str(cx, vstore_slice(r))
3117 format!("borrow-vec associated with bad sty: {:?}",
3123 fn borrow_fn(cx: &ctxt, span: Span, r: Region, ty: ty::t) -> ty::t {
3125 ty_closure(ref fty) => {
3126 ty::mk_closure(cx, ClosureTy {
3127 sigil: BorrowedSigil,
3136 format!("borrow-fn associated with bad sty: {:?}",
3142 fn borrow_obj(cx: &ctxt, span: Span, r: Region,
3143 m: ast::Mutability, ty: ty::t) -> ty::t {
3145 ty_trait(~ty::TyTrait {def_id, ref substs, bounds, .. }) => {
3146 ty::mk_trait(cx, def_id, substs.clone(),
3147 RegionTraitStore(r), m, bounds)
3152 format!("borrow-trait-obj associated with bad sty: {:?}",
3159 pub fn trait_adjustment_to_ty(cx: &ctxt, sigil: &ast::Sigil, region: &Option<Region>,
3160 def_id: ast::DefId, substs: &substs, m: ast::Mutability,
3161 bounds: BuiltinBounds) -> t {
3163 let trait_store = match *sigil {
3164 BorrowedSigil => RegionTraitStore(region.expect("expected valid region")),
3165 OwnedSigil => UniqTraitStore,
3166 ManagedSigil => unreachable!()
3169 mk_trait(cx, def_id, substs.clone(), trait_store, m, bounds)
3173 pub fn map_region(&self, f: |Region| -> Region) -> AutoRef {
3175 ty::AutoPtr(r, m) => ty::AutoPtr(f(r), m),
3176 ty::AutoBorrowVec(r, m) => ty::AutoBorrowVec(f(r), m),
3177 ty::AutoBorrowVecRef(r, m) => ty::AutoBorrowVecRef(f(r), m),
3178 ty::AutoBorrowFn(r) => ty::AutoBorrowFn(f(r)),
3179 ty::AutoUnsafe(m) => ty::AutoUnsafe(m),
3180 ty::AutoBorrowObj(r, m) => ty::AutoBorrowObj(f(r), m),
3185 pub struct ParamsTy {
3190 pub fn expr_ty_params_and_ty(cx: &ctxt,
3194 params: node_id_to_type_params(cx, expr.id),
3195 ty: node_id_to_type(cx, expr.id)
3199 pub fn expr_has_ty_params(cx: &ctxt, expr: &ast::Expr) -> bool {
3200 return node_id_has_type_params(cx, expr.id);
3203 pub fn method_call_type_param_defs(tcx: &ctxt, origin: typeck::MethodOrigin)
3204 -> Rc<Vec<TypeParameterDef>> {
3206 typeck::MethodStatic(did) => {
3207 // n.b.: When we encode impl methods, the bounds
3208 // that we encode include both the impl bounds
3209 // and then the method bounds themselves...
3210 ty::lookup_item_type(tcx, did).generics.type_param_defs
3212 typeck::MethodParam(typeck::MethodParam {
3214 method_num: n_mth, ..}) |
3215 typeck::MethodObject(typeck::MethodObject {
3217 method_num: n_mth, ..}) => {
3218 // ...trait methods bounds, in contrast, include only the
3219 // method bounds, so we must preprend the tps from the
3220 // trait itself. This ought to be harmonized.
3221 let trait_type_param_defs =
3222 lookup_trait_def(tcx, trt_id).generics.type_param_defs();
3223 Rc::new(Vec::from_slice(trait_type_param_defs).append(
3224 ty::trait_method(tcx, trt_id, n_mth).generics.type_param_defs()))
3229 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> ast::Def {
3230 match tcx.def_map.borrow().find(&expr.id) {
3233 tcx.sess.span_bug(expr.span, format!(
3234 "no def-map entry for expr {:?}", expr.id));
3239 pub fn expr_is_lval(tcx: &ctxt,
3240 method_map: MethodMap,
3241 e: &ast::Expr) -> bool {
3242 match expr_kind(tcx, method_map, e) {
3244 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
3248 /// We categorize expressions into three kinds. The distinction between
3249 /// lvalue/rvalue is fundamental to the language. The distinction between the
3250 /// two kinds of rvalues is an artifact of trans which reflects how we will
3251 /// generate code for that kind of expression. See trans/expr.rs for more
3260 pub fn expr_kind(tcx: &ctxt,
3261 method_map: MethodMap,
3262 expr: &ast::Expr) -> ExprKind {
3263 if method_map.borrow().contains_key(&MethodCall::expr(expr.id)) {
3264 // Overloaded operations are generally calls, and hence they are
3265 // generated via DPS, but there are two exceptions:
3266 return match expr.node {
3267 // `a += b` has a unit result.
3268 ast::ExprAssignOp(..) => RvalueStmtExpr,
3270 // the deref method invoked for `*a` always yields an `&T`
3271 ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
3273 // in the general case, result could be any type, use DPS
3279 ast::ExprPath(..) => {
3280 match resolve_expr(tcx, expr) {
3281 ast::DefVariant(tid, vid, _) => {
3282 let variant_info = enum_variant_with_id(tcx, tid, vid);
3283 if variant_info.args.len() > 0u {
3292 ast::DefStruct(_) => {
3293 match get(expr_ty(tcx, expr)).sty {
3294 ty_bare_fn(..) => RvalueDatumExpr,
3299 // Fn pointers are just scalar values.
3300 ast::DefFn(..) | ast::DefStaticMethod(..) => RvalueDatumExpr,
3302 // Note: there is actually a good case to be made that
3303 // DefArg's, particularly those of immediate type, ought to
3304 // considered rvalues.
3305 ast::DefStatic(..) |
3306 ast::DefBinding(..) |
3309 ast::DefLocal(..) => LvalueExpr,
3312 tcx.sess.span_bug(expr.span, format!(
3313 "uncategorized def for expr {:?}: {:?}",
3319 ast::ExprUnary(ast::UnDeref, _) |
3320 ast::ExprField(..) |
3321 ast::ExprIndex(..) => {
3326 ast::ExprMethodCall(..) |
3327 ast::ExprStruct(..) |
3330 ast::ExprMatch(..) |
3331 ast::ExprFnBlock(..) |
3333 ast::ExprBlock(..) |
3334 ast::ExprRepeat(..) |
3335 ast::ExprVstore(_, ast::ExprVstoreSlice) |
3336 ast::ExprVstore(_, ast::ExprVstoreMutSlice) |
3337 ast::ExprVec(..) => {
3341 ast::ExprLit(lit) if lit_is_str(lit) => {
3345 ast::ExprCast(..) => {
3346 match tcx.node_types.borrow().find(&(expr.id as uint)) {
3348 if type_is_trait(t) {
3355 // Technically, it should not happen that the expr is not
3356 // present within the table. However, it DOES happen
3357 // during type check, because the final types from the
3358 // expressions are not yet recorded in the tcx. At that
3359 // time, though, we are only interested in knowing lvalue
3360 // vs rvalue. It would be better to base this decision on
3361 // the AST type in cast node---but (at the time of this
3362 // writing) it's not easy to distinguish casts to traits
3363 // from other casts based on the AST. This should be
3364 // easier in the future, when casts to traits
3365 // would like @Foo, ~Foo, or &Foo.
3371 ast::ExprBreak(..) |
3372 ast::ExprAgain(..) |
3374 ast::ExprWhile(..) |
3376 ast::ExprAssign(..) |
3377 ast::ExprInlineAsm(..) |
3378 ast::ExprAssignOp(..) => {
3382 ast::ExprForLoop(..) => fail!("non-desugared expr_for_loop"),
3384 ast::ExprLit(_) | // Note: LitStr is carved out above
3385 ast::ExprUnary(..) |
3386 ast::ExprAddrOf(..) |
3387 ast::ExprBinary(..) |
3388 ast::ExprVstore(_, ast::ExprVstoreUniq) => {
3392 ast::ExprBox(place, _) => {
3393 // Special case `~T` for now:
3394 let definition = match tcx.def_map.borrow().find(&place.id) {
3396 None => fail!("no def for place"),
3398 let def_id = ast_util::def_id_of_def(definition);
3399 match tcx.lang_items.items.get(ExchangeHeapLangItem as uint) {
3400 &Some(item_def_id) if def_id == item_def_id => {
3403 &Some(_) | &None => RvalueDpsExpr,
3407 ast::ExprParen(e) => expr_kind(tcx, method_map, e),
3409 ast::ExprMac(..) => {
3412 "macro expression remains after expansion");
3417 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
3419 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
3422 ast::StmtMac(..) => fail!("unexpanded macro in trans")
3426 pub fn field_idx(name: ast::Name, fields: &[field]) -> Option<uint> {
3428 for f in fields.iter() { if f.ident.name == name { return Some(i); } i += 1u; }
3432 pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
3435 for f in fields.iter() { if f.ident.name == name { return i; } i += 1u; }
3436 tcx.sess.bug(format!(
3437 "no field named `{}` found in the list of fields `{:?}`",
3438 token::get_name(name),
3439 fields.iter().map(|f| token::get_ident(f.ident).get().to_str()).collect::<Vec<~str>>()));
3442 pub fn method_idx(id: ast::Ident, meths: &[@Method]) -> Option<uint> {
3443 meths.iter().position(|m| m.ident == id)
3446 /// Returns a vector containing the indices of all type parameters that appear
3447 /// in `ty`. The vector may contain duplicates. Probably should be converted
3448 /// to a bitset or some other representation.
3449 pub fn param_tys_in_type(ty: t) -> Vec<param_ty> {
3450 let mut rslt = Vec::new();
3462 pub fn ty_sort_str(cx: &ctxt, t: t) -> ~str {
3464 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) |
3465 ty_uint(_) | ty_float(_) | ty_str(_) => {
3466 ::util::ppaux::ty_to_str(cx, t)
3469 ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
3470 ty_box(_) => ~"@-ptr",
3471 ty_uniq(_) => ~"~-ptr",
3472 ty_vec(_, _) => ~"vector",
3473 ty_unboxed_vec(_) => ~"unboxed vector",
3474 ty_ptr(_) => ~"*-ptr",
3475 ty_rptr(_, _) => ~"&-ptr",
3476 ty_bare_fn(_) => ~"extern fn",
3477 ty_closure(_) => ~"fn",
3478 ty_trait(ref inner) => format!("trait {}", item_path_str(cx, inner.def_id)),
3479 ty_struct(id, _) => format!("struct {}", item_path_str(cx, id)),
3480 ty_tup(_) => ~"tuple",
3481 ty_infer(TyVar(_)) => ~"inferred type",
3482 ty_infer(IntVar(_)) => ~"integral variable",
3483 ty_infer(FloatVar(_)) => ~"floating-point variable",
3484 ty_param(_) => ~"type parameter",
3485 ty_self(_) => ~"self",
3486 ty_err => ~"type error"
3490 pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> ~str {
3493 * Explains the source of a type err in a short,
3494 * human readable way. This is meant to be placed in
3495 * parentheses after some larger message. You should
3496 * also invoke `note_and_explain_type_err()` afterwards
3497 * to present additional details, particularly when
3498 * it comes to lifetime-related errors. */
3500 fn terr_vstore_kind_to_str(k: terr_vstore_kind) -> ~str {
3505 terr_trait => ~"trait"
3510 terr_mismatch => ~"types differ",
3511 terr_purity_mismatch(values) => {
3512 format!("expected {} fn but found {} fn",
3513 values.expected.to_str(), values.found.to_str())
3515 terr_abi_mismatch(values) => {
3516 format!("expected {} fn but found {} fn",
3517 values.expected.to_str(), values.found.to_str())
3519 terr_onceness_mismatch(values) => {
3520 format!("expected {} fn but found {} fn",
3521 values.expected.to_str(), values.found.to_str())
3523 terr_sigil_mismatch(values) => {
3524 format!("expected {} closure, found {} closure",
3525 values.expected.to_str(),
3526 values.found.to_str())
3528 terr_mutability => ~"values differ in mutability",
3529 terr_box_mutability => ~"boxed values differ in mutability",
3530 terr_vec_mutability => ~"vectors differ in mutability",
3531 terr_ptr_mutability => ~"pointers differ in mutability",
3532 terr_ref_mutability => ~"references differ in mutability",
3533 terr_ty_param_size(values) => {
3534 format!("expected a type with {} type params \
3535 but found one with {} type params",
3536 values.expected, values.found)
3538 terr_tuple_size(values) => {
3539 format!("expected a tuple with {} elements \
3540 but found one with {} elements",
3541 values.expected, values.found)
3543 terr_record_size(values) => {
3544 format!("expected a record with {} fields \
3545 but found one with {} fields",
3546 values.expected, values.found)
3548 terr_record_mutability => {
3549 ~"record elements differ in mutability"
3551 terr_record_fields(values) => {
3552 format!("expected a record with field `{}` but found one with field \
3554 token::get_ident(values.expected),
3555 token::get_ident(values.found))
3557 terr_arg_count => ~"incorrect number of function parameters",
3558 terr_regions_does_not_outlive(..) => {
3559 format!("lifetime mismatch")
3561 terr_regions_not_same(..) => {
3562 format!("lifetimes are not the same")
3564 terr_regions_no_overlap(..) => {
3565 format!("lifetimes do not intersect")
3567 terr_regions_insufficiently_polymorphic(br, _) => {
3568 format!("expected bound lifetime parameter {}, \
3569 but found concrete lifetime",
3570 bound_region_ptr_to_str(cx, br))
3572 terr_regions_overly_polymorphic(br, _) => {
3573 format!("expected concrete lifetime, \
3574 but found bound lifetime parameter {}",
3575 bound_region_ptr_to_str(cx, br))
3577 terr_vstores_differ(k, ref values) => {
3578 format!("{} storage differs: expected `{}` but found `{}`",
3579 terr_vstore_kind_to_str(k),
3580 vstore_to_str(cx, (*values).expected),
3581 vstore_to_str(cx, (*values).found))
3583 terr_trait_stores_differ(_, ref values) => {
3584 format!("trait storage differs: expected `{}` but found `{}`",
3585 trait_store_to_str(cx, (*values).expected),
3586 trait_store_to_str(cx, (*values).found))
3588 terr_in_field(err, fname) => {
3589 format!("in field `{}`, {}", token::get_ident(fname),
3590 type_err_to_str(cx, err))
3592 terr_sorts(values) => {
3593 format!("expected {} but found {}",
3594 ty_sort_str(cx, values.expected),
3595 ty_sort_str(cx, values.found))
3597 terr_traits(values) => {
3598 format!("expected trait `{}` but found trait `{}`",
3599 item_path_str(cx, values.expected),
3600 item_path_str(cx, values.found))
3602 terr_builtin_bounds(values) => {
3603 if values.expected.is_empty() {
3604 format!("expected no bounds but found `{}`",
3605 values.found.user_string(cx))
3606 } else if values.found.is_empty() {
3607 format!("expected bounds `{}` but found no bounds",
3608 values.expected.user_string(cx))
3610 format!("expected bounds `{}` but found bounds `{}`",
3611 values.expected.user_string(cx),
3612 values.found.user_string(cx))
3615 terr_integer_as_char => {
3616 format!("expected an integral type but found `char`")
3618 terr_int_mismatch(ref values) => {
3619 format!("expected `{}` but found `{}`",
3620 values.expected.to_str(),
3621 values.found.to_str())
3623 terr_float_mismatch(ref values) => {
3624 format!("expected `{}` but found `{}`",
3625 values.expected.to_str(),
3626 values.found.to_str())
3628 terr_variadic_mismatch(ref values) => {
3629 format!("expected {} fn but found {} function",
3630 if values.expected { "variadic" } else { "non-variadic" },
3631 if values.found { "variadic" } else { "non-variadic" })
3636 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
3638 terr_regions_does_not_outlive(subregion, superregion) => {
3639 note_and_explain_region(cx, "", subregion, "...");
3640 note_and_explain_region(cx, "...does not necessarily outlive ",
3643 terr_regions_not_same(region1, region2) => {
3644 note_and_explain_region(cx, "", region1, "...");
3645 note_and_explain_region(cx, "...is not the same lifetime as ",
3648 terr_regions_no_overlap(region1, region2) => {
3649 note_and_explain_region(cx, "", region1, "...");
3650 note_and_explain_region(cx, "...does not overlap ",
3653 terr_regions_insufficiently_polymorphic(_, conc_region) => {
3654 note_and_explain_region(cx,
3655 "concrete lifetime that was found is ",
3658 terr_regions_overly_polymorphic(_, conc_region) => {
3659 note_and_explain_region(cx,
3660 "expected concrete lifetime is ",
3667 pub fn def_has_ty_params(def: ast::Def) -> bool {
3669 ast::DefFn(_, _) | ast::DefVariant(_, _, _) | ast::DefStruct(_)
3675 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
3676 cx.provided_method_sources.borrow().find(&id).map(|x| *x)
3679 pub fn provided_trait_methods(cx: &ctxt, id: ast::DefId) -> Vec<@Method> {
3682 match cx.map.find(id.node) {
3683 Some(ast_map::NodeItem(item)) => {
3685 ItemTrait(_, _, ref ms) => {
3687 ast_util::split_trait_methods(ms.as_slice());
3689 .map(|m| method(cx, ast_util::local_def(m.id)))
3693 cx.sess.bug(format!("provided_trait_methods: \
3694 `{:?}` is not a trait",
3700 cx.sess.bug(format!("provided_trait_methods: `{:?}` is not \
3707 csearch::get_provided_trait_methods(cx, id)
3711 pub fn trait_supertraits(cx: &ctxt, id: ast::DefId) -> @Vec<@TraitRef> {
3713 match cx.supertraits.borrow().find(&id) {
3714 Some(&trait_refs) => { return trait_refs; }
3715 None => {} // Continue.
3718 // Not in the cache. It had better be in the metadata, which means it
3719 // shouldn't be local.
3720 assert!(!is_local(id));
3722 // Get the supertraits out of the metadata and create the
3723 // TraitRef for each.
3724 let result = @csearch::get_supertraits(cx, id);
3725 cx.supertraits.borrow_mut().insert(id, result);
3729 pub fn trait_ref_supertraits(cx: &ctxt, trait_ref: &ty::TraitRef) -> Vec<@TraitRef> {
3730 let supertrait_refs = trait_supertraits(cx, trait_ref.def_id);
3731 supertrait_refs.iter().map(
3732 |supertrait_ref| supertrait_ref.subst(cx, &trait_ref.substs)).collect()
3735 fn lookup_locally_or_in_crate_store<V:Clone>(
3738 map: &mut DefIdMap<V>,
3739 load_external: || -> V) -> V {
3741 * Helper for looking things up in the various maps
3742 * that are populated during typeck::collect (e.g.,
3743 * `cx.methods`, `cx.tcache`, etc). All of these share
3744 * the pattern that if the id is local, it should have
3745 * been loaded into the map by the `typeck::collect` phase.
3746 * If the def-id is external, then we have to go consult
3747 * the crate loading code (and cache the result for the future).
3750 match map.find_copy(&def_id) {
3751 Some(v) => { return v; }
3755 if def_id.krate == ast::LOCAL_CRATE {
3756 fail!("No def'n found for {:?} in tcx.{}", def_id, descr);
3758 let v = load_external();
3759 map.insert(def_id, v.clone());
3763 pub fn trait_method(cx: &ctxt, trait_did: ast::DefId, idx: uint) -> @Method {
3764 let method_def_id = *ty::trait_method_def_ids(cx, trait_did).get(idx);
3765 ty::method(cx, method_def_id)
3769 pub fn trait_methods(cx: &ctxt, trait_did: ast::DefId) -> @Vec<@Method> {
3770 let mut trait_methods = cx.trait_methods_cache.borrow_mut();
3771 match trait_methods.find(&trait_did) {
3772 Some(&methods) => methods,
3774 let def_ids = ty::trait_method_def_ids(cx, trait_did);
3775 let methods = @def_ids.iter().map(|d| ty::method(cx, *d)).collect();
3776 trait_methods.insert(trait_did, methods);
3782 pub fn method(cx: &ctxt, id: ast::DefId) -> @Method {
3783 lookup_locally_or_in_crate_store("methods", id,
3784 &mut *cx.methods.borrow_mut(), || {
3785 @csearch::get_method(cx, id)
3789 pub fn trait_method_def_ids(cx: &ctxt, id: ast::DefId) -> @Vec<DefId> {
3790 lookup_locally_or_in_crate_store("trait_method_def_ids",
3792 &mut *cx.trait_method_def_ids.borrow_mut(),
3794 @csearch::get_trait_method_def_ids(&cx.sess.cstore, id)
3798 pub fn impl_trait_ref(cx: &ctxt, id: ast::DefId) -> Option<@TraitRef> {
3799 match cx.impl_trait_cache.borrow().find(&id) {
3800 Some(&ret) => { return ret; }
3804 let ret = if id.krate == ast::LOCAL_CRATE {
3805 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
3806 match cx.map.find(id.node) {
3807 Some(ast_map::NodeItem(item)) => {
3809 ast::ItemImpl(_, ref opt_trait, _, _) => {
3812 Some(ty::node_id_to_trait_ref(cx, t.ref_id))
3823 csearch::get_impl_trait(cx, id)
3826 cx.impl_trait_cache.borrow_mut().insert(id, ret);
3830 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
3831 let def = *tcx.def_map.borrow()
3833 .expect("no def-map entry for trait");
3834 ast_util::def_id_of_def(def)
3837 pub fn try_add_builtin_trait(tcx: &ctxt,
3838 trait_def_id: ast::DefId,
3839 builtin_bounds: &mut BuiltinBounds) -> bool {
3840 //! Checks whether `trait_ref` refers to one of the builtin
3841 //! traits, like `Send`, and adds the corresponding
3842 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
3843 //! is a builtin trait.
3845 match tcx.lang_items.to_builtin_kind(trait_def_id) {
3846 Some(bound) => { builtin_bounds.add(bound); true }
3851 pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> {
3853 ty_trait(~TyTrait { def_id: id, .. }) | ty_struct(id, _) | ty_enum(id, _) => Some(id),
3860 pub struct VariantInfo {
3862 pub arg_names: Option<Vec<ast::Ident> >,
3864 pub name: ast::Ident,
3872 /// Creates a new VariantInfo from the corresponding ast representation.
3874 /// Does not do any caching of the value in the type context.
3875 pub fn from_ast_variant(cx: &ctxt,
3876 ast_variant: &ast::Variant,
3877 discriminant: Disr) -> VariantInfo {
3878 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
3880 match ast_variant.node.kind {
3881 ast::TupleVariantKind(ref args) => {
3882 let arg_tys = if args.len() > 0 {
3883 ty_fn_args(ctor_ty).iter().map(|a| *a).collect()
3888 return VariantInfo {
3892 name: ast_variant.node.name,
3893 id: ast_util::local_def(ast_variant.node.id),
3894 disr_val: discriminant,
3895 vis: ast_variant.node.vis
3898 ast::StructVariantKind(ref struct_def) => {
3900 let fields: &[StructField] = struct_def.fields.as_slice();
3902 assert!(fields.len() > 0);
3904 let arg_tys = ty_fn_args(ctor_ty).iter().map(|a| *a).collect();
3905 let arg_names = fields.iter().map(|field| {
3906 match field.node.kind {
3907 NamedField(ident, _) => ident,
3908 UnnamedField(..) => cx.sess.bug(
3909 "enum_variants: all fields in struct must have a name")
3913 return VariantInfo {
3915 arg_names: Some(arg_names),
3917 name: ast_variant.node.name,
3918 id: ast_util::local_def(ast_variant.node.id),
3919 disr_val: discriminant,
3920 vis: ast_variant.node.vis
3927 pub fn substd_enum_variants(cx: &ctxt,
3930 -> Vec<@VariantInfo> {
3931 enum_variants(cx, id).iter().map(|variant_info| {
3932 let substd_args = variant_info.args.iter()
3933 .map(|aty| subst(cx, substs, *aty)).collect();
3935 let substd_ctor_ty = subst(cx, substs, variant_info.ctor_ty);
3939 ctor_ty: substd_ctor_ty,
3940 ..(**variant_info).clone()
3945 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> ~str {
3946 with_path(cx, id, |path| ast_map::path_to_str(path))
3951 TraitDtor(DefId, bool)
3955 pub fn is_not_present(&self) -> bool {
3962 pub fn is_present(&self) -> bool {
3963 !self.is_not_present()
3966 pub fn has_drop_flag(&self) -> bool {
3969 &TraitDtor(_, flag) => flag
3974 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
3975 Otherwise return none. */
3976 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
3977 match cx.destructor_for_type.borrow().find(&struct_id) {
3978 Some(&method_def_id) => {
3979 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
3981 TraitDtor(method_def_id, flag)
3987 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
3988 ty_dtor(cx, struct_id).is_present()
3991 pub fn with_path<T>(cx: &ctxt, id: ast::DefId, f: |ast_map::PathElems| -> T) -> T {
3992 if id.krate == ast::LOCAL_CRATE {
3993 cx.map.with_path(id.node, f)
3995 f(ast_map::Values(csearch::get_item_path(cx, id).iter()).chain(None))
3999 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
4000 enum_variants(cx, id).len() == 1
4003 pub fn type_is_empty(cx: &ctxt, t: t) -> bool {
4004 match ty::get(t).sty {
4005 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
4010 pub fn enum_variants(cx: &ctxt, id: ast::DefId) -> @Vec<@VariantInfo> {
4011 match cx.enum_var_cache.borrow().find(&id) {
4012 Some(&variants) => return variants,
4013 _ => { /* fallthrough */ }
4016 let result = if ast::LOCAL_CRATE != id.krate {
4017 @csearch::get_enum_variants(cx, id)
4020 Although both this code and check_enum_variants in typeck/check
4021 call eval_const_expr, it should never get called twice for the same
4022 expr, since check_enum_variants also updates the enum_var_cache
4025 match cx.map.get(id.node) {
4026 ast_map::NodeItem(item) => {
4028 ast::ItemEnum(ref enum_definition, _) => {
4029 let mut last_discriminant: Option<Disr> = None;
4030 @enum_definition.variants.iter().map(|&variant| {
4032 let mut discriminant = match last_discriminant {
4033 Some(val) => val + 1,
4034 None => INITIAL_DISCRIMINANT_VALUE
4037 match variant.node.disr_expr {
4038 Some(e) => match const_eval::eval_const_expr_partial(cx, e) {
4039 Ok(const_eval::const_int(val)) => {
4040 discriminant = val as Disr
4042 Ok(const_eval::const_uint(val)) => {
4043 discriminant = val as Disr
4048 "expected signed integer \
4063 @VariantInfo::from_ast_variant(cx,
4066 last_discriminant = Some(discriminant);
4072 cx.sess.bug("enum_variants: id not bound to an enum")
4076 _ => cx.sess.bug("enum_variants: id not bound to an enum")
4081 cx.enum_var_cache.borrow_mut().insert(id, result);
4086 // Returns information about the enum variant with the given ID:
4087 pub fn enum_variant_with_id(cx: &ctxt,
4088 enum_id: ast::DefId,
4089 variant_id: ast::DefId)
4091 let variants = enum_variants(cx, enum_id);
4093 while i < variants.len() {
4094 let variant = *variants.get(i);
4095 if variant.id == variant_id {
4100 cx.sess.bug("enum_variant_with_id(): no variant exists with that ID");
4104 // If the given item is in an external crate, looks up its type and adds it to
4105 // the type cache. Returns the type parameters and type.
4106 pub fn lookup_item_type(cx: &ctxt,
4108 -> ty_param_bounds_and_ty {
4109 lookup_locally_or_in_crate_store(
4110 "tcache", did, &mut *cx.tcache.borrow_mut(),
4111 || csearch::get_type(cx, did))
4114 pub fn lookup_impl_vtables(cx: &ctxt,
4116 -> typeck::impl_res {
4117 lookup_locally_or_in_crate_store(
4118 "impl_vtables", did, &mut *cx.impl_vtables.borrow_mut(),
4119 || csearch::get_impl_vtables(cx, did) )
4122 /// Given the did of a trait, returns its canonical trait ref.
4123 pub fn lookup_trait_def(cx: &ctxt, did: ast::DefId) -> @ty::TraitDef {
4124 let mut trait_defs = cx.trait_defs.borrow_mut();
4125 match trait_defs.find(&did) {
4126 Some(&trait_def) => {
4127 // The item is in this crate. The caller should have added it to the
4128 // type cache already
4132 assert!(did.krate != ast::LOCAL_CRATE);
4133 let trait_def = @csearch::get_trait_def(cx, did);
4134 trait_defs.insert(did, trait_def);
4140 /// Iterate over meta_items of a definition.
4141 // (This should really be an iterator, but that would require csearch and
4142 // decoder to use iterators instead of higher-order functions.)
4143 pub fn each_attr(tcx: &ctxt, did: DefId, f: |@MetaItem| -> bool) -> bool {
4145 let item = tcx.map.expect_item(did.node);
4146 item.attrs.iter().advance(|attr| f(attr.node.value))
4148 let mut cont = true;
4149 csearch::get_item_attrs(&tcx.sess.cstore, did, |meta_items| {
4151 cont = meta_items.iter().advance(|ptrptr| f(*ptrptr));
4158 /// Determine whether an item is annotated with an attribute
4159 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
4160 let mut found = false;
4161 each_attr(tcx, did, |item| {
4162 if item.name().equiv(&attr) {
4172 /// Determine whether an item is annotated with `#[packed]`
4173 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
4174 has_attr(tcx, did, "packed")
4177 /// Determine whether an item is annotated with `#[simd]`
4178 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
4179 has_attr(tcx, did, "simd")
4182 // Obtain the representation annotation for a definition.
4183 pub fn lookup_repr_hint(tcx: &ctxt, did: DefId) -> attr::ReprAttr {
4184 let mut acc = attr::ReprAny;
4185 ty::each_attr(tcx, did, |meta| {
4186 acc = attr::find_repr_attr(tcx.sess.diagnostic(), meta, acc);
4192 // Look up a field ID, whether or not it's local
4193 // Takes a list of type substs in case the struct is generic
4194 pub fn lookup_field_type(tcx: &ctxt,
4199 let t = if id.krate == ast::LOCAL_CRATE {
4200 node_id_to_type(tcx, id.node)
4202 let mut tcache = tcx.tcache.borrow_mut();
4203 match tcache.find(&id) {
4204 Some(&ty_param_bounds_and_ty {ty, ..}) => ty,
4206 let tpt = csearch::get_field_type(tcx, struct_id, id);
4207 tcache.insert(id, tpt.clone());
4212 subst(tcx, substs, t)
4215 // Look up the list of field names and IDs for a given struct
4216 // Fails if the id is not bound to a struct.
4217 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
4218 if did.krate == ast::LOCAL_CRATE {
4219 match cx.map.find(did.node) {
4220 Some(ast_map::NodeItem(i)) => {
4222 ast::ItemStruct(struct_def, _) => {
4223 struct_field_tys(struct_def.fields.as_slice())
4225 _ => cx.sess.bug("struct ID bound to non-struct")
4228 Some(ast_map::NodeVariant(ref variant)) => {
4229 match (*variant).node.kind {
4230 ast::StructVariantKind(struct_def) => {
4231 struct_field_tys(struct_def.fields.as_slice())
4234 cx.sess.bug("struct ID bound to enum variant that \
4241 format!("struct ID not bound to an item: {}",
4242 cx.map.node_to_str(did.node)));
4246 csearch::get_struct_fields(&cx.sess.cstore, did)
4250 pub fn lookup_struct_field(cx: &ctxt,
4252 field_id: ast::DefId)
4254 let r = lookup_struct_fields(cx, parent);
4255 match r.iter().find(
4256 |f| f.id.node == field_id.node) {
4258 None => cx.sess.bug("struct ID not found in parent's fields")
4262 fn struct_field_tys(fields: &[StructField]) -> Vec<field_ty> {
4263 fields.iter().map(|field| {
4264 match field.node.kind {
4265 NamedField(ident, visibility) => {
4268 id: ast_util::local_def(field.node.id),
4272 UnnamedField(visibility) => {
4274 name: syntax::parse::token::special_idents::unnamed_field.name,
4275 id: ast_util::local_def(field.node.id),
4283 // Returns a list of fields corresponding to the struct's items. trans uses
4284 // this. Takes a list of substs with which to instantiate field types.
4285 pub fn struct_fields(cx: &ctxt, did: ast::DefId, substs: &substs)
4287 lookup_struct_fields(cx, did).iter().map(|f| {
4289 // FIXME #6993: change type of field to Name and get rid of new()
4290 ident: ast::Ident::new(f.name),
4292 ty: lookup_field_type(cx, did, f.id, substs),
4299 pub fn is_binopable(cx: &ctxt, ty: t, op: ast::BinOp) -> bool {
4300 static tycat_other: int = 0;
4301 static tycat_bool: int = 1;
4302 static tycat_char: int = 2;
4303 static tycat_int: int = 3;
4304 static tycat_float: int = 4;
4305 static tycat_bot: int = 5;
4306 static tycat_raw_ptr: int = 6;
4308 static opcat_add: int = 0;
4309 static opcat_sub: int = 1;
4310 static opcat_mult: int = 2;
4311 static opcat_shift: int = 3;
4312 static opcat_rel: int = 4;
4313 static opcat_eq: int = 5;
4314 static opcat_bit: int = 6;
4315 static opcat_logic: int = 7;
4317 fn opcat(op: ast::BinOp) -> int {
4319 ast::BiAdd => opcat_add,
4320 ast::BiSub => opcat_sub,
4321 ast::BiMul => opcat_mult,
4322 ast::BiDiv => opcat_mult,
4323 ast::BiRem => opcat_mult,
4324 ast::BiAnd => opcat_logic,
4325 ast::BiOr => opcat_logic,
4326 ast::BiBitXor => opcat_bit,
4327 ast::BiBitAnd => opcat_bit,
4328 ast::BiBitOr => opcat_bit,
4329 ast::BiShl => opcat_shift,
4330 ast::BiShr => opcat_shift,
4331 ast::BiEq => opcat_eq,
4332 ast::BiNe => opcat_eq,
4333 ast::BiLt => opcat_rel,
4334 ast::BiLe => opcat_rel,
4335 ast::BiGe => opcat_rel,
4336 ast::BiGt => opcat_rel
4340 fn tycat(cx: &ctxt, ty: t) -> int {
4341 if type_is_simd(cx, ty) {
4342 return tycat(cx, simd_type(cx, ty))
4345 ty_char => tycat_char,
4346 ty_bool => tycat_bool,
4347 ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
4348 ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
4349 ty_bot => tycat_bot,
4350 ty_ptr(_) => tycat_raw_ptr,
4355 static t: bool = true;
4356 static f: bool = false;
4359 // +, -, *, shift, rel, ==, bit, logic
4360 /*other*/ [f, f, f, f, f, f, f, f],
4361 /*bool*/ [f, f, f, f, t, t, t, t],
4362 /*char*/ [f, f, f, f, t, t, f, f],
4363 /*int*/ [t, t, t, t, t, t, t, f],
4364 /*float*/ [t, t, t, f, t, t, f, f],
4365 /*bot*/ [t, t, t, t, t, t, t, t],
4366 /*raw ptr*/ [f, f, f, f, t, t, f, f]];
4368 return tbl[tycat(cx, ty) as uint ][opcat(op) as uint];
4371 pub fn ty_params_to_tys(tcx: &ctxt, generics: &ast::Generics) -> Vec<t> {
4372 Vec::from_fn(generics.ty_params.len(), |i| {
4373 let id = generics.ty_params.get(i).id;
4374 ty::mk_param(tcx, i, ast_util::local_def(id))
4378 /// Returns an equivalent type with all the typedefs and self regions removed.
4379 pub fn normalize_ty(cx: &ctxt, t: t) -> t {
4380 let u = TypeNormalizer(cx).fold_ty(t);
4383 struct TypeNormalizer<'a>(&'a ctxt);
4385 impl<'a> TypeFolder for TypeNormalizer<'a> {
4386 fn tcx<'a>(&'a self) -> &'a ctxt { let TypeNormalizer(c) = *self; c }
4388 fn fold_ty(&mut self, t: ty::t) -> ty::t {
4389 match self.tcx().normalized_cache.borrow().find_copy(&t) {
4394 let t_norm = ty_fold::super_fold_ty(self, t);
4395 self.tcx().normalized_cache.borrow_mut().insert(t, t_norm);
4399 fn fold_vstore(&mut self, vstore: vstore) -> vstore {
4401 vstore_fixed(..) | vstore_uniq => vstore,
4402 vstore_slice(_) => vstore_slice(ReStatic)
4406 fn fold_region(&mut self, _: ty::Region) -> ty::Region {
4410 fn fold_substs(&mut self,
4413 substs { regions: ErasedRegions,
4414 self_ty: ty_fold::fold_opt_ty(self, substs.self_ty),
4415 tps: ty_fold::fold_ty_vec(self, substs.tps.as_slice()) }
4418 fn fold_sig(&mut self,
4421 // The binder-id is only relevant to bound regions, which
4422 // are erased at trans time.
4424 binder_id: ast::DUMMY_NODE_ID,
4425 inputs: ty_fold::fold_ty_vec(self, sig.inputs.as_slice()),
4426 output: self.fold_ty(sig.output),
4427 variadic: sig.variadic,
4433 pub trait ExprTyProvider {
4434 fn expr_ty(&self, ex: &ast::Expr) -> t;
4435 fn ty_ctxt<'a>(&'a self) -> &'a ctxt;
4438 impl ExprTyProvider for ctxt {
4439 fn expr_ty(&self, ex: &ast::Expr) -> t {
4443 fn ty_ctxt<'a>(&'a self) -> &'a ctxt {
4448 // Returns the repeat count for a repeating vector expression.
4449 pub fn eval_repeat_count<T: ExprTyProvider>(tcx: &T, count_expr: &ast::Expr) -> uint {
4450 match const_eval::eval_const_expr_partial(tcx, count_expr) {
4451 Ok(ref const_val) => match *const_val {
4452 const_eval::const_int(count) => if count < 0 {
4453 tcx.ty_ctxt().sess.span_err(count_expr.span,
4454 "expected positive integer for \
4455 repeat count but found negative integer");
4458 return count as uint
4460 const_eval::const_uint(count) => return count as uint,
4461 const_eval::const_float(count) => {
4462 tcx.ty_ctxt().sess.span_err(count_expr.span,
4463 "expected positive integer for \
4464 repeat count but found float");
4465 return count as uint;
4467 const_eval::const_str(_) => {
4468 tcx.ty_ctxt().sess.span_err(count_expr.span,
4469 "expected positive integer for \
4470 repeat count but found string");
4473 const_eval::const_bool(_) => {
4474 tcx.ty_ctxt().sess.span_err(count_expr.span,
4475 "expected positive integer for \
4476 repeat count but found boolean");
4479 const_eval::const_binary(_) => {
4480 tcx.ty_ctxt().sess.span_err(count_expr.span,
4481 "expected positive integer for \
4482 repeat count but found binary array");
4487 tcx.ty_ctxt().sess.span_err(count_expr.span,
4488 "expected constant integer for repeat count \
4489 but found variable");
4495 // Determine what purity to check a nested function under
4496 pub fn determine_inherited_purity(parent: (ast::Purity, ast::NodeId),
4497 child: (ast::Purity, ast::NodeId),
4498 child_sigil: ast::Sigil)
4499 -> (ast::Purity, ast::NodeId) {
4500 // If the closure is a stack closure and hasn't had some non-standard
4501 // purity inferred for it, then check it under its parent's purity.
4502 // Otherwise, use its own
4504 ast::BorrowedSigil if child.val0() == ast::ImpureFn => parent,
4509 // Iterate over a type parameter's bounded traits and any supertraits
4510 // of those traits, ignoring kinds.
4511 // Here, the supertraits are the transitive closure of the supertrait
4512 // relation on the supertraits from each bounded trait's constraint
4514 pub fn each_bound_trait_and_supertraits(tcx: &ctxt,
4515 bounds: &[@TraitRef],
4516 f: |@TraitRef| -> bool)
4518 for &bound_trait_ref in bounds.iter() {
4519 let mut supertrait_set = HashMap::new();
4520 let mut trait_refs = Vec::new();
4523 // Seed the worklist with the trait from the bound
4524 supertrait_set.insert(bound_trait_ref.def_id, ());
4525 trait_refs.push(bound_trait_ref);
4527 // Add the given trait ty to the hash map
4528 while i < trait_refs.len() {
4529 debug!("each_bound_trait_and_supertraits(i={:?}, trait_ref={})",
4530 i, trait_refs.get(i).repr(tcx));
4532 if !f(*trait_refs.get(i)) {
4536 // Add supertraits to supertrait_set
4537 let supertrait_refs = trait_ref_supertraits(tcx,
4538 *trait_refs.get(i));
4539 for &supertrait_ref in supertrait_refs.iter() {
4540 debug!("each_bound_trait_and_supertraits(supertrait_ref={})",
4541 supertrait_ref.repr(tcx));
4543 let d_id = supertrait_ref.def_id;
4544 if !supertrait_set.contains_key(&d_id) {
4545 // FIXME(#5527) Could have same trait multiple times
4546 supertrait_set.insert(d_id, ());
4547 trait_refs.push(supertrait_ref);
4557 pub fn count_traits_and_supertraits(tcx: &ctxt,
4558 type_param_defs: &[TypeParameterDef]) -> uint {
4560 for type_param_def in type_param_defs.iter() {
4561 each_bound_trait_and_supertraits(
4562 tcx, type_param_def.bounds.trait_bounds.as_slice(), |_| {
4570 pub fn get_tydesc_ty(tcx: &ctxt) -> Result<t, ~str> {
4571 tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
4572 tcx.intrinsic_defs.borrow().find_copy(&tydesc_lang_item)
4573 .expect("Failed to resolve TyDesc")
4577 pub fn get_opaque_ty(tcx: &ctxt) -> Result<t, ~str> {
4578 tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| {
4579 tcx.intrinsic_defs.borrow().find_copy(&opaque_lang_item)
4580 .expect("Failed to resolve Opaque")
4584 pub fn visitor_object_ty(tcx: &ctxt,
4585 region: ty::Region) -> Result<(@TraitRef, t), ~str> {
4586 let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) {
4588 Err(s) => { return Err(s); }
4590 let substs = substs {
4591 regions: ty::NonerasedRegions(OwnedSlice::empty()),
4595 let trait_ref = @TraitRef { def_id: trait_lang_item, substs: substs };
4599 trait_ref.substs.clone(),
4600 RegionTraitStore(region),
4602 EmptyBuiltinBounds())))
4605 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> @ItemVariances {
4606 lookup_locally_or_in_crate_store(
4607 "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
4608 || @csearch::get_item_variances(&tcx.sess.cstore, item_id))
4611 /// Records a trait-to-implementation mapping.
4612 fn record_trait_implementation(tcx: &ctxt,
4613 trait_def_id: DefId,
4614 implementation: @Impl) {
4615 let implementation_list;
4616 let mut trait_impls = tcx.trait_impls.borrow_mut();
4617 match trait_impls.find(&trait_def_id) {
4619 implementation_list = @RefCell::new(Vec::new());
4620 trait_impls.insert(trait_def_id, implementation_list);
4622 Some(&existing_implementation_list) => {
4623 implementation_list = existing_implementation_list
4627 implementation_list.borrow_mut().push(implementation);
4630 /// Populates the type context with all the implementations for the given type
4632 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
4633 type_id: ast::DefId) {
4634 if type_id.krate == LOCAL_CRATE {
4637 if tcx.populated_external_types.borrow().contains(&type_id) {
4641 csearch::each_implementation_for_type(&tcx.sess.cstore, type_id,
4642 |implementation_def_id| {
4643 let implementation = @csearch::get_impl(tcx, implementation_def_id);
4645 // Record the trait->implementation mappings, if applicable.
4646 let associated_traits = csearch::get_impl_trait(tcx,
4647 implementation.did);
4648 for trait_ref in associated_traits.iter() {
4649 record_trait_implementation(tcx,
4654 // For any methods that use a default implementation, add them to
4655 // the map. This is a bit unfortunate.
4656 for method in implementation.methods.iter() {
4657 for source in method.provided_source.iter() {
4658 tcx.provided_method_sources.borrow_mut()
4659 .insert(method.def_id, *source);
4663 // If this is an inherent implementation, record it.
4664 if associated_traits.is_none() {
4665 let implementation_list;
4666 let mut inherent_impls = tcx.inherent_impls.borrow_mut();
4667 match inherent_impls.find(&type_id) {
4669 implementation_list = @RefCell::new(Vec::new());
4670 inherent_impls.insert(type_id, implementation_list);
4672 Some(&existing_implementation_list) => {
4673 implementation_list = existing_implementation_list;
4676 implementation_list.borrow_mut().push(implementation);
4679 // Store the implementation info.
4680 tcx.impls.borrow_mut().insert(implementation_def_id, implementation);
4683 tcx.populated_external_types.borrow_mut().insert(type_id);
4686 /// Populates the type context with all the implementations for the given
4687 /// trait if necessary.
4688 pub fn populate_implementations_for_trait_if_necessary(
4690 trait_id: ast::DefId) {
4691 if trait_id.krate == LOCAL_CRATE {
4694 if tcx.populated_external_traits.borrow().contains(&trait_id) {
4698 csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id,
4699 |implementation_def_id| {
4700 let implementation = @csearch::get_impl(tcx, implementation_def_id);
4702 // Record the trait->implementation mapping.
4703 record_trait_implementation(tcx, trait_id, implementation);
4705 // For any methods that use a default implementation, add them to
4706 // the map. This is a bit unfortunate.
4707 for method in implementation.methods.iter() {
4708 for source in method.provided_source.iter() {
4709 tcx.provided_method_sources.borrow_mut()
4710 .insert(method.def_id, *source);
4714 // Store the implementation info.
4715 tcx.impls.borrow_mut().insert(implementation_def_id, implementation);
4718 tcx.populated_external_traits.borrow_mut().insert(trait_id);
4721 /// Given the def_id of an impl, return the def_id of the trait it implements.
4722 /// If it implements no trait, return `None`.
4723 pub fn trait_id_of_impl(tcx: &ctxt,
4724 def_id: ast::DefId) -> Option<ast::DefId> {
4725 let node = match tcx.map.find(def_id.node) {
4730 ast_map::NodeItem(item) => {
4732 ast::ItemImpl(_, Some(ref trait_ref), _, _) => {
4733 Some(node_id_to_trait_ref(tcx, trait_ref.ref_id).def_id)
4742 /// If the given def ID describes a method belonging to a trait (either a
4743 /// default method or an implementation of a trait method), return the ID of
4744 /// the trait that the method belongs to. Otherwise, return `None`.
4745 pub fn trait_of_method(tcx: &ctxt, def_id: ast::DefId)
4746 -> Option<ast::DefId> {
4747 if def_id.krate != LOCAL_CRATE {
4748 return csearch::get_trait_of_method(&tcx.sess.cstore, def_id, tcx);
4750 match tcx.methods.borrow().find(&def_id).map(|m| *m) {
4752 match method.container {
4753 TraitContainer(def_id) => Some(def_id),
4754 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
4761 /// If the given def ID describes a method belonging to a trait, (either a
4762 /// default method or an implementation of a trait method), return the ID of
4763 /// the method inside trait definition (this means that if the given def ID
4764 /// is already that of the original trait method, then the return value is
4766 /// Otherwise, return `None`.
4767 pub fn trait_method_of_method(tcx: &ctxt,
4768 def_id: ast::DefId) -> Option<ast::DefId> {
4769 let method = match tcx.methods.borrow().find(&def_id) {
4771 None => return None,
4773 let name = method.ident.name;
4774 match trait_of_method(tcx, def_id) {
4775 Some(trait_did) => {
4776 let trait_methods = ty::trait_methods(tcx, trait_did);
4777 trait_methods.iter()
4778 .position(|m| m.ident.name == name)
4779 .map(|idx| ty::trait_method(tcx, trait_did, idx).def_id)
4785 /// Creates a hash of the type `t` which will be the same no matter what crate
4786 /// context it's calculated within. This is used by the `type_id` intrinsic.
4787 pub fn hash_crate_independent(tcx: &ctxt, t: t, svh: &Svh) -> u64 {
4788 let mut state = sip::SipState::new();
4789 macro_rules! byte( ($b:expr) => { ($b as u8).hash(&mut state) } );
4790 macro_rules! hash( ($e:expr) => { $e.hash(&mut state) } );
4792 let region = |_state: &mut sip::SipState, r: Region| {
4802 tcx.sess.bug("non-static region found when hashing a type")
4806 let vstore = |state: &mut sip::SipState, v: vstore| {
4808 vstore_fixed(_) => 0u8.hash(state),
4809 vstore_uniq => 1u8.hash(state),
4810 vstore_slice(r) => {
4816 let did = |state: &mut sip::SipState, did: DefId| {
4817 let h = if ast_util::is_local(did) {
4820 tcx.sess.cstore.get_crate_hash(did.krate)
4822 h.as_str().hash(state);
4823 did.node.hash(state);
4825 let mt = |state: &mut sip::SipState, mt: mt| {
4826 mt.mutbl.hash(state);
4828 ty::walk_ty(t, |t| {
4829 match ty::get(t).sty {
4832 ty_bool => byte!(2),
4833 ty_char => byte!(3),
4863 vstore(&mut state, v);
4871 region(&mut state, r);
4874 ty_bare_fn(ref b) => {
4879 ty_closure(ref c) => {
4885 region(&mut state, c.region);
4887 ty_trait(~ty::TyTrait { def_id: d, store, mutability: m, bounds, .. }) => {
4891 UniqTraitStore => byte!(0),
4892 RegionTraitStore(r) => {
4894 region(&mut state, r);
4900 ty_struct(d, _) => {
4904 ty_tup(ref inner) => {
4911 did(&mut state, p.def_id);
4917 ty_infer(_) => unreachable!(),
4918 ty_err => byte!(23),
4919 ty_unboxed_vec(m) => {
4930 pub fn to_str(self) -> &'static str {
4933 Contravariant => "-",
4940 pub fn construct_parameter_environment(
4942 self_bound: Option<@TraitRef>,
4943 item_type_params: &[TypeParameterDef],
4944 method_type_params: &[TypeParameterDef],
4945 item_region_params: &[RegionParameterDef],
4946 method_region_params: &[RegionParameterDef],
4947 free_id: ast::NodeId)
4948 -> ParameterEnvironment
4950 /*! See `ParameterEnvironment` struct def'n for details */
4953 // Construct the free substs.
4957 let self_ty = self_bound.map(|t| ty::mk_self(tcx, t.def_id));
4960 let num_item_type_params = item_type_params.len();
4961 let num_method_type_params = method_type_params.len();
4962 let num_type_params = num_item_type_params + num_method_type_params;
4963 let type_params = Vec::from_fn(num_type_params, |i| {
4964 let def_id = if i < num_item_type_params {
4965 item_type_params[i].def_id
4967 method_type_params[i - num_item_type_params].def_id
4970 ty::mk_param(tcx, i, def_id)
4973 // map bound 'a => free 'a
4974 let region_params = {
4975 fn push_region_params(mut accum: Vec<ty::Region>,
4976 free_id: ast::NodeId,
4977 region_params: &[RegionParameterDef])
4978 -> Vec<ty::Region> {
4979 for r in region_params.iter() {
4981 ty::ReFree(ty::FreeRegion {
4983 bound_region: ty::BrNamed(r.def_id, r.name)}));
4988 let t = push_region_params(vec!(), free_id, item_region_params);
4989 push_region_params(t, free_id, method_region_params)
4992 let free_substs = substs {
4995 regions: ty::NonerasedRegions(OwnedSlice::from_vec(region_params))
4999 // Compute the bounds on Self and the type parameters.
5002 let self_bound_substd = self_bound.map(|b| b.subst(tcx, &free_substs));
5003 let type_param_bounds_substd = Vec::from_fn(num_type_params, |i| {
5004 if i < num_item_type_params {
5005 (*item_type_params[i].bounds).subst(tcx, &free_substs)
5007 let j = i - num_item_type_params;
5008 (*method_type_params[j].bounds).subst(tcx, &free_substs)
5012 debug!("construct_parameter_environment: free_id={} \
5014 self_param_bound={} \
5015 type_param_bound={}",
5017 free_substs.repr(tcx),
5018 self_bound_substd.repr(tcx),
5019 type_param_bounds_substd.repr(tcx));
5021 ty::ParameterEnvironment {
5022 free_substs: free_substs,
5023 self_param_bound: self_bound_substd,
5024 type_param_bounds: type_param_bounds_substd,
5029 pub fn empty() -> substs {
5033 regions: NonerasedRegions(OwnedSlice::empty())
5039 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
5041 ast::MutMutable => MutBorrow,
5042 ast::MutImmutable => ImmBorrow,
5046 pub fn to_user_str(&self) -> &'static str {
5048 MutBorrow => "mutable",
5049 ImmBorrow => "immutable",
5050 UniqueImmBorrow => "uniquely immutable",
5054 pub fn to_short_str(&self) -> &'static str {
5058 UniqueImmBorrow => "own",