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)]
13 pub use self::terr_vstore_kind::*;
14 pub use self::type_err::*;
15 pub use self::BuiltinBound::*;
16 pub use self::InferTy::*;
17 pub use self::InferRegion::*;
18 pub use self::ImplOrTraitItemId::*;
19 pub use self::ClosureKind::*;
20 pub use self::Variance::*;
21 pub use self::AutoAdjustment::*;
22 pub use self::Representability::*;
23 pub use self::UnsizeKind::*;
24 pub use self::AutoRef::*;
25 pub use self::ExprKind::*;
26 pub use self::DtorKind::*;
27 pub use self::ExplicitSelfCategory::*;
28 pub use self::FnOutput::*;
29 pub use self::Region::*;
30 pub use self::ImplOrTraitItemContainer::*;
31 pub use self::BorrowKind::*;
32 pub use self::ImplOrTraitItem::*;
33 pub use self::BoundRegion::*;
35 pub use self::IntVarValue::*;
36 pub use self::ExprAdjustment::*;
37 pub use self::vtable_origin::*;
38 pub use self::MethodOrigin::*;
39 pub use self::CopyImplementationError::*;
44 use metadata::csearch;
46 use middle::check_const;
47 use middle::const_eval;
48 use middle::def::{self, DefMap, ExportMap};
49 use middle::dependency_format;
50 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
51 use middle::mem_categorization as mc;
53 use middle::resolve_lifetime;
56 use middle::stability;
57 use middle::subst::{self, ParamSpace, Subst, Substs, VecPerParamSpace};
60 use middle::ty_fold::{self, TypeFoldable, TypeFolder};
61 use middle::ty_walk::TypeWalker;
62 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_string};
63 use util::ppaux::ty_to_string;
64 use util::ppaux::{Repr, UserString};
65 use util::common::{memoized, ErrorReported};
66 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet};
67 use util::nodemap::{FnvHashMap};
69 use arena::TypedArena;
70 use std::borrow::{Borrow, Cow};
71 use std::cell::{Cell, RefCell};
74 use std::hash::{Hash, SipHasher, Hasher};
78 use std::vec::IntoIter;
79 use collections::enum_set::{EnumSet, CLike};
80 use std::collections::{HashMap, HashSet};
82 use syntax::ast::{CrateNum, DefId, Ident, ItemTrait, LOCAL_CRATE};
83 use syntax::ast::{MutImmutable, MutMutable, Name, NamedField, NodeId};
84 use syntax::ast::{StmtExpr, StmtSemi, StructField, UnnamedField, Visibility};
85 use syntax::ast_util::{self, is_local, lit_is_str, local_def};
86 use syntax::attr::{self, AttrMetaMethods};
87 use syntax::codemap::Span;
88 use syntax::parse::token::{self, InternedString, special_idents};
89 use syntax::{ast, ast_map};
93 pub const INITIAL_DISCRIMINANT_VALUE: Disr = 0;
97 /// The complete set of all analyses described in this module. This is
98 /// produced by the driver and fed to trans and later passes.
99 pub struct CrateAnalysis<'tcx> {
100 pub export_map: ExportMap,
101 pub exported_items: middle::privacy::ExportedItems,
102 pub public_items: middle::privacy::PublicItems,
103 pub ty_cx: ty::ctxt<'tcx>,
104 pub reachable: NodeSet,
106 pub glob_map: Option<GlobMap>,
109 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
110 pub struct field<'tcx> {
115 #[derive(Clone, Copy, Debug)]
116 pub enum ImplOrTraitItemContainer {
117 TraitContainer(ast::DefId),
118 ImplContainer(ast::DefId),
121 impl ImplOrTraitItemContainer {
122 pub fn id(&self) -> ast::DefId {
124 TraitContainer(id) => id,
125 ImplContainer(id) => id,
130 #[derive(Clone, Debug)]
131 pub enum ImplOrTraitItem<'tcx> {
132 MethodTraitItem(Rc<Method<'tcx>>),
133 TypeTraitItem(Rc<AssociatedType>),
136 impl<'tcx> ImplOrTraitItem<'tcx> {
137 fn id(&self) -> ImplOrTraitItemId {
139 MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
140 TypeTraitItem(ref associated_type) => {
141 TypeTraitItemId(associated_type.def_id)
146 pub fn def_id(&self) -> ast::DefId {
148 MethodTraitItem(ref method) => method.def_id,
149 TypeTraitItem(ref associated_type) => associated_type.def_id,
153 pub fn name(&self) -> ast::Name {
155 MethodTraitItem(ref method) => method.name,
156 TypeTraitItem(ref associated_type) => associated_type.name,
160 pub fn container(&self) -> ImplOrTraitItemContainer {
162 MethodTraitItem(ref method) => method.container,
163 TypeTraitItem(ref associated_type) => associated_type.container,
167 pub fn as_opt_method(&self) -> Option<Rc<Method<'tcx>>> {
169 MethodTraitItem(ref m) => Some((*m).clone()),
170 TypeTraitItem(_) => None
175 #[derive(Clone, Copy, Debug)]
176 pub enum ImplOrTraitItemId {
177 MethodTraitItemId(ast::DefId),
178 TypeTraitItemId(ast::DefId),
181 impl ImplOrTraitItemId {
182 pub fn def_id(&self) -> ast::DefId {
184 MethodTraitItemId(def_id) => def_id,
185 TypeTraitItemId(def_id) => def_id,
190 #[derive(Clone, Debug)]
191 pub struct Method<'tcx> {
193 pub generics: Generics<'tcx>,
194 pub predicates: GenericPredicates<'tcx>,
195 pub fty: BareFnTy<'tcx>,
196 pub explicit_self: ExplicitSelfCategory,
197 pub vis: ast::Visibility,
198 pub def_id: ast::DefId,
199 pub container: ImplOrTraitItemContainer,
201 // If this method is provided, we need to know where it came from
202 pub provided_source: Option<ast::DefId>
205 impl<'tcx> Method<'tcx> {
206 pub fn new(name: ast::Name,
207 generics: ty::Generics<'tcx>,
208 predicates: GenericPredicates<'tcx>,
210 explicit_self: ExplicitSelfCategory,
211 vis: ast::Visibility,
213 container: ImplOrTraitItemContainer,
214 provided_source: Option<ast::DefId>)
219 predicates: predicates,
221 explicit_self: explicit_self,
224 container: container,
225 provided_source: provided_source
229 pub fn container_id(&self) -> ast::DefId {
230 match self.container {
231 TraitContainer(id) => id,
232 ImplContainer(id) => id,
237 #[derive(Clone, Copy, Debug)]
238 pub struct AssociatedType {
240 pub vis: ast::Visibility,
241 pub def_id: ast::DefId,
242 pub container: ImplOrTraitItemContainer,
245 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
246 pub struct mt<'tcx> {
248 pub mutbl: ast::Mutability,
251 #[derive(Clone, Copy, Debug)]
252 pub struct field_ty {
255 pub vis: ast::Visibility,
256 pub origin: ast::DefId, // The DefId of the struct in which the field is declared.
259 // Contains information needed to resolve types and (in the future) look up
260 // the types of AST nodes.
261 #[derive(Copy, PartialEq, Eq, Hash)]
262 pub struct creader_cache_key {
268 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
269 pub struct ItemVariances {
270 pub types: VecPerParamSpace<Variance>,
271 pub regions: VecPerParamSpace<Variance>,
274 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug, Copy)]
276 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
277 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
278 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
279 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
282 #[derive(Clone, Debug)]
283 pub enum AutoAdjustment<'tcx> {
284 AdjustReifyFnPointer(ast::DefId), // go from a fn-item type to a fn-pointer type
285 AdjustUnsafeFnPointer, // go from a safe fn pointer to an unsafe fn pointer
286 AdjustDerefRef(AutoDerefRef<'tcx>)
289 #[derive(Clone, PartialEq, Debug)]
290 pub enum UnsizeKind<'tcx> {
291 // [T, ..n] -> [T], the uint field is n.
293 // An unsize coercion applied to the tail field of a struct.
294 // The uint is the index of the type parameter which is unsized.
295 UnsizeStruct(Box<UnsizeKind<'tcx>>, uint),
296 UnsizeVtable(TyTrait<'tcx>, /* the self type of the trait */ Ty<'tcx>),
297 UnsizeUpcast(Ty<'tcx>),
300 #[derive(Clone, Debug)]
301 pub struct AutoDerefRef<'tcx> {
302 pub autoderefs: uint,
303 pub autoref: Option<AutoRef<'tcx>>
306 #[derive(Clone, PartialEq, Debug)]
307 pub enum AutoRef<'tcx> {
308 /// Convert from T to &T
309 /// The third field allows us to wrap other AutoRef adjustments.
310 AutoPtr(Region, ast::Mutability, Option<Box<AutoRef<'tcx>>>),
312 /// Convert [T, ..n] to [T] (or similar, depending on the kind)
313 AutoUnsize(UnsizeKind<'tcx>),
315 /// Convert Box<[T, ..n]> to Box<[T]> or something similar in a Box.
316 /// With DST and Box a library type, this should be replaced by UnsizeStruct.
317 AutoUnsizeUniq(UnsizeKind<'tcx>),
319 /// Convert from T to *T
320 /// Value to thin pointer
321 /// The second field allows us to wrap other AutoRef adjustments.
322 AutoUnsafe(ast::Mutability, Option<Box<AutoRef<'tcx>>>),
325 // Ugly little helper function. The first bool in the returned tuple is true if
326 // there is an 'unsize to trait object' adjustment at the bottom of the
327 // adjustment. If that is surrounded by an AutoPtr, then we also return the
328 // region of the AutoPtr (in the third argument). The second bool is true if the
329 // adjustment is unique.
330 fn autoref_object_region(autoref: &AutoRef) -> (bool, bool, Option<Region>) {
331 fn unsize_kind_is_object(k: &UnsizeKind) -> bool {
333 &UnsizeVtable(..) => true,
334 &UnsizeStruct(box ref k, _) => unsize_kind_is_object(k),
340 &AutoUnsize(ref k) => (unsize_kind_is_object(k), false, None),
341 &AutoUnsizeUniq(ref k) => (unsize_kind_is_object(k), true, None),
342 &AutoPtr(adj_r, _, Some(box ref autoref)) => {
343 let (b, u, r) = autoref_object_region(autoref);
344 if r.is_some() || u {
350 &AutoUnsafe(_, Some(box ref autoref)) => autoref_object_region(autoref),
351 _ => (false, false, None)
355 // If the adjustment introduces a borrowed reference to a trait object, then
356 // returns the region of the borrowed reference.
357 pub fn adjusted_object_region(adj: &AutoAdjustment) -> Option<Region> {
359 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
360 let (b, _, r) = autoref_object_region(autoref);
371 // Returns true if there is a trait cast at the bottom of the adjustment.
372 pub fn adjust_is_object(adj: &AutoAdjustment) -> bool {
374 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
375 let (b, _, _) = autoref_object_region(autoref);
382 // If possible, returns the type expected from the given adjustment. This is not
383 // possible if the adjustment depends on the type of the adjusted expression.
384 pub fn type_of_adjust<'tcx>(cx: &ctxt<'tcx>, adj: &AutoAdjustment<'tcx>) -> Option<Ty<'tcx>> {
385 fn type_of_autoref<'tcx>(cx: &ctxt<'tcx>, autoref: &AutoRef<'tcx>) -> Option<Ty<'tcx>> {
387 &AutoUnsize(ref k) => match k {
388 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
389 Some(mk_trait(cx, principal.clone(), bounds.clone()))
393 &AutoUnsizeUniq(ref k) => match k {
394 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
395 Some(mk_uniq(cx, mk_trait(cx, principal.clone(), bounds.clone())))
399 &AutoPtr(r, m, Some(box ref autoref)) => {
400 match type_of_autoref(cx, autoref) {
401 Some(ty) => Some(mk_rptr(cx, cx.mk_region(r), mt {mutbl: m, ty: ty})),
405 &AutoUnsafe(m, Some(box ref autoref)) => {
406 match type_of_autoref(cx, autoref) {
407 Some(ty) => Some(mk_ptr(cx, mt {mutbl: m, ty: ty})),
416 &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
417 type_of_autoref(cx, autoref)
423 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Debug)]
424 pub struct param_index {
425 pub space: subst::ParamSpace,
429 #[derive(Clone, Debug)]
430 pub enum MethodOrigin<'tcx> {
431 // fully statically resolved method
432 MethodStatic(ast::DefId),
434 // fully statically resolved closure invocation
435 MethodStaticClosure(ast::DefId),
437 // method invoked on a type parameter with a bounded trait
438 MethodTypeParam(MethodParam<'tcx>),
440 // method invoked on a trait instance
441 MethodTraitObject(MethodObject<'tcx>),
445 // details for a method invoked with a receiver whose type is a type parameter
446 // with a bounded trait.
447 #[derive(Clone, Debug)]
448 pub struct MethodParam<'tcx> {
449 // the precise trait reference that occurs as a bound -- this may
450 // be a supertrait of what the user actually typed. Note that it
451 // never contains bound regions; those regions should have been
452 // instantiated with fresh variables at this point.
453 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
455 // index of uint in the list of trait items. Note that this is NOT
456 // the index into the vtable, because the list of trait items
457 // includes associated types.
458 pub method_num: uint,
460 /// The impl for the trait from which the method comes. This
461 /// should only be used for certain linting/heuristic purposes
462 /// since there is no guarantee that this is Some in every
463 /// situation that it could/should be.
464 pub impl_def_id: Option<ast::DefId>,
467 // details for a method invoked with a receiver whose type is an object
468 #[derive(Clone, Debug)]
469 pub struct MethodObject<'tcx> {
470 // the (super)trait containing the method to be invoked
471 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
473 // the actual base trait id of the object
474 pub object_trait_id: ast::DefId,
476 // index of the method to be invoked amongst the trait's items
477 pub method_num: uint,
479 // index into the actual runtime vtable.
480 // the vtable is formed by concatenating together the method lists of
481 // the base object trait and all supertraits; this is the index into
483 pub vtable_index: uint,
487 pub struct MethodCallee<'tcx> {
488 pub origin: MethodOrigin<'tcx>,
490 pub substs: subst::Substs<'tcx>
493 /// With method calls, we store some extra information in
494 /// side tables (i.e method_map). We use
495 /// MethodCall as a key to index into these tables instead of
496 /// just directly using the expression's NodeId. The reason
497 /// for this being that we may apply adjustments (coercions)
498 /// with the resulting expression also needing to use the
499 /// side tables. The problem with this is that we don't
500 /// assign a separate NodeId to this new expression
501 /// and so it would clash with the base expression if both
502 /// needed to add to the side tables. Thus to disambiguate
503 /// we also keep track of whether there's an adjustment in
505 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
506 pub struct MethodCall {
507 pub expr_id: ast::NodeId,
508 pub adjustment: ExprAdjustment
511 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
512 pub enum ExprAdjustment {
519 pub fn expr(id: ast::NodeId) -> MethodCall {
522 adjustment: NoAdjustment
526 pub fn autoobject(id: ast::NodeId) -> MethodCall {
529 adjustment: AutoObject
533 pub fn autoderef(expr_id: ast::NodeId, autoderef: uint) -> MethodCall {
536 adjustment: AutoDeref(1 + autoderef)
541 // maps from an expression id that corresponds to a method call to the details
542 // of the method to be invoked
543 pub type MethodMap<'tcx> = RefCell<FnvHashMap<MethodCall, MethodCallee<'tcx>>>;
545 pub type vtable_param_res<'tcx> = Vec<vtable_origin<'tcx>>;
547 // Resolutions for bounds of all parameters, left to right, for a given path.
548 pub type vtable_res<'tcx> = VecPerParamSpace<vtable_param_res<'tcx>>;
551 pub enum vtable_origin<'tcx> {
553 Statically known vtable. def_id gives the impl item
554 from whence comes the vtable, and tys are the type substs.
555 vtable_res is the vtable itself.
557 vtable_static(ast::DefId, subst::Substs<'tcx>, vtable_res<'tcx>),
560 Dynamic vtable, comes from a parameter that has a bound on it:
561 fn foo<T:quux,baz,bar>(a: T) -- a's vtable would have a
564 The first argument is the param index (identifying T in the example),
565 and the second is the bound number (identifying baz)
567 vtable_param(param_index, uint),
570 Vtable automatically generated for a closure. The def ID is the
571 ID of the closure expression.
573 vtable_closure(ast::DefId),
576 Asked to determine the vtable for ty_err. This is the value used
577 for the vtables of `Self` in a virtual call like `foo.bar()`
578 where `foo` is of object type. The same value is also used when
585 // For every explicit cast into an object type, maps from the cast
586 // expr to the associated trait ref.
587 pub type ObjectCastMap<'tcx> = RefCell<NodeMap<ty::PolyTraitRef<'tcx>>>;
589 /// A restriction that certain types must be the same size. The use of
590 /// `transmute` gives rise to these restrictions. These generally
591 /// cannot be checked until trans; therefore, each call to `transmute`
592 /// will push one or more such restriction into the
593 /// `transmute_restrictions` vector during `intrinsicck`. They are
594 /// then checked during `trans` by the fn `check_intrinsics`.
596 pub struct TransmuteRestriction<'tcx> {
597 /// The span whence the restriction comes.
600 /// The type being transmuted from.
601 pub original_from: Ty<'tcx>,
603 /// The type being transmuted to.
604 pub original_to: Ty<'tcx>,
606 /// The type being transmuted from, with all type parameters
607 /// substituted for an arbitrary representative. Not to be shown
609 pub substituted_from: Ty<'tcx>,
611 /// The type being transmuted to, with all type parameters
612 /// substituted for an arbitrary representative. Not to be shown
614 pub substituted_to: Ty<'tcx>,
616 /// NodeId of the transmute intrinsic.
621 pub struct CtxtArenas<'tcx> {
622 type_: TypedArena<TyS<'tcx>>,
623 substs: TypedArena<Substs<'tcx>>,
624 bare_fn: TypedArena<BareFnTy<'tcx>>,
625 region: TypedArena<Region>,
628 impl<'tcx> CtxtArenas<'tcx> {
629 pub fn new() -> CtxtArenas<'tcx> {
631 type_: TypedArena::new(),
632 substs: TypedArena::new(),
633 bare_fn: TypedArena::new(),
634 region: TypedArena::new(),
639 pub struct CommonTypes<'tcx> {
657 /// The data structure to keep track of all the information that typechecker
658 /// generates so that so that it can be reused and doesn't have to be redone
660 pub struct ctxt<'tcx> {
661 /// The arenas that types etc are allocated from.
662 arenas: &'tcx CtxtArenas<'tcx>,
664 /// Specifically use a speedy hash algorithm for this hash map, it's used
666 // FIXME(eddyb) use a FnvHashSet<InternedTy<'tcx>> when equivalent keys can
667 // queried from a HashSet.
668 interner: RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>,
670 // FIXME as above, use a hashset if equivalent elements can be queried.
671 substs_interner: RefCell<FnvHashMap<&'tcx Substs<'tcx>, &'tcx Substs<'tcx>>>,
672 bare_fn_interner: RefCell<FnvHashMap<&'tcx BareFnTy<'tcx>, &'tcx BareFnTy<'tcx>>>,
673 region_interner: RefCell<FnvHashMap<&'tcx Region, &'tcx Region>>,
675 /// Common types, pre-interned for your convenience.
676 pub types: CommonTypes<'tcx>,
681 pub named_region_map: resolve_lifetime::NamedRegionMap,
683 pub region_maps: middle::region::RegionMaps,
685 /// Stores the types for various nodes in the AST. Note that this table
686 /// is not guaranteed to be populated until after typeck. See
687 /// typeck::check::fn_ctxt for details.
688 pub node_types: RefCell<NodeMap<Ty<'tcx>>>,
690 /// Stores the type parameters which were substituted to obtain the type
691 /// of this node. This only applies to nodes that refer to entities
692 /// parameterized by type parameters, such as generic fns, types, or
694 pub item_substs: RefCell<NodeMap<ItemSubsts<'tcx>>>,
696 /// Maps from a trait item to the trait item "descriptor"
697 pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem<'tcx>>>,
699 /// Maps from a trait def-id to a list of the def-ids of its trait items
700 pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
702 /// A cache for the trait_items() routine
703 pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem<'tcx>>>>>,
705 pub impl_trait_cache: RefCell<DefIdMap<Option<Rc<ty::TraitRef<'tcx>>>>>,
707 pub impl_trait_refs: RefCell<NodeMap<Rc<TraitRef<'tcx>>>>,
708 pub trait_defs: RefCell<DefIdMap<Rc<TraitDef<'tcx>>>>,
710 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
711 /// associated predicates.
712 pub predicates: RefCell<DefIdMap<GenericPredicates<'tcx>>>,
714 /// Maps from the def-id of a trait to the list of
715 /// super-predicates. This is a subset of the full list of
716 /// predicates. We store these in a separate map because we must
717 /// evaluate them even during type conversion, often before the
718 /// full predicates are available (note that supertraits have
719 /// additional acyclicity requirements).
720 pub super_predicates: RefCell<DefIdMap<GenericPredicates<'tcx>>>,
722 /// Maps from node-id of a trait object cast (like `foo as
723 /// Box<Trait>`) to the trait reference.
724 pub object_cast_map: ObjectCastMap<'tcx>,
726 pub map: ast_map::Map<'tcx>,
727 pub freevars: RefCell<FreevarMap>,
728 pub tcache: RefCell<DefIdMap<TypeScheme<'tcx>>>,
729 pub rcache: RefCell<FnvHashMap<creader_cache_key, Ty<'tcx>>>,
730 pub short_names_cache: RefCell<FnvHashMap<Ty<'tcx>, String>>,
731 pub tc_cache: RefCell<FnvHashMap<Ty<'tcx>, TypeContents>>,
732 pub ast_ty_to_ty_cache: RefCell<NodeMap<Ty<'tcx>>>,
733 pub enum_var_cache: RefCell<DefIdMap<Rc<Vec<Rc<VariantInfo<'tcx>>>>>>,
734 pub ty_param_defs: RefCell<NodeMap<TypeParameterDef<'tcx>>>,
735 pub adjustments: RefCell<NodeMap<AutoAdjustment<'tcx>>>,
736 pub normalized_cache: RefCell<FnvHashMap<Ty<'tcx>, Ty<'tcx>>>,
737 pub lang_items: middle::lang_items::LanguageItems,
738 /// A mapping of fake provided method def_ids to the default implementation
739 pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
740 pub struct_fields: RefCell<DefIdMap<Rc<Vec<field_ty>>>>,
742 /// Maps from def-id of a type or region parameter to its
743 /// (inferred) variance.
744 pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
746 /// True if the variance has been computed yet; false otherwise.
747 pub variance_computed: Cell<bool>,
749 /// A mapping from the def ID of an enum or struct type to the def ID
750 /// of the method that implements its destructor. If the type is not
751 /// present in this map, it does not have a destructor. This map is
752 /// populated during the coherence phase of typechecking.
753 pub destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
755 /// A method will be in this list if and only if it is a destructor.
756 pub destructors: RefCell<DefIdSet>,
758 /// Maps a trait onto a list of impls of that trait.
759 pub trait_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
761 /// A set of traits that have a default impl
762 traits_with_default_impls: RefCell<DefIdMap<()>>,
764 /// Maps a DefId of a type to a list of its inherent impls.
765 /// Contains implementations of methods that are inherent to a type.
766 /// Methods in these implementations don't need to be exported.
767 pub inherent_impls: RefCell<DefIdMap<Rc<Vec<ast::DefId>>>>,
769 /// Maps a DefId of an impl to a list of its items.
770 /// Note that this contains all of the impls that we know about,
771 /// including ones in other crates. It's not clear that this is the best
773 pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
775 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
776 /// present in this set can be warned about.
777 pub used_unsafe: RefCell<NodeSet>,
779 /// Set of nodes which mark locals as mutable which end up getting used at
780 /// some point. Local variable definitions not in this set can be warned
782 pub used_mut_nodes: RefCell<NodeSet>,
784 /// The set of external nominal types whose implementations have been read.
785 /// This is used for lazy resolution of methods.
786 pub populated_external_types: RefCell<DefIdSet>,
788 /// The set of external traits whose implementations have been read. This
789 /// is used for lazy resolution of traits.
790 pub populated_external_traits: RefCell<DefIdSet>,
792 /// The set of external primitive inherent implementations that have been read.
793 pub populated_external_primitive_impls: RefCell<DefIdSet>,
796 pub upvar_capture_map: RefCell<UpvarCaptureMap>,
798 /// These two caches are used by const_eval when decoding external statics
799 /// and variants that are found.
800 pub extern_const_statics: RefCell<DefIdMap<ast::NodeId>>,
801 pub extern_const_variants: RefCell<DefIdMap<ast::NodeId>>,
803 pub method_map: MethodMap<'tcx>,
805 pub dependency_formats: RefCell<dependency_format::Dependencies>,
807 /// Records the type of each closure. The def ID is the ID of the
808 /// expression defining the closure.
809 pub closure_kinds: RefCell<DefIdMap<ClosureKind>>,
811 /// Records the type of each closure. The def ID is the ID of the
812 /// expression defining the closure.
813 pub closure_tys: RefCell<DefIdMap<ClosureTy<'tcx>>>,
815 pub node_lint_levels: RefCell<FnvHashMap<(ast::NodeId, lint::LintId),
818 /// The types that must be asserted to be the same size for `transmute`
819 /// to be valid. We gather up these restrictions in the intrinsicck pass
820 /// and check them in trans.
821 pub transmute_restrictions: RefCell<Vec<TransmuteRestriction<'tcx>>>,
823 /// Maps any item's def-id to its stability index.
824 pub stability: RefCell<stability::Index>,
826 /// Maps def IDs to true if and only if they're associated types.
827 pub associated_types: RefCell<DefIdMap<bool>>,
829 /// Caches the results of trait selection. This cache is used
830 /// for things that do not have to do with the parameters in scope.
831 pub selection_cache: traits::SelectionCache<'tcx>,
833 /// Caches the representation hints for struct definitions.
834 pub repr_hint_cache: RefCell<DefIdMap<Rc<Vec<attr::ReprAttr>>>>,
836 /// Caches whether types are known to impl Copy. Note that type
837 /// parameters are never placed into this cache, because their
838 /// results are dependent on the parameter environment.
839 pub type_impls_copy_cache: RefCell<HashMap<Ty<'tcx>,bool>>,
841 /// Caches whether types are known to impl Sized. Note that type
842 /// parameters are never placed into this cache, because their
843 /// results are dependent on the parameter environment.
844 pub type_impls_sized_cache: RefCell<HashMap<Ty<'tcx>,bool>>,
846 /// Caches whether traits are object safe
847 pub object_safety_cache: RefCell<DefIdMap<bool>>,
849 /// Maps Expr NodeId's to their constant qualification.
850 pub const_qualif_map: RefCell<NodeMap<check_const::ConstQualif>>,
853 // Flags that we track on types. These flags are propagated upwards
854 // through the type during type construction, so that we can quickly
855 // check whether the type has various kinds of types in it without
856 // recursing over the type itself.
858 flags TypeFlags: u32 {
859 const NO_TYPE_FLAGS = 0b0,
860 const HAS_PARAMS = 0b1,
861 const HAS_SELF = 0b10,
862 const HAS_TY_INFER = 0b100,
863 const HAS_RE_INFER = 0b1000,
864 const HAS_RE_LATE_BOUND = 0b10000,
865 const HAS_REGIONS = 0b100000,
866 const HAS_TY_ERR = 0b1000000,
867 const HAS_PROJECTION = 0b10000000,
868 const NEEDS_SUBST = HAS_PARAMS.bits | HAS_SELF.bits | HAS_REGIONS.bits,
872 macro_rules! sty_debug_print {
873 ($ctxt: expr, $($variant: ident),*) => {{
874 // curious inner module to allow variant names to be used as
886 pub fn go(tcx: &ty::ctxt) {
887 let mut total = DebugStat {
889 region_infer: 0, ty_infer: 0, both_infer: 0,
891 $(let mut $variant = total;)*
894 for (_, t) in &*tcx.interner.borrow() {
895 let variant = match t.sty {
896 ty::ty_bool | ty::ty_char | ty::ty_int(..) | ty::ty_uint(..) |
897 ty::ty_float(..) | ty::ty_str => continue,
898 ty::ty_err => /* unimportant */ continue,
899 $(ty::$variant(..) => &mut $variant,)*
901 let region = t.flags.intersects(ty::HAS_RE_INFER);
902 let ty = t.flags.intersects(ty::HAS_TY_INFER);
906 if region { total.region_infer += 1; variant.region_infer += 1 }
907 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
908 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
910 println!("Ty interner total ty region both");
911 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
912 {ty:4.1}% {region:5.1}% {both:4.1}%",
913 stringify!($variant),
914 uses = $variant.total,
915 usespc = $variant.total as f64 * 100.0 / total.total as f64,
916 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
917 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
918 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
920 println!(" total {uses:6} \
921 {ty:4.1}% {region:5.1}% {both:4.1}%",
923 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
924 region = total.region_infer as f64 * 100.0 / total.total as f64,
925 both = total.both_infer as f64 * 100.0 / total.total as f64)
933 impl<'tcx> ctxt<'tcx> {
934 pub fn print_debug_stats(&self) {
937 ty_enum, ty_uniq, ty_vec, ty_ptr, ty_rptr, ty_bare_fn, ty_trait,
938 ty_struct, ty_closure, ty_tup, ty_param, ty_infer, ty_projection);
940 println!("Substs interner: #{}", self.substs_interner.borrow().len());
941 println!("BareFnTy interner: #{}", self.bare_fn_interner.borrow().len());
942 println!("Region interner: #{}", self.region_interner.borrow().len());
947 pub struct TyS<'tcx> {
949 pub flags: TypeFlags,
951 // the maximal depth of any bound regions appearing in this type.
955 impl fmt::Debug for TypeFlags {
956 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
957 write!(f, "{}", self.bits)
961 impl<'tcx> PartialEq for TyS<'tcx> {
962 fn eq(&self, other: &TyS<'tcx>) -> bool {
963 // (self as *const _) == (other as *const _)
964 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
967 impl<'tcx> Eq for TyS<'tcx> {}
969 impl<'tcx> Hash for TyS<'tcx> {
970 fn hash<H: Hasher>(&self, s: &mut H) {
971 (self as *const _).hash(s)
975 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
977 /// An entry in the type interner.
978 pub struct InternedTy<'tcx> {
982 // NB: An InternedTy compares and hashes as a sty.
983 impl<'tcx> PartialEq for InternedTy<'tcx> {
984 fn eq(&self, other: &InternedTy<'tcx>) -> bool {
985 self.ty.sty == other.ty.sty
989 impl<'tcx> Eq for InternedTy<'tcx> {}
991 impl<'tcx> Hash for InternedTy<'tcx> {
992 fn hash<H: Hasher>(&self, s: &mut H) {
997 impl<'tcx> Borrow<sty<'tcx>> for InternedTy<'tcx> {
998 fn borrow<'a>(&'a self) -> &'a sty<'tcx> {
1003 pub fn type_has_params(ty: Ty) -> bool {
1004 ty.flags.intersects(HAS_PARAMS)
1006 pub fn type_has_self(ty: Ty) -> bool {
1007 ty.flags.intersects(HAS_SELF)
1009 pub fn type_has_ty_infer(ty: Ty) -> bool {
1010 ty.flags.intersects(HAS_TY_INFER)
1012 pub fn type_needs_infer(ty: Ty) -> bool {
1013 ty.flags.intersects(HAS_TY_INFER | HAS_RE_INFER)
1015 pub fn type_has_projection(ty: Ty) -> bool {
1016 ty.flags.intersects(HAS_PROJECTION)
1019 pub fn type_has_late_bound_regions(ty: Ty) -> bool {
1020 ty.flags.intersects(HAS_RE_LATE_BOUND)
1023 /// An "escaping region" is a bound region whose binder is not part of `t`.
1025 /// So, for example, consider a type like the following, which has two binders:
1027 /// for<'a> fn(x: for<'b> fn(&'a int, &'b int))
1028 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
1029 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
1031 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
1032 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
1033 /// fn type*, that type has an escaping region: `'a`.
1035 /// Note that what I'm calling an "escaping region" is often just called a "free region". However,
1036 /// we already use the term "free region". It refers to the regions that we use to represent bound
1037 /// regions on a fn definition while we are typechecking its body.
1039 /// To clarify, conceptually there is no particular difference between an "escaping" region and a
1040 /// "free" region. However, there is a big difference in practice. Basically, when "entering" a
1041 /// binding level, one is generally required to do some sort of processing to a bound region, such
1042 /// as replacing it with a fresh/skolemized region, or making an entry in the environment to
1043 /// represent the scope to which it is attached, etc. An escaping region represents a bound region
1044 /// for which this processing has not yet been done.
1045 pub fn type_has_escaping_regions(ty: Ty) -> bool {
1046 type_escapes_depth(ty, 0)
1049 pub fn type_escapes_depth(ty: Ty, depth: u32) -> bool {
1050 ty.region_depth > depth
1053 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1054 pub struct BareFnTy<'tcx> {
1055 pub unsafety: ast::Unsafety,
1057 pub sig: PolyFnSig<'tcx>,
1060 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1061 pub struct ClosureTy<'tcx> {
1062 pub unsafety: ast::Unsafety,
1064 pub sig: PolyFnSig<'tcx>,
1067 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1068 pub enum FnOutput<'tcx> {
1069 FnConverging(Ty<'tcx>),
1073 impl<'tcx> FnOutput<'tcx> {
1074 pub fn diverges(&self) -> bool {
1075 *self == FnDiverging
1078 pub fn unwrap(self) -> Ty<'tcx> {
1080 ty::FnConverging(t) => t,
1081 ty::FnDiverging => unreachable!()
1086 pub type PolyFnOutput<'tcx> = Binder<FnOutput<'tcx>>;
1088 impl<'tcx> PolyFnOutput<'tcx> {
1089 pub fn diverges(&self) -> bool {
1094 /// Signature of a function type, which I have arbitrarily
1095 /// decided to use to refer to the input/output types.
1097 /// - `inputs` is the list of arguments and their modes.
1098 /// - `output` is the return type.
1099 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
1100 #[derive(Clone, PartialEq, Eq, Hash)]
1101 pub struct FnSig<'tcx> {
1102 pub inputs: Vec<Ty<'tcx>>,
1103 pub output: FnOutput<'tcx>,
1107 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1109 impl<'tcx> PolyFnSig<'tcx> {
1110 pub fn inputs(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
1111 ty::Binder(self.0.inputs.clone())
1113 pub fn input(&self, index: uint) -> ty::Binder<Ty<'tcx>> {
1114 ty::Binder(self.0.inputs[index])
1116 pub fn output(&self) -> ty::Binder<FnOutput<'tcx>> {
1117 ty::Binder(self.0.output.clone())
1119 pub fn variadic(&self) -> bool {
1124 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1125 pub struct ParamTy {
1126 pub space: subst::ParamSpace,
1128 pub name: ast::Name,
1131 /// A [De Bruijn index][dbi] is a standard means of representing
1132 /// regions (and perhaps later types) in a higher-ranked setting. In
1133 /// particular, imagine a type like this:
1135 /// for<'a> fn(for<'b> fn(&'b int, &'a int), &'a char)
1138 /// | +------------+ 1 | |
1140 /// +--------------------------------+ 2 |
1142 /// +------------------------------------------+ 1
1144 /// In this type, there are two binders (the outer fn and the inner
1145 /// fn). We need to be able to determine, for any given region, which
1146 /// fn type it is bound by, the inner or the outer one. There are
1147 /// various ways you can do this, but a De Bruijn index is one of the
1148 /// more convenient and has some nice properties. The basic idea is to
1149 /// count the number of binders, inside out. Some examples should help
1150 /// clarify what I mean.
1152 /// Let's start with the reference type `&'b int` that is the first
1153 /// argument to the inner function. This region `'b` is assigned a De
1154 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
1155 /// fn). The region `'a` that appears in the second argument type (`&'a
1156 /// int`) would then be assigned a De Bruijn index of 2, meaning "the
1157 /// second-innermost binder". (These indices are written on the arrays
1158 /// in the diagram).
1160 /// What is interesting is that De Bruijn index attached to a particular
1161 /// variable will vary depending on where it appears. For example,
1162 /// the final type `&'a char` also refers to the region `'a` declared on
1163 /// the outermost fn. But this time, this reference is not nested within
1164 /// any other binders (i.e., it is not an argument to the inner fn, but
1165 /// rather the outer one). Therefore, in this case, it is assigned a
1166 /// De Bruijn index of 1, because the innermost binder in that location
1167 /// is the outer fn.
1169 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1170 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
1171 pub struct DebruijnIndex {
1172 // We maintain the invariant that this is never 0. So 1 indicates
1173 // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
1177 /// Representation of regions:
1178 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
1180 // Region bound in a type or fn declaration which will be
1181 // substituted 'early' -- that is, at the same time when type
1182 // parameters are substituted.
1183 ReEarlyBound(/* param id */ ast::NodeId,
1188 // Region bound in a function scope, which will be substituted when the
1189 // function is called.
1190 ReLateBound(DebruijnIndex, BoundRegion),
1192 /// When checking a function body, the types of all arguments and so forth
1193 /// that refer to bound region parameters are modified to refer to free
1194 /// region parameters.
1197 /// A concrete region naming some statically determined extent
1198 /// (e.g. an expression or sequence of statements) within the
1199 /// current function.
1200 ReScope(region::CodeExtent),
1202 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1205 /// A region variable. Should not exist after typeck.
1206 ReInfer(InferRegion),
1208 /// Empty lifetime is for data that is never accessed.
1209 /// Bottom in the region lattice. We treat ReEmpty somewhat
1210 /// specially; at least right now, we do not generate instances of
1211 /// it during the GLB computations, but rather
1212 /// generate an error instead. This is to improve error messages.
1213 /// The only way to get an instance of ReEmpty is to have a region
1214 /// variable with no constraints.
1218 /// Upvars do not get their own node-id. Instead, we use the pair of
1219 /// the original var id (that is, the root variable that is referenced
1220 /// by the upvar) and the id of the closure expression.
1221 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1222 pub struct UpvarId {
1223 pub var_id: ast::NodeId,
1224 pub closure_expr_id: ast::NodeId,
1227 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
1228 pub enum BorrowKind {
1229 /// Data must be immutable and is aliasable.
1232 /// Data must be immutable but not aliasable. This kind of borrow
1233 /// cannot currently be expressed by the user and is used only in
1234 /// implicit closure bindings. It is needed when you the closure
1235 /// is borrowing or mutating a mutable referent, e.g.:
1237 /// let x: &mut int = ...;
1238 /// let y = || *x += 5;
1240 /// If we were to try to translate this closure into a more explicit
1241 /// form, we'd encounter an error with the code as written:
1243 /// struct Env { x: & &mut int }
1244 /// let x: &mut int = ...;
1245 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
1246 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1248 /// This is then illegal because you cannot mutate a `&mut` found
1249 /// in an aliasable location. To solve, you'd have to translate with
1250 /// an `&mut` borrow:
1252 /// struct Env { x: & &mut int }
1253 /// let x: &mut int = ...;
1254 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
1255 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1257 /// Now the assignment to `**env.x` is legal, but creating a
1258 /// mutable pointer to `x` is not because `x` is not mutable. We
1259 /// could fix this by declaring `x` as `let mut x`. This is ok in
1260 /// user code, if awkward, but extra weird for closures, since the
1261 /// borrow is hidden.
1263 /// So we introduce a "unique imm" borrow -- the referent is
1264 /// immutable, but not aliasable. This solves the problem. For
1265 /// simplicity, we don't give users the way to express this
1266 /// borrow, it's just used when translating closures.
1269 /// Data is mutable and not aliasable.
1273 /// Information describing the capture of an upvar. This is computed
1274 /// during `typeck`, specifically by `regionck`.
1275 #[derive(PartialEq, Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1276 pub enum UpvarCapture {
1277 /// Upvar is captured by value. This is always true when the
1278 /// closure is labeled `move`, but can also be true in other cases
1279 /// depending on inference.
1282 /// Upvar is captured by reference.
1286 #[derive(PartialEq, Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1287 pub struct UpvarBorrow {
1288 /// The kind of borrow: by-ref upvars have access to shared
1289 /// immutable borrows, which are not part of the normal language
1291 pub kind: BorrowKind,
1293 /// Region of the resulting reference.
1294 pub region: ty::Region,
1297 pub type UpvarCaptureMap = FnvHashMap<UpvarId, UpvarCapture>;
1300 pub fn is_bound(&self) -> bool {
1302 ty::ReEarlyBound(..) => true,
1303 ty::ReLateBound(..) => true,
1308 pub fn escapes_depth(&self, depth: u32) -> bool {
1310 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1316 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1317 RustcEncodable, RustcDecodable, Debug, Copy)]
1318 /// A "free" region `fr` can be interpreted as "some region
1319 /// at least as big as the scope `fr.scope`".
1320 pub struct FreeRegion {
1321 pub scope: region::DestructionScopeData,
1322 pub bound_region: BoundRegion
1325 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1326 RustcEncodable, RustcDecodable, Debug, Copy)]
1327 pub enum BoundRegion {
1328 /// An anonymous region parameter for a given fn (&T)
1331 /// Named region parameters for functions (a in &'a T)
1333 /// The def-id is needed to distinguish free regions in
1334 /// the event of shadowing.
1335 BrNamed(ast::DefId, ast::Name),
1337 /// Fresh bound identifiers created during GLB computations.
1340 // Anonymous region for the implicit env pointer parameter
1345 // NB: If you change this, you'll probably want to change the corresponding
1346 // AST structure in libsyntax/ast.rs as well.
1347 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1348 pub enum sty<'tcx> {
1352 ty_uint(ast::UintTy),
1353 ty_float(ast::FloatTy),
1354 /// Substs here, possibly against intuition, *may* contain `ty_param`s.
1355 /// That is, even after substitution it is possible that there are type
1356 /// variables. This happens when the `ty_enum` corresponds to an enum
1357 /// definition and not a concrete use of it. To get the correct `ty_enum`
1358 /// from the tcx, use the `NodeId` from the `ast::Ty` and look it up in
1359 /// the `ast_ty_to_ty_cache`. This is probably true for `ty_struct` as
1361 ty_enum(DefId, &'tcx Substs<'tcx>),
1364 ty_vec(Ty<'tcx>, Option<uint>), // Second field is length.
1366 ty_rptr(&'tcx Region, mt<'tcx>),
1368 // If the def-id is Some(_), then this is the type of a specific
1369 // fn item. Otherwise, if None(_), it a fn pointer type.
1370 ty_bare_fn(Option<DefId>, &'tcx BareFnTy<'tcx>),
1372 ty_trait(Box<TyTrait<'tcx>>),
1373 ty_struct(DefId, &'tcx Substs<'tcx>),
1375 ty_closure(DefId, &'tcx Substs<'tcx>),
1377 ty_tup(Vec<Ty<'tcx>>),
1379 ty_projection(ProjectionTy<'tcx>),
1380 ty_param(ParamTy), // type parameter
1382 ty_infer(InferTy), // something used only during inference/typeck
1383 ty_err, // Also only used during inference/typeck, to represent
1384 // the type of an erroneous expression (helps cut down
1385 // on non-useful type error messages)
1388 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1389 pub struct TyTrait<'tcx> {
1390 pub principal: ty::PolyTraitRef<'tcx>,
1391 pub bounds: ExistentialBounds<'tcx>,
1394 impl<'tcx> TyTrait<'tcx> {
1395 pub fn principal_def_id(&self) -> ast::DefId {
1396 self.principal.0.def_id
1399 /// Object types don't have a self-type specified. Therefore, when
1400 /// we convert the principal trait-ref into a normal trait-ref,
1401 /// you must give *some* self-type. A common choice is `mk_err()`
1402 /// or some skolemized type.
1403 pub fn principal_trait_ref_with_self_ty(&self,
1406 -> ty::PolyTraitRef<'tcx>
1408 // otherwise the escaping regions would be captured by the binder
1409 assert!(!self_ty.has_escaping_regions());
1411 ty::Binder(Rc::new(ty::TraitRef {
1412 def_id: self.principal.0.def_id,
1413 substs: tcx.mk_substs(self.principal.0.substs.with_self_ty(self_ty)),
1417 pub fn projection_bounds_with_self_ty(&self,
1420 -> Vec<ty::PolyProjectionPredicate<'tcx>>
1422 // otherwise the escaping regions would be captured by the binders
1423 assert!(!self_ty.has_escaping_regions());
1425 self.bounds.projection_bounds.iter()
1426 .map(|in_poly_projection_predicate| {
1427 let in_projection_ty = &in_poly_projection_predicate.0.projection_ty;
1428 let substs = tcx.mk_substs(in_projection_ty.trait_ref.substs.with_self_ty(self_ty));
1430 Rc::new(ty::TraitRef::new(in_projection_ty.trait_ref.def_id,
1432 let projection_ty = ty::ProjectionTy {
1433 trait_ref: trait_ref,
1434 item_name: in_projection_ty.item_name
1436 ty::Binder(ty::ProjectionPredicate {
1437 projection_ty: projection_ty,
1438 ty: in_poly_projection_predicate.0.ty
1445 /// A complete reference to a trait. These take numerous guises in syntax,
1446 /// but perhaps the most recognizable form is in a where clause:
1450 /// This would be represented by a trait-reference where the def-id is the
1451 /// def-id for the trait `Foo` and the substs defines `T` as parameter 0 in the
1452 /// `SelfSpace` and `U` as parameter 0 in the `TypeSpace`.
1454 /// Trait references also appear in object types like `Foo<U>`, but in
1455 /// that case the `Self` parameter is absent from the substitutions.
1457 /// Note that a `TraitRef` introduces a level of region binding, to
1458 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
1459 /// U>` or higher-ranked object types.
1460 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1461 pub struct TraitRef<'tcx> {
1463 pub substs: &'tcx Substs<'tcx>,
1466 pub type PolyTraitRef<'tcx> = Binder<Rc<TraitRef<'tcx>>>;
1468 impl<'tcx> PolyTraitRef<'tcx> {
1469 pub fn self_ty(&self) -> Ty<'tcx> {
1473 pub fn def_id(&self) -> ast::DefId {
1477 pub fn substs(&self) -> &'tcx Substs<'tcx> {
1478 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
1482 pub fn input_types(&self) -> &[Ty<'tcx>] {
1483 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
1484 self.0.input_types()
1487 pub fn to_poly_trait_predicate(&self) -> PolyTraitPredicate<'tcx> {
1488 // Note that we preserve binding levels
1489 Binder(TraitPredicate { trait_ref: self.0.clone() })
1493 /// Binder is a binder for higher-ranked lifetimes. It is part of the
1494 /// compiler's representation for things like `for<'a> Fn(&'a int)`
1495 /// (which would be represented by the type `PolyTraitRef ==
1496 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
1497 /// erase, or otherwise "discharge" these bound regions, we change the
1498 /// type from `Binder<T>` to just `T` (see
1499 /// e.g. `liberate_late_bound_regions`).
1500 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1501 pub struct Binder<T>(pub T);
1504 /// Skips the binder and returns the "bound" value. This is a
1505 /// risky thing to do because it's easy to get confused about
1506 /// debruijn indices and the like. It is usually better to
1507 /// discharge the binder using `no_late_bound_regions` or
1508 /// `replace_late_bound_regions` or something like
1509 /// that. `skip_binder` is only valid when you are either
1510 /// extracting data that has nothing to do with bound regions, you
1511 /// are doing some sort of test that does not involve bound
1512 /// regions, or you are being very careful about your depth
1515 /// Some examples where `skip_binder` is reasonable:
1516 /// - extracting the def-id from a PolyTraitRef;
1517 /// - comparing the self type of a PolyTraitRef to see if it is equal to
1518 /// a type parameter `X`, since the type `X` does not reference any regions
1519 pub fn skip_binder(&self) -> &T {
1524 #[derive(Clone, Copy, PartialEq)]
1525 pub enum IntVarValue {
1526 IntType(ast::IntTy),
1527 UintType(ast::UintTy),
1530 #[derive(Clone, Copy, Debug)]
1531 pub enum terr_vstore_kind {
1538 #[derive(Clone, Copy, Debug)]
1539 pub struct expected_found<T> {
1544 // Data structures used in type unification
1545 #[derive(Clone, Copy, Debug)]
1546 pub enum type_err<'tcx> {
1548 terr_unsafety_mismatch(expected_found<ast::Unsafety>),
1549 terr_abi_mismatch(expected_found<abi::Abi>),
1551 terr_box_mutability,
1552 terr_ptr_mutability,
1553 terr_ref_mutability,
1554 terr_vec_mutability,
1555 terr_tuple_size(expected_found<uint>),
1556 terr_fixed_array_size(expected_found<uint>),
1557 terr_ty_param_size(expected_found<uint>),
1559 terr_regions_does_not_outlive(Region, Region),
1560 terr_regions_not_same(Region, Region),
1561 terr_regions_no_overlap(Region, Region),
1562 terr_regions_insufficiently_polymorphic(BoundRegion, Region),
1563 terr_regions_overly_polymorphic(BoundRegion, Region),
1564 terr_sorts(expected_found<Ty<'tcx>>),
1565 terr_integer_as_char,
1566 terr_int_mismatch(expected_found<IntVarValue>),
1567 terr_float_mismatch(expected_found<ast::FloatTy>),
1568 terr_traits(expected_found<ast::DefId>),
1569 terr_builtin_bounds(expected_found<BuiltinBounds>),
1570 terr_variadic_mismatch(expected_found<bool>),
1572 terr_convergence_mismatch(expected_found<bool>),
1573 terr_projection_name_mismatched(expected_found<ast::Name>),
1574 terr_projection_bounds_length(expected_found<uint>),
1577 /// Bounds suitable for a named type parameter like `A` in `fn foo<A>`
1578 /// as well as the existential type parameter in an object type.
1579 #[derive(PartialEq, Eq, Hash, Clone, Debug)]
1580 pub struct ParamBounds<'tcx> {
1581 pub region_bounds: Vec<ty::Region>,
1582 pub builtin_bounds: BuiltinBounds,
1583 pub trait_bounds: Vec<PolyTraitRef<'tcx>>,
1584 pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
1587 /// Bounds suitable for an existentially quantified type parameter
1588 /// such as those that appear in object types or closure types. The
1589 /// major difference between this case and `ParamBounds` is that
1590 /// general purpose trait bounds are omitted and there must be
1591 /// *exactly one* region.
1592 #[derive(PartialEq, Eq, Hash, Clone, Debug)]
1593 pub struct ExistentialBounds<'tcx> {
1594 pub region_bound: ty::Region,
1595 pub builtin_bounds: BuiltinBounds,
1596 pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
1599 pub type BuiltinBounds = EnumSet<BuiltinBound>;
1601 #[derive(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
1604 pub enum BuiltinBound {
1611 pub fn empty_builtin_bounds() -> BuiltinBounds {
1615 pub fn all_builtin_bounds() -> BuiltinBounds {
1616 let mut set = EnumSet::new();
1617 set.insert(BoundSend);
1618 set.insert(BoundSized);
1619 set.insert(BoundSync);
1623 /// An existential bound that does not implement any traits.
1624 pub fn region_existential_bound<'tcx>(r: ty::Region) -> ExistentialBounds<'tcx> {
1625 ty::ExistentialBounds { region_bound: r,
1626 builtin_bounds: empty_builtin_bounds(),
1627 projection_bounds: Vec::new() }
1630 impl CLike for BuiltinBound {
1631 fn to_usize(&self) -> uint {
1634 fn from_usize(v: uint) -> BuiltinBound {
1635 unsafe { mem::transmute(v) }
1639 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1644 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1649 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1650 pub struct FloatVid {
1654 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1655 pub struct RegionVid {
1659 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1665 /// A `FreshTy` is one that is generated as a replacement for an
1666 /// unbound type variable. This is convenient for caching etc. See
1667 /// `middle::infer::freshen` for more details.
1670 // FIXME -- once integral fallback is impl'd, we should remove
1671 // this type. It's only needed to prevent spurious errors for
1672 // integers whose type winds up never being constrained.
1676 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
1677 pub enum UnconstrainedNumeric {
1684 #[derive(Clone, RustcEncodable, RustcDecodable, Eq, Hash, Debug, Copy)]
1685 pub enum InferRegion {
1687 ReSkolemized(u32, BoundRegion)
1690 impl cmp::PartialEq for InferRegion {
1691 fn eq(&self, other: &InferRegion) -> bool {
1692 match ((*self), *other) {
1693 (ReVar(rva), ReVar(rvb)) => {
1696 (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
1702 fn ne(&self, other: &InferRegion) -> bool {
1703 !((*self) == (*other))
1707 impl fmt::Debug for TyVid {
1708 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
1709 write!(f, "_#{}t", self.index)
1713 impl fmt::Debug for IntVid {
1714 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1715 write!(f, "_#{}i", self.index)
1719 impl fmt::Debug for FloatVid {
1720 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1721 write!(f, "_#{}f", self.index)
1725 impl fmt::Debug for RegionVid {
1726 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1727 write!(f, "'_#{}r", self.index)
1731 impl<'tcx> fmt::Debug for FnSig<'tcx> {
1732 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1733 write!(f, "({:?}; variadic: {})->{:?}", self.inputs, self.variadic, self.output)
1737 impl fmt::Debug for InferTy {
1738 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1740 TyVar(ref v) => v.fmt(f),
1741 IntVar(ref v) => v.fmt(f),
1742 FloatVar(ref v) => v.fmt(f),
1743 FreshTy(v) => write!(f, "FreshTy({:?})", v),
1744 FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
1749 impl fmt::Debug for IntVarValue {
1750 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1752 IntType(ref v) => v.fmt(f),
1753 UintType(ref v) => v.fmt(f),
1758 /// Default region to use for the bound of objects that are
1759 /// supplied as the value for this type parameter. This is derived
1760 /// from `T:'a` annotations appearing in the type definition. If
1761 /// this is `None`, then the default is inherited from the
1762 /// surrounding context. See RFC #599 for details.
1763 #[derive(Copy, Clone, Debug)]
1764 pub enum ObjectLifetimeDefault {
1765 /// Require an explicit annotation. Occurs when multiple
1766 /// `T:'a` constraints are found.
1769 /// Use the given region as the default.
1773 #[derive(Clone, Debug)]
1774 pub struct TypeParameterDef<'tcx> {
1775 pub name: ast::Name,
1776 pub def_id: ast::DefId,
1777 pub space: subst::ParamSpace,
1779 pub default: Option<Ty<'tcx>>,
1780 pub object_lifetime_default: Option<ObjectLifetimeDefault>,
1783 #[derive(RustcEncodable, RustcDecodable, Clone, Debug)]
1784 pub struct RegionParameterDef {
1785 pub name: ast::Name,
1786 pub def_id: ast::DefId,
1787 pub space: subst::ParamSpace,
1789 pub bounds: Vec<ty::Region>,
1792 impl RegionParameterDef {
1793 pub fn to_early_bound_region(&self) -> ty::Region {
1794 ty::ReEarlyBound(self.def_id.node, self.space, self.index, self.name)
1798 /// Information about the formal type/lifetime parameters associated
1799 /// with an item or method. Analogous to ast::Generics.
1800 #[derive(Clone, Debug)]
1801 pub struct Generics<'tcx> {
1802 pub types: VecPerParamSpace<TypeParameterDef<'tcx>>,
1803 pub regions: VecPerParamSpace<RegionParameterDef>,
1806 impl<'tcx> Generics<'tcx> {
1807 pub fn empty() -> Generics<'tcx> {
1809 types: VecPerParamSpace::empty(),
1810 regions: VecPerParamSpace::empty(),
1814 pub fn is_empty(&self) -> bool {
1815 self.types.is_empty() && self.regions.is_empty()
1818 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
1819 !self.types.is_empty_in(space)
1822 pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
1823 !self.regions.is_empty_in(space)
1827 /// Bounds on generics.
1828 #[derive(Clone, Debug)]
1829 pub struct GenericPredicates<'tcx> {
1830 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
1833 impl<'tcx> GenericPredicates<'tcx> {
1834 pub fn empty() -> GenericPredicates<'tcx> {
1836 predicates: VecPerParamSpace::empty(),
1840 pub fn instantiate(&self, tcx: &ty::ctxt<'tcx>, substs: &Substs<'tcx>)
1841 -> InstantiatedPredicates<'tcx> {
1842 InstantiatedPredicates {
1843 predicates: self.predicates.subst(tcx, substs),
1847 pub fn instantiate_supertrait(&self,
1848 tcx: &ty::ctxt<'tcx>,
1849 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
1850 -> InstantiatedPredicates<'tcx>
1852 InstantiatedPredicates {
1853 predicates: self.predicates.map(|pred| pred.subst_supertrait(tcx, poly_trait_ref))
1858 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1859 pub enum Predicate<'tcx> {
1860 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
1861 /// the `Self` type of the trait reference and `A`, `B`, and `C`
1862 /// would be the parameters in the `TypeSpace`.
1863 Trait(PolyTraitPredicate<'tcx>),
1865 /// where `T1 == T2`.
1866 Equate(PolyEquatePredicate<'tcx>),
1869 RegionOutlives(PolyRegionOutlivesPredicate),
1872 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1874 /// where <T as TraitRef>::Name == X, approximately.
1875 /// See `ProjectionPredicate` struct for details.
1876 Projection(PolyProjectionPredicate<'tcx>),
1879 impl<'tcx> Predicate<'tcx> {
1880 /// Performs a substituion suitable for going from a
1881 /// poly-trait-ref to supertraits that must hold if that
1882 /// poly-trait-ref holds. This is slightly different from a normal
1883 /// substitution in terms of what happens with bound regions. See
1884 /// lengthy comment below for details.
1885 pub fn subst_supertrait(&self,
1886 tcx: &ty::ctxt<'tcx>,
1887 trait_ref: &ty::PolyTraitRef<'tcx>)
1888 -> ty::Predicate<'tcx>
1890 // The interaction between HRTB and supertraits is not entirely
1891 // obvious. Let me walk you (and myself) through an example.
1893 // Let's start with an easy case. Consider two traits:
1895 // trait Foo<'a> : Bar<'a,'a> { }
1896 // trait Bar<'b,'c> { }
1898 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
1899 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
1900 // knew that `Foo<'x>` (for any 'x) then we also know that
1901 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1902 // normal substitution.
1904 // In terms of why this is sound, the idea is that whenever there
1905 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1906 // holds. So if there is an impl of `T:Foo<'a>` that applies to
1907 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1910 // Another example to be careful of is this:
1912 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
1913 // trait Bar1<'b,'c> { }
1915 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
1916 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
1917 // reason is similar to the previous example: any impl of
1918 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
1919 // basically we would want to collapse the bound lifetimes from
1920 // the input (`trait_ref`) and the supertraits.
1922 // To achieve this in practice is fairly straightforward. Let's
1923 // consider the more complicated scenario:
1925 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
1926 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
1927 // where both `'x` and `'b` would have a DB index of 1.
1928 // The substitution from the input trait-ref is therefore going to be
1929 // `'a => 'x` (where `'x` has a DB index of 1).
1930 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1931 // early-bound parameter and `'b' is a late-bound parameter with a
1933 // - If we replace `'a` with `'x` from the input, it too will have
1934 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1935 // just as we wanted.
1937 // There is only one catch. If we just apply the substitution `'a
1938 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1939 // adjust the DB index because we substituting into a binder (it
1940 // tries to be so smart...) resulting in `for<'x> for<'b>
1941 // Bar1<'x,'b>` (we have no syntax for this, so use your
1942 // imagination). Basically the 'x will have DB index of 2 and 'b
1943 // will have DB index of 1. Not quite what we want. So we apply
1944 // the substitution to the *contents* of the trait reference,
1945 // rather than the trait reference itself (put another way, the
1946 // substitution code expects equal binding levels in the values
1947 // from the substitution and the value being substituted into, and
1948 // this trick achieves that).
1950 let substs = &trait_ref.0.substs;
1952 Predicate::Trait(ty::Binder(ref data)) =>
1953 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
1954 Predicate::Equate(ty::Binder(ref data)) =>
1955 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
1956 Predicate::RegionOutlives(ty::Binder(ref data)) =>
1957 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
1958 Predicate::TypeOutlives(ty::Binder(ref data)) =>
1959 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
1960 Predicate::Projection(ty::Binder(ref data)) =>
1961 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
1966 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1967 pub struct TraitPredicate<'tcx> {
1968 pub trait_ref: Rc<TraitRef<'tcx>>
1970 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1972 impl<'tcx> TraitPredicate<'tcx> {
1973 pub fn def_id(&self) -> ast::DefId {
1974 self.trait_ref.def_id
1977 pub fn input_types(&self) -> &[Ty<'tcx>] {
1978 self.trait_ref.substs.types.as_slice()
1981 pub fn self_ty(&self) -> Ty<'tcx> {
1982 self.trait_ref.self_ty()
1986 impl<'tcx> PolyTraitPredicate<'tcx> {
1987 pub fn def_id(&self) -> ast::DefId {
1992 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1993 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
1994 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
1996 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1997 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
1998 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
1999 pub type PolyRegionOutlivesPredicate = PolyOutlivesPredicate<ty::Region, ty::Region>;
2000 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region>;
2002 /// This kind of predicate has no *direct* correspondent in the
2003 /// syntax, but it roughly corresponds to the syntactic forms:
2005 /// 1. `T : TraitRef<..., Item=Type>`
2006 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
2008 /// In particular, form #1 is "desugared" to the combination of a
2009 /// normal trait predicate (`T : TraitRef<...>`) and one of these
2010 /// predicates. Form #2 is a broader form in that it also permits
2011 /// equality between arbitrary types. Processing an instance of Form
2012 /// #2 eventually yields one of these `ProjectionPredicate`
2013 /// instances to normalize the LHS.
2014 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2015 pub struct ProjectionPredicate<'tcx> {
2016 pub projection_ty: ProjectionTy<'tcx>,
2020 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
2022 impl<'tcx> PolyProjectionPredicate<'tcx> {
2023 pub fn item_name(&self) -> ast::Name {
2024 self.0.projection_ty.item_name // safe to skip the binder to access a name
2027 pub fn sort_key(&self) -> (ast::DefId, ast::Name) {
2028 self.0.projection_ty.sort_key()
2032 /// Represents the projection of an associated type. In explicit UFCS
2033 /// form this would be written `<T as Trait<..>>::N`.
2034 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2035 pub struct ProjectionTy<'tcx> {
2036 /// The trait reference `T as Trait<..>`.
2037 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
2039 /// The name `N` of the associated type.
2040 pub item_name: ast::Name,
2043 impl<'tcx> ProjectionTy<'tcx> {
2044 pub fn sort_key(&self) -> (ast::DefId, ast::Name) {
2045 (self.trait_ref.def_id, self.item_name)
2049 pub trait ToPolyTraitRef<'tcx> {
2050 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
2053 impl<'tcx> ToPolyTraitRef<'tcx> for Rc<TraitRef<'tcx>> {
2054 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2055 assert!(!self.has_escaping_regions());
2056 ty::Binder(self.clone())
2060 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
2061 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2062 // We are just preserving the binder levels here
2063 ty::Binder(self.0.trait_ref.clone())
2067 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
2068 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2069 // Note: unlike with TraitRef::to_poly_trait_ref(),
2070 // self.0.trait_ref is permitted to have escaping regions.
2071 // This is because here `self` has a `Binder` and so does our
2072 // return value, so we are preserving the number of binding
2074 ty::Binder(self.0.projection_ty.trait_ref.clone())
2078 pub trait AsPredicate<'tcx> {
2079 fn as_predicate(&self) -> Predicate<'tcx>;
2082 impl<'tcx> AsPredicate<'tcx> for Rc<TraitRef<'tcx>> {
2083 fn as_predicate(&self) -> Predicate<'tcx> {
2084 // we're about to add a binder, so let's check that we don't
2085 // accidentally capture anything, or else that might be some
2086 // weird debruijn accounting.
2087 assert!(!self.has_escaping_regions());
2089 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
2090 trait_ref: self.clone()
2095 impl<'tcx> AsPredicate<'tcx> for PolyTraitRef<'tcx> {
2096 fn as_predicate(&self) -> Predicate<'tcx> {
2097 ty::Predicate::Trait(self.to_poly_trait_predicate())
2101 impl<'tcx> AsPredicate<'tcx> for PolyEquatePredicate<'tcx> {
2102 fn as_predicate(&self) -> Predicate<'tcx> {
2103 Predicate::Equate(self.clone())
2107 impl<'tcx> AsPredicate<'tcx> for PolyRegionOutlivesPredicate {
2108 fn as_predicate(&self) -> Predicate<'tcx> {
2109 Predicate::RegionOutlives(self.clone())
2113 impl<'tcx> AsPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
2114 fn as_predicate(&self) -> Predicate<'tcx> {
2115 Predicate::TypeOutlives(self.clone())
2119 impl<'tcx> AsPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
2120 fn as_predicate(&self) -> Predicate<'tcx> {
2121 Predicate::Projection(self.clone())
2125 impl<'tcx> Predicate<'tcx> {
2126 /// Iterates over the types in this predicate. Note that in all
2127 /// cases this is skipping over a binder, so late-bound regions
2128 /// with depth 0 are bound by the predicate.
2129 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
2130 let vec: Vec<_> = match *self {
2131 ty::Predicate::Trait(ref data) => {
2132 data.0.trait_ref.substs.types.as_slice().to_vec()
2134 ty::Predicate::Equate(ty::Binder(ref data)) => {
2135 vec![data.0, data.1]
2137 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
2140 ty::Predicate::RegionOutlives(..) => {
2143 ty::Predicate::Projection(ref data) => {
2144 let trait_inputs = data.0.projection_ty.trait_ref.substs.types.as_slice();
2147 .chain(Some(data.0.ty).into_iter())
2152 // The only reason to collect into a vector here is that I was
2153 // too lazy to make the full (somewhat complicated) iterator
2154 // type that would be needed here. But I wanted this fn to
2155 // return an iterator conceptually, rather than a `Vec`, so as
2156 // to be closer to `Ty::walk`.
2160 pub fn has_escaping_regions(&self) -> bool {
2162 Predicate::Trait(ref trait_ref) => trait_ref.has_escaping_regions(),
2163 Predicate::Equate(ref p) => p.has_escaping_regions(),
2164 Predicate::RegionOutlives(ref p) => p.has_escaping_regions(),
2165 Predicate::TypeOutlives(ref p) => p.has_escaping_regions(),
2166 Predicate::Projection(ref p) => p.has_escaping_regions(),
2170 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
2172 Predicate::Trait(ref t) => {
2173 Some(t.to_poly_trait_ref())
2175 Predicate::Projection(..) |
2176 Predicate::Equate(..) |
2177 Predicate::RegionOutlives(..) |
2178 Predicate::TypeOutlives(..) => {
2185 /// Represents the bounds declared on a particular set of type
2186 /// parameters. Should eventually be generalized into a flag list of
2187 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
2188 /// `GenericPredicates` by using the `instantiate` method. Note that this method
2189 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
2190 /// the `GenericPredicates` are expressed in terms of the bound type
2191 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
2192 /// represented a set of bounds for some particular instantiation,
2193 /// meaning that the generic parameters have been substituted with
2198 /// struct Foo<T,U:Bar<T>> { ... }
2200 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
2201 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
2202 /// like `Foo<int,uint>`, then the `InstantiatedPredicates` would be `[[],
2203 /// [uint:Bar<int>]]`.
2204 #[derive(Clone, Debug)]
2205 pub struct InstantiatedPredicates<'tcx> {
2206 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
2209 impl<'tcx> InstantiatedPredicates<'tcx> {
2210 pub fn empty() -> InstantiatedPredicates<'tcx> {
2211 InstantiatedPredicates { predicates: VecPerParamSpace::empty() }
2214 pub fn has_escaping_regions(&self) -> bool {
2215 self.predicates.any(|p| p.has_escaping_regions())
2218 pub fn is_empty(&self) -> bool {
2219 self.predicates.is_empty()
2223 impl<'tcx> TraitRef<'tcx> {
2224 pub fn new(def_id: ast::DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
2225 TraitRef { def_id: def_id, substs: substs }
2228 pub fn self_ty(&self) -> Ty<'tcx> {
2229 self.substs.self_ty().unwrap()
2232 pub fn input_types(&self) -> &[Ty<'tcx>] {
2233 // Select only the "input types" from a trait-reference. For
2234 // now this is all the types that appear in the
2235 // trait-reference, but it should eventually exclude
2236 // associated types.
2237 self.substs.types.as_slice()
2241 /// When type checking, we use the `ParameterEnvironment` to track
2242 /// details about the type/lifetime parameters that are in scope.
2243 /// It primarily stores the bounds information.
2245 /// Note: This information might seem to be redundant with the data in
2246 /// `tcx.ty_param_defs`, but it is not. That table contains the
2247 /// parameter definitions from an "outside" perspective, but this
2248 /// struct will contain the bounds for a parameter as seen from inside
2249 /// the function body. Currently the only real distinction is that
2250 /// bound lifetime parameters are replaced with free ones, but in the
2251 /// future I hope to refine the representation of types so as to make
2252 /// more distinctions clearer.
2254 pub struct ParameterEnvironment<'a, 'tcx:'a> {
2255 pub tcx: &'a ctxt<'tcx>,
2257 /// See `construct_free_substs` for details.
2258 pub free_substs: Substs<'tcx>,
2260 /// Each type parameter has an implicit region bound that
2261 /// indicates it must outlive at least the function body (the user
2262 /// may specify stronger requirements). This field indicates the
2263 /// region of the callee.
2264 pub implicit_region_bound: ty::Region,
2266 /// Obligations that the caller must satisfy. This is basically
2267 /// the set of bounds on the in-scope type parameters, translated
2268 /// into Obligations.
2269 pub caller_bounds: Vec<ty::Predicate<'tcx>>,
2271 /// Caches the results of trait selection. This cache is used
2272 /// for things that have to do with the parameters in scope.
2273 pub selection_cache: traits::SelectionCache<'tcx>,
2276 impl<'a, 'tcx> ParameterEnvironment<'a, 'tcx> {
2277 pub fn with_caller_bounds(&self,
2278 caller_bounds: Vec<ty::Predicate<'tcx>>)
2279 -> ParameterEnvironment<'a,'tcx>
2281 ParameterEnvironment {
2283 free_substs: self.free_substs.clone(),
2284 implicit_region_bound: self.implicit_region_bound,
2285 caller_bounds: caller_bounds,
2286 selection_cache: traits::SelectionCache::new(),
2290 pub fn for_item(cx: &'a ctxt<'tcx>, id: NodeId) -> ParameterEnvironment<'a, 'tcx> {
2291 match cx.map.find(id) {
2292 Some(ast_map::NodeImplItem(ref impl_item)) => {
2293 match impl_item.node {
2294 ast::MethodImplItem(_, ref body) => {
2295 let method_def_id = ast_util::local_def(id);
2296 match ty::impl_or_trait_item(cx, method_def_id) {
2297 MethodTraitItem(ref method_ty) => {
2298 let method_generics = &method_ty.generics;
2299 let method_bounds = &method_ty.predicates;
2300 construct_parameter_environment(
2307 TypeTraitItem(_) => {
2309 .bug("ParameterEnvironment::for_item(): \
2310 can't create a parameter environment \
2311 for type trait items")
2315 ast::TypeImplItem(_) => {
2316 cx.sess.bug("ParameterEnvironment::for_item(): \
2317 can't create a parameter environment \
2318 for type impl items")
2320 ast::MacImplItem(_) => cx.sess.bug("unexpanded macro")
2323 Some(ast_map::NodeTraitItem(trait_item)) => {
2324 match trait_item.node {
2325 ast::MethodTraitItem(_, None) => {
2326 cx.sess.span_bug(trait_item.span,
2327 "ParameterEnvironment::for_item():
2328 can't create a parameter \
2329 environment for required trait \
2332 ast::MethodTraitItem(_, Some(ref body)) => {
2333 let method_def_id = ast_util::local_def(id);
2334 match ty::impl_or_trait_item(cx, method_def_id) {
2335 MethodTraitItem(ref method_ty) => {
2336 let method_generics = &method_ty.generics;
2337 let method_bounds = &method_ty.predicates;
2338 construct_parameter_environment(
2345 TypeTraitItem(_) => {
2347 .bug("ParameterEnvironment::for_item(): \
2348 can't create a parameter environment \
2349 for type trait items")
2353 ast::TypeTraitItem(..) => {
2354 cx.sess.bug("ParameterEnvironment::from_item(): \
2355 can't create a parameter environment \
2356 for type trait items")
2360 Some(ast_map::NodeItem(item)) => {
2362 ast::ItemFn(_, _, _, _, ref body) => {
2363 // We assume this is a function.
2364 let fn_def_id = ast_util::local_def(id);
2365 let fn_scheme = lookup_item_type(cx, fn_def_id);
2366 let fn_predicates = lookup_predicates(cx, fn_def_id);
2368 construct_parameter_environment(cx,
2370 &fn_scheme.generics,
2375 ast::ItemStruct(..) |
2377 ast::ItemConst(..) |
2378 ast::ItemStatic(..) => {
2379 let def_id = ast_util::local_def(id);
2380 let scheme = lookup_item_type(cx, def_id);
2381 let predicates = lookup_predicates(cx, def_id);
2382 construct_parameter_environment(cx,
2389 cx.sess.span_bug(item.span,
2390 "ParameterEnvironment::from_item():
2391 can't create a parameter \
2392 environment for this kind of item")
2396 Some(ast_map::NodeExpr(..)) => {
2397 // This is a convenience to allow closures to work.
2398 ParameterEnvironment::for_item(cx, cx.map.get_parent(id))
2401 cx.sess.bug(&format!("ParameterEnvironment::from_item(): \
2402 `{}` is not an item",
2403 cx.map.node_to_string(id)))
2409 /// A "type scheme", in ML terminology, is a type combined with some
2410 /// set of generic types that the type is, well, generic over. In Rust
2411 /// terms, it is the "type" of a fn item or struct -- this type will
2412 /// include various generic parameters that must be substituted when
2413 /// the item/struct is referenced. That is called converting the type
2414 /// scheme to a monotype.
2416 /// - `generics`: the set of type parameters and their bounds
2417 /// - `ty`: the base types, which may reference the parameters defined
2420 /// Note that TypeSchemes are also sometimes called "polytypes" (and
2421 /// in fact this struct used to carry that name, so you may find some
2422 /// stray references in a comment or something). We try to reserve the
2423 /// "poly" prefix to refer to higher-ranked things, as in
2426 /// Note that each item also comes with predicates, see
2427 /// `lookup_predicates`.
2428 #[derive(Clone, Debug)]
2429 pub struct TypeScheme<'tcx> {
2430 pub generics: Generics<'tcx>,
2434 /// As `TypeScheme` but for a trait ref.
2435 pub struct TraitDef<'tcx> {
2436 pub unsafety: ast::Unsafety,
2438 /// If `true`, then this trait had the `#[rustc_paren_sugar]`
2439 /// attribute, indicating that it should be used with `Foo()`
2440 /// sugar. This is a temporary thing -- eventually any trait wil
2441 /// be usable with the sugar (or without it).
2442 pub paren_sugar: bool,
2444 /// Generic type definitions. Note that `Self` is listed in here
2445 /// as having a single bound, the trait itself (e.g., in the trait
2446 /// `Eq`, there is a single bound `Self : Eq`). This is so that
2447 /// default methods get to assume that the `Self` parameters
2448 /// implements the trait.
2449 pub generics: Generics<'tcx>,
2451 pub trait_ref: Rc<ty::TraitRef<'tcx>>,
2453 /// A list of the associated types defined in this trait. Useful
2454 /// for resolving `X::Foo` type markers.
2455 pub associated_type_names: Vec<ast::Name>,
2458 /// Records the substitutions used to translate the polytype for an
2459 /// item into the monotype of an item reference.
2461 pub struct ItemSubsts<'tcx> {
2462 pub substs: Substs<'tcx>,
2465 #[derive(Clone, Copy, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
2466 pub enum ClosureKind {
2473 pub fn trait_did(&self, cx: &ctxt) -> ast::DefId {
2474 let result = match *self {
2475 FnClosureKind => cx.lang_items.require(FnTraitLangItem),
2476 FnMutClosureKind => {
2477 cx.lang_items.require(FnMutTraitLangItem)
2479 FnOnceClosureKind => {
2480 cx.lang_items.require(FnOnceTraitLangItem)
2484 Ok(trait_did) => trait_did,
2485 Err(err) => cx.sess.fatal(&err[..]),
2490 pub trait ClosureTyper<'tcx> {
2491 fn tcx(&self) -> &ty::ctxt<'tcx> {
2492 self.param_env().tcx
2495 fn param_env<'a>(&'a self) -> &'a ty::ParameterEnvironment<'a, 'tcx>;
2497 /// Is this a `Fn`, `FnMut` or `FnOnce` closure? During typeck,
2498 /// returns `None` if the kind of this closure has not yet been
2500 fn closure_kind(&self,
2502 -> Option<ty::ClosureKind>;
2504 /// Returns the argument/return types of this closure.
2505 fn closure_type(&self,
2507 substs: &subst::Substs<'tcx>)
2508 -> ty::ClosureTy<'tcx>;
2510 /// Returns the set of all upvars and their transformed
2511 /// types. During typeck, maybe return `None` if the upvar types
2512 /// have not yet been inferred.
2513 fn closure_upvars(&self,
2515 substs: &Substs<'tcx>)
2516 -> Option<Vec<ClosureUpvar<'tcx>>>;
2519 impl<'tcx> CommonTypes<'tcx> {
2520 fn new(arena: &'tcx TypedArena<TyS<'tcx>>,
2521 interner: &mut FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>)
2522 -> CommonTypes<'tcx>
2525 bool: intern_ty(arena, interner, ty_bool),
2526 char: intern_ty(arena, interner, ty_char),
2527 err: intern_ty(arena, interner, ty_err),
2528 int: intern_ty(arena, interner, ty_int(ast::TyIs(false))),
2529 i8: intern_ty(arena, interner, ty_int(ast::TyI8)),
2530 i16: intern_ty(arena, interner, ty_int(ast::TyI16)),
2531 i32: intern_ty(arena, interner, ty_int(ast::TyI32)),
2532 i64: intern_ty(arena, interner, ty_int(ast::TyI64)),
2533 uint: intern_ty(arena, interner, ty_uint(ast::TyUs(false))),
2534 u8: intern_ty(arena, interner, ty_uint(ast::TyU8)),
2535 u16: intern_ty(arena, interner, ty_uint(ast::TyU16)),
2536 u32: intern_ty(arena, interner, ty_uint(ast::TyU32)),
2537 u64: intern_ty(arena, interner, ty_uint(ast::TyU64)),
2538 f32: intern_ty(arena, interner, ty_float(ast::TyF32)),
2539 f64: intern_ty(arena, interner, ty_float(ast::TyF64)),
2544 pub fn mk_ctxt<'tcx>(s: Session,
2545 arenas: &'tcx CtxtArenas<'tcx>,
2547 named_region_map: resolve_lifetime::NamedRegionMap,
2548 map: ast_map::Map<'tcx>,
2549 freevars: RefCell<FreevarMap>,
2550 region_maps: middle::region::RegionMaps,
2551 lang_items: middle::lang_items::LanguageItems,
2552 stability: stability::Index) -> ctxt<'tcx>
2554 let mut interner = FnvHashMap();
2555 let common_types = CommonTypes::new(&arenas.type_, &mut interner);
2559 interner: RefCell::new(interner),
2560 substs_interner: RefCell::new(FnvHashMap()),
2561 bare_fn_interner: RefCell::new(FnvHashMap()),
2562 region_interner: RefCell::new(FnvHashMap()),
2563 types: common_types,
2564 named_region_map: named_region_map,
2565 item_variance_map: RefCell::new(DefIdMap()),
2566 variance_computed: Cell::new(false),
2569 region_maps: region_maps,
2570 node_types: RefCell::new(FnvHashMap()),
2571 item_substs: RefCell::new(NodeMap()),
2572 impl_trait_refs: RefCell::new(NodeMap()),
2573 trait_defs: RefCell::new(DefIdMap()),
2574 predicates: RefCell::new(DefIdMap()),
2575 super_predicates: RefCell::new(DefIdMap()),
2576 object_cast_map: RefCell::new(NodeMap()),
2579 tcache: RefCell::new(DefIdMap()),
2580 rcache: RefCell::new(FnvHashMap()),
2581 short_names_cache: RefCell::new(FnvHashMap()),
2582 tc_cache: RefCell::new(FnvHashMap()),
2583 ast_ty_to_ty_cache: RefCell::new(NodeMap()),
2584 enum_var_cache: RefCell::new(DefIdMap()),
2585 impl_or_trait_items: RefCell::new(DefIdMap()),
2586 trait_item_def_ids: RefCell::new(DefIdMap()),
2587 trait_items_cache: RefCell::new(DefIdMap()),
2588 impl_trait_cache: RefCell::new(DefIdMap()),
2589 ty_param_defs: RefCell::new(NodeMap()),
2590 adjustments: RefCell::new(NodeMap()),
2591 normalized_cache: RefCell::new(FnvHashMap()),
2592 lang_items: lang_items,
2593 provided_method_sources: RefCell::new(DefIdMap()),
2594 struct_fields: RefCell::new(DefIdMap()),
2595 destructor_for_type: RefCell::new(DefIdMap()),
2596 destructors: RefCell::new(DefIdSet()),
2597 trait_impls: RefCell::new(DefIdMap()),
2598 traits_with_default_impls: RefCell::new(DefIdMap()),
2599 inherent_impls: RefCell::new(DefIdMap()),
2600 impl_items: RefCell::new(DefIdMap()),
2601 used_unsafe: RefCell::new(NodeSet()),
2602 used_mut_nodes: RefCell::new(NodeSet()),
2603 populated_external_types: RefCell::new(DefIdSet()),
2604 populated_external_traits: RefCell::new(DefIdSet()),
2605 populated_external_primitive_impls: RefCell::new(DefIdSet()),
2606 upvar_capture_map: RefCell::new(FnvHashMap()),
2607 extern_const_statics: RefCell::new(DefIdMap()),
2608 extern_const_variants: RefCell::new(DefIdMap()),
2609 method_map: RefCell::new(FnvHashMap()),
2610 dependency_formats: RefCell::new(FnvHashMap()),
2611 closure_kinds: RefCell::new(DefIdMap()),
2612 closure_tys: RefCell::new(DefIdMap()),
2613 node_lint_levels: RefCell::new(FnvHashMap()),
2614 transmute_restrictions: RefCell::new(Vec::new()),
2615 stability: RefCell::new(stability),
2616 associated_types: RefCell::new(DefIdMap()),
2617 selection_cache: traits::SelectionCache::new(),
2618 repr_hint_cache: RefCell::new(DefIdMap()),
2619 type_impls_copy_cache: RefCell::new(HashMap::new()),
2620 type_impls_sized_cache: RefCell::new(HashMap::new()),
2621 object_safety_cache: RefCell::new(DefIdMap()),
2622 const_qualif_map: RefCell::new(NodeMap()),
2626 // Type constructors
2628 impl<'tcx> ctxt<'tcx> {
2629 pub fn mk_substs(&self, substs: Substs<'tcx>) -> &'tcx Substs<'tcx> {
2630 if let Some(substs) = self.substs_interner.borrow().get(&substs) {
2634 let substs = self.arenas.substs.alloc(substs);
2635 self.substs_interner.borrow_mut().insert(substs, substs);
2639 /// Create an unsafe fn ty based on a safe fn ty.
2640 pub fn safe_to_unsafe_fn_ty(&self, bare_fn: &BareFnTy<'tcx>) -> Ty<'tcx> {
2641 assert_eq!(bare_fn.unsafety, ast::Unsafety::Normal);
2642 let unsafe_fn_ty_a = self.mk_bare_fn(ty::BareFnTy {
2643 unsafety: ast::Unsafety::Unsafe,
2645 sig: bare_fn.sig.clone()
2647 ty::mk_bare_fn(self, None, unsafe_fn_ty_a)
2650 pub fn mk_bare_fn(&self, bare_fn: BareFnTy<'tcx>) -> &'tcx BareFnTy<'tcx> {
2651 if let Some(bare_fn) = self.bare_fn_interner.borrow().get(&bare_fn) {
2655 let bare_fn = self.arenas.bare_fn.alloc(bare_fn);
2656 self.bare_fn_interner.borrow_mut().insert(bare_fn, bare_fn);
2660 pub fn mk_region(&self, region: Region) -> &'tcx Region {
2661 if let Some(region) = self.region_interner.borrow().get(®ion) {
2665 let region = self.arenas.region.alloc(region);
2666 self.region_interner.borrow_mut().insert(region, region);
2670 pub fn closure_kind(&self, def_id: ast::DefId) -> ty::ClosureKind {
2671 *self.closure_kinds.borrow().get(&def_id).unwrap()
2674 pub fn closure_type(&self,
2676 substs: &subst::Substs<'tcx>)
2677 -> ty::ClosureTy<'tcx>
2679 self.closure_tys.borrow().get(&def_id).unwrap().subst(self, substs)
2682 pub fn type_parameter_def(&self,
2683 node_id: ast::NodeId)
2684 -> TypeParameterDef<'tcx>
2686 self.ty_param_defs.borrow().get(&node_id).unwrap().clone()
2689 pub fn pat_contains_ref_binding(&self, pat: &ast::Pat) -> bool {
2690 pat_util::pat_contains_ref_binding(&self.def_map, pat)
2693 pub fn arm_contains_ref_binding(&self, arm: &ast::Arm) -> bool {
2694 pat_util::arm_contains_ref_binding(&self.def_map, arm)
2698 // Interns a type/name combination, stores the resulting box in cx.interner,
2699 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
2700 pub fn mk_t<'tcx>(cx: &ctxt<'tcx>, st: sty<'tcx>) -> Ty<'tcx> {
2701 let mut interner = cx.interner.borrow_mut();
2702 intern_ty(&cx.arenas.type_, &mut *interner, st)
2705 fn intern_ty<'tcx>(type_arena: &'tcx TypedArena<TyS<'tcx>>,
2706 interner: &mut FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>,
2710 match interner.get(&st) {
2711 Some(ty) => return *ty,
2715 let flags = FlagComputation::for_sty(&st);
2718 () => type_arena.alloc(TyS { sty: st,
2720 region_depth: flags.depth, }),
2723 debug!("Interned type: {:?} Pointer: {:?}",
2724 ty, ty as *const _);
2726 interner.insert(InternedTy { ty: ty }, ty);
2731 struct FlagComputation {
2734 // maximum depth of any bound region that we have seen thus far
2738 impl FlagComputation {
2739 fn new() -> FlagComputation {
2740 FlagComputation { flags: NO_TYPE_FLAGS, depth: 0 }
2743 fn for_sty(st: &sty) -> FlagComputation {
2744 let mut result = FlagComputation::new();
2749 fn add_flags(&mut self, flags: TypeFlags) {
2750 self.flags = self.flags | flags;
2753 fn add_depth(&mut self, depth: u32) {
2754 if depth > self.depth {
2759 /// Adds the flags/depth from a set of types that appear within the current type, but within a
2761 fn add_bound_computation(&mut self, computation: &FlagComputation) {
2762 self.add_flags(computation.flags);
2764 // The types that contributed to `computation` occurred within
2765 // a region binder, so subtract one from the region depth
2766 // within when adding the depth to `self`.
2767 let depth = computation.depth;
2769 self.add_depth(depth - 1);
2773 fn add_sty(&mut self, st: &sty) {
2783 // You might think that we could just return ty_err for
2784 // any type containing ty_err as a component, and get
2785 // rid of the HAS_TY_ERR flag -- likewise for ty_bot (with
2786 // the exception of function types that return bot).
2787 // But doing so caused sporadic memory corruption, and
2788 // neither I (tjc) nor nmatsakis could figure out why,
2789 // so we're doing it this way.
2791 self.add_flags(HAS_TY_ERR)
2794 &ty_param(ref p) => {
2795 if p.space == subst::SelfSpace {
2796 self.add_flags(HAS_SELF);
2798 self.add_flags(HAS_PARAMS);
2802 &ty_closure(_, substs) => {
2803 self.add_substs(substs);
2807 self.add_flags(HAS_TY_INFER)
2810 &ty_enum(_, substs) | &ty_struct(_, substs) => {
2811 self.add_substs(substs);
2814 &ty_projection(ref data) => {
2815 self.add_flags(HAS_PROJECTION);
2816 self.add_projection_ty(data);
2819 &ty_trait(box TyTrait { ref principal, ref bounds }) => {
2820 let mut computation = FlagComputation::new();
2821 computation.add_substs(principal.0.substs);
2822 for projection_bound in &bounds.projection_bounds {
2823 let mut proj_computation = FlagComputation::new();
2824 proj_computation.add_projection_predicate(&projection_bound.0);
2825 computation.add_bound_computation(&proj_computation);
2827 self.add_bound_computation(&computation);
2829 self.add_bounds(bounds);
2832 &ty_uniq(tt) | &ty_vec(tt, _) => {
2840 &ty_rptr(r, ref m) => {
2841 self.add_region(*r);
2845 &ty_tup(ref ts) => {
2846 self.add_tys(&ts[..]);
2849 &ty_bare_fn(_, ref f) => {
2850 self.add_fn_sig(&f.sig);
2855 fn add_ty(&mut self, ty: Ty) {
2856 self.add_flags(ty.flags);
2857 self.add_depth(ty.region_depth);
2860 fn add_tys(&mut self, tys: &[Ty]) {
2866 fn add_fn_sig(&mut self, fn_sig: &PolyFnSig) {
2867 let mut computation = FlagComputation::new();
2869 computation.add_tys(&fn_sig.0.inputs);
2871 if let ty::FnConverging(output) = fn_sig.0.output {
2872 computation.add_ty(output);
2875 self.add_bound_computation(&computation);
2878 fn add_region(&mut self, r: Region) {
2879 self.add_flags(HAS_REGIONS);
2881 ty::ReInfer(_) => { self.add_flags(HAS_RE_INFER); }
2882 ty::ReLateBound(debruijn, _) => {
2883 self.add_flags(HAS_RE_LATE_BOUND);
2884 self.add_depth(debruijn.depth);
2890 fn add_projection_predicate(&mut self, projection_predicate: &ProjectionPredicate) {
2891 self.add_projection_ty(&projection_predicate.projection_ty);
2892 self.add_ty(projection_predicate.ty);
2895 fn add_projection_ty(&mut self, projection_ty: &ProjectionTy) {
2896 self.add_substs(projection_ty.trait_ref.substs);
2899 fn add_substs(&mut self, substs: &Substs) {
2900 self.add_tys(substs.types.as_slice());
2901 match substs.regions {
2902 subst::ErasedRegions => {}
2903 subst::NonerasedRegions(ref regions) => {
2904 for &r in regions.iter() {
2911 fn add_bounds(&mut self, bounds: &ExistentialBounds) {
2912 self.add_region(bounds.region_bound);
2916 pub fn mk_mach_int<'tcx>(tcx: &ctxt<'tcx>, tm: ast::IntTy) -> Ty<'tcx> {
2918 ast::TyIs(_) => tcx.types.int,
2919 ast::TyI8 => tcx.types.i8,
2920 ast::TyI16 => tcx.types.i16,
2921 ast::TyI32 => tcx.types.i32,
2922 ast::TyI64 => tcx.types.i64,
2926 pub fn mk_mach_uint<'tcx>(tcx: &ctxt<'tcx>, tm: ast::UintTy) -> Ty<'tcx> {
2928 ast::TyUs(_) => tcx.types.uint,
2929 ast::TyU8 => tcx.types.u8,
2930 ast::TyU16 => tcx.types.u16,
2931 ast::TyU32 => tcx.types.u32,
2932 ast::TyU64 => tcx.types.u64,
2936 pub fn mk_mach_float<'tcx>(tcx: &ctxt<'tcx>, tm: ast::FloatTy) -> Ty<'tcx> {
2938 ast::TyF32 => tcx.types.f32,
2939 ast::TyF64 => tcx.types.f64,
2943 pub fn mk_str<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2947 pub fn mk_str_slice<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, m: ast::Mutability) -> Ty<'tcx> {
2950 ty: mk_t(cx, ty_str),
2955 pub fn mk_enum<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
2956 // take a copy of substs so that we own the vectors inside
2957 mk_t(cx, ty_enum(did, substs))
2960 pub fn mk_uniq<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { mk_t(cx, ty_uniq(ty)) }
2962 pub fn mk_ptr<'tcx>(cx: &ctxt<'tcx>, tm: mt<'tcx>) -> Ty<'tcx> { mk_t(cx, ty_ptr(tm)) }
2964 pub fn mk_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, tm: mt<'tcx>) -> Ty<'tcx> {
2965 mk_t(cx, ty_rptr(r, tm))
2968 pub fn mk_mut_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
2969 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
2971 pub fn mk_imm_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
2972 mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
2975 pub fn mk_mut_ptr<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2976 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
2979 pub fn mk_imm_ptr<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2980 mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
2983 pub fn mk_nil_ptr<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2984 mk_ptr(cx, mt {ty: mk_nil(cx), mutbl: ast::MutImmutable})
2987 pub fn mk_vec<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>, sz: Option<uint>) -> Ty<'tcx> {
2988 mk_t(cx, ty_vec(ty, sz))
2991 pub fn mk_slice<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, tm: mt<'tcx>) -> Ty<'tcx> {
2994 ty: mk_vec(cx, tm.ty, None),
2999 pub fn mk_tup<'tcx>(cx: &ctxt<'tcx>, ts: Vec<Ty<'tcx>>) -> Ty<'tcx> {
3000 mk_t(cx, ty_tup(ts))
3003 pub fn mk_nil<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
3004 mk_tup(cx, Vec::new())
3007 pub fn mk_bare_fn<'tcx>(cx: &ctxt<'tcx>,
3008 opt_def_id: Option<ast::DefId>,
3009 fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
3010 mk_t(cx, ty_bare_fn(opt_def_id, fty))
3013 pub fn mk_ctor_fn<'tcx>(cx: &ctxt<'tcx>,
3015 input_tys: &[Ty<'tcx>],
3016 output: Ty<'tcx>) -> Ty<'tcx> {
3017 let input_args = input_tys.iter().cloned().collect();
3020 cx.mk_bare_fn(BareFnTy {
3021 unsafety: ast::Unsafety::Normal,
3023 sig: ty::Binder(FnSig {
3025 output: ty::FnConverging(output),
3031 pub fn mk_trait<'tcx>(cx: &ctxt<'tcx>,
3032 principal: ty::PolyTraitRef<'tcx>,
3033 bounds: ExistentialBounds<'tcx>)
3036 assert!(bound_list_is_sorted(&bounds.projection_bounds));
3038 let inner = box TyTrait {
3039 principal: principal,
3042 mk_t(cx, ty_trait(inner))
3045 fn bound_list_is_sorted(bounds: &[ty::PolyProjectionPredicate]) -> bool {
3046 bounds.len() == 0 ||
3047 bounds[1..].iter().enumerate().all(
3048 |(index, bound)| bounds[index].sort_key() <= bound.sort_key())
3051 pub fn sort_bounds_list(bounds: &mut [ty::PolyProjectionPredicate]) {
3052 bounds.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()))
3055 pub fn mk_projection<'tcx>(cx: &ctxt<'tcx>,
3056 trait_ref: Rc<ty::TraitRef<'tcx>>,
3057 item_name: ast::Name)
3059 // take a copy of substs so that we own the vectors inside
3060 let inner = ProjectionTy { trait_ref: trait_ref, item_name: item_name };
3061 mk_t(cx, ty_projection(inner))
3064 pub fn mk_struct<'tcx>(cx: &ctxt<'tcx>, struct_id: ast::DefId,
3065 substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
3066 // take a copy of substs so that we own the vectors inside
3067 mk_t(cx, ty_struct(struct_id, substs))
3070 pub fn mk_closure<'tcx>(cx: &ctxt<'tcx>, closure_id: ast::DefId, substs: &'tcx Substs<'tcx>)
3072 mk_t(cx, ty_closure(closure_id, substs))
3075 pub fn mk_var<'tcx>(cx: &ctxt<'tcx>, v: TyVid) -> Ty<'tcx> {
3076 mk_infer(cx, TyVar(v))
3079 pub fn mk_int_var<'tcx>(cx: &ctxt<'tcx>, v: IntVid) -> Ty<'tcx> {
3080 mk_infer(cx, IntVar(v))
3083 pub fn mk_float_var<'tcx>(cx: &ctxt<'tcx>, v: FloatVid) -> Ty<'tcx> {
3084 mk_infer(cx, FloatVar(v))
3087 pub fn mk_infer<'tcx>(cx: &ctxt<'tcx>, it: InferTy) -> Ty<'tcx> {
3088 mk_t(cx, ty_infer(it))
3091 pub fn mk_param<'tcx>(cx: &ctxt<'tcx>,
3092 space: subst::ParamSpace,
3094 name: ast::Name) -> Ty<'tcx> {
3095 mk_t(cx, ty_param(ParamTy { space: space, idx: index, name: name }))
3098 pub fn mk_self_type<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
3099 mk_param(cx, subst::SelfSpace, 0, special_idents::type_self.name)
3102 pub fn mk_param_from_def<'tcx>(cx: &ctxt<'tcx>, def: &TypeParameterDef) -> Ty<'tcx> {
3103 mk_param(cx, def.space, def.index, def.name)
3106 impl<'tcx> TyS<'tcx> {
3107 /// Iterator that walks `self` and any types reachable from
3108 /// `self`, in depth-first order. Note that just walks the types
3109 /// that appear in `self`, it does not descend into the fields of
3110 /// structs or variants. For example:
3114 /// Foo<Bar<int>> => { Foo<Bar<int>>, Bar<int>, int }
3115 /// [int] => { [int], int }
3117 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
3118 TypeWalker::new(self)
3121 /// Iterator that walks types reachable from `self`, in
3122 /// depth-first order. Note that this is a shallow walk. For
3127 /// Foo<Bar<int>> => { Bar<int>, int }
3128 /// [int] => { int }
3130 pub fn walk_children(&'tcx self) -> TypeWalker<'tcx> {
3131 // Walks type reachable from `self` but not `self
3132 let mut walker = self.walk();
3133 let r = walker.next();
3134 assert_eq!(r, Some(self));
3138 pub fn as_opt_param_ty(&self) -> Option<ty::ParamTy> {
3140 ty::ty_param(ref d) => Some(d.clone()),
3145 pub fn is_param(&self, space: ParamSpace, index: u32) -> bool {
3147 ty::ty_param(ref data) => data.space == space && data.idx == index,
3153 pub fn walk_ty<'tcx, F>(ty_root: Ty<'tcx>, mut f: F)
3154 where F: FnMut(Ty<'tcx>),
3156 for ty in ty_root.walk() {
3161 /// Walks `ty` and any types appearing within `ty`, invoking the
3162 /// callback `f` on each type. If the callback returns false, then the
3163 /// children of the current type are ignored.
3165 /// Note: prefer `ty.walk()` where possible.
3166 pub fn maybe_walk_ty<'tcx,F>(ty_root: Ty<'tcx>, mut f: F)
3167 where F : FnMut(Ty<'tcx>) -> bool
3169 let mut walker = ty_root.walk();
3170 while let Some(ty) = walker.next() {
3172 walker.skip_current_subtree();
3177 // Folds types from the bottom up.
3178 pub fn fold_ty<'tcx, F>(cx: &ctxt<'tcx>, t0: Ty<'tcx>,
3181 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
3183 let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
3188 pub fn new(space: subst::ParamSpace,
3192 ParamTy { space: space, idx: index, name: name }
3195 pub fn for_self() -> ParamTy {
3196 ParamTy::new(subst::SelfSpace, 0, special_idents::type_self.name)
3199 pub fn for_def(def: &TypeParameterDef) -> ParamTy {
3200 ParamTy::new(def.space, def.index, def.name)
3203 pub fn to_ty<'tcx>(self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx> {
3204 ty::mk_param(tcx, self.space, self.idx, self.name)
3207 pub fn is_self(&self) -> bool {
3208 self.space == subst::SelfSpace && self.idx == 0
3212 impl<'tcx> ItemSubsts<'tcx> {
3213 pub fn empty() -> ItemSubsts<'tcx> {
3214 ItemSubsts { substs: Substs::empty() }
3217 pub fn is_noop(&self) -> bool {
3218 self.substs.is_noop()
3222 impl<'tcx> ParamBounds<'tcx> {
3223 pub fn empty() -> ParamBounds<'tcx> {
3225 builtin_bounds: empty_builtin_bounds(),
3226 trait_bounds: Vec::new(),
3227 region_bounds: Vec::new(),
3228 projection_bounds: Vec::new(),
3235 pub fn type_is_nil(ty: Ty) -> bool {
3237 ty_tup(ref tys) => tys.is_empty(),
3242 pub fn type_is_error(ty: Ty) -> bool {
3243 ty.flags.intersects(HAS_TY_ERR)
3246 pub fn type_needs_subst(ty: Ty) -> bool {
3247 ty.flags.intersects(NEEDS_SUBST)
3250 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
3251 tref.substs.types.any(|&ty| type_is_error(ty))
3254 pub fn type_is_ty_var(ty: Ty) -> bool {
3256 ty_infer(TyVar(_)) => true,
3261 pub fn type_is_bool(ty: Ty) -> bool { ty.sty == ty_bool }
3263 pub fn type_is_self(ty: Ty) -> bool {
3265 ty_param(ref p) => p.space == subst::SelfSpace,
3270 fn type_is_slice(ty: Ty) -> bool {
3272 ty_ptr(mt) | ty_rptr(_, mt) => match mt.ty.sty {
3273 ty_vec(_, None) | ty_str => true,
3280 pub fn type_is_vec(ty: Ty) -> bool {
3283 ty_ptr(mt{ty, ..}) | ty_rptr(_, mt{ty, ..}) |
3284 ty_uniq(ty) => match ty.sty {
3285 ty_vec(_, None) => true,
3292 pub fn type_is_structural(ty: Ty) -> bool {
3294 ty_struct(..) | ty_tup(_) | ty_enum(..) |
3295 ty_vec(_, Some(_)) | ty_closure(..) => true,
3296 _ => type_is_slice(ty) | type_is_trait(ty)
3300 pub fn type_is_simd(cx: &ctxt, ty: Ty) -> bool {
3302 ty_struct(did, _) => lookup_simd(cx, did),
3307 pub fn sequence_element_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
3309 ty_vec(ty, _) => ty,
3310 ty_str => mk_mach_uint(cx, ast::TyU8),
3311 _ => cx.sess.bug(&format!("sequence_element_type called on non-sequence value: {}",
3312 ty_to_string(cx, ty))),
3316 pub fn simd_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
3318 ty_struct(did, substs) => {
3319 let fields = lookup_struct_fields(cx, did);
3320 lookup_field_type(cx, did, fields[0].id, substs)
3322 _ => panic!("simd_type called on invalid type")
3326 pub fn simd_size(cx: &ctxt, ty: Ty) -> uint {
3328 ty_struct(did, _) => {
3329 let fields = lookup_struct_fields(cx, did);
3332 _ => panic!("simd_size called on invalid type")
3336 pub fn type_is_region_ptr(ty: Ty) -> bool {
3338 ty_rptr(..) => true,
3343 pub fn type_is_unsafe_ptr(ty: Ty) -> bool {
3345 ty_ptr(_) => return true,
3350 pub fn type_is_unique(ty: Ty) -> bool {
3358 A scalar type is one that denotes an atomic datum, with no sub-components.
3359 (A ty_ptr is scalar because it represents a non-managed pointer, so its
3360 contents are abstract to rustc.)
3362 pub fn type_is_scalar(ty: Ty) -> bool {
3364 ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
3365 ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
3366 ty_bare_fn(..) | ty_ptr(_) => true,
3371 /// Returns true if this type is a floating point type and false otherwise.
3372 pub fn type_is_floating_point(ty: Ty) -> bool {
3374 ty_float(_) => true,
3379 /// Type contents is how the type checker reasons about kinds.
3380 /// They track what kinds of things are found within a type. You can
3381 /// think of them as kind of an "anti-kind". They track the kinds of values
3382 /// and thinks that are contained in types. Having a larger contents for
3383 /// a type tends to rule that type *out* from various kinds. For example,
3384 /// a type that contains a reference is not sendable.
3386 /// The reason we compute type contents and not kinds is that it is
3387 /// easier for me (nmatsakis) to think about what is contained within
3388 /// a type than to think about what is *not* contained within a type.
3389 #[derive(Clone, Copy)]
3390 pub struct TypeContents {
3394 macro_rules! def_type_content_sets {
3395 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
3396 #[allow(non_snake_case)]
3398 use middle::ty::TypeContents;
3400 #[allow(non_upper_case_globals)]
3401 pub const $name: TypeContents = TypeContents { bits: $bits };
3407 def_type_content_sets! {
3409 None = 0b0000_0000__0000_0000__0000,
3411 // Things that are interior to the value (first nibble):
3412 InteriorUnsized = 0b0000_0000__0000_0000__0001,
3413 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
3414 InteriorParam = 0b0000_0000__0000_0000__0100,
3415 // InteriorAll = 0b00000000__00000000__1111,
3417 // Things that are owned by the value (second and third nibbles):
3418 OwnsOwned = 0b0000_0000__0000_0001__0000,
3419 OwnsDtor = 0b0000_0000__0000_0010__0000,
3420 OwnsManaged /* see [1] below */ = 0b0000_0000__0000_0100__0000,
3421 OwnsAll = 0b0000_0000__1111_1111__0000,
3423 // Things that are reachable by the value in any way (fourth nibble):
3424 ReachesBorrowed = 0b0000_0010__0000_0000__0000,
3425 // ReachesManaged /* see [1] below */ = 0b0000_0100__0000_0000__0000,
3426 ReachesMutable = 0b0000_1000__0000_0000__0000,
3427 ReachesFfiUnsafe = 0b0010_0000__0000_0000__0000,
3428 ReachesAll = 0b0011_1111__0000_0000__0000,
3430 // Things that mean drop glue is necessary
3431 NeedsDrop = 0b0000_0000__0000_0111__0000,
3433 // Things that prevent values from being considered sized
3434 Nonsized = 0b0000_0000__0000_0000__0001,
3436 // Bits to set when a managed value is encountered
3438 // [1] Do not set the bits TC::OwnsManaged or
3439 // TC::ReachesManaged directly, instead reference
3440 // TC::Managed to set them both at once.
3441 Managed = 0b0000_0100__0000_0100__0000,
3444 All = 0b1111_1111__1111_1111__1111
3449 pub fn when(&self, cond: bool) -> TypeContents {
3450 if cond {*self} else {TC::None}
3453 pub fn intersects(&self, tc: TypeContents) -> bool {
3454 (self.bits & tc.bits) != 0
3457 pub fn owns_managed(&self) -> bool {
3458 self.intersects(TC::OwnsManaged)
3461 pub fn owns_owned(&self) -> bool {
3462 self.intersects(TC::OwnsOwned)
3465 pub fn is_sized(&self, _: &ctxt) -> bool {
3466 !self.intersects(TC::Nonsized)
3469 pub fn interior_param(&self) -> bool {
3470 self.intersects(TC::InteriorParam)
3473 pub fn interior_unsafe(&self) -> bool {
3474 self.intersects(TC::InteriorUnsafe)
3477 pub fn interior_unsized(&self) -> bool {
3478 self.intersects(TC::InteriorUnsized)
3481 pub fn needs_drop(&self, _: &ctxt) -> bool {
3482 self.intersects(TC::NeedsDrop)
3485 /// Includes only those bits that still apply when indirected through a `Box` pointer
3486 pub fn owned_pointer(&self) -> TypeContents {
3488 *self & (TC::OwnsAll | TC::ReachesAll))
3491 /// Includes only those bits that still apply when indirected through a reference (`&`)
3492 pub fn reference(&self, bits: TypeContents) -> TypeContents {
3494 *self & TC::ReachesAll)
3497 /// Includes only those bits that still apply when indirected through a managed pointer (`@`)
3498 pub fn managed_pointer(&self) -> TypeContents {
3500 *self & TC::ReachesAll)
3503 /// Includes only those bits that still apply when indirected through an unsafe pointer (`*`)
3504 pub fn unsafe_pointer(&self) -> TypeContents {
3505 *self & TC::ReachesAll
3508 pub fn union<T, F>(v: &[T], mut f: F) -> TypeContents where
3509 F: FnMut(&T) -> TypeContents,
3511 v.iter().fold(TC::None, |tc, ty| tc | f(ty))
3514 pub fn has_dtor(&self) -> bool {
3515 self.intersects(TC::OwnsDtor)
3519 impl ops::BitOr for TypeContents {
3520 type Output = TypeContents;
3522 fn bitor(self, other: TypeContents) -> TypeContents {
3523 TypeContents {bits: self.bits | other.bits}
3527 impl ops::BitAnd for TypeContents {
3528 type Output = TypeContents;
3530 fn bitand(self, other: TypeContents) -> TypeContents {
3531 TypeContents {bits: self.bits & other.bits}
3535 impl ops::Sub for TypeContents {
3536 type Output = TypeContents;
3538 fn sub(self, other: TypeContents) -> TypeContents {
3539 TypeContents {bits: self.bits & !other.bits}
3543 impl fmt::Debug for TypeContents {
3544 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3545 write!(f, "TypeContents({:b})", self.bits)
3549 pub fn type_interior_is_unsafe<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
3550 type_contents(cx, ty).interior_unsafe()
3553 pub fn type_contents<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> TypeContents {
3554 return memoized(&cx.tc_cache, ty, |ty| {
3555 tc_ty(cx, ty, &mut FnvHashMap())
3558 fn tc_ty<'tcx>(cx: &ctxt<'tcx>,
3560 cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
3562 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
3563 // private cache for this walk. This is needed in the case of cyclic
3566 // struct List { next: Box<Option<List>>, ... }
3568 // When computing the type contents of such a type, we wind up deeply
3569 // recursing as we go. So when we encounter the recursive reference
3570 // to List, we temporarily use TC::None as its contents. Later we'll
3571 // patch up the cache with the correct value, once we've computed it
3572 // (this is basically a co-inductive process, if that helps). So in
3573 // the end we'll compute TC::OwnsOwned, in this case.
3575 // The problem is, as we are doing the computation, we will also
3576 // compute an *intermediate* contents for, e.g., Option<List> of
3577 // TC::None. This is ok during the computation of List itself, but if
3578 // we stored this intermediate value into cx.tc_cache, then later
3579 // requests for the contents of Option<List> would also yield TC::None
3580 // which is incorrect. This value was computed based on the crutch
3581 // value for the type contents of list. The correct value is
3582 // TC::OwnsOwned. This manifested as issue #4821.
3583 match cache.get(&ty) {
3584 Some(tc) => { return *tc; }
3587 match cx.tc_cache.borrow().get(&ty) { // Must check both caches!
3588 Some(tc) => { return *tc; }
3591 cache.insert(ty, TC::None);
3593 let result = match ty.sty {
3594 // uint and int are ffi-unsafe
3595 ty_uint(ast::TyUs(_)) | ty_int(ast::TyIs(_)) => {
3596 TC::ReachesFfiUnsafe
3599 // Scalar and unique types are sendable, and durable
3600 ty_infer(ty::FreshIntTy(_)) |
3601 ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
3602 ty_bare_fn(..) | ty::ty_char => {
3607 TC::ReachesFfiUnsafe | match typ.sty {
3608 ty_str => TC::OwnsOwned,
3609 _ => tc_ty(cx, typ, cache).owned_pointer(),
3613 ty_trait(box TyTrait { ref bounds, .. }) => {
3614 object_contents(bounds) | TC::ReachesFfiUnsafe | TC::Nonsized
3618 tc_ty(cx, mt.ty, cache).unsafe_pointer()
3621 ty_rptr(r, ref mt) => {
3622 TC::ReachesFfiUnsafe | match mt.ty.sty {
3623 ty_str => borrowed_contents(*r, ast::MutImmutable),
3624 ty_vec(..) => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(*r,
3626 _ => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(*r, mt.mutbl)),
3630 ty_vec(ty, Some(_)) => {
3631 tc_ty(cx, ty, cache)
3634 ty_vec(ty, None) => {
3635 tc_ty(cx, ty, cache) | TC::Nonsized
3637 ty_str => TC::Nonsized,
3639 ty_struct(did, substs) => {
3640 let flds = struct_fields(cx, did, substs);
3642 TypeContents::union(&flds[..],
3643 |f| tc_mt(cx, f.mt, cache));
3645 if !lookup_repr_hints(cx, did).contains(&attr::ReprExtern) {
3646 res = res | TC::ReachesFfiUnsafe;
3649 if ty::has_dtor(cx, did) {
3650 res = res | TC::OwnsDtor;
3652 apply_lang_items(cx, did, res)
3655 ty_closure(did, substs) => {
3656 // FIXME(#14449): `borrowed_contents` below assumes `&mut` closure.
3657 let param_env = ty::empty_parameter_environment(cx);
3658 let upvars = closure_upvars(¶m_env, did, substs).unwrap();
3659 TypeContents::union(&upvars, |f| tc_ty(cx, &f.ty, cache))
3662 ty_tup(ref tys) => {
3663 TypeContents::union(&tys[..],
3664 |ty| tc_ty(cx, *ty, cache))
3667 ty_enum(did, substs) => {
3668 let variants = substd_enum_variants(cx, did, substs);
3670 TypeContents::union(&variants[..], |variant| {
3671 TypeContents::union(&variant.args,
3673 tc_ty(cx, *arg_ty, cache)
3677 if ty::has_dtor(cx, did) {
3678 res = res | TC::OwnsDtor;
3681 if variants.len() != 0 {
3682 let repr_hints = lookup_repr_hints(cx, did);
3683 if repr_hints.len() > 1 {
3684 // this is an error later on, but this type isn't safe
3685 res = res | TC::ReachesFfiUnsafe;
3688 match repr_hints.get(0) {
3689 Some(h) => if !h.is_ffi_safe() {
3690 res = res | TC::ReachesFfiUnsafe;
3694 res = res | TC::ReachesFfiUnsafe;
3696 // We allow ReprAny enums if they are eligible for
3697 // the nullable pointer optimization and the
3698 // contained type is an `extern fn`
3700 if variants.len() == 2 {
3701 let mut data_idx = 0;
3703 if variants[0].args.len() == 0 {
3707 if variants[data_idx].args.len() == 1 {
3708 match variants[data_idx].args[0].sty {
3709 ty_bare_fn(..) => { res = res - TC::ReachesFfiUnsafe; }
3719 apply_lang_items(cx, did, res)
3729 cx.sess.bug("asked to compute contents of error type");
3733 cache.insert(ty, result);
3737 fn tc_mt<'tcx>(cx: &ctxt<'tcx>,
3739 cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
3741 let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
3742 mc | tc_ty(cx, mt.ty, cache)
3745 fn apply_lang_items(cx: &ctxt, did: ast::DefId, tc: TypeContents)
3747 if Some(did) == cx.lang_items.managed_bound() {
3749 } else if Some(did) == cx.lang_items.unsafe_cell_type() {
3750 tc | TC::InteriorUnsafe
3756 /// Type contents due to containing a reference with the region `region` and borrow kind `bk`
3757 fn borrowed_contents(region: ty::Region,
3758 mutbl: ast::Mutability)
3760 let b = match mutbl {
3761 ast::MutMutable => TC::ReachesMutable,
3762 ast::MutImmutable => TC::None,
3764 b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
3767 fn object_contents(bounds: &ExistentialBounds) -> TypeContents {
3768 // These are the type contents of the (opaque) interior. We
3769 // make no assumptions (other than that it cannot have an
3770 // in-scope type parameter within, which makes no sense).
3771 let mut tc = TC::All - TC::InteriorParam;
3772 for bound in &bounds.builtin_bounds {
3773 tc = tc - match bound {
3774 BoundSync | BoundSend | BoundCopy => TC::None,
3775 BoundSized => TC::Nonsized,
3782 fn type_impls_bound<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>,
3783 cache: &RefCell<HashMap<Ty<'tcx>,bool>>,
3785 bound: ty::BuiltinBound,
3789 assert!(!ty::type_needs_infer(ty));
3791 if !type_has_params(ty) && !type_has_self(ty) {
3792 match cache.borrow().get(&ty) {
3795 debug!("type_impls_bound({}, {:?}) = {:?} (cached)",
3796 ty.repr(param_env.tcx),
3804 let infcx = infer::new_infer_ctxt(param_env.tcx);
3806 let is_impld = traits::type_known_to_meet_builtin_bound(&infcx, param_env, ty, bound, span);
3808 debug!("type_impls_bound({}, {:?}) = {:?}",
3809 ty.repr(param_env.tcx),
3813 if !type_has_params(ty) && !type_has_self(ty) {
3814 let old_value = cache.borrow_mut().insert(ty, is_impld);
3815 assert!(old_value.is_none());
3821 pub fn type_moves_by_default<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>,
3826 let tcx = param_env.tcx;
3827 !type_impls_bound(param_env, &tcx.type_impls_copy_cache, ty, ty::BoundCopy, span)
3830 pub fn type_is_sized<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>,
3835 let tcx = param_env.tcx;
3836 type_impls_bound(param_env, &tcx.type_impls_sized_cache, ty, ty::BoundSized, span)
3839 pub fn is_ffi_safe<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
3840 !type_contents(cx, ty).intersects(TC::ReachesFfiUnsafe)
3843 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
3844 pub fn is_instantiable<'tcx>(cx: &ctxt<'tcx>, r_ty: Ty<'tcx>) -> bool {
3845 fn type_requires<'tcx>(cx: &ctxt<'tcx>, seen: &mut Vec<DefId>,
3846 r_ty: Ty<'tcx>, ty: Ty<'tcx>) -> bool {
3847 debug!("type_requires({:?}, {:?})?",
3848 ::util::ppaux::ty_to_string(cx, r_ty),
3849 ::util::ppaux::ty_to_string(cx, ty));
3851 let r = r_ty == ty || subtypes_require(cx, seen, r_ty, ty);
3853 debug!("type_requires({:?}, {:?})? {:?}",
3854 ::util::ppaux::ty_to_string(cx, r_ty),
3855 ::util::ppaux::ty_to_string(cx, ty),
3860 fn subtypes_require<'tcx>(cx: &ctxt<'tcx>, seen: &mut Vec<DefId>,
3861 r_ty: Ty<'tcx>, ty: Ty<'tcx>) -> bool {
3862 debug!("subtypes_require({:?}, {:?})?",
3863 ::util::ppaux::ty_to_string(cx, r_ty),
3864 ::util::ppaux::ty_to_string(cx, ty));
3866 let r = match ty.sty {
3867 // fixed length vectors need special treatment compared to
3868 // normal vectors, since they don't necessarily have the
3869 // possibility to have length zero.
3870 ty_vec(_, Some(0)) => false, // don't need no contents
3871 ty_vec(ty, Some(_)) => type_requires(cx, seen, r_ty, ty),
3882 ty_vec(_, None) => {
3886 type_requires(cx, seen, r_ty, typ)
3888 ty_rptr(_, ref mt) => {
3889 type_requires(cx, seen, r_ty, mt.ty)
3893 false // unsafe ptrs can always be NULL
3900 ty_struct(ref did, _) if seen.contains(did) => {
3904 ty_struct(did, substs) => {
3906 let fields = struct_fields(cx, did, substs);
3907 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
3908 seen.pop().unwrap();
3915 // this check is run on type definitions, so we don't expect to see
3916 // inference by-products or closure types
3917 cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
3921 ts.iter().any(|ty| type_requires(cx, seen, r_ty, *ty))
3924 ty_enum(ref did, _) if seen.contains(did) => {
3928 ty_enum(did, substs) => {
3930 let vs = enum_variants(cx, did);
3931 let r = !vs.is_empty() && vs.iter().all(|variant| {
3932 variant.args.iter().any(|aty| {
3933 let sty = aty.subst(cx, substs);
3934 type_requires(cx, seen, r_ty, sty)
3937 seen.pop().unwrap();
3942 debug!("subtypes_require({:?}, {:?})? {:?}",
3943 ::util::ppaux::ty_to_string(cx, r_ty),
3944 ::util::ppaux::ty_to_string(cx, ty),
3950 let mut seen = Vec::new();
3951 !subtypes_require(cx, &mut seen, r_ty, r_ty)
3954 /// Describes whether a type is representable. For types that are not
3955 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
3956 /// distinguish between types that are recursive with themselves and types that
3957 /// contain a different recursive type. These cases can therefore be treated
3958 /// differently when reporting errors.
3960 /// The ordering of the cases is significant. They are sorted so that cmp::max
3961 /// will keep the "more erroneous" of two values.
3962 #[derive(Copy, PartialOrd, Ord, Eq, PartialEq, Debug)]
3963 pub enum Representability {
3969 /// Check whether a type is representable. This means it cannot contain unboxed
3970 /// structural recursion. This check is needed for structs and enums.
3971 pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>)
3972 -> Representability {
3974 // Iterate until something non-representable is found
3975 fn find_nonrepresentable<'tcx, It: Iterator<Item=Ty<'tcx>>>(cx: &ctxt<'tcx>, sp: Span,
3976 seen: &mut Vec<Ty<'tcx>>,
3978 -> Representability {
3979 iter.fold(Representable,
3980 |r, ty| cmp::max(r, is_type_structurally_recursive(cx, sp, seen, ty)))
3983 fn are_inner_types_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
3984 seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
3985 -> Representability {
3988 find_nonrepresentable(cx, sp, seen, ts.iter().cloned())
3990 // Fixed-length vectors.
3991 // FIXME(#11924) Behavior undecided for zero-length vectors.
3992 ty_vec(ty, Some(_)) => {
3993 is_type_structurally_recursive(cx, sp, seen, ty)
3995 ty_struct(did, substs) => {
3996 let fields = struct_fields(cx, did, substs);
3997 find_nonrepresentable(cx, sp, seen, fields.iter().map(|f| f.mt.ty))
3999 ty_enum(did, substs) => {
4000 let vs = enum_variants(cx, did);
4001 let iter = vs.iter()
4002 .flat_map(|variant| { variant.args.iter() })
4003 .map(|aty| { aty.subst_spanned(cx, substs, Some(sp)) });
4005 find_nonrepresentable(cx, sp, seen, iter)
4008 // this check is run on type definitions, so we don't expect
4009 // to see closure types
4010 cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
4016 fn same_struct_or_enum_def_id(ty: Ty, did: DefId) -> bool {
4018 ty_struct(ty_did, _) | ty_enum(ty_did, _) => {
4025 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
4026 match (&a.sty, &b.sty) {
4027 (&ty_struct(did_a, ref substs_a), &ty_struct(did_b, ref substs_b)) |
4028 (&ty_enum(did_a, ref substs_a), &ty_enum(did_b, ref substs_b)) => {
4033 let types_a = substs_a.types.get_slice(subst::TypeSpace);
4034 let types_b = substs_b.types.get_slice(subst::TypeSpace);
4036 let mut pairs = types_a.iter().zip(types_b.iter());
4038 pairs.all(|(&a, &b)| same_type(a, b))
4046 // Does the type `ty` directly (without indirection through a pointer)
4047 // contain any types on stack `seen`?
4048 fn is_type_structurally_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
4049 seen: &mut Vec<Ty<'tcx>>,
4050 ty: Ty<'tcx>) -> Representability {
4051 debug!("is_type_structurally_recursive: {:?}",
4052 ::util::ppaux::ty_to_string(cx, ty));
4055 ty_struct(did, _) | ty_enum(did, _) => {
4057 // Iterate through stack of previously seen types.
4058 let mut iter = seen.iter();
4060 // The first item in `seen` is the type we are actually curious about.
4061 // We want to return SelfRecursive if this type contains itself.
4062 // It is important that we DON'T take generic parameters into account
4063 // for this check, so that Bar<T> in this example counts as SelfRecursive:
4066 // struct Bar<T> { x: Bar<Foo> }
4069 Some(&seen_type) => {
4070 if same_struct_or_enum_def_id(seen_type, did) {
4071 debug!("SelfRecursive: {:?} contains {:?}",
4072 ::util::ppaux::ty_to_string(cx, seen_type),
4073 ::util::ppaux::ty_to_string(cx, ty));
4074 return SelfRecursive;
4080 // We also need to know whether the first item contains other types that
4081 // are structurally recursive. If we don't catch this case, we will recurse
4082 // infinitely for some inputs.
4084 // It is important that we DO take generic parameters into account here,
4085 // so that code like this is considered SelfRecursive, not ContainsRecursive:
4087 // struct Foo { Option<Option<Foo>> }
4089 for &seen_type in iter {
4090 if same_type(ty, seen_type) {
4091 debug!("ContainsRecursive: {:?} contains {:?}",
4092 ::util::ppaux::ty_to_string(cx, seen_type),
4093 ::util::ppaux::ty_to_string(cx, ty));
4094 return ContainsRecursive;
4099 // For structs and enums, track all previously seen types by pushing them
4100 // onto the 'seen' stack.
4102 let out = are_inner_types_recursive(cx, sp, seen, ty);
4107 // No need to push in other cases.
4108 are_inner_types_recursive(cx, sp, seen, ty)
4113 debug!("is_type_representable: {:?}",
4114 ::util::ppaux::ty_to_string(cx, ty));
4116 // To avoid a stack overflow when checking an enum variant or struct that
4117 // contains a different, structurally recursive type, maintain a stack
4118 // of seen types and check recursion for each of them (issues #3008, #3779).
4119 let mut seen: Vec<Ty> = Vec::new();
4120 let r = is_type_structurally_recursive(cx, sp, &mut seen, ty);
4121 debug!("is_type_representable: {:?} is {:?}",
4122 ::util::ppaux::ty_to_string(cx, ty), r);
4126 pub fn type_is_trait(ty: Ty) -> bool {
4127 type_trait_info(ty).is_some()
4130 pub fn type_trait_info<'tcx>(ty: Ty<'tcx>) -> Option<&'tcx TyTrait<'tcx>> {
4132 ty_uniq(ty) | ty_rptr(_, mt { ty, ..}) | ty_ptr(mt { ty, ..}) => match ty.sty {
4133 ty_trait(ref t) => Some(&**t),
4136 ty_trait(ref t) => Some(&**t),
4141 pub fn type_is_integral(ty: Ty) -> bool {
4143 ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
4148 pub fn type_is_fresh(ty: Ty) -> bool {
4150 ty_infer(FreshTy(_)) => true,
4151 ty_infer(FreshIntTy(_)) => true,
4156 pub fn type_is_uint(ty: Ty) -> bool {
4158 ty_infer(IntVar(_)) | ty_uint(ast::TyUs(_)) => true,
4163 pub fn type_is_char(ty: Ty) -> bool {
4170 pub fn type_is_bare_fn(ty: Ty) -> bool {
4172 ty_bare_fn(..) => true,
4177 pub fn type_is_bare_fn_item(ty: Ty) -> bool {
4179 ty_bare_fn(Some(_), _) => true,
4184 pub fn type_is_fp(ty: Ty) -> bool {
4186 ty_infer(FloatVar(_)) | ty_float(_) => true,
4191 pub fn type_is_numeric(ty: Ty) -> bool {
4192 return type_is_integral(ty) || type_is_fp(ty);
4195 pub fn type_is_signed(ty: Ty) -> bool {
4202 pub fn type_is_machine(ty: Ty) -> bool {
4204 ty_int(ast::TyIs(_)) | ty_uint(ast::TyUs(_)) => false,
4205 ty_int(..) | ty_uint(..) | ty_float(..) => true,
4210 // Whether a type is enum like, that is an enum type with only nullary
4212 pub fn type_is_c_like_enum(cx: &ctxt, ty: Ty) -> bool {
4214 ty_enum(did, _) => {
4215 let variants = enum_variants(cx, did);
4216 if variants.len() == 0 {
4219 variants.iter().all(|v| v.args.len() == 0)
4226 // Returns the type and mutability of *ty.
4228 // The parameter `explicit` indicates if this is an *explicit* dereference.
4229 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
4230 pub fn deref<'tcx>(ty: Ty<'tcx>, explicit: bool) -> Option<mt<'tcx>> {
4235 mutbl: ast::MutImmutable,
4238 ty_rptr(_, mt) => Some(mt),
4239 ty_ptr(mt) if explicit => Some(mt),
4244 pub fn type_content<'tcx>(ty: Ty<'tcx>) -> Ty<'tcx> {
4247 ty_rptr(_, mt) |ty_ptr(mt) => mt.ty,
4252 // Returns the type of ty[i]
4253 pub fn index<'tcx>(ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
4255 ty_vec(ty, _) => Some(ty),
4260 // Returns the type of elements contained within an 'array-like' type.
4261 // This is exactly the same as the above, except it supports strings,
4262 // which can't actually be indexed.
4263 pub fn array_element_ty<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
4265 ty_vec(ty, _) => Some(ty),
4266 ty_str => Some(tcx.types.u8),
4271 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
4272 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
4273 pub fn positional_element_ty<'tcx>(cx: &ctxt<'tcx>,
4276 variant: Option<ast::DefId>) -> Option<Ty<'tcx>> {
4278 match (&ty.sty, variant) {
4279 (&ty_tup(ref v), None) => v.get(i).cloned(),
4282 (&ty_struct(def_id, substs), None) => lookup_struct_fields(cx, def_id)
4284 .map(|&t|lookup_item_type(cx, t.id).ty.subst(cx, substs)),
4286 (&ty_enum(def_id, substs), Some(variant_def_id)) => {
4287 let variant_info = enum_variant_with_id(cx, def_id, variant_def_id);
4288 variant_info.args.get(i).map(|t|t.subst(cx, substs))
4291 (&ty_enum(def_id, substs), None) => {
4292 assert!(enum_is_univariant(cx, def_id));
4293 let enum_variants = enum_variants(cx, def_id);
4294 let variant_info = &(*enum_variants)[0];
4295 variant_info.args.get(i).map(|t|t.subst(cx, substs))
4302 /// Returns the type of element at field `n` in struct or struct-like type `t`.
4303 /// For an enum `t`, `variant` must be some def id.
4304 pub fn named_element_ty<'tcx>(cx: &ctxt<'tcx>,
4307 variant: Option<ast::DefId>) -> Option<Ty<'tcx>> {
4309 match (&ty.sty, variant) {
4310 (&ty_struct(def_id, substs), None) => {
4311 let r = lookup_struct_fields(cx, def_id);
4312 r.iter().find(|f| f.name == n)
4313 .map(|&f| lookup_field_type(cx, def_id, f.id, substs))
4315 (&ty_enum(def_id, substs), Some(variant_def_id)) => {
4316 let variant_info = enum_variant_with_id(cx, def_id, variant_def_id);
4317 variant_info.arg_names.as_ref()
4318 .expect("must have struct enum variant if accessing a named fields")
4319 .iter().zip(variant_info.args.iter())
4320 .find(|&(ident, _)| ident.name == n)
4321 .map(|(_ident, arg_t)| arg_t.subst(cx, substs))
4327 pub fn impl_id_to_trait_ref<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId)
4328 -> Rc<ty::TraitRef<'tcx>> {
4329 match cx.impl_trait_refs.borrow().get(&id) {
4330 Some(ty) => ty.clone(),
4331 None => cx.sess.bug(
4332 &format!("impl_id_to_trait_ref: no trait ref for impl `{}`",
4333 cx.map.node_to_string(id)))
4337 pub fn node_id_to_type<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> Ty<'tcx> {
4338 match node_id_to_type_opt(cx, id) {
4340 None => cx.sess.bug(
4341 &format!("node_id_to_type: no type for node `{}`",
4342 cx.map.node_to_string(id)))
4346 pub fn node_id_to_type_opt<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> Option<Ty<'tcx>> {
4347 match cx.node_types.borrow().get(&id) {
4348 Some(&ty) => Some(ty),
4353 pub fn node_id_item_substs<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> ItemSubsts<'tcx> {
4354 match cx.item_substs.borrow().get(&id) {
4355 None => ItemSubsts::empty(),
4356 Some(ts) => ts.clone(),
4360 pub fn fn_is_variadic(fty: Ty) -> bool {
4362 ty_bare_fn(_, ref f) => f.sig.0.variadic,
4364 panic!("fn_is_variadic() called on non-fn type: {:?}", s)
4369 pub fn ty_fn_sig<'tcx>(fty: Ty<'tcx>) -> &'tcx PolyFnSig<'tcx> {
4371 ty_bare_fn(_, ref f) => &f.sig,
4373 panic!("ty_fn_sig() called on non-fn type: {:?}", s)
4378 /// Returns the ABI of the given function.
4379 pub fn ty_fn_abi(fty: Ty) -> abi::Abi {
4381 ty_bare_fn(_, ref f) => f.abi,
4382 _ => panic!("ty_fn_abi() called on non-fn type"),
4386 // Type accessors for substructures of types
4387 pub fn ty_fn_args<'tcx>(fty: Ty<'tcx>) -> ty::Binder<Vec<Ty<'tcx>>> {
4388 ty_fn_sig(fty).inputs()
4391 pub fn ty_fn_ret<'tcx>(fty: Ty<'tcx>) -> Binder<FnOutput<'tcx>> {
4393 ty_bare_fn(_, ref f) => f.sig.output(),
4395 panic!("ty_fn_ret() called on non-fn type: {:?}", s)
4400 pub fn is_fn_ty(fty: Ty) -> bool {
4402 ty_bare_fn(..) => true,
4407 pub fn ty_region(tcx: &ctxt,
4411 ty_rptr(r, _) => *r,
4415 &format!("ty_region() invoked on an inappropriate ty: {:?}",
4421 pub fn free_region_from_def(outlives_extent: region::DestructionScopeData,
4422 def: &RegionParameterDef)
4426 ty::ReFree(ty::FreeRegion { scope: outlives_extent,
4427 bound_region: ty::BrNamed(def.def_id,
4429 debug!("free_region_from_def returns {:?}", ret);
4433 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
4434 // doesn't provide type parameter substitutions.
4435 pub fn pat_ty<'tcx>(cx: &ctxt<'tcx>, pat: &ast::Pat) -> Ty<'tcx> {
4436 return node_id_to_type(cx, pat.id);
4438 pub fn pat_ty_opt<'tcx>(cx: &ctxt<'tcx>, pat: &ast::Pat) -> Option<Ty<'tcx>> {
4439 return node_id_to_type_opt(cx, pat.id);
4443 // Returns the type of an expression as a monotype.
4445 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
4446 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
4447 // auto-ref. The type returned by this function does not consider such
4448 // adjustments. See `expr_ty_adjusted()` instead.
4450 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
4451 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
4452 // instead of "fn(ty) -> T with T = int".
4453 pub fn expr_ty<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Ty<'tcx> {
4454 return node_id_to_type(cx, expr.id);
4457 pub fn expr_ty_opt<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Option<Ty<'tcx>> {
4458 return node_id_to_type_opt(cx, expr.id);
4461 /// Returns the type of `expr`, considering any `AutoAdjustment`
4462 /// entry recorded for that expression.
4464 /// It would almost certainly be better to store the adjusted ty in with
4465 /// the `AutoAdjustment`, but I opted not to do this because it would
4466 /// require serializing and deserializing the type and, although that's not
4467 /// hard to do, I just hate that code so much I didn't want to touch it
4468 /// unless it was to fix it properly, which seemed a distraction from the
4469 /// task at hand! -nmatsakis
4470 pub fn expr_ty_adjusted<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Ty<'tcx> {
4471 adjust_ty(cx, expr.span, expr.id, expr_ty(cx, expr),
4472 cx.adjustments.borrow().get(&expr.id),
4473 |method_call| cx.method_map.borrow().get(&method_call).map(|method| method.ty))
4476 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
4477 match cx.map.find(id) {
4478 Some(ast_map::NodeExpr(e)) => {
4482 cx.sess.bug(&format!("Node id {} is not an expr: {:?}",
4487 cx.sess.bug(&format!("Node id {} is not present \
4488 in the node map", id));
4493 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
4494 match cx.map.find(id) {
4495 Some(ast_map::NodeLocal(pat)) => {
4497 ast::PatIdent(_, ref path1, _) => {
4498 token::get_ident(path1.node)
4502 &format!("Variable id {} maps to {:?}, not local",
4509 cx.sess.bug(&format!("Variable id {} maps to {:?}, not local",
4516 /// See `expr_ty_adjusted`
4517 pub fn adjust_ty<'tcx, F>(cx: &ctxt<'tcx>,
4519 expr_id: ast::NodeId,
4520 unadjusted_ty: Ty<'tcx>,
4521 adjustment: Option<&AutoAdjustment<'tcx>>,
4524 F: FnMut(MethodCall) -> Option<Ty<'tcx>>,
4526 if let ty_err = unadjusted_ty.sty {
4527 return unadjusted_ty;
4530 return match adjustment {
4531 Some(adjustment) => {
4533 AdjustReifyFnPointer(_) => {
4534 match unadjusted_ty.sty {
4535 ty::ty_bare_fn(Some(_), b) => {
4536 ty::mk_bare_fn(cx, None, b)
4540 &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
4547 AdjustUnsafeFnPointer => {
4548 match unadjusted_ty.sty {
4549 ty::ty_bare_fn(None, b) => cx.safe_to_unsafe_fn_ty(b),
4552 &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
4559 AdjustDerefRef(ref adj) => {
4560 let mut adjusted_ty = unadjusted_ty;
4562 if !ty::type_is_error(adjusted_ty) {
4563 for i in 0..adj.autoderefs {
4564 let method_call = MethodCall::autoderef(expr_id, i);
4565 match method_type(method_call) {
4566 Some(method_ty) => {
4567 // overloaded deref operators have all late-bound
4568 // regions fully instantiated and coverge
4570 ty::no_late_bound_regions(cx,
4571 &ty_fn_ret(method_ty)).unwrap();
4572 adjusted_ty = fn_ret.unwrap();
4576 match deref(adjusted_ty, true) {
4577 Some(mt) => { adjusted_ty = mt.ty; }
4581 &format!("the {}th autoderef failed: \
4584 ty_to_string(cx, adjusted_ty))
4591 adjust_ty_for_autoref(cx, span, adjusted_ty, adj.autoref.as_ref())
4595 None => unadjusted_ty
4599 pub fn adjust_ty_for_autoref<'tcx>(cx: &ctxt<'tcx>,
4602 autoref: Option<&AutoRef<'tcx>>)
4608 Some(&AutoPtr(r, m, ref a)) => {
4609 let adjusted_ty = match a {
4610 &Some(box ref a) => adjust_ty_for_autoref(cx, span, ty, Some(a)),
4613 mk_rptr(cx, cx.mk_region(r), mt {
4619 Some(&AutoUnsafe(m, ref a)) => {
4620 let adjusted_ty = match a {
4621 &Some(box ref a) => adjust_ty_for_autoref(cx, span, ty, Some(a)),
4624 mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
4627 Some(&AutoUnsize(ref k)) => unsize_ty(cx, ty, k, span),
4629 Some(&AutoUnsizeUniq(ref k)) => ty::mk_uniq(cx, unsize_ty(cx, ty, k, span)),
4633 // Take a sized type and a sizing adjustment and produce an unsized version of
4635 pub fn unsize_ty<'tcx>(cx: &ctxt<'tcx>,
4637 kind: &UnsizeKind<'tcx>,
4641 &UnsizeLength(len) => match ty.sty {
4642 ty_vec(ty, Some(n)) => {
4644 mk_vec(cx, ty, None)
4646 _ => cx.sess.span_bug(span,
4647 &format!("UnsizeLength with bad sty: {:?}",
4648 ty_to_string(cx, ty)))
4650 &UnsizeStruct(box ref k, tp_index) => match ty.sty {
4651 ty_struct(did, substs) => {
4652 let ty_substs = substs.types.get_slice(subst::TypeSpace);
4653 let new_ty = unsize_ty(cx, ty_substs[tp_index], k, span);
4654 let mut unsized_substs = substs.clone();
4655 unsized_substs.types.get_mut_slice(subst::TypeSpace)[tp_index] = new_ty;
4656 mk_struct(cx, did, cx.mk_substs(unsized_substs))
4658 _ => cx.sess.span_bug(span,
4659 &format!("UnsizeStruct with bad sty: {:?}",
4660 ty_to_string(cx, ty)))
4662 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
4663 mk_trait(cx, principal.clone(), bounds.clone())
4665 &UnsizeUpcast(target_ty) => {
4671 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> def::Def {
4672 match tcx.def_map.borrow().get(&expr.id) {
4673 Some(def) => def.full_def(),
4675 tcx.sess.span_bug(expr.span, &format!(
4676 "no def-map entry for expr {}", expr.id));
4681 pub fn expr_is_lval(tcx: &ctxt, e: &ast::Expr) -> bool {
4682 match expr_kind(tcx, e) {
4684 RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
4688 /// We categorize expressions into three kinds. The distinction between
4689 /// lvalue/rvalue is fundamental to the language. The distinction between the
4690 /// two kinds of rvalues is an artifact of trans which reflects how we will
4691 /// generate code for that kind of expression. See trans/expr.rs for more
4701 pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
4702 if tcx.method_map.borrow().contains_key(&MethodCall::expr(expr.id)) {
4703 // Overloaded operations are generally calls, and hence they are
4704 // generated via DPS, but there are a few exceptions:
4705 return match expr.node {
4706 // `a += b` has a unit result.
4707 ast::ExprAssignOp(..) => RvalueStmtExpr,
4709 // the deref method invoked for `*a` always yields an `&T`
4710 ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
4712 // the index method invoked for `a[i]` always yields an `&T`
4713 ast::ExprIndex(..) => LvalueExpr,
4715 // in the general case, result could be any type, use DPS
4721 ast::ExprPath(..) => {
4722 match resolve_expr(tcx, expr) {
4723 def::DefVariant(tid, vid, _) => {
4724 let variant_info = enum_variant_with_id(tcx, tid, vid);
4725 if variant_info.args.len() > 0 {
4734 def::DefStruct(_) => {
4735 match tcx.node_types.borrow().get(&expr.id) {
4736 Some(ty) => match ty.sty {
4737 ty_bare_fn(..) => RvalueDatumExpr,
4740 // See ExprCast below for why types might be missing.
4741 None => RvalueDatumExpr
4745 // Special case: A unit like struct's constructor must be called without () at the
4746 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
4747 // of unit structs this is should not be interpreted as function pointer but as
4748 // call to the constructor.
4749 def::DefFn(_, true) => RvalueDpsExpr,
4751 // Fn pointers are just scalar values.
4752 def::DefFn(..) | def::DefMethod(..) => RvalueDatumExpr,
4754 // Note: there is actually a good case to be made that
4755 // DefArg's, particularly those of immediate type, ought to
4756 // considered rvalues.
4757 def::DefStatic(..) |
4759 def::DefLocal(..) => LvalueExpr,
4761 def::DefConst(..) => RvalueDatumExpr,
4766 &format!("uncategorized def for expr {}: {:?}",
4773 ast::ExprUnary(ast::UnDeref, _) |
4774 ast::ExprField(..) |
4775 ast::ExprTupField(..) |
4776 ast::ExprIndex(..) => {
4781 ast::ExprMethodCall(..) |
4782 ast::ExprStruct(..) |
4783 ast::ExprRange(..) |
4786 ast::ExprMatch(..) |
4787 ast::ExprClosure(..) |
4788 ast::ExprBlock(..) |
4789 ast::ExprRepeat(..) |
4790 ast::ExprVec(..) => {
4794 ast::ExprIfLet(..) => {
4795 tcx.sess.span_bug(expr.span, "non-desugared ExprIfLet");
4797 ast::ExprWhileLet(..) => {
4798 tcx.sess.span_bug(expr.span, "non-desugared ExprWhileLet");
4801 ast::ExprForLoop(..) => {
4802 tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
4805 ast::ExprLit(ref lit) if lit_is_str(&**lit) => {
4809 ast::ExprCast(..) => {
4810 match tcx.node_types.borrow().get(&expr.id) {
4812 if type_is_trait(ty) {
4819 // Technically, it should not happen that the expr is not
4820 // present within the table. However, it DOES happen
4821 // during type check, because the final types from the
4822 // expressions are not yet recorded in the tcx. At that
4823 // time, though, we are only interested in knowing lvalue
4824 // vs rvalue. It would be better to base this decision on
4825 // the AST type in cast node---but (at the time of this
4826 // writing) it's not easy to distinguish casts to traits
4827 // from other casts based on the AST. This should be
4828 // easier in the future, when casts to traits
4829 // would like @Foo, Box<Foo>, or &Foo.
4835 ast::ExprBreak(..) |
4836 ast::ExprAgain(..) |
4838 ast::ExprWhile(..) |
4840 ast::ExprAssign(..) |
4841 ast::ExprInlineAsm(..) |
4842 ast::ExprAssignOp(..) => {
4846 ast::ExprLit(_) | // Note: LitStr is carved out above
4847 ast::ExprUnary(..) |
4848 ast::ExprBox(None, _) |
4849 ast::ExprAddrOf(..) |
4850 ast::ExprBinary(..) => {
4854 ast::ExprBox(Some(ref place), _) => {
4855 // Special case `Box<T>` for now:
4856 let def_id = match tcx.def_map.borrow().get(&place.id) {
4857 Some(def) => def.def_id(),
4858 None => panic!("no def for place"),
4860 if tcx.lang_items.exchange_heap() == Some(def_id) {
4867 ast::ExprParen(ref e) => expr_kind(tcx, &**e),
4869 ast::ExprMac(..) => {
4872 "macro expression remains after expansion");
4877 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
4879 ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
4882 ast::StmtMac(..) => panic!("unexpanded macro in trans")
4886 pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
4889 for f in fields { if f.name == name { return i; } i += 1; }
4890 tcx.sess.bug(&format!(
4891 "no field named `{}` found in the list of fields `{:?}`",
4892 token::get_name(name),
4894 .map(|f| token::get_name(f.name).to_string())
4895 .collect::<Vec<String>>()));
4898 pub fn impl_or_trait_item_idx(id: ast::Name, trait_items: &[ImplOrTraitItem])
4900 trait_items.iter().position(|m| m.name() == id)
4903 pub fn ty_sort_string<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> String {
4905 ty_bool | ty_char | ty_int(_) |
4906 ty_uint(_) | ty_float(_) | ty_str => {
4907 ::util::ppaux::ty_to_string(cx, ty)
4909 ty_tup(ref tys) if tys.is_empty() => ::util::ppaux::ty_to_string(cx, ty),
4911 ty_enum(id, _) => format!("enum `{}`", item_path_str(cx, id)),
4912 ty_uniq(_) => "box".to_string(),
4913 ty_vec(_, Some(n)) => format!("array of {} elements", n),
4914 ty_vec(_, None) => "slice".to_string(),
4915 ty_ptr(_) => "*-ptr".to_string(),
4916 ty_rptr(_, _) => "&-ptr".to_string(),
4917 ty_bare_fn(Some(_), _) => format!("fn item"),
4918 ty_bare_fn(None, _) => "fn pointer".to_string(),
4919 ty_trait(ref inner) => {
4920 format!("trait {}", item_path_str(cx, inner.principal_def_id()))
4922 ty_struct(id, _) => {
4923 format!("struct `{}`", item_path_str(cx, id))
4925 ty_closure(..) => "closure".to_string(),
4926 ty_tup(_) => "tuple".to_string(),
4927 ty_infer(TyVar(_)) => "inferred type".to_string(),
4928 ty_infer(IntVar(_)) => "integral variable".to_string(),
4929 ty_infer(FloatVar(_)) => "floating-point variable".to_string(),
4930 ty_infer(FreshTy(_)) => "skolemized type".to_string(),
4931 ty_infer(FreshIntTy(_)) => "skolemized integral type".to_string(),
4932 ty_projection(_) => "associated type".to_string(),
4933 ty_param(ref p) => {
4934 if p.space == subst::SelfSpace {
4937 "type parameter".to_string()
4940 ty_err => "type error".to_string(),
4944 impl<'tcx> Repr<'tcx> for ty::type_err<'tcx> {
4945 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
4946 ty::type_err_to_str(tcx, self)
4950 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
4951 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
4952 /// afterwards to present additional details, particularly when it comes to lifetime-related
4954 pub fn type_err_to_str<'tcx>(cx: &ctxt<'tcx>, err: &type_err<'tcx>) -> String {
4956 terr_cyclic_ty => "cyclic type of infinite size".to_string(),
4957 terr_mismatch => "types differ".to_string(),
4958 terr_unsafety_mismatch(values) => {
4959 format!("expected {} fn, found {} fn",
4963 terr_abi_mismatch(values) => {
4964 format!("expected {} fn, found {} fn",
4968 terr_mutability => "values differ in mutability".to_string(),
4969 terr_box_mutability => {
4970 "boxed values differ in mutability".to_string()
4972 terr_vec_mutability => "vectors differ in mutability".to_string(),
4973 terr_ptr_mutability => "pointers differ in mutability".to_string(),
4974 terr_ref_mutability => "references differ in mutability".to_string(),
4975 terr_ty_param_size(values) => {
4976 format!("expected a type with {} type params, \
4977 found one with {} type params",
4981 terr_fixed_array_size(values) => {
4982 format!("expected an array with a fixed size of {} elements, \
4983 found one with {} elements",
4987 terr_tuple_size(values) => {
4988 format!("expected a tuple with {} elements, \
4989 found one with {} elements",
4994 "incorrect number of function parameters".to_string()
4996 terr_regions_does_not_outlive(..) => {
4997 "lifetime mismatch".to_string()
4999 terr_regions_not_same(..) => {
5000 "lifetimes are not the same".to_string()
5002 terr_regions_no_overlap(..) => {
5003 "lifetimes do not intersect".to_string()
5005 terr_regions_insufficiently_polymorphic(br, _) => {
5006 format!("expected bound lifetime parameter {}, \
5007 found concrete lifetime",
5008 bound_region_ptr_to_string(cx, br))
5010 terr_regions_overly_polymorphic(br, _) => {
5011 format!("expected concrete lifetime, \
5012 found bound lifetime parameter {}",
5013 bound_region_ptr_to_string(cx, br))
5015 terr_sorts(values) => {
5016 // A naive approach to making sure that we're not reporting silly errors such as:
5017 // (expected closure, found closure).
5018 let expected_str = ty_sort_string(cx, values.expected);
5019 let found_str = ty_sort_string(cx, values.found);
5020 if expected_str == found_str {
5021 format!("expected {}, found a different {}", expected_str, found_str)
5023 format!("expected {}, found {}", expected_str, found_str)
5026 terr_traits(values) => {
5027 format!("expected trait `{}`, found trait `{}`",
5028 item_path_str(cx, values.expected),
5029 item_path_str(cx, values.found))
5031 terr_builtin_bounds(values) => {
5032 if values.expected.is_empty() {
5033 format!("expected no bounds, found `{}`",
5034 values.found.user_string(cx))
5035 } else if values.found.is_empty() {
5036 format!("expected bounds `{}`, found no bounds",
5037 values.expected.user_string(cx))
5039 format!("expected bounds `{}`, found bounds `{}`",
5040 values.expected.user_string(cx),
5041 values.found.user_string(cx))
5044 terr_integer_as_char => {
5045 "expected an integral type, found `char`".to_string()
5047 terr_int_mismatch(ref values) => {
5048 format!("expected `{:?}`, found `{:?}`",
5052 terr_float_mismatch(ref values) => {
5053 format!("expected `{:?}`, found `{:?}`",
5057 terr_variadic_mismatch(ref values) => {
5058 format!("expected {} fn, found {} function",
5059 if values.expected { "variadic" } else { "non-variadic" },
5060 if values.found { "variadic" } else { "non-variadic" })
5062 terr_convergence_mismatch(ref values) => {
5063 format!("expected {} fn, found {} function",
5064 if values.expected { "converging" } else { "diverging" },
5065 if values.found { "converging" } else { "diverging" })
5067 terr_projection_name_mismatched(ref values) => {
5068 format!("expected {}, found {}",
5069 token::get_name(values.expected),
5070 token::get_name(values.found))
5072 terr_projection_bounds_length(ref values) => {
5073 format!("expected {} associated type bindings, found {}",
5080 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
5082 terr_regions_does_not_outlive(subregion, superregion) => {
5083 note_and_explain_region(cx, "", subregion, "...");
5084 note_and_explain_region(cx, "...does not necessarily outlive ",
5087 terr_regions_not_same(region1, region2) => {
5088 note_and_explain_region(cx, "", region1, "...");
5089 note_and_explain_region(cx, "...is not the same lifetime as ",
5092 terr_regions_no_overlap(region1, region2) => {
5093 note_and_explain_region(cx, "", region1, "...");
5094 note_and_explain_region(cx, "...does not overlap ",
5097 terr_regions_insufficiently_polymorphic(_, conc_region) => {
5098 note_and_explain_region(cx,
5099 "concrete lifetime that was found is ",
5102 terr_regions_overly_polymorphic(_, ty::ReInfer(ty::ReVar(_))) => {
5103 // don't bother to print out the message below for
5104 // inference variables, it's not very illuminating.
5106 terr_regions_overly_polymorphic(_, conc_region) => {
5107 note_and_explain_region(cx,
5108 "expected concrete lifetime is ",
5115 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
5116 cx.provided_method_sources.borrow().get(&id).cloned()
5119 pub fn provided_trait_methods<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5120 -> Vec<Rc<Method<'tcx>>> {
5122 if let ItemTrait(_, _, _, ref ms) = cx.map.expect_item(id.node).node {
5123 ms.iter().filter_map(|ti| {
5124 if let ast::MethodTraitItem(_, Some(_)) = ti.node {
5125 match impl_or_trait_item(cx, ast_util::local_def(ti.id)) {
5126 MethodTraitItem(m) => Some(m),
5127 TypeTraitItem(_) => {
5128 cx.sess.bug("provided_trait_methods(): \
5129 associated type found from \
5130 looking up ProvidedMethod?!")
5138 cx.sess.bug(&format!("provided_trait_methods: `{:?}` is not a trait", id))
5141 csearch::get_provided_trait_methods(cx, id)
5145 /// Helper for looking things up in the various maps that are populated during
5146 /// typeck::collect (e.g., `cx.impl_or_trait_items`, `cx.tcache`, etc). All of
5147 /// these share the pattern that if the id is local, it should have been loaded
5148 /// into the map by the `typeck::collect` phase. If the def-id is external,
5149 /// then we have to go consult the crate loading code (and cache the result for
5151 fn lookup_locally_or_in_crate_store<V, F>(descr: &str,
5153 map: &mut DefIdMap<V>,
5154 load_external: F) -> V where
5158 match map.get(&def_id).cloned() {
5159 Some(v) => { return v; }
5163 if def_id.krate == ast::LOCAL_CRATE {
5164 panic!("No def'n found for {:?} in tcx.{}", def_id, descr);
5166 let v = load_external();
5167 map.insert(def_id, v.clone());
5171 pub fn trait_item<'tcx>(cx: &ctxt<'tcx>, trait_did: ast::DefId, idx: uint)
5172 -> ImplOrTraitItem<'tcx> {
5173 let method_def_id = (*ty::trait_item_def_ids(cx, trait_did))[idx].def_id();
5174 impl_or_trait_item(cx, method_def_id)
5177 pub fn trait_items<'tcx>(cx: &ctxt<'tcx>, trait_did: ast::DefId)
5178 -> Rc<Vec<ImplOrTraitItem<'tcx>>> {
5179 let mut trait_items = cx.trait_items_cache.borrow_mut();
5180 match trait_items.get(&trait_did).cloned() {
5181 Some(trait_items) => trait_items,
5183 let def_ids = ty::trait_item_def_ids(cx, trait_did);
5184 let items: Rc<Vec<ImplOrTraitItem>> =
5185 Rc::new(def_ids.iter()
5186 .map(|d| impl_or_trait_item(cx, d.def_id()))
5188 trait_items.insert(trait_did, items.clone());
5194 pub fn trait_impl_polarity<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5195 -> Option<ast::ImplPolarity> {
5196 if id.krate == ast::LOCAL_CRATE {
5197 match cx.map.find(id.node) {
5198 Some(ast_map::NodeItem(item)) => {
5200 ast::ItemImpl(_, polarity, _, _, _, _) => Some(polarity),
5207 csearch::get_impl_polarity(cx, id)
5211 pub fn impl_or_trait_item<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5212 -> ImplOrTraitItem<'tcx> {
5213 lookup_locally_or_in_crate_store("impl_or_trait_items",
5215 &mut *cx.impl_or_trait_items
5218 csearch::get_impl_or_trait_item(cx, id)
5222 /// Returns true if the given ID refers to an associated type and false if it
5223 /// refers to anything else.
5224 pub fn is_associated_type(cx: &ctxt, id: ast::DefId) -> bool {
5225 memoized(&cx.associated_types, id, |id: ast::DefId| {
5226 if id.krate == ast::LOCAL_CRATE {
5227 match cx.impl_or_trait_items.borrow().get(&id) {
5230 TypeTraitItem(_) => true,
5231 MethodTraitItem(_) => false,
5237 csearch::is_associated_type(&cx.sess.cstore, id)
5242 /// Returns the parameter index that the given associated type corresponds to.
5243 pub fn associated_type_parameter_index(cx: &ctxt,
5244 trait_def: &TraitDef,
5245 associated_type_id: ast::DefId)
5247 for type_parameter_def in trait_def.generics.types.iter() {
5248 if type_parameter_def.def_id == associated_type_id {
5249 return type_parameter_def.index as uint
5252 cx.sess.bug("couldn't find associated type parameter index")
5255 pub fn trait_item_def_ids(cx: &ctxt, id: ast::DefId)
5256 -> Rc<Vec<ImplOrTraitItemId>> {
5257 lookup_locally_or_in_crate_store("trait_item_def_ids",
5259 &mut *cx.trait_item_def_ids.borrow_mut(),
5261 Rc::new(csearch::get_trait_item_def_ids(&cx.sess.cstore, id))
5265 pub fn impl_trait_ref<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5266 -> Option<Rc<TraitRef<'tcx>>> {
5267 memoized(&cx.impl_trait_cache, id, |id: ast::DefId| {
5268 if id.krate == ast::LOCAL_CRATE {
5269 debug!("(impl_trait_ref) searching for trait impl {:?}", id);
5270 if let Some(ast_map::NodeItem(item)) = cx.map.find(id.node) {
5272 ast::ItemImpl(_, _, _, Some(_), _, _) |
5273 ast::ItemDefaultImpl(..) => {
5274 Some(ty::impl_id_to_trait_ref(cx, id.node))
5282 csearch::get_impl_trait(cx, id)
5287 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
5288 tcx.def_map.borrow().get(&tr.ref_id).expect("no def-map entry for trait").def_id()
5291 pub fn try_add_builtin_trait(
5293 trait_def_id: ast::DefId,
5294 builtin_bounds: &mut EnumSet<BuiltinBound>)
5297 //! Checks whether `trait_ref` refers to one of the builtin
5298 //! traits, like `Send`, and adds the corresponding
5299 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
5300 //! is a builtin trait.
5302 match tcx.lang_items.to_builtin_kind(trait_def_id) {
5303 Some(bound) => { builtin_bounds.insert(bound); true }
5308 pub fn ty_to_def_id(ty: Ty) -> Option<ast::DefId> {
5311 Some(tt.principal_def_id()),
5314 ty_closure(id, _) =>
5323 pub struct VariantInfo<'tcx> {
5324 pub args: Vec<Ty<'tcx>>,
5325 pub arg_names: Option<Vec<ast::Ident>>,
5326 pub ctor_ty: Option<Ty<'tcx>>,
5327 pub name: ast::Name,
5333 impl<'tcx> VariantInfo<'tcx> {
5335 /// Creates a new VariantInfo from the corresponding ast representation.
5337 /// Does not do any caching of the value in the type context.
5338 pub fn from_ast_variant(cx: &ctxt<'tcx>,
5339 ast_variant: &ast::Variant,
5340 discriminant: Disr) -> VariantInfo<'tcx> {
5341 let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
5343 match ast_variant.node.kind {
5344 ast::TupleVariantKind(ref args) => {
5345 let arg_tys = if args.len() > 0 {
5346 // the regions in the argument types come from the
5347 // enum def'n, and hence will all be early bound
5348 ty::no_late_bound_regions(cx, &ty_fn_args(ctor_ty)).unwrap()
5353 return VariantInfo {
5356 ctor_ty: Some(ctor_ty),
5357 name: ast_variant.node.name.name,
5358 id: ast_util::local_def(ast_variant.node.id),
5359 disr_val: discriminant,
5360 vis: ast_variant.node.vis
5363 ast::StructVariantKind(ref struct_def) => {
5364 let fields: &[StructField] = &struct_def.fields;
5366 assert!(fields.len() > 0);
5368 let arg_tys = struct_def.fields.iter()
5369 .map(|field| node_id_to_type(cx, field.node.id)).collect();
5370 let arg_names = fields.iter().map(|field| {
5371 match field.node.kind {
5372 NamedField(ident, _) => ident,
5373 UnnamedField(..) => cx.sess.bug(
5374 "enum_variants: all fields in struct must have a name")
5378 return VariantInfo {
5380 arg_names: Some(arg_names),
5382 name: ast_variant.node.name.name,
5383 id: ast_util::local_def(ast_variant.node.id),
5384 disr_val: discriminant,
5385 vis: ast_variant.node.vis
5392 pub fn substd_enum_variants<'tcx>(cx: &ctxt<'tcx>,
5394 substs: &Substs<'tcx>)
5395 -> Vec<Rc<VariantInfo<'tcx>>> {
5396 enum_variants(cx, id).iter().map(|variant_info| {
5397 let substd_args = variant_info.args.iter()
5398 .map(|aty| aty.subst(cx, substs)).collect::<Vec<_>>();
5400 let substd_ctor_ty = variant_info.ctor_ty.subst(cx, substs);
5402 Rc::new(VariantInfo {
5404 ctor_ty: substd_ctor_ty,
5405 ..(**variant_info).clone()
5410 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
5411 with_path(cx, id, |path| ast_map::path_to_string(path)).to_string()
5417 TraitDtor(DefId, bool)
5421 pub fn is_present(&self) -> bool {
5423 TraitDtor(..) => true,
5428 pub fn has_drop_flag(&self) -> bool {
5431 &TraitDtor(_, flag) => flag
5436 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
5437 Otherwise return none. */
5438 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
5439 match cx.destructor_for_type.borrow().get(&struct_id) {
5440 Some(&method_def_id) => {
5441 let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
5443 TraitDtor(method_def_id, flag)
5449 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
5450 cx.destructor_for_type.borrow().contains_key(&struct_id)
5453 pub fn with_path<T, F>(cx: &ctxt, id: ast::DefId, f: F) -> T where
5454 F: FnOnce(ast_map::PathElems) -> T,
5456 if id.krate == ast::LOCAL_CRATE {
5457 cx.map.with_path(id.node, f)
5459 f(csearch::get_item_path(cx, id).iter().cloned().chain(None))
5463 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
5464 enum_variants(cx, id).len() == 1
5467 pub fn type_is_empty(cx: &ctxt, ty: Ty) -> bool {
5469 ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
5474 pub fn enum_variants<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5475 -> Rc<Vec<Rc<VariantInfo<'tcx>>>> {
5476 use std::num::Int; // For checked_add
5477 memoized(&cx.enum_var_cache, id, |id: ast::DefId| {
5478 if ast::LOCAL_CRATE != id.krate {
5479 Rc::new(csearch::get_enum_variants(cx, id))
5482 Although both this code and check_enum_variants in typeck/check
5483 call eval_const_expr, it should never get called twice for the same
5484 expr, since check_enum_variants also updates the enum_var_cache
5486 match cx.map.get(id.node) {
5487 ast_map::NodeItem(ref item) => {
5489 ast::ItemEnum(ref enum_definition, _) => {
5490 let mut last_discriminant: Option<Disr> = None;
5491 Rc::new(enum_definition.variants.iter().map(|variant| {
5493 let mut discriminant = INITIAL_DISCRIMINANT_VALUE;
5494 if let Some(ref e) = variant.node.disr_expr {
5495 // Preserve all values, and prefer signed.
5496 let ty = Some(cx.types.i64);
5497 match const_eval::eval_const_expr_partial(cx, &**e, ty) {
5498 Ok(const_eval::const_int(val)) => {
5499 discriminant = val as Disr;
5501 Ok(const_eval::const_uint(val)) => {
5502 discriminant = val as Disr;
5505 span_err!(cx.sess, e.span, E0304,
5506 "expected signed integer constant");
5509 span_err!(cx.sess, err.span, E0305,
5510 "constant evaluation error: {}",
5515 if let Some(val) = last_discriminant {
5516 if let Some(v) = val.checked_add(1) {
5521 &format!("Discriminant overflowed!"));
5524 discriminant = INITIAL_DISCRIMINANT_VALUE;
5528 last_discriminant = Some(discriminant);
5529 Rc::new(VariantInfo::from_ast_variant(cx, &**variant,
5534 cx.sess.bug("enum_variants: id not bound to an enum")
5538 _ => cx.sess.bug("enum_variants: id not bound to an enum")
5544 // Returns information about the enum variant with the given ID:
5545 pub fn enum_variant_with_id<'tcx>(cx: &ctxt<'tcx>,
5546 enum_id: ast::DefId,
5547 variant_id: ast::DefId)
5548 -> Rc<VariantInfo<'tcx>> {
5549 enum_variants(cx, enum_id).iter()
5550 .find(|variant| variant.id == variant_id)
5551 .expect("enum_variant_with_id(): no variant exists with that ID")
5556 // If the given item is in an external crate, looks up its type and adds it to
5557 // the type cache. Returns the type parameters and type.
5558 pub fn lookup_item_type<'tcx>(cx: &ctxt<'tcx>,
5560 -> TypeScheme<'tcx> {
5561 lookup_locally_or_in_crate_store(
5562 "tcache", did, &mut *cx.tcache.borrow_mut(),
5563 || csearch::get_type(cx, did))
5566 /// Given the did of a trait, returns its canonical trait ref.
5567 pub fn lookup_trait_def<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId)
5568 -> Rc<TraitDef<'tcx>> {
5569 memoized(&cx.trait_defs, did, |did: DefId| {
5570 assert!(did.krate != ast::LOCAL_CRATE);
5571 Rc::new(csearch::get_trait_def(cx, did))
5575 /// Given the did of an item, returns its full set of predicates.
5576 pub fn lookup_predicates<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId)
5577 -> GenericPredicates<'tcx>
5579 memoized(&cx.predicates, did, |did: DefId| {
5580 assert!(did.krate != ast::LOCAL_CRATE);
5581 csearch::get_predicates(cx, did)
5585 /// Given the did of a trait, returns its superpredicates.
5586 pub fn lookup_super_predicates<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId)
5587 -> GenericPredicates<'tcx>
5589 memoized(&cx.super_predicates, did, |did: DefId| {
5590 assert!(did.krate != ast::LOCAL_CRATE);
5591 csearch::get_super_predicates(cx, did)
5595 pub fn predicates<'tcx>(
5598 bounds: &ParamBounds<'tcx>)
5599 -> Vec<Predicate<'tcx>>
5601 let mut vec = Vec::new();
5603 for builtin_bound in &bounds.builtin_bounds {
5604 match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty) {
5605 Ok(trait_ref) => { vec.push(trait_ref.as_predicate()); }
5606 Err(ErrorReported) => { }
5610 for ®ion_bound in &bounds.region_bounds {
5611 // account for the binder being introduced below; no need to shift `param_ty`
5612 // because, at present at least, it can only refer to early-bound regions
5613 let region_bound = ty_fold::shift_region(region_bound, 1);
5614 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).as_predicate());
5617 for bound_trait_ref in &bounds.trait_bounds {
5618 vec.push(bound_trait_ref.as_predicate());
5621 for projection in &bounds.projection_bounds {
5622 vec.push(projection.as_predicate());
5628 /// Get the attributes of a definition.
5629 pub fn get_attrs<'tcx>(tcx: &'tcx ctxt, did: DefId)
5630 -> Cow<'tcx, [ast::Attribute]> {
5632 Cow::Borrowed(tcx.map.attrs(did.node))
5634 Cow::Owned(csearch::get_item_attrs(&tcx.sess.cstore, did))
5638 /// Determine whether an item is annotated with an attribute
5639 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
5640 get_attrs(tcx, did).iter().any(|item| item.check_name(attr))
5643 /// Determine whether an item is annotated with `#[repr(packed)]`
5644 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
5645 lookup_repr_hints(tcx, did).contains(&attr::ReprPacked)
5648 /// Determine whether an item is annotated with `#[simd]`
5649 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
5650 has_attr(tcx, did, "simd")
5653 /// Obtain the representation annotation for a struct definition.
5654 pub fn lookup_repr_hints(tcx: &ctxt, did: DefId) -> Rc<Vec<attr::ReprAttr>> {
5655 memoized(&tcx.repr_hint_cache, did, |did: DefId| {
5656 Rc::new(if did.krate == LOCAL_CRATE {
5657 get_attrs(tcx, did).iter().flat_map(|meta| {
5658 attr::find_repr_attrs(tcx.sess.diagnostic(), meta).into_iter()
5661 csearch::get_repr_attrs(&tcx.sess.cstore, did)
5666 // Look up a field ID, whether or not it's local
5667 // Takes a list of type substs in case the struct is generic
5668 pub fn lookup_field_type<'tcx>(tcx: &ctxt<'tcx>,
5671 substs: &Substs<'tcx>)
5673 let ty = if id.krate == ast::LOCAL_CRATE {
5674 node_id_to_type(tcx, id.node)
5676 let mut tcache = tcx.tcache.borrow_mut();
5677 let pty = tcache.entry(id).get().unwrap_or_else(
5678 |vacant_entry| vacant_entry.insert(csearch::get_field_type(tcx, struct_id, id)));
5681 ty.subst(tcx, substs)
5684 // Look up the list of field names and IDs for a given struct.
5685 // Panics if the id is not bound to a struct.
5686 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
5687 if did.krate == ast::LOCAL_CRATE {
5688 let struct_fields = cx.struct_fields.borrow();
5689 match struct_fields.get(&did) {
5690 Some(fields) => (**fields).clone(),
5693 &format!("ID not mapped to struct fields: {}",
5694 cx.map.node_to_string(did.node)));
5698 csearch::get_struct_fields(&cx.sess.cstore, did)
5702 pub fn is_tuple_struct(cx: &ctxt, did: ast::DefId) -> bool {
5703 let fields = lookup_struct_fields(cx, did);
5704 !fields.is_empty() && fields.iter().all(|f| f.name == token::special_names::unnamed_field)
5707 // Returns a list of fields corresponding to the struct's items. trans uses
5708 // this. Takes a list of substs with which to instantiate field types.
5709 pub fn struct_fields<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId, substs: &Substs<'tcx>)
5710 -> Vec<field<'tcx>> {
5711 lookup_struct_fields(cx, did).iter().map(|f| {
5715 ty: lookup_field_type(cx, did, f.id, substs),
5722 // Returns a list of fields corresponding to the tuple's items. trans uses
5724 pub fn tup_fields<'tcx>(v: &[Ty<'tcx>]) -> Vec<field<'tcx>> {
5725 v.iter().enumerate().map(|(i, &f)| {
5727 name: token::intern(&i.to_string()),
5736 #[derive(Copy, Clone)]
5737 pub struct ClosureUpvar<'tcx> {
5743 // Returns a list of `ClosureUpvar`s for each upvar.
5744 pub fn closure_upvars<'tcx>(typer: &mc::Typer<'tcx>,
5745 closure_id: ast::DefId,
5746 substs: &Substs<'tcx>)
5747 -> Option<Vec<ClosureUpvar<'tcx>>>
5749 // Presently an unboxed closure type cannot "escape" out of a
5750 // function, so we will only encounter ones that originated in the
5751 // local crate or were inlined into it along with some function.
5752 // This may change if abstract return types of some sort are
5754 assert!(closure_id.krate == ast::LOCAL_CRATE);
5755 let tcx = typer.tcx();
5756 match tcx.freevars.borrow().get(&closure_id.node) {
5757 None => Some(vec![]),
5758 Some(ref freevars) => {
5761 let freevar_def_id = freevar.def.def_id();
5762 let freevar_ty = match typer.node_ty(freevar_def_id.node) {
5764 Err(()) => { return None; }
5766 let freevar_ty = freevar_ty.subst(tcx, substs);
5768 let upvar_id = ty::UpvarId {
5769 var_id: freevar_def_id.node,
5770 closure_expr_id: closure_id.node
5773 typer.upvar_capture(upvar_id).map(|capture| {
5774 let freevar_ref_ty = match capture {
5775 UpvarCapture::ByValue => {
5778 UpvarCapture::ByRef(borrow) => {
5780 tcx.mk_region(borrow.region),
5783 mutbl: borrow.kind.to_mutbl_lossy(),
5800 pub fn is_binopable<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>, op: ast::BinOp) -> bool {
5801 #![allow(non_upper_case_globals)]
5802 const tycat_other: int = 0;
5803 const tycat_bool: int = 1;
5804 const tycat_char: int = 2;
5805 const tycat_int: int = 3;
5806 const tycat_float: int = 4;
5807 const tycat_raw_ptr: int = 6;
5809 const opcat_add: int = 0;
5810 const opcat_sub: int = 1;
5811 const opcat_mult: int = 2;
5812 const opcat_shift: int = 3;
5813 const opcat_rel: int = 4;
5814 const opcat_eq: int = 5;
5815 const opcat_bit: int = 6;
5816 const opcat_logic: int = 7;
5817 const opcat_mod: int = 8;
5819 fn opcat(op: ast::BinOp) -> int {
5821 ast::BiAdd => opcat_add,
5822 ast::BiSub => opcat_sub,
5823 ast::BiMul => opcat_mult,
5824 ast::BiDiv => opcat_mult,
5825 ast::BiRem => opcat_mod,
5826 ast::BiAnd => opcat_logic,
5827 ast::BiOr => opcat_logic,
5828 ast::BiBitXor => opcat_bit,
5829 ast::BiBitAnd => opcat_bit,
5830 ast::BiBitOr => opcat_bit,
5831 ast::BiShl => opcat_shift,
5832 ast::BiShr => opcat_shift,
5833 ast::BiEq => opcat_eq,
5834 ast::BiNe => opcat_eq,
5835 ast::BiLt => opcat_rel,
5836 ast::BiLe => opcat_rel,
5837 ast::BiGe => opcat_rel,
5838 ast::BiGt => opcat_rel
5842 fn tycat<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> int {
5843 if type_is_simd(cx, ty) {
5844 return tycat(cx, simd_type(cx, ty))
5847 ty_char => tycat_char,
5848 ty_bool => tycat_bool,
5849 ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
5850 ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
5851 ty_ptr(_) => tycat_raw_ptr,
5856 const t: bool = true;
5857 const f: bool = false;
5860 // +, -, *, shift, rel, ==, bit, logic, mod
5861 /*other*/ [f, f, f, f, f, f, f, f, f],
5862 /*bool*/ [f, f, f, f, t, t, t, t, f],
5863 /*char*/ [f, f, f, f, t, t, f, f, f],
5864 /*int*/ [t, t, t, t, t, t, t, f, t],
5865 /*float*/ [t, t, t, f, t, t, f, f, f],
5866 /*bot*/ [t, t, t, t, t, t, t, t, t],
5867 /*raw ptr*/ [f, f, f, f, t, t, f, f, f]];
5869 return tbl[tycat(cx, ty) as uint ][opcat(op) as uint];
5872 // Returns the repeat count for a repeating vector expression.
5873 pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> uint {
5874 match const_eval::eval_const_expr_partial(tcx, count_expr, Some(tcx.types.uint)) {
5876 let found = match val {
5877 const_eval::const_uint(count) => return count as uint,
5878 const_eval::const_int(count) if count >= 0 => return count as uint,
5879 const_eval::const_int(_) => "negative integer",
5880 const_eval::const_float(_) => "float",
5881 const_eval::const_str(_) => "string",
5882 const_eval::const_bool(_) => "boolean",
5883 const_eval::const_binary(_) => "binary array",
5884 const_eval::Struct(..) => "struct",
5885 const_eval::Tuple(_) => "tuple"
5887 span_err!(tcx.sess, count_expr.span, E0306,
5888 "expected positive integer for repeat count, found {}",
5892 let found = match count_expr.node {
5893 ast::ExprPath(None, ast::Path {
5897 }) if segments.len() == 1 =>
5900 "non-constant expression"
5902 span_err!(tcx.sess, count_expr.span, E0307,
5903 "expected constant integer for repeat count, found {}",
5910 // Iterate over a type parameter's bounded traits and any supertraits
5911 // of those traits, ignoring kinds.
5912 // Here, the supertraits are the transitive closure of the supertrait
5913 // relation on the supertraits from each bounded trait's constraint
5915 pub fn each_bound_trait_and_supertraits<'tcx, F>(tcx: &ctxt<'tcx>,
5916 bounds: &[PolyTraitRef<'tcx>],
5919 F: FnMut(PolyTraitRef<'tcx>) -> bool,
5921 for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
5922 if !f(bound_trait_ref) {
5929 /// Given a set of predicates that apply to an object type, returns
5930 /// the region bounds that the (erased) `Self` type must
5931 /// outlive. Precisely *because* the `Self` type is erased, the
5932 /// parameter `erased_self_ty` must be supplied to indicate what type
5933 /// has been used to represent `Self` in the predicates
5934 /// themselves. This should really be a unique type; `FreshTy(0)` is a
5937 /// Requires that trait definitions have been processed so that we can
5938 /// elaborate predicates and walk supertraits.
5939 pub fn required_region_bounds<'tcx>(tcx: &ctxt<'tcx>,
5940 erased_self_ty: Ty<'tcx>,
5941 predicates: Vec<ty::Predicate<'tcx>>)
5944 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
5945 erased_self_ty.repr(tcx),
5946 predicates.repr(tcx));
5948 assert!(!erased_self_ty.has_escaping_regions());
5950 traits::elaborate_predicates(tcx, predicates)
5951 .filter_map(|predicate| {
5953 ty::Predicate::Projection(..) |
5954 ty::Predicate::Trait(..) |
5955 ty::Predicate::Equate(..) |
5956 ty::Predicate::RegionOutlives(..) => {
5959 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
5960 // Search for a bound of the form `erased_self_ty
5961 // : 'a`, but be wary of something like `for<'a>
5962 // erased_self_ty : 'a` (we interpret a
5963 // higher-ranked bound like that as 'static,
5964 // though at present the code in `fulfill.rs`
5965 // considers such bounds to be unsatisfiable, so
5966 // it's kind of a moot point since you could never
5967 // construct such an object, but this seems
5968 // correct even if that code changes).
5969 if t == erased_self_ty && !r.has_escaping_regions() {
5970 if r.has_escaping_regions() {
5984 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> Rc<ItemVariances> {
5985 lookup_locally_or_in_crate_store(
5986 "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
5987 || Rc::new(csearch::get_item_variances(&tcx.sess.cstore, item_id)))
5990 pub fn trait_has_default_impl(tcx: &ctxt, trait_def_id: DefId) -> bool {
5991 populate_implementations_for_trait_if_necessary(tcx, trait_def_id);
5992 tcx.traits_with_default_impls.borrow().contains_key(&trait_def_id)
5995 /// Records a trait-to-implementation mapping.
5996 pub fn record_trait_has_default_impl(tcx: &ctxt, trait_def_id: DefId) {
5997 // We're using the latest implementation found as the reference one.
5998 // Duplicated implementations are caught and reported in the coherence
6000 tcx.traits_with_default_impls.borrow_mut().insert(trait_def_id, ());
6003 /// Records a trait-to-implementation mapping.
6004 pub fn record_trait_implementation(tcx: &ctxt,
6005 trait_def_id: DefId,
6006 impl_def_id: DefId) {
6008 match tcx.trait_impls.borrow().get(&trait_def_id) {
6009 Some(impls_for_trait) => {
6010 impls_for_trait.borrow_mut().push(impl_def_id);
6016 tcx.trait_impls.borrow_mut().insert(trait_def_id, Rc::new(RefCell::new(vec!(impl_def_id))));
6019 /// Load primitive inherent implementations if necessary
6020 pub fn populate_implementations_for_primitive_if_necessary(tcx: &ctxt, lang_def_id: ast::DefId) {
6021 if lang_def_id.krate == LOCAL_CRATE {
6024 if tcx.populated_external_primitive_impls.borrow().contains(&lang_def_id) {
6028 debug!("populate_implementations_for_primitive_if_necessary: searching for {:?}", lang_def_id);
6030 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, lang_def_id);
6032 // Store the implementation info.
6033 tcx.impl_items.borrow_mut().insert(lang_def_id, impl_items);
6035 tcx.populated_external_primitive_impls.borrow_mut().insert(lang_def_id);
6038 /// Populates the type context with all the implementations for the given type
6040 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
6041 type_id: ast::DefId) {
6042 if type_id.krate == LOCAL_CRATE {
6045 if tcx.populated_external_types.borrow().contains(&type_id) {
6049 debug!("populate_implementations_for_type_if_necessary: searching for {:?}", type_id);
6051 let mut inherent_impls = Vec::new();
6052 csearch::each_implementation_for_type(&tcx.sess.cstore, type_id, |impl_def_id| {
6053 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, impl_def_id);
6055 // Record the trait->implementation mappings, if applicable.
6056 let associated_traits = csearch::get_impl_trait(tcx, impl_def_id);
6057 if let Some(ref trait_ref) = associated_traits {
6058 record_trait_implementation(tcx, trait_ref.def_id, impl_def_id);
6061 // For any methods that use a default implementation, add them to
6062 // the map. This is a bit unfortunate.
6063 for impl_item_def_id in &impl_items {
6064 let method_def_id = impl_item_def_id.def_id();
6065 match impl_or_trait_item(tcx, method_def_id) {
6066 MethodTraitItem(method) => {
6067 if let Some(source) = method.provided_source {
6068 tcx.provided_method_sources
6070 .insert(method_def_id, source);
6073 TypeTraitItem(_) => {}
6077 // Store the implementation info.
6078 tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
6080 // If this is an inherent implementation, record it.
6081 if associated_traits.is_none() {
6082 inherent_impls.push(impl_def_id);
6086 tcx.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
6087 tcx.populated_external_types.borrow_mut().insert(type_id);
6090 /// Populates the type context with all the implementations for the given
6091 /// trait if necessary.
6092 pub fn populate_implementations_for_trait_if_necessary(
6094 trait_id: ast::DefId) {
6095 if trait_id.krate == LOCAL_CRATE {
6099 if tcx.populated_external_traits.borrow().contains(&trait_id) {
6103 if csearch::is_defaulted_trait(&tcx.sess.cstore, trait_id) {
6104 record_trait_has_default_impl(tcx, trait_id);
6107 csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id, |implementation_def_id| {
6108 let impl_items = csearch::get_impl_items(&tcx.sess.cstore, implementation_def_id);
6110 // Record the trait->implementation mapping.
6111 record_trait_implementation(tcx, trait_id, implementation_def_id);
6113 // For any methods that use a default implementation, add them to
6114 // the map. This is a bit unfortunate.
6115 for impl_item_def_id in &impl_items {
6116 let method_def_id = impl_item_def_id.def_id();
6117 match impl_or_trait_item(tcx, method_def_id) {
6118 MethodTraitItem(method) => {
6119 if let Some(source) = method.provided_source {
6120 tcx.provided_method_sources
6122 .insert(method_def_id, source);
6125 TypeTraitItem(_) => {}
6129 // Store the implementation info.
6130 tcx.impl_items.borrow_mut().insert(implementation_def_id, impl_items);
6133 tcx.populated_external_traits.borrow_mut().insert(trait_id);
6136 /// Given the def_id of an impl, return the def_id of the trait it implements.
6137 /// If it implements no trait, return `None`.
6138 pub fn trait_id_of_impl(tcx: &ctxt,
6140 -> Option<ast::DefId> {
6141 ty::impl_trait_ref(tcx, def_id).map(|tr| tr.def_id)
6144 /// If the given def ID describes a method belonging to an impl, return the
6145 /// ID of the impl that the method belongs to. Otherwise, return `None`.
6146 pub fn impl_of_method(tcx: &ctxt, def_id: ast::DefId)
6147 -> Option<ast::DefId> {
6148 if def_id.krate != LOCAL_CRATE {
6149 return match csearch::get_impl_or_trait_item(tcx,
6150 def_id).container() {
6151 TraitContainer(_) => None,
6152 ImplContainer(def_id) => Some(def_id),
6155 match tcx.impl_or_trait_items.borrow().get(&def_id).cloned() {
6156 Some(trait_item) => {
6157 match trait_item.container() {
6158 TraitContainer(_) => None,
6159 ImplContainer(def_id) => Some(def_id),
6166 /// If the given def ID describes an item belonging to a trait (either a
6167 /// default method or an implementation of a trait method), return the ID of
6168 /// the trait that the method belongs to. Otherwise, return `None`.
6169 pub fn trait_of_item(tcx: &ctxt, def_id: ast::DefId) -> Option<ast::DefId> {
6170 if def_id.krate != LOCAL_CRATE {
6171 return csearch::get_trait_of_item(&tcx.sess.cstore, def_id, tcx);
6173 match tcx.impl_or_trait_items.borrow().get(&def_id).cloned() {
6174 Some(impl_or_trait_item) => {
6175 match impl_or_trait_item.container() {
6176 TraitContainer(def_id) => Some(def_id),
6177 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
6184 /// If the given def ID describes an item belonging to a trait, (either a
6185 /// default method or an implementation of a trait method), return the ID of
6186 /// the method inside trait definition (this means that if the given def ID
6187 /// is already that of the original trait method, then the return value is
6189 /// Otherwise, return `None`.
6190 pub fn trait_item_of_item(tcx: &ctxt, def_id: ast::DefId)
6191 -> Option<ImplOrTraitItemId> {
6192 let impl_item = match tcx.impl_or_trait_items.borrow().get(&def_id) {
6193 Some(m) => m.clone(),
6194 None => return None,
6196 let name = impl_item.name();
6197 match trait_of_item(tcx, def_id) {
6198 Some(trait_did) => {
6199 let trait_items = ty::trait_items(tcx, trait_did);
6201 .position(|m| m.name() == name)
6202 .map(|idx| ty::trait_item(tcx, trait_did, idx).id())
6208 /// Creates a hash of the type `Ty` which will be the same no matter what crate
6209 /// context it's calculated within. This is used by the `type_id` intrinsic.
6210 pub fn hash_crate_independent<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh) -> u64 {
6211 let mut state = SipHasher::new();
6212 helper(tcx, ty, svh, &mut state);
6213 return state.finish();
6215 fn helper<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh,
6216 state: &mut SipHasher) {
6217 macro_rules! byte { ($b:expr) => { ($b as u8).hash(state) } }
6218 macro_rules! hash { ($e:expr) => { $e.hash(state) } }
6220 let region = |state: &mut SipHasher, r: Region| {
6223 ReLateBound(db, BrAnon(i)) => {
6233 tcx.sess.bug("unexpected region found when hashing a type")
6237 let did = |state: &mut SipHasher, did: DefId| {
6238 let h = if ast_util::is_local(did) {
6241 tcx.sess.cstore.get_crate_hash(did.krate)
6243 h.as_str().hash(state);
6244 did.node.hash(state);
6246 let mt = |state: &mut SipHasher, mt: mt| {
6247 mt.mutbl.hash(state);
6249 let fn_sig = |state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| {
6250 let sig = anonymize_late_bound_regions(tcx, sig).0;
6251 for a in &sig.inputs { helper(tcx, *a, svh, state); }
6252 if let ty::FnConverging(output) = sig.output {
6253 helper(tcx, output, svh, state);
6256 maybe_walk_ty(ty, |ty| {
6258 ty_bool => byte!(2),
6259 ty_char => byte!(3),
6282 ty_vec(_, Some(n)) => {
6286 ty_vec(_, None) => {
6298 ty_bare_fn(opt_def_id, ref b) => {
6303 fn_sig(state, &b.sig);
6306 ty_trait(ref data) => {
6308 did(state, data.principal_def_id());
6311 let principal = anonymize_late_bound_regions(tcx, &data.principal).0;
6312 for subty in principal.substs.types.iter() {
6313 helper(tcx, *subty, svh, state);
6318 ty_struct(d, _) => {
6322 ty_tup(ref inner) => {
6330 hash!(token::get_name(p.name));
6332 ty_infer(_) => unreachable!(),
6333 ty_err => byte!(21),
6334 ty_closure(d, _) => {
6338 ty_projection(ref data) => {
6340 did(state, data.trait_ref.def_id);
6341 hash!(token::get_name(data.item_name));
6350 pub fn to_string(self) -> &'static str {
6353 Contravariant => "-",
6360 /// Construct a parameter environment suitable for static contexts or other contexts where there
6361 /// are no free type/lifetime parameters in scope.
6362 pub fn empty_parameter_environment<'a,'tcx>(cx: &'a ctxt<'tcx>) -> ParameterEnvironment<'a,'tcx> {
6363 ty::ParameterEnvironment { tcx: cx,
6364 free_substs: Substs::empty(),
6365 caller_bounds: Vec::new(),
6366 implicit_region_bound: ty::ReEmpty,
6367 selection_cache: traits::SelectionCache::new(), }
6370 /// Constructs and returns a substitution that can be applied to move from
6371 /// the "outer" view of a type or method to the "inner" view.
6372 /// In general, this means converting from bound parameters to
6373 /// free parameters. Since we currently represent bound/free type
6374 /// parameters in the same way, this only has an effect on regions.
6375 pub fn construct_free_substs<'a,'tcx>(
6376 tcx: &'a ctxt<'tcx>,
6377 generics: &Generics<'tcx>,
6378 free_id: ast::NodeId)
6382 let mut types = VecPerParamSpace::empty();
6383 push_types_from_defs(tcx, &mut types, generics.types.as_slice());
6385 let free_id_outlive = region::DestructionScopeData::new(free_id);
6387 // map bound 'a => free 'a
6388 let mut regions = VecPerParamSpace::empty();
6389 push_region_params(&mut regions, free_id_outlive, generics.regions.as_slice());
6393 regions: subst::NonerasedRegions(regions)
6396 fn push_region_params(regions: &mut VecPerParamSpace<ty::Region>,
6397 all_outlive_extent: region::DestructionScopeData,
6398 region_params: &[RegionParameterDef])
6400 for r in region_params {
6401 regions.push(r.space, ty::free_region_from_def(all_outlive_extent, r));
6405 fn push_types_from_defs<'tcx>(tcx: &ty::ctxt<'tcx>,
6406 types: &mut VecPerParamSpace<Ty<'tcx>>,
6407 defs: &[TypeParameterDef<'tcx>]) {
6409 debug!("construct_parameter_environment(): push_types_from_defs: def={:?}",
6411 let ty = ty::mk_param_from_def(tcx, def);
6412 types.push(def.space, ty);
6417 /// See `ParameterEnvironment` struct def'n for details
6418 pub fn construct_parameter_environment<'a,'tcx>(
6419 tcx: &'a ctxt<'tcx>,
6421 generics: &ty::Generics<'tcx>,
6422 generic_predicates: &ty::GenericPredicates<'tcx>,
6423 free_id: ast::NodeId)
6424 -> ParameterEnvironment<'a, 'tcx>
6427 // Construct the free substs.
6430 let free_substs = construct_free_substs(tcx, generics, free_id);
6431 let free_id_outlive = region::DestructionScopeData::new(free_id);
6434 // Compute the bounds on Self and the type parameters.
6437 let bounds = generic_predicates.instantiate(tcx, &free_substs);
6438 let bounds = liberate_late_bound_regions(tcx, free_id_outlive, &ty::Binder(bounds));
6439 let predicates = bounds.predicates.into_vec();
6442 // Compute region bounds. For now, these relations are stored in a
6443 // global table on the tcx, so just enter them there. I'm not
6444 // crazy about this scheme, but it's convenient, at least.
6447 record_region_bounds(tcx, &*predicates);
6449 debug!("construct_parameter_environment: free_id={:?} free_subst={:?} predicates={:?}",
6451 free_substs.repr(tcx),
6452 predicates.repr(tcx));
6455 // Finally, we have to normalize the bounds in the environment, in
6456 // case they contain any associated type projections. This process
6457 // can yield errors if the put in illegal associated types, like
6458 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
6459 // report these errors right here; this doesn't actually feel
6460 // right to me, because constructing the environment feels like a
6461 // kind of a "idempotent" action, but I'm not sure where would be
6462 // a better place. In practice, we construct environments for
6463 // every fn once during type checking, and we'll abort if there
6464 // are any errors at that point, so after type checking you can be
6465 // sure that this will succeed without errors anyway.
6468 let unnormalized_env = ty::ParameterEnvironment {
6470 free_substs: free_substs,
6471 implicit_region_bound: ty::ReScope(free_id_outlive.to_code_extent()),
6472 caller_bounds: predicates,
6473 selection_cache: traits::SelectionCache::new(),
6476 let cause = traits::ObligationCause::misc(span, free_id);
6477 return traits::normalize_param_env_or_error(unnormalized_env, cause);
6479 fn record_region_bounds<'tcx>(tcx: &ty::ctxt<'tcx>, predicates: &[ty::Predicate<'tcx>]) {
6480 debug!("record_region_bounds(predicates={:?})", predicates.repr(tcx));
6482 for predicate in predicates {
6484 Predicate::Projection(..) |
6485 Predicate::Trait(..) |
6486 Predicate::Equate(..) |
6487 Predicate::TypeOutlives(..) => {
6488 // No region bounds here
6490 Predicate::RegionOutlives(ty::Binder(ty::OutlivesPredicate(r_a, r_b))) => {
6492 (ty::ReFree(fr_a), ty::ReFree(fr_b)) => {
6493 // Record that `'a:'b`. Or, put another way, `'b <= 'a`.
6494 tcx.region_maps.relate_free_regions(fr_b, fr_a);
6497 // All named regions are instantiated with free regions.
6499 &format!("record_region_bounds: non free region: {} / {}",
6511 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
6513 ast::MutMutable => MutBorrow,
6514 ast::MutImmutable => ImmBorrow,
6518 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
6519 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
6520 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
6522 pub fn to_mutbl_lossy(self) -> ast::Mutability {
6524 MutBorrow => ast::MutMutable,
6525 ImmBorrow => ast::MutImmutable,
6527 // We have no type corresponding to a unique imm borrow, so
6528 // use `&mut`. It gives all the capabilities of an `&uniq`
6529 // and hence is a safe "over approximation".
6530 UniqueImmBorrow => ast::MutMutable,
6534 pub fn to_user_str(&self) -> &'static str {
6536 MutBorrow => "mutable",
6537 ImmBorrow => "immutable",
6538 UniqueImmBorrow => "uniquely immutable",
6543 impl<'tcx> ctxt<'tcx> {
6544 pub fn is_method_call(&self, expr_id: ast::NodeId) -> bool {
6545 self.method_map.borrow().contains_key(&MethodCall::expr(expr_id))
6548 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
6549 Some(self.upvar_capture_map.borrow().get(&upvar_id).unwrap().clone())
6553 impl<'a,'tcx> mc::Typer<'tcx> for ParameterEnvironment<'a,'tcx> {
6554 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<Ty<'tcx>> {
6555 Ok(ty::node_id_to_type(self.tcx, id))
6558 fn expr_ty_adjusted(&self, expr: &ast::Expr) -> mc::McResult<Ty<'tcx>> {
6559 Ok(ty::expr_ty_adjusted(self.tcx, expr))
6562 fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>> {
6563 self.tcx.method_map.borrow().get(&method_call).map(|method| method.ty)
6566 fn node_method_origin(&self, method_call: ty::MethodCall)
6567 -> Option<ty::MethodOrigin<'tcx>>
6569 self.tcx.method_map.borrow().get(&method_call).map(|method| method.origin.clone())
6572 fn adjustments(&self) -> &RefCell<NodeMap<ty::AutoAdjustment<'tcx>>> {
6573 &self.tcx.adjustments
6576 fn is_method_call(&self, id: ast::NodeId) -> bool {
6577 self.tcx.is_method_call(id)
6580 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent> {
6581 self.tcx.region_maps.temporary_scope(rvalue_id)
6584 fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
6585 self.tcx.upvar_capture(upvar_id)
6588 fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool {
6589 type_moves_by_default(self, span, ty)
6593 impl<'a,'tcx> ClosureTyper<'tcx> for ty::ParameterEnvironment<'a,'tcx> {
6594 fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> {
6598 fn closure_kind(&self,
6600 -> Option<ty::ClosureKind>
6602 Some(self.tcx.closure_kind(def_id))
6605 fn closure_type(&self,
6607 substs: &subst::Substs<'tcx>)
6608 -> ty::ClosureTy<'tcx>
6610 self.tcx.closure_type(def_id, substs)
6613 fn closure_upvars(&self,
6615 substs: &Substs<'tcx>)
6616 -> Option<Vec<ClosureUpvar<'tcx>>>
6618 closure_upvars(self, def_id, substs)
6623 /// The category of explicit self.
6624 #[derive(Clone, Copy, Eq, PartialEq, Debug)]
6625 pub enum ExplicitSelfCategory {
6626 StaticExplicitSelfCategory,
6627 ByValueExplicitSelfCategory,
6628 ByReferenceExplicitSelfCategory(Region, ast::Mutability),
6629 ByBoxExplicitSelfCategory,
6632 /// Pushes all the lifetimes in the given type onto the given list. A
6633 /// "lifetime in a type" is a lifetime specified by a reference or a lifetime
6634 /// in a list of type substitutions. This does *not* traverse into nominal
6635 /// types, nor does it resolve fictitious types.
6636 pub fn accumulate_lifetimes_in_type(accumulator: &mut Vec<ty::Region>,
6640 ty_rptr(region, _) => {
6641 accumulator.push(*region)
6643 ty_trait(ref t) => {
6644 accumulator.push_all(t.principal.0.substs.regions().as_slice());
6646 ty_enum(_, substs) |
6647 ty_struct(_, substs) => {
6648 accum_substs(accumulator, substs);
6650 ty_closure(_, substs) => {
6651 accum_substs(accumulator, substs);
6672 fn accum_substs(accumulator: &mut Vec<Region>, substs: &Substs) {
6673 match substs.regions {
6674 subst::ErasedRegions => {}
6675 subst::NonerasedRegions(ref regions) => {
6676 for region in regions.iter() {
6677 accumulator.push(*region)
6684 /// A free variable referred to in a function.
6685 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
6686 pub struct Freevar {
6687 /// The variable being accessed free.
6690 // First span where it is accessed (there can be multiple).
6694 pub type FreevarMap = NodeMap<Vec<Freevar>>;
6696 pub type CaptureModeMap = NodeMap<ast::CaptureClause>;
6698 // Trait method resolution
6699 pub type TraitMap = NodeMap<Vec<DefId>>;
6701 // Map from the NodeId of a glob import to a list of items which are actually
6703 pub type GlobMap = HashMap<NodeId, HashSet<Name>>;
6705 pub fn with_freevars<T, F>(tcx: &ty::ctxt, fid: ast::NodeId, f: F) -> T where
6706 F: FnOnce(&[Freevar]) -> T,
6708 match tcx.freevars.borrow().get(&fid) {
6710 Some(d) => f(&d[..])
6714 impl<'tcx> AutoAdjustment<'tcx> {
6715 pub fn is_identity(&self) -> bool {
6717 AdjustReifyFnPointer(..) => false,
6718 AdjustUnsafeFnPointer(..) => false,
6719 AdjustDerefRef(ref r) => r.is_identity(),
6724 impl<'tcx> AutoDerefRef<'tcx> {
6725 pub fn is_identity(&self) -> bool {
6726 self.autoderefs == 0 && self.autoref.is_none()
6730 /// Replace any late-bound regions bound in `value` with free variants attached to scope-id
6732 pub fn liberate_late_bound_regions<'tcx, T>(
6733 tcx: &ty::ctxt<'tcx>,
6734 all_outlive_scope: region::DestructionScopeData,
6737 where T : TypeFoldable<'tcx> + Repr<'tcx>
6739 replace_late_bound_regions(
6741 |br| ty::ReFree(ty::FreeRegion{scope: all_outlive_scope, bound_region: br})).0
6744 pub fn count_late_bound_regions<'tcx, T>(
6745 tcx: &ty::ctxt<'tcx>,
6748 where T : TypeFoldable<'tcx> + Repr<'tcx>
6750 let (_, skol_map) = replace_late_bound_regions(tcx, value, |_| ty::ReStatic);
6754 pub fn binds_late_bound_regions<'tcx, T>(
6755 tcx: &ty::ctxt<'tcx>,
6758 where T : TypeFoldable<'tcx> + Repr<'tcx>
6760 count_late_bound_regions(tcx, value) > 0
6763 pub fn no_late_bound_regions<'tcx, T>(
6764 tcx: &ty::ctxt<'tcx>,
6767 where T : TypeFoldable<'tcx> + Repr<'tcx> + Clone
6769 if binds_late_bound_regions(tcx, value) {
6772 Some(value.0.clone())
6776 /// Replace any late-bound regions bound in `value` with `'static`. Useful in trans but also
6777 /// method lookup and a few other places where precise region relationships are not required.
6778 pub fn erase_late_bound_regions<'tcx, T>(
6779 tcx: &ty::ctxt<'tcx>,
6782 where T : TypeFoldable<'tcx> + Repr<'tcx>
6784 replace_late_bound_regions(tcx, value, |_| ty::ReStatic).0
6787 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
6788 /// assigned starting at 1 and increasing monotonically in the order traversed
6789 /// by the fold operation.
6791 /// The chief purpose of this function is to canonicalize regions so that two
6792 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
6793 /// structurally identical. For example, `for<'a, 'b> fn(&'a int, &'b int)` and
6794 /// `for<'a, 'b> fn(&'b int, &'a int)` will become identical after anonymization.
6795 pub fn anonymize_late_bound_regions<'tcx, T>(
6799 where T : TypeFoldable<'tcx> + Repr<'tcx>,
6801 let mut counter = 0;
6802 ty::Binder(replace_late_bound_regions(tcx, sig, |_| {
6804 ReLateBound(ty::DebruijnIndex::new(1), BrAnon(counter))
6808 /// Replaces the late-bound-regions in `value` that are bound by `value`.
6809 pub fn replace_late_bound_regions<'tcx, T, F>(
6810 tcx: &ty::ctxt<'tcx>,
6813 -> (T, FnvHashMap<ty::BoundRegion,ty::Region>)
6814 where T : TypeFoldable<'tcx> + Repr<'tcx>,
6815 F : FnMut(BoundRegion) -> ty::Region,
6817 debug!("replace_late_bound_regions({})", binder.repr(tcx));
6819 let mut map = FnvHashMap();
6821 // Note: fold the field `0`, not the binder, so that late-bound
6822 // regions bound by `binder` are considered free.
6823 let value = ty_fold::fold_regions(tcx, &binder.0, |region, current_depth| {
6824 debug!("region={}", region.repr(tcx));
6826 ty::ReLateBound(debruijn, br) if debruijn.depth == current_depth => {
6828 * map.entry(br).get().unwrap_or_else(
6829 |vacant_entry| vacant_entry.insert(mapf(br)));
6831 if let ty::ReLateBound(debruijn1, br) = region {
6832 // If the callback returns a late-bound region,
6833 // that region should always use depth 1. Then we
6834 // adjust it to the correct depth.
6835 assert_eq!(debruijn1.depth, 1);
6836 ty::ReLateBound(debruijn, br)
6847 debug!("resulting map: {:?} value: {:?}", map, value.repr(tcx));
6851 impl DebruijnIndex {
6852 pub fn new(depth: u32) -> DebruijnIndex {
6854 DebruijnIndex { depth: depth }
6857 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
6858 DebruijnIndex { depth: self.depth + amount }
6862 impl<'tcx> Repr<'tcx> for AutoAdjustment<'tcx> {
6863 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6865 AdjustReifyFnPointer(def_id) => {
6866 format!("AdjustReifyFnPointer({})", def_id.repr(tcx))
6868 AdjustUnsafeFnPointer => {
6869 format!("AdjustUnsafeFnPointer")
6871 AdjustDerefRef(ref data) => {
6878 impl<'tcx> Repr<'tcx> for UnsizeKind<'tcx> {
6879 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6881 UnsizeLength(n) => format!("UnsizeLength({})", n),
6882 UnsizeStruct(ref k, n) => format!("UnsizeStruct({},{})", k.repr(tcx), n),
6883 UnsizeVtable(ref a, ref b) => format!("UnsizeVtable({},{})", a.repr(tcx), b.repr(tcx)),
6884 UnsizeUpcast(ref a) => format!("UnsizeUpcast({})", a.repr(tcx)),
6889 impl<'tcx> Repr<'tcx> for AutoDerefRef<'tcx> {
6890 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6891 format!("AutoDerefRef({}, {})", self.autoderefs, self.autoref.repr(tcx))
6895 impl<'tcx> Repr<'tcx> for AutoRef<'tcx> {
6896 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6898 AutoPtr(a, b, ref c) => {
6899 format!("AutoPtr({},{:?},{})", a.repr(tcx), b, c.repr(tcx))
6901 AutoUnsize(ref a) => {
6902 format!("AutoUnsize({})", a.repr(tcx))
6904 AutoUnsizeUniq(ref a) => {
6905 format!("AutoUnsizeUniq({})", a.repr(tcx))
6907 AutoUnsafe(ref a, ref b) => {
6908 format!("AutoUnsafe({:?},{})", a, b.repr(tcx))
6914 impl<'tcx> Repr<'tcx> for TyTrait<'tcx> {
6915 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6916 format!("TyTrait({},{})",
6917 self.principal.repr(tcx),
6918 self.bounds.repr(tcx))
6922 impl<'tcx> Repr<'tcx> for ty::Predicate<'tcx> {
6923 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6925 Predicate::Trait(ref a) => a.repr(tcx),
6926 Predicate::Equate(ref pair) => pair.repr(tcx),
6927 Predicate::RegionOutlives(ref pair) => pair.repr(tcx),
6928 Predicate::TypeOutlives(ref pair) => pair.repr(tcx),
6929 Predicate::Projection(ref pair) => pair.repr(tcx),
6934 impl<'tcx> Repr<'tcx> for vtable_origin<'tcx> {
6935 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
6937 vtable_static(def_id, ref tys, ref vtable_res) => {
6938 format!("vtable_static({:?}:{}, {}, {})",
6940 ty::item_path_str(tcx, def_id),
6942 vtable_res.repr(tcx))
6945 vtable_param(x, y) => {
6946 format!("vtable_param({:?}, {})", x, y)
6949 vtable_closure(def_id) => {
6950 format!("vtable_closure({:?})", def_id)
6954 format!("vtable_error")
6960 pub fn make_substs_for_receiver_types<'tcx>(tcx: &ty::ctxt<'tcx>,
6961 trait_ref: &ty::TraitRef<'tcx>,
6962 method: &ty::Method<'tcx>)
6963 -> subst::Substs<'tcx>
6966 * Substitutes the values for the receiver's type parameters
6967 * that are found in method, leaving the method's type parameters
6971 let meth_tps: Vec<Ty> =
6972 method.generics.types.get_slice(subst::FnSpace)
6974 .map(|def| ty::mk_param_from_def(tcx, def))
6976 let meth_regions: Vec<ty::Region> =
6977 method.generics.regions.get_slice(subst::FnSpace)
6979 .map(|def| ty::ReEarlyBound(def.def_id.node, def.space,
6980 def.index, def.name))
6982 trait_ref.substs.clone().with_method(meth_tps, meth_regions)
6986 pub enum CopyImplementationError {
6987 FieldDoesNotImplementCopy(ast::Name),
6988 VariantDoesNotImplementCopy(ast::Name),
6993 pub fn can_type_implement_copy<'a,'tcx>(param_env: &ParameterEnvironment<'a, 'tcx>,
6995 self_type: Ty<'tcx>)
6996 -> Result<(),CopyImplementationError>
6998 let tcx = param_env.tcx;
7000 let did = match self_type.sty {
7001 ty::ty_struct(struct_did, substs) => {
7002 let fields = ty::struct_fields(tcx, struct_did, substs);
7003 for field in &fields {
7004 if type_moves_by_default(param_env, span, field.mt.ty) {
7005 return Err(FieldDoesNotImplementCopy(field.name))
7010 ty::ty_enum(enum_did, substs) => {
7011 let enum_variants = ty::enum_variants(tcx, enum_did);
7012 for variant in &*enum_variants {
7013 for variant_arg_type in &variant.args {
7014 let substd_arg_type =
7015 variant_arg_type.subst(tcx, substs);
7016 if type_moves_by_default(param_env, span, substd_arg_type) {
7017 return Err(VariantDoesNotImplementCopy(variant.name))
7023 _ => return Err(TypeIsStructural),
7026 if ty::has_dtor(tcx, did) {
7027 return Err(TypeHasDestructor)
7033 // FIXME(#20298) -- all of these types basically walk various
7034 // structures to test whether types/regions are reachable with various
7035 // properties. It should be possible to express them in terms of one
7036 // common "walker" trait or something.
7038 pub trait RegionEscape {
7039 fn has_escaping_regions(&self) -> bool {
7040 self.has_regions_escaping_depth(0)
7043 fn has_regions_escaping_depth(&self, depth: u32) -> bool;
7046 impl<'tcx> RegionEscape for Ty<'tcx> {
7047 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7048 ty::type_escapes_depth(*self, depth)
7052 impl<'tcx> RegionEscape for Substs<'tcx> {
7053 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7054 self.types.has_regions_escaping_depth(depth) ||
7055 self.regions.has_regions_escaping_depth(depth)
7059 impl<'tcx,T:RegionEscape> RegionEscape for VecPerParamSpace<T> {
7060 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7061 self.iter_enumerated().any(|(space, _, t)| {
7062 if space == subst::FnSpace {
7063 t.has_regions_escaping_depth(depth+1)
7065 t.has_regions_escaping_depth(depth)
7071 impl<'tcx> RegionEscape for TypeScheme<'tcx> {
7072 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7073 self.ty.has_regions_escaping_depth(depth)
7077 impl RegionEscape for Region {
7078 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7079 self.escapes_depth(depth)
7083 impl<'tcx> RegionEscape for GenericPredicates<'tcx> {
7084 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7085 self.predicates.has_regions_escaping_depth(depth)
7089 impl<'tcx> RegionEscape for Predicate<'tcx> {
7090 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7092 Predicate::Trait(ref data) => data.has_regions_escaping_depth(depth),
7093 Predicate::Equate(ref data) => data.has_regions_escaping_depth(depth),
7094 Predicate::RegionOutlives(ref data) => data.has_regions_escaping_depth(depth),
7095 Predicate::TypeOutlives(ref data) => data.has_regions_escaping_depth(depth),
7096 Predicate::Projection(ref data) => data.has_regions_escaping_depth(depth),
7101 impl<'tcx> RegionEscape for TraitRef<'tcx> {
7102 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7103 self.substs.types.iter().any(|t| t.has_regions_escaping_depth(depth)) ||
7104 self.substs.regions.has_regions_escaping_depth(depth)
7108 impl<'tcx> RegionEscape for subst::RegionSubsts {
7109 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7111 subst::ErasedRegions => false,
7112 subst::NonerasedRegions(ref r) => {
7113 r.iter().any(|t| t.has_regions_escaping_depth(depth))
7119 impl<'tcx,T:RegionEscape> RegionEscape for Binder<T> {
7120 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7121 self.0.has_regions_escaping_depth(depth + 1)
7125 impl<'tcx> RegionEscape for EquatePredicate<'tcx> {
7126 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7127 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7131 impl<'tcx> RegionEscape for TraitPredicate<'tcx> {
7132 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7133 self.trait_ref.has_regions_escaping_depth(depth)
7137 impl<T:RegionEscape,U:RegionEscape> RegionEscape for OutlivesPredicate<T,U> {
7138 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7139 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7143 impl<'tcx> RegionEscape for ProjectionPredicate<'tcx> {
7144 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7145 self.projection_ty.has_regions_escaping_depth(depth) ||
7146 self.ty.has_regions_escaping_depth(depth)
7150 impl<'tcx> RegionEscape for ProjectionTy<'tcx> {
7151 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7152 self.trait_ref.has_regions_escaping_depth(depth)
7156 impl<'tcx> Repr<'tcx> for ty::ProjectionPredicate<'tcx> {
7157 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7158 format!("ProjectionPredicate({}, {})",
7159 self.projection_ty.repr(tcx),
7164 pub trait HasProjectionTypes {
7165 fn has_projection_types(&self) -> bool;
7168 impl<'tcx,T:HasProjectionTypes> HasProjectionTypes for Vec<T> {
7169 fn has_projection_types(&self) -> bool {
7170 self.iter().any(|p| p.has_projection_types())
7174 impl<'tcx,T:HasProjectionTypes> HasProjectionTypes for VecPerParamSpace<T> {
7175 fn has_projection_types(&self) -> bool {
7176 self.iter().any(|p| p.has_projection_types())
7180 impl<'tcx> HasProjectionTypes for ClosureTy<'tcx> {
7181 fn has_projection_types(&self) -> bool {
7182 self.sig.has_projection_types()
7186 impl<'tcx> HasProjectionTypes for ClosureUpvar<'tcx> {
7187 fn has_projection_types(&self) -> bool {
7188 self.ty.has_projection_types()
7192 impl<'tcx> HasProjectionTypes for ty::InstantiatedPredicates<'tcx> {
7193 fn has_projection_types(&self) -> bool {
7194 self.predicates.has_projection_types()
7198 impl<'tcx> HasProjectionTypes for Predicate<'tcx> {
7199 fn has_projection_types(&self) -> bool {
7201 Predicate::Trait(ref data) => data.has_projection_types(),
7202 Predicate::Equate(ref data) => data.has_projection_types(),
7203 Predicate::RegionOutlives(ref data) => data.has_projection_types(),
7204 Predicate::TypeOutlives(ref data) => data.has_projection_types(),
7205 Predicate::Projection(ref data) => data.has_projection_types(),
7210 impl<'tcx> HasProjectionTypes for TraitPredicate<'tcx> {
7211 fn has_projection_types(&self) -> bool {
7212 self.trait_ref.has_projection_types()
7216 impl<'tcx> HasProjectionTypes for EquatePredicate<'tcx> {
7217 fn has_projection_types(&self) -> bool {
7218 self.0.has_projection_types() || self.1.has_projection_types()
7222 impl HasProjectionTypes for Region {
7223 fn has_projection_types(&self) -> bool {
7228 impl<T:HasProjectionTypes,U:HasProjectionTypes> HasProjectionTypes for OutlivesPredicate<T,U> {
7229 fn has_projection_types(&self) -> bool {
7230 self.0.has_projection_types() || self.1.has_projection_types()
7234 impl<'tcx> HasProjectionTypes for ProjectionPredicate<'tcx> {
7235 fn has_projection_types(&self) -> bool {
7236 self.projection_ty.has_projection_types() || self.ty.has_projection_types()
7240 impl<'tcx> HasProjectionTypes for ProjectionTy<'tcx> {
7241 fn has_projection_types(&self) -> bool {
7242 self.trait_ref.has_projection_types()
7246 impl<'tcx> HasProjectionTypes for Ty<'tcx> {
7247 fn has_projection_types(&self) -> bool {
7248 ty::type_has_projection(*self)
7252 impl<'tcx> HasProjectionTypes for TraitRef<'tcx> {
7253 fn has_projection_types(&self) -> bool {
7254 self.substs.has_projection_types()
7258 impl<'tcx> HasProjectionTypes for subst::Substs<'tcx> {
7259 fn has_projection_types(&self) -> bool {
7260 self.types.iter().any(|t| t.has_projection_types())
7264 impl<'tcx,T> HasProjectionTypes for Option<T>
7265 where T : HasProjectionTypes
7267 fn has_projection_types(&self) -> bool {
7268 self.iter().any(|t| t.has_projection_types())
7272 impl<'tcx,T> HasProjectionTypes for Rc<T>
7273 where T : HasProjectionTypes
7275 fn has_projection_types(&self) -> bool {
7276 (**self).has_projection_types()
7280 impl<'tcx,T> HasProjectionTypes for Box<T>
7281 where T : HasProjectionTypes
7283 fn has_projection_types(&self) -> bool {
7284 (**self).has_projection_types()
7288 impl<T> HasProjectionTypes for Binder<T>
7289 where T : HasProjectionTypes
7291 fn has_projection_types(&self) -> bool {
7292 self.0.has_projection_types()
7296 impl<'tcx> HasProjectionTypes for FnOutput<'tcx> {
7297 fn has_projection_types(&self) -> bool {
7299 FnConverging(t) => t.has_projection_types(),
7300 FnDiverging => false,
7305 impl<'tcx> HasProjectionTypes for FnSig<'tcx> {
7306 fn has_projection_types(&self) -> bool {
7307 self.inputs.iter().any(|t| t.has_projection_types()) ||
7308 self.output.has_projection_types()
7312 impl<'tcx> HasProjectionTypes for field<'tcx> {
7313 fn has_projection_types(&self) -> bool {
7314 self.mt.ty.has_projection_types()
7318 impl<'tcx> HasProjectionTypes for BareFnTy<'tcx> {
7319 fn has_projection_types(&self) -> bool {
7320 self.sig.has_projection_types()
7324 pub trait ReferencesError {
7325 fn references_error(&self) -> bool;
7328 impl<T:ReferencesError> ReferencesError for Binder<T> {
7329 fn references_error(&self) -> bool {
7330 self.0.references_error()
7334 impl<T:ReferencesError> ReferencesError for Rc<T> {
7335 fn references_error(&self) -> bool {
7336 (&**self).references_error()
7340 impl<'tcx> ReferencesError for TraitPredicate<'tcx> {
7341 fn references_error(&self) -> bool {
7342 self.trait_ref.references_error()
7346 impl<'tcx> ReferencesError for ProjectionPredicate<'tcx> {
7347 fn references_error(&self) -> bool {
7348 self.projection_ty.trait_ref.references_error() || self.ty.references_error()
7352 impl<'tcx> ReferencesError for TraitRef<'tcx> {
7353 fn references_error(&self) -> bool {
7354 self.input_types().iter().any(|t| t.references_error())
7358 impl<'tcx> ReferencesError for Ty<'tcx> {
7359 fn references_error(&self) -> bool {
7360 type_is_error(*self)
7364 impl<'tcx> ReferencesError for Predicate<'tcx> {
7365 fn references_error(&self) -> bool {
7367 Predicate::Trait(ref data) => data.references_error(),
7368 Predicate::Equate(ref data) => data.references_error(),
7369 Predicate::RegionOutlives(ref data) => data.references_error(),
7370 Predicate::TypeOutlives(ref data) => data.references_error(),
7371 Predicate::Projection(ref data) => data.references_error(),
7376 impl<A,B> ReferencesError for OutlivesPredicate<A,B>
7377 where A : ReferencesError, B : ReferencesError
7379 fn references_error(&self) -> bool {
7380 self.0.references_error() || self.1.references_error()
7384 impl<'tcx> ReferencesError for EquatePredicate<'tcx>
7386 fn references_error(&self) -> bool {
7387 self.0.references_error() || self.1.references_error()
7391 impl ReferencesError for Region
7393 fn references_error(&self) -> bool {
7398 impl<'tcx> Repr<'tcx> for ClosureTy<'tcx> {
7399 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7400 format!("ClosureTy({},{},{})",
7407 impl<'tcx> Repr<'tcx> for ClosureUpvar<'tcx> {
7408 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7409 format!("ClosureUpvar({},{})",
7415 impl<'tcx> Repr<'tcx> for field<'tcx> {
7416 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7417 format!("field({},{})",
7418 self.name.repr(tcx),
7423 impl<'a, 'tcx> Repr<'tcx> for ParameterEnvironment<'a, 'tcx> {
7424 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7425 format!("ParameterEnvironment(\
7427 implicit_region_bound={}, \
7429 self.free_substs.repr(tcx),
7430 self.implicit_region_bound.repr(tcx),
7431 self.caller_bounds.repr(tcx))
7435 impl<'tcx> Repr<'tcx> for ObjectLifetimeDefault {
7436 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7438 ObjectLifetimeDefault::Ambiguous => format!("Ambiguous"),
7439 ObjectLifetimeDefault::Specific(ref r) => r.repr(tcx),