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 // FIXME: (@jroesch) @eddyb should remove this when he renames ctxt
12 #![allow(non_camel_case_types)]
14 pub use self::InferTy::*;
15 pub use self::ImplOrTraitItemId::*;
16 pub use self::ClosureKind::*;
17 pub use self::Variance::*;
18 pub use self::AutoAdjustment::*;
19 pub use self::Representability::*;
20 pub use self::AutoRef::*;
21 pub use self::DtorKind::*;
22 pub use self::ExplicitSelfCategory::*;
23 pub use self::FnOutput::*;
24 pub use self::Region::*;
25 pub use self::ImplOrTraitItemContainer::*;
26 pub use self::BorrowKind::*;
27 pub use self::ImplOrTraitItem::*;
28 pub use self::BoundRegion::*;
29 pub use self::TypeVariants::*;
30 pub use self::IntVarValue::*;
31 pub use self::CopyImplementationError::*;
33 pub use self::BuiltinBound::Send as BoundSend;
34 pub use self::BuiltinBound::Sized as BoundSized;
35 pub use self::BuiltinBound::Copy as BoundCopy;
36 pub use self::BuiltinBound::Sync as BoundSync;
38 use ast_map::{self, LinkedPath};
42 use metadata::csearch;
45 use middle::check_const;
46 use middle::const_eval::{self, ConstVal, ErrKind};
47 use middle::const_eval::EvalHint::UncheckedExprHint;
48 use middle::def::{self, DefMap, ExportMap};
49 use middle::def_id::{DefId, LOCAL_CRATE};
50 use middle::fast_reject;
51 use middle::free_region::FreeRegionMap;
52 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
54 use middle::resolve_lifetime;
56 use middle::infer::type_variable;
58 use middle::region::RegionMaps;
59 use middle::stability;
60 use middle::subst::{self, ParamSpace, Subst, Substs, VecPerParamSpace};
63 use middle::ty_fold::{self, TypeFoldable, TypeFolder};
64 use middle::ty_walk::{self, TypeWalker};
65 use util::common::{memoized, ErrorReported};
66 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet};
67 use util::nodemap::FnvHashMap;
68 use util::num::ToPrimitive;
70 use arena::TypedArena;
71 use std::borrow::{Borrow, Cow};
72 use std::cell::{Cell, RefCell, Ref};
75 use std::hash::{Hash, SipHasher, Hasher};
77 use std::marker::PhantomData;
82 use std::vec::IntoIter;
83 use collections::enum_set::{self, EnumSet, CLike};
84 use core::nonzero::NonZero;
85 use std::collections::{HashMap, HashSet};
86 use rustc_data_structures::ivar;
88 use syntax::ast::{CrateNum, ItemImpl, ItemTrait};
89 use syntax::ast::{MutImmutable, MutMutable, Name, NodeId, Visibility};
90 use syntax::attr::{self, AttrMetaMethods, SignedInt, UnsignedInt};
91 use syntax::codemap::Span;
92 use syntax::parse::token::{InternedString, special_idents};
97 pub const INITIAL_DISCRIMINANT_VALUE: Disr = 0;
101 /// The complete set of all analyses described in this module. This is
102 /// produced by the driver and fed to trans and later passes.
103 pub struct CrateAnalysis {
104 pub export_map: ExportMap,
105 pub exported_items: middle::privacy::ExportedItems,
106 pub public_items: middle::privacy::PublicItems,
107 pub reachable: NodeSet,
109 pub glob_map: Option<GlobMap>,
112 #[derive(Copy, Clone)]
119 pub fn is_present(&self) -> bool {
121 TraitDtor(..) => true,
126 pub fn has_drop_flag(&self) -> bool {
129 &TraitDtor(flag) => flag
134 pub trait IntTypeExt {
135 fn to_ty<'tcx>(&self, cx: &ctxt<'tcx>) -> Ty<'tcx>;
136 fn i64_to_disr(&self, val: i64) -> Option<Disr>;
137 fn u64_to_disr(&self, val: u64) -> Option<Disr>;
138 fn disr_incr(&self, val: Disr) -> Option<Disr>;
139 fn disr_string(&self, val: Disr) -> String;
140 fn disr_wrap_incr(&self, val: Option<Disr>) -> Disr;
143 impl IntTypeExt for attr::IntType {
144 fn to_ty<'tcx>(&self, cx: &ctxt<'tcx>) -> Ty<'tcx> {
146 SignedInt(ast::TyI8) => cx.types.i8,
147 SignedInt(ast::TyI16) => cx.types.i16,
148 SignedInt(ast::TyI32) => cx.types.i32,
149 SignedInt(ast::TyI64) => cx.types.i64,
150 SignedInt(ast::TyIs) => cx.types.isize,
151 UnsignedInt(ast::TyU8) => cx.types.u8,
152 UnsignedInt(ast::TyU16) => cx.types.u16,
153 UnsignedInt(ast::TyU32) => cx.types.u32,
154 UnsignedInt(ast::TyU64) => cx.types.u64,
155 UnsignedInt(ast::TyUs) => cx.types.usize,
159 fn i64_to_disr(&self, val: i64) -> Option<Disr> {
161 SignedInt(ast::TyI8) => val.to_i8() .map(|v| v as Disr),
162 SignedInt(ast::TyI16) => val.to_i16() .map(|v| v as Disr),
163 SignedInt(ast::TyI32) => val.to_i32() .map(|v| v as Disr),
164 SignedInt(ast::TyI64) => val.to_i64() .map(|v| v as Disr),
165 UnsignedInt(ast::TyU8) => val.to_u8() .map(|v| v as Disr),
166 UnsignedInt(ast::TyU16) => val.to_u16() .map(|v| v as Disr),
167 UnsignedInt(ast::TyU32) => val.to_u32() .map(|v| v as Disr),
168 UnsignedInt(ast::TyU64) => val.to_u64() .map(|v| v as Disr),
170 UnsignedInt(ast::TyUs) |
171 SignedInt(ast::TyIs) => unreachable!(),
175 fn u64_to_disr(&self, val: u64) -> Option<Disr> {
177 SignedInt(ast::TyI8) => val.to_i8() .map(|v| v as Disr),
178 SignedInt(ast::TyI16) => val.to_i16() .map(|v| v as Disr),
179 SignedInt(ast::TyI32) => val.to_i32() .map(|v| v as Disr),
180 SignedInt(ast::TyI64) => val.to_i64() .map(|v| v as Disr),
181 UnsignedInt(ast::TyU8) => val.to_u8() .map(|v| v as Disr),
182 UnsignedInt(ast::TyU16) => val.to_u16() .map(|v| v as Disr),
183 UnsignedInt(ast::TyU32) => val.to_u32() .map(|v| v as Disr),
184 UnsignedInt(ast::TyU64) => val.to_u64() .map(|v| v as Disr),
186 UnsignedInt(ast::TyUs) |
187 SignedInt(ast::TyIs) => unreachable!(),
191 fn disr_incr(&self, val: Disr) -> Option<Disr> {
193 ($e:expr) => { $e.and_then(|v|v.checked_add(1)).map(|v| v as Disr) }
196 // SignedInt repr means we *want* to reinterpret the bits
197 // treating the highest bit of Disr as a sign-bit, so
198 // cast to i64 before range-checking.
199 SignedInt(ast::TyI8) => add1!((val as i64).to_i8()),
200 SignedInt(ast::TyI16) => add1!((val as i64).to_i16()),
201 SignedInt(ast::TyI32) => add1!((val as i64).to_i32()),
202 SignedInt(ast::TyI64) => add1!(Some(val as i64)),
204 UnsignedInt(ast::TyU8) => add1!(val.to_u8()),
205 UnsignedInt(ast::TyU16) => add1!(val.to_u16()),
206 UnsignedInt(ast::TyU32) => add1!(val.to_u32()),
207 UnsignedInt(ast::TyU64) => add1!(Some(val)),
209 UnsignedInt(ast::TyUs) |
210 SignedInt(ast::TyIs) => unreachable!(),
214 // This returns a String because (1.) it is only used for
215 // rendering an error message and (2.) a string can represent the
216 // full range from `i64::MIN` through `u64::MAX`.
217 fn disr_string(&self, val: Disr) -> String {
219 SignedInt(ast::TyI8) => format!("{}", val as i8 ),
220 SignedInt(ast::TyI16) => format!("{}", val as i16),
221 SignedInt(ast::TyI32) => format!("{}", val as i32),
222 SignedInt(ast::TyI64) => format!("{}", val as i64),
223 UnsignedInt(ast::TyU8) => format!("{}", val as u8 ),
224 UnsignedInt(ast::TyU16) => format!("{}", val as u16),
225 UnsignedInt(ast::TyU32) => format!("{}", val as u32),
226 UnsignedInt(ast::TyU64) => format!("{}", val as u64),
228 UnsignedInt(ast::TyUs) |
229 SignedInt(ast::TyIs) => unreachable!(),
233 fn disr_wrap_incr(&self, val: Option<Disr>) -> Disr {
235 ($e:expr) => { ($e).wrapping_add(1) as Disr }
237 let val = val.unwrap_or(ty::INITIAL_DISCRIMINANT_VALUE);
239 SignedInt(ast::TyI8) => add1!(val as i8 ),
240 SignedInt(ast::TyI16) => add1!(val as i16),
241 SignedInt(ast::TyI32) => add1!(val as i32),
242 SignedInt(ast::TyI64) => add1!(val as i64),
243 UnsignedInt(ast::TyU8) => add1!(val as u8 ),
244 UnsignedInt(ast::TyU16) => add1!(val as u16),
245 UnsignedInt(ast::TyU32) => add1!(val as u32),
246 UnsignedInt(ast::TyU64) => add1!(val as u64),
248 UnsignedInt(ast::TyUs) |
249 SignedInt(ast::TyIs) => unreachable!(),
254 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
255 pub enum ImplOrTraitItemContainer {
256 TraitContainer(DefId),
257 ImplContainer(DefId),
260 impl ImplOrTraitItemContainer {
261 pub fn id(&self) -> DefId {
263 TraitContainer(id) => id,
264 ImplContainer(id) => id,
270 pub enum ImplOrTraitItem<'tcx> {
271 ConstTraitItem(Rc<AssociatedConst<'tcx>>),
272 MethodTraitItem(Rc<Method<'tcx>>),
273 TypeTraitItem(Rc<AssociatedType<'tcx>>),
276 impl<'tcx> ImplOrTraitItem<'tcx> {
277 fn id(&self) -> ImplOrTraitItemId {
279 ConstTraitItem(ref associated_const) => {
280 ConstTraitItemId(associated_const.def_id)
282 MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
283 TypeTraitItem(ref associated_type) => {
284 TypeTraitItemId(associated_type.def_id)
289 pub fn def_id(&self) -> DefId {
291 ConstTraitItem(ref associated_const) => associated_const.def_id,
292 MethodTraitItem(ref method) => method.def_id,
293 TypeTraitItem(ref associated_type) => associated_type.def_id,
297 pub fn name(&self) -> ast::Name {
299 ConstTraitItem(ref associated_const) => associated_const.name,
300 MethodTraitItem(ref method) => method.name,
301 TypeTraitItem(ref associated_type) => associated_type.name,
305 pub fn vis(&self) -> ast::Visibility {
307 ConstTraitItem(ref associated_const) => associated_const.vis,
308 MethodTraitItem(ref method) => method.vis,
309 TypeTraitItem(ref associated_type) => associated_type.vis,
313 pub fn container(&self) -> ImplOrTraitItemContainer {
315 ConstTraitItem(ref associated_const) => associated_const.container,
316 MethodTraitItem(ref method) => method.container,
317 TypeTraitItem(ref associated_type) => associated_type.container,
321 pub fn as_opt_method(&self) -> Option<Rc<Method<'tcx>>> {
323 MethodTraitItem(ref m) => Some((*m).clone()),
329 #[derive(Clone, Copy, Debug)]
330 pub enum ImplOrTraitItemId {
331 ConstTraitItemId(DefId),
332 MethodTraitItemId(DefId),
333 TypeTraitItemId(DefId),
336 impl ImplOrTraitItemId {
337 pub fn def_id(&self) -> DefId {
339 ConstTraitItemId(def_id) => def_id,
340 MethodTraitItemId(def_id) => def_id,
341 TypeTraitItemId(def_id) => def_id,
346 #[derive(Clone, Debug)]
347 pub struct Method<'tcx> {
349 pub generics: Generics<'tcx>,
350 pub predicates: GenericPredicates<'tcx>,
351 pub fty: BareFnTy<'tcx>,
352 pub explicit_self: ExplicitSelfCategory,
353 pub vis: ast::Visibility,
355 pub container: ImplOrTraitItemContainer,
357 // If this method is provided, we need to know where it came from
358 pub provided_source: Option<DefId>
361 impl<'tcx> Method<'tcx> {
362 pub fn new(name: ast::Name,
363 generics: ty::Generics<'tcx>,
364 predicates: GenericPredicates<'tcx>,
366 explicit_self: ExplicitSelfCategory,
367 vis: ast::Visibility,
369 container: ImplOrTraitItemContainer,
370 provided_source: Option<DefId>)
375 predicates: predicates,
377 explicit_self: explicit_self,
380 container: container,
381 provided_source: provided_source
385 pub fn container_id(&self) -> DefId {
386 match self.container {
387 TraitContainer(id) => id,
388 ImplContainer(id) => id,
393 #[derive(Clone, Copy, Debug)]
394 pub struct AssociatedConst<'tcx> {
397 pub vis: ast::Visibility,
399 pub container: ImplOrTraitItemContainer,
400 pub default: Option<DefId>,
403 #[derive(Clone, Copy, Debug)]
404 pub struct AssociatedType<'tcx> {
406 pub ty: Option<Ty<'tcx>>,
407 pub vis: ast::Visibility,
409 pub container: ImplOrTraitItemContainer,
412 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
413 pub struct TypeAndMut<'tcx> {
415 pub mutbl: ast::Mutability,
418 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
419 pub struct ItemVariances {
420 pub types: VecPerParamSpace<Variance>,
421 pub regions: VecPerParamSpace<Variance>,
424 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
426 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
427 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
428 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
429 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
432 impl fmt::Debug for Variance {
433 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
434 f.write_str(match *self {
436 Contravariant => "-",
443 #[derive(Copy, Clone)]
444 pub enum AutoAdjustment<'tcx> {
445 AdjustReifyFnPointer, // go from a fn-item type to a fn-pointer type
446 AdjustUnsafeFnPointer, // go from a safe fn pointer to an unsafe fn pointer
447 AdjustDerefRef(AutoDerefRef<'tcx>),
450 /// Represents coercing a pointer to a different kind of pointer - where 'kind'
451 /// here means either or both of raw vs borrowed vs unique and fat vs thin.
453 /// We transform pointers by following the following steps in order:
454 /// 1. Deref the pointer `self.autoderefs` times (may be 0).
455 /// 2. If `autoref` is `Some(_)`, then take the address and produce either a
456 /// `&` or `*` pointer.
457 /// 3. If `unsize` is `Some(_)`, then apply the unsize transformation,
458 /// which will do things like convert thin pointers to fat
459 /// pointers, or convert structs containing thin pointers to
460 /// structs containing fat pointers, or convert between fat
461 /// pointers. We don't store the details of how the transform is
462 /// done (in fact, we don't know that, because it might depend on
463 /// the precise type parameters). We just store the target
464 /// type. Trans figures out what has to be done at monomorphization
465 /// time based on the precise source/target type at hand.
467 /// To make that more concrete, here are some common scenarios:
469 /// 1. The simplest cases are where the pointer is not adjusted fat vs thin.
470 /// Here the pointer will be dereferenced N times (where a dereference can
471 /// happen to to raw or borrowed pointers or any smart pointer which implements
472 /// Deref, including Box<_>). The number of dereferences is given by
473 /// `autoderefs`. It can then be auto-referenced zero or one times, indicated
474 /// by `autoref`, to either a raw or borrowed pointer. In these cases unsize is
477 /// 2. A thin-to-fat coercon involves unsizing the underlying data. We start
478 /// with a thin pointer, deref a number of times, unsize the underlying data,
479 /// then autoref. The 'unsize' phase may change a fixed length array to a
480 /// dynamically sized one, a concrete object to a trait object, or statically
481 /// sized struct to a dyncamically sized one. E.g., &[i32; 4] -> &[i32] is
486 /// autoderefs: 1, // &[i32; 4] -> [i32; 4]
487 /// autoref: Some(AutoPtr), // [i32] -> &[i32]
488 /// unsize: Some([i32]), // [i32; 4] -> [i32]
492 /// Note that for a struct, the 'deep' unsizing of the struct is not recorded.
493 /// E.g., `struct Foo<T> { x: T }` we can coerce &Foo<[i32; 4]> to &Foo<[i32]>
494 /// The autoderef and -ref are the same as in the above example, but the type
495 /// stored in `unsize` is `Foo<[i32]>`, we don't store any further detail about
496 /// the underlying conversions from `[i32; 4]` to `[i32]`.
498 /// 3. Coercing a `Box<T>` to `Box<Trait>` is an interesting special case. In
499 /// that case, we have the pointer we need coming in, so there are no
500 /// autoderefs, and no autoref. Instead we just do the `Unsize` transformation.
501 /// At some point, of course, `Box` should move out of the compiler, in which
502 /// case this is analogous to transformating a struct. E.g., Box<[i32; 4]> ->
503 /// Box<[i32]> is represented by:
509 /// unsize: Some(Box<[i32]>),
512 #[derive(Copy, Clone)]
513 pub struct AutoDerefRef<'tcx> {
514 /// Step 1. Apply a number of dereferences, producing an lvalue.
515 pub autoderefs: usize,
517 /// Step 2. Optionally produce a pointer/reference from the value.
518 pub autoref: Option<AutoRef<'tcx>>,
520 /// Step 3. Unsize a pointer/reference value, e.g. `&[T; n]` to
521 /// `&[T]`. The stored type is the target pointer type. Note that
522 /// the source could be a thin or fat pointer.
523 pub unsize: Option<Ty<'tcx>>,
526 #[derive(Copy, Clone, PartialEq, Debug)]
527 pub enum AutoRef<'tcx> {
528 /// Convert from T to &T.
529 AutoPtr(&'tcx Region, ast::Mutability),
531 /// Convert from T to *T.
532 /// Value to thin pointer.
533 AutoUnsafe(ast::Mutability),
536 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
537 pub enum CustomCoerceUnsized {
538 /// Records the index of the field being coerced.
542 #[derive(Clone, Copy, Debug)]
543 pub struct MethodCallee<'tcx> {
544 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
547 pub substs: &'tcx subst::Substs<'tcx>
550 /// With method calls, we store some extra information in
551 /// side tables (i.e method_map). We use
552 /// MethodCall as a key to index into these tables instead of
553 /// just directly using the expression's NodeId. The reason
554 /// for this being that we may apply adjustments (coercions)
555 /// with the resulting expression also needing to use the
556 /// side tables. The problem with this is that we don't
557 /// assign a separate NodeId to this new expression
558 /// and so it would clash with the base expression if both
559 /// needed to add to the side tables. Thus to disambiguate
560 /// we also keep track of whether there's an adjustment in
562 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
563 pub struct MethodCall {
564 pub expr_id: ast::NodeId,
569 pub fn expr(id: ast::NodeId) -> MethodCall {
576 pub fn autoderef(expr_id: ast::NodeId, autoderef: u32) -> MethodCall {
579 autoderef: 1 + autoderef
584 // maps from an expression id that corresponds to a method call to the details
585 // of the method to be invoked
586 pub type MethodMap<'tcx> = FnvHashMap<MethodCall, MethodCallee<'tcx>>;
588 // Contains information needed to resolve types and (in the future) look up
589 // the types of AST nodes.
590 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
591 pub struct CReaderCacheKey {
597 /// A restriction that certain types must be the same size. The use of
598 /// `transmute` gives rise to these restrictions. These generally
599 /// cannot be checked until trans; therefore, each call to `transmute`
600 /// will push one or more such restriction into the
601 /// `transmute_restrictions` vector during `intrinsicck`. They are
602 /// then checked during `trans` by the fn `check_intrinsics`.
603 #[derive(Copy, Clone)]
604 pub struct TransmuteRestriction<'tcx> {
605 /// The span whence the restriction comes.
608 /// The type being transmuted from.
609 pub original_from: Ty<'tcx>,
611 /// The type being transmuted to.
612 pub original_to: Ty<'tcx>,
614 /// The type being transmuted from, with all type parameters
615 /// substituted for an arbitrary representative. Not to be shown
617 pub substituted_from: Ty<'tcx>,
619 /// The type being transmuted to, with all type parameters
620 /// substituted for an arbitrary representative. Not to be shown
622 pub substituted_to: Ty<'tcx>,
624 /// NodeId of the transmute intrinsic.
629 pub struct CtxtArenas<'tcx> {
631 type_: TypedArena<TyS<'tcx>>,
632 substs: TypedArena<Substs<'tcx>>,
633 bare_fn: TypedArena<BareFnTy<'tcx>>,
634 region: TypedArena<Region>,
635 stability: TypedArena<attr::Stability>,
638 trait_defs: TypedArena<TraitDef<'tcx>>,
639 adt_defs: TypedArena<AdtDefData<'tcx, 'tcx>>,
642 impl<'tcx> CtxtArenas<'tcx> {
643 pub fn new() -> CtxtArenas<'tcx> {
645 type_: TypedArena::new(),
646 substs: TypedArena::new(),
647 bare_fn: TypedArena::new(),
648 region: TypedArena::new(),
649 stability: TypedArena::new(),
651 trait_defs: TypedArena::new(),
652 adt_defs: TypedArena::new()
657 pub struct CommonTypes<'tcx> {
675 pub struct Tables<'tcx> {
676 /// Stores the types for various nodes in the AST. Note that this table
677 /// is not guaranteed to be populated until after typeck. See
678 /// typeck::check::fn_ctxt for details.
679 pub node_types: NodeMap<Ty<'tcx>>,
681 /// Stores the type parameters which were substituted to obtain the type
682 /// of this node. This only applies to nodes that refer to entities
683 /// parameterized by type parameters, such as generic fns, types, or
685 pub item_substs: NodeMap<ItemSubsts<'tcx>>,
687 pub adjustments: NodeMap<ty::AutoAdjustment<'tcx>>,
689 pub method_map: MethodMap<'tcx>,
692 pub upvar_capture_map: UpvarCaptureMap,
694 /// Records the type of each closure. The def ID is the ID of the
695 /// expression defining the closure.
696 pub closure_tys: DefIdMap<ClosureTy<'tcx>>,
698 /// Records the type of each closure. The def ID is the ID of the
699 /// expression defining the closure.
700 pub closure_kinds: DefIdMap<ClosureKind>,
703 impl<'tcx> Tables<'tcx> {
704 pub fn empty() -> Tables<'tcx> {
706 node_types: FnvHashMap(),
707 item_substs: NodeMap(),
708 adjustments: NodeMap(),
709 method_map: FnvHashMap(),
710 upvar_capture_map: FnvHashMap(),
711 closure_tys: DefIdMap(),
712 closure_kinds: DefIdMap(),
717 /// The data structure to keep track of all the information that typechecker
718 /// generates so that so that it can be reused and doesn't have to be redone
720 pub struct ctxt<'tcx> {
721 /// The arenas that types etc are allocated from.
722 arenas: &'tcx CtxtArenas<'tcx>,
724 /// Specifically use a speedy hash algorithm for this hash map, it's used
726 // FIXME(eddyb) use a FnvHashSet<InternedTy<'tcx>> when equivalent keys can
727 // queried from a HashSet.
728 interner: RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>,
730 // FIXME as above, use a hashset if equivalent elements can be queried.
731 substs_interner: RefCell<FnvHashMap<&'tcx Substs<'tcx>, &'tcx Substs<'tcx>>>,
732 bare_fn_interner: RefCell<FnvHashMap<&'tcx BareFnTy<'tcx>, &'tcx BareFnTy<'tcx>>>,
733 region_interner: RefCell<FnvHashMap<&'tcx Region, &'tcx Region>>,
734 stability_interner: RefCell<FnvHashMap<&'tcx attr::Stability, &'tcx attr::Stability>>,
736 /// Common types, pre-interned for your convenience.
737 pub types: CommonTypes<'tcx>,
742 pub named_region_map: resolve_lifetime::NamedRegionMap,
744 pub region_maps: RegionMaps,
746 // For each fn declared in the local crate, type check stores the
747 // free-region relationships that were deduced from its where
748 // clauses and parameter types. These are then read-again by
749 // borrowck. (They are not used during trans, and hence are not
750 // serialized or needed for cross-crate fns.)
751 free_region_maps: RefCell<NodeMap<FreeRegionMap>>,
752 // FIXME: jroesch make this a refcell
754 pub tables: RefCell<Tables<'tcx>>,
756 /// Maps from a trait item to the trait item "descriptor"
757 pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem<'tcx>>>,
759 /// Maps from a trait def-id to a list of the def-ids of its trait items
760 pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
762 /// A cache for the trait_items() routine
763 pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem<'tcx>>>>>,
765 pub impl_trait_refs: RefCell<DefIdMap<Option<TraitRef<'tcx>>>>,
766 pub trait_defs: RefCell<DefIdMap<&'tcx TraitDef<'tcx>>>,
767 pub adt_defs: RefCell<DefIdMap<AdtDefMaster<'tcx>>>,
769 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
770 /// associated predicates.
771 pub predicates: RefCell<DefIdMap<GenericPredicates<'tcx>>>,
773 /// Maps from the def-id of a trait to the list of
774 /// super-predicates. This is a subset of the full list of
775 /// predicates. We store these in a separate map because we must
776 /// evaluate them even during type conversion, often before the
777 /// full predicates are available (note that supertraits have
778 /// additional acyclicity requirements).
779 pub super_predicates: RefCell<DefIdMap<GenericPredicates<'tcx>>>,
781 pub map: ast_map::Map<'tcx>,
782 pub freevars: RefCell<FreevarMap>,
783 pub tcache: RefCell<DefIdMap<TypeScheme<'tcx>>>,
784 pub rcache: RefCell<FnvHashMap<CReaderCacheKey, Ty<'tcx>>>,
785 pub tc_cache: RefCell<FnvHashMap<Ty<'tcx>, TypeContents>>,
786 pub ast_ty_to_ty_cache: RefCell<NodeMap<Ty<'tcx>>>,
787 pub ty_param_defs: RefCell<NodeMap<TypeParameterDef<'tcx>>>,
788 pub normalized_cache: RefCell<FnvHashMap<Ty<'tcx>, Ty<'tcx>>>,
789 pub lang_items: middle::lang_items::LanguageItems,
790 /// A mapping of fake provided method def_ids to the default implementation
791 pub provided_method_sources: RefCell<DefIdMap<DefId>>,
793 /// Maps from def-id of a type or region parameter to its
794 /// (inferred) variance.
795 pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
797 /// True if the variance has been computed yet; false otherwise.
798 pub variance_computed: Cell<bool>,
800 /// A method will be in this list if and only if it is a destructor.
801 pub destructors: RefCell<DefIdSet>,
803 /// Maps a DefId of a type to a list of its inherent impls.
804 /// Contains implementations of methods that are inherent to a type.
805 /// Methods in these implementations don't need to be exported.
806 pub inherent_impls: RefCell<DefIdMap<Rc<Vec<DefId>>>>,
808 /// Maps a DefId of an impl to a list of its items.
809 /// Note that this contains all of the impls that we know about,
810 /// including ones in other crates. It's not clear that this is the best
812 pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
814 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
815 /// present in this set can be warned about.
816 pub used_unsafe: RefCell<NodeSet>,
818 /// Set of nodes which mark locals as mutable which end up getting used at
819 /// some point. Local variable definitions not in this set can be warned
821 pub used_mut_nodes: RefCell<NodeSet>,
823 /// The set of external nominal types whose implementations have been read.
824 /// This is used for lazy resolution of methods.
825 pub populated_external_types: RefCell<DefIdSet>,
826 /// The set of external primitive types whose implementations have been read.
827 /// FIXME(arielb1): why is this separate from populated_external_types?
828 pub populated_external_primitive_impls: RefCell<DefIdSet>,
830 /// These caches are used by const_eval when decoding external constants.
831 pub extern_const_statics: RefCell<DefIdMap<ast::NodeId>>,
832 pub extern_const_variants: RefCell<DefIdMap<ast::NodeId>>,
833 pub extern_const_fns: RefCell<DefIdMap<ast::NodeId>>,
835 pub node_lint_levels: RefCell<FnvHashMap<(ast::NodeId, lint::LintId),
838 /// The types that must be asserted to be the same size for `transmute`
839 /// to be valid. We gather up these restrictions in the intrinsicck pass
840 /// and check them in trans.
841 pub transmute_restrictions: RefCell<Vec<TransmuteRestriction<'tcx>>>,
843 /// Maps any item's def-id to its stability index.
844 pub stability: RefCell<stability::Index<'tcx>>,
846 /// Caches the results of trait selection. This cache is used
847 /// for things that do not have to do with the parameters in scope.
848 pub selection_cache: traits::SelectionCache<'tcx>,
850 /// A set of predicates that have been fulfilled *somewhere*.
851 /// This is used to avoid duplicate work. Predicates are only
852 /// added to this set when they mention only "global" names
853 /// (i.e., no type or lifetime parameters).
854 pub fulfilled_predicates: RefCell<traits::FulfilledPredicates<'tcx>>,
856 /// Caches the representation hints for struct definitions.
857 pub repr_hint_cache: RefCell<DefIdMap<Rc<Vec<attr::ReprAttr>>>>,
859 /// Maps Expr NodeId's to their constant qualification.
860 pub const_qualif_map: RefCell<NodeMap<check_const::ConstQualif>>,
862 /// Caches CoerceUnsized kinds for impls on custom types.
863 pub custom_coerce_unsized_kinds: RefCell<DefIdMap<CustomCoerceUnsized>>,
865 /// Maps a cast expression to its kind. This is keyed on the
866 /// *from* expression of the cast, not the cast itself.
867 pub cast_kinds: RefCell<NodeMap<cast::CastKind>>,
869 /// Maps Fn items to a collection of fragment infos.
871 /// The main goal is to identify data (each of which may be moved
872 /// or assigned) whose subparts are not moved nor assigned
873 /// (i.e. their state is *unfragmented*) and corresponding ast
874 /// nodes where the path to that data is moved or assigned.
876 /// In the long term, unfragmented values will have their
877 /// destructor entirely driven by a single stack-local drop-flag,
878 /// and their parents, the collections of the unfragmented values
879 /// (or more simply, "fragmented values"), are mapped to the
880 /// corresponding collections of stack-local drop-flags.
882 /// (However, in the short term that is not the case; e.g. some
883 /// unfragmented paths still need to be zeroed, namely when they
884 /// reference parent data from an outer scope that was not
885 /// entirely moved, and therefore that needs to be zeroed so that
886 /// we do not get double-drop when we hit the end of the parent
889 /// Also: currently the table solely holds keys for node-ids of
890 /// unfragmented values (see `FragmentInfo` enum definition), but
891 /// longer-term we will need to also store mappings from
892 /// fragmented data to the set of unfragmented pieces that
894 pub fragment_infos: RefCell<DefIdMap<Vec<FragmentInfo>>>,
897 /// Describes the fragment-state associated with a NodeId.
899 /// Currently only unfragmented paths have entries in the table,
900 /// but longer-term this enum is expected to expand to also
901 /// include data for fragmented paths.
902 #[derive(Copy, Clone, Debug)]
903 pub enum FragmentInfo {
904 Moved { var: NodeId, move_expr: NodeId },
905 Assigned { var: NodeId, assign_expr: NodeId, assignee_id: NodeId },
908 impl<'tcx> ctxt<'tcx> {
909 pub fn node_types(&self) -> Ref<NodeMap<Ty<'tcx>>> {
910 fn projection<'a, 'tcx>(tables: &'a Tables<'tcx>) -> &'a NodeMap<Ty<'tcx>> {
914 Ref::map(self.tables.borrow(), projection)
917 pub fn node_type_insert(&self, id: NodeId, ty: Ty<'tcx>) {
918 self.tables.borrow_mut().node_types.insert(id, ty);
921 pub fn intern_trait_def(&self, def: TraitDef<'tcx>) -> &'tcx TraitDef<'tcx> {
922 let did = def.trait_ref.def_id;
923 let interned = self.arenas.trait_defs.alloc(def);
924 self.trait_defs.borrow_mut().insert(did, interned);
928 pub fn intern_adt_def(&self,
931 variants: Vec<VariantDefData<'tcx, 'tcx>>)
932 -> AdtDefMaster<'tcx> {
933 let def = AdtDefData::new(self, did, kind, variants);
934 let interned = self.arenas.adt_defs.alloc(def);
935 // this will need a transmute when reverse-variance is removed
936 self.adt_defs.borrow_mut().insert(did, interned);
940 pub fn intern_stability(&self, stab: attr::Stability) -> &'tcx attr::Stability {
941 if let Some(st) = self.stability_interner.borrow().get(&stab) {
945 let interned = self.arenas.stability.alloc(stab);
946 self.stability_interner.borrow_mut().insert(interned, interned);
950 pub fn store_free_region_map(&self, id: NodeId, map: FreeRegionMap) {
951 self.free_region_maps.borrow_mut()
955 pub fn free_region_map(&self, id: NodeId) -> FreeRegionMap {
956 self.free_region_maps.borrow()[&id].clone()
959 pub fn lift<T: ?Sized + Lift<'tcx>>(&self, value: &T) -> Option<T::Lifted> {
960 value.lift_to_tcx(self)
964 /// A trait implemented for all X<'a> types which can be safely and
965 /// efficiently converted to X<'tcx> as long as they are part of the
966 /// provided ty::ctxt<'tcx>.
967 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
968 /// by looking them up in their respective interners.
969 /// None is returned if the value or one of the components is not part
970 /// of the provided context.
971 /// For Ty, None can be returned if either the type interner doesn't
972 /// contain the TypeVariants key or if the address of the interned
973 /// pointer differs. The latter case is possible if a primitive type,
974 /// e.g. `()` or `u8`, was interned in a different context.
975 pub trait Lift<'tcx> {
977 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted>;
980 impl<'tcx, A: Lift<'tcx>, B: Lift<'tcx>> Lift<'tcx> for (A, B) {
981 type Lifted = (A::Lifted, B::Lifted);
982 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
983 tcx.lift(&self.0).and_then(|a| tcx.lift(&self.1).map(|b| (a, b)))
987 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for [T] {
988 type Lifted = Vec<T::Lifted>;
989 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
990 let mut result = Vec::with_capacity(self.len());
992 if let Some(value) = tcx.lift(x) {
1002 impl<'tcx> Lift<'tcx> for Region {
1004 fn lift_to_tcx(&self, _: &ctxt<'tcx>) -> Option<Region> {
1009 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
1010 type Lifted = Ty<'tcx>;
1011 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Ty<'tcx>> {
1012 if let Some(&ty) = tcx.interner.borrow().get(&self.sty) {
1013 if *self as *const _ == ty as *const _ {
1021 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
1022 type Lifted = &'tcx Substs<'tcx>;
1023 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<&'tcx Substs<'tcx>> {
1024 if let Some(&substs) = tcx.substs_interner.borrow().get(*self) {
1025 if *self as *const _ == substs as *const _ {
1026 return Some(substs);
1033 impl<'a, 'tcx> Lift<'tcx> for TraitRef<'a> {
1034 type Lifted = TraitRef<'tcx>;
1035 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<TraitRef<'tcx>> {
1036 tcx.lift(&self.substs).map(|substs| TraitRef {
1037 def_id: self.def_id,
1043 impl<'a, 'tcx> Lift<'tcx> for TraitPredicate<'a> {
1044 type Lifted = TraitPredicate<'tcx>;
1045 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<TraitPredicate<'tcx>> {
1046 tcx.lift(&self.trait_ref).map(|trait_ref| TraitPredicate {
1047 trait_ref: trait_ref
1052 impl<'a, 'tcx> Lift<'tcx> for EquatePredicate<'a> {
1053 type Lifted = EquatePredicate<'tcx>;
1054 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<EquatePredicate<'tcx>> {
1055 tcx.lift(&(self.0, self.1)).map(|(a, b)| EquatePredicate(a, b))
1059 impl<'tcx, A: Copy+Lift<'tcx>, B: Copy+Lift<'tcx>> Lift<'tcx> for OutlivesPredicate<A, B> {
1060 type Lifted = OutlivesPredicate<A::Lifted, B::Lifted>;
1061 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
1062 tcx.lift(&(self.0, self.1)).map(|(a, b)| OutlivesPredicate(a, b))
1066 impl<'a, 'tcx> Lift<'tcx> for ProjectionPredicate<'a> {
1067 type Lifted = ProjectionPredicate<'tcx>;
1068 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<ProjectionPredicate<'tcx>> {
1069 tcx.lift(&(self.projection_ty.trait_ref, self.ty)).map(|(trait_ref, ty)| {
1070 ProjectionPredicate {
1071 projection_ty: ProjectionTy {
1072 trait_ref: trait_ref,
1073 item_name: self.projection_ty.item_name
1081 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Binder<T> {
1082 type Lifted = Binder<T::Lifted>;
1083 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
1084 tcx.lift(&self.0).map(|x| Binder(x))
1090 use session::Session;
1093 use syntax::codemap;
1095 /// Marker type used for the scoped TLS slot.
1096 /// The type context cannot be used directly because the scoped TLS
1097 /// in libstd doesn't allow types generic over lifetimes.
1098 struct ThreadLocalTyCx;
1100 scoped_thread_local!(static TLS_TCX: ThreadLocalTyCx);
1102 fn span_debug(span: codemap::Span, f: &mut fmt::Formatter) -> fmt::Result {
1104 write!(f, "{}", tcx.sess.codemap().span_to_string(span))
1108 pub fn enter<'tcx, F: FnOnce(&ty::ctxt<'tcx>) -> R, R>(tcx: ty::ctxt<'tcx>, f: F)
1110 let result = codemap::SPAN_DEBUG.with(|span_dbg| {
1111 let original_span_debug = span_dbg.get();
1112 span_dbg.set(span_debug);
1113 let tls_ptr = &tcx as *const _ as *const ThreadLocalTyCx;
1114 let result = TLS_TCX.set(unsafe { &*tls_ptr }, || f(&tcx));
1115 span_dbg.set(original_span_debug);
1121 pub fn with<F: FnOnce(&ty::ctxt) -> R, R>(f: F) -> R {
1122 TLS_TCX.with(|tcx| f(unsafe { &*(tcx as *const _ as *const ty::ctxt) }))
1125 pub fn with_opt<F: FnOnce(Option<&ty::ctxt>) -> R, R>(f: F) -> R {
1126 if TLS_TCX.is_set() {
1127 with(|v| f(Some(v)))
1134 // Flags that we track on types. These flags are propagated upwards
1135 // through the type during type construction, so that we can quickly
1136 // check whether the type has various kinds of types in it without
1137 // recursing over the type itself.
1139 flags TypeFlags: u32 {
1140 const HAS_PARAMS = 1 << 0,
1141 const HAS_SELF = 1 << 1,
1142 const HAS_TY_INFER = 1 << 2,
1143 const HAS_RE_INFER = 1 << 3,
1144 const HAS_RE_EARLY_BOUND = 1 << 4,
1145 const HAS_FREE_REGIONS = 1 << 5,
1146 const HAS_TY_ERR = 1 << 6,
1147 const HAS_PROJECTION = 1 << 7,
1148 const HAS_TY_CLOSURE = 1 << 8,
1150 // true if there are "names" of types and regions and so forth
1151 // that are local to a particular fn
1152 const HAS_LOCAL_NAMES = 1 << 9,
1154 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
1155 TypeFlags::HAS_SELF.bits |
1156 TypeFlags::HAS_RE_EARLY_BOUND.bits,
1158 // Flags representing the nominal content of a type,
1159 // computed by FlagsComputation. If you add a new nominal
1160 // flag, it should be added here too.
1161 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
1162 TypeFlags::HAS_SELF.bits |
1163 TypeFlags::HAS_TY_INFER.bits |
1164 TypeFlags::HAS_RE_INFER.bits |
1165 TypeFlags::HAS_RE_EARLY_BOUND.bits |
1166 TypeFlags::HAS_FREE_REGIONS.bits |
1167 TypeFlags::HAS_TY_ERR.bits |
1168 TypeFlags::HAS_PROJECTION.bits |
1169 TypeFlags::HAS_TY_CLOSURE.bits |
1170 TypeFlags::HAS_LOCAL_NAMES.bits,
1172 // Caches for type_is_sized, type_moves_by_default
1173 const SIZEDNESS_CACHED = 1 << 16,
1174 const IS_SIZED = 1 << 17,
1175 const MOVENESS_CACHED = 1 << 18,
1176 const MOVES_BY_DEFAULT = 1 << 19,
1180 macro_rules! sty_debug_print {
1181 ($ctxt: expr, $($variant: ident),*) => {{
1182 // curious inner module to allow variant names to be used as
1184 #[allow(non_snake_case)]
1187 #[derive(Copy, Clone)]
1190 region_infer: usize,
1195 pub fn go(tcx: &ty::ctxt) {
1196 let mut total = DebugStat {
1198 region_infer: 0, ty_infer: 0, both_infer: 0,
1200 $(let mut $variant = total;)*
1203 for (_, t) in tcx.interner.borrow().iter() {
1204 let variant = match t.sty {
1205 ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1206 ty::TyFloat(..) | ty::TyStr => continue,
1207 ty::TyError => /* unimportant */ continue,
1208 $(ty::$variant(..) => &mut $variant,)*
1210 let region = t.flags.get().intersects(ty::TypeFlags::HAS_RE_INFER);
1211 let ty = t.flags.get().intersects(ty::TypeFlags::HAS_TY_INFER);
1215 if region { total.region_infer += 1; variant.region_infer += 1 }
1216 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1217 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1219 println!("Ty interner total ty region both");
1220 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
1221 {ty:4.1}% {region:5.1}% {both:4.1}%",
1222 stringify!($variant),
1223 uses = $variant.total,
1224 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1225 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1226 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
1227 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
1229 println!(" total {uses:6} \
1230 {ty:4.1}% {region:5.1}% {both:4.1}%",
1232 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1233 region = total.region_infer as f64 * 100.0 / total.total as f64,
1234 both = total.both_infer as f64 * 100.0 / total.total as f64)
1242 impl<'tcx> ctxt<'tcx> {
1243 pub fn print_debug_stats(&self) {
1246 TyEnum, TyBox, TyArray, TySlice, TyRawPtr, TyRef, TyBareFn, TyTrait,
1247 TyStruct, TyClosure, TyTuple, TyParam, TyInfer, TyProjection);
1249 println!("Substs interner: #{}", self.substs_interner.borrow().len());
1250 println!("BareFnTy interner: #{}", self.bare_fn_interner.borrow().len());
1251 println!("Region interner: #{}", self.region_interner.borrow().len());
1252 println!("Stability interner: #{}", self.stability_interner.borrow().len());
1256 pub struct TyS<'tcx> {
1257 pub sty: TypeVariants<'tcx>,
1258 pub flags: Cell<TypeFlags>,
1260 // the maximal depth of any bound regions appearing in this type.
1264 impl fmt::Debug for TypeFlags {
1265 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1266 write!(f, "{}", self.bits)
1270 impl<'tcx> PartialEq for TyS<'tcx> {
1272 fn eq(&self, other: &TyS<'tcx>) -> bool {
1273 // (self as *const _) == (other as *const _)
1274 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
1277 impl<'tcx> Eq for TyS<'tcx> {}
1279 impl<'tcx> Hash for TyS<'tcx> {
1280 fn hash<H: Hasher>(&self, s: &mut H) {
1281 (self as *const TyS).hash(s)
1285 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
1287 /// An IVar that contains a Ty. 'lt is a (reverse-variant) upper bound
1288 /// on the lifetime of the IVar. This is required because of variance
1289 /// problems: the IVar needs to be variant with respect to 'tcx (so
1290 /// it can be referred to from Ty) but can only be modified if its
1291 /// lifetime is exactly 'tcx.
1293 /// Safety invariants:
1294 /// (A) self.0, if fulfilled, is a valid Ty<'tcx>
1295 /// (B) no aliases to this value with a 'tcx longer than this
1296 /// value's 'lt exist
1298 /// NonZero is used rather than Unique because Unique isn't Copy.
1299 pub struct TyIVar<'tcx, 'lt: 'tcx>(ivar::Ivar<NonZero<*const TyS<'static>>>,
1300 PhantomData<fn(TyS<'lt>)->TyS<'tcx>>);
1302 impl<'tcx, 'lt> TyIVar<'tcx, 'lt> {
1304 pub fn new() -> Self {
1305 // Invariant (A) satisfied because the IVar is unfulfilled
1306 // Invariant (B) because 'lt : 'tcx
1307 TyIVar(ivar::Ivar::new(), PhantomData)
1311 pub fn get(&self) -> Option<Ty<'tcx>> {
1312 match self.0.get() {
1314 // valid because of invariant (A)
1315 Some(v) => Some(unsafe { &*(*v as *const TyS<'tcx>) })
1319 pub fn unwrap(&self) -> Ty<'tcx> {
1323 pub fn fulfill(&self, value: Ty<'lt>) {
1324 // Invariant (A) is fulfilled, because by (B), every alias
1325 // of this has a 'tcx longer than 'lt.
1326 let value: *const TyS<'lt> = value;
1327 // FIXME(27214): unneeded [as *const ()]
1328 let value = value as *const () as *const TyS<'static>;
1329 self.0.fulfill(unsafe { NonZero::new(value) })
1333 impl<'tcx, 'lt> fmt::Debug for TyIVar<'tcx, 'lt> {
1334 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1336 Some(val) => write!(f, "TyIVar({:?})", val),
1337 None => f.write_str("TyIVar(<unfulfilled>)")
1342 /// An entry in the type interner.
1343 pub struct InternedTy<'tcx> {
1347 // NB: An InternedTy compares and hashes as a sty.
1348 impl<'tcx> PartialEq for InternedTy<'tcx> {
1349 fn eq(&self, other: &InternedTy<'tcx>) -> bool {
1350 self.ty.sty == other.ty.sty
1354 impl<'tcx> Eq for InternedTy<'tcx> {}
1356 impl<'tcx> Hash for InternedTy<'tcx> {
1357 fn hash<H: Hasher>(&self, s: &mut H) {
1362 impl<'tcx> Borrow<TypeVariants<'tcx>> for InternedTy<'tcx> {
1363 fn borrow<'a>(&'a self) -> &'a TypeVariants<'tcx> {
1368 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1369 pub struct BareFnTy<'tcx> {
1370 pub unsafety: ast::Unsafety,
1372 pub sig: PolyFnSig<'tcx>,
1375 #[derive(Clone, PartialEq, Eq, Hash)]
1376 pub struct ClosureTy<'tcx> {
1377 pub unsafety: ast::Unsafety,
1379 pub sig: PolyFnSig<'tcx>,
1382 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1383 pub enum FnOutput<'tcx> {
1384 FnConverging(Ty<'tcx>),
1388 impl<'tcx> FnOutput<'tcx> {
1389 pub fn diverges(&self) -> bool {
1390 *self == FnDiverging
1393 pub fn unwrap(self) -> Ty<'tcx> {
1395 ty::FnConverging(t) => t,
1396 ty::FnDiverging => unreachable!()
1400 pub fn unwrap_or(self, def: Ty<'tcx>) -> Ty<'tcx> {
1402 ty::FnConverging(t) => t,
1403 ty::FnDiverging => def
1408 pub type PolyFnOutput<'tcx> = Binder<FnOutput<'tcx>>;
1410 impl<'tcx> PolyFnOutput<'tcx> {
1411 pub fn diverges(&self) -> bool {
1416 /// Signature of a function type, which I have arbitrarily
1417 /// decided to use to refer to the input/output types.
1419 /// - `inputs` is the list of arguments and their modes.
1420 /// - `output` is the return type.
1421 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
1422 #[derive(Clone, PartialEq, Eq, Hash)]
1423 pub struct FnSig<'tcx> {
1424 pub inputs: Vec<Ty<'tcx>>,
1425 pub output: FnOutput<'tcx>,
1429 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1431 impl<'tcx> PolyFnSig<'tcx> {
1432 pub fn inputs(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
1433 self.map_bound_ref(|fn_sig| fn_sig.inputs.clone())
1435 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
1436 self.map_bound_ref(|fn_sig| fn_sig.inputs[index])
1438 pub fn output(&self) -> ty::Binder<FnOutput<'tcx>> {
1439 self.map_bound_ref(|fn_sig| fn_sig.output.clone())
1441 pub fn variadic(&self) -> bool {
1442 self.skip_binder().variadic
1446 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1447 pub struct ParamTy {
1448 pub space: subst::ParamSpace,
1450 pub name: ast::Name,
1453 /// A [De Bruijn index][dbi] is a standard means of representing
1454 /// regions (and perhaps later types) in a higher-ranked setting. In
1455 /// particular, imagine a type like this:
1457 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
1460 /// | +------------+ 1 | |
1462 /// +--------------------------------+ 2 |
1464 /// +------------------------------------------+ 1
1466 /// In this type, there are two binders (the outer fn and the inner
1467 /// fn). We need to be able to determine, for any given region, which
1468 /// fn type it is bound by, the inner or the outer one. There are
1469 /// various ways you can do this, but a De Bruijn index is one of the
1470 /// more convenient and has some nice properties. The basic idea is to
1471 /// count the number of binders, inside out. Some examples should help
1472 /// clarify what I mean.
1474 /// Let's start with the reference type `&'b isize` that is the first
1475 /// argument to the inner function. This region `'b` is assigned a De
1476 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
1477 /// fn). The region `'a` that appears in the second argument type (`&'a
1478 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
1479 /// second-innermost binder". (These indices are written on the arrays
1480 /// in the diagram).
1482 /// What is interesting is that De Bruijn index attached to a particular
1483 /// variable will vary depending on where it appears. For example,
1484 /// the final type `&'a char` also refers to the region `'a` declared on
1485 /// the outermost fn. But this time, this reference is not nested within
1486 /// any other binders (i.e., it is not an argument to the inner fn, but
1487 /// rather the outer one). Therefore, in this case, it is assigned a
1488 /// De Bruijn index of 1, because the innermost binder in that location
1489 /// is the outer fn.
1491 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1492 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
1493 pub struct DebruijnIndex {
1494 // We maintain the invariant that this is never 0. So 1 indicates
1495 // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
1499 /// Representation of regions.
1501 /// Unlike types, most region variants are "fictitious", not concrete,
1502 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1503 /// ones representing concrete regions.
1505 /// ## Bound Regions
1507 /// These are regions that are stored behind a binder and must be substituted
1508 /// with some concrete region before being used. There are 2 kind of
1509 /// bound regions: early-bound, which are bound in a TypeScheme/TraitDef,
1510 /// and are substituted by a Substs, and late-bound, which are part of
1511 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
1512 /// the likes of `liberate_late_bound_regions`. The distinction exists
1513 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1515 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
1516 /// outside their binder, e.g. in types passed to type inference, and
1517 /// should first be substituted (by skolemized regions, free regions,
1518 /// or region variables).
1520 /// ## Skolemized and Free Regions
1522 /// One often wants to work with bound regions without knowing their precise
1523 /// identity. For example, when checking a function, the lifetime of a borrow
1524 /// can end up being assigned to some region parameter. In these cases,
1525 /// it must be ensured that bounds on the region can't be accidentally
1526 /// assumed without being checked.
1528 /// The process of doing that is called "skolemization". The bound regions
1529 /// are replaced by skolemized markers, which don't satisfy any relation
1530 /// not explicity provided.
1532 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
1533 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
1534 /// to be used. These also support explicit bounds: both the internally-stored
1535 /// *scope*, which the region is assumed to outlive, as well as other
1536 /// relations stored in the `FreeRegionMap`. Note that these relations
1537 /// aren't checked when you `make_subregion` (or `mk_eqty`), only by
1538 /// `resolve_regions_and_report_errors`.
1540 /// When working with higher-ranked types, some region relations aren't
1541 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1542 /// `ReSkolemized` is designed for this purpose. In these contexts,
1543 /// there's also the risk that some inference variable laying around will
1544 /// get unified with your skolemized region: if you want to check whether
1545 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1546 /// with a skolemized region `'%a`, the variable `'_` would just be
1547 /// instantiated to the skolemized region `'%a`, which is wrong because
1548 /// the inference variable is supposed to satisfy the relation
1549 /// *for every value of the skolemized region*. To ensure that doesn't
1550 /// happen, you can use `leak_check`. This is more clearly explained
1551 /// by infer/higher_ranked/README.md.
1553 /// [1] http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1554 /// [2] http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1555 #[derive(Clone, PartialEq, Eq, Hash, Copy)]
1557 // Region bound in a type or fn declaration which will be
1558 // substituted 'early' -- that is, at the same time when type
1559 // parameters are substituted.
1560 ReEarlyBound(EarlyBoundRegion),
1562 // Region bound in a function scope, which will be substituted when the
1563 // function is called.
1564 ReLateBound(DebruijnIndex, BoundRegion),
1566 /// When checking a function body, the types of all arguments and so forth
1567 /// that refer to bound region parameters are modified to refer to free
1568 /// region parameters.
1571 /// A concrete region naming some statically determined extent
1572 /// (e.g. an expression or sequence of statements) within the
1573 /// current function.
1574 ReScope(region::CodeExtent),
1576 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1579 /// A region variable. Should not exist after typeck.
1582 /// A skolemized region - basically the higher-ranked version of ReFree.
1583 /// Should not exist after typeck.
1584 ReSkolemized(SkolemizedRegionVid, BoundRegion),
1586 /// Empty lifetime is for data that is never accessed.
1587 /// Bottom in the region lattice. We treat ReEmpty somewhat
1588 /// specially; at least right now, we do not generate instances of
1589 /// it during the GLB computations, but rather
1590 /// generate an error instead. This is to improve error messages.
1591 /// The only way to get an instance of ReEmpty is to have a region
1592 /// variable with no constraints.
1596 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
1597 pub struct EarlyBoundRegion {
1598 pub param_id: ast::NodeId,
1599 pub space: subst::ParamSpace,
1601 pub name: ast::Name,
1604 /// Upvars do not get their own node-id. Instead, we use the pair of
1605 /// the original var id (that is, the root variable that is referenced
1606 /// by the upvar) and the id of the closure expression.
1607 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1608 pub struct UpvarId {
1609 pub var_id: ast::NodeId,
1610 pub closure_expr_id: ast::NodeId,
1613 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
1614 pub enum BorrowKind {
1615 /// Data must be immutable and is aliasable.
1618 /// Data must be immutable but not aliasable. This kind of borrow
1619 /// cannot currently be expressed by the user and is used only in
1620 /// implicit closure bindings. It is needed when you the closure
1621 /// is borrowing or mutating a mutable referent, e.g.:
1623 /// let x: &mut isize = ...;
1624 /// let y = || *x += 5;
1626 /// If we were to try to translate this closure into a more explicit
1627 /// form, we'd encounter an error with the code as written:
1629 /// struct Env { x: & &mut isize }
1630 /// let x: &mut isize = ...;
1631 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
1632 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1634 /// This is then illegal because you cannot mutate a `&mut` found
1635 /// in an aliasable location. To solve, you'd have to translate with
1636 /// an `&mut` borrow:
1638 /// struct Env { x: & &mut isize }
1639 /// let x: &mut isize = ...;
1640 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
1641 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1643 /// Now the assignment to `**env.x` is legal, but creating a
1644 /// mutable pointer to `x` is not because `x` is not mutable. We
1645 /// could fix this by declaring `x` as `let mut x`. This is ok in
1646 /// user code, if awkward, but extra weird for closures, since the
1647 /// borrow is hidden.
1649 /// So we introduce a "unique imm" borrow -- the referent is
1650 /// immutable, but not aliasable. This solves the problem. For
1651 /// simplicity, we don't give users the way to express this
1652 /// borrow, it's just used when translating closures.
1655 /// Data is mutable and not aliasable.
1659 /// Information describing the capture of an upvar. This is computed
1660 /// during `typeck`, specifically by `regionck`.
1661 #[derive(PartialEq, Clone, Debug, Copy)]
1662 pub enum UpvarCapture {
1663 /// Upvar is captured by value. This is always true when the
1664 /// closure is labeled `move`, but can also be true in other cases
1665 /// depending on inference.
1668 /// Upvar is captured by reference.
1672 #[derive(PartialEq, Clone, Copy)]
1673 pub struct UpvarBorrow {
1674 /// The kind of borrow: by-ref upvars have access to shared
1675 /// immutable borrows, which are not part of the normal language
1677 pub kind: BorrowKind,
1679 /// Region of the resulting reference.
1680 pub region: ty::Region,
1683 pub type UpvarCaptureMap = FnvHashMap<UpvarId, UpvarCapture>;
1685 #[derive(Copy, Clone)]
1686 pub struct ClosureUpvar<'tcx> {
1693 pub fn is_bound(&self) -> bool {
1695 ty::ReEarlyBound(..) => true,
1696 ty::ReLateBound(..) => true,
1701 pub fn needs_infer(&self) -> bool {
1703 ty::ReVar(..) | ty::ReSkolemized(..) => true,
1708 pub fn escapes_depth(&self, depth: u32) -> bool {
1710 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1715 /// Returns the depth of `self` from the (1-based) binding level `depth`
1716 pub fn from_depth(&self, depth: u32) -> Region {
1718 ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
1719 depth: debruijn.depth - (depth - 1)
1726 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1727 RustcEncodable, RustcDecodable, Copy)]
1728 /// A "free" region `fr` can be interpreted as "some region
1729 /// at least as big as the scope `fr.scope`".
1730 pub struct FreeRegion {
1731 pub scope: region::CodeExtent,
1732 pub bound_region: BoundRegion
1735 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1736 RustcEncodable, RustcDecodable, Copy)]
1737 pub enum BoundRegion {
1738 /// An anonymous region parameter for a given fn (&T)
1741 /// Named region parameters for functions (a in &'a T)
1743 /// The def-id is needed to distinguish free regions in
1744 /// the event of shadowing.
1745 BrNamed(DefId, ast::Name),
1747 /// Fresh bound identifiers created during GLB computations.
1750 // Anonymous region for the implicit env pointer parameter
1755 // NB: If you change this, you'll probably want to change the corresponding
1756 // AST structure in libsyntax/ast.rs as well.
1757 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1758 pub enum TypeVariants<'tcx> {
1759 /// The primitive boolean type. Written as `bool`.
1762 /// The primitive character type; holds a Unicode scalar value
1763 /// (a non-surrogate code point). Written as `char`.
1766 /// A primitive signed integer type. For example, `i32`.
1769 /// A primitive unsigned integer type. For example, `u32`.
1770 TyUint(ast::UintTy),
1772 /// A primitive floating-point type. For example, `f64`.
1773 TyFloat(ast::FloatTy),
1775 /// An enumerated type, defined with `enum`.
1777 /// Substs here, possibly against intuition, *may* contain `TyParam`s.
1778 /// That is, even after substitution it is possible that there are type
1779 /// variables. This happens when the `TyEnum` corresponds to an enum
1780 /// definition and not a concrete use of it. To get the correct `TyEnum`
1781 /// from the tcx, use the `NodeId` from the `ast::Ty` and look it up in
1782 /// the `ast_ty_to_ty_cache`. This is probably true for `TyStruct` as
1784 TyEnum(AdtDef<'tcx>, &'tcx Substs<'tcx>),
1786 /// A structure type, defined with `struct`.
1788 /// See warning about substitutions for enumerated types.
1789 TyStruct(AdtDef<'tcx>, &'tcx Substs<'tcx>),
1791 /// `Box<T>`; this is nominally a struct in the documentation, but is
1792 /// special-cased internally. For example, it is possible to implicitly
1793 /// move the contents of a box out of that box, and methods of any type
1794 /// can have type `Box<Self>`.
1797 /// The pointee of a string slice. Written as `str`.
1800 /// An array with the given length. Written as `[T; n]`.
1801 TyArray(Ty<'tcx>, usize),
1803 /// The pointee of an array slice. Written as `[T]`.
1806 /// A raw pointer. Written as `*mut T` or `*const T`
1807 TyRawPtr(TypeAndMut<'tcx>),
1809 /// A reference; a pointer with an associated lifetime. Written as
1810 /// `&a mut T` or `&'a T`.
1811 TyRef(&'tcx Region, TypeAndMut<'tcx>),
1813 /// If the def-id is Some(_), then this is the type of a specific
1814 /// fn item. Otherwise, if None(_), it a fn pointer type.
1816 /// FIXME: Conflating function pointers and the type of a
1817 /// function is probably a terrible idea; a function pointer is a
1818 /// value with a specific type, but a function can be polymorphic
1819 /// or dynamically dispatched.
1820 TyBareFn(Option<DefId>, &'tcx BareFnTy<'tcx>),
1822 /// A trait, defined with `trait`.
1823 TyTrait(Box<TraitTy<'tcx>>),
1825 /// The anonymous type of a closure. Used to represent the type of
1827 TyClosure(DefId, Box<ClosureSubsts<'tcx>>),
1829 /// A tuple type. For example, `(i32, bool)`.
1830 TyTuple(Vec<Ty<'tcx>>),
1832 /// The projection of an associated type. For example,
1833 /// `<T as Trait<..>>::N`.
1834 TyProjection(ProjectionTy<'tcx>),
1836 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
1839 /// A type variable used during type-checking.
1842 /// A placeholder for a type which could not be computed; this is
1843 /// propagated to avoid useless error messages.
1847 /// A closure can be modeled as a struct that looks like:
1849 /// struct Closure<'l0...'li, T0...Tj, U0...Uk> {
1855 /// where 'l0...'li and T0...Tj are the lifetime and type parameters
1856 /// in scope on the function that defined the closure, and U0...Uk are
1857 /// type parameters representing the types of its upvars (borrowed, if
1860 /// So, for example, given this function:
1862 /// fn foo<'a, T>(data: &'a mut T) {
1863 /// do(|| data.count += 1)
1866 /// the type of the closure would be something like:
1868 /// struct Closure<'a, T, U0> {
1872 /// Note that the type of the upvar is not specified in the struct.
1873 /// You may wonder how the impl would then be able to use the upvar,
1874 /// if it doesn't know it's type? The answer is that the impl is
1875 /// (conceptually) not fully generic over Closure but rather tied to
1876 /// instances with the expected upvar types:
1878 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
1882 /// You can see that the *impl* fully specified the type of the upvar
1883 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
1884 /// (Here, I am assuming that `data` is mut-borrowed.)
1886 /// Now, the last question you may ask is: Why include the upvar types
1887 /// as extra type parameters? The reason for this design is that the
1888 /// upvar types can reference lifetimes that are internal to the
1889 /// creating function. In my example above, for example, the lifetime
1890 /// `'b` represents the extent of the closure itself; this is some
1891 /// subset of `foo`, probably just the extent of the call to the to
1892 /// `do()`. If we just had the lifetime/type parameters from the
1893 /// enclosing function, we couldn't name this lifetime `'b`. Note that
1894 /// there can also be lifetimes in the types of the upvars themselves,
1895 /// if one of them happens to be a reference to something that the
1896 /// creating fn owns.
1898 /// OK, you say, so why not create a more minimal set of parameters
1899 /// that just includes the extra lifetime parameters? The answer is
1900 /// primarily that it would be hard --- we don't know at the time when
1901 /// we create the closure type what the full types of the upvars are,
1902 /// nor do we know which are borrowed and which are not. In this
1903 /// design, we can just supply a fresh type parameter and figure that
1906 /// All right, you say, but why include the type parameters from the
1907 /// original function then? The answer is that trans may need them
1908 /// when monomorphizing, and they may not appear in the upvars. A
1909 /// closure could capture no variables but still make use of some
1910 /// in-scope type parameter with a bound (e.g., if our example above
1911 /// had an extra `U: Default`, and the closure called `U::default()`).
1913 /// There is another reason. This design (implicitly) prohibits
1914 /// closures from capturing themselves (except via a trait
1915 /// object). This simplifies closure inference considerably, since it
1916 /// means that when we infer the kind of a closure or its upvars, we
1917 /// don't have to handle cycles where the decisions we make for
1918 /// closure C wind up influencing the decisions we ought to make for
1919 /// closure C (which would then require fixed point iteration to
1920 /// handle). Plus it fixes an ICE. :P
1921 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1922 pub struct ClosureSubsts<'tcx> {
1923 /// Lifetime and type parameters from the enclosing function.
1924 /// These are separated out because trans wants to pass them around
1925 /// when monomorphizing.
1926 pub func_substs: &'tcx Substs<'tcx>,
1928 /// The types of the upvars. The list parallels the freevars and
1929 /// `upvar_borrows` lists. These are kept distinct so that we can
1930 /// easily index into them.
1931 pub upvar_tys: Vec<Ty<'tcx>>
1934 #[derive(Clone, PartialEq, Eq, Hash)]
1935 pub struct TraitTy<'tcx> {
1936 pub principal: ty::PolyTraitRef<'tcx>,
1937 pub bounds: ExistentialBounds<'tcx>,
1940 impl<'tcx> TraitTy<'tcx> {
1941 pub fn principal_def_id(&self) -> DefId {
1942 self.principal.0.def_id
1945 /// Object types don't have a self-type specified. Therefore, when
1946 /// we convert the principal trait-ref into a normal trait-ref,
1947 /// you must give *some* self-type. A common choice is `mk_err()`
1948 /// or some skolemized type.
1949 pub fn principal_trait_ref_with_self_ty(&self,
1952 -> ty::PolyTraitRef<'tcx>
1954 // otherwise the escaping regions would be captured by the binder
1955 assert!(!self_ty.has_escaping_regions());
1957 ty::Binder(TraitRef {
1958 def_id: self.principal.0.def_id,
1959 substs: tcx.mk_substs(self.principal.0.substs.with_self_ty(self_ty)),
1963 pub fn projection_bounds_with_self_ty(&self,
1966 -> Vec<ty::PolyProjectionPredicate<'tcx>>
1968 // otherwise the escaping regions would be captured by the binders
1969 assert!(!self_ty.has_escaping_regions());
1971 self.bounds.projection_bounds.iter()
1972 .map(|in_poly_projection_predicate| {
1973 let in_projection_ty = &in_poly_projection_predicate.0.projection_ty;
1974 let substs = tcx.mk_substs(in_projection_ty.trait_ref.substs.with_self_ty(self_ty));
1975 let trait_ref = ty::TraitRef::new(in_projection_ty.trait_ref.def_id,
1977 let projection_ty = ty::ProjectionTy {
1978 trait_ref: trait_ref,
1979 item_name: in_projection_ty.item_name
1981 ty::Binder(ty::ProjectionPredicate {
1982 projection_ty: projection_ty,
1983 ty: in_poly_projection_predicate.0.ty
1990 /// A complete reference to a trait. These take numerous guises in syntax,
1991 /// but perhaps the most recognizable form is in a where clause:
1995 /// This would be represented by a trait-reference where the def-id is the
1996 /// def-id for the trait `Foo` and the substs defines `T` as parameter 0 in the
1997 /// `SelfSpace` and `U` as parameter 0 in the `TypeSpace`.
1999 /// Trait references also appear in object types like `Foo<U>`, but in
2000 /// that case the `Self` parameter is absent from the substitutions.
2002 /// Note that a `TraitRef` introduces a level of region binding, to
2003 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
2004 /// U>` or higher-ranked object types.
2005 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2006 pub struct TraitRef<'tcx> {
2008 pub substs: &'tcx Substs<'tcx>,
2011 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
2013 impl<'tcx> PolyTraitRef<'tcx> {
2014 pub fn self_ty(&self) -> Ty<'tcx> {
2018 pub fn def_id(&self) -> DefId {
2022 pub fn substs(&self) -> &'tcx Substs<'tcx> {
2023 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
2027 pub fn input_types(&self) -> &[Ty<'tcx>] {
2028 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
2029 self.0.input_types()
2032 pub fn to_poly_trait_predicate(&self) -> PolyTraitPredicate<'tcx> {
2033 // Note that we preserve binding levels
2034 Binder(TraitPredicate { trait_ref: self.0.clone() })
2038 /// Binder is a binder for higher-ranked lifetimes. It is part of the
2039 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
2040 /// (which would be represented by the type `PolyTraitRef ==
2041 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
2042 /// erase, or otherwise "discharge" these bound regions, we change the
2043 /// type from `Binder<T>` to just `T` (see
2044 /// e.g. `liberate_late_bound_regions`).
2045 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
2046 pub struct Binder<T>(pub T);
2049 /// Skips the binder and returns the "bound" value. This is a
2050 /// risky thing to do because it's easy to get confused about
2051 /// debruijn indices and the like. It is usually better to
2052 /// discharge the binder using `no_late_bound_regions` or
2053 /// `replace_late_bound_regions` or something like
2054 /// that. `skip_binder` is only valid when you are either
2055 /// extracting data that has nothing to do with bound regions, you
2056 /// are doing some sort of test that does not involve bound
2057 /// regions, or you are being very careful about your depth
2060 /// Some examples where `skip_binder` is reasonable:
2061 /// - extracting the def-id from a PolyTraitRef;
2062 /// - comparing the self type of a PolyTraitRef to see if it is equal to
2063 /// a type parameter `X`, since the type `X` does not reference any regions
2064 pub fn skip_binder(&self) -> &T {
2068 pub fn as_ref(&self) -> Binder<&T> {
2072 pub fn map_bound_ref<F,U>(&self, f: F) -> Binder<U>
2073 where F: FnOnce(&T) -> U
2075 self.as_ref().map_bound(f)
2078 pub fn map_bound<F,U>(self, f: F) -> Binder<U>
2079 where F: FnOnce(T) -> U
2081 ty::Binder(f(self.0))
2085 #[derive(Clone, Copy, PartialEq)]
2086 pub enum IntVarValue {
2087 IntType(ast::IntTy),
2088 UintType(ast::UintTy),
2091 #[derive(Clone, Copy, Debug)]
2092 pub struct ExpectedFound<T> {
2097 // Data structures used in type unification
2098 #[derive(Clone, Debug)]
2099 pub enum TypeError<'tcx> {
2101 UnsafetyMismatch(ExpectedFound<ast::Unsafety>),
2102 AbiMismatch(ExpectedFound<abi::Abi>),
2108 TupleSize(ExpectedFound<usize>),
2109 FixedArraySize(ExpectedFound<usize>),
2110 TyParamSize(ExpectedFound<usize>),
2112 RegionsDoesNotOutlive(Region, Region),
2113 RegionsNotSame(Region, Region),
2114 RegionsNoOverlap(Region, Region),
2115 RegionsInsufficientlyPolymorphic(BoundRegion, Region),
2116 RegionsOverlyPolymorphic(BoundRegion, Region),
2117 Sorts(ExpectedFound<Ty<'tcx>>),
2119 IntMismatch(ExpectedFound<IntVarValue>),
2120 FloatMismatch(ExpectedFound<ast::FloatTy>),
2121 Traits(ExpectedFound<DefId>),
2122 BuiltinBoundsMismatch(ExpectedFound<BuiltinBounds>),
2123 VariadicMismatch(ExpectedFound<bool>),
2125 ConvergenceMismatch(ExpectedFound<bool>),
2126 ProjectionNameMismatched(ExpectedFound<ast::Name>),
2127 ProjectionBoundsLength(ExpectedFound<usize>),
2128 TyParamDefaultMismatch(ExpectedFound<type_variable::Default<'tcx>>)
2131 /// Bounds suitable for an existentially quantified type parameter
2132 /// such as those that appear in object types or closure types.
2133 #[derive(PartialEq, Eq, Hash, Clone)]
2134 pub struct ExistentialBounds<'tcx> {
2135 pub region_bound: ty::Region,
2136 pub builtin_bounds: BuiltinBounds,
2137 pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
2140 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
2141 pub struct BuiltinBounds(EnumSet<BuiltinBound>);
2143 impl BuiltinBounds {
2144 pub fn empty() -> BuiltinBounds {
2145 BuiltinBounds(EnumSet::new())
2148 pub fn iter(&self) -> enum_set::Iter<BuiltinBound> {
2152 pub fn to_predicates<'tcx>(&self,
2153 tcx: &ty::ctxt<'tcx>,
2154 self_ty: Ty<'tcx>) -> Vec<Predicate<'tcx>> {
2155 self.iter().filter_map(|builtin_bound|
2156 match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, self_ty) {
2157 Ok(trait_ref) => Some(trait_ref.to_predicate()),
2158 Err(ErrorReported) => { None }
2164 impl ops::Deref for BuiltinBounds {
2165 type Target = EnumSet<BuiltinBound>;
2166 fn deref(&self) -> &Self::Target { &self.0 }
2169 impl ops::DerefMut for BuiltinBounds {
2170 fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
2173 impl<'a> IntoIterator for &'a BuiltinBounds {
2174 type Item = BuiltinBound;
2175 type IntoIter = enum_set::Iter<BuiltinBound>;
2176 fn into_iter(self) -> Self::IntoIter {
2177 (**self).into_iter()
2181 #[derive(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
2184 pub enum BuiltinBound {
2191 impl CLike for BuiltinBound {
2192 fn to_usize(&self) -> usize {
2195 fn from_usize(v: usize) -> BuiltinBound {
2196 unsafe { mem::transmute(v) }
2200 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2205 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2210 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2211 pub struct FloatVid {
2215 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
2216 pub struct RegionVid {
2220 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2221 pub struct SkolemizedRegionVid {
2225 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2231 /// A `FreshTy` is one that is generated as a replacement for an
2232 /// unbound type variable. This is convenient for caching etc. See
2233 /// `middle::infer::freshen` for more details.
2239 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
2240 pub enum UnconstrainedNumeric {
2247 impl fmt::Debug for TyVid {
2248 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2249 write!(f, "_#{}t", self.index)
2253 impl fmt::Debug for IntVid {
2254 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2255 write!(f, "_#{}i", self.index)
2259 impl fmt::Debug for FloatVid {
2260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2261 write!(f, "_#{}f", self.index)
2265 impl fmt::Debug for RegionVid {
2266 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2267 write!(f, "'_#{}r", self.index)
2271 impl<'tcx> fmt::Debug for FnSig<'tcx> {
2272 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2273 write!(f, "({:?}; variadic: {})->{:?}", self.inputs, self.variadic, self.output)
2277 impl fmt::Debug for InferTy {
2278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2280 TyVar(ref v) => v.fmt(f),
2281 IntVar(ref v) => v.fmt(f),
2282 FloatVar(ref v) => v.fmt(f),
2283 FreshTy(v) => write!(f, "FreshTy({:?})", v),
2284 FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
2285 FreshFloatTy(v) => write!(f, "FreshFloatTy({:?})", v)
2290 impl fmt::Debug for IntVarValue {
2291 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2293 IntType(ref v) => v.fmt(f),
2294 UintType(ref v) => v.fmt(f),
2299 /// Default region to use for the bound of objects that are
2300 /// supplied as the value for this type parameter. This is derived
2301 /// from `T:'a` annotations appearing in the type definition. If
2302 /// this is `None`, then the default is inherited from the
2303 /// surrounding context. See RFC #599 for details.
2304 #[derive(Copy, Clone)]
2305 pub enum ObjectLifetimeDefault {
2306 /// Require an explicit annotation. Occurs when multiple
2307 /// `T:'a` constraints are found.
2310 /// Use the base default, typically 'static, but in a fn body it is a fresh variable
2313 /// Use the given region as the default.
2318 pub struct TypeParameterDef<'tcx> {
2319 pub name: ast::Name,
2321 pub space: subst::ParamSpace,
2323 pub default_def_id: DefId, // for use in error reporing about defaults
2324 pub default: Option<Ty<'tcx>>,
2325 pub object_lifetime_default: ObjectLifetimeDefault,
2329 pub struct RegionParameterDef {
2330 pub name: ast::Name,
2332 pub space: subst::ParamSpace,
2334 pub bounds: Vec<ty::Region>,
2337 impl RegionParameterDef {
2338 pub fn to_early_bound_region(&self) -> ty::Region {
2339 ty::ReEarlyBound(ty::EarlyBoundRegion {
2340 param_id: self.def_id.node,
2346 pub fn to_bound_region(&self) -> ty::BoundRegion {
2347 ty::BoundRegion::BrNamed(self.def_id, self.name)
2351 /// Information about the formal type/lifetime parameters associated
2352 /// with an item or method. Analogous to ast::Generics.
2353 #[derive(Clone, Debug)]
2354 pub struct Generics<'tcx> {
2355 pub types: VecPerParamSpace<TypeParameterDef<'tcx>>,
2356 pub regions: VecPerParamSpace<RegionParameterDef>,
2359 impl<'tcx> Generics<'tcx> {
2360 pub fn empty() -> Generics<'tcx> {
2362 types: VecPerParamSpace::empty(),
2363 regions: VecPerParamSpace::empty(),
2367 pub fn is_empty(&self) -> bool {
2368 self.types.is_empty() && self.regions.is_empty()
2371 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
2372 !self.types.is_empty_in(space)
2375 pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
2376 !self.regions.is_empty_in(space)
2380 /// Bounds on generics.
2382 pub struct GenericPredicates<'tcx> {
2383 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
2386 impl<'tcx> GenericPredicates<'tcx> {
2387 pub fn empty() -> GenericPredicates<'tcx> {
2389 predicates: VecPerParamSpace::empty(),
2393 pub fn instantiate(&self, tcx: &ctxt<'tcx>, substs: &Substs<'tcx>)
2394 -> InstantiatedPredicates<'tcx> {
2395 InstantiatedPredicates {
2396 predicates: self.predicates.subst(tcx, substs),
2400 pub fn instantiate_supertrait(&self,
2402 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
2403 -> InstantiatedPredicates<'tcx>
2405 InstantiatedPredicates {
2406 predicates: self.predicates.map(|pred| pred.subst_supertrait(tcx, poly_trait_ref))
2411 #[derive(Clone, PartialEq, Eq, Hash)]
2412 pub enum Predicate<'tcx> {
2413 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
2414 /// the `Self` type of the trait reference and `A`, `B`, and `C`
2415 /// would be the parameters in the `TypeSpace`.
2416 Trait(PolyTraitPredicate<'tcx>),
2418 /// where `T1 == T2`.
2419 Equate(PolyEquatePredicate<'tcx>),
2422 RegionOutlives(PolyRegionOutlivesPredicate),
2425 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
2427 /// where <T as TraitRef>::Name == X, approximately.
2428 /// See `ProjectionPredicate` struct for details.
2429 Projection(PolyProjectionPredicate<'tcx>),
2432 WellFormed(Ty<'tcx>),
2434 /// trait must be object-safe
2438 impl<'tcx> Predicate<'tcx> {
2439 /// Performs a substitution suitable for going from a
2440 /// poly-trait-ref to supertraits that must hold if that
2441 /// poly-trait-ref holds. This is slightly different from a normal
2442 /// substitution in terms of what happens with bound regions. See
2443 /// lengthy comment below for details.
2444 pub fn subst_supertrait(&self,
2446 trait_ref: &ty::PolyTraitRef<'tcx>)
2447 -> ty::Predicate<'tcx>
2449 // The interaction between HRTB and supertraits is not entirely
2450 // obvious. Let me walk you (and myself) through an example.
2452 // Let's start with an easy case. Consider two traits:
2454 // trait Foo<'a> : Bar<'a,'a> { }
2455 // trait Bar<'b,'c> { }
2457 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
2458 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
2459 // knew that `Foo<'x>` (for any 'x) then we also know that
2460 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
2461 // normal substitution.
2463 // In terms of why this is sound, the idea is that whenever there
2464 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
2465 // holds. So if there is an impl of `T:Foo<'a>` that applies to
2466 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
2469 // Another example to be careful of is this:
2471 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
2472 // trait Bar1<'b,'c> { }
2474 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
2475 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
2476 // reason is similar to the previous example: any impl of
2477 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
2478 // basically we would want to collapse the bound lifetimes from
2479 // the input (`trait_ref`) and the supertraits.
2481 // To achieve this in practice is fairly straightforward. Let's
2482 // consider the more complicated scenario:
2484 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
2485 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
2486 // where both `'x` and `'b` would have a DB index of 1.
2487 // The substitution from the input trait-ref is therefore going to be
2488 // `'a => 'x` (where `'x` has a DB index of 1).
2489 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
2490 // early-bound parameter and `'b' is a late-bound parameter with a
2492 // - If we replace `'a` with `'x` from the input, it too will have
2493 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
2494 // just as we wanted.
2496 // There is only one catch. If we just apply the substitution `'a
2497 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
2498 // adjust the DB index because we substituting into a binder (it
2499 // tries to be so smart...) resulting in `for<'x> for<'b>
2500 // Bar1<'x,'b>` (we have no syntax for this, so use your
2501 // imagination). Basically the 'x will have DB index of 2 and 'b
2502 // will have DB index of 1. Not quite what we want. So we apply
2503 // the substitution to the *contents* of the trait reference,
2504 // rather than the trait reference itself (put another way, the
2505 // substitution code expects equal binding levels in the values
2506 // from the substitution and the value being substituted into, and
2507 // this trick achieves that).
2509 let substs = &trait_ref.0.substs;
2511 Predicate::Trait(ty::Binder(ref data)) =>
2512 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
2513 Predicate::Equate(ty::Binder(ref data)) =>
2514 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
2515 Predicate::RegionOutlives(ty::Binder(ref data)) =>
2516 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
2517 Predicate::TypeOutlives(ty::Binder(ref data)) =>
2518 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
2519 Predicate::Projection(ty::Binder(ref data)) =>
2520 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
2521 Predicate::WellFormed(data) =>
2522 Predicate::WellFormed(data.subst(tcx, substs)),
2523 Predicate::ObjectSafe(trait_def_id) =>
2524 Predicate::ObjectSafe(trait_def_id),
2529 #[derive(Clone, PartialEq, Eq, Hash)]
2530 pub struct TraitPredicate<'tcx> {
2531 pub trait_ref: TraitRef<'tcx>
2533 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
2535 impl<'tcx> TraitPredicate<'tcx> {
2536 pub fn def_id(&self) -> DefId {
2537 self.trait_ref.def_id
2540 pub fn input_types(&self) -> &[Ty<'tcx>] {
2541 self.trait_ref.substs.types.as_slice()
2544 pub fn self_ty(&self) -> Ty<'tcx> {
2545 self.trait_ref.self_ty()
2549 impl<'tcx> PolyTraitPredicate<'tcx> {
2550 pub fn def_id(&self) -> DefId {
2555 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2556 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
2557 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
2559 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2560 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
2561 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
2562 pub type PolyRegionOutlivesPredicate = PolyOutlivesPredicate<ty::Region, ty::Region>;
2563 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region>;
2565 /// This kind of predicate has no *direct* correspondent in the
2566 /// syntax, but it roughly corresponds to the syntactic forms:
2568 /// 1. `T : TraitRef<..., Item=Type>`
2569 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
2571 /// In particular, form #1 is "desugared" to the combination of a
2572 /// normal trait predicate (`T : TraitRef<...>`) and one of these
2573 /// predicates. Form #2 is a broader form in that it also permits
2574 /// equality between arbitrary types. Processing an instance of Form
2575 /// #2 eventually yields one of these `ProjectionPredicate`
2576 /// instances to normalize the LHS.
2577 #[derive(Clone, PartialEq, Eq, Hash)]
2578 pub struct ProjectionPredicate<'tcx> {
2579 pub projection_ty: ProjectionTy<'tcx>,
2583 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
2585 impl<'tcx> PolyProjectionPredicate<'tcx> {
2586 pub fn item_name(&self) -> ast::Name {
2587 self.0.projection_ty.item_name // safe to skip the binder to access a name
2590 pub fn sort_key(&self) -> (DefId, ast::Name) {
2591 self.0.projection_ty.sort_key()
2595 /// Represents the projection of an associated type. In explicit UFCS
2596 /// form this would be written `<T as Trait<..>>::N`.
2597 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
2598 pub struct ProjectionTy<'tcx> {
2599 /// The trait reference `T as Trait<..>`.
2600 pub trait_ref: ty::TraitRef<'tcx>,
2602 /// The name `N` of the associated type.
2603 pub item_name: ast::Name,
2606 impl<'tcx> ProjectionTy<'tcx> {
2607 pub fn sort_key(&self) -> (DefId, ast::Name) {
2608 (self.trait_ref.def_id, self.item_name)
2612 pub trait ToPolyTraitRef<'tcx> {
2613 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
2616 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
2617 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2618 assert!(!self.has_escaping_regions());
2619 ty::Binder(self.clone())
2623 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
2624 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2625 self.map_bound_ref(|trait_pred| trait_pred.trait_ref.clone())
2629 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
2630 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2631 // Note: unlike with TraitRef::to_poly_trait_ref(),
2632 // self.0.trait_ref is permitted to have escaping regions.
2633 // This is because here `self` has a `Binder` and so does our
2634 // return value, so we are preserving the number of binding
2636 ty::Binder(self.0.projection_ty.trait_ref.clone())
2640 pub trait ToPredicate<'tcx> {
2641 fn to_predicate(&self) -> Predicate<'tcx>;
2644 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
2645 fn to_predicate(&self) -> Predicate<'tcx> {
2646 // we're about to add a binder, so let's check that we don't
2647 // accidentally capture anything, or else that might be some
2648 // weird debruijn accounting.
2649 assert!(!self.has_escaping_regions());
2651 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
2652 trait_ref: self.clone()
2657 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
2658 fn to_predicate(&self) -> Predicate<'tcx> {
2659 ty::Predicate::Trait(self.to_poly_trait_predicate())
2663 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
2664 fn to_predicate(&self) -> Predicate<'tcx> {
2665 Predicate::Equate(self.clone())
2669 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate {
2670 fn to_predicate(&self) -> Predicate<'tcx> {
2671 Predicate::RegionOutlives(self.clone())
2675 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
2676 fn to_predicate(&self) -> Predicate<'tcx> {
2677 Predicate::TypeOutlives(self.clone())
2681 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
2682 fn to_predicate(&self) -> Predicate<'tcx> {
2683 Predicate::Projection(self.clone())
2687 impl<'tcx> Predicate<'tcx> {
2688 /// Iterates over the types in this predicate. Note that in all
2689 /// cases this is skipping over a binder, so late-bound regions
2690 /// with depth 0 are bound by the predicate.
2691 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
2692 let vec: Vec<_> = match *self {
2693 ty::Predicate::Trait(ref data) => {
2694 data.0.trait_ref.substs.types.as_slice().to_vec()
2696 ty::Predicate::Equate(ty::Binder(ref data)) => {
2697 vec![data.0, data.1]
2699 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
2702 ty::Predicate::RegionOutlives(..) => {
2705 ty::Predicate::Projection(ref data) => {
2706 let trait_inputs = data.0.projection_ty.trait_ref.substs.types.as_slice();
2709 .chain(Some(data.0.ty))
2712 ty::Predicate::WellFormed(data) => {
2715 ty::Predicate::ObjectSafe(_trait_def_id) => {
2720 // The only reason to collect into a vector here is that I was
2721 // too lazy to make the full (somewhat complicated) iterator
2722 // type that would be needed here. But I wanted this fn to
2723 // return an iterator conceptually, rather than a `Vec`, so as
2724 // to be closer to `Ty::walk`.
2728 pub fn has_escaping_regions(&self) -> bool {
2730 Predicate::Trait(ref trait_ref) => trait_ref.has_escaping_regions(),
2731 Predicate::Equate(ref p) => p.has_escaping_regions(),
2732 Predicate::RegionOutlives(ref p) => p.has_escaping_regions(),
2733 Predicate::TypeOutlives(ref p) => p.has_escaping_regions(),
2734 Predicate::Projection(ref p) => p.has_escaping_regions(),
2735 Predicate::WellFormed(p) => p.has_escaping_regions(),
2736 Predicate::ObjectSafe(_trait_def_id) => false,
2740 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
2742 Predicate::Trait(ref t) => {
2743 Some(t.to_poly_trait_ref())
2745 Predicate::Projection(..) |
2746 Predicate::Equate(..) |
2747 Predicate::RegionOutlives(..) |
2748 Predicate::WellFormed(..) |
2749 Predicate::ObjectSafe(..) |
2750 Predicate::TypeOutlives(..) => {
2757 /// Represents the bounds declared on a particular set of type
2758 /// parameters. Should eventually be generalized into a flag list of
2759 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
2760 /// `GenericPredicates` by using the `instantiate` method. Note that this method
2761 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
2762 /// the `GenericPredicates` are expressed in terms of the bound type
2763 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
2764 /// represented a set of bounds for some particular instantiation,
2765 /// meaning that the generic parameters have been substituted with
2770 /// struct Foo<T,U:Bar<T>> { ... }
2772 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
2773 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
2774 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
2775 /// [usize:Bar<isize>]]`.
2777 pub struct InstantiatedPredicates<'tcx> {
2778 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
2781 impl<'tcx> InstantiatedPredicates<'tcx> {
2782 pub fn empty() -> InstantiatedPredicates<'tcx> {
2783 InstantiatedPredicates { predicates: VecPerParamSpace::empty() }
2786 pub fn has_escaping_regions(&self) -> bool {
2787 self.predicates.any(|p| p.has_escaping_regions())
2790 pub fn is_empty(&self) -> bool {
2791 self.predicates.is_empty()
2795 impl<'tcx> TraitRef<'tcx> {
2796 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
2797 TraitRef { def_id: def_id, substs: substs }
2800 pub fn self_ty(&self) -> Ty<'tcx> {
2801 self.substs.self_ty().unwrap()
2804 pub fn input_types(&self) -> &[Ty<'tcx>] {
2805 // Select only the "input types" from a trait-reference. For
2806 // now this is all the types that appear in the
2807 // trait-reference, but it should eventually exclude
2808 // associated types.
2809 self.substs.types.as_slice()
2813 /// When type checking, we use the `ParameterEnvironment` to track
2814 /// details about the type/lifetime parameters that are in scope.
2815 /// It primarily stores the bounds information.
2817 /// Note: This information might seem to be redundant with the data in
2818 /// `tcx.ty_param_defs`, but it is not. That table contains the
2819 /// parameter definitions from an "outside" perspective, but this
2820 /// struct will contain the bounds for a parameter as seen from inside
2821 /// the function body. Currently the only real distinction is that
2822 /// bound lifetime parameters are replaced with free ones, but in the
2823 /// future I hope to refine the representation of types so as to make
2824 /// more distinctions clearer.
2826 pub struct ParameterEnvironment<'a, 'tcx:'a> {
2827 pub tcx: &'a ctxt<'tcx>,
2829 /// See `construct_free_substs` for details.
2830 pub free_substs: Substs<'tcx>,
2832 /// Each type parameter has an implicit region bound that
2833 /// indicates it must outlive at least the function body (the user
2834 /// may specify stronger requirements). This field indicates the
2835 /// region of the callee.
2836 pub implicit_region_bound: ty::Region,
2838 /// Obligations that the caller must satisfy. This is basically
2839 /// the set of bounds on the in-scope type parameters, translated
2840 /// into Obligations, and elaborated and normalized.
2841 pub caller_bounds: Vec<ty::Predicate<'tcx>>,
2843 /// Caches the results of trait selection. This cache is used
2844 /// for things that have to do with the parameters in scope.
2845 pub selection_cache: traits::SelectionCache<'tcx>,
2847 /// Scope that is attached to free regions for this scope. This
2848 /// is usually the id of the fn body, but for more abstract scopes
2849 /// like structs we often use the node-id of the struct.
2851 /// FIXME(#3696). It would be nice to refactor so that free
2852 /// regions don't have this implicit scope and instead introduce
2853 /// relationships in the environment.
2854 pub free_id: ast::NodeId,
2857 impl<'a, 'tcx> ParameterEnvironment<'a, 'tcx> {
2858 pub fn with_caller_bounds(&self,
2859 caller_bounds: Vec<ty::Predicate<'tcx>>)
2860 -> ParameterEnvironment<'a,'tcx>
2862 ParameterEnvironment {
2864 free_substs: self.free_substs.clone(),
2865 implicit_region_bound: self.implicit_region_bound,
2866 caller_bounds: caller_bounds,
2867 selection_cache: traits::SelectionCache::new(),
2868 free_id: self.free_id,
2872 pub fn for_item(cx: &'a ctxt<'tcx>, id: NodeId) -> ParameterEnvironment<'a, 'tcx> {
2873 match cx.map.find(id) {
2874 Some(ast_map::NodeImplItem(ref impl_item)) => {
2875 match impl_item.node {
2876 ast::TypeImplItem(_) => {
2877 // associated types don't have their own entry (for some reason),
2878 // so for now just grab environment for the impl
2879 let impl_id = cx.map.get_parent(id);
2880 let impl_def_id = DefId::local(impl_id);
2881 let scheme = cx.lookup_item_type(impl_def_id);
2882 let predicates = cx.lookup_predicates(impl_def_id);
2883 cx.construct_parameter_environment(impl_item.span,
2888 ast::ConstImplItem(_, _) => {
2889 let def_id = DefId::local(id);
2890 let scheme = cx.lookup_item_type(def_id);
2891 let predicates = cx.lookup_predicates(def_id);
2892 cx.construct_parameter_environment(impl_item.span,
2897 ast::MethodImplItem(_, ref body) => {
2898 let method_def_id = DefId::local(id);
2899 match cx.impl_or_trait_item(method_def_id) {
2900 MethodTraitItem(ref method_ty) => {
2901 let method_generics = &method_ty.generics;
2902 let method_bounds = &method_ty.predicates;
2903 cx.construct_parameter_environment(
2911 .bug("ParameterEnvironment::for_item(): \
2912 got non-method item from impl method?!")
2916 ast::MacImplItem(_) => cx.sess.bug("unexpanded macro")
2919 Some(ast_map::NodeTraitItem(trait_item)) => {
2920 match trait_item.node {
2921 ast::TypeTraitItem(..) => {
2922 // associated types don't have their own entry (for some reason),
2923 // so for now just grab environment for the trait
2924 let trait_id = cx.map.get_parent(id);
2925 let trait_def_id = DefId::local(trait_id);
2926 let trait_def = cx.lookup_trait_def(trait_def_id);
2927 let predicates = cx.lookup_predicates(trait_def_id);
2928 cx.construct_parameter_environment(trait_item.span,
2929 &trait_def.generics,
2933 ast::ConstTraitItem(..) => {
2934 let def_id = DefId::local(id);
2935 let scheme = cx.lookup_item_type(def_id);
2936 let predicates = cx.lookup_predicates(def_id);
2937 cx.construct_parameter_environment(trait_item.span,
2942 ast::MethodTraitItem(_, ref body) => {
2943 // for the body-id, use the id of the body
2944 // block, unless this is a trait method with
2945 // no default, then fallback to the method id.
2946 let body_id = body.as_ref().map(|b| b.id).unwrap_or(id);
2947 let method_def_id = DefId::local(id);
2948 match cx.impl_or_trait_item(method_def_id) {
2949 MethodTraitItem(ref method_ty) => {
2950 let method_generics = &method_ty.generics;
2951 let method_bounds = &method_ty.predicates;
2952 cx.construct_parameter_environment(
2960 .bug("ParameterEnvironment::for_item(): \
2961 got non-method item from provided \
2968 Some(ast_map::NodeItem(item)) => {
2970 ast::ItemFn(_, _, _, _, _, ref body) => {
2971 // We assume this is a function.
2972 let fn_def_id = DefId::local(id);
2973 let fn_scheme = cx.lookup_item_type(fn_def_id);
2974 let fn_predicates = cx.lookup_predicates(fn_def_id);
2976 cx.construct_parameter_environment(item.span,
2977 &fn_scheme.generics,
2982 ast::ItemStruct(..) |
2984 ast::ItemConst(..) |
2985 ast::ItemStatic(..) => {
2986 let def_id = DefId::local(id);
2987 let scheme = cx.lookup_item_type(def_id);
2988 let predicates = cx.lookup_predicates(def_id);
2989 cx.construct_parameter_environment(item.span,
2994 ast::ItemTrait(..) => {
2995 let def_id = DefId::local(id);
2996 let trait_def = cx.lookup_trait_def(def_id);
2997 let predicates = cx.lookup_predicates(def_id);
2998 cx.construct_parameter_environment(item.span,
2999 &trait_def.generics,
3004 cx.sess.span_bug(item.span,
3005 "ParameterEnvironment::from_item():
3006 can't create a parameter \
3007 environment for this kind of item")
3011 Some(ast_map::NodeExpr(..)) => {
3012 // This is a convenience to allow closures to work.
3013 ParameterEnvironment::for_item(cx, cx.map.get_parent(id))
3016 cx.sess.bug(&format!("ParameterEnvironment::from_item(): \
3017 `{}` is not an item",
3018 cx.map.node_to_string(id)))
3023 pub fn can_type_implement_copy(&self, self_type: Ty<'tcx>, span: Span)
3024 -> Result<(),CopyImplementationError> {
3027 // FIXME: (@jroesch) float this code up
3028 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(self.clone()), false);
3030 let adt = match self_type.sty {
3031 ty::TyStruct(struct_def, substs) => {
3032 for field in struct_def.all_fields() {
3033 let field_ty = field.ty(tcx, substs);
3034 if infcx.type_moves_by_default(field_ty, span) {
3035 return Err(FieldDoesNotImplementCopy(field.name))
3040 ty::TyEnum(enum_def, substs) => {
3041 for variant in &enum_def.variants {
3042 for field in &variant.fields {
3043 let field_ty = field.ty(tcx, substs);
3044 if infcx.type_moves_by_default(field_ty, span) {
3045 return Err(VariantDoesNotImplementCopy(variant.name))
3051 _ => return Err(TypeIsStructural),
3055 return Err(TypeHasDestructor)
3062 #[derive(Copy, Clone)]
3063 pub enum CopyImplementationError {
3064 FieldDoesNotImplementCopy(ast::Name),
3065 VariantDoesNotImplementCopy(ast::Name),
3070 /// A "type scheme", in ML terminology, is a type combined with some
3071 /// set of generic types that the type is, well, generic over. In Rust
3072 /// terms, it is the "type" of a fn item or struct -- this type will
3073 /// include various generic parameters that must be substituted when
3074 /// the item/struct is referenced. That is called converting the type
3075 /// scheme to a monotype.
3077 /// - `generics`: the set of type parameters and their bounds
3078 /// - `ty`: the base types, which may reference the parameters defined
3081 /// Note that TypeSchemes are also sometimes called "polytypes" (and
3082 /// in fact this struct used to carry that name, so you may find some
3083 /// stray references in a comment or something). We try to reserve the
3084 /// "poly" prefix to refer to higher-ranked things, as in
3087 /// Note that each item also comes with predicates, see
3088 /// `lookup_predicates`.
3089 #[derive(Clone, Debug)]
3090 pub struct TypeScheme<'tcx> {
3091 pub generics: Generics<'tcx>,
3096 flags TraitFlags: u32 {
3097 const NO_TRAIT_FLAGS = 0,
3098 const HAS_DEFAULT_IMPL = 1 << 0,
3099 const IS_OBJECT_SAFE = 1 << 1,
3100 const OBJECT_SAFETY_VALID = 1 << 2,
3101 const IMPLS_VALID = 1 << 3,
3105 /// As `TypeScheme` but for a trait ref.
3106 pub struct TraitDef<'tcx> {
3107 pub unsafety: ast::Unsafety,
3109 /// If `true`, then this trait had the `#[rustc_paren_sugar]`
3110 /// attribute, indicating that it should be used with `Foo()`
3111 /// sugar. This is a temporary thing -- eventually any trait wil
3112 /// be usable with the sugar (or without it).
3113 pub paren_sugar: bool,
3115 /// Generic type definitions. Note that `Self` is listed in here
3116 /// as having a single bound, the trait itself (e.g., in the trait
3117 /// `Eq`, there is a single bound `Self : Eq`). This is so that
3118 /// default methods get to assume that the `Self` parameters
3119 /// implements the trait.
3120 pub generics: Generics<'tcx>,
3122 pub trait_ref: TraitRef<'tcx>,
3124 /// A list of the associated types defined in this trait. Useful
3125 /// for resolving `X::Foo` type markers.
3126 pub associated_type_names: Vec<ast::Name>,
3128 // Impls of this trait. To allow for quicker lookup, the impls are indexed
3129 // by a simplified version of their Self type: impls with a simplifiable
3130 // Self are stored in nonblanket_impls keyed by it, while all other impls
3131 // are stored in blanket_impls.
3133 /// Impls of the trait.
3134 pub nonblanket_impls: RefCell<
3135 FnvHashMap<fast_reject::SimplifiedType, Vec<DefId>>
3138 /// Blanket impls associated with the trait.
3139 pub blanket_impls: RefCell<Vec<DefId>>,
3142 pub flags: Cell<TraitFlags>
3145 impl<'tcx> TraitDef<'tcx> {
3146 // returns None if not yet calculated
3147 pub fn object_safety(&self) -> Option<bool> {
3148 if self.flags.get().intersects(TraitFlags::OBJECT_SAFETY_VALID) {
3149 Some(self.flags.get().intersects(TraitFlags::IS_OBJECT_SAFE))
3155 pub fn set_object_safety(&self, is_safe: bool) {
3156 assert!(self.object_safety().map(|cs| cs == is_safe).unwrap_or(true));
3158 self.flags.get() | if is_safe {
3159 TraitFlags::OBJECT_SAFETY_VALID | TraitFlags::IS_OBJECT_SAFE
3161 TraitFlags::OBJECT_SAFETY_VALID
3166 /// Records a trait-to-implementation mapping.
3167 pub fn record_impl(&self,
3170 impl_trait_ref: TraitRef<'tcx>) {
3171 debug!("TraitDef::record_impl for {:?}, from {:?}",
3172 self, impl_trait_ref);
3174 // We don't want to borrow_mut after we already populated all impls,
3175 // so check if an impl is present with an immutable borrow first.
3176 if let Some(sty) = fast_reject::simplify_type(tcx,
3177 impl_trait_ref.self_ty(), false) {
3178 if let Some(is) = self.nonblanket_impls.borrow().get(&sty) {
3179 if is.contains(&impl_def_id) {
3180 return // duplicate - skip
3184 self.nonblanket_impls.borrow_mut().entry(sty).or_insert(vec![]).push(impl_def_id)
3186 if self.blanket_impls.borrow().contains(&impl_def_id) {
3187 return // duplicate - skip
3189 self.blanket_impls.borrow_mut().push(impl_def_id)
3194 pub fn for_each_impl<F: FnMut(DefId)>(&self, tcx: &ctxt<'tcx>, mut f: F) {
3195 tcx.populate_implementations_for_trait_if_necessary(self.trait_ref.def_id);
3197 for &impl_def_id in self.blanket_impls.borrow().iter() {
3201 for v in self.nonblanket_impls.borrow().values() {
3202 for &impl_def_id in v {
3208 /// Iterate over every impl that could possibly match the
3209 /// self-type `self_ty`.
3210 pub fn for_each_relevant_impl<F: FnMut(DefId)>(&self,
3215 tcx.populate_implementations_for_trait_if_necessary(self.trait_ref.def_id);
3217 for &impl_def_id in self.blanket_impls.borrow().iter() {
3221 // simplify_type(.., false) basically replaces type parameters and
3222 // projections with infer-variables. This is, of course, done on
3223 // the impl trait-ref when it is instantiated, but not on the
3224 // predicate trait-ref which is passed here.
3226 // for example, if we match `S: Copy` against an impl like
3227 // `impl<T:Copy> Copy for Option<T>`, we replace the type variable
3228 // in `Option<T>` with an infer variable, to `Option<_>` (this
3229 // doesn't actually change fast_reject output), but we don't
3230 // replace `S` with anything - this impl of course can't be
3231 // selected, and as there are hundreds of similar impls,
3232 // considering them would significantly harm performance.
3233 if let Some(simp) = fast_reject::simplify_type(tcx, self_ty, true) {
3234 if let Some(impls) = self.nonblanket_impls.borrow().get(&simp) {
3235 for &impl_def_id in impls {
3240 for v in self.nonblanket_impls.borrow().values() {
3241 for &impl_def_id in v {
3251 flags AdtFlags: u32 {
3252 const NO_ADT_FLAGS = 0,
3253 const IS_ENUM = 1 << 0,
3254 const IS_DTORCK = 1 << 1, // is this a dtorck type?
3255 const IS_DTORCK_VALID = 1 << 2,
3256 const IS_PHANTOM_DATA = 1 << 3,
3257 const IS_SIMD = 1 << 4,
3258 const IS_FUNDAMENTAL = 1 << 5,
3259 const IS_NO_DROP_FLAG = 1 << 6,
3263 pub type AdtDef<'tcx> = &'tcx AdtDefData<'tcx, 'static>;
3264 pub type VariantDef<'tcx> = &'tcx VariantDefData<'tcx, 'static>;
3265 pub type FieldDef<'tcx> = &'tcx FieldDefData<'tcx, 'static>;
3267 // See comment on AdtDefData for explanation
3268 pub type AdtDefMaster<'tcx> = &'tcx AdtDefData<'tcx, 'tcx>;
3269 pub type VariantDefMaster<'tcx> = &'tcx VariantDefData<'tcx, 'tcx>;
3270 pub type FieldDefMaster<'tcx> = &'tcx FieldDefData<'tcx, 'tcx>;
3272 pub struct VariantDefData<'tcx, 'container: 'tcx> {
3274 pub name: Name, // struct's name if this is a struct
3276 pub fields: Vec<FieldDefData<'tcx, 'container>>
3279 pub struct FieldDefData<'tcx, 'container: 'tcx> {
3280 /// The field's DefId. NOTE: the fields of tuple-like enum variants
3281 /// are not real items, and don't have entries in tcache etc.
3283 /// special_idents::unnamed_field.name
3284 /// if this is a tuple-like field
3286 pub vis: ast::Visibility,
3287 /// TyIVar is used here to allow for variance (see the doc at
3289 ty: TyIVar<'tcx, 'container>
3292 /// The definition of an abstract data type - a struct or enum.
3294 /// These are all interned (by intern_adt_def) into the adt_defs
3297 /// Because of the possibility of nested tcx-s, this type
3298 /// needs 2 lifetimes: the traditional variant lifetime ('tcx)
3299 /// bounding the lifetime of the inner types is of course necessary.
3300 /// However, it is not sufficient - types from a child tcx must
3301 /// not be leaked into the master tcx by being stored in an AdtDefData.
3303 /// The 'container lifetime ensures that by outliving the container
3304 /// tcx and preventing shorter-lived types from being inserted. When
3305 /// write access is not needed, the 'container lifetime can be
3306 /// erased to 'static, which can be done by the AdtDef wrapper.
3307 pub struct AdtDefData<'tcx, 'container: 'tcx> {
3309 pub variants: Vec<VariantDefData<'tcx, 'container>>,
3310 destructor: Cell<Option<DefId>>,
3311 flags: Cell<AdtFlags>,
3314 impl<'tcx, 'container> PartialEq for AdtDefData<'tcx, 'container> {
3315 // AdtDefData are always interned and this is part of TyS equality
3317 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
3320 impl<'tcx, 'container> Eq for AdtDefData<'tcx, 'container> {}
3322 impl<'tcx, 'container> Hash for AdtDefData<'tcx, 'container> {
3324 fn hash<H: Hasher>(&self, s: &mut H) {
3325 (self as *const AdtDefData).hash(s)
3330 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3331 pub enum AdtKind { Struct, Enum }
3333 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3334 pub enum VariantKind { Dict, Tuple, Unit }
3336 impl<'tcx, 'container> AdtDefData<'tcx, 'container> {
3337 fn new(tcx: &ctxt<'tcx>,
3340 variants: Vec<VariantDefData<'tcx, 'container>>) -> Self {
3341 let mut flags = AdtFlags::NO_ADT_FLAGS;
3342 let attrs = tcx.get_attrs(did);
3343 if attr::contains_name(&attrs, "fundamental") {
3344 flags = flags | AdtFlags::IS_FUNDAMENTAL;
3346 if attr::contains_name(&attrs, "unsafe_no_drop_flag") {
3347 flags = flags | AdtFlags::IS_NO_DROP_FLAG;
3349 if tcx.lookup_simd(did) {
3350 flags = flags | AdtFlags::IS_SIMD;
3352 if Some(did) == tcx.lang_items.phantom_data() {
3353 flags = flags | AdtFlags::IS_PHANTOM_DATA;
3355 if let AdtKind::Enum = kind {
3356 flags = flags | AdtFlags::IS_ENUM;
3361 flags: Cell::new(flags),
3362 destructor: Cell::new(None)
3366 fn calculate_dtorck(&'tcx self, tcx: &ctxt<'tcx>) {
3367 if tcx.is_adt_dtorck(self) {
3368 self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK);
3370 self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK_VALID)
3373 /// Returns the kind of the ADT - Struct or Enum.
3375 pub fn adt_kind(&self) -> AdtKind {
3376 if self.flags.get().intersects(AdtFlags::IS_ENUM) {
3383 /// Returns whether this is a dtorck type. If this returns
3384 /// true, this type being safe for destruction requires it to be
3385 /// alive; Otherwise, only the contents are required to be.
3387 pub fn is_dtorck(&'tcx self, tcx: &ctxt<'tcx>) -> bool {
3388 if !self.flags.get().intersects(AdtFlags::IS_DTORCK_VALID) {
3389 self.calculate_dtorck(tcx)
3391 self.flags.get().intersects(AdtFlags::IS_DTORCK)
3394 /// Returns whether this type is #[fundamental] for the purposes
3395 /// of coherence checking.
3397 pub fn is_fundamental(&self) -> bool {
3398 self.flags.get().intersects(AdtFlags::IS_FUNDAMENTAL)
3402 pub fn is_simd(&self) -> bool {
3403 self.flags.get().intersects(AdtFlags::IS_SIMD)
3406 /// Returns true if this is PhantomData<T>.
3408 pub fn is_phantom_data(&self) -> bool {
3409 self.flags.get().intersects(AdtFlags::IS_PHANTOM_DATA)
3412 /// Returns whether this type has a destructor.
3413 pub fn has_dtor(&self) -> bool {
3414 match self.dtor_kind() {
3416 TraitDtor(..) => true
3420 /// Asserts this is a struct and returns the struct's unique
3422 pub fn struct_variant(&self) -> &VariantDefData<'tcx, 'container> {
3423 assert!(self.adt_kind() == AdtKind::Struct);
3428 pub fn type_scheme(&self, tcx: &ctxt<'tcx>) -> TypeScheme<'tcx> {
3429 tcx.lookup_item_type(self.did)
3433 pub fn predicates(&self, tcx: &ctxt<'tcx>) -> GenericPredicates<'tcx> {
3434 tcx.lookup_predicates(self.did)
3437 /// Returns an iterator over all fields contained
3440 pub fn all_fields(&self) ->
3442 slice::Iter<VariantDefData<'tcx, 'container>>,
3443 slice::Iter<FieldDefData<'tcx, 'container>>,
3444 for<'s> fn(&'s VariantDefData<'tcx, 'container>)
3445 -> slice::Iter<'s, FieldDefData<'tcx, 'container>>
3447 self.variants.iter().flat_map(VariantDefData::fields_iter)
3451 pub fn is_empty(&self) -> bool {
3452 self.variants.is_empty()
3456 pub fn is_univariant(&self) -> bool {
3457 self.variants.len() == 1
3460 pub fn is_payloadfree(&self) -> bool {
3461 !self.variants.is_empty() &&
3462 self.variants.iter().all(|v| v.fields.is_empty())
3465 pub fn variant_with_id(&self, vid: DefId) -> &VariantDefData<'tcx, 'container> {
3468 .find(|v| v.did == vid)
3469 .expect("variant_with_id: unknown variant")
3472 pub fn variant_of_def(&self, def: def::Def) -> &VariantDefData<'tcx, 'container> {
3474 def::DefVariant(_, vid, _) => self.variant_with_id(vid),
3475 def::DefStruct(..) | def::DefTy(..) => self.struct_variant(),
3476 _ => panic!("unexpected def {:?} in variant_of_def", def)
3480 pub fn destructor(&self) -> Option<DefId> {
3481 self.destructor.get()
3484 pub fn set_destructor(&self, dtor: DefId) {
3485 assert!(self.destructor.get().is_none());
3486 self.destructor.set(Some(dtor));
3489 pub fn dtor_kind(&self) -> DtorKind {
3490 match self.destructor.get() {
3492 TraitDtor(!self.flags.get().intersects(AdtFlags::IS_NO_DROP_FLAG))
3499 impl<'tcx, 'container> VariantDefData<'tcx, 'container> {
3501 fn fields_iter(&self) -> slice::Iter<FieldDefData<'tcx, 'container>> {
3505 pub fn kind(&self) -> VariantKind {
3506 match self.fields.get(0) {
3507 None => VariantKind::Unit,
3508 Some(&FieldDefData { name, .. }) if name == special_idents::unnamed_field.name => {
3511 Some(_) => VariantKind::Dict
3515 pub fn is_tuple_struct(&self) -> bool {
3516 self.kind() == VariantKind::Tuple
3520 pub fn find_field_named(&self,
3522 -> Option<&FieldDefData<'tcx, 'container>> {
3523 self.fields.iter().find(|f| f.name == name)
3527 pub fn field_named(&self, name: ast::Name) -> &FieldDefData<'tcx, 'container> {
3528 self.find_field_named(name).unwrap()
3532 impl<'tcx, 'container> FieldDefData<'tcx, 'container> {
3533 pub fn new(did: DefId,
3535 vis: ast::Visibility) -> Self {
3544 pub fn ty(&self, tcx: &ctxt<'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
3545 self.unsubst_ty().subst(tcx, subst)
3548 pub fn unsubst_ty(&self) -> Ty<'tcx> {
3552 pub fn fulfill_ty(&self, ty: Ty<'container>) {
3553 self.ty.fulfill(ty);
3557 /// Records the substitutions used to translate the polytype for an
3558 /// item into the monotype of an item reference.
3560 pub struct ItemSubsts<'tcx> {
3561 pub substs: Substs<'tcx>,
3564 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
3565 pub enum ClosureKind {
3566 // Warning: Ordering is significant here! The ordering is chosen
3567 // because the trait Fn is a subtrait of FnMut and so in turn, and
3568 // hence we order it so that Fn < FnMut < FnOnce.
3575 pub fn trait_did(&self, cx: &ctxt) -> DefId {
3576 let result = match *self {
3577 FnClosureKind => cx.lang_items.require(FnTraitLangItem),
3578 FnMutClosureKind => {
3579 cx.lang_items.require(FnMutTraitLangItem)
3581 FnOnceClosureKind => {
3582 cx.lang_items.require(FnOnceTraitLangItem)
3586 Ok(trait_did) => trait_did,
3587 Err(err) => cx.sess.fatal(&err[..]),
3591 /// True if this a type that impls this closure kind
3592 /// must also implement `other`.
3593 pub fn extends(self, other: ty::ClosureKind) -> bool {
3594 match (self, other) {
3595 (FnClosureKind, FnClosureKind) => true,
3596 (FnClosureKind, FnMutClosureKind) => true,
3597 (FnClosureKind, FnOnceClosureKind) => true,
3598 (FnMutClosureKind, FnMutClosureKind) => true,
3599 (FnMutClosureKind, FnOnceClosureKind) => true,
3600 (FnOnceClosureKind, FnOnceClosureKind) => true,
3606 impl<'tcx> CommonTypes<'tcx> {
3607 fn new(arena: &'tcx TypedArena<TyS<'tcx>>,
3608 interner: &RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>)
3609 -> CommonTypes<'tcx>
3611 let mk = |sty| ctxt::intern_ty(arena, interner, sty);
3616 isize: mk(TyInt(ast::TyIs)),
3617 i8: mk(TyInt(ast::TyI8)),
3618 i16: mk(TyInt(ast::TyI16)),
3619 i32: mk(TyInt(ast::TyI32)),
3620 i64: mk(TyInt(ast::TyI64)),
3621 usize: mk(TyUint(ast::TyUs)),
3622 u8: mk(TyUint(ast::TyU8)),
3623 u16: mk(TyUint(ast::TyU16)),
3624 u32: mk(TyUint(ast::TyU32)),
3625 u64: mk(TyUint(ast::TyU64)),
3626 f32: mk(TyFloat(ast::TyF32)),
3627 f64: mk(TyFloat(ast::TyF64)),
3632 struct FlagComputation {
3635 // maximum depth of any bound region that we have seen thus far
3639 impl FlagComputation {
3640 fn new() -> FlagComputation {
3641 FlagComputation { flags: TypeFlags::empty(), depth: 0 }
3644 fn for_sty(st: &TypeVariants) -> FlagComputation {
3645 let mut result = FlagComputation::new();
3650 fn add_flags(&mut self, flags: TypeFlags) {
3651 self.flags = self.flags | (flags & TypeFlags::NOMINAL_FLAGS);
3654 fn add_depth(&mut self, depth: u32) {
3655 if depth > self.depth {
3660 /// Adds the flags/depth from a set of types that appear within the current type, but within a
3662 fn add_bound_computation(&mut self, computation: &FlagComputation) {
3663 self.add_flags(computation.flags);
3665 // The types that contributed to `computation` occurred within
3666 // a region binder, so subtract one from the region depth
3667 // within when adding the depth to `self`.
3668 let depth = computation.depth;
3670 self.add_depth(depth - 1);
3674 fn add_sty(&mut self, st: &TypeVariants) {
3684 // You might think that we could just return TyError for
3685 // any type containing TyError as a component, and get
3686 // rid of the TypeFlags::HAS_TY_ERR flag -- likewise for ty_bot (with
3687 // the exception of function types that return bot).
3688 // But doing so caused sporadic memory corruption, and
3689 // neither I (tjc) nor nmatsakis could figure out why,
3690 // so we're doing it this way.
3692 self.add_flags(TypeFlags::HAS_TY_ERR)
3695 &TyParam(ref p) => {
3696 self.add_flags(TypeFlags::HAS_LOCAL_NAMES);
3697 if p.space == subst::SelfSpace {
3698 self.add_flags(TypeFlags::HAS_SELF);
3700 self.add_flags(TypeFlags::HAS_PARAMS);
3704 &TyClosure(_, ref substs) => {
3705 self.add_flags(TypeFlags::HAS_TY_CLOSURE);
3706 self.add_flags(TypeFlags::HAS_LOCAL_NAMES);
3707 self.add_substs(&substs.func_substs);
3708 self.add_tys(&substs.upvar_tys);
3712 self.add_flags(TypeFlags::HAS_LOCAL_NAMES); // it might, right?
3713 self.add_flags(TypeFlags::HAS_TY_INFER)
3716 &TyEnum(_, substs) | &TyStruct(_, substs) => {
3717 self.add_substs(substs);
3720 &TyProjection(ref data) => {
3721 self.add_flags(TypeFlags::HAS_PROJECTION);
3722 self.add_projection_ty(data);
3725 &TyTrait(box TraitTy { ref principal, ref bounds }) => {
3726 let mut computation = FlagComputation::new();
3727 computation.add_substs(principal.0.substs);
3728 for projection_bound in &bounds.projection_bounds {
3729 let mut proj_computation = FlagComputation::new();
3730 proj_computation.add_projection_predicate(&projection_bound.0);
3731 self.add_bound_computation(&proj_computation);
3733 self.add_bound_computation(&computation);
3735 self.add_bounds(bounds);
3738 &TyBox(tt) | &TyArray(tt, _) | &TySlice(tt) => {
3742 &TyRawPtr(ref m) => {
3746 &TyRef(r, ref m) => {
3747 self.add_region(*r);
3751 &TyTuple(ref ts) => {
3752 self.add_tys(&ts[..]);
3755 &TyBareFn(_, ref f) => {
3756 self.add_fn_sig(&f.sig);
3761 fn add_ty(&mut self, ty: Ty) {
3762 self.add_flags(ty.flags.get());
3763 self.add_depth(ty.region_depth);
3766 fn add_tys(&mut self, tys: &[Ty]) {
3772 fn add_fn_sig(&mut self, fn_sig: &PolyFnSig) {
3773 let mut computation = FlagComputation::new();
3775 computation.add_tys(&fn_sig.0.inputs);
3777 if let ty::FnConverging(output) = fn_sig.0.output {
3778 computation.add_ty(output);
3781 self.add_bound_computation(&computation);
3784 fn add_region(&mut self, r: Region) {
3787 ty::ReSkolemized(..) => { self.add_flags(TypeFlags::HAS_RE_INFER); }
3788 ty::ReLateBound(debruijn, _) => { self.add_depth(debruijn.depth); }
3789 ty::ReEarlyBound(..) => { self.add_flags(TypeFlags::HAS_RE_EARLY_BOUND); }
3791 _ => { self.add_flags(TypeFlags::HAS_FREE_REGIONS); }
3795 self.add_flags(TypeFlags::HAS_LOCAL_NAMES);
3799 fn add_projection_predicate(&mut self, projection_predicate: &ProjectionPredicate) {
3800 self.add_projection_ty(&projection_predicate.projection_ty);
3801 self.add_ty(projection_predicate.ty);
3804 fn add_projection_ty(&mut self, projection_ty: &ProjectionTy) {
3805 self.add_substs(projection_ty.trait_ref.substs);
3808 fn add_substs(&mut self, substs: &Substs) {
3809 self.add_tys(substs.types.as_slice());
3810 match substs.regions {
3811 subst::ErasedRegions => {}
3812 subst::NonerasedRegions(ref regions) => {
3820 fn add_bounds(&mut self, bounds: &ExistentialBounds) {
3821 self.add_region(bounds.region_bound);
3825 impl<'tcx> ctxt<'tcx> {
3826 /// Create a type context and call the closure with a `&ty::ctxt` reference
3827 /// to the context. The closure enforces that the type context and any interned
3828 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
3829 /// reference to the context, to allow formatting values that need it.
3830 pub fn create_and_enter<F, R>(s: Session,
3831 arenas: &'tcx CtxtArenas<'tcx>,
3833 named_region_map: resolve_lifetime::NamedRegionMap,
3834 map: ast_map::Map<'tcx>,
3835 freevars: RefCell<FreevarMap>,
3836 region_maps: RegionMaps,
3837 lang_items: middle::lang_items::LanguageItems,
3838 stability: stability::Index<'tcx>,
3839 f: F) -> (Session, R)
3840 where F: FnOnce(&ctxt<'tcx>) -> R
3842 let interner = RefCell::new(FnvHashMap());
3843 let common_types = CommonTypes::new(&arenas.type_, &interner);
3848 substs_interner: RefCell::new(FnvHashMap()),
3849 bare_fn_interner: RefCell::new(FnvHashMap()),
3850 region_interner: RefCell::new(FnvHashMap()),
3851 stability_interner: RefCell::new(FnvHashMap()),
3852 types: common_types,
3853 named_region_map: named_region_map,
3854 region_maps: region_maps,
3855 free_region_maps: RefCell::new(FnvHashMap()),
3856 item_variance_map: RefCell::new(DefIdMap()),
3857 variance_computed: Cell::new(false),
3860 tables: RefCell::new(Tables::empty()),
3861 impl_trait_refs: RefCell::new(DefIdMap()),
3862 trait_defs: RefCell::new(DefIdMap()),
3863 adt_defs: RefCell::new(DefIdMap()),
3864 predicates: RefCell::new(DefIdMap()),
3865 super_predicates: RefCell::new(DefIdMap()),
3866 fulfilled_predicates: RefCell::new(traits::FulfilledPredicates::new()),
3869 tcache: RefCell::new(DefIdMap()),
3870 rcache: RefCell::new(FnvHashMap()),
3871 tc_cache: RefCell::new(FnvHashMap()),
3872 ast_ty_to_ty_cache: RefCell::new(NodeMap()),
3873 impl_or_trait_items: RefCell::new(DefIdMap()),
3874 trait_item_def_ids: RefCell::new(DefIdMap()),
3875 trait_items_cache: RefCell::new(DefIdMap()),
3876 ty_param_defs: RefCell::new(NodeMap()),
3877 normalized_cache: RefCell::new(FnvHashMap()),
3878 lang_items: lang_items,
3879 provided_method_sources: RefCell::new(DefIdMap()),
3880 destructors: RefCell::new(DefIdSet()),
3881 inherent_impls: RefCell::new(DefIdMap()),
3882 impl_items: RefCell::new(DefIdMap()),
3883 used_unsafe: RefCell::new(NodeSet()),
3884 used_mut_nodes: RefCell::new(NodeSet()),
3885 populated_external_types: RefCell::new(DefIdSet()),
3886 populated_external_primitive_impls: RefCell::new(DefIdSet()),
3887 extern_const_statics: RefCell::new(DefIdMap()),
3888 extern_const_variants: RefCell::new(DefIdMap()),
3889 extern_const_fns: RefCell::new(DefIdMap()),
3890 node_lint_levels: RefCell::new(FnvHashMap()),
3891 transmute_restrictions: RefCell::new(Vec::new()),
3892 stability: RefCell::new(stability),
3893 selection_cache: traits::SelectionCache::new(),
3894 repr_hint_cache: RefCell::new(DefIdMap()),
3895 const_qualif_map: RefCell::new(NodeMap()),
3896 custom_coerce_unsized_kinds: RefCell::new(DefIdMap()),
3897 cast_kinds: RefCell::new(NodeMap()),
3898 fragment_infos: RefCell::new(DefIdMap()),
3902 // Type constructors
3904 pub fn mk_substs(&self, substs: Substs<'tcx>) -> &'tcx Substs<'tcx> {
3905 if let Some(substs) = self.substs_interner.borrow().get(&substs) {
3909 let substs = self.arenas.substs.alloc(substs);
3910 self.substs_interner.borrow_mut().insert(substs, substs);
3914 /// Create an unsafe fn ty based on a safe fn ty.
3915 pub fn safe_to_unsafe_fn_ty(&self, bare_fn: &BareFnTy<'tcx>) -> Ty<'tcx> {
3916 assert_eq!(bare_fn.unsafety, ast::Unsafety::Normal);
3917 let unsafe_fn_ty_a = self.mk_bare_fn(ty::BareFnTy {
3918 unsafety: ast::Unsafety::Unsafe,
3920 sig: bare_fn.sig.clone()
3922 self.mk_fn(None, unsafe_fn_ty_a)
3925 pub fn mk_bare_fn(&self, bare_fn: BareFnTy<'tcx>) -> &'tcx BareFnTy<'tcx> {
3926 if let Some(bare_fn) = self.bare_fn_interner.borrow().get(&bare_fn) {
3930 let bare_fn = self.arenas.bare_fn.alloc(bare_fn);
3931 self.bare_fn_interner.borrow_mut().insert(bare_fn, bare_fn);
3935 pub fn mk_region(&self, region: Region) -> &'tcx Region {
3936 if let Some(region) = self.region_interner.borrow().get(®ion) {
3940 let region = self.arenas.region.alloc(region);
3941 self.region_interner.borrow_mut().insert(region, region);
3945 pub fn closure_kind(&self, def_id: DefId) -> ty::ClosureKind {
3946 *self.tables.borrow().closure_kinds.get(&def_id).unwrap()
3949 pub fn closure_type(&self,
3951 substs: &ClosureSubsts<'tcx>)
3952 -> ty::ClosureTy<'tcx>
3954 self.tables.borrow().closure_tys.get(&def_id).unwrap().subst(self, &substs.func_substs)
3957 pub fn type_parameter_def(&self,
3958 node_id: ast::NodeId)
3959 -> TypeParameterDef<'tcx>
3961 self.ty_param_defs.borrow().get(&node_id).unwrap().clone()
3964 pub fn pat_contains_ref_binding(&self, pat: &ast::Pat) -> Option<ast::Mutability> {
3965 pat_util::pat_contains_ref_binding(&self.def_map, pat)
3968 pub fn arm_contains_ref_binding(&self, arm: &ast::Arm) -> Option<ast::Mutability> {
3969 pat_util::arm_contains_ref_binding(&self.def_map, arm)
3972 fn intern_ty(type_arena: &'tcx TypedArena<TyS<'tcx>>,
3973 interner: &RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>,
3974 st: TypeVariants<'tcx>)
3976 let ty: Ty /* don't be &mut TyS */ = {
3977 let mut interner = interner.borrow_mut();
3978 match interner.get(&st) {
3979 Some(ty) => return *ty,
3983 let flags = FlagComputation::for_sty(&st);
3986 () => type_arena.alloc(TyS { sty: st,
3987 flags: Cell::new(flags.flags),
3988 region_depth: flags.depth, }),
3991 interner.insert(InternedTy { ty: ty }, ty);
3995 debug!("Interned type: {:?} Pointer: {:?}",
3996 ty, ty as *const TyS);
4000 // Interns a type/name combination, stores the resulting box in cx.interner,
4001 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
4002 pub fn mk_ty(&self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
4003 ctxt::intern_ty(&self.arenas.type_, &self.interner, st)
4006 pub fn mk_mach_int(&self, tm: ast::IntTy) -> Ty<'tcx> {
4008 ast::TyIs => self.types.isize,
4009 ast::TyI8 => self.types.i8,
4010 ast::TyI16 => self.types.i16,
4011 ast::TyI32 => self.types.i32,
4012 ast::TyI64 => self.types.i64,
4016 pub fn mk_mach_uint(&self, tm: ast::UintTy) -> Ty<'tcx> {
4018 ast::TyUs => self.types.usize,
4019 ast::TyU8 => self.types.u8,
4020 ast::TyU16 => self.types.u16,
4021 ast::TyU32 => self.types.u32,
4022 ast::TyU64 => self.types.u64,
4026 pub fn mk_mach_float(&self, tm: ast::FloatTy) -> Ty<'tcx> {
4028 ast::TyF32 => self.types.f32,
4029 ast::TyF64 => self.types.f64,
4033 pub fn mk_str(&self) -> Ty<'tcx> {
4037 pub fn mk_static_str(&self) -> Ty<'tcx> {
4038 self.mk_imm_ref(self.mk_region(ty::ReStatic), self.mk_str())
4041 pub fn mk_enum(&self, def: AdtDef<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
4042 // take a copy of substs so that we own the vectors inside
4043 self.mk_ty(TyEnum(def, substs))
4046 pub fn mk_box(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4047 self.mk_ty(TyBox(ty))
4050 pub fn mk_ptr(&self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
4051 self.mk_ty(TyRawPtr(tm))
4054 pub fn mk_ref(&self, r: &'tcx Region, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
4055 self.mk_ty(TyRef(r, tm))
4058 pub fn mk_mut_ref(&self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
4059 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: ast::MutMutable})
4062 pub fn mk_imm_ref(&self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
4063 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: ast::MutImmutable})
4066 pub fn mk_mut_ptr(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4067 self.mk_ptr(TypeAndMut {ty: ty, mutbl: ast::MutMutable})
4070 pub fn mk_imm_ptr(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4071 self.mk_ptr(TypeAndMut {ty: ty, mutbl: ast::MutImmutable})
4074 pub fn mk_nil_ptr(&self) -> Ty<'tcx> {
4075 self.mk_imm_ptr(self.mk_nil())
4078 pub fn mk_array(&self, ty: Ty<'tcx>, n: usize) -> Ty<'tcx> {
4079 self.mk_ty(TyArray(ty, n))
4082 pub fn mk_slice(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4083 self.mk_ty(TySlice(ty))
4086 pub fn mk_tup(&self, ts: Vec<Ty<'tcx>>) -> Ty<'tcx> {
4087 self.mk_ty(TyTuple(ts))
4090 pub fn mk_nil(&self) -> Ty<'tcx> {
4091 self.mk_tup(Vec::new())
4094 pub fn mk_bool(&self) -> Ty<'tcx> {
4099 opt_def_id: Option<DefId>,
4100 fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
4101 self.mk_ty(TyBareFn(opt_def_id, fty))
4104 pub fn mk_ctor_fn(&self,
4106 input_tys: &[Ty<'tcx>],
4107 output: Ty<'tcx>) -> Ty<'tcx> {
4108 let input_args = input_tys.iter().cloned().collect();
4109 self.mk_fn(Some(def_id), self.mk_bare_fn(BareFnTy {
4110 unsafety: ast::Unsafety::Normal,
4112 sig: ty::Binder(FnSig {
4114 output: ty::FnConverging(output),
4120 pub fn mk_trait(&self,
4121 principal: ty::PolyTraitRef<'tcx>,
4122 bounds: ExistentialBounds<'tcx>)
4125 assert!(bound_list_is_sorted(&bounds.projection_bounds));
4127 let inner = box TraitTy {
4128 principal: principal,
4131 self.mk_ty(TyTrait(inner))
4134 pub fn mk_projection(&self,
4135 trait_ref: TraitRef<'tcx>,
4136 item_name: ast::Name)
4138 // take a copy of substs so that we own the vectors inside
4139 let inner = ProjectionTy { trait_ref: trait_ref, item_name: item_name };
4140 self.mk_ty(TyProjection(inner))
4143 pub fn mk_struct(&self, def: AdtDef<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
4144 // take a copy of substs so that we own the vectors inside
4145 self.mk_ty(TyStruct(def, substs))
4148 pub fn mk_closure(&self,
4150 substs: &'tcx Substs<'tcx>,
4153 self.mk_closure_from_closure_substs(closure_id, Box::new(ClosureSubsts {
4154 func_substs: substs,
4159 pub fn mk_closure_from_closure_substs(&self,
4161 closure_substs: Box<ClosureSubsts<'tcx>>)
4163 self.mk_ty(TyClosure(closure_id, closure_substs))
4166 pub fn mk_var(&self, v: TyVid) -> Ty<'tcx> {
4167 self.mk_infer(TyVar(v))
4170 pub fn mk_int_var(&self, v: IntVid) -> Ty<'tcx> {
4171 self.mk_infer(IntVar(v))
4174 pub fn mk_float_var(&self, v: FloatVid) -> Ty<'tcx> {
4175 self.mk_infer(FloatVar(v))
4178 pub fn mk_infer(&self, it: InferTy) -> Ty<'tcx> {
4179 self.mk_ty(TyInfer(it))
4182 pub fn mk_param(&self,
4183 space: subst::ParamSpace,
4185 name: ast::Name) -> Ty<'tcx> {
4186 self.mk_ty(TyParam(ParamTy { space: space, idx: index, name: name }))
4189 pub fn mk_self_type(&self) -> Ty<'tcx> {
4190 self.mk_param(subst::SelfSpace, 0, special_idents::type_self.name)
4193 pub fn mk_param_from_def(&self, def: &TypeParameterDef) -> Ty<'tcx> {
4194 self.mk_param(def.space, def.index, def.name)
4198 fn bound_list_is_sorted(bounds: &[ty::PolyProjectionPredicate]) -> bool {
4199 bounds.is_empty() ||
4200 bounds[1..].iter().enumerate().all(
4201 |(index, bound)| bounds[index].sort_key() <= bound.sort_key())
4204 pub fn sort_bounds_list(bounds: &mut [ty::PolyProjectionPredicate]) {
4205 bounds.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()))
4208 impl<'tcx> TyS<'tcx> {
4209 /// Iterator that walks `self` and any types reachable from
4210 /// `self`, in depth-first order. Note that just walks the types
4211 /// that appear in `self`, it does not descend into the fields of
4212 /// structs or variants. For example:
4215 /// isize => { isize }
4216 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
4217 /// [isize] => { [isize], isize }
4219 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
4220 TypeWalker::new(self)
4223 /// Iterator that walks the immediate children of `self`. Hence
4224 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
4225 /// (but not `i32`, like `walk`).
4226 pub fn walk_shallow(&'tcx self) -> IntoIter<Ty<'tcx>> {
4227 ty_walk::walk_shallow(self)
4230 pub fn as_opt_param_ty(&self) -> Option<ty::ParamTy> {
4232 ty::TyParam(ref d) => Some(d.clone()),
4237 pub fn is_param(&self, space: ParamSpace, index: u32) -> bool {
4239 ty::TyParam(ref data) => data.space == space && data.idx == index,
4244 /// Returns the regions directly referenced from this type (but
4245 /// not types reachable from this type via `walk_tys`). This
4246 /// ignores late-bound regions binders.
4247 pub fn regions(&self) -> Vec<ty::Region> {
4249 TyRef(region, _) => {
4252 TyTrait(ref obj) => {
4253 let mut v = vec![obj.bounds.region_bound];
4254 v.push_all(obj.principal.skip_binder().substs.regions().as_slice());
4258 TyStruct(_, substs) => {
4259 substs.regions().as_slice().to_vec()
4261 TyClosure(_, ref substs) => {
4262 substs.func_substs.regions().as_slice().to_vec()
4264 TyProjection(ref data) => {
4265 data.trait_ref.substs.regions().as_slice().to_vec()
4287 /// Walks `ty` and any types appearing within `ty`, invoking the
4288 /// callback `f` on each type. If the callback returns false, then the
4289 /// children of the current type are ignored.
4291 /// Note: prefer `ty.walk()` where possible.
4292 pub fn maybe_walk<F>(&'tcx self, mut f: F)
4293 where F : FnMut(Ty<'tcx>) -> bool
4295 let mut walker = self.walk();
4296 while let Some(ty) = walker.next() {
4298 walker.skip_current_subtree();
4305 pub fn new(space: subst::ParamSpace,
4309 ParamTy { space: space, idx: index, name: name }
4312 pub fn for_self() -> ParamTy {
4313 ParamTy::new(subst::SelfSpace, 0, special_idents::type_self.name)
4316 pub fn for_def(def: &TypeParameterDef) -> ParamTy {
4317 ParamTy::new(def.space, def.index, def.name)
4320 pub fn to_ty<'tcx>(self, tcx: &ctxt<'tcx>) -> Ty<'tcx> {
4321 tcx.mk_param(self.space, self.idx, self.name)
4324 pub fn is_self(&self) -> bool {
4325 self.space == subst::SelfSpace && self.idx == 0
4329 impl<'tcx> ItemSubsts<'tcx> {
4330 pub fn empty() -> ItemSubsts<'tcx> {
4331 ItemSubsts { substs: Substs::empty() }
4334 pub fn is_noop(&self) -> bool {
4335 self.substs.is_noop()
4340 impl<'tcx> TyS<'tcx> {
4341 pub fn is_nil(&self) -> bool {
4343 TyTuple(ref tys) => tys.is_empty(),
4348 pub fn is_empty(&self, _cx: &ctxt) -> bool {
4349 // FIXME(#24885): be smarter here
4351 TyEnum(def, _) | TyStruct(def, _) => def.is_empty(),
4356 pub fn is_ty_var(&self) -> bool {
4358 TyInfer(TyVar(_)) => true,
4363 pub fn is_bool(&self) -> bool { self.sty == TyBool }
4365 pub fn is_self(&self) -> bool {
4367 TyParam(ref p) => p.space == subst::SelfSpace,
4372 fn is_slice(&self) -> bool {
4374 TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
4375 TySlice(_) | TyStr => true,
4382 pub fn is_structural(&self) -> bool {
4384 TyStruct(..) | TyTuple(_) | TyEnum(..) |
4385 TyArray(..) | TyClosure(..) => true,
4386 _ => self.is_slice() | self.is_trait()
4391 pub fn is_simd(&self) -> bool {
4393 TyStruct(def, _) => def.is_simd(),
4398 pub fn sequence_element_type(&self, cx: &ctxt<'tcx>) -> Ty<'tcx> {
4400 TyArray(ty, _) | TySlice(ty) => ty,
4401 TyStr => cx.mk_mach_uint(ast::TyU8),
4402 _ => cx.sess.bug(&format!("sequence_element_type called on non-sequence value: {}",
4407 pub fn simd_type(&self, cx: &ctxt<'tcx>) -> Ty<'tcx> {
4409 TyStruct(def, substs) => {
4410 def.struct_variant().fields[0].ty(cx, substs)
4412 _ => panic!("simd_type called on invalid type")
4416 pub fn simd_size(&self, _cx: &ctxt) -> usize {
4418 TyStruct(def, _) => def.struct_variant().fields.len(),
4419 _ => panic!("simd_size called on invalid type")
4423 pub fn is_region_ptr(&self) -> bool {
4430 pub fn is_unsafe_ptr(&self) -> bool {
4432 TyRawPtr(_) => return true,
4437 pub fn is_unique(&self) -> bool {
4445 A scalar type is one that denotes an atomic datum, with no sub-components.
4446 (A TyRawPtr is scalar because it represents a non-managed pointer, so its
4447 contents are abstract to rustc.)
4449 pub fn is_scalar(&self) -> bool {
4451 TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
4452 TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
4453 TyBareFn(..) | TyRawPtr(_) => true,
4458 /// Returns true if this type is a floating point type and false otherwise.
4459 pub fn is_floating_point(&self) -> bool {
4462 TyInfer(FloatVar(_)) => true,
4467 pub fn ty_to_def_id(&self) -> Option<DefId> {
4469 TyTrait(ref tt) => Some(tt.principal_def_id()),
4471 TyEnum(def, _) => Some(def.did),
4472 TyClosure(id, _) => Some(id),
4477 pub fn ty_adt_def(&self) -> Option<AdtDef<'tcx>> {
4479 TyStruct(adt, _) | TyEnum(adt, _) => Some(adt),
4485 /// Type contents is how the type checker reasons about kinds.
4486 /// They track what kinds of things are found within a type. You can
4487 /// think of them as kind of an "anti-kind". They track the kinds of values
4488 /// and thinks that are contained in types. Having a larger contents for
4489 /// a type tends to rule that type *out* from various kinds. For example,
4490 /// a type that contains a reference is not sendable.
4492 /// The reason we compute type contents and not kinds is that it is
4493 /// easier for me (nmatsakis) to think about what is contained within
4494 /// a type than to think about what is *not* contained within a type.
4495 #[derive(Clone, Copy)]
4496 pub struct TypeContents {
4500 macro_rules! def_type_content_sets {
4501 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
4502 #[allow(non_snake_case)]
4504 use middle::ty::TypeContents;
4506 #[allow(non_upper_case_globals)]
4507 pub const $name: TypeContents = TypeContents { bits: $bits };
4513 def_type_content_sets! {
4515 None = 0b0000_0000__0000_0000__0000,
4517 // Things that are interior to the value (first nibble):
4518 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
4519 InteriorParam = 0b0000_0000__0000_0000__0100,
4520 // InteriorAll = 0b00000000__00000000__1111,
4522 // Things that are owned by the value (second and third nibbles):
4523 OwnsOwned = 0b0000_0000__0000_0001__0000,
4524 OwnsDtor = 0b0000_0000__0000_0010__0000,
4525 OwnsAll = 0b0000_0000__1111_1111__0000,
4527 // Things that mean drop glue is necessary
4528 NeedsDrop = 0b0000_0000__0000_0111__0000,
4531 All = 0b1111_1111__1111_1111__1111
4536 pub fn when(&self, cond: bool) -> TypeContents {
4537 if cond {*self} else {TC::None}
4540 pub fn intersects(&self, tc: TypeContents) -> bool {
4541 (self.bits & tc.bits) != 0
4544 pub fn owns_owned(&self) -> bool {
4545 self.intersects(TC::OwnsOwned)
4548 pub fn interior_param(&self) -> bool {
4549 self.intersects(TC::InteriorParam)
4552 pub fn interior_unsafe(&self) -> bool {
4553 self.intersects(TC::InteriorUnsafe)
4556 pub fn needs_drop(&self, _: &ctxt) -> bool {
4557 self.intersects(TC::NeedsDrop)
4560 /// Includes only those bits that still apply when indirected through a `Box` pointer
4561 pub fn owned_pointer(&self) -> TypeContents {
4562 TC::OwnsOwned | (*self & TC::OwnsAll)
4565 pub fn union<T, F>(v: &[T], mut f: F) -> TypeContents where
4566 F: FnMut(&T) -> TypeContents,
4568 v.iter().fold(TC::None, |tc, ty| tc | f(ty))
4571 pub fn has_dtor(&self) -> bool {
4572 self.intersects(TC::OwnsDtor)
4576 impl ops::BitOr for TypeContents {
4577 type Output = TypeContents;
4579 fn bitor(self, other: TypeContents) -> TypeContents {
4580 TypeContents {bits: self.bits | other.bits}
4584 impl ops::BitAnd for TypeContents {
4585 type Output = TypeContents;
4587 fn bitand(self, other: TypeContents) -> TypeContents {
4588 TypeContents {bits: self.bits & other.bits}
4592 impl ops::Sub for TypeContents {
4593 type Output = TypeContents;
4595 fn sub(self, other: TypeContents) -> TypeContents {
4596 TypeContents {bits: self.bits & !other.bits}
4600 impl fmt::Debug for TypeContents {
4601 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4602 write!(f, "TypeContents({:b})", self.bits)
4606 impl<'tcx> TyS<'tcx> {
4607 pub fn type_contents(&'tcx self, cx: &ctxt<'tcx>) -> TypeContents {
4608 return memoized(&cx.tc_cache, self, |ty| {
4609 tc_ty(cx, ty, &mut FnvHashMap())
4612 fn tc_ty<'tcx>(cx: &ctxt<'tcx>,
4614 cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
4616 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
4617 // private cache for this walk. This is needed in the case of cyclic
4620 // struct List { next: Box<Option<List>>, ... }
4622 // When computing the type contents of such a type, we wind up deeply
4623 // recursing as we go. So when we encounter the recursive reference
4624 // to List, we temporarily use TC::None as its contents. Later we'll
4625 // patch up the cache with the correct value, once we've computed it
4626 // (this is basically a co-inductive process, if that helps). So in
4627 // the end we'll compute TC::OwnsOwned, in this case.
4629 // The problem is, as we are doing the computation, we will also
4630 // compute an *intermediate* contents for, e.g., Option<List> of
4631 // TC::None. This is ok during the computation of List itself, but if
4632 // we stored this intermediate value into cx.tc_cache, then later
4633 // requests for the contents of Option<List> would also yield TC::None
4634 // which is incorrect. This value was computed based on the crutch
4635 // value for the type contents of list. The correct value is
4636 // TC::OwnsOwned. This manifested as issue #4821.
4637 match cache.get(&ty) {
4638 Some(tc) => { return *tc; }
4641 match cx.tc_cache.borrow().get(&ty) { // Must check both caches!
4642 Some(tc) => { return *tc; }
4645 cache.insert(ty, TC::None);
4647 let result = match ty.sty {
4648 // usize and isize are ffi-unsafe
4649 TyUint(ast::TyUs) | TyInt(ast::TyIs) => {
4653 // Scalar and unique types are sendable, and durable
4654 TyInfer(ty::FreshIntTy(_)) | TyInfer(ty::FreshFloatTy(_)) |
4655 TyBool | TyInt(_) | TyUint(_) | TyFloat(_) |
4656 TyBareFn(..) | ty::TyChar => {
4661 tc_ty(cx, typ, cache).owned_pointer()
4665 TC::All - TC::InteriorParam
4677 tc_ty(cx, ty, cache)
4681 tc_ty(cx, ty, cache)
4685 TyClosure(_, ref substs) => {
4686 TypeContents::union(&substs.upvar_tys, |ty| tc_ty(cx, &ty, cache))
4689 TyTuple(ref tys) => {
4690 TypeContents::union(&tys[..],
4691 |ty| tc_ty(cx, *ty, cache))
4694 TyStruct(def, substs) | TyEnum(def, substs) => {
4696 TypeContents::union(&def.variants, |v| {
4697 TypeContents::union(&v.fields, |f| {
4698 tc_ty(cx, f.ty(cx, substs), cache)
4703 res = res | TC::OwnsDtor;
4706 apply_lang_items(cx, def.did, res)
4716 cx.sess.bug("asked to compute contents of error type");
4720 cache.insert(ty, result);
4724 fn apply_lang_items(cx: &ctxt, did: DefId, tc: TypeContents)
4726 if Some(did) == cx.lang_items.unsafe_cell_type() {
4727 tc | TC::InteriorUnsafe
4734 fn impls_bound<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4735 bound: ty::BuiltinBound,
4739 let tcx = param_env.tcx;
4740 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env.clone()), false);
4742 let is_impld = traits::type_known_to_meet_builtin_bound(&infcx,
4745 debug!("Ty::impls_bound({:?}, {:?}) = {:?}",
4746 self, bound, is_impld);
4751 // FIXME (@jroesch): I made this public to use it, not sure if should be private
4752 pub fn moves_by_default<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4753 span: Span) -> bool {
4754 if self.flags.get().intersects(TypeFlags::MOVENESS_CACHED) {
4755 return self.flags.get().intersects(TypeFlags::MOVES_BY_DEFAULT);
4758 assert!(!self.needs_infer());
4760 // Fast-path for primitive types
4761 let result = match self.sty {
4762 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
4763 TyRawPtr(..) | TyBareFn(..) | TyRef(_, TypeAndMut {
4764 mutbl: ast::MutImmutable, ..
4767 TyStr | TyBox(..) | TyRef(_, TypeAndMut {
4768 mutbl: ast::MutMutable, ..
4771 TyArray(..) | TySlice(_) | TyTrait(..) | TyTuple(..) |
4772 TyClosure(..) | TyEnum(..) | TyStruct(..) |
4773 TyProjection(..) | TyParam(..) | TyInfer(..) | TyError => None
4774 }.unwrap_or_else(|| !self.impls_bound(param_env, ty::BoundCopy, span));
4776 if !self.has_param_types() && !self.has_self_ty() {
4777 self.flags.set(self.flags.get() | if result {
4778 TypeFlags::MOVENESS_CACHED | TypeFlags::MOVES_BY_DEFAULT
4780 TypeFlags::MOVENESS_CACHED
4788 pub fn is_sized<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4791 if self.flags.get().intersects(TypeFlags::SIZEDNESS_CACHED) {
4792 return self.flags.get().intersects(TypeFlags::IS_SIZED);
4795 self.is_sized_uncached(param_env, span)
4798 fn is_sized_uncached<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4799 span: Span) -> bool {
4800 assert!(!self.needs_infer());
4802 // Fast-path for primitive types
4803 let result = match self.sty {
4804 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
4805 TyBox(..) | TyRawPtr(..) | TyRef(..) | TyBareFn(..) |
4806 TyArray(..) | TyTuple(..) | TyClosure(..) => Some(true),
4808 TyStr | TyTrait(..) | TySlice(_) => Some(false),
4810 TyEnum(..) | TyStruct(..) | TyProjection(..) | TyParam(..) |
4811 TyInfer(..) | TyError => None
4812 }.unwrap_or_else(|| self.impls_bound(param_env, ty::BoundSized, span));
4814 if !self.has_param_types() && !self.has_self_ty() {
4815 self.flags.set(self.flags.get() | if result {
4816 TypeFlags::SIZEDNESS_CACHED | TypeFlags::IS_SIZED
4818 TypeFlags::SIZEDNESS_CACHED
4826 /// Describes whether a type is representable. For types that are not
4827 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
4828 /// distinguish between types that are recursive with themselves and types that
4829 /// contain a different recursive type. These cases can therefore be treated
4830 /// differently when reporting errors.
4832 /// The ordering of the cases is significant. They are sorted so that cmp::max
4833 /// will keep the "more erroneous" of two values.
4834 #[derive(Copy, Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
4835 pub enum Representability {
4841 impl<'tcx> TyS<'tcx> {
4842 /// Check whether a type is representable. This means it cannot contain unboxed
4843 /// structural recursion. This check is needed for structs and enums.
4844 pub fn is_representable(&'tcx self, cx: &ctxt<'tcx>, sp: Span) -> Representability {
4846 // Iterate until something non-representable is found
4847 fn find_nonrepresentable<'tcx, It: Iterator<Item=Ty<'tcx>>>(cx: &ctxt<'tcx>, sp: Span,
4848 seen: &mut Vec<Ty<'tcx>>,
4850 -> Representability {
4851 iter.fold(Representable,
4852 |r, ty| cmp::max(r, is_type_structurally_recursive(cx, sp, seen, ty)))
4855 fn are_inner_types_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
4856 seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
4857 -> Representability {
4859 TyTuple(ref ts) => {
4860 find_nonrepresentable(cx, sp, seen, ts.iter().cloned())
4862 // Fixed-length vectors.
4863 // FIXME(#11924) Behavior undecided for zero-length vectors.
4865 is_type_structurally_recursive(cx, sp, seen, ty)
4867 TyStruct(def, substs) | TyEnum(def, substs) => {
4868 find_nonrepresentable(cx,
4871 def.all_fields().map(|f| f.ty(cx, substs)))
4874 // this check is run on type definitions, so we don't expect
4875 // to see closure types
4876 cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
4882 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: AdtDef<'tcx>) -> bool {
4884 TyStruct(ty_def, _) | TyEnum(ty_def, _) => {
4891 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
4892 match (&a.sty, &b.sty) {
4893 (&TyStruct(did_a, ref substs_a), &TyStruct(did_b, ref substs_b)) |
4894 (&TyEnum(did_a, ref substs_a), &TyEnum(did_b, ref substs_b)) => {
4899 let types_a = substs_a.types.get_slice(subst::TypeSpace);
4900 let types_b = substs_b.types.get_slice(subst::TypeSpace);
4902 let mut pairs = types_a.iter().zip(types_b);
4904 pairs.all(|(&a, &b)| same_type(a, b))
4912 // Does the type `ty` directly (without indirection through a pointer)
4913 // contain any types on stack `seen`?
4914 fn is_type_structurally_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
4915 seen: &mut Vec<Ty<'tcx>>,
4916 ty: Ty<'tcx>) -> Representability {
4917 debug!("is_type_structurally_recursive: {:?}", ty);
4920 TyStruct(def, _) | TyEnum(def, _) => {
4922 // Iterate through stack of previously seen types.
4923 let mut iter = seen.iter();
4925 // The first item in `seen` is the type we are actually curious about.
4926 // We want to return SelfRecursive if this type contains itself.
4927 // It is important that we DON'T take generic parameters into account
4928 // for this check, so that Bar<T> in this example counts as SelfRecursive:
4931 // struct Bar<T> { x: Bar<Foo> }
4934 Some(&seen_type) => {
4935 if same_struct_or_enum(seen_type, def) {
4936 debug!("SelfRecursive: {:?} contains {:?}",
4939 return SelfRecursive;
4945 // We also need to know whether the first item contains other types
4946 // that are structurally recursive. If we don't catch this case, we
4947 // will recurse infinitely for some inputs.
4949 // It is important that we DO take generic parameters into account
4950 // here, so that code like this is considered SelfRecursive, not
4951 // ContainsRecursive:
4953 // struct Foo { Option<Option<Foo>> }
4955 for &seen_type in iter {
4956 if same_type(ty, seen_type) {
4957 debug!("ContainsRecursive: {:?} contains {:?}",
4960 return ContainsRecursive;
4965 // For structs and enums, track all previously seen types by pushing them
4966 // onto the 'seen' stack.
4968 let out = are_inner_types_recursive(cx, sp, seen, ty);
4973 // No need to push in other cases.
4974 are_inner_types_recursive(cx, sp, seen, ty)
4979 debug!("is_type_representable: {:?}", self);
4981 // To avoid a stack overflow when checking an enum variant or struct that
4982 // contains a different, structurally recursive type, maintain a stack
4983 // of seen types and check recursion for each of them (issues #3008, #3779).
4984 let mut seen: Vec<Ty> = Vec::new();
4985 let r = is_type_structurally_recursive(cx, sp, &mut seen, self);
4986 debug!("is_type_representable: {:?} is {:?}", self, r);
4990 pub fn is_trait(&self) -> bool {
4992 TyTrait(..) => true,
4997 pub fn is_integral(&self) -> bool {
4999 TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
5004 pub fn is_fresh(&self) -> bool {
5006 TyInfer(FreshTy(_)) => true,
5007 TyInfer(FreshIntTy(_)) => true,
5008 TyInfer(FreshFloatTy(_)) => true,
5013 pub fn is_uint(&self) -> bool {
5015 TyInfer(IntVar(_)) | TyUint(ast::TyUs) => true,
5020 pub fn is_char(&self) -> bool {
5027 pub fn is_bare_fn(&self) -> bool {
5029 TyBareFn(..) => true,
5034 pub fn is_bare_fn_item(&self) -> bool {
5036 TyBareFn(Some(_), _) => true,
5041 pub fn is_fp(&self) -> bool {
5043 TyInfer(FloatVar(_)) | TyFloat(_) => true,
5048 pub fn is_numeric(&self) -> bool {
5049 self.is_integral() || self.is_fp()
5052 pub fn is_signed(&self) -> bool {
5059 pub fn is_machine(&self) -> bool {
5061 TyInt(ast::TyIs) | TyUint(ast::TyUs) => false,
5062 TyInt(..) | TyUint(..) | TyFloat(..) => true,
5067 // Returns the type and mutability of *ty.
5069 // The parameter `explicit` indicates if this is an *explicit* dereference.
5070 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
5071 pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
5076 mutbl: ast::MutImmutable,
5079 TyRef(_, mt) => Some(mt),
5080 TyRawPtr(mt) if explicit => Some(mt),
5085 // Returns the type of ty[i]
5086 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
5088 TyArray(ty, _) | TySlice(ty) => Some(ty),
5093 pub fn fn_sig(&self) -> &'tcx PolyFnSig<'tcx> {
5095 TyBareFn(_, ref f) => &f.sig,
5096 _ => panic!("Ty::fn_sig() called on non-fn type: {:?}", self)
5100 /// Returns the ABI of the given function.
5101 pub fn fn_abi(&self) -> abi::Abi {
5103 TyBareFn(_, ref f) => f.abi,
5104 _ => panic!("Ty::fn_abi() called on non-fn type"),
5108 // Type accessors for substructures of types
5109 pub fn fn_args(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
5110 self.fn_sig().inputs()
5113 pub fn fn_ret(&self) -> Binder<FnOutput<'tcx>> {
5114 self.fn_sig().output()
5117 pub fn is_fn(&self) -> bool {
5119 TyBareFn(..) => true,
5124 /// See `expr_ty_adjusted`
5125 pub fn adjust<F>(&'tcx self, cx: &ctxt<'tcx>,
5127 expr_id: ast::NodeId,
5128 adjustment: Option<&AutoAdjustment<'tcx>>,
5131 F: FnMut(MethodCall) -> Option<Ty<'tcx>>,
5133 if let TyError = self.sty {
5137 return match adjustment {
5138 Some(adjustment) => {
5140 AdjustReifyFnPointer => {
5142 ty::TyBareFn(Some(_), b) => {
5147 &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
5153 AdjustUnsafeFnPointer => {
5155 ty::TyBareFn(None, b) => cx.safe_to_unsafe_fn_ty(b),
5158 &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
5165 AdjustDerefRef(ref adj) => {
5166 let mut adjusted_ty = self;
5168 if !adjusted_ty.references_error() {
5169 for i in 0..adj.autoderefs {
5170 let method_call = MethodCall::autoderef(expr_id, i as u32);
5171 match method_type(method_call) {
5172 Some(method_ty) => {
5173 // Overloaded deref operators have all late-bound
5174 // regions fully instantiated and coverge.
5176 cx.no_late_bound_regions(&method_ty.fn_ret()).unwrap();
5177 adjusted_ty = fn_ret.unwrap();
5181 match adjusted_ty.builtin_deref(true) {
5182 Some(mt) => { adjusted_ty = mt.ty; }
5186 &format!("the {}th autoderef failed: {}",
5195 if let Some(target) = adj.unsize {
5198 adjusted_ty.adjust_for_autoref(cx, adj.autoref)
5207 pub fn adjust_for_autoref(&'tcx self, cx: &ctxt<'tcx>,
5208 autoref: Option<AutoRef<'tcx>>)
5212 Some(AutoPtr(r, m)) => {
5213 cx.mk_ref(r, TypeAndMut { ty: self, mutbl: m })
5215 Some(AutoUnsafe(m)) => {
5216 cx.mk_ptr(TypeAndMut { ty: self, mutbl: m })
5221 fn sort_string(&self, cx: &ctxt) -> String {
5224 TyBool | TyChar | TyInt(_) |
5225 TyUint(_) | TyFloat(_) | TyStr => self.to_string(),
5226 TyTuple(ref tys) if tys.is_empty() => self.to_string(),
5228 TyEnum(def, _) => format!("enum `{}`", cx.item_path_str(def.did)),
5229 TyBox(_) => "box".to_string(),
5230 TyArray(_, n) => format!("array of {} elements", n),
5231 TySlice(_) => "slice".to_string(),
5232 TyRawPtr(_) => "*-ptr".to_string(),
5233 TyRef(_, _) => "&-ptr".to_string(),
5234 TyBareFn(Some(_), _) => format!("fn item"),
5235 TyBareFn(None, _) => "fn pointer".to_string(),
5236 TyTrait(ref inner) => {
5237 format!("trait {}", cx.item_path_str(inner.principal_def_id()))
5239 TyStruct(def, _) => {
5240 format!("struct `{}`", cx.item_path_str(def.did))
5242 TyClosure(..) => "closure".to_string(),
5243 TyTuple(_) => "tuple".to_string(),
5244 TyInfer(TyVar(_)) => "inferred type".to_string(),
5245 TyInfer(IntVar(_)) => "integral variable".to_string(),
5246 TyInfer(FloatVar(_)) => "floating-point variable".to_string(),
5247 TyInfer(FreshTy(_)) => "skolemized type".to_string(),
5248 TyInfer(FreshIntTy(_)) => "skolemized integral type".to_string(),
5249 TyInfer(FreshFloatTy(_)) => "skolemized floating-point type".to_string(),
5250 TyProjection(_) => "associated type".to_string(),
5252 if p.space == subst::SelfSpace {
5255 "type parameter".to_string()
5258 TyError => "type error".to_string(),
5262 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
5263 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
5264 /// afterwards to present additional details, particularly when it comes to lifetime-related
5266 impl<'tcx> fmt::Display for TypeError<'tcx> {
5267 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5268 use self::TypeError::*;
5271 CyclicTy => write!(f, "cyclic type of infinite size"),
5272 Mismatch => write!(f, "types differ"),
5273 UnsafetyMismatch(values) => {
5274 write!(f, "expected {} fn, found {} fn",
5278 AbiMismatch(values) => {
5279 write!(f, "expected {} fn, found {} fn",
5283 Mutability => write!(f, "values differ in mutability"),
5285 write!(f, "boxed values differ in mutability")
5287 VecMutability => write!(f, "vectors differ in mutability"),
5288 PtrMutability => write!(f, "pointers differ in mutability"),
5289 RefMutability => write!(f, "references differ in mutability"),
5290 TyParamSize(values) => {
5291 write!(f, "expected a type with {} type params, \
5292 found one with {} type params",
5296 FixedArraySize(values) => {
5297 write!(f, "expected an array with a fixed size of {} elements, \
5298 found one with {} elements",
5302 TupleSize(values) => {
5303 write!(f, "expected a tuple with {} elements, \
5304 found one with {} elements",
5309 write!(f, "incorrect number of function parameters")
5311 RegionsDoesNotOutlive(..) => {
5312 write!(f, "lifetime mismatch")
5314 RegionsNotSame(..) => {
5315 write!(f, "lifetimes are not the same")
5317 RegionsNoOverlap(..) => {
5318 write!(f, "lifetimes do not intersect")
5320 RegionsInsufficientlyPolymorphic(br, _) => {
5321 write!(f, "expected bound lifetime parameter {}, \
5322 found concrete lifetime", br)
5324 RegionsOverlyPolymorphic(br, _) => {
5325 write!(f, "expected concrete lifetime, \
5326 found bound lifetime parameter {}", br)
5328 Sorts(values) => tls::with(|tcx| {
5329 // A naive approach to making sure that we're not reporting silly errors such as:
5330 // (expected closure, found closure).
5331 let expected_str = values.expected.sort_string(tcx);
5332 let found_str = values.found.sort_string(tcx);
5333 if expected_str == found_str {
5334 write!(f, "expected {}, found a different {}", expected_str, found_str)
5336 write!(f, "expected {}, found {}", expected_str, found_str)
5339 Traits(values) => tls::with(|tcx| {
5340 write!(f, "expected trait `{}`, found trait `{}`",
5341 tcx.item_path_str(values.expected),
5342 tcx.item_path_str(values.found))
5344 BuiltinBoundsMismatch(values) => {
5345 if values.expected.is_empty() {
5346 write!(f, "expected no bounds, found `{}`",
5348 } else if values.found.is_empty() {
5349 write!(f, "expected bounds `{}`, found no bounds",
5352 write!(f, "expected bounds `{}`, found bounds `{}`",
5358 write!(f, "expected an integral type, found `char`")
5360 IntMismatch(ref values) => {
5361 write!(f, "expected `{:?}`, found `{:?}`",
5365 FloatMismatch(ref values) => {
5366 write!(f, "expected `{:?}`, found `{:?}`",
5370 VariadicMismatch(ref values) => {
5371 write!(f, "expected {} fn, found {} function",
5372 if values.expected { "variadic" } else { "non-variadic" },
5373 if values.found { "variadic" } else { "non-variadic" })
5375 ConvergenceMismatch(ref values) => {
5376 write!(f, "expected {} fn, found {} function",
5377 if values.expected { "converging" } else { "diverging" },
5378 if values.found { "converging" } else { "diverging" })
5380 ProjectionNameMismatched(ref values) => {
5381 write!(f, "expected {}, found {}",
5385 ProjectionBoundsLength(ref values) => {
5386 write!(f, "expected {} associated type bindings, found {}",
5390 TyParamDefaultMismatch(ref values) => {
5391 write!(f, "conflicting type parameter defaults `{}` and `{}`",
5399 /// Helper for looking things up in the various maps that are populated during
5400 /// typeck::collect (e.g., `cx.impl_or_trait_items`, `cx.tcache`, etc). All of
5401 /// these share the pattern that if the id is local, it should have been loaded
5402 /// into the map by the `typeck::collect` phase. If the def-id is external,
5403 /// then we have to go consult the crate loading code (and cache the result for
5405 fn lookup_locally_or_in_crate_store<V, F>(descr: &str,
5407 map: &RefCell<DefIdMap<V>>,
5408 load_external: F) -> V where
5412 match map.borrow().get(&def_id).cloned() {
5413 Some(v) => { return v; }
5417 if def_id.is_local() {
5418 panic!("No def'n found for {:?} in tcx.{}", def_id, descr);
5420 let v = load_external();
5421 map.borrow_mut().insert(def_id, v.clone());
5426 pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
5428 ast::MutMutable => MutBorrow,
5429 ast::MutImmutable => ImmBorrow,
5433 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
5434 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
5435 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
5437 pub fn to_mutbl_lossy(self) -> ast::Mutability {
5439 MutBorrow => ast::MutMutable,
5440 ImmBorrow => ast::MutImmutable,
5442 // We have no type corresponding to a unique imm borrow, so
5443 // use `&mut`. It gives all the capabilities of an `&uniq`
5444 // and hence is a safe "over approximation".
5445 UniqueImmBorrow => ast::MutMutable,
5449 pub fn to_user_str(&self) -> &'static str {
5451 MutBorrow => "mutable",
5452 ImmBorrow => "immutable",
5453 UniqueImmBorrow => "uniquely immutable",
5458 impl<'tcx> ctxt<'tcx> {
5459 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
5460 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
5461 pub fn positional_element_ty(&self,
5464 variant: Option<DefId>) -> Option<Ty<'tcx>> {
5465 match (&ty.sty, variant) {
5466 (&TyStruct(def, substs), None) => {
5467 def.struct_variant().fields.get(i).map(|f| f.ty(self, substs))
5469 (&TyEnum(def, substs), Some(vid)) => {
5470 def.variant_with_id(vid).fields.get(i).map(|f| f.ty(self, substs))
5472 (&TyEnum(def, substs), None) => {
5473 assert!(def.is_univariant());
5474 def.variants[0].fields.get(i).map(|f| f.ty(self, substs))
5476 (&TyTuple(ref v), None) => v.get(i).cloned(),
5481 /// Returns the type of element at field `n` in struct or struct-like type `t`.
5482 /// For an enum `t`, `variant` must be some def id.
5483 pub fn named_element_ty(&self,
5486 variant: Option<DefId>) -> Option<Ty<'tcx>> {
5487 match (&ty.sty, variant) {
5488 (&TyStruct(def, substs), None) => {
5489 def.struct_variant().find_field_named(n).map(|f| f.ty(self, substs))
5491 (&TyEnum(def, substs), Some(vid)) => {
5492 def.variant_with_id(vid).find_field_named(n).map(|f| f.ty(self, substs))
5498 pub fn node_id_to_type(&self, id: ast::NodeId) -> Ty<'tcx> {
5499 match self.node_id_to_type_opt(id) {
5501 None => self.sess.bug(
5502 &format!("node_id_to_type: no type for node `{}`",
5503 self.map.node_to_string(id)))
5507 pub fn node_id_to_type_opt(&self, id: ast::NodeId) -> Option<Ty<'tcx>> {
5508 self.tables.borrow().node_types.get(&id).cloned()
5511 pub fn node_id_item_substs(&self, id: ast::NodeId) -> ItemSubsts<'tcx> {
5512 match self.tables.borrow().item_substs.get(&id) {
5513 None => ItemSubsts::empty(),
5514 Some(ts) => ts.clone(),
5518 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
5519 // doesn't provide type parameter substitutions.
5520 pub fn pat_ty(&self, pat: &ast::Pat) -> Ty<'tcx> {
5521 self.node_id_to_type(pat.id)
5523 pub fn pat_ty_opt(&self, pat: &ast::Pat) -> Option<Ty<'tcx>> {
5524 self.node_id_to_type_opt(pat.id)
5527 // Returns the type of an expression as a monotype.
5529 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
5530 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
5531 // auto-ref. The type returned by this function does not consider such
5532 // adjustments. See `expr_ty_adjusted()` instead.
5534 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
5535 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
5536 // instead of "fn(ty) -> T with T = isize".
5537 pub fn expr_ty(&self, expr: &ast::Expr) -> Ty<'tcx> {
5538 self.node_id_to_type(expr.id)
5541 pub fn expr_ty_opt(&self, expr: &ast::Expr) -> Option<Ty<'tcx>> {
5542 self.node_id_to_type_opt(expr.id)
5545 /// Returns the type of `expr`, considering any `AutoAdjustment`
5546 /// entry recorded for that expression.
5548 /// It would almost certainly be better to store the adjusted ty in with
5549 /// the `AutoAdjustment`, but I opted not to do this because it would
5550 /// require serializing and deserializing the type and, although that's not
5551 /// hard to do, I just hate that code so much I didn't want to touch it
5552 /// unless it was to fix it properly, which seemed a distraction from the
5553 /// thread at hand! -nmatsakis
5554 pub fn expr_ty_adjusted(&self, expr: &ast::Expr) -> Ty<'tcx> {
5556 .adjust(self, expr.span, expr.id,
5557 self.tables.borrow().adjustments.get(&expr.id),
5559 self.tables.borrow().method_map.get(&method_call).map(|method| method.ty)
5563 pub fn expr_span(&self, id: NodeId) -> Span {
5564 match self.map.find(id) {
5565 Some(ast_map::NodeExpr(e)) => {
5569 self.sess.bug(&format!("Node id {} is not an expr: {:?}",
5573 self.sess.bug(&format!("Node id {} is not present \
5574 in the node map", id));
5579 pub fn local_var_name_str(&self, id: NodeId) -> InternedString {
5580 match self.map.find(id) {
5581 Some(ast_map::NodeLocal(pat)) => {
5583 ast::PatIdent(_, ref path1, _) => path1.node.name.as_str(),
5585 self.sess.bug(&format!("Variable id {} maps to {:?}, not local", id, pat));
5589 r => self.sess.bug(&format!("Variable id {} maps to {:?}, not local", id, r)),
5593 pub fn resolve_expr(&self, expr: &ast::Expr) -> def::Def {
5594 match self.def_map.borrow().get(&expr.id) {
5595 Some(def) => def.full_def(),
5597 self.sess.span_bug(expr.span, &format!(
5598 "no def-map entry for expr {}", expr.id));
5603 pub fn expr_is_lval(&self, expr: &ast::Expr) -> bool {
5605 ast::ExprPath(..) => {
5606 // We can't use resolve_expr here, as this needs to run on broken
5607 // programs. We don't need to through - associated items are all
5609 match self.def_map.borrow().get(&expr.id) {
5610 Some(&def::PathResolution {
5611 base_def: def::DefStatic(..), ..
5612 }) | Some(&def::PathResolution {
5613 base_def: def::DefUpvar(..), ..
5614 }) | Some(&def::PathResolution {
5615 base_def: def::DefLocal(..), ..
5622 None => self.sess.span_bug(expr.span, &format!(
5623 "no def for path {}", expr.id))
5627 ast::ExprUnary(ast::UnDeref, _) |
5628 ast::ExprField(..) |
5629 ast::ExprTupField(..) |
5630 ast::ExprIndex(..) => {
5635 ast::ExprMethodCall(..) |
5636 ast::ExprStruct(..) |
5637 ast::ExprRange(..) |
5640 ast::ExprMatch(..) |
5641 ast::ExprClosure(..) |
5642 ast::ExprBlock(..) |
5643 ast::ExprRepeat(..) |
5645 ast::ExprBreak(..) |
5646 ast::ExprAgain(..) |
5648 ast::ExprWhile(..) |
5650 ast::ExprAssign(..) |
5651 ast::ExprInlineAsm(..) |
5652 ast::ExprAssignOp(..) |
5654 ast::ExprUnary(..) |
5656 ast::ExprAddrOf(..) |
5657 ast::ExprBinary(..) |
5658 ast::ExprCast(..) => {
5662 ast::ExprParen(ref e) => self.expr_is_lval(e),
5664 ast::ExprIfLet(..) |
5665 ast::ExprWhileLet(..) |
5666 ast::ExprForLoop(..) |
5667 ast::ExprMac(..) => {
5670 "macro expression remains after expansion");
5675 pub fn note_and_explain_type_err(&self, err: &TypeError<'tcx>, sp: Span) {
5676 use self::TypeError::*;
5679 RegionsDoesNotOutlive(subregion, superregion) => {
5680 self.note_and_explain_region("", subregion, "...");
5681 self.note_and_explain_region("...does not necessarily outlive ",
5684 RegionsNotSame(region1, region2) => {
5685 self.note_and_explain_region("", region1, "...");
5686 self.note_and_explain_region("...is not the same lifetime as ",
5689 RegionsNoOverlap(region1, region2) => {
5690 self.note_and_explain_region("", region1, "...");
5691 self.note_and_explain_region("...does not overlap ",
5694 RegionsInsufficientlyPolymorphic(_, conc_region) => {
5695 self.note_and_explain_region("concrete lifetime that was found is ",
5698 RegionsOverlyPolymorphic(_, ty::ReVar(_)) => {
5699 // don't bother to print out the message below for
5700 // inference variables, it's not very illuminating.
5702 RegionsOverlyPolymorphic(_, conc_region) => {
5703 self.note_and_explain_region("expected concrete lifetime is ",
5707 let expected_str = values.expected.sort_string(self);
5708 let found_str = values.found.sort_string(self);
5709 if expected_str == found_str && expected_str == "closure" {
5710 self.sess.span_note(sp,
5711 &format!("no two closures, even if identical, have the same type"));
5712 self.sess.span_help(sp,
5713 &format!("consider boxing your closure and/or \
5714 using it as a trait object"));
5717 TyParamDefaultMismatch(values) => {
5718 let expected = values.expected;
5719 let found = values.found;
5720 self.sess.span_note(sp,
5721 &format!("conflicting type parameter defaults `{}` and `{}`",
5725 match (expected.def_id.is_local(),
5726 self.map.opt_span(expected.def_id.node)) {
5727 (true, Some(span)) => {
5728 self.sess.span_note(span,
5729 &format!("a default was defined here..."));
5733 &format!("a default is defined on `{}`",
5734 self.item_path_str(expected.def_id)));
5738 self.sess.span_note(
5739 expected.origin_span,
5740 &format!("...that was applied to an unconstrained type variable here"));
5742 match (found.def_id.is_local(),
5743 self.map.opt_span(found.def_id.node)) {
5744 (true, Some(span)) => {
5745 self.sess.span_note(span,
5746 &format!("a second default was defined here..."));
5750 &format!("a second default is defined on `{}`",
5751 self.item_path_str(found.def_id)));
5755 self.sess.span_note(
5757 &format!("...that also applies to the same type variable here"));
5763 pub fn provided_source(&self, id: DefId) -> Option<DefId> {
5764 self.provided_method_sources.borrow().get(&id).cloned()
5767 pub fn provided_trait_methods(&self, id: DefId) -> Vec<Rc<Method<'tcx>>> {
5769 if let ItemTrait(_, _, _, ref ms) = self.map.expect_item(id.node).node {
5770 ms.iter().filter_map(|ti| {
5771 if let ast::MethodTraitItem(_, Some(_)) = ti.node {
5772 match self.impl_or_trait_item(DefId::local(ti.id)) {
5773 MethodTraitItem(m) => Some(m),
5775 self.sess.bug("provided_trait_methods(): \
5776 non-method item found from \
5777 looking up provided method?!")
5785 self.sess.bug(&format!("provided_trait_methods: `{:?}` is not a trait", id))
5788 csearch::get_provided_trait_methods(self, id)
5792 pub fn associated_consts(&self, id: DefId) -> Vec<Rc<AssociatedConst<'tcx>>> {
5794 match self.map.expect_item(id.node).node {
5795 ItemTrait(_, _, _, ref tis) => {
5796 tis.iter().filter_map(|ti| {
5797 if let ast::ConstTraitItem(_, _) = ti.node {
5798 match self.impl_or_trait_item(DefId::local(ti.id)) {
5799 ConstTraitItem(ac) => Some(ac),
5801 self.sess.bug("associated_consts(): \
5802 non-const item found from \
5803 looking up a constant?!")
5811 ItemImpl(_, _, _, _, _, ref iis) => {
5812 iis.iter().filter_map(|ii| {
5813 if let ast::ConstImplItem(_, _) = ii.node {
5814 match self.impl_or_trait_item(DefId::local(ii.id)) {
5815 ConstTraitItem(ac) => Some(ac),
5817 self.sess.bug("associated_consts(): \
5818 non-const item found from \
5819 looking up a constant?!")
5828 self.sess.bug(&format!("associated_consts: `{:?}` is not a trait \
5833 csearch::get_associated_consts(self, id)
5837 pub fn trait_items(&self, trait_did: DefId) -> Rc<Vec<ImplOrTraitItem<'tcx>>> {
5838 let mut trait_items = self.trait_items_cache.borrow_mut();
5839 match trait_items.get(&trait_did).cloned() {
5840 Some(trait_items) => trait_items,
5842 let def_ids = self.trait_item_def_ids(trait_did);
5843 let items: Rc<Vec<ImplOrTraitItem>> =
5844 Rc::new(def_ids.iter()
5845 .map(|d| self.impl_or_trait_item(d.def_id()))
5847 trait_items.insert(trait_did, items.clone());
5853 pub fn trait_impl_polarity(&self, id: DefId) -> Option<ast::ImplPolarity> {
5855 match self.map.find(id.node) {
5856 Some(ast_map::NodeItem(item)) => {
5858 ast::ItemImpl(_, polarity, _, _, _, _) => Some(polarity),
5865 csearch::get_impl_polarity(self, id)
5869 pub fn custom_coerce_unsized_kind(&self, did: DefId) -> CustomCoerceUnsized {
5870 memoized(&self.custom_coerce_unsized_kinds, did, |did: DefId| {
5871 let (kind, src) = if did.krate != LOCAL_CRATE {
5872 (csearch::get_custom_coerce_unsized_kind(self, did), "external")
5880 self.sess.bug(&format!("custom_coerce_unsized_kind: \
5881 {} impl `{}` is missing its kind",
5882 src, self.item_path_str(did)));
5888 pub fn impl_or_trait_item(&self, id: DefId) -> ImplOrTraitItem<'tcx> {
5889 lookup_locally_or_in_crate_store(
5890 "impl_or_trait_items", id, &self.impl_or_trait_items,
5891 || csearch::get_impl_or_trait_item(self, id))
5894 pub fn trait_item_def_ids(&self, id: DefId) -> Rc<Vec<ImplOrTraitItemId>> {
5895 lookup_locally_or_in_crate_store(
5896 "trait_item_def_ids", id, &self.trait_item_def_ids,
5897 || Rc::new(csearch::get_trait_item_def_ids(&self.sess.cstore, id)))
5900 /// Returns the trait-ref corresponding to a given impl, or None if it is
5901 /// an inherent impl.
5902 pub fn impl_trait_ref(&self, id: DefId) -> Option<TraitRef<'tcx>> {
5903 lookup_locally_or_in_crate_store(
5904 "impl_trait_refs", id, &self.impl_trait_refs,
5905 || csearch::get_impl_trait(self, id))
5908 /// Returns whether this DefId refers to an impl
5909 pub fn is_impl(&self, id: DefId) -> bool {
5911 if let Some(ast_map::NodeItem(
5912 &ast::Item { node: ast::ItemImpl(..), .. })) = self.map.find(id.node) {
5918 csearch::is_impl(&self.sess.cstore, id)
5922 pub fn trait_ref_to_def_id(&self, tr: &ast::TraitRef) -> DefId {
5923 self.def_map.borrow().get(&tr.ref_id).expect("no def-map entry for trait").def_id()
5926 pub fn try_add_builtin_trait(&self,
5927 trait_def_id: DefId,
5928 builtin_bounds: &mut EnumSet<BuiltinBound>)
5931 //! Checks whether `trait_ref` refers to one of the builtin
5932 //! traits, like `Send`, and adds the corresponding
5933 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
5934 //! is a builtin trait.
5936 match self.lang_items.to_builtin_kind(trait_def_id) {
5937 Some(bound) => { builtin_bounds.insert(bound); true }
5942 pub fn item_path_str(&self, id: DefId) -> String {
5943 self.with_path(id, |path| ast_map::path_to_string(path))
5946 pub fn with_path<T, F>(&self, id: DefId, f: F) -> T where
5947 F: FnOnce(ast_map::PathElems) -> T,
5950 self.map.with_path(id.node, f)
5952 f(csearch::get_item_path(self, id).iter().cloned().chain(LinkedPath::empty()))
5956 pub fn item_name(&self, id: DefId) -> ast::Name {
5958 self.map.get_path_elem(id.node).name()
5960 csearch::get_item_name(self, id)
5964 /// Returns `(normalized_type, ty)`, where `normalized_type` is the
5965 /// IntType representation of one of {i64,i32,i16,i8,u64,u32,u16,u8},
5966 /// and `ty` is the original type (i.e. may include `isize` or
5968 pub fn enum_repr_type(&self, opt_hint: Option<&attr::ReprAttr>)
5969 -> (attr::IntType, Ty<'tcx>) {
5970 let repr_type = match opt_hint {
5971 // Feed in the given type
5972 Some(&attr::ReprInt(_, int_t)) => int_t,
5973 // ... but provide sensible default if none provided
5975 // NB. Historically `fn enum_variants` generate i64 here, while
5976 // rustc_typeck::check would generate isize.
5977 _ => SignedInt(ast::TyIs),
5980 let repr_type_ty = repr_type.to_ty(self);
5981 let repr_type = match repr_type {
5982 SignedInt(ast::TyIs) =>
5983 SignedInt(self.sess.target.int_type),
5984 UnsignedInt(ast::TyUs) =>
5985 UnsignedInt(self.sess.target.uint_type),
5989 (repr_type, repr_type_ty)
5992 // Register a given item type
5993 pub fn register_item_type(&self, did: DefId, ty: TypeScheme<'tcx>) {
5994 self.tcache.borrow_mut().insert(did, ty);
5997 // If the given item is in an external crate, looks up its type and adds it to
5998 // the type cache. Returns the type parameters and type.
5999 pub fn lookup_item_type(&self, did: DefId) -> TypeScheme<'tcx> {
6000 lookup_locally_or_in_crate_store(
6001 "tcache", did, &self.tcache,
6002 || csearch::get_type(self, did))
6005 /// Given the did of a trait, returns its canonical trait ref.
6006 pub fn lookup_trait_def(&self, did: DefId) -> &'tcx TraitDef<'tcx> {
6007 lookup_locally_or_in_crate_store(
6008 "trait_defs", did, &self.trait_defs,
6009 || self.arenas.trait_defs.alloc(csearch::get_trait_def(self, did))
6013 /// Given the did of an ADT, return a master reference to its
6014 /// definition. Unless you are planning on fulfilling the ADT's fields,
6015 /// use lookup_adt_def instead.
6016 pub fn lookup_adt_def_master(&self, did: DefId) -> AdtDefMaster<'tcx> {
6017 lookup_locally_or_in_crate_store(
6018 "adt_defs", did, &self.adt_defs,
6019 || csearch::get_adt_def(self, did)
6023 /// Given the did of an ADT, return a reference to its definition.
6024 pub fn lookup_adt_def(&self, did: DefId) -> AdtDef<'tcx> {
6025 // when reverse-variance goes away, a transmute::<AdtDefMaster,AdtDef>
6026 // woud be needed here.
6027 self.lookup_adt_def_master(did)
6030 /// Return the list of all interned ADT definitions
6031 pub fn adt_defs(&self) -> Vec<AdtDef<'tcx>> {
6032 self.adt_defs.borrow().values().cloned().collect()
6035 /// Given the did of an item, returns its full set of predicates.
6036 pub fn lookup_predicates(&self, did: DefId) -> GenericPredicates<'tcx> {
6037 lookup_locally_or_in_crate_store(
6038 "predicates", did, &self.predicates,
6039 || csearch::get_predicates(self, did))
6042 /// Given the did of a trait, returns its superpredicates.
6043 pub fn lookup_super_predicates(&self, did: DefId) -> GenericPredicates<'tcx> {
6044 lookup_locally_or_in_crate_store(
6045 "super_predicates", did, &self.super_predicates,
6046 || csearch::get_super_predicates(self, did))
6049 /// Get the attributes of a definition.
6050 pub fn get_attrs(&self, did: DefId) -> Cow<'tcx, [ast::Attribute]> {
6052 Cow::Borrowed(self.map.attrs(did.node))
6054 Cow::Owned(csearch::get_item_attrs(&self.sess.cstore, did))
6058 /// Determine whether an item is annotated with an attribute
6059 pub fn has_attr(&self, did: DefId, attr: &str) -> bool {
6060 self.get_attrs(did).iter().any(|item| item.check_name(attr))
6063 /// Determine whether an item is annotated with `#[repr(packed)]`
6064 pub fn lookup_packed(&self, did: DefId) -> bool {
6065 self.lookup_repr_hints(did).contains(&attr::ReprPacked)
6068 /// Determine whether an item is annotated with `#[simd]`
6069 pub fn lookup_simd(&self, did: DefId) -> bool {
6070 self.has_attr(did, "simd")
6071 || self.lookup_repr_hints(did).contains(&attr::ReprSimd)
6074 /// Obtain the representation annotation for a struct definition.
6075 pub fn lookup_repr_hints(&self, did: DefId) -> Rc<Vec<attr::ReprAttr>> {
6076 memoized(&self.repr_hint_cache, did, |did: DefId| {
6077 Rc::new(if did.is_local() {
6078 self.get_attrs(did).iter().flat_map(|meta| {
6079 attr::find_repr_attrs(self.sess.diagnostic(), meta).into_iter()
6082 csearch::get_repr_attrs(&self.sess.cstore, did)
6087 /// Returns the deeply last field of nested structures, or the same type,
6088 /// if not a structure at all. Corresponds to the only possible unsized
6089 /// field, and its type can be used to determine unsizing strategy.
6090 pub fn struct_tail(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
6091 while let TyStruct(def, substs) = ty.sty {
6092 match def.struct_variant().fields.last() {
6093 Some(f) => ty = f.ty(self, substs),
6100 /// Same as applying struct_tail on `source` and `target`, but only
6101 /// keeps going as long as the two types are instances of the same
6102 /// structure definitions.
6103 /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
6104 /// whereas struct_tail produces `T`, and `Trait`, respectively.
6105 pub fn struct_lockstep_tails(&self,
6108 -> (Ty<'tcx>, Ty<'tcx>) {
6109 let (mut a, mut b) = (source, target);
6110 while let (&TyStruct(a_def, a_substs), &TyStruct(b_def, b_substs)) = (&a.sty, &b.sty) {
6114 if let Some(f) = a_def.struct_variant().fields.last() {
6115 a = f.ty(self, a_substs);
6116 b = f.ty(self, b_substs);
6124 // Returns the repeat count for a repeating vector expression.
6125 pub fn eval_repeat_count(&self, count_expr: &ast::Expr) -> usize {
6126 let hint = UncheckedExprHint(self.types.usize);
6127 match const_eval::eval_const_expr_partial(self, count_expr, hint) {
6129 let found = match val {
6130 ConstVal::Uint(count) => return count as usize,
6131 ConstVal::Int(count) if count >= 0 => return count as usize,
6132 const_val => const_val.description(),
6134 span_err!(self.sess, count_expr.span, E0306,
6135 "expected positive integer for repeat count, found {}",
6139 let err_msg = match count_expr.node {
6140 ast::ExprPath(None, ast::Path {
6144 }) if segments.len() == 1 =>
6145 format!("found variable"),
6146 _ => match err.kind {
6147 ErrKind::MiscCatchAll => format!("but found {}", err.description()),
6148 _ => format!("but {}", err.description())
6151 span_err!(self.sess, count_expr.span, E0307,
6152 "expected constant integer for repeat count, {}", err_msg);
6158 // Iterate over a type parameter's bounded traits and any supertraits
6159 // of those traits, ignoring kinds.
6160 // Here, the supertraits are the transitive closure of the supertrait
6161 // relation on the supertraits from each bounded trait's constraint
6163 pub fn each_bound_trait_and_supertraits<F>(&self,
6164 bounds: &[PolyTraitRef<'tcx>],
6167 F: FnMut(PolyTraitRef<'tcx>) -> bool,
6169 for bound_trait_ref in traits::transitive_bounds(self, bounds) {
6170 if !f(bound_trait_ref) {
6177 /// Given a set of predicates that apply to an object type, returns
6178 /// the region bounds that the (erased) `Self` type must
6179 /// outlive. Precisely *because* the `Self` type is erased, the
6180 /// parameter `erased_self_ty` must be supplied to indicate what type
6181 /// has been used to represent `Self` in the predicates
6182 /// themselves. This should really be a unique type; `FreshTy(0)` is a
6185 /// NB: in some cases, particularly around higher-ranked bounds,
6186 /// this function returns a kind of conservative approximation.
6187 /// That is, all regions returned by this function are definitely
6188 /// required, but there may be other region bounds that are not
6189 /// returned, as well as requirements like `for<'a> T: 'a`.
6191 /// Requires that trait definitions have been processed so that we can
6192 /// elaborate predicates and walk supertraits.
6193 pub fn required_region_bounds(&self,
6194 erased_self_ty: Ty<'tcx>,
6195 predicates: Vec<ty::Predicate<'tcx>>)
6196 -> Vec<ty::Region> {
6197 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
6201 assert!(!erased_self_ty.has_escaping_regions());
6203 traits::elaborate_predicates(self, predicates)
6204 .filter_map(|predicate| {
6206 ty::Predicate::Projection(..) |
6207 ty::Predicate::Trait(..) |
6208 ty::Predicate::Equate(..) |
6209 ty::Predicate::WellFormed(..) |
6210 ty::Predicate::ObjectSafe(..) |
6211 ty::Predicate::RegionOutlives(..) => {
6214 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
6215 // Search for a bound of the form `erased_self_ty
6216 // : 'a`, but be wary of something like `for<'a>
6217 // erased_self_ty : 'a` (we interpret a
6218 // higher-ranked bound like that as 'static,
6219 // though at present the code in `fulfill.rs`
6220 // considers such bounds to be unsatisfiable, so
6221 // it's kind of a moot point since you could never
6222 // construct such an object, but this seems
6223 // correct even if that code changes).
6224 if t == erased_self_ty && !r.has_escaping_regions() {
6235 pub fn item_variances(&self, item_id: DefId) -> Rc<ItemVariances> {
6236 lookup_locally_or_in_crate_store(
6237 "item_variance_map", item_id, &self.item_variance_map,
6238 || Rc::new(csearch::get_item_variances(&self.sess.cstore, item_id)))
6241 pub fn trait_has_default_impl(&self, trait_def_id: DefId) -> bool {
6242 self.populate_implementations_for_trait_if_necessary(trait_def_id);
6244 let def = self.lookup_trait_def(trait_def_id);
6245 def.flags.get().intersects(TraitFlags::HAS_DEFAULT_IMPL)
6248 /// Records a trait-to-implementation mapping.
6249 pub fn record_trait_has_default_impl(&self, trait_def_id: DefId) {
6250 let def = self.lookup_trait_def(trait_def_id);
6251 def.flags.set(def.flags.get() | TraitFlags::HAS_DEFAULT_IMPL)
6254 /// Load primitive inherent implementations if necessary
6255 pub fn populate_implementations_for_primitive_if_necessary(&self,
6256 primitive_def_id: DefId) {
6257 if primitive_def_id.is_local() {
6261 if self.populated_external_primitive_impls.borrow().contains(&primitive_def_id) {
6265 debug!("populate_implementations_for_primitive_if_necessary: searching for {:?}",
6268 let impl_items = csearch::get_impl_items(&self.sess.cstore, primitive_def_id);
6270 // Store the implementation info.
6271 self.impl_items.borrow_mut().insert(primitive_def_id, impl_items);
6272 self.populated_external_primitive_impls.borrow_mut().insert(primitive_def_id);
6275 /// Populates the type context with all the inherent implementations for
6276 /// the given type if necessary.
6277 pub fn populate_inherent_implementations_for_type_if_necessary(&self,
6279 if type_id.is_local() {
6283 if self.populated_external_types.borrow().contains(&type_id) {
6287 debug!("populate_inherent_implementations_for_type_if_necessary: searching for {:?}",
6290 let mut inherent_impls = Vec::new();
6291 csearch::each_inherent_implementation_for_type(&self.sess.cstore, type_id, |impl_def_id| {
6292 // Record the implementation.
6293 inherent_impls.push(impl_def_id);
6295 // Store the implementation info.
6296 let impl_items = csearch::get_impl_items(&self.sess.cstore, impl_def_id);
6297 self.impl_items.borrow_mut().insert(impl_def_id, impl_items);
6300 self.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
6301 self.populated_external_types.borrow_mut().insert(type_id);
6304 /// Populates the type context with all the implementations for the given
6305 /// trait if necessary.
6306 pub fn populate_implementations_for_trait_if_necessary(&self, trait_id: DefId) {
6307 if trait_id.is_local() {
6311 let def = self.lookup_trait_def(trait_id);
6312 if def.flags.get().intersects(TraitFlags::IMPLS_VALID) {
6316 debug!("populate_implementations_for_trait_if_necessary: searching for {:?}", def);
6318 if csearch::is_defaulted_trait(&self.sess.cstore, trait_id) {
6319 self.record_trait_has_default_impl(trait_id);
6322 csearch::each_implementation_for_trait(&self.sess.cstore, trait_id, |impl_def_id| {
6323 let impl_items = csearch::get_impl_items(&self.sess.cstore, impl_def_id);
6324 let trait_ref = self.impl_trait_ref(impl_def_id).unwrap();
6325 // Record the trait->implementation mapping.
6326 def.record_impl(self, impl_def_id, trait_ref);
6328 // For any methods that use a default implementation, add them to
6329 // the map. This is a bit unfortunate.
6330 for impl_item_def_id in &impl_items {
6331 let method_def_id = impl_item_def_id.def_id();
6332 match self.impl_or_trait_item(method_def_id) {
6333 MethodTraitItem(method) => {
6334 if let Some(source) = method.provided_source {
6335 self.provided_method_sources
6337 .insert(method_def_id, source);
6344 // Store the implementation info.
6345 self.impl_items.borrow_mut().insert(impl_def_id, impl_items);
6348 def.flags.set(def.flags.get() | TraitFlags::IMPLS_VALID);
6351 /// Given the def_id of an impl, return the def_id of the trait it implements.
6352 /// If it implements no trait, return `None`.
6353 pub fn trait_id_of_impl(&self, def_id: DefId) -> Option<DefId> {
6354 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
6357 /// If the given def ID describes a method belonging to an impl, return the
6358 /// ID of the impl that the method belongs to. Otherwise, return `None`.
6359 pub fn impl_of_method(&self, def_id: DefId) -> Option<DefId> {
6360 if def_id.krate != LOCAL_CRATE {
6361 return match csearch::get_impl_or_trait_item(self,
6362 def_id).container() {
6363 TraitContainer(_) => None,
6364 ImplContainer(def_id) => Some(def_id),
6367 match self.impl_or_trait_items.borrow().get(&def_id).cloned() {
6368 Some(trait_item) => {
6369 match trait_item.container() {
6370 TraitContainer(_) => None,
6371 ImplContainer(def_id) => Some(def_id),
6378 /// If the given def ID describes an item belonging to a trait (either a
6379 /// default method or an implementation of a trait method), return the ID of
6380 /// the trait that the method belongs to. Otherwise, return `None`.
6381 pub fn trait_of_item(&self, def_id: DefId) -> Option<DefId> {
6382 if def_id.krate != LOCAL_CRATE {
6383 return csearch::get_trait_of_item(&self.sess.cstore, def_id, self);
6385 match self.impl_or_trait_items.borrow().get(&def_id).cloned() {
6386 Some(impl_or_trait_item) => {
6387 match impl_or_trait_item.container() {
6388 TraitContainer(def_id) => Some(def_id),
6389 ImplContainer(def_id) => self.trait_id_of_impl(def_id),
6396 /// If the given def ID describes an item belonging to a trait, (either a
6397 /// default method or an implementation of a trait method), return the ID of
6398 /// the method inside trait definition (this means that if the given def ID
6399 /// is already that of the original trait method, then the return value is
6401 /// Otherwise, return `None`.
6402 pub fn trait_item_of_item(&self, def_id: DefId) -> Option<ImplOrTraitItemId> {
6403 let impl_item = match self.impl_or_trait_items.borrow().get(&def_id) {
6404 Some(m) => m.clone(),
6405 None => return None,
6407 let name = impl_item.name();
6408 match self.trait_of_item(def_id) {
6409 Some(trait_did) => {
6410 self.trait_items(trait_did).iter()
6411 .find(|item| item.name() == name)
6412 .map(|item| item.id())
6418 /// Creates a hash of the type `Ty` which will be the same no matter what crate
6419 /// context it's calculated within. This is used by the `type_id` intrinsic.
6420 pub fn hash_crate_independent(&self, ty: Ty<'tcx>, svh: &Svh) -> u64 {
6421 let mut state = SipHasher::new();
6422 helper(self, ty, svh, &mut state);
6423 return state.finish();
6425 fn helper<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh,
6426 state: &mut SipHasher) {
6427 macro_rules! byte { ($b:expr) => { ($b as u8).hash(state) } }
6428 macro_rules! hash { ($e:expr) => { $e.hash(state) } }
6430 let region = |state: &mut SipHasher, r: Region| {
6433 ReLateBound(db, BrAnon(i)) => {
6443 ReSkolemized(..) => {
6444 tcx.sess.bug("unexpected region found when hashing a type")
6448 let did = |state: &mut SipHasher, did: DefId| {
6449 let h = if did.is_local() {
6452 tcx.sess.cstore.get_crate_hash(did.krate)
6454 h.as_str().hash(state);
6455 did.node.hash(state);
6457 let mt = |state: &mut SipHasher, mt: TypeAndMut| {
6458 mt.mutbl.hash(state);
6460 let fn_sig = |state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| {
6461 let sig = tcx.anonymize_late_bound_regions(sig).0;
6462 for a in &sig.inputs { helper(tcx, *a, svh, state); }
6463 if let ty::FnConverging(output) = sig.output {
6464 helper(tcx, output, svh, state);
6467 ty.maybe_walk(|ty| {
6509 TyBareFn(opt_def_id, ref b) => {
6514 fn_sig(state, &b.sig);
6517 TyTrait(ref data) => {
6519 did(state, data.principal_def_id());
6522 let principal = tcx.anonymize_late_bound_regions(&data.principal).0;
6523 for subty in &principal.substs.types {
6524 helper(tcx, subty, svh, state);
6533 TyTuple(ref inner) => {
6541 hash!(p.name.as_str());
6543 TyInfer(_) => unreachable!(),
6544 TyError => byte!(21),
6545 TyClosure(d, _) => {
6549 TyProjection(ref data) => {
6551 did(state, data.trait_ref.def_id);
6552 hash!(data.item_name.as_str());
6560 /// Construct a parameter environment suitable for static contexts or other contexts where there
6561 /// are no free type/lifetime parameters in scope.
6562 pub fn empty_parameter_environment<'a>(&'a self)
6563 -> ParameterEnvironment<'a,'tcx> {
6564 ty::ParameterEnvironment { tcx: self,
6565 free_substs: Substs::empty(),
6566 caller_bounds: Vec::new(),
6567 implicit_region_bound: ty::ReEmpty,
6568 selection_cache: traits::SelectionCache::new(),
6570 // for an empty parameter
6571 // environment, there ARE no free
6572 // regions, so it shouldn't matter
6573 // what we use for the free id
6574 free_id: ast::DUMMY_NODE_ID }
6577 /// Constructs and returns a substitution that can be applied to move from
6578 /// the "outer" view of a type or method to the "inner" view.
6579 /// In general, this means converting from bound parameters to
6580 /// free parameters. Since we currently represent bound/free type
6581 /// parameters in the same way, this only has an effect on regions.
6582 pub fn construct_free_substs(&self, generics: &Generics<'tcx>,
6583 free_id: ast::NodeId) -> Substs<'tcx> {
6585 let mut types = VecPerParamSpace::empty();
6586 for def in generics.types.as_slice() {
6587 debug!("construct_parameter_environment(): push_types_from_defs: def={:?}",
6589 types.push(def.space, self.mk_param_from_def(def));
6592 let free_id_outlive = self.region_maps.item_extent(free_id);
6594 // map bound 'a => free 'a
6595 let mut regions = VecPerParamSpace::empty();
6596 for def in generics.regions.as_slice() {
6598 ReFree(FreeRegion { scope: free_id_outlive,
6599 bound_region: BrNamed(def.def_id, def.name) });
6600 debug!("push_region_params {:?}", region);
6601 regions.push(def.space, region);
6606 regions: subst::NonerasedRegions(regions)
6610 /// See `ParameterEnvironment` struct def'n for details
6611 pub fn construct_parameter_environment<'a>(&'a self,
6613 generics: &ty::Generics<'tcx>,
6614 generic_predicates: &ty::GenericPredicates<'tcx>,
6615 free_id: ast::NodeId)
6616 -> ParameterEnvironment<'a, 'tcx>
6619 // Construct the free substs.
6622 let free_substs = self.construct_free_substs(generics, free_id);
6623 let free_id_outlive = self.region_maps.item_extent(free_id);
6626 // Compute the bounds on Self and the type parameters.
6629 let bounds = generic_predicates.instantiate(self, &free_substs);
6630 let bounds = self.liberate_late_bound_regions(free_id_outlive, &ty::Binder(bounds));
6631 let predicates = bounds.predicates.into_vec();
6633 debug!("construct_parameter_environment: free_id={:?} free_subst={:?} predicates={:?}",
6639 // Finally, we have to normalize the bounds in the environment, in
6640 // case they contain any associated type projections. This process
6641 // can yield errors if the put in illegal associated types, like
6642 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
6643 // report these errors right here; this doesn't actually feel
6644 // right to me, because constructing the environment feels like a
6645 // kind of a "idempotent" action, but I'm not sure where would be
6646 // a better place. In practice, we construct environments for
6647 // every fn once during type checking, and we'll abort if there
6648 // are any errors at that point, so after type checking you can be
6649 // sure that this will succeed without errors anyway.
6652 let unnormalized_env = ty::ParameterEnvironment {
6654 free_substs: free_substs,
6655 implicit_region_bound: ty::ReScope(free_id_outlive),
6656 caller_bounds: predicates,
6657 selection_cache: traits::SelectionCache::new(),
6661 let cause = traits::ObligationCause::misc(span, free_id);
6662 traits::normalize_param_env_or_error(unnormalized_env, cause)
6665 pub fn is_method_call(&self, expr_id: ast::NodeId) -> bool {
6666 self.tables.borrow().method_map.contains_key(&MethodCall::expr(expr_id))
6669 pub fn is_overloaded_autoderef(&self, expr_id: ast::NodeId, autoderefs: u32) -> bool {
6670 self.tables.borrow().method_map.contains_key(&MethodCall::autoderef(expr_id,
6674 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
6675 Some(self.tables.borrow().upvar_capture_map.get(&upvar_id).unwrap().clone())
6679 /// Returns true if this ADT is a dtorck type, i.e. whether it being
6680 /// safe for destruction requires it to be alive
6681 fn is_adt_dtorck(&self, adt: AdtDef<'tcx>) -> bool {
6682 let dtor_method = match adt.destructor() {
6684 None => return false
6686 let impl_did = self.impl_of_method(dtor_method).unwrap_or_else(|| {
6687 self.sess.bug(&format!("no Drop impl for the dtor of `{:?}`", adt))
6689 let generics = adt.type_scheme(self).generics;
6691 // In `impl<'a> Drop ...`, we automatically assume
6692 // `'a` is meaningful and thus represents a bound
6693 // through which we could reach borrowed data.
6695 // FIXME (pnkfelix): In the future it would be good to
6696 // extend the language to allow the user to express,
6697 // in the impl signature, that a lifetime is not
6698 // actually used (something like `where 'a: ?Live`).
6699 if generics.has_region_params(subst::TypeSpace) {
6700 debug!("typ: {:?} has interesting dtor due to region params",
6705 let mut seen_items = Vec::new();
6706 let mut items_to_inspect = vec![impl_did];
6707 while let Some(item_def_id) = items_to_inspect.pop() {
6708 if seen_items.contains(&item_def_id) {
6712 for pred in self.lookup_predicates(item_def_id).predicates {
6713 let result = match pred {
6714 ty::Predicate::Equate(..) |
6715 ty::Predicate::RegionOutlives(..) |
6716 ty::Predicate::TypeOutlives(..) |
6717 ty::Predicate::WellFormed(..) |
6718 ty::Predicate::ObjectSafe(..) |
6719 ty::Predicate::Projection(..) => {
6720 // For now, assume all these where-clauses
6721 // may give drop implementation capabilty
6722 // to access borrowed data.
6726 ty::Predicate::Trait(ty::Binder(ref t_pred)) => {
6727 let def_id = t_pred.trait_ref.def_id;
6728 if self.trait_items(def_id).len() != 0 {
6729 // If trait has items, assume it adds
6730 // capability to access borrowed data.
6733 // Trait without items is itself
6734 // uninteresting from POV of dropck.
6736 // However, may have parent w/ items;
6737 // so schedule checking of predicates,
6738 items_to_inspect.push(def_id);
6739 // and say "no capability found" for now.
6746 debug!("typ: {:?} has interesting dtor due to generic preds, e.g. {:?}",
6752 seen_items.push(item_def_id);
6755 debug!("typ: {:?} is dtorck-safe", adt);
6760 /// The category of explicit self.
6761 #[derive(Clone, Copy, Eq, PartialEq, Debug)]
6762 pub enum ExplicitSelfCategory {
6763 StaticExplicitSelfCategory,
6764 ByValueExplicitSelfCategory,
6765 ByReferenceExplicitSelfCategory(Region, ast::Mutability),
6766 ByBoxExplicitSelfCategory,
6769 /// A free variable referred to in a function.
6770 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
6771 pub struct Freevar {
6772 /// The variable being accessed free.
6775 // First span where it is accessed (there can be multiple).
6779 pub type FreevarMap = NodeMap<Vec<Freevar>>;
6781 pub type CaptureModeMap = NodeMap<ast::CaptureClause>;
6783 // Trait method resolution
6784 pub type TraitMap = NodeMap<Vec<DefId>>;
6786 // Map from the NodeId of a glob import to a list of items which are actually
6788 pub type GlobMap = HashMap<NodeId, HashSet<Name>>;
6790 impl<'tcx> AutoAdjustment<'tcx> {
6791 pub fn is_identity(&self) -> bool {
6793 AdjustReifyFnPointer |
6794 AdjustUnsafeFnPointer => false,
6795 AdjustDerefRef(ref r) => r.is_identity(),
6800 impl<'tcx> AutoDerefRef<'tcx> {
6801 pub fn is_identity(&self) -> bool {
6802 self.autoderefs == 0 && self.unsize.is_none() && self.autoref.is_none()
6806 impl<'tcx> ctxt<'tcx> {
6807 pub fn with_freevars<T, F>(&self, fid: ast::NodeId, f: F) -> T where
6808 F: FnOnce(&[Freevar]) -> T,
6810 match self.freevars.borrow().get(&fid) {
6812 Some(d) => f(&d[..])
6816 /// Replace any late-bound regions bound in `value` with free variants attached to scope-id
6818 pub fn liberate_late_bound_regions<T>(&self,
6819 all_outlive_scope: region::CodeExtent,
6822 where T : TypeFoldable<'tcx>
6824 ty_fold::replace_late_bound_regions(
6826 |br| ty::ReFree(ty::FreeRegion{scope: all_outlive_scope, bound_region: br})).0
6829 /// Flattens two binding levels into one. So `for<'a> for<'b> Foo`
6830 /// becomes `for<'a,'b> Foo`.
6831 pub fn flatten_late_bound_regions<T>(&self, bound2_value: &Binder<Binder<T>>)
6833 where T: TypeFoldable<'tcx>
6835 let bound0_value = bound2_value.skip_binder().skip_binder();
6836 let value = ty_fold::fold_regions(self, bound0_value, &mut false,
6837 |region, current_depth| {
6839 ty::ReLateBound(debruijn, br) if debruijn.depth >= current_depth => {
6840 // should be true if no escaping regions from bound2_value
6841 assert!(debruijn.depth - current_depth <= 1);
6842 ty::ReLateBound(DebruijnIndex::new(current_depth), br)
6852 pub fn no_late_bound_regions<T>(&self, value: &Binder<T>) -> Option<T>
6853 where T : TypeFoldable<'tcx> + RegionEscape
6855 if value.0.has_escaping_regions() {
6858 Some(value.0.clone())
6862 /// Replace any late-bound regions bound in `value` with `'static`. Useful in trans but also
6863 /// method lookup and a few other places where precise region relationships are not required.
6864 pub fn erase_late_bound_regions<T>(&self, value: &Binder<T>) -> T
6865 where T : TypeFoldable<'tcx>
6867 ty_fold::replace_late_bound_regions(self, value, |_| ty::ReStatic).0
6870 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
6871 /// assigned starting at 1 and increasing monotonically in the order traversed
6872 /// by the fold operation.
6874 /// The chief purpose of this function is to canonicalize regions so that two
6875 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
6876 /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
6877 /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
6878 pub fn anonymize_late_bound_regions<T>(&self, sig: &Binder<T>) -> Binder<T>
6879 where T : TypeFoldable<'tcx>,
6881 let mut counter = 0;
6882 ty::Binder(ty_fold::replace_late_bound_regions(self, sig, |_| {
6884 ReLateBound(ty::DebruijnIndex::new(1), BrAnon(counter))
6888 pub fn make_substs_for_receiver_types(&self,
6889 trait_ref: &ty::TraitRef<'tcx>,
6890 method: &ty::Method<'tcx>)
6891 -> subst::Substs<'tcx>
6894 * Substitutes the values for the receiver's type parameters
6895 * that are found in method, leaving the method's type parameters
6899 let meth_tps: Vec<Ty> =
6900 method.generics.types.get_slice(subst::FnSpace)
6902 .map(|def| self.mk_param_from_def(def))
6904 let meth_regions: Vec<ty::Region> =
6905 method.generics.regions.get_slice(subst::FnSpace)
6907 .map(|def| def.to_early_bound_region())
6909 trait_ref.substs.clone().with_method(meth_tps, meth_regions)
6913 impl DebruijnIndex {
6914 pub fn new(depth: u32) -> DebruijnIndex {
6916 DebruijnIndex { depth: depth }
6919 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
6920 DebruijnIndex { depth: self.depth + amount }
6924 impl<'tcx> fmt::Debug for AutoAdjustment<'tcx> {
6925 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6927 AdjustReifyFnPointer => {
6928 write!(f, "AdjustReifyFnPointer")
6930 AdjustUnsafeFnPointer => {
6931 write!(f, "AdjustUnsafeFnPointer")
6933 AdjustDerefRef(ref data) => {
6934 write!(f, "{:?}", data)
6940 impl<'tcx> fmt::Debug for AutoDerefRef<'tcx> {
6941 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6942 write!(f, "AutoDerefRef({}, unsize={:?}, {:?})",
6943 self.autoderefs, self.unsize, self.autoref)
6947 impl<'tcx> fmt::Debug for TraitTy<'tcx> {
6948 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6949 write!(f, "TraitTy({:?},{:?})",
6955 impl<'tcx> fmt::Debug for ty::Predicate<'tcx> {
6956 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6958 Predicate::Trait(ref a) => write!(f, "{:?}", a),
6959 Predicate::Equate(ref pair) => write!(f, "{:?}", pair),
6960 Predicate::RegionOutlives(ref pair) => write!(f, "{:?}", pair),
6961 Predicate::TypeOutlives(ref pair) => write!(f, "{:?}", pair),
6962 Predicate::Projection(ref pair) => write!(f, "{:?}", pair),
6963 Predicate::WellFormed(ty) => write!(f, "WF({:?})", ty),
6964 Predicate::ObjectSafe(trait_def_id) => write!(f, "ObjectSafe({:?})", trait_def_id),
6969 // FIXME(#20298) -- all of these traits basically walk various
6970 // structures to test whether types/regions are reachable with various
6971 // properties. It should be possible to express them in terms of one
6972 // common "walker" trait or something.
6974 /// An "escaping region" is a bound region whose binder is not part of `t`.
6976 /// So, for example, consider a type like the following, which has two binders:
6978 /// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
6979 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
6980 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
6982 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
6983 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
6984 /// fn type*, that type has an escaping region: `'a`.
6986 /// Note that what I'm calling an "escaping region" is often just called a "free region". However,
6987 /// we already use the term "free region". It refers to the regions that we use to represent bound
6988 /// regions on a fn definition while we are typechecking its body.
6990 /// To clarify, conceptually there is no particular difference between an "escaping" region and a
6991 /// "free" region. However, there is a big difference in practice. Basically, when "entering" a
6992 /// binding level, one is generally required to do some sort of processing to a bound region, such
6993 /// as replacing it with a fresh/skolemized region, or making an entry in the environment to
6994 /// represent the scope to which it is attached, etc. An escaping region represents a bound region
6995 /// for which this processing has not yet been done.
6996 pub trait RegionEscape {
6997 fn has_escaping_regions(&self) -> bool {
6998 self.has_regions_escaping_depth(0)
7001 fn has_regions_escaping_depth(&self, depth: u32) -> bool;
7004 impl<'tcx> RegionEscape for Ty<'tcx> {
7005 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7006 self.region_depth > depth
7010 impl<'tcx> RegionEscape for TraitTy<'tcx> {
7011 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7012 self.principal.has_regions_escaping_depth(depth) ||
7013 self.bounds.has_regions_escaping_depth(depth)
7017 impl<'tcx> RegionEscape for ExistentialBounds<'tcx> {
7018 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7019 self.region_bound.has_regions_escaping_depth(depth) ||
7020 self.projection_bounds.has_regions_escaping_depth(depth)
7024 impl<'tcx> RegionEscape for Substs<'tcx> {
7025 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7026 self.types.has_regions_escaping_depth(depth) ||
7027 self.regions.has_regions_escaping_depth(depth)
7031 impl<'tcx> RegionEscape for ClosureSubsts<'tcx> {
7032 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7033 self.func_substs.has_regions_escaping_depth(depth) ||
7034 self.upvar_tys.iter().any(|t| t.has_regions_escaping_depth(depth))
7038 impl<T:RegionEscape> RegionEscape for Vec<T> {
7039 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7040 self.iter().any(|t| t.has_regions_escaping_depth(depth))
7044 impl<'tcx> RegionEscape for FnSig<'tcx> {
7045 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7046 self.inputs.has_regions_escaping_depth(depth) ||
7047 self.output.has_regions_escaping_depth(depth)
7051 impl<'tcx,T:RegionEscape> RegionEscape for VecPerParamSpace<T> {
7052 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7053 self.iter_enumerated().any(|(space, _, t)| {
7054 if space == subst::FnSpace {
7055 t.has_regions_escaping_depth(depth+1)
7057 t.has_regions_escaping_depth(depth)
7063 impl<'tcx> RegionEscape for TypeScheme<'tcx> {
7064 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7065 self.ty.has_regions_escaping_depth(depth)
7069 impl RegionEscape for Region {
7070 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7071 self.escapes_depth(depth)
7075 impl<'tcx> RegionEscape for GenericPredicates<'tcx> {
7076 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7077 self.predicates.has_regions_escaping_depth(depth)
7081 impl<'tcx> RegionEscape for Predicate<'tcx> {
7082 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7084 Predicate::Trait(ref data) => data.has_regions_escaping_depth(depth),
7085 Predicate::Equate(ref data) => data.has_regions_escaping_depth(depth),
7086 Predicate::RegionOutlives(ref data) => data.has_regions_escaping_depth(depth),
7087 Predicate::TypeOutlives(ref data) => data.has_regions_escaping_depth(depth),
7088 Predicate::Projection(ref data) => data.has_regions_escaping_depth(depth),
7089 Predicate::WellFormed(ty) => ty.has_regions_escaping_depth(depth),
7090 Predicate::ObjectSafe(_trait_def_id) => false,
7095 impl<'tcx,P:RegionEscape> RegionEscape for traits::Obligation<'tcx,P> {
7096 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7097 self.predicate.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 FnOutput<'tcx> {
7126 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7128 FnConverging(t) => t.has_regions_escaping_depth(depth),
7129 FnDiverging => false
7134 impl<'tcx> RegionEscape for EquatePredicate<'tcx> {
7135 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7136 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7140 impl<'tcx> RegionEscape for TraitPredicate<'tcx> {
7141 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7142 self.trait_ref.has_regions_escaping_depth(depth)
7146 impl<T:RegionEscape,U:RegionEscape> RegionEscape for OutlivesPredicate<T,U> {
7147 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7148 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7152 impl<'tcx> RegionEscape for ProjectionPredicate<'tcx> {
7153 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7154 self.projection_ty.has_regions_escaping_depth(depth) ||
7155 self.ty.has_regions_escaping_depth(depth)
7159 impl<'tcx> RegionEscape for ProjectionTy<'tcx> {
7160 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7161 self.trait_ref.has_regions_escaping_depth(depth)
7165 pub trait HasTypeFlags {
7166 fn has_type_flags(&self, flags: TypeFlags) -> bool;
7167 fn has_projection_types(&self) -> bool {
7168 self.has_type_flags(TypeFlags::HAS_PROJECTION)
7170 fn references_error(&self) -> bool {
7171 self.has_type_flags(TypeFlags::HAS_TY_ERR)
7173 fn has_param_types(&self) -> bool {
7174 self.has_type_flags(TypeFlags::HAS_PARAMS)
7176 fn has_self_ty(&self) -> bool {
7177 self.has_type_flags(TypeFlags::HAS_SELF)
7179 fn has_infer_types(&self) -> bool {
7180 self.has_type_flags(TypeFlags::HAS_TY_INFER)
7182 fn needs_infer(&self) -> bool {
7183 self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_RE_INFER)
7185 fn needs_subst(&self) -> bool {
7186 self.has_type_flags(TypeFlags::NEEDS_SUBST)
7188 fn has_closure_types(&self) -> bool {
7189 self.has_type_flags(TypeFlags::HAS_TY_CLOSURE)
7191 fn has_erasable_regions(&self) -> bool {
7192 self.has_type_flags(TypeFlags::HAS_RE_EARLY_BOUND |
7193 TypeFlags::HAS_RE_INFER |
7194 TypeFlags::HAS_FREE_REGIONS)
7196 /// Indicates whether this value references only 'global'
7197 /// types/lifetimes that are the same regardless of what fn we are
7198 /// in. This is used for caching. Errs on the side of returning
7200 fn is_global(&self) -> bool {
7201 !self.has_type_flags(TypeFlags::HAS_LOCAL_NAMES)
7205 impl<'tcx,T:HasTypeFlags> HasTypeFlags for Vec<T> {
7206 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7207 self[..].has_type_flags(flags)
7211 impl<'tcx,T:HasTypeFlags> HasTypeFlags for [T] {
7212 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7213 self.iter().any(|p| p.has_type_flags(flags))
7217 impl<'tcx,T:HasTypeFlags> HasTypeFlags for VecPerParamSpace<T> {
7218 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7219 self.iter().any(|p| p.has_type_flags(flags))
7223 impl HasTypeFlags for abi::Abi {
7224 fn has_type_flags(&self, _flags: TypeFlags) -> bool {
7229 impl HasTypeFlags for ast::Unsafety {
7230 fn has_type_flags(&self, _flags: TypeFlags) -> bool {
7235 impl HasTypeFlags for BuiltinBounds {
7236 fn has_type_flags(&self, _flags: TypeFlags) -> bool {
7241 impl<'tcx> HasTypeFlags for ClosureTy<'tcx> {
7242 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7243 self.sig.has_type_flags(flags)
7247 impl<'tcx> HasTypeFlags for ClosureUpvar<'tcx> {
7248 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7249 self.ty.has_type_flags(flags)
7253 impl<'tcx> HasTypeFlags for ExistentialBounds<'tcx> {
7254 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7255 self.projection_bounds.has_type_flags(flags)
7259 impl<'tcx> HasTypeFlags for ty::InstantiatedPredicates<'tcx> {
7260 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7261 self.predicates.has_type_flags(flags)
7265 impl<'tcx> HasTypeFlags for Predicate<'tcx> {
7266 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7268 Predicate::Trait(ref data) => data.has_type_flags(flags),
7269 Predicate::Equate(ref data) => data.has_type_flags(flags),
7270 Predicate::RegionOutlives(ref data) => data.has_type_flags(flags),
7271 Predicate::TypeOutlives(ref data) => data.has_type_flags(flags),
7272 Predicate::Projection(ref data) => data.has_type_flags(flags),
7273 Predicate::WellFormed(data) => data.has_type_flags(flags),
7274 Predicate::ObjectSafe(_trait_def_id) => false,
7279 impl<'tcx> HasTypeFlags for TraitPredicate<'tcx> {
7280 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7281 self.trait_ref.has_type_flags(flags)
7285 impl<'tcx> HasTypeFlags for EquatePredicate<'tcx> {
7286 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7287 self.0.has_type_flags(flags) || self.1.has_type_flags(flags)
7291 impl HasTypeFlags for Region {
7292 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7293 if flags.intersects(TypeFlags::HAS_LOCAL_NAMES) {
7294 // does this represent a region that cannot be named in a global
7295 // way? used in fulfillment caching.
7297 ty::ReStatic | ty::ReEmpty => {}
7301 if flags.intersects(TypeFlags::HAS_RE_INFER) {
7303 ty::ReVar(_) | ty::ReSkolemized(..) => { return true }
7311 impl<T:HasTypeFlags,U:HasTypeFlags> HasTypeFlags for OutlivesPredicate<T,U> {
7312 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7313 self.0.has_type_flags(flags) || self.1.has_type_flags(flags)
7317 impl<'tcx> HasTypeFlags for ProjectionPredicate<'tcx> {
7318 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7319 self.projection_ty.has_type_flags(flags) || self.ty.has_type_flags(flags)
7323 impl<'tcx> HasTypeFlags for ProjectionTy<'tcx> {
7324 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7325 self.trait_ref.has_type_flags(flags)
7329 impl<'tcx> HasTypeFlags for Ty<'tcx> {
7330 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7331 self.flags.get().intersects(flags)
7335 impl<'tcx> HasTypeFlags for TypeAndMut<'tcx> {
7336 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7337 self.ty.has_type_flags(flags)
7341 impl<'tcx> HasTypeFlags for TraitRef<'tcx> {
7342 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7343 self.substs.has_type_flags(flags)
7347 impl<'tcx> HasTypeFlags for subst::Substs<'tcx> {
7348 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7349 self.types.has_type_flags(flags) || match self.regions {
7350 subst::ErasedRegions => false,
7351 subst::NonerasedRegions(ref r) => r.has_type_flags(flags)
7356 impl<'tcx,T> HasTypeFlags for Option<T>
7357 where T : HasTypeFlags
7359 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7360 self.iter().any(|t| t.has_type_flags(flags))
7364 impl<'tcx,T> HasTypeFlags for Rc<T>
7365 where T : HasTypeFlags
7367 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7368 (**self).has_type_flags(flags)
7372 impl<'tcx,T> HasTypeFlags for Box<T>
7373 where T : HasTypeFlags
7375 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7376 (**self).has_type_flags(flags)
7380 impl<T> HasTypeFlags for Binder<T>
7381 where T : HasTypeFlags
7383 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7384 self.0.has_type_flags(flags)
7388 impl<'tcx> HasTypeFlags for FnOutput<'tcx> {
7389 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7391 FnConverging(t) => t.has_type_flags(flags),
7392 FnDiverging => false,
7397 impl<'tcx> HasTypeFlags for FnSig<'tcx> {
7398 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7399 self.inputs.iter().any(|t| t.has_type_flags(flags)) ||
7400 self.output.has_type_flags(flags)
7404 impl<'tcx> HasTypeFlags for BareFnTy<'tcx> {
7405 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7406 self.sig.has_type_flags(flags)
7410 impl<'tcx> HasTypeFlags for ClosureSubsts<'tcx> {
7411 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7412 self.func_substs.has_type_flags(flags) ||
7413 self.upvar_tys.iter().any(|t| t.has_type_flags(flags))
7417 impl<'tcx> fmt::Debug for ClosureTy<'tcx> {
7418 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7419 write!(f, "ClosureTy({},{:?},{})",
7426 impl<'tcx> fmt::Debug for ClosureUpvar<'tcx> {
7427 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7428 write!(f, "ClosureUpvar({:?},{:?})",
7434 impl<'a, 'tcx> fmt::Debug for ParameterEnvironment<'a, 'tcx> {
7435 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7436 write!(f, "ParameterEnvironment(\
7438 implicit_region_bound={:?}, \
7439 caller_bounds={:?})",
7441 self.implicit_region_bound,
7446 impl<'tcx> fmt::Debug for ObjectLifetimeDefault {
7447 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7449 ObjectLifetimeDefault::Ambiguous => write!(f, "Ambiguous"),
7450 ObjectLifetimeDefault::BaseDefault => write!(f, "BaseDefault"),
7451 ObjectLifetimeDefault::Specific(ref r) => write!(f, "{:?}", r),