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 region_bounds: Vec<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 and there must be
1020 /// *exactly one* region.
1021 #[deriving(PartialEq, Eq, Hash, Clone, Show)]
1022 pub struct ExistentialBounds {
1023 pub region_bound: ty::Region,
1024 pub builtin_bounds: BuiltinBounds
1027 pub type BuiltinBounds = EnumSet<BuiltinBound>;
1029 #[deriving(Clone, Encodable, PartialEq, Eq, Decodable, Hash, Show)]
1031 pub enum BuiltinBound {
1038 pub fn empty_builtin_bounds() -> BuiltinBounds {
1042 pub fn all_builtin_bounds() -> BuiltinBounds {
1043 let mut set = EnumSet::empty();
1045 set.add(BoundSized);
1050 pub fn region_existential_bound(r: ty::Region) -> ExistentialBounds {
1052 * An existential bound that does not implement any traits.
1055 ty::ExistentialBounds { region_bound: r,
1056 builtin_bounds: empty_builtin_bounds() }
1059 impl CLike for BuiltinBound {
1060 fn to_uint(&self) -> uint {
1063 fn from_uint(v: uint) -> BuiltinBound {
1064 unsafe { mem::transmute(v) }
1068 #[deriving(Clone, PartialEq, Eq, Hash)]
1073 #[deriving(Clone, PartialEq, Eq, Hash)]
1078 #[deriving(Clone, PartialEq, Eq, Hash)]
1079 pub struct FloatVid {
1083 #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)]
1084 pub struct RegionVid {
1088 #[deriving(Clone, PartialEq, Eq, Hash)]
1095 // FIXME -- once integral fallback is impl'd, we should remove
1096 // this type. It's only needed to prevent spurious errors for
1097 // integers whose type winds up never being constrained.
1098 SkolemizedIntTy(uint),
1101 #[deriving(Clone, Encodable, Decodable, Eq, Hash, Show)]
1102 pub enum InferRegion {
1104 ReSkolemized(uint, BoundRegion)
1107 impl cmp::PartialEq for InferRegion {
1108 fn eq(&self, other: &InferRegion) -> bool {
1109 match ((*self), *other) {
1110 (ReVar(rva), ReVar(rvb)) => {
1113 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
1119 fn ne(&self, other: &InferRegion) -> bool {
1120 !((*self) == (*other))
1124 impl fmt::Show for TyVid {
1125 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
1126 write!(f, "<generic #{}>", self.index)
1130 impl fmt::Show for IntVid {
1131 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1132 write!(f, "<generic integer #{}>", self.index)
1136 impl fmt::Show for FloatVid {
1137 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1138 write!(f, "<generic float #{}>", self.index)
1142 impl fmt::Show for RegionVid {
1143 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1144 write!(f, "'<generic lifetime #{}>", self.index)
1148 impl fmt::Show for FnSig {
1149 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1150 // grr, without tcx not much we can do.
1155 impl fmt::Show for InferTy {
1156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1158 TyVar(ref v) => v.fmt(f),
1159 IntVar(ref v) => v.fmt(f),
1160 FloatVar(ref v) => v.fmt(f),
1161 SkolemizedTy(v) => write!(f, "SkolemizedTy({})", v),
1162 SkolemizedIntTy(v) => write!(f, "SkolemizedIntTy({})", v),
1167 impl fmt::Show for IntVarValue {
1168 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1170 IntType(ref v) => v.fmt(f),
1171 UintType(ref v) => v.fmt(f),
1176 #[deriving(Clone, Show)]
1177 pub struct TypeParameterDef {
1178 pub ident: ast::Ident,
1179 pub def_id: ast::DefId,
1180 pub space: subst::ParamSpace,
1182 pub bounds: ParamBounds,
1183 pub default: Option<ty::t>,
1186 #[deriving(Encodable, Decodable, Clone, Show)]
1187 pub struct RegionParameterDef {
1188 pub name: ast::Name,
1189 pub def_id: ast::DefId,
1190 pub space: subst::ParamSpace,
1192 pub bounds: Vec<ty::Region>,
1195 /// Information about the type/lifetime parameters associated with an
1196 /// item or method. Analogous to ast::Generics.
1197 #[deriving(Clone, Show)]
1198 pub struct Generics {
1199 pub types: VecPerParamSpace<TypeParameterDef>,
1200 pub regions: VecPerParamSpace<RegionParameterDef>,
1204 pub fn empty() -> Generics {
1205 Generics { types: VecPerParamSpace::empty(),
1206 regions: VecPerParamSpace::empty() }
1209 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
1210 !self.types.is_empty_in(space)
1213 pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
1214 !self.regions.is_empty_in(space)
1219 pub fn self_ty(&self) -> ty::t {
1220 self.substs.self_ty().unwrap()
1224 /// When type checking, we use the `ParameterEnvironment` to track
1225 /// details about the type/lifetime parameters that are in scope.
1226 /// It primarily stores the bounds information.
1228 /// Note: This information might seem to be redundant with the data in
1229 /// `tcx.ty_param_defs`, but it is not. That table contains the
1230 /// parameter definitions from an "outside" perspective, but this
1231 /// struct will contain the bounds for a parameter as seen from inside
1232 /// the function body. Currently the only real distinction is that
1233 /// bound lifetime parameters are replaced with free ones, but in the
1234 /// future I hope to refine the representation of types so as to make
1235 /// more distinctions clearer.
1236 pub struct ParameterEnvironment {
1237 /// A substitution that can be applied to move from
1238 /// the "outer" view of a type or method to the "inner" view.
1239 /// In general, this means converting from bound parameters to
1240 /// free parameters. Since we currently represent bound/free type
1241 /// parameters in the same way, this only has an affect on regions.
1242 pub free_substs: Substs,
1244 /// Bounds on the various type parameters
1245 pub bounds: VecPerParamSpace<ParamBounds>,
1247 /// Each type parameter has an implicit region bound that
1248 /// indicates it must outlive at least the function body (the user
1249 /// may specify stronger requirements). This field indicates the
1250 /// region of the callee.
1251 pub implicit_region_bound: ty::Region,
1253 /// Obligations that the caller must satisfy. This is basically
1254 /// the set of bounds on the in-scope type parameters, translated
1255 /// into Obligations.
1257 /// Note: This effectively *duplicates* the `bounds` array for
1259 pub caller_obligations: VecPerParamSpace<traits::Obligation>,
1262 impl ParameterEnvironment {
1263 pub fn for_item(cx: &ctxt, id: NodeId) -> ParameterEnvironment {
1264 match cx.map.find(id) {
1265 Some(ast_map::NodeImplItem(ref impl_item)) => {
1267 ast::MethodImplItem(ref method) => {
1268 let method_def_id = ast_util::local_def(id);
1269 match ty::impl_or_trait_item(cx, method_def_id) {
1270 MethodTraitItem(ref method_ty) => {
1271 let method_generics = &method_ty.generics;
1272 construct_parameter_environment(
1276 method.pe_body().id)
1282 Some(ast_map::NodeTraitItem(trait_method)) => {
1283 match *trait_method {
1284 ast::RequiredMethod(ref required) => {
1285 cx.sess.span_bug(required.span,
1286 "ParameterEnvironment::from_item():
1287 can't create a parameter \
1288 environment for required trait \
1291 ast::ProvidedMethod(ref method) => {
1292 let method_def_id = ast_util::local_def(id);
1293 match ty::impl_or_trait_item(cx, method_def_id) {
1294 MethodTraitItem(ref method_ty) => {
1295 let method_generics = &method_ty.generics;
1296 construct_parameter_environment(
1300 method.pe_body().id)
1306 Some(ast_map::NodeItem(item)) => {
1308 ast::ItemFn(_, _, _, _, ref body) => {
1309 // We assume this is a function.
1310 let fn_def_id = ast_util::local_def(id);
1311 let fn_pty = ty::lookup_item_type(cx, fn_def_id);
1313 construct_parameter_environment(cx,
1319 ast::ItemStruct(..) |
1321 ast::ItemStatic(..) => {
1322 let def_id = ast_util::local_def(id);
1323 let pty = ty::lookup_item_type(cx, def_id);
1324 construct_parameter_environment(cx, item.span,
1328 cx.sess.span_bug(item.span,
1329 "ParameterEnvironment::from_item():
1330 can't create a parameter \
1331 environment for this kind of item")
1336 cx.sess.bug(format!("ParameterEnvironment::from_item(): \
1337 `{}` is not an item",
1338 cx.map.node_to_string(id)).as_slice())
1346 /// - `generics`: the set of type parameters and their bounds
1347 /// - `ty`: the base types, which may reference the parameters defined
1349 #[deriving(Clone, Show)]
1350 pub struct Polytype {
1351 pub generics: Generics,
1355 /// As `Polytype` but for a trait ref.
1356 pub struct TraitDef {
1357 /// Generic type definitions. Note that `Self` is listed in here
1358 /// as having a single bound, the trait itself (e.g., in the trait
1359 /// `Eq`, there is a single bound `Self : Eq`). This is so that
1360 /// default methods get to assume that the `Self` parameters
1361 /// implements the trait.
1362 pub generics: Generics,
1364 /// The "supertrait" bounds.
1365 pub bounds: ParamBounds,
1366 pub trait_ref: Rc<ty::TraitRef>,
1369 /// Records the substitutions used to translate the polytype for an
1370 /// item into the monotype of an item reference.
1372 pub struct ItemSubsts {
1376 pub type type_cache = RefCell<DefIdMap<Polytype>>;
1378 pub type node_type_table = RefCell<HashMap<uint,t>>;
1380 /// Records information about each unboxed closure.
1382 pub struct UnboxedClosure {
1383 /// The type of the unboxed closure.
1384 pub closure_type: ClosureTy,
1385 /// The kind of unboxed closure this is.
1386 pub kind: UnboxedClosureKind,
1389 #[deriving(Clone, PartialEq, Eq)]
1390 pub enum UnboxedClosureKind {
1391 FnUnboxedClosureKind,
1392 FnMutUnboxedClosureKind,
1393 FnOnceUnboxedClosureKind,
1396 impl UnboxedClosureKind {
1397 pub fn trait_did(&self, cx: &ctxt) -> ast::DefId {
1398 let result = match *self {
1399 FnUnboxedClosureKind => cx.lang_items.require(FnTraitLangItem),
1400 FnMutUnboxedClosureKind => {
1401 cx.lang_items.require(FnMutTraitLangItem)
1403 FnOnceUnboxedClosureKind => {
1404 cx.lang_items.require(FnOnceTraitLangItem)
1408 Ok(trait_did) => trait_did,
1409 Err(err) => cx.sess.fatal(err.as_slice()),
1414 pub fn mk_ctxt<'tcx>(s: Session,
1415 type_arena: &'tcx TypedArena<t_box_>,
1416 dm: resolve::DefMap,
1417 named_region_map: resolve_lifetime::NamedRegionMap,
1418 map: ast_map::Map<'tcx>,
1419 freevars: freevars::freevar_map,
1420 capture_modes: freevars::CaptureModeMap,
1421 region_maps: middle::region::RegionMaps,
1422 lang_items: middle::lang_items::LanguageItems,
1423 stability: stability::Index) -> ctxt<'tcx> {
1425 type_arena: type_arena,
1426 interner: RefCell::new(FnvHashMap::new()),
1427 named_region_map: named_region_map,
1428 item_variance_map: RefCell::new(DefIdMap::new()),
1429 variance_computed: Cell::new(false),
1430 next_id: Cell::new(primitives::LAST_PRIMITIVE_ID),
1433 region_maps: region_maps,
1434 node_types: RefCell::new(HashMap::new()),
1435 item_substs: RefCell::new(NodeMap::new()),
1436 trait_refs: RefCell::new(NodeMap::new()),
1437 trait_defs: RefCell::new(DefIdMap::new()),
1438 object_cast_map: RefCell::new(NodeMap::new()),
1440 intrinsic_defs: RefCell::new(DefIdMap::new()),
1441 freevars: RefCell::new(freevars),
1442 tcache: RefCell::new(DefIdMap::new()),
1443 rcache: RefCell::new(HashMap::new()),
1444 short_names_cache: RefCell::new(HashMap::new()),
1445 needs_unwind_cleanup_cache: RefCell::new(HashMap::new()),
1446 tc_cache: RefCell::new(HashMap::new()),
1447 ast_ty_to_ty_cache: RefCell::new(NodeMap::new()),
1448 enum_var_cache: RefCell::new(DefIdMap::new()),
1449 impl_or_trait_items: RefCell::new(DefIdMap::new()),
1450 trait_item_def_ids: RefCell::new(DefIdMap::new()),
1451 trait_items_cache: RefCell::new(DefIdMap::new()),
1452 impl_trait_cache: RefCell::new(DefIdMap::new()),
1453 ty_param_defs: RefCell::new(NodeMap::new()),
1454 adjustments: RefCell::new(NodeMap::new()),
1455 normalized_cache: RefCell::new(HashMap::new()),
1456 lang_items: lang_items,
1457 provided_method_sources: RefCell::new(DefIdMap::new()),
1458 superstructs: RefCell::new(DefIdMap::new()),
1459 struct_fields: RefCell::new(DefIdMap::new()),
1460 destructor_for_type: RefCell::new(DefIdMap::new()),
1461 destructors: RefCell::new(DefIdSet::new()),
1462 trait_impls: RefCell::new(DefIdMap::new()),
1463 inherent_impls: RefCell::new(DefIdMap::new()),
1464 impl_items: RefCell::new(DefIdMap::new()),
1465 used_unsafe: RefCell::new(NodeSet::new()),
1466 used_mut_nodes: RefCell::new(NodeSet::new()),
1467 populated_external_types: RefCell::new(DefIdSet::new()),
1468 populated_external_traits: RefCell::new(DefIdSet::new()),
1469 upvar_borrow_map: RefCell::new(HashMap::new()),
1470 extern_const_statics: RefCell::new(DefIdMap::new()),
1471 extern_const_variants: RefCell::new(DefIdMap::new()),
1472 method_map: RefCell::new(FnvHashMap::new()),
1473 dependency_formats: RefCell::new(HashMap::new()),
1474 unboxed_closures: RefCell::new(DefIdMap::new()),
1475 node_lint_levels: RefCell::new(HashMap::new()),
1476 transmute_restrictions: RefCell::new(Vec::new()),
1477 stability: RefCell::new(stability),
1478 capture_modes: RefCell::new(capture_modes),
1482 // Type constructors
1484 // Interns a type/name combination, stores the resulting box in cx.interner,
1485 // and returns the box as cast to an unsafe ptr (see comments for t above).
1486 pub fn mk_t(cx: &ctxt, st: sty) -> t {
1487 // Check for primitive types.
1489 ty_nil => return mk_nil(),
1490 ty_err => return mk_err(),
1491 ty_bool => return mk_bool(),
1492 ty_int(i) => return mk_mach_int(i),
1493 ty_uint(u) => return mk_mach_uint(u),
1494 ty_float(f) => return mk_mach_float(f),
1495 ty_char => return mk_char(),
1496 ty_bot => return mk_bot(),
1500 let key = intern_key { sty: &st };
1502 match cx.interner.borrow().find(&key) {
1503 Some(t) => unsafe { return mem::transmute(&t.sty); },
1508 fn rflags(r: Region) -> uint {
1509 (has_regions as uint) | {
1511 ty::ReInfer(_) => needs_infer as uint,
1516 fn sflags(substs: &Substs) -> uint {
1518 let mut i = substs.types.iter();
1520 f |= get(*tt).flags;
1522 match substs.regions {
1523 subst::ErasedRegions => {}
1524 subst::NonerasedRegions(ref regions) => {
1525 for r in regions.iter() {
1532 fn flags_for_bounds(bounds: &ExistentialBounds) -> uint {
1533 rflags(bounds.region_bound)
1536 &ty_nil | &ty_bool | &ty_char | &ty_int(_) | &ty_float(_) | &ty_uint(_) |
1538 // You might think that we could just return ty_err for
1539 // any type containing ty_err as a component, and get
1540 // rid of the has_ty_err flag -- likewise for ty_bot (with
1541 // the exception of function types that return bot).
1542 // But doing so caused sporadic memory corruption, and
1543 // neither I (tjc) nor nmatsakis could figure out why,
1544 // so we're doing it this way.
1545 &ty_bot => flags |= has_ty_bot as uint,
1546 &ty_err => flags |= has_ty_err as uint,
1547 &ty_param(ref p) => {
1548 if p.space == subst::SelfSpace {
1549 flags |= has_self as uint;
1551 flags |= has_params as uint;
1554 &ty_unboxed_closure(_, ref region) => flags |= rflags(*region),
1555 &ty_infer(_) => flags |= needs_infer as uint,
1556 &ty_enum(_, ref substs) | &ty_struct(_, ref substs) => {
1557 flags |= sflags(substs);
1559 &ty_trait(box TyTrait { ref substs, ref bounds, .. }) => {
1560 flags |= sflags(substs);
1561 flags |= flags_for_bounds(bounds);
1563 &ty_box(tt) | &ty_uniq(tt) | &ty_vec(tt, _) | &ty_open(tt) => {
1564 flags |= get(tt).flags
1567 flags |= get(m.ty).flags;
1569 &ty_rptr(r, ref m) => {
1571 flags |= get(m.ty).flags;
1573 &ty_tup(ref ts) => for tt in ts.iter() { flags |= get(*tt).flags; },
1574 &ty_bare_fn(ref f) => {
1575 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1576 flags |= get(f.sig.output).flags;
1577 // T -> _|_ is *not* _|_ !
1578 flags &= !(has_ty_bot as uint);
1580 &ty_closure(ref f) => {
1582 RegionTraitStore(r, _) => {
1587 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1588 flags |= get(f.sig.output).flags;
1589 // T -> _|_ is *not* _|_ !
1590 flags &= !(has_ty_bot as uint);
1591 flags |= flags_for_bounds(&f.bounds);
1595 let t = cx.type_arena.alloc(t_box_ {
1597 id: cx.next_id.get(),
1601 let sty_ptr = &t.sty as *const sty;
1603 let key = intern_key {
1607 cx.interner.borrow_mut().insert(key, t);
1609 cx.next_id.set(cx.next_id.get() + 1);
1612 mem::transmute::<*const sty, t>(sty_ptr)
1617 pub fn mk_prim_t(primitive: &'static t_box_) -> t {
1619 mem::transmute::<&'static t_box_, t>(primitive)
1624 pub fn mk_nil() -> t { mk_prim_t(&primitives::TY_NIL) }
1627 pub fn mk_err() -> t { mk_prim_t(&primitives::TY_ERR) }
1630 pub fn mk_bot() -> t { mk_prim_t(&primitives::TY_BOT) }
1633 pub fn mk_bool() -> t { mk_prim_t(&primitives::TY_BOOL) }
1636 pub fn mk_int() -> t { mk_prim_t(&primitives::TY_INT) }
1639 pub fn mk_i8() -> t { mk_prim_t(&primitives::TY_I8) }
1642 pub fn mk_i16() -> t { mk_prim_t(&primitives::TY_I16) }
1645 pub fn mk_i32() -> t { mk_prim_t(&primitives::TY_I32) }
1648 pub fn mk_i64() -> t { mk_prim_t(&primitives::TY_I64) }
1651 pub fn mk_f32() -> t { mk_prim_t(&primitives::TY_F32) }
1654 pub fn mk_f64() -> t { mk_prim_t(&primitives::TY_F64) }
1657 pub fn mk_uint() -> t { mk_prim_t(&primitives::TY_UINT) }
1660 pub fn mk_u8() -> t { mk_prim_t(&primitives::TY_U8) }
1663 pub fn mk_u16() -> t { mk_prim_t(&primitives::TY_U16) }
1666 pub fn mk_u32() -> t { mk_prim_t(&primitives::TY_U32) }
1669 pub fn mk_u64() -> t { mk_prim_t(&primitives::TY_U64) }
1671 pub fn mk_mach_int(tm: ast::IntTy) -> t {
1673 ast::TyI => mk_int(),
1674 ast::TyI8 => mk_i8(),
1675 ast::TyI16 => mk_i16(),
1676 ast::TyI32 => mk_i32(),
1677 ast::TyI64 => mk_i64(),
1681 pub fn mk_mach_uint(tm: ast::UintTy) -> t {
1683 ast::TyU => mk_uint(),
1684 ast::TyU8 => mk_u8(),
1685 ast::TyU16 => mk_u16(),
1686 ast::TyU32 => mk_u32(),
1687 ast::TyU64 => mk_u64(),
1691 pub fn mk_mach_float(tm: ast::FloatTy) -> t {
1693 ast::TyF32 => mk_f32(),
1694 ast::TyF64 => mk_f64(),
1699 pub fn mk_char() -> t { mk_prim_t(&primitives::TY_CHAR) }
1701 pub fn mk_str(cx: &ctxt) -> t {
1705 pub fn mk_str_slice(cx: &ctxt, r: Region, m: ast::Mutability) -> t {
1708 ty: mk_t(cx, ty_str),
1713 pub fn mk_enum(cx: &ctxt, did: ast::DefId, substs: Substs) -> t {
1714 // take a copy of substs so that we own the vectors inside
1715 mk_t(cx, ty_enum(did, substs))
1718 pub fn mk_box(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_box(ty)) }
1720 pub fn mk_uniq(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_uniq(ty)) }
1722 pub fn mk_ptr(cx: &ctxt, tm: mt) -> t { mk_t(cx, ty_ptr(tm)) }
1724 pub fn mk_rptr(cx: &ctxt, r: Region, tm: mt) -> t { mk_t(cx, ty_rptr(r, tm)) }
1726 pub fn mk_mut_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1727 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
1729 pub fn mk_imm_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1730 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
1733 pub fn mk_mut_ptr(cx: &ctxt, ty: t) -> t {
1734 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
1737 pub fn mk_imm_ptr(cx: &ctxt, ty: t) -> t {
1738 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
1741 pub fn mk_nil_ptr(cx: &ctxt) -> t {
1742 mk_ptr(cx, mt {ty: mk_nil(), mutbl: ast::MutImmutable})
1745 pub fn mk_vec(cx: &ctxt, t: t, sz: Option<uint>) -> t {
1746 mk_t(cx, ty_vec(t, sz))
1749 pub fn mk_slice(cx: &ctxt, r: Region, tm: mt) -> t {
1752 ty: mk_vec(cx, tm.ty, None),
1757 pub fn mk_tup(cx: &ctxt, ts: Vec<t>) -> t { mk_t(cx, ty_tup(ts)) }
1759 pub fn mk_closure(cx: &ctxt, fty: ClosureTy) -> t {
1760 mk_t(cx, ty_closure(box fty))
1763 pub fn mk_bare_fn(cx: &ctxt, fty: BareFnTy) -> t {
1764 mk_t(cx, ty_bare_fn(fty))
1767 pub fn mk_ctor_fn(cx: &ctxt,
1768 binder_id: ast::NodeId,
1769 input_tys: &[ty::t],
1770 output: ty::t) -> t {
1771 let input_args = input_tys.iter().map(|t| *t).collect();
1774 fn_style: ast::NormalFn,
1777 binder_id: binder_id,
1786 pub fn mk_trait(cx: &ctxt,
1789 bounds: ExistentialBounds)
1791 // take a copy of substs so that we own the vectors inside
1792 let inner = box TyTrait {
1797 mk_t(cx, ty_trait(inner))
1800 pub fn mk_struct(cx: &ctxt, struct_id: ast::DefId, substs: Substs) -> t {
1801 // take a copy of substs so that we own the vectors inside
1802 mk_t(cx, ty_struct(struct_id, substs))
1805 pub fn mk_unboxed_closure(cx: &ctxt, closure_id: ast::DefId, region: Region)
1807 mk_t(cx, ty_unboxed_closure(closure_id, region))
1810 pub fn mk_var(cx: &ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) }
1812 pub fn mk_int_var(cx: &ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) }
1814 pub fn mk_float_var(cx: &ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) }
1816 pub fn mk_infer(cx: &ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) }
1818 pub fn mk_param(cx: &ctxt, space: subst::ParamSpace, n: uint, k: DefId) -> t {
1819 mk_t(cx, ty_param(ParamTy { space: space, idx: n, def_id: k }))
1822 pub fn mk_self_type(cx: &ctxt, did: ast::DefId) -> t {
1823 mk_param(cx, subst::SelfSpace, 0, did)
1826 pub fn mk_param_from_def(cx: &ctxt, def: &TypeParameterDef) -> t {
1827 mk_param(cx, def.space, def.index, def.def_id)
1830 pub fn mk_open(cx: &ctxt, t: t) -> t { mk_t(cx, ty_open(t)) }
1832 pub fn walk_ty(ty: t, f: |t|) {
1833 maybe_walk_ty(ty, |t| { f(t); true });
1836 pub fn maybe_walk_ty(ty: t, f: |t| -> bool) {
1841 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) |
1842 ty_str | ty_infer(_) | ty_param(_) | ty_unboxed_closure(_, _) | ty_err => {}
1843 ty_box(ty) | ty_uniq(ty) | ty_vec(ty, _) | ty_open(ty) => maybe_walk_ty(ty, f),
1844 ty_ptr(ref tm) | ty_rptr(_, ref tm) => {
1845 maybe_walk_ty(tm.ty, f);
1847 ty_enum(_, ref substs) | ty_struct(_, ref substs) |
1848 ty_trait(box TyTrait { ref substs, .. }) => {
1849 for subty in (*substs).types.iter() {
1850 maybe_walk_ty(*subty, |x| f(x));
1853 ty_tup(ref ts) => { for tt in ts.iter() { maybe_walk_ty(*tt, |x| f(x)); } }
1854 ty_bare_fn(ref ft) => {
1855 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1856 maybe_walk_ty(ft.sig.output, f);
1858 ty_closure(ref ft) => {
1859 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1860 maybe_walk_ty(ft.sig.output, f);
1865 // Folds types from the bottom up.
1866 pub fn fold_ty(cx: &ctxt, t0: t, fldop: |t| -> t) -> t {
1867 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
1871 pub fn walk_regions_and_ty(cx: &ctxt, ty: t, fldr: |r: Region|, fldt: |t: t|)
1873 ty_fold::RegionFolder::general(cx,
1875 |t| { fldt(t); t }).fold_ty(ty)
1879 pub fn new(space: subst::ParamSpace,
1883 ParamTy { space: space, idx: index, def_id: def_id }
1886 pub fn for_self(trait_def_id: ast::DefId) -> ParamTy {
1887 ParamTy::new(subst::SelfSpace, 0, trait_def_id)
1890 pub fn for_def(def: &TypeParameterDef) -> ParamTy {
1891 ParamTy::new(def.space, def.index, def.def_id)
1894 pub fn to_ty(self, tcx: &ty::ctxt) -> ty::t {
1895 ty::mk_param(tcx, self.space, self.idx, self.def_id)
1900 pub fn empty() -> ItemSubsts {
1901 ItemSubsts { substs: Substs::empty() }
1904 pub fn is_noop(&self) -> bool {
1905 self.substs.is_noop()
1911 pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil }
1913 pub fn type_is_bot(ty: t) -> bool {
1914 (get(ty).flags & (has_ty_bot as uint)) != 0
1917 pub fn type_is_error(ty: t) -> bool {
1918 (get(ty).flags & (has_ty_err as uint)) != 0
1921 pub fn type_needs_subst(ty: t) -> bool {
1922 tbox_has_flag(get(ty), needs_subst)
1925 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
1926 tref.substs.types.any(|&t| type_is_error(t))
1929 pub fn type_is_ty_var(ty: t) -> bool {
1931 ty_infer(TyVar(_)) => true,
1936 pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool }
1938 pub fn type_is_self(ty: t) -> bool {
1940 ty_param(ref p) => p.space == subst::SelfSpace,
1945 fn type_is_slice(ty: t) -> bool {
1947 ty_ptr(mt) | ty_rptr(_, mt) => match get(mt.ty).sty {
1948 ty_vec(_, None) | ty_str => true,
1955 pub fn type_is_vec(ty: t) -> bool {
1958 ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) |
1959 ty_box(t) | ty_uniq(t) => match get(t).sty {
1960 ty_vec(_, None) => true,
1967 pub fn type_is_structural(ty: t) -> bool {
1969 ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) |
1970 ty_vec(_, Some(_)) | ty_unboxed_closure(..) => true,
1971 _ => type_is_slice(ty) | type_is_trait(ty)
1975 pub fn type_is_simd(cx: &ctxt, ty: t) -> bool {
1977 ty_struct(did, _) => lookup_simd(cx, did),
1982 pub fn sequence_element_type(cx: &ctxt, ty: t) -> t {
1984 ty_vec(ty, _) => ty,
1985 ty_str => mk_mach_uint(ast::TyU8),
1986 ty_open(ty) => sequence_element_type(cx, ty),
1987 _ => cx.sess.bug(format!("sequence_element_type called on non-sequence value: {}",
1988 ty_to_string(cx, ty)).as_slice()),
1992 pub fn simd_type(cx: &ctxt, ty: t) -> t {
1994 ty_struct(did, ref substs) => {
1995 let fields = lookup_struct_fields(cx, did);
1996 lookup_field_type(cx, did, fields.get(0).id, substs)
1998 _ => fail!("simd_type called on invalid type")
2002 pub fn simd_size(cx: &ctxt, ty: t) -> uint {
2004 ty_struct(did, _) => {
2005 let fields = lookup_struct_fields(cx, did);
2008 _ => fail!("simd_size called on invalid type")
2012 pub fn type_is_boxed(ty: t) -> bool {
2019 pub fn type_is_region_ptr(ty: t) -> bool {
2021 ty_rptr(..) => true,
2026 pub fn type_is_unsafe_ptr(ty: t) -> bool {
2028 ty_ptr(_) => return true,
2033 pub fn type_is_unique(ty: t) -> bool {
2035 ty_uniq(_) => match get(ty).sty {
2036 ty_trait(..) => false,
2043 pub fn type_is_fat_ptr(cx: &ctxt, ty: t) -> bool {
2045 ty_ptr(mt{ty, ..}) | ty_rptr(_, mt{ty, ..})
2046 | ty_uniq(ty) if !type_is_sized(cx, ty) => true,
2052 A scalar type is one that denotes an atomic datum, with no sub-components.
2053 (A ty_ptr is scalar because it represents a non-managed pointer, so its
2054 contents are abstract to rustc.)
2056 pub fn type_is_scalar(ty: t) -> bool {
2058 ty_nil | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
2059 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
2060 ty_bare_fn(..) | ty_ptr(_) => true,
2065 /// Returns true if this type is a floating point type and false otherwise.
2066 pub fn type_is_floating_point(ty: t) -> bool {
2068 ty_float(_) => true,
2073 pub fn type_needs_drop(cx: &ctxt, ty: t) -> bool {
2074 type_contents(cx, ty).needs_drop(cx)
2077 // Some things don't need cleanups during unwinding because the
2078 // task can free them all at once later. Currently only things
2079 // that only contain scalars and shared boxes can avoid unwind
2081 pub fn type_needs_unwind_cleanup(cx: &ctxt, ty: t) -> bool {
2082 match cx.needs_unwind_cleanup_cache.borrow().find(&ty) {
2083 Some(&result) => return result,
2087 let mut tycache = HashSet::new();
2088 let needs_unwind_cleanup =
2089 type_needs_unwind_cleanup_(cx, ty, &mut tycache, false);
2090 cx.needs_unwind_cleanup_cache.borrow_mut().insert(ty, needs_unwind_cleanup);
2091 return needs_unwind_cleanup;
2094 fn type_needs_unwind_cleanup_(cx: &ctxt, ty: t,
2095 tycache: &mut HashSet<t>,
2096 encountered_box: bool) -> bool {
2098 // Prevent infinite recursion
2099 if !tycache.insert(ty) {
2103 let mut encountered_box = encountered_box;
2104 let mut needs_unwind_cleanup = false;
2105 maybe_walk_ty(ty, |ty| {
2106 let old_encountered_box = encountered_box;
2107 let result = match get(ty).sty {
2109 encountered_box = true;
2112 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2113 ty_tup(_) | ty_ptr(_) => {
2116 ty_enum(did, ref substs) => {
2117 for v in (*enum_variants(cx, did)).iter() {
2118 for aty in v.args.iter() {
2119 let t = aty.subst(cx, substs);
2120 needs_unwind_cleanup |=
2121 type_needs_unwind_cleanup_(cx, t, tycache,
2125 !needs_unwind_cleanup
2128 // Once we're inside a box, the annihilator will find
2129 // it and destroy it.
2130 if !encountered_box {
2131 needs_unwind_cleanup = true;
2138 needs_unwind_cleanup = true;
2143 encountered_box = old_encountered_box;
2147 return needs_unwind_cleanup;
2151 * Type contents is how the type checker reasons about kinds.
2152 * They track what kinds of things are found within a type. You can
2153 * think of them as kind of an "anti-kind". They track the kinds of values
2154 * and thinks that are contained in types. Having a larger contents for
2155 * a type tends to rule that type *out* from various kinds. For example,
2156 * a type that contains a reference is not sendable.
2158 * The reason we compute type contents and not kinds is that it is
2159 * easier for me (nmatsakis) to think about what is contained within
2160 * a type than to think about what is *not* contained within a type.
2162 pub struct TypeContents {
2166 macro_rules! def_type_content_sets(
2167 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
2168 #[allow(non_snake_case)]
2170 use middle::ty::TypeContents;
2171 $(pub static $name: TypeContents = TypeContents { bits: $bits };)+
2176 def_type_content_sets!(
2178 None = 0b0000_0000__0000_0000__0000,
2180 // Things that are interior to the value (first nibble):
2181 InteriorUnsized = 0b0000_0000__0000_0000__0001,
2182 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
2183 // InteriorAll = 0b00000000__00000000__1111,
2185 // Things that are owned by the value (second and third nibbles):
2186 OwnsOwned = 0b0000_0000__0000_0001__0000,
2187 OwnsDtor = 0b0000_0000__0000_0010__0000,
2188 OwnsManaged /* see [1] below */ = 0b0000_0000__0000_0100__0000,
2189 OwnsAffine = 0b0000_0000__0000_1000__0000,
2190 OwnsAll = 0b0000_0000__1111_1111__0000,
2192 // Things that are reachable by the value in any way (fourth nibble):
2193 ReachesNonsendAnnot = 0b0000_0001__0000_0000__0000,
2194 ReachesBorrowed = 0b0000_0010__0000_0000__0000,
2195 // ReachesManaged /* see [1] below */ = 0b0000_0100__0000_0000__0000,
2196 ReachesMutable = 0b0000_1000__0000_0000__0000,
2197 ReachesNoSync = 0b0001_0000__0000_0000__0000,
2198 ReachesFfiUnsafe = 0b0010_0000__0000_0000__0000,
2199 ReachesAll = 0b0011_1111__0000_0000__0000,
2201 // Things that cause values to *move* rather than *copy*
2202 Moves = 0b0000_0000__0000_1011__0000,
2204 // Things that mean drop glue is necessary
2205 NeedsDrop = 0b0000_0000__0000_0111__0000,
2207 // Things that prevent values from being sent
2209 // Note: For checking whether something is sendable, it'd
2210 // be sufficient to have ReachesManaged. However, we include
2211 // both ReachesManaged and OwnsManaged so that when
2212 // a parameter has a bound T:Send, we are able to deduce
2213 // that it neither reaches nor owns a managed pointer.
2214 Nonsendable = 0b0000_0111__0000_0100__0000,
2216 // Things that prevent values from being considered sized
2217 Nonsized = 0b0000_0000__0000_0000__0001,
2219 // Things that prevent values from being sync
2220 Nonsync = 0b0001_0000__0000_0000__0000,
2222 // Things that make values considered not POD (would be same
2223 // as `Moves`, but for the fact that managed data `@` is
2224 // not considered POD)
2225 Noncopy = 0b0000_0000__0000_1111__0000,
2227 // Bits to set when a managed value is encountered
2229 // [1] Do not set the bits TC::OwnsManaged or
2230 // TC::ReachesManaged directly, instead reference
2231 // TC::Managed to set them both at once.
2232 Managed = 0b0000_0100__0000_0100__0000,
2235 All = 0b1111_1111__1111_1111__1111
2240 pub fn meets_builtin_bound(&self, cx: &ctxt, bb: BuiltinBound) -> bool {
2242 BoundSend => self.is_sendable(cx),
2243 BoundSized => self.is_sized(cx),
2244 BoundCopy => self.is_copy(cx),
2245 BoundSync => self.is_sync(cx),
2249 pub fn when(&self, cond: bool) -> TypeContents {
2250 if cond {*self} else {TC::None}
2253 pub fn intersects(&self, tc: TypeContents) -> bool {
2254 (self.bits & tc.bits) != 0
2257 pub fn is_sendable(&self, _: &ctxt) -> bool {
2258 !self.intersects(TC::Nonsendable)
2261 pub fn is_sync(&self, _: &ctxt) -> bool {
2262 !self.intersects(TC::Nonsync)
2265 pub fn owns_managed(&self) -> bool {
2266 self.intersects(TC::OwnsManaged)
2269 pub fn owns_owned(&self) -> bool {
2270 self.intersects(TC::OwnsOwned)
2273 pub fn is_sized(&self, _: &ctxt) -> bool {
2274 !self.intersects(TC::Nonsized)
2277 pub fn is_copy(&self, _: &ctxt) -> bool {
2278 !self.intersects(TC::Noncopy)
2281 pub fn interior_unsafe(&self) -> bool {
2282 self.intersects(TC::InteriorUnsafe)
2285 pub fn interior_unsized(&self) -> bool {
2286 self.intersects(TC::InteriorUnsized)
2289 pub fn moves_by_default(&self, _: &ctxt) -> bool {
2290 self.intersects(TC::Moves)
2293 pub fn needs_drop(&self, _: &ctxt) -> bool {
2294 self.intersects(TC::NeedsDrop)
2297 pub fn owned_pointer(&self) -> TypeContents {
2299 * Includes only those bits that still apply
2300 * when indirected through a `Box` pointer
2303 *self & (TC::OwnsAll | TC::ReachesAll))
2306 pub fn reference(&self, bits: TypeContents) -> TypeContents {
2308 * Includes only those bits that still apply
2309 * when indirected through a reference (`&`)
2312 *self & TC::ReachesAll)
2315 pub fn managed_pointer(&self) -> TypeContents {
2317 * Includes only those bits that still apply
2318 * when indirected through a managed pointer (`@`)
2321 *self & TC::ReachesAll)
2324 pub fn unsafe_pointer(&self) -> TypeContents {
2326 * Includes only those bits that still apply
2327 * when indirected through an unsafe pointer (`*`)
2329 *self & TC::ReachesAll
2332 pub fn union<T>(v: &[T], f: |&T| -> TypeContents) -> TypeContents {
2333 v.iter().fold(TC::None, |tc, t| tc | f(t))
2336 pub fn has_dtor(&self) -> bool {
2337 self.intersects(TC::OwnsDtor)
2341 impl ops::BitOr<TypeContents,TypeContents> for TypeContents {
2342 fn bitor(&self, other: &TypeContents) -> TypeContents {
2343 TypeContents {bits: self.bits | other.bits}
2347 impl ops::BitAnd<TypeContents,TypeContents> for TypeContents {
2348 fn bitand(&self, other: &TypeContents) -> TypeContents {
2349 TypeContents {bits: self.bits & other.bits}
2353 impl ops::Sub<TypeContents,TypeContents> for TypeContents {
2354 fn sub(&self, other: &TypeContents) -> TypeContents {
2355 TypeContents {bits: self.bits & !other.bits}
2359 impl fmt::Show for TypeContents {
2360 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2361 write!(f, "TypeContents({:t})", self.bits)
2365 pub fn type_is_sendable(cx: &ctxt, t: ty::t) -> bool {
2366 type_contents(cx, t).is_sendable(cx)
2369 pub fn type_interior_is_unsafe(cx: &ctxt, t: ty::t) -> bool {
2370 type_contents(cx, t).interior_unsafe()
2373 pub fn type_contents(cx: &ctxt, ty: t) -> TypeContents {
2374 let ty_id = type_id(ty);
2376 match cx.tc_cache.borrow().find(&ty_id) {
2377 Some(tc) => { return *tc; }
2381 let mut cache = HashMap::new();
2382 let result = tc_ty(cx, ty, &mut cache);
2384 cx.tc_cache.borrow_mut().insert(ty_id, result);
2389 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2391 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
2392 // private cache for this walk. This is needed in the case of cyclic
2395 // struct List { next: Box<Option<List>>, ... }
2397 // When computing the type contents of such a type, we wind up deeply
2398 // recursing as we go. So when we encounter the recursive reference
2399 // to List, we temporarily use TC::None as its contents. Later we'll
2400 // patch up the cache with the correct value, once we've computed it
2401 // (this is basically a co-inductive process, if that helps). So in
2402 // the end we'll compute TC::OwnsOwned, in this case.
2404 // The problem is, as we are doing the computation, we will also
2405 // compute an *intermediate* contents for, e.g., Option<List> of
2406 // TC::None. This is ok during the computation of List itself, but if
2407 // we stored this intermediate value into cx.tc_cache, then later
2408 // requests for the contents of Option<List> would also yield TC::None
2409 // which is incorrect. This value was computed based on the crutch
2410 // value for the type contents of list. The correct value is
2411 // TC::OwnsOwned. This manifested as issue #4821.
2412 let ty_id = type_id(ty);
2413 match cache.find(&ty_id) {
2414 Some(tc) => { return *tc; }
2417 match cx.tc_cache.borrow().find(&ty_id) { // Must check both caches!
2418 Some(tc) => { return *tc; }
2421 cache.insert(ty_id, TC::None);
2423 let result = match get(ty).sty {
2424 // uint and int are ffi-unsafe
2425 ty_uint(ast::TyU) | ty_int(ast::TyI) => {
2426 TC::ReachesFfiUnsafe
2429 // Scalar and unique types are sendable, and durable
2430 ty_infer(ty::SkolemizedIntTy(_)) |
2431 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2432 ty_bare_fn(_) | ty::ty_char => {
2436 ty_closure(ref c) => {
2437 closure_contents(cx, &**c) | TC::ReachesFfiUnsafe
2441 tc_ty(cx, typ, cache).managed_pointer() | TC::ReachesFfiUnsafe
2445 TC::ReachesFfiUnsafe | match get(typ).sty {
2446 ty_str => TC::OwnsOwned,
2447 _ => tc_ty(cx, typ, cache).owned_pointer(),
2451 ty_trait(box TyTrait { bounds, .. }) => {
2452 object_contents(cx, bounds) | TC::ReachesFfiUnsafe | TC::Nonsized
2456 tc_ty(cx, mt.ty, cache).unsafe_pointer()
2459 ty_rptr(r, ref mt) => {
2460 TC::ReachesFfiUnsafe | match get(mt.ty).sty {
2461 ty_str => borrowed_contents(r, ast::MutImmutable),
2462 ty_vec(..) => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(r, mt.mutbl)),
2463 _ => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(r, mt.mutbl)),
2467 ty_vec(t, Some(_)) => {
2471 ty_vec(t, None) => {
2472 tc_ty(cx, t, cache) | TC::Nonsized
2474 ty_str => TC::Nonsized,
2476 ty_struct(did, ref substs) => {
2477 let flds = struct_fields(cx, did, substs);
2479 TypeContents::union(flds.as_slice(),
2480 |f| tc_mt(cx, f.mt, cache));
2482 if !lookup_repr_hints(cx, did).contains(&attr::ReprExtern) {
2483 res = res | TC::ReachesFfiUnsafe;
2486 if ty::has_dtor(cx, did) {
2487 res = res | TC::OwnsDtor;
2489 apply_lang_items(cx, did, res)
2492 ty_unboxed_closure(did, r) => {
2493 // FIXME(#14449): `borrowed_contents` below assumes `&mut`
2495 let upvars = unboxed_closure_upvars(cx, did);
2496 TypeContents::union(upvars.as_slice(),
2497 |f| tc_ty(cx, f.ty, cache)) |
2498 borrowed_contents(r, MutMutable)
2501 ty_tup(ref tys) => {
2502 TypeContents::union(tys.as_slice(),
2503 |ty| tc_ty(cx, *ty, cache))
2506 ty_enum(did, ref substs) => {
2507 let variants = substd_enum_variants(cx, did, substs);
2509 TypeContents::union(variants.as_slice(), |variant| {
2510 TypeContents::union(variant.args.as_slice(),
2512 tc_ty(cx, *arg_ty, cache)
2516 if ty::has_dtor(cx, did) {
2517 res = res | TC::OwnsDtor;
2520 if variants.len() != 0 {
2521 let repr_hints = lookup_repr_hints(cx, did);
2522 if repr_hints.len() > 1 {
2523 // this is an error later on, but this type isn't safe
2524 res = res | TC::ReachesFfiUnsafe;
2527 match repr_hints.as_slice().get(0) {
2528 Some(h) => if !h.is_ffi_safe() {
2529 res = res | TC::ReachesFfiUnsafe;
2533 res = res | TC::ReachesFfiUnsafe;
2535 // We allow ReprAny enums if they are eligible for
2536 // the nullable pointer optimization and the
2537 // contained type is an `extern fn`
2539 if variants.len() == 2 {
2540 let mut data_idx = 0;
2542 if variants.get(0).args.len() == 0 {
2546 if variants.get(data_idx).args.len() == 1 {
2547 match get(*variants.get(data_idx).args.get(0)).sty {
2548 ty_bare_fn(..) => { res = res - TC::ReachesFfiUnsafe; }
2558 apply_lang_items(cx, did, res)
2562 // We only ever ask for the kind of types that are defined in
2563 // the current crate; therefore, the only type parameters that
2564 // could be in scope are those defined in the current crate.
2565 // If this assertion failures, it is likely because of a
2566 // failure in the cross-crate inlining code to translate a
2568 assert_eq!(p.def_id.krate, ast::LOCAL_CRATE);
2570 let ty_param_defs = cx.ty_param_defs.borrow();
2571 let tp_def = ty_param_defs.get(&p.def_id.node);
2572 kind_bounds_to_contents(
2574 tp_def.bounds.builtin_bounds,
2575 tp_def.bounds.trait_bounds.as_slice())
2579 // This occurs during coherence, but shouldn't occur at other
2585 let result = tc_ty(cx, t, cache);
2586 assert!(!result.is_sized(cx))
2587 result.unsafe_pointer() | TC::Nonsized
2591 cx.sess.bug("asked to compute contents of error type");
2595 cache.insert(ty_id, result);
2601 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2603 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
2604 mc | tc_ty(cx, mt.ty, cache)
2607 fn apply_lang_items(cx: &ctxt,
2611 if Some(did) == cx.lang_items.no_send_bound() {
2612 tc | TC::ReachesNonsendAnnot
2613 } else if Some(did) == cx.lang_items.managed_bound() {
2615 } else if Some(did) == cx.lang_items.no_copy_bound() {
2617 } else if Some(did) == cx.lang_items.no_sync_bound() {
2618 tc | TC::ReachesNoSync
2619 } else if Some(did) == cx.lang_items.unsafe_type() {
2620 // FIXME(#13231): This shouldn't be needed after
2621 // opt-in built-in bounds are implemented.
2622 (tc | TC::InteriorUnsafe) - TC::Nonsync
2628 fn borrowed_contents(region: ty::Region,
2629 mutbl: ast::Mutability)
2632 * Type contents due to containing a reference
2633 * with the region `region` and borrow kind `bk`
2636 let b = match mutbl {
2637 ast::MutMutable => TC::ReachesMutable | TC::OwnsAffine,
2638 ast::MutImmutable => TC::None,
2640 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
2643 fn closure_contents(cx: &ctxt, cty: &ClosureTy) -> TypeContents {
2644 // Closure contents are just like trait contents, but with potentially
2646 let st = object_contents(cx, cty.bounds);
2648 let st = match cty.store {
2652 RegionTraitStore(r, mutbl) => {
2653 st.reference(borrowed_contents(r, mutbl))
2657 // This also prohibits "@once fn" from being copied, which allows it to
2658 // be called. Neither way really makes much sense.
2659 let ot = match cty.onceness {
2660 ast::Once => TC::OwnsAffine,
2661 ast::Many => TC::None,
2667 fn object_contents(cx: &ctxt,
2668 bounds: ExistentialBounds)
2670 // These are the type contents of the (opaque) interior
2671 kind_bounds_to_contents(cx, bounds.builtin_bounds, [])
2674 fn kind_bounds_to_contents(cx: &ctxt,
2675 bounds: BuiltinBounds,
2676 traits: &[Rc<TraitRef>])
2678 let _i = indenter();
2679 let mut tc = TC::All;
2680 each_inherited_builtin_bound(cx, bounds, traits, |bound| {
2681 tc = tc - match bound {
2682 BoundSend => TC::Nonsendable,
2683 BoundSized => TC::Nonsized,
2684 BoundCopy => TC::Noncopy,
2685 BoundSync => TC::Nonsync,
2690 // Iterates over all builtin bounds on the type parameter def, including
2691 // those inherited from traits with builtin-kind-supertraits.
2692 fn each_inherited_builtin_bound(cx: &ctxt,
2693 bounds: BuiltinBounds,
2694 traits: &[Rc<TraitRef>],
2695 f: |BuiltinBound|) {
2696 for bound in bounds.iter() {
2700 each_bound_trait_and_supertraits(cx, traits, |trait_ref| {
2701 let trait_def = lookup_trait_def(cx, trait_ref.def_id);
2702 for bound in trait_def.bounds.builtin_bounds.iter() {
2711 pub fn type_moves_by_default(cx: &ctxt, ty: t) -> bool {
2712 type_contents(cx, ty).moves_by_default(cx)
2715 pub fn is_ffi_safe(cx: &ctxt, ty: t) -> bool {
2716 !type_contents(cx, ty).intersects(TC::ReachesFfiUnsafe)
2719 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
2720 pub fn is_instantiable(cx: &ctxt, r_ty: t) -> bool {
2721 fn type_requires(cx: &ctxt, seen: &mut Vec<DefId>,
2722 r_ty: t, ty: t) -> bool {
2723 debug!("type_requires({}, {})?",
2724 ::util::ppaux::ty_to_string(cx, r_ty),
2725 ::util::ppaux::ty_to_string(cx, ty));
2728 get(r_ty).sty == get(ty).sty ||
2729 subtypes_require(cx, seen, r_ty, ty)
2732 debug!("type_requires({}, {})? {}",
2733 ::util::ppaux::ty_to_string(cx, r_ty),
2734 ::util::ppaux::ty_to_string(cx, ty),
2739 fn subtypes_require(cx: &ctxt, seen: &mut Vec<DefId>,
2740 r_ty: t, ty: t) -> bool {
2741 debug!("subtypes_require({}, {})?",
2742 ::util::ppaux::ty_to_string(cx, r_ty),
2743 ::util::ppaux::ty_to_string(cx, ty));
2745 let r = match get(ty).sty {
2746 // fixed length vectors need special treatment compared to
2747 // normal vectors, since they don't necessarily have the
2748 // possibility to have length zero.
2749 ty_vec(_, Some(0)) => false, // don't need no contents
2750 ty_vec(ty, Some(_)) => type_requires(cx, seen, r_ty, ty),
2765 ty_vec(_, None) => {
2768 ty_box(typ) | ty_uniq(typ) | ty_open(typ) => {
2769 type_requires(cx, seen, r_ty, typ)
2771 ty_rptr(_, ref mt) => {
2772 type_requires(cx, seen, r_ty, mt.ty)
2776 false // unsafe ptrs can always be NULL
2783 ty_struct(ref did, _) if seen.contains(did) => {
2787 ty_struct(did, ref substs) => {
2789 let fields = struct_fields(cx, did, substs);
2790 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
2791 seen.pop().unwrap();
2795 ty_unboxed_closure(did, _) => {
2796 let upvars = unboxed_closure_upvars(cx, did);
2797 upvars.iter().any(|f| type_requires(cx, seen, r_ty, f.ty))
2801 ts.iter().any(|t| type_requires(cx, seen, r_ty, *t))
2804 ty_enum(ref did, _) if seen.contains(did) => {
2808 ty_enum(did, ref substs) => {
2810 let vs = enum_variants(cx, did);
2811 let r = !vs.is_empty() && vs.iter().all(|variant| {
2812 variant.args.iter().any(|aty| {
2813 let sty = aty.subst(cx, substs);
2814 type_requires(cx, seen, r_ty, sty)
2817 seen.pop().unwrap();
2822 debug!("subtypes_require({}, {})? {}",
2823 ::util::ppaux::ty_to_string(cx, r_ty),
2824 ::util::ppaux::ty_to_string(cx, ty),
2830 let mut seen = Vec::new();
2831 !subtypes_require(cx, &mut seen, r_ty, r_ty)
2834 /// Describes whether a type is representable. For types that are not
2835 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
2836 /// distinguish between types that are recursive with themselves and types that
2837 /// contain a different recursive type. These cases can therefore be treated
2838 /// differently when reporting errors.
2839 #[deriving(PartialEq)]
2840 pub enum Representability {
2846 /// Check whether a type is representable. This means it cannot contain unboxed
2847 /// structural recursion. This check is needed for structs and enums.
2848 pub fn is_type_representable(cx: &ctxt, sp: Span, ty: t) -> Representability {
2850 // Iterate until something non-representable is found
2851 fn find_nonrepresentable<It: Iterator<t>>(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2852 mut iter: It) -> Representability {
2854 let r = type_structurally_recursive(cx, sp, seen, ty);
2855 if r != Representable {
2862 // Does the type `ty` directly (without indirection through a pointer)
2863 // contain any types on stack `seen`?
2864 fn type_structurally_recursive(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2865 ty: t) -> Representability {
2866 debug!("type_structurally_recursive: {}",
2867 ::util::ppaux::ty_to_string(cx, ty));
2869 // Compare current type to previously seen types
2872 ty_enum(did, _) => {
2873 for (i, &seen_did) in seen.iter().enumerate() {
2874 if did == seen_did {
2875 return if i == 0 { SelfRecursive }
2876 else { ContainsRecursive }
2883 // Check inner types
2887 find_nonrepresentable(cx, sp, seen, ts.iter().map(|t| *t))
2889 // Fixed-length vectors.
2890 // FIXME(#11924) Behavior undecided for zero-length vectors.
2891 ty_vec(ty, Some(_)) => {
2892 type_structurally_recursive(cx, sp, seen, ty)
2895 // Push struct and enum def-ids onto `seen` before recursing.
2896 ty_struct(did, ref substs) => {
2898 let fields = struct_fields(cx, did, substs);
2899 let r = find_nonrepresentable(cx, sp, seen,
2900 fields.iter().map(|f| f.mt.ty));
2905 ty_enum(did, ref substs) => {
2907 let vs = enum_variants(cx, did);
2909 let mut r = Representable;
2910 for variant in vs.iter() {
2911 let iter = variant.args.iter().map(|aty| {
2912 aty.subst_spanned(cx, substs, Some(sp))
2914 r = find_nonrepresentable(cx, sp, seen, iter);
2916 if r != Representable { break }
2923 ty_unboxed_closure(did, _) => {
2924 let upvars = unboxed_closure_upvars(cx, did);
2925 find_nonrepresentable(cx,
2928 upvars.iter().map(|f| f.ty))
2935 debug!("is_type_representable: {}",
2936 ::util::ppaux::ty_to_string(cx, ty));
2938 // To avoid a stack overflow when checking an enum variant or struct that
2939 // contains a different, structurally recursive type, maintain a stack
2940 // of seen types and check recursion for each of them (issues #3008, #3779).
2941 let mut seen: Vec<DefId> = Vec::new();
2942 type_structurally_recursive(cx, sp, &mut seen, ty)
2945 pub fn type_is_trait(ty: t) -> bool {
2946 type_trait_info(ty).is_some()
2949 pub fn type_trait_info(ty: t) -> Option<&'static TyTrait> {
2951 ty_uniq(ty) | ty_rptr(_, mt { ty, ..}) | ty_ptr(mt { ty, ..}) => match get(ty).sty {
2952 ty_trait(ref t) => Some(&**t),
2955 ty_trait(ref t) => Some(&**t),
2960 pub fn type_is_integral(ty: t) -> bool {
2962 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
2967 pub fn type_is_skolemized(ty: t) -> bool {
2969 ty_infer(SkolemizedTy(_)) => true,
2970 ty_infer(SkolemizedIntTy(_)) => true,
2975 pub fn type_is_uint(ty: t) -> bool {
2977 ty_infer(IntVar(_)) | ty_uint(ast::TyU) => true,
2982 pub fn type_is_char(ty: t) -> bool {
2989 pub fn type_is_bare_fn(ty: t) -> bool {
2991 ty_bare_fn(..) => true,
2996 pub fn type_is_fp(ty: t) -> bool {
2998 ty_infer(FloatVar(_)) | ty_float(_) => true,
3003 pub fn type_is_numeric(ty: t) -> bool {
3004 return type_is_integral(ty) || type_is_fp(ty);
3007 pub fn type_is_signed(ty: t) -> bool {
3014 pub fn type_is_machine(ty: t) -> bool {
3016 ty_int(ast::TyI) | ty_uint(ast::TyU) => false,
3017 ty_int(..) | ty_uint(..) | ty_float(..) => true,
3022 // Is the type's representation size known at compile time?
3023 pub fn type_is_sized(cx: &ctxt, ty: t) -> bool {
3024 type_contents(cx, ty).is_sized(cx)
3027 pub fn lltype_is_sized(cx: &ctxt, ty: t) -> bool {
3030 _ => type_contents(cx, ty).is_sized(cx)
3034 // Return the smallest part of t which is unsized. Fails if t is sized.
3035 // 'Smallest' here means component of the static representation of the type; not
3036 // the size of an object at runtime.
3037 pub fn unsized_part_of_type(cx: &ctxt, ty: t) -> t {
3039 ty_str | ty_trait(..) | ty_vec(..) => ty,
3040 ty_struct(def_id, ref substs) => {
3041 let unsized_fields: Vec<_> = struct_fields(cx, def_id, substs).iter()
3042 .map(|f| f.mt.ty).filter(|ty| !type_is_sized(cx, *ty)).collect();
3043 // Exactly one of the fields must be unsized.
3044 assert!(unsized_fields.len() == 1)
3046 unsized_part_of_type(cx, unsized_fields[0])
3049 assert!(type_is_sized(cx, ty),
3050 "unsized_part_of_type failed even though ty is unsized");
3051 fail!("called unsized_part_of_type with sized ty");
3056 // Whether a type is enum like, that is an enum type with only nullary
3058 pub fn type_is_c_like_enum(cx: &ctxt, ty: t) -> bool {
3060 ty_enum(did, _) => {
3061 let variants = enum_variants(cx, did);
3062 if variants.len() == 0 {
3065 variants.iter().all(|v| v.args.len() == 0)
3072 // Returns the type and mutability of *t.
3074 // The parameter `explicit` indicates if this is an *explicit* dereference.
3075 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
3076 pub fn deref(t: t, explicit: bool) -> Option<mt> {
3078 ty_box(ty) | ty_uniq(ty) => {
3081 mutbl: ast::MutImmutable,
3084 ty_rptr(_, mt) => Some(mt),
3085 ty_ptr(mt) if explicit => Some(mt),
3090 pub fn deref_or_dont(t: t) -> t {
3092 ty_box(ty) | ty_uniq(ty) => {
3095 ty_rptr(_, mt) | ty_ptr(mt) => mt.ty,
3100 pub fn close_type(cx: &ctxt, t: t) -> t {
3102 ty_open(t) => mk_rptr(cx, ReStatic, mt {ty: t, mutbl:ast::MutImmutable}),
3103 _ => cx.sess.bug(format!("Trying to close a non-open type {}",
3104 ty_to_string(cx, t)).as_slice())
3108 pub fn type_content(t: t) -> t {
3110 ty_box(ty) | ty_uniq(ty) => ty,
3111 ty_rptr(_, mt) |ty_ptr(mt) => mt.ty,
3117 // Extract the unsized type in an open type (or just return t if it is not open).
3118 pub fn unopen_type(t: t) -> t {
3125 // Returns the type of t[i]
3126 pub fn index(ty: t) -> Option<t> {
3128 ty_vec(t, _) => Some(t),
3133 // Returns the type of elements contained within an 'array-like' type.
3134 // This is exactly the same as the above, except it supports strings,
3135 // which can't actually be indexed.
3136 pub fn array_element_ty(t: t) -> Option<t> {
3138 ty_vec(t, _) => Some(t),
3139 ty_str => Some(mk_u8()),
3144 pub fn node_id_to_trait_ref(cx: &ctxt, id: ast::NodeId) -> Rc<ty::TraitRef> {
3145 match cx.trait_refs.borrow().find(&id) {
3146 Some(t) => t.clone(),
3147 None => cx.sess.bug(
3148 format!("node_id_to_trait_ref: no trait ref for node `{}`",
3149 cx.map.node_to_string(id)).as_slice())
3153 pub fn try_node_id_to_type(cx: &ctxt, id: ast::NodeId) -> Option<t> {
3154 cx.node_types.borrow().find_copy(&(id as uint))
3157 pub fn node_id_to_type(cx: &ctxt, id: ast::NodeId) -> t {
3158 match try_node_id_to_type(cx, id) {
3160 None => cx.sess.bug(
3161 format!("node_id_to_type: no type for node `{}`",
3162 cx.map.node_to_string(id)).as_slice())
3166 pub fn node_id_to_type_opt(cx: &ctxt, id: ast::NodeId) -> Option<t> {
3167 match cx.node_types.borrow().find(&(id as uint)) {
3168 Some(&t) => Some(t),
3173 pub fn node_id_item_substs(cx: &ctxt, id: ast::NodeId) -> ItemSubsts {
3174 match cx.item_substs.borrow().find(&id) {
3175 None => ItemSubsts::empty(),
3176 Some(ts) => ts.clone(),
3180 pub fn fn_is_variadic(fty: t) -> bool {
3181 match get(fty).sty {
3182 ty_bare_fn(ref f) => f.sig.variadic,
3183 ty_closure(ref f) => f.sig.variadic,
3185 fail!("fn_is_variadic() called on non-fn type: {:?}", s)
3190 pub fn ty_fn_sig(fty: t) -> FnSig {
3191 match get(fty).sty {
3192 ty_bare_fn(ref f) => f.sig.clone(),
3193 ty_closure(ref f) => f.sig.clone(),
3195 fail!("ty_fn_sig() called on non-fn type: {:?}", s)
3200 /// Returns the ABI of the given function.
3201 pub fn ty_fn_abi(fty: t) -> abi::Abi {
3202 match get(fty).sty {
3203 ty_bare_fn(ref f) => f.abi,
3204 ty_closure(ref f) => f.abi,
3205 _ => fail!("ty_fn_abi() called on non-fn type"),
3209 // Type accessors for substructures of types
3210 pub fn ty_fn_args(fty: t) -> Vec<t> {
3211 match get(fty).sty {
3212 ty_bare_fn(ref f) => f.sig.inputs.clone(),
3213 ty_closure(ref f) => f.sig.inputs.clone(),
3215 fail!("ty_fn_args() called on non-fn type: {:?}", s)
3220 pub fn ty_closure_store(fty: t) -> TraitStore {
3221 match get(fty).sty {
3222 ty_closure(ref f) => f.store,
3223 ty_unboxed_closure(..) => {
3224 // Close enough for the purposes of all the callers of this
3225 // function (which is soon to be deprecated anyhow).
3229 fail!("ty_closure_store() called on non-closure type: {:?}", s)
3234 pub fn ty_fn_ret(fty: t) -> t {
3235 match get(fty).sty {
3236 ty_bare_fn(ref f) => f.sig.output,
3237 ty_closure(ref f) => f.sig.output,
3239 fail!("ty_fn_ret() called on non-fn type: {:?}", s)
3244 pub fn is_fn_ty(fty: t) -> bool {
3245 match get(fty).sty {
3246 ty_bare_fn(_) => true,
3247 ty_closure(_) => true,
3252 pub fn ty_region(tcx: &ctxt,
3260 format!("ty_region() invoked on in appropriate ty: {:?}",
3266 pub fn free_region_from_def(free_id: ast::NodeId, def: &RegionParameterDef)
3269 ty::ReFree(ty::FreeRegion { scope_id: free_id,
3270 bound_region: ty::BrNamed(def.def_id,
3274 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
3275 // doesn't provide type parameter substitutions.
3276 pub fn pat_ty(cx: &ctxt, pat: &ast::Pat) -> t {
3277 return node_id_to_type(cx, pat.id);
3281 // Returns the type of an expression as a monotype.
3283 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
3284 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
3285 // auto-ref. The type returned by this function does not consider such
3286 // adjustments. See `expr_ty_adjusted()` instead.
3288 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
3289 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
3290 // instead of "fn(t) -> T with T = int".
3291 pub fn expr_ty(cx: &ctxt, expr: &ast::Expr) -> t {
3292 return node_id_to_type(cx, expr.id);
3295 pub fn expr_ty_opt(cx: &ctxt, expr: &ast::Expr) -> Option<t> {
3296 return node_id_to_type_opt(cx, expr.id);
3299 pub fn expr_ty_adjusted(cx: &ctxt, expr: &ast::Expr) -> t {
3302 * Returns the type of `expr`, considering any `AutoAdjustment`
3303 * entry recorded for that expression.
3305 * It would almost certainly be better to store the adjusted ty in with
3306 * the `AutoAdjustment`, but I opted not to do this because it would
3307 * require serializing and deserializing the type and, although that's not
3308 * hard to do, I just hate that code so much I didn't want to touch it
3309 * unless it was to fix it properly, which seemed a distraction from the
3310 * task at hand! -nmatsakis
3313 adjust_ty(cx, expr.span, expr.id, expr_ty(cx, expr),
3314 cx.adjustments.borrow().find(&expr.id),
3315 |method_call| cx.method_map.borrow().find(&method_call).map(|method| method.ty))
3318 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
3319 match cx.map.find(id) {
3320 Some(ast_map::NodeExpr(e)) => {
3324 cx.sess.bug(format!("Node id {} is not an expr: {:?}",
3329 cx.sess.bug(format!("Node id {} is not present \
3330 in the node map", id).as_slice());
3335 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
3336 match cx.map.find(id) {
3337 Some(ast_map::NodeLocal(pat)) => {
3339 ast::PatIdent(_, ref path1, _) => {
3340 token::get_ident(path1.node)
3344 format!("Variable id {} maps to {:?}, not local",
3351 cx.sess.bug(format!("Variable id {} maps to {:?}, not local",
3358 pub fn adjust_ty(cx: &ctxt,
3360 expr_id: ast::NodeId,
3361 unadjusted_ty: ty::t,
3362 adjustment: Option<&AutoAdjustment>,
3363 method_type: |typeck::MethodCall| -> Option<ty::t>)
3365 /*! See `expr_ty_adjusted` */
3367 match get(unadjusted_ty).sty {
3368 ty_err => return unadjusted_ty,
3372 return match adjustment {
3373 Some(adjustment) => {
3375 AutoAddEnv(store) => {
3376 match ty::get(unadjusted_ty).sty {
3377 ty::ty_bare_fn(ref b) => {
3378 let bounds = ty::ExistentialBounds {
3379 region_bound: ReStatic,
3380 builtin_bounds: all_builtin_bounds(),
3385 ty::ClosureTy {fn_style: b.fn_style,
3386 onceness: ast::Many,
3394 format!("add_env adjustment on non-bare-fn: \
3401 AutoDerefRef(ref adj) => {
3402 let mut adjusted_ty = unadjusted_ty;
3404 if !ty::type_is_error(adjusted_ty) {
3405 for i in range(0, adj.autoderefs) {
3406 let method_call = typeck::MethodCall::autoderef(expr_id, i);
3407 match method_type(method_call) {
3408 Some(method_ty) => {
3409 adjusted_ty = ty_fn_ret(method_ty);
3413 match deref(adjusted_ty, true) {
3414 Some(mt) => { adjusted_ty = mt.ty; }
3418 format!("the {}th autoderef failed: \
3421 ty_to_string(cx, adjusted_ty))
3429 None => adjusted_ty,
3430 Some(ref autoref) => adjust_for_autoref(cx, span, adjusted_ty, autoref)
3435 None => unadjusted_ty
3438 fn adjust_for_autoref(cx: &ctxt,
3441 autoref: &AutoRef) -> ty::t{
3443 AutoPtr(r, m, ref a) => {
3444 let adjusted_ty = match a {
3445 &Some(box ref a) => adjust_for_autoref(cx, span, ty, a),
3454 AutoUnsafe(m, ref a) => {
3455 let adjusted_ty = match a {
3456 &Some(box ref a) => adjust_for_autoref(cx, span, ty, a),
3459 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
3462 AutoUnsize(ref k) => unsize_ty(cx, ty, k, span),
3463 AutoUnsizeUniq(ref k) => ty::mk_uniq(cx, unsize_ty(cx, ty, k, span)),
3468 // Take a sized type and a sizing adjustment and produce an unsized version of
3470 pub fn unsize_ty(cx: &ctxt,
3476 &UnsizeLength(len) => match get(ty).sty {
3477 ty_vec(t, Some(n)) => {
3481 _ => cx.sess.span_bug(span,
3482 format!("UnsizeLength with bad sty: {}",
3483 ty_to_string(cx, ty)).as_slice())
3485 &UnsizeStruct(box ref k, tp_index) => match get(ty).sty {
3486 ty_struct(did, ref substs) => {
3487 let ty_substs = substs.types.get_slice(subst::TypeSpace);
3488 let new_ty = unsize_ty(cx, ty_substs[tp_index], k, span);
3489 let mut unsized_substs = substs.clone();
3490 unsized_substs.types.get_mut_slice(subst::TypeSpace)[tp_index] = new_ty;
3491 mk_struct(cx, did, unsized_substs)
3493 _ => cx.sess.span_bug(span,
3494 format!("UnsizeStruct with bad sty: {}",
3495 ty_to_string(cx, ty)).as_slice())
3497 &UnsizeVtable(TyTrait { def_id, substs: ref substs, bounds }, _) => {
3498 mk_trait(cx, def_id, substs.clone(), bounds)
3504 pub fn map_region(&self, f: |Region| -> Region) -> AutoRef {
3506 ty::AutoPtr(r, m, None) => ty::AutoPtr(f(r), m, None),
3507 ty::AutoPtr(r, m, Some(ref a)) => ty::AutoPtr(f(r), m, Some(box a.map_region(f))),
3508 ty::AutoUnsize(ref k) => ty::AutoUnsize(k.clone()),
3509 ty::AutoUnsizeUniq(ref k) => ty::AutoUnsizeUniq(k.clone()),
3510 ty::AutoUnsafe(m, None) => ty::AutoUnsafe(m, None),
3511 ty::AutoUnsafe(m, Some(ref a)) => ty::AutoUnsafe(m, Some(box a.map_region(f))),
3516 pub fn method_call_type_param_defs<'tcx, T>(typer: &T,
3517 origin: &typeck::MethodOrigin)
3518 -> VecPerParamSpace<TypeParameterDef>
3519 where T: mc::Typer<'tcx> {
3521 typeck::MethodStatic(did) => {
3522 ty::lookup_item_type(typer.tcx(), did).generics.types.clone()
3524 typeck::MethodStaticUnboxedClosure(did) => {
3525 let def_id = typer.unboxed_closures()
3528 .expect("method_call_type_param_defs: didn't \
3529 find unboxed closure")
3531 .trait_did(typer.tcx());
3532 lookup_trait_def(typer.tcx(), def_id).generics.types.clone()
3534 typeck::MethodParam(typeck::MethodParam{
3535 trait_ref: ref trait_ref,
3539 typeck::MethodObject(typeck::MethodObject{
3540 trait_ref: ref trait_ref,
3544 match ty::trait_item(typer.tcx(), trait_ref.def_id, n_mth) {
3545 ty::MethodTraitItem(method) => method.generics.types.clone(),
3551 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> def::Def {
3552 match tcx.def_map.borrow().find(&expr.id) {
3555 tcx.sess.span_bug(expr.span, format!(
3556 "no def-map entry for expr {:?}", expr.id).as_slice());
3561 pub fn expr_is_lval(tcx: &ctxt, e: &ast::Expr) -> bool {
3562 match expr_kind(tcx, e) {
3564 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
3568 /// We categorize expressions into three kinds. The distinction between
3569 /// lvalue/rvalue is fundamental to the language. The distinction between the
3570 /// two kinds of rvalues is an artifact of trans which reflects how we will
3571 /// generate code for that kind of expression. See trans/expr.rs for more
3580 pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
3581 if tcx.method_map.borrow().contains_key(&typeck::MethodCall::expr(expr.id)) {
3582 // Overloaded operations are generally calls, and hence they are
3583 // generated via DPS, but there are a few exceptions:
3584 return match expr.node {
3585 // `a += b` has a unit result.
3586 ast::ExprAssignOp(..) => RvalueStmtExpr,
3588 // the deref method invoked for `*a` always yields an `&T`
3589 ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
3591 // the index method invoked for `a[i]` always yields an `&T`
3592 ast::ExprIndex(..) => LvalueExpr,
3594 // `for` loops are statements
3595 ast::ExprForLoop(..) => RvalueStmtExpr,
3597 // in the general case, result could be any type, use DPS
3603 ast::ExprPath(..) => {
3604 match resolve_expr(tcx, expr) {
3605 def::DefVariant(tid, vid, _) => {
3606 let variant_info = enum_variant_with_id(tcx, tid, vid);
3607 if variant_info.args.len() > 0u {
3616 def::DefStruct(_) => {
3617 match get(expr_ty(tcx, expr)).sty {
3618 ty_bare_fn(..) => RvalueDatumExpr,
3623 // Fn pointers are just scalar values.
3624 def::DefFn(..) | def::DefStaticMethod(..) => RvalueDatumExpr,
3626 // Note: there is actually a good case to be made that
3627 // DefArg's, particularly those of immediate type, ought to
3628 // considered rvalues.
3629 def::DefStatic(..) |
3630 def::DefBinding(..) |
3633 def::DefLocal(..) => LvalueExpr,
3638 format!("uncategorized def for expr {:?}: {:?}",
3645 ast::ExprUnary(ast::UnDeref, _) |
3646 ast::ExprField(..) |
3647 ast::ExprTupField(..) |
3648 ast::ExprIndex(..) => {
3653 ast::ExprMethodCall(..) |
3654 ast::ExprStruct(..) |
3657 ast::ExprMatch(..) |
3658 ast::ExprFnBlock(..) |
3660 ast::ExprUnboxedFn(..) |
3661 ast::ExprBlock(..) |
3662 ast::ExprRepeat(..) |
3663 ast::ExprVec(..) => {
3667 ast::ExprLit(ref lit) if lit_is_str(&**lit) => {
3671 ast::ExprCast(..) => {
3672 match tcx.node_types.borrow().find(&(expr.id as uint)) {
3674 if type_is_trait(t) {
3681 // Technically, it should not happen that the expr is not
3682 // present within the table. However, it DOES happen
3683 // during type check, because the final types from the
3684 // expressions are not yet recorded in the tcx. At that
3685 // time, though, we are only interested in knowing lvalue
3686 // vs rvalue. It would be better to base this decision on
3687 // the AST type in cast node---but (at the time of this
3688 // writing) it's not easy to distinguish casts to traits
3689 // from other casts based on the AST. This should be
3690 // easier in the future, when casts to traits
3691 // would like @Foo, Box<Foo>, or &Foo.
3697 ast::ExprBreak(..) |
3698 ast::ExprAgain(..) |
3700 ast::ExprWhile(..) |
3702 ast::ExprAssign(..) |
3703 ast::ExprInlineAsm(..) |
3704 ast::ExprAssignOp(..) |
3705 ast::ExprForLoop(..) => {
3709 ast::ExprLit(_) | // Note: LitStr is carved out above
3710 ast::ExprUnary(..) |
3711 ast::ExprAddrOf(..) |
3712 ast::ExprBinary(..) => {
3716 ast::ExprBox(ref place, _) => {
3717 // Special case `Box<T>`/`Gc<T>` for now:
3718 let definition = match tcx.def_map.borrow().find(&place.id) {
3720 None => fail!("no def for place"),
3722 let def_id = definition.def_id();
3723 if tcx.lang_items.exchange_heap() == Some(def_id) ||
3724 tcx.lang_items.managed_heap() == Some(def_id) {
3731 ast::ExprParen(ref e) => expr_kind(tcx, &**e),
3733 ast::ExprMac(..) => {
3736 "macro expression remains after expansion");
3741 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
3743 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
3746 ast::StmtMac(..) => fail!("unexpanded macro in trans")
3750 pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
3753 for f in fields.iter() { if f.ident.name == name { return i; } i += 1u; }
3754 tcx.sess.bug(format!(
3755 "no field named `{}` found in the list of fields `{:?}`",
3756 token::get_name(name),
3758 .map(|f| token::get_ident(f.ident).get().to_string())
3759 .collect::<Vec<String>>()).as_slice());
3762 pub fn impl_or_trait_item_idx(id: ast::Ident, trait_items: &[ImplOrTraitItem])
3764 trait_items.iter().position(|m| m.ident() == id)
3767 /// Returns a vector containing the indices of all type parameters that appear
3768 /// in `ty`. The vector may contain duplicates. Probably should be converted
3769 /// to a bitset or some other representation.
3770 pub fn param_tys_in_type(ty: t) -> Vec<ParamTy> {
3771 let mut rslt = Vec::new();
3783 pub fn ty_sort_string(cx: &ctxt, t: t) -> String {
3785 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) |
3786 ty_uint(_) | ty_float(_) | ty_str => {
3787 ::util::ppaux::ty_to_string(cx, t)
3790 ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
3791 ty_box(_) => "Gc-ptr".to_string(),
3792 ty_uniq(_) => "box".to_string(),
3793 ty_vec(_, Some(_)) => "array".to_string(),
3794 ty_vec(_, None) => "unsized array".to_string(),
3795 ty_ptr(_) => "*-ptr".to_string(),
3796 ty_rptr(_, _) => "&-ptr".to_string(),
3797 ty_bare_fn(_) => "extern fn".to_string(),
3798 ty_closure(_) => "fn".to_string(),
3799 ty_trait(ref inner) => {
3800 format!("trait {}", item_path_str(cx, inner.def_id))
3802 ty_struct(id, _) => {
3803 format!("struct {}", item_path_str(cx, id))
3805 ty_unboxed_closure(..) => "closure".to_string(),
3806 ty_tup(_) => "tuple".to_string(),
3807 ty_infer(TyVar(_)) => "inferred type".to_string(),
3808 ty_infer(IntVar(_)) => "integral variable".to_string(),
3809 ty_infer(FloatVar(_)) => "floating-point variable".to_string(),
3810 ty_infer(SkolemizedTy(_)) => "skolemized type".to_string(),
3811 ty_infer(SkolemizedIntTy(_)) => "skolemized integral type".to_string(),
3812 ty_param(ref p) => {
3813 if p.space == subst::SelfSpace {
3816 "type parameter".to_string()
3819 ty_err => "type error".to_string(),
3820 ty_open(_) => "opened DST".to_string(),
3824 pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> String {
3827 * Explains the source of a type err in a short,
3828 * human readable way. This is meant to be placed in
3829 * parentheses after some larger message. You should
3830 * also invoke `note_and_explain_type_err()` afterwards
3831 * to present additional details, particularly when
3832 * it comes to lifetime-related errors. */
3834 fn tstore_to_closure(s: &TraitStore) -> String {
3836 &UniqTraitStore => "proc".to_string(),
3837 &RegionTraitStore(..) => "closure".to_string()
3842 terr_cyclic_ty => "cyclic type of infinite size".to_string(),
3843 terr_mismatch => "types differ".to_string(),
3844 terr_fn_style_mismatch(values) => {
3845 format!("expected {} fn, found {} fn",
3846 values.expected.to_string(),
3847 values.found.to_string())
3849 terr_abi_mismatch(values) => {
3850 format!("expected {} fn, found {} fn",
3851 values.expected.to_string(),
3852 values.found.to_string())
3854 terr_onceness_mismatch(values) => {
3855 format!("expected {} fn, found {} fn",
3856 values.expected.to_string(),
3857 values.found.to_string())
3859 terr_sigil_mismatch(values) => {
3860 format!("expected {}, found {}",
3861 tstore_to_closure(&values.expected),
3862 tstore_to_closure(&values.found))
3864 terr_mutability => "values differ in mutability".to_string(),
3865 terr_box_mutability => {
3866 "boxed values differ in mutability".to_string()
3868 terr_vec_mutability => "vectors differ in mutability".to_string(),
3869 terr_ptr_mutability => "pointers differ in mutability".to_string(),
3870 terr_ref_mutability => "references differ in mutability".to_string(),
3871 terr_ty_param_size(values) => {
3872 format!("expected a type with {} type params, \
3873 found one with {} type params",
3877 terr_tuple_size(values) => {
3878 format!("expected a tuple with {} elements, \
3879 found one with {} elements",
3883 terr_record_size(values) => {
3884 format!("expected a record with {} fields, \
3885 found one with {} fields",
3889 terr_record_mutability => {
3890 "record elements differ in mutability".to_string()
3892 terr_record_fields(values) => {
3893 format!("expected a record with field `{}`, found one \
3895 token::get_ident(values.expected),
3896 token::get_ident(values.found))
3899 "incorrect number of function parameters".to_string()
3901 terr_regions_does_not_outlive(..) => {
3902 "lifetime mismatch".to_string()
3904 terr_regions_not_same(..) => {
3905 "lifetimes are not the same".to_string()
3907 terr_regions_no_overlap(..) => {
3908 "lifetimes do not intersect".to_string()
3910 terr_regions_insufficiently_polymorphic(br, _) => {
3911 format!("expected bound lifetime parameter {}, \
3912 found concrete lifetime",
3913 bound_region_ptr_to_string(cx, br))
3915 terr_regions_overly_polymorphic(br, _) => {
3916 format!("expected concrete lifetime, \
3917 found bound lifetime parameter {}",
3918 bound_region_ptr_to_string(cx, br))
3920 terr_trait_stores_differ(_, ref values) => {
3921 format!("trait storage differs: expected `{}`, found `{}`",
3922 trait_store_to_string(cx, (*values).expected),
3923 trait_store_to_string(cx, (*values).found))
3925 terr_sorts(values) => {
3926 format!("expected {}, found {}",
3927 ty_sort_string(cx, values.expected),
3928 ty_sort_string(cx, values.found))
3930 terr_traits(values) => {
3931 format!("expected trait `{}`, found trait `{}`",
3932 item_path_str(cx, values.expected),
3933 item_path_str(cx, values.found))
3935 terr_builtin_bounds(values) => {
3936 if values.expected.is_empty() {
3937 format!("expected no bounds, found `{}`",
3938 values.found.user_string(cx))
3939 } else if values.found.is_empty() {
3940 format!("expected bounds `{}`, found no bounds",
3941 values.expected.user_string(cx))
3943 format!("expected bounds `{}`, found bounds `{}`",
3944 values.expected.user_string(cx),
3945 values.found.user_string(cx))
3948 terr_integer_as_char => {
3949 "expected an integral type, found `char`".to_string()
3951 terr_int_mismatch(ref values) => {
3952 format!("expected `{}`, found `{}`",
3953 values.expected.to_string(),
3954 values.found.to_string())
3956 terr_float_mismatch(ref values) => {
3957 format!("expected `{}`, found `{}`",
3958 values.expected.to_string(),
3959 values.found.to_string())
3961 terr_variadic_mismatch(ref values) => {
3962 format!("expected {} fn, found {} function",
3963 if values.expected { "variadic" } else { "non-variadic" },
3964 if values.found { "variadic" } else { "non-variadic" })
3969 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
3971 terr_regions_does_not_outlive(subregion, superregion) => {
3972 note_and_explain_region(cx, "", subregion, "...");
3973 note_and_explain_region(cx, "...does not necessarily outlive ",
3976 terr_regions_not_same(region1, region2) => {
3977 note_and_explain_region(cx, "", region1, "...");
3978 note_and_explain_region(cx, "...is not the same lifetime as ",
3981 terr_regions_no_overlap(region1, region2) => {
3982 note_and_explain_region(cx, "", region1, "...");
3983 note_and_explain_region(cx, "...does not overlap ",
3986 terr_regions_insufficiently_polymorphic(_, conc_region) => {
3987 note_and_explain_region(cx,
3988 "concrete lifetime that was found is ",
3991 terr_regions_overly_polymorphic(_, conc_region) => {
3992 note_and_explain_region(cx,
3993 "expected concrete lifetime is ",
4000 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
4001 cx.provided_method_sources.borrow().find(&id).map(|x| *x)
4004 pub fn provided_trait_methods(cx: &ctxt, id: ast::DefId) -> Vec<Rc<Method>> {
4006 match cx.map.find(id.node) {
4007 Some(ast_map::NodeItem(item)) => {
4009 ItemTrait(_, _, _, ref ms) => {
4010 ms.iter().filter_map(|m| match *m {
4011 ast::RequiredMethod(_) => None,
4012 ast::ProvidedMethod(ref m) => {
4013 match impl_or_trait_item(cx,
4014 ast_util::local_def(m.id)) {
4015 MethodTraitItem(m) => Some(m),
4021 cx.sess.bug(format!("provided_trait_methods: `{}` is \
4028 cx.sess.bug(format!("provided_trait_methods: `{}` is not a \
4034 csearch::get_provided_trait_methods(cx, id)
4038 fn lookup_locally_or_in_crate_store<V:Clone>(
4041 map: &mut DefIdMap<V>,
4042 load_external: || -> V) -> V {
4044 * Helper for looking things up in the various maps
4045 * that are populated during typeck::collect (e.g.,
4046 * `cx.impl_or_trait_items`, `cx.tcache`, etc). All of these share
4047 * the pattern that if the id is local, it should have
4048 * been loaded into the map by the `typeck::collect` phase.
4049 * If the def-id is external, then we have to go consult
4050 * the crate loading code (and cache the result for the future).
4053 match map.find_copy(&def_id) {
4054 Some(v) => { return v; }
4058 if def_id.krate == ast::LOCAL_CRATE {
4059 fail!("No def'n found for {:?} in tcx.{}", def_id, descr);
4061 let v = load_external();
4062 map.insert(def_id, v.clone());
4066 pub fn trait_item(cx: &ctxt, trait_did: ast::DefId, idx: uint)
4067 -> ImplOrTraitItem {
4068 let method_def_id = ty::trait_item_def_ids(cx, trait_did).get(idx)
4070 impl_or_trait_item(cx, method_def_id)
4073 pub fn trait_items(cx: &ctxt, trait_did: ast::DefId)
4074 -> Rc<Vec<ImplOrTraitItem>> {
4075 let mut trait_items = cx.trait_items_cache.borrow_mut();
4076 match trait_items.find_copy(&trait_did) {
4077 Some(trait_items) => trait_items,
4079 let def_ids = ty::trait_item_def_ids(cx, trait_did);
4080 let items: Rc<Vec<ImplOrTraitItem>> =
4081 Rc::new(def_ids.iter()
4082 .map(|d| impl_or_trait_item(cx, d.def_id()))
4084 trait_items.insert(trait_did, items.clone());
4090 pub fn impl_or_trait_item(cx: &ctxt, id: ast::DefId) -> ImplOrTraitItem {
4091 lookup_locally_or_in_crate_store("impl_or_trait_items",
4093 &mut *cx.impl_or_trait_items
4096 csearch::get_impl_or_trait_item(cx, id)
4100 pub fn trait_item_def_ids(cx: &ctxt, id: ast::DefId)
4101 -> Rc<Vec<ImplOrTraitItemId>> {
4102 lookup_locally_or_in_crate_store("trait_item_def_ids",
4104 &mut *cx.trait_item_def_ids.borrow_mut(),
4106 Rc::new(csearch::get_trait_item_def_ids(&cx.sess.cstore, id))
4110 pub fn impl_trait_ref(cx: &ctxt, id: ast::DefId) -> Option<Rc<TraitRef>> {
4111 match cx.impl_trait_cache.borrow().find(&id) {
4112 Some(ret) => { return ret.clone(); }
4116 let ret = if id.krate == ast::LOCAL_CRATE {
4117 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
4118 match cx.map.find(id.node) {
4119 Some(ast_map::NodeItem(item)) => {
4121 ast::ItemImpl(_, ref opt_trait, _, _) => {
4124 Some(ty::node_id_to_trait_ref(cx, t.ref_id))
4135 csearch::get_impl_trait(cx, id)
4138 cx.impl_trait_cache.borrow_mut().insert(id, ret.clone());
4142 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
4143 let def = *tcx.def_map.borrow()
4145 .expect("no def-map entry for trait");
4149 pub fn try_add_builtin_trait(
4151 trait_def_id: ast::DefId,
4152 builtin_bounds: &mut EnumSet<BuiltinBound>)
4155 //! Checks whether `trait_ref` refers to one of the builtin
4156 //! traits, like `Send`, and adds the corresponding
4157 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
4158 //! is a builtin trait.
4160 match tcx.lang_items.to_builtin_kind(trait_def_id) {
4161 Some(bound) => { builtin_bounds.add(bound); true }
4166 pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> {
4168 ty_trait(box TyTrait { def_id: id, .. }) |
4171 ty_unboxed_closure(id, _) => Some(id),
4178 pub struct VariantInfo {
4180 pub arg_names: Option<Vec<ast::Ident> >,
4182 pub name: ast::Ident,
4190 /// Creates a new VariantInfo from the corresponding ast representation.
4192 /// Does not do any caching of the value in the type context.
4193 pub fn from_ast_variant(cx: &ctxt,
4194 ast_variant: &ast::Variant,
4195 discriminant: Disr) -> VariantInfo {
4196 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
4198 match ast_variant.node.kind {
4199 ast::TupleVariantKind(ref args) => {
4200 let arg_tys = if args.len() > 0 {
4201 ty_fn_args(ctor_ty).iter().map(|a| *a).collect()
4206 return VariantInfo {
4210 name: ast_variant.node.name,
4211 id: ast_util::local_def(ast_variant.node.id),
4212 disr_val: discriminant,
4213 vis: ast_variant.node.vis
4216 ast::StructVariantKind(ref struct_def) => {
4218 let fields: &[StructField] = struct_def.fields.as_slice();
4220 assert!(fields.len() > 0);
4222 let arg_tys = ty_fn_args(ctor_ty).iter().map(|a| *a).collect();
4223 let arg_names = fields.iter().map(|field| {
4224 match field.node.kind {
4225 NamedField(ident, _) => ident,
4226 UnnamedField(..) => cx.sess.bug(
4227 "enum_variants: all fields in struct must have a name")
4231 return VariantInfo {
4233 arg_names: Some(arg_names),
4235 name: ast_variant.node.name,
4236 id: ast_util::local_def(ast_variant.node.id),
4237 disr_val: discriminant,
4238 vis: ast_variant.node.vis
4245 pub fn substd_enum_variants(cx: &ctxt,
4248 -> Vec<Rc<VariantInfo>> {
4249 enum_variants(cx, id).iter().map(|variant_info| {
4250 let substd_args = variant_info.args.iter()
4251 .map(|aty| aty.subst(cx, substs)).collect::<Vec<_>>();
4253 let substd_ctor_ty = variant_info.ctor_ty.subst(cx, substs);
4255 Rc::new(VariantInfo {
4257 ctor_ty: substd_ctor_ty,
4258 ..(**variant_info).clone()
4263 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
4264 with_path(cx, id, |path| ast_map::path_to_string(path)).to_string()
4269 TraitDtor(DefId, bool)
4273 pub fn is_present(&self) -> bool {
4275 TraitDtor(..) => true,
4280 pub fn has_drop_flag(&self) -> bool {
4283 &TraitDtor(_, flag) => flag
4288 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
4289 Otherwise return none. */
4290 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
4291 match cx.destructor_for_type.borrow().find(&struct_id) {
4292 Some(&method_def_id) => {
4293 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
4295 TraitDtor(method_def_id, flag)
4301 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
4302 ty_dtor(cx, struct_id).is_present()
4305 pub fn with_path<T>(cx: &ctxt, id: ast::DefId, f: |ast_map::PathElems| -> T) -> T {
4306 if id.krate == ast::LOCAL_CRATE {
4307 cx.map.with_path(id.node, f)
4309 f(ast_map::Values(csearch::get_item_path(cx, id).iter()).chain(None))
4313 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
4314 enum_variants(cx, id).len() == 1
4317 pub fn type_is_empty(cx: &ctxt, t: t) -> bool {
4318 match ty::get(t).sty {
4319 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
4324 pub fn enum_variants(cx: &ctxt, id: ast::DefId) -> Rc<Vec<Rc<VariantInfo>>> {
4325 match cx.enum_var_cache.borrow().find(&id) {
4326 Some(variants) => return variants.clone(),
4327 _ => { /* fallthrough */ }
4330 let result = if ast::LOCAL_CRATE != id.krate {
4331 Rc::new(csearch::get_enum_variants(cx, id))
4334 Although both this code and check_enum_variants in typeck/check
4335 call eval_const_expr, it should never get called twice for the same
4336 expr, since check_enum_variants also updates the enum_var_cache
4338 match cx.map.get(id.node) {
4339 ast_map::NodeItem(ref item) => {
4341 ast::ItemEnum(ref enum_definition, _) => {
4342 let mut last_discriminant: Option<Disr> = None;
4343 Rc::new(enum_definition.variants.iter().map(|variant| {
4345 let mut discriminant = match last_discriminant {
4346 Some(val) => val + 1,
4347 None => INITIAL_DISCRIMINANT_VALUE
4350 match variant.node.disr_expr {
4351 Some(ref e) => match const_eval::eval_const_expr_partial(cx, &**e) {
4352 Ok(const_eval::const_int(val)) => {
4353 discriminant = val as Disr
4355 Ok(const_eval::const_uint(val)) => {
4356 discriminant = val as Disr
4361 "expected signed integer constant");
4366 format!("expected constant: {}",
4373 last_discriminant = Some(discriminant);
4374 Rc::new(VariantInfo::from_ast_variant(cx, &**variant,
4379 cx.sess.bug("enum_variants: id not bound to an enum")
4383 _ => cx.sess.bug("enum_variants: id not bound to an enum")
4387 cx.enum_var_cache.borrow_mut().insert(id, result.clone());
4392 // Returns information about the enum variant with the given ID:
4393 pub fn enum_variant_with_id(cx: &ctxt,
4394 enum_id: ast::DefId,
4395 variant_id: ast::DefId)
4396 -> Rc<VariantInfo> {
4397 enum_variants(cx, enum_id).iter()
4398 .find(|variant| variant.id == variant_id)
4399 .expect("enum_variant_with_id(): no variant exists with that ID")
4404 // If the given item is in an external crate, looks up its type and adds it to
4405 // the type cache. Returns the type parameters and type.
4406 pub fn lookup_item_type(cx: &ctxt,
4409 lookup_locally_or_in_crate_store(
4410 "tcache", did, &mut *cx.tcache.borrow_mut(),
4411 || csearch::get_type(cx, did))
4414 /// Given the did of a trait, returns its canonical trait ref.
4415 pub fn lookup_trait_def(cx: &ctxt, did: ast::DefId) -> Rc<ty::TraitDef> {
4416 let mut trait_defs = cx.trait_defs.borrow_mut();
4417 match trait_defs.find_copy(&did) {
4418 Some(trait_def) => {
4419 // The item is in this crate. The caller should have added it to the
4420 // type cache already
4424 assert!(did.krate != ast::LOCAL_CRATE);
4425 let trait_def = Rc::new(csearch::get_trait_def(cx, did));
4426 trait_defs.insert(did, trait_def.clone());
4432 /// Given a reference to a trait, returns the bounds declared on the
4433 /// trait, with appropriate substitutions applied.
4434 pub fn bounds_for_trait_ref(tcx: &ctxt,
4435 trait_ref: &TraitRef)
4438 let trait_def = lookup_trait_def(tcx, trait_ref.def_id);
4439 debug!("bounds_for_trait_ref(trait_def={}, trait_ref={})",
4440 trait_def.repr(tcx), trait_ref.repr(tcx));
4441 trait_def.bounds.subst(tcx, &trait_ref.substs)
4444 /// Iterate over attributes of a definition.
4445 // (This should really be an iterator, but that would require csearch and
4446 // decoder to use iterators instead of higher-order functions.)
4447 pub fn each_attr(tcx: &ctxt, did: DefId, f: |&ast::Attribute| -> bool) -> bool {
4449 let item = tcx.map.expect_item(did.node);
4450 item.attrs.iter().all(|attr| f(attr))
4452 info!("getting foreign attrs");
4453 let mut cont = true;
4454 csearch::get_item_attrs(&tcx.sess.cstore, did, |attrs| {
4456 cont = attrs.iter().all(|attr| f(attr));
4464 /// Determine whether an item is annotated with an attribute
4465 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
4466 let mut found = false;
4467 each_attr(tcx, did, |item| {
4468 if item.check_name(attr) {
4478 /// Determine whether an item is annotated with `#[repr(packed)]`
4479 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
4480 lookup_repr_hints(tcx, did).contains(&attr::ReprPacked)
4483 /// Determine whether an item is annotated with `#[simd]`
4484 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
4485 has_attr(tcx, did, "simd")
4488 /// Obtain the representation annotation for a struct definition.
4489 pub fn lookup_repr_hints(tcx: &ctxt, did: DefId) -> Vec<attr::ReprAttr> {
4490 let mut acc = Vec::new();
4492 ty::each_attr(tcx, did, |meta| {
4493 acc.extend(attr::find_repr_attrs(tcx.sess.diagnostic(), meta).into_iter());
4500 // Look up a field ID, whether or not it's local
4501 // Takes a list of type substs in case the struct is generic
4502 pub fn lookup_field_type(tcx: &ctxt,
4507 let t = if id.krate == ast::LOCAL_CRATE {
4508 node_id_to_type(tcx, id.node)
4510 let mut tcache = tcx.tcache.borrow_mut();
4511 let pty = tcache.find_or_insert_with(id, |_| {
4512 csearch::get_field_type(tcx, struct_id, id)
4516 t.subst(tcx, substs)
4519 // Lookup all ancestor structs of a struct indicated by did. That is the reflexive,
4520 // transitive closure of doing a single lookup in cx.superstructs.
4521 fn each_super_struct(cx: &ctxt, mut did: ast::DefId, f: |ast::DefId|) {
4522 let superstructs = cx.superstructs.borrow();
4526 match superstructs.find(&did) {
4527 Some(&Some(def_id)) => {
4530 Some(&None) => break,
4533 format!("ID not mapped to super-struct: {}",
4534 cx.map.node_to_string(did.node)).as_slice());
4540 // Look up the list of field names and IDs for a given struct.
4541 // Fails if the id is not bound to a struct.
4542 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
4543 if did.krate == ast::LOCAL_CRATE {
4544 // We store the fields which are syntactically in each struct in cx. So
4545 // we have to walk the inheritance chain of the struct to get all the
4546 // structs (explicit and inherited) for a struct. If this is expensive
4547 // we could cache the whole list of fields here.
4548 let struct_fields = cx.struct_fields.borrow();
4549 let mut results: SmallVector<&[field_ty]> = SmallVector::zero();
4550 each_super_struct(cx, did, |s| {
4551 match struct_fields.find(&s) {
4552 Some(fields) => results.push(fields.as_slice()),
4555 format!("ID not mapped to struct fields: {}",
4556 cx.map.node_to_string(did.node)).as_slice());
4561 let len = results.as_slice().iter().map(|x| x.len()).sum();
4562 let mut result: Vec<field_ty> = Vec::with_capacity(len);
4563 result.extend(results.as_slice().iter().flat_map(|rs| rs.iter().map(|f| f.clone())));
4564 assert!(result.len() == len);
4567 csearch::get_struct_fields(&cx.sess.cstore, did)
4571 pub fn is_tuple_struct(cx: &ctxt, did: ast::DefId) -> bool {
4572 let fields = lookup_struct_fields(cx, did);
4573 !fields.is_empty() && fields.iter().all(|f| f.name == token::special_names::unnamed_field)
4576 pub fn lookup_struct_field(cx: &ctxt,
4578 field_id: ast::DefId)
4580 let r = lookup_struct_fields(cx, parent);
4581 match r.iter().find(|f| f.id.node == field_id.node) {
4582 Some(t) => t.clone(),
4583 None => cx.sess.bug("struct ID not found in parent's fields")
4587 // Returns a list of fields corresponding to the struct's items. trans uses
4588 // this. Takes a list of substs with which to instantiate field types.
4589 pub fn struct_fields(cx: &ctxt, did: ast::DefId, substs: &Substs)
4591 lookup_struct_fields(cx, did).iter().map(|f| {
4593 // FIXME #6993: change type of field to Name and get rid of new()
4594 ident: ast::Ident::new(f.name),
4596 ty: lookup_field_type(cx, did, f.id, substs),
4603 // Returns a list of fields corresponding to the tuple's items. trans uses
4605 pub fn tup_fields(v: &[t]) -> Vec<field> {
4606 v.iter().enumerate().map(|(i, &f)| {
4608 // FIXME #6993: change type of field to Name and get rid of new()
4609 ident: ast::Ident::new(token::intern(i.to_string().as_slice())),
4618 pub struct UnboxedClosureUpvar {
4624 // Returns a list of `UnboxedClosureUpvar`s for each upvar.
4625 pub fn unboxed_closure_upvars(tcx: &ctxt, closure_id: ast::DefId)
4626 -> Vec<UnboxedClosureUpvar> {
4627 if closure_id.krate == ast::LOCAL_CRATE {
4628 match tcx.freevars.borrow().find(&closure_id.node) {
4629 None => tcx.sess.bug("no freevars for unboxed closure?!"),
4630 Some(ref freevars) => {
4631 freevars.iter().map(|freevar| {
4632 let freevar_def_id = freevar.def.def_id();
4633 UnboxedClosureUpvar {
4636 ty: node_id_to_type(tcx, freevar_def_id.node),
4642 tcx.sess.bug("unimplemented cross-crate closure upvars")
4646 pub fn is_binopable(cx: &ctxt, ty: t, op: ast::BinOp) -> bool {
4647 static tycat_other: int = 0;
4648 static tycat_bool: int = 1;
4649 static tycat_char: int = 2;
4650 static tycat_int: int = 3;
4651 static tycat_float: int = 4;
4652 static tycat_bot: int = 5;
4653 static tycat_raw_ptr: int = 6;
4655 static opcat_add: int = 0;
4656 static opcat_sub: int = 1;
4657 static opcat_mult: int = 2;
4658 static opcat_shift: int = 3;
4659 static opcat_rel: int = 4;
4660 static opcat_eq: int = 5;
4661 static opcat_bit: int = 6;
4662 static opcat_logic: int = 7;
4663 static opcat_mod: int = 8;
4665 fn opcat(op: ast::BinOp) -> int {
4667 ast::BiAdd => opcat_add,
4668 ast::BiSub => opcat_sub,
4669 ast::BiMul => opcat_mult,
4670 ast::BiDiv => opcat_mult,
4671 ast::BiRem => opcat_mod,
4672 ast::BiAnd => opcat_logic,
4673 ast::BiOr => opcat_logic,
4674 ast::BiBitXor => opcat_bit,
4675 ast::BiBitAnd => opcat_bit,
4676 ast::BiBitOr => opcat_bit,
4677 ast::BiShl => opcat_shift,
4678 ast::BiShr => opcat_shift,
4679 ast::BiEq => opcat_eq,
4680 ast::BiNe => opcat_eq,
4681 ast::BiLt => opcat_rel,
4682 ast::BiLe => opcat_rel,
4683 ast::BiGe => opcat_rel,
4684 ast::BiGt => opcat_rel
4688 fn tycat(cx: &ctxt, ty: t) -> int {
4689 if type_is_simd(cx, ty) {
4690 return tycat(cx, simd_type(cx, ty))
4693 ty_char => tycat_char,
4694 ty_bool => tycat_bool,
4695 ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
4696 ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
4697 ty_bot => tycat_bot,
4698 ty_ptr(_) => tycat_raw_ptr,
4703 static t: bool = true;
4704 static f: bool = false;
4707 // +, -, *, shift, rel, ==, bit, logic, mod
4708 /*other*/ [f, f, f, f, f, f, f, f, f],
4709 /*bool*/ [f, f, f, f, t, t, t, t, f],
4710 /*char*/ [f, f, f, f, t, t, f, f, f],
4711 /*int*/ [t, t, t, t, t, t, t, f, t],
4712 /*float*/ [t, t, t, f, t, t, f, f, f],
4713 /*bot*/ [t, t, t, t, t, t, t, t, t],
4714 /*raw ptr*/ [f, f, f, f, t, t, f, f, f]];
4716 return tbl[tycat(cx, ty) as uint ][opcat(op) as uint];
4719 /// Returns an equivalent type with all the typedefs and self regions removed.
4720 pub fn normalize_ty(cx: &ctxt, t: t) -> t {
4721 let u = TypeNormalizer(cx).fold_ty(t);
4724 struct TypeNormalizer<'a, 'tcx: 'a>(&'a ctxt<'tcx>);
4726 impl<'a, 'tcx> TypeFolder<'tcx> for TypeNormalizer<'a, 'tcx> {
4727 fn tcx(&self) -> &ctxt<'tcx> { let TypeNormalizer(c) = *self; c }
4729 fn fold_ty(&mut self, t: ty::t) -> ty::t {
4730 match self.tcx().normalized_cache.borrow().find_copy(&t) {
4735 let t_norm = ty_fold::super_fold_ty(self, t);
4736 self.tcx().normalized_cache.borrow_mut().insert(t, t_norm);
4740 fn fold_region(&mut self, _: ty::Region) -> ty::Region {
4744 fn fold_substs(&mut self,
4745 substs: &subst::Substs)
4747 subst::Substs { regions: subst::ErasedRegions,
4748 types: substs.types.fold_with(self) }
4751 fn fold_sig(&mut self,
4754 // The binder-id is only relevant to bound regions, which
4755 // are erased at trans time.
4757 binder_id: ast::DUMMY_NODE_ID,
4758 inputs: sig.inputs.fold_with(self),
4759 output: sig.output.fold_with(self),
4760 variadic: sig.variadic,
4766 // Returns the repeat count for a repeating vector expression.
4767 pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> uint {
4768 match const_eval::eval_const_expr_partial(tcx, count_expr) {
4769 Ok(ref const_val) => match *const_val {
4770 const_eval::const_int(count) => if count < 0 {
4771 tcx.sess.span_err(count_expr.span,
4772 "expected positive integer for \
4773 repeat count, found negative integer");
4778 const_eval::const_uint(count) => count as uint,
4779 const_eval::const_float(count) => {
4780 tcx.sess.span_err(count_expr.span,
4781 "expected positive integer for \
4782 repeat count, found float");
4785 const_eval::const_str(_) => {
4786 tcx.sess.span_err(count_expr.span,
4787 "expected positive integer for \
4788 repeat count, found string");
4791 const_eval::const_bool(_) => {
4792 tcx.sess.span_err(count_expr.span,
4793 "expected positive integer for \
4794 repeat count, found boolean");
4797 const_eval::const_binary(_) => {
4798 tcx.sess.span_err(count_expr.span,
4799 "expected positive integer for \
4800 repeat count, found binary array");
4803 const_eval::const_nil => {
4804 tcx.sess.span_err(count_expr.span,
4805 "expected positive integer for \
4806 repeat count, found ()");
4811 tcx.sess.span_err(count_expr.span,
4812 "expected constant integer for repeat count, \
4819 // Iterate over a type parameter's bounded traits and any supertraits
4820 // of those traits, ignoring kinds.
4821 // Here, the supertraits are the transitive closure of the supertrait
4822 // relation on the supertraits from each bounded trait's constraint
4824 pub fn each_bound_trait_and_supertraits(tcx: &ctxt,
4825 bounds: &[Rc<TraitRef>],
4826 f: |Rc<TraitRef>| -> bool)
4829 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
4830 if !f(bound_trait_ref) {
4837 pub fn required_region_bounds(tcx: &ctxt,
4838 region_bounds: &[ty::Region],
4839 builtin_bounds: BuiltinBounds,
4840 trait_bounds: &[Rc<TraitRef>])
4844 * Given a type which must meet the builtin bounds and trait
4845 * bounds, returns a set of lifetimes which the type must outlive.
4847 * Requires that trait definitions have been processed.
4850 let mut all_bounds = Vec::new();
4852 debug!("required_region_bounds(builtin_bounds={}, trait_bounds={})",
4853 builtin_bounds.repr(tcx),
4854 trait_bounds.repr(tcx));
4856 all_bounds.push_all(region_bounds);
4858 push_region_bounds([],
4862 debug!("from builtin bounds: all_bounds={}", all_bounds.repr(tcx));
4864 each_bound_trait_and_supertraits(
4868 let bounds = ty::bounds_for_trait_ref(tcx, &*trait_ref);
4869 push_region_bounds(bounds.region_bounds.as_slice(),
4870 bounds.builtin_bounds,
4872 debug!("from {}: bounds={} all_bounds={}",
4873 trait_ref.repr(tcx),
4875 all_bounds.repr(tcx));
4881 fn push_region_bounds(region_bounds: &[ty::Region],
4882 builtin_bounds: ty::BuiltinBounds,
4883 all_bounds: &mut Vec<ty::Region>) {
4884 all_bounds.push_all(region_bounds.as_slice());
4886 if builtin_bounds.contains_elem(ty::BoundSend) {
4887 all_bounds.push(ty::ReStatic);
4892 pub fn get_tydesc_ty(tcx: &ctxt) -> Result<t, String> {
4893 tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
4894 tcx.intrinsic_defs.borrow().find_copy(&tydesc_lang_item)
4895 .expect("Failed to resolve TyDesc")
4899 pub fn get_opaque_ty(tcx: &ctxt) -> Result<t, String> {
4900 tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| {
4901 tcx.intrinsic_defs.borrow().find_copy(&opaque_lang_item)
4902 .expect("Failed to resolve Opaque")
4906 pub fn visitor_object_ty(tcx: &ctxt,
4907 ptr_region: ty::Region,
4908 trait_region: ty::Region)
4909 -> Result<(Rc<TraitRef>, t), String>
4911 let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) {
4913 Err(s) => { return Err(s); }
4915 let substs = Substs::empty();
4916 let trait_ref = Rc::new(TraitRef { def_id: trait_lang_item, substs: substs });
4917 Ok((trait_ref.clone(),
4918 mk_rptr(tcx, ptr_region,
4919 mt {mutbl: ast::MutMutable,
4922 trait_ref.substs.clone(),
4923 ty::region_existential_bound(trait_region))})))
4926 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> Rc<ItemVariances> {
4927 lookup_locally_or_in_crate_store(
4928 "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
4929 || Rc::new(csearch::get_item_variances(&tcx.sess.cstore, item_id)))
4932 /// Records a trait-to-implementation mapping.
4933 pub fn record_trait_implementation(tcx: &ctxt,
4934 trait_def_id: DefId,
4935 impl_def_id: DefId) {
4936 match tcx.trait_impls.borrow().find(&trait_def_id) {
4937 Some(impls_for_trait) => {
4938 impls_for_trait.borrow_mut().push(impl_def_id);
4943 tcx.trait_impls.borrow_mut().insert(trait_def_id, Rc::new(RefCell::new(vec!(impl_def_id))));
4946 /// Populates the type context with all the implementations for the given type
4948 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
4949 type_id: ast::DefId) {
4950 if type_id.krate == LOCAL_CRATE {
4953 if tcx.populated_external_types.borrow().contains(&type_id) {
4957 let mut inherent_impls = Vec::new();
4958 csearch::each_implementation_for_type(&tcx.sess.cstore, type_id,
4960 let impl_items = csearch::get_impl_items(&tcx.sess.cstore,
4963 // Record the trait->implementation mappings, if applicable.
4964 let associated_traits = csearch::get_impl_trait(tcx, impl_def_id);
4965 for trait_ref in associated_traits.iter() {
4966 record_trait_implementation(tcx, trait_ref.def_id, impl_def_id);
4969 // For any methods that use a default implementation, add them to
4970 // the map. This is a bit unfortunate.
4971 for impl_item_def_id in impl_items.iter() {
4972 let method_def_id = impl_item_def_id.def_id();
4973 match impl_or_trait_item(tcx, method_def_id) {
4974 MethodTraitItem(method) => {
4975 for &source in method.provided_source.iter() {
4976 tcx.provided_method_sources
4978 .insert(method_def_id, source);
4984 // Store the implementation info.
4985 tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
4987 // If this is an inherent implementation, record it.
4988 if associated_traits.is_none() {
4989 inherent_impls.push(impl_def_id);
4993 tcx.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
4994 tcx.populated_external_types.borrow_mut().insert(type_id);
4997 /// Populates the type context with all the implementations for the given
4998 /// trait if necessary.
4999 pub fn populate_implementations_for_trait_if_necessary(
5001 trait_id: ast::DefId) {
5002 if trait_id.krate == LOCAL_CRATE {
5005 if tcx.populated_external_traits.borrow().contains(&trait_id) {
5009 csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id,
5010 |implementation_def_id| {
5011 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, implementation_def_id);
5013 // Record the trait->implementation mapping.
5014 record_trait_implementation(tcx, trait_id, implementation_def_id);
5016 // For any methods that use a default implementation, add them to
5017 // the map. This is a bit unfortunate.
5018 for impl_item_def_id in impl_items.iter() {
5019 let method_def_id = impl_item_def_id.def_id();
5020 match impl_or_trait_item(tcx, method_def_id) {
5021 MethodTraitItem(method) => {
5022 for &source in method.provided_source.iter() {
5023 tcx.provided_method_sources
5025 .insert(method_def_id, source);
5031 // Store the implementation info.
5032 tcx.impl_items.borrow_mut().insert(implementation_def_id, impl_items);
5035 tcx.populated_external_traits.borrow_mut().insert(trait_id);
5038 /// Given the def_id of an impl, return the def_id of the trait it implements.
5039 /// If it implements no trait, return `None`.
5040 pub fn trait_id_of_impl(tcx: &ctxt,
5041 def_id: ast::DefId) -> Option<ast::DefId> {
5042 let node = match tcx.map.find(def_id.node) {
5047 ast_map::NodeItem(item) => {
5049 ast::ItemImpl(_, Some(ref trait_ref), _, _) => {
5050 Some(node_id_to_trait_ref(tcx, trait_ref.ref_id).def_id)
5059 /// If the given def ID describes a method belonging to an impl, return the
5060 /// ID of the impl that the method belongs to. Otherwise, return `None`.
5061 pub fn impl_of_method(tcx: &ctxt, def_id: ast::DefId)
5062 -> Option<ast::DefId> {
5063 if def_id.krate != LOCAL_CRATE {
5064 return match csearch::get_impl_or_trait_item(tcx,
5065 def_id).container() {
5066 TraitContainer(_) => None,
5067 ImplContainer(def_id) => Some(def_id),
5070 match tcx.impl_or_trait_items.borrow().find_copy(&def_id) {
5071 Some(trait_item) => {
5072 match trait_item.container() {
5073 TraitContainer(_) => None,
5074 ImplContainer(def_id) => Some(def_id),
5081 /// If the given def ID describes an item belonging to a trait (either a
5082 /// default method or an implementation of a trait method), return the ID of
5083 /// the trait that the method belongs to. Otherwise, return `None`.
5084 pub fn trait_of_item(tcx: &ctxt, def_id: ast::DefId) -> Option<ast::DefId> {
5085 if def_id.krate != LOCAL_CRATE {
5086 return csearch::get_trait_of_item(&tcx.sess.cstore, def_id, tcx);
5088 match tcx.impl_or_trait_items.borrow().find_copy(&def_id) {
5089 Some(impl_or_trait_item) => {
5090 match impl_or_trait_item.container() {
5091 TraitContainer(def_id) => Some(def_id),
5092 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
5099 /// If the given def ID describes an item belonging to a trait, (either a
5100 /// default method or an implementation of a trait method), return the ID of
5101 /// the method inside trait definition (this means that if the given def ID
5102 /// is already that of the original trait method, then the return value is
5104 /// Otherwise, return `None`.
5105 pub fn trait_item_of_item(tcx: &ctxt, def_id: ast::DefId)
5106 -> Option<ImplOrTraitItemId> {
5107 let impl_item = match tcx.impl_or_trait_items.borrow().find(&def_id) {
5108 Some(m) => m.clone(),
5109 None => return None,
5111 let name = match impl_item {
5112 MethodTraitItem(method) => method.ident.name,
5114 match trait_of_item(tcx, def_id) {
5115 Some(trait_did) => {
5116 let trait_items = ty::trait_items(tcx, trait_did);
5118 .position(|m| m.ident().name == name)
5119 .map(|idx| ty::trait_item(tcx, trait_did, idx).id())
5125 /// Creates a hash of the type `t` which will be the same no matter what crate
5126 /// context it's calculated within. This is used by the `type_id` intrinsic.
5127 pub fn hash_crate_independent(tcx: &ctxt, t: t, svh: &Svh) -> u64 {
5128 let mut state = sip::SipState::new();
5129 macro_rules! byte( ($b:expr) => { ($b as u8).hash(&mut state) } );
5130 macro_rules! hash( ($e:expr) => { $e.hash(&mut state) } );
5132 let region = |_state: &mut sip::SipState, r: Region| {
5142 tcx.sess.bug("non-static region found when hashing a type")
5146 let did = |state: &mut sip::SipState, did: DefId| {
5147 let h = if ast_util::is_local(did) {
5150 tcx.sess.cstore.get_crate_hash(did.krate)
5152 h.as_str().hash(state);
5153 did.node.hash(state);
5155 let mt = |state: &mut sip::SipState, mt: mt| {
5156 mt.mutbl.hash(state);
5158 ty::walk_ty(t, |t| {
5159 match ty::get(t).sty {
5162 ty_bool => byte!(2),
5163 ty_char => byte!(3),
5189 ty_vec(_, Some(n)) => {
5193 ty_vec(_, None) => {
5195 0u8.hash(&mut state);
5203 region(&mut state, r);
5206 ty_bare_fn(ref b) => {
5211 ty_closure(ref c) => {
5217 UniqTraitStore => byte!(0),
5218 RegionTraitStore(r, m) => {
5220 region(&mut state, r);
5221 assert_eq!(m, ast::MutMutable);
5225 ty_trait(box TyTrait { def_id: d, bounds, .. }) => {
5230 ty_struct(d, _) => {
5234 ty_tup(ref inner) => {
5241 did(&mut state, p.def_id);
5243 ty_open(_) => byte!(22),
5244 ty_infer(_) => unreachable!(),
5245 ty_err => byte!(23),
5246 ty_unboxed_closure(d, r) => {
5249 region(&mut state, r);
5258 pub fn to_string(self) -> &'static str {
5261 Contravariant => "-",
5268 pub fn empty_parameter_environment() -> ParameterEnvironment {
5270 * Construct a parameter environment suitable for static contexts
5271 * or other contexts where there are no free type/lifetime
5272 * parameters in scope.
5275 ty::ParameterEnvironment { free_substs: Substs::empty(),
5276 bounds: VecPerParamSpace::empty(),
5277 caller_obligations: VecPerParamSpace::empty(),
5278 implicit_region_bound: ty::ReEmpty }
5281 pub fn construct_parameter_environment(
5284 generics: &ty::Generics,
5285 free_id: ast::NodeId)
5286 -> ParameterEnvironment
5288 /*! See `ParameterEnvironment` struct def'n for details */
5291 // Construct the free substs.
5295 let mut types = VecPerParamSpace::empty();
5296 for &space in subst::ParamSpace::all().iter() {
5297 push_types_from_defs(tcx, &mut types, space,
5298 generics.types.get_slice(space));
5301 // map bound 'a => free 'a
5302 let mut regions = VecPerParamSpace::empty();
5303 for &space in subst::ParamSpace::all().iter() {
5304 push_region_params(&mut regions, space, free_id,
5305 generics.regions.get_slice(space));
5308 let free_substs = Substs {
5310 regions: subst::NonerasedRegions(regions)
5314 // Compute the bounds on Self and the type parameters.
5317 let mut bounds = VecPerParamSpace::empty();
5318 for &space in subst::ParamSpace::all().iter() {
5319 push_bounds_from_defs(tcx, &mut bounds, space, &free_substs,
5320 generics.types.get_slice(space));
5324 // Compute region bounds. For now, these relations are stored in a
5325 // global table on the tcx, so just enter them there. I'm not
5326 // crazy about this scheme, but it's convenient, at least.
5329 for &space in subst::ParamSpace::all().iter() {
5330 record_region_bounds_from_defs(tcx, space, &free_substs,
5331 generics.regions.get_slice(space));
5335 debug!("construct_parameter_environment: free_id={} \
5339 free_substs.repr(tcx),
5342 let obligations = traits::obligations_for_generics(tcx, traits::ObligationCause::misc(span),
5343 generics, &free_substs);
5345 return ty::ParameterEnvironment {
5346 free_substs: free_substs,
5348 implicit_region_bound: ty::ReScope(free_id),
5349 caller_obligations: obligations,
5352 fn push_region_params(regions: &mut VecPerParamSpace<ty::Region>,
5353 space: subst::ParamSpace,
5354 free_id: ast::NodeId,
5355 region_params: &[RegionParameterDef])
5357 for r in region_params.iter() {
5358 regions.push(space, ty::free_region_from_def(free_id, r));
5362 fn push_types_from_defs(tcx: &ty::ctxt,
5363 types: &mut subst::VecPerParamSpace<ty::t>,
5364 space: subst::ParamSpace,
5365 defs: &[TypeParameterDef]) {
5366 for (i, def) in defs.iter().enumerate() {
5367 let ty = ty::mk_param(tcx, space, i, def.def_id);
5368 types.push(space, ty);
5372 fn push_bounds_from_defs(tcx: &ty::ctxt,
5373 bounds: &mut subst::VecPerParamSpace<ParamBounds>,
5374 space: subst::ParamSpace,
5375 free_substs: &subst::Substs,
5376 defs: &[TypeParameterDef]) {
5377 for def in defs.iter() {
5378 let b = def.bounds.subst(tcx, free_substs);
5379 bounds.push(space, b);
5383 fn record_region_bounds_from_defs(tcx: &ty::ctxt,
5384 space: subst::ParamSpace,
5385 free_substs: &subst::Substs,
5386 defs: &[RegionParameterDef]) {
5387 for (subst_region, def) in
5388 free_substs.regions().get_slice(space).iter().zip(
5391 // For each region parameter 'subst...
5392 let bounds = def.bounds.subst(tcx, free_substs);
5393 for bound_region in bounds.iter() {
5394 // Which is declared with a bound like 'subst:'bound...
5395 match (subst_region, bound_region) {
5396 (&ty::ReFree(subst_fr), &ty::ReFree(bound_fr)) => {
5397 // Record that 'subst outlives 'bound. Or, put
5398 // another way, 'bound <= 'subst.
5399 tcx.region_maps.relate_free_regions(bound_fr, subst_fr);
5402 // All named regions are instantiated with free regions.
5404 format!("push_region_bounds_from_defs: \
5405 non free region: {} / {}",
5406 subst_region.repr(tcx),
5407 bound_region.repr(tcx)).as_slice());
5416 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
5418 ast::MutMutable => MutBorrow,
5419 ast::MutImmutable => ImmBorrow,
5423 pub fn to_mutbl_lossy(self) -> ast::Mutability {
5425 * Returns a mutability `m` such that an `&m T` pointer could
5426 * be used to obtain this borrow kind. Because borrow kinds
5427 * are richer than mutabilities, we sometimes have to pick a
5428 * mutability that is stronger than necessary so that it at
5429 * least *would permit* the borrow in question.
5433 MutBorrow => ast::MutMutable,
5434 ImmBorrow => ast::MutImmutable,
5436 // We have no type correponding to a unique imm borrow, so
5437 // use `&mut`. It gives all the capabilities of an `&uniq`
5438 // and hence is a safe "over approximation".
5439 UniqueImmBorrow => ast::MutMutable,
5443 pub fn to_user_str(&self) -> &'static str {
5445 MutBorrow => "mutable",
5446 ImmBorrow => "immutable",
5447 UniqueImmBorrow => "uniquely immutable",
5452 impl<'tcx> mc::Typer<'tcx> for ty::ctxt<'tcx> {
5453 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
5457 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<ty::t> {
5458 Ok(ty::node_id_to_type(self, id))
5461 fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t> {
5462 self.method_map.borrow().find(&method_call).map(|method| method.ty)
5465 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment>> {
5469 fn is_method_call(&self, id: ast::NodeId) -> bool {
5470 self.method_map.borrow().contains_key(&typeck::MethodCall::expr(id))
5473 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<ast::NodeId> {
5474 self.region_maps.temporary_scope(rvalue_id)
5477 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow {
5478 self.upvar_borrow_map.borrow().get_copy(&upvar_id)
5481 fn capture_mode(&self, closure_expr_id: ast::NodeId)
5482 -> freevars::CaptureMode {
5483 self.capture_modes.borrow().get_copy(&closure_expr_id)
5486 fn unboxed_closures<'a>(&'a self)
5487 -> &'a RefCell<DefIdMap<UnboxedClosure>> {
5488 &self.unboxed_closures
5492 /// The category of explicit self.
5493 #[deriving(Clone, Eq, PartialEq)]
5494 pub enum ExplicitSelfCategory {
5495 StaticExplicitSelfCategory,
5496 ByValueExplicitSelfCategory,
5497 ByReferenceExplicitSelfCategory(Region, ast::Mutability),
5498 ByBoxExplicitSelfCategory,
5501 /// Pushes all the lifetimes in the given type onto the given list. A
5502 /// "lifetime in a type" is a lifetime specified by a reference or a lifetime
5503 /// in a list of type substitutions. This does *not* traverse into nominal
5504 /// types, nor does it resolve fictitious types.
5505 pub fn accumulate_lifetimes_in_type(accumulator: &mut Vec<ty::Region>,
5507 walk_ty(typ, |typ| {
5508 match get(typ).sty {
5509 ty_rptr(region, _) => accumulator.push(region),
5510 ty_enum(_, ref substs) |
5511 ty_trait(box TyTrait {
5515 ty_struct(_, ref substs) => {
5516 match substs.regions {
5517 subst::ErasedRegions => {}
5518 subst::NonerasedRegions(ref regions) => {
5519 for region in regions.iter() {
5520 accumulator.push(*region)
5525 ty_closure(ref closure_ty) => {
5526 match closure_ty.store {
5527 RegionTraitStore(region, _) => accumulator.push(region),
5528 UniqTraitStore => {}
5531 ty_unboxed_closure(_, ref region) => accumulator.push(*region),