1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(non_camel_case_types)]
14 use driver::session::Session;
16 use metadata::csearch;
17 use middle::const_eval;
19 use middle::dependency_format;
20 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem};
21 use middle::lang_items::{FnOnceTraitLangItem, OpaqueStructLangItem};
22 use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem};
23 use middle::mem_categorization as mc;
25 use middle::resolve_lifetime;
26 use middle::stability;
27 use middle::subst::{Subst, Substs, VecPerParamSpace};
33 use middle::ty_fold::{TypeFoldable,TypeFolder};
35 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_string};
36 use util::ppaux::{trait_store_to_string, ty_to_string};
37 use util::ppaux::{Repr, UserString};
38 use util::common::{indenter};
39 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet, FnvHashMap};
41 use std::cell::{Cell, RefCell};
45 use std::hash::{Hash, sip, Writer};
46 use std::iter::AdditiveIterator;
50 use std::collections::{HashMap, HashSet};
51 use arena::TypedArena;
53 use syntax::ast::{CrateNum, DefId, FnStyle, Ident, ItemTrait, LOCAL_CRATE};
54 use syntax::ast::{MutImmutable, MutMutable, Name, NamedField, NodeId};
55 use syntax::ast::{Onceness, StmtExpr, StmtSemi, StructField, UnnamedField};
56 use syntax::ast::{Visibility};
57 use syntax::ast_util::{PostExpansionMethod, is_local, lit_is_str};
60 use syntax::attr::AttrMetaMethods;
61 use syntax::codemap::Span;
62 use syntax::parse::token;
63 use syntax::parse::token::InternedString;
64 use syntax::{ast, ast_map};
65 use syntax::util::small_vector::SmallVector;
66 use std::collections::enum_set::{EnumSet, CLike};
70 pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0;
74 #[deriving(PartialEq, Eq, Hash)]
76 pub ident: ast::Ident,
81 pub enum ImplOrTraitItemContainer {
82 TraitContainer(ast::DefId),
83 ImplContainer(ast::DefId),
86 impl ImplOrTraitItemContainer {
87 pub fn id(&self) -> ast::DefId {
89 TraitContainer(id) => id,
90 ImplContainer(id) => id,
96 pub enum ImplOrTraitItem {
97 MethodTraitItem(Rc<Method>),
98 TypeTraitItem(Rc<AssociatedType>),
101 impl ImplOrTraitItem {
102 fn id(&self) -> ImplOrTraitItemId {
104 MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
105 TypeTraitItem(ref associated_type) => {
106 TypeTraitItemId(associated_type.def_id)
111 pub fn def_id(&self) -> ast::DefId {
113 MethodTraitItem(ref method) => method.def_id,
114 TypeTraitItem(ref associated_type) => associated_type.def_id,
118 pub fn ident(&self) -> ast::Ident {
120 MethodTraitItem(ref method) => method.ident,
121 TypeTraitItem(ref associated_type) => associated_type.ident,
125 pub fn container(&self) -> ImplOrTraitItemContainer {
127 MethodTraitItem(ref method) => method.container,
128 TypeTraitItem(ref associated_type) => associated_type.container,
134 pub enum ImplOrTraitItemId {
135 MethodTraitItemId(ast::DefId),
136 TypeTraitItemId(ast::DefId),
139 impl ImplOrTraitItemId {
140 pub fn def_id(&self) -> ast::DefId {
142 MethodTraitItemId(def_id) => def_id,
143 TypeTraitItemId(def_id) => def_id,
150 pub ident: ast::Ident,
151 pub generics: ty::Generics,
153 pub explicit_self: ExplicitSelfCategory,
154 pub vis: ast::Visibility,
155 pub def_id: ast::DefId,
156 pub container: ImplOrTraitItemContainer,
158 // If this method is provided, we need to know where it came from
159 pub provided_source: Option<ast::DefId>
163 pub fn new(ident: ast::Ident,
164 generics: ty::Generics,
166 explicit_self: ExplicitSelfCategory,
167 vis: ast::Visibility,
169 container: ImplOrTraitItemContainer,
170 provided_source: Option<ast::DefId>)
176 explicit_self: explicit_self,
179 container: container,
180 provided_source: provided_source
184 pub fn container_id(&self) -> ast::DefId {
185 match self.container {
186 TraitContainer(id) => id,
187 ImplContainer(id) => id,
193 pub struct AssociatedType {
194 pub ident: ast::Ident,
195 pub vis: ast::Visibility,
196 pub def_id: ast::DefId,
197 pub container: ImplOrTraitItemContainer,
200 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
203 pub mutbl: ast::Mutability,
206 #[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
207 pub enum TraitStore {
210 /// &Trait and &mut Trait
211 RegionTraitStore(Region, ast::Mutability),
214 #[deriving(Clone, Show)]
215 pub struct field_ty {
218 pub vis: ast::Visibility,
219 pub origin: ast::DefId, // The DefId of the struct in which the field is declared.
222 // Contains information needed to resolve types and (in the future) look up
223 // the types of AST nodes.
224 #[deriving(PartialEq, Eq, Hash)]
225 pub struct creader_cache_key {
231 pub type creader_cache = RefCell<HashMap<creader_cache_key, t>>;
233 pub struct intern_key {
237 // NB: Do not replace this with #[deriving(PartialEq)]. The automatically-derived
238 // implementation will not recurse through sty and you will get stack
240 impl cmp::PartialEq for intern_key {
241 fn eq(&self, other: &intern_key) -> bool {
243 *self.sty == *other.sty
246 fn ne(&self, other: &intern_key) -> bool {
251 impl Eq for intern_key {}
253 impl<W:Writer> Hash<W> for intern_key {
254 fn hash(&self, s: &mut W) {
255 unsafe { (*self.sty).hash(s) }
259 pub enum ast_ty_to_ty_cache_entry {
260 atttce_unresolved, /* not resolved yet */
261 atttce_resolved(t) /* resolved to a type, irrespective of region */
264 #[deriving(Clone, PartialEq, Decodable, Encodable)]
265 pub struct ItemVariances {
266 pub types: VecPerParamSpace<Variance>,
267 pub regions: VecPerParamSpace<Variance>,
270 #[deriving(Clone, PartialEq, Decodable, Encodable, Show)]
272 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
273 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
274 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
275 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
279 pub enum AutoAdjustment {
280 AdjustAddEnv(ty::TraitStore),
281 AdjustDerefRef(AutoDerefRef)
284 #[deriving(Clone, PartialEq)]
285 pub enum UnsizeKind {
286 // [T, ..n] -> [T], the uint field is n.
288 // An unsize coercion applied to the tail field of a struct.
289 // The uint is the index of the type parameter which is unsized.
290 UnsizeStruct(Box<UnsizeKind>, uint),
291 UnsizeVtable(TyTrait, /* the self type of the trait */ ty::t)
295 pub struct AutoDerefRef {
296 pub autoderefs: uint,
297 pub autoref: Option<AutoRef>
300 #[deriving(Clone, PartialEq)]
302 /// Convert from T to &T
303 /// The third field allows us to wrap other AutoRef adjustments.
304 AutoPtr(Region, ast::Mutability, Option<Box<AutoRef>>),
306 /// Convert [T, ..n] to [T] (or similar, depending on the kind)
307 AutoUnsize(UnsizeKind),
309 /// Convert Box<[T, ..n]> to Box<[T]> or something similar in a Box.
310 /// With DST and Box a library type, this should be replaced by UnsizeStruct.
311 AutoUnsizeUniq(UnsizeKind),
313 /// Convert from T to *T
314 /// Value to thin pointer
315 /// The second field allows us to wrap other AutoRef adjustments.
316 AutoUnsafe(ast::Mutability, Option<Box<AutoRef>>),
319 // Ugly little helper function. The first bool in the returned tuple is true if
320 // there is an 'unsize to trait object' adjustment at the bottom of the
321 // adjustment. If that is surrounded by an AutoPtr, then we also return the
322 // region of the AutoPtr (in the third argument). The second bool is true if the
323 // adjustment is unique.
324 fn autoref_object_region(autoref: &AutoRef) -> (bool, bool, Option<Region>) {
325 fn unsize_kind_is_object(k: &UnsizeKind) -> bool {
327 &UnsizeVtable(..) => true,
328 &UnsizeStruct(box ref k, _) => unsize_kind_is_object(k),
334 &AutoUnsize(ref k) => (unsize_kind_is_object(k), false, None),
335 &AutoUnsizeUniq(ref k) => (unsize_kind_is_object(k), true, None),
336 &AutoPtr(adj_r, _, Some(box ref autoref)) => {
337 let (b, u, r) = autoref_object_region(autoref);
338 if r.is_some() || u {
344 &AutoUnsafe(_, Some(box ref autoref)) => autoref_object_region(autoref),
345 _ => (false, false, None)
349 // If the adjustment introduces a borrowed reference to a trait object, then
350 // returns the region of the borrowed reference.
351 pub fn adjusted_object_region(adj: &AutoAdjustment) -> Option<Region> {
353 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
354 let (b, _, r) = autoref_object_region(autoref);
365 // Returns true if there is a trait cast at the bottom of the adjustment.
366 pub fn adjust_is_object(adj: &AutoAdjustment) -> bool {
368 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
369 let (b, _, _) = autoref_object_region(autoref);
376 // If possible, returns the type expected from the given adjustment. This is not
377 // possible if the adjustment depends on the type of the adjusted expression.
378 pub fn type_of_adjust(cx: &ctxt, adj: &AutoAdjustment) -> Option<t> {
379 fn type_of_autoref(cx: &ctxt, autoref: &AutoRef) -> Option<t> {
381 &AutoUnsize(ref k) => match k {
382 &UnsizeVtable(TyTrait { def_id, substs: ref substs, bounds }, _) => {
383 Some(mk_trait(cx, def_id, substs.clone(), bounds))
387 &AutoUnsizeUniq(ref k) => match k {
388 &UnsizeVtable(TyTrait { def_id, substs: ref substs, bounds }, _) => {
389 Some(mk_uniq(cx, mk_trait(cx, def_id, substs.clone(), bounds)))
393 &AutoPtr(r, m, Some(box ref autoref)) => {
394 match type_of_autoref(cx, autoref) {
395 Some(t) => Some(mk_rptr(cx, r, mt {mutbl: m, ty: t})),
399 &AutoUnsafe(m, Some(box ref autoref)) => {
400 match type_of_autoref(cx, autoref) {
401 Some(t) => Some(mk_ptr(cx, mt {mutbl: m, ty: t})),
410 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
411 type_of_autoref(cx, autoref)
419 /// A restriction that certain types must be the same size. The use of
420 /// `transmute` gives rise to these restrictions.
421 pub struct TransmuteRestriction {
422 /// The span from whence the restriction comes.
424 /// The type being transmuted from.
426 /// The type being transmuted to.
428 /// NodeIf of the transmute intrinsic.
432 /// The data structure to keep track of all the information that typechecker
433 /// generates so that so that it can be reused and doesn't have to be redone
435 pub struct ctxt<'tcx> {
436 /// The arena that types are allocated from.
437 type_arena: &'tcx TypedArena<t_box_>,
439 /// Specifically use a speedy hash algorithm for this hash map, it's used
441 interner: RefCell<FnvHashMap<intern_key, &'tcx t_box_>>,
442 pub next_id: Cell<uint>,
444 pub def_map: resolve::DefMap,
446 pub named_region_map: resolve_lifetime::NamedRegionMap,
448 pub region_maps: middle::region::RegionMaps,
450 /// Stores the types for various nodes in the AST. Note that this table
451 /// is not guaranteed to be populated until after typeck. See
452 /// typeck::check::fn_ctxt for details.
453 pub node_types: node_type_table,
455 /// Stores the type parameters which were substituted to obtain the type
456 /// of this node. This only applies to nodes that refer to entities
457 /// parameterized by type parameters, such as generic fns, types, or
459 pub item_substs: RefCell<NodeMap<ItemSubsts>>,
461 /// Maps from a trait item to the trait item "descriptor"
462 pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem>>,
464 /// Maps from a trait def-id to a list of the def-ids of its trait items
465 pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
467 /// A cache for the trait_items() routine
468 pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem>>>>,
470 pub impl_trait_cache: RefCell<DefIdMap<Option<Rc<ty::TraitRef>>>>,
472 pub trait_refs: RefCell<NodeMap<Rc<TraitRef>>>,
473 pub trait_defs: RefCell<DefIdMap<Rc<TraitDef>>>,
475 /// Maps from node-id of a trait object cast (like `foo as
476 /// Box<Trait>`) to the trait reference.
477 pub object_cast_map: typeck::ObjectCastMap,
479 pub map: ast_map::Map<'tcx>,
480 pub intrinsic_defs: RefCell<DefIdMap<t>>,
481 pub freevars: RefCell<FreevarMap>,
482 pub tcache: type_cache,
483 pub rcache: creader_cache,
484 pub short_names_cache: RefCell<HashMap<t, String>>,
485 pub needs_unwind_cleanup_cache: RefCell<HashMap<t, bool>>,
486 pub tc_cache: RefCell<HashMap<uint, TypeContents>>,
487 pub ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry>>,
488 pub enum_var_cache: RefCell<DefIdMap<Rc<Vec<Rc<VariantInfo>>>>>,
489 pub ty_param_defs: RefCell<NodeMap<TypeParameterDef>>,
490 pub adjustments: RefCell<NodeMap<AutoAdjustment>>,
491 pub normalized_cache: RefCell<HashMap<t, t>>,
492 pub lang_items: middle::lang_items::LanguageItems,
493 /// A mapping of fake provided method def_ids to the default implementation
494 pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
495 pub superstructs: RefCell<DefIdMap<Option<ast::DefId>>>,
496 pub struct_fields: RefCell<DefIdMap<Rc<Vec<field_ty>>>>,
498 /// Maps from def-id of a type or region parameter to its
499 /// (inferred) variance.
500 pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
502 /// True if the variance has been computed yet; false otherwise.
503 pub variance_computed: Cell<bool>,
505 /// A mapping from the def ID of an enum or struct type to the def ID
506 /// of the method that implements its destructor. If the type is not
507 /// present in this map, it does not have a destructor. This map is
508 /// populated during the coherence phase of typechecking.
509 pub destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
511 /// A method will be in this list if and only if it is a destructor.
512 pub destructors: RefCell<DefIdSet>,
514 /// Maps a trait onto a list of impls of that trait.
515 pub trait_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
517 /// Maps a DefId of a type to a list of its inherent impls.
518 /// Contains implementations of methods that are inherent to a type.
519 /// Methods in these implementations don't need to be exported.
520 pub inherent_impls: RefCell<DefIdMap<Rc<Vec<ast::DefId>>>>,
522 /// Maps a DefId of an impl to a list of its items.
523 /// Note that this contains all of the impls that we know about,
524 /// including ones in other crates. It's not clear that this is the best
526 pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
528 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
529 /// present in this set can be warned about.
530 pub used_unsafe: RefCell<NodeSet>,
532 /// Set of nodes which mark locals as mutable which end up getting used at
533 /// some point. Local variable definitions not in this set can be warned
535 pub used_mut_nodes: RefCell<NodeSet>,
537 /// The set of external nominal types whose implementations have been read.
538 /// This is used for lazy resolution of methods.
539 pub populated_external_types: RefCell<DefIdSet>,
541 /// The set of external traits whose implementations have been read. This
542 /// is used for lazy resolution of traits.
543 pub populated_external_traits: RefCell<DefIdSet>,
546 pub upvar_borrow_map: RefCell<UpvarBorrowMap>,
548 /// These two caches are used by const_eval when decoding external statics
549 /// and variants that are found.
550 pub extern_const_statics: RefCell<DefIdMap<ast::NodeId>>,
551 pub extern_const_variants: RefCell<DefIdMap<ast::NodeId>>,
553 pub method_map: typeck::MethodMap,
555 pub dependency_formats: RefCell<dependency_format::Dependencies>,
557 /// Records the type of each unboxed closure. The def ID is the ID of the
558 /// expression defining the unboxed closure.
559 pub unboxed_closures: RefCell<DefIdMap<UnboxedClosure>>,
561 pub node_lint_levels: RefCell<HashMap<(ast::NodeId, lint::LintId),
564 /// The types that must be asserted to be the same size for `transmute`
565 /// to be valid. We gather up these restrictions in the intrinsicck pass
566 /// and check them in trans.
567 pub transmute_restrictions: RefCell<Vec<TransmuteRestriction>>,
569 /// Maps any item's def-id to its stability index.
570 pub stability: RefCell<stability::Index>,
572 /// Maps closures to their capture clauses.
573 pub capture_modes: RefCell<CaptureModeMap>,
575 /// Maps def IDs to true if and only if they're associated types.
576 pub associated_types: RefCell<DefIdMap<bool>>,
578 /// Maps def IDs of traits to information about their associated types.
579 pub trait_associated_types:
580 RefCell<DefIdMap<Rc<Vec<AssociatedTypeInfo>>>>,
591 // a meta-pub flag: subst may be required if the type has parameters, a self
592 // type, or references bound regions
593 needs_subst = 1 | 2 | 8
596 pub type t_box = &'static t_box_;
605 // To reduce refcounting cost, we're representing types as unsafe pointers
606 // throughout the compiler. These are simply casted t_box values. Use ty::get
607 // to cast them back to a box. (Without the cast, compiler performance suffers
608 // ~15%.) This does mean that a t value relies on the ctxt to keep its box
609 // alive, and using ty::get is unsafe when the ctxt is no longer alive.
612 #[allow(raw_pointer_deriving)]
613 #[deriving(Clone, PartialEq, Eq, Hash)]
614 pub struct t { inner: *const t_opaque }
616 impl fmt::Show for t {
617 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
618 write!(f, "{}", get(*self))
622 pub fn get(t: t) -> t_box {
624 let t2: t_box = mem::transmute(t);
629 pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
630 (tb.flags & (flag as uint)) != 0u
632 pub fn type_has_params(t: t) -> bool {
633 tbox_has_flag(get(t), has_params)
635 pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
636 pub fn type_needs_infer(t: t) -> bool {
637 tbox_has_flag(get(t), needs_infer)
639 pub fn type_id(t: t) -> uint { get(t).id }
641 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
642 pub struct BareFnTy {
643 pub fn_style: ast::FnStyle,
648 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
649 pub struct ClosureTy {
650 pub fn_style: ast::FnStyle,
651 pub onceness: ast::Onceness,
652 pub store: TraitStore,
653 pub bounds: ExistentialBounds,
659 * Signature of a function type, which I have arbitrarily
660 * decided to use to refer to the input/output types.
662 * - `binder_id` is the node id where this fn type appeared;
663 * it is used to identify all the bound regions appearing
664 * in the input/output types that are bound by this fn type
665 * (vs some enclosing or enclosed fn type)
666 * - `inputs` is the list of arguments and their modes.
667 * - `output` is the return type.
668 * - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
670 #[deriving(Clone, PartialEq, Eq, Hash)]
672 pub binder_id: ast::NodeId,
678 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
680 pub space: subst::ParamSpace,
685 /// Representation of regions:
686 #[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
688 // Region bound in a type or fn declaration which will be
689 // substituted 'early' -- that is, at the same time when type
690 // parameters are substituted.
691 ReEarlyBound(/* param id */ ast::NodeId,
696 // Region bound in a function scope, which will be substituted when the
697 // function is called. The first argument must be the `binder_id` of
698 // some enclosing function signature.
699 ReLateBound(/* binder_id */ ast::NodeId, BoundRegion),
701 /// When checking a function body, the types of all arguments and so forth
702 /// that refer to bound region parameters are modified to refer to free
703 /// region parameters.
706 /// A concrete region naming some expression within the current function.
709 /// Static data that has an "infinite" lifetime. Top in the region lattice.
712 /// A region variable. Should not exist after typeck.
713 ReInfer(InferRegion),
715 /// Empty lifetime is for data that is never accessed.
716 /// Bottom in the region lattice. We treat ReEmpty somewhat
717 /// specially; at least right now, we do not generate instances of
718 /// it during the GLB computations, but rather
719 /// generate an error instead. This is to improve error messages.
720 /// The only way to get an instance of ReEmpty is to have a region
721 /// variable with no constraints.
726 * Upvars do not get their own node-id. Instead, we use the pair of
727 * the original var id (that is, the root variable that is referenced
728 * by the upvar) and the id of the closure expression.
730 #[deriving(Clone, PartialEq, Eq, Hash)]
732 pub var_id: ast::NodeId,
733 pub closure_expr_id: ast::NodeId,
736 #[deriving(Clone, PartialEq, Eq, Hash, Show, Encodable, Decodable)]
737 pub enum BorrowKind {
738 /// Data must be immutable and is aliasable.
741 /// Data must be immutable but not aliasable. This kind of borrow
742 /// cannot currently be expressed by the user and is used only in
743 /// implicit closure bindings. It is needed when you the closure
744 /// is borrowing or mutating a mutable referent, e.g.:
746 /// let x: &mut int = ...;
747 /// let y = || *x += 5;
749 /// If we were to try to translate this closure into a more explicit
750 /// form, we'd encounter an error with the code as written:
752 /// struct Env { x: & &mut int }
753 /// let x: &mut int = ...;
754 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
755 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
757 /// This is then illegal because you cannot mutate a `&mut` found
758 /// in an aliasable location. To solve, you'd have to translate with
759 /// an `&mut` borrow:
761 /// struct Env { x: & &mut int }
762 /// let x: &mut int = ...;
763 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
764 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
766 /// Now the assignment to `**env.x` is legal, but creating a
767 /// mutable pointer to `x` is not because `x` is not mutable. We
768 /// could fix this by declaring `x` as `let mut x`. This is ok in
769 /// user code, if awkward, but extra weird for closures, since the
770 /// borrow is hidden.
772 /// So we introduce a "unique imm" borrow -- the referent is
773 /// immutable, but not aliasable. This solves the problem. For
774 /// simplicity, we don't give users the way to express this
775 /// borrow, it's just used when translating closures.
778 /// Data is mutable and not aliasable.
783 * Information describing the borrowing of an upvar. This is computed
784 * during `typeck`, specifically by `regionck`. The general idea is
785 * that the compiler analyses treat closures like:
787 * let closure: &'e fn() = || {
788 * x = 1; // upvar x is assigned to
789 * use(y); // upvar y is read
790 * foo(&z); // upvar z is borrowed immutably
793 * as if they were "desugared" to something loosely like:
795 * struct Vars<'x,'y,'z> { x: &'x mut int,
798 * let closure: &'e fn() = {
804 * let env: &'e mut Vars<'x,'y,'z> = &mut Vars { x: &'x mut x,
810 * This is basically what happens at runtime. The closure is basically
811 * an existentially quantified version of the `(env, f)` pair.
813 * This data structure indicates the region and mutability of a single
814 * one of the `x...z` borrows.
816 * It may not be obvious why each borrowed variable gets its own
817 * lifetime (in the desugared version of the example, these are indicated
818 * by the lifetime parameters `'x`, `'y`, and `'z` in the `Vars` definition).
819 * Each such lifetime must encompass the lifetime `'e` of the closure itself,
820 * but need not be identical to it. The reason that this makes sense:
822 * - Callers are only permitted to invoke the closure, and hence to
823 * use the pointers, within the lifetime `'e`, so clearly `'e` must
824 * be a sublifetime of `'x...'z`.
825 * - The closure creator knows which upvars were borrowed by the closure
826 * and thus `x...z` will be reserved for `'x...'z` respectively.
827 * - Through mutation, the borrowed upvars can actually escape
828 * the closure, so sometimes it is necessary for them to be larger
829 * than the closure lifetime itself.
831 #[deriving(PartialEq, Clone, Encodable, Decodable)]
832 pub struct UpvarBorrow {
833 pub kind: BorrowKind,
834 pub region: ty::Region,
837 pub type UpvarBorrowMap = HashMap<UpvarId, UpvarBorrow>;
840 pub fn is_bound(&self) -> bool {
842 &ty::ReEarlyBound(..) => true,
843 &ty::ReLateBound(..) => true,
849 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
850 pub struct FreeRegion {
851 pub scope_id: NodeId,
852 pub bound_region: BoundRegion
855 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
856 pub enum BoundRegion {
857 /// An anonymous region parameter for a given fn (&T)
860 /// Named region parameters for functions (a in &'a T)
862 /// The def-id is needed to distinguish free regions in
863 /// the event of shadowing.
864 BrNamed(ast::DefId, ast::Name),
866 /// Fresh bound identifiers created during GLB computations.
875 macro_rules! def_prim_ty(
876 ($name:ident, $sty:expr, $id:expr) => (
877 pub static $name: t_box_ = t_box_ {
885 def_prim_ty!(TY_NIL, super::ty_nil, 0)
886 def_prim_ty!(TY_BOOL, super::ty_bool, 1)
887 def_prim_ty!(TY_CHAR, super::ty_char, 2)
888 def_prim_ty!(TY_INT, super::ty_int(ast::TyI), 3)
889 def_prim_ty!(TY_I8, super::ty_int(ast::TyI8), 4)
890 def_prim_ty!(TY_I16, super::ty_int(ast::TyI16), 5)
891 def_prim_ty!(TY_I32, super::ty_int(ast::TyI32), 6)
892 def_prim_ty!(TY_I64, super::ty_int(ast::TyI64), 7)
893 def_prim_ty!(TY_UINT, super::ty_uint(ast::TyU), 8)
894 def_prim_ty!(TY_U8, super::ty_uint(ast::TyU8), 9)
895 def_prim_ty!(TY_U16, super::ty_uint(ast::TyU16), 10)
896 def_prim_ty!(TY_U32, super::ty_uint(ast::TyU32), 11)
897 def_prim_ty!(TY_U64, super::ty_uint(ast::TyU64), 12)
898 def_prim_ty!(TY_F32, super::ty_float(ast::TyF32), 14)
899 def_prim_ty!(TY_F64, super::ty_float(ast::TyF64), 15)
901 pub static TY_BOT: t_box_ = t_box_ {
904 flags: super::has_ty_bot as uint,
907 pub static TY_ERR: t_box_ = t_box_ {
910 flags: super::has_ty_err as uint,
913 pub static LAST_PRIMITIVE_ID: uint = 18;
916 // NB: If you change this, you'll probably want to change the corresponding
917 // AST structure in libsyntax/ast.rs as well.
918 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
925 ty_uint(ast::UintTy),
926 ty_float(ast::FloatTy),
927 /// Substs here, possibly against intuition, *may* contain `ty_param`s.
928 /// That is, even after substitution it is possible that there are type
929 /// variables. This happens when the `ty_enum` corresponds to an enum
930 /// definition and not a concrete use of it. To get the correct `ty_enum`
931 /// from the tcx, use the `NodeId` from the `ast::Ty` and look it up in
932 /// the `ast_ty_to_ty_cache`. This is probably true for `ty_struct` as
934 ty_enum(DefId, Substs),
938 ty_vec(t, Option<uint>), // Second field is length.
941 ty_bare_fn(BareFnTy),
942 ty_closure(Box<ClosureTy>),
943 ty_trait(Box<TyTrait>),
944 ty_struct(DefId, Substs),
945 ty_unboxed_closure(DefId, Region),
948 ty_param(ParamTy), // type parameter
949 ty_open(t), // A deref'ed fat pointer, i.e., a dynamically sized value
950 // and its size. Only ever used in trans. It is not necessary
951 // earlier since we don't need to distinguish a DST with its
952 // size (e.g., in a deref) vs a DST with the size elsewhere (
953 // e.g., in a field).
955 ty_infer(InferTy), // something used only during inference/typeck
956 ty_err, // Also only used during inference/typeck, to represent
957 // the type of an erroneous expression (helps cut down
958 // on non-useful type error messages)
961 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
965 pub bounds: ExistentialBounds
968 #[deriving(PartialEq, Eq, Hash, Show)]
969 pub struct TraitRef {
974 #[deriving(Clone, PartialEq)]
975 pub enum IntVarValue {
977 UintType(ast::UintTy),
980 #[deriving(Clone, Show)]
981 pub enum terr_vstore_kind {
988 #[deriving(Clone, Show)]
989 pub struct expected_found<T> {
994 // Data structures used in type unification
995 #[deriving(Clone, Show)]
998 terr_fn_style_mismatch(expected_found<FnStyle>),
999 terr_onceness_mismatch(expected_found<Onceness>),
1000 terr_abi_mismatch(expected_found<abi::Abi>),
1002 terr_sigil_mismatch(expected_found<TraitStore>),
1003 terr_box_mutability,
1004 terr_ptr_mutability,
1005 terr_ref_mutability,
1006 terr_vec_mutability,
1007 terr_tuple_size(expected_found<uint>),
1008 terr_ty_param_size(expected_found<uint>),
1009 terr_record_size(expected_found<uint>),
1010 terr_record_mutability,
1011 terr_record_fields(expected_found<Ident>),
1013 terr_regions_does_not_outlive(Region, Region),
1014 terr_regions_not_same(Region, Region),
1015 terr_regions_no_overlap(Region, Region),
1016 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
1017 terr_regions_overly_polymorphic(BoundRegion, Region),
1018 terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
1019 terr_sorts(expected_found<t>),
1020 terr_integer_as_char,
1021 terr_int_mismatch(expected_found<IntVarValue>),
1022 terr_float_mismatch(expected_found<ast::FloatTy>),
1023 terr_traits(expected_found<ast::DefId>),
1024 terr_builtin_bounds(expected_found<BuiltinBounds>),
1025 terr_variadic_mismatch(expected_found<bool>),
1029 /// Bounds suitable for a named type parameter like `A` in `fn foo<A>`
1030 /// as well as the existential type parameter in an object type.
1031 #[deriving(PartialEq, Eq, Hash, Clone, Show)]
1032 pub struct ParamBounds {
1033 pub region_bounds: Vec<ty::Region>,
1034 pub builtin_bounds: BuiltinBounds,
1035 pub trait_bounds: Vec<Rc<TraitRef>>
1038 /// Bounds suitable for an existentially quantified type parameter
1039 /// such as those that appear in object types or closure types. The
1040 /// major difference between this case and `ParamBounds` is that
1041 /// general purpose trait bounds are omitted and there must be
1042 /// *exactly one* region.
1043 #[deriving(PartialEq, Eq, Hash, Clone, Show)]
1044 pub struct ExistentialBounds {
1045 pub region_bound: ty::Region,
1046 pub builtin_bounds: BuiltinBounds
1049 pub type BuiltinBounds = EnumSet<BuiltinBound>;
1051 #[deriving(Clone, Encodable, PartialEq, Eq, Decodable, Hash, Show)]
1053 pub enum BuiltinBound {
1060 pub fn empty_builtin_bounds() -> BuiltinBounds {
1064 pub fn all_builtin_bounds() -> BuiltinBounds {
1065 let mut set = EnumSet::empty();
1067 set.add(BoundSized);
1072 pub fn region_existential_bound(r: ty::Region) -> ExistentialBounds {
1074 * An existential bound that does not implement any traits.
1077 ty::ExistentialBounds { region_bound: r,
1078 builtin_bounds: empty_builtin_bounds() }
1081 impl CLike for BuiltinBound {
1082 fn to_uint(&self) -> uint {
1085 fn from_uint(v: uint) -> BuiltinBound {
1086 unsafe { mem::transmute(v) }
1090 #[deriving(Clone, PartialEq, Eq, Hash)]
1095 #[deriving(Clone, PartialEq, Eq, Hash)]
1100 #[deriving(Clone, PartialEq, Eq, Hash)]
1101 pub struct FloatVid {
1105 #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)]
1106 pub struct RegionVid {
1110 #[deriving(Clone, PartialEq, Eq, Hash)]
1117 // FIXME -- once integral fallback is impl'd, we should remove
1118 // this type. It's only needed to prevent spurious errors for
1119 // integers whose type winds up never being constrained.
1120 SkolemizedIntTy(uint),
1123 #[deriving(Clone, Encodable, Decodable, Eq, Hash, Show)]
1124 pub enum InferRegion {
1126 ReSkolemized(uint, BoundRegion)
1129 impl cmp::PartialEq for InferRegion {
1130 fn eq(&self, other: &InferRegion) -> bool {
1131 match ((*self), *other) {
1132 (ReVar(rva), ReVar(rvb)) => {
1135 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
1141 fn ne(&self, other: &InferRegion) -> bool {
1142 !((*self) == (*other))
1146 impl fmt::Show for TyVid {
1147 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
1148 write!(f, "<generic #{}>", self.index)
1152 impl fmt::Show for IntVid {
1153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1154 write!(f, "<generic integer #{}>", self.index)
1158 impl fmt::Show for FloatVid {
1159 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1160 write!(f, "<generic float #{}>", self.index)
1164 impl fmt::Show for RegionVid {
1165 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1166 write!(f, "'<generic lifetime #{}>", self.index)
1170 impl fmt::Show for FnSig {
1171 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1172 // grr, without tcx not much we can do.
1177 impl fmt::Show for InferTy {
1178 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1180 TyVar(ref v) => v.fmt(f),
1181 IntVar(ref v) => v.fmt(f),
1182 FloatVar(ref v) => v.fmt(f),
1183 SkolemizedTy(v) => write!(f, "SkolemizedTy({})", v),
1184 SkolemizedIntTy(v) => write!(f, "SkolemizedIntTy({})", v),
1189 impl fmt::Show for IntVarValue {
1190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1192 IntType(ref v) => v.fmt(f),
1193 UintType(ref v) => v.fmt(f),
1198 #[deriving(Clone, Show)]
1199 pub struct TypeParameterDef {
1200 pub ident: ast::Ident,
1201 pub def_id: ast::DefId,
1202 pub space: subst::ParamSpace,
1204 pub associated_with: Option<ast::DefId>,
1205 pub bounds: ParamBounds,
1206 pub default: Option<ty::t>,
1209 #[deriving(Encodable, Decodable, Clone, Show)]
1210 pub struct RegionParameterDef {
1211 pub name: ast::Name,
1212 pub def_id: ast::DefId,
1213 pub space: subst::ParamSpace,
1215 pub bounds: Vec<ty::Region>,
1218 /// Information about the type/lifetime parameters associated with an
1219 /// item or method. Analogous to ast::Generics.
1220 #[deriving(Clone, Show)]
1221 pub struct Generics {
1222 pub types: VecPerParamSpace<TypeParameterDef>,
1223 pub regions: VecPerParamSpace<RegionParameterDef>,
1227 pub fn empty() -> Generics {
1228 Generics { types: VecPerParamSpace::empty(),
1229 regions: VecPerParamSpace::empty() }
1232 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
1233 !self.types.is_empty_in(space)
1236 pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
1237 !self.regions.is_empty_in(space)
1242 pub fn self_ty(&self) -> ty::t {
1243 self.substs.self_ty().unwrap()
1247 /// When type checking, we use the `ParameterEnvironment` to track
1248 /// details about the type/lifetime parameters that are in scope.
1249 /// It primarily stores the bounds information.
1251 /// Note: This information might seem to be redundant with the data in
1252 /// `tcx.ty_param_defs`, but it is not. That table contains the
1253 /// parameter definitions from an "outside" perspective, but this
1254 /// struct will contain the bounds for a parameter as seen from inside
1255 /// the function body. Currently the only real distinction is that
1256 /// bound lifetime parameters are replaced with free ones, but in the
1257 /// future I hope to refine the representation of types so as to make
1258 /// more distinctions clearer.
1259 pub struct ParameterEnvironment {
1260 /// A substitution that can be applied to move from
1261 /// the "outer" view of a type or method to the "inner" view.
1262 /// In general, this means converting from bound parameters to
1263 /// free parameters. Since we currently represent bound/free type
1264 /// parameters in the same way, this only has an effect on regions.
1265 pub free_substs: Substs,
1267 /// Bounds on the various type parameters
1268 pub bounds: VecPerParamSpace<ParamBounds>,
1270 /// Each type parameter has an implicit region bound that
1271 /// indicates it must outlive at least the function body (the user
1272 /// may specify stronger requirements). This field indicates the
1273 /// region of the callee.
1274 pub implicit_region_bound: ty::Region,
1276 /// Obligations that the caller must satisfy. This is basically
1277 /// the set of bounds on the in-scope type parameters, translated
1278 /// into Obligations.
1280 /// Note: This effectively *duplicates* the `bounds` array for
1282 pub caller_obligations: VecPerParamSpace<traits::Obligation>,
1285 impl ParameterEnvironment {
1286 pub fn for_item(cx: &ctxt, id: NodeId) -> ParameterEnvironment {
1287 match cx.map.find(id) {
1288 Some(ast_map::NodeImplItem(ref impl_item)) => {
1290 ast::MethodImplItem(ref method) => {
1291 let method_def_id = ast_util::local_def(id);
1292 match ty::impl_or_trait_item(cx, method_def_id) {
1293 MethodTraitItem(ref method_ty) => {
1294 let method_generics = &method_ty.generics;
1295 construct_parameter_environment(
1299 method.pe_body().id)
1301 TypeTraitItem(_) => {
1303 .bug("ParameterEnvironment::from_item(): \
1304 can't create a parameter environment \
1305 for type trait items")
1309 ast::TypeImplItem(_) => {
1310 cx.sess.bug("ParameterEnvironment::from_item(): \
1311 can't create a parameter environment \
1312 for type impl items")
1316 Some(ast_map::NodeTraitItem(trait_method)) => {
1317 match *trait_method {
1318 ast::RequiredMethod(ref required) => {
1319 cx.sess.span_bug(required.span,
1320 "ParameterEnvironment::from_item():
1321 can't create a parameter \
1322 environment for required trait \
1325 ast::ProvidedMethod(ref method) => {
1326 let method_def_id = ast_util::local_def(id);
1327 match ty::impl_or_trait_item(cx, method_def_id) {
1328 MethodTraitItem(ref method_ty) => {
1329 let method_generics = &method_ty.generics;
1330 construct_parameter_environment(
1334 method.pe_body().id)
1336 TypeTraitItem(_) => {
1338 .bug("ParameterEnvironment::from_item(): \
1339 can't create a parameter environment \
1340 for type trait items")
1344 ast::TypeTraitItem(_) => {
1345 cx.sess.bug("ParameterEnvironment::from_item(): \
1346 can't create a parameter environment \
1347 for type trait items")
1351 Some(ast_map::NodeItem(item)) => {
1353 ast::ItemFn(_, _, _, _, ref body) => {
1354 // We assume this is a function.
1355 let fn_def_id = ast_util::local_def(id);
1356 let fn_pty = ty::lookup_item_type(cx, fn_def_id);
1358 construct_parameter_environment(cx,
1364 ast::ItemStruct(..) |
1366 ast::ItemStatic(..) => {
1367 let def_id = ast_util::local_def(id);
1368 let pty = ty::lookup_item_type(cx, def_id);
1369 construct_parameter_environment(cx, item.span,
1373 cx.sess.span_bug(item.span,
1374 "ParameterEnvironment::from_item():
1375 can't create a parameter \
1376 environment for this kind of item")
1381 cx.sess.bug(format!("ParameterEnvironment::from_item(): \
1382 `{}` is not an item",
1383 cx.map.node_to_string(id)).as_slice())
1391 /// - `generics`: the set of type parameters and their bounds
1392 /// - `ty`: the base types, which may reference the parameters defined
1394 #[deriving(Clone, Show)]
1395 pub struct Polytype {
1396 pub generics: Generics,
1400 /// As `Polytype` but for a trait ref.
1401 pub struct TraitDef {
1402 /// Generic type definitions. Note that `Self` is listed in here
1403 /// as having a single bound, the trait itself (e.g., in the trait
1404 /// `Eq`, there is a single bound `Self : Eq`). This is so that
1405 /// default methods get to assume that the `Self` parameters
1406 /// implements the trait.
1407 pub generics: Generics,
1409 /// The "supertrait" bounds.
1410 pub bounds: ParamBounds,
1411 pub trait_ref: Rc<ty::TraitRef>,
1414 /// Records the substitutions used to translate the polytype for an
1415 /// item into the monotype of an item reference.
1417 pub struct ItemSubsts {
1421 pub type type_cache = RefCell<DefIdMap<Polytype>>;
1423 pub type node_type_table = RefCell<HashMap<uint,t>>;
1425 /// Records information about each unboxed closure.
1427 pub struct UnboxedClosure {
1428 /// The type of the unboxed closure.
1429 pub closure_type: ClosureTy,
1430 /// The kind of unboxed closure this is.
1431 pub kind: UnboxedClosureKind,
1434 #[deriving(Clone, PartialEq, Eq)]
1435 pub enum UnboxedClosureKind {
1436 FnUnboxedClosureKind,
1437 FnMutUnboxedClosureKind,
1438 FnOnceUnboxedClosureKind,
1441 impl UnboxedClosureKind {
1442 pub fn trait_did(&self, cx: &ctxt) -> ast::DefId {
1443 let result = match *self {
1444 FnUnboxedClosureKind => cx.lang_items.require(FnTraitLangItem),
1445 FnMutUnboxedClosureKind => {
1446 cx.lang_items.require(FnMutTraitLangItem)
1448 FnOnceUnboxedClosureKind => {
1449 cx.lang_items.require(FnOnceTraitLangItem)
1453 Ok(trait_did) => trait_did,
1454 Err(err) => cx.sess.fatal(err.as_slice()),
1459 pub fn mk_ctxt<'tcx>(s: Session,
1460 type_arena: &'tcx TypedArena<t_box_>,
1461 dm: resolve::DefMap,
1462 named_region_map: resolve_lifetime::NamedRegionMap,
1463 map: ast_map::Map<'tcx>,
1464 freevars: RefCell<FreevarMap>,
1465 capture_modes: RefCell<CaptureModeMap>,
1466 region_maps: middle::region::RegionMaps,
1467 lang_items: middle::lang_items::LanguageItems,
1468 stability: stability::Index) -> ctxt<'tcx> {
1470 type_arena: type_arena,
1471 interner: RefCell::new(FnvHashMap::new()),
1472 named_region_map: named_region_map,
1473 item_variance_map: RefCell::new(DefIdMap::new()),
1474 variance_computed: Cell::new(false),
1475 next_id: Cell::new(primitives::LAST_PRIMITIVE_ID),
1478 region_maps: region_maps,
1479 node_types: RefCell::new(HashMap::new()),
1480 item_substs: RefCell::new(NodeMap::new()),
1481 trait_refs: RefCell::new(NodeMap::new()),
1482 trait_defs: RefCell::new(DefIdMap::new()),
1483 object_cast_map: RefCell::new(NodeMap::new()),
1485 intrinsic_defs: RefCell::new(DefIdMap::new()),
1487 tcache: RefCell::new(DefIdMap::new()),
1488 rcache: RefCell::new(HashMap::new()),
1489 short_names_cache: RefCell::new(HashMap::new()),
1490 needs_unwind_cleanup_cache: RefCell::new(HashMap::new()),
1491 tc_cache: RefCell::new(HashMap::new()),
1492 ast_ty_to_ty_cache: RefCell::new(NodeMap::new()),
1493 enum_var_cache: RefCell::new(DefIdMap::new()),
1494 impl_or_trait_items: RefCell::new(DefIdMap::new()),
1495 trait_item_def_ids: RefCell::new(DefIdMap::new()),
1496 trait_items_cache: RefCell::new(DefIdMap::new()),
1497 impl_trait_cache: RefCell::new(DefIdMap::new()),
1498 ty_param_defs: RefCell::new(NodeMap::new()),
1499 adjustments: RefCell::new(NodeMap::new()),
1500 normalized_cache: RefCell::new(HashMap::new()),
1501 lang_items: lang_items,
1502 provided_method_sources: RefCell::new(DefIdMap::new()),
1503 superstructs: RefCell::new(DefIdMap::new()),
1504 struct_fields: RefCell::new(DefIdMap::new()),
1505 destructor_for_type: RefCell::new(DefIdMap::new()),
1506 destructors: RefCell::new(DefIdSet::new()),
1507 trait_impls: RefCell::new(DefIdMap::new()),
1508 inherent_impls: RefCell::new(DefIdMap::new()),
1509 impl_items: RefCell::new(DefIdMap::new()),
1510 used_unsafe: RefCell::new(NodeSet::new()),
1511 used_mut_nodes: RefCell::new(NodeSet::new()),
1512 populated_external_types: RefCell::new(DefIdSet::new()),
1513 populated_external_traits: RefCell::new(DefIdSet::new()),
1514 upvar_borrow_map: RefCell::new(HashMap::new()),
1515 extern_const_statics: RefCell::new(DefIdMap::new()),
1516 extern_const_variants: RefCell::new(DefIdMap::new()),
1517 method_map: RefCell::new(FnvHashMap::new()),
1518 dependency_formats: RefCell::new(HashMap::new()),
1519 unboxed_closures: RefCell::new(DefIdMap::new()),
1520 node_lint_levels: RefCell::new(HashMap::new()),
1521 transmute_restrictions: RefCell::new(Vec::new()),
1522 stability: RefCell::new(stability),
1523 capture_modes: capture_modes,
1524 associated_types: RefCell::new(DefIdMap::new()),
1525 trait_associated_types: RefCell::new(DefIdMap::new()),
1529 // Type constructors
1531 // Interns a type/name combination, stores the resulting box in cx.interner,
1532 // and returns the box as cast to an unsafe ptr (see comments for t above).
1533 pub fn mk_t(cx: &ctxt, st: sty) -> t {
1534 // Check for primitive types.
1536 ty_nil => return mk_nil(),
1537 ty_err => return mk_err(),
1538 ty_bool => return mk_bool(),
1539 ty_int(i) => return mk_mach_int(i),
1540 ty_uint(u) => return mk_mach_uint(u),
1541 ty_float(f) => return mk_mach_float(f),
1542 ty_char => return mk_char(),
1543 ty_bot => return mk_bot(),
1547 let key = intern_key { sty: &st };
1549 match cx.interner.borrow().find(&key) {
1550 Some(t) => unsafe { return mem::transmute(&t.sty); },
1555 fn rflags(r: Region) -> uint {
1556 (has_regions as uint) | {
1558 ty::ReInfer(_) => needs_infer as uint,
1563 fn sflags(substs: &Substs) -> uint {
1565 let mut i = substs.types.iter();
1567 f |= get(*tt).flags;
1569 match substs.regions {
1570 subst::ErasedRegions => {}
1571 subst::NonerasedRegions(ref regions) => {
1572 for r in regions.iter() {
1579 fn flags_for_bounds(bounds: &ExistentialBounds) -> uint {
1580 rflags(bounds.region_bound)
1583 &ty_nil | &ty_bool | &ty_char | &ty_int(_) | &ty_float(_) | &ty_uint(_) |
1585 // You might think that we could just return ty_err for
1586 // any type containing ty_err as a component, and get
1587 // rid of the has_ty_err flag -- likewise for ty_bot (with
1588 // the exception of function types that return bot).
1589 // But doing so caused sporadic memory corruption, and
1590 // neither I (tjc) nor nmatsakis could figure out why,
1591 // so we're doing it this way.
1592 &ty_bot => flags |= has_ty_bot as uint,
1593 &ty_err => flags |= has_ty_err as uint,
1594 &ty_param(ref p) => {
1595 if p.space == subst::SelfSpace {
1596 flags |= has_self as uint;
1598 flags |= has_params as uint;
1601 &ty_unboxed_closure(_, ref region) => flags |= rflags(*region),
1602 &ty_infer(_) => flags |= needs_infer as uint,
1603 &ty_enum(_, ref substs) | &ty_struct(_, ref substs) => {
1604 flags |= sflags(substs);
1606 &ty_trait(box TyTrait { ref substs, ref bounds, .. }) => {
1607 flags |= sflags(substs);
1608 flags |= flags_for_bounds(bounds);
1610 &ty_box(tt) | &ty_uniq(tt) | &ty_vec(tt, _) | &ty_open(tt) => {
1611 flags |= get(tt).flags
1614 flags |= get(m.ty).flags;
1616 &ty_rptr(r, ref m) => {
1618 flags |= get(m.ty).flags;
1620 &ty_tup(ref ts) => for tt in ts.iter() { flags |= get(*tt).flags; },
1621 &ty_bare_fn(ref f) => {
1622 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1623 flags |= get(f.sig.output).flags;
1624 // T -> _|_ is *not* _|_ !
1625 flags &= !(has_ty_bot as uint);
1627 &ty_closure(ref f) => {
1629 RegionTraitStore(r, _) => {
1634 for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1635 flags |= get(f.sig.output).flags;
1636 // T -> _|_ is *not* _|_ !
1637 flags &= !(has_ty_bot as uint);
1638 flags |= flags_for_bounds(&f.bounds);
1642 let t = cx.type_arena.alloc(t_box_ {
1644 id: cx.next_id.get(),
1648 let sty_ptr = &t.sty as *const sty;
1650 let key = intern_key {
1654 cx.interner.borrow_mut().insert(key, t);
1656 cx.next_id.set(cx.next_id.get() + 1);
1659 mem::transmute::<*const sty, t>(sty_ptr)
1664 pub fn mk_prim_t(primitive: &'static t_box_) -> t {
1666 mem::transmute::<&'static t_box_, t>(primitive)
1671 pub fn mk_nil() -> t { mk_prim_t(&primitives::TY_NIL) }
1674 pub fn mk_err() -> t { mk_prim_t(&primitives::TY_ERR) }
1677 pub fn mk_bot() -> t { mk_prim_t(&primitives::TY_BOT) }
1680 pub fn mk_bool() -> t { mk_prim_t(&primitives::TY_BOOL) }
1683 pub fn mk_int() -> t { mk_prim_t(&primitives::TY_INT) }
1686 pub fn mk_i8() -> t { mk_prim_t(&primitives::TY_I8) }
1689 pub fn mk_i16() -> t { mk_prim_t(&primitives::TY_I16) }
1692 pub fn mk_i32() -> t { mk_prim_t(&primitives::TY_I32) }
1695 pub fn mk_i64() -> t { mk_prim_t(&primitives::TY_I64) }
1698 pub fn mk_f32() -> t { mk_prim_t(&primitives::TY_F32) }
1701 pub fn mk_f64() -> t { mk_prim_t(&primitives::TY_F64) }
1704 pub fn mk_uint() -> t { mk_prim_t(&primitives::TY_UINT) }
1707 pub fn mk_u8() -> t { mk_prim_t(&primitives::TY_U8) }
1710 pub fn mk_u16() -> t { mk_prim_t(&primitives::TY_U16) }
1713 pub fn mk_u32() -> t { mk_prim_t(&primitives::TY_U32) }
1716 pub fn mk_u64() -> t { mk_prim_t(&primitives::TY_U64) }
1718 pub fn mk_mach_int(tm: ast::IntTy) -> t {
1720 ast::TyI => mk_int(),
1721 ast::TyI8 => mk_i8(),
1722 ast::TyI16 => mk_i16(),
1723 ast::TyI32 => mk_i32(),
1724 ast::TyI64 => mk_i64(),
1728 pub fn mk_mach_uint(tm: ast::UintTy) -> t {
1730 ast::TyU => mk_uint(),
1731 ast::TyU8 => mk_u8(),
1732 ast::TyU16 => mk_u16(),
1733 ast::TyU32 => mk_u32(),
1734 ast::TyU64 => mk_u64(),
1738 pub fn mk_mach_float(tm: ast::FloatTy) -> t {
1740 ast::TyF32 => mk_f32(),
1741 ast::TyF64 => mk_f64(),
1746 pub fn mk_char() -> t { mk_prim_t(&primitives::TY_CHAR) }
1748 pub fn mk_str(cx: &ctxt) -> t {
1752 pub fn mk_str_slice(cx: &ctxt, r: Region, m: ast::Mutability) -> t {
1755 ty: mk_t(cx, ty_str),
1760 pub fn mk_enum(cx: &ctxt, did: ast::DefId, substs: Substs) -> t {
1761 // take a copy of substs so that we own the vectors inside
1762 mk_t(cx, ty_enum(did, substs))
1765 pub fn mk_box(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_box(ty)) }
1767 pub fn mk_uniq(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_uniq(ty)) }
1769 pub fn mk_ptr(cx: &ctxt, tm: mt) -> t { mk_t(cx, ty_ptr(tm)) }
1771 pub fn mk_rptr(cx: &ctxt, r: Region, tm: mt) -> t { mk_t(cx, ty_rptr(r, tm)) }
1773 pub fn mk_mut_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1774 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
1776 pub fn mk_imm_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1777 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
1780 pub fn mk_mut_ptr(cx: &ctxt, ty: t) -> t {
1781 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
1784 pub fn mk_imm_ptr(cx: &ctxt, ty: t) -> t {
1785 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
1788 pub fn mk_nil_ptr(cx: &ctxt) -> t {
1789 mk_ptr(cx, mt {ty: mk_nil(), mutbl: ast::MutImmutable})
1792 pub fn mk_vec(cx: &ctxt, t: t, sz: Option<uint>) -> t {
1793 mk_t(cx, ty_vec(t, sz))
1796 pub fn mk_slice(cx: &ctxt, r: Region, tm: mt) -> t {
1799 ty: mk_vec(cx, tm.ty, None),
1804 pub fn mk_tup(cx: &ctxt, ts: Vec<t>) -> t { mk_t(cx, ty_tup(ts)) }
1806 pub fn mk_closure(cx: &ctxt, fty: ClosureTy) -> t {
1807 mk_t(cx, ty_closure(box fty))
1810 pub fn mk_bare_fn(cx: &ctxt, fty: BareFnTy) -> t {
1811 mk_t(cx, ty_bare_fn(fty))
1814 pub fn mk_ctor_fn(cx: &ctxt,
1815 binder_id: ast::NodeId,
1816 input_tys: &[ty::t],
1817 output: ty::t) -> t {
1818 let input_args = input_tys.iter().map(|t| *t).collect();
1821 fn_style: ast::NormalFn,
1824 binder_id: binder_id,
1833 pub fn mk_trait(cx: &ctxt,
1836 bounds: ExistentialBounds)
1838 // take a copy of substs so that we own the vectors inside
1839 let inner = box TyTrait {
1844 mk_t(cx, ty_trait(inner))
1847 pub fn mk_struct(cx: &ctxt, struct_id: ast::DefId, substs: Substs) -> t {
1848 // take a copy of substs so that we own the vectors inside
1849 mk_t(cx, ty_struct(struct_id, substs))
1852 pub fn mk_unboxed_closure(cx: &ctxt, closure_id: ast::DefId, region: Region)
1854 mk_t(cx, ty_unboxed_closure(closure_id, region))
1857 pub fn mk_var(cx: &ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) }
1859 pub fn mk_int_var(cx: &ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) }
1861 pub fn mk_float_var(cx: &ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) }
1863 pub fn mk_infer(cx: &ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) }
1865 pub fn mk_param(cx: &ctxt, space: subst::ParamSpace, n: uint, k: DefId) -> t {
1866 mk_t(cx, ty_param(ParamTy { space: space, idx: n, def_id: k }))
1869 pub fn mk_self_type(cx: &ctxt, did: ast::DefId) -> t {
1870 mk_param(cx, subst::SelfSpace, 0, did)
1873 pub fn mk_param_from_def(cx: &ctxt, def: &TypeParameterDef) -> t {
1874 mk_param(cx, def.space, def.index, def.def_id)
1877 pub fn mk_open(cx: &ctxt, t: t) -> t { mk_t(cx, ty_open(t)) }
1879 pub fn walk_ty(ty: t, f: |t|) {
1880 maybe_walk_ty(ty, |t| { f(t); true });
1883 pub fn maybe_walk_ty(ty: t, f: |t| -> bool) {
1888 ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) |
1889 ty_str | ty_infer(_) | ty_param(_) | ty_unboxed_closure(_, _) | ty_err => {}
1890 ty_box(ty) | ty_uniq(ty) | ty_vec(ty, _) | ty_open(ty) => maybe_walk_ty(ty, f),
1891 ty_ptr(ref tm) | ty_rptr(_, ref tm) => {
1892 maybe_walk_ty(tm.ty, f);
1894 ty_enum(_, ref substs) | ty_struct(_, ref substs) |
1895 ty_trait(box TyTrait { ref substs, .. }) => {
1896 for subty in (*substs).types.iter() {
1897 maybe_walk_ty(*subty, |x| f(x));
1900 ty_tup(ref ts) => { for tt in ts.iter() { maybe_walk_ty(*tt, |x| f(x)); } }
1901 ty_bare_fn(ref ft) => {
1902 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1903 maybe_walk_ty(ft.sig.output, f);
1905 ty_closure(ref ft) => {
1906 for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1907 maybe_walk_ty(ft.sig.output, f);
1912 // Folds types from the bottom up.
1913 pub fn fold_ty(cx: &ctxt, t0: t, fldop: |t| -> t) -> t {
1914 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
1918 pub fn walk_regions_and_ty(cx: &ctxt, ty: t, fldr: |r: Region|, fldt: |t: t|)
1920 ty_fold::RegionFolder::general(cx,
1922 |t| { fldt(t); t }).fold_ty(ty)
1926 pub fn new(space: subst::ParamSpace,
1930 ParamTy { space: space, idx: index, def_id: def_id }
1933 pub fn for_self(trait_def_id: ast::DefId) -> ParamTy {
1934 ParamTy::new(subst::SelfSpace, 0, trait_def_id)
1937 pub fn for_def(def: &TypeParameterDef) -> ParamTy {
1938 ParamTy::new(def.space, def.index, def.def_id)
1941 pub fn to_ty(self, tcx: &ty::ctxt) -> ty::t {
1942 ty::mk_param(tcx, self.space, self.idx, self.def_id)
1945 pub fn is_self(&self) -> bool {
1946 self.space == subst::SelfSpace && self.idx == 0
1951 pub fn empty() -> ItemSubsts {
1952 ItemSubsts { substs: Substs::empty() }
1955 pub fn is_noop(&self) -> bool {
1956 self.substs.is_noop()
1962 pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil }
1964 pub fn type_is_bot(ty: t) -> bool {
1965 (get(ty).flags & (has_ty_bot as uint)) != 0
1968 pub fn type_is_error(ty: t) -> bool {
1969 (get(ty).flags & (has_ty_err as uint)) != 0
1972 pub fn type_needs_subst(ty: t) -> bool {
1973 tbox_has_flag(get(ty), needs_subst)
1976 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
1977 tref.substs.types.any(|&t| type_is_error(t))
1980 pub fn type_is_ty_var(ty: t) -> bool {
1982 ty_infer(TyVar(_)) => true,
1987 pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool }
1989 pub fn type_is_self(ty: t) -> bool {
1991 ty_param(ref p) => p.space == subst::SelfSpace,
1996 fn type_is_slice(ty: t) -> bool {
1998 ty_ptr(mt) | ty_rptr(_, mt) => match get(mt.ty).sty {
1999 ty_vec(_, None) | ty_str => true,
2006 pub fn type_is_vec(ty: t) -> bool {
2009 ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) |
2010 ty_box(t) | ty_uniq(t) => match get(t).sty {
2011 ty_vec(_, None) => true,
2018 pub fn type_is_structural(ty: t) -> bool {
2020 ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) |
2021 ty_vec(_, Some(_)) | ty_unboxed_closure(..) => true,
2022 _ => type_is_slice(ty) | type_is_trait(ty)
2026 pub fn type_is_simd(cx: &ctxt, ty: t) -> bool {
2028 ty_struct(did, _) => lookup_simd(cx, did),
2033 pub fn sequence_element_type(cx: &ctxt, ty: t) -> t {
2035 ty_vec(ty, _) => ty,
2036 ty_str => mk_mach_uint(ast::TyU8),
2037 ty_open(ty) => sequence_element_type(cx, ty),
2038 _ => cx.sess.bug(format!("sequence_element_type called on non-sequence value: {}",
2039 ty_to_string(cx, ty)).as_slice()),
2043 pub fn simd_type(cx: &ctxt, ty: t) -> t {
2045 ty_struct(did, ref substs) => {
2046 let fields = lookup_struct_fields(cx, did);
2047 lookup_field_type(cx, did, fields.get(0).id, substs)
2049 _ => fail!("simd_type called on invalid type")
2053 pub fn simd_size(cx: &ctxt, ty: t) -> uint {
2055 ty_struct(did, _) => {
2056 let fields = lookup_struct_fields(cx, did);
2059 _ => fail!("simd_size called on invalid type")
2063 pub fn type_is_boxed(ty: t) -> bool {
2070 pub fn type_is_region_ptr(ty: t) -> bool {
2072 ty_rptr(..) => true,
2077 pub fn type_is_unsafe_ptr(ty: t) -> bool {
2079 ty_ptr(_) => return true,
2084 pub fn type_is_unique(ty: t) -> bool {
2086 ty_uniq(_) => match get(ty).sty {
2087 ty_trait(..) => false,
2094 pub fn type_is_fat_ptr(cx: &ctxt, ty: t) -> bool {
2096 ty_ptr(mt{ty, ..}) | ty_rptr(_, mt{ty, ..})
2097 | ty_uniq(ty) if !type_is_sized(cx, ty) => true,
2103 A scalar type is one that denotes an atomic datum, with no sub-components.
2104 (A ty_ptr is scalar because it represents a non-managed pointer, so its
2105 contents are abstract to rustc.)
2107 pub fn type_is_scalar(ty: t) -> bool {
2109 ty_nil | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
2110 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
2111 ty_bare_fn(..) | ty_ptr(_) => true,
2116 /// Returns true if this type is a floating point type and false otherwise.
2117 pub fn type_is_floating_point(ty: t) -> bool {
2119 ty_float(_) => true,
2124 pub fn type_needs_drop(cx: &ctxt, ty: t) -> bool {
2125 type_contents(cx, ty).needs_drop(cx)
2128 // Some things don't need cleanups during unwinding because the
2129 // task can free them all at once later. Currently only things
2130 // that only contain scalars and shared boxes can avoid unwind
2132 pub fn type_needs_unwind_cleanup(cx: &ctxt, ty: t) -> bool {
2133 match cx.needs_unwind_cleanup_cache.borrow().find(&ty) {
2134 Some(&result) => return result,
2138 let mut tycache = HashSet::new();
2139 let needs_unwind_cleanup =
2140 type_needs_unwind_cleanup_(cx, ty, &mut tycache, false);
2141 cx.needs_unwind_cleanup_cache.borrow_mut().insert(ty, needs_unwind_cleanup);
2142 return needs_unwind_cleanup;
2145 fn type_needs_unwind_cleanup_(cx: &ctxt, ty: t,
2146 tycache: &mut HashSet<t>,
2147 encountered_box: bool) -> bool {
2149 // Prevent infinite recursion
2150 if !tycache.insert(ty) {
2154 let mut encountered_box = encountered_box;
2155 let mut needs_unwind_cleanup = false;
2156 maybe_walk_ty(ty, |ty| {
2157 let old_encountered_box = encountered_box;
2158 let result = match get(ty).sty {
2160 encountered_box = true;
2163 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2164 ty_tup(_) | ty_ptr(_) => {
2167 ty_enum(did, ref substs) => {
2168 for v in (*enum_variants(cx, did)).iter() {
2169 for aty in v.args.iter() {
2170 let t = aty.subst(cx, substs);
2171 needs_unwind_cleanup |=
2172 type_needs_unwind_cleanup_(cx, t, tycache,
2176 !needs_unwind_cleanup
2179 // Once we're inside a box, the annihilator will find
2180 // it and destroy it.
2181 if !encountered_box {
2182 needs_unwind_cleanup = true;
2189 needs_unwind_cleanup = true;
2194 encountered_box = old_encountered_box;
2198 return needs_unwind_cleanup;
2202 * Type contents is how the type checker reasons about kinds.
2203 * They track what kinds of things are found within a type. You can
2204 * think of them as kind of an "anti-kind". They track the kinds of values
2205 * and thinks that are contained in types. Having a larger contents for
2206 * a type tends to rule that type *out* from various kinds. For example,
2207 * a type that contains a reference is not sendable.
2209 * The reason we compute type contents and not kinds is that it is
2210 * easier for me (nmatsakis) to think about what is contained within
2211 * a type than to think about what is *not* contained within a type.
2213 pub struct TypeContents {
2217 macro_rules! def_type_content_sets(
2218 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
2219 #[allow(non_snake_case)]
2221 use middle::ty::TypeContents;
2222 $(pub static $name: TypeContents = TypeContents { bits: $bits };)+
2227 def_type_content_sets!(
2229 None = 0b0000_0000__0000_0000__0000,
2231 // Things that are interior to the value (first nibble):
2232 InteriorUnsized = 0b0000_0000__0000_0000__0001,
2233 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
2234 // InteriorAll = 0b00000000__00000000__1111,
2236 // Things that are owned by the value (second and third nibbles):
2237 OwnsOwned = 0b0000_0000__0000_0001__0000,
2238 OwnsDtor = 0b0000_0000__0000_0010__0000,
2239 OwnsManaged /* see [1] below */ = 0b0000_0000__0000_0100__0000,
2240 OwnsAffine = 0b0000_0000__0000_1000__0000,
2241 OwnsAll = 0b0000_0000__1111_1111__0000,
2243 // Things that are reachable by the value in any way (fourth nibble):
2244 ReachesNonsendAnnot = 0b0000_0001__0000_0000__0000,
2245 ReachesBorrowed = 0b0000_0010__0000_0000__0000,
2246 // ReachesManaged /* see [1] below */ = 0b0000_0100__0000_0000__0000,
2247 ReachesMutable = 0b0000_1000__0000_0000__0000,
2248 ReachesNoSync = 0b0001_0000__0000_0000__0000,
2249 ReachesFfiUnsafe = 0b0010_0000__0000_0000__0000,
2250 ReachesAll = 0b0011_1111__0000_0000__0000,
2252 // Things that cause values to *move* rather than *copy*
2253 Moves = 0b0000_0000__0000_1011__0000,
2255 // Things that mean drop glue is necessary
2256 NeedsDrop = 0b0000_0000__0000_0111__0000,
2258 // Things that prevent values from being sent
2260 // Note: For checking whether something is sendable, it'd
2261 // be sufficient to have ReachesManaged. However, we include
2262 // both ReachesManaged and OwnsManaged so that when
2263 // a parameter has a bound T:Send, we are able to deduce
2264 // that it neither reaches nor owns a managed pointer.
2265 Nonsendable = 0b0000_0111__0000_0100__0000,
2267 // Things that prevent values from being considered sized
2268 Nonsized = 0b0000_0000__0000_0000__0001,
2270 // Things that prevent values from being sync
2271 Nonsync = 0b0001_0000__0000_0000__0000,
2273 // Things that make values considered not POD (would be same
2274 // as `Moves`, but for the fact that managed data `@` is
2275 // not considered POD)
2276 Noncopy = 0b0000_0000__0000_1111__0000,
2278 // Bits to set when a managed value is encountered
2280 // [1] Do not set the bits TC::OwnsManaged or
2281 // TC::ReachesManaged directly, instead reference
2282 // TC::Managed to set them both at once.
2283 Managed = 0b0000_0100__0000_0100__0000,
2286 All = 0b1111_1111__1111_1111__1111
2291 pub fn meets_builtin_bound(&self, cx: &ctxt, bb: BuiltinBound) -> bool {
2293 BoundSend => self.is_sendable(cx),
2294 BoundSized => self.is_sized(cx),
2295 BoundCopy => self.is_copy(cx),
2296 BoundSync => self.is_sync(cx),
2300 pub fn when(&self, cond: bool) -> TypeContents {
2301 if cond {*self} else {TC::None}
2304 pub fn intersects(&self, tc: TypeContents) -> bool {
2305 (self.bits & tc.bits) != 0
2308 pub fn is_sendable(&self, _: &ctxt) -> bool {
2309 !self.intersects(TC::Nonsendable)
2312 pub fn is_sync(&self, _: &ctxt) -> bool {
2313 !self.intersects(TC::Nonsync)
2316 pub fn owns_managed(&self) -> bool {
2317 self.intersects(TC::OwnsManaged)
2320 pub fn owns_owned(&self) -> bool {
2321 self.intersects(TC::OwnsOwned)
2324 pub fn is_sized(&self, _: &ctxt) -> bool {
2325 !self.intersects(TC::Nonsized)
2328 pub fn is_copy(&self, _: &ctxt) -> bool {
2329 !self.intersects(TC::Noncopy)
2332 pub fn interior_unsafe(&self) -> bool {
2333 self.intersects(TC::InteriorUnsafe)
2336 pub fn interior_unsized(&self) -> bool {
2337 self.intersects(TC::InteriorUnsized)
2340 pub fn moves_by_default(&self, _: &ctxt) -> bool {
2341 self.intersects(TC::Moves)
2344 pub fn needs_drop(&self, _: &ctxt) -> bool {
2345 self.intersects(TC::NeedsDrop)
2348 pub fn owned_pointer(&self) -> TypeContents {
2350 * Includes only those bits that still apply
2351 * when indirected through a `Box` pointer
2354 *self & (TC::OwnsAll | TC::ReachesAll))
2357 pub fn reference(&self, bits: TypeContents) -> TypeContents {
2359 * Includes only those bits that still apply
2360 * when indirected through a reference (`&`)
2363 *self & TC::ReachesAll)
2366 pub fn managed_pointer(&self) -> TypeContents {
2368 * Includes only those bits that still apply
2369 * when indirected through a managed pointer (`@`)
2372 *self & TC::ReachesAll)
2375 pub fn unsafe_pointer(&self) -> TypeContents {
2377 * Includes only those bits that still apply
2378 * when indirected through an unsafe pointer (`*`)
2380 *self & TC::ReachesAll
2383 pub fn union<T>(v: &[T], f: |&T| -> TypeContents) -> TypeContents {
2384 v.iter().fold(TC::None, |tc, t| tc | f(t))
2387 pub fn has_dtor(&self) -> bool {
2388 self.intersects(TC::OwnsDtor)
2392 impl ops::BitOr<TypeContents,TypeContents> for TypeContents {
2393 fn bitor(&self, other: &TypeContents) -> TypeContents {
2394 TypeContents {bits: self.bits | other.bits}
2398 impl ops::BitAnd<TypeContents,TypeContents> for TypeContents {
2399 fn bitand(&self, other: &TypeContents) -> TypeContents {
2400 TypeContents {bits: self.bits & other.bits}
2404 impl ops::Sub<TypeContents,TypeContents> for TypeContents {
2405 fn sub(&self, other: &TypeContents) -> TypeContents {
2406 TypeContents {bits: self.bits & !other.bits}
2410 impl fmt::Show for TypeContents {
2411 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2412 write!(f, "TypeContents({:t})", self.bits)
2416 pub fn type_is_sendable(cx: &ctxt, t: ty::t) -> bool {
2417 type_contents(cx, t).is_sendable(cx)
2420 pub fn type_interior_is_unsafe(cx: &ctxt, t: ty::t) -> bool {
2421 type_contents(cx, t).interior_unsafe()
2424 pub fn type_contents(cx: &ctxt, ty: t) -> TypeContents {
2425 let ty_id = type_id(ty);
2427 match cx.tc_cache.borrow().find(&ty_id) {
2428 Some(tc) => { return *tc; }
2432 let mut cache = HashMap::new();
2433 let result = tc_ty(cx, ty, &mut cache);
2435 cx.tc_cache.borrow_mut().insert(ty_id, result);
2440 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2442 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
2443 // private cache for this walk. This is needed in the case of cyclic
2446 // struct List { next: Box<Option<List>>, ... }
2448 // When computing the type contents of such a type, we wind up deeply
2449 // recursing as we go. So when we encounter the recursive reference
2450 // to List, we temporarily use TC::None as its contents. Later we'll
2451 // patch up the cache with the correct value, once we've computed it
2452 // (this is basically a co-inductive process, if that helps). So in
2453 // the end we'll compute TC::OwnsOwned, in this case.
2455 // The problem is, as we are doing the computation, we will also
2456 // compute an *intermediate* contents for, e.g., Option<List> of
2457 // TC::None. This is ok during the computation of List itself, but if
2458 // we stored this intermediate value into cx.tc_cache, then later
2459 // requests for the contents of Option<List> would also yield TC::None
2460 // which is incorrect. This value was computed based on the crutch
2461 // value for the type contents of list. The correct value is
2462 // TC::OwnsOwned. This manifested as issue #4821.
2463 let ty_id = type_id(ty);
2464 match cache.find(&ty_id) {
2465 Some(tc) => { return *tc; }
2468 match cx.tc_cache.borrow().find(&ty_id) { // Must check both caches!
2469 Some(tc) => { return *tc; }
2472 cache.insert(ty_id, TC::None);
2474 let result = match get(ty).sty {
2475 // uint and int are ffi-unsafe
2476 ty_uint(ast::TyU) | ty_int(ast::TyI) => {
2477 TC::ReachesFfiUnsafe
2480 // Scalar and unique types are sendable, and durable
2481 ty_infer(ty::SkolemizedIntTy(_)) |
2482 ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2483 ty_bare_fn(_) | ty::ty_char => {
2487 ty_closure(ref c) => {
2488 closure_contents(cx, &**c) | TC::ReachesFfiUnsafe
2492 tc_ty(cx, typ, cache).managed_pointer() | TC::ReachesFfiUnsafe
2496 TC::ReachesFfiUnsafe | match get(typ).sty {
2497 ty_str => TC::OwnsOwned,
2498 _ => tc_ty(cx, typ, cache).owned_pointer(),
2502 ty_trait(box TyTrait { bounds, .. }) => {
2503 object_contents(cx, bounds) | TC::ReachesFfiUnsafe | TC::Nonsized
2507 tc_ty(cx, mt.ty, cache).unsafe_pointer()
2510 ty_rptr(r, ref mt) => {
2511 TC::ReachesFfiUnsafe | match get(mt.ty).sty {
2512 ty_str => borrowed_contents(r, ast::MutImmutable),
2513 ty_vec(..) => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(r, mt.mutbl)),
2514 _ => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(r, mt.mutbl)),
2518 ty_vec(t, Some(_)) => {
2522 ty_vec(t, None) => {
2523 tc_ty(cx, t, cache) | TC::Nonsized
2525 ty_str => TC::Nonsized,
2527 ty_struct(did, ref substs) => {
2528 let flds = struct_fields(cx, did, substs);
2530 TypeContents::union(flds.as_slice(),
2531 |f| tc_mt(cx, f.mt, cache));
2533 if !lookup_repr_hints(cx, did).contains(&attr::ReprExtern) {
2534 res = res | TC::ReachesFfiUnsafe;
2537 if ty::has_dtor(cx, did) {
2538 res = res | TC::OwnsDtor;
2540 apply_lang_items(cx, did, res)
2543 ty_unboxed_closure(did, r) => {
2544 // FIXME(#14449): `borrowed_contents` below assumes `&mut`
2546 let upvars = unboxed_closure_upvars(cx, did);
2547 TypeContents::union(upvars.as_slice(),
2548 |f| tc_ty(cx, f.ty, cache)) |
2549 borrowed_contents(r, MutMutable)
2552 ty_tup(ref tys) => {
2553 TypeContents::union(tys.as_slice(),
2554 |ty| tc_ty(cx, *ty, cache))
2557 ty_enum(did, ref substs) => {
2558 let variants = substd_enum_variants(cx, did, substs);
2560 TypeContents::union(variants.as_slice(), |variant| {
2561 TypeContents::union(variant.args.as_slice(),
2563 tc_ty(cx, *arg_ty, cache)
2567 if ty::has_dtor(cx, did) {
2568 res = res | TC::OwnsDtor;
2571 if variants.len() != 0 {
2572 let repr_hints = lookup_repr_hints(cx, did);
2573 if repr_hints.len() > 1 {
2574 // this is an error later on, but this type isn't safe
2575 res = res | TC::ReachesFfiUnsafe;
2578 match repr_hints.as_slice().get(0) {
2579 Some(h) => if !h.is_ffi_safe() {
2580 res = res | TC::ReachesFfiUnsafe;
2584 res = res | TC::ReachesFfiUnsafe;
2586 // We allow ReprAny enums if they are eligible for
2587 // the nullable pointer optimization and the
2588 // contained type is an `extern fn`
2590 if variants.len() == 2 {
2591 let mut data_idx = 0;
2593 if variants.get(0).args.len() == 0 {
2597 if variants.get(data_idx).args.len() == 1 {
2598 match get(*variants.get(data_idx).args.get(0)).sty {
2599 ty_bare_fn(..) => { res = res - TC::ReachesFfiUnsafe; }
2609 apply_lang_items(cx, did, res)
2613 // We only ever ask for the kind of types that are defined in
2614 // the current crate; therefore, the only type parameters that
2615 // could be in scope are those defined in the current crate.
2616 // If this assertion failures, it is likely because of a
2617 // failure in the cross-crate inlining code to translate a
2619 assert_eq!(p.def_id.krate, ast::LOCAL_CRATE);
2621 let ty_param_defs = cx.ty_param_defs.borrow();
2622 let tp_def = ty_param_defs.get(&p.def_id.node);
2623 kind_bounds_to_contents(
2625 tp_def.bounds.builtin_bounds,
2626 tp_def.bounds.trait_bounds.as_slice())
2630 // This occurs during coherence, but shouldn't occur at other
2636 let result = tc_ty(cx, t, cache);
2637 assert!(!result.is_sized(cx))
2638 result.unsafe_pointer() | TC::Nonsized
2642 cx.sess.bug("asked to compute contents of error type");
2646 cache.insert(ty_id, result);
2652 cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2654 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
2655 mc | tc_ty(cx, mt.ty, cache)
2658 fn apply_lang_items(cx: &ctxt,
2662 if Some(did) == cx.lang_items.no_send_bound() {
2663 tc | TC::ReachesNonsendAnnot
2664 } else if Some(did) == cx.lang_items.managed_bound() {
2666 } else if Some(did) == cx.lang_items.no_copy_bound() {
2668 } else if Some(did) == cx.lang_items.no_sync_bound() {
2669 tc | TC::ReachesNoSync
2670 } else if Some(did) == cx.lang_items.unsafe_type() {
2671 // FIXME(#13231): This shouldn't be needed after
2672 // opt-in built-in bounds are implemented.
2673 (tc | TC::InteriorUnsafe) - TC::Nonsync
2679 fn borrowed_contents(region: ty::Region,
2680 mutbl: ast::Mutability)
2683 * Type contents due to containing a reference
2684 * with the region `region` and borrow kind `bk`
2687 let b = match mutbl {
2688 ast::MutMutable => TC::ReachesMutable | TC::OwnsAffine,
2689 ast::MutImmutable => TC::None,
2691 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
2694 fn closure_contents(cx: &ctxt, cty: &ClosureTy) -> TypeContents {
2695 // Closure contents are just like trait contents, but with potentially
2697 let st = object_contents(cx, cty.bounds);
2699 let st = match cty.store {
2703 RegionTraitStore(r, mutbl) => {
2704 st.reference(borrowed_contents(r, mutbl))
2708 // This also prohibits "@once fn" from being copied, which allows it to
2709 // be called. Neither way really makes much sense.
2710 let ot = match cty.onceness {
2711 ast::Once => TC::OwnsAffine,
2712 ast::Many => TC::None,
2718 fn object_contents(cx: &ctxt,
2719 bounds: ExistentialBounds)
2721 // These are the type contents of the (opaque) interior
2722 kind_bounds_to_contents(cx, bounds.builtin_bounds, [])
2725 fn kind_bounds_to_contents(cx: &ctxt,
2726 bounds: BuiltinBounds,
2727 traits: &[Rc<TraitRef>])
2729 let _i = indenter();
2730 let mut tc = TC::All;
2731 each_inherited_builtin_bound(cx, bounds, traits, |bound| {
2732 tc = tc - match bound {
2733 BoundSend => TC::Nonsendable,
2734 BoundSized => TC::Nonsized,
2735 BoundCopy => TC::Noncopy,
2736 BoundSync => TC::Nonsync,
2741 // Iterates over all builtin bounds on the type parameter def, including
2742 // those inherited from traits with builtin-kind-supertraits.
2743 fn each_inherited_builtin_bound(cx: &ctxt,
2744 bounds: BuiltinBounds,
2745 traits: &[Rc<TraitRef>],
2746 f: |BuiltinBound|) {
2747 for bound in bounds.iter() {
2751 each_bound_trait_and_supertraits(cx, traits, |trait_ref| {
2752 let trait_def = lookup_trait_def(cx, trait_ref.def_id);
2753 for bound in trait_def.bounds.builtin_bounds.iter() {
2762 pub fn type_moves_by_default(cx: &ctxt, ty: t) -> bool {
2763 type_contents(cx, ty).moves_by_default(cx)
2766 pub fn is_ffi_safe(cx: &ctxt, ty: t) -> bool {
2767 !type_contents(cx, ty).intersects(TC::ReachesFfiUnsafe)
2770 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
2771 pub fn is_instantiable(cx: &ctxt, r_ty: t) -> bool {
2772 fn type_requires(cx: &ctxt, seen: &mut Vec<DefId>,
2773 r_ty: t, ty: t) -> bool {
2774 debug!("type_requires({}, {})?",
2775 ::util::ppaux::ty_to_string(cx, r_ty),
2776 ::util::ppaux::ty_to_string(cx, ty));
2779 get(r_ty).sty == get(ty).sty ||
2780 subtypes_require(cx, seen, r_ty, ty)
2783 debug!("type_requires({}, {})? {}",
2784 ::util::ppaux::ty_to_string(cx, r_ty),
2785 ::util::ppaux::ty_to_string(cx, ty),
2790 fn subtypes_require(cx: &ctxt, seen: &mut Vec<DefId>,
2791 r_ty: t, ty: t) -> bool {
2792 debug!("subtypes_require({}, {})?",
2793 ::util::ppaux::ty_to_string(cx, r_ty),
2794 ::util::ppaux::ty_to_string(cx, ty));
2796 let r = match get(ty).sty {
2797 // fixed length vectors need special treatment compared to
2798 // normal vectors, since they don't necessarily have the
2799 // possibility to have length zero.
2800 ty_vec(_, Some(0)) => false, // don't need no contents
2801 ty_vec(ty, Some(_)) => type_requires(cx, seen, r_ty, ty),
2816 ty_vec(_, None) => {
2819 ty_box(typ) | ty_uniq(typ) | ty_open(typ) => {
2820 type_requires(cx, seen, r_ty, typ)
2822 ty_rptr(_, ref mt) => {
2823 type_requires(cx, seen, r_ty, mt.ty)
2827 false // unsafe ptrs can always be NULL
2834 ty_struct(ref did, _) if seen.contains(did) => {
2838 ty_struct(did, ref substs) => {
2840 let fields = struct_fields(cx, did, substs);
2841 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
2842 seen.pop().unwrap();
2846 ty_unboxed_closure(did, _) => {
2847 let upvars = unboxed_closure_upvars(cx, did);
2848 upvars.iter().any(|f| type_requires(cx, seen, r_ty, f.ty))
2852 ts.iter().any(|t| type_requires(cx, seen, r_ty, *t))
2855 ty_enum(ref did, _) if seen.contains(did) => {
2859 ty_enum(did, ref substs) => {
2861 let vs = enum_variants(cx, did);
2862 let r = !vs.is_empty() && vs.iter().all(|variant| {
2863 variant.args.iter().any(|aty| {
2864 let sty = aty.subst(cx, substs);
2865 type_requires(cx, seen, r_ty, sty)
2868 seen.pop().unwrap();
2873 debug!("subtypes_require({}, {})? {}",
2874 ::util::ppaux::ty_to_string(cx, r_ty),
2875 ::util::ppaux::ty_to_string(cx, ty),
2881 let mut seen = Vec::new();
2882 !subtypes_require(cx, &mut seen, r_ty, r_ty)
2885 /// Describes whether a type is representable. For types that are not
2886 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
2887 /// distinguish between types that are recursive with themselves and types that
2888 /// contain a different recursive type. These cases can therefore be treated
2889 /// differently when reporting errors.
2890 #[deriving(PartialEq)]
2891 pub enum Representability {
2897 /// Check whether a type is representable. This means it cannot contain unboxed
2898 /// structural recursion. This check is needed for structs and enums.
2899 pub fn is_type_representable(cx: &ctxt, sp: Span, ty: t) -> Representability {
2901 // Iterate until something non-representable is found
2902 fn find_nonrepresentable<It: Iterator<t>>(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2903 mut iter: It) -> Representability {
2905 let r = type_structurally_recursive(cx, sp, seen, ty);
2906 if r != Representable {
2913 // Does the type `ty` directly (without indirection through a pointer)
2914 // contain any types on stack `seen`?
2915 fn type_structurally_recursive(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2916 ty: t) -> Representability {
2917 debug!("type_structurally_recursive: {}",
2918 ::util::ppaux::ty_to_string(cx, ty));
2920 // Compare current type to previously seen types
2923 ty_enum(did, _) => {
2924 for (i, &seen_did) in seen.iter().enumerate() {
2925 if did == seen_did {
2926 return if i == 0 { SelfRecursive }
2927 else { ContainsRecursive }
2934 // Check inner types
2938 find_nonrepresentable(cx, sp, seen, ts.iter().map(|t| *t))
2940 // Fixed-length vectors.
2941 // FIXME(#11924) Behavior undecided for zero-length vectors.
2942 ty_vec(ty, Some(_)) => {
2943 type_structurally_recursive(cx, sp, seen, ty)
2946 // Push struct and enum def-ids onto `seen` before recursing.
2947 ty_struct(did, ref substs) => {
2949 let fields = struct_fields(cx, did, substs);
2950 let r = find_nonrepresentable(cx, sp, seen,
2951 fields.iter().map(|f| f.mt.ty));
2956 ty_enum(did, ref substs) => {
2958 let vs = enum_variants(cx, did);
2960 let mut r = Representable;
2961 for variant in vs.iter() {
2962 let iter = variant.args.iter().map(|aty| {
2963 aty.subst_spanned(cx, substs, Some(sp))
2965 r = find_nonrepresentable(cx, sp, seen, iter);
2967 if r != Representable { break }
2974 ty_unboxed_closure(did, _) => {
2975 let upvars = unboxed_closure_upvars(cx, did);
2976 find_nonrepresentable(cx,
2979 upvars.iter().map(|f| f.ty))
2986 debug!("is_type_representable: {}",
2987 ::util::ppaux::ty_to_string(cx, ty));
2989 // To avoid a stack overflow when checking an enum variant or struct that
2990 // contains a different, structurally recursive type, maintain a stack
2991 // of seen types and check recursion for each of them (issues #3008, #3779).
2992 let mut seen: Vec<DefId> = Vec::new();
2993 type_structurally_recursive(cx, sp, &mut seen, ty)
2996 pub fn type_is_trait(ty: t) -> bool {
2997 type_trait_info(ty).is_some()
3000 pub fn type_trait_info(ty: t) -> Option<&'static TyTrait> {
3002 ty_uniq(ty) | ty_rptr(_, mt { ty, ..}) | ty_ptr(mt { ty, ..}) => match get(ty).sty {
3003 ty_trait(ref t) => Some(&**t),
3006 ty_trait(ref t) => Some(&**t),
3011 pub fn type_is_integral(ty: t) -> bool {
3013 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
3018 pub fn type_is_skolemized(ty: t) -> bool {
3020 ty_infer(SkolemizedTy(_)) => true,
3021 ty_infer(SkolemizedIntTy(_)) => true,
3026 pub fn type_is_uint(ty: t) -> bool {
3028 ty_infer(IntVar(_)) | ty_uint(ast::TyU) => true,
3033 pub fn type_is_char(ty: t) -> bool {
3040 pub fn type_is_bare_fn(ty: t) -> bool {
3042 ty_bare_fn(..) => true,
3047 pub fn type_is_fp(ty: t) -> bool {
3049 ty_infer(FloatVar(_)) | ty_float(_) => true,
3054 pub fn type_is_numeric(ty: t) -> bool {
3055 return type_is_integral(ty) || type_is_fp(ty);
3058 pub fn type_is_signed(ty: t) -> bool {
3065 pub fn type_is_machine(ty: t) -> bool {
3067 ty_int(ast::TyI) | ty_uint(ast::TyU) => false,
3068 ty_int(..) | ty_uint(..) | ty_float(..) => true,
3073 // Is the type's representation size known at compile time?
3074 pub fn type_is_sized(cx: &ctxt, ty: t) -> bool {
3075 type_contents(cx, ty).is_sized(cx)
3078 pub fn lltype_is_sized(cx: &ctxt, ty: t) -> bool {
3081 _ => type_contents(cx, ty).is_sized(cx)
3085 // Return the smallest part of t which is unsized. Fails if t is sized.
3086 // 'Smallest' here means component of the static representation of the type; not
3087 // the size of an object at runtime.
3088 pub fn unsized_part_of_type(cx: &ctxt, ty: t) -> t {
3090 ty_str | ty_trait(..) | ty_vec(..) => ty,
3091 ty_struct(def_id, ref substs) => {
3092 let unsized_fields: Vec<_> = struct_fields(cx, def_id, substs).iter()
3093 .map(|f| f.mt.ty).filter(|ty| !type_is_sized(cx, *ty)).collect();
3094 // Exactly one of the fields must be unsized.
3095 assert!(unsized_fields.len() == 1)
3097 unsized_part_of_type(cx, unsized_fields[0])
3100 assert!(type_is_sized(cx, ty),
3101 "unsized_part_of_type failed even though ty is unsized");
3102 fail!("called unsized_part_of_type with sized ty");
3107 // Whether a type is enum like, that is an enum type with only nullary
3109 pub fn type_is_c_like_enum(cx: &ctxt, ty: t) -> bool {
3111 ty_enum(did, _) => {
3112 let variants = enum_variants(cx, did);
3113 if variants.len() == 0 {
3116 variants.iter().all(|v| v.args.len() == 0)
3123 // Returns the type and mutability of *t.
3125 // The parameter `explicit` indicates if this is an *explicit* dereference.
3126 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
3127 pub fn deref(t: t, explicit: bool) -> Option<mt> {
3129 ty_box(ty) | ty_uniq(ty) => {
3132 mutbl: ast::MutImmutable,
3135 ty_rptr(_, mt) => Some(mt),
3136 ty_ptr(mt) if explicit => Some(mt),
3141 pub fn deref_or_dont(t: t) -> t {
3143 ty_box(ty) | ty_uniq(ty) => {
3146 ty_rptr(_, mt) | ty_ptr(mt) => mt.ty,
3151 pub fn close_type(cx: &ctxt, t: t) -> t {
3153 ty_open(t) => mk_rptr(cx, ReStatic, mt {ty: t, mutbl:ast::MutImmutable}),
3154 _ => cx.sess.bug(format!("Trying to close a non-open type {}",
3155 ty_to_string(cx, t)).as_slice())
3159 pub fn type_content(t: t) -> t {
3161 ty_box(ty) | ty_uniq(ty) => ty,
3162 ty_rptr(_, mt) |ty_ptr(mt) => mt.ty,
3168 // Extract the unsized type in an open type (or just return t if it is not open).
3169 pub fn unopen_type(t: t) -> t {
3176 // Returns the type of t[i]
3177 pub fn index(ty: t) -> Option<t> {
3179 ty_vec(t, _) => Some(t),
3184 // Returns the type of elements contained within an 'array-like' type.
3185 // This is exactly the same as the above, except it supports strings,
3186 // which can't actually be indexed.
3187 pub fn array_element_ty(t: t) -> Option<t> {
3189 ty_vec(t, _) => Some(t),
3190 ty_str => Some(mk_u8()),
3195 pub fn node_id_to_trait_ref(cx: &ctxt, id: ast::NodeId) -> Rc<ty::TraitRef> {
3196 match cx.trait_refs.borrow().find(&id) {
3197 Some(t) => t.clone(),
3198 None => cx.sess.bug(
3199 format!("node_id_to_trait_ref: no trait ref for node `{}`",
3200 cx.map.node_to_string(id)).as_slice())
3204 pub fn try_node_id_to_type(cx: &ctxt, id: ast::NodeId) -> Option<t> {
3205 cx.node_types.borrow().find_copy(&(id as uint))
3208 pub fn node_id_to_type(cx: &ctxt, id: ast::NodeId) -> t {
3209 match try_node_id_to_type(cx, id) {
3211 None => cx.sess.bug(
3212 format!("node_id_to_type: no type for node `{}`",
3213 cx.map.node_to_string(id)).as_slice())
3217 pub fn node_id_to_type_opt(cx: &ctxt, id: ast::NodeId) -> Option<t> {
3218 match cx.node_types.borrow().find(&(id as uint)) {
3219 Some(&t) => Some(t),
3224 pub fn node_id_item_substs(cx: &ctxt, id: ast::NodeId) -> ItemSubsts {
3225 match cx.item_substs.borrow().find(&id) {
3226 None => ItemSubsts::empty(),
3227 Some(ts) => ts.clone(),
3231 pub fn fn_is_variadic(fty: t) -> bool {
3232 match get(fty).sty {
3233 ty_bare_fn(ref f) => f.sig.variadic,
3234 ty_closure(ref f) => f.sig.variadic,
3236 fail!("fn_is_variadic() called on non-fn type: {:?}", s)
3241 pub fn ty_fn_sig(fty: t) -> FnSig {
3242 match get(fty).sty {
3243 ty_bare_fn(ref f) => f.sig.clone(),
3244 ty_closure(ref f) => f.sig.clone(),
3246 fail!("ty_fn_sig() called on non-fn type: {:?}", s)
3251 /// Returns the ABI of the given function.
3252 pub fn ty_fn_abi(fty: t) -> abi::Abi {
3253 match get(fty).sty {
3254 ty_bare_fn(ref f) => f.abi,
3255 ty_closure(ref f) => f.abi,
3256 _ => fail!("ty_fn_abi() called on non-fn type"),
3260 // Type accessors for substructures of types
3261 pub fn ty_fn_args(fty: t) -> Vec<t> {
3262 match get(fty).sty {
3263 ty_bare_fn(ref f) => f.sig.inputs.clone(),
3264 ty_closure(ref f) => f.sig.inputs.clone(),
3266 fail!("ty_fn_args() called on non-fn type: {:?}", s)
3271 pub fn ty_closure_store(fty: t) -> TraitStore {
3272 match get(fty).sty {
3273 ty_closure(ref f) => f.store,
3274 ty_unboxed_closure(..) => {
3275 // Close enough for the purposes of all the callers of this
3276 // function (which is soon to be deprecated anyhow).
3280 fail!("ty_closure_store() called on non-closure type: {:?}", s)
3285 pub fn ty_fn_ret(fty: t) -> t {
3286 match get(fty).sty {
3287 ty_bare_fn(ref f) => f.sig.output,
3288 ty_closure(ref f) => f.sig.output,
3290 fail!("ty_fn_ret() called on non-fn type: {:?}", s)
3295 pub fn is_fn_ty(fty: t) -> bool {
3296 match get(fty).sty {
3297 ty_bare_fn(_) => true,
3298 ty_closure(_) => true,
3303 pub fn ty_region(tcx: &ctxt,
3311 format!("ty_region() invoked on in appropriate ty: {:?}",
3317 pub fn free_region_from_def(free_id: ast::NodeId, def: &RegionParameterDef)
3320 ty::ReFree(ty::FreeRegion { scope_id: free_id,
3321 bound_region: ty::BrNamed(def.def_id,
3325 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
3326 // doesn't provide type parameter substitutions.
3327 pub fn pat_ty(cx: &ctxt, pat: &ast::Pat) -> t {
3328 return node_id_to_type(cx, pat.id);
3332 // Returns the type of an expression as a monotype.
3334 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
3335 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
3336 // auto-ref. The type returned by this function does not consider such
3337 // adjustments. See `expr_ty_adjusted()` instead.
3339 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
3340 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
3341 // instead of "fn(t) -> T with T = int".
3342 pub fn expr_ty(cx: &ctxt, expr: &ast::Expr) -> t {
3343 return node_id_to_type(cx, expr.id);
3346 pub fn expr_ty_opt(cx: &ctxt, expr: &ast::Expr) -> Option<t> {
3347 return node_id_to_type_opt(cx, expr.id);
3350 pub fn expr_ty_adjusted(cx: &ctxt, expr: &ast::Expr) -> t {
3353 * Returns the type of `expr`, considering any `AutoAdjustment`
3354 * entry recorded for that expression.
3356 * It would almost certainly be better to store the adjusted ty in with
3357 * the `AutoAdjustment`, but I opted not to do this because it would
3358 * require serializing and deserializing the type and, although that's not
3359 * hard to do, I just hate that code so much I didn't want to touch it
3360 * unless it was to fix it properly, which seemed a distraction from the
3361 * task at hand! -nmatsakis
3364 adjust_ty(cx, expr.span, expr.id, expr_ty(cx, expr),
3365 cx.adjustments.borrow().find(&expr.id),
3366 |method_call| cx.method_map.borrow().find(&method_call).map(|method| method.ty))
3369 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
3370 match cx.map.find(id) {
3371 Some(ast_map::NodeExpr(e)) => {
3375 cx.sess.bug(format!("Node id {} is not an expr: {:?}",
3380 cx.sess.bug(format!("Node id {} is not present \
3381 in the node map", id).as_slice());
3386 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
3387 match cx.map.find(id) {
3388 Some(ast_map::NodeLocal(pat)) => {
3390 ast::PatIdent(_, ref path1, _) => {
3391 token::get_ident(path1.node)
3395 format!("Variable id {} maps to {:?}, not local",
3402 cx.sess.bug(format!("Variable id {} maps to {:?}, not local",
3409 pub fn adjust_ty(cx: &ctxt,
3411 expr_id: ast::NodeId,
3412 unadjusted_ty: ty::t,
3413 adjustment: Option<&AutoAdjustment>,
3414 method_type: |typeck::MethodCall| -> Option<ty::t>)
3416 /*! See `expr_ty_adjusted` */
3418 match get(unadjusted_ty).sty {
3419 ty_err => return unadjusted_ty,
3423 return match adjustment {
3424 Some(adjustment) => {
3426 AdjustAddEnv(store) => {
3427 match ty::get(unadjusted_ty).sty {
3428 ty::ty_bare_fn(ref b) => {
3429 let bounds = ty::ExistentialBounds {
3430 region_bound: ReStatic,
3431 builtin_bounds: all_builtin_bounds(),
3436 ty::ClosureTy {fn_style: b.fn_style,
3437 onceness: ast::Many,
3445 format!("add_env adjustment on non-bare-fn: \
3452 AdjustDerefRef(ref adj) => {
3453 let mut adjusted_ty = unadjusted_ty;
3455 if !ty::type_is_error(adjusted_ty) {
3456 for i in range(0, adj.autoderefs) {
3457 let method_call = typeck::MethodCall::autoderef(expr_id, i);
3458 match method_type(method_call) {
3459 Some(method_ty) => {
3460 adjusted_ty = ty_fn_ret(method_ty);
3464 match deref(adjusted_ty, true) {
3465 Some(mt) => { adjusted_ty = mt.ty; }
3469 format!("the {}th autoderef failed: \
3472 ty_to_string(cx, adjusted_ty))
3480 None => adjusted_ty,
3481 Some(ref autoref) => adjust_for_autoref(cx, span, adjusted_ty, autoref)
3486 None => unadjusted_ty
3489 fn adjust_for_autoref(cx: &ctxt,
3492 autoref: &AutoRef) -> ty::t{
3494 AutoPtr(r, m, ref a) => {
3495 let adjusted_ty = match a {
3496 &Some(box ref a) => adjust_for_autoref(cx, span, ty, a),
3505 AutoUnsafe(m, ref a) => {
3506 let adjusted_ty = match a {
3507 &Some(box ref a) => adjust_for_autoref(cx, span, ty, a),
3510 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
3513 AutoUnsize(ref k) => unsize_ty(cx, ty, k, span),
3514 AutoUnsizeUniq(ref k) => ty::mk_uniq(cx, unsize_ty(cx, ty, k, span)),
3519 // Take a sized type and a sizing adjustment and produce an unsized version of
3521 pub fn unsize_ty(cx: &ctxt,
3527 &UnsizeLength(len) => match get(ty).sty {
3528 ty_vec(t, Some(n)) => {
3532 _ => cx.sess.span_bug(span,
3533 format!("UnsizeLength with bad sty: {}",
3534 ty_to_string(cx, ty)).as_slice())
3536 &UnsizeStruct(box ref k, tp_index) => match get(ty).sty {
3537 ty_struct(did, ref substs) => {
3538 let ty_substs = substs.types.get_slice(subst::TypeSpace);
3539 let new_ty = unsize_ty(cx, ty_substs[tp_index], k, span);
3540 let mut unsized_substs = substs.clone();
3541 unsized_substs.types.get_mut_slice(subst::TypeSpace)[tp_index] = new_ty;
3542 mk_struct(cx, did, unsized_substs)
3544 _ => cx.sess.span_bug(span,
3545 format!("UnsizeStruct with bad sty: {}",
3546 ty_to_string(cx, ty)).as_slice())
3548 &UnsizeVtable(TyTrait { def_id, substs: ref substs, bounds }, _) => {
3549 mk_trait(cx, def_id, substs.clone(), bounds)
3555 pub fn map_region(&self, f: |Region| -> Region) -> AutoRef {
3557 ty::AutoPtr(r, m, None) => ty::AutoPtr(f(r), m, None),
3558 ty::AutoPtr(r, m, Some(ref a)) => ty::AutoPtr(f(r), m, Some(box a.map_region(f))),
3559 ty::AutoUnsize(ref k) => ty::AutoUnsize(k.clone()),
3560 ty::AutoUnsizeUniq(ref k) => ty::AutoUnsizeUniq(k.clone()),
3561 ty::AutoUnsafe(m, None) => ty::AutoUnsafe(m, None),
3562 ty::AutoUnsafe(m, Some(ref a)) => ty::AutoUnsafe(m, Some(box a.map_region(f))),
3567 pub fn method_call_type_param_defs<'tcx, T>(typer: &T,
3568 origin: &typeck::MethodOrigin)
3569 -> VecPerParamSpace<TypeParameterDef>
3570 where T: mc::Typer<'tcx> {
3572 typeck::MethodStatic(did) => {
3573 ty::lookup_item_type(typer.tcx(), did).generics.types.clone()
3575 typeck::MethodStaticUnboxedClosure(did) => {
3576 let def_id = typer.unboxed_closures()
3579 .expect("method_call_type_param_defs: didn't \
3580 find unboxed closure")
3582 .trait_did(typer.tcx());
3583 lookup_trait_def(typer.tcx(), def_id).generics.types.clone()
3585 typeck::MethodTypeParam(typeck::MethodParam{
3586 trait_ref: ref trait_ref,
3590 typeck::MethodTraitObject(typeck::MethodObject{
3591 trait_ref: ref trait_ref,
3595 match ty::trait_item(typer.tcx(), trait_ref.def_id, n_mth) {
3596 ty::MethodTraitItem(method) => method.generics.types.clone(),
3597 ty::TypeTraitItem(_) => {
3598 typer.tcx().sess.bug("method_call_type_param_defs() \
3599 called on associated type")
3606 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> def::Def {
3607 match tcx.def_map.borrow().find(&expr.id) {
3610 tcx.sess.span_bug(expr.span, format!(
3611 "no def-map entry for expr {:?}", expr.id).as_slice());
3616 pub fn expr_is_lval(tcx: &ctxt, e: &ast::Expr) -> bool {
3617 match expr_kind(tcx, e) {
3619 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
3623 /// We categorize expressions into three kinds. The distinction between
3624 /// lvalue/rvalue is fundamental to the language. The distinction between the
3625 /// two kinds of rvalues is an artifact of trans which reflects how we will
3626 /// generate code for that kind of expression. See trans/expr.rs for more
3635 pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
3636 if tcx.method_map.borrow().contains_key(&typeck::MethodCall::expr(expr.id)) {
3637 // Overloaded operations are generally calls, and hence they are
3638 // generated via DPS, but there are a few exceptions:
3639 return match expr.node {
3640 // `a += b` has a unit result.
3641 ast::ExprAssignOp(..) => RvalueStmtExpr,
3643 // the deref method invoked for `*a` always yields an `&T`
3644 ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
3646 // the index method invoked for `a[i]` always yields an `&T`
3647 ast::ExprIndex(..) => LvalueExpr,
3649 // the slice method invoked for `a[..]` always yields an `&T`
3650 ast::ExprSlice(..) => LvalueExpr,
3652 // `for` loops are statements
3653 ast::ExprForLoop(..) => RvalueStmtExpr,
3655 // in the general case, result could be any type, use DPS
3661 ast::ExprPath(..) => {
3662 match resolve_expr(tcx, expr) {
3663 def::DefVariant(tid, vid, _) => {
3664 let variant_info = enum_variant_with_id(tcx, tid, vid);
3665 if variant_info.args.len() > 0u {
3674 def::DefStruct(_) => {
3675 match get(expr_ty(tcx, expr)).sty {
3676 ty_bare_fn(..) => RvalueDatumExpr,
3681 // Fn pointers are just scalar values.
3682 def::DefFn(..) | def::DefStaticMethod(..) => RvalueDatumExpr,
3684 // Note: there is actually a good case to be made that
3685 // DefArg's, particularly those of immediate type, ought to
3686 // considered rvalues.
3687 def::DefStatic(..) |
3689 def::DefLocal(..) => LvalueExpr,
3694 format!("uncategorized def for expr {:?}: {:?}",
3701 ast::ExprUnary(ast::UnDeref, _) |
3702 ast::ExprField(..) |
3703 ast::ExprTupField(..) |
3704 ast::ExprIndex(..) |
3705 ast::ExprSlice(..) => {
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) {
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 -> ast::CaptureClause {
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),
5692 /// A free variable referred to in a function.
5693 #[deriving(Encodable, Decodable)]
5694 pub struct Freevar {
5695 /// The variable being accessed free.
5698 // First span where it is accessed (there can be multiple).
5702 pub type FreevarMap = NodeMap<Vec<Freevar>>;
5704 pub type CaptureModeMap = NodeMap<ast::CaptureClause>;
5706 pub fn with_freevars<T>(tcx: &ty::ctxt, fid: ast::NodeId, f: |&[Freevar]| -> T) -> T {
5707 match tcx.freevars.borrow().find(&fid) {
5709 Some(d) => f(d.as_slice())