1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(non_camel_case_types)]
14 use driver::session::Session;
16 use metadata::csearch;
17 use middle::const_eval;
19 use middle::dependency_format;
20 use middle::freevars::CaptureModeMap;
22 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem};
23 use middle::lang_items::{FnOnceTraitLangItem, OpaqueStructLangItem};
24 use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem};
25 use middle::mem_categorization as mc;
27 use middle::resolve_lifetime;
28 use middle::stability;
29 use middle::subst::{Subst, Substs, VecPerParamSpace};
35 use middle::ty_fold::{TypeFoldable,TypeFolder};
37 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_string};
38 use util::ppaux::{trait_store_to_string, ty_to_string};
39 use util::ppaux::{Repr, UserString};
40 use util::common::{indenter};
41 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet, FnvHashMap};
43 use std::cell::{Cell, RefCell};
47 use std::hash::{Hash, sip, Writer};
48 use std::iter::AdditiveIterator;
52 use std::collections::{HashMap, HashSet};
53 use arena::TypedArena;
55 use syntax::ast::{CrateNum, DefId, FnStyle, Ident, ItemTrait, LOCAL_CRATE};
56 use syntax::ast::{MutImmutable, MutMutable, Name, NamedField, NodeId};
57 use syntax::ast::{Onceness, StmtExpr, StmtSemi, StructField, UnnamedField};
58 use syntax::ast::{Visibility};
59 use syntax::ast_util::{PostExpansionMethod, is_local, lit_is_str};
62 use syntax::attr::AttrMetaMethods;
63 use syntax::codemap::Span;
64 use syntax::parse::token;
65 use syntax::parse::token::InternedString;
66 use syntax::{ast, ast_map};
67 use syntax::util::small_vector::SmallVector;
68 use std::collections::enum_set::{EnumSet, CLike};
72 pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0;
76 #[deriving(PartialEq, Eq, Hash)]
78 pub ident: ast::Ident,
83 pub enum ImplOrTraitItemContainer {
84 TraitContainer(ast::DefId),
85 ImplContainer(ast::DefId),
88 impl ImplOrTraitItemContainer {
89 pub fn id(&self) -> ast::DefId {
91 TraitContainer(id) => id,
92 ImplContainer(id) => id,
98 pub enum ImplOrTraitItem {
99 MethodTraitItem(Rc<Method>),
100 TypeTraitItem(Rc<AssociatedType>),
103 impl ImplOrTraitItem {
104 fn id(&self) -> ImplOrTraitItemId {
106 MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
107 TypeTraitItem(ref associated_type) => {
108 TypeTraitItemId(associated_type.def_id)
113 pub fn def_id(&self) -> ast::DefId {
115 MethodTraitItem(ref method) => method.def_id,
116 TypeTraitItem(ref associated_type) => associated_type.def_id,
120 pub fn ident(&self) -> ast::Ident {
122 MethodTraitItem(ref method) => method.ident,
123 TypeTraitItem(ref associated_type) => associated_type.ident,
127 pub fn container(&self) -> ImplOrTraitItemContainer {
129 MethodTraitItem(ref method) => method.container,
130 TypeTraitItem(ref associated_type) => associated_type.container,
136 pub enum ImplOrTraitItemId {
137 MethodTraitItemId(ast::DefId),
138 TypeTraitItemId(ast::DefId),
141 impl ImplOrTraitItemId {
142 pub fn def_id(&self) -> ast::DefId {
144 MethodTraitItemId(def_id) => def_id,
145 TypeTraitItemId(def_id) => def_id,
152 pub ident: ast::Ident,
153 pub generics: ty::Generics,
155 pub explicit_self: ExplicitSelfCategory,
156 pub vis: ast::Visibility,
157 pub def_id: ast::DefId,
158 pub container: ImplOrTraitItemContainer,
160 // If this method is provided, we need to know where it came from
161 pub provided_source: Option<ast::DefId>
165 pub fn new(ident: ast::Ident,
166 generics: ty::Generics,
168 explicit_self: ExplicitSelfCategory,
169 vis: ast::Visibility,
171 container: ImplOrTraitItemContainer,
172 provided_source: Option<ast::DefId>)
178 explicit_self: explicit_self,
181 container: container,
182 provided_source: provided_source
186 pub fn container_id(&self) -> ast::DefId {
187 match self.container {
188 TraitContainer(id) => id,
189 ImplContainer(id) => id,
195 pub struct AssociatedType {
196 pub ident: ast::Ident,
197 pub vis: ast::Visibility,
198 pub def_id: ast::DefId,
199 pub container: ImplOrTraitItemContainer,
202 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
205 pub mutbl: ast::Mutability,
208 #[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
209 pub enum TraitStore {
212 /// &Trait and &mut Trait
213 RegionTraitStore(Region, ast::Mutability),
216 #[deriving(Clone, Show)]
217 pub struct field_ty {
220 pub vis: ast::Visibility,
221 pub origin: ast::DefId, // The DefId of the struct in which the field is declared.
224 // Contains information needed to resolve types and (in the future) look up
225 // the types of AST nodes.
226 #[deriving(PartialEq, Eq, Hash)]
227 pub struct creader_cache_key {
233 pub type creader_cache = RefCell<HashMap<creader_cache_key, t>>;
235 pub struct intern_key {
239 // NB: Do not replace this with #[deriving(PartialEq)]. The automatically-derived
240 // implementation will not recurse through sty and you will get stack
242 impl cmp::PartialEq for intern_key {
243 fn eq(&self, other: &intern_key) -> bool {
245 *self.sty == *other.sty
248 fn ne(&self, other: &intern_key) -> bool {
253 impl Eq for intern_key {}
255 impl<W:Writer> Hash<W> for intern_key {
256 fn hash(&self, s: &mut W) {
257 unsafe { (*self.sty).hash(s) }
261 pub enum ast_ty_to_ty_cache_entry {
262 atttce_unresolved, /* not resolved yet */
263 atttce_resolved(t) /* resolved to a type, irrespective of region */
266 #[deriving(Clone, PartialEq, Decodable, Encodable)]
267 pub struct ItemVariances {
268 pub types: VecPerParamSpace<Variance>,
269 pub regions: VecPerParamSpace<Variance>,
272 #[deriving(Clone, PartialEq, Decodable, Encodable, Show)]
274 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
275 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
276 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
277 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
281 pub enum AutoAdjustment {
282 AutoAddEnv(ty::TraitStore),
283 AutoDerefRef(AutoDerefRef)
286 #[deriving(Clone, PartialEq)]
287 pub enum UnsizeKind {
288 // [T, ..n] -> [T], the uint field is n.
290 // An unsize coercion applied to the tail field of a struct.
291 // The uint is the index of the type parameter which is unsized.
292 UnsizeStruct(Box<UnsizeKind>, uint),
293 UnsizeVtable(TyTrait, /* the self type of the trait */ ty::t)
297 pub struct AutoDerefRef {
298 pub autoderefs: uint,
299 pub autoref: Option<AutoRef>
302 #[deriving(Clone, PartialEq)]
304 /// Convert from T to &T
305 /// The third field allows us to wrap other AutoRef adjustments.
306 AutoPtr(Region, ast::Mutability, Option<Box<AutoRef>>),
308 /// Convert [T, ..n] to [T] (or similar, depending on the kind)
309 AutoUnsize(UnsizeKind),
311 /// Convert Box<[T, ..n]> to Box<[T]> or something similar in a Box.
312 /// With DST and Box a library type, this should be replaced by UnsizeStruct.
313 AutoUnsizeUniq(UnsizeKind),
315 /// Convert from T to *T
316 /// Value to thin pointer
317 /// The second field allows us to wrap other AutoRef adjustments.
318 AutoUnsafe(ast::Mutability, Option<Box<AutoRef>>),
321 // Ugly little helper function. The first bool in the returned tuple is true if
322 // there is an 'unsize to trait object' adjustment at the bottom of the
323 // adjustment. If that is surrounded by an AutoPtr, then we also return the
324 // region of the AutoPtr (in the third argument). The second bool is true if the
325 // adjustment is unique.
326 fn autoref_object_region(autoref: &AutoRef) -> (bool, bool, Option<Region>) {
327 fn unsize_kind_is_object(k: &UnsizeKind) -> bool {
329 &UnsizeVtable(..) => true,
330 &UnsizeStruct(box ref k, _) => unsize_kind_is_object(k),
336 &AutoUnsize(ref k) => (unsize_kind_is_object(k), false, None),
337 &AutoUnsizeUniq(ref k) => (unsize_kind_is_object(k), true, None),
338 &AutoPtr(adj_r, _, Some(box ref autoref)) => {
339 let (b, u, r) = autoref_object_region(autoref);
340 if r.is_some() || u {
346 &AutoUnsafe(_, Some(box ref autoref)) => autoref_object_region(autoref),
347 _ => (false, false, None)
351 // If the adjustment introduces a borrowed reference to a trait object, then
352 // returns the region of the borrowed reference.
353 pub fn adjusted_object_region(adj: &AutoAdjustment) -> Option<Region> {
355 &AutoDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
356 let (b, _, r) = autoref_object_region(autoref);
367 // Returns true if there is a trait cast at the bottom of the adjustment.
368 pub fn adjust_is_object(adj: &AutoAdjustment) -> bool {
370 &AutoDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
371 let (b, _, _) = autoref_object_region(autoref);
378 // If possible, returns the type expected from the given adjustment. This is not
379 // possible if the adjustment depends on the type of the adjusted expression.
380 pub fn type_of_adjust(cx: &ctxt, adj: &AutoAdjustment) -> Option<t> {
381 fn type_of_autoref(cx: &ctxt, autoref: &AutoRef) -> Option<t> {
383 &AutoUnsize(ref k) => match k {
384 &UnsizeVtable(TyTrait { def_id, substs: ref substs, bounds }, _) => {
385 Some(mk_trait(cx, def_id, substs.clone(), bounds))
389 &AutoUnsizeUniq(ref k) => match k {
390 &UnsizeVtable(TyTrait { def_id, substs: ref substs, bounds }, _) => {
391 Some(mk_uniq(cx, mk_trait(cx, def_id, substs.clone(), bounds)))
395 &AutoPtr(r, m, Some(box ref autoref)) => {
396 match type_of_autoref(cx, autoref) {
397 Some(t) => Some(mk_rptr(cx, r, mt {mutbl: m, ty: t})),
401 &AutoUnsafe(m, Some(box ref autoref)) => {
402 match type_of_autoref(cx, autoref) {
403 Some(t) => Some(mk_ptr(cx, mt {mutbl: m, ty: t})),
412 &AutoDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
413 type_of_autoref(cx, autoref)
421 /// A restriction that certain types must be the same size. The use of
422 /// `transmute` gives rise to these restrictions.
423 pub struct TransmuteRestriction {
424 /// The span from whence the restriction comes.
426 /// The type being transmuted from.
428 /// The type being transmuted to.
430 /// NodeIf of the transmute intrinsic.
434 /// The data structure to keep track of all the information that typechecker
435 /// generates so that so that it can be reused and doesn't have to be redone
437 pub struct ctxt<'tcx> {
438 /// The arena that types are allocated from.
439 type_arena: &'tcx TypedArena<t_box_>,
441 /// Specifically use a speedy hash algorithm for this hash map, it's used
443 interner: RefCell<FnvHashMap<intern_key, &'tcx t_box_>>,
444 pub next_id: Cell<uint>,
446 pub def_map: resolve::DefMap,
448 pub named_region_map: resolve_lifetime::NamedRegionMap,
450 pub region_maps: middle::region::RegionMaps,
452 /// Stores the types for various nodes in the AST. Note that this table
453 /// is not guaranteed to be populated until after typeck. See
454 /// typeck::check::fn_ctxt for details.
455 pub node_types: node_type_table,
457 /// Stores the type parameters which were substituted to obtain the type
458 /// of this node. This only applies to nodes that refer to entities
459 /// parameterized by type parameters, such as generic fns, types, or
461 pub item_substs: RefCell<NodeMap<ItemSubsts>>,
463 /// Maps from a trait item to the trait item "descriptor"
464 pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem>>,
466 /// Maps from a trait def-id to a list of the def-ids of its trait items
467 pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
469 /// A cache for the trait_items() routine
470 pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem>>>>,
472 pub impl_trait_cache: RefCell<DefIdMap<Option<Rc<ty::TraitRef>>>>,
474 pub trait_refs: RefCell<NodeMap<Rc<TraitRef>>>,
475 pub trait_defs: RefCell<DefIdMap<Rc<TraitDef>>>,
477 /// Maps from node-id of a trait object cast (like `foo as
478 /// Box<Trait>`) to the trait reference.
479 pub object_cast_map: typeck::ObjectCastMap,
481 pub map: ast_map::Map<'tcx>,
482 pub intrinsic_defs: RefCell<DefIdMap<t>>,
483 pub freevars: RefCell<freevars::freevar_map>,
484 pub tcache: type_cache,
485 pub rcache: creader_cache,
486 pub short_names_cache: RefCell<HashMap<t, String>>,
487 pub needs_unwind_cleanup_cache: RefCell<HashMap<t, bool>>,
488 pub tc_cache: RefCell<HashMap<uint, TypeContents>>,
489 pub ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry>>,
490 pub enum_var_cache: RefCell<DefIdMap<Rc<Vec<Rc<VariantInfo>>>>>,
491 pub ty_param_defs: RefCell<NodeMap<TypeParameterDef>>,
492 pub adjustments: RefCell<NodeMap<AutoAdjustment>>,
493 pub normalized_cache: RefCell<HashMap<t, t>>,
494 pub lang_items: middle::lang_items::LanguageItems,
495 /// A mapping of fake provided method def_ids to the default implementation
496 pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
497 pub superstructs: RefCell<DefIdMap<Option<ast::DefId>>>,
498 pub struct_fields: RefCell<DefIdMap<Rc<Vec<field_ty>>>>,
500 /// Maps from def-id of a type or region parameter to its
501 /// (inferred) variance.
502 pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
504 /// True if the variance has been computed yet; false otherwise.
505 pub variance_computed: Cell<bool>,
507 /// A mapping from the def ID of an enum or struct type to the def ID
508 /// of the method that implements its destructor. If the type is not
509 /// present in this map, it does not have a destructor. This map is
510 /// populated during the coherence phase of typechecking.
511 pub destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
513 /// A method will be in this list if and only if it is a destructor.
514 pub destructors: RefCell<DefIdSet>,
516 /// Maps a trait onto a list of impls of that trait.
517 pub trait_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
519 /// Maps a DefId of a type to a list of its inherent impls.
520 /// Contains implementations of methods that are inherent to a type.
521 /// Methods in these implementations don't need to be exported.
522 pub inherent_impls: RefCell<DefIdMap<Rc<Vec<ast::DefId>>>>,
524 /// Maps a DefId of an impl to a list of its items.
525 /// Note that this contains all of the impls that we know about,
526 /// including ones in other crates. It's not clear that this is the best
528 pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
530 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
531 /// present in this set can be warned about.
532 pub used_unsafe: RefCell<NodeSet>,
534 /// Set of nodes which mark locals as mutable which end up getting used at
535 /// some point. Local variable definitions not in this set can be warned
537 pub used_mut_nodes: RefCell<NodeSet>,
539 /// The set of external nominal types whose implementations have been read.
540 /// This is used for lazy resolution of methods.
541 pub populated_external_types: RefCell<DefIdSet>,
543 /// The set of external traits whose implementations have been read. This
544 /// is used for lazy resolution of traits.
545 pub populated_external_traits: RefCell<DefIdSet>,
548 pub upvar_borrow_map: RefCell<UpvarBorrowMap>,
550 /// These two caches are used by const_eval when decoding external statics
551 /// and variants that are found.
552 pub extern_const_statics: RefCell<DefIdMap<ast::NodeId>>,
553 pub extern_const_variants: RefCell<DefIdMap<ast::NodeId>>,
555 pub method_map: typeck::MethodMap,
557 pub dependency_formats: RefCell<dependency_format::Dependencies>,
559 /// Records the type of each unboxed closure. The def ID is the ID of the
560 /// expression defining the unboxed closure.
561 pub unboxed_closures: RefCell<DefIdMap<UnboxedClosure>>,
563 pub node_lint_levels: RefCell<HashMap<(ast::NodeId, lint::LintId),
566 /// The types that must be asserted to be the same size for `transmute`
567 /// to be valid. We gather up these restrictions in the intrinsicck pass
568 /// and check them in trans.
569 pub transmute_restrictions: RefCell<Vec<TransmuteRestriction>>,
571 /// Maps any item's def-id to its stability index.
572 pub stability: RefCell<stability::Index>,
574 /// Maps closures to their capture clauses.
575 pub capture_modes: RefCell<CaptureModeMap>,
577 /// Maps def IDs to true if and only if they're associated types.
578 pub associated_types: RefCell<DefIdMap<bool>>,
580 /// Maps def IDs of traits to information about their associated types.
581 pub trait_associated_types:
582 RefCell<DefIdMap<Rc<Vec<AssociatedTypeInfo>>>>,
593 // a meta-pub flag: subst may be required if the type has parameters, a self
594 // type, or references bound regions
595 needs_subst = 1 | 2 | 8
598 pub type t_box = &'static t_box_;
607 // To reduce refcounting cost, we're representing types as unsafe pointers
608 // throughout the compiler. These are simply casted t_box values. Use ty::get
609 // to cast them back to a box. (Without the cast, compiler performance suffers
610 // ~15%.) This does mean that a t value relies on the ctxt to keep its box
611 // alive, and using ty::get is unsafe when the ctxt is no longer alive.
614 #[allow(raw_pointer_deriving)]
615 #[deriving(Clone, PartialEq, Eq, Hash)]
616 pub struct t { inner: *const t_opaque }
618 impl fmt::Show for t {
619 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
620 write!(f, "{}", get(*self))
624 pub fn get(t: t) -> t_box {
626 let t2: t_box = mem::transmute(t);
631 pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
632 (tb.flags & (flag as uint)) != 0u
634 pub fn type_has_params(t: t) -> bool {
635 tbox_has_flag(get(t), has_params)
637 pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
638 pub fn type_needs_infer(t: t) -> bool {
639 tbox_has_flag(get(t), needs_infer)
641 pub fn type_id(t: t) -> uint { get(t).id }
643 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
644 pub struct BareFnTy {
645 pub fn_style: ast::FnStyle,
650 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
651 pub struct ClosureTy {
652 pub fn_style: ast::FnStyle,
653 pub onceness: ast::Onceness,
654 pub store: TraitStore,
655 pub bounds: ExistentialBounds,
661 * Signature of a function type, which I have arbitrarily
662 * decided to use to refer to the input/output types.
664 * - `binder_id` is the node id where this fn type appeared;
665 * it is used to identify all the bound regions appearing
666 * in the input/output types that are bound by this fn type
667 * (vs some enclosing or enclosed fn type)
668 * - `inputs` is the list of arguments and their modes.
669 * - `output` is the return type.
670 * - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
672 #[deriving(Clone, PartialEq, Eq, Hash)]
674 pub binder_id: ast::NodeId,
680 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
682 pub space: subst::ParamSpace,
687 /// Representation of regions:
688 #[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
690 // Region bound in a type or fn declaration which will be
691 // substituted 'early' -- that is, at the same time when type
692 // parameters are substituted.
693 ReEarlyBound(/* param id */ ast::NodeId,
698 // Region bound in a function scope, which will be substituted when the
699 // function is called. The first argument must be the `binder_id` of
700 // some enclosing function signature.
701 ReLateBound(/* binder_id */ ast::NodeId, BoundRegion),
703 /// When checking a function body, the types of all arguments and so forth
704 /// that refer to bound region parameters are modified to refer to free
705 /// region parameters.
708 /// A concrete region naming some expression within the current function.
711 /// Static data that has an "infinite" lifetime. Top in the region lattice.
714 /// A region variable. Should not exist after typeck.
715 ReInfer(InferRegion),
717 /// Empty lifetime is for data that is never accessed.
718 /// Bottom in the region lattice. We treat ReEmpty somewhat
719 /// specially; at least right now, we do not generate instances of
720 /// it during the GLB computations, but rather
721 /// generate an error instead. This is to improve error messages.
722 /// The only way to get an instance of ReEmpty is to have a region
723 /// variable with no constraints.
728 * Upvars do not get their own node-id. Instead, we use the pair of
729 * the original var id (that is, the root variable that is referenced
730 * by the upvar) and the id of the closure expression.
732 #[deriving(Clone, PartialEq, Eq, Hash)]
734 pub var_id: ast::NodeId,
735 pub closure_expr_id: ast::NodeId,
738 #[deriving(Clone, PartialEq, Eq, Hash, Show, Encodable, Decodable)]
739 pub enum BorrowKind {
740 /// Data must be immutable and is aliasable.
743 /// Data must be immutable but not aliasable. This kind of borrow
744 /// cannot currently be expressed by the user and is used only in
745 /// implicit closure bindings. It is needed when you the closure
746 /// is borrowing or mutating a mutable referent, e.g.:
748 /// let x: &mut int = ...;
749 /// let y = || *x += 5;
751 /// If we were to try to translate this closure into a more explicit
752 /// form, we'd encounter an error with the code as written:
754 /// struct Env { x: & &mut int }
755 /// let x: &mut int = ...;
756 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
757 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
759 /// This is then illegal because you cannot mutate a `&mut` found
760 /// in an aliasable location. To solve, you'd have to translate with
761 /// an `&mut` borrow:
763 /// struct Env { x: & &mut int }
764 /// let x: &mut int = ...;
765 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
766 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
768 /// Now the assignment to `**env.x` is legal, but creating a
769 /// mutable pointer to `x` is not because `x` is not mutable. We
770 /// could fix this by declaring `x` as `let mut x`. This is ok in
771 /// user code, if awkward, but extra weird for closures, since the
772 /// borrow is hidden.
774 /// So we introduce a "unique imm" borrow -- the referent is
775 /// immutable, but not aliasable. This solves the problem. For
776 /// simplicity, we don't give users the way to express this
777 /// borrow, it's just used when translating closures.
780 /// Data is mutable and not aliasable.
785 * Information describing the borrowing of an upvar. This is computed
786 * during `typeck`, specifically by `regionck`. The general idea is
787 * that the compiler analyses treat closures like:
789 * let closure: &'e fn() = || {
790 * x = 1; // upvar x is assigned to
791 * use(y); // upvar y is read
792 * foo(&z); // upvar z is borrowed immutably
795 * as if they were "desugared" to something loosely like:
797 * struct Vars<'x,'y,'z> { x: &'x mut int,
800 * let closure: &'e fn() = {
806 * let env: &'e mut Vars<'x,'y,'z> = &mut Vars { x: &'x mut x,
812 * This is basically what happens at runtime. The closure is basically
813 * an existentially quantified version of the `(env, f)` pair.
815 * This data structure indicates the region and mutability of a single
816 * one of the `x...z` borrows.
818 * It may not be obvious why each borrowed variable gets its own
819 * lifetime (in the desugared version of the example, these are indicated
820 * by the lifetime parameters `'x`, `'y`, and `'z` in the `Vars` definition).
821 * Each such lifetime must encompass the lifetime `'e` of the closure itself,
822 * but need not be identical to it. The reason that this makes sense:
824 * - Callers are only permitted to invoke the closure, and hence to
825 * use the pointers, within the lifetime `'e`, so clearly `'e` must
826 * be a sublifetime of `'x...'z`.
827 * - The closure creator knows which upvars were borrowed by the closure
828 * and thus `x...z` will be reserved for `'x...'z` respectively.
829 * - Through mutation, the borrowed upvars can actually escape
830 * the closure, so sometimes it is necessary for them to be larger
831 * than the closure lifetime itself.
833 #[deriving(PartialEq, Clone, Encodable, Decodable)]
834 pub struct UpvarBorrow {
835 pub kind: BorrowKind,
836 pub region: ty::Region,
839 pub type UpvarBorrowMap = HashMap<UpvarId, UpvarBorrow>;
842 pub fn is_bound(&self) -> bool {
844 &ty::ReEarlyBound(..) => true,
845 &ty::ReLateBound(..) => true,
851 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
852 pub struct FreeRegion {
853 pub scope_id: NodeId,
854 pub bound_region: BoundRegion
857 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
858 pub enum BoundRegion {
859 /// An anonymous region parameter for a given fn (&T)
862 /// Named region parameters for functions (a in &'a T)
864 /// The def-id is needed to distinguish free regions in
865 /// the event of shadowing.
866 BrNamed(ast::DefId, ast::Name),
868 /// Fresh bound identifiers created during GLB computations.
877 macro_rules! def_prim_ty(
878 ($name:ident, $sty:expr, $id:expr) => (
879 pub static $name: t_box_ = t_box_ {
887 def_prim_ty!(TY_NIL, super::ty_nil, 0)
888 def_prim_ty!(TY_BOOL, super::ty_bool, 1)
889 def_prim_ty!(TY_CHAR, super::ty_char, 2)
890 def_prim_ty!(TY_INT, super::ty_int(ast::TyI), 3)
891 def_prim_ty!(TY_I8, super::ty_int(ast::TyI8), 4)
892 def_prim_ty!(TY_I16, super::ty_int(ast::TyI16), 5)
893 def_prim_ty!(TY_I32, super::ty_int(ast::TyI32), 6)
894 def_prim_ty!(TY_I64, super::ty_int(ast::TyI64), 7)
895 def_prim_ty!(TY_UINT, super::ty_uint(ast::TyU), 8)
896 def_prim_ty!(TY_U8, super::ty_uint(ast::TyU8), 9)
897 def_prim_ty!(TY_U16, super::ty_uint(ast::TyU16), 10)
898 def_prim_ty!(TY_U32, super::ty_uint(ast::TyU32), 11)
899 def_prim_ty!(TY_U64, super::ty_uint(ast::TyU64), 12)
900 def_prim_ty!(TY_F32, super::ty_float(ast::TyF32), 14)
901 def_prim_ty!(TY_F64, super::ty_float(ast::TyF64), 15)
903 pub static TY_BOT: t_box_ = t_box_ {
906 flags: super::has_ty_bot as uint,
909 pub static TY_ERR: t_box_ = t_box_ {
912 flags: super::has_ty_err as uint,
915 pub static LAST_PRIMITIVE_ID: uint = 18;
918 // NB: If you change this, you'll probably want to change the corresponding
919 // AST structure in libsyntax/ast.rs as well.
920 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
927 ty_uint(ast::UintTy),
928 ty_float(ast::FloatTy),
929 /// Substs here, possibly against intuition, *may* contain `ty_param`s.
930 /// That is, even after substitution it is possible that there are type
931 /// variables. This happens when the `ty_enum` corresponds to an enum
932 /// definition and not a concrete use of it. To get the correct `ty_enum`
933 /// from the tcx, use the `NodeId` from the `ast::Ty` and look it up in
934 /// the `ast_ty_to_ty_cache`. This is probably true for `ty_struct` as
936 ty_enum(DefId, Substs),
940 ty_vec(t, Option<uint>), // Second field is length.
943 ty_bare_fn(BareFnTy),
944 ty_closure(Box<ClosureTy>),
945 ty_trait(Box<TyTrait>),
946 ty_struct(DefId, Substs),
947 ty_unboxed_closure(DefId, Region),
950 ty_param(ParamTy), // type parameter
951 ty_open(t), // A deref'ed fat pointer, i.e., a dynamically sized value
952 // and its size. Only ever used in trans. It is not necessary
953 // earlier since we don't need to distinguish a DST with its
954 // size (e.g., in a deref) vs a DST with the size elsewhere (
955 // e.g., in a field).
957 ty_infer(InferTy), // something used only during inference/typeck
958 ty_err, // Also only used during inference/typeck, to represent
959 // the type of an erroneous expression (helps cut down
960 // on non-useful type error messages)
963 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
967 pub bounds: ExistentialBounds
970 #[deriving(PartialEq, Eq, Hash, Show)]
971 pub struct TraitRef {
976 #[deriving(Clone, PartialEq)]
977 pub enum IntVarValue {
979 UintType(ast::UintTy),
982 #[deriving(Clone, Show)]
983 pub enum terr_vstore_kind {
990 #[deriving(Clone, Show)]
991 pub struct expected_found<T> {
996 // Data structures used in type unification
997 #[deriving(Clone, Show)]
1000 terr_fn_style_mismatch(expected_found<FnStyle>),
1001 terr_onceness_mismatch(expected_found<Onceness>),
1002 terr_abi_mismatch(expected_found<abi::Abi>),
1004 terr_sigil_mismatch(expected_found<TraitStore>),
1005 terr_box_mutability,
1006 terr_ptr_mutability,
1007 terr_ref_mutability,
1008 terr_vec_mutability,
1009 terr_tuple_size(expected_found<uint>),
1010 terr_ty_param_size(expected_found<uint>),
1011 terr_record_size(expected_found<uint>),
1012 terr_record_mutability,
1013 terr_record_fields(expected_found<Ident>),
1015 terr_regions_does_not_outlive(Region, Region),
1016 terr_regions_not_same(Region, Region),
1017 terr_regions_no_overlap(Region, Region),
1018 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
1019 terr_regions_overly_polymorphic(BoundRegion, Region),
1020 terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
1021 terr_sorts(expected_found<t>),
1022 terr_integer_as_char,
1023 terr_int_mismatch(expected_found<IntVarValue>),
1024 terr_float_mismatch(expected_found<ast::FloatTy>),
1025 terr_traits(expected_found<ast::DefId>),
1026 terr_builtin_bounds(expected_found<BuiltinBounds>),
1027 terr_variadic_mismatch(expected_found<bool>),
1031 /// Bounds suitable for a named type parameter like `A` in `fn foo<A>`
1032 /// as well as the existential type parameter in an object type.
1033 #[deriving(PartialEq, Eq, Hash, Clone, Show)]
1034 pub struct ParamBounds {
1035 pub region_bounds: Vec<ty::Region>,
1036 pub builtin_bounds: BuiltinBounds,
1037 pub trait_bounds: Vec<Rc<TraitRef>>
1040 /// Bounds suitable for an existentially quantified type parameter
1041 /// such as those that appear in object types or closure types. The
1042 /// major difference between this case and `ParamBounds` is that
1043 /// general purpose trait bounds are omitted and there must be
1044 /// *exactly one* region.
1045 #[deriving(PartialEq, Eq, Hash, Clone, Show)]
1046 pub struct ExistentialBounds {
1047 pub region_bound: ty::Region,
1048 pub builtin_bounds: BuiltinBounds
1051 pub type BuiltinBounds = EnumSet<BuiltinBound>;
1053 #[deriving(Clone, Encodable, PartialEq, Eq, Decodable, Hash, Show)]
1055 pub enum BuiltinBound {
1062 pub fn empty_builtin_bounds() -> BuiltinBounds {
1066 pub fn all_builtin_bounds() -> BuiltinBounds {
1067 let mut set = EnumSet::empty();
1069 set.add(BoundSized);
1074 pub fn region_existential_bound(r: ty::Region) -> ExistentialBounds {
1076 * An existential bound that does not implement any traits.
1079 ty::ExistentialBounds { region_bound: r,
1080 builtin_bounds: empty_builtin_bounds() }
1083 impl CLike for BuiltinBound {
1084 fn to_uint(&self) -> uint {
1087 fn from_uint(v: uint) -> BuiltinBound {
1088 unsafe { mem::transmute(v) }
1092 #[deriving(Clone, PartialEq, Eq, Hash)]
1097 #[deriving(Clone, PartialEq, Eq, Hash)]
1102 #[deriving(Clone, PartialEq, Eq, Hash)]
1103 pub struct FloatVid {
1107 #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)]
1108 pub struct RegionVid {
1112 #[deriving(Clone, PartialEq, Eq, Hash)]
1119 // FIXME -- once integral fallback is impl'd, we should remove
1120 // this type. It's only needed to prevent spurious errors for
1121 // integers whose type winds up never being constrained.
1122 SkolemizedIntTy(uint),
1125 #[deriving(Clone, Encodable, Decodable, Eq, Hash, Show)]
1126 pub enum InferRegion {
1128 ReSkolemized(uint, BoundRegion)
1131 impl cmp::PartialEq for InferRegion {
1132 fn eq(&self, other: &InferRegion) -> bool {
1133 match ((*self), *other) {
1134 (ReVar(rva), ReVar(rvb)) => {
1137 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
1143 fn ne(&self, other: &InferRegion) -> bool {
1144 !((*self) == (*other))
1148 impl fmt::Show for TyVid {
1149 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
1150 write!(f, "<generic #{}>", self.index)
1154 impl fmt::Show for IntVid {
1155 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1156 write!(f, "<generic integer #{}>", self.index)
1160 impl fmt::Show for FloatVid {
1161 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1162 write!(f, "<generic float #{}>", self.index)
1166 impl fmt::Show for RegionVid {
1167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1168 write!(f, "'<generic lifetime #{}>", self.index)
1172 impl fmt::Show for FnSig {
1173 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1174 // grr, without tcx not much we can do.
1179 impl fmt::Show for InferTy {
1180 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1182 TyVar(ref v) => v.fmt(f),
1183 IntVar(ref v) => v.fmt(f),
1184 FloatVar(ref v) => v.fmt(f),
1185 SkolemizedTy(v) => write!(f, "SkolemizedTy({})", v),
1186 SkolemizedIntTy(v) => write!(f, "SkolemizedIntTy({})", v),
1191 impl fmt::Show for IntVarValue {
1192 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1194 IntType(ref v) => v.fmt(f),
1195 UintType(ref v) => v.fmt(f),
1200 #[deriving(Clone, Show)]
1201 pub struct TypeParameterDef {
1202 pub ident: ast::Ident,
1203 pub def_id: ast::DefId,
1204 pub space: subst::ParamSpace,
1206 pub associated_with: Option<ast::DefId>,
1207 pub bounds: ParamBounds,
1208 pub default: Option<ty::t>,
1211 #[deriving(Encodable, Decodable, Clone, Show)]
1212 pub struct RegionParameterDef {
1213 pub name: ast::Name,
1214 pub def_id: ast::DefId,
1215 pub space: subst::ParamSpace,
1217 pub bounds: Vec<ty::Region>,
1220 /// Information about the type/lifetime parameters associated with an
1221 /// item or method. Analogous to ast::Generics.
1222 #[deriving(Clone, Show)]
1223 pub struct Generics {
1224 pub types: VecPerParamSpace<TypeParameterDef>,
1225 pub regions: VecPerParamSpace<RegionParameterDef>,
1229 pub fn empty() -> Generics {
1230 Generics { types: VecPerParamSpace::empty(),
1231 regions: VecPerParamSpace::empty() }
1234 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
1235 !self.types.is_empty_in(space)
1238 pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
1239 !self.regions.is_empty_in(space)
1244 pub fn self_ty(&self) -> ty::t {
1245 self.substs.self_ty().unwrap()
1249 /// When type checking, we use the `ParameterEnvironment` to track
1250 /// details about the type/lifetime parameters that are in scope.
1251 /// It primarily stores the bounds information.
1253 /// Note: This information might seem to be redundant with the data in
1254 /// `tcx.ty_param_defs`, but it is not. That table contains the
1255 /// parameter definitions from an "outside" perspective, but this
1256 /// struct will contain the bounds for a parameter as seen from inside
1257 /// the function body. Currently the only real distinction is that
1258 /// bound lifetime parameters are replaced with free ones, but in the
1259 /// future I hope to refine the representation of types so as to make
1260 /// more distinctions clearer.
1261 pub struct ParameterEnvironment {
1262 /// A substitution that can be applied to move from
1263 /// the "outer" view of a type or method to the "inner" view.
1264 /// In general, this means converting from bound parameters to
1265 /// free parameters. Since we currently represent bound/free type
1266 /// parameters in the same way, this only has an effect on regions.
1267 pub free_substs: Substs,
1269 /// Bounds on the various type parameters
1270 pub bounds: VecPerParamSpace<ParamBounds>,
1272 /// Each type parameter has an implicit region bound that
1273 /// indicates it must outlive at least the function body (the user
1274 /// may specify stronger requirements). This field indicates the
1275 /// region of the callee.
1276 pub implicit_region_bound: ty::Region,
1278 /// Obligations that the caller must satisfy. This is basically
1279 /// the set of bounds on the in-scope type parameters, translated
1280 /// into Obligations.
1282 /// Note: This effectively *duplicates* the `bounds` array for
1284 pub caller_obligations: VecPerParamSpace<traits::Obligation>,
1287 impl ParameterEnvironment {
1288 pub fn for_item(cx: &ctxt, id: NodeId) -> ParameterEnvironment {
1289 match cx.map.find(id) {
1290 Some(ast_map::NodeImplItem(ref impl_item)) => {
1292 ast::MethodImplItem(ref method) => {
1293 let method_def_id = ast_util::local_def(id);
1294 match ty::impl_or_trait_item(cx, method_def_id) {
1295 MethodTraitItem(ref method_ty) => {
1296 let method_generics = &method_ty.generics;
1297 construct_parameter_environment(
1301 method.pe_body().id)
1303 TypeTraitItem(_) => {
1305 .bug("ParameterEnvironment::from_item(): \
1306 can't create a parameter environment \
1307 for type trait items")
1311 ast::TypeImplItem(_) => {
1312 cx.sess.bug("ParameterEnvironment::from_item(): \
1313 can't create a parameter environment \
1314 for type impl items")
1318 Some(ast_map::NodeTraitItem(trait_method)) => {
1319 match *trait_method {
1320 ast::RequiredMethod(ref required) => {
1321 cx.sess.span_bug(required.span,
1322 "ParameterEnvironment::from_item():
1323 can't create a parameter \
1324 environment for required trait \
1327 ast::ProvidedMethod(ref method) => {
1328 let method_def_id = ast_util::local_def(id);
1329 match ty::impl_or_trait_item(cx, method_def_id) {
1330 MethodTraitItem(ref method_ty) => {
1331 let method_generics = &method_ty.generics;
1332 construct_parameter_environment(
1336 method.pe_body().id)
1338 TypeTraitItem(_) => {
1340 .bug("ParameterEnvironment::from_item(): \
1341 can't create a parameter environment \
1342 for type trait items")
1346 ast::TypeTraitItem(_) => {
1347 cx.sess.bug("ParameterEnvironment::from_item(): \
1348 can't create a parameter environment \
1349 for type trait items")
1353 Some(ast_map::NodeItem(item)) => {
1355 ast::ItemFn(_, _, _, _, ref body) => {
1356 // We assume this is a function.
1357 let fn_def_id = ast_util::local_def(id);
1358 let fn_pty = ty::lookup_item_type(cx, fn_def_id);
1360 construct_parameter_environment(cx,
1366 ast::ItemStruct(..) |
1368 ast::ItemStatic(..) => {
1369 let def_id = ast_util::local_def(id);
1370 let pty = ty::lookup_item_type(cx, def_id);
1371 construct_parameter_environment(cx, item.span,
1375 cx.sess.span_bug(item.span,
1376 "ParameterEnvironment::from_item():
1377 can't create a parameter \
1378 environment for this kind of item")
1383 cx.sess.bug(format!("ParameterEnvironment::from_item(): \
1384 `{}` is not an item",
1385 cx.map.node_to_string(id)).as_slice())
1393 /// - `generics`: the set of type parameters and their bounds
1394 /// - `ty`: the base types, which may reference the parameters defined
1396 #[deriving(Clone, Show)]
1397 pub struct Polytype {
1398 pub generics: Generics,
1402 /// As `Polytype` but for a trait ref.
1403 pub struct TraitDef {
1404 /// Generic type definitions. Note that `Self` is listed in here
1405 /// as having a single bound, the trait itself (e.g., in the trait
1406 /// `Eq`, there is a single bound `Self : Eq`). This is so that
1407 /// default methods get to assume that the `Self` parameters
1408 /// implements the trait.
1409 pub generics: Generics,
1411 /// The "supertrait" bounds.
1412 pub bounds: ParamBounds,
1413 pub trait_ref: Rc<ty::TraitRef>,
1416 /// Records the substitutions used to translate the polytype for an
1417 /// item into the monotype of an item reference.
1419 pub struct ItemSubsts {
1423 pub type type_cache = RefCell<DefIdMap<Polytype>>;
1425 pub type node_type_table = RefCell<HashMap<uint,t>>;
1427 /// Records information about each unboxed closure.
1429 pub struct UnboxedClosure {
1430 /// The type of the unboxed closure.
1431 pub closure_type: ClosureTy,
1432 /// The kind of unboxed closure this is.
1433 pub kind: UnboxedClosureKind,
1436 #[deriving(Clone, PartialEq, Eq)]
1437 pub enum UnboxedClosureKind {
1438 FnUnboxedClosureKind,
1439 FnMutUnboxedClosureKind,
1440 FnOnceUnboxedClosureKind,
1443 impl UnboxedClosureKind {
1444 pub fn trait_did(&self, cx: &ctxt) -> ast::DefId {
1445 let result = match *self {
1446 FnUnboxedClosureKind => cx.lang_items.require(FnTraitLangItem),
1447 FnMutUnboxedClosureKind => {
1448 cx.lang_items.require(FnMutTraitLangItem)
1450 FnOnceUnboxedClosureKind => {
1451 cx.lang_items.require(FnOnceTraitLangItem)
1455 Ok(trait_did) => trait_did,
1456 Err(err) => cx.sess.fatal(err.as_slice()),
1461 pub fn mk_ctxt<'tcx>(s: Session,
1462 type_arena: &'tcx TypedArena<t_box_>,
1463 dm: resolve::DefMap,
1464 named_region_map: resolve_lifetime::NamedRegionMap,
1465 map: ast_map::Map<'tcx>,
1466 freevars: freevars::freevar_map,
1467 capture_modes: freevars::CaptureModeMap,
1468 region_maps: middle::region::RegionMaps,
1469 lang_items: middle::lang_items::LanguageItems,
1470 stability: stability::Index) -> ctxt<'tcx> {
1472 type_arena: type_arena,
1473 interner: RefCell::new(FnvHashMap::new()),
1474 named_region_map: named_region_map,
1475 item_variance_map: RefCell::new(DefIdMap::new()),
1476 variance_computed: Cell::new(false),
1477 next_id: Cell::new(primitives::LAST_PRIMITIVE_ID),
1480 region_maps: region_maps,
1481 node_types: RefCell::new(HashMap::new()),
1482 item_substs: RefCell::new(NodeMap::new()),
1483 trait_refs: RefCell::new(NodeMap::new()),
1484 trait_defs: RefCell::new(DefIdMap::new()),
1485 object_cast_map: RefCell::new(NodeMap::new()),
1487 intrinsic_defs: RefCell::new(DefIdMap::new()),
1488 freevars: RefCell::new(freevars),
1489 tcache: RefCell::new(DefIdMap::new()),
1490 rcache: RefCell::new(HashMap::new()),
1491 short_names_cache: RefCell::new(HashMap::new()),
1492 needs_unwind_cleanup_cache: RefCell::new(HashMap::new()),
1493 tc_cache: RefCell::new(HashMap::new()),
1494 ast_ty_to_ty_cache: RefCell::new(NodeMap::new()),
1495 enum_var_cache: RefCell::new(DefIdMap::new()),
1496 impl_or_trait_items: RefCell::new(DefIdMap::new()),
1497 trait_item_def_ids: RefCell::new(DefIdMap::new()),
1498 trait_items_cache: RefCell::new(DefIdMap::new()),
1499 impl_trait_cache: RefCell::new(DefIdMap::new()),
1500 ty_param_defs: RefCell::new(NodeMap::new()),
1501 adjustments: RefCell::new(NodeMap::new()),
1502 normalized_cache: RefCell::new(HashMap::new()),
1503 lang_items: lang_items,
1504 provided_method_sources: RefCell::new(DefIdMap::new()),
1505 superstructs: RefCell::new(DefIdMap::new()),
1506 struct_fields: RefCell::new(DefIdMap::new()),
1507 destructor_for_type: RefCell::new(DefIdMap::new()),
1508 destructors: RefCell::new(DefIdSet::new()),
1509 trait_impls: RefCell::new(DefIdMap::new()),
1510 inherent_impls: RefCell::new(DefIdMap::new()),
1511 impl_items: RefCell::new(DefIdMap::new()),
1512 used_unsafe: RefCell::new(NodeSet::new()),
1513 used_mut_nodes: RefCell::new(NodeSet::new()),
1514 populated_external_types: RefCell::new(DefIdSet::new()),
1515 populated_external_traits: RefCell::new(DefIdSet::new()),
1516 upvar_borrow_map: RefCell::new(HashMap::new()),
1517 extern_const_statics: RefCell::new(DefIdMap::new()),
1518 extern_const_variants: RefCell::new(DefIdMap::new()),
1519 method_map: RefCell::new(FnvHashMap::new()),
1520 dependency_formats: RefCell::new(HashMap::new()),
1521 unboxed_closures: RefCell::new(DefIdMap::new()),
1522 node_lint_levels: RefCell::new(HashMap::new()),
1523 transmute_restrictions: RefCell::new(Vec::new()),
1524 stability: RefCell::new(stability),
1525 capture_modes: RefCell::new(capture_modes),
1526 associated_types: RefCell::new(DefIdMap::new()),
1527 trait_associated_types: RefCell::new(DefIdMap::new()),
1531 // Type constructors
1533 // Interns a type/name combination, stores the resulting box in cx.interner,
1534 // and returns the box as cast to an unsafe ptr (see comments for t above).
1535 pub fn mk_t(cx: &ctxt, st: sty) -> t {
1536 // Check for primitive types.
1538 ty_nil => return mk_nil(),
1539 ty_err => return mk_err(),
1540 ty_bool => return mk_bool(),
1541 ty_int(i) => return mk_mach_int(i),
1542 ty_uint(u) => return mk_mach_uint(u),
1543 ty_float(f) => return mk_mach_float(f),
1544 ty_char => return mk_char(),
1545 ty_bot => return mk_bot(),
1549 let key = intern_key { sty: &st };
1551 match cx.interner.borrow().find(&key) {
1552 Some(t) => unsafe { return mem::transmute(&t.sty); },
1557 fn rflags(r: Region) -> uint {
1558 (has_regions as uint) | {
1560 ty::ReInfer(_) => needs_infer as uint,
1565 fn sflags(substs: &Substs) -> uint {
1567 let mut i = substs.types.iter();
1569 f |= get(*tt).flags;
1571 match substs.regions {
1572 subst::ErasedRegions => {}
1573 subst::NonerasedRegions(ref regions) => {
1574 for r in regions.iter() {
1581 fn flags_for_bounds(bounds: &ExistentialBounds) -> uint {
1582 rflags(bounds.region_bound)
1585 &ty_nil | &ty_bool | &ty_char | &ty_int(_) | &ty_float(_) | &ty_uint(_) |
1587 // You might think that we could just return ty_err for
1588 // any type containing ty_err as a component, and get
1589 // rid of the has_ty_err flag -- likewise for ty_bot (with
1590 // the exception of function types that return bot).
1591 // But doing so caused sporadic memory corruption, and
1592 // neither I (tjc) nor nmatsakis could figure out why,
1593 // so we're doing it this way.
1594 &ty_bot => flags |= has_ty_bot as uint,
1595 &ty_err => flags |= has_ty_err as uint,
1596 &ty_param(ref p) => {
1597 if p.space == subst::SelfSpace {
1598 flags |= has_self as uint;
1600 flags |= has_params as uint;
1603 &ty_unboxed_closure(_, ref region) => flags |= rflags(*region),
1604 &ty_infer(_) => flags |= needs_infer as uint,
1605 &ty_enum(_, ref substs) | &ty_struct(_, ref substs) => {
1606 flags |= sflags(substs);
1608 &ty_trait(box TyTrait { ref substs, ref bounds, .. }) => {
1609 flags |= sflags(substs);
1610 flags |= flags_for_bounds(bounds);
1612 &ty_box(tt) | &ty_uniq(tt) | &ty_vec(tt, _) | &ty_open(tt) => {
1613 flags |= get(tt).flags
1616 flags |= get(m.ty).flags;
1618 &ty_rptr(r, ref m) => {
1620 flags |= get(m.ty).flags;
1622 &ty_tup(ref ts) => for tt in ts.iter() { flags |= get(*tt).flags; },
1623 &ty_bare_fn(ref f) => {
1624 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1625 flags |= get(f.sig.output).flags;
1626 // T -> _|_ is *not* _|_ !
1627 flags &= !(has_ty_bot as uint);
1629 &ty_closure(ref f) => {
1631 RegionTraitStore(r, _) => {
1636 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1637 flags |= get(f.sig.output).flags;
1638 // T -> _|_ is *not* _|_ !
1639 flags &= !(has_ty_bot as uint);
1640 flags |= flags_for_bounds(&f.bounds);
1644 let t = cx.type_arena.alloc(t_box_ {
1646 id: cx.next_id.get(),
1650 let sty_ptr = &t.sty as *const sty;
1652 let key = intern_key {
1656 cx.interner.borrow_mut().insert(key, t);
1658 cx.next_id.set(cx.next_id.get() + 1);
1661 mem::transmute::<*const sty, t>(sty_ptr)
1666 pub fn mk_prim_t(primitive: &'static t_box_) -> t {
1668 mem::transmute::<&'static t_box_, t>(primitive)
1673 pub fn mk_nil() -> t { mk_prim_t(&primitives::TY_NIL) }
1676 pub fn mk_err() -> t { mk_prim_t(&primitives::TY_ERR) }
1679 pub fn mk_bot() -> t { mk_prim_t(&primitives::TY_BOT) }
1682 pub fn mk_bool() -> t { mk_prim_t(&primitives::TY_BOOL) }
1685 pub fn mk_int() -> t { mk_prim_t(&primitives::TY_INT) }
1688 pub fn mk_i8() -> t { mk_prim_t(&primitives::TY_I8) }
1691 pub fn mk_i16() -> t { mk_prim_t(&primitives::TY_I16) }
1694 pub fn mk_i32() -> t { mk_prim_t(&primitives::TY_I32) }
1697 pub fn mk_i64() -> t { mk_prim_t(&primitives::TY_I64) }
1700 pub fn mk_f32() -> t { mk_prim_t(&primitives::TY_F32) }
1703 pub fn mk_f64() -> t { mk_prim_t(&primitives::TY_F64) }
1706 pub fn mk_uint() -> t { mk_prim_t(&primitives::TY_UINT) }
1709 pub fn mk_u8() -> t { mk_prim_t(&primitives::TY_U8) }
1712 pub fn mk_u16() -> t { mk_prim_t(&primitives::TY_U16) }
1715 pub fn mk_u32() -> t { mk_prim_t(&primitives::TY_U32) }
1718 pub fn mk_u64() -> t { mk_prim_t(&primitives::TY_U64) }
1720 pub fn mk_mach_int(tm: ast::IntTy) -> t {
1722 ast::TyI => mk_int(),
1723 ast::TyI8 => mk_i8(),
1724 ast::TyI16 => mk_i16(),
1725 ast::TyI32 => mk_i32(),
1726 ast::TyI64 => mk_i64(),
1730 pub fn mk_mach_uint(tm: ast::UintTy) -> t {
1732 ast::TyU => mk_uint(),
1733 ast::TyU8 => mk_u8(),
1734 ast::TyU16 => mk_u16(),
1735 ast::TyU32 => mk_u32(),
1736 ast::TyU64 => mk_u64(),
1740 pub fn mk_mach_float(tm: ast::FloatTy) -> t {
1742 ast::TyF32 => mk_f32(),
1743 ast::TyF64 => mk_f64(),
1748 pub fn mk_char() -> t { mk_prim_t(&primitives::TY_CHAR) }
1750 pub fn mk_str(cx: &ctxt) -> t {
1754 pub fn mk_str_slice(cx: &ctxt, r: Region, m: ast::Mutability) -> t {
1757 ty: mk_t(cx, ty_str),
1762 pub fn mk_enum(cx: &ctxt, did: ast::DefId, substs: Substs) -> t {
1763 // take a copy of substs so that we own the vectors inside
1764 mk_t(cx, ty_enum(did, substs))
1767 pub fn mk_box(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_box(ty)) }
1769 pub fn mk_uniq(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_uniq(ty)) }
1771 pub fn mk_ptr(cx: &ctxt, tm: mt) -> t { mk_t(cx, ty_ptr(tm)) }
1773 pub fn mk_rptr(cx: &ctxt, r: Region, tm: mt) -> t { mk_t(cx, ty_rptr(r, tm)) }
1775 pub fn mk_mut_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1776 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
1778 pub fn mk_imm_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1779 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
1782 pub fn mk_mut_ptr(cx: &ctxt, ty: t) -> t {
1783 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
1786 pub fn mk_imm_ptr(cx: &ctxt, ty: t) -> t {
1787 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
1790 pub fn mk_nil_ptr(cx: &ctxt) -> t {
1791 mk_ptr(cx, mt {ty: mk_nil(), mutbl: ast::MutImmutable})
1794 pub fn mk_vec(cx: &ctxt, t: t, sz: Option<uint>) -> t {
1795 mk_t(cx, ty_vec(t, sz))
1798 pub fn mk_slice(cx: &ctxt, r: Region, tm: mt) -> t {
1801 ty: mk_vec(cx, tm.ty, None),
1806 pub fn mk_tup(cx: &ctxt, ts: Vec<t>) -> t { mk_t(cx, ty_tup(ts)) }
1808 pub fn mk_closure(cx: &ctxt, fty: ClosureTy) -> t {
1809 mk_t(cx, ty_closure(box fty))
1812 pub fn mk_bare_fn(cx: &ctxt, fty: BareFnTy) -> t {
1813 mk_t(cx, ty_bare_fn(fty))
1816 pub fn mk_ctor_fn(cx: &ctxt,
1817 binder_id: ast::NodeId,
1818 input_tys: &[ty::t],
1819 output: ty::t) -> t {
1820 let input_args = input_tys.iter().map(|t| *t).collect();
1823 fn_style: ast::NormalFn,
1826 binder_id: binder_id,
1835 pub fn mk_trait(cx: &ctxt,
1838 bounds: ExistentialBounds)
1840 // take a copy of substs so that we own the vectors inside
1841 let inner = box TyTrait {
1846 mk_t(cx, ty_trait(inner))
1849 pub fn mk_struct(cx: &ctxt, struct_id: ast::DefId, substs: Substs) -> t {
1850 // take a copy of substs so that we own the vectors inside
1851 mk_t(cx, ty_struct(struct_id, substs))
1854 pub fn mk_unboxed_closure(cx: &ctxt, closure_id: ast::DefId, region: Region)
1856 mk_t(cx, ty_unboxed_closure(closure_id, region))
1859 pub fn mk_var(cx: &ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) }
1861 pub fn mk_int_var(cx: &ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) }
1863 pub fn mk_float_var(cx: &ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) }
1865 pub fn mk_infer(cx: &ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) }
1867 pub fn mk_param(cx: &ctxt, space: subst::ParamSpace, n: uint, k: DefId) -> t {
1868 mk_t(cx, ty_param(ParamTy { space: space, idx: n, def_id: k }))
1871 pub fn mk_self_type(cx: &ctxt, did: ast::DefId) -> t {
1872 mk_param(cx, subst::SelfSpace, 0, did)
1875 pub fn mk_param_from_def(cx: &ctxt, def: &TypeParameterDef) -> t {
1876 mk_param(cx, def.space, def.index, def.def_id)
1879 pub fn mk_open(cx: &ctxt, t: t) -> t { mk_t(cx, ty_open(t)) }
1881 pub fn walk_ty(ty: t, f: |t|) {
1882 maybe_walk_ty(ty, |t| { f(t); true });
1885 pub fn maybe_walk_ty(ty: t, f: |t| -> bool) {
1890 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) |
1891 ty_str | ty_infer(_) | ty_param(_) | ty_unboxed_closure(_, _) | ty_err => {}
1892 ty_box(ty) | ty_uniq(ty) | ty_vec(ty, _) | ty_open(ty) => maybe_walk_ty(ty, f),
1893 ty_ptr(ref tm) | ty_rptr(_, ref tm) => {
1894 maybe_walk_ty(tm.ty, f);
1896 ty_enum(_, ref substs) | ty_struct(_, ref substs) |
1897 ty_trait(box TyTrait { ref substs, .. }) => {
1898 for subty in (*substs).types.iter() {
1899 maybe_walk_ty(*subty, |x| f(x));
1902 ty_tup(ref ts) => { for tt in ts.iter() { maybe_walk_ty(*tt, |x| f(x)); } }
1903 ty_bare_fn(ref ft) => {
1904 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1905 maybe_walk_ty(ft.sig.output, f);
1907 ty_closure(ref ft) => {
1908 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1909 maybe_walk_ty(ft.sig.output, f);
1914 // Folds types from the bottom up.
1915 pub fn fold_ty(cx: &ctxt, t0: t, fldop: |t| -> t) -> t {
1916 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
1920 pub fn walk_regions_and_ty(cx: &ctxt, ty: t, fldr: |r: Region|, fldt: |t: t|)
1922 ty_fold::RegionFolder::general(cx,
1924 |t| { fldt(t); t }).fold_ty(ty)
1928 pub fn new(space: subst::ParamSpace,
1932 ParamTy { space: space, idx: index, def_id: def_id }
1935 pub fn for_self(trait_def_id: ast::DefId) -> ParamTy {
1936 ParamTy::new(subst::SelfSpace, 0, trait_def_id)
1939 pub fn for_def(def: &TypeParameterDef) -> ParamTy {
1940 ParamTy::new(def.space, def.index, def.def_id)
1943 pub fn to_ty(self, tcx: &ty::ctxt) -> ty::t {
1944 ty::mk_param(tcx, self.space, self.idx, self.def_id)
1947 pub fn is_self(&self) -> bool {
1948 self.space == subst::SelfSpace && self.idx == 0
1953 pub fn empty() -> ItemSubsts {
1954 ItemSubsts { substs: Substs::empty() }
1957 pub fn is_noop(&self) -> bool {
1958 self.substs.is_noop()
1964 pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil }
1966 pub fn type_is_bot(ty: t) -> bool {
1967 (get(ty).flags & (has_ty_bot as uint)) != 0
1970 pub fn type_is_error(ty: t) -> bool {
1971 (get(ty).flags & (has_ty_err as uint)) != 0
1974 pub fn type_needs_subst(ty: t) -> bool {
1975 tbox_has_flag(get(ty), needs_subst)
1978 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
1979 tref.substs.types.any(|&t| type_is_error(t))
1982 pub fn type_is_ty_var(ty: t) -> bool {
1984 ty_infer(TyVar(_)) => true,
1989 pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool }
1991 pub fn type_is_self(ty: t) -> bool {
1993 ty_param(ref p) => p.space == subst::SelfSpace,
1998 fn type_is_slice(ty: t) -> bool {
2000 ty_ptr(mt) | ty_rptr(_, mt) => match get(mt.ty).sty {
2001 ty_vec(_, None) | ty_str => true,
2008 pub fn type_is_vec(ty: t) -> bool {
2011 ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) |
2012 ty_box(t) | ty_uniq(t) => match get(t).sty {
2013 ty_vec(_, None) => true,
2020 pub fn type_is_structural(ty: t) -> bool {
2022 ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) |
2023 ty_vec(_, Some(_)) | ty_unboxed_closure(..) => true,
2024 _ => type_is_slice(ty) | type_is_trait(ty)
2028 pub fn type_is_simd(cx: &ctxt, ty: t) -> bool {
2030 ty_struct(did, _) => lookup_simd(cx, did),
2035 pub fn sequence_element_type(cx: &ctxt, ty: t) -> t {
2037 ty_vec(ty, _) => ty,
2038 ty_str => mk_mach_uint(ast::TyU8),
2039 ty_open(ty) => sequence_element_type(cx, ty),
2040 _ => cx.sess.bug(format!("sequence_element_type called on non-sequence value: {}",
2041 ty_to_string(cx, ty)).as_slice()),
2045 pub fn simd_type(cx: &ctxt, ty: t) -> t {
2047 ty_struct(did, ref substs) => {
2048 let fields = lookup_struct_fields(cx, did);
2049 lookup_field_type(cx, did, fields.get(0).id, substs)
2051 _ => fail!("simd_type called on invalid type")
2055 pub fn simd_size(cx: &ctxt, ty: t) -> uint {
2057 ty_struct(did, _) => {
2058 let fields = lookup_struct_fields(cx, did);
2061 _ => fail!("simd_size called on invalid type")
2065 pub fn type_is_boxed(ty: t) -> bool {
2072 pub fn type_is_region_ptr(ty: t) -> bool {
2074 ty_rptr(..) => true,
2079 pub fn type_is_unsafe_ptr(ty: t) -> bool {
2081 ty_ptr(_) => return true,
2086 pub fn type_is_unique(ty: t) -> bool {
2088 ty_uniq(_) => match get(ty).sty {
2089 ty_trait(..) => false,
2096 pub fn type_is_fat_ptr(cx: &ctxt, ty: t) -> bool {
2098 ty_ptr(mt{ty, ..}) | ty_rptr(_, mt{ty, ..})
2099 | ty_uniq(ty) if !type_is_sized(cx, ty) => true,
2105 A scalar type is one that denotes an atomic datum, with no sub-components.
2106 (A ty_ptr is scalar because it represents a non-managed pointer, so its
2107 contents are abstract to rustc.)
2109 pub fn type_is_scalar(ty: t) -> bool {
2111 ty_nil | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
2112 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
2113 ty_bare_fn(..) | ty_ptr(_) => true,
2118 /// Returns true if this type is a floating point type and false otherwise.
2119 pub fn type_is_floating_point(ty: t) -> bool {
2121 ty_float(_) => true,
2126 pub fn type_needs_drop(cx: &ctxt, ty: t) -> bool {
2127 type_contents(cx, ty).needs_drop(cx)
2130 // Some things don't need cleanups during unwinding because the
2131 // task can free them all at once later. Currently only things
2132 // that only contain scalars and shared boxes can avoid unwind
2134 pub fn type_needs_unwind_cleanup(cx: &ctxt, ty: t) -> bool {
2135 match cx.needs_unwind_cleanup_cache.borrow().find(&ty) {
2136 Some(&result) => return result,
2140 let mut tycache = HashSet::new();
2141 let needs_unwind_cleanup =
2142 type_needs_unwind_cleanup_(cx, ty, &mut tycache, false);
2143 cx.needs_unwind_cleanup_cache.borrow_mut().insert(ty, needs_unwind_cleanup);
2144 return needs_unwind_cleanup;
2147 fn type_needs_unwind_cleanup_(cx: &ctxt, ty: t,
2148 tycache: &mut HashSet<t>,
2149 encountered_box: bool) -> bool {
2151 // Prevent infinite recursion
2152 if !tycache.insert(ty) {
2156 let mut encountered_box = encountered_box;
2157 let mut needs_unwind_cleanup = false;
2158 maybe_walk_ty(ty, |ty| {
2159 let old_encountered_box = encountered_box;
2160 let result = match get(ty).sty {
2162 encountered_box = true;
2165 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2166 ty_tup(_) | ty_ptr(_) => {
2169 ty_enum(did, ref substs) => {
2170 for v in (*enum_variants(cx, did)).iter() {
2171 for aty in v.args.iter() {
2172 let t = aty.subst(cx, substs);
2173 needs_unwind_cleanup |=
2174 type_needs_unwind_cleanup_(cx, t, tycache,
2178 !needs_unwind_cleanup
2181 // Once we're inside a box, the annihilator will find
2182 // it and destroy it.
2183 if !encountered_box {
2184 needs_unwind_cleanup = true;
2191 needs_unwind_cleanup = true;
2196 encountered_box = old_encountered_box;
2200 return needs_unwind_cleanup;
2204 * Type contents is how the type checker reasons about kinds.
2205 * They track what kinds of things are found within a type. You can
2206 * think of them as kind of an "anti-kind". They track the kinds of values
2207 * and thinks that are contained in types. Having a larger contents for
2208 * a type tends to rule that type *out* from various kinds. For example,
2209 * a type that contains a reference is not sendable.
2211 * The reason we compute type contents and not kinds is that it is
2212 * easier for me (nmatsakis) to think about what is contained within
2213 * a type than to think about what is *not* contained within a type.
2215 pub struct TypeContents {
2219 macro_rules! def_type_content_sets(
2220 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
2221 #[allow(non_snake_case)]
2223 use middle::ty::TypeContents;
2224 $(pub static $name: TypeContents = TypeContents { bits: $bits };)+
2229 def_type_content_sets!(
2231 None = 0b0000_0000__0000_0000__0000,
2233 // Things that are interior to the value (first nibble):
2234 InteriorUnsized = 0b0000_0000__0000_0000__0001,
2235 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
2236 // InteriorAll = 0b00000000__00000000__1111,
2238 // Things that are owned by the value (second and third nibbles):
2239 OwnsOwned = 0b0000_0000__0000_0001__0000,
2240 OwnsDtor = 0b0000_0000__0000_0010__0000,
2241 OwnsManaged /* see [1] below */ = 0b0000_0000__0000_0100__0000,
2242 OwnsAffine = 0b0000_0000__0000_1000__0000,
2243 OwnsAll = 0b0000_0000__1111_1111__0000,
2245 // Things that are reachable by the value in any way (fourth nibble):
2246 ReachesNonsendAnnot = 0b0000_0001__0000_0000__0000,
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 ReachesNoSync = 0b0001_0000__0000_0000__0000,
2251 ReachesFfiUnsafe = 0b0010_0000__0000_0000__0000,
2252 ReachesAll = 0b0011_1111__0000_0000__0000,
2254 // Things that cause values to *move* rather than *copy*
2255 Moves = 0b0000_0000__0000_1011__0000,
2257 // Things that mean drop glue is necessary
2258 NeedsDrop = 0b0000_0000__0000_0111__0000,
2260 // Things that prevent values from being sent
2262 // Note: For checking whether something is sendable, it'd
2263 // be sufficient to have ReachesManaged. However, we include
2264 // both ReachesManaged and OwnsManaged so that when
2265 // a parameter has a bound T:Send, we are able to deduce
2266 // that it neither reaches nor owns a managed pointer.
2267 Nonsendable = 0b0000_0111__0000_0100__0000,
2269 // Things that prevent values from being considered sized
2270 Nonsized = 0b0000_0000__0000_0000__0001,
2272 // Things that prevent values from being sync
2273 Nonsync = 0b0001_0000__0000_0000__0000,
2275 // Things that make values considered not POD (would be same
2276 // as `Moves`, but for the fact that managed data `@` is
2277 // not considered POD)
2278 Noncopy = 0b0000_0000__0000_1111__0000,
2280 // Bits to set when a managed value is encountered
2282 // [1] Do not set the bits TC::OwnsManaged or
2283 // TC::ReachesManaged directly, instead reference
2284 // TC::Managed to set them both at once.
2285 Managed = 0b0000_0100__0000_0100__0000,
2288 All = 0b1111_1111__1111_1111__1111
2293 pub fn meets_builtin_bound(&self, cx: &ctxt, bb: BuiltinBound) -> bool {
2295 BoundSend => self.is_sendable(cx),
2296 BoundSized => self.is_sized(cx),
2297 BoundCopy => self.is_copy(cx),
2298 BoundSync => self.is_sync(cx),
2302 pub fn when(&self, cond: bool) -> TypeContents {
2303 if cond {*self} else {TC::None}
2306 pub fn intersects(&self, tc: TypeContents) -> bool {
2307 (self.bits & tc.bits) != 0
2310 pub fn is_sendable(&self, _: &ctxt) -> bool {
2311 !self.intersects(TC::Nonsendable)
2314 pub fn is_sync(&self, _: &ctxt) -> bool {
2315 !self.intersects(TC::Nonsync)
2318 pub fn owns_managed(&self) -> bool {
2319 self.intersects(TC::OwnsManaged)
2322 pub fn owns_owned(&self) -> bool {
2323 self.intersects(TC::OwnsOwned)
2326 pub fn is_sized(&self, _: &ctxt) -> bool {
2327 !self.intersects(TC::Nonsized)
2330 pub fn is_copy(&self, _: &ctxt) -> bool {
2331 !self.intersects(TC::Noncopy)
2334 pub fn interior_unsafe(&self) -> bool {
2335 self.intersects(TC::InteriorUnsafe)
2338 pub fn interior_unsized(&self) -> bool {
2339 self.intersects(TC::InteriorUnsized)
2342 pub fn moves_by_default(&self, _: &ctxt) -> bool {
2343 self.intersects(TC::Moves)
2346 pub fn needs_drop(&self, _: &ctxt) -> bool {
2347 self.intersects(TC::NeedsDrop)
2350 pub fn owned_pointer(&self) -> TypeContents {
2352 * Includes only those bits that still apply
2353 * when indirected through a `Box` pointer
2356 *self & (TC::OwnsAll | TC::ReachesAll))
2359 pub fn reference(&self, bits: TypeContents) -> TypeContents {
2361 * Includes only those bits that still apply
2362 * when indirected through a reference (`&`)
2365 *self & TC::ReachesAll)
2368 pub fn managed_pointer(&self) -> TypeContents {
2370 * Includes only those bits that still apply
2371 * when indirected through a managed pointer (`@`)
2374 *self & TC::ReachesAll)
2377 pub fn unsafe_pointer(&self) -> TypeContents {
2379 * Includes only those bits that still apply
2380 * when indirected through an unsafe pointer (`*`)
2382 *self & TC::ReachesAll
2385 pub fn union<T>(v: &[T], f: |&T| -> TypeContents) -> TypeContents {
2386 v.iter().fold(TC::None, |tc, t| tc | f(t))
2389 pub fn has_dtor(&self) -> bool {
2390 self.intersects(TC::OwnsDtor)
2394 impl ops::BitOr<TypeContents,TypeContents> for TypeContents {
2395 fn bitor(&self, other: &TypeContents) -> TypeContents {
2396 TypeContents {bits: self.bits | other.bits}
2400 impl ops::BitAnd<TypeContents,TypeContents> for TypeContents {
2401 fn bitand(&self, other: &TypeContents) -> TypeContents {
2402 TypeContents {bits: self.bits & other.bits}
2406 impl ops::Sub<TypeContents,TypeContents> for TypeContents {
2407 fn sub(&self, other: &TypeContents) -> TypeContents {
2408 TypeContents {bits: self.bits & !other.bits}
2412 impl fmt::Show for TypeContents {
2413 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2414 write!(f, "TypeContents({:t})", self.bits)
2418 pub fn type_is_sendable(cx: &ctxt, t: ty::t) -> bool {
2419 type_contents(cx, t).is_sendable(cx)
2422 pub fn type_interior_is_unsafe(cx: &ctxt, t: ty::t) -> bool {
2423 type_contents(cx, t).interior_unsafe()
2426 pub fn type_contents(cx: &ctxt, ty: t) -> TypeContents {
2427 let ty_id = type_id(ty);
2429 match cx.tc_cache.borrow().find(&ty_id) {
2430 Some(tc) => { return *tc; }
2434 let mut cache = HashMap::new();
2435 let result = tc_ty(cx, ty, &mut cache);
2437 cx.tc_cache.borrow_mut().insert(ty_id, result);
2442 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2444 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
2445 // private cache for this walk. This is needed in the case of cyclic
2448 // struct List { next: Box<Option<List>>, ... }
2450 // When computing the type contents of such a type, we wind up deeply
2451 // recursing as we go. So when we encounter the recursive reference
2452 // to List, we temporarily use TC::None as its contents. Later we'll
2453 // patch up the cache with the correct value, once we've computed it
2454 // (this is basically a co-inductive process, if that helps). So in
2455 // the end we'll compute TC::OwnsOwned, in this case.
2457 // The problem is, as we are doing the computation, we will also
2458 // compute an *intermediate* contents for, e.g., Option<List> of
2459 // TC::None. This is ok during the computation of List itself, but if
2460 // we stored this intermediate value into cx.tc_cache, then later
2461 // requests for the contents of Option<List> would also yield TC::None
2462 // which is incorrect. This value was computed based on the crutch
2463 // value for the type contents of list. The correct value is
2464 // TC::OwnsOwned. This manifested as issue #4821.
2465 let ty_id = type_id(ty);
2466 match cache.find(&ty_id) {
2467 Some(tc) => { return *tc; }
2470 match cx.tc_cache.borrow().find(&ty_id) { // Must check both caches!
2471 Some(tc) => { return *tc; }
2474 cache.insert(ty_id, TC::None);
2476 let result = match get(ty).sty {
2477 // uint and int are ffi-unsafe
2478 ty_uint(ast::TyU) | ty_int(ast::TyI) => {
2479 TC::ReachesFfiUnsafe
2482 // Scalar and unique types are sendable, and durable
2483 ty_infer(ty::SkolemizedIntTy(_)) |
2484 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2485 ty_bare_fn(_) | ty::ty_char => {
2489 ty_closure(ref c) => {
2490 closure_contents(cx, &**c) | TC::ReachesFfiUnsafe
2494 tc_ty(cx, typ, cache).managed_pointer() | TC::ReachesFfiUnsafe
2498 TC::ReachesFfiUnsafe | match get(typ).sty {
2499 ty_str => TC::OwnsOwned,
2500 _ => tc_ty(cx, typ, cache).owned_pointer(),
2504 ty_trait(box TyTrait { bounds, .. }) => {
2505 object_contents(cx, bounds) | TC::ReachesFfiUnsafe | TC::Nonsized
2509 tc_ty(cx, mt.ty, cache).unsafe_pointer()
2512 ty_rptr(r, ref mt) => {
2513 TC::ReachesFfiUnsafe | match get(mt.ty).sty {
2514 ty_str => borrowed_contents(r, ast::MutImmutable),
2515 ty_vec(..) => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(r, mt.mutbl)),
2516 _ => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(r, mt.mutbl)),
2520 ty_vec(t, Some(_)) => {
2524 ty_vec(t, None) => {
2525 tc_ty(cx, t, cache) | TC::Nonsized
2527 ty_str => TC::Nonsized,
2529 ty_struct(did, ref substs) => {
2530 let flds = struct_fields(cx, did, substs);
2532 TypeContents::union(flds.as_slice(),
2533 |f| tc_mt(cx, f.mt, cache));
2535 if !lookup_repr_hints(cx, did).contains(&attr::ReprExtern) {
2536 res = res | TC::ReachesFfiUnsafe;
2539 if ty::has_dtor(cx, did) {
2540 res = res | TC::OwnsDtor;
2542 apply_lang_items(cx, did, res)
2545 ty_unboxed_closure(did, r) => {
2546 // FIXME(#14449): `borrowed_contents` below assumes `&mut`
2548 let upvars = unboxed_closure_upvars(cx, did);
2549 TypeContents::union(upvars.as_slice(),
2550 |f| tc_ty(cx, f.ty, cache)) |
2551 borrowed_contents(r, MutMutable)
2554 ty_tup(ref tys) => {
2555 TypeContents::union(tys.as_slice(),
2556 |ty| tc_ty(cx, *ty, cache))
2559 ty_enum(did, ref substs) => {
2560 let variants = substd_enum_variants(cx, did, substs);
2562 TypeContents::union(variants.as_slice(), |variant| {
2563 TypeContents::union(variant.args.as_slice(),
2565 tc_ty(cx, *arg_ty, cache)
2569 if ty::has_dtor(cx, did) {
2570 res = res | TC::OwnsDtor;
2573 if variants.len() != 0 {
2574 let repr_hints = lookup_repr_hints(cx, did);
2575 if repr_hints.len() > 1 {
2576 // this is an error later on, but this type isn't safe
2577 res = res | TC::ReachesFfiUnsafe;
2580 match repr_hints.as_slice().get(0) {
2581 Some(h) => if !h.is_ffi_safe() {
2582 res = res | TC::ReachesFfiUnsafe;
2586 res = res | TC::ReachesFfiUnsafe;
2588 // We allow ReprAny enums if they are eligible for
2589 // the nullable pointer optimization and the
2590 // contained type is an `extern fn`
2592 if variants.len() == 2 {
2593 let mut data_idx = 0;
2595 if variants.get(0).args.len() == 0 {
2599 if variants.get(data_idx).args.len() == 1 {
2600 match get(*variants.get(data_idx).args.get(0)).sty {
2601 ty_bare_fn(..) => { res = res - TC::ReachesFfiUnsafe; }
2611 apply_lang_items(cx, did, res)
2615 // We only ever ask for the kind of types that are defined in
2616 // the current crate; therefore, the only type parameters that
2617 // could be in scope are those defined in the current crate.
2618 // If this assertion failures, it is likely because of a
2619 // failure in the cross-crate inlining code to translate a
2621 assert_eq!(p.def_id.krate, ast::LOCAL_CRATE);
2623 let ty_param_defs = cx.ty_param_defs.borrow();
2624 let tp_def = ty_param_defs.get(&p.def_id.node);
2625 kind_bounds_to_contents(
2627 tp_def.bounds.builtin_bounds,
2628 tp_def.bounds.trait_bounds.as_slice())
2632 // This occurs during coherence, but shouldn't occur at other
2638 let result = tc_ty(cx, t, cache);
2639 assert!(!result.is_sized(cx))
2640 result.unsafe_pointer() | TC::Nonsized
2644 cx.sess.bug("asked to compute contents of error type");
2648 cache.insert(ty_id, result);
2654 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2656 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
2657 mc | tc_ty(cx, mt.ty, cache)
2660 fn apply_lang_items(cx: &ctxt,
2664 if Some(did) == cx.lang_items.no_send_bound() {
2665 tc | TC::ReachesNonsendAnnot
2666 } else if Some(did) == cx.lang_items.managed_bound() {
2668 } else if Some(did) == cx.lang_items.no_copy_bound() {
2670 } else if Some(did) == cx.lang_items.no_sync_bound() {
2671 tc | TC::ReachesNoSync
2672 } else if Some(did) == cx.lang_items.unsafe_type() {
2673 // FIXME(#13231): This shouldn't be needed after
2674 // opt-in built-in bounds are implemented.
2675 (tc | TC::InteriorUnsafe) - TC::Nonsync
2681 fn borrowed_contents(region: ty::Region,
2682 mutbl: ast::Mutability)
2685 * Type contents due to containing a reference
2686 * with the region `region` and borrow kind `bk`
2689 let b = match mutbl {
2690 ast::MutMutable => TC::ReachesMutable | TC::OwnsAffine,
2691 ast::MutImmutable => TC::None,
2693 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
2696 fn closure_contents(cx: &ctxt, cty: &ClosureTy) -> TypeContents {
2697 // Closure contents are just like trait contents, but with potentially
2699 let st = object_contents(cx, cty.bounds);
2701 let st = match cty.store {
2705 RegionTraitStore(r, mutbl) => {
2706 st.reference(borrowed_contents(r, mutbl))
2710 // This also prohibits "@once fn" from being copied, which allows it to
2711 // be called. Neither way really makes much sense.
2712 let ot = match cty.onceness {
2713 ast::Once => TC::OwnsAffine,
2714 ast::Many => TC::None,
2720 fn object_contents(cx: &ctxt,
2721 bounds: ExistentialBounds)
2723 // These are the type contents of the (opaque) interior
2724 kind_bounds_to_contents(cx, bounds.builtin_bounds, [])
2727 fn kind_bounds_to_contents(cx: &ctxt,
2728 bounds: BuiltinBounds,
2729 traits: &[Rc<TraitRef>])
2731 let _i = indenter();
2732 let mut tc = TC::All;
2733 each_inherited_builtin_bound(cx, bounds, traits, |bound| {
2734 tc = tc - match bound {
2735 BoundSend => TC::Nonsendable,
2736 BoundSized => TC::Nonsized,
2737 BoundCopy => TC::Noncopy,
2738 BoundSync => TC::Nonsync,
2743 // Iterates over all builtin bounds on the type parameter def, including
2744 // those inherited from traits with builtin-kind-supertraits.
2745 fn each_inherited_builtin_bound(cx: &ctxt,
2746 bounds: BuiltinBounds,
2747 traits: &[Rc<TraitRef>],
2748 f: |BuiltinBound|) {
2749 for bound in bounds.iter() {
2753 each_bound_trait_and_supertraits(cx, traits, |trait_ref| {
2754 let trait_def = lookup_trait_def(cx, trait_ref.def_id);
2755 for bound in trait_def.bounds.builtin_bounds.iter() {
2764 pub fn type_moves_by_default(cx: &ctxt, ty: t) -> bool {
2765 type_contents(cx, ty).moves_by_default(cx)
2768 pub fn is_ffi_safe(cx: &ctxt, ty: t) -> bool {
2769 !type_contents(cx, ty).intersects(TC::ReachesFfiUnsafe)
2772 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
2773 pub fn is_instantiable(cx: &ctxt, r_ty: t) -> bool {
2774 fn type_requires(cx: &ctxt, seen: &mut Vec<DefId>,
2775 r_ty: t, ty: t) -> bool {
2776 debug!("type_requires({}, {})?",
2777 ::util::ppaux::ty_to_string(cx, r_ty),
2778 ::util::ppaux::ty_to_string(cx, ty));
2781 get(r_ty).sty == get(ty).sty ||
2782 subtypes_require(cx, seen, r_ty, ty)
2785 debug!("type_requires({}, {})? {}",
2786 ::util::ppaux::ty_to_string(cx, r_ty),
2787 ::util::ppaux::ty_to_string(cx, ty),
2792 fn subtypes_require(cx: &ctxt, seen: &mut Vec<DefId>,
2793 r_ty: t, ty: t) -> bool {
2794 debug!("subtypes_require({}, {})?",
2795 ::util::ppaux::ty_to_string(cx, r_ty),
2796 ::util::ppaux::ty_to_string(cx, ty));
2798 let r = match get(ty).sty {
2799 // fixed length vectors need special treatment compared to
2800 // normal vectors, since they don't necessarily have the
2801 // possibility to have length zero.
2802 ty_vec(_, Some(0)) => false, // don't need no contents
2803 ty_vec(ty, Some(_)) => type_requires(cx, seen, r_ty, ty),
2818 ty_vec(_, None) => {
2821 ty_box(typ) | ty_uniq(typ) | ty_open(typ) => {
2822 type_requires(cx, seen, r_ty, typ)
2824 ty_rptr(_, ref mt) => {
2825 type_requires(cx, seen, r_ty, mt.ty)
2829 false // unsafe ptrs can always be NULL
2836 ty_struct(ref did, _) if seen.contains(did) => {
2840 ty_struct(did, ref substs) => {
2842 let fields = struct_fields(cx, did, substs);
2843 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
2844 seen.pop().unwrap();
2848 ty_unboxed_closure(did, _) => {
2849 let upvars = unboxed_closure_upvars(cx, did);
2850 upvars.iter().any(|f| type_requires(cx, seen, r_ty, f.ty))
2854 ts.iter().any(|t| type_requires(cx, seen, r_ty, *t))
2857 ty_enum(ref did, _) if seen.contains(did) => {
2861 ty_enum(did, ref substs) => {
2863 let vs = enum_variants(cx, did);
2864 let r = !vs.is_empty() && vs.iter().all(|variant| {
2865 variant.args.iter().any(|aty| {
2866 let sty = aty.subst(cx, substs);
2867 type_requires(cx, seen, r_ty, sty)
2870 seen.pop().unwrap();
2875 debug!("subtypes_require({}, {})? {}",
2876 ::util::ppaux::ty_to_string(cx, r_ty),
2877 ::util::ppaux::ty_to_string(cx, ty),
2883 let mut seen = Vec::new();
2884 !subtypes_require(cx, &mut seen, r_ty, r_ty)
2887 /// Describes whether a type is representable. For types that are not
2888 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
2889 /// distinguish between types that are recursive with themselves and types that
2890 /// contain a different recursive type. These cases can therefore be treated
2891 /// differently when reporting errors.
2892 #[deriving(PartialEq)]
2893 pub enum Representability {
2899 /// Check whether a type is representable. This means it cannot contain unboxed
2900 /// structural recursion. This check is needed for structs and enums.
2901 pub fn is_type_representable(cx: &ctxt, sp: Span, ty: t) -> Representability {
2903 // Iterate until something non-representable is found
2904 fn find_nonrepresentable<It: Iterator<t>>(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2905 mut iter: It) -> Representability {
2907 let r = type_structurally_recursive(cx, sp, seen, ty);
2908 if r != Representable {
2915 // Does the type `ty` directly (without indirection through a pointer)
2916 // contain any types on stack `seen`?
2917 fn type_structurally_recursive(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2918 ty: t) -> Representability {
2919 debug!("type_structurally_recursive: {}",
2920 ::util::ppaux::ty_to_string(cx, ty));
2922 // Compare current type to previously seen types
2925 ty_enum(did, _) => {
2926 for (i, &seen_did) in seen.iter().enumerate() {
2927 if did == seen_did {
2928 return if i == 0 { SelfRecursive }
2929 else { ContainsRecursive }
2936 // Check inner types
2940 find_nonrepresentable(cx, sp, seen, ts.iter().map(|t| *t))
2942 // Fixed-length vectors.
2943 // FIXME(#11924) Behavior undecided for zero-length vectors.
2944 ty_vec(ty, Some(_)) => {
2945 type_structurally_recursive(cx, sp, seen, ty)
2948 // Push struct and enum def-ids onto `seen` before recursing.
2949 ty_struct(did, ref substs) => {
2951 let fields = struct_fields(cx, did, substs);
2952 let r = find_nonrepresentable(cx, sp, seen,
2953 fields.iter().map(|f| f.mt.ty));
2958 ty_enum(did, ref substs) => {
2960 let vs = enum_variants(cx, did);
2962 let mut r = Representable;
2963 for variant in vs.iter() {
2964 let iter = variant.args.iter().map(|aty| {
2965 aty.subst_spanned(cx, substs, Some(sp))
2967 r = find_nonrepresentable(cx, sp, seen, iter);
2969 if r != Representable { break }
2976 ty_unboxed_closure(did, _) => {
2977 let upvars = unboxed_closure_upvars(cx, did);
2978 find_nonrepresentable(cx,
2981 upvars.iter().map(|f| f.ty))
2988 debug!("is_type_representable: {}",
2989 ::util::ppaux::ty_to_string(cx, ty));
2991 // To avoid a stack overflow when checking an enum variant or struct that
2992 // contains a different, structurally recursive type, maintain a stack
2993 // of seen types and check recursion for each of them (issues #3008, #3779).
2994 let mut seen: Vec<DefId> = Vec::new();
2995 type_structurally_recursive(cx, sp, &mut seen, ty)
2998 pub fn type_is_trait(ty: t) -> bool {
2999 type_trait_info(ty).is_some()
3002 pub fn type_trait_info(ty: t) -> Option<&'static TyTrait> {
3004 ty_uniq(ty) | ty_rptr(_, mt { ty, ..}) | ty_ptr(mt { ty, ..}) => match get(ty).sty {
3005 ty_trait(ref t) => Some(&**t),
3008 ty_trait(ref t) => Some(&**t),
3013 pub fn type_is_integral(ty: t) -> bool {
3015 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
3020 pub fn type_is_skolemized(ty: t) -> bool {
3022 ty_infer(SkolemizedTy(_)) => true,
3023 ty_infer(SkolemizedIntTy(_)) => true,
3028 pub fn type_is_uint(ty: t) -> bool {
3030 ty_infer(IntVar(_)) | ty_uint(ast::TyU) => true,
3035 pub fn type_is_char(ty: t) -> bool {
3042 pub fn type_is_bare_fn(ty: t) -> bool {
3044 ty_bare_fn(..) => true,
3049 pub fn type_is_fp(ty: t) -> bool {
3051 ty_infer(FloatVar(_)) | ty_float(_) => true,
3056 pub fn type_is_numeric(ty: t) -> bool {
3057 return type_is_integral(ty) || type_is_fp(ty);
3060 pub fn type_is_signed(ty: t) -> bool {
3067 pub fn type_is_machine(ty: t) -> bool {
3069 ty_int(ast::TyI) | ty_uint(ast::TyU) => false,
3070 ty_int(..) | ty_uint(..) | ty_float(..) => true,
3075 // Is the type's representation size known at compile time?
3076 pub fn type_is_sized(cx: &ctxt, ty: t) -> bool {
3077 type_contents(cx, ty).is_sized(cx)
3080 pub fn lltype_is_sized(cx: &ctxt, ty: t) -> bool {
3083 _ => type_contents(cx, ty).is_sized(cx)
3087 // Return the smallest part of t which is unsized. Fails if t is sized.
3088 // 'Smallest' here means component of the static representation of the type; not
3089 // the size of an object at runtime.
3090 pub fn unsized_part_of_type(cx: &ctxt, ty: t) -> t {
3092 ty_str | ty_trait(..) | ty_vec(..) => ty,
3093 ty_struct(def_id, ref substs) => {
3094 let unsized_fields: Vec<_> = struct_fields(cx, def_id, substs).iter()
3095 .map(|f| f.mt.ty).filter(|ty| !type_is_sized(cx, *ty)).collect();
3096 // Exactly one of the fields must be unsized.
3097 assert!(unsized_fields.len() == 1)
3099 unsized_part_of_type(cx, unsized_fields[0])
3102 assert!(type_is_sized(cx, ty),
3103 "unsized_part_of_type failed even though ty is unsized");
3104 fail!("called unsized_part_of_type with sized ty");
3109 // Whether a type is enum like, that is an enum type with only nullary
3111 pub fn type_is_c_like_enum(cx: &ctxt, ty: t) -> bool {
3113 ty_enum(did, _) => {
3114 let variants = enum_variants(cx, did);
3115 if variants.len() == 0 {
3118 variants.iter().all(|v| v.args.len() == 0)
3125 // Returns the type and mutability of *t.
3127 // The parameter `explicit` indicates if this is an *explicit* dereference.
3128 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
3129 pub fn deref(t: t, explicit: bool) -> Option<mt> {
3131 ty_box(ty) | ty_uniq(ty) => {
3134 mutbl: ast::MutImmutable,
3137 ty_rptr(_, mt) => Some(mt),
3138 ty_ptr(mt) if explicit => Some(mt),
3143 pub fn deref_or_dont(t: t) -> t {
3145 ty_box(ty) | ty_uniq(ty) => {
3148 ty_rptr(_, mt) | ty_ptr(mt) => mt.ty,
3153 pub fn close_type(cx: &ctxt, t: t) -> t {
3155 ty_open(t) => mk_rptr(cx, ReStatic, mt {ty: t, mutbl:ast::MutImmutable}),
3156 _ => cx.sess.bug(format!("Trying to close a non-open type {}",
3157 ty_to_string(cx, t)).as_slice())
3161 pub fn type_content(t: t) -> t {
3163 ty_box(ty) | ty_uniq(ty) => ty,
3164 ty_rptr(_, mt) |ty_ptr(mt) => mt.ty,
3170 // Extract the unsized type in an open type (or just return t if it is not open).
3171 pub fn unopen_type(t: t) -> t {
3178 // Returns the type of t[i]
3179 pub fn index(ty: t) -> Option<t> {
3181 ty_vec(t, _) => Some(t),
3186 // Returns the type of elements contained within an 'array-like' type.
3187 // This is exactly the same as the above, except it supports strings,
3188 // which can't actually be indexed.
3189 pub fn array_element_ty(t: t) -> Option<t> {
3191 ty_vec(t, _) => Some(t),
3192 ty_str => Some(mk_u8()),
3197 pub fn node_id_to_trait_ref(cx: &ctxt, id: ast::NodeId) -> Rc<ty::TraitRef> {
3198 match cx.trait_refs.borrow().find(&id) {
3199 Some(t) => t.clone(),
3200 None => cx.sess.bug(
3201 format!("node_id_to_trait_ref: no trait ref for node `{}`",
3202 cx.map.node_to_string(id)).as_slice())
3206 pub fn try_node_id_to_type(cx: &ctxt, id: ast::NodeId) -> Option<t> {
3207 cx.node_types.borrow().find_copy(&(id as uint))
3210 pub fn node_id_to_type(cx: &ctxt, id: ast::NodeId) -> t {
3211 match try_node_id_to_type(cx, id) {
3213 None => cx.sess.bug(
3214 format!("node_id_to_type: no type for node `{}`",
3215 cx.map.node_to_string(id)).as_slice())
3219 pub fn node_id_to_type_opt(cx: &ctxt, id: ast::NodeId) -> Option<t> {
3220 match cx.node_types.borrow().find(&(id as uint)) {
3221 Some(&t) => Some(t),
3226 pub fn node_id_item_substs(cx: &ctxt, id: ast::NodeId) -> ItemSubsts {
3227 match cx.item_substs.borrow().find(&id) {
3228 None => ItemSubsts::empty(),
3229 Some(ts) => ts.clone(),
3233 pub fn fn_is_variadic(fty: t) -> bool {
3234 match get(fty).sty {
3235 ty_bare_fn(ref f) => f.sig.variadic,
3236 ty_closure(ref f) => f.sig.variadic,
3238 fail!("fn_is_variadic() called on non-fn type: {:?}", s)
3243 pub fn ty_fn_sig(fty: t) -> FnSig {
3244 match get(fty).sty {
3245 ty_bare_fn(ref f) => f.sig.clone(),
3246 ty_closure(ref f) => f.sig.clone(),
3248 fail!("ty_fn_sig() called on non-fn type: {:?}", s)
3253 /// Returns the ABI of the given function.
3254 pub fn ty_fn_abi(fty: t) -> abi::Abi {
3255 match get(fty).sty {
3256 ty_bare_fn(ref f) => f.abi,
3257 ty_closure(ref f) => f.abi,
3258 _ => fail!("ty_fn_abi() called on non-fn type"),
3262 // Type accessors for substructures of types
3263 pub fn ty_fn_args(fty: t) -> Vec<t> {
3264 match get(fty).sty {
3265 ty_bare_fn(ref f) => f.sig.inputs.clone(),
3266 ty_closure(ref f) => f.sig.inputs.clone(),
3268 fail!("ty_fn_args() called on non-fn type: {:?}", s)
3273 pub fn ty_closure_store(fty: t) -> TraitStore {
3274 match get(fty).sty {
3275 ty_closure(ref f) => f.store,
3276 ty_unboxed_closure(..) => {
3277 // Close enough for the purposes of all the callers of this
3278 // function (which is soon to be deprecated anyhow).
3282 fail!("ty_closure_store() called on non-closure type: {:?}", s)
3287 pub fn ty_fn_ret(fty: t) -> t {
3288 match get(fty).sty {
3289 ty_bare_fn(ref f) => f.sig.output,
3290 ty_closure(ref f) => f.sig.output,
3292 fail!("ty_fn_ret() called on non-fn type: {:?}", s)
3297 pub fn is_fn_ty(fty: t) -> bool {
3298 match get(fty).sty {
3299 ty_bare_fn(_) => true,
3300 ty_closure(_) => true,
3305 pub fn ty_region(tcx: &ctxt,
3313 format!("ty_region() invoked on in appropriate ty: {:?}",
3319 pub fn free_region_from_def(free_id: ast::NodeId, def: &RegionParameterDef)
3322 ty::ReFree(ty::FreeRegion { scope_id: free_id,
3323 bound_region: ty::BrNamed(def.def_id,
3327 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
3328 // doesn't provide type parameter substitutions.
3329 pub fn pat_ty(cx: &ctxt, pat: &ast::Pat) -> t {
3330 return node_id_to_type(cx, pat.id);
3334 // Returns the type of an expression as a monotype.
3336 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
3337 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
3338 // auto-ref. The type returned by this function does not consider such
3339 // adjustments. See `expr_ty_adjusted()` instead.
3341 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
3342 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
3343 // instead of "fn(t) -> T with T = int".
3344 pub fn expr_ty(cx: &ctxt, expr: &ast::Expr) -> t {
3345 return node_id_to_type(cx, expr.id);
3348 pub fn expr_ty_opt(cx: &ctxt, expr: &ast::Expr) -> Option<t> {
3349 return node_id_to_type_opt(cx, expr.id);
3352 pub fn expr_ty_adjusted(cx: &ctxt, expr: &ast::Expr) -> t {
3355 * Returns the type of `expr`, considering any `AutoAdjustment`
3356 * entry recorded for that expression.
3358 * It would almost certainly be better to store the adjusted ty in with
3359 * the `AutoAdjustment`, but I opted not to do this because it would
3360 * require serializing and deserializing the type and, although that's not
3361 * hard to do, I just hate that code so much I didn't want to touch it
3362 * unless it was to fix it properly, which seemed a distraction from the
3363 * task at hand! -nmatsakis
3366 adjust_ty(cx, expr.span, expr.id, expr_ty(cx, expr),
3367 cx.adjustments.borrow().find(&expr.id),
3368 |method_call| cx.method_map.borrow().find(&method_call).map(|method| method.ty))
3371 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
3372 match cx.map.find(id) {
3373 Some(ast_map::NodeExpr(e)) => {
3377 cx.sess.bug(format!("Node id {} is not an expr: {:?}",
3382 cx.sess.bug(format!("Node id {} is not present \
3383 in the node map", id).as_slice());
3388 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
3389 match cx.map.find(id) {
3390 Some(ast_map::NodeLocal(pat)) => {
3392 ast::PatIdent(_, ref path1, _) => {
3393 token::get_ident(path1.node)
3397 format!("Variable id {} maps to {:?}, not local",
3404 cx.sess.bug(format!("Variable id {} maps to {:?}, not local",
3411 pub fn adjust_ty(cx: &ctxt,
3413 expr_id: ast::NodeId,
3414 unadjusted_ty: ty::t,
3415 adjustment: Option<&AutoAdjustment>,
3416 method_type: |typeck::MethodCall| -> Option<ty::t>)
3418 /*! See `expr_ty_adjusted` */
3420 match get(unadjusted_ty).sty {
3421 ty_err => return unadjusted_ty,
3425 return match adjustment {
3426 Some(adjustment) => {
3428 AutoAddEnv(store) => {
3429 match ty::get(unadjusted_ty).sty {
3430 ty::ty_bare_fn(ref b) => {
3431 let bounds = ty::ExistentialBounds {
3432 region_bound: ReStatic,
3433 builtin_bounds: all_builtin_bounds(),
3438 ty::ClosureTy {fn_style: b.fn_style,
3439 onceness: ast::Many,
3447 format!("add_env adjustment on non-bare-fn: \
3454 AutoDerefRef(ref adj) => {
3455 let mut adjusted_ty = unadjusted_ty;
3457 if !ty::type_is_error(adjusted_ty) {
3458 for i in range(0, adj.autoderefs) {
3459 let method_call = typeck::MethodCall::autoderef(expr_id, i);
3460 match method_type(method_call) {
3461 Some(method_ty) => {
3462 adjusted_ty = ty_fn_ret(method_ty);
3466 match deref(adjusted_ty, true) {
3467 Some(mt) => { adjusted_ty = mt.ty; }
3471 format!("the {}th autoderef failed: \
3474 ty_to_string(cx, adjusted_ty))
3482 None => adjusted_ty,
3483 Some(ref autoref) => adjust_for_autoref(cx, span, adjusted_ty, autoref)
3488 None => unadjusted_ty
3491 fn adjust_for_autoref(cx: &ctxt,
3494 autoref: &AutoRef) -> ty::t{
3496 AutoPtr(r, m, ref a) => {
3497 let adjusted_ty = match a {
3498 &Some(box ref a) => adjust_for_autoref(cx, span, ty, a),
3507 AutoUnsafe(m, ref a) => {
3508 let adjusted_ty = match a {
3509 &Some(box ref a) => adjust_for_autoref(cx, span, ty, a),
3512 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
3515 AutoUnsize(ref k) => unsize_ty(cx, ty, k, span),
3516 AutoUnsizeUniq(ref k) => ty::mk_uniq(cx, unsize_ty(cx, ty, k, span)),
3521 // Take a sized type and a sizing adjustment and produce an unsized version of
3523 pub fn unsize_ty(cx: &ctxt,
3529 &UnsizeLength(len) => match get(ty).sty {
3530 ty_vec(t, Some(n)) => {
3534 _ => cx.sess.span_bug(span,
3535 format!("UnsizeLength with bad sty: {}",
3536 ty_to_string(cx, ty)).as_slice())
3538 &UnsizeStruct(box ref k, tp_index) => match get(ty).sty {
3539 ty_struct(did, ref substs) => {
3540 let ty_substs = substs.types.get_slice(subst::TypeSpace);
3541 let new_ty = unsize_ty(cx, ty_substs[tp_index], k, span);
3542 let mut unsized_substs = substs.clone();
3543 unsized_substs.types.get_mut_slice(subst::TypeSpace)[tp_index] = new_ty;
3544 mk_struct(cx, did, unsized_substs)
3546 _ => cx.sess.span_bug(span,
3547 format!("UnsizeStruct with bad sty: {}",
3548 ty_to_string(cx, ty)).as_slice())
3550 &UnsizeVtable(TyTrait { def_id, substs: ref substs, bounds }, _) => {
3551 mk_trait(cx, def_id, substs.clone(), bounds)
3557 pub fn map_region(&self, f: |Region| -> Region) -> AutoRef {
3559 ty::AutoPtr(r, m, None) => ty::AutoPtr(f(r), m, None),
3560 ty::AutoPtr(r, m, Some(ref a)) => ty::AutoPtr(f(r), m, Some(box a.map_region(f))),
3561 ty::AutoUnsize(ref k) => ty::AutoUnsize(k.clone()),
3562 ty::AutoUnsizeUniq(ref k) => ty::AutoUnsizeUniq(k.clone()),
3563 ty::AutoUnsafe(m, None) => ty::AutoUnsafe(m, None),
3564 ty::AutoUnsafe(m, Some(ref a)) => ty::AutoUnsafe(m, Some(box a.map_region(f))),
3569 pub fn method_call_type_param_defs<'tcx, T>(typer: &T,
3570 origin: &typeck::MethodOrigin)
3571 -> VecPerParamSpace<TypeParameterDef>
3572 where T: mc::Typer<'tcx> {
3574 typeck::MethodStatic(did) => {
3575 ty::lookup_item_type(typer.tcx(), did).generics.types.clone()
3577 typeck::MethodStaticUnboxedClosure(did) => {
3578 let def_id = typer.unboxed_closures()
3581 .expect("method_call_type_param_defs: didn't \
3582 find unboxed closure")
3584 .trait_did(typer.tcx());
3585 lookup_trait_def(typer.tcx(), def_id).generics.types.clone()
3587 typeck::MethodParam(typeck::MethodParam{
3588 trait_ref: ref trait_ref,
3592 typeck::MethodObject(typeck::MethodObject{
3593 trait_ref: ref trait_ref,
3597 match ty::trait_item(typer.tcx(), trait_ref.def_id, n_mth) {
3598 ty::MethodTraitItem(method) => method.generics.types.clone(),
3599 ty::TypeTraitItem(_) => {
3600 typer.tcx().sess.bug("method_call_type_param_defs() \
3601 called on associated type")
3608 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> def::Def {
3609 match tcx.def_map.borrow().find(&expr.id) {
3612 tcx.sess.span_bug(expr.span, format!(
3613 "no def-map entry for expr {:?}", expr.id).as_slice());
3618 pub fn expr_is_lval(tcx: &ctxt, e: &ast::Expr) -> bool {
3619 match expr_kind(tcx, e) {
3621 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
3625 /// We categorize expressions into three kinds. The distinction between
3626 /// lvalue/rvalue is fundamental to the language. The distinction between the
3627 /// two kinds of rvalues is an artifact of trans which reflects how we will
3628 /// generate code for that kind of expression. See trans/expr.rs for more
3637 pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
3638 if tcx.method_map.borrow().contains_key(&typeck::MethodCall::expr(expr.id)) {
3639 // Overloaded operations are generally calls, and hence they are
3640 // generated via DPS, but there are a few exceptions:
3641 return match expr.node {
3642 // `a += b` has a unit result.
3643 ast::ExprAssignOp(..) => RvalueStmtExpr,
3645 // the deref method invoked for `*a` always yields an `&T`
3646 ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
3648 // the index method invoked for `a[i]` always yields an `&T`
3649 ast::ExprIndex(..) => LvalueExpr,
3651 // `for` loops are statements
3652 ast::ExprForLoop(..) => RvalueStmtExpr,
3654 // in the general case, result could be any type, use DPS
3660 ast::ExprPath(..) => {
3661 match resolve_expr(tcx, expr) {
3662 def::DefVariant(tid, vid, _) => {
3663 let variant_info = enum_variant_with_id(tcx, tid, vid);
3664 if variant_info.args.len() > 0u {
3673 def::DefStruct(_) => {
3674 match get(expr_ty(tcx, expr)).sty {
3675 ty_bare_fn(..) => RvalueDatumExpr,
3680 // Fn pointers are just scalar values.
3681 def::DefFn(..) | def::DefStaticMethod(..) => RvalueDatumExpr,
3683 // Note: there is actually a good case to be made that
3684 // DefArg's, particularly those of immediate type, ought to
3685 // considered rvalues.
3686 def::DefStatic(..) |
3687 def::DefBinding(..) |
3690 def::DefLocal(..) => LvalueExpr,
3695 format!("uncategorized def for expr {:?}: {:?}",
3702 ast::ExprUnary(ast::UnDeref, _) |
3703 ast::ExprField(..) |
3704 ast::ExprTupField(..) |
3705 ast::ExprIndex(..) => {
3710 ast::ExprMethodCall(..) |
3711 ast::ExprStruct(..) |
3714 ast::ExprMatch(..) |
3715 ast::ExprFnBlock(..) |
3717 ast::ExprUnboxedFn(..) |
3718 ast::ExprBlock(..) |
3719 ast::ExprRepeat(..) |
3720 ast::ExprVec(..) => {
3724 ast::ExprLit(ref lit) if lit_is_str(&**lit) => {
3728 ast::ExprCast(..) => {
3729 match tcx.node_types.borrow().find(&(expr.id as uint)) {
3731 if type_is_trait(t) {
3738 // Technically, it should not happen that the expr is not
3739 // present within the table. However, it DOES happen
3740 // during type check, because the final types from the
3741 // expressions are not yet recorded in the tcx. At that
3742 // time, though, we are only interested in knowing lvalue
3743 // vs rvalue. It would be better to base this decision on
3744 // the AST type in cast node---but (at the time of this
3745 // writing) it's not easy to distinguish casts to traits
3746 // from other casts based on the AST. This should be
3747 // easier in the future, when casts to traits
3748 // would like @Foo, Box<Foo>, or &Foo.
3754 ast::ExprBreak(..) |
3755 ast::ExprAgain(..) |
3757 ast::ExprWhile(..) |
3759 ast::ExprAssign(..) |
3760 ast::ExprInlineAsm(..) |
3761 ast::ExprAssignOp(..) |
3762 ast::ExprForLoop(..) => {
3766 ast::ExprLit(_) | // Note: LitStr is carved out above
3767 ast::ExprUnary(..) |
3768 ast::ExprAddrOf(..) |
3769 ast::ExprBinary(..) => {
3773 ast::ExprBox(ref place, _) => {
3774 // Special case `Box<T>`/`Gc<T>` for now:
3775 let definition = match tcx.def_map.borrow().find(&place.id) {
3777 None => fail!("no def for place"),
3779 let def_id = definition.def_id();
3780 if tcx.lang_items.exchange_heap() == Some(def_id) ||
3781 tcx.lang_items.managed_heap() == Some(def_id) {
3788 ast::ExprParen(ref e) => expr_kind(tcx, &**e),
3790 ast::ExprMac(..) => {
3793 "macro expression remains after expansion");
3798 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
3800 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
3803 ast::StmtMac(..) => fail!("unexpanded macro in trans")
3807 pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
3810 for f in fields.iter() { if f.ident.name == name { return i; } i += 1u; }
3811 tcx.sess.bug(format!(
3812 "no field named `{}` found in the list of fields `{:?}`",
3813 token::get_name(name),
3815 .map(|f| token::get_ident(f.ident).get().to_string())
3816 .collect::<Vec<String>>()).as_slice());
3819 pub fn impl_or_trait_item_idx(id: ast::Ident, trait_items: &[ImplOrTraitItem])
3821 trait_items.iter().position(|m| m.ident() == id)
3824 /// Returns a vector containing the indices of all type parameters that appear
3825 /// in `ty`. The vector may contain duplicates. Probably should be converted
3826 /// to a bitset or some other representation.
3827 pub fn param_tys_in_type(ty: t) -> Vec<ParamTy> {
3828 let mut rslt = Vec::new();
3840 pub fn ty_sort_string(cx: &ctxt, t: t) -> String {
3842 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) |
3843 ty_uint(_) | ty_float(_) | ty_str => {
3844 ::util::ppaux::ty_to_string(cx, t)
3847 ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
3848 ty_box(_) => "Gc-ptr".to_string(),
3849 ty_uniq(_) => "box".to_string(),
3850 ty_vec(_, Some(_)) => "array".to_string(),
3851 ty_vec(_, None) => "unsized array".to_string(),
3852 ty_ptr(_) => "*-ptr".to_string(),
3853 ty_rptr(_, _) => "&-ptr".to_string(),
3854 ty_bare_fn(_) => "extern fn".to_string(),
3855 ty_closure(_) => "fn".to_string(),
3856 ty_trait(ref inner) => {
3857 format!("trait {}", item_path_str(cx, inner.def_id))
3859 ty_struct(id, _) => {
3860 format!("struct {}", item_path_str(cx, id))
3862 ty_unboxed_closure(..) => "closure".to_string(),
3863 ty_tup(_) => "tuple".to_string(),
3864 ty_infer(TyVar(_)) => "inferred type".to_string(),
3865 ty_infer(IntVar(_)) => "integral variable".to_string(),
3866 ty_infer(FloatVar(_)) => "floating-point variable".to_string(),
3867 ty_infer(SkolemizedTy(_)) => "skolemized type".to_string(),
3868 ty_infer(SkolemizedIntTy(_)) => "skolemized integral type".to_string(),
3869 ty_param(ref p) => {
3870 if p.space == subst::SelfSpace {
3873 "type parameter".to_string()
3876 ty_err => "type error".to_string(),
3877 ty_open(_) => "opened DST".to_string(),
3881 pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> String {
3884 * Explains the source of a type err in a short,
3885 * human readable way. This is meant to be placed in
3886 * parentheses after some larger message. You should
3887 * also invoke `note_and_explain_type_err()` afterwards
3888 * to present additional details, particularly when
3889 * it comes to lifetime-related errors. */
3891 fn tstore_to_closure(s: &TraitStore) -> String {
3893 &UniqTraitStore => "proc".to_string(),
3894 &RegionTraitStore(..) => "closure".to_string()
3899 terr_cyclic_ty => "cyclic type of infinite size".to_string(),
3900 terr_mismatch => "types differ".to_string(),
3901 terr_fn_style_mismatch(values) => {
3902 format!("expected {} fn, found {} fn",
3903 values.expected.to_string(),
3904 values.found.to_string())
3906 terr_abi_mismatch(values) => {
3907 format!("expected {} fn, found {} fn",
3908 values.expected.to_string(),
3909 values.found.to_string())
3911 terr_onceness_mismatch(values) => {
3912 format!("expected {} fn, found {} fn",
3913 values.expected.to_string(),
3914 values.found.to_string())
3916 terr_sigil_mismatch(values) => {
3917 format!("expected {}, found {}",
3918 tstore_to_closure(&values.expected),
3919 tstore_to_closure(&values.found))
3921 terr_mutability => "values differ in mutability".to_string(),
3922 terr_box_mutability => {
3923 "boxed values differ in mutability".to_string()
3925 terr_vec_mutability => "vectors differ in mutability".to_string(),
3926 terr_ptr_mutability => "pointers differ in mutability".to_string(),
3927 terr_ref_mutability => "references differ in mutability".to_string(),
3928 terr_ty_param_size(values) => {
3929 format!("expected a type with {} type params, \
3930 found one with {} type params",
3934 terr_tuple_size(values) => {
3935 format!("expected a tuple with {} elements, \
3936 found one with {} elements",
3940 terr_record_size(values) => {
3941 format!("expected a record with {} fields, \
3942 found one with {} fields",
3946 terr_record_mutability => {
3947 "record elements differ in mutability".to_string()
3949 terr_record_fields(values) => {
3950 format!("expected a record with field `{}`, found one \
3952 token::get_ident(values.expected),
3953 token::get_ident(values.found))
3956 "incorrect number of function parameters".to_string()
3958 terr_regions_does_not_outlive(..) => {
3959 "lifetime mismatch".to_string()
3961 terr_regions_not_same(..) => {
3962 "lifetimes are not the same".to_string()
3964 terr_regions_no_overlap(..) => {
3965 "lifetimes do not intersect".to_string()
3967 terr_regions_insufficiently_polymorphic(br, _) => {
3968 format!("expected bound lifetime parameter {}, \
3969 found concrete lifetime",
3970 bound_region_ptr_to_string(cx, br))
3972 terr_regions_overly_polymorphic(br, _) => {
3973 format!("expected concrete lifetime, \
3974 found bound lifetime parameter {}",
3975 bound_region_ptr_to_string(cx, br))
3977 terr_trait_stores_differ(_, ref values) => {
3978 format!("trait storage differs: expected `{}`, found `{}`",
3979 trait_store_to_string(cx, (*values).expected),
3980 trait_store_to_string(cx, (*values).found))
3982 terr_sorts(values) => {
3983 format!("expected {}, found {}",
3984 ty_sort_string(cx, values.expected),
3985 ty_sort_string(cx, values.found))
3987 terr_traits(values) => {
3988 format!("expected trait `{}`, found trait `{}`",
3989 item_path_str(cx, values.expected),
3990 item_path_str(cx, values.found))
3992 terr_builtin_bounds(values) => {
3993 if values.expected.is_empty() {
3994 format!("expected no bounds, found `{}`",
3995 values.found.user_string(cx))
3996 } else if values.found.is_empty() {
3997 format!("expected bounds `{}`, found no bounds",
3998 values.expected.user_string(cx))
4000 format!("expected bounds `{}`, found bounds `{}`",
4001 values.expected.user_string(cx),
4002 values.found.user_string(cx))
4005 terr_integer_as_char => {
4006 "expected an integral type, found `char`".to_string()
4008 terr_int_mismatch(ref values) => {
4009 format!("expected `{}`, found `{}`",
4010 values.expected.to_string(),
4011 values.found.to_string())
4013 terr_float_mismatch(ref values) => {
4014 format!("expected `{}`, found `{}`",
4015 values.expected.to_string(),
4016 values.found.to_string())
4018 terr_variadic_mismatch(ref values) => {
4019 format!("expected {} fn, found {} function",
4020 if values.expected { "variadic" } else { "non-variadic" },
4021 if values.found { "variadic" } else { "non-variadic" })
4026 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
4028 terr_regions_does_not_outlive(subregion, superregion) => {
4029 note_and_explain_region(cx, "", subregion, "...");
4030 note_and_explain_region(cx, "...does not necessarily outlive ",
4033 terr_regions_not_same(region1, region2) => {
4034 note_and_explain_region(cx, "", region1, "...");
4035 note_and_explain_region(cx, "...is not the same lifetime as ",
4038 terr_regions_no_overlap(region1, region2) => {
4039 note_and_explain_region(cx, "", region1, "...");
4040 note_and_explain_region(cx, "...does not overlap ",
4043 terr_regions_insufficiently_polymorphic(_, conc_region) => {
4044 note_and_explain_region(cx,
4045 "concrete lifetime that was found is ",
4048 terr_regions_overly_polymorphic(_, conc_region) => {
4049 note_and_explain_region(cx,
4050 "expected concrete lifetime is ",
4057 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
4058 cx.provided_method_sources.borrow().find(&id).map(|x| *x)
4061 pub fn provided_trait_methods(cx: &ctxt, id: ast::DefId) -> Vec<Rc<Method>> {
4063 match cx.map.find(id.node) {
4064 Some(ast_map::NodeItem(item)) => {
4066 ItemTrait(_, _, _, ref ms) => {
4068 ast_util::split_trait_methods(ms.as_slice());
4071 match impl_or_trait_item(
4073 ast_util::local_def(m.id)) {
4074 MethodTraitItem(m) => m,
4075 TypeTraitItem(_) => {
4076 cx.sess.bug("provided_trait_methods(): \
4077 split_trait_methods() put \
4078 associated types in the \
4079 provided method bucket?!")
4085 cx.sess.bug(format!("provided_trait_methods: `{}` is \
4092 cx.sess.bug(format!("provided_trait_methods: `{}` is not a \
4098 csearch::get_provided_trait_methods(cx, id)
4102 fn lookup_locally_or_in_crate_store<V:Clone>(
4105 map: &mut DefIdMap<V>,
4106 load_external: || -> V) -> V {
4108 * Helper for looking things up in the various maps
4109 * that are populated during typeck::collect (e.g.,
4110 * `cx.impl_or_trait_items`, `cx.tcache`, etc). All of these share
4111 * the pattern that if the id is local, it should have
4112 * been loaded into the map by the `typeck::collect` phase.
4113 * If the def-id is external, then we have to go consult
4114 * the crate loading code (and cache the result for the future).
4117 match map.find_copy(&def_id) {
4118 Some(v) => { return v; }
4122 if def_id.krate == ast::LOCAL_CRATE {
4123 fail!("No def'n found for {:?} in tcx.{}", def_id, descr);
4125 let v = load_external();
4126 map.insert(def_id, v.clone());
4130 pub fn trait_item(cx: &ctxt, trait_did: ast::DefId, idx: uint)
4131 -> ImplOrTraitItem {
4132 let method_def_id = ty::trait_item_def_ids(cx, trait_did).get(idx)
4134 impl_or_trait_item(cx, method_def_id)
4137 pub fn trait_items(cx: &ctxt, trait_did: ast::DefId)
4138 -> Rc<Vec<ImplOrTraitItem>> {
4139 let mut trait_items = cx.trait_items_cache.borrow_mut();
4140 match trait_items.find_copy(&trait_did) {
4141 Some(trait_items) => trait_items,
4143 let def_ids = ty::trait_item_def_ids(cx, trait_did);
4144 let items: Rc<Vec<ImplOrTraitItem>> =
4145 Rc::new(def_ids.iter()
4146 .map(|d| impl_or_trait_item(cx, d.def_id()))
4148 trait_items.insert(trait_did, items.clone());
4154 pub fn impl_or_trait_item(cx: &ctxt, id: ast::DefId) -> ImplOrTraitItem {
4155 lookup_locally_or_in_crate_store("impl_or_trait_items",
4157 &mut *cx.impl_or_trait_items
4160 csearch::get_impl_or_trait_item(cx, id)
4164 /// Returns true if the given ID refers to an associated type and false if it
4165 /// refers to anything else.
4166 pub fn is_associated_type(cx: &ctxt, id: ast::DefId) -> bool {
4167 let result = match cx.associated_types.borrow_mut().find(&id) {
4168 Some(result) => return *result,
4169 None if id.krate == ast::LOCAL_CRATE => {
4170 match cx.impl_or_trait_items.borrow().find(&id) {
4173 TypeTraitItem(_) => true,
4174 MethodTraitItem(_) => false,
4181 csearch::is_associated_type(&cx.sess.cstore, id)
4185 cx.associated_types.borrow_mut().insert(id, result);
4189 /// Returns the parameter index that the given associated type corresponds to.
4190 pub fn associated_type_parameter_index(cx: &ctxt,
4191 trait_def: &TraitDef,
4192 associated_type_id: ast::DefId)
4194 for type_parameter_def in trait_def.generics.types.iter() {
4195 if type_parameter_def.def_id == associated_type_id {
4196 return type_parameter_def.index
4199 cx.sess.bug("couldn't find associated type parameter index")
4202 #[deriving(PartialEq, Eq)]
4203 pub struct AssociatedTypeInfo {
4204 pub def_id: ast::DefId,
4206 pub ident: ast::Ident,
4209 impl PartialOrd for AssociatedTypeInfo {
4210 fn partial_cmp(&self, other: &AssociatedTypeInfo) -> Option<Ordering> {
4211 Some(self.index.cmp(&other.index))
4215 impl Ord for AssociatedTypeInfo {
4216 fn cmp(&self, other: &AssociatedTypeInfo) -> Ordering {
4217 self.index.cmp(&other.index)
4221 /// Returns the associated types belonging to the given trait, in parameter
4223 pub fn associated_types_for_trait(cx: &ctxt, trait_id: ast::DefId)
4224 -> Rc<Vec<AssociatedTypeInfo>> {
4225 cx.trait_associated_types
4228 .expect("associated_types_for_trait(): trait not found, try calling \
4229 ensure_associated_types()")
4233 pub fn trait_item_def_ids(cx: &ctxt, id: ast::DefId)
4234 -> Rc<Vec<ImplOrTraitItemId>> {
4235 lookup_locally_or_in_crate_store("trait_item_def_ids",
4237 &mut *cx.trait_item_def_ids.borrow_mut(),
4239 Rc::new(csearch::get_trait_item_def_ids(&cx.sess.cstore, id))
4243 pub fn impl_trait_ref(cx: &ctxt, id: ast::DefId) -> Option<Rc<TraitRef>> {
4244 match cx.impl_trait_cache.borrow().find(&id) {
4245 Some(ret) => { return ret.clone(); }
4249 let ret = if id.krate == ast::LOCAL_CRATE {
4250 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
4251 match cx.map.find(id.node) {
4252 Some(ast_map::NodeItem(item)) => {
4254 ast::ItemImpl(_, ref opt_trait, _, _) => {
4257 Some(ty::node_id_to_trait_ref(cx, t.ref_id))
4268 csearch::get_impl_trait(cx, id)
4271 cx.impl_trait_cache.borrow_mut().insert(id, ret.clone());
4275 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
4276 let def = *tcx.def_map.borrow()
4278 .expect("no def-map entry for trait");
4282 pub fn try_add_builtin_trait(
4284 trait_def_id: ast::DefId,
4285 builtin_bounds: &mut EnumSet<BuiltinBound>)
4288 //! Checks whether `trait_ref` refers to one of the builtin
4289 //! traits, like `Send`, and adds the corresponding
4290 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
4291 //! is a builtin trait.
4293 match tcx.lang_items.to_builtin_kind(trait_def_id) {
4294 Some(bound) => { builtin_bounds.add(bound); true }
4299 pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> {
4301 ty_trait(box TyTrait { def_id: id, .. }) |
4304 ty_unboxed_closure(id, _) => Some(id),
4311 pub struct VariantInfo {
4313 pub arg_names: Option<Vec<ast::Ident> >,
4315 pub name: ast::Ident,
4323 /// Creates a new VariantInfo from the corresponding ast representation.
4325 /// Does not do any caching of the value in the type context.
4326 pub fn from_ast_variant(cx: &ctxt,
4327 ast_variant: &ast::Variant,
4328 discriminant: Disr) -> VariantInfo {
4329 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
4331 match ast_variant.node.kind {
4332 ast::TupleVariantKind(ref args) => {
4333 let arg_tys = if args.len() > 0 {
4334 ty_fn_args(ctor_ty).iter().map(|a| *a).collect()
4339 return VariantInfo {
4343 name: ast_variant.node.name,
4344 id: ast_util::local_def(ast_variant.node.id),
4345 disr_val: discriminant,
4346 vis: ast_variant.node.vis
4349 ast::StructVariantKind(ref struct_def) => {
4351 let fields: &[StructField] = struct_def.fields.as_slice();
4353 assert!(fields.len() > 0);
4355 let arg_tys = ty_fn_args(ctor_ty).iter().map(|a| *a).collect();
4356 let arg_names = fields.iter().map(|field| {
4357 match field.node.kind {
4358 NamedField(ident, _) => ident,
4359 UnnamedField(..) => cx.sess.bug(
4360 "enum_variants: all fields in struct must have a name")
4364 return VariantInfo {
4366 arg_names: Some(arg_names),
4368 name: ast_variant.node.name,
4369 id: ast_util::local_def(ast_variant.node.id),
4370 disr_val: discriminant,
4371 vis: ast_variant.node.vis
4378 pub fn substd_enum_variants(cx: &ctxt,
4381 -> Vec<Rc<VariantInfo>> {
4382 enum_variants(cx, id).iter().map(|variant_info| {
4383 let substd_args = variant_info.args.iter()
4384 .map(|aty| aty.subst(cx, substs)).collect::<Vec<_>>();
4386 let substd_ctor_ty = variant_info.ctor_ty.subst(cx, substs);
4388 Rc::new(VariantInfo {
4390 ctor_ty: substd_ctor_ty,
4391 ..(**variant_info).clone()
4396 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
4397 with_path(cx, id, |path| ast_map::path_to_string(path)).to_string()
4402 TraitDtor(DefId, bool)
4406 pub fn is_present(&self) -> bool {
4408 TraitDtor(..) => true,
4413 pub fn has_drop_flag(&self) -> bool {
4416 &TraitDtor(_, flag) => flag
4421 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
4422 Otherwise return none. */
4423 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
4424 match cx.destructor_for_type.borrow().find(&struct_id) {
4425 Some(&method_def_id) => {
4426 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
4428 TraitDtor(method_def_id, flag)
4434 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
4435 ty_dtor(cx, struct_id).is_present()
4438 pub fn with_path<T>(cx: &ctxt, id: ast::DefId, f: |ast_map::PathElems| -> T) -> T {
4439 if id.krate == ast::LOCAL_CRATE {
4440 cx.map.with_path(id.node, f)
4442 f(ast_map::Values(csearch::get_item_path(cx, id).iter()).chain(None))
4446 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
4447 enum_variants(cx, id).len() == 1
4450 pub fn type_is_empty(cx: &ctxt, t: t) -> bool {
4451 match ty::get(t).sty {
4452 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
4457 pub fn enum_variants(cx: &ctxt, id: ast::DefId) -> Rc<Vec<Rc<VariantInfo>>> {
4458 match cx.enum_var_cache.borrow().find(&id) {
4459 Some(variants) => return variants.clone(),
4460 _ => { /* fallthrough */ }
4463 let result = if ast::LOCAL_CRATE != id.krate {
4464 Rc::new(csearch::get_enum_variants(cx, id))
4467 Although both this code and check_enum_variants in typeck/check
4468 call eval_const_expr, it should never get called twice for the same
4469 expr, since check_enum_variants also updates the enum_var_cache
4471 match cx.map.get(id.node) {
4472 ast_map::NodeItem(ref item) => {
4474 ast::ItemEnum(ref enum_definition, _) => {
4475 let mut last_discriminant: Option<Disr> = None;
4476 Rc::new(enum_definition.variants.iter().map(|variant| {
4478 let mut discriminant = match last_discriminant {
4479 Some(val) => val + 1,
4480 None => INITIAL_DISCRIMINANT_VALUE
4483 match variant.node.disr_expr {
4484 Some(ref e) => match const_eval::eval_const_expr_partial(cx, &**e) {
4485 Ok(const_eval::const_int(val)) => {
4486 discriminant = val as Disr
4488 Ok(const_eval::const_uint(val)) => {
4489 discriminant = val as Disr
4494 "expected signed integer constant");
4499 format!("expected constant: {}",
4506 last_discriminant = Some(discriminant);
4507 Rc::new(VariantInfo::from_ast_variant(cx, &**variant,
4512 cx.sess.bug("enum_variants: id not bound to an enum")
4516 _ => cx.sess.bug("enum_variants: id not bound to an enum")
4520 cx.enum_var_cache.borrow_mut().insert(id, result.clone());
4525 // Returns information about the enum variant with the given ID:
4526 pub fn enum_variant_with_id(cx: &ctxt,
4527 enum_id: ast::DefId,
4528 variant_id: ast::DefId)
4529 -> Rc<VariantInfo> {
4530 enum_variants(cx, enum_id).iter()
4531 .find(|variant| variant.id == variant_id)
4532 .expect("enum_variant_with_id(): no variant exists with that ID")
4537 // If the given item is in an external crate, looks up its type and adds it to
4538 // the type cache. Returns the type parameters and type.
4539 pub fn lookup_item_type(cx: &ctxt,
4542 lookup_locally_or_in_crate_store(
4543 "tcache", did, &mut *cx.tcache.borrow_mut(),
4544 || csearch::get_type(cx, did))
4547 /// Given the did of a trait, returns its canonical trait ref.
4548 pub fn lookup_trait_def(cx: &ctxt, did: ast::DefId) -> Rc<ty::TraitDef> {
4549 let mut trait_defs = cx.trait_defs.borrow_mut();
4550 match trait_defs.find_copy(&did) {
4551 Some(trait_def) => {
4552 // The item is in this crate. The caller should have added it to the
4553 // type cache already
4557 assert!(did.krate != ast::LOCAL_CRATE);
4558 let trait_def = Rc::new(csearch::get_trait_def(cx, did));
4559 trait_defs.insert(did, trait_def.clone());
4565 /// Given a reference to a trait, returns the bounds declared on the
4566 /// trait, with appropriate substitutions applied.
4567 pub fn bounds_for_trait_ref(tcx: &ctxt,
4568 trait_ref: &TraitRef)
4571 let trait_def = lookup_trait_def(tcx, trait_ref.def_id);
4572 debug!("bounds_for_trait_ref(trait_def={}, trait_ref={})",
4573 trait_def.repr(tcx), trait_ref.repr(tcx));
4574 trait_def.bounds.subst(tcx, &trait_ref.substs)
4577 /// Iterate over attributes of a definition.
4578 // (This should really be an iterator, but that would require csearch and
4579 // decoder to use iterators instead of higher-order functions.)
4580 pub fn each_attr(tcx: &ctxt, did: DefId, f: |&ast::Attribute| -> bool) -> bool {
4582 let item = tcx.map.expect_item(did.node);
4583 item.attrs.iter().all(|attr| f(attr))
4585 info!("getting foreign attrs");
4586 let mut cont = true;
4587 csearch::get_item_attrs(&tcx.sess.cstore, did, |attrs| {
4589 cont = attrs.iter().all(|attr| f(attr));
4597 /// Determine whether an item is annotated with an attribute
4598 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
4599 let mut found = false;
4600 each_attr(tcx, did, |item| {
4601 if item.check_name(attr) {
4611 /// Determine whether an item is annotated with `#[repr(packed)]`
4612 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
4613 lookup_repr_hints(tcx, did).contains(&attr::ReprPacked)
4616 /// Determine whether an item is annotated with `#[simd]`
4617 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
4618 has_attr(tcx, did, "simd")
4621 /// Obtain the representation annotation for a struct definition.
4622 pub fn lookup_repr_hints(tcx: &ctxt, did: DefId) -> Vec<attr::ReprAttr> {
4623 let mut acc = Vec::new();
4625 ty::each_attr(tcx, did, |meta| {
4626 acc.extend(attr::find_repr_attrs(tcx.sess.diagnostic(), meta).into_iter());
4633 // Look up a field ID, whether or not it's local
4634 // Takes a list of type substs in case the struct is generic
4635 pub fn lookup_field_type(tcx: &ctxt,
4640 let t = if id.krate == ast::LOCAL_CRATE {
4641 node_id_to_type(tcx, id.node)
4643 let mut tcache = tcx.tcache.borrow_mut();
4644 let pty = tcache.find_or_insert_with(id, |_| {
4645 csearch::get_field_type(tcx, struct_id, id)
4649 t.subst(tcx, substs)
4652 // Lookup all ancestor structs of a struct indicated by did. That is the reflexive,
4653 // transitive closure of doing a single lookup in cx.superstructs.
4654 fn each_super_struct(cx: &ctxt, mut did: ast::DefId, f: |ast::DefId|) {
4655 let superstructs = cx.superstructs.borrow();
4659 match superstructs.find(&did) {
4660 Some(&Some(def_id)) => {
4663 Some(&None) => break,
4666 format!("ID not mapped to super-struct: {}",
4667 cx.map.node_to_string(did.node)).as_slice());
4673 // Look up the list of field names and IDs for a given struct.
4674 // Fails if the id is not bound to a struct.
4675 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
4676 if did.krate == ast::LOCAL_CRATE {
4677 // We store the fields which are syntactically in each struct in cx. So
4678 // we have to walk the inheritance chain of the struct to get all the
4679 // structs (explicit and inherited) for a struct. If this is expensive
4680 // we could cache the whole list of fields here.
4681 let struct_fields = cx.struct_fields.borrow();
4682 let mut results: SmallVector<&[field_ty]> = SmallVector::zero();
4683 each_super_struct(cx, did, |s| {
4684 match struct_fields.find(&s) {
4685 Some(fields) => results.push(fields.as_slice()),
4688 format!("ID not mapped to struct fields: {}",
4689 cx.map.node_to_string(did.node)).as_slice());
4694 let len = results.as_slice().iter().map(|x| x.len()).sum();
4695 let mut result: Vec<field_ty> = Vec::with_capacity(len);
4696 result.extend(results.as_slice().iter().flat_map(|rs| rs.iter().map(|f| f.clone())));
4697 assert!(result.len() == len);
4700 csearch::get_struct_fields(&cx.sess.cstore, did)
4704 pub fn is_tuple_struct(cx: &ctxt, did: ast::DefId) -> bool {
4705 let fields = lookup_struct_fields(cx, did);
4706 !fields.is_empty() && fields.iter().all(|f| f.name == token::special_names::unnamed_field)
4709 pub fn lookup_struct_field(cx: &ctxt,
4711 field_id: ast::DefId)
4713 let r = lookup_struct_fields(cx, parent);
4714 match r.iter().find(|f| f.id.node == field_id.node) {
4715 Some(t) => t.clone(),
4716 None => cx.sess.bug("struct ID not found in parent's fields")
4720 // Returns a list of fields corresponding to the struct's items. trans uses
4721 // this. Takes a list of substs with which to instantiate field types.
4722 pub fn struct_fields(cx: &ctxt, did: ast::DefId, substs: &Substs)
4724 lookup_struct_fields(cx, did).iter().map(|f| {
4726 // FIXME #6993: change type of field to Name and get rid of new()
4727 ident: ast::Ident::new(f.name),
4729 ty: lookup_field_type(cx, did, f.id, substs),
4736 // Returns a list of fields corresponding to the tuple's items. trans uses
4738 pub fn tup_fields(v: &[t]) -> Vec<field> {
4739 v.iter().enumerate().map(|(i, &f)| {
4741 // FIXME #6993: change type of field to Name and get rid of new()
4742 ident: ast::Ident::new(token::intern(i.to_string().as_slice())),
4751 pub struct UnboxedClosureUpvar {
4757 // Returns a list of `UnboxedClosureUpvar`s for each upvar.
4758 pub fn unboxed_closure_upvars(tcx: &ctxt, closure_id: ast::DefId)
4759 -> Vec<UnboxedClosureUpvar> {
4760 if closure_id.krate == ast::LOCAL_CRATE {
4761 match tcx.freevars.borrow().find(&closure_id.node) {
4762 None => tcx.sess.bug("no freevars for unboxed closure?!"),
4763 Some(ref freevars) => {
4764 freevars.iter().map(|freevar| {
4765 let freevar_def_id = freevar.def.def_id();
4766 UnboxedClosureUpvar {
4769 ty: node_id_to_type(tcx, freevar_def_id.node),
4775 tcx.sess.bug("unimplemented cross-crate closure upvars")
4779 pub fn is_binopable(cx: &ctxt, ty: t, op: ast::BinOp) -> bool {
4780 static tycat_other: int = 0;
4781 static tycat_bool: int = 1;
4782 static tycat_char: int = 2;
4783 static tycat_int: int = 3;
4784 static tycat_float: int = 4;
4785 static tycat_bot: int = 5;
4786 static tycat_raw_ptr: int = 6;
4788 static opcat_add: int = 0;
4789 static opcat_sub: int = 1;
4790 static opcat_mult: int = 2;
4791 static opcat_shift: int = 3;
4792 static opcat_rel: int = 4;
4793 static opcat_eq: int = 5;
4794 static opcat_bit: int = 6;
4795 static opcat_logic: int = 7;
4796 static opcat_mod: int = 8;
4798 fn opcat(op: ast::BinOp) -> int {
4800 ast::BiAdd => opcat_add,
4801 ast::BiSub => opcat_sub,
4802 ast::BiMul => opcat_mult,
4803 ast::BiDiv => opcat_mult,
4804 ast::BiRem => opcat_mod,
4805 ast::BiAnd => opcat_logic,
4806 ast::BiOr => opcat_logic,
4807 ast::BiBitXor => opcat_bit,
4808 ast::BiBitAnd => opcat_bit,
4809 ast::BiBitOr => opcat_bit,
4810 ast::BiShl => opcat_shift,
4811 ast::BiShr => opcat_shift,
4812 ast::BiEq => opcat_eq,
4813 ast::BiNe => opcat_eq,
4814 ast::BiLt => opcat_rel,
4815 ast::BiLe => opcat_rel,
4816 ast::BiGe => opcat_rel,
4817 ast::BiGt => opcat_rel
4821 fn tycat(cx: &ctxt, ty: t) -> int {
4822 if type_is_simd(cx, ty) {
4823 return tycat(cx, simd_type(cx, ty))
4826 ty_char => tycat_char,
4827 ty_bool => tycat_bool,
4828 ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
4829 ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
4830 ty_bot => tycat_bot,
4831 ty_ptr(_) => tycat_raw_ptr,
4836 static t: bool = true;
4837 static f: bool = false;
4840 // +, -, *, shift, rel, ==, bit, logic, mod
4841 /*other*/ [f, f, f, f, f, f, f, f, f],
4842 /*bool*/ [f, f, f, f, t, t, t, t, f],
4843 /*char*/ [f, f, f, f, t, t, f, f, f],
4844 /*int*/ [t, t, t, t, t, t, t, f, t],
4845 /*float*/ [t, t, t, f, t, t, f, f, f],
4846 /*bot*/ [t, t, t, t, t, t, t, t, t],
4847 /*raw ptr*/ [f, f, f, f, t, t, f, f, f]];
4849 return tbl[tycat(cx, ty) as uint ][opcat(op) as uint];
4852 /// Returns an equivalent type with all the typedefs and self regions removed.
4853 pub fn normalize_ty(cx: &ctxt, t: t) -> t {
4854 let u = TypeNormalizer(cx).fold_ty(t);
4857 struct TypeNormalizer<'a, 'tcx: 'a>(&'a ctxt<'tcx>);
4859 impl<'a, 'tcx> TypeFolder<'tcx> for TypeNormalizer<'a, 'tcx> {
4860 fn tcx(&self) -> &ctxt<'tcx> { let TypeNormalizer(c) = *self; c }
4862 fn fold_ty(&mut self, t: ty::t) -> ty::t {
4863 match self.tcx().normalized_cache.borrow().find_copy(&t) {
4868 let t_norm = ty_fold::super_fold_ty(self, t);
4869 self.tcx().normalized_cache.borrow_mut().insert(t, t_norm);
4873 fn fold_region(&mut self, _: ty::Region) -> ty::Region {
4877 fn fold_substs(&mut self,
4878 substs: &subst::Substs)
4880 subst::Substs { regions: subst::ErasedRegions,
4881 types: substs.types.fold_with(self) }
4884 fn fold_sig(&mut self,
4887 // The binder-id is only relevant to bound regions, which
4888 // are erased at trans time.
4890 binder_id: ast::DUMMY_NODE_ID,
4891 inputs: sig.inputs.fold_with(self),
4892 output: sig.output.fold_with(self),
4893 variadic: sig.variadic,
4899 // Returns the repeat count for a repeating vector expression.
4900 pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> uint {
4901 match const_eval::eval_const_expr_partial(tcx, count_expr) {
4902 Ok(ref const_val) => match *const_val {
4903 const_eval::const_int(count) => if count < 0 {
4904 tcx.sess.span_err(count_expr.span,
4905 "expected positive integer for \
4906 repeat count, found negative integer");
4911 const_eval::const_uint(count) => count as uint,
4912 const_eval::const_float(count) => {
4913 tcx.sess.span_err(count_expr.span,
4914 "expected positive integer for \
4915 repeat count, found float");
4918 const_eval::const_str(_) => {
4919 tcx.sess.span_err(count_expr.span,
4920 "expected positive integer for \
4921 repeat count, found string");
4924 const_eval::const_bool(_) => {
4925 tcx.sess.span_err(count_expr.span,
4926 "expected positive integer for \
4927 repeat count, found boolean");
4930 const_eval::const_binary(_) => {
4931 tcx.sess.span_err(count_expr.span,
4932 "expected positive integer for \
4933 repeat count, found binary array");
4936 const_eval::const_nil => {
4937 tcx.sess.span_err(count_expr.span,
4938 "expected positive integer for \
4939 repeat count, found ()");
4944 tcx.sess.span_err(count_expr.span,
4945 "expected constant integer for repeat count, \
4952 // Iterate over a type parameter's bounded traits and any supertraits
4953 // of those traits, ignoring kinds.
4954 // Here, the supertraits are the transitive closure of the supertrait
4955 // relation on the supertraits from each bounded trait's constraint
4957 pub fn each_bound_trait_and_supertraits(tcx: &ctxt,
4958 bounds: &[Rc<TraitRef>],
4959 f: |Rc<TraitRef>| -> bool)
4962 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
4963 if !f(bound_trait_ref) {
4970 pub fn required_region_bounds(tcx: &ctxt,
4971 region_bounds: &[ty::Region],
4972 builtin_bounds: BuiltinBounds,
4973 trait_bounds: &[Rc<TraitRef>])
4977 * Given a type which must meet the builtin bounds and trait
4978 * bounds, returns a set of lifetimes which the type must outlive.
4980 * Requires that trait definitions have been processed.
4983 let mut all_bounds = Vec::new();
4985 debug!("required_region_bounds(builtin_bounds={}, trait_bounds={})",
4986 builtin_bounds.repr(tcx),
4987 trait_bounds.repr(tcx));
4989 all_bounds.push_all(region_bounds);
4991 push_region_bounds([],
4995 debug!("from builtin bounds: all_bounds={}", all_bounds.repr(tcx));
4997 each_bound_trait_and_supertraits(
5001 let bounds = ty::bounds_for_trait_ref(tcx, &*trait_ref);
5002 push_region_bounds(bounds.region_bounds.as_slice(),
5003 bounds.builtin_bounds,
5005 debug!("from {}: bounds={} all_bounds={}",
5006 trait_ref.repr(tcx),
5008 all_bounds.repr(tcx));
5014 fn push_region_bounds(region_bounds: &[ty::Region],
5015 builtin_bounds: ty::BuiltinBounds,
5016 all_bounds: &mut Vec<ty::Region>) {
5017 all_bounds.push_all(region_bounds.as_slice());
5019 if builtin_bounds.contains_elem(ty::BoundSend) {
5020 all_bounds.push(ty::ReStatic);
5025 pub fn get_tydesc_ty(tcx: &ctxt) -> Result<t, String> {
5026 tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
5027 tcx.intrinsic_defs.borrow().find_copy(&tydesc_lang_item)
5028 .expect("Failed to resolve TyDesc")
5032 pub fn get_opaque_ty(tcx: &ctxt) -> Result<t, String> {
5033 tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| {
5034 tcx.intrinsic_defs.borrow().find_copy(&opaque_lang_item)
5035 .expect("Failed to resolve Opaque")
5039 pub fn visitor_object_ty(tcx: &ctxt,
5040 ptr_region: ty::Region,
5041 trait_region: ty::Region)
5042 -> Result<(Rc<TraitRef>, t), String>
5044 let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) {
5046 Err(s) => { return Err(s); }
5048 let substs = Substs::empty();
5049 let trait_ref = Rc::new(TraitRef { def_id: trait_lang_item, substs: substs });
5050 Ok((trait_ref.clone(),
5051 mk_rptr(tcx, ptr_region,
5052 mt {mutbl: ast::MutMutable,
5055 trait_ref.substs.clone(),
5056 ty::region_existential_bound(trait_region))})))
5059 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> Rc<ItemVariances> {
5060 lookup_locally_or_in_crate_store(
5061 "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
5062 || Rc::new(csearch::get_item_variances(&tcx.sess.cstore, item_id)))
5065 /// Records a trait-to-implementation mapping.
5066 pub fn record_trait_implementation(tcx: &ctxt,
5067 trait_def_id: DefId,
5068 impl_def_id: DefId) {
5069 match tcx.trait_impls.borrow().find(&trait_def_id) {
5070 Some(impls_for_trait) => {
5071 impls_for_trait.borrow_mut().push(impl_def_id);
5076 tcx.trait_impls.borrow_mut().insert(trait_def_id, Rc::new(RefCell::new(vec!(impl_def_id))));
5079 /// Populates the type context with all the implementations for the given type
5081 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
5082 type_id: ast::DefId) {
5083 if type_id.krate == LOCAL_CRATE {
5086 if tcx.populated_external_types.borrow().contains(&type_id) {
5090 let mut inherent_impls = Vec::new();
5091 csearch::each_implementation_for_type(&tcx.sess.cstore, type_id,
5093 let impl_items = csearch::get_impl_items(&tcx.sess.cstore,
5096 // Record the trait->implementation mappings, if applicable.
5097 let associated_traits = csearch::get_impl_trait(tcx, impl_def_id);
5098 for trait_ref in associated_traits.iter() {
5099 record_trait_implementation(tcx, trait_ref.def_id, impl_def_id);
5102 // For any methods that use a default implementation, add them to
5103 // the map. This is a bit unfortunate.
5104 for impl_item_def_id in impl_items.iter() {
5105 let method_def_id = impl_item_def_id.def_id();
5106 match impl_or_trait_item(tcx, method_def_id) {
5107 MethodTraitItem(method) => {
5108 for &source in method.provided_source.iter() {
5109 tcx.provided_method_sources
5111 .insert(method_def_id, source);
5114 TypeTraitItem(_) => {}
5118 // Store the implementation info.
5119 tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
5121 // If this is an inherent implementation, record it.
5122 if associated_traits.is_none() {
5123 inherent_impls.push(impl_def_id);
5127 tcx.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
5128 tcx.populated_external_types.borrow_mut().insert(type_id);
5131 /// Populates the type context with all the implementations for the given
5132 /// trait if necessary.
5133 pub fn populate_implementations_for_trait_if_necessary(
5135 trait_id: ast::DefId) {
5136 if trait_id.krate == LOCAL_CRATE {
5139 if tcx.populated_external_traits.borrow().contains(&trait_id) {
5143 csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id,
5144 |implementation_def_id| {
5145 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, implementation_def_id);
5147 // Record the trait->implementation mapping.
5148 record_trait_implementation(tcx, trait_id, implementation_def_id);
5150 // For any methods that use a default implementation, add them to
5151 // the map. This is a bit unfortunate.
5152 for impl_item_def_id in impl_items.iter() {
5153 let method_def_id = impl_item_def_id.def_id();
5154 match impl_or_trait_item(tcx, method_def_id) {
5155 MethodTraitItem(method) => {
5156 for &source in method.provided_source.iter() {
5157 tcx.provided_method_sources
5159 .insert(method_def_id, source);
5162 TypeTraitItem(_) => {}
5166 // Store the implementation info.
5167 tcx.impl_items.borrow_mut().insert(implementation_def_id, impl_items);
5170 tcx.populated_external_traits.borrow_mut().insert(trait_id);
5173 /// Given the def_id of an impl, return the def_id of the trait it implements.
5174 /// If it implements no trait, return `None`.
5175 pub fn trait_id_of_impl(tcx: &ctxt,
5176 def_id: ast::DefId) -> Option<ast::DefId> {
5177 let node = match tcx.map.find(def_id.node) {
5182 ast_map::NodeItem(item) => {
5184 ast::ItemImpl(_, Some(ref trait_ref), _, _) => {
5185 Some(node_id_to_trait_ref(tcx, trait_ref.ref_id).def_id)
5194 /// If the given def ID describes a method belonging to an impl, return the
5195 /// ID of the impl that the method belongs to. Otherwise, return `None`.
5196 pub fn impl_of_method(tcx: &ctxt, def_id: ast::DefId)
5197 -> Option<ast::DefId> {
5198 if def_id.krate != LOCAL_CRATE {
5199 return match csearch::get_impl_or_trait_item(tcx,
5200 def_id).container() {
5201 TraitContainer(_) => None,
5202 ImplContainer(def_id) => Some(def_id),
5205 match tcx.impl_or_trait_items.borrow().find_copy(&def_id) {
5206 Some(trait_item) => {
5207 match trait_item.container() {
5208 TraitContainer(_) => None,
5209 ImplContainer(def_id) => Some(def_id),
5216 /// If the given def ID describes an item belonging to a trait (either a
5217 /// default method or an implementation of a trait method), return the ID of
5218 /// the trait that the method belongs to. Otherwise, return `None`.
5219 pub fn trait_of_item(tcx: &ctxt, def_id: ast::DefId) -> Option<ast::DefId> {
5220 if def_id.krate != LOCAL_CRATE {
5221 return csearch::get_trait_of_item(&tcx.sess.cstore, def_id, tcx);
5223 match tcx.impl_or_trait_items.borrow().find_copy(&def_id) {
5224 Some(impl_or_trait_item) => {
5225 match impl_or_trait_item.container() {
5226 TraitContainer(def_id) => Some(def_id),
5227 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
5234 /// If the given def ID describes an item belonging to a trait, (either a
5235 /// default method or an implementation of a trait method), return the ID of
5236 /// the method inside trait definition (this means that if the given def ID
5237 /// is already that of the original trait method, then the return value is
5239 /// Otherwise, return `None`.
5240 pub fn trait_item_of_item(tcx: &ctxt, def_id: ast::DefId)
5241 -> Option<ImplOrTraitItemId> {
5242 let impl_item = match tcx.impl_or_trait_items.borrow().find(&def_id) {
5243 Some(m) => m.clone(),
5244 None => return None,
5246 let name = impl_item.ident().name;
5247 match trait_of_item(tcx, def_id) {
5248 Some(trait_did) => {
5249 let trait_items = ty::trait_items(tcx, trait_did);
5251 .position(|m| m.ident().name == name)
5252 .map(|idx| ty::trait_item(tcx, trait_did, idx).id())
5258 /// Creates a hash of the type `t` which will be the same no matter what crate
5259 /// context it's calculated within. This is used by the `type_id` intrinsic.
5260 pub fn hash_crate_independent(tcx: &ctxt, t: t, svh: &Svh) -> u64 {
5261 let mut state = sip::SipState::new();
5262 macro_rules! byte( ($b:expr) => { ($b as u8).hash(&mut state) } );
5263 macro_rules! hash( ($e:expr) => { $e.hash(&mut state) } );
5265 let region = |_state: &mut sip::SipState, r: Region| {
5275 tcx.sess.bug("non-static region found when hashing a type")
5279 let did = |state: &mut sip::SipState, did: DefId| {
5280 let h = if ast_util::is_local(did) {
5283 tcx.sess.cstore.get_crate_hash(did.krate)
5285 h.as_str().hash(state);
5286 did.node.hash(state);
5288 let mt = |state: &mut sip::SipState, mt: mt| {
5289 mt.mutbl.hash(state);
5291 ty::walk_ty(t, |t| {
5292 match ty::get(t).sty {
5295 ty_bool => byte!(2),
5296 ty_char => byte!(3),
5322 ty_vec(_, Some(n)) => {
5326 ty_vec(_, None) => {
5328 0u8.hash(&mut state);
5336 region(&mut state, r);
5339 ty_bare_fn(ref b) => {
5344 ty_closure(ref c) => {
5350 UniqTraitStore => byte!(0),
5351 RegionTraitStore(r, m) => {
5353 region(&mut state, r);
5354 assert_eq!(m, ast::MutMutable);
5358 ty_trait(box TyTrait { def_id: d, bounds, .. }) => {
5363 ty_struct(d, _) => {
5367 ty_tup(ref inner) => {
5374 did(&mut state, p.def_id);
5376 ty_open(_) => byte!(22),
5377 ty_infer(_) => unreachable!(),
5378 ty_err => byte!(23),
5379 ty_unboxed_closure(d, r) => {
5382 region(&mut state, r);
5391 pub fn to_string(self) -> &'static str {
5394 Contravariant => "-",
5401 pub fn empty_parameter_environment() -> ParameterEnvironment {
5403 * Construct a parameter environment suitable for static contexts
5404 * or other contexts where there are no free type/lifetime
5405 * parameters in scope.
5408 ty::ParameterEnvironment { free_substs: Substs::empty(),
5409 bounds: VecPerParamSpace::empty(),
5410 caller_obligations: VecPerParamSpace::empty(),
5411 implicit_region_bound: ty::ReEmpty }
5414 pub fn construct_parameter_environment(
5417 generics: &ty::Generics,
5418 free_id: ast::NodeId)
5419 -> ParameterEnvironment
5421 /*! See `ParameterEnvironment` struct def'n for details */
5424 // Construct the free substs.
5428 let mut types = VecPerParamSpace::empty();
5429 for &space in subst::ParamSpace::all().iter() {
5430 push_types_from_defs(tcx, &mut types, space,
5431 generics.types.get_slice(space));
5434 // map bound 'a => free 'a
5435 let mut regions = VecPerParamSpace::empty();
5436 for &space in subst::ParamSpace::all().iter() {
5437 push_region_params(&mut regions, space, free_id,
5438 generics.regions.get_slice(space));
5441 let free_substs = Substs {
5443 regions: subst::NonerasedRegions(regions)
5447 // Compute the bounds on Self and the type parameters.
5450 let mut bounds = VecPerParamSpace::empty();
5451 for &space in subst::ParamSpace::all().iter() {
5452 push_bounds_from_defs(tcx, &mut bounds, space, &free_substs,
5453 generics.types.get_slice(space));
5457 // Compute region bounds. For now, these relations are stored in a
5458 // global table on the tcx, so just enter them there. I'm not
5459 // crazy about this scheme, but it's convenient, at least.
5462 for &space in subst::ParamSpace::all().iter() {
5463 record_region_bounds_from_defs(tcx, space, &free_substs,
5464 generics.regions.get_slice(space));
5468 debug!("construct_parameter_environment: free_id={} \
5472 free_substs.repr(tcx),
5475 let obligations = traits::obligations_for_generics(tcx, traits::ObligationCause::misc(span),
5476 generics, &free_substs);
5478 return ty::ParameterEnvironment {
5479 free_substs: free_substs,
5481 implicit_region_bound: ty::ReScope(free_id),
5482 caller_obligations: obligations,
5485 fn push_region_params(regions: &mut VecPerParamSpace<ty::Region>,
5486 space: subst::ParamSpace,
5487 free_id: ast::NodeId,
5488 region_params: &[RegionParameterDef])
5490 for r in region_params.iter() {
5491 regions.push(space, ty::free_region_from_def(free_id, r));
5495 fn push_types_from_defs(tcx: &ty::ctxt,
5496 types: &mut subst::VecPerParamSpace<ty::t>,
5497 space: subst::ParamSpace,
5498 defs: &[TypeParameterDef]) {
5499 for (i, def) in defs.iter().enumerate() {
5500 debug!("construct_parameter_environment(): push_types_from_defs: \
5501 space={} def={} index={}",
5505 let ty = ty::mk_param(tcx, space, i, def.def_id);
5506 types.push(space, ty);
5510 fn push_bounds_from_defs(tcx: &ty::ctxt,
5511 bounds: &mut subst::VecPerParamSpace<ParamBounds>,
5512 space: subst::ParamSpace,
5513 free_substs: &subst::Substs,
5514 defs: &[TypeParameterDef]) {
5515 for def in defs.iter() {
5516 let b = def.bounds.subst(tcx, free_substs);
5517 bounds.push(space, b);
5521 fn record_region_bounds_from_defs(tcx: &ty::ctxt,
5522 space: subst::ParamSpace,
5523 free_substs: &subst::Substs,
5524 defs: &[RegionParameterDef]) {
5525 for (subst_region, def) in
5526 free_substs.regions().get_slice(space).iter().zip(
5529 // For each region parameter 'subst...
5530 let bounds = def.bounds.subst(tcx, free_substs);
5531 for bound_region in bounds.iter() {
5532 // Which is declared with a bound like 'subst:'bound...
5533 match (subst_region, bound_region) {
5534 (&ty::ReFree(subst_fr), &ty::ReFree(bound_fr)) => {
5535 // Record that 'subst outlives 'bound. Or, put
5536 // another way, 'bound <= 'subst.
5537 tcx.region_maps.relate_free_regions(bound_fr, subst_fr);
5540 // All named regions are instantiated with free regions.
5542 format!("push_region_bounds_from_defs: \
5543 non free region: {} / {}",
5544 subst_region.repr(tcx),
5545 bound_region.repr(tcx)).as_slice());
5554 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
5556 ast::MutMutable => MutBorrow,
5557 ast::MutImmutable => ImmBorrow,
5561 pub fn to_mutbl_lossy(self) -> ast::Mutability {
5563 * Returns a mutability `m` such that an `&m T` pointer could
5564 * be used to obtain this borrow kind. Because borrow kinds
5565 * are richer than mutabilities, we sometimes have to pick a
5566 * mutability that is stronger than necessary so that it at
5567 * least *would permit* the borrow in question.
5571 MutBorrow => ast::MutMutable,
5572 ImmBorrow => ast::MutImmutable,
5574 // We have no type correponding to a unique imm borrow, so
5575 // use `&mut`. It gives all the capabilities of an `&uniq`
5576 // and hence is a safe "over approximation".
5577 UniqueImmBorrow => ast::MutMutable,
5581 pub fn to_user_str(&self) -> &'static str {
5583 MutBorrow => "mutable",
5584 ImmBorrow => "immutable",
5585 UniqueImmBorrow => "uniquely immutable",
5590 impl<'tcx> mc::Typer<'tcx> for ty::ctxt<'tcx> {
5591 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
5595 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<ty::t> {
5596 Ok(ty::node_id_to_type(self, id))
5599 fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t> {
5600 self.method_map.borrow().find(&method_call).map(|method| method.ty)
5603 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment>> {
5607 fn is_method_call(&self, id: ast::NodeId) -> bool {
5608 self.method_map.borrow().contains_key(&typeck::MethodCall::expr(id))
5611 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<ast::NodeId> {
5612 self.region_maps.temporary_scope(rvalue_id)
5615 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow {
5616 self.upvar_borrow_map.borrow().get_copy(&upvar_id)
5619 fn capture_mode(&self, closure_expr_id: ast::NodeId)
5620 -> freevars::CaptureMode {
5621 self.capture_modes.borrow().get_copy(&closure_expr_id)
5624 fn unboxed_closures<'a>(&'a self)
5625 -> &'a RefCell<DefIdMap<UnboxedClosure>> {
5626 &self.unboxed_closures
5630 /// The category of explicit self.
5631 #[deriving(Clone, Eq, PartialEq)]
5632 pub enum ExplicitSelfCategory {
5633 StaticExplicitSelfCategory,
5634 ByValueExplicitSelfCategory,
5635 ByReferenceExplicitSelfCategory(Region, ast::Mutability),
5636 ByBoxExplicitSelfCategory,
5639 /// Pushes all the lifetimes in the given type onto the given list. A
5640 /// "lifetime in a type" is a lifetime specified by a reference or a lifetime
5641 /// in a list of type substitutions. This does *not* traverse into nominal
5642 /// types, nor does it resolve fictitious types.
5643 pub fn accumulate_lifetimes_in_type(accumulator: &mut Vec<ty::Region>,
5645 walk_ty(typ, |typ| {
5646 match get(typ).sty {
5647 ty_rptr(region, _) => accumulator.push(region),
5648 ty_enum(_, ref substs) |
5649 ty_trait(box TyTrait {
5653 ty_struct(_, ref substs) => {
5654 match substs.regions {
5655 subst::ErasedRegions => {}
5656 subst::NonerasedRegions(ref regions) => {
5657 for region in regions.iter() {
5658 accumulator.push(*region)
5663 ty_closure(ref closure_ty) => {
5664 match closure_ty.store {
5665 RegionTraitStore(region, _) => accumulator.push(region),
5666 UniqTraitStore => {}
5669 ty_unboxed_closure(_, ref region) => accumulator.push(*region),