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::lang_items::{FnTraitLangItem, FnMutTraitLangItem};
21 use middle::lang_items::{FnOnceTraitLangItem, OpaqueStructLangItem};
22 use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem};
23 use middle::mem_categorization as mc;
25 use middle::resolve_lifetime;
26 use middle::stability;
27 use middle::subst::{Subst, Substs, VecPerParamSpace};
33 use middle::ty_fold::{TypeFoldable,TypeFolder};
35 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_string};
36 use util::ppaux::{trait_store_to_string, ty_to_string};
37 use util::ppaux::{Repr, UserString};
38 use util::common::{indenter};
39 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet, FnvHashMap};
41 use std::cell::{Cell, RefCell};
45 use std::hash::{Hash, sip, Writer};
46 use std::iter::AdditiveIterator;
50 use std::collections::{HashMap, HashSet};
51 use std::collections::hashmap::{Occupied, Vacant};
52 use arena::TypedArena;
54 use syntax::ast::{CrateNum, DefId, FnStyle, Ident, ItemTrait, LOCAL_CRATE};
55 use syntax::ast::{MutImmutable, MutMutable, Name, NamedField, NodeId};
56 use syntax::ast::{Onceness, StmtExpr, StmtSemi, StructField, UnnamedField};
57 use syntax::ast::{Visibility};
58 use syntax::ast_util::{PostExpansionMethod, is_local, lit_is_str};
61 use syntax::attr::AttrMetaMethods;
62 use syntax::codemap::Span;
63 use syntax::parse::token;
64 use syntax::parse::token::InternedString;
65 use syntax::{ast, ast_map};
66 use syntax::util::small_vector::SmallVector;
67 use std::collections::enum_set::{EnumSet, CLike};
71 pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0;
75 #[deriving(PartialEq, Eq, Hash)]
77 pub ident: ast::Ident,
82 pub enum ImplOrTraitItemContainer {
83 TraitContainer(ast::DefId),
84 ImplContainer(ast::DefId),
87 impl ImplOrTraitItemContainer {
88 pub fn id(&self) -> ast::DefId {
90 TraitContainer(id) => id,
91 ImplContainer(id) => id,
97 pub enum ImplOrTraitItem {
98 MethodTraitItem(Rc<Method>),
99 TypeTraitItem(Rc<AssociatedType>),
102 impl ImplOrTraitItem {
103 fn id(&self) -> ImplOrTraitItemId {
105 MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
106 TypeTraitItem(ref associated_type) => {
107 TypeTraitItemId(associated_type.def_id)
112 pub fn def_id(&self) -> ast::DefId {
114 MethodTraitItem(ref method) => method.def_id,
115 TypeTraitItem(ref associated_type) => associated_type.def_id,
119 pub fn ident(&self) -> ast::Ident {
121 MethodTraitItem(ref method) => method.ident,
122 TypeTraitItem(ref associated_type) => associated_type.ident,
126 pub fn container(&self) -> ImplOrTraitItemContainer {
128 MethodTraitItem(ref method) => method.container,
129 TypeTraitItem(ref associated_type) => associated_type.container,
135 pub enum ImplOrTraitItemId {
136 MethodTraitItemId(ast::DefId),
137 TypeTraitItemId(ast::DefId),
140 impl ImplOrTraitItemId {
141 pub fn def_id(&self) -> ast::DefId {
143 MethodTraitItemId(def_id) => def_id,
144 TypeTraitItemId(def_id) => def_id,
151 pub ident: ast::Ident,
152 pub generics: ty::Generics,
154 pub explicit_self: ExplicitSelfCategory,
155 pub vis: ast::Visibility,
156 pub def_id: ast::DefId,
157 pub container: ImplOrTraitItemContainer,
159 // If this method is provided, we need to know where it came from
160 pub provided_source: Option<ast::DefId>
164 pub fn new(ident: ast::Ident,
165 generics: ty::Generics,
167 explicit_self: ExplicitSelfCategory,
168 vis: ast::Visibility,
170 container: ImplOrTraitItemContainer,
171 provided_source: Option<ast::DefId>)
177 explicit_self: explicit_self,
180 container: container,
181 provided_source: provided_source
185 pub fn container_id(&self) -> ast::DefId {
186 match self.container {
187 TraitContainer(id) => id,
188 ImplContainer(id) => id,
194 pub struct AssociatedType {
195 pub ident: ast::Ident,
196 pub vis: ast::Visibility,
197 pub def_id: ast::DefId,
198 pub container: ImplOrTraitItemContainer,
201 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
204 pub mutbl: ast::Mutability,
207 #[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
208 pub enum TraitStore {
211 /// &Trait and &mut Trait
212 RegionTraitStore(Region, ast::Mutability),
215 #[deriving(Clone, Show)]
216 pub struct field_ty {
219 pub vis: ast::Visibility,
220 pub origin: ast::DefId, // The DefId of the struct in which the field is declared.
223 // Contains information needed to resolve types and (in the future) look up
224 // the types of AST nodes.
225 #[deriving(PartialEq, Eq, Hash)]
226 pub struct creader_cache_key {
232 pub type creader_cache = RefCell<HashMap<creader_cache_key, t>>;
234 pub struct intern_key {
238 // NB: Do not replace this with #[deriving(PartialEq)]. The automatically-derived
239 // implementation will not recurse through sty and you will get stack
241 impl cmp::PartialEq for intern_key {
242 fn eq(&self, other: &intern_key) -> bool {
244 *self.sty == *other.sty
247 fn ne(&self, other: &intern_key) -> bool {
252 impl Eq for intern_key {}
254 impl<W:Writer> Hash<W> for intern_key {
255 fn hash(&self, s: &mut W) {
256 unsafe { (*self.sty).hash(s) }
260 pub enum ast_ty_to_ty_cache_entry {
261 atttce_unresolved, /* not resolved yet */
262 atttce_resolved(t) /* resolved to a type, irrespective of region */
265 #[deriving(Clone, PartialEq, Decodable, Encodable)]
266 pub struct ItemVariances {
267 pub types: VecPerParamSpace<Variance>,
268 pub regions: VecPerParamSpace<Variance>,
271 #[deriving(Clone, PartialEq, Decodable, Encodable, Show)]
273 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
274 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
275 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
276 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
280 pub enum AutoAdjustment {
281 AdjustAddEnv(ty::TraitStore),
282 AdjustDerefRef(AutoDerefRef)
285 #[deriving(Clone, PartialEq)]
286 pub enum UnsizeKind {
287 // [T, ..n] -> [T], the uint field is n.
289 // An unsize coercion applied to the tail field of a struct.
290 // The uint is the index of the type parameter which is unsized.
291 UnsizeStruct(Box<UnsizeKind>, uint),
292 UnsizeVtable(TyTrait, /* the self type of the trait */ ty::t)
296 pub struct AutoDerefRef {
297 pub autoderefs: uint,
298 pub autoref: Option<AutoRef>
301 #[deriving(Clone, PartialEq)]
303 /// Convert from T to &T
304 /// The third field allows us to wrap other AutoRef adjustments.
305 AutoPtr(Region, ast::Mutability, Option<Box<AutoRef>>),
307 /// Convert [T, ..n] to [T] (or similar, depending on the kind)
308 AutoUnsize(UnsizeKind),
310 /// Convert Box<[T, ..n]> to Box<[T]> or something similar in a Box.
311 /// With DST and Box a library type, this should be replaced by UnsizeStruct.
312 AutoUnsizeUniq(UnsizeKind),
314 /// Convert from T to *T
315 /// Value to thin pointer
316 /// The second field allows us to wrap other AutoRef adjustments.
317 AutoUnsafe(ast::Mutability, Option<Box<AutoRef>>),
320 // Ugly little helper function. The first bool in the returned tuple is true if
321 // there is an 'unsize to trait object' adjustment at the bottom of the
322 // adjustment. If that is surrounded by an AutoPtr, then we also return the
323 // region of the AutoPtr (in the third argument). The second bool is true if the
324 // adjustment is unique.
325 fn autoref_object_region(autoref: &AutoRef) -> (bool, bool, Option<Region>) {
326 fn unsize_kind_is_object(k: &UnsizeKind) -> bool {
328 &UnsizeVtable(..) => true,
329 &UnsizeStruct(box ref k, _) => unsize_kind_is_object(k),
335 &AutoUnsize(ref k) => (unsize_kind_is_object(k), false, None),
336 &AutoUnsizeUniq(ref k) => (unsize_kind_is_object(k), true, None),
337 &AutoPtr(adj_r, _, Some(box ref autoref)) => {
338 let (b, u, r) = autoref_object_region(autoref);
339 if r.is_some() || u {
345 &AutoUnsafe(_, Some(box ref autoref)) => autoref_object_region(autoref),
346 _ => (false, false, None)
350 // If the adjustment introduces a borrowed reference to a trait object, then
351 // returns the region of the borrowed reference.
352 pub fn adjusted_object_region(adj: &AutoAdjustment) -> Option<Region> {
354 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
355 let (b, _, r) = autoref_object_region(autoref);
366 // Returns true if there is a trait cast at the bottom of the adjustment.
367 pub fn adjust_is_object(adj: &AutoAdjustment) -> bool {
369 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
370 let (b, _, _) = autoref_object_region(autoref);
377 // If possible, returns the type expected from the given adjustment. This is not
378 // possible if the adjustment depends on the type of the adjusted expression.
379 pub fn type_of_adjust(cx: &ctxt, adj: &AutoAdjustment) -> Option<t> {
380 fn type_of_autoref(cx: &ctxt, autoref: &AutoRef) -> Option<t> {
382 &AutoUnsize(ref k) => match k {
383 &UnsizeVtable(TyTrait { def_id, substs: ref substs, bounds }, _) => {
384 Some(mk_trait(cx, def_id, substs.clone(), bounds))
388 &AutoUnsizeUniq(ref k) => match k {
389 &UnsizeVtable(TyTrait { def_id, substs: ref substs, bounds }, _) => {
390 Some(mk_uniq(cx, mk_trait(cx, def_id, substs.clone(), bounds)))
394 &AutoPtr(r, m, Some(box ref autoref)) => {
395 match type_of_autoref(cx, autoref) {
396 Some(t) => Some(mk_rptr(cx, r, mt {mutbl: m, ty: t})),
400 &AutoUnsafe(m, Some(box ref autoref)) => {
401 match type_of_autoref(cx, autoref) {
402 Some(t) => Some(mk_ptr(cx, mt {mutbl: m, ty: t})),
411 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
412 type_of_autoref(cx, autoref)
420 /// A restriction that certain types must be the same size. The use of
421 /// `transmute` gives rise to these restrictions.
422 pub struct TransmuteRestriction {
423 /// The span from whence the restriction comes.
425 /// The type being transmuted from.
427 /// The type being transmuted to.
429 /// NodeIf of the transmute intrinsic.
433 /// The data structure to keep track of all the information that typechecker
434 /// generates so that so that it can be reused and doesn't have to be redone
436 pub struct ctxt<'tcx> {
437 /// The arena that types are allocated from.
438 type_arena: &'tcx TypedArena<t_box_>,
440 /// Specifically use a speedy hash algorithm for this hash map, it's used
442 interner: RefCell<FnvHashMap<intern_key, &'tcx t_box_>>,
443 pub next_id: Cell<uint>,
445 pub def_map: resolve::DefMap,
447 pub named_region_map: resolve_lifetime::NamedRegionMap,
449 pub region_maps: middle::region::RegionMaps,
451 /// Stores the types for various nodes in the AST. Note that this table
452 /// is not guaranteed to be populated until after typeck. See
453 /// typeck::check::fn_ctxt for details.
454 pub node_types: node_type_table,
456 /// Stores the type parameters which were substituted to obtain the type
457 /// of this node. This only applies to nodes that refer to entities
458 /// parameterized by type parameters, such as generic fns, types, or
460 pub item_substs: RefCell<NodeMap<ItemSubsts>>,
462 /// Maps from a trait item to the trait item "descriptor"
463 pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem>>,
465 /// Maps from a trait def-id to a list of the def-ids of its trait items
466 pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
468 /// A cache for the trait_items() routine
469 pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem>>>>,
471 pub impl_trait_cache: RefCell<DefIdMap<Option<Rc<ty::TraitRef>>>>,
473 pub trait_refs: RefCell<NodeMap<Rc<TraitRef>>>,
474 pub trait_defs: RefCell<DefIdMap<Rc<TraitDef>>>,
476 /// Maps from node-id of a trait object cast (like `foo as
477 /// Box<Trait>`) to the trait reference.
478 pub object_cast_map: typeck::ObjectCastMap,
480 pub map: ast_map::Map<'tcx>,
481 pub intrinsic_defs: RefCell<DefIdMap<t>>,
482 pub freevars: RefCell<FreevarMap>,
483 pub tcache: type_cache,
484 pub rcache: creader_cache,
485 pub short_names_cache: RefCell<HashMap<t, String>>,
486 pub needs_unwind_cleanup_cache: RefCell<HashMap<t, bool>>,
487 pub tc_cache: RefCell<HashMap<uint, TypeContents>>,
488 pub ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry>>,
489 pub enum_var_cache: RefCell<DefIdMap<Rc<Vec<Rc<VariantInfo>>>>>,
490 pub ty_param_defs: RefCell<NodeMap<TypeParameterDef>>,
491 pub adjustments: RefCell<NodeMap<AutoAdjustment>>,
492 pub normalized_cache: RefCell<HashMap<t, t>>,
493 pub lang_items: middle::lang_items::LanguageItems,
494 /// A mapping of fake provided method def_ids to the default implementation
495 pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
496 pub superstructs: RefCell<DefIdMap<Option<ast::DefId>>>,
497 pub struct_fields: RefCell<DefIdMap<Rc<Vec<field_ty>>>>,
499 /// Maps from def-id of a type or region parameter to its
500 /// (inferred) variance.
501 pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
503 /// True if the variance has been computed yet; false otherwise.
504 pub variance_computed: Cell<bool>,
506 /// A mapping from the def ID of an enum or struct type to the def ID
507 /// of the method that implements its destructor. If the type is not
508 /// present in this map, it does not have a destructor. This map is
509 /// populated during the coherence phase of typechecking.
510 pub destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
512 /// A method will be in this list if and only if it is a destructor.
513 pub destructors: RefCell<DefIdSet>,
515 /// Maps a trait onto a list of impls of that trait.
516 pub trait_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
518 /// Maps a DefId of a type to a list of its inherent impls.
519 /// Contains implementations of methods that are inherent to a type.
520 /// Methods in these implementations don't need to be exported.
521 pub inherent_impls: RefCell<DefIdMap<Rc<Vec<ast::DefId>>>>,
523 /// Maps a DefId of an impl to a list of its items.
524 /// Note that this contains all of the impls that we know about,
525 /// including ones in other crates. It's not clear that this is the best
527 pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
529 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
530 /// present in this set can be warned about.
531 pub used_unsafe: RefCell<NodeSet>,
533 /// Set of nodes which mark locals as mutable which end up getting used at
534 /// some point. Local variable definitions not in this set can be warned
536 pub used_mut_nodes: RefCell<NodeSet>,
538 /// The set of external nominal types whose implementations have been read.
539 /// This is used for lazy resolution of methods.
540 pub populated_external_types: RefCell<DefIdSet>,
542 /// The set of external traits whose implementations have been read. This
543 /// is used for lazy resolution of traits.
544 pub populated_external_traits: RefCell<DefIdSet>,
547 pub upvar_borrow_map: RefCell<UpvarBorrowMap>,
549 /// These two caches are used by const_eval when decoding external statics
550 /// and variants that are found.
551 pub extern_const_statics: RefCell<DefIdMap<ast::NodeId>>,
552 pub extern_const_variants: RefCell<DefIdMap<ast::NodeId>>,
554 pub method_map: typeck::MethodMap,
556 pub dependency_formats: RefCell<dependency_format::Dependencies>,
558 /// Records the type of each unboxed closure. The def ID is the ID of the
559 /// expression defining the unboxed closure.
560 pub unboxed_closures: RefCell<DefIdMap<UnboxedClosure>>,
562 pub node_lint_levels: RefCell<HashMap<(ast::NodeId, lint::LintId),
565 /// The types that must be asserted to be the same size for `transmute`
566 /// to be valid. We gather up these restrictions in the intrinsicck pass
567 /// and check them in trans.
568 pub transmute_restrictions: RefCell<Vec<TransmuteRestriction>>,
570 /// Maps any item's def-id to its stability index.
571 pub stability: RefCell<stability::Index>,
573 /// Maps closures to their capture clauses.
574 pub capture_modes: RefCell<CaptureModeMap>,
576 /// Maps def IDs to true if and only if they're associated types.
577 pub associated_types: RefCell<DefIdMap<bool>>,
579 /// Maps def IDs of traits to information about their associated types.
580 pub trait_associated_types:
581 RefCell<DefIdMap<Rc<Vec<AssociatedTypeInfo>>>>,
583 /// Caches the results of trait selection. This cache is used
584 /// for things that do not have to do with the parameters in scope.
585 pub selection_cache: traits::SelectionCache,
596 // a meta-pub flag: subst may be required if the type has parameters, a self
597 // type, or references bound regions
598 needs_subst = 1 | 2 | 8
601 pub type t_box = &'static t_box_;
610 // To reduce refcounting cost, we're representing types as unsafe pointers
611 // throughout the compiler. These are simply casted t_box values. Use ty::get
612 // to cast them back to a box. (Without the cast, compiler performance suffers
613 // ~15%.) This does mean that a t value relies on the ctxt to keep its box
614 // alive, and using ty::get is unsafe when the ctxt is no longer alive.
617 #[allow(raw_pointer_deriving)]
618 #[deriving(Clone, PartialEq, Eq, Hash)]
619 pub struct t { inner: *const t_opaque }
621 impl fmt::Show for t {
622 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
623 write!(f, "{}", get(*self))
627 pub fn get(t: t) -> t_box {
629 let t2: t_box = mem::transmute(t);
634 pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
635 (tb.flags & (flag as uint)) != 0u
637 pub fn type_has_params(t: t) -> bool {
638 tbox_has_flag(get(t), has_params)
640 pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
641 pub fn type_needs_infer(t: t) -> bool {
642 tbox_has_flag(get(t), needs_infer)
644 pub fn type_id(t: t) -> uint { get(t).id }
646 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
647 pub struct BareFnTy {
648 pub fn_style: ast::FnStyle,
653 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
654 pub struct ClosureTy {
655 pub fn_style: ast::FnStyle,
656 pub onceness: ast::Onceness,
657 pub store: TraitStore,
658 pub bounds: ExistentialBounds,
664 * Signature of a function type, which I have arbitrarily
665 * decided to use to refer to the input/output types.
667 * - `binder_id` is the node id where this fn type appeared;
668 * it is used to identify all the bound regions appearing
669 * in the input/output types that are bound by this fn type
670 * (vs some enclosing or enclosed fn type)
671 * - `inputs` is the list of arguments and their modes.
672 * - `output` is the return type.
673 * - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
675 #[deriving(Clone, PartialEq, Eq, Hash)]
677 pub binder_id: ast::NodeId,
683 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
685 pub space: subst::ParamSpace,
690 /// Representation of regions:
691 #[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
693 // Region bound in a type or fn declaration which will be
694 // substituted 'early' -- that is, at the same time when type
695 // parameters are substituted.
696 ReEarlyBound(/* param id */ ast::NodeId,
701 // Region bound in a function scope, which will be substituted when the
702 // function is called. The first argument must be the `binder_id` of
703 // some enclosing function signature.
704 ReLateBound(/* binder_id */ ast::NodeId, BoundRegion),
706 /// When checking a function body, the types of all arguments and so forth
707 /// that refer to bound region parameters are modified to refer to free
708 /// region parameters.
711 /// A concrete region naming some expression within the current function.
714 /// Static data that has an "infinite" lifetime. Top in the region lattice.
717 /// A region variable. Should not exist after typeck.
718 ReInfer(InferRegion),
720 /// Empty lifetime is for data that is never accessed.
721 /// Bottom in the region lattice. We treat ReEmpty somewhat
722 /// specially; at least right now, we do not generate instances of
723 /// it during the GLB computations, but rather
724 /// generate an error instead. This is to improve error messages.
725 /// The only way to get an instance of ReEmpty is to have a region
726 /// variable with no constraints.
731 * Upvars do not get their own node-id. Instead, we use the pair of
732 * the original var id (that is, the root variable that is referenced
733 * by the upvar) and the id of the closure expression.
735 #[deriving(Clone, PartialEq, Eq, Hash)]
737 pub var_id: ast::NodeId,
738 pub closure_expr_id: ast::NodeId,
741 #[deriving(Clone, PartialEq, Eq, Hash, Show, Encodable, Decodable)]
742 pub enum BorrowKind {
743 /// Data must be immutable and is aliasable.
746 /// Data must be immutable but not aliasable. This kind of borrow
747 /// cannot currently be expressed by the user and is used only in
748 /// implicit closure bindings. It is needed when you the closure
749 /// is borrowing or mutating a mutable referent, e.g.:
751 /// let x: &mut int = ...;
752 /// let y = || *x += 5;
754 /// If we were to try to translate this closure into a more explicit
755 /// form, we'd encounter an error with the code as written:
757 /// struct Env { x: & &mut int }
758 /// let x: &mut int = ...;
759 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
760 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
762 /// This is then illegal because you cannot mutate a `&mut` found
763 /// in an aliasable location. To solve, you'd have to translate with
764 /// an `&mut` borrow:
766 /// struct Env { x: & &mut int }
767 /// let x: &mut int = ...;
768 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
769 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
771 /// Now the assignment to `**env.x` is legal, but creating a
772 /// mutable pointer to `x` is not because `x` is not mutable. We
773 /// could fix this by declaring `x` as `let mut x`. This is ok in
774 /// user code, if awkward, but extra weird for closures, since the
775 /// borrow is hidden.
777 /// So we introduce a "unique imm" borrow -- the referent is
778 /// immutable, but not aliasable. This solves the problem. For
779 /// simplicity, we don't give users the way to express this
780 /// borrow, it's just used when translating closures.
783 /// Data is mutable and not aliasable.
788 * Information describing the borrowing of an upvar. This is computed
789 * during `typeck`, specifically by `regionck`. The general idea is
790 * that the compiler analyses treat closures like:
792 * let closure: &'e fn() = || {
793 * x = 1; // upvar x is assigned to
794 * use(y); // upvar y is read
795 * foo(&z); // upvar z is borrowed immutably
798 * as if they were "desugared" to something loosely like:
800 * struct Vars<'x,'y,'z> { x: &'x mut int,
803 * let closure: &'e fn() = {
809 * let env: &'e mut Vars<'x,'y,'z> = &mut Vars { x: &'x mut x,
815 * This is basically what happens at runtime. The closure is basically
816 * an existentially quantified version of the `(env, f)` pair.
818 * This data structure indicates the region and mutability of a single
819 * one of the `x...z` borrows.
821 * It may not be obvious why each borrowed variable gets its own
822 * lifetime (in the desugared version of the example, these are indicated
823 * by the lifetime parameters `'x`, `'y`, and `'z` in the `Vars` definition).
824 * Each such lifetime must encompass the lifetime `'e` of the closure itself,
825 * but need not be identical to it. The reason that this makes sense:
827 * - Callers are only permitted to invoke the closure, and hence to
828 * use the pointers, within the lifetime `'e`, so clearly `'e` must
829 * be a sublifetime of `'x...'z`.
830 * - The closure creator knows which upvars were borrowed by the closure
831 * and thus `x...z` will be reserved for `'x...'z` respectively.
832 * - Through mutation, the borrowed upvars can actually escape
833 * the closure, so sometimes it is necessary for them to be larger
834 * than the closure lifetime itself.
836 #[deriving(PartialEq, Clone, Encodable, Decodable)]
837 pub struct UpvarBorrow {
838 pub kind: BorrowKind,
839 pub region: ty::Region,
842 pub type UpvarBorrowMap = HashMap<UpvarId, UpvarBorrow>;
845 pub fn is_bound(&self) -> bool {
847 &ty::ReEarlyBound(..) => true,
848 &ty::ReLateBound(..) => true,
854 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
855 pub struct FreeRegion {
856 pub scope_id: NodeId,
857 pub bound_region: BoundRegion
860 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
861 pub enum BoundRegion {
862 /// An anonymous region parameter for a given fn (&T)
865 /// Named region parameters for functions (a in &'a T)
867 /// The def-id is needed to distinguish free regions in
868 /// the event of shadowing.
869 BrNamed(ast::DefId, ast::Name),
871 /// Fresh bound identifiers created during GLB computations.
880 macro_rules! def_prim_ty(
881 ($name:ident, $sty:expr, $id:expr) => (
882 pub static $name: t_box_ = t_box_ {
890 def_prim_ty!(TY_NIL, super::ty_nil, 0)
891 def_prim_ty!(TY_BOOL, super::ty_bool, 1)
892 def_prim_ty!(TY_CHAR, super::ty_char, 2)
893 def_prim_ty!(TY_INT, super::ty_int(ast::TyI), 3)
894 def_prim_ty!(TY_I8, super::ty_int(ast::TyI8), 4)
895 def_prim_ty!(TY_I16, super::ty_int(ast::TyI16), 5)
896 def_prim_ty!(TY_I32, super::ty_int(ast::TyI32), 6)
897 def_prim_ty!(TY_I64, super::ty_int(ast::TyI64), 7)
898 def_prim_ty!(TY_UINT, super::ty_uint(ast::TyU), 8)
899 def_prim_ty!(TY_U8, super::ty_uint(ast::TyU8), 9)
900 def_prim_ty!(TY_U16, super::ty_uint(ast::TyU16), 10)
901 def_prim_ty!(TY_U32, super::ty_uint(ast::TyU32), 11)
902 def_prim_ty!(TY_U64, super::ty_uint(ast::TyU64), 12)
903 def_prim_ty!(TY_F32, super::ty_float(ast::TyF32), 14)
904 def_prim_ty!(TY_F64, super::ty_float(ast::TyF64), 15)
906 pub static TY_BOT: t_box_ = t_box_ {
909 flags: super::has_ty_bot as uint,
912 pub static TY_ERR: t_box_ = t_box_ {
915 flags: super::has_ty_err as uint,
918 pub static LAST_PRIMITIVE_ID: uint = 18;
921 // NB: If you change this, you'll probably want to change the corresponding
922 // AST structure in libsyntax/ast.rs as well.
923 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
930 ty_uint(ast::UintTy),
931 ty_float(ast::FloatTy),
932 /// Substs here, possibly against intuition, *may* contain `ty_param`s.
933 /// That is, even after substitution it is possible that there are type
934 /// variables. This happens when the `ty_enum` corresponds to an enum
935 /// definition and not a concrete use of it. To get the correct `ty_enum`
936 /// from the tcx, use the `NodeId` from the `ast::Ty` and look it up in
937 /// the `ast_ty_to_ty_cache`. This is probably true for `ty_struct` as
939 ty_enum(DefId, Substs),
943 ty_vec(t, Option<uint>), // Second field is length.
946 ty_bare_fn(BareFnTy),
947 ty_closure(Box<ClosureTy>),
948 ty_trait(Box<TyTrait>),
949 ty_struct(DefId, Substs),
950 ty_unboxed_closure(DefId, Region),
953 ty_param(ParamTy), // type parameter
954 ty_open(t), // A deref'ed fat pointer, i.e., a dynamically sized value
955 // and its size. Only ever used in trans. It is not necessary
956 // earlier since we don't need to distinguish a DST with its
957 // size (e.g., in a deref) vs a DST with the size elsewhere (
958 // e.g., in a field).
960 ty_infer(InferTy), // something used only during inference/typeck
961 ty_err, // Also only used during inference/typeck, to represent
962 // the type of an erroneous expression (helps cut down
963 // on non-useful type error messages)
966 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
970 pub bounds: ExistentialBounds
973 #[deriving(PartialEq, Eq, Hash, Show)]
974 pub struct TraitRef {
979 #[deriving(Clone, PartialEq)]
980 pub enum IntVarValue {
982 UintType(ast::UintTy),
985 #[deriving(Clone, Show)]
986 pub enum terr_vstore_kind {
993 #[deriving(Clone, Show)]
994 pub struct expected_found<T> {
999 // Data structures used in type unification
1000 #[deriving(Clone, Show)]
1003 terr_fn_style_mismatch(expected_found<FnStyle>),
1004 terr_onceness_mismatch(expected_found<Onceness>),
1005 terr_abi_mismatch(expected_found<abi::Abi>),
1007 terr_sigil_mismatch(expected_found<TraitStore>),
1008 terr_box_mutability,
1009 terr_ptr_mutability,
1010 terr_ref_mutability,
1011 terr_vec_mutability,
1012 terr_tuple_size(expected_found<uint>),
1013 terr_ty_param_size(expected_found<uint>),
1014 terr_record_size(expected_found<uint>),
1015 terr_record_mutability,
1016 terr_record_fields(expected_found<Ident>),
1018 terr_regions_does_not_outlive(Region, Region),
1019 terr_regions_not_same(Region, Region),
1020 terr_regions_no_overlap(Region, Region),
1021 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
1022 terr_regions_overly_polymorphic(BoundRegion, Region),
1023 terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
1024 terr_sorts(expected_found<t>),
1025 terr_integer_as_char,
1026 terr_int_mismatch(expected_found<IntVarValue>),
1027 terr_float_mismatch(expected_found<ast::FloatTy>),
1028 terr_traits(expected_found<ast::DefId>),
1029 terr_builtin_bounds(expected_found<BuiltinBounds>),
1030 terr_variadic_mismatch(expected_found<bool>),
1034 /// Bounds suitable for a named type parameter like `A` in `fn foo<A>`
1035 /// as well as the existential type parameter in an object type.
1036 #[deriving(PartialEq, Eq, Hash, Clone, Show)]
1037 pub struct ParamBounds {
1038 pub region_bounds: Vec<ty::Region>,
1039 pub builtin_bounds: BuiltinBounds,
1040 pub trait_bounds: Vec<Rc<TraitRef>>
1043 /// Bounds suitable for an existentially quantified type parameter
1044 /// such as those that appear in object types or closure types. The
1045 /// major difference between this case and `ParamBounds` is that
1046 /// general purpose trait bounds are omitted and there must be
1047 /// *exactly one* region.
1048 #[deriving(PartialEq, Eq, Hash, Clone, Show)]
1049 pub struct ExistentialBounds {
1050 pub region_bound: ty::Region,
1051 pub builtin_bounds: BuiltinBounds
1054 pub type BuiltinBounds = EnumSet<BuiltinBound>;
1056 #[deriving(Clone, Encodable, PartialEq, Eq, Decodable, Hash, Show)]
1058 pub enum BuiltinBound {
1065 pub fn empty_builtin_bounds() -> BuiltinBounds {
1069 pub fn all_builtin_bounds() -> BuiltinBounds {
1070 let mut set = EnumSet::empty();
1072 set.add(BoundSized);
1077 pub fn region_existential_bound(r: ty::Region) -> ExistentialBounds {
1079 * An existential bound that does not implement any traits.
1082 ty::ExistentialBounds { region_bound: r,
1083 builtin_bounds: empty_builtin_bounds() }
1086 impl CLike for BuiltinBound {
1087 fn to_uint(&self) -> uint {
1090 fn from_uint(v: uint) -> BuiltinBound {
1091 unsafe { mem::transmute(v) }
1095 #[deriving(Clone, PartialEq, Eq, Hash)]
1100 #[deriving(Clone, PartialEq, Eq, Hash)]
1105 #[deriving(Clone, PartialEq, Eq, Hash)]
1106 pub struct FloatVid {
1110 #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)]
1111 pub struct RegionVid {
1115 #[deriving(Clone, PartialEq, Eq, Hash)]
1122 // FIXME -- once integral fallback is impl'd, we should remove
1123 // this type. It's only needed to prevent spurious errors for
1124 // integers whose type winds up never being constrained.
1125 SkolemizedIntTy(uint),
1128 #[deriving(Clone, Encodable, Decodable, Eq, Hash, Show)]
1129 pub enum InferRegion {
1131 ReSkolemized(uint, BoundRegion)
1134 impl cmp::PartialEq for InferRegion {
1135 fn eq(&self, other: &InferRegion) -> bool {
1136 match ((*self), *other) {
1137 (ReVar(rva), ReVar(rvb)) => {
1140 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
1146 fn ne(&self, other: &InferRegion) -> bool {
1147 !((*self) == (*other))
1151 impl fmt::Show for TyVid {
1152 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
1153 write!(f, "<generic #{}>", self.index)
1157 impl fmt::Show for IntVid {
1158 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1159 write!(f, "<generic integer #{}>", self.index)
1163 impl fmt::Show for FloatVid {
1164 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1165 write!(f, "<generic float #{}>", self.index)
1169 impl fmt::Show for RegionVid {
1170 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1171 write!(f, "'<generic lifetime #{}>", self.index)
1175 impl fmt::Show for FnSig {
1176 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1177 // grr, without tcx not much we can do.
1182 impl fmt::Show for InferTy {
1183 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1185 TyVar(ref v) => v.fmt(f),
1186 IntVar(ref v) => v.fmt(f),
1187 FloatVar(ref v) => v.fmt(f),
1188 SkolemizedTy(v) => write!(f, "SkolemizedTy({})", v),
1189 SkolemizedIntTy(v) => write!(f, "SkolemizedIntTy({})", v),
1194 impl fmt::Show for IntVarValue {
1195 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1197 IntType(ref v) => v.fmt(f),
1198 UintType(ref v) => v.fmt(f),
1203 #[deriving(Clone, Show)]
1204 pub struct TypeParameterDef {
1205 pub ident: ast::Ident,
1206 pub def_id: ast::DefId,
1207 pub space: subst::ParamSpace,
1209 pub associated_with: Option<ast::DefId>,
1210 pub bounds: ParamBounds,
1211 pub default: Option<ty::t>,
1214 #[deriving(Encodable, Decodable, Clone, Show)]
1215 pub struct RegionParameterDef {
1216 pub name: ast::Name,
1217 pub def_id: ast::DefId,
1218 pub space: subst::ParamSpace,
1220 pub bounds: Vec<ty::Region>,
1223 /// Information about the type/lifetime parameters associated with an
1224 /// item or method. Analogous to ast::Generics.
1225 #[deriving(Clone, Show)]
1226 pub struct Generics {
1227 pub types: VecPerParamSpace<TypeParameterDef>,
1228 pub regions: VecPerParamSpace<RegionParameterDef>,
1232 pub fn empty() -> Generics {
1233 Generics { types: VecPerParamSpace::empty(),
1234 regions: VecPerParamSpace::empty() }
1237 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
1238 !self.types.is_empty_in(space)
1241 pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
1242 !self.regions.is_empty_in(space)
1247 pub fn self_ty(&self) -> ty::t {
1248 self.substs.self_ty().unwrap()
1252 /// When type checking, we use the `ParameterEnvironment` to track
1253 /// details about the type/lifetime parameters that are in scope.
1254 /// It primarily stores the bounds information.
1256 /// Note: This information might seem to be redundant with the data in
1257 /// `tcx.ty_param_defs`, but it is not. That table contains the
1258 /// parameter definitions from an "outside" perspective, but this
1259 /// struct will contain the bounds for a parameter as seen from inside
1260 /// the function body. Currently the only real distinction is that
1261 /// bound lifetime parameters are replaced with free ones, but in the
1262 /// future I hope to refine the representation of types so as to make
1263 /// more distinctions clearer.
1264 pub struct ParameterEnvironment {
1265 /// A substitution that can be applied to move from
1266 /// the "outer" view of a type or method to the "inner" view.
1267 /// In general, this means converting from bound parameters to
1268 /// free parameters. Since we currently represent bound/free type
1269 /// parameters in the same way, this only has an effect on regions.
1270 pub free_substs: Substs,
1272 /// Bounds on the various type parameters
1273 pub bounds: VecPerParamSpace<ParamBounds>,
1275 /// Each type parameter has an implicit region bound that
1276 /// indicates it must outlive at least the function body (the user
1277 /// may specify stronger requirements). This field indicates the
1278 /// region of the callee.
1279 pub implicit_region_bound: ty::Region,
1281 /// Obligations that the caller must satisfy. This is basically
1282 /// the set of bounds on the in-scope type parameters, translated
1283 /// into Obligations.
1285 /// Note: This effectively *duplicates* the `bounds` array for
1287 pub caller_obligations: VecPerParamSpace<traits::Obligation>,
1289 /// Caches the results of trait selection. This cache is used
1290 /// for things that have to do with the parameters in scope.
1291 pub selection_cache: traits::SelectionCache,
1294 impl ParameterEnvironment {
1295 pub fn for_item(cx: &ctxt, id: NodeId) -> ParameterEnvironment {
1296 match cx.map.find(id) {
1297 Some(ast_map::NodeImplItem(ref impl_item)) => {
1299 ast::MethodImplItem(ref method) => {
1300 let method_def_id = ast_util::local_def(id);
1301 match ty::impl_or_trait_item(cx, method_def_id) {
1302 MethodTraitItem(ref method_ty) => {
1303 let method_generics = &method_ty.generics;
1304 construct_parameter_environment(
1308 method.pe_body().id)
1310 TypeTraitItem(_) => {
1312 .bug("ParameterEnvironment::from_item(): \
1313 can't create a parameter environment \
1314 for type trait items")
1318 ast::TypeImplItem(_) => {
1319 cx.sess.bug("ParameterEnvironment::from_item(): \
1320 can't create a parameter environment \
1321 for type impl items")
1325 Some(ast_map::NodeTraitItem(trait_method)) => {
1326 match *trait_method {
1327 ast::RequiredMethod(ref required) => {
1328 cx.sess.span_bug(required.span,
1329 "ParameterEnvironment::from_item():
1330 can't create a parameter \
1331 environment for required trait \
1334 ast::ProvidedMethod(ref method) => {
1335 let method_def_id = ast_util::local_def(id);
1336 match ty::impl_or_trait_item(cx, method_def_id) {
1337 MethodTraitItem(ref method_ty) => {
1338 let method_generics = &method_ty.generics;
1339 construct_parameter_environment(
1343 method.pe_body().id)
1345 TypeTraitItem(_) => {
1347 .bug("ParameterEnvironment::from_item(): \
1348 can't create a parameter environment \
1349 for type trait items")
1353 ast::TypeTraitItem(_) => {
1354 cx.sess.bug("ParameterEnvironment::from_item(): \
1355 can't create a parameter environment \
1356 for type trait items")
1360 Some(ast_map::NodeItem(item)) => {
1362 ast::ItemFn(_, _, _, _, ref body) => {
1363 // We assume this is a function.
1364 let fn_def_id = ast_util::local_def(id);
1365 let fn_pty = ty::lookup_item_type(cx, fn_def_id);
1367 construct_parameter_environment(cx,
1373 ast::ItemStruct(..) |
1375 ast::ItemStatic(..) => {
1376 let def_id = ast_util::local_def(id);
1377 let pty = ty::lookup_item_type(cx, def_id);
1378 construct_parameter_environment(cx, item.span,
1382 cx.sess.span_bug(item.span,
1383 "ParameterEnvironment::from_item():
1384 can't create a parameter \
1385 environment for this kind of item")
1390 cx.sess.bug(format!("ParameterEnvironment::from_item(): \
1391 `{}` is not an item",
1392 cx.map.node_to_string(id)).as_slice())
1400 /// - `generics`: the set of type parameters and their bounds
1401 /// - `ty`: the base types, which may reference the parameters defined
1403 #[deriving(Clone, Show)]
1404 pub struct Polytype {
1405 pub generics: Generics,
1409 /// As `Polytype` but for a trait ref.
1410 pub struct TraitDef {
1411 /// Generic type definitions. Note that `Self` is listed in here
1412 /// as having a single bound, the trait itself (e.g., in the trait
1413 /// `Eq`, there is a single bound `Self : Eq`). This is so that
1414 /// default methods get to assume that the `Self` parameters
1415 /// implements the trait.
1416 pub generics: Generics,
1418 /// The "supertrait" bounds.
1419 pub bounds: ParamBounds,
1420 pub trait_ref: Rc<ty::TraitRef>,
1423 /// Records the substitutions used to translate the polytype for an
1424 /// item into the monotype of an item reference.
1426 pub struct ItemSubsts {
1430 pub type type_cache = RefCell<DefIdMap<Polytype>>;
1432 pub type node_type_table = RefCell<HashMap<uint,t>>;
1434 /// Records information about each unboxed closure.
1436 pub struct UnboxedClosure {
1437 /// The type of the unboxed closure.
1438 pub closure_type: ClosureTy,
1439 /// The kind of unboxed closure this is.
1440 pub kind: UnboxedClosureKind,
1443 #[deriving(Clone, PartialEq, Eq)]
1444 pub enum UnboxedClosureKind {
1445 FnUnboxedClosureKind,
1446 FnMutUnboxedClosureKind,
1447 FnOnceUnboxedClosureKind,
1450 impl UnboxedClosureKind {
1451 pub fn trait_did(&self, cx: &ctxt) -> ast::DefId {
1452 let result = match *self {
1453 FnUnboxedClosureKind => cx.lang_items.require(FnTraitLangItem),
1454 FnMutUnboxedClosureKind => {
1455 cx.lang_items.require(FnMutTraitLangItem)
1457 FnOnceUnboxedClosureKind => {
1458 cx.lang_items.require(FnOnceTraitLangItem)
1462 Ok(trait_did) => trait_did,
1463 Err(err) => cx.sess.fatal(err.as_slice()),
1468 pub fn mk_ctxt<'tcx>(s: Session,
1469 type_arena: &'tcx TypedArena<t_box_>,
1470 dm: resolve::DefMap,
1471 named_region_map: resolve_lifetime::NamedRegionMap,
1472 map: ast_map::Map<'tcx>,
1473 freevars: RefCell<FreevarMap>,
1474 capture_modes: RefCell<CaptureModeMap>,
1475 region_maps: middle::region::RegionMaps,
1476 lang_items: middle::lang_items::LanguageItems,
1477 stability: stability::Index) -> ctxt<'tcx> {
1479 type_arena: type_arena,
1480 interner: RefCell::new(FnvHashMap::new()),
1481 named_region_map: named_region_map,
1482 item_variance_map: RefCell::new(DefIdMap::new()),
1483 variance_computed: Cell::new(false),
1484 next_id: Cell::new(primitives::LAST_PRIMITIVE_ID),
1487 region_maps: region_maps,
1488 node_types: RefCell::new(HashMap::new()),
1489 item_substs: RefCell::new(NodeMap::new()),
1490 trait_refs: RefCell::new(NodeMap::new()),
1491 trait_defs: RefCell::new(DefIdMap::new()),
1492 object_cast_map: RefCell::new(NodeMap::new()),
1494 intrinsic_defs: RefCell::new(DefIdMap::new()),
1496 tcache: RefCell::new(DefIdMap::new()),
1497 rcache: RefCell::new(HashMap::new()),
1498 short_names_cache: RefCell::new(HashMap::new()),
1499 needs_unwind_cleanup_cache: RefCell::new(HashMap::new()),
1500 tc_cache: RefCell::new(HashMap::new()),
1501 ast_ty_to_ty_cache: RefCell::new(NodeMap::new()),
1502 enum_var_cache: RefCell::new(DefIdMap::new()),
1503 impl_or_trait_items: RefCell::new(DefIdMap::new()),
1504 trait_item_def_ids: RefCell::new(DefIdMap::new()),
1505 trait_items_cache: RefCell::new(DefIdMap::new()),
1506 impl_trait_cache: RefCell::new(DefIdMap::new()),
1507 ty_param_defs: RefCell::new(NodeMap::new()),
1508 adjustments: RefCell::new(NodeMap::new()),
1509 normalized_cache: RefCell::new(HashMap::new()),
1510 lang_items: lang_items,
1511 provided_method_sources: RefCell::new(DefIdMap::new()),
1512 superstructs: RefCell::new(DefIdMap::new()),
1513 struct_fields: RefCell::new(DefIdMap::new()),
1514 destructor_for_type: RefCell::new(DefIdMap::new()),
1515 destructors: RefCell::new(DefIdSet::new()),
1516 trait_impls: RefCell::new(DefIdMap::new()),
1517 inherent_impls: RefCell::new(DefIdMap::new()),
1518 impl_items: RefCell::new(DefIdMap::new()),
1519 used_unsafe: RefCell::new(NodeSet::new()),
1520 used_mut_nodes: RefCell::new(NodeSet::new()),
1521 populated_external_types: RefCell::new(DefIdSet::new()),
1522 populated_external_traits: RefCell::new(DefIdSet::new()),
1523 upvar_borrow_map: RefCell::new(HashMap::new()),
1524 extern_const_statics: RefCell::new(DefIdMap::new()),
1525 extern_const_variants: RefCell::new(DefIdMap::new()),
1526 method_map: RefCell::new(FnvHashMap::new()),
1527 dependency_formats: RefCell::new(HashMap::new()),
1528 unboxed_closures: RefCell::new(DefIdMap::new()),
1529 node_lint_levels: RefCell::new(HashMap::new()),
1530 transmute_restrictions: RefCell::new(Vec::new()),
1531 stability: RefCell::new(stability),
1532 capture_modes: capture_modes,
1533 associated_types: RefCell::new(DefIdMap::new()),
1534 trait_associated_types: RefCell::new(DefIdMap::new()),
1535 selection_cache: traits::SelectionCache::new(),
1539 // Type constructors
1541 // Interns a type/name combination, stores the resulting box in cx.interner,
1542 // and returns the box as cast to an unsafe ptr (see comments for t above).
1543 pub fn mk_t(cx: &ctxt, st: sty) -> t {
1544 // Check for primitive types.
1546 ty_nil => return mk_nil(),
1547 ty_err => return mk_err(),
1548 ty_bool => return mk_bool(),
1549 ty_int(i) => return mk_mach_int(i),
1550 ty_uint(u) => return mk_mach_uint(u),
1551 ty_float(f) => return mk_mach_float(f),
1552 ty_char => return mk_char(),
1553 ty_bot => return mk_bot(),
1557 let key = intern_key { sty: &st };
1559 match cx.interner.borrow().find(&key) {
1560 Some(t) => unsafe { return mem::transmute(&t.sty); },
1565 fn rflags(r: Region) -> uint {
1566 (has_regions as uint) | {
1568 ty::ReInfer(_) => needs_infer as uint,
1573 fn sflags(substs: &Substs) -> uint {
1575 let mut i = substs.types.iter();
1577 f |= get(*tt).flags;
1579 match substs.regions {
1580 subst::ErasedRegions => {}
1581 subst::NonerasedRegions(ref regions) => {
1582 for r in regions.iter() {
1589 fn flags_for_bounds(bounds: &ExistentialBounds) -> uint {
1590 rflags(bounds.region_bound)
1593 &ty_nil | &ty_bool | &ty_char | &ty_int(_) | &ty_float(_) | &ty_uint(_) |
1595 // You might think that we could just return ty_err for
1596 // any type containing ty_err as a component, and get
1597 // rid of the has_ty_err flag -- likewise for ty_bot (with
1598 // the exception of function types that return bot).
1599 // But doing so caused sporadic memory corruption, and
1600 // neither I (tjc) nor nmatsakis could figure out why,
1601 // so we're doing it this way.
1602 &ty_bot => flags |= has_ty_bot as uint,
1603 &ty_err => flags |= has_ty_err as uint,
1604 &ty_param(ref p) => {
1605 if p.space == subst::SelfSpace {
1606 flags |= has_self as uint;
1608 flags |= has_params as uint;
1611 &ty_unboxed_closure(_, ref region) => flags |= rflags(*region),
1612 &ty_infer(_) => flags |= needs_infer as uint,
1613 &ty_enum(_, ref substs) | &ty_struct(_, ref substs) => {
1614 flags |= sflags(substs);
1616 &ty_trait(box TyTrait { ref substs, ref bounds, .. }) => {
1617 flags |= sflags(substs);
1618 flags |= flags_for_bounds(bounds);
1620 &ty_box(tt) | &ty_uniq(tt) | &ty_vec(tt, _) | &ty_open(tt) => {
1621 flags |= get(tt).flags
1624 flags |= get(m.ty).flags;
1626 &ty_rptr(r, ref m) => {
1628 flags |= get(m.ty).flags;
1630 &ty_tup(ref ts) => for tt in ts.iter() { flags |= get(*tt).flags; },
1631 &ty_bare_fn(ref f) => {
1632 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1633 flags |= get(f.sig.output).flags;
1634 // T -> _|_ is *not* _|_ !
1635 flags &= !(has_ty_bot as uint);
1637 &ty_closure(ref f) => {
1639 RegionTraitStore(r, _) => {
1644 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1645 flags |= get(f.sig.output).flags;
1646 // T -> _|_ is *not* _|_ !
1647 flags &= !(has_ty_bot as uint);
1648 flags |= flags_for_bounds(&f.bounds);
1652 let t = cx.type_arena.alloc(t_box_ {
1654 id: cx.next_id.get(),
1658 let sty_ptr = &t.sty as *const sty;
1660 let key = intern_key {
1664 cx.interner.borrow_mut().insert(key, t);
1666 cx.next_id.set(cx.next_id.get() + 1);
1669 mem::transmute::<*const sty, t>(sty_ptr)
1674 pub fn mk_prim_t(primitive: &'static t_box_) -> t {
1676 mem::transmute::<&'static t_box_, t>(primitive)
1681 pub fn mk_nil() -> t { mk_prim_t(&primitives::TY_NIL) }
1684 pub fn mk_err() -> t { mk_prim_t(&primitives::TY_ERR) }
1687 pub fn mk_bot() -> t { mk_prim_t(&primitives::TY_BOT) }
1690 pub fn mk_bool() -> t { mk_prim_t(&primitives::TY_BOOL) }
1693 pub fn mk_int() -> t { mk_prim_t(&primitives::TY_INT) }
1696 pub fn mk_i8() -> t { mk_prim_t(&primitives::TY_I8) }
1699 pub fn mk_i16() -> t { mk_prim_t(&primitives::TY_I16) }
1702 pub fn mk_i32() -> t { mk_prim_t(&primitives::TY_I32) }
1705 pub fn mk_i64() -> t { mk_prim_t(&primitives::TY_I64) }
1708 pub fn mk_f32() -> t { mk_prim_t(&primitives::TY_F32) }
1711 pub fn mk_f64() -> t { mk_prim_t(&primitives::TY_F64) }
1714 pub fn mk_uint() -> t { mk_prim_t(&primitives::TY_UINT) }
1717 pub fn mk_u8() -> t { mk_prim_t(&primitives::TY_U8) }
1720 pub fn mk_u16() -> t { mk_prim_t(&primitives::TY_U16) }
1723 pub fn mk_u32() -> t { mk_prim_t(&primitives::TY_U32) }
1726 pub fn mk_u64() -> t { mk_prim_t(&primitives::TY_U64) }
1728 pub fn mk_mach_int(tm: ast::IntTy) -> t {
1730 ast::TyI => mk_int(),
1731 ast::TyI8 => mk_i8(),
1732 ast::TyI16 => mk_i16(),
1733 ast::TyI32 => mk_i32(),
1734 ast::TyI64 => mk_i64(),
1738 pub fn mk_mach_uint(tm: ast::UintTy) -> t {
1740 ast::TyU => mk_uint(),
1741 ast::TyU8 => mk_u8(),
1742 ast::TyU16 => mk_u16(),
1743 ast::TyU32 => mk_u32(),
1744 ast::TyU64 => mk_u64(),
1748 pub fn mk_mach_float(tm: ast::FloatTy) -> t {
1750 ast::TyF32 => mk_f32(),
1751 ast::TyF64 => mk_f64(),
1756 pub fn mk_char() -> t { mk_prim_t(&primitives::TY_CHAR) }
1758 pub fn mk_str(cx: &ctxt) -> t {
1762 pub fn mk_str_slice(cx: &ctxt, r: Region, m: ast::Mutability) -> t {
1765 ty: mk_t(cx, ty_str),
1770 pub fn mk_enum(cx: &ctxt, did: ast::DefId, substs: Substs) -> t {
1771 // take a copy of substs so that we own the vectors inside
1772 mk_t(cx, ty_enum(did, substs))
1775 pub fn mk_box(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_box(ty)) }
1777 pub fn mk_uniq(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_uniq(ty)) }
1779 pub fn mk_ptr(cx: &ctxt, tm: mt) -> t { mk_t(cx, ty_ptr(tm)) }
1781 pub fn mk_rptr(cx: &ctxt, r: Region, tm: mt) -> t { mk_t(cx, ty_rptr(r, tm)) }
1783 pub fn mk_mut_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1784 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
1786 pub fn mk_imm_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1787 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
1790 pub fn mk_mut_ptr(cx: &ctxt, ty: t) -> t {
1791 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
1794 pub fn mk_imm_ptr(cx: &ctxt, ty: t) -> t {
1795 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
1798 pub fn mk_nil_ptr(cx: &ctxt) -> t {
1799 mk_ptr(cx, mt {ty: mk_nil(), mutbl: ast::MutImmutable})
1802 pub fn mk_vec(cx: &ctxt, t: t, sz: Option<uint>) -> t {
1803 mk_t(cx, ty_vec(t, sz))
1806 pub fn mk_slice(cx: &ctxt, r: Region, tm: mt) -> t {
1809 ty: mk_vec(cx, tm.ty, None),
1814 pub fn mk_tup(cx: &ctxt, ts: Vec<t>) -> t { mk_t(cx, ty_tup(ts)) }
1816 pub fn mk_closure(cx: &ctxt, fty: ClosureTy) -> t {
1817 mk_t(cx, ty_closure(box fty))
1820 pub fn mk_bare_fn(cx: &ctxt, fty: BareFnTy) -> t {
1821 mk_t(cx, ty_bare_fn(fty))
1824 pub fn mk_ctor_fn(cx: &ctxt,
1825 binder_id: ast::NodeId,
1826 input_tys: &[ty::t],
1827 output: ty::t) -> t {
1828 let input_args = input_tys.iter().map(|t| *t).collect();
1831 fn_style: ast::NormalFn,
1834 binder_id: binder_id,
1843 pub fn mk_trait(cx: &ctxt,
1846 bounds: ExistentialBounds)
1848 // take a copy of substs so that we own the vectors inside
1849 let inner = box TyTrait {
1854 mk_t(cx, ty_trait(inner))
1857 pub fn mk_struct(cx: &ctxt, struct_id: ast::DefId, substs: Substs) -> t {
1858 // take a copy of substs so that we own the vectors inside
1859 mk_t(cx, ty_struct(struct_id, substs))
1862 pub fn mk_unboxed_closure(cx: &ctxt, closure_id: ast::DefId, region: Region)
1864 mk_t(cx, ty_unboxed_closure(closure_id, region))
1867 pub fn mk_var(cx: &ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) }
1869 pub fn mk_int_var(cx: &ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) }
1871 pub fn mk_float_var(cx: &ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) }
1873 pub fn mk_infer(cx: &ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) }
1875 pub fn mk_param(cx: &ctxt, space: subst::ParamSpace, n: uint, k: DefId) -> t {
1876 mk_t(cx, ty_param(ParamTy { space: space, idx: n, def_id: k }))
1879 pub fn mk_self_type(cx: &ctxt, did: ast::DefId) -> t {
1880 mk_param(cx, subst::SelfSpace, 0, did)
1883 pub fn mk_param_from_def(cx: &ctxt, def: &TypeParameterDef) -> t {
1884 mk_param(cx, def.space, def.index, def.def_id)
1887 pub fn mk_open(cx: &ctxt, t: t) -> t { mk_t(cx, ty_open(t)) }
1889 pub fn walk_ty(ty: t, f: |t|) {
1890 maybe_walk_ty(ty, |t| { f(t); true });
1893 pub fn maybe_walk_ty(ty: t, f: |t| -> bool) {
1898 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) |
1899 ty_str | ty_infer(_) | ty_param(_) | ty_unboxed_closure(_, _) | ty_err => {}
1900 ty_box(ty) | ty_uniq(ty) | ty_vec(ty, _) | ty_open(ty) => maybe_walk_ty(ty, f),
1901 ty_ptr(ref tm) | ty_rptr(_, ref tm) => {
1902 maybe_walk_ty(tm.ty, f);
1904 ty_enum(_, ref substs) | ty_struct(_, ref substs) |
1905 ty_trait(box TyTrait { ref substs, .. }) => {
1906 for subty in (*substs).types.iter() {
1907 maybe_walk_ty(*subty, |x| f(x));
1910 ty_tup(ref ts) => { for tt in ts.iter() { maybe_walk_ty(*tt, |x| f(x)); } }
1911 ty_bare_fn(ref ft) => {
1912 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1913 maybe_walk_ty(ft.sig.output, f);
1915 ty_closure(ref ft) => {
1916 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1917 maybe_walk_ty(ft.sig.output, f);
1922 // Folds types from the bottom up.
1923 pub fn fold_ty(cx: &ctxt, t0: t, fldop: |t| -> t) -> t {
1924 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
1929 pub fn new(space: subst::ParamSpace,
1933 ParamTy { space: space, idx: index, def_id: def_id }
1936 pub fn for_self(trait_def_id: ast::DefId) -> ParamTy {
1937 ParamTy::new(subst::SelfSpace, 0, trait_def_id)
1940 pub fn for_def(def: &TypeParameterDef) -> ParamTy {
1941 ParamTy::new(def.space, def.index, def.def_id)
1944 pub fn to_ty(self, tcx: &ty::ctxt) -> ty::t {
1945 ty::mk_param(tcx, self.space, self.idx, self.def_id)
1948 pub fn is_self(&self) -> bool {
1949 self.space == subst::SelfSpace && self.idx == 0
1954 pub fn empty() -> ItemSubsts {
1955 ItemSubsts { substs: Substs::empty() }
1958 pub fn is_noop(&self) -> bool {
1959 self.substs.is_noop()
1965 pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil }
1967 pub fn type_is_bot(ty: t) -> bool {
1968 (get(ty).flags & (has_ty_bot as uint)) != 0
1971 pub fn type_is_error(ty: t) -> bool {
1972 (get(ty).flags & (has_ty_err as uint)) != 0
1975 pub fn type_needs_subst(ty: t) -> bool {
1976 tbox_has_flag(get(ty), needs_subst)
1979 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
1980 tref.substs.types.any(|&t| type_is_error(t))
1983 pub fn type_is_ty_var(ty: t) -> bool {
1985 ty_infer(TyVar(_)) => true,
1990 pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool }
1992 pub fn type_is_self(ty: t) -> bool {
1994 ty_param(ref p) => p.space == subst::SelfSpace,
1999 fn type_is_slice(ty: t) -> bool {
2001 ty_ptr(mt) | ty_rptr(_, mt) => match get(mt.ty).sty {
2002 ty_vec(_, None) | ty_str => true,
2009 pub fn type_is_vec(ty: t) -> bool {
2012 ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) |
2013 ty_box(t) | ty_uniq(t) => match get(t).sty {
2014 ty_vec(_, None) => true,
2021 pub fn type_is_structural(ty: t) -> bool {
2023 ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) |
2024 ty_vec(_, Some(_)) | ty_unboxed_closure(..) => true,
2025 _ => type_is_slice(ty) | type_is_trait(ty)
2029 pub fn type_is_simd(cx: &ctxt, ty: t) -> bool {
2031 ty_struct(did, _) => lookup_simd(cx, did),
2036 pub fn sequence_element_type(cx: &ctxt, ty: t) -> t {
2038 ty_vec(ty, _) => ty,
2039 ty_str => mk_mach_uint(ast::TyU8),
2040 ty_open(ty) => sequence_element_type(cx, ty),
2041 _ => cx.sess.bug(format!("sequence_element_type called on non-sequence value: {}",
2042 ty_to_string(cx, ty)).as_slice()),
2046 pub fn simd_type(cx: &ctxt, ty: t) -> t {
2048 ty_struct(did, ref substs) => {
2049 let fields = lookup_struct_fields(cx, did);
2050 lookup_field_type(cx, did, fields.get(0).id, substs)
2052 _ => fail!("simd_type called on invalid type")
2056 pub fn simd_size(cx: &ctxt, ty: t) -> uint {
2058 ty_struct(did, _) => {
2059 let fields = lookup_struct_fields(cx, did);
2062 _ => fail!("simd_size called on invalid type")
2066 pub fn type_is_boxed(ty: t) -> bool {
2073 pub fn type_is_region_ptr(ty: t) -> bool {
2075 ty_rptr(..) => true,
2080 pub fn type_is_unsafe_ptr(ty: t) -> bool {
2082 ty_ptr(_) => return true,
2087 pub fn type_is_unique(ty: t) -> bool {
2089 ty_uniq(_) => match get(ty).sty {
2090 ty_trait(..) => false,
2097 pub fn type_is_fat_ptr(cx: &ctxt, ty: t) -> bool {
2099 ty_ptr(mt{ty, ..}) | ty_rptr(_, mt{ty, ..})
2100 | ty_uniq(ty) if !type_is_sized(cx, ty) => true,
2106 A scalar type is one that denotes an atomic datum, with no sub-components.
2107 (A ty_ptr is scalar because it represents a non-managed pointer, so its
2108 contents are abstract to rustc.)
2110 pub fn type_is_scalar(ty: t) -> bool {
2112 ty_nil | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
2113 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
2114 ty_bare_fn(..) | ty_ptr(_) => true,
2119 /// Returns true if this type is a floating point type and false otherwise.
2120 pub fn type_is_floating_point(ty: t) -> bool {
2122 ty_float(_) => true,
2127 pub fn type_needs_drop(cx: &ctxt, ty: t) -> bool {
2128 type_contents(cx, ty).needs_drop(cx)
2131 // Some things don't need cleanups during unwinding because the
2132 // task can free them all at once later. Currently only things
2133 // that only contain scalars and shared boxes can avoid unwind
2135 pub fn type_needs_unwind_cleanup(cx: &ctxt, ty: t) -> bool {
2136 match cx.needs_unwind_cleanup_cache.borrow().find(&ty) {
2137 Some(&result) => return result,
2141 let mut tycache = HashSet::new();
2142 let needs_unwind_cleanup =
2143 type_needs_unwind_cleanup_(cx, ty, &mut tycache, false);
2144 cx.needs_unwind_cleanup_cache.borrow_mut().insert(ty, needs_unwind_cleanup);
2145 return needs_unwind_cleanup;
2148 fn type_needs_unwind_cleanup_(cx: &ctxt, ty: t,
2149 tycache: &mut HashSet<t>,
2150 encountered_box: bool) -> bool {
2152 // Prevent infinite recursion
2153 if !tycache.insert(ty) {
2157 let mut encountered_box = encountered_box;
2158 let mut needs_unwind_cleanup = false;
2159 maybe_walk_ty(ty, |ty| {
2160 let old_encountered_box = encountered_box;
2161 let result = match get(ty).sty {
2163 encountered_box = true;
2166 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2167 ty_tup(_) | ty_ptr(_) => {
2170 ty_enum(did, ref substs) => {
2171 for v in (*enum_variants(cx, did)).iter() {
2172 for aty in v.args.iter() {
2173 let t = aty.subst(cx, substs);
2174 needs_unwind_cleanup |=
2175 type_needs_unwind_cleanup_(cx, t, tycache,
2179 !needs_unwind_cleanup
2182 // Once we're inside a box, the annihilator will find
2183 // it and destroy it.
2184 if !encountered_box {
2185 needs_unwind_cleanup = true;
2192 needs_unwind_cleanup = true;
2197 encountered_box = old_encountered_box;
2201 return needs_unwind_cleanup;
2205 * Type contents is how the type checker reasons about kinds.
2206 * They track what kinds of things are found within a type. You can
2207 * think of them as kind of an "anti-kind". They track the kinds of values
2208 * and thinks that are contained in types. Having a larger contents for
2209 * a type tends to rule that type *out* from various kinds. For example,
2210 * a type that contains a reference is not sendable.
2212 * The reason we compute type contents and not kinds is that it is
2213 * easier for me (nmatsakis) to think about what is contained within
2214 * a type than to think about what is *not* contained within a type.
2216 pub struct TypeContents {
2220 macro_rules! def_type_content_sets(
2221 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
2222 #[allow(non_snake_case)]
2224 use middle::ty::TypeContents;
2225 $(pub static $name: TypeContents = TypeContents { bits: $bits };)+
2230 def_type_content_sets!(
2232 None = 0b0000_0000__0000_0000__0000,
2234 // Things that are interior to the value (first nibble):
2235 InteriorUnsized = 0b0000_0000__0000_0000__0001,
2236 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
2237 // InteriorAll = 0b00000000__00000000__1111,
2239 // Things that are owned by the value (second and third nibbles):
2240 OwnsOwned = 0b0000_0000__0000_0001__0000,
2241 OwnsDtor = 0b0000_0000__0000_0010__0000,
2242 OwnsManaged /* see [1] below */ = 0b0000_0000__0000_0100__0000,
2243 OwnsAffine = 0b0000_0000__0000_1000__0000,
2244 OwnsAll = 0b0000_0000__1111_1111__0000,
2246 // Things that are reachable by the value in any way (fourth nibble):
2247 ReachesBorrowed = 0b0000_0010__0000_0000__0000,
2248 // ReachesManaged /* see [1] below */ = 0b0000_0100__0000_0000__0000,
2249 ReachesMutable = 0b0000_1000__0000_0000__0000,
2250 ReachesFfiUnsafe = 0b0010_0000__0000_0000__0000,
2251 ReachesAll = 0b0011_1111__0000_0000__0000,
2253 // Things that cause values to *move* rather than *copy*. This
2254 // is almost the same as the `Copy` trait, but for managed
2255 // data -- atm, we consider managed data to copy, not move,
2256 // but it does not impl Copy as a pure memcpy is not good
2258 Moves = 0b0000_0000__0000_1011__0000,
2260 // Things that mean drop glue is necessary
2261 NeedsDrop = 0b0000_0000__0000_0111__0000,
2263 // Things that prevent values from being considered sized
2264 Nonsized = 0b0000_0000__0000_0000__0001,
2266 // Things that make values considered not POD (would be same
2267 // as `Moves`, but for the fact that managed data `@` is
2268 // not considered POD)
2269 Noncopy = 0b0000_0000__0000_1111__0000,
2271 // Bits to set when a managed value is encountered
2273 // [1] Do not set the bits TC::OwnsManaged or
2274 // TC::ReachesManaged directly, instead reference
2275 // TC::Managed to set them both at once.
2276 Managed = 0b0000_0100__0000_0100__0000,
2279 All = 0b1111_1111__1111_1111__1111
2284 pub fn when(&self, cond: bool) -> TypeContents {
2285 if cond {*self} else {TC::None}
2288 pub fn intersects(&self, tc: TypeContents) -> bool {
2289 (self.bits & tc.bits) != 0
2292 pub fn owns_managed(&self) -> bool {
2293 self.intersects(TC::OwnsManaged)
2296 pub fn owns_owned(&self) -> bool {
2297 self.intersects(TC::OwnsOwned)
2300 pub fn is_sized(&self, _: &ctxt) -> bool {
2301 !self.intersects(TC::Nonsized)
2304 pub fn interior_unsafe(&self) -> bool {
2305 self.intersects(TC::InteriorUnsafe)
2308 pub fn interior_unsized(&self) -> bool {
2309 self.intersects(TC::InteriorUnsized)
2312 pub fn moves_by_default(&self, _: &ctxt) -> bool {
2313 self.intersects(TC::Moves)
2316 pub fn needs_drop(&self, _: &ctxt) -> bool {
2317 self.intersects(TC::NeedsDrop)
2320 pub fn owned_pointer(&self) -> TypeContents {
2322 * Includes only those bits that still apply
2323 * when indirected through a `Box` pointer
2326 *self & (TC::OwnsAll | TC::ReachesAll))
2329 pub fn reference(&self, bits: TypeContents) -> TypeContents {
2331 * Includes only those bits that still apply
2332 * when indirected through a reference (`&`)
2335 *self & TC::ReachesAll)
2338 pub fn managed_pointer(&self) -> TypeContents {
2340 * Includes only those bits that still apply
2341 * when indirected through a managed pointer (`@`)
2344 *self & TC::ReachesAll)
2347 pub fn unsafe_pointer(&self) -> TypeContents {
2349 * Includes only those bits that still apply
2350 * when indirected through an unsafe pointer (`*`)
2352 *self & TC::ReachesAll
2355 pub fn union<T>(v: &[T], f: |&T| -> TypeContents) -> TypeContents {
2356 v.iter().fold(TC::None, |tc, t| tc | f(t))
2359 pub fn has_dtor(&self) -> bool {
2360 self.intersects(TC::OwnsDtor)
2364 impl ops::BitOr<TypeContents,TypeContents> for TypeContents {
2365 fn bitor(&self, other: &TypeContents) -> TypeContents {
2366 TypeContents {bits: self.bits | other.bits}
2370 impl ops::BitAnd<TypeContents,TypeContents> for TypeContents {
2371 fn bitand(&self, other: &TypeContents) -> TypeContents {
2372 TypeContents {bits: self.bits & other.bits}
2376 impl ops::Sub<TypeContents,TypeContents> for TypeContents {
2377 fn sub(&self, other: &TypeContents) -> TypeContents {
2378 TypeContents {bits: self.bits & !other.bits}
2382 impl fmt::Show for TypeContents {
2383 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2384 write!(f, "TypeContents({:t})", self.bits)
2388 pub fn type_interior_is_unsafe(cx: &ctxt, t: ty::t) -> bool {
2389 type_contents(cx, t).interior_unsafe()
2392 pub fn type_contents(cx: &ctxt, ty: t) -> TypeContents {
2393 let ty_id = type_id(ty);
2395 match cx.tc_cache.borrow().find(&ty_id) {
2396 Some(tc) => { return *tc; }
2400 let mut cache = HashMap::new();
2401 let result = tc_ty(cx, ty, &mut cache);
2403 cx.tc_cache.borrow_mut().insert(ty_id, result);
2408 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2410 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
2411 // private cache for this walk. This is needed in the case of cyclic
2414 // struct List { next: Box<Option<List>>, ... }
2416 // When computing the type contents of such a type, we wind up deeply
2417 // recursing as we go. So when we encounter the recursive reference
2418 // to List, we temporarily use TC::None as its contents. Later we'll
2419 // patch up the cache with the correct value, once we've computed it
2420 // (this is basically a co-inductive process, if that helps). So in
2421 // the end we'll compute TC::OwnsOwned, in this case.
2423 // The problem is, as we are doing the computation, we will also
2424 // compute an *intermediate* contents for, e.g., Option<List> of
2425 // TC::None. This is ok during the computation of List itself, but if
2426 // we stored this intermediate value into cx.tc_cache, then later
2427 // requests for the contents of Option<List> would also yield TC::None
2428 // which is incorrect. This value was computed based on the crutch
2429 // value for the type contents of list. The correct value is
2430 // TC::OwnsOwned. This manifested as issue #4821.
2431 let ty_id = type_id(ty);
2432 match cache.find(&ty_id) {
2433 Some(tc) => { return *tc; }
2436 match cx.tc_cache.borrow().find(&ty_id) { // Must check both caches!
2437 Some(tc) => { return *tc; }
2440 cache.insert(ty_id, TC::None);
2442 let result = match get(ty).sty {
2443 // uint and int are ffi-unsafe
2444 ty_uint(ast::TyU) | ty_int(ast::TyI) => {
2445 TC::ReachesFfiUnsafe
2448 // Scalar and unique types are sendable, and durable
2449 ty_infer(ty::SkolemizedIntTy(_)) |
2450 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2451 ty_bare_fn(_) | ty::ty_char => {
2455 ty_closure(ref c) => {
2456 closure_contents(cx, &**c) | TC::ReachesFfiUnsafe
2460 tc_ty(cx, typ, cache).managed_pointer() | TC::ReachesFfiUnsafe
2464 TC::ReachesFfiUnsafe | match get(typ).sty {
2465 ty_str => TC::OwnsOwned,
2466 _ => tc_ty(cx, typ, cache).owned_pointer(),
2470 ty_trait(box TyTrait { bounds, .. }) => {
2471 object_contents(cx, bounds) | TC::ReachesFfiUnsafe | TC::Nonsized
2475 tc_ty(cx, mt.ty, cache).unsafe_pointer()
2478 ty_rptr(r, ref mt) => {
2479 TC::ReachesFfiUnsafe | match get(mt.ty).sty {
2480 ty_str => borrowed_contents(r, ast::MutImmutable),
2481 ty_vec(..) => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(r, mt.mutbl)),
2482 _ => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(r, mt.mutbl)),
2486 ty_vec(t, Some(_)) => {
2490 ty_vec(t, None) => {
2491 tc_ty(cx, t, cache) | TC::Nonsized
2493 ty_str => TC::Nonsized,
2495 ty_struct(did, ref substs) => {
2496 let flds = struct_fields(cx, did, substs);
2498 TypeContents::union(flds.as_slice(),
2499 |f| tc_mt(cx, f.mt, cache));
2501 if !lookup_repr_hints(cx, did).contains(&attr::ReprExtern) {
2502 res = res | TC::ReachesFfiUnsafe;
2505 if ty::has_dtor(cx, did) {
2506 res = res | TC::OwnsDtor;
2508 apply_lang_items(cx, did, res)
2511 ty_unboxed_closure(did, r) => {
2512 // FIXME(#14449): `borrowed_contents` below assumes `&mut`
2514 let upvars = unboxed_closure_upvars(cx, did);
2515 TypeContents::union(upvars.as_slice(),
2516 |f| tc_ty(cx, f.ty, cache)) |
2517 borrowed_contents(r, MutMutable)
2520 ty_tup(ref tys) => {
2521 TypeContents::union(tys.as_slice(),
2522 |ty| tc_ty(cx, *ty, cache))
2525 ty_enum(did, ref substs) => {
2526 let variants = substd_enum_variants(cx, did, substs);
2528 TypeContents::union(variants.as_slice(), |variant| {
2529 TypeContents::union(variant.args.as_slice(),
2531 tc_ty(cx, *arg_ty, cache)
2535 if ty::has_dtor(cx, did) {
2536 res = res | TC::OwnsDtor;
2539 if variants.len() != 0 {
2540 let repr_hints = lookup_repr_hints(cx, did);
2541 if repr_hints.len() > 1 {
2542 // this is an error later on, but this type isn't safe
2543 res = res | TC::ReachesFfiUnsafe;
2546 match repr_hints.as_slice().get(0) {
2547 Some(h) => if !h.is_ffi_safe() {
2548 res = res | TC::ReachesFfiUnsafe;
2552 res = res | TC::ReachesFfiUnsafe;
2554 // We allow ReprAny enums if they are eligible for
2555 // the nullable pointer optimization and the
2556 // contained type is an `extern fn`
2558 if variants.len() == 2 {
2559 let mut data_idx = 0;
2561 if variants.get(0).args.len() == 0 {
2565 if variants.get(data_idx).args.len() == 1 {
2566 match get(*variants.get(data_idx).args.get(0)).sty {
2567 ty_bare_fn(..) => { res = res - TC::ReachesFfiUnsafe; }
2577 apply_lang_items(cx, did, res)
2581 // We only ever ask for the kind of types that are defined in
2582 // the current crate; therefore, the only type parameters that
2583 // could be in scope are those defined in the current crate.
2584 // If this assertion failures, it is likely because of a
2585 // failure in the cross-crate inlining code to translate a
2587 assert_eq!(p.def_id.krate, ast::LOCAL_CRATE);
2589 let ty_param_defs = cx.ty_param_defs.borrow();
2590 let tp_def = ty_param_defs.get(&p.def_id.node);
2591 kind_bounds_to_contents(
2593 tp_def.bounds.builtin_bounds,
2594 tp_def.bounds.trait_bounds.as_slice())
2598 // This occurs during coherence, but shouldn't occur at other
2604 let result = tc_ty(cx, t, cache);
2605 assert!(!result.is_sized(cx))
2606 result.unsafe_pointer() | TC::Nonsized
2610 cx.sess.bug("asked to compute contents of error type");
2614 cache.insert(ty_id, result);
2620 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2622 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
2623 mc | tc_ty(cx, mt.ty, cache)
2626 fn apply_lang_items(cx: &ctxt,
2631 if Some(did) == cx.lang_items.managed_bound() {
2633 } else if Some(did) == cx.lang_items.no_copy_bound() {
2635 } else if Some(did) == cx.lang_items.unsafe_type() {
2636 tc | TC::InteriorUnsafe
2642 fn borrowed_contents(region: ty::Region,
2643 mutbl: ast::Mutability)
2646 * Type contents due to containing a reference
2647 * with the region `region` and borrow kind `bk`
2650 let b = match mutbl {
2651 ast::MutMutable => TC::ReachesMutable | TC::OwnsAffine,
2652 ast::MutImmutable => TC::None,
2654 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
2657 fn closure_contents(cx: &ctxt, cty: &ClosureTy) -> TypeContents {
2658 // Closure contents are just like trait contents, but with potentially
2660 let st = object_contents(cx, cty.bounds);
2662 let st = match cty.store {
2666 RegionTraitStore(r, mutbl) => {
2667 st.reference(borrowed_contents(r, mutbl))
2671 // This also prohibits "@once fn" from being copied, which allows it to
2672 // be called. Neither way really makes much sense.
2673 let ot = match cty.onceness {
2674 ast::Once => TC::OwnsAffine,
2675 ast::Many => TC::None,
2681 fn object_contents(cx: &ctxt,
2682 bounds: ExistentialBounds)
2684 // These are the type contents of the (opaque) interior
2685 kind_bounds_to_contents(cx, bounds.builtin_bounds, [])
2688 fn kind_bounds_to_contents(cx: &ctxt,
2689 bounds: BuiltinBounds,
2690 traits: &[Rc<TraitRef>])
2692 let _i = indenter();
2693 let mut tc = TC::All;
2694 each_inherited_builtin_bound(cx, bounds, traits, |bound| {
2695 tc = tc - match bound {
2696 BoundSync | BoundSend => TC::None,
2697 BoundSized => TC::Nonsized,
2698 BoundCopy => TC::Noncopy,
2703 // Iterates over all builtin bounds on the type parameter def, including
2704 // those inherited from traits with builtin-kind-supertraits.
2705 fn each_inherited_builtin_bound(cx: &ctxt,
2706 bounds: BuiltinBounds,
2707 traits: &[Rc<TraitRef>],
2708 f: |BuiltinBound|) {
2709 for bound in bounds.iter() {
2713 each_bound_trait_and_supertraits(cx, traits, |trait_ref| {
2714 let trait_def = lookup_trait_def(cx, trait_ref.def_id);
2715 for bound in trait_def.bounds.builtin_bounds.iter() {
2724 pub fn type_moves_by_default(cx: &ctxt, ty: t) -> bool {
2725 type_contents(cx, ty).moves_by_default(cx)
2728 pub fn is_ffi_safe(cx: &ctxt, ty: t) -> bool {
2729 !type_contents(cx, ty).intersects(TC::ReachesFfiUnsafe)
2732 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
2733 pub fn is_instantiable(cx: &ctxt, r_ty: t) -> bool {
2734 fn type_requires(cx: &ctxt, seen: &mut Vec<DefId>,
2735 r_ty: t, ty: t) -> bool {
2736 debug!("type_requires({}, {})?",
2737 ::util::ppaux::ty_to_string(cx, r_ty),
2738 ::util::ppaux::ty_to_string(cx, ty));
2741 get(r_ty).sty == get(ty).sty ||
2742 subtypes_require(cx, seen, r_ty, ty)
2745 debug!("type_requires({}, {})? {}",
2746 ::util::ppaux::ty_to_string(cx, r_ty),
2747 ::util::ppaux::ty_to_string(cx, ty),
2752 fn subtypes_require(cx: &ctxt, seen: &mut Vec<DefId>,
2753 r_ty: t, ty: t) -> bool {
2754 debug!("subtypes_require({}, {})?",
2755 ::util::ppaux::ty_to_string(cx, r_ty),
2756 ::util::ppaux::ty_to_string(cx, ty));
2758 let r = match get(ty).sty {
2759 // fixed length vectors need special treatment compared to
2760 // normal vectors, since they don't necessarily have the
2761 // possibility to have length zero.
2762 ty_vec(_, Some(0)) => false, // don't need no contents
2763 ty_vec(ty, Some(_)) => type_requires(cx, seen, r_ty, ty),
2778 ty_vec(_, None) => {
2781 ty_box(typ) | ty_uniq(typ) | ty_open(typ) => {
2782 type_requires(cx, seen, r_ty, typ)
2784 ty_rptr(_, ref mt) => {
2785 type_requires(cx, seen, r_ty, mt.ty)
2789 false // unsafe ptrs can always be NULL
2796 ty_struct(ref did, _) if seen.contains(did) => {
2800 ty_struct(did, ref substs) => {
2802 let fields = struct_fields(cx, did, substs);
2803 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
2804 seen.pop().unwrap();
2808 ty_unboxed_closure(did, _) => {
2809 let upvars = unboxed_closure_upvars(cx, did);
2810 upvars.iter().any(|f| type_requires(cx, seen, r_ty, f.ty))
2814 ts.iter().any(|t| type_requires(cx, seen, r_ty, *t))
2817 ty_enum(ref did, _) if seen.contains(did) => {
2821 ty_enum(did, ref substs) => {
2823 let vs = enum_variants(cx, did);
2824 let r = !vs.is_empty() && vs.iter().all(|variant| {
2825 variant.args.iter().any(|aty| {
2826 let sty = aty.subst(cx, substs);
2827 type_requires(cx, seen, r_ty, sty)
2830 seen.pop().unwrap();
2835 debug!("subtypes_require({}, {})? {}",
2836 ::util::ppaux::ty_to_string(cx, r_ty),
2837 ::util::ppaux::ty_to_string(cx, ty),
2843 let mut seen = Vec::new();
2844 !subtypes_require(cx, &mut seen, r_ty, r_ty)
2847 /// Describes whether a type is representable. For types that are not
2848 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
2849 /// distinguish between types that are recursive with themselves and types that
2850 /// contain a different recursive type. These cases can therefore be treated
2851 /// differently when reporting errors.
2852 #[deriving(PartialEq)]
2853 pub enum Representability {
2859 /// Check whether a type is representable. This means it cannot contain unboxed
2860 /// structural recursion. This check is needed for structs and enums.
2861 pub fn is_type_representable(cx: &ctxt, sp: Span, ty: t) -> Representability {
2863 // Iterate until something non-representable is found
2864 fn find_nonrepresentable<It: Iterator<t>>(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2865 mut iter: It) -> Representability {
2867 let r = type_structurally_recursive(cx, sp, seen, ty);
2868 if r != Representable {
2875 // Does the type `ty` directly (without indirection through a pointer)
2876 // contain any types on stack `seen`?
2877 fn type_structurally_recursive(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2878 ty: t) -> Representability {
2879 debug!("type_structurally_recursive: {}",
2880 ::util::ppaux::ty_to_string(cx, ty));
2882 // Compare current type to previously seen types
2885 ty_enum(did, _) => {
2886 for (i, &seen_did) in seen.iter().enumerate() {
2887 if did == seen_did {
2888 return if i == 0 { SelfRecursive }
2889 else { ContainsRecursive }
2896 // Check inner types
2900 find_nonrepresentable(cx, sp, seen, ts.iter().map(|t| *t))
2902 // Fixed-length vectors.
2903 // FIXME(#11924) Behavior undecided for zero-length vectors.
2904 ty_vec(ty, Some(_)) => {
2905 type_structurally_recursive(cx, sp, seen, ty)
2908 // Push struct and enum def-ids onto `seen` before recursing.
2909 ty_struct(did, ref substs) => {
2911 let fields = struct_fields(cx, did, substs);
2912 let r = find_nonrepresentable(cx, sp, seen,
2913 fields.iter().map(|f| f.mt.ty));
2918 ty_enum(did, ref substs) => {
2920 let vs = enum_variants(cx, did);
2922 let mut r = Representable;
2923 for variant in vs.iter() {
2924 let iter = variant.args.iter().map(|aty| {
2925 aty.subst_spanned(cx, substs, Some(sp))
2927 r = find_nonrepresentable(cx, sp, seen, iter);
2929 if r != Representable { break }
2936 ty_unboxed_closure(did, _) => {
2937 let upvars = unboxed_closure_upvars(cx, did);
2938 find_nonrepresentable(cx,
2941 upvars.iter().map(|f| f.ty))
2948 debug!("is_type_representable: {}",
2949 ::util::ppaux::ty_to_string(cx, ty));
2951 // To avoid a stack overflow when checking an enum variant or struct that
2952 // contains a different, structurally recursive type, maintain a stack
2953 // of seen types and check recursion for each of them (issues #3008, #3779).
2954 let mut seen: Vec<DefId> = Vec::new();
2955 type_structurally_recursive(cx, sp, &mut seen, ty)
2958 pub fn type_is_trait(ty: t) -> bool {
2959 type_trait_info(ty).is_some()
2962 pub fn type_trait_info(ty: t) -> Option<&'static TyTrait> {
2964 ty_uniq(ty) | ty_rptr(_, mt { ty, ..}) | ty_ptr(mt { ty, ..}) => match get(ty).sty {
2965 ty_trait(ref t) => Some(&**t),
2968 ty_trait(ref t) => Some(&**t),
2973 pub fn type_is_integral(ty: t) -> bool {
2975 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
2980 pub fn type_is_skolemized(ty: t) -> bool {
2982 ty_infer(SkolemizedTy(_)) => true,
2983 ty_infer(SkolemizedIntTy(_)) => true,
2988 pub fn type_is_uint(ty: t) -> bool {
2990 ty_infer(IntVar(_)) | ty_uint(ast::TyU) => true,
2995 pub fn type_is_char(ty: t) -> bool {
3002 pub fn type_is_bare_fn(ty: t) -> bool {
3004 ty_bare_fn(..) => true,
3009 pub fn type_is_fp(ty: t) -> bool {
3011 ty_infer(FloatVar(_)) | ty_float(_) => true,
3016 pub fn type_is_numeric(ty: t) -> bool {
3017 return type_is_integral(ty) || type_is_fp(ty);
3020 pub fn type_is_signed(ty: t) -> bool {
3027 pub fn type_is_machine(ty: t) -> bool {
3029 ty_int(ast::TyI) | ty_uint(ast::TyU) => false,
3030 ty_int(..) | ty_uint(..) | ty_float(..) => true,
3035 // Is the type's representation size known at compile time?
3036 pub fn type_is_sized(cx: &ctxt, ty: t) -> bool {
3037 type_contents(cx, ty).is_sized(cx)
3040 pub fn lltype_is_sized(cx: &ctxt, ty: t) -> bool {
3043 _ => type_contents(cx, ty).is_sized(cx)
3047 // Return the smallest part of t which is unsized. Fails if t is sized.
3048 // 'Smallest' here means component of the static representation of the type; not
3049 // the size of an object at runtime.
3050 pub fn unsized_part_of_type(cx: &ctxt, ty: t) -> t {
3052 ty_str | ty_trait(..) | ty_vec(..) => ty,
3053 ty_struct(def_id, ref substs) => {
3054 let unsized_fields: Vec<_> = struct_fields(cx, def_id, substs).iter()
3055 .map(|f| f.mt.ty).filter(|ty| !type_is_sized(cx, *ty)).collect();
3056 // Exactly one of the fields must be unsized.
3057 assert!(unsized_fields.len() == 1)
3059 unsized_part_of_type(cx, unsized_fields[0])
3062 assert!(type_is_sized(cx, ty),
3063 "unsized_part_of_type failed even though ty is unsized");
3064 fail!("called unsized_part_of_type with sized ty");
3069 // Whether a type is enum like, that is an enum type with only nullary
3071 pub fn type_is_c_like_enum(cx: &ctxt, ty: t) -> bool {
3073 ty_enum(did, _) => {
3074 let variants = enum_variants(cx, did);
3075 if variants.len() == 0 {
3078 variants.iter().all(|v| v.args.len() == 0)
3085 // Returns the type and mutability of *t.
3087 // The parameter `explicit` indicates if this is an *explicit* dereference.
3088 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
3089 pub fn deref(t: t, explicit: bool) -> Option<mt> {
3091 ty_box(ty) | ty_uniq(ty) => {
3094 mutbl: ast::MutImmutable,
3097 ty_rptr(_, mt) => Some(mt),
3098 ty_ptr(mt) if explicit => Some(mt),
3103 pub fn deref_or_dont(t: t) -> t {
3105 ty_box(ty) | ty_uniq(ty) => {
3108 ty_rptr(_, mt) | ty_ptr(mt) => mt.ty,
3113 pub fn close_type(cx: &ctxt, t: t) -> t {
3115 ty_open(t) => mk_rptr(cx, ReStatic, mt {ty: t, mutbl:ast::MutImmutable}),
3116 _ => cx.sess.bug(format!("Trying to close a non-open type {}",
3117 ty_to_string(cx, t)).as_slice())
3121 pub fn type_content(t: t) -> t {
3123 ty_box(ty) | ty_uniq(ty) => ty,
3124 ty_rptr(_, mt) |ty_ptr(mt) => mt.ty,
3130 // Extract the unsized type in an open type (or just return t if it is not open).
3131 pub fn unopen_type(t: t) -> t {
3138 // Returns the type of t[i]
3139 pub fn index(ty: t) -> Option<t> {
3141 ty_vec(t, _) => Some(t),
3146 // Returns the type of elements contained within an 'array-like' type.
3147 // This is exactly the same as the above, except it supports strings,
3148 // which can't actually be indexed.
3149 pub fn array_element_ty(t: t) -> Option<t> {
3151 ty_vec(t, _) => Some(t),
3152 ty_str => Some(mk_u8()),
3157 pub fn node_id_to_trait_ref(cx: &ctxt, id: ast::NodeId) -> Rc<ty::TraitRef> {
3158 match cx.trait_refs.borrow().find(&id) {
3159 Some(t) => t.clone(),
3160 None => cx.sess.bug(
3161 format!("node_id_to_trait_ref: no trait ref for node `{}`",
3162 cx.map.node_to_string(id)).as_slice())
3166 pub fn try_node_id_to_type(cx: &ctxt, id: ast::NodeId) -> Option<t> {
3167 cx.node_types.borrow().find_copy(&(id as uint))
3170 pub fn node_id_to_type(cx: &ctxt, id: ast::NodeId) -> t {
3171 match try_node_id_to_type(cx, id) {
3173 None => cx.sess.bug(
3174 format!("node_id_to_type: no type for node `{}`",
3175 cx.map.node_to_string(id)).as_slice())
3179 pub fn node_id_to_type_opt(cx: &ctxt, id: ast::NodeId) -> Option<t> {
3180 match cx.node_types.borrow().find(&(id as uint)) {
3181 Some(&t) => Some(t),
3186 pub fn node_id_item_substs(cx: &ctxt, id: ast::NodeId) -> ItemSubsts {
3187 match cx.item_substs.borrow().find(&id) {
3188 None => ItemSubsts::empty(),
3189 Some(ts) => ts.clone(),
3193 pub fn fn_is_variadic(fty: t) -> bool {
3194 match get(fty).sty {
3195 ty_bare_fn(ref f) => f.sig.variadic,
3196 ty_closure(ref f) => f.sig.variadic,
3198 fail!("fn_is_variadic() called on non-fn type: {:?}", s)
3203 pub fn ty_fn_sig(fty: t) -> FnSig {
3204 match get(fty).sty {
3205 ty_bare_fn(ref f) => f.sig.clone(),
3206 ty_closure(ref f) => f.sig.clone(),
3208 fail!("ty_fn_sig() called on non-fn type: {:?}", s)
3213 /// Returns the ABI of the given function.
3214 pub fn ty_fn_abi(fty: t) -> abi::Abi {
3215 match get(fty).sty {
3216 ty_bare_fn(ref f) => f.abi,
3217 ty_closure(ref f) => f.abi,
3218 _ => fail!("ty_fn_abi() called on non-fn type"),
3222 // Type accessors for substructures of types
3223 pub fn ty_fn_args(fty: t) -> Vec<t> {
3224 match get(fty).sty {
3225 ty_bare_fn(ref f) => f.sig.inputs.clone(),
3226 ty_closure(ref f) => f.sig.inputs.clone(),
3228 fail!("ty_fn_args() called on non-fn type: {:?}", s)
3233 pub fn ty_closure_store(fty: t) -> TraitStore {
3234 match get(fty).sty {
3235 ty_closure(ref f) => f.store,
3236 ty_unboxed_closure(..) => {
3237 // Close enough for the purposes of all the callers of this
3238 // function (which is soon to be deprecated anyhow).
3242 fail!("ty_closure_store() called on non-closure type: {:?}", s)
3247 pub fn ty_fn_ret(fty: t) -> t {
3248 match get(fty).sty {
3249 ty_bare_fn(ref f) => f.sig.output,
3250 ty_closure(ref f) => f.sig.output,
3252 fail!("ty_fn_ret() called on non-fn type: {:?}", s)
3257 pub fn is_fn_ty(fty: t) -> bool {
3258 match get(fty).sty {
3259 ty_bare_fn(_) => true,
3260 ty_closure(_) => true,
3265 pub fn ty_region(tcx: &ctxt,
3273 format!("ty_region() invoked on an inappropriate ty: {:?}",
3279 pub fn free_region_from_def(free_id: ast::NodeId, def: &RegionParameterDef)
3282 ty::ReFree(ty::FreeRegion { scope_id: free_id,
3283 bound_region: ty::BrNamed(def.def_id,
3287 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
3288 // doesn't provide type parameter substitutions.
3289 pub fn pat_ty(cx: &ctxt, pat: &ast::Pat) -> t {
3290 return node_id_to_type(cx, pat.id);
3294 // Returns the type of an expression as a monotype.
3296 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
3297 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
3298 // auto-ref. The type returned by this function does not consider such
3299 // adjustments. See `expr_ty_adjusted()` instead.
3301 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
3302 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
3303 // instead of "fn(t) -> T with T = int".
3304 pub fn expr_ty(cx: &ctxt, expr: &ast::Expr) -> t {
3305 return node_id_to_type(cx, expr.id);
3308 pub fn expr_ty_opt(cx: &ctxt, expr: &ast::Expr) -> Option<t> {
3309 return node_id_to_type_opt(cx, expr.id);
3312 pub fn expr_ty_adjusted(cx: &ctxt, expr: &ast::Expr) -> t {
3315 * Returns the type of `expr`, considering any `AutoAdjustment`
3316 * entry recorded for that expression.
3318 * It would almost certainly be better to store the adjusted ty in with
3319 * the `AutoAdjustment`, but I opted not to do this because it would
3320 * require serializing and deserializing the type and, although that's not
3321 * hard to do, I just hate that code so much I didn't want to touch it
3322 * unless it was to fix it properly, which seemed a distraction from the
3323 * task at hand! -nmatsakis
3326 adjust_ty(cx, expr.span, expr.id, expr_ty(cx, expr),
3327 cx.adjustments.borrow().find(&expr.id),
3328 |method_call| cx.method_map.borrow().find(&method_call).map(|method| method.ty))
3331 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
3332 match cx.map.find(id) {
3333 Some(ast_map::NodeExpr(e)) => {
3337 cx.sess.bug(format!("Node id {} is not an expr: {:?}",
3342 cx.sess.bug(format!("Node id {} is not present \
3343 in the node map", id).as_slice());
3348 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
3349 match cx.map.find(id) {
3350 Some(ast_map::NodeLocal(pat)) => {
3352 ast::PatIdent(_, ref path1, _) => {
3353 token::get_ident(path1.node)
3357 format!("Variable id {} maps to {:?}, not local",
3364 cx.sess.bug(format!("Variable id {} maps to {:?}, not local",
3371 pub fn adjust_ty(cx: &ctxt,
3373 expr_id: ast::NodeId,
3374 unadjusted_ty: ty::t,
3375 adjustment: Option<&AutoAdjustment>,
3376 method_type: |typeck::MethodCall| -> Option<ty::t>)
3378 /*! See `expr_ty_adjusted` */
3380 match get(unadjusted_ty).sty {
3381 ty_err => return unadjusted_ty,
3385 return match adjustment {
3386 Some(adjustment) => {
3388 AdjustAddEnv(store) => {
3389 match ty::get(unadjusted_ty).sty {
3390 ty::ty_bare_fn(ref b) => {
3391 let bounds = ty::ExistentialBounds {
3392 region_bound: ReStatic,
3393 builtin_bounds: all_builtin_bounds(),
3398 ty::ClosureTy {fn_style: b.fn_style,
3399 onceness: ast::Many,
3407 format!("add_env adjustment on non-bare-fn: \
3414 AdjustDerefRef(ref adj) => {
3415 let mut adjusted_ty = unadjusted_ty;
3417 if !ty::type_is_error(adjusted_ty) {
3418 for i in range(0, adj.autoderefs) {
3419 let method_call = typeck::MethodCall::autoderef(expr_id, i);
3420 match method_type(method_call) {
3421 Some(method_ty) => {
3422 adjusted_ty = ty_fn_ret(method_ty);
3426 match deref(adjusted_ty, true) {
3427 Some(mt) => { adjusted_ty = mt.ty; }
3431 format!("the {}th autoderef failed: \
3434 ty_to_string(cx, adjusted_ty))
3442 None => adjusted_ty,
3443 Some(ref autoref) => adjust_for_autoref(cx, span, adjusted_ty, autoref)
3448 None => unadjusted_ty
3451 fn adjust_for_autoref(cx: &ctxt,
3454 autoref: &AutoRef) -> ty::t{
3456 AutoPtr(r, m, ref a) => {
3457 let adjusted_ty = match a {
3458 &Some(box ref a) => adjust_for_autoref(cx, span, ty, a),
3467 AutoUnsafe(m, ref a) => {
3468 let adjusted_ty = match a {
3469 &Some(box ref a) => adjust_for_autoref(cx, span, ty, a),
3472 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
3475 AutoUnsize(ref k) => unsize_ty(cx, ty, k, span),
3476 AutoUnsizeUniq(ref k) => ty::mk_uniq(cx, unsize_ty(cx, ty, k, span)),
3481 // Take a sized type and a sizing adjustment and produce an unsized version of
3483 pub fn unsize_ty(cx: &ctxt,
3489 &UnsizeLength(len) => match get(ty).sty {
3490 ty_vec(t, Some(n)) => {
3494 _ => cx.sess.span_bug(span,
3495 format!("UnsizeLength with bad sty: {}",
3496 ty_to_string(cx, ty)).as_slice())
3498 &UnsizeStruct(box ref k, tp_index) => match get(ty).sty {
3499 ty_struct(did, ref substs) => {
3500 let ty_substs = substs.types.get_slice(subst::TypeSpace);
3501 let new_ty = unsize_ty(cx, ty_substs[tp_index], k, span);
3502 let mut unsized_substs = substs.clone();
3503 unsized_substs.types.get_mut_slice(subst::TypeSpace)[tp_index] = new_ty;
3504 mk_struct(cx, did, unsized_substs)
3506 _ => cx.sess.span_bug(span,
3507 format!("UnsizeStruct with bad sty: {}",
3508 ty_to_string(cx, ty)).as_slice())
3510 &UnsizeVtable(TyTrait { def_id, substs: ref substs, bounds }, _) => {
3511 mk_trait(cx, def_id, substs.clone(), bounds)
3516 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> def::Def {
3517 match tcx.def_map.borrow().find(&expr.id) {
3520 tcx.sess.span_bug(expr.span, format!(
3521 "no def-map entry for expr {:?}", expr.id).as_slice());
3526 pub fn expr_is_lval(tcx: &ctxt, e: &ast::Expr) -> bool {
3527 match expr_kind(tcx, e) {
3529 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
3533 /// We categorize expressions into three kinds. The distinction between
3534 /// lvalue/rvalue is fundamental to the language. The distinction between the
3535 /// two kinds of rvalues is an artifact of trans which reflects how we will
3536 /// generate code for that kind of expression. See trans/expr.rs for more
3545 pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
3546 if tcx.method_map.borrow().contains_key(&typeck::MethodCall::expr(expr.id)) {
3547 // Overloaded operations are generally calls, and hence they are
3548 // generated via DPS, but there are a few exceptions:
3549 return match expr.node {
3550 // `a += b` has a unit result.
3551 ast::ExprAssignOp(..) => RvalueStmtExpr,
3553 // the deref method invoked for `*a` always yields an `&T`
3554 ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
3556 // the index method invoked for `a[i]` always yields an `&T`
3557 ast::ExprIndex(..) => LvalueExpr,
3559 // the slice method invoked for `a[..]` always yields an `&T`
3560 ast::ExprSlice(..) => LvalueExpr,
3562 // `for` loops are statements
3563 ast::ExprForLoop(..) => RvalueStmtExpr,
3565 // in the general case, result could be any type, use DPS
3571 ast::ExprPath(..) => {
3572 match resolve_expr(tcx, expr) {
3573 def::DefVariant(tid, vid, _) => {
3574 let variant_info = enum_variant_with_id(tcx, tid, vid);
3575 if variant_info.args.len() > 0u {
3584 def::DefStruct(_) => {
3585 match get(expr_ty(tcx, expr)).sty {
3586 ty_bare_fn(..) => RvalueDatumExpr,
3591 // Fn pointers are just scalar values.
3592 def::DefFn(..) | def::DefStaticMethod(..) => RvalueDatumExpr,
3594 // Note: there is actually a good case to be made that
3595 // DefArg's, particularly those of immediate type, ought to
3596 // considered rvalues.
3597 def::DefStatic(..) |
3599 def::DefLocal(..) => LvalueExpr,
3604 format!("uncategorized def for expr {:?}: {:?}",
3611 ast::ExprUnary(ast::UnDeref, _) |
3612 ast::ExprField(..) |
3613 ast::ExprTupField(..) |
3614 ast::ExprIndex(..) |
3615 ast::ExprSlice(..) => {
3620 ast::ExprMethodCall(..) |
3621 ast::ExprStruct(..) |
3624 ast::ExprMatch(..) |
3625 ast::ExprFnBlock(..) |
3627 ast::ExprUnboxedFn(..) |
3628 ast::ExprBlock(..) |
3629 ast::ExprRepeat(..) |
3630 ast::ExprVec(..) => {
3634 ast::ExprLit(ref lit) if lit_is_str(&**lit) => {
3638 ast::ExprCast(..) => {
3639 match tcx.node_types.borrow().find(&(expr.id as uint)) {
3641 if type_is_trait(t) {
3648 // Technically, it should not happen that the expr is not
3649 // present within the table. However, it DOES happen
3650 // during type check, because the final types from the
3651 // expressions are not yet recorded in the tcx. At that
3652 // time, though, we are only interested in knowing lvalue
3653 // vs rvalue. It would be better to base this decision on
3654 // the AST type in cast node---but (at the time of this
3655 // writing) it's not easy to distinguish casts to traits
3656 // from other casts based on the AST. This should be
3657 // easier in the future, when casts to traits
3658 // would like @Foo, Box<Foo>, or &Foo.
3664 ast::ExprBreak(..) |
3665 ast::ExprAgain(..) |
3667 ast::ExprWhile(..) |
3669 ast::ExprAssign(..) |
3670 ast::ExprInlineAsm(..) |
3671 ast::ExprAssignOp(..) |
3672 ast::ExprForLoop(..) => {
3676 ast::ExprLit(_) | // Note: LitStr is carved out above
3677 ast::ExprUnary(..) |
3678 ast::ExprAddrOf(..) |
3679 ast::ExprBinary(..) => {
3683 ast::ExprBox(ref place, _) => {
3684 // Special case `Box<T>`/`Gc<T>` for now:
3685 let definition = match tcx.def_map.borrow().find(&place.id) {
3687 None => fail!("no def for place"),
3689 let def_id = definition.def_id();
3690 if tcx.lang_items.exchange_heap() == Some(def_id) ||
3691 tcx.lang_items.managed_heap() == Some(def_id) {
3698 ast::ExprParen(ref e) => expr_kind(tcx, &**e),
3700 ast::ExprMac(..) => {
3703 "macro expression remains after expansion");
3708 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
3710 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
3713 ast::StmtMac(..) => fail!("unexpanded macro in trans")
3717 pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
3720 for f in fields.iter() { if f.ident.name == name { return i; } i += 1u; }
3721 tcx.sess.bug(format!(
3722 "no field named `{}` found in the list of fields `{:?}`",
3723 token::get_name(name),
3725 .map(|f| token::get_ident(f.ident).get().to_string())
3726 .collect::<Vec<String>>()).as_slice());
3729 pub fn impl_or_trait_item_idx(id: ast::Ident, trait_items: &[ImplOrTraitItem])
3731 trait_items.iter().position(|m| m.ident() == id)
3734 pub fn ty_sort_string(cx: &ctxt, t: t) -> String {
3736 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) |
3737 ty_uint(_) | ty_float(_) | ty_str => {
3738 ::util::ppaux::ty_to_string(cx, t)
3741 ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
3742 ty_box(_) => "Gc-ptr".to_string(),
3743 ty_uniq(_) => "box".to_string(),
3744 ty_vec(_, Some(_)) => "array".to_string(),
3745 ty_vec(_, None) => "unsized array".to_string(),
3746 ty_ptr(_) => "*-ptr".to_string(),
3747 ty_rptr(_, _) => "&-ptr".to_string(),
3748 ty_bare_fn(_) => "extern fn".to_string(),
3749 ty_closure(_) => "fn".to_string(),
3750 ty_trait(ref inner) => {
3751 format!("trait {}", item_path_str(cx, inner.def_id))
3753 ty_struct(id, _) => {
3754 format!("struct {}", item_path_str(cx, id))
3756 ty_unboxed_closure(..) => "closure".to_string(),
3757 ty_tup(_) => "tuple".to_string(),
3758 ty_infer(TyVar(_)) => "inferred type".to_string(),
3759 ty_infer(IntVar(_)) => "integral variable".to_string(),
3760 ty_infer(FloatVar(_)) => "floating-point variable".to_string(),
3761 ty_infer(SkolemizedTy(_)) => "skolemized type".to_string(),
3762 ty_infer(SkolemizedIntTy(_)) => "skolemized integral type".to_string(),
3763 ty_param(ref p) => {
3764 if p.space == subst::SelfSpace {
3767 "type parameter".to_string()
3770 ty_err => "type error".to_string(),
3771 ty_open(_) => "opened DST".to_string(),
3775 pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> String {
3778 * Explains the source of a type err in a short,
3779 * human readable way. This is meant to be placed in
3780 * parentheses after some larger message. You should
3781 * also invoke `note_and_explain_type_err()` afterwards
3782 * to present additional details, particularly when
3783 * it comes to lifetime-related errors. */
3785 fn tstore_to_closure(s: &TraitStore) -> String {
3787 &UniqTraitStore => "proc".to_string(),
3788 &RegionTraitStore(..) => "closure".to_string()
3793 terr_cyclic_ty => "cyclic type of infinite size".to_string(),
3794 terr_mismatch => "types differ".to_string(),
3795 terr_fn_style_mismatch(values) => {
3796 format!("expected {} fn, found {} fn",
3797 values.expected.to_string(),
3798 values.found.to_string())
3800 terr_abi_mismatch(values) => {
3801 format!("expected {} fn, found {} fn",
3802 values.expected.to_string(),
3803 values.found.to_string())
3805 terr_onceness_mismatch(values) => {
3806 format!("expected {} fn, found {} fn",
3807 values.expected.to_string(),
3808 values.found.to_string())
3810 terr_sigil_mismatch(values) => {
3811 format!("expected {}, found {}",
3812 tstore_to_closure(&values.expected),
3813 tstore_to_closure(&values.found))
3815 terr_mutability => "values differ in mutability".to_string(),
3816 terr_box_mutability => {
3817 "boxed values differ in mutability".to_string()
3819 terr_vec_mutability => "vectors differ in mutability".to_string(),
3820 terr_ptr_mutability => "pointers differ in mutability".to_string(),
3821 terr_ref_mutability => "references differ in mutability".to_string(),
3822 terr_ty_param_size(values) => {
3823 format!("expected a type with {} type params, \
3824 found one with {} type params",
3828 terr_tuple_size(values) => {
3829 format!("expected a tuple with {} elements, \
3830 found one with {} elements",
3834 terr_record_size(values) => {
3835 format!("expected a record with {} fields, \
3836 found one with {} fields",
3840 terr_record_mutability => {
3841 "record elements differ in mutability".to_string()
3843 terr_record_fields(values) => {
3844 format!("expected a record with field `{}`, found one \
3846 token::get_ident(values.expected),
3847 token::get_ident(values.found))
3850 "incorrect number of function parameters".to_string()
3852 terr_regions_does_not_outlive(..) => {
3853 "lifetime mismatch".to_string()
3855 terr_regions_not_same(..) => {
3856 "lifetimes are not the same".to_string()
3858 terr_regions_no_overlap(..) => {
3859 "lifetimes do not intersect".to_string()
3861 terr_regions_insufficiently_polymorphic(br, _) => {
3862 format!("expected bound lifetime parameter {}, \
3863 found concrete lifetime",
3864 bound_region_ptr_to_string(cx, br))
3866 terr_regions_overly_polymorphic(br, _) => {
3867 format!("expected concrete lifetime, \
3868 found bound lifetime parameter {}",
3869 bound_region_ptr_to_string(cx, br))
3871 terr_trait_stores_differ(_, ref values) => {
3872 format!("trait storage differs: expected `{}`, found `{}`",
3873 trait_store_to_string(cx, (*values).expected),
3874 trait_store_to_string(cx, (*values).found))
3876 terr_sorts(values) => {
3877 format!("expected {}, found {}",
3878 ty_sort_string(cx, values.expected),
3879 ty_sort_string(cx, values.found))
3881 terr_traits(values) => {
3882 format!("expected trait `{}`, found trait `{}`",
3883 item_path_str(cx, values.expected),
3884 item_path_str(cx, values.found))
3886 terr_builtin_bounds(values) => {
3887 if values.expected.is_empty() {
3888 format!("expected no bounds, found `{}`",
3889 values.found.user_string(cx))
3890 } else if values.found.is_empty() {
3891 format!("expected bounds `{}`, found no bounds",
3892 values.expected.user_string(cx))
3894 format!("expected bounds `{}`, found bounds `{}`",
3895 values.expected.user_string(cx),
3896 values.found.user_string(cx))
3899 terr_integer_as_char => {
3900 "expected an integral type, found `char`".to_string()
3902 terr_int_mismatch(ref values) => {
3903 format!("expected `{}`, found `{}`",
3904 values.expected.to_string(),
3905 values.found.to_string())
3907 terr_float_mismatch(ref values) => {
3908 format!("expected `{}`, found `{}`",
3909 values.expected.to_string(),
3910 values.found.to_string())
3912 terr_variadic_mismatch(ref values) => {
3913 format!("expected {} fn, found {} function",
3914 if values.expected { "variadic" } else { "non-variadic" },
3915 if values.found { "variadic" } else { "non-variadic" })
3920 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
3922 terr_regions_does_not_outlive(subregion, superregion) => {
3923 note_and_explain_region(cx, "", subregion, "...");
3924 note_and_explain_region(cx, "...does not necessarily outlive ",
3927 terr_regions_not_same(region1, region2) => {
3928 note_and_explain_region(cx, "", region1, "...");
3929 note_and_explain_region(cx, "...is not the same lifetime as ",
3932 terr_regions_no_overlap(region1, region2) => {
3933 note_and_explain_region(cx, "", region1, "...");
3934 note_and_explain_region(cx, "...does not overlap ",
3937 terr_regions_insufficiently_polymorphic(_, conc_region) => {
3938 note_and_explain_region(cx,
3939 "concrete lifetime that was found is ",
3942 terr_regions_overly_polymorphic(_, conc_region) => {
3943 note_and_explain_region(cx,
3944 "expected concrete lifetime is ",
3951 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
3952 cx.provided_method_sources.borrow().find(&id).map(|x| *x)
3955 pub fn provided_trait_methods(cx: &ctxt, id: ast::DefId) -> Vec<Rc<Method>> {
3957 match cx.map.find(id.node) {
3958 Some(ast_map::NodeItem(item)) => {
3960 ItemTrait(_, _, _, ref ms) => {
3962 ast_util::split_trait_methods(ms.as_slice());
3965 match impl_or_trait_item(
3967 ast_util::local_def(m.id)) {
3968 MethodTraitItem(m) => m,
3969 TypeTraitItem(_) => {
3970 cx.sess.bug("provided_trait_methods(): \
3971 split_trait_methods() put \
3972 associated types in the \
3973 provided method bucket?!")
3979 cx.sess.bug(format!("provided_trait_methods: `{}` is \
3986 cx.sess.bug(format!("provided_trait_methods: `{}` is not a \
3992 csearch::get_provided_trait_methods(cx, id)
3996 fn lookup_locally_or_in_crate_store<V:Clone>(
3999 map: &mut DefIdMap<V>,
4000 load_external: || -> V) -> V {
4002 * Helper for looking things up in the various maps
4003 * that are populated during typeck::collect (e.g.,
4004 * `cx.impl_or_trait_items`, `cx.tcache`, etc). All of these share
4005 * the pattern that if the id is local, it should have
4006 * been loaded into the map by the `typeck::collect` phase.
4007 * If the def-id is external, then we have to go consult
4008 * the crate loading code (and cache the result for the future).
4011 match map.find_copy(&def_id) {
4012 Some(v) => { return v; }
4016 if def_id.krate == ast::LOCAL_CRATE {
4017 fail!("No def'n found for {:?} in tcx.{}", def_id, descr);
4019 let v = load_external();
4020 map.insert(def_id, v.clone());
4024 pub fn trait_item(cx: &ctxt, trait_did: ast::DefId, idx: uint)
4025 -> ImplOrTraitItem {
4026 let method_def_id = ty::trait_item_def_ids(cx, trait_did).get(idx)
4028 impl_or_trait_item(cx, method_def_id)
4031 pub fn trait_items(cx: &ctxt, trait_did: ast::DefId)
4032 -> Rc<Vec<ImplOrTraitItem>> {
4033 let mut trait_items = cx.trait_items_cache.borrow_mut();
4034 match trait_items.find_copy(&trait_did) {
4035 Some(trait_items) => trait_items,
4037 let def_ids = ty::trait_item_def_ids(cx, trait_did);
4038 let items: Rc<Vec<ImplOrTraitItem>> =
4039 Rc::new(def_ids.iter()
4040 .map(|d| impl_or_trait_item(cx, d.def_id()))
4042 trait_items.insert(trait_did, items.clone());
4048 pub fn impl_or_trait_item(cx: &ctxt, id: ast::DefId) -> ImplOrTraitItem {
4049 lookup_locally_or_in_crate_store("impl_or_trait_items",
4051 &mut *cx.impl_or_trait_items
4054 csearch::get_impl_or_trait_item(cx, id)
4058 /// Returns true if the given ID refers to an associated type and false if it
4059 /// refers to anything else.
4060 pub fn is_associated_type(cx: &ctxt, id: ast::DefId) -> bool {
4061 let result = match cx.associated_types.borrow_mut().find(&id) {
4062 Some(result) => return *result,
4063 None if id.krate == ast::LOCAL_CRATE => {
4064 match cx.impl_or_trait_items.borrow().find(&id) {
4067 TypeTraitItem(_) => true,
4068 MethodTraitItem(_) => false,
4075 csearch::is_associated_type(&cx.sess.cstore, id)
4079 cx.associated_types.borrow_mut().insert(id, result);
4083 /// Returns the parameter index that the given associated type corresponds to.
4084 pub fn associated_type_parameter_index(cx: &ctxt,
4085 trait_def: &TraitDef,
4086 associated_type_id: ast::DefId)
4088 for type_parameter_def in trait_def.generics.types.iter() {
4089 if type_parameter_def.def_id == associated_type_id {
4090 return type_parameter_def.index
4093 cx.sess.bug("couldn't find associated type parameter index")
4096 #[deriving(PartialEq, Eq)]
4097 pub struct AssociatedTypeInfo {
4098 pub def_id: ast::DefId,
4100 pub ident: ast::Ident,
4103 impl PartialOrd for AssociatedTypeInfo {
4104 fn partial_cmp(&self, other: &AssociatedTypeInfo) -> Option<Ordering> {
4105 Some(self.index.cmp(&other.index))
4109 impl Ord for AssociatedTypeInfo {
4110 fn cmp(&self, other: &AssociatedTypeInfo) -> Ordering {
4111 self.index.cmp(&other.index)
4115 /// Returns the associated types belonging to the given trait, in parameter
4117 pub fn associated_types_for_trait(cx: &ctxt, trait_id: ast::DefId)
4118 -> Rc<Vec<AssociatedTypeInfo>> {
4119 cx.trait_associated_types
4122 .expect("associated_types_for_trait(): trait not found, try calling \
4123 ensure_associated_types()")
4127 pub fn trait_item_def_ids(cx: &ctxt, id: ast::DefId)
4128 -> Rc<Vec<ImplOrTraitItemId>> {
4129 lookup_locally_or_in_crate_store("trait_item_def_ids",
4131 &mut *cx.trait_item_def_ids.borrow_mut(),
4133 Rc::new(csearch::get_trait_item_def_ids(&cx.sess.cstore, id))
4137 pub fn impl_trait_ref(cx: &ctxt, id: ast::DefId) -> Option<Rc<TraitRef>> {
4138 match cx.impl_trait_cache.borrow().find(&id) {
4139 Some(ret) => { return ret.clone(); }
4143 let ret = if id.krate == ast::LOCAL_CRATE {
4144 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
4145 match cx.map.find(id.node) {
4146 Some(ast_map::NodeItem(item)) => {
4148 ast::ItemImpl(_, ref opt_trait, _, _) => {
4151 Some(ty::node_id_to_trait_ref(cx, t.ref_id))
4162 csearch::get_impl_trait(cx, id)
4165 cx.impl_trait_cache.borrow_mut().insert(id, ret.clone());
4169 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
4170 let def = *tcx.def_map.borrow()
4172 .expect("no def-map entry for trait");
4176 pub fn try_add_builtin_trait(
4178 trait_def_id: ast::DefId,
4179 builtin_bounds: &mut EnumSet<BuiltinBound>)
4182 //! Checks whether `trait_ref` refers to one of the builtin
4183 //! traits, like `Send`, and adds the corresponding
4184 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
4185 //! is a builtin trait.
4187 match tcx.lang_items.to_builtin_kind(trait_def_id) {
4188 Some(bound) => { builtin_bounds.add(bound); true }
4193 pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> {
4195 ty_trait(box TyTrait { def_id: id, .. }) |
4198 ty_unboxed_closure(id, _) => Some(id),
4205 pub struct VariantInfo {
4207 pub arg_names: Option<Vec<ast::Ident> >,
4209 pub name: ast::Ident,
4217 /// Creates a new VariantInfo from the corresponding ast representation.
4219 /// Does not do any caching of the value in the type context.
4220 pub fn from_ast_variant(cx: &ctxt,
4221 ast_variant: &ast::Variant,
4222 discriminant: Disr) -> VariantInfo {
4223 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
4225 match ast_variant.node.kind {
4226 ast::TupleVariantKind(ref args) => {
4227 let arg_tys = if args.len() > 0 {
4228 ty_fn_args(ctor_ty).iter().map(|a| *a).collect()
4233 return VariantInfo {
4237 name: ast_variant.node.name,
4238 id: ast_util::local_def(ast_variant.node.id),
4239 disr_val: discriminant,
4240 vis: ast_variant.node.vis
4243 ast::StructVariantKind(ref struct_def) => {
4245 let fields: &[StructField] = struct_def.fields.as_slice();
4247 assert!(fields.len() > 0);
4249 let arg_tys = ty_fn_args(ctor_ty).iter().map(|a| *a).collect();
4250 let arg_names = fields.iter().map(|field| {
4251 match field.node.kind {
4252 NamedField(ident, _) => ident,
4253 UnnamedField(..) => cx.sess.bug(
4254 "enum_variants: all fields in struct must have a name")
4258 return VariantInfo {
4260 arg_names: Some(arg_names),
4262 name: ast_variant.node.name,
4263 id: ast_util::local_def(ast_variant.node.id),
4264 disr_val: discriminant,
4265 vis: ast_variant.node.vis
4272 pub fn substd_enum_variants(cx: &ctxt,
4275 -> Vec<Rc<VariantInfo>> {
4276 enum_variants(cx, id).iter().map(|variant_info| {
4277 let substd_args = variant_info.args.iter()
4278 .map(|aty| aty.subst(cx, substs)).collect::<Vec<_>>();
4280 let substd_ctor_ty = variant_info.ctor_ty.subst(cx, substs);
4282 Rc::new(VariantInfo {
4284 ctor_ty: substd_ctor_ty,
4285 ..(**variant_info).clone()
4290 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
4291 with_path(cx, id, |path| ast_map::path_to_string(path)).to_string()
4296 TraitDtor(DefId, bool)
4300 pub fn is_present(&self) -> bool {
4302 TraitDtor(..) => true,
4307 pub fn has_drop_flag(&self) -> bool {
4310 &TraitDtor(_, flag) => flag
4315 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
4316 Otherwise return none. */
4317 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
4318 match cx.destructor_for_type.borrow().find(&struct_id) {
4319 Some(&method_def_id) => {
4320 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
4322 TraitDtor(method_def_id, flag)
4328 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
4329 ty_dtor(cx, struct_id).is_present()
4332 pub fn with_path<T>(cx: &ctxt, id: ast::DefId, f: |ast_map::PathElems| -> T) -> T {
4333 if id.krate == ast::LOCAL_CRATE {
4334 cx.map.with_path(id.node, f)
4336 f(ast_map::Values(csearch::get_item_path(cx, id).iter()).chain(None))
4340 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
4341 enum_variants(cx, id).len() == 1
4344 pub fn type_is_empty(cx: &ctxt, t: t) -> bool {
4345 match ty::get(t).sty {
4346 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
4351 pub fn enum_variants(cx: &ctxt, id: ast::DefId) -> Rc<Vec<Rc<VariantInfo>>> {
4352 match cx.enum_var_cache.borrow().find(&id) {
4353 Some(variants) => return variants.clone(),
4354 _ => { /* fallthrough */ }
4357 let result = if ast::LOCAL_CRATE != id.krate {
4358 Rc::new(csearch::get_enum_variants(cx, id))
4361 Although both this code and check_enum_variants in typeck/check
4362 call eval_const_expr, it should never get called twice for the same
4363 expr, since check_enum_variants also updates the enum_var_cache
4365 match cx.map.get(id.node) {
4366 ast_map::NodeItem(ref item) => {
4368 ast::ItemEnum(ref enum_definition, _) => {
4369 let mut last_discriminant: Option<Disr> = None;
4370 Rc::new(enum_definition.variants.iter().map(|variant| {
4372 let mut discriminant = match last_discriminant {
4373 Some(val) => val + 1,
4374 None => INITIAL_DISCRIMINANT_VALUE
4377 match variant.node.disr_expr {
4378 Some(ref e) => match const_eval::eval_const_expr_partial(cx, &**e) {
4379 Ok(const_eval::const_int(val)) => {
4380 discriminant = val as Disr
4382 Ok(const_eval::const_uint(val)) => {
4383 discriminant = val as Disr
4388 "expected signed integer constant");
4393 format!("expected constant: {}",
4400 last_discriminant = Some(discriminant);
4401 Rc::new(VariantInfo::from_ast_variant(cx, &**variant,
4406 cx.sess.bug("enum_variants: id not bound to an enum")
4410 _ => cx.sess.bug("enum_variants: id not bound to an enum")
4414 cx.enum_var_cache.borrow_mut().insert(id, result.clone());
4419 // Returns information about the enum variant with the given ID:
4420 pub fn enum_variant_with_id(cx: &ctxt,
4421 enum_id: ast::DefId,
4422 variant_id: ast::DefId)
4423 -> Rc<VariantInfo> {
4424 enum_variants(cx, enum_id).iter()
4425 .find(|variant| variant.id == variant_id)
4426 .expect("enum_variant_with_id(): no variant exists with that ID")
4431 // If the given item is in an external crate, looks up its type and adds it to
4432 // the type cache. Returns the type parameters and type.
4433 pub fn lookup_item_type(cx: &ctxt,
4436 lookup_locally_or_in_crate_store(
4437 "tcache", did, &mut *cx.tcache.borrow_mut(),
4438 || csearch::get_type(cx, did))
4441 /// Given the did of a trait, returns its canonical trait ref.
4442 pub fn lookup_trait_def(cx: &ctxt, did: ast::DefId) -> Rc<ty::TraitDef> {
4443 let mut trait_defs = cx.trait_defs.borrow_mut();
4444 match trait_defs.find_copy(&did) {
4445 Some(trait_def) => {
4446 // The item is in this crate. The caller should have added it to the
4447 // type cache already
4451 assert!(did.krate != ast::LOCAL_CRATE);
4452 let trait_def = Rc::new(csearch::get_trait_def(cx, did));
4453 trait_defs.insert(did, trait_def.clone());
4459 /// Given a reference to a trait, returns the bounds declared on the
4460 /// trait, with appropriate substitutions applied.
4461 pub fn bounds_for_trait_ref(tcx: &ctxt,
4462 trait_ref: &TraitRef)
4465 let trait_def = lookup_trait_def(tcx, trait_ref.def_id);
4466 debug!("bounds_for_trait_ref(trait_def={}, trait_ref={})",
4467 trait_def.repr(tcx), trait_ref.repr(tcx));
4468 trait_def.bounds.subst(tcx, &trait_ref.substs)
4471 /// Iterate over attributes of a definition.
4472 // (This should really be an iterator, but that would require csearch and
4473 // decoder to use iterators instead of higher-order functions.)
4474 pub fn each_attr(tcx: &ctxt, did: DefId, f: |&ast::Attribute| -> bool) -> bool {
4476 let item = tcx.map.expect_item(did.node);
4477 item.attrs.iter().all(|attr| f(attr))
4479 info!("getting foreign attrs");
4480 let mut cont = true;
4481 csearch::get_item_attrs(&tcx.sess.cstore, did, |attrs| {
4483 cont = attrs.iter().all(|attr| f(attr));
4491 /// Determine whether an item is annotated with an attribute
4492 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
4493 let mut found = false;
4494 each_attr(tcx, did, |item| {
4495 if item.check_name(attr) {
4505 /// Determine whether an item is annotated with `#[repr(packed)]`
4506 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
4507 lookup_repr_hints(tcx, did).contains(&attr::ReprPacked)
4510 /// Determine whether an item is annotated with `#[simd]`
4511 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
4512 has_attr(tcx, did, "simd")
4515 /// Obtain the representation annotation for a struct definition.
4516 pub fn lookup_repr_hints(tcx: &ctxt, did: DefId) -> Vec<attr::ReprAttr> {
4517 let mut acc = Vec::new();
4519 ty::each_attr(tcx, did, |meta| {
4520 acc.extend(attr::find_repr_attrs(tcx.sess.diagnostic(), meta).into_iter());
4527 // Look up a field ID, whether or not it's local
4528 // Takes a list of type substs in case the struct is generic
4529 pub fn lookup_field_type(tcx: &ctxt,
4534 let t = if id.krate == ast::LOCAL_CRATE {
4535 node_id_to_type(tcx, id.node)
4537 let mut tcache = tcx.tcache.borrow_mut();
4538 let pty = match tcache.entry(id) {
4539 Occupied(entry) => entry.into_mut(),
4540 Vacant(entry) => entry.set(csearch::get_field_type(tcx, struct_id, id)),
4544 t.subst(tcx, substs)
4547 // Lookup all ancestor structs of a struct indicated by did. That is the reflexive,
4548 // transitive closure of doing a single lookup in cx.superstructs.
4549 fn each_super_struct(cx: &ctxt, mut did: ast::DefId, f: |ast::DefId|) {
4550 let superstructs = cx.superstructs.borrow();
4554 match superstructs.find(&did) {
4555 Some(&Some(def_id)) => {
4558 Some(&None) => break,
4561 format!("ID not mapped to super-struct: {}",
4562 cx.map.node_to_string(did.node)).as_slice());
4568 // Look up the list of field names and IDs for a given struct.
4569 // Fails if the id is not bound to a struct.
4570 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
4571 if did.krate == ast::LOCAL_CRATE {
4572 // We store the fields which are syntactically in each struct in cx. So
4573 // we have to walk the inheritance chain of the struct to get all the
4574 // fields (explicit and inherited) for a struct. If this is expensive
4575 // we could cache the whole list of fields here.
4576 let struct_fields = cx.struct_fields.borrow();
4577 let mut results: SmallVector<&[field_ty]> = SmallVector::zero();
4578 each_super_struct(cx, did, |s| {
4579 match struct_fields.find(&s) {
4580 Some(fields) => results.push(fields.as_slice()),
4583 format!("ID not mapped to struct fields: {}",
4584 cx.map.node_to_string(did.node)).as_slice());
4589 let len = results.as_slice().iter().map(|x| x.len()).sum();
4590 let mut result: Vec<field_ty> = Vec::with_capacity(len);
4591 result.extend(results.as_slice().iter().flat_map(|rs| rs.iter().map(|f| f.clone())));
4592 assert!(result.len() == len);
4595 csearch::get_struct_fields(&cx.sess.cstore, did)
4599 pub fn is_tuple_struct(cx: &ctxt, did: ast::DefId) -> bool {
4600 let fields = lookup_struct_fields(cx, did);
4601 !fields.is_empty() && fields.iter().all(|f| f.name == token::special_names::unnamed_field)
4604 // Returns a list of fields corresponding to the struct's items. trans uses
4605 // this. Takes a list of substs with which to instantiate field types.
4606 pub fn struct_fields(cx: &ctxt, did: ast::DefId, substs: &Substs)
4608 lookup_struct_fields(cx, did).iter().map(|f| {
4610 // FIXME #6993: change type of field to Name and get rid of new()
4611 ident: ast::Ident::new(f.name),
4613 ty: lookup_field_type(cx, did, f.id, substs),
4620 // Returns a list of fields corresponding to the tuple's items. trans uses
4622 pub fn tup_fields(v: &[t]) -> Vec<field> {
4623 v.iter().enumerate().map(|(i, &f)| {
4625 // FIXME #6993: change type of field to Name and get rid of new()
4626 ident: ast::Ident::new(token::intern(i.to_string().as_slice())),
4635 pub struct UnboxedClosureUpvar {
4641 // Returns a list of `UnboxedClosureUpvar`s for each upvar.
4642 pub fn unboxed_closure_upvars(tcx: &ctxt, closure_id: ast::DefId)
4643 -> Vec<UnboxedClosureUpvar> {
4644 if closure_id.krate == ast::LOCAL_CRATE {
4645 match tcx.freevars.borrow().find(&closure_id.node) {
4647 Some(ref freevars) => {
4648 freevars.iter().map(|freevar| {
4649 let freevar_def_id = freevar.def.def_id();
4650 UnboxedClosureUpvar {
4653 ty: node_id_to_type(tcx, freevar_def_id.node),
4659 tcx.sess.bug("unimplemented cross-crate closure upvars")
4663 pub fn is_binopable(cx: &ctxt, ty: t, op: ast::BinOp) -> bool {
4664 static tycat_other: int = 0;
4665 static tycat_bool: int = 1;
4666 static tycat_char: int = 2;
4667 static tycat_int: int = 3;
4668 static tycat_float: int = 4;
4669 static tycat_bot: int = 5;
4670 static tycat_raw_ptr: int = 6;
4672 static opcat_add: int = 0;
4673 static opcat_sub: int = 1;
4674 static opcat_mult: int = 2;
4675 static opcat_shift: int = 3;
4676 static opcat_rel: int = 4;
4677 static opcat_eq: int = 5;
4678 static opcat_bit: int = 6;
4679 static opcat_logic: int = 7;
4680 static opcat_mod: int = 8;
4682 fn opcat(op: ast::BinOp) -> int {
4684 ast::BiAdd => opcat_add,
4685 ast::BiSub => opcat_sub,
4686 ast::BiMul => opcat_mult,
4687 ast::BiDiv => opcat_mult,
4688 ast::BiRem => opcat_mod,
4689 ast::BiAnd => opcat_logic,
4690 ast::BiOr => opcat_logic,
4691 ast::BiBitXor => opcat_bit,
4692 ast::BiBitAnd => opcat_bit,
4693 ast::BiBitOr => opcat_bit,
4694 ast::BiShl => opcat_shift,
4695 ast::BiShr => opcat_shift,
4696 ast::BiEq => opcat_eq,
4697 ast::BiNe => opcat_eq,
4698 ast::BiLt => opcat_rel,
4699 ast::BiLe => opcat_rel,
4700 ast::BiGe => opcat_rel,
4701 ast::BiGt => opcat_rel
4705 fn tycat(cx: &ctxt, ty: t) -> int {
4706 if type_is_simd(cx, ty) {
4707 return tycat(cx, simd_type(cx, ty))
4710 ty_char => tycat_char,
4711 ty_bool => tycat_bool,
4712 ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
4713 ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
4714 ty_bot => tycat_bot,
4715 ty_ptr(_) => tycat_raw_ptr,
4720 static t: bool = true;
4721 static f: bool = false;
4724 // +, -, *, shift, rel, ==, bit, logic, mod
4725 /*other*/ [f, f, f, f, f, f, f, f, f],
4726 /*bool*/ [f, f, f, f, t, t, t, t, f],
4727 /*char*/ [f, f, f, f, t, t, f, f, f],
4728 /*int*/ [t, t, t, t, t, t, t, f, t],
4729 /*float*/ [t, t, t, f, t, t, f, f, f],
4730 /*bot*/ [t, t, t, t, t, t, t, t, t],
4731 /*raw ptr*/ [f, f, f, f, t, t, f, f, f]];
4733 return tbl[tycat(cx, ty) as uint ][opcat(op) as uint];
4736 /// Returns an equivalent type with all the typedefs and self regions removed.
4737 pub fn normalize_ty(cx: &ctxt, t: t) -> t {
4738 let u = TypeNormalizer(cx).fold_ty(t);
4741 struct TypeNormalizer<'a, 'tcx: 'a>(&'a ctxt<'tcx>);
4743 impl<'a, 'tcx> TypeFolder<'tcx> for TypeNormalizer<'a, 'tcx> {
4744 fn tcx(&self) -> &ctxt<'tcx> { let TypeNormalizer(c) = *self; c }
4746 fn fold_ty(&mut self, t: ty::t) -> ty::t {
4747 match self.tcx().normalized_cache.borrow().find_copy(&t) {
4752 let t_norm = ty_fold::super_fold_ty(self, t);
4753 self.tcx().normalized_cache.borrow_mut().insert(t, t_norm);
4757 fn fold_region(&mut self, _: ty::Region) -> ty::Region {
4761 fn fold_substs(&mut self,
4762 substs: &subst::Substs)
4764 subst::Substs { regions: subst::ErasedRegions,
4765 types: substs.types.fold_with(self) }
4768 fn fold_sig(&mut self,
4771 // The binder-id is only relevant to bound regions, which
4772 // are erased at trans time.
4774 binder_id: ast::DUMMY_NODE_ID,
4775 inputs: sig.inputs.fold_with(self),
4776 output: sig.output.fold_with(self),
4777 variadic: sig.variadic,
4783 // Returns the repeat count for a repeating vector expression.
4784 pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> uint {
4785 match const_eval::eval_const_expr_partial(tcx, count_expr) {
4786 Ok(ref const_val) => match *const_val {
4787 const_eval::const_int(count) => if count < 0 {
4788 tcx.sess.span_err(count_expr.span,
4789 "expected positive integer for \
4790 repeat count, found negative integer");
4795 const_eval::const_uint(count) => count as uint,
4796 const_eval::const_float(count) => {
4797 tcx.sess.span_err(count_expr.span,
4798 "expected positive integer for \
4799 repeat count, found float");
4802 const_eval::const_str(_) => {
4803 tcx.sess.span_err(count_expr.span,
4804 "expected positive integer for \
4805 repeat count, found string");
4808 const_eval::const_bool(_) => {
4809 tcx.sess.span_err(count_expr.span,
4810 "expected positive integer for \
4811 repeat count, found boolean");
4814 const_eval::const_binary(_) => {
4815 tcx.sess.span_err(count_expr.span,
4816 "expected positive integer for \
4817 repeat count, found binary array");
4820 const_eval::const_nil => {
4821 tcx.sess.span_err(count_expr.span,
4822 "expected positive integer for \
4823 repeat count, found ()");
4828 tcx.sess.span_err(count_expr.span,
4829 "expected constant integer for repeat count, \
4836 // Iterate over a type parameter's bounded traits and any supertraits
4837 // of those traits, ignoring kinds.
4838 // Here, the supertraits are the transitive closure of the supertrait
4839 // relation on the supertraits from each bounded trait's constraint
4841 pub fn each_bound_trait_and_supertraits(tcx: &ctxt,
4842 bounds: &[Rc<TraitRef>],
4843 f: |Rc<TraitRef>| -> bool)
4846 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
4847 if !f(bound_trait_ref) {
4854 pub fn required_region_bounds(tcx: &ctxt,
4855 region_bounds: &[ty::Region],
4856 builtin_bounds: BuiltinBounds,
4857 trait_bounds: &[Rc<TraitRef>])
4861 * Given a type which must meet the builtin bounds and trait
4862 * bounds, returns a set of lifetimes which the type must outlive.
4864 * Requires that trait definitions have been processed.
4867 let mut all_bounds = Vec::new();
4869 debug!("required_region_bounds(builtin_bounds={}, trait_bounds={})",
4870 builtin_bounds.repr(tcx),
4871 trait_bounds.repr(tcx));
4873 all_bounds.push_all(region_bounds);
4875 push_region_bounds([],
4879 debug!("from builtin bounds: all_bounds={}", all_bounds.repr(tcx));
4881 each_bound_trait_and_supertraits(
4885 let bounds = ty::bounds_for_trait_ref(tcx, &*trait_ref);
4886 push_region_bounds(bounds.region_bounds.as_slice(),
4887 bounds.builtin_bounds,
4889 debug!("from {}: bounds={} all_bounds={}",
4890 trait_ref.repr(tcx),
4892 all_bounds.repr(tcx));
4898 fn push_region_bounds(region_bounds: &[ty::Region],
4899 builtin_bounds: ty::BuiltinBounds,
4900 all_bounds: &mut Vec<ty::Region>) {
4901 all_bounds.push_all(region_bounds.as_slice());
4903 if builtin_bounds.contains_elem(ty::BoundSend) {
4904 all_bounds.push(ty::ReStatic);
4909 pub fn get_tydesc_ty(tcx: &ctxt) -> Result<t, String> {
4910 tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
4911 tcx.intrinsic_defs.borrow().find_copy(&tydesc_lang_item)
4912 .expect("Failed to resolve TyDesc")
4916 pub fn get_opaque_ty(tcx: &ctxt) -> Result<t, String> {
4917 tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| {
4918 tcx.intrinsic_defs.borrow().find_copy(&opaque_lang_item)
4919 .expect("Failed to resolve Opaque")
4923 pub fn visitor_object_ty(tcx: &ctxt,
4924 ptr_region: ty::Region,
4925 trait_region: ty::Region)
4926 -> Result<(Rc<TraitRef>, t), String>
4928 let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) {
4930 Err(s) => { return Err(s); }
4932 let substs = Substs::empty();
4933 let trait_ref = Rc::new(TraitRef { def_id: trait_lang_item, substs: substs });
4934 Ok((trait_ref.clone(),
4935 mk_rptr(tcx, ptr_region,
4936 mt {mutbl: ast::MutMutable,
4939 trait_ref.substs.clone(),
4940 ty::region_existential_bound(trait_region))})))
4943 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> Rc<ItemVariances> {
4944 lookup_locally_or_in_crate_store(
4945 "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
4946 || Rc::new(csearch::get_item_variances(&tcx.sess.cstore, item_id)))
4949 /// Records a trait-to-implementation mapping.
4950 pub fn record_trait_implementation(tcx: &ctxt,
4951 trait_def_id: DefId,
4952 impl_def_id: DefId) {
4953 match tcx.trait_impls.borrow().find(&trait_def_id) {
4954 Some(impls_for_trait) => {
4955 impls_for_trait.borrow_mut().push(impl_def_id);
4960 tcx.trait_impls.borrow_mut().insert(trait_def_id, Rc::new(RefCell::new(vec!(impl_def_id))));
4963 /// Populates the type context with all the implementations for the given type
4965 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
4966 type_id: ast::DefId) {
4967 if type_id.krate == LOCAL_CRATE {
4970 if tcx.populated_external_types.borrow().contains(&type_id) {
4974 let mut inherent_impls = Vec::new();
4975 csearch::each_implementation_for_type(&tcx.sess.cstore, type_id,
4977 let impl_items = csearch::get_impl_items(&tcx.sess.cstore,
4980 // Record the trait->implementation mappings, if applicable.
4981 let associated_traits = csearch::get_impl_trait(tcx, impl_def_id);
4982 for trait_ref in associated_traits.iter() {
4983 record_trait_implementation(tcx, trait_ref.def_id, impl_def_id);
4986 // For any methods that use a default implementation, add them to
4987 // the map. This is a bit unfortunate.
4988 for impl_item_def_id in impl_items.iter() {
4989 let method_def_id = impl_item_def_id.def_id();
4990 match impl_or_trait_item(tcx, method_def_id) {
4991 MethodTraitItem(method) => {
4992 for &source in method.provided_source.iter() {
4993 tcx.provided_method_sources
4995 .insert(method_def_id, source);
4998 TypeTraitItem(_) => {}
5002 // Store the implementation info.
5003 tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
5005 // If this is an inherent implementation, record it.
5006 if associated_traits.is_none() {
5007 inherent_impls.push(impl_def_id);
5011 tcx.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
5012 tcx.populated_external_types.borrow_mut().insert(type_id);
5015 /// Populates the type context with all the implementations for the given
5016 /// trait if necessary.
5017 pub fn populate_implementations_for_trait_if_necessary(
5019 trait_id: ast::DefId) {
5020 if trait_id.krate == LOCAL_CRATE {
5023 if tcx.populated_external_traits.borrow().contains(&trait_id) {
5027 csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id,
5028 |implementation_def_id| {
5029 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, implementation_def_id);
5031 // Record the trait->implementation mapping.
5032 record_trait_implementation(tcx, trait_id, implementation_def_id);
5034 // For any methods that use a default implementation, add them to
5035 // the map. This is a bit unfortunate.
5036 for impl_item_def_id in impl_items.iter() {
5037 let method_def_id = impl_item_def_id.def_id();
5038 match impl_or_trait_item(tcx, method_def_id) {
5039 MethodTraitItem(method) => {
5040 for &source in method.provided_source.iter() {
5041 tcx.provided_method_sources
5043 .insert(method_def_id, source);
5046 TypeTraitItem(_) => {}
5050 // Store the implementation info.
5051 tcx.impl_items.borrow_mut().insert(implementation_def_id, impl_items);
5054 tcx.populated_external_traits.borrow_mut().insert(trait_id);
5057 /// Given the def_id of an impl, return the def_id of the trait it implements.
5058 /// If it implements no trait, return `None`.
5059 pub fn trait_id_of_impl(tcx: &ctxt,
5060 def_id: ast::DefId) -> Option<ast::DefId> {
5061 let node = match tcx.map.find(def_id.node) {
5066 ast_map::NodeItem(item) => {
5068 ast::ItemImpl(_, Some(ref trait_ref), _, _) => {
5069 Some(node_id_to_trait_ref(tcx, trait_ref.ref_id).def_id)
5078 /// If the given def ID describes a method belonging to an impl, return the
5079 /// ID of the impl that the method belongs to. Otherwise, return `None`.
5080 pub fn impl_of_method(tcx: &ctxt, def_id: ast::DefId)
5081 -> Option<ast::DefId> {
5082 if def_id.krate != LOCAL_CRATE {
5083 return match csearch::get_impl_or_trait_item(tcx,
5084 def_id).container() {
5085 TraitContainer(_) => None,
5086 ImplContainer(def_id) => Some(def_id),
5089 match tcx.impl_or_trait_items.borrow().find_copy(&def_id) {
5090 Some(trait_item) => {
5091 match trait_item.container() {
5092 TraitContainer(_) => None,
5093 ImplContainer(def_id) => Some(def_id),
5100 /// If the given def ID describes an item belonging to a trait (either a
5101 /// default method or an implementation of a trait method), return the ID of
5102 /// the trait that the method belongs to. Otherwise, return `None`.
5103 pub fn trait_of_item(tcx: &ctxt, def_id: ast::DefId) -> Option<ast::DefId> {
5104 if def_id.krate != LOCAL_CRATE {
5105 return csearch::get_trait_of_item(&tcx.sess.cstore, def_id, tcx);
5107 match tcx.impl_or_trait_items.borrow().find_copy(&def_id) {
5108 Some(impl_or_trait_item) => {
5109 match impl_or_trait_item.container() {
5110 TraitContainer(def_id) => Some(def_id),
5111 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
5118 /// If the given def ID describes an item belonging to a trait, (either a
5119 /// default method or an implementation of a trait method), return the ID of
5120 /// the method inside trait definition (this means that if the given def ID
5121 /// is already that of the original trait method, then the return value is
5123 /// Otherwise, return `None`.
5124 pub fn trait_item_of_item(tcx: &ctxt, def_id: ast::DefId)
5125 -> Option<ImplOrTraitItemId> {
5126 let impl_item = match tcx.impl_or_trait_items.borrow().find(&def_id) {
5127 Some(m) => m.clone(),
5128 None => return None,
5130 let name = impl_item.ident().name;
5131 match trait_of_item(tcx, def_id) {
5132 Some(trait_did) => {
5133 let trait_items = ty::trait_items(tcx, trait_did);
5135 .position(|m| m.ident().name == name)
5136 .map(|idx| ty::trait_item(tcx, trait_did, idx).id())
5142 /// Creates a hash of the type `t` which will be the same no matter what crate
5143 /// context it's calculated within. This is used by the `type_id` intrinsic.
5144 pub fn hash_crate_independent(tcx: &ctxt, t: t, svh: &Svh) -> u64 {
5145 let mut state = sip::SipState::new();
5146 macro_rules! byte( ($b:expr) => { ($b as u8).hash(&mut state) } );
5147 macro_rules! hash( ($e:expr) => { $e.hash(&mut state) } );
5149 let region = |_state: &mut sip::SipState, r: Region| {
5159 tcx.sess.bug("non-static region found when hashing a type")
5163 let did = |state: &mut sip::SipState, did: DefId| {
5164 let h = if ast_util::is_local(did) {
5167 tcx.sess.cstore.get_crate_hash(did.krate)
5169 h.as_str().hash(state);
5170 did.node.hash(state);
5172 let mt = |state: &mut sip::SipState, mt: mt| {
5173 mt.mutbl.hash(state);
5175 ty::walk_ty(t, |t| {
5176 match ty::get(t).sty {
5179 ty_bool => byte!(2),
5180 ty_char => byte!(3),
5206 ty_vec(_, Some(n)) => {
5210 ty_vec(_, None) => {
5212 0u8.hash(&mut state);
5220 region(&mut state, r);
5223 ty_bare_fn(ref b) => {
5228 ty_closure(ref c) => {
5234 UniqTraitStore => byte!(0),
5235 RegionTraitStore(r, m) => {
5237 region(&mut state, r);
5238 assert_eq!(m, ast::MutMutable);
5242 ty_trait(box TyTrait { def_id: d, bounds, .. }) => {
5247 ty_struct(d, _) => {
5251 ty_tup(ref inner) => {
5258 did(&mut state, p.def_id);
5260 ty_open(_) => byte!(22),
5261 ty_infer(_) => unreachable!(),
5262 ty_err => byte!(23),
5263 ty_unboxed_closure(d, r) => {
5266 region(&mut state, r);
5275 pub fn to_string(self) -> &'static str {
5278 Contravariant => "-",
5285 pub fn empty_parameter_environment() -> ParameterEnvironment {
5287 * Construct a parameter environment suitable for static contexts
5288 * or other contexts where there are no free type/lifetime
5289 * parameters in scope.
5292 ty::ParameterEnvironment { free_substs: Substs::empty(),
5293 bounds: VecPerParamSpace::empty(),
5294 caller_obligations: VecPerParamSpace::empty(),
5295 implicit_region_bound: ty::ReEmpty,
5296 selection_cache: traits::SelectionCache::new(), }
5299 pub fn construct_parameter_environment(
5302 generics: &ty::Generics,
5303 free_id: ast::NodeId)
5304 -> ParameterEnvironment
5306 /*! See `ParameterEnvironment` struct def'n for details */
5309 // Construct the free substs.
5313 let mut types = VecPerParamSpace::empty();
5314 for &space in subst::ParamSpace::all().iter() {
5315 push_types_from_defs(tcx, &mut types, space,
5316 generics.types.get_slice(space));
5319 // map bound 'a => free 'a
5320 let mut regions = VecPerParamSpace::empty();
5321 for &space in subst::ParamSpace::all().iter() {
5322 push_region_params(&mut regions, space, free_id,
5323 generics.regions.get_slice(space));
5326 let free_substs = Substs {
5328 regions: subst::NonerasedRegions(regions)
5332 // Compute the bounds on Self and the type parameters.
5335 let mut bounds = VecPerParamSpace::empty();
5336 for &space in subst::ParamSpace::all().iter() {
5337 push_bounds_from_defs(tcx, &mut bounds, space, &free_substs,
5338 generics.types.get_slice(space));
5342 // Compute region bounds. For now, these relations are stored in a
5343 // global table on the tcx, so just enter them there. I'm not
5344 // crazy about this scheme, but it's convenient, at least.
5347 for &space in subst::ParamSpace::all().iter() {
5348 record_region_bounds_from_defs(tcx, space, &free_substs,
5349 generics.regions.get_slice(space));
5353 debug!("construct_parameter_environment: free_id={} \
5357 free_substs.repr(tcx),
5360 let obligations = traits::obligations_for_generics(tcx, traits::ObligationCause::misc(span),
5361 generics, &free_substs);
5363 return ty::ParameterEnvironment {
5364 free_substs: free_substs,
5366 implicit_region_bound: ty::ReScope(free_id),
5367 caller_obligations: obligations,
5368 selection_cache: traits::SelectionCache::new(),
5371 fn push_region_params(regions: &mut VecPerParamSpace<ty::Region>,
5372 space: subst::ParamSpace,
5373 free_id: ast::NodeId,
5374 region_params: &[RegionParameterDef])
5376 for r in region_params.iter() {
5377 regions.push(space, ty::free_region_from_def(free_id, r));
5381 fn push_types_from_defs(tcx: &ty::ctxt,
5382 types: &mut subst::VecPerParamSpace<ty::t>,
5383 space: subst::ParamSpace,
5384 defs: &[TypeParameterDef]) {
5385 for (i, def) in defs.iter().enumerate() {
5386 debug!("construct_parameter_environment(): push_types_from_defs: \
5387 space={} def={} index={}",
5391 let ty = ty::mk_param(tcx, space, i, def.def_id);
5392 types.push(space, ty);
5396 fn push_bounds_from_defs(tcx: &ty::ctxt,
5397 bounds: &mut subst::VecPerParamSpace<ParamBounds>,
5398 space: subst::ParamSpace,
5399 free_substs: &subst::Substs,
5400 defs: &[TypeParameterDef]) {
5401 for def in defs.iter() {
5402 let b = def.bounds.subst(tcx, free_substs);
5403 bounds.push(space, b);
5407 fn record_region_bounds_from_defs(tcx: &ty::ctxt,
5408 space: subst::ParamSpace,
5409 free_substs: &subst::Substs,
5410 defs: &[RegionParameterDef]) {
5411 for (subst_region, def) in
5412 free_substs.regions().get_slice(space).iter().zip(
5415 // For each region parameter 'subst...
5416 let bounds = def.bounds.subst(tcx, free_substs);
5417 for bound_region in bounds.iter() {
5418 // Which is declared with a bound like 'subst:'bound...
5419 match (subst_region, bound_region) {
5420 (&ty::ReFree(subst_fr), &ty::ReFree(bound_fr)) => {
5421 // Record that 'subst outlives 'bound. Or, put
5422 // another way, 'bound <= 'subst.
5423 tcx.region_maps.relate_free_regions(bound_fr, subst_fr);
5426 // All named regions are instantiated with free regions.
5428 format!("push_region_bounds_from_defs: \
5429 non free region: {} / {}",
5430 subst_region.repr(tcx),
5431 bound_region.repr(tcx)).as_slice());
5440 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
5442 ast::MutMutable => MutBorrow,
5443 ast::MutImmutable => ImmBorrow,
5447 pub fn to_mutbl_lossy(self) -> ast::Mutability {
5449 * Returns a mutability `m` such that an `&m T` pointer could
5450 * be used to obtain this borrow kind. Because borrow kinds
5451 * are richer than mutabilities, we sometimes have to pick a
5452 * mutability that is stronger than necessary so that it at
5453 * least *would permit* the borrow in question.
5457 MutBorrow => ast::MutMutable,
5458 ImmBorrow => ast::MutImmutable,
5460 // We have no type correponding to a unique imm borrow, so
5461 // use `&mut`. It gives all the capabilities of an `&uniq`
5462 // and hence is a safe "over approximation".
5463 UniqueImmBorrow => ast::MutMutable,
5467 pub fn to_user_str(&self) -> &'static str {
5469 MutBorrow => "mutable",
5470 ImmBorrow => "immutable",
5471 UniqueImmBorrow => "uniquely immutable",
5476 impl<'tcx> mc::Typer<'tcx> for ty::ctxt<'tcx> {
5477 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
5481 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<ty::t> {
5482 Ok(ty::node_id_to_type(self, id))
5485 fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t> {
5486 self.method_map.borrow().find(&method_call).map(|method| method.ty)
5489 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment>> {
5493 fn is_method_call(&self, id: ast::NodeId) -> bool {
5494 self.method_map.borrow().contains_key(&typeck::MethodCall::expr(id))
5497 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<ast::NodeId> {
5498 self.region_maps.temporary_scope(rvalue_id)
5501 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow {
5502 self.upvar_borrow_map.borrow().get_copy(&upvar_id)
5505 fn capture_mode(&self, closure_expr_id: ast::NodeId)
5506 -> ast::CaptureClause {
5507 self.capture_modes.borrow().get_copy(&closure_expr_id)
5510 fn unboxed_closures<'a>(&'a self)
5511 -> &'a RefCell<DefIdMap<UnboxedClosure>> {
5512 &self.unboxed_closures
5516 /// The category of explicit self.
5517 #[deriving(Clone, Eq, PartialEq)]
5518 pub enum ExplicitSelfCategory {
5519 StaticExplicitSelfCategory,
5520 ByValueExplicitSelfCategory,
5521 ByReferenceExplicitSelfCategory(Region, ast::Mutability),
5522 ByBoxExplicitSelfCategory,
5525 /// Pushes all the lifetimes in the given type onto the given list. A
5526 /// "lifetime in a type" is a lifetime specified by a reference or a lifetime
5527 /// in a list of type substitutions. This does *not* traverse into nominal
5528 /// types, nor does it resolve fictitious types.
5529 pub fn accumulate_lifetimes_in_type(accumulator: &mut Vec<ty::Region>,
5531 walk_ty(typ, |typ| {
5532 match get(typ).sty {
5533 ty_rptr(region, _) => accumulator.push(region),
5534 ty_enum(_, ref substs) |
5535 ty_trait(box TyTrait {
5539 ty_struct(_, ref substs) => {
5540 match substs.regions {
5541 subst::ErasedRegions => {}
5542 subst::NonerasedRegions(ref regions) => {
5543 for region in regions.iter() {
5544 accumulator.push(*region)
5549 ty_closure(ref closure_ty) => {
5550 match closure_ty.store {
5551 RegionTraitStore(region, _) => accumulator.push(region),
5552 UniqTraitStore => {}
5555 ty_unboxed_closure(_, ref region) => accumulator.push(*region),
5578 /// A free variable referred to in a function.
5579 #[deriving(Encodable, Decodable)]
5580 pub struct Freevar {
5581 /// The variable being accessed free.
5584 // First span where it is accessed (there can be multiple).
5588 pub type FreevarMap = NodeMap<Vec<Freevar>>;
5590 pub type CaptureModeMap = NodeMap<ast::CaptureClause>;
5592 pub fn with_freevars<T>(tcx: &ty::ctxt, fid: ast::NodeId, f: |&[Freevar]| -> T) -> T {
5593 match tcx.freevars.borrow().find(&fid) {
5595 Some(d) => f(d.as_slice())