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;
16 use metadata::csearch;
17 use middle::const_eval;
19 use middle::dependency_format;
20 use middle::freevars::CaptureModeMap;
22 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem};
23 use middle::lang_items::{FnOnceTraitLangItem, OpaqueStructLangItem};
24 use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem};
25 use middle::mem_categorization as mc;
27 use middle::resolve_lifetime;
28 use middle::stability;
29 use middle::subst::{Subst, Substs, VecPerParamSpace};
35 use middle::ty_fold::{TypeFoldable,TypeFolder};
37 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_string};
38 use util::ppaux::{trait_store_to_string, ty_to_string};
39 use util::ppaux::{Repr, UserString};
40 use util::common::{indenter};
41 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet, FnvHashMap};
43 use std::cell::{Cell, RefCell};
47 use std::hash::{Hash, sip, Writer};
48 use std::iter::AdditiveIterator;
52 use std::collections::{HashMap, HashSet};
53 use arena::TypedArena;
55 use syntax::ast::{CrateNum, DefId, FnStyle, Ident, ItemTrait, LOCAL_CRATE};
56 use syntax::ast::{MutImmutable, MutMutable, Name, NamedField, NodeId};
57 use syntax::ast::{Onceness, StmtExpr, StmtSemi, StructField, UnnamedField};
58 use syntax::ast::{Visibility};
59 use syntax::ast_util::{PostExpansionMethod, is_local, lit_is_str};
62 use syntax::attr::AttrMetaMethods;
63 use syntax::codemap::Span;
64 use syntax::parse::token;
65 use syntax::parse::token::InternedString;
66 use syntax::{ast, ast_map};
67 use syntax::util::small_vector::SmallVector;
68 use std::collections::enum_set::{EnumSet, CLike};
72 pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0;
76 #[deriving(PartialEq, Eq, Hash)]
78 pub ident: ast::Ident,
83 pub enum ImplOrTraitItemContainer {
84 TraitContainer(ast::DefId),
85 ImplContainer(ast::DefId),
88 impl ImplOrTraitItemContainer {
89 pub fn id(&self) -> ast::DefId {
91 TraitContainer(id) => id,
92 ImplContainer(id) => id,
98 pub enum ImplOrTraitItem {
99 MethodTraitItem(Rc<Method>),
102 impl ImplOrTraitItem {
103 fn id(&self) -> ImplOrTraitItemId {
105 MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
109 pub fn def_id(&self) -> ast::DefId {
111 MethodTraitItem(ref method) => method.def_id,
115 pub fn ident(&self) -> ast::Ident {
117 MethodTraitItem(ref method) => method.ident,
121 pub fn container(&self) -> ImplOrTraitItemContainer {
123 MethodTraitItem(ref method) => method.container,
129 pub enum ImplOrTraitItemId {
130 MethodTraitItemId(ast::DefId),
133 impl ImplOrTraitItemId {
134 pub fn def_id(&self) -> ast::DefId {
136 MethodTraitItemId(def_id) => def_id,
143 pub ident: ast::Ident,
144 pub generics: ty::Generics,
146 pub explicit_self: ExplicitSelfCategory,
147 pub vis: ast::Visibility,
148 pub def_id: ast::DefId,
149 pub container: ImplOrTraitItemContainer,
151 // If this method is provided, we need to know where it came from
152 pub provided_source: Option<ast::DefId>
156 pub fn new(ident: ast::Ident,
157 generics: ty::Generics,
159 explicit_self: ExplicitSelfCategory,
160 vis: ast::Visibility,
162 container: ImplOrTraitItemContainer,
163 provided_source: Option<ast::DefId>)
169 explicit_self: explicit_self,
172 container: container,
173 provided_source: provided_source
177 pub fn container_id(&self) -> ast::DefId {
178 match self.container {
179 TraitContainer(id) => id,
180 ImplContainer(id) => id,
185 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
188 pub mutbl: ast::Mutability,
191 #[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
192 pub enum TraitStore {
195 /// &Trait and &mut Trait
196 RegionTraitStore(Region, ast::Mutability),
199 #[deriving(Clone, Show)]
200 pub struct field_ty {
203 pub vis: ast::Visibility,
204 pub origin: ast::DefId, // The DefId of the struct in which the field is declared.
207 // Contains information needed to resolve types and (in the future) look up
208 // the types of AST nodes.
209 #[deriving(PartialEq, Eq, Hash)]
210 pub struct creader_cache_key {
216 pub type creader_cache = RefCell<HashMap<creader_cache_key, t>>;
218 pub struct intern_key {
222 // NB: Do not replace this with #[deriving(PartialEq)]. The automatically-derived
223 // implementation will not recurse through sty and you will get stack
225 impl cmp::PartialEq for intern_key {
226 fn eq(&self, other: &intern_key) -> bool {
228 *self.sty == *other.sty
231 fn ne(&self, other: &intern_key) -> bool {
236 impl Eq for intern_key {}
238 impl<W:Writer> Hash<W> for intern_key {
239 fn hash(&self, s: &mut W) {
240 unsafe { (*self.sty).hash(s) }
244 pub enum ast_ty_to_ty_cache_entry {
245 atttce_unresolved, /* not resolved yet */
246 atttce_resolved(t) /* resolved to a type, irrespective of region */
249 #[deriving(Clone, PartialEq, Decodable, Encodable)]
250 pub struct ItemVariances {
251 pub types: VecPerParamSpace<Variance>,
252 pub regions: VecPerParamSpace<Variance>,
255 #[deriving(Clone, PartialEq, Decodable, Encodable, Show)]
257 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
258 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
259 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
260 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
264 pub enum AutoAdjustment {
265 AutoAddEnv(ty::TraitStore),
266 AutoDerefRef(AutoDerefRef)
269 #[deriving(Clone, PartialEq)]
270 pub enum UnsizeKind {
271 // [T, ..n] -> [T], the uint field is n.
273 // An unsize coercion applied to the tail field of a struct.
274 // The uint is the index of the type parameter which is unsized.
275 UnsizeStruct(Box<UnsizeKind>, uint),
276 UnsizeVtable(TyTrait, /* the self type of the trait */ ty::t)
280 pub struct AutoDerefRef {
281 pub autoderefs: uint,
282 pub autoref: Option<AutoRef>
285 #[deriving(Clone, PartialEq)]
287 /// Convert from T to &T
288 /// The third field allows us to wrap other AutoRef adjustments.
289 AutoPtr(Region, ast::Mutability, Option<Box<AutoRef>>),
291 /// Convert [T, ..n] to [T] (or similar, depending on the kind)
292 AutoUnsize(UnsizeKind),
294 /// Convert Box<[T, ..n]> to Box<[T]> or something similar in a Box.
295 /// With DST and Box a library type, this should be replaced by UnsizeStruct.
296 AutoUnsizeUniq(UnsizeKind),
298 /// Convert from T to *T
299 /// Value to thin pointer
300 /// The second field allows us to wrap other AutoRef adjustments.
301 AutoUnsafe(ast::Mutability, Option<Box<AutoRef>>),
304 // Ugly little helper function. The first bool in the returned tuple is true if
305 // there is an 'unsize to trait object' adjustment at the bottom of the
306 // adjustment. If that is surrounded by an AutoPtr, then we also return the
307 // region of the AutoPtr (in the third argument). The second bool is true if the
308 // adjustment is unique.
309 fn autoref_object_region(autoref: &AutoRef) -> (bool, bool, Option<Region>) {
310 fn unsize_kind_is_object(k: &UnsizeKind) -> bool {
312 &UnsizeVtable(..) => true,
313 &UnsizeStruct(box ref k, _) => unsize_kind_is_object(k),
319 &AutoUnsize(ref k) => (unsize_kind_is_object(k), false, None),
320 &AutoUnsizeUniq(ref k) => (unsize_kind_is_object(k), true, None),
321 &AutoPtr(adj_r, _, Some(box ref autoref)) => {
322 let (b, u, r) = autoref_object_region(autoref);
323 if r.is_some() || u {
329 &AutoUnsafe(_, Some(box ref autoref)) => autoref_object_region(autoref),
330 _ => (false, false, None)
334 // If the adjustment introduces a borrowed reference to a trait object, then
335 // returns the region of the borrowed reference.
336 pub fn adjusted_object_region(adj: &AutoAdjustment) -> Option<Region> {
338 &AutoDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
339 let (b, _, r) = autoref_object_region(autoref);
350 // Returns true if there is a trait cast at the bottom of the adjustment.
351 pub fn adjust_is_object(adj: &AutoAdjustment) -> bool {
353 &AutoDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
354 let (b, _, _) = autoref_object_region(autoref);
361 // If possible, returns the type expected from the given adjustment. This is not
362 // possible if the adjustment depends on the type of the adjusted expression.
363 pub fn type_of_adjust(cx: &ctxt, adj: &AutoAdjustment) -> Option<t> {
364 fn type_of_autoref(cx: &ctxt, autoref: &AutoRef) -> Option<t> {
366 &AutoUnsize(ref k) => match k {
367 &UnsizeVtable(TyTrait { def_id, substs: ref substs, bounds }, _) => {
368 Some(mk_trait(cx, def_id, substs.clone(), bounds))
372 &AutoUnsizeUniq(ref k) => match k {
373 &UnsizeVtable(TyTrait { def_id, substs: ref substs, bounds }, _) => {
374 Some(mk_uniq(cx, mk_trait(cx, def_id, substs.clone(), bounds)))
378 &AutoPtr(r, m, Some(box ref autoref)) => {
379 match type_of_autoref(cx, autoref) {
380 Some(t) => Some(mk_rptr(cx, r, mt {mutbl: m, ty: t})),
384 &AutoUnsafe(m, Some(box ref autoref)) => {
385 match type_of_autoref(cx, autoref) {
386 Some(t) => Some(mk_ptr(cx, mt {mutbl: m, ty: t})),
395 &AutoDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
396 type_of_autoref(cx, autoref)
404 /// A restriction that certain types must be the same size. The use of
405 /// `transmute` gives rise to these restrictions.
406 pub struct TransmuteRestriction {
407 /// The span from whence the restriction comes.
409 /// The type being transmuted from.
411 /// The type being transmuted to.
413 /// NodeIf of the transmute intrinsic.
417 /// The data structure to keep track of all the information that typechecker
418 /// generates so that so that it can be reused and doesn't have to be redone
420 pub struct ctxt<'tcx> {
421 /// The arena that types are allocated from.
422 type_arena: &'tcx TypedArena<t_box_>,
424 /// Specifically use a speedy hash algorithm for this hash map, it's used
426 interner: RefCell<FnvHashMap<intern_key, &'tcx t_box_>>,
427 pub next_id: Cell<uint>,
429 pub def_map: resolve::DefMap,
431 pub named_region_map: resolve_lifetime::NamedRegionMap,
433 pub region_maps: middle::region::RegionMaps,
435 /// Stores the types for various nodes in the AST. Note that this table
436 /// is not guaranteed to be populated until after typeck. See
437 /// typeck::check::fn_ctxt for details.
438 pub node_types: node_type_table,
440 /// Stores the type parameters which were substituted to obtain the type
441 /// of this node. This only applies to nodes that refer to entities
442 /// parameterized by type parameters, such as generic fns, types, or
444 pub item_substs: RefCell<NodeMap<ItemSubsts>>,
446 /// Maps from a trait item to the trait item "descriptor"
447 pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem>>,
449 /// Maps from a trait def-id to a list of the def-ids of its trait items
450 pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
452 /// A cache for the trait_items() routine
453 pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem>>>>,
455 pub impl_trait_cache: RefCell<DefIdMap<Option<Rc<ty::TraitRef>>>>,
457 pub trait_refs: RefCell<NodeMap<Rc<TraitRef>>>,
458 pub trait_defs: RefCell<DefIdMap<Rc<TraitDef>>>,
460 /// Maps from node-id of a trait object cast (like `foo as
461 /// Box<Trait>`) to the trait reference.
462 pub object_cast_map: typeck::ObjectCastMap,
464 pub map: ast_map::Map<'tcx>,
465 pub intrinsic_defs: RefCell<DefIdMap<t>>,
466 pub freevars: RefCell<freevars::freevar_map>,
467 pub tcache: type_cache,
468 pub rcache: creader_cache,
469 pub short_names_cache: RefCell<HashMap<t, String>>,
470 pub needs_unwind_cleanup_cache: RefCell<HashMap<t, bool>>,
471 pub tc_cache: RefCell<HashMap<uint, TypeContents>>,
472 pub ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry>>,
473 pub enum_var_cache: RefCell<DefIdMap<Rc<Vec<Rc<VariantInfo>>>>>,
474 pub ty_param_defs: RefCell<NodeMap<TypeParameterDef>>,
475 pub adjustments: RefCell<NodeMap<AutoAdjustment>>,
476 pub normalized_cache: RefCell<HashMap<t, t>>,
477 pub lang_items: middle::lang_items::LanguageItems,
478 /// A mapping of fake provided method def_ids to the default implementation
479 pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
480 pub superstructs: RefCell<DefIdMap<Option<ast::DefId>>>,
481 pub struct_fields: RefCell<DefIdMap<Rc<Vec<field_ty>>>>,
483 /// Maps from def-id of a type or region parameter to its
484 /// (inferred) variance.
485 pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
487 /// True if the variance has been computed yet; false otherwise.
488 pub variance_computed: Cell<bool>,
490 /// A mapping from the def ID of an enum or struct type to the def ID
491 /// of the method that implements its destructor. If the type is not
492 /// present in this map, it does not have a destructor. This map is
493 /// populated during the coherence phase of typechecking.
494 pub destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
496 /// A method will be in this list if and only if it is a destructor.
497 pub destructors: RefCell<DefIdSet>,
499 /// Maps a trait onto a list of impls of that trait.
500 pub trait_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
502 /// Maps a DefId of a type to a list of its inherent impls.
503 /// Contains implementations of methods that are inherent to a type.
504 /// Methods in these implementations don't need to be exported.
505 pub inherent_impls: RefCell<DefIdMap<Rc<Vec<ast::DefId>>>>,
507 /// Maps a DefId of an impl to a list of its items.
508 /// Note that this contains all of the impls that we know about,
509 /// including ones in other crates. It's not clear that this is the best
511 pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
513 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
514 /// present in this set can be warned about.
515 pub used_unsafe: RefCell<NodeSet>,
517 /// Set of nodes which mark locals as mutable which end up getting used at
518 /// some point. Local variable definitions not in this set can be warned
520 pub used_mut_nodes: RefCell<NodeSet>,
522 /// The set of external nominal types whose implementations have been read.
523 /// This is used for lazy resolution of methods.
524 pub populated_external_types: RefCell<DefIdSet>,
526 /// The set of external traits whose implementations have been read. This
527 /// is used for lazy resolution of traits.
528 pub populated_external_traits: RefCell<DefIdSet>,
531 pub upvar_borrow_map: RefCell<UpvarBorrowMap>,
533 /// These two caches are used by const_eval when decoding external statics
534 /// and variants that are found.
535 pub extern_const_statics: RefCell<DefIdMap<ast::NodeId>>,
536 pub extern_const_variants: RefCell<DefIdMap<ast::NodeId>>,
538 pub method_map: typeck::MethodMap,
540 pub dependency_formats: RefCell<dependency_format::Dependencies>,
542 /// Records the type of each unboxed closure. The def ID is the ID of the
543 /// expression defining the unboxed closure.
544 pub unboxed_closures: RefCell<DefIdMap<UnboxedClosure>>,
546 pub node_lint_levels: RefCell<HashMap<(ast::NodeId, lint::LintId),
549 /// The types that must be asserted to be the same size for `transmute`
550 /// to be valid. We gather up these restrictions in the intrinsicck pass
551 /// and check them in trans.
552 pub transmute_restrictions: RefCell<Vec<TransmuteRestriction>>,
554 /// Maps any item's def-id to its stability index.
555 pub stability: RefCell<stability::Index>,
557 /// Maps closures to their capture clauses.
558 pub capture_modes: RefCell<CaptureModeMap>,
569 // a meta-pub flag: subst may be required if the type has parameters, a self
570 // type, or references bound regions
571 needs_subst = 1 | 2 | 8
574 pub type t_box = &'static t_box_;
583 // To reduce refcounting cost, we're representing types as unsafe pointers
584 // throughout the compiler. These are simply casted t_box values. Use ty::get
585 // to cast them back to a box. (Without the cast, compiler performance suffers
586 // ~15%.) This does mean that a t value relies on the ctxt to keep its box
587 // alive, and using ty::get is unsafe when the ctxt is no longer alive.
590 #[allow(raw_pointer_deriving)]
591 #[deriving(Clone, PartialEq, Eq, Hash)]
592 pub struct t { inner: *const t_opaque }
594 impl fmt::Show for t {
595 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
596 write!(f, "{}", get(*self))
600 pub fn get(t: t) -> t_box {
602 let t2: t_box = mem::transmute(t);
607 pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
608 (tb.flags & (flag as uint)) != 0u
610 pub fn type_has_params(t: t) -> bool {
611 tbox_has_flag(get(t), has_params)
613 pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
614 pub fn type_needs_infer(t: t) -> bool {
615 tbox_has_flag(get(t), needs_infer)
617 pub fn type_id(t: t) -> uint { get(t).id }
619 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
620 pub struct BareFnTy {
621 pub fn_style: ast::FnStyle,
626 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
627 pub struct ClosureTy {
628 pub fn_style: ast::FnStyle,
629 pub onceness: ast::Onceness,
630 pub store: TraitStore,
631 pub bounds: ExistentialBounds,
637 * Signature of a function type, which I have arbitrarily
638 * decided to use to refer to the input/output types.
640 * - `binder_id` is the node id where this fn type appeared;
641 * it is used to identify all the bound regions appearing
642 * in the input/output types that are bound by this fn type
643 * (vs some enclosing or enclosed fn type)
644 * - `inputs` is the list of arguments and their modes.
645 * - `output` is the return type.
646 * - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
648 #[deriving(Clone, PartialEq, Eq, Hash)]
650 pub binder_id: ast::NodeId,
656 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
658 pub space: subst::ParamSpace,
663 /// Representation of regions:
664 #[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
666 // Region bound in a type or fn declaration which will be
667 // substituted 'early' -- that is, at the same time when type
668 // parameters are substituted.
669 ReEarlyBound(/* param id */ ast::NodeId,
674 // Region bound in a function scope, which will be substituted when the
675 // function is called. The first argument must be the `binder_id` of
676 // some enclosing function signature.
677 ReLateBound(/* binder_id */ ast::NodeId, BoundRegion),
679 /// When checking a function body, the types of all arguments and so forth
680 /// that refer to bound region parameters are modified to refer to free
681 /// region parameters.
684 /// A concrete region naming some expression within the current function.
687 /// Static data that has an "infinite" lifetime. Top in the region lattice.
690 /// A region variable. Should not exist after typeck.
691 ReInfer(InferRegion),
693 /// Empty lifetime is for data that is never accessed.
694 /// Bottom in the region lattice. We treat ReEmpty somewhat
695 /// specially; at least right now, we do not generate instances of
696 /// it during the GLB computations, but rather
697 /// generate an error instead. This is to improve error messages.
698 /// The only way to get an instance of ReEmpty is to have a region
699 /// variable with no constraints.
704 * Upvars do not get their own node-id. Instead, we use the pair of
705 * the original var id (that is, the root variable that is referenced
706 * by the upvar) and the id of the closure expression.
708 #[deriving(Clone, PartialEq, Eq, Hash)]
710 pub var_id: ast::NodeId,
711 pub closure_expr_id: ast::NodeId,
714 #[deriving(Clone, PartialEq, Eq, Hash, Show, Encodable, Decodable)]
715 pub enum BorrowKind {
716 /// Data must be immutable and is aliasable.
719 /// Data must be immutable but not aliasable. This kind of borrow
720 /// cannot currently be expressed by the user and is used only in
721 /// implicit closure bindings. It is needed when you the closure
722 /// is borrowing or mutating a mutable referent, e.g.:
724 /// let x: &mut int = ...;
725 /// let y = || *x += 5;
727 /// If we were to try to translate this closure into a more explicit
728 /// form, we'd encounter an error with the code as written:
730 /// struct Env { x: & &mut int }
731 /// let x: &mut int = ...;
732 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
733 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
735 /// This is then illegal because you cannot mutate a `&mut` found
736 /// in an aliasable location. To solve, you'd have to translate with
737 /// an `&mut` borrow:
739 /// struct Env { x: & &mut int }
740 /// let x: &mut int = ...;
741 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
742 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
744 /// Now the assignment to `**env.x` is legal, but creating a
745 /// mutable pointer to `x` is not because `x` is not mutable. We
746 /// could fix this by declaring `x` as `let mut x`. This is ok in
747 /// user code, if awkward, but extra weird for closures, since the
748 /// borrow is hidden.
750 /// So we introduce a "unique imm" borrow -- the referent is
751 /// immutable, but not aliasable. This solves the problem. For
752 /// simplicity, we don't give users the way to express this
753 /// borrow, it's just used when translating closures.
756 /// Data is mutable and not aliasable.
761 * Information describing the borrowing of an upvar. This is computed
762 * during `typeck`, specifically by `regionck`. The general idea is
763 * that the compiler analyses treat closures like:
765 * let closure: &'e fn() = || {
766 * x = 1; // upvar x is assigned to
767 * use(y); // upvar y is read
768 * foo(&z); // upvar z is borrowed immutably
771 * as if they were "desugared" to something loosely like:
773 * struct Vars<'x,'y,'z> { x: &'x mut int,
776 * let closure: &'e fn() = {
782 * let env: &'e mut Vars<'x,'y,'z> = &mut Vars { x: &'x mut x,
788 * This is basically what happens at runtime. The closure is basically
789 * an existentially quantified version of the `(env, f)` pair.
791 * This data structure indicates the region and mutability of a single
792 * one of the `x...z` borrows.
794 * It may not be obvious why each borrowed variable gets its own
795 * lifetime (in the desugared version of the example, these are indicated
796 * by the lifetime parameters `'x`, `'y`, and `'z` in the `Vars` definition).
797 * Each such lifetime must encompass the lifetime `'e` of the closure itself,
798 * but need not be identical to it. The reason that this makes sense:
800 * - Callers are only permitted to invoke the closure, and hence to
801 * use the pointers, within the lifetime `'e`, so clearly `'e` must
802 * be a sublifetime of `'x...'z`.
803 * - The closure creator knows which upvars were borrowed by the closure
804 * and thus `x...z` will be reserved for `'x...'z` respectively.
805 * - Through mutation, the borrowed upvars can actually escape
806 * the closure, so sometimes it is necessary for them to be larger
807 * than the closure lifetime itself.
809 #[deriving(PartialEq, Clone, Encodable, Decodable)]
810 pub struct UpvarBorrow {
811 pub kind: BorrowKind,
812 pub region: ty::Region,
815 pub type UpvarBorrowMap = HashMap<UpvarId, UpvarBorrow>;
818 pub fn is_bound(&self) -> bool {
820 &ty::ReEarlyBound(..) => true,
821 &ty::ReLateBound(..) => true,
827 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
828 pub struct FreeRegion {
829 pub scope_id: NodeId,
830 pub bound_region: BoundRegion
833 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
834 pub enum BoundRegion {
835 /// An anonymous region parameter for a given fn (&T)
838 /// Named region parameters for functions (a in &'a T)
840 /// The def-id is needed to distinguish free regions in
841 /// the event of shadowing.
842 BrNamed(ast::DefId, ast::Name),
844 /// Fresh bound identifiers created during GLB computations.
853 macro_rules! def_prim_ty(
854 ($name:ident, $sty:expr, $id:expr) => (
855 pub static $name: t_box_ = t_box_ {
863 def_prim_ty!(TY_NIL, super::ty_nil, 0)
864 def_prim_ty!(TY_BOOL, super::ty_bool, 1)
865 def_prim_ty!(TY_CHAR, super::ty_char, 2)
866 def_prim_ty!(TY_INT, super::ty_int(ast::TyI), 3)
867 def_prim_ty!(TY_I8, super::ty_int(ast::TyI8), 4)
868 def_prim_ty!(TY_I16, super::ty_int(ast::TyI16), 5)
869 def_prim_ty!(TY_I32, super::ty_int(ast::TyI32), 6)
870 def_prim_ty!(TY_I64, super::ty_int(ast::TyI64), 7)
871 def_prim_ty!(TY_UINT, super::ty_uint(ast::TyU), 8)
872 def_prim_ty!(TY_U8, super::ty_uint(ast::TyU8), 9)
873 def_prim_ty!(TY_U16, super::ty_uint(ast::TyU16), 10)
874 def_prim_ty!(TY_U32, super::ty_uint(ast::TyU32), 11)
875 def_prim_ty!(TY_U64, super::ty_uint(ast::TyU64), 12)
876 def_prim_ty!(TY_F32, super::ty_float(ast::TyF32), 14)
877 def_prim_ty!(TY_F64, super::ty_float(ast::TyF64), 15)
879 pub static TY_BOT: t_box_ = t_box_ {
882 flags: super::has_ty_bot as uint,
885 pub static TY_ERR: t_box_ = t_box_ {
888 flags: super::has_ty_err as uint,
891 pub static LAST_PRIMITIVE_ID: uint = 18;
894 // NB: If you change this, you'll probably want to change the corresponding
895 // AST structure in libsyntax/ast.rs as well.
896 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
903 ty_uint(ast::UintTy),
904 ty_float(ast::FloatTy),
905 /// Substs here, possibly against intuition, *may* contain `ty_param`s.
906 /// That is, even after substitution it is possible that there are type
907 /// variables. This happens when the `ty_enum` corresponds to an enum
908 /// definition and not a concrete use of it. To get the correct `ty_enum`
909 /// from the tcx, use the `NodeId` from the `ast::Ty` and look it up in
910 /// the `ast_ty_to_ty_cache`. This is probably true for `ty_struct` as
912 ty_enum(DefId, Substs),
916 ty_vec(t, Option<uint>), // Second field is length.
919 ty_bare_fn(BareFnTy),
920 ty_closure(Box<ClosureTy>),
921 ty_trait(Box<TyTrait>),
922 ty_struct(DefId, Substs),
923 ty_unboxed_closure(DefId, Region),
926 ty_param(ParamTy), // type parameter
927 ty_open(t), // A deref'ed fat pointer, i.e., a dynamically sized value
928 // and its size. Only ever used in trans. It is not necessary
929 // earlier since we don't need to distinguish a DST with its
930 // size (e.g., in a deref) vs a DST with the size elsewhere (
931 // e.g., in a field).
933 ty_infer(InferTy), // something used only during inference/typeck
934 ty_err, // Also only used during inference/typeck, to represent
935 // the type of an erroneous expression (helps cut down
936 // on non-useful type error messages)
939 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
943 pub bounds: ExistentialBounds
946 #[deriving(PartialEq, Eq, Hash, Show)]
947 pub struct TraitRef {
952 #[deriving(Clone, PartialEq)]
953 pub enum IntVarValue {
955 UintType(ast::UintTy),
958 #[deriving(Clone, Show)]
959 pub enum terr_vstore_kind {
966 #[deriving(Clone, Show)]
967 pub struct expected_found<T> {
972 // Data structures used in type unification
973 #[deriving(Clone, Show)]
976 terr_fn_style_mismatch(expected_found<FnStyle>),
977 terr_onceness_mismatch(expected_found<Onceness>),
978 terr_abi_mismatch(expected_found<abi::Abi>),
980 terr_sigil_mismatch(expected_found<TraitStore>),
985 terr_tuple_size(expected_found<uint>),
986 terr_ty_param_size(expected_found<uint>),
987 terr_record_size(expected_found<uint>),
988 terr_record_mutability,
989 terr_record_fields(expected_found<Ident>),
991 terr_regions_does_not_outlive(Region, Region),
992 terr_regions_not_same(Region, Region),
993 terr_regions_no_overlap(Region, Region),
994 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
995 terr_regions_overly_polymorphic(BoundRegion, Region),
996 terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
997 terr_sorts(expected_found<t>),
998 terr_integer_as_char,
999 terr_int_mismatch(expected_found<IntVarValue>),
1000 terr_float_mismatch(expected_found<ast::FloatTy>),
1001 terr_traits(expected_found<ast::DefId>),
1002 terr_builtin_bounds(expected_found<BuiltinBounds>),
1003 terr_variadic_mismatch(expected_found<bool>),
1007 /// Bounds suitable for a named type parameter like `A` in `fn foo<A>`
1008 /// as well as the existential type parameter in an object type.
1009 #[deriving(PartialEq, Eq, Hash, Clone, Show)]
1010 pub struct ParamBounds {
1011 pub opt_region_bound: Option<ty::Region>,
1012 pub builtin_bounds: BuiltinBounds,
1013 pub trait_bounds: Vec<Rc<TraitRef>>
1016 /// Bounds suitable for an existentially quantified type parameter
1017 /// such as those that appear in object types or closure types. The
1018 /// major difference between this case and `ParamBounds` is that
1019 /// general purpose trait bounds are omitted.
1020 #[deriving(PartialEq, Eq, Hash, Clone, Show)]
1021 pub struct ExistentialBounds {
1022 pub region_bound: ty::Region,
1023 pub builtin_bounds: BuiltinBounds
1026 pub type BuiltinBounds = EnumSet<BuiltinBound>;
1028 #[deriving(Clone, Encodable, PartialEq, Eq, Decodable, Hash, Show)]
1030 pub enum BuiltinBound {
1037 pub fn empty_builtin_bounds() -> BuiltinBounds {
1041 pub fn all_builtin_bounds() -> BuiltinBounds {
1042 let mut set = EnumSet::empty();
1044 set.add(BoundSized);
1049 pub fn region_existential_bound(r: ty::Region) -> ExistentialBounds {
1051 * An existential bound that does not implement any traits.
1054 ty::ExistentialBounds { region_bound: r,
1055 builtin_bounds: empty_builtin_bounds() }
1058 impl CLike for BuiltinBound {
1059 fn to_uint(&self) -> uint {
1062 fn from_uint(v: uint) -> BuiltinBound {
1063 unsafe { mem::transmute(v) }
1067 #[deriving(Clone, PartialEq, Eq, Hash)]
1072 #[deriving(Clone, PartialEq, Eq, Hash)]
1077 #[deriving(Clone, PartialEq, Eq, Hash)]
1078 pub struct FloatVid {
1082 #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)]
1083 pub struct RegionVid {
1087 #[deriving(Clone, PartialEq, Eq, Hash)]
1094 // FIXME -- once integral fallback is impl'd, we should remove
1095 // this type. It's only needed to prevent spurious errors for
1096 // integers whose type winds up never being constrained.
1097 SkolemizedIntTy(uint),
1100 #[deriving(Clone, Encodable, Decodable, Eq, Hash, Show)]
1101 pub enum InferRegion {
1103 ReSkolemized(uint, BoundRegion)
1106 impl cmp::PartialEq for InferRegion {
1107 fn eq(&self, other: &InferRegion) -> bool {
1108 match ((*self), *other) {
1109 (ReVar(rva), ReVar(rvb)) => {
1112 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
1118 fn ne(&self, other: &InferRegion) -> bool {
1119 !((*self) == (*other))
1123 impl fmt::Show for TyVid {
1124 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
1125 write!(f, "<generic #{}>", self.index)
1129 impl fmt::Show for IntVid {
1130 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1131 write!(f, "<generic integer #{}>", self.index)
1135 impl fmt::Show for FloatVid {
1136 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1137 write!(f, "<generic float #{}>", self.index)
1141 impl fmt::Show for RegionVid {
1142 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1143 write!(f, "'<generic lifetime #{}>", self.index)
1147 impl fmt::Show for FnSig {
1148 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1149 // grr, without tcx not much we can do.
1154 impl fmt::Show for InferTy {
1155 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1157 TyVar(ref v) => v.fmt(f),
1158 IntVar(ref v) => v.fmt(f),
1159 FloatVar(ref v) => v.fmt(f),
1160 SkolemizedTy(v) => write!(f, "SkolemizedTy({})", v),
1161 SkolemizedIntTy(v) => write!(f, "SkolemizedIntTy({})", v),
1166 impl fmt::Show for IntVarValue {
1167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1169 IntType(ref v) => v.fmt(f),
1170 UintType(ref v) => v.fmt(f),
1175 #[deriving(Clone, Show)]
1176 pub struct TypeParameterDef {
1177 pub ident: ast::Ident,
1178 pub def_id: ast::DefId,
1179 pub space: subst::ParamSpace,
1181 pub bounds: ParamBounds,
1182 pub default: Option<ty::t>,
1185 #[deriving(Encodable, Decodable, Clone, Show)]
1186 pub struct RegionParameterDef {
1187 pub name: ast::Name,
1188 pub def_id: ast::DefId,
1189 pub space: subst::ParamSpace,
1191 pub bounds: Vec<ty::Region>,
1194 /// Information about the type/lifetime parameters associated with an
1195 /// item or method. Analogous to ast::Generics.
1196 #[deriving(Clone, Show)]
1197 pub struct Generics {
1198 pub types: VecPerParamSpace<TypeParameterDef>,
1199 pub regions: VecPerParamSpace<RegionParameterDef>,
1203 pub fn empty() -> Generics {
1204 Generics { types: VecPerParamSpace::empty(),
1205 regions: VecPerParamSpace::empty() }
1208 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
1209 !self.types.is_empty_in(space)
1212 pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
1213 !self.regions.is_empty_in(space)
1218 pub fn self_ty(&self) -> ty::t {
1219 self.substs.self_ty().unwrap()
1223 /// When type checking, we use the `ParameterEnvironment` to track
1224 /// details about the type/lifetime parameters that are in scope.
1225 /// It primarily stores the bounds information.
1227 /// Note: This information might seem to be redundant with the data in
1228 /// `tcx.ty_param_defs`, but it is not. That table contains the
1229 /// parameter definitions from an "outside" perspective, but this
1230 /// struct will contain the bounds for a parameter as seen from inside
1231 /// the function body. Currently the only real distinction is that
1232 /// bound lifetime parameters are replaced with free ones, but in the
1233 /// future I hope to refine the representation of types so as to make
1234 /// more distinctions clearer.
1235 pub struct ParameterEnvironment {
1236 /// A substitution that can be applied to move from
1237 /// the "outer" view of a type or method to the "inner" view.
1238 /// In general, this means converting from bound parameters to
1239 /// free parameters. Since we currently represent bound/free type
1240 /// parameters in the same way, this only has an affect on regions.
1241 pub free_substs: Substs,
1243 /// Bounds on the various type parameters
1244 pub bounds: VecPerParamSpace<ParamBounds>,
1246 /// Each type parameter has an implicit region bound that
1247 /// indicates it must outlive at least the function body (the user
1248 /// may specify stronger requirements). This field indicates the
1249 /// region of the callee.
1250 pub implicit_region_bound: ty::Region,
1252 /// Obligations that the caller must satisfy. This is basically
1253 /// the set of bounds on the in-scope type parameters, translated
1254 /// into Obligations.
1256 /// Note: This effectively *duplicates* the `bounds` array for
1258 pub caller_obligations: VecPerParamSpace<traits::Obligation>,
1261 impl ParameterEnvironment {
1262 pub fn for_item(cx: &ctxt, id: NodeId) -> ParameterEnvironment {
1263 match cx.map.find(id) {
1264 Some(ast_map::NodeImplItem(ref impl_item)) => {
1266 ast::MethodImplItem(ref method) => {
1267 let method_def_id = ast_util::local_def(id);
1268 match ty::impl_or_trait_item(cx, method_def_id) {
1269 MethodTraitItem(ref method_ty) => {
1270 let method_generics = &method_ty.generics;
1271 construct_parameter_environment(
1275 method.pe_body().id)
1281 Some(ast_map::NodeTraitItem(trait_method)) => {
1282 match *trait_method {
1283 ast::RequiredMethod(ref required) => {
1284 cx.sess.span_bug(required.span,
1285 "ParameterEnvironment::from_item():
1286 can't create a parameter \
1287 environment for required trait \
1290 ast::ProvidedMethod(ref method) => {
1291 let method_def_id = ast_util::local_def(id);
1292 match ty::impl_or_trait_item(cx, method_def_id) {
1293 MethodTraitItem(ref method_ty) => {
1294 let method_generics = &method_ty.generics;
1295 construct_parameter_environment(
1299 method.pe_body().id)
1305 Some(ast_map::NodeItem(item)) => {
1307 ast::ItemFn(_, _, _, _, ref body) => {
1308 // We assume this is a function.
1309 let fn_def_id = ast_util::local_def(id);
1310 let fn_pty = ty::lookup_item_type(cx, fn_def_id);
1312 construct_parameter_environment(cx,
1318 ast::ItemStruct(..) |
1320 ast::ItemStatic(..) => {
1321 let def_id = ast_util::local_def(id);
1322 let pty = ty::lookup_item_type(cx, def_id);
1323 construct_parameter_environment(cx, item.span,
1327 cx.sess.span_bug(item.span,
1328 "ParameterEnvironment::from_item():
1329 can't create a parameter \
1330 environment for this kind of item")
1335 cx.sess.bug(format!("ParameterEnvironment::from_item(): \
1336 `{}` is not an item",
1337 cx.map.node_to_string(id)).as_slice())
1345 /// - `generics`: the set of type parameters and their bounds
1346 /// - `ty`: the base types, which may reference the parameters defined
1348 #[deriving(Clone, Show)]
1349 pub struct Polytype {
1350 pub generics: Generics,
1354 /// As `Polytype` but for a trait ref.
1355 pub struct TraitDef {
1356 /// Generic type definitions. Note that `Self` is listed in here
1357 /// as having a single bound, the trait itself (e.g., in the trait
1358 /// `Eq`, there is a single bound `Self : Eq`). This is so that
1359 /// default methods get to assume that the `Self` parameters
1360 /// implements the trait.
1361 pub generics: Generics,
1363 /// The "supertrait" bounds.
1364 pub bounds: ParamBounds,
1365 pub trait_ref: Rc<ty::TraitRef>,
1368 /// Records the substitutions used to translate the polytype for an
1369 /// item into the monotype of an item reference.
1371 pub struct ItemSubsts {
1375 pub type type_cache = RefCell<DefIdMap<Polytype>>;
1377 pub type node_type_table = RefCell<HashMap<uint,t>>;
1379 /// Records information about each unboxed closure.
1381 pub struct UnboxedClosure {
1382 /// The type of the unboxed closure.
1383 pub closure_type: ClosureTy,
1384 /// The kind of unboxed closure this is.
1385 pub kind: UnboxedClosureKind,
1388 #[deriving(Clone, PartialEq, Eq)]
1389 pub enum UnboxedClosureKind {
1390 FnUnboxedClosureKind,
1391 FnMutUnboxedClosureKind,
1392 FnOnceUnboxedClosureKind,
1395 impl UnboxedClosureKind {
1396 pub fn trait_did(&self, cx: &ctxt) -> ast::DefId {
1397 let result = match *self {
1398 FnUnboxedClosureKind => cx.lang_items.require(FnTraitLangItem),
1399 FnMutUnboxedClosureKind => {
1400 cx.lang_items.require(FnMutTraitLangItem)
1402 FnOnceUnboxedClosureKind => {
1403 cx.lang_items.require(FnOnceTraitLangItem)
1407 Ok(trait_did) => trait_did,
1408 Err(err) => cx.sess.fatal(err.as_slice()),
1413 pub fn mk_ctxt<'tcx>(s: Session,
1414 type_arena: &'tcx TypedArena<t_box_>,
1415 dm: resolve::DefMap,
1416 named_region_map: resolve_lifetime::NamedRegionMap,
1417 map: ast_map::Map<'tcx>,
1418 freevars: freevars::freevar_map,
1419 capture_modes: freevars::CaptureModeMap,
1420 region_maps: middle::region::RegionMaps,
1421 lang_items: middle::lang_items::LanguageItems,
1422 stability: stability::Index) -> ctxt<'tcx> {
1424 type_arena: type_arena,
1425 interner: RefCell::new(FnvHashMap::new()),
1426 named_region_map: named_region_map,
1427 item_variance_map: RefCell::new(DefIdMap::new()),
1428 variance_computed: Cell::new(false),
1429 next_id: Cell::new(primitives::LAST_PRIMITIVE_ID),
1432 region_maps: region_maps,
1433 node_types: RefCell::new(HashMap::new()),
1434 item_substs: RefCell::new(NodeMap::new()),
1435 trait_refs: RefCell::new(NodeMap::new()),
1436 trait_defs: RefCell::new(DefIdMap::new()),
1437 object_cast_map: RefCell::new(NodeMap::new()),
1439 intrinsic_defs: RefCell::new(DefIdMap::new()),
1440 freevars: RefCell::new(freevars),
1441 tcache: RefCell::new(DefIdMap::new()),
1442 rcache: RefCell::new(HashMap::new()),
1443 short_names_cache: RefCell::new(HashMap::new()),
1444 needs_unwind_cleanup_cache: RefCell::new(HashMap::new()),
1445 tc_cache: RefCell::new(HashMap::new()),
1446 ast_ty_to_ty_cache: RefCell::new(NodeMap::new()),
1447 enum_var_cache: RefCell::new(DefIdMap::new()),
1448 impl_or_trait_items: RefCell::new(DefIdMap::new()),
1449 trait_item_def_ids: RefCell::new(DefIdMap::new()),
1450 trait_items_cache: RefCell::new(DefIdMap::new()),
1451 impl_trait_cache: RefCell::new(DefIdMap::new()),
1452 ty_param_defs: RefCell::new(NodeMap::new()),
1453 adjustments: RefCell::new(NodeMap::new()),
1454 normalized_cache: RefCell::new(HashMap::new()),
1455 lang_items: lang_items,
1456 provided_method_sources: RefCell::new(DefIdMap::new()),
1457 superstructs: RefCell::new(DefIdMap::new()),
1458 struct_fields: RefCell::new(DefIdMap::new()),
1459 destructor_for_type: RefCell::new(DefIdMap::new()),
1460 destructors: RefCell::new(DefIdSet::new()),
1461 trait_impls: RefCell::new(DefIdMap::new()),
1462 inherent_impls: RefCell::new(DefIdMap::new()),
1463 impl_items: RefCell::new(DefIdMap::new()),
1464 used_unsafe: RefCell::new(NodeSet::new()),
1465 used_mut_nodes: RefCell::new(NodeSet::new()),
1466 populated_external_types: RefCell::new(DefIdSet::new()),
1467 populated_external_traits: RefCell::new(DefIdSet::new()),
1468 upvar_borrow_map: RefCell::new(HashMap::new()),
1469 extern_const_statics: RefCell::new(DefIdMap::new()),
1470 extern_const_variants: RefCell::new(DefIdMap::new()),
1471 method_map: RefCell::new(FnvHashMap::new()),
1472 dependency_formats: RefCell::new(HashMap::new()),
1473 unboxed_closures: RefCell::new(DefIdMap::new()),
1474 node_lint_levels: RefCell::new(HashMap::new()),
1475 transmute_restrictions: RefCell::new(Vec::new()),
1476 stability: RefCell::new(stability),
1477 capture_modes: RefCell::new(capture_modes),
1481 // Type constructors
1483 // Interns a type/name combination, stores the resulting box in cx.interner,
1484 // and returns the box as cast to an unsafe ptr (see comments for t above).
1485 pub fn mk_t(cx: &ctxt, st: sty) -> t {
1486 // Check for primitive types.
1488 ty_nil => return mk_nil(),
1489 ty_err => return mk_err(),
1490 ty_bool => return mk_bool(),
1491 ty_int(i) => return mk_mach_int(i),
1492 ty_uint(u) => return mk_mach_uint(u),
1493 ty_float(f) => return mk_mach_float(f),
1494 ty_char => return mk_char(),
1495 ty_bot => return mk_bot(),
1499 let key = intern_key { sty: &st };
1501 match cx.interner.borrow().find(&key) {
1502 Some(t) => unsafe { return mem::transmute(&t.sty); },
1507 fn rflags(r: Region) -> uint {
1508 (has_regions as uint) | {
1510 ty::ReInfer(_) => needs_infer as uint,
1515 fn sflags(substs: &Substs) -> uint {
1517 let mut i = substs.types.iter();
1519 f |= get(*tt).flags;
1521 match substs.regions {
1522 subst::ErasedRegions => {}
1523 subst::NonerasedRegions(ref regions) => {
1524 for r in regions.iter() {
1531 fn flags_for_bounds(bounds: &ExistentialBounds) -> uint {
1532 rflags(bounds.region_bound)
1535 &ty_nil | &ty_bool | &ty_char | &ty_int(_) | &ty_float(_) | &ty_uint(_) |
1537 // You might think that we could just return ty_err for
1538 // any type containing ty_err as a component, and get
1539 // rid of the has_ty_err flag -- likewise for ty_bot (with
1540 // the exception of function types that return bot).
1541 // But doing so caused sporadic memory corruption, and
1542 // neither I (tjc) nor nmatsakis could figure out why,
1543 // so we're doing it this way.
1544 &ty_bot => flags |= has_ty_bot as uint,
1545 &ty_err => flags |= has_ty_err as uint,
1546 &ty_param(ref p) => {
1547 if p.space == subst::SelfSpace {
1548 flags |= has_self as uint;
1550 flags |= has_params as uint;
1553 &ty_unboxed_closure(_, ref region) => flags |= rflags(*region),
1554 &ty_infer(_) => flags |= needs_infer as uint,
1555 &ty_enum(_, ref substs) | &ty_struct(_, ref substs) => {
1556 flags |= sflags(substs);
1558 &ty_trait(box TyTrait { ref substs, ref bounds, .. }) => {
1559 flags |= sflags(substs);
1560 flags |= flags_for_bounds(bounds);
1562 &ty_box(tt) | &ty_uniq(tt) | &ty_vec(tt, _) | &ty_open(tt) => {
1563 flags |= get(tt).flags
1566 flags |= get(m.ty).flags;
1568 &ty_rptr(r, ref m) => {
1570 flags |= get(m.ty).flags;
1572 &ty_tup(ref ts) => for tt in ts.iter() { flags |= get(*tt).flags; },
1573 &ty_bare_fn(ref f) => {
1574 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1575 flags |= get(f.sig.output).flags;
1576 // T -> _|_ is *not* _|_ !
1577 flags &= !(has_ty_bot as uint);
1579 &ty_closure(ref f) => {
1581 RegionTraitStore(r, _) => {
1586 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1587 flags |= get(f.sig.output).flags;
1588 // T -> _|_ is *not* _|_ !
1589 flags &= !(has_ty_bot as uint);
1590 flags |= flags_for_bounds(&f.bounds);
1594 let t = cx.type_arena.alloc(t_box_ {
1596 id: cx.next_id.get(),
1600 let sty_ptr = &t.sty as *const sty;
1602 let key = intern_key {
1606 cx.interner.borrow_mut().insert(key, t);
1608 cx.next_id.set(cx.next_id.get() + 1);
1611 mem::transmute::<*const sty, t>(sty_ptr)
1616 pub fn mk_prim_t(primitive: &'static t_box_) -> t {
1618 mem::transmute::<&'static t_box_, t>(primitive)
1623 pub fn mk_nil() -> t { mk_prim_t(&primitives::TY_NIL) }
1626 pub fn mk_err() -> t { mk_prim_t(&primitives::TY_ERR) }
1629 pub fn mk_bot() -> t { mk_prim_t(&primitives::TY_BOT) }
1632 pub fn mk_bool() -> t { mk_prim_t(&primitives::TY_BOOL) }
1635 pub fn mk_int() -> t { mk_prim_t(&primitives::TY_INT) }
1638 pub fn mk_i8() -> t { mk_prim_t(&primitives::TY_I8) }
1641 pub fn mk_i16() -> t { mk_prim_t(&primitives::TY_I16) }
1644 pub fn mk_i32() -> t { mk_prim_t(&primitives::TY_I32) }
1647 pub fn mk_i64() -> t { mk_prim_t(&primitives::TY_I64) }
1650 pub fn mk_f32() -> t { mk_prim_t(&primitives::TY_F32) }
1653 pub fn mk_f64() -> t { mk_prim_t(&primitives::TY_F64) }
1656 pub fn mk_uint() -> t { mk_prim_t(&primitives::TY_UINT) }
1659 pub fn mk_u8() -> t { mk_prim_t(&primitives::TY_U8) }
1662 pub fn mk_u16() -> t { mk_prim_t(&primitives::TY_U16) }
1665 pub fn mk_u32() -> t { mk_prim_t(&primitives::TY_U32) }
1668 pub fn mk_u64() -> t { mk_prim_t(&primitives::TY_U64) }
1670 pub fn mk_mach_int(tm: ast::IntTy) -> t {
1672 ast::TyI => mk_int(),
1673 ast::TyI8 => mk_i8(),
1674 ast::TyI16 => mk_i16(),
1675 ast::TyI32 => mk_i32(),
1676 ast::TyI64 => mk_i64(),
1680 pub fn mk_mach_uint(tm: ast::UintTy) -> t {
1682 ast::TyU => mk_uint(),
1683 ast::TyU8 => mk_u8(),
1684 ast::TyU16 => mk_u16(),
1685 ast::TyU32 => mk_u32(),
1686 ast::TyU64 => mk_u64(),
1690 pub fn mk_mach_float(tm: ast::FloatTy) -> t {
1692 ast::TyF32 => mk_f32(),
1693 ast::TyF64 => mk_f64(),
1698 pub fn mk_char() -> t { mk_prim_t(&primitives::TY_CHAR) }
1700 pub fn mk_str(cx: &ctxt) -> t {
1704 pub fn mk_str_slice(cx: &ctxt, r: Region, m: ast::Mutability) -> t {
1707 ty: mk_t(cx, ty_str),
1712 pub fn mk_enum(cx: &ctxt, did: ast::DefId, substs: Substs) -> t {
1713 // take a copy of substs so that we own the vectors inside
1714 mk_t(cx, ty_enum(did, substs))
1717 pub fn mk_box(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_box(ty)) }
1719 pub fn mk_uniq(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_uniq(ty)) }
1721 pub fn mk_ptr(cx: &ctxt, tm: mt) -> t { mk_t(cx, ty_ptr(tm)) }
1723 pub fn mk_rptr(cx: &ctxt, r: Region, tm: mt) -> t { mk_t(cx, ty_rptr(r, tm)) }
1725 pub fn mk_mut_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1726 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
1728 pub fn mk_imm_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1729 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
1732 pub fn mk_mut_ptr(cx: &ctxt, ty: t) -> t {
1733 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
1736 pub fn mk_imm_ptr(cx: &ctxt, ty: t) -> t {
1737 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
1740 pub fn mk_nil_ptr(cx: &ctxt) -> t {
1741 mk_ptr(cx, mt {ty: mk_nil(), mutbl: ast::MutImmutable})
1744 pub fn mk_vec(cx: &ctxt, t: t, sz: Option<uint>) -> t {
1745 mk_t(cx, ty_vec(t, sz))
1748 pub fn mk_slice(cx: &ctxt, r: Region, tm: mt) -> t {
1751 ty: mk_vec(cx, tm.ty, None),
1756 pub fn mk_tup(cx: &ctxt, ts: Vec<t>) -> t { mk_t(cx, ty_tup(ts)) }
1758 pub fn mk_closure(cx: &ctxt, fty: ClosureTy) -> t {
1759 mk_t(cx, ty_closure(box fty))
1762 pub fn mk_bare_fn(cx: &ctxt, fty: BareFnTy) -> t {
1763 mk_t(cx, ty_bare_fn(fty))
1766 pub fn mk_ctor_fn(cx: &ctxt,
1767 binder_id: ast::NodeId,
1768 input_tys: &[ty::t],
1769 output: ty::t) -> t {
1770 let input_args = input_tys.iter().map(|t| *t).collect();
1773 fn_style: ast::NormalFn,
1776 binder_id: binder_id,
1785 pub fn mk_trait(cx: &ctxt,
1788 bounds: ExistentialBounds)
1790 // take a copy of substs so that we own the vectors inside
1791 let inner = box TyTrait {
1796 mk_t(cx, ty_trait(inner))
1799 pub fn mk_struct(cx: &ctxt, struct_id: ast::DefId, substs: Substs) -> t {
1800 // take a copy of substs so that we own the vectors inside
1801 mk_t(cx, ty_struct(struct_id, substs))
1804 pub fn mk_unboxed_closure(cx: &ctxt, closure_id: ast::DefId, region: Region)
1806 mk_t(cx, ty_unboxed_closure(closure_id, region))
1809 pub fn mk_var(cx: &ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) }
1811 pub fn mk_int_var(cx: &ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) }
1813 pub fn mk_float_var(cx: &ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) }
1815 pub fn mk_infer(cx: &ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) }
1817 pub fn mk_param(cx: &ctxt, space: subst::ParamSpace, n: uint, k: DefId) -> t {
1818 mk_t(cx, ty_param(ParamTy { space: space, idx: n, def_id: k }))
1821 pub fn mk_self_type(cx: &ctxt, did: ast::DefId) -> t {
1822 mk_param(cx, subst::SelfSpace, 0, did)
1825 pub fn mk_param_from_def(cx: &ctxt, def: &TypeParameterDef) -> t {
1826 mk_param(cx, def.space, def.index, def.def_id)
1829 pub fn mk_open(cx: &ctxt, t: t) -> t { mk_t(cx, ty_open(t)) }
1831 pub fn walk_ty(ty: t, f: |t|) {
1832 maybe_walk_ty(ty, |t| { f(t); true });
1835 pub fn maybe_walk_ty(ty: t, f: |t| -> bool) {
1840 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) |
1841 ty_str | ty_infer(_) | ty_param(_) | ty_unboxed_closure(_, _) | ty_err => {}
1842 ty_box(ty) | ty_uniq(ty) | ty_vec(ty, _) | ty_open(ty) => maybe_walk_ty(ty, f),
1843 ty_ptr(ref tm) | ty_rptr(_, ref tm) => {
1844 maybe_walk_ty(tm.ty, f);
1846 ty_enum(_, ref substs) | ty_struct(_, ref substs) |
1847 ty_trait(box TyTrait { ref substs, .. }) => {
1848 for subty in (*substs).types.iter() {
1849 maybe_walk_ty(*subty, |x| f(x));
1852 ty_tup(ref ts) => { for tt in ts.iter() { maybe_walk_ty(*tt, |x| f(x)); } }
1853 ty_bare_fn(ref ft) => {
1854 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1855 maybe_walk_ty(ft.sig.output, f);
1857 ty_closure(ref ft) => {
1858 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1859 maybe_walk_ty(ft.sig.output, f);
1864 // Folds types from the bottom up.
1865 pub fn fold_ty(cx: &ctxt, t0: t, fldop: |t| -> t) -> t {
1866 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
1870 pub fn walk_regions_and_ty(cx: &ctxt, ty: t, fldr: |r: Region|, fldt: |t: t|)
1872 ty_fold::RegionFolder::general(cx,
1874 |t| { fldt(t); t }).fold_ty(ty)
1878 pub fn new(space: subst::ParamSpace,
1882 ParamTy { space: space, idx: index, def_id: def_id }
1885 pub fn for_self(trait_def_id: ast::DefId) -> ParamTy {
1886 ParamTy::new(subst::SelfSpace, 0, trait_def_id)
1889 pub fn for_def(def: &TypeParameterDef) -> ParamTy {
1890 ParamTy::new(def.space, def.index, def.def_id)
1893 pub fn to_ty(self, tcx: &ty::ctxt) -> ty::t {
1894 ty::mk_param(tcx, self.space, self.idx, self.def_id)
1899 pub fn empty() -> ItemSubsts {
1900 ItemSubsts { substs: Substs::empty() }
1903 pub fn is_noop(&self) -> bool {
1904 self.substs.is_noop()
1910 pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil }
1912 pub fn type_is_bot(ty: t) -> bool {
1913 (get(ty).flags & (has_ty_bot as uint)) != 0
1916 pub fn type_is_error(ty: t) -> bool {
1917 (get(ty).flags & (has_ty_err as uint)) != 0
1920 pub fn type_needs_subst(ty: t) -> bool {
1921 tbox_has_flag(get(ty), needs_subst)
1924 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
1925 tref.substs.types.any(|&t| type_is_error(t))
1928 pub fn type_is_ty_var(ty: t) -> bool {
1930 ty_infer(TyVar(_)) => true,
1935 pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool }
1937 pub fn type_is_self(ty: t) -> bool {
1939 ty_param(ref p) => p.space == subst::SelfSpace,
1944 fn type_is_slice(ty: t) -> bool {
1946 ty_ptr(mt) | ty_rptr(_, mt) => match get(mt.ty).sty {
1947 ty_vec(_, None) | ty_str => true,
1954 pub fn type_is_vec(ty: t) -> bool {
1957 ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) |
1958 ty_box(t) | ty_uniq(t) => match get(t).sty {
1959 ty_vec(_, None) => true,
1966 pub fn type_is_structural(ty: t) -> bool {
1968 ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) |
1969 ty_vec(_, Some(_)) | ty_unboxed_closure(..) => true,
1970 _ => type_is_slice(ty) | type_is_trait(ty)
1974 pub fn type_is_simd(cx: &ctxt, ty: t) -> bool {
1976 ty_struct(did, _) => lookup_simd(cx, did),
1981 pub fn sequence_element_type(cx: &ctxt, ty: t) -> t {
1983 ty_vec(ty, _) => ty,
1984 ty_str => mk_mach_uint(ast::TyU8),
1985 ty_open(ty) => sequence_element_type(cx, ty),
1986 _ => cx.sess.bug(format!("sequence_element_type called on non-sequence value: {}",
1987 ty_to_string(cx, ty)).as_slice()),
1991 pub fn simd_type(cx: &ctxt, ty: t) -> t {
1993 ty_struct(did, ref substs) => {
1994 let fields = lookup_struct_fields(cx, did);
1995 lookup_field_type(cx, did, fields.get(0).id, substs)
1997 _ => fail!("simd_type called on invalid type")
2001 pub fn simd_size(cx: &ctxt, ty: t) -> uint {
2003 ty_struct(did, _) => {
2004 let fields = lookup_struct_fields(cx, did);
2007 _ => fail!("simd_size called on invalid type")
2011 pub fn type_is_boxed(ty: t) -> bool {
2018 pub fn type_is_region_ptr(ty: t) -> bool {
2020 ty_rptr(..) => true,
2025 pub fn type_is_unsafe_ptr(ty: t) -> bool {
2027 ty_ptr(_) => return true,
2032 pub fn type_is_unique(ty: t) -> bool {
2034 ty_uniq(_) => match get(ty).sty {
2035 ty_trait(..) => false,
2042 pub fn type_is_fat_ptr(cx: &ctxt, ty: t) -> bool {
2044 ty_ptr(mt{ty, ..}) | ty_rptr(_, mt{ty, ..})
2045 | ty_uniq(ty) if !type_is_sized(cx, ty) => true,
2051 A scalar type is one that denotes an atomic datum, with no sub-components.
2052 (A ty_ptr is scalar because it represents a non-managed pointer, so its
2053 contents are abstract to rustc.)
2055 pub fn type_is_scalar(ty: t) -> bool {
2057 ty_nil | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
2058 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
2059 ty_bare_fn(..) | ty_ptr(_) => true,
2064 /// Returns true if this type is a floating point type and false otherwise.
2065 pub fn type_is_floating_point(ty: t) -> bool {
2067 ty_float(_) => true,
2072 pub fn type_needs_drop(cx: &ctxt, ty: t) -> bool {
2073 type_contents(cx, ty).needs_drop(cx)
2076 // Some things don't need cleanups during unwinding because the
2077 // task can free them all at once later. Currently only things
2078 // that only contain scalars and shared boxes can avoid unwind
2080 pub fn type_needs_unwind_cleanup(cx: &ctxt, ty: t) -> bool {
2081 match cx.needs_unwind_cleanup_cache.borrow().find(&ty) {
2082 Some(&result) => return result,
2086 let mut tycache = HashSet::new();
2087 let needs_unwind_cleanup =
2088 type_needs_unwind_cleanup_(cx, ty, &mut tycache, false);
2089 cx.needs_unwind_cleanup_cache.borrow_mut().insert(ty, needs_unwind_cleanup);
2090 return needs_unwind_cleanup;
2093 fn type_needs_unwind_cleanup_(cx: &ctxt, ty: t,
2094 tycache: &mut HashSet<t>,
2095 encountered_box: bool) -> bool {
2097 // Prevent infinite recursion
2098 if !tycache.insert(ty) {
2102 let mut encountered_box = encountered_box;
2103 let mut needs_unwind_cleanup = false;
2104 maybe_walk_ty(ty, |ty| {
2105 let old_encountered_box = encountered_box;
2106 let result = match get(ty).sty {
2108 encountered_box = true;
2111 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2112 ty_tup(_) | ty_ptr(_) => {
2115 ty_enum(did, ref substs) => {
2116 for v in (*enum_variants(cx, did)).iter() {
2117 for aty in v.args.iter() {
2118 let t = aty.subst(cx, substs);
2119 needs_unwind_cleanup |=
2120 type_needs_unwind_cleanup_(cx, t, tycache,
2124 !needs_unwind_cleanup
2127 // Once we're inside a box, the annihilator will find
2128 // it and destroy it.
2129 if !encountered_box {
2130 needs_unwind_cleanup = true;
2137 needs_unwind_cleanup = true;
2142 encountered_box = old_encountered_box;
2146 return needs_unwind_cleanup;
2150 * Type contents is how the type checker reasons about kinds.
2151 * They track what kinds of things are found within a type. You can
2152 * think of them as kind of an "anti-kind". They track the kinds of values
2153 * and thinks that are contained in types. Having a larger contents for
2154 * a type tends to rule that type *out* from various kinds. For example,
2155 * a type that contains a reference is not sendable.
2157 * The reason we compute type contents and not kinds is that it is
2158 * easier for me (nmatsakis) to think about what is contained within
2159 * a type than to think about what is *not* contained within a type.
2161 pub struct TypeContents {
2165 macro_rules! def_type_content_sets(
2166 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
2167 #[allow(non_snake_case)]
2169 use middle::ty::TypeContents;
2170 $(pub static $name: TypeContents = TypeContents { bits: $bits };)+
2175 def_type_content_sets!(
2177 None = 0b0000_0000__0000_0000__0000,
2179 // Things that are interior to the value (first nibble):
2180 InteriorUnsized = 0b0000_0000__0000_0000__0001,
2181 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
2182 // InteriorAll = 0b00000000__00000000__1111,
2184 // Things that are owned by the value (second and third nibbles):
2185 OwnsOwned = 0b0000_0000__0000_0001__0000,
2186 OwnsDtor = 0b0000_0000__0000_0010__0000,
2187 OwnsManaged /* see [1] below */ = 0b0000_0000__0000_0100__0000,
2188 OwnsAffine = 0b0000_0000__0000_1000__0000,
2189 OwnsAll = 0b0000_0000__1111_1111__0000,
2191 // Things that are reachable by the value in any way (fourth nibble):
2192 ReachesNonsendAnnot = 0b0000_0001__0000_0000__0000,
2193 ReachesBorrowed = 0b0000_0010__0000_0000__0000,
2194 // ReachesManaged /* see [1] below */ = 0b0000_0100__0000_0000__0000,
2195 ReachesMutable = 0b0000_1000__0000_0000__0000,
2196 ReachesNoSync = 0b0001_0000__0000_0000__0000,
2197 ReachesFfiUnsafe = 0b0010_0000__0000_0000__0000,
2198 ReachesAll = 0b0011_1111__0000_0000__0000,
2200 // Things that cause values to *move* rather than *copy*
2201 Moves = 0b0000_0000__0000_1011__0000,
2203 // Things that mean drop glue is necessary
2204 NeedsDrop = 0b0000_0000__0000_0111__0000,
2206 // Things that prevent values from being sent
2208 // Note: For checking whether something is sendable, it'd
2209 // be sufficient to have ReachesManaged. However, we include
2210 // both ReachesManaged and OwnsManaged so that when
2211 // a parameter has a bound T:Send, we are able to deduce
2212 // that it neither reaches nor owns a managed pointer.
2213 Nonsendable = 0b0000_0111__0000_0100__0000,
2215 // Things that prevent values from being considered sized
2216 Nonsized = 0b0000_0000__0000_0000__0001,
2218 // Things that prevent values from being sync
2219 Nonsync = 0b0001_0000__0000_0000__0000,
2221 // Things that make values considered not POD (would be same
2222 // as `Moves`, but for the fact that managed data `@` is
2223 // not considered POD)
2224 Noncopy = 0b0000_0000__0000_1111__0000,
2226 // Bits to set when a managed value is encountered
2228 // [1] Do not set the bits TC::OwnsManaged or
2229 // TC::ReachesManaged directly, instead reference
2230 // TC::Managed to set them both at once.
2231 Managed = 0b0000_0100__0000_0100__0000,
2234 All = 0b1111_1111__1111_1111__1111
2239 pub fn meets_builtin_bound(&self, cx: &ctxt, bb: BuiltinBound) -> bool {
2241 BoundSend => self.is_sendable(cx),
2242 BoundSized => self.is_sized(cx),
2243 BoundCopy => self.is_copy(cx),
2244 BoundSync => self.is_sync(cx),
2248 pub fn when(&self, cond: bool) -> TypeContents {
2249 if cond {*self} else {TC::None}
2252 pub fn intersects(&self, tc: TypeContents) -> bool {
2253 (self.bits & tc.bits) != 0
2256 pub fn is_sendable(&self, _: &ctxt) -> bool {
2257 !self.intersects(TC::Nonsendable)
2260 pub fn is_sync(&self, _: &ctxt) -> bool {
2261 !self.intersects(TC::Nonsync)
2264 pub fn owns_managed(&self) -> bool {
2265 self.intersects(TC::OwnsManaged)
2268 pub fn owns_owned(&self) -> bool {
2269 self.intersects(TC::OwnsOwned)
2272 pub fn is_sized(&self, _: &ctxt) -> bool {
2273 !self.intersects(TC::Nonsized)
2276 pub fn is_copy(&self, _: &ctxt) -> bool {
2277 !self.intersects(TC::Noncopy)
2280 pub fn interior_unsafe(&self) -> bool {
2281 self.intersects(TC::InteriorUnsafe)
2284 pub fn interior_unsized(&self) -> bool {
2285 self.intersects(TC::InteriorUnsized)
2288 pub fn moves_by_default(&self, _: &ctxt) -> bool {
2289 self.intersects(TC::Moves)
2292 pub fn needs_drop(&self, _: &ctxt) -> bool {
2293 self.intersects(TC::NeedsDrop)
2296 pub fn owned_pointer(&self) -> TypeContents {
2298 * Includes only those bits that still apply
2299 * when indirected through a `Box` pointer
2302 *self & (TC::OwnsAll | TC::ReachesAll))
2305 pub fn reference(&self, bits: TypeContents) -> TypeContents {
2307 * Includes only those bits that still apply
2308 * when indirected through a reference (`&`)
2311 *self & TC::ReachesAll)
2314 pub fn managed_pointer(&self) -> TypeContents {
2316 * Includes only those bits that still apply
2317 * when indirected through a managed pointer (`@`)
2320 *self & TC::ReachesAll)
2323 pub fn unsafe_pointer(&self) -> TypeContents {
2325 * Includes only those bits that still apply
2326 * when indirected through an unsafe pointer (`*`)
2328 *self & TC::ReachesAll
2331 pub fn union<T>(v: &[T], f: |&T| -> TypeContents) -> TypeContents {
2332 v.iter().fold(TC::None, |tc, t| tc | f(t))
2335 pub fn has_dtor(&self) -> bool {
2336 self.intersects(TC::OwnsDtor)
2340 impl ops::BitOr<TypeContents,TypeContents> for TypeContents {
2341 fn bitor(&self, other: &TypeContents) -> TypeContents {
2342 TypeContents {bits: self.bits | other.bits}
2346 impl ops::BitAnd<TypeContents,TypeContents> for TypeContents {
2347 fn bitand(&self, other: &TypeContents) -> TypeContents {
2348 TypeContents {bits: self.bits & other.bits}
2352 impl ops::Sub<TypeContents,TypeContents> for TypeContents {
2353 fn sub(&self, other: &TypeContents) -> TypeContents {
2354 TypeContents {bits: self.bits & !other.bits}
2358 impl fmt::Show for TypeContents {
2359 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2360 write!(f, "TypeContents({:t})", self.bits)
2364 pub fn type_is_sendable(cx: &ctxt, t: ty::t) -> bool {
2365 type_contents(cx, t).is_sendable(cx)
2368 pub fn type_interior_is_unsafe(cx: &ctxt, t: ty::t) -> bool {
2369 type_contents(cx, t).interior_unsafe()
2372 pub fn type_contents(cx: &ctxt, ty: t) -> TypeContents {
2373 let ty_id = type_id(ty);
2375 match cx.tc_cache.borrow().find(&ty_id) {
2376 Some(tc) => { return *tc; }
2380 let mut cache = HashMap::new();
2381 let result = tc_ty(cx, ty, &mut cache);
2383 cx.tc_cache.borrow_mut().insert(ty_id, result);
2388 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2390 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
2391 // private cache for this walk. This is needed in the case of cyclic
2394 // struct List { next: Box<Option<List>>, ... }
2396 // When computing the type contents of such a type, we wind up deeply
2397 // recursing as we go. So when we encounter the recursive reference
2398 // to List, we temporarily use TC::None as its contents. Later we'll
2399 // patch up the cache with the correct value, once we've computed it
2400 // (this is basically a co-inductive process, if that helps). So in
2401 // the end we'll compute TC::OwnsOwned, in this case.
2403 // The problem is, as we are doing the computation, we will also
2404 // compute an *intermediate* contents for, e.g., Option<List> of
2405 // TC::None. This is ok during the computation of List itself, but if
2406 // we stored this intermediate value into cx.tc_cache, then later
2407 // requests for the contents of Option<List> would also yield TC::None
2408 // which is incorrect. This value was computed based on the crutch
2409 // value for the type contents of list. The correct value is
2410 // TC::OwnsOwned. This manifested as issue #4821.
2411 let ty_id = type_id(ty);
2412 match cache.find(&ty_id) {
2413 Some(tc) => { return *tc; }
2416 match cx.tc_cache.borrow().find(&ty_id) { // Must check both caches!
2417 Some(tc) => { return *tc; }
2420 cache.insert(ty_id, TC::None);
2422 let result = match get(ty).sty {
2423 // uint and int are ffi-unsafe
2424 ty_uint(ast::TyU) | ty_int(ast::TyI) => {
2425 TC::ReachesFfiUnsafe
2428 // Scalar and unique types are sendable, and durable
2429 ty_infer(ty::SkolemizedIntTy(_)) |
2430 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2431 ty_bare_fn(_) | ty::ty_char => {
2435 ty_closure(ref c) => {
2436 closure_contents(cx, &**c) | TC::ReachesFfiUnsafe
2440 tc_ty(cx, typ, cache).managed_pointer() | TC::ReachesFfiUnsafe
2444 TC::ReachesFfiUnsafe | match get(typ).sty {
2445 ty_str => TC::OwnsOwned,
2446 _ => tc_ty(cx, typ, cache).owned_pointer(),
2450 ty_trait(box TyTrait { bounds, .. }) => {
2451 object_contents(cx, bounds) | TC::ReachesFfiUnsafe | TC::Nonsized
2455 tc_ty(cx, mt.ty, cache).unsafe_pointer()
2458 ty_rptr(r, ref mt) => {
2459 TC::ReachesFfiUnsafe | match get(mt.ty).sty {
2460 ty_str => borrowed_contents(r, ast::MutImmutable),
2461 ty_vec(..) => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(r, mt.mutbl)),
2462 _ => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(r, mt.mutbl)),
2466 ty_vec(t, Some(_)) => {
2470 ty_vec(t, None) => {
2471 tc_ty(cx, t, cache) | TC::Nonsized
2473 ty_str => TC::Nonsized,
2475 ty_struct(did, ref substs) => {
2476 let flds = struct_fields(cx, did, substs);
2478 TypeContents::union(flds.as_slice(),
2479 |f| tc_mt(cx, f.mt, cache));
2481 if !lookup_repr_hints(cx, did).contains(&attr::ReprExtern) {
2482 res = res | TC::ReachesFfiUnsafe;
2485 if ty::has_dtor(cx, did) {
2486 res = res | TC::OwnsDtor;
2488 apply_lang_items(cx, did, res)
2491 ty_unboxed_closure(did, r) => {
2492 // FIXME(#14449): `borrowed_contents` below assumes `&mut`
2494 let upvars = unboxed_closure_upvars(cx, did);
2495 TypeContents::union(upvars.as_slice(),
2496 |f| tc_ty(cx, f.ty, cache)) |
2497 borrowed_contents(r, MutMutable)
2500 ty_tup(ref tys) => {
2501 TypeContents::union(tys.as_slice(),
2502 |ty| tc_ty(cx, *ty, cache))
2505 ty_enum(did, ref substs) => {
2506 let variants = substd_enum_variants(cx, did, substs);
2508 TypeContents::union(variants.as_slice(), |variant| {
2509 TypeContents::union(variant.args.as_slice(),
2511 tc_ty(cx, *arg_ty, cache)
2515 if ty::has_dtor(cx, did) {
2516 res = res | TC::OwnsDtor;
2519 if variants.len() != 0 {
2520 let repr_hints = lookup_repr_hints(cx, did);
2521 if repr_hints.len() > 1 {
2522 // this is an error later on, but this type isn't safe
2523 res = res | TC::ReachesFfiUnsafe;
2526 match repr_hints.as_slice().get(0) {
2527 Some(h) => if !h.is_ffi_safe() {
2528 res = res | TC::ReachesFfiUnsafe;
2532 res = res | TC::ReachesFfiUnsafe;
2534 // We allow ReprAny enums if they are eligible for
2535 // the nullable pointer optimization and the
2536 // contained type is an `extern fn`
2538 if variants.len() == 2 {
2539 let mut data_idx = 0;
2541 if variants.get(0).args.len() == 0 {
2545 if variants.get(data_idx).args.len() == 1 {
2546 match get(*variants.get(data_idx).args.get(0)).sty {
2547 ty_bare_fn(..) => { res = res - TC::ReachesFfiUnsafe; }
2557 apply_lang_items(cx, did, res)
2561 // We only ever ask for the kind of types that are defined in
2562 // the current crate; therefore, the only type parameters that
2563 // could be in scope are those defined in the current crate.
2564 // If this assertion failures, it is likely because of a
2565 // failure in the cross-crate inlining code to translate a
2567 assert_eq!(p.def_id.krate, ast::LOCAL_CRATE);
2569 let ty_param_defs = cx.ty_param_defs.borrow();
2570 let tp_def = ty_param_defs.get(&p.def_id.node);
2571 kind_bounds_to_contents(
2573 tp_def.bounds.builtin_bounds,
2574 tp_def.bounds.trait_bounds.as_slice())
2578 // This occurs during coherence, but shouldn't occur at other
2584 let result = tc_ty(cx, t, cache);
2585 assert!(!result.is_sized(cx))
2586 result.unsafe_pointer() | TC::Nonsized
2590 cx.sess.bug("asked to compute contents of error type");
2594 cache.insert(ty_id, result);
2600 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2602 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
2603 mc | tc_ty(cx, mt.ty, cache)
2606 fn apply_lang_items(cx: &ctxt,
2610 if Some(did) == cx.lang_items.no_send_bound() {
2611 tc | TC::ReachesNonsendAnnot
2612 } else if Some(did) == cx.lang_items.managed_bound() {
2614 } else if Some(did) == cx.lang_items.no_copy_bound() {
2616 } else if Some(did) == cx.lang_items.no_sync_bound() {
2617 tc | TC::ReachesNoSync
2618 } else if Some(did) == cx.lang_items.unsafe_type() {
2619 // FIXME(#13231): This shouldn't be needed after
2620 // opt-in built-in bounds are implemented.
2621 (tc | TC::InteriorUnsafe) - TC::Nonsync
2627 fn borrowed_contents(region: ty::Region,
2628 mutbl: ast::Mutability)
2631 * Type contents due to containing a reference
2632 * with the region `region` and borrow kind `bk`
2635 let b = match mutbl {
2636 ast::MutMutable => TC::ReachesMutable | TC::OwnsAffine,
2637 ast::MutImmutable => TC::None,
2639 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
2642 fn closure_contents(cx: &ctxt, cty: &ClosureTy) -> TypeContents {
2643 // Closure contents are just like trait contents, but with potentially
2645 let st = object_contents(cx, cty.bounds);
2647 let st = match cty.store {
2651 RegionTraitStore(r, mutbl) => {
2652 st.reference(borrowed_contents(r, mutbl))
2656 // This also prohibits "@once fn" from being copied, which allows it to
2657 // be called. Neither way really makes much sense.
2658 let ot = match cty.onceness {
2659 ast::Once => TC::OwnsAffine,
2660 ast::Many => TC::None,
2666 fn object_contents(cx: &ctxt,
2667 bounds: ExistentialBounds)
2669 // These are the type contents of the (opaque) interior
2670 kind_bounds_to_contents(cx, bounds.builtin_bounds, [])
2673 fn kind_bounds_to_contents(cx: &ctxt,
2674 bounds: BuiltinBounds,
2675 traits: &[Rc<TraitRef>])
2677 let _i = indenter();
2678 let mut tc = TC::All;
2679 each_inherited_builtin_bound(cx, bounds, traits, |bound| {
2680 tc = tc - match bound {
2681 BoundSend => TC::Nonsendable,
2682 BoundSized => TC::Nonsized,
2683 BoundCopy => TC::Noncopy,
2684 BoundSync => TC::Nonsync,
2689 // Iterates over all builtin bounds on the type parameter def, including
2690 // those inherited from traits with builtin-kind-supertraits.
2691 fn each_inherited_builtin_bound(cx: &ctxt,
2692 bounds: BuiltinBounds,
2693 traits: &[Rc<TraitRef>],
2694 f: |BuiltinBound|) {
2695 for bound in bounds.iter() {
2699 each_bound_trait_and_supertraits(cx, traits, |trait_ref| {
2700 let trait_def = lookup_trait_def(cx, trait_ref.def_id);
2701 for bound in trait_def.bounds.builtin_bounds.iter() {
2710 pub fn type_moves_by_default(cx: &ctxt, ty: t) -> bool {
2711 type_contents(cx, ty).moves_by_default(cx)
2714 pub fn is_ffi_safe(cx: &ctxt, ty: t) -> bool {
2715 !type_contents(cx, ty).intersects(TC::ReachesFfiUnsafe)
2718 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
2719 pub fn is_instantiable(cx: &ctxt, r_ty: t) -> bool {
2720 fn type_requires(cx: &ctxt, seen: &mut Vec<DefId>,
2721 r_ty: t, ty: t) -> bool {
2722 debug!("type_requires({}, {})?",
2723 ::util::ppaux::ty_to_string(cx, r_ty),
2724 ::util::ppaux::ty_to_string(cx, ty));
2727 get(r_ty).sty == get(ty).sty ||
2728 subtypes_require(cx, seen, r_ty, ty)
2731 debug!("type_requires({}, {})? {}",
2732 ::util::ppaux::ty_to_string(cx, r_ty),
2733 ::util::ppaux::ty_to_string(cx, ty),
2738 fn subtypes_require(cx: &ctxt, seen: &mut Vec<DefId>,
2739 r_ty: t, ty: t) -> bool {
2740 debug!("subtypes_require({}, {})?",
2741 ::util::ppaux::ty_to_string(cx, r_ty),
2742 ::util::ppaux::ty_to_string(cx, ty));
2744 let r = match get(ty).sty {
2745 // fixed length vectors need special treatment compared to
2746 // normal vectors, since they don't necessarily have the
2747 // possibility to have length zero.
2748 ty_vec(_, Some(0)) => false, // don't need no contents
2749 ty_vec(ty, Some(_)) => type_requires(cx, seen, r_ty, ty),
2764 ty_vec(_, None) => {
2767 ty_box(typ) | ty_uniq(typ) | ty_open(typ) => {
2768 type_requires(cx, seen, r_ty, typ)
2770 ty_rptr(_, ref mt) => {
2771 type_requires(cx, seen, r_ty, mt.ty)
2775 false // unsafe ptrs can always be NULL
2782 ty_struct(ref did, _) if seen.contains(did) => {
2786 ty_struct(did, ref substs) => {
2788 let fields = struct_fields(cx, did, substs);
2789 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
2790 seen.pop().unwrap();
2794 ty_unboxed_closure(did, _) => {
2795 let upvars = unboxed_closure_upvars(cx, did);
2796 upvars.iter().any(|f| type_requires(cx, seen, r_ty, f.ty))
2800 ts.iter().any(|t| type_requires(cx, seen, r_ty, *t))
2803 ty_enum(ref did, _) if seen.contains(did) => {
2807 ty_enum(did, ref substs) => {
2809 let vs = enum_variants(cx, did);
2810 let r = !vs.is_empty() && vs.iter().all(|variant| {
2811 variant.args.iter().any(|aty| {
2812 let sty = aty.subst(cx, substs);
2813 type_requires(cx, seen, r_ty, sty)
2816 seen.pop().unwrap();
2821 debug!("subtypes_require({}, {})? {}",
2822 ::util::ppaux::ty_to_string(cx, r_ty),
2823 ::util::ppaux::ty_to_string(cx, ty),
2829 let mut seen = Vec::new();
2830 !subtypes_require(cx, &mut seen, r_ty, r_ty)
2833 /// Describes whether a type is representable. For types that are not
2834 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
2835 /// distinguish between types that are recursive with themselves and types that
2836 /// contain a different recursive type. These cases can therefore be treated
2837 /// differently when reporting errors.
2838 #[deriving(PartialEq)]
2839 pub enum Representability {
2845 /// Check whether a type is representable. This means it cannot contain unboxed
2846 /// structural recursion. This check is needed for structs and enums.
2847 pub fn is_type_representable(cx: &ctxt, sp: Span, ty: t) -> Representability {
2849 // Iterate until something non-representable is found
2850 fn find_nonrepresentable<It: Iterator<t>>(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2851 mut iter: It) -> Representability {
2853 let r = type_structurally_recursive(cx, sp, seen, ty);
2854 if r != Representable {
2861 // Does the type `ty` directly (without indirection through a pointer)
2862 // contain any types on stack `seen`?
2863 fn type_structurally_recursive(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2864 ty: t) -> Representability {
2865 debug!("type_structurally_recursive: {}",
2866 ::util::ppaux::ty_to_string(cx, ty));
2868 // Compare current type to previously seen types
2871 ty_enum(did, _) => {
2872 for (i, &seen_did) in seen.iter().enumerate() {
2873 if did == seen_did {
2874 return if i == 0 { SelfRecursive }
2875 else { ContainsRecursive }
2882 // Check inner types
2886 find_nonrepresentable(cx, sp, seen, ts.iter().map(|t| *t))
2888 // Fixed-length vectors.
2889 // FIXME(#11924) Behavior undecided for zero-length vectors.
2890 ty_vec(ty, Some(_)) => {
2891 type_structurally_recursive(cx, sp, seen, ty)
2894 // Push struct and enum def-ids onto `seen` before recursing.
2895 ty_struct(did, ref substs) => {
2897 let fields = struct_fields(cx, did, substs);
2898 let r = find_nonrepresentable(cx, sp, seen,
2899 fields.iter().map(|f| f.mt.ty));
2904 ty_enum(did, ref substs) => {
2906 let vs = enum_variants(cx, did);
2908 let mut r = Representable;
2909 for variant in vs.iter() {
2910 let iter = variant.args.iter().map(|aty| {
2911 aty.subst_spanned(cx, substs, Some(sp))
2913 r = find_nonrepresentable(cx, sp, seen, iter);
2915 if r != Representable { break }
2922 ty_unboxed_closure(did, _) => {
2923 let upvars = unboxed_closure_upvars(cx, did);
2924 find_nonrepresentable(cx,
2927 upvars.iter().map(|f| f.ty))
2934 debug!("is_type_representable: {}",
2935 ::util::ppaux::ty_to_string(cx, ty));
2937 // To avoid a stack overflow when checking an enum variant or struct that
2938 // contains a different, structurally recursive type, maintain a stack
2939 // of seen types and check recursion for each of them (issues #3008, #3779).
2940 let mut seen: Vec<DefId> = Vec::new();
2941 type_structurally_recursive(cx, sp, &mut seen, ty)
2944 pub fn type_is_trait(ty: t) -> bool {
2945 type_trait_info(ty).is_some()
2948 pub fn type_trait_info(ty: t) -> Option<&'static TyTrait> {
2950 ty_uniq(ty) | ty_rptr(_, mt { ty, ..}) | ty_ptr(mt { ty, ..}) => match get(ty).sty {
2951 ty_trait(ref t) => Some(&**t),
2954 ty_trait(ref t) => Some(&**t),
2959 pub fn type_is_integral(ty: t) -> bool {
2961 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
2966 pub fn type_is_skolemized(ty: t) -> bool {
2968 ty_infer(SkolemizedTy(_)) => true,
2969 ty_infer(SkolemizedIntTy(_)) => true,
2974 pub fn type_is_uint(ty: t) -> bool {
2976 ty_infer(IntVar(_)) | ty_uint(ast::TyU) => true,
2981 pub fn type_is_char(ty: t) -> bool {
2988 pub fn type_is_bare_fn(ty: t) -> bool {
2990 ty_bare_fn(..) => true,
2995 pub fn type_is_fp(ty: t) -> bool {
2997 ty_infer(FloatVar(_)) | ty_float(_) => true,
3002 pub fn type_is_numeric(ty: t) -> bool {
3003 return type_is_integral(ty) || type_is_fp(ty);
3006 pub fn type_is_signed(ty: t) -> bool {
3013 pub fn type_is_machine(ty: t) -> bool {
3015 ty_int(ast::TyI) | ty_uint(ast::TyU) => false,
3016 ty_int(..) | ty_uint(..) | ty_float(..) => true,
3021 // Is the type's representation size known at compile time?
3022 pub fn type_is_sized(cx: &ctxt, ty: t) -> bool {
3023 type_contents(cx, ty).is_sized(cx)
3026 pub fn lltype_is_sized(cx: &ctxt, ty: t) -> bool {
3029 _ => type_contents(cx, ty).is_sized(cx)
3033 // Return the smallest part of t which is unsized. Fails if t is sized.
3034 // 'Smallest' here means component of the static representation of the type; not
3035 // the size of an object at runtime.
3036 pub fn unsized_part_of_type(cx: &ctxt, ty: t) -> t {
3038 ty_str | ty_trait(..) | ty_vec(..) => ty,
3039 ty_struct(def_id, ref substs) => {
3040 let unsized_fields: Vec<_> = struct_fields(cx, def_id, substs).iter()
3041 .map(|f| f.mt.ty).filter(|ty| !type_is_sized(cx, *ty)).collect();
3042 // Exactly one of the fields must be unsized.
3043 assert!(unsized_fields.len() == 1)
3045 unsized_part_of_type(cx, unsized_fields[0])
3048 assert!(type_is_sized(cx, ty),
3049 "unsized_part_of_type failed even though ty is unsized");
3050 fail!("called unsized_part_of_type with sized ty");
3055 // Whether a type is enum like, that is an enum type with only nullary
3057 pub fn type_is_c_like_enum(cx: &ctxt, ty: t) -> bool {
3059 ty_enum(did, _) => {
3060 let variants = enum_variants(cx, did);
3061 if variants.len() == 0 {
3064 variants.iter().all(|v| v.args.len() == 0)
3071 // Returns the type and mutability of *t.
3073 // The parameter `explicit` indicates if this is an *explicit* dereference.
3074 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
3075 pub fn deref(t: t, explicit: bool) -> Option<mt> {
3077 ty_box(ty) | ty_uniq(ty) => {
3080 mutbl: ast::MutImmutable,
3083 ty_rptr(_, mt) => Some(mt),
3084 ty_ptr(mt) if explicit => Some(mt),
3089 pub fn deref_or_dont(t: t) -> t {
3091 ty_box(ty) | ty_uniq(ty) => {
3094 ty_rptr(_, mt) | ty_ptr(mt) => mt.ty,
3099 pub fn close_type(cx: &ctxt, t: t) -> t {
3101 ty_open(t) => mk_rptr(cx, ReStatic, mt {ty: t, mutbl:ast::MutImmutable}),
3102 _ => cx.sess.bug(format!("Trying to close a non-open type {}",
3103 ty_to_string(cx, t)).as_slice())
3107 pub fn type_content(t: t) -> t {
3109 ty_box(ty) | ty_uniq(ty) => ty,
3110 ty_rptr(_, mt) |ty_ptr(mt) => mt.ty,
3116 // Extract the unsized type in an open type (or just return t if it is not open).
3117 pub fn unopen_type(t: t) -> t {
3124 // Returns the type of t[i]
3125 pub fn index(ty: t) -> Option<t> {
3127 ty_vec(t, _) => Some(t),
3132 // Returns the type of elements contained within an 'array-like' type.
3133 // This is exactly the same as the above, except it supports strings,
3134 // which can't actually be indexed.
3135 pub fn array_element_ty(t: t) -> Option<t> {
3137 ty_vec(t, _) => Some(t),
3138 ty_str => Some(mk_u8()),
3143 pub fn node_id_to_trait_ref(cx: &ctxt, id: ast::NodeId) -> Rc<ty::TraitRef> {
3144 match cx.trait_refs.borrow().find(&id) {
3145 Some(t) => t.clone(),
3146 None => cx.sess.bug(
3147 format!("node_id_to_trait_ref: no trait ref for node `{}`",
3148 cx.map.node_to_string(id)).as_slice())
3152 pub fn try_node_id_to_type(cx: &ctxt, id: ast::NodeId) -> Option<t> {
3153 cx.node_types.borrow().find_copy(&(id as uint))
3156 pub fn node_id_to_type(cx: &ctxt, id: ast::NodeId) -> t {
3157 match try_node_id_to_type(cx, id) {
3159 None => cx.sess.bug(
3160 format!("node_id_to_type: no type for node `{}`",
3161 cx.map.node_to_string(id)).as_slice())
3165 pub fn node_id_to_type_opt(cx: &ctxt, id: ast::NodeId) -> Option<t> {
3166 match cx.node_types.borrow().find(&(id as uint)) {
3167 Some(&t) => Some(t),
3172 pub fn node_id_item_substs(cx: &ctxt, id: ast::NodeId) -> ItemSubsts {
3173 match cx.item_substs.borrow().find(&id) {
3174 None => ItemSubsts::empty(),
3175 Some(ts) => ts.clone(),
3179 pub fn fn_is_variadic(fty: t) -> bool {
3180 match get(fty).sty {
3181 ty_bare_fn(ref f) => f.sig.variadic,
3182 ty_closure(ref f) => f.sig.variadic,
3184 fail!("fn_is_variadic() called on non-fn type: {:?}", s)
3189 pub fn ty_fn_sig(fty: t) -> FnSig {
3190 match get(fty).sty {
3191 ty_bare_fn(ref f) => f.sig.clone(),
3192 ty_closure(ref f) => f.sig.clone(),
3194 fail!("ty_fn_sig() called on non-fn type: {:?}", s)
3199 /// Returns the ABI of the given function.
3200 pub fn ty_fn_abi(fty: t) -> abi::Abi {
3201 match get(fty).sty {
3202 ty_bare_fn(ref f) => f.abi,
3203 ty_closure(ref f) => f.abi,
3204 _ => fail!("ty_fn_abi() called on non-fn type"),
3208 // Type accessors for substructures of types
3209 pub fn ty_fn_args(fty: t) -> Vec<t> {
3210 match get(fty).sty {
3211 ty_bare_fn(ref f) => f.sig.inputs.clone(),
3212 ty_closure(ref f) => f.sig.inputs.clone(),
3214 fail!("ty_fn_args() called on non-fn type: {:?}", s)
3219 pub fn ty_closure_store(fty: t) -> TraitStore {
3220 match get(fty).sty {
3221 ty_closure(ref f) => f.store,
3222 ty_unboxed_closure(..) => {
3223 // Close enough for the purposes of all the callers of this
3224 // function (which is soon to be deprecated anyhow).
3228 fail!("ty_closure_store() called on non-closure type: {:?}", s)
3233 pub fn ty_fn_ret(fty: t) -> t {
3234 match get(fty).sty {
3235 ty_bare_fn(ref f) => f.sig.output,
3236 ty_closure(ref f) => f.sig.output,
3238 fail!("ty_fn_ret() called on non-fn type: {:?}", s)
3243 pub fn is_fn_ty(fty: t) -> bool {
3244 match get(fty).sty {
3245 ty_bare_fn(_) => true,
3246 ty_closure(_) => true,
3251 pub fn ty_region(tcx: &ctxt,
3259 format!("ty_region() invoked on in appropriate ty: {:?}",
3265 pub fn free_region_from_def(free_id: ast::NodeId, def: &RegionParameterDef)
3268 ty::ReFree(ty::FreeRegion { scope_id: free_id,
3269 bound_region: ty::BrNamed(def.def_id,
3273 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
3274 // doesn't provide type parameter substitutions.
3275 pub fn pat_ty(cx: &ctxt, pat: &ast::Pat) -> t {
3276 return node_id_to_type(cx, pat.id);
3280 // Returns the type of an expression as a monotype.
3282 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
3283 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
3284 // auto-ref. The type returned by this function does not consider such
3285 // adjustments. See `expr_ty_adjusted()` instead.
3287 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
3288 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
3289 // instead of "fn(t) -> T with T = int".
3290 pub fn expr_ty(cx: &ctxt, expr: &ast::Expr) -> t {
3291 return node_id_to_type(cx, expr.id);
3294 pub fn expr_ty_opt(cx: &ctxt, expr: &ast::Expr) -> Option<t> {
3295 return node_id_to_type_opt(cx, expr.id);
3298 pub fn expr_ty_adjusted(cx: &ctxt, expr: &ast::Expr) -> t {
3301 * Returns the type of `expr`, considering any `AutoAdjustment`
3302 * entry recorded for that expression.
3304 * It would almost certainly be better to store the adjusted ty in with
3305 * the `AutoAdjustment`, but I opted not to do this because it would
3306 * require serializing and deserializing the type and, although that's not
3307 * hard to do, I just hate that code so much I didn't want to touch it
3308 * unless it was to fix it properly, which seemed a distraction from the
3309 * task at hand! -nmatsakis
3312 adjust_ty(cx, expr.span, expr.id, expr_ty(cx, expr),
3313 cx.adjustments.borrow().find(&expr.id),
3314 |method_call| cx.method_map.borrow().find(&method_call).map(|method| method.ty))
3317 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
3318 match cx.map.find(id) {
3319 Some(ast_map::NodeExpr(e)) => {
3323 cx.sess.bug(format!("Node id {} is not an expr: {:?}",
3328 cx.sess.bug(format!("Node id {} is not present \
3329 in the node map", id).as_slice());
3334 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
3335 match cx.map.find(id) {
3336 Some(ast_map::NodeLocal(pat)) => {
3338 ast::PatIdent(_, ref path1, _) => {
3339 token::get_ident(path1.node)
3343 format!("Variable id {} maps to {:?}, not local",
3350 cx.sess.bug(format!("Variable id {} maps to {:?}, not local",
3357 pub fn adjust_ty(cx: &ctxt,
3359 expr_id: ast::NodeId,
3360 unadjusted_ty: ty::t,
3361 adjustment: Option<&AutoAdjustment>,
3362 method_type: |typeck::MethodCall| -> Option<ty::t>)
3364 /*! See `expr_ty_adjusted` */
3366 match get(unadjusted_ty).sty {
3367 ty_err => return unadjusted_ty,
3371 return match adjustment {
3372 Some(adjustment) => {
3374 AutoAddEnv(store) => {
3375 match ty::get(unadjusted_ty).sty {
3376 ty::ty_bare_fn(ref b) => {
3377 let bounds = ty::ExistentialBounds {
3378 region_bound: ReStatic,
3379 builtin_bounds: all_builtin_bounds(),
3384 ty::ClosureTy {fn_style: b.fn_style,
3385 onceness: ast::Many,
3393 format!("add_env adjustment on non-bare-fn: \
3400 AutoDerefRef(ref adj) => {
3401 let mut adjusted_ty = unadjusted_ty;
3403 if !ty::type_is_error(adjusted_ty) {
3404 for i in range(0, adj.autoderefs) {
3405 let method_call = typeck::MethodCall::autoderef(expr_id, i);
3406 match method_type(method_call) {
3407 Some(method_ty) => {
3408 adjusted_ty = ty_fn_ret(method_ty);
3412 match deref(adjusted_ty, true) {
3413 Some(mt) => { adjusted_ty = mt.ty; }
3417 format!("the {}th autoderef failed: \
3420 ty_to_string(cx, adjusted_ty))
3428 None => adjusted_ty,
3429 Some(ref autoref) => adjust_for_autoref(cx, span, adjusted_ty, autoref)
3434 None => unadjusted_ty
3437 fn adjust_for_autoref(cx: &ctxt,
3440 autoref: &AutoRef) -> ty::t{
3442 AutoPtr(r, m, ref a) => {
3443 let adjusted_ty = match a {
3444 &Some(box ref a) => adjust_for_autoref(cx, span, ty, a),
3453 AutoUnsafe(m, ref a) => {
3454 let adjusted_ty = match a {
3455 &Some(box ref a) => adjust_for_autoref(cx, span, ty, a),
3458 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
3461 AutoUnsize(ref k) => unsize_ty(cx, ty, k, span),
3462 AutoUnsizeUniq(ref k) => ty::mk_uniq(cx, unsize_ty(cx, ty, k, span)),
3467 // Take a sized type and a sizing adjustment and produce an unsized version of
3469 pub fn unsize_ty(cx: &ctxt,
3475 &UnsizeLength(len) => match get(ty).sty {
3476 ty_vec(t, Some(n)) => {
3480 _ => cx.sess.span_bug(span,
3481 format!("UnsizeLength with bad sty: {}",
3482 ty_to_string(cx, ty)).as_slice())
3484 &UnsizeStruct(box ref k, tp_index) => match get(ty).sty {
3485 ty_struct(did, ref substs) => {
3486 let ty_substs = substs.types.get_slice(subst::TypeSpace);
3487 let new_ty = unsize_ty(cx, ty_substs[tp_index], k, span);
3488 let mut unsized_substs = substs.clone();
3489 unsized_substs.types.get_mut_slice(subst::TypeSpace)[tp_index] = new_ty;
3490 mk_struct(cx, did, unsized_substs)
3492 _ => cx.sess.span_bug(span,
3493 format!("UnsizeStruct with bad sty: {}",
3494 ty_to_string(cx, ty)).as_slice())
3496 &UnsizeVtable(TyTrait { def_id, substs: ref substs, bounds }, _) => {
3497 mk_trait(cx, def_id, substs.clone(), bounds)
3503 pub fn map_region(&self, f: |Region| -> Region) -> AutoRef {
3505 ty::AutoPtr(r, m, None) => ty::AutoPtr(f(r), m, None),
3506 ty::AutoPtr(r, m, Some(ref a)) => ty::AutoPtr(f(r), m, Some(box a.map_region(f))),
3507 ty::AutoUnsize(ref k) => ty::AutoUnsize(k.clone()),
3508 ty::AutoUnsizeUniq(ref k) => ty::AutoUnsizeUniq(k.clone()),
3509 ty::AutoUnsafe(m, None) => ty::AutoUnsafe(m, None),
3510 ty::AutoUnsafe(m, Some(ref a)) => ty::AutoUnsafe(m, Some(box a.map_region(f))),
3515 pub fn method_call_type_param_defs<'tcx, T>(typer: &T,
3516 origin: &typeck::MethodOrigin)
3517 -> VecPerParamSpace<TypeParameterDef>
3518 where T: mc::Typer<'tcx> {
3520 typeck::MethodStatic(did) => {
3521 ty::lookup_item_type(typer.tcx(), did).generics.types.clone()
3523 typeck::MethodStaticUnboxedClosure(did) => {
3524 let def_id = typer.unboxed_closures()
3527 .expect("method_call_type_param_defs: didn't \
3528 find unboxed closure")
3530 .trait_did(typer.tcx());
3531 lookup_trait_def(typer.tcx(), def_id).generics.types.clone()
3533 typeck::MethodParam(typeck::MethodParam{
3534 trait_ref: ref trait_ref,
3538 typeck::MethodObject(typeck::MethodObject{
3539 trait_ref: ref trait_ref,
3543 match ty::trait_item(typer.tcx(), trait_ref.def_id, n_mth) {
3544 ty::MethodTraitItem(method) => method.generics.types.clone(),
3550 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> def::Def {
3551 match tcx.def_map.borrow().find(&expr.id) {
3554 tcx.sess.span_bug(expr.span, format!(
3555 "no def-map entry for expr {:?}", expr.id).as_slice());
3560 pub fn expr_is_lval(tcx: &ctxt, e: &ast::Expr) -> bool {
3561 match expr_kind(tcx, e) {
3563 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
3567 /// We categorize expressions into three kinds. The distinction between
3568 /// lvalue/rvalue is fundamental to the language. The distinction between the
3569 /// two kinds of rvalues is an artifact of trans which reflects how we will
3570 /// generate code for that kind of expression. See trans/expr.rs for more
3579 pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
3580 if tcx.method_map.borrow().contains_key(&typeck::MethodCall::expr(expr.id)) {
3581 // Overloaded operations are generally calls, and hence they are
3582 // generated via DPS, but there are a few exceptions:
3583 return match expr.node {
3584 // `a += b` has a unit result.
3585 ast::ExprAssignOp(..) => RvalueStmtExpr,
3587 // the deref method invoked for `*a` always yields an `&T`
3588 ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
3590 // the index method invoked for `a[i]` always yields an `&T`
3591 ast::ExprIndex(..) => LvalueExpr,
3593 // `for` loops are statements
3594 ast::ExprForLoop(..) => RvalueStmtExpr,
3596 // in the general case, result could be any type, use DPS
3602 ast::ExprPath(..) => {
3603 match resolve_expr(tcx, expr) {
3604 def::DefVariant(tid, vid, _) => {
3605 let variant_info = enum_variant_with_id(tcx, tid, vid);
3606 if variant_info.args.len() > 0u {
3615 def::DefStruct(_) => {
3616 match get(expr_ty(tcx, expr)).sty {
3617 ty_bare_fn(..) => RvalueDatumExpr,
3622 // Fn pointers are just scalar values.
3623 def::DefFn(..) | def::DefStaticMethod(..) => RvalueDatumExpr,
3625 // Note: there is actually a good case to be made that
3626 // DefArg's, particularly those of immediate type, ought to
3627 // considered rvalues.
3628 def::DefStatic(..) |
3629 def::DefBinding(..) |
3632 def::DefLocal(..) => LvalueExpr,
3637 format!("uncategorized def for expr {:?}: {:?}",
3644 ast::ExprUnary(ast::UnDeref, _) |
3645 ast::ExprField(..) |
3646 ast::ExprTupField(..) |
3647 ast::ExprIndex(..) => {
3652 ast::ExprMethodCall(..) |
3653 ast::ExprStruct(..) |
3656 ast::ExprMatch(..) |
3657 ast::ExprFnBlock(..) |
3659 ast::ExprUnboxedFn(..) |
3660 ast::ExprBlock(..) |
3661 ast::ExprRepeat(..) |
3662 ast::ExprVec(..) => {
3666 ast::ExprLit(ref lit) if lit_is_str(&**lit) => {
3670 ast::ExprCast(..) => {
3671 match tcx.node_types.borrow().find(&(expr.id as uint)) {
3673 if type_is_trait(t) {
3680 // Technically, it should not happen that the expr is not
3681 // present within the table. However, it DOES happen
3682 // during type check, because the final types from the
3683 // expressions are not yet recorded in the tcx. At that
3684 // time, though, we are only interested in knowing lvalue
3685 // vs rvalue. It would be better to base this decision on
3686 // the AST type in cast node---but (at the time of this
3687 // writing) it's not easy to distinguish casts to traits
3688 // from other casts based on the AST. This should be
3689 // easier in the future, when casts to traits
3690 // would like @Foo, Box<Foo>, or &Foo.
3696 ast::ExprBreak(..) |
3697 ast::ExprAgain(..) |
3699 ast::ExprWhile(..) |
3701 ast::ExprAssign(..) |
3702 ast::ExprInlineAsm(..) |
3703 ast::ExprAssignOp(..) |
3704 ast::ExprForLoop(..) => {
3708 ast::ExprLit(_) | // Note: LitStr is carved out above
3709 ast::ExprUnary(..) |
3710 ast::ExprAddrOf(..) |
3711 ast::ExprBinary(..) => {
3715 ast::ExprBox(ref place, _) => {
3716 // Special case `Box<T>`/`Gc<T>` for now:
3717 let definition = match tcx.def_map.borrow().find(&place.id) {
3719 None => fail!("no def for place"),
3721 let def_id = definition.def_id();
3722 if tcx.lang_items.exchange_heap() == Some(def_id) ||
3723 tcx.lang_items.managed_heap() == Some(def_id) {
3730 ast::ExprParen(ref e) => expr_kind(tcx, &**e),
3732 ast::ExprMac(..) => {
3735 "macro expression remains after expansion");
3740 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
3742 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
3745 ast::StmtMac(..) => fail!("unexpanded macro in trans")
3749 pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
3752 for f in fields.iter() { if f.ident.name == name { return i; } i += 1u; }
3753 tcx.sess.bug(format!(
3754 "no field named `{}` found in the list of fields `{:?}`",
3755 token::get_name(name),
3757 .map(|f| token::get_ident(f.ident).get().to_string())
3758 .collect::<Vec<String>>()).as_slice());
3761 pub fn impl_or_trait_item_idx(id: ast::Ident, trait_items: &[ImplOrTraitItem])
3763 trait_items.iter().position(|m| m.ident() == id)
3766 /// Returns a vector containing the indices of all type parameters that appear
3767 /// in `ty`. The vector may contain duplicates. Probably should be converted
3768 /// to a bitset or some other representation.
3769 pub fn param_tys_in_type(ty: t) -> Vec<ParamTy> {
3770 let mut rslt = Vec::new();
3782 pub fn ty_sort_string(cx: &ctxt, t: t) -> String {
3784 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) |
3785 ty_uint(_) | ty_float(_) | ty_str => {
3786 ::util::ppaux::ty_to_string(cx, t)
3789 ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
3790 ty_box(_) => "Gc-ptr".to_string(),
3791 ty_uniq(_) => "box".to_string(),
3792 ty_vec(_, _) => "vector".to_string(),
3793 ty_ptr(_) => "*-ptr".to_string(),
3794 ty_rptr(_, _) => "&-ptr".to_string(),
3795 ty_bare_fn(_) => "extern fn".to_string(),
3796 ty_closure(_) => "fn".to_string(),
3797 ty_trait(ref inner) => {
3798 format!("trait {}", item_path_str(cx, inner.def_id))
3800 ty_struct(id, _) => {
3801 format!("struct {}", item_path_str(cx, id))
3803 ty_unboxed_closure(..) => "closure".to_string(),
3804 ty_tup(_) => "tuple".to_string(),
3805 ty_infer(TyVar(_)) => "inferred type".to_string(),
3806 ty_infer(IntVar(_)) => "integral variable".to_string(),
3807 ty_infer(FloatVar(_)) => "floating-point variable".to_string(),
3808 ty_infer(SkolemizedTy(_)) => "skolemized type".to_string(),
3809 ty_infer(SkolemizedIntTy(_)) => "skolemized integral type".to_string(),
3810 ty_param(ref p) => {
3811 if p.space == subst::SelfSpace {
3814 "type parameter".to_string()
3817 ty_err => "type error".to_string(),
3818 ty_open(_) => "opened DST".to_string(),
3822 pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> String {
3825 * Explains the source of a type err in a short,
3826 * human readable way. This is meant to be placed in
3827 * parentheses after some larger message. You should
3828 * also invoke `note_and_explain_type_err()` afterwards
3829 * to present additional details, particularly when
3830 * it comes to lifetime-related errors. */
3832 fn tstore_to_closure(s: &TraitStore) -> String {
3834 &UniqTraitStore => "proc".to_string(),
3835 &RegionTraitStore(..) => "closure".to_string()
3840 terr_cyclic_ty => "cyclic type of infinite size".to_string(),
3841 terr_mismatch => "types differ".to_string(),
3842 terr_fn_style_mismatch(values) => {
3843 format!("expected {} fn, found {} fn",
3844 values.expected.to_string(),
3845 values.found.to_string())
3847 terr_abi_mismatch(values) => {
3848 format!("expected {} fn, found {} fn",
3849 values.expected.to_string(),
3850 values.found.to_string())
3852 terr_onceness_mismatch(values) => {
3853 format!("expected {} fn, found {} fn",
3854 values.expected.to_string(),
3855 values.found.to_string())
3857 terr_sigil_mismatch(values) => {
3858 format!("expected {}, found {}",
3859 tstore_to_closure(&values.expected),
3860 tstore_to_closure(&values.found))
3862 terr_mutability => "values differ in mutability".to_string(),
3863 terr_box_mutability => {
3864 "boxed values differ in mutability".to_string()
3866 terr_vec_mutability => "vectors differ in mutability".to_string(),
3867 terr_ptr_mutability => "pointers differ in mutability".to_string(),
3868 terr_ref_mutability => "references differ in mutability".to_string(),
3869 terr_ty_param_size(values) => {
3870 format!("expected a type with {} type params, \
3871 found one with {} type params",
3875 terr_tuple_size(values) => {
3876 format!("expected a tuple with {} elements, \
3877 found one with {} elements",
3881 terr_record_size(values) => {
3882 format!("expected a record with {} fields, \
3883 found one with {} fields",
3887 terr_record_mutability => {
3888 "record elements differ in mutability".to_string()
3890 terr_record_fields(values) => {
3891 format!("expected a record with field `{}`, found one \
3893 token::get_ident(values.expected),
3894 token::get_ident(values.found))
3897 "incorrect number of function parameters".to_string()
3899 terr_regions_does_not_outlive(..) => {
3900 "lifetime mismatch".to_string()
3902 terr_regions_not_same(..) => {
3903 "lifetimes are not the same".to_string()
3905 terr_regions_no_overlap(..) => {
3906 "lifetimes do not intersect".to_string()
3908 terr_regions_insufficiently_polymorphic(br, _) => {
3909 format!("expected bound lifetime parameter {}, \
3910 found concrete lifetime",
3911 bound_region_ptr_to_string(cx, br))
3913 terr_regions_overly_polymorphic(br, _) => {
3914 format!("expected concrete lifetime, \
3915 found bound lifetime parameter {}",
3916 bound_region_ptr_to_string(cx, br))
3918 terr_trait_stores_differ(_, ref values) => {
3919 format!("trait storage differs: expected `{}`, found `{}`",
3920 trait_store_to_string(cx, (*values).expected),
3921 trait_store_to_string(cx, (*values).found))
3923 terr_sorts(values) => {
3924 format!("expected {}, found {}",
3925 ty_sort_string(cx, values.expected),
3926 ty_sort_string(cx, values.found))
3928 terr_traits(values) => {
3929 format!("expected trait `{}`, found trait `{}`",
3930 item_path_str(cx, values.expected),
3931 item_path_str(cx, values.found))
3933 terr_builtin_bounds(values) => {
3934 if values.expected.is_empty() {
3935 format!("expected no bounds, found `{}`",
3936 values.found.user_string(cx))
3937 } else if values.found.is_empty() {
3938 format!("expected bounds `{}`, found no bounds",
3939 values.expected.user_string(cx))
3941 format!("expected bounds `{}`, found bounds `{}`",
3942 values.expected.user_string(cx),
3943 values.found.user_string(cx))
3946 terr_integer_as_char => {
3947 "expected an integral type, found `char`".to_string()
3949 terr_int_mismatch(ref values) => {
3950 format!("expected `{}`, found `{}`",
3951 values.expected.to_string(),
3952 values.found.to_string())
3954 terr_float_mismatch(ref values) => {
3955 format!("expected `{}`, found `{}`",
3956 values.expected.to_string(),
3957 values.found.to_string())
3959 terr_variadic_mismatch(ref values) => {
3960 format!("expected {} fn, found {} function",
3961 if values.expected { "variadic" } else { "non-variadic" },
3962 if values.found { "variadic" } else { "non-variadic" })
3967 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
3969 terr_regions_does_not_outlive(subregion, superregion) => {
3970 note_and_explain_region(cx, "", subregion, "...");
3971 note_and_explain_region(cx, "...does not necessarily outlive ",
3974 terr_regions_not_same(region1, region2) => {
3975 note_and_explain_region(cx, "", region1, "...");
3976 note_and_explain_region(cx, "...is not the same lifetime as ",
3979 terr_regions_no_overlap(region1, region2) => {
3980 note_and_explain_region(cx, "", region1, "...");
3981 note_and_explain_region(cx, "...does not overlap ",
3984 terr_regions_insufficiently_polymorphic(_, conc_region) => {
3985 note_and_explain_region(cx,
3986 "concrete lifetime that was found is ",
3989 terr_regions_overly_polymorphic(_, conc_region) => {
3990 note_and_explain_region(cx,
3991 "expected concrete lifetime is ",
3998 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
3999 cx.provided_method_sources.borrow().find(&id).map(|x| *x)
4002 pub fn provided_trait_methods(cx: &ctxt, id: ast::DefId) -> Vec<Rc<Method>> {
4004 match cx.map.find(id.node) {
4005 Some(ast_map::NodeItem(item)) => {
4007 ItemTrait(_, _, _, ref ms) => {
4008 ms.iter().filter_map(|m| match *m {
4009 ast::RequiredMethod(_) => None,
4010 ast::ProvidedMethod(ref m) => {
4011 match impl_or_trait_item(cx,
4012 ast_util::local_def(m.id)) {
4013 MethodTraitItem(m) => Some(m),
4019 cx.sess.bug(format!("provided_trait_methods: `{}` is \
4026 cx.sess.bug(format!("provided_trait_methods: `{}` is not a \
4032 csearch::get_provided_trait_methods(cx, id)
4036 fn lookup_locally_or_in_crate_store<V:Clone>(
4039 map: &mut DefIdMap<V>,
4040 load_external: || -> V) -> V {
4042 * Helper for looking things up in the various maps
4043 * that are populated during typeck::collect (e.g.,
4044 * `cx.impl_or_trait_items`, `cx.tcache`, etc). All of these share
4045 * the pattern that if the id is local, it should have
4046 * been loaded into the map by the `typeck::collect` phase.
4047 * If the def-id is external, then we have to go consult
4048 * the crate loading code (and cache the result for the future).
4051 match map.find_copy(&def_id) {
4052 Some(v) => { return v; }
4056 if def_id.krate == ast::LOCAL_CRATE {
4057 fail!("No def'n found for {:?} in tcx.{}", def_id, descr);
4059 let v = load_external();
4060 map.insert(def_id, v.clone());
4064 pub fn trait_item(cx: &ctxt, trait_did: ast::DefId, idx: uint)
4065 -> ImplOrTraitItem {
4066 let method_def_id = ty::trait_item_def_ids(cx, trait_did).get(idx)
4068 impl_or_trait_item(cx, method_def_id)
4071 pub fn trait_items(cx: &ctxt, trait_did: ast::DefId)
4072 -> Rc<Vec<ImplOrTraitItem>> {
4073 let mut trait_items = cx.trait_items_cache.borrow_mut();
4074 match trait_items.find_copy(&trait_did) {
4075 Some(trait_items) => trait_items,
4077 let def_ids = ty::trait_item_def_ids(cx, trait_did);
4078 let items: Rc<Vec<ImplOrTraitItem>> =
4079 Rc::new(def_ids.iter()
4080 .map(|d| impl_or_trait_item(cx, d.def_id()))
4082 trait_items.insert(trait_did, items.clone());
4088 pub fn impl_or_trait_item(cx: &ctxt, id: ast::DefId) -> ImplOrTraitItem {
4089 lookup_locally_or_in_crate_store("impl_or_trait_items",
4091 &mut *cx.impl_or_trait_items
4094 csearch::get_impl_or_trait_item(cx, id)
4098 pub fn trait_item_def_ids(cx: &ctxt, id: ast::DefId)
4099 -> Rc<Vec<ImplOrTraitItemId>> {
4100 lookup_locally_or_in_crate_store("trait_item_def_ids",
4102 &mut *cx.trait_item_def_ids.borrow_mut(),
4104 Rc::new(csearch::get_trait_item_def_ids(&cx.sess.cstore, id))
4108 pub fn impl_trait_ref(cx: &ctxt, id: ast::DefId) -> Option<Rc<TraitRef>> {
4109 match cx.impl_trait_cache.borrow().find(&id) {
4110 Some(ret) => { return ret.clone(); }
4114 let ret = if id.krate == ast::LOCAL_CRATE {
4115 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
4116 match cx.map.find(id.node) {
4117 Some(ast_map::NodeItem(item)) => {
4119 ast::ItemImpl(_, ref opt_trait, _, _) => {
4122 Some(ty::node_id_to_trait_ref(cx, t.ref_id))
4133 csearch::get_impl_trait(cx, id)
4136 cx.impl_trait_cache.borrow_mut().insert(id, ret.clone());
4140 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
4141 let def = *tcx.def_map.borrow()
4143 .expect("no def-map entry for trait");
4147 pub fn try_add_builtin_trait(
4149 trait_def_id: ast::DefId,
4150 builtin_bounds: &mut EnumSet<BuiltinBound>)
4153 //! Checks whether `trait_ref` refers to one of the builtin
4154 //! traits, like `Send`, and adds the corresponding
4155 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
4156 //! is a builtin trait.
4158 match tcx.lang_items.to_builtin_kind(trait_def_id) {
4159 Some(bound) => { builtin_bounds.add(bound); true }
4164 pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> {
4166 ty_trait(box TyTrait { def_id: id, .. }) |
4169 ty_unboxed_closure(id, _) => Some(id),
4176 pub struct VariantInfo {
4178 pub arg_names: Option<Vec<ast::Ident> >,
4180 pub name: ast::Ident,
4188 /// Creates a new VariantInfo from the corresponding ast representation.
4190 /// Does not do any caching of the value in the type context.
4191 pub fn from_ast_variant(cx: &ctxt,
4192 ast_variant: &ast::Variant,
4193 discriminant: Disr) -> VariantInfo {
4194 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
4196 match ast_variant.node.kind {
4197 ast::TupleVariantKind(ref args) => {
4198 let arg_tys = if args.len() > 0 {
4199 ty_fn_args(ctor_ty).iter().map(|a| *a).collect()
4204 return VariantInfo {
4208 name: ast_variant.node.name,
4209 id: ast_util::local_def(ast_variant.node.id),
4210 disr_val: discriminant,
4211 vis: ast_variant.node.vis
4214 ast::StructVariantKind(ref struct_def) => {
4216 let fields: &[StructField] = struct_def.fields.as_slice();
4218 assert!(fields.len() > 0);
4220 let arg_tys = ty_fn_args(ctor_ty).iter().map(|a| *a).collect();
4221 let arg_names = fields.iter().map(|field| {
4222 match field.node.kind {
4223 NamedField(ident, _) => ident,
4224 UnnamedField(..) => cx.sess.bug(
4225 "enum_variants: all fields in struct must have a name")
4229 return VariantInfo {
4231 arg_names: Some(arg_names),
4233 name: ast_variant.node.name,
4234 id: ast_util::local_def(ast_variant.node.id),
4235 disr_val: discriminant,
4236 vis: ast_variant.node.vis
4243 pub fn substd_enum_variants(cx: &ctxt,
4246 -> Vec<Rc<VariantInfo>> {
4247 enum_variants(cx, id).iter().map(|variant_info| {
4248 let substd_args = variant_info.args.iter()
4249 .map(|aty| aty.subst(cx, substs)).collect::<Vec<_>>();
4251 let substd_ctor_ty = variant_info.ctor_ty.subst(cx, substs);
4253 Rc::new(VariantInfo {
4255 ctor_ty: substd_ctor_ty,
4256 ..(**variant_info).clone()
4261 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
4262 with_path(cx, id, |path| ast_map::path_to_string(path)).to_string()
4267 TraitDtor(DefId, bool)
4271 pub fn is_present(&self) -> bool {
4273 TraitDtor(..) => true,
4278 pub fn has_drop_flag(&self) -> bool {
4281 &TraitDtor(_, flag) => flag
4286 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
4287 Otherwise return none. */
4288 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
4289 match cx.destructor_for_type.borrow().find(&struct_id) {
4290 Some(&method_def_id) => {
4291 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
4293 TraitDtor(method_def_id, flag)
4299 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
4300 ty_dtor(cx, struct_id).is_present()
4303 pub fn with_path<T>(cx: &ctxt, id: ast::DefId, f: |ast_map::PathElems| -> T) -> T {
4304 if id.krate == ast::LOCAL_CRATE {
4305 cx.map.with_path(id.node, f)
4307 f(ast_map::Values(csearch::get_item_path(cx, id).iter()).chain(None))
4311 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
4312 enum_variants(cx, id).len() == 1
4315 pub fn type_is_empty(cx: &ctxt, t: t) -> bool {
4316 match ty::get(t).sty {
4317 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
4322 pub fn enum_variants(cx: &ctxt, id: ast::DefId) -> Rc<Vec<Rc<VariantInfo>>> {
4323 match cx.enum_var_cache.borrow().find(&id) {
4324 Some(variants) => return variants.clone(),
4325 _ => { /* fallthrough */ }
4328 let result = if ast::LOCAL_CRATE != id.krate {
4329 Rc::new(csearch::get_enum_variants(cx, id))
4332 Although both this code and check_enum_variants in typeck/check
4333 call eval_const_expr, it should never get called twice for the same
4334 expr, since check_enum_variants also updates the enum_var_cache
4336 match cx.map.get(id.node) {
4337 ast_map::NodeItem(ref item) => {
4339 ast::ItemEnum(ref enum_definition, _) => {
4340 let mut last_discriminant: Option<Disr> = None;
4341 Rc::new(enum_definition.variants.iter().map(|variant| {
4343 let mut discriminant = match last_discriminant {
4344 Some(val) => val + 1,
4345 None => INITIAL_DISCRIMINANT_VALUE
4348 match variant.node.disr_expr {
4349 Some(ref e) => match const_eval::eval_const_expr_partial(cx, &**e) {
4350 Ok(const_eval::const_int(val)) => {
4351 discriminant = val as Disr
4353 Ok(const_eval::const_uint(val)) => {
4354 discriminant = val as Disr
4359 "expected signed integer constant");
4364 format!("expected constant: {}",
4371 last_discriminant = Some(discriminant);
4372 Rc::new(VariantInfo::from_ast_variant(cx, &**variant,
4377 cx.sess.bug("enum_variants: id not bound to an enum")
4381 _ => cx.sess.bug("enum_variants: id not bound to an enum")
4385 cx.enum_var_cache.borrow_mut().insert(id, result.clone());
4390 // Returns information about the enum variant with the given ID:
4391 pub fn enum_variant_with_id(cx: &ctxt,
4392 enum_id: ast::DefId,
4393 variant_id: ast::DefId)
4394 -> Rc<VariantInfo> {
4395 enum_variants(cx, enum_id).iter()
4396 .find(|variant| variant.id == variant_id)
4397 .expect("enum_variant_with_id(): no variant exists with that ID")
4402 // If the given item is in an external crate, looks up its type and adds it to
4403 // the type cache. Returns the type parameters and type.
4404 pub fn lookup_item_type(cx: &ctxt,
4407 lookup_locally_or_in_crate_store(
4408 "tcache", did, &mut *cx.tcache.borrow_mut(),
4409 || csearch::get_type(cx, did))
4412 /// Given the did of a trait, returns its canonical trait ref.
4413 pub fn lookup_trait_def(cx: &ctxt, did: ast::DefId) -> Rc<ty::TraitDef> {
4414 let mut trait_defs = cx.trait_defs.borrow_mut();
4415 match trait_defs.find_copy(&did) {
4416 Some(trait_def) => {
4417 // The item is in this crate. The caller should have added it to the
4418 // type cache already
4422 assert!(did.krate != ast::LOCAL_CRATE);
4423 let trait_def = Rc::new(csearch::get_trait_def(cx, did));
4424 trait_defs.insert(did, trait_def.clone());
4430 /// Given a reference to a trait, returns the bounds declared on the
4431 /// trait, with appropriate substitutions applied.
4432 pub fn bounds_for_trait_ref(tcx: &ctxt,
4433 trait_ref: &TraitRef)
4436 let trait_def = lookup_trait_def(tcx, trait_ref.def_id);
4437 debug!("bounds_for_trait_ref(trait_def={}, trait_ref={})",
4438 trait_def.repr(tcx), trait_ref.repr(tcx));
4439 trait_def.bounds.subst(tcx, &trait_ref.substs)
4442 /// Iterate over attributes of a definition.
4443 // (This should really be an iterator, but that would require csearch and
4444 // decoder to use iterators instead of higher-order functions.)
4445 pub fn each_attr(tcx: &ctxt, did: DefId, f: |&ast::Attribute| -> bool) -> bool {
4447 let item = tcx.map.expect_item(did.node);
4448 item.attrs.iter().all(|attr| f(attr))
4450 info!("getting foreign attrs");
4451 let mut cont = true;
4452 csearch::get_item_attrs(&tcx.sess.cstore, did, |attrs| {
4454 cont = attrs.iter().all(|attr| f(attr));
4462 /// Determine whether an item is annotated with an attribute
4463 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
4464 let mut found = false;
4465 each_attr(tcx, did, |item| {
4466 if item.check_name(attr) {
4476 /// Determine whether an item is annotated with `#[repr(packed)]`
4477 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
4478 lookup_repr_hints(tcx, did).contains(&attr::ReprPacked)
4481 /// Determine whether an item is annotated with `#[simd]`
4482 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
4483 has_attr(tcx, did, "simd")
4486 /// Obtain the representation annotation for a struct definition.
4487 pub fn lookup_repr_hints(tcx: &ctxt, did: DefId) -> Vec<attr::ReprAttr> {
4488 let mut acc = Vec::new();
4490 ty::each_attr(tcx, did, |meta| {
4491 acc.extend(attr::find_repr_attrs(tcx.sess.diagnostic(), meta).move_iter());
4498 // Look up a field ID, whether or not it's local
4499 // Takes a list of type substs in case the struct is generic
4500 pub fn lookup_field_type(tcx: &ctxt,
4505 let t = if id.krate == ast::LOCAL_CRATE {
4506 node_id_to_type(tcx, id.node)
4508 let mut tcache = tcx.tcache.borrow_mut();
4509 let pty = tcache.find_or_insert_with(id, |_| {
4510 csearch::get_field_type(tcx, struct_id, id)
4514 t.subst(tcx, substs)
4517 // Lookup all ancestor structs of a struct indicated by did. That is the reflexive,
4518 // transitive closure of doing a single lookup in cx.superstructs.
4519 fn each_super_struct(cx: &ctxt, mut did: ast::DefId, f: |ast::DefId|) {
4520 let superstructs = cx.superstructs.borrow();
4524 match superstructs.find(&did) {
4525 Some(&Some(def_id)) => {
4528 Some(&None) => break,
4531 format!("ID not mapped to super-struct: {}",
4532 cx.map.node_to_string(did.node)).as_slice());
4538 // Look up the list of field names and IDs for a given struct.
4539 // Fails if the id is not bound to a struct.
4540 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
4541 if did.krate == ast::LOCAL_CRATE {
4542 // We store the fields which are syntactically in each struct in cx. So
4543 // we have to walk the inheritance chain of the struct to get all the
4544 // structs (explicit and inherited) for a struct. If this is expensive
4545 // we could cache the whole list of fields here.
4546 let struct_fields = cx.struct_fields.borrow();
4547 let mut results: SmallVector<&[field_ty]> = SmallVector::zero();
4548 each_super_struct(cx, did, |s| {
4549 match struct_fields.find(&s) {
4550 Some(fields) => results.push(fields.as_slice()),
4553 format!("ID not mapped to struct fields: {}",
4554 cx.map.node_to_string(did.node)).as_slice());
4559 let len = results.as_slice().iter().map(|x| x.len()).sum();
4560 let mut result: Vec<field_ty> = Vec::with_capacity(len);
4561 result.extend(results.as_slice().iter().flat_map(|rs| rs.iter().map(|f| f.clone())));
4562 assert!(result.len() == len);
4565 csearch::get_struct_fields(&cx.sess.cstore, did)
4569 pub fn is_tuple_struct(cx: &ctxt, did: ast::DefId) -> bool {
4570 let fields = lookup_struct_fields(cx, did);
4571 !fields.is_empty() && fields.iter().all(|f| f.name == token::special_names::unnamed_field)
4574 pub fn lookup_struct_field(cx: &ctxt,
4576 field_id: ast::DefId)
4578 let r = lookup_struct_fields(cx, parent);
4579 match r.iter().find(|f| f.id.node == field_id.node) {
4580 Some(t) => t.clone(),
4581 None => cx.sess.bug("struct ID not found in parent's fields")
4585 // Returns a list of fields corresponding to the struct's items. trans uses
4586 // this. Takes a list of substs with which to instantiate field types.
4587 pub fn struct_fields(cx: &ctxt, did: ast::DefId, substs: &Substs)
4589 lookup_struct_fields(cx, did).iter().map(|f| {
4591 // FIXME #6993: change type of field to Name and get rid of new()
4592 ident: ast::Ident::new(f.name),
4594 ty: lookup_field_type(cx, did, f.id, substs),
4601 // Returns a list of fields corresponding to the tuple's items. trans uses
4603 pub fn tup_fields(v: &[t]) -> Vec<field> {
4604 v.iter().enumerate().map(|(i, &f)| {
4606 // FIXME #6993: change type of field to Name and get rid of new()
4607 ident: ast::Ident::new(token::intern(i.to_string().as_slice())),
4616 pub struct UnboxedClosureUpvar {
4622 // Returns a list of `UnboxedClosureUpvar`s for each upvar.
4623 pub fn unboxed_closure_upvars(tcx: &ctxt, closure_id: ast::DefId)
4624 -> Vec<UnboxedClosureUpvar> {
4625 if closure_id.krate == ast::LOCAL_CRATE {
4626 match tcx.freevars.borrow().find(&closure_id.node) {
4627 None => tcx.sess.bug("no freevars for unboxed closure?!"),
4628 Some(ref freevars) => {
4629 freevars.iter().map(|freevar| {
4630 let freevar_def_id = freevar.def.def_id();
4631 UnboxedClosureUpvar {
4634 ty: node_id_to_type(tcx, freevar_def_id.node),
4640 tcx.sess.bug("unimplemented cross-crate closure upvars")
4644 pub fn is_binopable(cx: &ctxt, ty: t, op: ast::BinOp) -> bool {
4645 static tycat_other: int = 0;
4646 static tycat_bool: int = 1;
4647 static tycat_char: int = 2;
4648 static tycat_int: int = 3;
4649 static tycat_float: int = 4;
4650 static tycat_bot: int = 5;
4651 static tycat_raw_ptr: int = 6;
4653 static opcat_add: int = 0;
4654 static opcat_sub: int = 1;
4655 static opcat_mult: int = 2;
4656 static opcat_shift: int = 3;
4657 static opcat_rel: int = 4;
4658 static opcat_eq: int = 5;
4659 static opcat_bit: int = 6;
4660 static opcat_logic: int = 7;
4661 static opcat_mod: int = 8;
4663 fn opcat(op: ast::BinOp) -> int {
4665 ast::BiAdd => opcat_add,
4666 ast::BiSub => opcat_sub,
4667 ast::BiMul => opcat_mult,
4668 ast::BiDiv => opcat_mult,
4669 ast::BiRem => opcat_mod,
4670 ast::BiAnd => opcat_logic,
4671 ast::BiOr => opcat_logic,
4672 ast::BiBitXor => opcat_bit,
4673 ast::BiBitAnd => opcat_bit,
4674 ast::BiBitOr => opcat_bit,
4675 ast::BiShl => opcat_shift,
4676 ast::BiShr => opcat_shift,
4677 ast::BiEq => opcat_eq,
4678 ast::BiNe => opcat_eq,
4679 ast::BiLt => opcat_rel,
4680 ast::BiLe => opcat_rel,
4681 ast::BiGe => opcat_rel,
4682 ast::BiGt => opcat_rel
4686 fn tycat(cx: &ctxt, ty: t) -> int {
4687 if type_is_simd(cx, ty) {
4688 return tycat(cx, simd_type(cx, ty))
4691 ty_char => tycat_char,
4692 ty_bool => tycat_bool,
4693 ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
4694 ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
4695 ty_bot => tycat_bot,
4696 ty_ptr(_) => tycat_raw_ptr,
4701 static t: bool = true;
4702 static f: bool = false;
4705 // +, -, *, shift, rel, ==, bit, logic, mod
4706 /*other*/ [f, f, f, f, f, f, f, f, f],
4707 /*bool*/ [f, f, f, f, t, t, t, t, f],
4708 /*char*/ [f, f, f, f, t, t, f, f, f],
4709 /*int*/ [t, t, t, t, t, t, t, f, t],
4710 /*float*/ [t, t, t, f, t, t, f, f, f],
4711 /*bot*/ [t, t, t, t, t, t, t, t, t],
4712 /*raw ptr*/ [f, f, f, f, t, t, f, f, f]];
4714 return tbl[tycat(cx, ty) as uint ][opcat(op) as uint];
4717 /// Returns an equivalent type with all the typedefs and self regions removed.
4718 pub fn normalize_ty(cx: &ctxt, t: t) -> t {
4719 let u = TypeNormalizer(cx).fold_ty(t);
4722 struct TypeNormalizer<'a, 'tcx: 'a>(&'a ctxt<'tcx>);
4724 impl<'a, 'tcx> TypeFolder<'tcx> for TypeNormalizer<'a, 'tcx> {
4725 fn tcx(&self) -> &ctxt<'tcx> { let TypeNormalizer(c) = *self; c }
4727 fn fold_ty(&mut self, t: ty::t) -> ty::t {
4728 match self.tcx().normalized_cache.borrow().find_copy(&t) {
4733 let t_norm = ty_fold::super_fold_ty(self, t);
4734 self.tcx().normalized_cache.borrow_mut().insert(t, t_norm);
4738 fn fold_region(&mut self, _: ty::Region) -> ty::Region {
4742 fn fold_substs(&mut self,
4743 substs: &subst::Substs)
4745 subst::Substs { regions: subst::ErasedRegions,
4746 types: substs.types.fold_with(self) }
4749 fn fold_sig(&mut self,
4752 // The binder-id is only relevant to bound regions, which
4753 // are erased at trans time.
4755 binder_id: ast::DUMMY_NODE_ID,
4756 inputs: sig.inputs.fold_with(self),
4757 output: sig.output.fold_with(self),
4758 variadic: sig.variadic,
4764 // Returns the repeat count for a repeating vector expression.
4765 pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> uint {
4766 match const_eval::eval_const_expr_partial(tcx, count_expr) {
4767 Ok(ref const_val) => match *const_val {
4768 const_eval::const_int(count) => if count < 0 {
4769 tcx.sess.span_err(count_expr.span,
4770 "expected positive integer for \
4771 repeat count, found negative integer");
4776 const_eval::const_uint(count) => count as uint,
4777 const_eval::const_float(count) => {
4778 tcx.sess.span_err(count_expr.span,
4779 "expected positive integer for \
4780 repeat count, found float");
4783 const_eval::const_str(_) => {
4784 tcx.sess.span_err(count_expr.span,
4785 "expected positive integer for \
4786 repeat count, found string");
4789 const_eval::const_bool(_) => {
4790 tcx.sess.span_err(count_expr.span,
4791 "expected positive integer for \
4792 repeat count, found boolean");
4795 const_eval::const_binary(_) => {
4796 tcx.sess.span_err(count_expr.span,
4797 "expected positive integer for \
4798 repeat count, found binary array");
4801 const_eval::const_nil => {
4802 tcx.sess.span_err(count_expr.span,
4803 "expected positive integer for \
4804 repeat count, found ()");
4809 tcx.sess.span_err(count_expr.span,
4810 "expected constant integer for repeat count, \
4817 // Iterate over a type parameter's bounded traits and any supertraits
4818 // of those traits, ignoring kinds.
4819 // Here, the supertraits are the transitive closure of the supertrait
4820 // relation on the supertraits from each bounded trait's constraint
4822 pub fn each_bound_trait_and_supertraits(tcx: &ctxt,
4823 bounds: &[Rc<TraitRef>],
4824 f: |Rc<TraitRef>| -> bool)
4827 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
4828 if !f(bound_trait_ref) {
4835 pub fn required_region_bounds(tcx: &ctxt,
4836 region_bounds: &[ty::Region],
4837 builtin_bounds: BuiltinBounds,
4838 trait_bounds: &[Rc<TraitRef>])
4842 * Given a type which must meet the builtin bounds and trait
4843 * bounds, returns a set of lifetimes which the type must outlive.
4845 * Requires that trait definitions have been processed.
4848 let mut all_bounds = Vec::new();
4850 debug!("required_region_bounds(builtin_bounds={}, trait_bounds={})",
4851 builtin_bounds.repr(tcx),
4852 trait_bounds.repr(tcx));
4854 all_bounds.push_all(region_bounds);
4856 push_region_bounds([],
4860 debug!("from builtin bounds: all_bounds={}", all_bounds.repr(tcx));
4862 each_bound_trait_and_supertraits(
4866 let bounds = ty::bounds_for_trait_ref(tcx, &*trait_ref);
4867 push_region_bounds(bounds.opt_region_bound.as_slice(),
4868 bounds.builtin_bounds,
4870 debug!("from {}: bounds={} all_bounds={}",
4871 trait_ref.repr(tcx),
4873 all_bounds.repr(tcx));
4879 fn push_region_bounds(region_bounds: &[ty::Region],
4880 builtin_bounds: ty::BuiltinBounds,
4881 all_bounds: &mut Vec<ty::Region>) {
4882 all_bounds.push_all(region_bounds.as_slice());
4884 if builtin_bounds.contains_elem(ty::BoundSend) {
4885 all_bounds.push(ty::ReStatic);
4890 pub fn get_tydesc_ty(tcx: &ctxt) -> Result<t, String> {
4891 tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
4892 tcx.intrinsic_defs.borrow().find_copy(&tydesc_lang_item)
4893 .expect("Failed to resolve TyDesc")
4897 pub fn get_opaque_ty(tcx: &ctxt) -> Result<t, String> {
4898 tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| {
4899 tcx.intrinsic_defs.borrow().find_copy(&opaque_lang_item)
4900 .expect("Failed to resolve Opaque")
4904 pub fn visitor_object_ty(tcx: &ctxt,
4905 ptr_region: ty::Region,
4906 trait_region: ty::Region)
4907 -> Result<(Rc<TraitRef>, t), String>
4909 let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) {
4911 Err(s) => { return Err(s); }
4913 let substs = Substs::empty();
4914 let trait_ref = Rc::new(TraitRef { def_id: trait_lang_item, substs: substs });
4915 Ok((trait_ref.clone(),
4916 mk_rptr(tcx, ptr_region,
4917 mt {mutbl: ast::MutMutable,
4920 trait_ref.substs.clone(),
4921 ty::region_existential_bound(trait_region))})))
4924 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> Rc<ItemVariances> {
4925 lookup_locally_or_in_crate_store(
4926 "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
4927 || Rc::new(csearch::get_item_variances(&tcx.sess.cstore, item_id)))
4930 /// Records a trait-to-implementation mapping.
4931 pub fn record_trait_implementation(tcx: &ctxt,
4932 trait_def_id: DefId,
4933 impl_def_id: DefId) {
4934 match tcx.trait_impls.borrow().find(&trait_def_id) {
4935 Some(impls_for_trait) => {
4936 impls_for_trait.borrow_mut().push(impl_def_id);
4941 tcx.trait_impls.borrow_mut().insert(trait_def_id, Rc::new(RefCell::new(vec!(impl_def_id))));
4944 /// Populates the type context with all the implementations for the given type
4946 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
4947 type_id: ast::DefId) {
4948 if type_id.krate == LOCAL_CRATE {
4951 if tcx.populated_external_types.borrow().contains(&type_id) {
4955 let mut inherent_impls = Vec::new();
4956 csearch::each_implementation_for_type(&tcx.sess.cstore, type_id,
4958 let impl_items = csearch::get_impl_items(&tcx.sess.cstore,
4961 // Record the trait->implementation mappings, if applicable.
4962 let associated_traits = csearch::get_impl_trait(tcx, impl_def_id);
4963 for trait_ref in associated_traits.iter() {
4964 record_trait_implementation(tcx, trait_ref.def_id, impl_def_id);
4967 // For any methods that use a default implementation, add them to
4968 // the map. This is a bit unfortunate.
4969 for impl_item_def_id in impl_items.iter() {
4970 let method_def_id = impl_item_def_id.def_id();
4971 match impl_or_trait_item(tcx, method_def_id) {
4972 MethodTraitItem(method) => {
4973 for &source in method.provided_source.iter() {
4974 tcx.provided_method_sources
4976 .insert(method_def_id, source);
4982 // Store the implementation info.
4983 tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
4985 // If this is an inherent implementation, record it.
4986 if associated_traits.is_none() {
4987 inherent_impls.push(impl_def_id);
4991 tcx.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
4992 tcx.populated_external_types.borrow_mut().insert(type_id);
4995 /// Populates the type context with all the implementations for the given
4996 /// trait if necessary.
4997 pub fn populate_implementations_for_trait_if_necessary(
4999 trait_id: ast::DefId) {
5000 if trait_id.krate == LOCAL_CRATE {
5003 if tcx.populated_external_traits.borrow().contains(&trait_id) {
5007 csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id,
5008 |implementation_def_id| {
5009 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, implementation_def_id);
5011 // Record the trait->implementation mapping.
5012 record_trait_implementation(tcx, trait_id, implementation_def_id);
5014 // For any methods that use a default implementation, add them to
5015 // the map. This is a bit unfortunate.
5016 for impl_item_def_id in impl_items.iter() {
5017 let method_def_id = impl_item_def_id.def_id();
5018 match impl_or_trait_item(tcx, method_def_id) {
5019 MethodTraitItem(method) => {
5020 for &source in method.provided_source.iter() {
5021 tcx.provided_method_sources
5023 .insert(method_def_id, source);
5029 // Store the implementation info.
5030 tcx.impl_items.borrow_mut().insert(implementation_def_id, impl_items);
5033 tcx.populated_external_traits.borrow_mut().insert(trait_id);
5036 /// Given the def_id of an impl, return the def_id of the trait it implements.
5037 /// If it implements no trait, return `None`.
5038 pub fn trait_id_of_impl(tcx: &ctxt,
5039 def_id: ast::DefId) -> Option<ast::DefId> {
5040 let node = match tcx.map.find(def_id.node) {
5045 ast_map::NodeItem(item) => {
5047 ast::ItemImpl(_, Some(ref trait_ref), _, _) => {
5048 Some(node_id_to_trait_ref(tcx, trait_ref.ref_id).def_id)
5057 /// If the given def ID describes a method belonging to an impl, return the
5058 /// ID of the impl that the method belongs to. Otherwise, return `None`.
5059 pub fn impl_of_method(tcx: &ctxt, def_id: ast::DefId)
5060 -> Option<ast::DefId> {
5061 if def_id.krate != LOCAL_CRATE {
5062 return match csearch::get_impl_or_trait_item(tcx,
5063 def_id).container() {
5064 TraitContainer(_) => None,
5065 ImplContainer(def_id) => Some(def_id),
5068 match tcx.impl_or_trait_items.borrow().find_copy(&def_id) {
5069 Some(trait_item) => {
5070 match trait_item.container() {
5071 TraitContainer(_) => None,
5072 ImplContainer(def_id) => Some(def_id),
5079 /// If the given def ID describes an item belonging to a trait (either a
5080 /// default method or an implementation of a trait method), return the ID of
5081 /// the trait that the method belongs to. Otherwise, return `None`.
5082 pub fn trait_of_item(tcx: &ctxt, def_id: ast::DefId) -> Option<ast::DefId> {
5083 if def_id.krate != LOCAL_CRATE {
5084 return csearch::get_trait_of_item(&tcx.sess.cstore, def_id, tcx);
5086 match tcx.impl_or_trait_items.borrow().find_copy(&def_id) {
5087 Some(impl_or_trait_item) => {
5088 match impl_or_trait_item.container() {
5089 TraitContainer(def_id) => Some(def_id),
5090 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
5097 /// If the given def ID describes an item belonging to a trait, (either a
5098 /// default method or an implementation of a trait method), return the ID of
5099 /// the method inside trait definition (this means that if the given def ID
5100 /// is already that of the original trait method, then the return value is
5102 /// Otherwise, return `None`.
5103 pub fn trait_item_of_item(tcx: &ctxt, def_id: ast::DefId)
5104 -> Option<ImplOrTraitItemId> {
5105 let impl_item = match tcx.impl_or_trait_items.borrow().find(&def_id) {
5106 Some(m) => m.clone(),
5107 None => return None,
5109 let name = match impl_item {
5110 MethodTraitItem(method) => method.ident.name,
5112 match trait_of_item(tcx, def_id) {
5113 Some(trait_did) => {
5114 let trait_items = ty::trait_items(tcx, trait_did);
5116 .position(|m| m.ident().name == name)
5117 .map(|idx| ty::trait_item(tcx, trait_did, idx).id())
5123 /// Creates a hash of the type `t` which will be the same no matter what crate
5124 /// context it's calculated within. This is used by the `type_id` intrinsic.
5125 pub fn hash_crate_independent(tcx: &ctxt, t: t, svh: &Svh) -> u64 {
5126 let mut state = sip::SipState::new();
5127 macro_rules! byte( ($b:expr) => { ($b as u8).hash(&mut state) } );
5128 macro_rules! hash( ($e:expr) => { $e.hash(&mut state) } );
5130 let region = |_state: &mut sip::SipState, r: Region| {
5140 tcx.sess.bug("non-static region found when hashing a type")
5144 let did = |state: &mut sip::SipState, did: DefId| {
5145 let h = if ast_util::is_local(did) {
5148 tcx.sess.cstore.get_crate_hash(did.krate)
5150 h.as_str().hash(state);
5151 did.node.hash(state);
5153 let mt = |state: &mut sip::SipState, mt: mt| {
5154 mt.mutbl.hash(state);
5156 ty::walk_ty(t, |t| {
5157 match ty::get(t).sty {
5160 ty_bool => byte!(2),
5161 ty_char => byte!(3),
5187 ty_vec(_, Some(n)) => {
5191 ty_vec(_, None) => {
5193 0u8.hash(&mut state);
5201 region(&mut state, r);
5204 ty_bare_fn(ref b) => {
5209 ty_closure(ref c) => {
5215 UniqTraitStore => byte!(0),
5216 RegionTraitStore(r, m) => {
5218 region(&mut state, r);
5219 assert_eq!(m, ast::MutMutable);
5223 ty_trait(box TyTrait { def_id: d, bounds, .. }) => {
5228 ty_struct(d, _) => {
5232 ty_tup(ref inner) => {
5239 did(&mut state, p.def_id);
5241 ty_open(_) => byte!(22),
5242 ty_infer(_) => unreachable!(),
5243 ty_err => byte!(23),
5244 ty_unboxed_closure(d, r) => {
5247 region(&mut state, r);
5256 pub fn to_string(self) -> &'static str {
5259 Contravariant => "-",
5266 pub fn empty_parameter_environment() -> ParameterEnvironment {
5268 * Construct a parameter environment suitable for static contexts
5269 * or other contexts where there are no free type/lifetime
5270 * parameters in scope.
5273 ty::ParameterEnvironment { free_substs: Substs::empty(),
5274 bounds: VecPerParamSpace::empty(),
5275 caller_obligations: VecPerParamSpace::empty(),
5276 implicit_region_bound: ty::ReEmpty }
5279 pub fn construct_parameter_environment(
5282 generics: &ty::Generics,
5283 free_id: ast::NodeId)
5284 -> ParameterEnvironment
5286 /*! See `ParameterEnvironment` struct def'n for details */
5289 // Construct the free substs.
5293 let mut types = VecPerParamSpace::empty();
5294 for &space in subst::ParamSpace::all().iter() {
5295 push_types_from_defs(tcx, &mut types, space,
5296 generics.types.get_slice(space));
5299 // map bound 'a => free 'a
5300 let mut regions = VecPerParamSpace::empty();
5301 for &space in subst::ParamSpace::all().iter() {
5302 push_region_params(&mut regions, space, free_id,
5303 generics.regions.get_slice(space));
5306 let free_substs = Substs {
5308 regions: subst::NonerasedRegions(regions)
5312 // Compute the bounds on Self and the type parameters.
5315 let mut bounds = VecPerParamSpace::empty();
5316 for &space in subst::ParamSpace::all().iter() {
5317 push_bounds_from_defs(tcx, &mut bounds, space, &free_substs,
5318 generics.types.get_slice(space));
5322 // Compute region bounds. For now, these relations are stored in a
5323 // global table on the tcx, so just enter them there. I'm not
5324 // crazy about this scheme, but it's convenient, at least.
5327 for &space in subst::ParamSpace::all().iter() {
5328 record_region_bounds_from_defs(tcx, space, &free_substs,
5329 generics.regions.get_slice(space));
5333 debug!("construct_parameter_environment: free_id={} \
5337 free_substs.repr(tcx),
5340 let obligations = traits::obligations_for_generics(tcx, traits::ObligationCause::misc(span),
5341 generics, &free_substs);
5343 return ty::ParameterEnvironment {
5344 free_substs: free_substs,
5346 implicit_region_bound: ty::ReScope(free_id),
5347 caller_obligations: obligations,
5350 fn push_region_params(regions: &mut VecPerParamSpace<ty::Region>,
5351 space: subst::ParamSpace,
5352 free_id: ast::NodeId,
5353 region_params: &[RegionParameterDef])
5355 for r in region_params.iter() {
5356 regions.push(space, ty::free_region_from_def(free_id, r));
5360 fn push_types_from_defs(tcx: &ty::ctxt,
5361 types: &mut subst::VecPerParamSpace<ty::t>,
5362 space: subst::ParamSpace,
5363 defs: &[TypeParameterDef]) {
5364 for (i, def) in defs.iter().enumerate() {
5365 let ty = ty::mk_param(tcx, space, i, def.def_id);
5366 types.push(space, ty);
5370 fn push_bounds_from_defs(tcx: &ty::ctxt,
5371 bounds: &mut subst::VecPerParamSpace<ParamBounds>,
5372 space: subst::ParamSpace,
5373 free_substs: &subst::Substs,
5374 defs: &[TypeParameterDef]) {
5375 for def in defs.iter() {
5376 let b = def.bounds.subst(tcx, free_substs);
5377 bounds.push(space, b);
5381 fn record_region_bounds_from_defs(tcx: &ty::ctxt,
5382 space: subst::ParamSpace,
5383 free_substs: &subst::Substs,
5384 defs: &[RegionParameterDef]) {
5385 for (subst_region, def) in
5386 free_substs.regions().get_slice(space).iter().zip(
5389 // For each region parameter 'subst...
5390 let bounds = def.bounds.subst(tcx, free_substs);
5391 for bound_region in bounds.iter() {
5392 // Which is declared with a bound like 'subst:'bound...
5393 match (subst_region, bound_region) {
5394 (&ty::ReFree(subst_fr), &ty::ReFree(bound_fr)) => {
5395 // Record that 'subst outlives 'bound. Or, put
5396 // another way, 'bound <= 'subst.
5397 tcx.region_maps.relate_free_regions(bound_fr, subst_fr);
5400 // All named regions are instantiated with free regions.
5402 format!("push_region_bounds_from_defs: \
5403 non free region: {} / {}",
5404 subst_region.repr(tcx),
5405 bound_region.repr(tcx)).as_slice());
5414 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
5416 ast::MutMutable => MutBorrow,
5417 ast::MutImmutable => ImmBorrow,
5421 pub fn to_mutbl_lossy(self) -> ast::Mutability {
5423 * Returns a mutability `m` such that an `&m T` pointer could
5424 * be used to obtain this borrow kind. Because borrow kinds
5425 * are richer than mutabilities, we sometimes have to pick a
5426 * mutability that is stronger than necessary so that it at
5427 * least *would permit* the borrow in question.
5431 MutBorrow => ast::MutMutable,
5432 ImmBorrow => ast::MutImmutable,
5434 // We have no type correponding to a unique imm borrow, so
5435 // use `&mut`. It gives all the capabilities of an `&uniq`
5436 // and hence is a safe "over approximation".
5437 UniqueImmBorrow => ast::MutMutable,
5441 pub fn to_user_str(&self) -> &'static str {
5443 MutBorrow => "mutable",
5444 ImmBorrow => "immutable",
5445 UniqueImmBorrow => "uniquely immutable",
5450 impl<'tcx> mc::Typer<'tcx> for ty::ctxt<'tcx> {
5451 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
5455 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<ty::t> {
5456 Ok(ty::node_id_to_type(self, id))
5459 fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t> {
5460 self.method_map.borrow().find(&method_call).map(|method| method.ty)
5463 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment>> {
5467 fn is_method_call(&self, id: ast::NodeId) -> bool {
5468 self.method_map.borrow().contains_key(&typeck::MethodCall::expr(id))
5471 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<ast::NodeId> {
5472 self.region_maps.temporary_scope(rvalue_id)
5475 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow {
5476 self.upvar_borrow_map.borrow().get_copy(&upvar_id)
5479 fn capture_mode(&self, closure_expr_id: ast::NodeId)
5480 -> freevars::CaptureMode {
5481 self.capture_modes.borrow().get_copy(&closure_expr_id)
5484 fn unboxed_closures<'a>(&'a self)
5485 -> &'a RefCell<DefIdMap<UnboxedClosure>> {
5486 &self.unboxed_closures
5490 /// The category of explicit self.
5491 #[deriving(Clone, Eq, PartialEq)]
5492 pub enum ExplicitSelfCategory {
5493 StaticExplicitSelfCategory,
5494 ByValueExplicitSelfCategory,
5495 ByReferenceExplicitSelfCategory(Region, ast::Mutability),
5496 ByBoxExplicitSelfCategory,
5499 /// Pushes all the lifetimes in the given type onto the given list. A
5500 /// "lifetime in a type" is a lifetime specified by a reference or a lifetime
5501 /// in a list of type substitutions. This does *not* traverse into nominal
5502 /// types, nor does it resolve fictitious types.
5503 pub fn accumulate_lifetimes_in_type(accumulator: &mut Vec<ty::Region>,
5505 walk_ty(typ, |typ| {
5506 match get(typ).sty {
5507 ty_rptr(region, _) => accumulator.push(region),
5508 ty_enum(_, ref substs) |
5509 ty_trait(box TyTrait {
5513 ty_struct(_, ref substs) => {
5514 match substs.regions {
5515 subst::ErasedRegions => {}
5516 subst::NonerasedRegions(ref regions) => {
5517 for region in regions.iter() {
5518 accumulator.push(*region)
5523 ty_closure(ref closure_ty) => {
5524 match closure_ty.store {
5525 RegionTraitStore(region, _) => accumulator.push(region),
5526 UniqTraitStore => {}
5529 ty_unboxed_closure(_, ref region) => accumulator.push(*region),