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::*;
32 pub use self::LvaluePreference::*;
34 pub use self::BuiltinBound::Send as BoundSend;
35 pub use self::BuiltinBound::Sized as BoundSized;
36 pub use self::BuiltinBound::Copy as BoundCopy;
37 pub use self::BuiltinBound::Sync as BoundSync;
42 use front::map as ast_map;
43 use front::map::LinkedPath;
44 use metadata::csearch;
46 use middle::check_const;
47 use middle::const_eval::{self, ConstVal, ErrKind};
48 use middle::const_eval::EvalHint::UncheckedExprHint;
49 use middle::def::{self, DefMap, ExportMap};
50 use middle::def_id::{DefId, LOCAL_CRATE};
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::{TypeFoldable, TypeFolder};
64 use middle::ty::walk::{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::{self, CrateNum, Name, NodeId};
89 use syntax::codemap::Span;
90 use syntax::parse::token::{InternedString, special_idents};
93 use rustc_front::hir::{ItemImpl, ItemTrait};
94 use rustc_front::hir::{MutImmutable, MutMutable, Visibility};
95 use rustc_front::attr::{self, AttrMetaMethods, SignedInt, UnsignedInt};
108 pub const INITIAL_DISCRIMINANT_VALUE: Disr = 0;
112 /// The complete set of all analyses described in this module. This is
113 /// produced by the driver and fed to trans and later passes.
114 pub struct CrateAnalysis {
115 pub export_map: ExportMap,
116 pub exported_items: middle::privacy::ExportedItems,
117 pub public_items: middle::privacy::PublicItems,
118 pub reachable: NodeSet,
120 pub glob_map: Option<GlobMap>,
124 #[derive(Copy, Clone)]
131 pub fn is_present(&self) -> bool {
133 TraitDtor(..) => true,
138 pub fn has_drop_flag(&self) -> bool {
141 &TraitDtor(flag) => flag
146 pub trait IntTypeExt {
147 fn to_ty<'tcx>(&self, cx: &ctxt<'tcx>) -> Ty<'tcx>;
148 fn i64_to_disr(&self, val: i64) -> Option<Disr>;
149 fn u64_to_disr(&self, val: u64) -> Option<Disr>;
150 fn disr_incr(&self, val: Disr) -> Option<Disr>;
151 fn disr_string(&self, val: Disr) -> String;
152 fn disr_wrap_incr(&self, val: Option<Disr>) -> Disr;
155 impl IntTypeExt for attr::IntType {
156 fn to_ty<'tcx>(&self, cx: &ctxt<'tcx>) -> Ty<'tcx> {
158 SignedInt(hir::TyI8) => cx.types.i8,
159 SignedInt(hir::TyI16) => cx.types.i16,
160 SignedInt(hir::TyI32) => cx.types.i32,
161 SignedInt(hir::TyI64) => cx.types.i64,
162 SignedInt(hir::TyIs) => cx.types.isize,
163 UnsignedInt(hir::TyU8) => cx.types.u8,
164 UnsignedInt(hir::TyU16) => cx.types.u16,
165 UnsignedInt(hir::TyU32) => cx.types.u32,
166 UnsignedInt(hir::TyU64) => cx.types.u64,
167 UnsignedInt(hir::TyUs) => cx.types.usize,
171 fn i64_to_disr(&self, val: i64) -> Option<Disr> {
173 SignedInt(hir::TyI8) => val.to_i8() .map(|v| v as Disr),
174 SignedInt(hir::TyI16) => val.to_i16() .map(|v| v as Disr),
175 SignedInt(hir::TyI32) => val.to_i32() .map(|v| v as Disr),
176 SignedInt(hir::TyI64) => val.to_i64() .map(|v| v as Disr),
177 UnsignedInt(hir::TyU8) => val.to_u8() .map(|v| v as Disr),
178 UnsignedInt(hir::TyU16) => val.to_u16() .map(|v| v as Disr),
179 UnsignedInt(hir::TyU32) => val.to_u32() .map(|v| v as Disr),
180 UnsignedInt(hir::TyU64) => val.to_u64() .map(|v| v as Disr),
182 UnsignedInt(hir::TyUs) |
183 SignedInt(hir::TyIs) => unreachable!(),
187 fn u64_to_disr(&self, val: u64) -> Option<Disr> {
189 SignedInt(hir::TyI8) => val.to_i8() .map(|v| v as Disr),
190 SignedInt(hir::TyI16) => val.to_i16() .map(|v| v as Disr),
191 SignedInt(hir::TyI32) => val.to_i32() .map(|v| v as Disr),
192 SignedInt(hir::TyI64) => val.to_i64() .map(|v| v as Disr),
193 UnsignedInt(hir::TyU8) => val.to_u8() .map(|v| v as Disr),
194 UnsignedInt(hir::TyU16) => val.to_u16() .map(|v| v as Disr),
195 UnsignedInt(hir::TyU32) => val.to_u32() .map(|v| v as Disr),
196 UnsignedInt(hir::TyU64) => val.to_u64() .map(|v| v as Disr),
198 UnsignedInt(hir::TyUs) |
199 SignedInt(hir::TyIs) => unreachable!(),
203 fn disr_incr(&self, val: Disr) -> Option<Disr> {
205 ($e:expr) => { $e.and_then(|v|v.checked_add(1)).map(|v| v as Disr) }
208 // SignedInt repr means we *want* to reinterpret the bits
209 // treating the highest bit of Disr as a sign-bit, so
210 // cast to i64 before range-checking.
211 SignedInt(hir::TyI8) => add1!((val as i64).to_i8()),
212 SignedInt(hir::TyI16) => add1!((val as i64).to_i16()),
213 SignedInt(hir::TyI32) => add1!((val as i64).to_i32()),
214 SignedInt(hir::TyI64) => add1!(Some(val as i64)),
216 UnsignedInt(hir::TyU8) => add1!(val.to_u8()),
217 UnsignedInt(hir::TyU16) => add1!(val.to_u16()),
218 UnsignedInt(hir::TyU32) => add1!(val.to_u32()),
219 UnsignedInt(hir::TyU64) => add1!(Some(val)),
221 UnsignedInt(hir::TyUs) |
222 SignedInt(hir::TyIs) => unreachable!(),
226 // This returns a String because (1.) it is only used for
227 // rendering an error message and (2.) a string can represent the
228 // full range from `i64::MIN` through `u64::MAX`.
229 fn disr_string(&self, val: Disr) -> String {
231 SignedInt(hir::TyI8) => format!("{}", val as i8 ),
232 SignedInt(hir::TyI16) => format!("{}", val as i16),
233 SignedInt(hir::TyI32) => format!("{}", val as i32),
234 SignedInt(hir::TyI64) => format!("{}", val as i64),
235 UnsignedInt(hir::TyU8) => format!("{}", val as u8 ),
236 UnsignedInt(hir::TyU16) => format!("{}", val as u16),
237 UnsignedInt(hir::TyU32) => format!("{}", val as u32),
238 UnsignedInt(hir::TyU64) => format!("{}", val as u64),
240 UnsignedInt(hir::TyUs) |
241 SignedInt(hir::TyIs) => unreachable!(),
245 fn disr_wrap_incr(&self, val: Option<Disr>) -> Disr {
247 ($e:expr) => { ($e).wrapping_add(1) as Disr }
249 let val = val.unwrap_or(ty::INITIAL_DISCRIMINANT_VALUE);
251 SignedInt(hir::TyI8) => add1!(val as i8 ),
252 SignedInt(hir::TyI16) => add1!(val as i16),
253 SignedInt(hir::TyI32) => add1!(val as i32),
254 SignedInt(hir::TyI64) => add1!(val as i64),
255 UnsignedInt(hir::TyU8) => add1!(val as u8 ),
256 UnsignedInt(hir::TyU16) => add1!(val as u16),
257 UnsignedInt(hir::TyU32) => add1!(val as u32),
258 UnsignedInt(hir::TyU64) => add1!(val as u64),
260 UnsignedInt(hir::TyUs) |
261 SignedInt(hir::TyIs) => unreachable!(),
266 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
267 pub enum ImplOrTraitItemContainer {
268 TraitContainer(DefId),
269 ImplContainer(DefId),
272 impl ImplOrTraitItemContainer {
273 pub fn id(&self) -> DefId {
275 TraitContainer(id) => id,
276 ImplContainer(id) => id,
282 pub enum ImplOrTraitItem<'tcx> {
283 ConstTraitItem(Rc<AssociatedConst<'tcx>>),
284 MethodTraitItem(Rc<Method<'tcx>>),
285 TypeTraitItem(Rc<AssociatedType<'tcx>>),
288 impl<'tcx> ImplOrTraitItem<'tcx> {
289 fn id(&self) -> ImplOrTraitItemId {
291 ConstTraitItem(ref associated_const) => {
292 ConstTraitItemId(associated_const.def_id)
294 MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
295 TypeTraitItem(ref associated_type) => {
296 TypeTraitItemId(associated_type.def_id)
301 pub fn def_id(&self) -> DefId {
303 ConstTraitItem(ref associated_const) => associated_const.def_id,
304 MethodTraitItem(ref method) => method.def_id,
305 TypeTraitItem(ref associated_type) => associated_type.def_id,
309 pub fn name(&self) -> Name {
311 ConstTraitItem(ref associated_const) => associated_const.name,
312 MethodTraitItem(ref method) => method.name,
313 TypeTraitItem(ref associated_type) => associated_type.name,
317 pub fn vis(&self) -> hir::Visibility {
319 ConstTraitItem(ref associated_const) => associated_const.vis,
320 MethodTraitItem(ref method) => method.vis,
321 TypeTraitItem(ref associated_type) => associated_type.vis,
325 pub fn container(&self) -> ImplOrTraitItemContainer {
327 ConstTraitItem(ref associated_const) => associated_const.container,
328 MethodTraitItem(ref method) => method.container,
329 TypeTraitItem(ref associated_type) => associated_type.container,
333 pub fn as_opt_method(&self) -> Option<Rc<Method<'tcx>>> {
335 MethodTraitItem(ref m) => Some((*m).clone()),
341 #[derive(Clone, Copy, Debug)]
342 pub enum ImplOrTraitItemId {
343 ConstTraitItemId(DefId),
344 MethodTraitItemId(DefId),
345 TypeTraitItemId(DefId),
348 impl ImplOrTraitItemId {
349 pub fn def_id(&self) -> DefId {
351 ConstTraitItemId(def_id) => def_id,
352 MethodTraitItemId(def_id) => def_id,
353 TypeTraitItemId(def_id) => def_id,
358 #[derive(Clone, Debug)]
359 pub struct Method<'tcx> {
361 pub generics: Generics<'tcx>,
362 pub predicates: GenericPredicates<'tcx>,
363 pub fty: BareFnTy<'tcx>,
364 pub explicit_self: ExplicitSelfCategory,
365 pub vis: hir::Visibility,
367 pub container: ImplOrTraitItemContainer,
369 // If this method is provided, we need to know where it came from
370 pub provided_source: Option<DefId>
373 impl<'tcx> Method<'tcx> {
374 pub fn new(name: Name,
375 generics: ty::Generics<'tcx>,
376 predicates: GenericPredicates<'tcx>,
378 explicit_self: ExplicitSelfCategory,
379 vis: hir::Visibility,
381 container: ImplOrTraitItemContainer,
382 provided_source: Option<DefId>)
387 predicates: predicates,
389 explicit_self: explicit_self,
392 container: container,
393 provided_source: provided_source
397 pub fn container_id(&self) -> DefId {
398 match self.container {
399 TraitContainer(id) => id,
400 ImplContainer(id) => id,
405 #[derive(Clone, Copy, Debug)]
406 pub struct AssociatedConst<'tcx> {
409 pub vis: hir::Visibility,
411 pub container: ImplOrTraitItemContainer,
412 pub default: Option<DefId>,
415 #[derive(Clone, Copy, Debug)]
416 pub struct AssociatedType<'tcx> {
418 pub ty: Option<Ty<'tcx>>,
419 pub vis: hir::Visibility,
421 pub container: ImplOrTraitItemContainer,
424 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
425 pub struct TypeAndMut<'tcx> {
427 pub mutbl: hir::Mutability,
431 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
432 pub struct ItemVariances {
433 pub types: VecPerParamSpace<Variance>,
434 pub regions: VecPerParamSpace<Variance>,
437 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
439 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
440 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
441 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
442 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
445 impl fmt::Debug for Variance {
446 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
447 f.write_str(match *self {
449 Contravariant => "-",
456 #[derive(Copy, Clone)]
457 pub enum AutoAdjustment<'tcx> {
458 AdjustReifyFnPointer, // go from a fn-item type to a fn-pointer type
459 AdjustUnsafeFnPointer, // go from a safe fn pointer to an unsafe fn pointer
460 AdjustDerefRef(AutoDerefRef<'tcx>),
463 /// Represents coercing a pointer to a different kind of pointer - where 'kind'
464 /// here means either or both of raw vs borrowed vs unique and fat vs thin.
466 /// We transform pointers by following the following steps in order:
467 /// 1. Deref the pointer `self.autoderefs` times (may be 0).
468 /// 2. If `autoref` is `Some(_)`, then take the address and produce either a
469 /// `&` or `*` pointer.
470 /// 3. If `unsize` is `Some(_)`, then apply the unsize transformation,
471 /// which will do things like convert thin pointers to fat
472 /// pointers, or convert structs containing thin pointers to
473 /// structs containing fat pointers, or convert between fat
474 /// pointers. We don't store the details of how the transform is
475 /// done (in fact, we don't know that, because it might depend on
476 /// the precise type parameters). We just store the target
477 /// type. Trans figures out what has to be done at monomorphization
478 /// time based on the precise source/target type at hand.
480 /// To make that more concrete, here are some common scenarios:
482 /// 1. The simplest cases are where the pointer is not adjusted fat vs thin.
483 /// Here the pointer will be dereferenced N times (where a dereference can
484 /// happen to to raw or borrowed pointers or any smart pointer which implements
485 /// Deref, including Box<_>). The number of dereferences is given by
486 /// `autoderefs`. It can then be auto-referenced zero or one times, indicated
487 /// by `autoref`, to either a raw or borrowed pointer. In these cases unsize is
490 /// 2. A thin-to-fat coercon involves unsizing the underlying data. We start
491 /// with a thin pointer, deref a number of times, unsize the underlying data,
492 /// then autoref. The 'unsize' phase may change a fixed length array to a
493 /// dynamically sized one, a concrete object to a trait object, or statically
494 /// sized struct to a dyncamically sized one. E.g., &[i32; 4] -> &[i32] is
499 /// autoderefs: 1, // &[i32; 4] -> [i32; 4]
500 /// autoref: Some(AutoPtr), // [i32] -> &[i32]
501 /// unsize: Some([i32]), // [i32; 4] -> [i32]
505 /// Note that for a struct, the 'deep' unsizing of the struct is not recorded.
506 /// E.g., `struct Foo<T> { x: T }` we can coerce &Foo<[i32; 4]> to &Foo<[i32]>
507 /// The autoderef and -ref are the same as in the above example, but the type
508 /// stored in `unsize` is `Foo<[i32]>`, we don't store any further detail about
509 /// the underlying conversions from `[i32; 4]` to `[i32]`.
511 /// 3. Coercing a `Box<T>` to `Box<Trait>` is an interesting special case. In
512 /// that case, we have the pointer we need coming in, so there are no
513 /// autoderefs, and no autoref. Instead we just do the `Unsize` transformation.
514 /// At some point, of course, `Box` should move out of the compiler, in which
515 /// case this is analogous to transformating a struct. E.g., Box<[i32; 4]> ->
516 /// Box<[i32]> is represented by:
522 /// unsize: Some(Box<[i32]>),
525 #[derive(Copy, Clone)]
526 pub struct AutoDerefRef<'tcx> {
527 /// Step 1. Apply a number of dereferences, producing an lvalue.
528 pub autoderefs: usize,
530 /// Step 2. Optionally produce a pointer/reference from the value.
531 pub autoref: Option<AutoRef<'tcx>>,
533 /// Step 3. Unsize a pointer/reference value, e.g. `&[T; n]` to
534 /// `&[T]`. The stored type is the target pointer type. Note that
535 /// the source could be a thin or fat pointer.
536 pub unsize: Option<Ty<'tcx>>,
539 #[derive(Copy, Clone, PartialEq, Debug)]
540 pub enum AutoRef<'tcx> {
541 /// Convert from T to &T.
542 AutoPtr(&'tcx Region, hir::Mutability),
544 /// Convert from T to *T.
545 /// Value to thin pointer.
546 AutoUnsafe(hir::Mutability),
549 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
550 pub enum CustomCoerceUnsized {
551 /// Records the index of the field being coerced.
555 #[derive(Clone, Copy, Debug)]
556 pub struct MethodCallee<'tcx> {
557 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
560 pub substs: &'tcx subst::Substs<'tcx>
563 /// With method calls, we store some extra information in
564 /// side tables (i.e method_map). We use
565 /// MethodCall as a key to index into these tables instead of
566 /// just directly using the expression's NodeId. The reason
567 /// for this being that we may apply adjustments (coercions)
568 /// with the resulting expression also needing to use the
569 /// side tables. The problem with this is that we don't
570 /// assign a separate NodeId to this new expression
571 /// and so it would clash with the base expression if both
572 /// needed to add to the side tables. Thus to disambiguate
573 /// we also keep track of whether there's an adjustment in
575 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
576 pub struct MethodCall {
582 pub fn expr(id: NodeId) -> MethodCall {
589 pub fn autoderef(expr_id: NodeId, autoderef: u32) -> MethodCall {
592 autoderef: 1 + autoderef
597 // maps from an expression id that corresponds to a method call to the details
598 // of the method to be invoked
599 pub type MethodMap<'tcx> = FnvHashMap<MethodCall, MethodCallee<'tcx>>;
601 // Contains information needed to resolve types and (in the future) look up
602 // the types of AST nodes.
603 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
604 pub struct CReaderCacheKey {
610 /// A restriction that certain types must be the same size. The use of
611 /// `transmute` gives rise to these restrictions. These generally
612 /// cannot be checked until trans; therefore, each call to `transmute`
613 /// will push one or more such restriction into the
614 /// `transmute_restrictions` vector during `intrinsicck`. They are
615 /// then checked during `trans` by the fn `check_intrinsics`.
616 #[derive(Copy, Clone)]
617 pub struct TransmuteRestriction<'tcx> {
618 /// The span whence the restriction comes.
621 /// The type being transmuted from.
622 pub original_from: Ty<'tcx>,
624 /// The type being transmuted to.
625 pub original_to: Ty<'tcx>,
627 /// The type being transmuted from, with all type parameters
628 /// substituted for an arbitrary representative. Not to be shown
630 pub substituted_from: Ty<'tcx>,
632 /// The type being transmuted to, with all type parameters
633 /// substituted for an arbitrary representative. Not to be shown
635 pub substituted_to: Ty<'tcx>,
637 /// NodeId of the transmute intrinsic.
642 pub struct CtxtArenas<'tcx> {
644 type_: TypedArena<TyS<'tcx>>,
645 substs: TypedArena<Substs<'tcx>>,
646 bare_fn: TypedArena<BareFnTy<'tcx>>,
647 region: TypedArena<Region>,
648 stability: TypedArena<attr::Stability>,
651 trait_defs: TypedArena<TraitDef<'tcx>>,
652 adt_defs: TypedArena<AdtDefData<'tcx, 'tcx>>,
655 impl<'tcx> CtxtArenas<'tcx> {
656 pub fn new() -> CtxtArenas<'tcx> {
658 type_: TypedArena::new(),
659 substs: TypedArena::new(),
660 bare_fn: TypedArena::new(),
661 region: TypedArena::new(),
662 stability: TypedArena::new(),
664 trait_defs: TypedArena::new(),
665 adt_defs: TypedArena::new()
670 pub struct CommonTypes<'tcx> {
688 pub struct Tables<'tcx> {
689 /// Stores the types for various nodes in the AST. Note that this table
690 /// is not guaranteed to be populated until after typeck. See
691 /// typeck::check::fn_ctxt for details.
692 pub node_types: NodeMap<Ty<'tcx>>,
694 /// Stores the type parameters which were substituted to obtain the type
695 /// of this node. This only applies to nodes that refer to entities
696 /// parameterized by type parameters, such as generic fns, types, or
698 pub item_substs: NodeMap<ItemSubsts<'tcx>>,
700 pub adjustments: NodeMap<ty::AutoAdjustment<'tcx>>,
702 pub method_map: MethodMap<'tcx>,
705 pub upvar_capture_map: UpvarCaptureMap,
707 /// Records the type of each closure. The def ID is the ID of the
708 /// expression defining the closure.
709 pub closure_tys: DefIdMap<ClosureTy<'tcx>>,
711 /// Records the type of each closure. The def ID is the ID of the
712 /// expression defining the closure.
713 pub closure_kinds: DefIdMap<ClosureKind>,
716 impl<'tcx> Tables<'tcx> {
717 pub fn empty() -> Tables<'tcx> {
719 node_types: FnvHashMap(),
720 item_substs: NodeMap(),
721 adjustments: NodeMap(),
722 method_map: FnvHashMap(),
723 upvar_capture_map: FnvHashMap(),
724 closure_tys: DefIdMap(),
725 closure_kinds: DefIdMap(),
730 /// The data structure to keep track of all the information that typechecker
731 /// generates so that so that it can be reused and doesn't have to be redone
733 pub struct ctxt<'tcx> {
734 /// The arenas that types etc are allocated from.
735 arenas: &'tcx CtxtArenas<'tcx>,
737 /// Specifically use a speedy hash algorithm for this hash map, it's used
739 // FIXME(eddyb) use a FnvHashSet<InternedTy<'tcx>> when equivalent keys can
740 // queried from a HashSet.
741 interner: RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>,
743 // FIXME as above, use a hashset if equivalent elements can be queried.
744 substs_interner: RefCell<FnvHashMap<&'tcx Substs<'tcx>, &'tcx Substs<'tcx>>>,
745 bare_fn_interner: RefCell<FnvHashMap<&'tcx BareFnTy<'tcx>, &'tcx BareFnTy<'tcx>>>,
746 region_interner: RefCell<FnvHashMap<&'tcx Region, &'tcx Region>>,
747 stability_interner: RefCell<FnvHashMap<&'tcx attr::Stability, &'tcx attr::Stability>>,
749 /// Common types, pre-interned for your convenience.
750 pub types: CommonTypes<'tcx>,
755 pub named_region_map: resolve_lifetime::NamedRegionMap,
757 pub region_maps: RegionMaps,
759 // For each fn declared in the local crate, type check stores the
760 // free-region relationships that were deduced from its where
761 // clauses and parameter types. These are then read-again by
762 // borrowck. (They are not used during trans, and hence are not
763 // serialized or needed for cross-crate fns.)
764 free_region_maps: RefCell<NodeMap<FreeRegionMap>>,
765 // FIXME: jroesch make this a refcell
767 pub tables: RefCell<Tables<'tcx>>,
769 /// Maps from a trait item to the trait item "descriptor"
770 pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem<'tcx>>>,
772 /// Maps from a trait def-id to a list of the def-ids of its trait items
773 pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
775 /// A cache for the trait_items() routine
776 pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem<'tcx>>>>>,
778 pub impl_trait_refs: RefCell<DefIdMap<Option<TraitRef<'tcx>>>>,
779 pub trait_defs: RefCell<DefIdMap<&'tcx TraitDef<'tcx>>>,
780 pub adt_defs: RefCell<DefIdMap<AdtDefMaster<'tcx>>>,
782 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
783 /// associated predicates.
784 pub predicates: RefCell<DefIdMap<GenericPredicates<'tcx>>>,
786 /// Maps from the def-id of a trait to the list of
787 /// super-predicates. This is a subset of the full list of
788 /// predicates. We store these in a separate map because we must
789 /// evaluate them even during type conversion, often before the
790 /// full predicates are available (note that supertraits have
791 /// additional acyclicity requirements).
792 pub super_predicates: RefCell<DefIdMap<GenericPredicates<'tcx>>>,
794 pub map: ast_map::Map<'tcx>,
795 pub freevars: RefCell<FreevarMap>,
796 pub tcache: RefCell<DefIdMap<TypeScheme<'tcx>>>,
797 pub rcache: RefCell<FnvHashMap<CReaderCacheKey, Ty<'tcx>>>,
798 pub tc_cache: RefCell<FnvHashMap<Ty<'tcx>, TypeContents>>,
799 pub ast_ty_to_ty_cache: RefCell<NodeMap<Ty<'tcx>>>,
800 pub ty_param_defs: RefCell<NodeMap<TypeParameterDef<'tcx>>>,
801 pub normalized_cache: RefCell<FnvHashMap<Ty<'tcx>, Ty<'tcx>>>,
802 pub lang_items: middle::lang_items::LanguageItems,
803 /// A mapping of fake provided method def_ids to the default implementation
804 pub provided_method_sources: RefCell<DefIdMap<DefId>>,
806 /// Maps from def-id of a type or region parameter to its
807 /// (inferred) variance.
808 pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
810 /// True if the variance has been computed yet; false otherwise.
811 pub variance_computed: Cell<bool>,
813 /// A method will be in this list if and only if it is a destructor.
814 pub destructors: RefCell<DefIdSet>,
816 /// Maps a DefId of a type to a list of its inherent impls.
817 /// Contains implementations of methods that are inherent to a type.
818 /// Methods in these implementations don't need to be exported.
819 pub inherent_impls: RefCell<DefIdMap<Rc<Vec<DefId>>>>,
821 /// Maps a DefId of an impl to a list of its items.
822 /// Note that this contains all of the impls that we know about,
823 /// including ones in other crates. It's not clear that this is the best
825 pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
827 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
828 /// present in this set can be warned about.
829 pub used_unsafe: RefCell<NodeSet>,
831 /// Set of nodes which mark locals as mutable which end up getting used at
832 /// some point. Local variable definitions not in this set can be warned
834 pub used_mut_nodes: RefCell<NodeSet>,
836 /// The set of external nominal types whose implementations have been read.
837 /// This is used for lazy resolution of methods.
838 pub populated_external_types: RefCell<DefIdSet>,
839 /// The set of external primitive types whose implementations have been read.
840 /// FIXME(arielb1): why is this separate from populated_external_types?
841 pub populated_external_primitive_impls: RefCell<DefIdSet>,
843 /// These caches are used by const_eval when decoding external constants.
844 pub extern_const_statics: RefCell<DefIdMap<NodeId>>,
845 pub extern_const_variants: RefCell<DefIdMap<NodeId>>,
846 pub extern_const_fns: RefCell<DefIdMap<NodeId>>,
848 pub node_lint_levels: RefCell<FnvHashMap<(NodeId, lint::LintId),
851 /// The types that must be asserted to be the same size for `transmute`
852 /// to be valid. We gather up these restrictions in the intrinsicck pass
853 /// and check them in trans.
854 pub transmute_restrictions: RefCell<Vec<TransmuteRestriction<'tcx>>>,
856 /// Maps any item's def-id to its stability index.
857 pub stability: RefCell<stability::Index<'tcx>>,
859 /// Caches the results of trait selection. This cache is used
860 /// for things that do not have to do with the parameters in scope.
861 pub selection_cache: traits::SelectionCache<'tcx>,
863 /// A set of predicates that have been fulfilled *somewhere*.
864 /// This is used to avoid duplicate work. Predicates are only
865 /// added to this set when they mention only "global" names
866 /// (i.e., no type or lifetime parameters).
867 pub fulfilled_predicates: RefCell<traits::FulfilledPredicates<'tcx>>,
869 /// Caches the representation hints for struct definitions.
870 pub repr_hint_cache: RefCell<DefIdMap<Rc<Vec<attr::ReprAttr>>>>,
872 /// Maps Expr NodeId's to their constant qualification.
873 pub const_qualif_map: RefCell<NodeMap<check_const::ConstQualif>>,
875 /// Caches CoerceUnsized kinds for impls on custom types.
876 pub custom_coerce_unsized_kinds: RefCell<DefIdMap<CustomCoerceUnsized>>,
878 /// Maps a cast expression to its kind. This is keyed on the
879 /// *from* expression of the cast, not the cast itself.
880 pub cast_kinds: RefCell<NodeMap<cast::CastKind>>,
882 /// Maps Fn items to a collection of fragment infos.
884 /// The main goal is to identify data (each of which may be moved
885 /// or assigned) whose subparts are not moved nor assigned
886 /// (i.e. their state is *unfragmented*) and corresponding ast
887 /// nodes where the path to that data is moved or assigned.
889 /// In the long term, unfragmented values will have their
890 /// destructor entirely driven by a single stack-local drop-flag,
891 /// and their parents, the collections of the unfragmented values
892 /// (or more simply, "fragmented values"), are mapped to the
893 /// corresponding collections of stack-local drop-flags.
895 /// (However, in the short term that is not the case; e.g. some
896 /// unfragmented paths still need to be zeroed, namely when they
897 /// reference parent data from an outer scope that was not
898 /// entirely moved, and therefore that needs to be zeroed so that
899 /// we do not get double-drop when we hit the end of the parent
902 /// Also: currently the table solely holds keys for node-ids of
903 /// unfragmented values (see `FragmentInfo` enum definition), but
904 /// longer-term we will need to also store mappings from
905 /// fragmented data to the set of unfragmented pieces that
907 pub fragment_infos: RefCell<DefIdMap<Vec<FragmentInfo>>>,
910 /// Describes the fragment-state associated with a NodeId.
912 /// Currently only unfragmented paths have entries in the table,
913 /// but longer-term this enum is expected to expand to also
914 /// include data for fragmented paths.
915 #[derive(Copy, Clone, Debug)]
916 pub enum FragmentInfo {
917 Moved { var: NodeId, move_expr: NodeId },
918 Assigned { var: NodeId, assign_expr: NodeId, assignee_id: NodeId },
921 impl<'tcx> ctxt<'tcx> {
922 pub fn node_types(&self) -> Ref<NodeMap<Ty<'tcx>>> {
923 fn projection<'a, 'tcx>(tables: &'a Tables<'tcx>) -> &'a NodeMap<Ty<'tcx>> {
927 Ref::map(self.tables.borrow(), projection)
930 pub fn node_type_insert(&self, id: NodeId, ty: Ty<'tcx>) {
931 self.tables.borrow_mut().node_types.insert(id, ty);
934 pub fn intern_trait_def(&self, def: TraitDef<'tcx>) -> &'tcx TraitDef<'tcx> {
935 let did = def.trait_ref.def_id;
936 let interned = self.arenas.trait_defs.alloc(def);
937 self.trait_defs.borrow_mut().insert(did, interned);
941 pub fn intern_adt_def(&self,
944 variants: Vec<VariantDefData<'tcx, 'tcx>>)
945 -> AdtDefMaster<'tcx> {
946 let def = AdtDefData::new(self, did, kind, variants);
947 let interned = self.arenas.adt_defs.alloc(def);
948 // this will need a transmute when reverse-variance is removed
949 self.adt_defs.borrow_mut().insert(did, interned);
953 pub fn intern_stability(&self, stab: attr::Stability) -> &'tcx attr::Stability {
954 if let Some(st) = self.stability_interner.borrow().get(&stab) {
958 let interned = self.arenas.stability.alloc(stab);
959 self.stability_interner.borrow_mut().insert(interned, interned);
963 pub fn store_free_region_map(&self, id: NodeId, map: FreeRegionMap) {
964 self.free_region_maps.borrow_mut()
968 pub fn free_region_map(&self, id: NodeId) -> FreeRegionMap {
969 self.free_region_maps.borrow()[&id].clone()
972 pub fn lift<T: ?Sized + Lift<'tcx>>(&self, value: &T) -> Option<T::Lifted> {
973 value.lift_to_tcx(self)
977 /// A trait implemented for all X<'a> types which can be safely and
978 /// efficiently converted to X<'tcx> as long as they are part of the
979 /// provided ty::ctxt<'tcx>.
980 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
981 /// by looking them up in their respective interners.
982 /// None is returned if the value or one of the components is not part
983 /// of the provided context.
984 /// For Ty, None can be returned if either the type interner doesn't
985 /// contain the TypeVariants key or if the address of the interned
986 /// pointer differs. The latter case is possible if a primitive type,
987 /// e.g. `()` or `u8`, was interned in a different context.
988 pub trait Lift<'tcx> {
990 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted>;
993 impl<'tcx, A: Lift<'tcx>, B: Lift<'tcx>> Lift<'tcx> for (A, B) {
994 type Lifted = (A::Lifted, B::Lifted);
995 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
996 tcx.lift(&self.0).and_then(|a| tcx.lift(&self.1).map(|b| (a, b)))
1000 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for [T] {
1001 type Lifted = Vec<T::Lifted>;
1002 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
1003 let mut result = Vec::with_capacity(self.len());
1005 if let Some(value) = tcx.lift(x) {
1015 impl<'tcx> Lift<'tcx> for Region {
1017 fn lift_to_tcx(&self, _: &ctxt<'tcx>) -> Option<Region> {
1022 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
1023 type Lifted = Ty<'tcx>;
1024 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Ty<'tcx>> {
1025 if let Some(&ty) = tcx.interner.borrow().get(&self.sty) {
1026 if *self as *const _ == ty as *const _ {
1034 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
1035 type Lifted = &'tcx Substs<'tcx>;
1036 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<&'tcx Substs<'tcx>> {
1037 if let Some(&substs) = tcx.substs_interner.borrow().get(*self) {
1038 if *self as *const _ == substs as *const _ {
1039 return Some(substs);
1046 impl<'a, 'tcx> Lift<'tcx> for TraitRef<'a> {
1047 type Lifted = TraitRef<'tcx>;
1048 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<TraitRef<'tcx>> {
1049 tcx.lift(&self.substs).map(|substs| TraitRef {
1050 def_id: self.def_id,
1056 impl<'a, 'tcx> Lift<'tcx> for TraitPredicate<'a> {
1057 type Lifted = TraitPredicate<'tcx>;
1058 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<TraitPredicate<'tcx>> {
1059 tcx.lift(&self.trait_ref).map(|trait_ref| TraitPredicate {
1060 trait_ref: trait_ref
1065 impl<'a, 'tcx> Lift<'tcx> for EquatePredicate<'a> {
1066 type Lifted = EquatePredicate<'tcx>;
1067 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<EquatePredicate<'tcx>> {
1068 tcx.lift(&(self.0, self.1)).map(|(a, b)| EquatePredicate(a, b))
1072 impl<'tcx, A: Copy+Lift<'tcx>, B: Copy+Lift<'tcx>> Lift<'tcx> for OutlivesPredicate<A, B> {
1073 type Lifted = OutlivesPredicate<A::Lifted, B::Lifted>;
1074 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
1075 tcx.lift(&(self.0, self.1)).map(|(a, b)| OutlivesPredicate(a, b))
1079 impl<'a, 'tcx> Lift<'tcx> for ProjectionPredicate<'a> {
1080 type Lifted = ProjectionPredicate<'tcx>;
1081 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<ProjectionPredicate<'tcx>> {
1082 tcx.lift(&(self.projection_ty.trait_ref, self.ty)).map(|(trait_ref, ty)| {
1083 ProjectionPredicate {
1084 projection_ty: ProjectionTy {
1085 trait_ref: trait_ref,
1086 item_name: self.projection_ty.item_name
1094 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Binder<T> {
1095 type Lifted = Binder<T::Lifted>;
1096 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
1097 tcx.lift(&self.0).map(|x| Binder(x))
1103 use session::Session;
1106 use syntax::codemap;
1108 /// Marker type used for the scoped TLS slot.
1109 /// The type context cannot be used directly because the scoped TLS
1110 /// in libstd doesn't allow types generic over lifetimes.
1111 struct ThreadLocalTyCx;
1113 scoped_thread_local!(static TLS_TCX: ThreadLocalTyCx);
1115 fn span_debug(span: codemap::Span, f: &mut fmt::Formatter) -> fmt::Result {
1117 write!(f, "{}", tcx.sess.codemap().span_to_string(span))
1121 pub fn enter<'tcx, F: FnOnce(&ty::ctxt<'tcx>) -> R, R>(tcx: ty::ctxt<'tcx>, f: F)
1123 let result = codemap::SPAN_DEBUG.with(|span_dbg| {
1124 let original_span_debug = span_dbg.get();
1125 span_dbg.set(span_debug);
1126 let tls_ptr = &tcx as *const _ as *const ThreadLocalTyCx;
1127 let result = TLS_TCX.set(unsafe { &*tls_ptr }, || f(&tcx));
1128 span_dbg.set(original_span_debug);
1134 pub fn with<F: FnOnce(&ty::ctxt) -> R, R>(f: F) -> R {
1135 TLS_TCX.with(|tcx| f(unsafe { &*(tcx as *const _ as *const ty::ctxt) }))
1138 pub fn with_opt<F: FnOnce(Option<&ty::ctxt>) -> R, R>(f: F) -> R {
1139 if TLS_TCX.is_set() {
1140 with(|v| f(Some(v)))
1147 // Flags that we track on types. These flags are propagated upwards
1148 // through the type during type construction, so that we can quickly
1149 // check whether the type has various kinds of types in it without
1150 // recursing over the type itself.
1152 flags TypeFlags: u32 {
1153 const HAS_PARAMS = 1 << 0,
1154 const HAS_SELF = 1 << 1,
1155 const HAS_TY_INFER = 1 << 2,
1156 const HAS_RE_INFER = 1 << 3,
1157 const HAS_RE_EARLY_BOUND = 1 << 4,
1158 const HAS_FREE_REGIONS = 1 << 5,
1159 const HAS_TY_ERR = 1 << 6,
1160 const HAS_PROJECTION = 1 << 7,
1161 const HAS_TY_CLOSURE = 1 << 8,
1163 // true if there are "names" of types and regions and so forth
1164 // that are local to a particular fn
1165 const HAS_LOCAL_NAMES = 1 << 9,
1167 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
1168 TypeFlags::HAS_SELF.bits |
1169 TypeFlags::HAS_RE_EARLY_BOUND.bits,
1171 // Flags representing the nominal content of a type,
1172 // computed by FlagsComputation. If you add a new nominal
1173 // flag, it should be added here too.
1174 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
1175 TypeFlags::HAS_SELF.bits |
1176 TypeFlags::HAS_TY_INFER.bits |
1177 TypeFlags::HAS_RE_INFER.bits |
1178 TypeFlags::HAS_RE_EARLY_BOUND.bits |
1179 TypeFlags::HAS_FREE_REGIONS.bits |
1180 TypeFlags::HAS_TY_ERR.bits |
1181 TypeFlags::HAS_PROJECTION.bits |
1182 TypeFlags::HAS_TY_CLOSURE.bits |
1183 TypeFlags::HAS_LOCAL_NAMES.bits,
1185 // Caches for type_is_sized, type_moves_by_default
1186 const SIZEDNESS_CACHED = 1 << 16,
1187 const IS_SIZED = 1 << 17,
1188 const MOVENESS_CACHED = 1 << 18,
1189 const MOVES_BY_DEFAULT = 1 << 19,
1193 macro_rules! sty_debug_print {
1194 ($ctxt: expr, $($variant: ident),*) => {{
1195 // curious inner module to allow variant names to be used as
1197 #[allow(non_snake_case)]
1200 #[derive(Copy, Clone)]
1203 region_infer: usize,
1208 pub fn go(tcx: &ty::ctxt) {
1209 let mut total = DebugStat {
1211 region_infer: 0, ty_infer: 0, both_infer: 0,
1213 $(let mut $variant = total;)*
1216 for (_, t) in tcx.interner.borrow().iter() {
1217 let variant = match t.sty {
1218 ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1219 ty::TyFloat(..) | ty::TyStr => continue,
1220 ty::TyError => /* unimportant */ continue,
1221 $(ty::$variant(..) => &mut $variant,)*
1223 let region = t.flags.get().intersects(ty::TypeFlags::HAS_RE_INFER);
1224 let ty = t.flags.get().intersects(ty::TypeFlags::HAS_TY_INFER);
1228 if region { total.region_infer += 1; variant.region_infer += 1 }
1229 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1230 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1232 println!("Ty interner total ty region both");
1233 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
1234 {ty:4.1}% {region:5.1}% {both:4.1}%",
1235 stringify!($variant),
1236 uses = $variant.total,
1237 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1238 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1239 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
1240 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
1242 println!(" total {uses:6} \
1243 {ty:4.1}% {region:5.1}% {both:4.1}%",
1245 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1246 region = total.region_infer as f64 * 100.0 / total.total as f64,
1247 both = total.both_infer as f64 * 100.0 / total.total as f64)
1255 impl<'tcx> ctxt<'tcx> {
1256 pub fn print_debug_stats(&self) {
1259 TyEnum, TyBox, TyArray, TySlice, TyRawPtr, TyRef, TyBareFn, TyTrait,
1260 TyStruct, TyClosure, TyTuple, TyParam, TyInfer, TyProjection);
1262 println!("Substs interner: #{}", self.substs_interner.borrow().len());
1263 println!("BareFnTy interner: #{}", self.bare_fn_interner.borrow().len());
1264 println!("Region interner: #{}", self.region_interner.borrow().len());
1265 println!("Stability interner: #{}", self.stability_interner.borrow().len());
1269 pub struct TyS<'tcx> {
1270 pub sty: TypeVariants<'tcx>,
1271 pub flags: Cell<TypeFlags>,
1273 // the maximal depth of any bound regions appearing in this type.
1277 impl fmt::Debug for TypeFlags {
1278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1279 write!(f, "{}", self.bits)
1283 impl<'tcx> PartialEq for TyS<'tcx> {
1285 fn eq(&self, other: &TyS<'tcx>) -> bool {
1286 // (self as *const _) == (other as *const _)
1287 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
1290 impl<'tcx> Eq for TyS<'tcx> {}
1292 impl<'tcx> Hash for TyS<'tcx> {
1293 fn hash<H: Hasher>(&self, s: &mut H) {
1294 (self as *const TyS).hash(s)
1298 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
1300 /// An IVar that contains a Ty. 'lt is a (reverse-variant) upper bound
1301 /// on the lifetime of the IVar. This is required because of variance
1302 /// problems: the IVar needs to be variant with respect to 'tcx (so
1303 /// it can be referred to from Ty) but can only be modified if its
1304 /// lifetime is exactly 'tcx.
1306 /// Safety invariants:
1307 /// (A) self.0, if fulfilled, is a valid Ty<'tcx>
1308 /// (B) no aliases to this value with a 'tcx longer than this
1309 /// value's 'lt exist
1311 /// NonZero is used rather than Unique because Unique isn't Copy.
1312 pub struct TyIVar<'tcx, 'lt: 'tcx>(ivar::Ivar<NonZero<*const TyS<'static>>>,
1313 PhantomData<fn(TyS<'lt>)->TyS<'tcx>>);
1315 impl<'tcx, 'lt> TyIVar<'tcx, 'lt> {
1317 pub fn new() -> Self {
1318 // Invariant (A) satisfied because the IVar is unfulfilled
1319 // Invariant (B) because 'lt : 'tcx
1320 TyIVar(ivar::Ivar::new(), PhantomData)
1324 pub fn get(&self) -> Option<Ty<'tcx>> {
1325 match self.0.get() {
1327 // valid because of invariant (A)
1328 Some(v) => Some(unsafe { &*(*v as *const TyS<'tcx>) })
1332 pub fn unwrap(&self) -> Ty<'tcx> {
1336 pub fn fulfill(&self, value: Ty<'lt>) {
1337 // Invariant (A) is fulfilled, because by (B), every alias
1338 // of this has a 'tcx longer than 'lt.
1339 let value: *const TyS<'lt> = value;
1340 // FIXME(27214): unneeded [as *const ()]
1341 let value = value as *const () as *const TyS<'static>;
1342 self.0.fulfill(unsafe { NonZero::new(value) })
1346 impl<'tcx, 'lt> fmt::Debug for TyIVar<'tcx, 'lt> {
1347 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1349 Some(val) => write!(f, "TyIVar({:?})", val),
1350 None => f.write_str("TyIVar(<unfulfilled>)")
1355 /// An entry in the type interner.
1356 pub struct InternedTy<'tcx> {
1360 // NB: An InternedTy compares and hashes as a sty.
1361 impl<'tcx> PartialEq for InternedTy<'tcx> {
1362 fn eq(&self, other: &InternedTy<'tcx>) -> bool {
1363 self.ty.sty == other.ty.sty
1367 impl<'tcx> Eq for InternedTy<'tcx> {}
1369 impl<'tcx> Hash for InternedTy<'tcx> {
1370 fn hash<H: Hasher>(&self, s: &mut H) {
1375 impl<'tcx> Borrow<TypeVariants<'tcx>> for InternedTy<'tcx> {
1376 fn borrow<'a>(&'a self) -> &'a TypeVariants<'tcx> {
1381 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1382 pub struct BareFnTy<'tcx> {
1383 pub unsafety: hir::Unsafety,
1385 pub sig: PolyFnSig<'tcx>,
1388 #[derive(Clone, PartialEq, Eq, Hash)]
1389 pub struct ClosureTy<'tcx> {
1390 pub unsafety: hir::Unsafety,
1392 pub sig: PolyFnSig<'tcx>,
1395 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1396 pub enum FnOutput<'tcx> {
1397 FnConverging(Ty<'tcx>),
1401 impl<'tcx> FnOutput<'tcx> {
1402 pub fn diverges(&self) -> bool {
1403 *self == FnDiverging
1406 pub fn unwrap(self) -> Ty<'tcx> {
1408 ty::FnConverging(t) => t,
1409 ty::FnDiverging => unreachable!()
1413 pub fn unwrap_or(self, def: Ty<'tcx>) -> Ty<'tcx> {
1415 ty::FnConverging(t) => t,
1416 ty::FnDiverging => def
1421 pub type PolyFnOutput<'tcx> = Binder<FnOutput<'tcx>>;
1423 impl<'tcx> PolyFnOutput<'tcx> {
1424 pub fn diverges(&self) -> bool {
1429 /// Signature of a function type, which I have arbitrarily
1430 /// decided to use to refer to the input/output types.
1432 /// - `inputs` is the list of arguments and their modes.
1433 /// - `output` is the return type.
1434 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
1435 #[derive(Clone, PartialEq, Eq, Hash)]
1436 pub struct FnSig<'tcx> {
1437 pub inputs: Vec<Ty<'tcx>>,
1438 pub output: FnOutput<'tcx>,
1442 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1444 impl<'tcx> PolyFnSig<'tcx> {
1445 pub fn inputs(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
1446 self.map_bound_ref(|fn_sig| fn_sig.inputs.clone())
1448 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
1449 self.map_bound_ref(|fn_sig| fn_sig.inputs[index])
1451 pub fn output(&self) -> ty::Binder<FnOutput<'tcx>> {
1452 self.map_bound_ref(|fn_sig| fn_sig.output.clone())
1454 pub fn variadic(&self) -> bool {
1455 self.skip_binder().variadic
1459 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1460 pub struct ParamTy {
1461 pub space: subst::ParamSpace,
1466 /// A [De Bruijn index][dbi] is a standard means of representing
1467 /// regions (and perhaps later types) in a higher-ranked setting. In
1468 /// particular, imagine a type like this:
1470 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
1473 /// | +------------+ 1 | |
1475 /// +--------------------------------+ 2 |
1477 /// +------------------------------------------+ 1
1479 /// In this type, there are two binders (the outer fn and the inner
1480 /// fn). We need to be able to determine, for any given region, which
1481 /// fn type it is bound by, the inner or the outer one. There are
1482 /// various ways you can do this, but a De Bruijn index is one of the
1483 /// more convenient and has some nice properties. The basic idea is to
1484 /// count the number of binders, inside out. Some examples should help
1485 /// clarify what I mean.
1487 /// Let's start with the reference type `&'b isize` that is the first
1488 /// argument to the inner function. This region `'b` is assigned a De
1489 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
1490 /// fn). The region `'a` that appears in the second argument type (`&'a
1491 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
1492 /// second-innermost binder". (These indices are written on the arrays
1493 /// in the diagram).
1495 /// What is interesting is that De Bruijn index attached to a particular
1496 /// variable will vary depending on where it appears. For example,
1497 /// the final type `&'a char` also refers to the region `'a` declared on
1498 /// the outermost fn. But this time, this reference is not nested within
1499 /// any other binders (i.e., it is not an argument to the inner fn, but
1500 /// rather the outer one). Therefore, in this case, it is assigned a
1501 /// De Bruijn index of 1, because the innermost binder in that location
1502 /// is the outer fn.
1504 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1505 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
1506 pub struct DebruijnIndex {
1507 // We maintain the invariant that this is never 0. So 1 indicates
1508 // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
1512 /// Representation of regions.
1514 /// Unlike types, most region variants are "fictitious", not concrete,
1515 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1516 /// ones representing concrete regions.
1518 /// ## Bound Regions
1520 /// These are regions that are stored behind a binder and must be substituted
1521 /// with some concrete region before being used. There are 2 kind of
1522 /// bound regions: early-bound, which are bound in a TypeScheme/TraitDef,
1523 /// and are substituted by a Substs, and late-bound, which are part of
1524 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
1525 /// the likes of `liberate_late_bound_regions`. The distinction exists
1526 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1528 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
1529 /// outside their binder, e.g. in types passed to type inference, and
1530 /// should first be substituted (by skolemized regions, free regions,
1531 /// or region variables).
1533 /// ## Skolemized and Free Regions
1535 /// One often wants to work with bound regions without knowing their precise
1536 /// identity. For example, when checking a function, the lifetime of a borrow
1537 /// can end up being assigned to some region parameter. In these cases,
1538 /// it must be ensured that bounds on the region can't be accidentally
1539 /// assumed without being checked.
1541 /// The process of doing that is called "skolemization". The bound regions
1542 /// are replaced by skolemized markers, which don't satisfy any relation
1543 /// not explicity provided.
1545 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
1546 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
1547 /// to be used. These also support explicit bounds: both the internally-stored
1548 /// *scope*, which the region is assumed to outlive, as well as other
1549 /// relations stored in the `FreeRegionMap`. Note that these relations
1550 /// aren't checked when you `make_subregion` (or `mk_eqty`), only by
1551 /// `resolve_regions_and_report_errors`.
1553 /// When working with higher-ranked types, some region relations aren't
1554 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1555 /// `ReSkolemized` is designed for this purpose. In these contexts,
1556 /// there's also the risk that some inference variable laying around will
1557 /// get unified with your skolemized region: if you want to check whether
1558 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1559 /// with a skolemized region `'%a`, the variable `'_` would just be
1560 /// instantiated to the skolemized region `'%a`, which is wrong because
1561 /// the inference variable is supposed to satisfy the relation
1562 /// *for every value of the skolemized region*. To ensure that doesn't
1563 /// happen, you can use `leak_check`. This is more clearly explained
1564 /// by infer/higher_ranked/README.md.
1566 /// [1] http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1567 /// [2] http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1568 #[derive(Clone, PartialEq, Eq, Hash, Copy)]
1570 // Region bound in a type or fn declaration which will be
1571 // substituted 'early' -- that is, at the same time when type
1572 // parameters are substituted.
1573 ReEarlyBound(EarlyBoundRegion),
1575 // Region bound in a function scope, which will be substituted when the
1576 // function is called.
1577 ReLateBound(DebruijnIndex, BoundRegion),
1579 /// When checking a function body, the types of all arguments and so forth
1580 /// that refer to bound region parameters are modified to refer to free
1581 /// region parameters.
1584 /// A concrete region naming some statically determined extent
1585 /// (e.g. an expression or sequence of statements) within the
1586 /// current function.
1587 ReScope(region::CodeExtent),
1589 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1592 /// A region variable. Should not exist after typeck.
1595 /// A skolemized region - basically the higher-ranked version of ReFree.
1596 /// Should not exist after typeck.
1597 ReSkolemized(SkolemizedRegionVid, BoundRegion),
1599 /// Empty lifetime is for data that is never accessed.
1600 /// Bottom in the region lattice. We treat ReEmpty somewhat
1601 /// specially; at least right now, we do not generate instances of
1602 /// it during the GLB computations, but rather
1603 /// generate an error instead. This is to improve error messages.
1604 /// The only way to get an instance of ReEmpty is to have a region
1605 /// variable with no constraints.
1609 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
1610 pub struct EarlyBoundRegion {
1611 pub param_id: NodeId,
1612 pub space: subst::ParamSpace,
1617 /// Upvars do not get their own node-id. Instead, we use the pair of
1618 /// the original var id (that is, the root variable that is referenced
1619 /// by the upvar) and the id of the closure expression.
1620 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1621 pub struct UpvarId {
1623 pub closure_expr_id: NodeId,
1626 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
1627 pub enum BorrowKind {
1628 /// Data must be immutable and is aliasable.
1631 /// Data must be immutable but not aliasable. This kind of borrow
1632 /// cannot currently be expressed by the user and is used only in
1633 /// implicit closure bindings. It is needed when you the closure
1634 /// is borrowing or mutating a mutable referent, e.g.:
1636 /// let x: &mut isize = ...;
1637 /// let y = || *x += 5;
1639 /// If we were to try to translate this closure into a more explicit
1640 /// form, we'd encounter an error with the code as written:
1642 /// struct Env { x: & &mut isize }
1643 /// let x: &mut isize = ...;
1644 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
1645 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1647 /// This is then illegal because you cannot mutate a `&mut` found
1648 /// in an aliasable location. To solve, you'd have to translate with
1649 /// an `&mut` borrow:
1651 /// struct Env { x: & &mut isize }
1652 /// let x: &mut isize = ...;
1653 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
1654 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1656 /// Now the assignment to `**env.x` is legal, but creating a
1657 /// mutable pointer to `x` is not because `x` is not mutable. We
1658 /// could fix this by declaring `x` as `let mut x`. This is ok in
1659 /// user code, if awkward, but extra weird for closures, since the
1660 /// borrow is hidden.
1662 /// So we introduce a "unique imm" borrow -- the referent is
1663 /// immutable, but not aliasable. This solves the problem. For
1664 /// simplicity, we don't give users the way to express this
1665 /// borrow, it's just used when translating closures.
1668 /// Data is mutable and not aliasable.
1672 /// Information describing the capture of an upvar. This is computed
1673 /// during `typeck`, specifically by `regionck`.
1674 #[derive(PartialEq, Clone, Debug, Copy)]
1675 pub enum UpvarCapture {
1676 /// Upvar is captured by value. This is always true when the
1677 /// closure is labeled `move`, but can also be true in other cases
1678 /// depending on inference.
1681 /// Upvar is captured by reference.
1685 #[derive(PartialEq, Clone, Copy)]
1686 pub struct UpvarBorrow {
1687 /// The kind of borrow: by-ref upvars have access to shared
1688 /// immutable borrows, which are not part of the normal language
1690 pub kind: BorrowKind,
1692 /// Region of the resulting reference.
1693 pub region: ty::Region,
1696 pub type UpvarCaptureMap = FnvHashMap<UpvarId, UpvarCapture>;
1698 #[derive(Copy, Clone)]
1699 pub struct ClosureUpvar<'tcx> {
1706 pub fn is_bound(&self) -> bool {
1708 ty::ReEarlyBound(..) => true,
1709 ty::ReLateBound(..) => true,
1714 pub fn needs_infer(&self) -> bool {
1716 ty::ReVar(..) | ty::ReSkolemized(..) => true,
1721 pub fn escapes_depth(&self, depth: u32) -> bool {
1723 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1728 /// Returns the depth of `self` from the (1-based) binding level `depth`
1729 pub fn from_depth(&self, depth: u32) -> Region {
1731 ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
1732 depth: debruijn.depth - (depth - 1)
1739 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1740 RustcEncodable, RustcDecodable, Copy)]
1741 /// A "free" region `fr` can be interpreted as "some region
1742 /// at least as big as the scope `fr.scope`".
1743 pub struct FreeRegion {
1744 pub scope: region::CodeExtent,
1745 pub bound_region: BoundRegion
1748 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1749 RustcEncodable, RustcDecodable, Copy)]
1750 pub enum BoundRegion {
1751 /// An anonymous region parameter for a given fn (&T)
1754 /// Named region parameters for functions (a in &'a T)
1756 /// The def-id is needed to distinguish free regions in
1757 /// the event of shadowing.
1758 BrNamed(DefId, Name),
1760 /// Fresh bound identifiers created during GLB computations.
1763 // Anonymous region for the implicit env pointer parameter
1768 // NB: If you change this, you'll probably want to change the corresponding
1769 // AST structure in libsyntax/ast.rs as well.
1770 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1771 pub enum TypeVariants<'tcx> {
1772 /// The primitive boolean type. Written as `bool`.
1775 /// The primitive character type; holds a Unicode scalar value
1776 /// (a non-surrogate code point). Written as `char`.
1779 /// A primitive signed integer type. For example, `i32`.
1782 /// A primitive unsigned integer type. For example, `u32`.
1783 TyUint(hir::UintTy),
1785 /// A primitive floating-point type. For example, `f64`.
1786 TyFloat(hir::FloatTy),
1788 /// An enumerated type, defined with `enum`.
1790 /// Substs here, possibly against intuition, *may* contain `TyParam`s.
1791 /// That is, even after substitution it is possible that there are type
1792 /// variables. This happens when the `TyEnum` corresponds to an enum
1793 /// definition and not a concrete use of it. To get the correct `TyEnum`
1794 /// from the tcx, use the `NodeId` from the `hir::Ty` and look it up in
1795 /// the `ast_ty_to_ty_cache`. This is probably true for `TyStruct` as
1797 TyEnum(AdtDef<'tcx>, &'tcx Substs<'tcx>),
1799 /// A structure type, defined with `struct`.
1801 /// See warning about substitutions for enumerated types.
1802 TyStruct(AdtDef<'tcx>, &'tcx Substs<'tcx>),
1804 /// `Box<T>`; this is nominally a struct in the documentation, but is
1805 /// special-cased internally. For example, it is possible to implicitly
1806 /// move the contents of a box out of that box, and methods of any type
1807 /// can have type `Box<Self>`.
1810 /// The pointee of a string slice. Written as `str`.
1813 /// An array with the given length. Written as `[T; n]`.
1814 TyArray(Ty<'tcx>, usize),
1816 /// The pointee of an array slice. Written as `[T]`.
1819 /// A raw pointer. Written as `*mut T` or `*const T`
1820 TyRawPtr(TypeAndMut<'tcx>),
1822 /// A reference; a pointer with an associated lifetime. Written as
1823 /// `&a mut T` or `&'a T`.
1824 TyRef(&'tcx Region, TypeAndMut<'tcx>),
1826 /// If the def-id is Some(_), then this is the type of a specific
1827 /// fn item. Otherwise, if None(_), it a fn pointer type.
1829 /// FIXME: Conflating function pointers and the type of a
1830 /// function is probably a terrible idea; a function pointer is a
1831 /// value with a specific type, but a function can be polymorphic
1832 /// or dynamically dispatched.
1833 TyBareFn(Option<DefId>, &'tcx BareFnTy<'tcx>),
1835 /// A trait, defined with `trait`.
1836 TyTrait(Box<TraitTy<'tcx>>),
1838 /// The anonymous type of a closure. Used to represent the type of
1840 TyClosure(DefId, Box<ClosureSubsts<'tcx>>),
1842 /// A tuple type. For example, `(i32, bool)`.
1843 TyTuple(Vec<Ty<'tcx>>),
1845 /// The projection of an associated type. For example,
1846 /// `<T as Trait<..>>::N`.
1847 TyProjection(ProjectionTy<'tcx>),
1849 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
1852 /// A type variable used during type-checking.
1855 /// A placeholder for a type which could not be computed; this is
1856 /// propagated to avoid useless error messages.
1860 /// A closure can be modeled as a struct that looks like:
1862 /// struct Closure<'l0...'li, T0...Tj, U0...Uk> {
1868 /// where 'l0...'li and T0...Tj are the lifetime and type parameters
1869 /// in scope on the function that defined the closure, and U0...Uk are
1870 /// type parameters representing the types of its upvars (borrowed, if
1873 /// So, for example, given this function:
1875 /// fn foo<'a, T>(data: &'a mut T) {
1876 /// do(|| data.count += 1)
1879 /// the type of the closure would be something like:
1881 /// struct Closure<'a, T, U0> {
1885 /// Note that the type of the upvar is not specified in the struct.
1886 /// You may wonder how the impl would then be able to use the upvar,
1887 /// if it doesn't know it's type? The answer is that the impl is
1888 /// (conceptually) not fully generic over Closure but rather tied to
1889 /// instances with the expected upvar types:
1891 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
1895 /// You can see that the *impl* fully specified the type of the upvar
1896 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
1897 /// (Here, I am assuming that `data` is mut-borrowed.)
1899 /// Now, the last question you may ask is: Why include the upvar types
1900 /// as extra type parameters? The reason for this design is that the
1901 /// upvar types can reference lifetimes that are internal to the
1902 /// creating function. In my example above, for example, the lifetime
1903 /// `'b` represents the extent of the closure itself; this is some
1904 /// subset of `foo`, probably just the extent of the call to the to
1905 /// `do()`. If we just had the lifetime/type parameters from the
1906 /// enclosing function, we couldn't name this lifetime `'b`. Note that
1907 /// there can also be lifetimes in the types of the upvars themselves,
1908 /// if one of them happens to be a reference to something that the
1909 /// creating fn owns.
1911 /// OK, you say, so why not create a more minimal set of parameters
1912 /// that just includes the extra lifetime parameters? The answer is
1913 /// primarily that it would be hard --- we don't know at the time when
1914 /// we create the closure type what the full types of the upvars are,
1915 /// nor do we know which are borrowed and which are not. In this
1916 /// design, we can just supply a fresh type parameter and figure that
1919 /// All right, you say, but why include the type parameters from the
1920 /// original function then? The answer is that trans may need them
1921 /// when monomorphizing, and they may not appear in the upvars. A
1922 /// closure could capture no variables but still make use of some
1923 /// in-scope type parameter with a bound (e.g., if our example above
1924 /// had an extra `U: Default`, and the closure called `U::default()`).
1926 /// There is another reason. This design (implicitly) prohibits
1927 /// closures from capturing themselves (except via a trait
1928 /// object). This simplifies closure inference considerably, since it
1929 /// means that when we infer the kind of a closure or its upvars, we
1930 /// don't have to handle cycles where the decisions we make for
1931 /// closure C wind up influencing the decisions we ought to make for
1932 /// closure C (which would then require fixed point iteration to
1933 /// handle). Plus it fixes an ICE. :P
1934 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1935 pub struct ClosureSubsts<'tcx> {
1936 /// Lifetime and type parameters from the enclosing function.
1937 /// These are separated out because trans wants to pass them around
1938 /// when monomorphizing.
1939 pub func_substs: &'tcx Substs<'tcx>,
1941 /// The types of the upvars. The list parallels the freevars and
1942 /// `upvar_borrows` lists. These are kept distinct so that we can
1943 /// easily index into them.
1944 pub upvar_tys: Vec<Ty<'tcx>>
1947 #[derive(Clone, PartialEq, Eq, Hash)]
1948 pub struct TraitTy<'tcx> {
1949 pub principal: ty::PolyTraitRef<'tcx>,
1950 pub bounds: ExistentialBounds<'tcx>,
1953 impl<'tcx> TraitTy<'tcx> {
1954 pub fn principal_def_id(&self) -> DefId {
1955 self.principal.0.def_id
1958 /// Object types don't have a self-type specified. Therefore, when
1959 /// we convert the principal trait-ref into a normal trait-ref,
1960 /// you must give *some* self-type. A common choice is `mk_err()`
1961 /// or some skolemized type.
1962 pub fn principal_trait_ref_with_self_ty(&self,
1965 -> ty::PolyTraitRef<'tcx>
1967 // otherwise the escaping regions would be captured by the binder
1968 assert!(!self_ty.has_escaping_regions());
1970 ty::Binder(TraitRef {
1971 def_id: self.principal.0.def_id,
1972 substs: tcx.mk_substs(self.principal.0.substs.with_self_ty(self_ty)),
1976 pub fn projection_bounds_with_self_ty(&self,
1979 -> Vec<ty::PolyProjectionPredicate<'tcx>>
1981 // otherwise the escaping regions would be captured by the binders
1982 assert!(!self_ty.has_escaping_regions());
1984 self.bounds.projection_bounds.iter()
1985 .map(|in_poly_projection_predicate| {
1986 let in_projection_ty = &in_poly_projection_predicate.0.projection_ty;
1987 let substs = tcx.mk_substs(in_projection_ty.trait_ref.substs.with_self_ty(self_ty));
1988 let trait_ref = ty::TraitRef::new(in_projection_ty.trait_ref.def_id,
1990 let projection_ty = ty::ProjectionTy {
1991 trait_ref: trait_ref,
1992 item_name: in_projection_ty.item_name
1994 ty::Binder(ty::ProjectionPredicate {
1995 projection_ty: projection_ty,
1996 ty: in_poly_projection_predicate.0.ty
2003 /// A complete reference to a trait. These take numerous guises in syntax,
2004 /// but perhaps the most recognizable form is in a where clause:
2008 /// This would be represented by a trait-reference where the def-id is the
2009 /// def-id for the trait `Foo` and the substs defines `T` as parameter 0 in the
2010 /// `SelfSpace` and `U` as parameter 0 in the `TypeSpace`.
2012 /// Trait references also appear in object types like `Foo<U>`, but in
2013 /// that case the `Self` parameter is absent from the substitutions.
2015 /// Note that a `TraitRef` introduces a level of region binding, to
2016 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
2017 /// U>` or higher-ranked object types.
2018 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2019 pub struct TraitRef<'tcx> {
2021 pub substs: &'tcx Substs<'tcx>,
2024 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
2026 impl<'tcx> PolyTraitRef<'tcx> {
2027 pub fn self_ty(&self) -> Ty<'tcx> {
2031 pub fn def_id(&self) -> DefId {
2035 pub fn substs(&self) -> &'tcx Substs<'tcx> {
2036 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
2040 pub fn input_types(&self) -> &[Ty<'tcx>] {
2041 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
2042 self.0.input_types()
2045 pub fn to_poly_trait_predicate(&self) -> PolyTraitPredicate<'tcx> {
2046 // Note that we preserve binding levels
2047 Binder(TraitPredicate { trait_ref: self.0.clone() })
2051 /// Binder is a binder for higher-ranked lifetimes. It is part of the
2052 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
2053 /// (which would be represented by the type `PolyTraitRef ==
2054 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
2055 /// erase, or otherwise "discharge" these bound regions, we change the
2056 /// type from `Binder<T>` to just `T` (see
2057 /// e.g. `liberate_late_bound_regions`).
2058 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
2059 pub struct Binder<T>(pub T);
2062 /// Skips the binder and returns the "bound" value. This is a
2063 /// risky thing to do because it's easy to get confused about
2064 /// debruijn indices and the like. It is usually better to
2065 /// discharge the binder using `no_late_bound_regions` or
2066 /// `replace_late_bound_regions` or something like
2067 /// that. `skip_binder` is only valid when you are either
2068 /// extracting data that has nothing to do with bound regions, you
2069 /// are doing some sort of test that does not involve bound
2070 /// regions, or you are being very careful about your depth
2073 /// Some examples where `skip_binder` is reasonable:
2074 /// - extracting the def-id from a PolyTraitRef;
2075 /// - comparing the self type of a PolyTraitRef to see if it is equal to
2076 /// a type parameter `X`, since the type `X` does not reference any regions
2077 pub fn skip_binder(&self) -> &T {
2081 pub fn as_ref(&self) -> Binder<&T> {
2085 pub fn map_bound_ref<F,U>(&self, f: F) -> Binder<U>
2086 where F: FnOnce(&T) -> U
2088 self.as_ref().map_bound(f)
2091 pub fn map_bound<F,U>(self, f: F) -> Binder<U>
2092 where F: FnOnce(T) -> U
2094 ty::Binder(f(self.0))
2098 #[derive(Clone, Copy, PartialEq)]
2099 pub enum IntVarValue {
2100 IntType(hir::IntTy),
2101 UintType(hir::UintTy),
2104 #[derive(Clone, Copy, Debug)]
2105 pub struct ExpectedFound<T> {
2110 // Data structures used in type unification
2111 #[derive(Clone, Debug)]
2112 pub enum TypeError<'tcx> {
2114 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
2115 AbiMismatch(ExpectedFound<abi::Abi>),
2121 TupleSize(ExpectedFound<usize>),
2122 FixedArraySize(ExpectedFound<usize>),
2123 TyParamSize(ExpectedFound<usize>),
2125 RegionsDoesNotOutlive(Region, Region),
2126 RegionsNotSame(Region, Region),
2127 RegionsNoOverlap(Region, Region),
2128 RegionsInsufficientlyPolymorphic(BoundRegion, Region),
2129 RegionsOverlyPolymorphic(BoundRegion, Region),
2130 Sorts(ExpectedFound<Ty<'tcx>>),
2132 IntMismatch(ExpectedFound<IntVarValue>),
2133 FloatMismatch(ExpectedFound<hir::FloatTy>),
2134 Traits(ExpectedFound<DefId>),
2135 BuiltinBoundsMismatch(ExpectedFound<BuiltinBounds>),
2136 VariadicMismatch(ExpectedFound<bool>),
2138 ConvergenceMismatch(ExpectedFound<bool>),
2139 ProjectionNameMismatched(ExpectedFound<Name>),
2140 ProjectionBoundsLength(ExpectedFound<usize>),
2141 TyParamDefaultMismatch(ExpectedFound<type_variable::Default<'tcx>>)
2144 /// Bounds suitable for an existentially quantified type parameter
2145 /// such as those that appear in object types or closure types.
2146 #[derive(PartialEq, Eq, Hash, Clone)]
2147 pub struct ExistentialBounds<'tcx> {
2148 pub region_bound: ty::Region,
2149 pub builtin_bounds: BuiltinBounds,
2150 pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
2153 impl<'tcx> ExistentialBounds<'tcx> {
2154 pub fn new(region_bound: ty::Region,
2155 builtin_bounds: BuiltinBounds,
2156 projection_bounds: Vec<PolyProjectionPredicate<'tcx>>)
2158 let mut projection_bounds = projection_bounds;
2159 ty::sort_bounds_list(&mut projection_bounds);
2161 region_bound: region_bound,
2162 builtin_bounds: builtin_bounds,
2163 projection_bounds: projection_bounds
2168 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
2169 pub struct BuiltinBounds(EnumSet<BuiltinBound>);
2171 impl BuiltinBounds {
2172 pub fn empty() -> BuiltinBounds {
2173 BuiltinBounds(EnumSet::new())
2176 pub fn iter(&self) -> enum_set::Iter<BuiltinBound> {
2180 pub fn to_predicates<'tcx>(&self,
2181 tcx: &ty::ctxt<'tcx>,
2182 self_ty: Ty<'tcx>) -> Vec<Predicate<'tcx>> {
2183 self.iter().filter_map(|builtin_bound|
2184 match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, self_ty) {
2185 Ok(trait_ref) => Some(trait_ref.to_predicate()),
2186 Err(ErrorReported) => { None }
2192 impl ops::Deref for BuiltinBounds {
2193 type Target = EnumSet<BuiltinBound>;
2194 fn deref(&self) -> &Self::Target { &self.0 }
2197 impl ops::DerefMut for BuiltinBounds {
2198 fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
2201 impl<'a> IntoIterator for &'a BuiltinBounds {
2202 type Item = BuiltinBound;
2203 type IntoIter = enum_set::Iter<BuiltinBound>;
2204 fn into_iter(self) -> Self::IntoIter {
2205 (**self).into_iter()
2209 #[derive(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
2212 pub enum BuiltinBound {
2219 impl CLike for BuiltinBound {
2220 fn to_usize(&self) -> usize {
2223 fn from_usize(v: usize) -> BuiltinBound {
2224 unsafe { mem::transmute(v) }
2228 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2233 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2238 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2239 pub struct FloatVid {
2243 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
2244 pub struct RegionVid {
2248 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2249 pub struct SkolemizedRegionVid {
2253 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2259 /// A `FreshTy` is one that is generated as a replacement for an
2260 /// unbound type variable. This is convenient for caching etc. See
2261 /// `middle::infer::freshen` for more details.
2267 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
2268 pub enum UnconstrainedNumeric {
2275 impl fmt::Debug for TyVid {
2276 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2277 write!(f, "_#{}t", self.index)
2281 impl fmt::Debug for IntVid {
2282 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2283 write!(f, "_#{}i", self.index)
2287 impl fmt::Debug for FloatVid {
2288 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2289 write!(f, "_#{}f", self.index)
2293 impl fmt::Debug for RegionVid {
2294 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2295 write!(f, "'_#{}r", self.index)
2299 impl<'tcx> fmt::Debug for FnSig<'tcx> {
2300 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2301 write!(f, "({:?}; variadic: {})->{:?}", self.inputs, self.variadic, self.output)
2305 impl fmt::Debug for InferTy {
2306 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2308 TyVar(ref v) => v.fmt(f),
2309 IntVar(ref v) => v.fmt(f),
2310 FloatVar(ref v) => v.fmt(f),
2311 FreshTy(v) => write!(f, "FreshTy({:?})", v),
2312 FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
2313 FreshFloatTy(v) => write!(f, "FreshFloatTy({:?})", v)
2318 impl fmt::Debug for IntVarValue {
2319 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2321 IntType(ref v) => v.fmt(f),
2322 UintType(ref v) => v.fmt(f),
2327 /// Default region to use for the bound of objects that are
2328 /// supplied as the value for this type parameter. This is derived
2329 /// from `T:'a` annotations appearing in the type definition. If
2330 /// this is `None`, then the default is inherited from the
2331 /// surrounding context. See RFC #599 for details.
2332 #[derive(Copy, Clone)]
2333 pub enum ObjectLifetimeDefault {
2334 /// Require an explicit annotation. Occurs when multiple
2335 /// `T:'a` constraints are found.
2338 /// Use the base default, typically 'static, but in a fn body it is a fresh variable
2341 /// Use the given region as the default.
2346 pub struct TypeParameterDef<'tcx> {
2349 pub space: subst::ParamSpace,
2351 pub default_def_id: DefId, // for use in error reporing about defaults
2352 pub default: Option<Ty<'tcx>>,
2353 pub object_lifetime_default: ObjectLifetimeDefault,
2357 pub struct RegionParameterDef {
2360 pub space: subst::ParamSpace,
2362 pub bounds: Vec<ty::Region>,
2365 impl RegionParameterDef {
2366 pub fn to_early_bound_region(&self) -> ty::Region {
2367 ty::ReEarlyBound(ty::EarlyBoundRegion {
2368 param_id: self.def_id.node,
2374 pub fn to_bound_region(&self) -> ty::BoundRegion {
2375 ty::BoundRegion::BrNamed(self.def_id, self.name)
2379 /// Information about the formal type/lifetime parameters associated
2380 /// with an item or method. Analogous to hir::Generics.
2381 #[derive(Clone, Debug)]
2382 pub struct Generics<'tcx> {
2383 pub types: VecPerParamSpace<TypeParameterDef<'tcx>>,
2384 pub regions: VecPerParamSpace<RegionParameterDef>,
2387 impl<'tcx> Generics<'tcx> {
2388 pub fn empty() -> Generics<'tcx> {
2390 types: VecPerParamSpace::empty(),
2391 regions: VecPerParamSpace::empty(),
2395 pub fn is_empty(&self) -> bool {
2396 self.types.is_empty() && self.regions.is_empty()
2399 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
2400 !self.types.is_empty_in(space)
2403 pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
2404 !self.regions.is_empty_in(space)
2408 /// Bounds on generics.
2410 pub struct GenericPredicates<'tcx> {
2411 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
2414 impl<'tcx> GenericPredicates<'tcx> {
2415 pub fn empty() -> GenericPredicates<'tcx> {
2417 predicates: VecPerParamSpace::empty(),
2421 pub fn instantiate(&self, tcx: &ctxt<'tcx>, substs: &Substs<'tcx>)
2422 -> InstantiatedPredicates<'tcx> {
2423 InstantiatedPredicates {
2424 predicates: self.predicates.subst(tcx, substs),
2428 pub fn instantiate_supertrait(&self,
2430 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
2431 -> InstantiatedPredicates<'tcx>
2433 InstantiatedPredicates {
2434 predicates: self.predicates.map(|pred| pred.subst_supertrait(tcx, poly_trait_ref))
2439 #[derive(Clone, PartialEq, Eq, Hash)]
2440 pub enum Predicate<'tcx> {
2441 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
2442 /// the `Self` type of the trait reference and `A`, `B`, and `C`
2443 /// would be the parameters in the `TypeSpace`.
2444 Trait(PolyTraitPredicate<'tcx>),
2446 /// where `T1 == T2`.
2447 Equate(PolyEquatePredicate<'tcx>),
2450 RegionOutlives(PolyRegionOutlivesPredicate),
2453 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
2455 /// where <T as TraitRef>::Name == X, approximately.
2456 /// See `ProjectionPredicate` struct for details.
2457 Projection(PolyProjectionPredicate<'tcx>),
2460 WellFormed(Ty<'tcx>),
2462 /// trait must be object-safe
2466 impl<'tcx> Predicate<'tcx> {
2467 /// Performs a substitution suitable for going from a
2468 /// poly-trait-ref to supertraits that must hold if that
2469 /// poly-trait-ref holds. This is slightly different from a normal
2470 /// substitution in terms of what happens with bound regions. See
2471 /// lengthy comment below for details.
2472 pub fn subst_supertrait(&self,
2474 trait_ref: &ty::PolyTraitRef<'tcx>)
2475 -> ty::Predicate<'tcx>
2477 // The interaction between HRTB and supertraits is not entirely
2478 // obvious. Let me walk you (and myself) through an example.
2480 // Let's start with an easy case. Consider two traits:
2482 // trait Foo<'a> : Bar<'a,'a> { }
2483 // trait Bar<'b,'c> { }
2485 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
2486 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
2487 // knew that `Foo<'x>` (for any 'x) then we also know that
2488 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
2489 // normal substitution.
2491 // In terms of why this is sound, the idea is that whenever there
2492 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
2493 // holds. So if there is an impl of `T:Foo<'a>` that applies to
2494 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
2497 // Another example to be careful of is this:
2499 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
2500 // trait Bar1<'b,'c> { }
2502 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
2503 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
2504 // reason is similar to the previous example: any impl of
2505 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
2506 // basically we would want to collapse the bound lifetimes from
2507 // the input (`trait_ref`) and the supertraits.
2509 // To achieve this in practice is fairly straightforward. Let's
2510 // consider the more complicated scenario:
2512 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
2513 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
2514 // where both `'x` and `'b` would have a DB index of 1.
2515 // The substitution from the input trait-ref is therefore going to be
2516 // `'a => 'x` (where `'x` has a DB index of 1).
2517 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
2518 // early-bound parameter and `'b' is a late-bound parameter with a
2520 // - If we replace `'a` with `'x` from the input, it too will have
2521 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
2522 // just as we wanted.
2524 // There is only one catch. If we just apply the substitution `'a
2525 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
2526 // adjust the DB index because we substituting into a binder (it
2527 // tries to be so smart...) resulting in `for<'x> for<'b>
2528 // Bar1<'x,'b>` (we have no syntax for this, so use your
2529 // imagination). Basically the 'x will have DB index of 2 and 'b
2530 // will have DB index of 1. Not quite what we want. So we apply
2531 // the substitution to the *contents* of the trait reference,
2532 // rather than the trait reference itself (put another way, the
2533 // substitution code expects equal binding levels in the values
2534 // from the substitution and the value being substituted into, and
2535 // this trick achieves that).
2537 let substs = &trait_ref.0.substs;
2539 Predicate::Trait(ty::Binder(ref data)) =>
2540 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
2541 Predicate::Equate(ty::Binder(ref data)) =>
2542 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
2543 Predicate::RegionOutlives(ty::Binder(ref data)) =>
2544 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
2545 Predicate::TypeOutlives(ty::Binder(ref data)) =>
2546 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
2547 Predicate::Projection(ty::Binder(ref data)) =>
2548 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
2549 Predicate::WellFormed(data) =>
2550 Predicate::WellFormed(data.subst(tcx, substs)),
2551 Predicate::ObjectSafe(trait_def_id) =>
2552 Predicate::ObjectSafe(trait_def_id),
2557 #[derive(Clone, PartialEq, Eq, Hash)]
2558 pub struct TraitPredicate<'tcx> {
2559 pub trait_ref: TraitRef<'tcx>
2561 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
2563 impl<'tcx> TraitPredicate<'tcx> {
2564 pub fn def_id(&self) -> DefId {
2565 self.trait_ref.def_id
2568 pub fn input_types(&self) -> &[Ty<'tcx>] {
2569 self.trait_ref.substs.types.as_slice()
2572 pub fn self_ty(&self) -> Ty<'tcx> {
2573 self.trait_ref.self_ty()
2577 impl<'tcx> PolyTraitPredicate<'tcx> {
2578 pub fn def_id(&self) -> DefId {
2583 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2584 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
2585 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
2587 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2588 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
2589 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
2590 pub type PolyRegionOutlivesPredicate = PolyOutlivesPredicate<ty::Region, ty::Region>;
2591 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region>;
2593 /// This kind of predicate has no *direct* correspondent in the
2594 /// syntax, but it roughly corresponds to the syntactic forms:
2596 /// 1. `T : TraitRef<..., Item=Type>`
2597 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
2599 /// In particular, form #1 is "desugared" to the combination of a
2600 /// normal trait predicate (`T : TraitRef<...>`) and one of these
2601 /// predicates. Form #2 is a broader form in that it also permits
2602 /// equality between arbitrary types. Processing an instance of Form
2603 /// #2 eventually yields one of these `ProjectionPredicate`
2604 /// instances to normalize the LHS.
2605 #[derive(Clone, PartialEq, Eq, Hash)]
2606 pub struct ProjectionPredicate<'tcx> {
2607 pub projection_ty: ProjectionTy<'tcx>,
2611 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
2613 impl<'tcx> PolyProjectionPredicate<'tcx> {
2614 pub fn item_name(&self) -> Name {
2615 self.0.projection_ty.item_name // safe to skip the binder to access a name
2618 pub fn sort_key(&self) -> (DefId, Name) {
2619 self.0.projection_ty.sort_key()
2623 /// Represents the projection of an associated type. In explicit UFCS
2624 /// form this would be written `<T as Trait<..>>::N`.
2625 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
2626 pub struct ProjectionTy<'tcx> {
2627 /// The trait reference `T as Trait<..>`.
2628 pub trait_ref: ty::TraitRef<'tcx>,
2630 /// The name `N` of the associated type.
2631 pub item_name: Name,
2634 impl<'tcx> ProjectionTy<'tcx> {
2635 pub fn sort_key(&self) -> (DefId, Name) {
2636 (self.trait_ref.def_id, self.item_name)
2640 pub trait ToPolyTraitRef<'tcx> {
2641 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
2644 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
2645 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2646 assert!(!self.has_escaping_regions());
2647 ty::Binder(self.clone())
2651 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
2652 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2653 self.map_bound_ref(|trait_pred| trait_pred.trait_ref.clone())
2657 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
2658 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2659 // Note: unlike with TraitRef::to_poly_trait_ref(),
2660 // self.0.trait_ref is permitted to have escaping regions.
2661 // This is because here `self` has a `Binder` and so does our
2662 // return value, so we are preserving the number of binding
2664 ty::Binder(self.0.projection_ty.trait_ref.clone())
2668 pub trait ToPredicate<'tcx> {
2669 fn to_predicate(&self) -> Predicate<'tcx>;
2672 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
2673 fn to_predicate(&self) -> Predicate<'tcx> {
2674 // we're about to add a binder, so let's check that we don't
2675 // accidentally capture anything, or else that might be some
2676 // weird debruijn accounting.
2677 assert!(!self.has_escaping_regions());
2679 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
2680 trait_ref: self.clone()
2685 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
2686 fn to_predicate(&self) -> Predicate<'tcx> {
2687 ty::Predicate::Trait(self.to_poly_trait_predicate())
2691 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
2692 fn to_predicate(&self) -> Predicate<'tcx> {
2693 Predicate::Equate(self.clone())
2697 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate {
2698 fn to_predicate(&self) -> Predicate<'tcx> {
2699 Predicate::RegionOutlives(self.clone())
2703 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
2704 fn to_predicate(&self) -> Predicate<'tcx> {
2705 Predicate::TypeOutlives(self.clone())
2709 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
2710 fn to_predicate(&self) -> Predicate<'tcx> {
2711 Predicate::Projection(self.clone())
2715 impl<'tcx> Predicate<'tcx> {
2716 /// Iterates over the types in this predicate. Note that in all
2717 /// cases this is skipping over a binder, so late-bound regions
2718 /// with depth 0 are bound by the predicate.
2719 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
2720 let vec: Vec<_> = match *self {
2721 ty::Predicate::Trait(ref data) => {
2722 data.0.trait_ref.substs.types.as_slice().to_vec()
2724 ty::Predicate::Equate(ty::Binder(ref data)) => {
2725 vec![data.0, data.1]
2727 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
2730 ty::Predicate::RegionOutlives(..) => {
2733 ty::Predicate::Projection(ref data) => {
2734 let trait_inputs = data.0.projection_ty.trait_ref.substs.types.as_slice();
2737 .chain(Some(data.0.ty))
2740 ty::Predicate::WellFormed(data) => {
2743 ty::Predicate::ObjectSafe(_trait_def_id) => {
2748 // The only reason to collect into a vector here is that I was
2749 // too lazy to make the full (somewhat complicated) iterator
2750 // type that would be needed here. But I wanted this fn to
2751 // return an iterator conceptually, rather than a `Vec`, so as
2752 // to be closer to `Ty::walk`.
2756 pub fn has_escaping_regions(&self) -> bool {
2758 Predicate::Trait(ref trait_ref) => trait_ref.has_escaping_regions(),
2759 Predicate::Equate(ref p) => p.has_escaping_regions(),
2760 Predicate::RegionOutlives(ref p) => p.has_escaping_regions(),
2761 Predicate::TypeOutlives(ref p) => p.has_escaping_regions(),
2762 Predicate::Projection(ref p) => p.has_escaping_regions(),
2763 Predicate::WellFormed(p) => p.has_escaping_regions(),
2764 Predicate::ObjectSafe(_trait_def_id) => false,
2768 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
2770 Predicate::Trait(ref t) => {
2771 Some(t.to_poly_trait_ref())
2773 Predicate::Projection(..) |
2774 Predicate::Equate(..) |
2775 Predicate::RegionOutlives(..) |
2776 Predicate::WellFormed(..) |
2777 Predicate::ObjectSafe(..) |
2778 Predicate::TypeOutlives(..) => {
2785 /// Represents the bounds declared on a particular set of type
2786 /// parameters. Should eventually be generalized into a flag list of
2787 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
2788 /// `GenericPredicates` by using the `instantiate` method. Note that this method
2789 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
2790 /// the `GenericPredicates` are expressed in terms of the bound type
2791 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
2792 /// represented a set of bounds for some particular instantiation,
2793 /// meaning that the generic parameters have been substituted with
2798 /// struct Foo<T,U:Bar<T>> { ... }
2800 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
2801 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
2802 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
2803 /// [usize:Bar<isize>]]`.
2805 pub struct InstantiatedPredicates<'tcx> {
2806 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
2809 impl<'tcx> InstantiatedPredicates<'tcx> {
2810 pub fn empty() -> InstantiatedPredicates<'tcx> {
2811 InstantiatedPredicates { predicates: VecPerParamSpace::empty() }
2814 pub fn has_escaping_regions(&self) -> bool {
2815 self.predicates.any(|p| p.has_escaping_regions())
2818 pub fn is_empty(&self) -> bool {
2819 self.predicates.is_empty()
2823 impl<'tcx> TraitRef<'tcx> {
2824 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
2825 TraitRef { def_id: def_id, substs: substs }
2828 pub fn self_ty(&self) -> Ty<'tcx> {
2829 self.substs.self_ty().unwrap()
2832 pub fn input_types(&self) -> &[Ty<'tcx>] {
2833 // Select only the "input types" from a trait-reference. For
2834 // now this is all the types that appear in the
2835 // trait-reference, but it should eventually exclude
2836 // associated types.
2837 self.substs.types.as_slice()
2841 /// When type checking, we use the `ParameterEnvironment` to track
2842 /// details about the type/lifetime parameters that are in scope.
2843 /// It primarily stores the bounds information.
2845 /// Note: This information might seem to be redundant with the data in
2846 /// `tcx.ty_param_defs`, but it is not. That table contains the
2847 /// parameter definitions from an "outside" perspective, but this
2848 /// struct will contain the bounds for a parameter as seen from inside
2849 /// the function body. Currently the only real distinction is that
2850 /// bound lifetime parameters are replaced with free ones, but in the
2851 /// future I hope to refine the representation of types so as to make
2852 /// more distinctions clearer.
2854 pub struct ParameterEnvironment<'a, 'tcx:'a> {
2855 pub tcx: &'a ctxt<'tcx>,
2857 /// See `construct_free_substs` for details.
2858 pub free_substs: Substs<'tcx>,
2860 /// Each type parameter has an implicit region bound that
2861 /// indicates it must outlive at least the function body (the user
2862 /// may specify stronger requirements). This field indicates the
2863 /// region of the callee.
2864 pub implicit_region_bound: ty::Region,
2866 /// Obligations that the caller must satisfy. This is basically
2867 /// the set of bounds on the in-scope type parameters, translated
2868 /// into Obligations, and elaborated and normalized.
2869 pub caller_bounds: Vec<ty::Predicate<'tcx>>,
2871 /// Caches the results of trait selection. This cache is used
2872 /// for things that have to do with the parameters in scope.
2873 pub selection_cache: traits::SelectionCache<'tcx>,
2875 /// Scope that is attached to free regions for this scope. This
2876 /// is usually the id of the fn body, but for more abstract scopes
2877 /// like structs we often use the node-id of the struct.
2879 /// FIXME(#3696). It would be nice to refactor so that free
2880 /// regions don't have this implicit scope and instead introduce
2881 /// relationships in the environment.
2882 pub free_id: ast::NodeId,
2885 impl<'a, 'tcx> ParameterEnvironment<'a, 'tcx> {
2886 pub fn with_caller_bounds(&self,
2887 caller_bounds: Vec<ty::Predicate<'tcx>>)
2888 -> ParameterEnvironment<'a,'tcx>
2890 ParameterEnvironment {
2892 free_substs: self.free_substs.clone(),
2893 implicit_region_bound: self.implicit_region_bound,
2894 caller_bounds: caller_bounds,
2895 selection_cache: traits::SelectionCache::new(),
2896 free_id: self.free_id,
2900 pub fn for_item(cx: &'a ctxt<'tcx>, id: NodeId) -> ParameterEnvironment<'a, 'tcx> {
2901 match cx.map.find(id) {
2902 Some(ast_map::NodeImplItem(ref impl_item)) => {
2903 match impl_item.node {
2904 hir::TypeImplItem(_) => {
2905 // associated types don't have their own entry (for some reason),
2906 // so for now just grab environment for the impl
2907 let impl_id = cx.map.get_parent(id);
2908 let impl_def_id = DefId::local(impl_id);
2909 let scheme = cx.lookup_item_type(impl_def_id);
2910 let predicates = cx.lookup_predicates(impl_def_id);
2911 cx.construct_parameter_environment(impl_item.span,
2916 hir::ConstImplItem(_, _) => {
2917 let def_id = DefId::local(id);
2918 let scheme = cx.lookup_item_type(def_id);
2919 let predicates = cx.lookup_predicates(def_id);
2920 cx.construct_parameter_environment(impl_item.span,
2925 hir::MethodImplItem(_, ref body) => {
2926 let method_def_id = DefId::local(id);
2927 match cx.impl_or_trait_item(method_def_id) {
2928 MethodTraitItem(ref method_ty) => {
2929 let method_generics = &method_ty.generics;
2930 let method_bounds = &method_ty.predicates;
2931 cx.construct_parameter_environment(
2939 .bug("ParameterEnvironment::for_item(): \
2940 got non-method item from impl method?!")
2946 Some(ast_map::NodeTraitItem(trait_item)) => {
2947 match trait_item.node {
2948 hir::TypeTraitItem(..) => {
2949 // associated types don't have their own entry (for some reason),
2950 // so for now just grab environment for the trait
2951 let trait_id = cx.map.get_parent(id);
2952 let trait_def_id = DefId::local(trait_id);
2953 let trait_def = cx.lookup_trait_def(trait_def_id);
2954 let predicates = cx.lookup_predicates(trait_def_id);
2955 cx.construct_parameter_environment(trait_item.span,
2956 &trait_def.generics,
2960 hir::ConstTraitItem(..) => {
2961 let def_id = DefId::local(id);
2962 let scheme = cx.lookup_item_type(def_id);
2963 let predicates = cx.lookup_predicates(def_id);
2964 cx.construct_parameter_environment(trait_item.span,
2969 hir::MethodTraitItem(_, ref body) => {
2970 // for the body-id, use the id of the body
2971 // block, unless this is a trait method with
2972 // no default, then fallback to the method id.
2973 let body_id = body.as_ref().map(|b| b.id).unwrap_or(id);
2974 let method_def_id = DefId::local(id);
2976 match cx.impl_or_trait_item(method_def_id) {
2977 MethodTraitItem(ref method_ty) => {
2978 let method_generics = &method_ty.generics;
2979 let method_bounds = &method_ty.predicates;
2980 cx.construct_parameter_environment(
2988 .bug("ParameterEnvironment::for_item(): \
2989 got non-method item from provided \
2996 Some(ast_map::NodeItem(item)) => {
2998 hir::ItemFn(_, _, _, _, _, ref body) => {
2999 // We assume this is a function.
3000 let fn_def_id = DefId::local(id);
3001 let fn_scheme = cx.lookup_item_type(fn_def_id);
3002 let fn_predicates = cx.lookup_predicates(fn_def_id);
3004 cx.construct_parameter_environment(item.span,
3005 &fn_scheme.generics,
3010 hir::ItemStruct(..) |
3012 hir::ItemConst(..) |
3013 hir::ItemStatic(..) => {
3014 let def_id = DefId::local(id);
3015 let scheme = cx.lookup_item_type(def_id);
3016 let predicates = cx.lookup_predicates(def_id);
3017 cx.construct_parameter_environment(item.span,
3022 hir::ItemTrait(..) => {
3023 let def_id = DefId::local(id);
3024 let trait_def = cx.lookup_trait_def(def_id);
3025 let predicates = cx.lookup_predicates(def_id);
3026 cx.construct_parameter_environment(item.span,
3027 &trait_def.generics,
3032 cx.sess.span_bug(item.span,
3033 "ParameterEnvironment::from_item():
3034 can't create a parameter \
3035 environment for this kind of item")
3039 Some(ast_map::NodeExpr(..)) => {
3040 // This is a convenience to allow closures to work.
3041 ParameterEnvironment::for_item(cx, cx.map.get_parent(id))
3044 cx.sess.bug(&format!("ParameterEnvironment::from_item(): \
3045 `{}` is not an item",
3046 cx.map.node_to_string(id)))
3051 pub fn can_type_implement_copy(&self, self_type: Ty<'tcx>, span: Span)
3052 -> Result<(),CopyImplementationError> {
3055 // FIXME: (@jroesch) float this code up
3056 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(self.clone()), false);
3058 let adt = match self_type.sty {
3059 ty::TyStruct(struct_def, substs) => {
3060 for field in struct_def.all_fields() {
3061 let field_ty = field.ty(tcx, substs);
3062 if infcx.type_moves_by_default(field_ty, span) {
3063 return Err(FieldDoesNotImplementCopy(field.name))
3068 ty::TyEnum(enum_def, substs) => {
3069 for variant in &enum_def.variants {
3070 for field in &variant.fields {
3071 let field_ty = field.ty(tcx, substs);
3072 if infcx.type_moves_by_default(field_ty, span) {
3073 return Err(VariantDoesNotImplementCopy(variant.name))
3079 _ => return Err(TypeIsStructural),
3083 return Err(TypeHasDestructor)
3090 #[derive(Copy, Clone)]
3091 pub enum CopyImplementationError {
3092 FieldDoesNotImplementCopy(Name),
3093 VariantDoesNotImplementCopy(Name),
3098 /// A "type scheme", in ML terminology, is a type combined with some
3099 /// set of generic types that the type is, well, generic over. In Rust
3100 /// terms, it is the "type" of a fn item or struct -- this type will
3101 /// include various generic parameters that must be substituted when
3102 /// the item/struct is referenced. That is called converting the type
3103 /// scheme to a monotype.
3105 /// - `generics`: the set of type parameters and their bounds
3106 /// - `ty`: the base types, which may reference the parameters defined
3109 /// Note that TypeSchemes are also sometimes called "polytypes" (and
3110 /// in fact this struct used to carry that name, so you may find some
3111 /// stray references in a comment or something). We try to reserve the
3112 /// "poly" prefix to refer to higher-ranked things, as in
3115 /// Note that each item also comes with predicates, see
3116 /// `lookup_predicates`.
3117 #[derive(Clone, Debug)]
3118 pub struct TypeScheme<'tcx> {
3119 pub generics: Generics<'tcx>,
3124 flags TraitFlags: u32 {
3125 const NO_TRAIT_FLAGS = 0,
3126 const HAS_DEFAULT_IMPL = 1 << 0,
3127 const IS_OBJECT_SAFE = 1 << 1,
3128 const OBJECT_SAFETY_VALID = 1 << 2,
3129 const IMPLS_VALID = 1 << 3,
3133 /// As `TypeScheme` but for a trait ref.
3134 pub struct TraitDef<'tcx> {
3135 pub unsafety: hir::Unsafety,
3137 /// If `true`, then this trait had the `#[rustc_paren_sugar]`
3138 /// attribute, indicating that it should be used with `Foo()`
3139 /// sugar. This is a temporary thing -- eventually any trait wil
3140 /// be usable with the sugar (or without it).
3141 pub paren_sugar: bool,
3143 /// Generic type definitions. Note that `Self` is listed in here
3144 /// as having a single bound, the trait itself (e.g., in the trait
3145 /// `Eq`, there is a single bound `Self : Eq`). This is so that
3146 /// default methods get to assume that the `Self` parameters
3147 /// implements the trait.
3148 pub generics: Generics<'tcx>,
3150 pub trait_ref: TraitRef<'tcx>,
3152 /// A list of the associated types defined in this trait. Useful
3153 /// for resolving `X::Foo` type markers.
3154 pub associated_type_names: Vec<Name>,
3156 // Impls of this trait. To allow for quicker lookup, the impls are indexed
3157 // by a simplified version of their Self type: impls with a simplifiable
3158 // Self are stored in nonblanket_impls keyed by it, while all other impls
3159 // are stored in blanket_impls.
3161 /// Impls of the trait.
3162 pub nonblanket_impls: RefCell<
3163 FnvHashMap<fast_reject::SimplifiedType, Vec<DefId>>
3166 /// Blanket impls associated with the trait.
3167 pub blanket_impls: RefCell<Vec<DefId>>,
3170 pub flags: Cell<TraitFlags>
3173 impl<'tcx> TraitDef<'tcx> {
3174 // returns None if not yet calculated
3175 pub fn object_safety(&self) -> Option<bool> {
3176 if self.flags.get().intersects(TraitFlags::OBJECT_SAFETY_VALID) {
3177 Some(self.flags.get().intersects(TraitFlags::IS_OBJECT_SAFE))
3183 pub fn set_object_safety(&self, is_safe: bool) {
3184 assert!(self.object_safety().map(|cs| cs == is_safe).unwrap_or(true));
3186 self.flags.get() | if is_safe {
3187 TraitFlags::OBJECT_SAFETY_VALID | TraitFlags::IS_OBJECT_SAFE
3189 TraitFlags::OBJECT_SAFETY_VALID
3194 /// Records a trait-to-implementation mapping.
3195 pub fn record_impl(&self,
3198 impl_trait_ref: TraitRef<'tcx>) {
3199 debug!("TraitDef::record_impl for {:?}, from {:?}",
3200 self, impl_trait_ref);
3202 // We don't want to borrow_mut after we already populated all impls,
3203 // so check if an impl is present with an immutable borrow first.
3204 if let Some(sty) = fast_reject::simplify_type(tcx,
3205 impl_trait_ref.self_ty(), false) {
3206 if let Some(is) = self.nonblanket_impls.borrow().get(&sty) {
3207 if is.contains(&impl_def_id) {
3208 return // duplicate - skip
3212 self.nonblanket_impls.borrow_mut().entry(sty).or_insert(vec![]).push(impl_def_id)
3214 if self.blanket_impls.borrow().contains(&impl_def_id) {
3215 return // duplicate - skip
3217 self.blanket_impls.borrow_mut().push(impl_def_id)
3222 pub fn for_each_impl<F: FnMut(DefId)>(&self, tcx: &ctxt<'tcx>, mut f: F) {
3223 tcx.populate_implementations_for_trait_if_necessary(self.trait_ref.def_id);
3225 for &impl_def_id in self.blanket_impls.borrow().iter() {
3229 for v in self.nonblanket_impls.borrow().values() {
3230 for &impl_def_id in v {
3236 /// Iterate over every impl that could possibly match the
3237 /// self-type `self_ty`.
3238 pub fn for_each_relevant_impl<F: FnMut(DefId)>(&self,
3243 tcx.populate_implementations_for_trait_if_necessary(self.trait_ref.def_id);
3245 for &impl_def_id in self.blanket_impls.borrow().iter() {
3249 // simplify_type(.., false) basically replaces type parameters and
3250 // projections with infer-variables. This is, of course, done on
3251 // the impl trait-ref when it is instantiated, but not on the
3252 // predicate trait-ref which is passed here.
3254 // for example, if we match `S: Copy` against an impl like
3255 // `impl<T:Copy> Copy for Option<T>`, we replace the type variable
3256 // in `Option<T>` with an infer variable, to `Option<_>` (this
3257 // doesn't actually change fast_reject output), but we don't
3258 // replace `S` with anything - this impl of course can't be
3259 // selected, and as there are hundreds of similar impls,
3260 // considering them would significantly harm performance.
3261 if let Some(simp) = fast_reject::simplify_type(tcx, self_ty, true) {
3262 if let Some(impls) = self.nonblanket_impls.borrow().get(&simp) {
3263 for &impl_def_id in impls {
3268 for v in self.nonblanket_impls.borrow().values() {
3269 for &impl_def_id in v {
3279 flags AdtFlags: u32 {
3280 const NO_ADT_FLAGS = 0,
3281 const IS_ENUM = 1 << 0,
3282 const IS_DTORCK = 1 << 1, // is this a dtorck type?
3283 const IS_DTORCK_VALID = 1 << 2,
3284 const IS_PHANTOM_DATA = 1 << 3,
3285 const IS_SIMD = 1 << 4,
3286 const IS_FUNDAMENTAL = 1 << 5,
3287 const IS_NO_DROP_FLAG = 1 << 6,
3291 pub type AdtDef<'tcx> = &'tcx AdtDefData<'tcx, 'static>;
3292 pub type VariantDef<'tcx> = &'tcx VariantDefData<'tcx, 'static>;
3293 pub type FieldDef<'tcx> = &'tcx FieldDefData<'tcx, 'static>;
3295 // See comment on AdtDefData for explanation
3296 pub type AdtDefMaster<'tcx> = &'tcx AdtDefData<'tcx, 'tcx>;
3297 pub type VariantDefMaster<'tcx> = &'tcx VariantDefData<'tcx, 'tcx>;
3298 pub type FieldDefMaster<'tcx> = &'tcx FieldDefData<'tcx, 'tcx>;
3300 pub struct VariantDefData<'tcx, 'container: 'tcx> {
3302 pub name: Name, // struct's name if this is a struct
3304 pub fields: Vec<FieldDefData<'tcx, 'container>>
3307 pub struct FieldDefData<'tcx, 'container: 'tcx> {
3308 /// The field's DefId. NOTE: the fields of tuple-like enum variants
3309 /// are not real items, and don't have entries in tcache etc.
3311 /// special_idents::unnamed_field.name
3312 /// if this is a tuple-like field
3314 pub vis: hir::Visibility,
3315 /// TyIVar is used here to allow for variance (see the doc at
3317 ty: TyIVar<'tcx, 'container>
3320 /// The definition of an abstract data type - a struct or enum.
3322 /// These are all interned (by intern_adt_def) into the adt_defs
3325 /// Because of the possibility of nested tcx-s, this type
3326 /// needs 2 lifetimes: the traditional variant lifetime ('tcx)
3327 /// bounding the lifetime of the inner types is of course necessary.
3328 /// However, it is not sufficient - types from a child tcx must
3329 /// not be leaked into the master tcx by being stored in an AdtDefData.
3331 /// The 'container lifetime ensures that by outliving the container
3332 /// tcx and preventing shorter-lived types from being inserted. When
3333 /// write access is not needed, the 'container lifetime can be
3334 /// erased to 'static, which can be done by the AdtDef wrapper.
3335 pub struct AdtDefData<'tcx, 'container: 'tcx> {
3337 pub variants: Vec<VariantDefData<'tcx, 'container>>,
3338 destructor: Cell<Option<DefId>>,
3339 flags: Cell<AdtFlags>,
3342 impl<'tcx, 'container> PartialEq for AdtDefData<'tcx, 'container> {
3343 // AdtDefData are always interned and this is part of TyS equality
3345 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
3348 impl<'tcx, 'container> Eq for AdtDefData<'tcx, 'container> {}
3350 impl<'tcx, 'container> Hash for AdtDefData<'tcx, 'container> {
3352 fn hash<H: Hasher>(&self, s: &mut H) {
3353 (self as *const AdtDefData).hash(s)
3358 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3359 pub enum AdtKind { Struct, Enum }
3361 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3362 pub enum VariantKind { Dict, Tuple, Unit }
3364 impl<'tcx, 'container> AdtDefData<'tcx, 'container> {
3365 fn new(tcx: &ctxt<'tcx>,
3368 variants: Vec<VariantDefData<'tcx, 'container>>) -> Self {
3369 let mut flags = AdtFlags::NO_ADT_FLAGS;
3370 let attrs = tcx.get_attrs(did);
3371 if attr::contains_name(&attrs, "fundamental") {
3372 flags = flags | AdtFlags::IS_FUNDAMENTAL;
3374 if attr::contains_name(&attrs, "unsafe_no_drop_flag") {
3375 flags = flags | AdtFlags::IS_NO_DROP_FLAG;
3377 if tcx.lookup_simd(did) {
3378 flags = flags | AdtFlags::IS_SIMD;
3380 if Some(did) == tcx.lang_items.phantom_data() {
3381 flags = flags | AdtFlags::IS_PHANTOM_DATA;
3383 if let AdtKind::Enum = kind {
3384 flags = flags | AdtFlags::IS_ENUM;
3389 flags: Cell::new(flags),
3390 destructor: Cell::new(None)
3394 fn calculate_dtorck(&'tcx self, tcx: &ctxt<'tcx>) {
3395 if tcx.is_adt_dtorck(self) {
3396 self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK);
3398 self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK_VALID)
3401 /// Returns the kind of the ADT - Struct or Enum.
3403 pub fn adt_kind(&self) -> AdtKind {
3404 if self.flags.get().intersects(AdtFlags::IS_ENUM) {
3411 /// Returns whether this is a dtorck type. If this returns
3412 /// true, this type being safe for destruction requires it to be
3413 /// alive; Otherwise, only the contents are required to be.
3415 pub fn is_dtorck(&'tcx self, tcx: &ctxt<'tcx>) -> bool {
3416 if !self.flags.get().intersects(AdtFlags::IS_DTORCK_VALID) {
3417 self.calculate_dtorck(tcx)
3419 self.flags.get().intersects(AdtFlags::IS_DTORCK)
3422 /// Returns whether this type is #[fundamental] for the purposes
3423 /// of coherence checking.
3425 pub fn is_fundamental(&self) -> bool {
3426 self.flags.get().intersects(AdtFlags::IS_FUNDAMENTAL)
3430 pub fn is_simd(&self) -> bool {
3431 self.flags.get().intersects(AdtFlags::IS_SIMD)
3434 /// Returns true if this is PhantomData<T>.
3436 pub fn is_phantom_data(&self) -> bool {
3437 self.flags.get().intersects(AdtFlags::IS_PHANTOM_DATA)
3440 /// Returns whether this type has a destructor.
3441 pub fn has_dtor(&self) -> bool {
3442 match self.dtor_kind() {
3444 TraitDtor(..) => true
3448 /// Asserts this is a struct and returns the struct's unique
3450 pub fn struct_variant(&self) -> &VariantDefData<'tcx, 'container> {
3451 assert!(self.adt_kind() == AdtKind::Struct);
3456 pub fn type_scheme(&self, tcx: &ctxt<'tcx>) -> TypeScheme<'tcx> {
3457 tcx.lookup_item_type(self.did)
3461 pub fn predicates(&self, tcx: &ctxt<'tcx>) -> GenericPredicates<'tcx> {
3462 tcx.lookup_predicates(self.did)
3465 /// Returns an iterator over all fields contained
3468 pub fn all_fields(&self) ->
3470 slice::Iter<VariantDefData<'tcx, 'container>>,
3471 slice::Iter<FieldDefData<'tcx, 'container>>,
3472 for<'s> fn(&'s VariantDefData<'tcx, 'container>)
3473 -> slice::Iter<'s, FieldDefData<'tcx, 'container>>
3475 self.variants.iter().flat_map(VariantDefData::fields_iter)
3479 pub fn is_empty(&self) -> bool {
3480 self.variants.is_empty()
3484 pub fn is_univariant(&self) -> bool {
3485 self.variants.len() == 1
3488 pub fn is_payloadfree(&self) -> bool {
3489 !self.variants.is_empty() &&
3490 self.variants.iter().all(|v| v.fields.is_empty())
3493 pub fn variant_with_id(&self, vid: DefId) -> &VariantDefData<'tcx, 'container> {
3496 .find(|v| v.did == vid)
3497 .expect("variant_with_id: unknown variant")
3500 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
3503 .position(|v| v.did == vid)
3504 .expect("variant_index_with_id: unknown variant")
3507 pub fn variant_of_def(&self, def: def::Def) -> &VariantDefData<'tcx, 'container> {
3509 def::DefVariant(_, vid, _) => self.variant_with_id(vid),
3510 def::DefStruct(..) | def::DefTy(..) => self.struct_variant(),
3511 _ => panic!("unexpected def {:?} in variant_of_def", def)
3515 pub fn destructor(&self) -> Option<DefId> {
3516 self.destructor.get()
3519 pub fn set_destructor(&self, dtor: DefId) {
3520 assert!(self.destructor.get().is_none());
3521 self.destructor.set(Some(dtor));
3524 pub fn dtor_kind(&self) -> DtorKind {
3525 match self.destructor.get() {
3527 TraitDtor(!self.flags.get().intersects(AdtFlags::IS_NO_DROP_FLAG))
3534 impl<'tcx, 'container> VariantDefData<'tcx, 'container> {
3536 fn fields_iter(&self) -> slice::Iter<FieldDefData<'tcx, 'container>> {
3540 pub fn kind(&self) -> VariantKind {
3541 match self.fields.get(0) {
3542 None => VariantKind::Unit,
3543 Some(&FieldDefData { name, .. }) if name == special_idents::unnamed_field.name => {
3546 Some(_) => VariantKind::Dict
3550 pub fn is_tuple_struct(&self) -> bool {
3551 self.kind() == VariantKind::Tuple
3555 pub fn find_field_named(&self,
3557 -> Option<&FieldDefData<'tcx, 'container>> {
3558 self.fields.iter().find(|f| f.name == name)
3562 pub fn field_named(&self, name: ast::Name) -> &FieldDefData<'tcx, 'container> {
3563 self.find_field_named(name).unwrap()
3567 impl<'tcx, 'container> FieldDefData<'tcx, 'container> {
3568 pub fn new(did: DefId,
3570 vis: hir::Visibility) -> Self {
3579 pub fn ty(&self, tcx: &ctxt<'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
3580 self.unsubst_ty().subst(tcx, subst)
3583 pub fn unsubst_ty(&self) -> Ty<'tcx> {
3587 pub fn fulfill_ty(&self, ty: Ty<'container>) {
3588 self.ty.fulfill(ty);
3592 /// Records the substitutions used to translate the polytype for an
3593 /// item into the monotype of an item reference.
3595 pub struct ItemSubsts<'tcx> {
3596 pub substs: Substs<'tcx>,
3599 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
3600 pub enum ClosureKind {
3601 // Warning: Ordering is significant here! The ordering is chosen
3602 // because the trait Fn is a subtrait of FnMut and so in turn, and
3603 // hence we order it so that Fn < FnMut < FnOnce.
3610 pub fn trait_did(&self, cx: &ctxt) -> DefId {
3611 let result = match *self {
3612 FnClosureKind => cx.lang_items.require(FnTraitLangItem),
3613 FnMutClosureKind => {
3614 cx.lang_items.require(FnMutTraitLangItem)
3616 FnOnceClosureKind => {
3617 cx.lang_items.require(FnOnceTraitLangItem)
3621 Ok(trait_did) => trait_did,
3622 Err(err) => cx.sess.fatal(&err[..]),
3626 /// True if this a type that impls this closure kind
3627 /// must also implement `other`.
3628 pub fn extends(self, other: ty::ClosureKind) -> bool {
3629 match (self, other) {
3630 (FnClosureKind, FnClosureKind) => true,
3631 (FnClosureKind, FnMutClosureKind) => true,
3632 (FnClosureKind, FnOnceClosureKind) => true,
3633 (FnMutClosureKind, FnMutClosureKind) => true,
3634 (FnMutClosureKind, FnOnceClosureKind) => true,
3635 (FnOnceClosureKind, FnOnceClosureKind) => true,
3641 impl<'tcx> CommonTypes<'tcx> {
3642 fn new(arena: &'tcx TypedArena<TyS<'tcx>>,
3643 interner: &RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>)
3644 -> CommonTypes<'tcx>
3646 let mk = |sty| ctxt::intern_ty(arena, interner, sty);
3651 isize: mk(TyInt(hir::TyIs)),
3652 i8: mk(TyInt(hir::TyI8)),
3653 i16: mk(TyInt(hir::TyI16)),
3654 i32: mk(TyInt(hir::TyI32)),
3655 i64: mk(TyInt(hir::TyI64)),
3656 usize: mk(TyUint(hir::TyUs)),
3657 u8: mk(TyUint(hir::TyU8)),
3658 u16: mk(TyUint(hir::TyU16)),
3659 u32: mk(TyUint(hir::TyU32)),
3660 u64: mk(TyUint(hir::TyU64)),
3661 f32: mk(TyFloat(hir::TyF32)),
3662 f64: mk(TyFloat(hir::TyF64)),
3667 struct FlagComputation {
3670 // maximum depth of any bound region that we have seen thus far
3674 impl FlagComputation {
3675 fn new() -> FlagComputation {
3676 FlagComputation { flags: TypeFlags::empty(), depth: 0 }
3679 fn for_sty(st: &TypeVariants) -> FlagComputation {
3680 let mut result = FlagComputation::new();
3685 fn add_flags(&mut self, flags: TypeFlags) {
3686 self.flags = self.flags | (flags & TypeFlags::NOMINAL_FLAGS);
3689 fn add_depth(&mut self, depth: u32) {
3690 if depth > self.depth {
3695 /// Adds the flags/depth from a set of types that appear within the current type, but within a
3697 fn add_bound_computation(&mut self, computation: &FlagComputation) {
3698 self.add_flags(computation.flags);
3700 // The types that contributed to `computation` occurred within
3701 // a region binder, so subtract one from the region depth
3702 // within when adding the depth to `self`.
3703 let depth = computation.depth;
3705 self.add_depth(depth - 1);
3709 fn add_sty(&mut self, st: &TypeVariants) {
3719 // You might think that we could just return TyError for
3720 // any type containing TyError as a component, and get
3721 // rid of the TypeFlags::HAS_TY_ERR flag -- likewise for ty_bot (with
3722 // the exception of function types that return bot).
3723 // But doing so caused sporadic memory corruption, and
3724 // neither I (tjc) nor nmatsakis could figure out why,
3725 // so we're doing it this way.
3727 self.add_flags(TypeFlags::HAS_TY_ERR)
3730 &TyParam(ref p) => {
3731 self.add_flags(TypeFlags::HAS_LOCAL_NAMES);
3732 if p.space == subst::SelfSpace {
3733 self.add_flags(TypeFlags::HAS_SELF);
3735 self.add_flags(TypeFlags::HAS_PARAMS);
3739 &TyClosure(_, ref substs) => {
3740 self.add_flags(TypeFlags::HAS_TY_CLOSURE);
3741 self.add_flags(TypeFlags::HAS_LOCAL_NAMES);
3742 self.add_substs(&substs.func_substs);
3743 self.add_tys(&substs.upvar_tys);
3747 self.add_flags(TypeFlags::HAS_LOCAL_NAMES); // it might, right?
3748 self.add_flags(TypeFlags::HAS_TY_INFER)
3751 &TyEnum(_, substs) | &TyStruct(_, substs) => {
3752 self.add_substs(substs);
3755 &TyProjection(ref data) => {
3756 self.add_flags(TypeFlags::HAS_PROJECTION);
3757 self.add_projection_ty(data);
3760 &TyTrait(box TraitTy { ref principal, ref bounds }) => {
3761 let mut computation = FlagComputation::new();
3762 computation.add_substs(principal.0.substs);
3763 for projection_bound in &bounds.projection_bounds {
3764 let mut proj_computation = FlagComputation::new();
3765 proj_computation.add_projection_predicate(&projection_bound.0);
3766 self.add_bound_computation(&proj_computation);
3768 self.add_bound_computation(&computation);
3770 self.add_bounds(bounds);
3773 &TyBox(tt) | &TyArray(tt, _) | &TySlice(tt) => {
3777 &TyRawPtr(ref m) => {
3781 &TyRef(r, ref m) => {
3782 self.add_region(*r);
3786 &TyTuple(ref ts) => {
3787 self.add_tys(&ts[..]);
3790 &TyBareFn(_, ref f) => {
3791 self.add_fn_sig(&f.sig);
3796 fn add_ty(&mut self, ty: Ty) {
3797 self.add_flags(ty.flags.get());
3798 self.add_depth(ty.region_depth);
3801 fn add_tys(&mut self, tys: &[Ty]) {
3807 fn add_fn_sig(&mut self, fn_sig: &PolyFnSig) {
3808 let mut computation = FlagComputation::new();
3810 computation.add_tys(&fn_sig.0.inputs);
3812 if let ty::FnConverging(output) = fn_sig.0.output {
3813 computation.add_ty(output);
3816 self.add_bound_computation(&computation);
3819 fn add_region(&mut self, r: Region) {
3822 ty::ReSkolemized(..) => { self.add_flags(TypeFlags::HAS_RE_INFER); }
3823 ty::ReLateBound(debruijn, _) => { self.add_depth(debruijn.depth); }
3824 ty::ReEarlyBound(..) => { self.add_flags(TypeFlags::HAS_RE_EARLY_BOUND); }
3826 _ => { self.add_flags(TypeFlags::HAS_FREE_REGIONS); }
3830 self.add_flags(TypeFlags::HAS_LOCAL_NAMES);
3834 fn add_projection_predicate(&mut self, projection_predicate: &ProjectionPredicate) {
3835 self.add_projection_ty(&projection_predicate.projection_ty);
3836 self.add_ty(projection_predicate.ty);
3839 fn add_projection_ty(&mut self, projection_ty: &ProjectionTy) {
3840 self.add_substs(projection_ty.trait_ref.substs);
3843 fn add_substs(&mut self, substs: &Substs) {
3844 self.add_tys(substs.types.as_slice());
3845 match substs.regions {
3846 subst::ErasedRegions => {}
3847 subst::NonerasedRegions(ref regions) => {
3855 fn add_bounds(&mut self, bounds: &ExistentialBounds) {
3856 self.add_region(bounds.region_bound);
3860 impl<'tcx> ctxt<'tcx> {
3861 /// Create a type context and call the closure with a `&ty::ctxt` reference
3862 /// to the context. The closure enforces that the type context and any interned
3863 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
3864 /// reference to the context, to allow formatting values that need it.
3865 pub fn create_and_enter<F, R>(s: Session,
3866 arenas: &'tcx CtxtArenas<'tcx>,
3868 named_region_map: resolve_lifetime::NamedRegionMap,
3869 map: ast_map::Map<'tcx>,
3870 freevars: RefCell<FreevarMap>,
3871 region_maps: RegionMaps,
3872 lang_items: middle::lang_items::LanguageItems,
3873 stability: stability::Index<'tcx>,
3874 f: F) -> (Session, R)
3875 where F: FnOnce(&ctxt<'tcx>) -> R
3877 let interner = RefCell::new(FnvHashMap());
3878 let common_types = CommonTypes::new(&arenas.type_, &interner);
3883 substs_interner: RefCell::new(FnvHashMap()),
3884 bare_fn_interner: RefCell::new(FnvHashMap()),
3885 region_interner: RefCell::new(FnvHashMap()),
3886 stability_interner: RefCell::new(FnvHashMap()),
3887 types: common_types,
3888 named_region_map: named_region_map,
3889 region_maps: region_maps,
3890 free_region_maps: RefCell::new(FnvHashMap()),
3891 item_variance_map: RefCell::new(DefIdMap()),
3892 variance_computed: Cell::new(false),
3895 tables: RefCell::new(Tables::empty()),
3896 impl_trait_refs: RefCell::new(DefIdMap()),
3897 trait_defs: RefCell::new(DefIdMap()),
3898 adt_defs: RefCell::new(DefIdMap()),
3899 predicates: RefCell::new(DefIdMap()),
3900 super_predicates: RefCell::new(DefIdMap()),
3901 fulfilled_predicates: RefCell::new(traits::FulfilledPredicates::new()),
3904 tcache: RefCell::new(DefIdMap()),
3905 rcache: RefCell::new(FnvHashMap()),
3906 tc_cache: RefCell::new(FnvHashMap()),
3907 ast_ty_to_ty_cache: RefCell::new(NodeMap()),
3908 impl_or_trait_items: RefCell::new(DefIdMap()),
3909 trait_item_def_ids: RefCell::new(DefIdMap()),
3910 trait_items_cache: RefCell::new(DefIdMap()),
3911 ty_param_defs: RefCell::new(NodeMap()),
3912 normalized_cache: RefCell::new(FnvHashMap()),
3913 lang_items: lang_items,
3914 provided_method_sources: RefCell::new(DefIdMap()),
3915 destructors: RefCell::new(DefIdSet()),
3916 inherent_impls: RefCell::new(DefIdMap()),
3917 impl_items: RefCell::new(DefIdMap()),
3918 used_unsafe: RefCell::new(NodeSet()),
3919 used_mut_nodes: RefCell::new(NodeSet()),
3920 populated_external_types: RefCell::new(DefIdSet()),
3921 populated_external_primitive_impls: RefCell::new(DefIdSet()),
3922 extern_const_statics: RefCell::new(DefIdMap()),
3923 extern_const_variants: RefCell::new(DefIdMap()),
3924 extern_const_fns: RefCell::new(DefIdMap()),
3925 node_lint_levels: RefCell::new(FnvHashMap()),
3926 transmute_restrictions: RefCell::new(Vec::new()),
3927 stability: RefCell::new(stability),
3928 selection_cache: traits::SelectionCache::new(),
3929 repr_hint_cache: RefCell::new(DefIdMap()),
3930 const_qualif_map: RefCell::new(NodeMap()),
3931 custom_coerce_unsized_kinds: RefCell::new(DefIdMap()),
3932 cast_kinds: RefCell::new(NodeMap()),
3933 fragment_infos: RefCell::new(DefIdMap()),
3937 // Type constructors
3939 pub fn mk_substs(&self, substs: Substs<'tcx>) -> &'tcx Substs<'tcx> {
3940 if let Some(substs) = self.substs_interner.borrow().get(&substs) {
3944 let substs = self.arenas.substs.alloc(substs);
3945 self.substs_interner.borrow_mut().insert(substs, substs);
3949 /// Create an unsafe fn ty based on a safe fn ty.
3950 pub fn safe_to_unsafe_fn_ty(&self, bare_fn: &BareFnTy<'tcx>) -> Ty<'tcx> {
3951 assert_eq!(bare_fn.unsafety, hir::Unsafety::Normal);
3952 let unsafe_fn_ty_a = self.mk_bare_fn(ty::BareFnTy {
3953 unsafety: hir::Unsafety::Unsafe,
3955 sig: bare_fn.sig.clone()
3957 self.mk_fn(None, unsafe_fn_ty_a)
3960 pub fn mk_bare_fn(&self, bare_fn: BareFnTy<'tcx>) -> &'tcx BareFnTy<'tcx> {
3961 if let Some(bare_fn) = self.bare_fn_interner.borrow().get(&bare_fn) {
3965 let bare_fn = self.arenas.bare_fn.alloc(bare_fn);
3966 self.bare_fn_interner.borrow_mut().insert(bare_fn, bare_fn);
3970 pub fn mk_region(&self, region: Region) -> &'tcx Region {
3971 if let Some(region) = self.region_interner.borrow().get(®ion) {
3975 let region = self.arenas.region.alloc(region);
3976 self.region_interner.borrow_mut().insert(region, region);
3980 pub fn closure_kind(&self, def_id: DefId) -> ty::ClosureKind {
3981 *self.tables.borrow().closure_kinds.get(&def_id).unwrap()
3984 pub fn closure_type(&self,
3986 substs: &ClosureSubsts<'tcx>)
3987 -> ty::ClosureTy<'tcx>
3989 self.tables.borrow().closure_tys.get(&def_id).unwrap().subst(self, &substs.func_substs)
3992 pub fn type_parameter_def(&self,
3994 -> TypeParameterDef<'tcx>
3996 self.ty_param_defs.borrow().get(&node_id).unwrap().clone()
3999 pub fn pat_contains_ref_binding(&self, pat: &hir::Pat) -> Option<hir::Mutability> {
4000 pat_util::pat_contains_ref_binding(&self.def_map, pat)
4003 pub fn arm_contains_ref_binding(&self, arm: &hir::Arm) -> Option<hir::Mutability> {
4004 pat_util::arm_contains_ref_binding(&self.def_map, arm)
4007 fn intern_ty(type_arena: &'tcx TypedArena<TyS<'tcx>>,
4008 interner: &RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>,
4009 st: TypeVariants<'tcx>)
4011 let ty: Ty /* don't be &mut TyS */ = {
4012 let mut interner = interner.borrow_mut();
4013 match interner.get(&st) {
4014 Some(ty) => return *ty,
4018 let flags = FlagComputation::for_sty(&st);
4021 () => type_arena.alloc(TyS { sty: st,
4022 flags: Cell::new(flags.flags),
4023 region_depth: flags.depth, }),
4026 interner.insert(InternedTy { ty: ty }, ty);
4030 debug!("Interned type: {:?} Pointer: {:?}",
4031 ty, ty as *const TyS);
4035 // Interns a type/name combination, stores the resulting box in cx.interner,
4036 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
4037 pub fn mk_ty(&self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
4038 ctxt::intern_ty(&self.arenas.type_, &self.interner, st)
4041 pub fn mk_mach_int(&self, tm: hir::IntTy) -> Ty<'tcx> {
4043 hir::TyIs => self.types.isize,
4044 hir::TyI8 => self.types.i8,
4045 hir::TyI16 => self.types.i16,
4046 hir::TyI32 => self.types.i32,
4047 hir::TyI64 => self.types.i64,
4051 pub fn mk_mach_uint(&self, tm: hir::UintTy) -> Ty<'tcx> {
4053 hir::TyUs => self.types.usize,
4054 hir::TyU8 => self.types.u8,
4055 hir::TyU16 => self.types.u16,
4056 hir::TyU32 => self.types.u32,
4057 hir::TyU64 => self.types.u64,
4061 pub fn mk_mach_float(&self, tm: hir::FloatTy) -> Ty<'tcx> {
4063 hir::TyF32 => self.types.f32,
4064 hir::TyF64 => self.types.f64,
4068 pub fn mk_str(&self) -> Ty<'tcx> {
4072 pub fn mk_static_str(&self) -> Ty<'tcx> {
4073 self.mk_imm_ref(self.mk_region(ty::ReStatic), self.mk_str())
4076 pub fn mk_enum(&self, def: AdtDef<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
4077 // take a copy of substs so that we own the vectors inside
4078 self.mk_ty(TyEnum(def, substs))
4081 pub fn mk_box(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4082 self.mk_ty(TyBox(ty))
4085 pub fn mk_ptr(&self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
4086 self.mk_ty(TyRawPtr(tm))
4089 pub fn mk_ref(&self, r: &'tcx Region, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
4090 self.mk_ty(TyRef(r, tm))
4093 pub fn mk_mut_ref(&self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
4094 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
4097 pub fn mk_imm_ref(&self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
4098 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
4101 pub fn mk_mut_ptr(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4102 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
4105 pub fn mk_imm_ptr(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4106 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
4109 pub fn mk_nil_ptr(&self) -> Ty<'tcx> {
4110 self.mk_imm_ptr(self.mk_nil())
4113 pub fn mk_array(&self, ty: Ty<'tcx>, n: usize) -> Ty<'tcx> {
4114 self.mk_ty(TyArray(ty, n))
4117 pub fn mk_slice(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4118 self.mk_ty(TySlice(ty))
4121 pub fn mk_tup(&self, ts: Vec<Ty<'tcx>>) -> Ty<'tcx> {
4122 self.mk_ty(TyTuple(ts))
4125 pub fn mk_nil(&self) -> Ty<'tcx> {
4126 self.mk_tup(Vec::new())
4129 pub fn mk_bool(&self) -> Ty<'tcx> {
4134 opt_def_id: Option<DefId>,
4135 fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
4136 self.mk_ty(TyBareFn(opt_def_id, fty))
4139 pub fn mk_ctor_fn(&self,
4141 input_tys: &[Ty<'tcx>],
4142 output: Ty<'tcx>) -> Ty<'tcx> {
4143 let input_args = input_tys.iter().cloned().collect();
4144 self.mk_fn(Some(def_id), self.mk_bare_fn(BareFnTy {
4145 unsafety: hir::Unsafety::Normal,
4147 sig: ty::Binder(FnSig {
4149 output: ty::FnConverging(output),
4155 pub fn mk_trait(&self,
4156 principal: ty::PolyTraitRef<'tcx>,
4157 bounds: ExistentialBounds<'tcx>)
4160 assert!(bound_list_is_sorted(&bounds.projection_bounds));
4162 let inner = box TraitTy {
4163 principal: principal,
4166 self.mk_ty(TyTrait(inner))
4169 pub fn mk_projection(&self,
4170 trait_ref: TraitRef<'tcx>,
4173 // take a copy of substs so that we own the vectors inside
4174 let inner = ProjectionTy { trait_ref: trait_ref, item_name: item_name };
4175 self.mk_ty(TyProjection(inner))
4178 pub fn mk_struct(&self, def: AdtDef<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
4179 // take a copy of substs so that we own the vectors inside
4180 self.mk_ty(TyStruct(def, substs))
4183 pub fn mk_closure(&self,
4185 substs: &'tcx Substs<'tcx>,
4188 self.mk_closure_from_closure_substs(closure_id, Box::new(ClosureSubsts {
4189 func_substs: substs,
4194 pub fn mk_closure_from_closure_substs(&self,
4196 closure_substs: Box<ClosureSubsts<'tcx>>)
4198 self.mk_ty(TyClosure(closure_id, closure_substs))
4201 pub fn mk_var(&self, v: TyVid) -> Ty<'tcx> {
4202 self.mk_infer(TyVar(v))
4205 pub fn mk_int_var(&self, v: IntVid) -> Ty<'tcx> {
4206 self.mk_infer(IntVar(v))
4209 pub fn mk_float_var(&self, v: FloatVid) -> Ty<'tcx> {
4210 self.mk_infer(FloatVar(v))
4213 pub fn mk_infer(&self, it: InferTy) -> Ty<'tcx> {
4214 self.mk_ty(TyInfer(it))
4217 pub fn mk_param(&self,
4218 space: subst::ParamSpace,
4220 name: Name) -> Ty<'tcx> {
4221 self.mk_ty(TyParam(ParamTy { space: space, idx: index, name: name }))
4224 pub fn mk_self_type(&self) -> Ty<'tcx> {
4225 self.mk_param(subst::SelfSpace, 0, special_idents::type_self.name)
4228 pub fn mk_param_from_def(&self, def: &TypeParameterDef) -> Ty<'tcx> {
4229 self.mk_param(def.space, def.index, def.name)
4233 fn bound_list_is_sorted(bounds: &[ty::PolyProjectionPredicate]) -> bool {
4234 bounds.is_empty() ||
4235 bounds[1..].iter().enumerate().all(
4236 |(index, bound)| bounds[index].sort_key() <= bound.sort_key())
4239 pub fn sort_bounds_list(bounds: &mut [ty::PolyProjectionPredicate]) {
4240 bounds.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()))
4243 impl<'tcx> TyS<'tcx> {
4244 /// Iterator that walks `self` and any types reachable from
4245 /// `self`, in depth-first order. Note that just walks the types
4246 /// that appear in `self`, it does not descend into the fields of
4247 /// structs or variants. For example:
4250 /// isize => { isize }
4251 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
4252 /// [isize] => { [isize], isize }
4254 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
4255 TypeWalker::new(self)
4258 /// Iterator that walks the immediate children of `self`. Hence
4259 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
4260 /// (but not `i32`, like `walk`).
4261 pub fn walk_shallow(&'tcx self) -> IntoIter<Ty<'tcx>> {
4262 walk::walk_shallow(self)
4265 pub fn as_opt_param_ty(&self) -> Option<ty::ParamTy> {
4267 ty::TyParam(ref d) => Some(d.clone()),
4272 pub fn is_param(&self, space: ParamSpace, index: u32) -> bool {
4274 ty::TyParam(ref data) => data.space == space && data.idx == index,
4279 /// Returns the regions directly referenced from this type (but
4280 /// not types reachable from this type via `walk_tys`). This
4281 /// ignores late-bound regions binders.
4282 pub fn regions(&self) -> Vec<ty::Region> {
4284 TyRef(region, _) => {
4287 TyTrait(ref obj) => {
4288 let mut v = vec![obj.bounds.region_bound];
4289 v.push_all(obj.principal.skip_binder().substs.regions().as_slice());
4293 TyStruct(_, substs) => {
4294 substs.regions().as_slice().to_vec()
4296 TyClosure(_, ref substs) => {
4297 substs.func_substs.regions().as_slice().to_vec()
4299 TyProjection(ref data) => {
4300 data.trait_ref.substs.regions().as_slice().to_vec()
4322 /// Walks `ty` and any types appearing within `ty`, invoking the
4323 /// callback `f` on each type. If the callback returns false, then the
4324 /// children of the current type are ignored.
4326 /// Note: prefer `ty.walk()` where possible.
4327 pub fn maybe_walk<F>(&'tcx self, mut f: F)
4328 where F : FnMut(Ty<'tcx>) -> bool
4330 let mut walker = self.walk();
4331 while let Some(ty) = walker.next() {
4333 walker.skip_current_subtree();
4340 pub fn new(space: subst::ParamSpace,
4344 ParamTy { space: space, idx: index, name: name }
4347 pub fn for_self() -> ParamTy {
4348 ParamTy::new(subst::SelfSpace, 0, special_idents::type_self.name)
4351 pub fn for_def(def: &TypeParameterDef) -> ParamTy {
4352 ParamTy::new(def.space, def.index, def.name)
4355 pub fn to_ty<'tcx>(self, tcx: &ctxt<'tcx>) -> Ty<'tcx> {
4356 tcx.mk_param(self.space, self.idx, self.name)
4359 pub fn is_self(&self) -> bool {
4360 self.space == subst::SelfSpace && self.idx == 0
4364 impl<'tcx> ItemSubsts<'tcx> {
4365 pub fn empty() -> ItemSubsts<'tcx> {
4366 ItemSubsts { substs: Substs::empty() }
4369 pub fn is_noop(&self) -> bool {
4370 self.substs.is_noop()
4375 impl<'tcx> TyS<'tcx> {
4376 pub fn is_nil(&self) -> bool {
4378 TyTuple(ref tys) => tys.is_empty(),
4383 pub fn is_empty(&self, _cx: &ctxt) -> bool {
4384 // FIXME(#24885): be smarter here
4386 TyEnum(def, _) | TyStruct(def, _) => def.is_empty(),
4391 pub fn is_ty_var(&self) -> bool {
4393 TyInfer(TyVar(_)) => true,
4398 pub fn is_bool(&self) -> bool { self.sty == TyBool }
4400 pub fn is_self(&self) -> bool {
4402 TyParam(ref p) => p.space == subst::SelfSpace,
4407 fn is_slice(&self) -> bool {
4409 TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
4410 TySlice(_) | TyStr => true,
4417 pub fn is_structural(&self) -> bool {
4419 TyStruct(..) | TyTuple(_) | TyEnum(..) |
4420 TyArray(..) | TyClosure(..) => true,
4421 _ => self.is_slice() | self.is_trait()
4426 pub fn is_simd(&self) -> bool {
4428 TyStruct(def, _) => def.is_simd(),
4433 pub fn sequence_element_type(&self, cx: &ctxt<'tcx>) -> Ty<'tcx> {
4435 TyArray(ty, _) | TySlice(ty) => ty,
4436 TyStr => cx.mk_mach_uint(hir::TyU8),
4437 _ => cx.sess.bug(&format!("sequence_element_type called on non-sequence value: {}",
4442 pub fn simd_type(&self, cx: &ctxt<'tcx>) -> Ty<'tcx> {
4444 TyStruct(def, substs) => {
4445 def.struct_variant().fields[0].ty(cx, substs)
4447 _ => panic!("simd_type called on invalid type")
4451 pub fn simd_size(&self, _cx: &ctxt) -> usize {
4453 TyStruct(def, _) => def.struct_variant().fields.len(),
4454 _ => panic!("simd_size called on invalid type")
4458 pub fn is_region_ptr(&self) -> bool {
4465 pub fn is_unsafe_ptr(&self) -> bool {
4467 TyRawPtr(_) => return true,
4472 pub fn is_unique(&self) -> bool {
4480 A scalar type is one that denotes an atomic datum, with no sub-components.
4481 (A TyRawPtr is scalar because it represents a non-managed pointer, so its
4482 contents are abstract to rustc.)
4484 pub fn is_scalar(&self) -> bool {
4486 TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
4487 TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
4488 TyBareFn(..) | TyRawPtr(_) => true,
4493 /// Returns true if this type is a floating point type and false otherwise.
4494 pub fn is_floating_point(&self) -> bool {
4497 TyInfer(FloatVar(_)) => true,
4502 pub fn ty_to_def_id(&self) -> Option<DefId> {
4504 TyTrait(ref tt) => Some(tt.principal_def_id()),
4506 TyEnum(def, _) => Some(def.did),
4507 TyClosure(id, _) => Some(id),
4512 pub fn ty_adt_def(&self) -> Option<AdtDef<'tcx>> {
4514 TyStruct(adt, _) | TyEnum(adt, _) => Some(adt),
4520 /// Type contents is how the type checker reasons about kinds.
4521 /// They track what kinds of things are found within a type. You can
4522 /// think of them as kind of an "anti-kind". They track the kinds of values
4523 /// and thinks that are contained in types. Having a larger contents for
4524 /// a type tends to rule that type *out* from various kinds. For example,
4525 /// a type that contains a reference is not sendable.
4527 /// The reason we compute type contents and not kinds is that it is
4528 /// easier for me (nmatsakis) to think about what is contained within
4529 /// a type than to think about what is *not* contained within a type.
4530 #[derive(Clone, Copy)]
4531 pub struct TypeContents {
4535 macro_rules! def_type_content_sets {
4536 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
4537 #[allow(non_snake_case)]
4539 use middle::ty::TypeContents;
4541 #[allow(non_upper_case_globals)]
4542 pub const $name: TypeContents = TypeContents { bits: $bits };
4548 def_type_content_sets! {
4550 None = 0b0000_0000__0000_0000__0000,
4552 // Things that are interior to the value (first nibble):
4553 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
4554 InteriorParam = 0b0000_0000__0000_0000__0100,
4555 // InteriorAll = 0b00000000__00000000__1111,
4557 // Things that are owned by the value (second and third nibbles):
4558 OwnsOwned = 0b0000_0000__0000_0001__0000,
4559 OwnsDtor = 0b0000_0000__0000_0010__0000,
4560 OwnsAll = 0b0000_0000__1111_1111__0000,
4562 // Things that mean drop glue is necessary
4563 NeedsDrop = 0b0000_0000__0000_0111__0000,
4566 All = 0b1111_1111__1111_1111__1111
4571 pub fn when(&self, cond: bool) -> TypeContents {
4572 if cond {*self} else {TC::None}
4575 pub fn intersects(&self, tc: TypeContents) -> bool {
4576 (self.bits & tc.bits) != 0
4579 pub fn owns_owned(&self) -> bool {
4580 self.intersects(TC::OwnsOwned)
4583 pub fn interior_param(&self) -> bool {
4584 self.intersects(TC::InteriorParam)
4587 pub fn interior_unsafe(&self) -> bool {
4588 self.intersects(TC::InteriorUnsafe)
4591 pub fn needs_drop(&self, _: &ctxt) -> bool {
4592 self.intersects(TC::NeedsDrop)
4595 /// Includes only those bits that still apply when indirected through a `Box` pointer
4596 pub fn owned_pointer(&self) -> TypeContents {
4597 TC::OwnsOwned | (*self & TC::OwnsAll)
4600 pub fn union<T, F>(v: &[T], mut f: F) -> TypeContents where
4601 F: FnMut(&T) -> TypeContents,
4603 v.iter().fold(TC::None, |tc, ty| tc | f(ty))
4606 pub fn has_dtor(&self) -> bool {
4607 self.intersects(TC::OwnsDtor)
4611 impl ops::BitOr for TypeContents {
4612 type Output = TypeContents;
4614 fn bitor(self, other: TypeContents) -> TypeContents {
4615 TypeContents {bits: self.bits | other.bits}
4619 impl ops::BitAnd for TypeContents {
4620 type Output = TypeContents;
4622 fn bitand(self, other: TypeContents) -> TypeContents {
4623 TypeContents {bits: self.bits & other.bits}
4627 impl ops::Sub for TypeContents {
4628 type Output = TypeContents;
4630 fn sub(self, other: TypeContents) -> TypeContents {
4631 TypeContents {bits: self.bits & !other.bits}
4635 impl fmt::Debug for TypeContents {
4636 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4637 write!(f, "TypeContents({:b})", self.bits)
4641 impl<'tcx> TyS<'tcx> {
4642 pub fn type_contents(&'tcx self, cx: &ctxt<'tcx>) -> TypeContents {
4643 return memoized(&cx.tc_cache, self, |ty| {
4644 tc_ty(cx, ty, &mut FnvHashMap())
4647 fn tc_ty<'tcx>(cx: &ctxt<'tcx>,
4649 cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
4651 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
4652 // private cache for this walk. This is needed in the case of cyclic
4655 // struct List { next: Box<Option<List>>, ... }
4657 // When computing the type contents of such a type, we wind up deeply
4658 // recursing as we go. So when we encounter the recursive reference
4659 // to List, we temporarily use TC::None as its contents. Later we'll
4660 // patch up the cache with the correct value, once we've computed it
4661 // (this is basically a co-inductive process, if that helps). So in
4662 // the end we'll compute TC::OwnsOwned, in this case.
4664 // The problem is, as we are doing the computation, we will also
4665 // compute an *intermediate* contents for, e.g., Option<List> of
4666 // TC::None. This is ok during the computation of List itself, but if
4667 // we stored this intermediate value into cx.tc_cache, then later
4668 // requests for the contents of Option<List> would also yield TC::None
4669 // which is incorrect. This value was computed based on the crutch
4670 // value for the type contents of list. The correct value is
4671 // TC::OwnsOwned. This manifested as issue #4821.
4672 match cache.get(&ty) {
4673 Some(tc) => { return *tc; }
4676 match cx.tc_cache.borrow().get(&ty) { // Must check both caches!
4677 Some(tc) => { return *tc; }
4680 cache.insert(ty, TC::None);
4682 let result = match ty.sty {
4683 // usize and isize are ffi-unsafe
4684 TyUint(hir::TyUs) | TyInt(hir::TyIs) => {
4688 // Scalar and unique types are sendable, and durable
4689 TyInfer(ty::FreshIntTy(_)) | TyInfer(ty::FreshFloatTy(_)) |
4690 TyBool | TyInt(_) | TyUint(_) | TyFloat(_) |
4691 TyBareFn(..) | ty::TyChar => {
4696 tc_ty(cx, typ, cache).owned_pointer()
4700 TC::All - TC::InteriorParam
4712 tc_ty(cx, ty, cache)
4716 tc_ty(cx, ty, cache)
4720 TyClosure(_, ref substs) => {
4721 TypeContents::union(&substs.upvar_tys, |ty| tc_ty(cx, &ty, cache))
4724 TyTuple(ref tys) => {
4725 TypeContents::union(&tys[..],
4726 |ty| tc_ty(cx, *ty, cache))
4729 TyStruct(def, substs) | TyEnum(def, substs) => {
4731 TypeContents::union(&def.variants, |v| {
4732 TypeContents::union(&v.fields, |f| {
4733 tc_ty(cx, f.ty(cx, substs), cache)
4738 res = res | TC::OwnsDtor;
4741 apply_lang_items(cx, def.did, res)
4751 cx.sess.bug("asked to compute contents of error type");
4755 cache.insert(ty, result);
4759 fn apply_lang_items(cx: &ctxt, did: DefId, tc: TypeContents)
4761 if Some(did) == cx.lang_items.unsafe_cell_type() {
4762 tc | TC::InteriorUnsafe
4769 fn impls_bound<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4770 bound: ty::BuiltinBound,
4774 let tcx = param_env.tcx;
4775 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env.clone()), false);
4777 let is_impld = traits::type_known_to_meet_builtin_bound(&infcx,
4780 debug!("Ty::impls_bound({:?}, {:?}) = {:?}",
4781 self, bound, is_impld);
4786 // FIXME (@jroesch): I made this public to use it, not sure if should be private
4787 pub fn moves_by_default<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4788 span: Span) -> bool {
4789 if self.flags.get().intersects(TypeFlags::MOVENESS_CACHED) {
4790 return self.flags.get().intersects(TypeFlags::MOVES_BY_DEFAULT);
4793 assert!(!self.needs_infer());
4795 // Fast-path for primitive types
4796 let result = match self.sty {
4797 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
4798 TyRawPtr(..) | TyBareFn(..) | TyRef(_, TypeAndMut {
4799 mutbl: hir::MutImmutable, ..
4802 TyStr | TyBox(..) | TyRef(_, TypeAndMut {
4803 mutbl: hir::MutMutable, ..
4806 TyArray(..) | TySlice(_) | TyTrait(..) | TyTuple(..) |
4807 TyClosure(..) | TyEnum(..) | TyStruct(..) |
4808 TyProjection(..) | TyParam(..) | TyInfer(..) | TyError => None
4809 }.unwrap_or_else(|| !self.impls_bound(param_env, ty::BoundCopy, span));
4811 if !self.has_param_types() && !self.has_self_ty() {
4812 self.flags.set(self.flags.get() | if result {
4813 TypeFlags::MOVENESS_CACHED | TypeFlags::MOVES_BY_DEFAULT
4815 TypeFlags::MOVENESS_CACHED
4823 pub fn is_sized<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4826 if self.flags.get().intersects(TypeFlags::SIZEDNESS_CACHED) {
4827 return self.flags.get().intersects(TypeFlags::IS_SIZED);
4830 self.is_sized_uncached(param_env, span)
4833 fn is_sized_uncached<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4834 span: Span) -> bool {
4835 assert!(!self.needs_infer());
4837 // Fast-path for primitive types
4838 let result = match self.sty {
4839 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
4840 TyBox(..) | TyRawPtr(..) | TyRef(..) | TyBareFn(..) |
4841 TyArray(..) | TyTuple(..) | TyClosure(..) => Some(true),
4843 TyStr | TyTrait(..) | TySlice(_) => Some(false),
4845 TyEnum(..) | TyStruct(..) | TyProjection(..) | TyParam(..) |
4846 TyInfer(..) | TyError => None
4847 }.unwrap_or_else(|| self.impls_bound(param_env, ty::BoundSized, span));
4849 if !self.has_param_types() && !self.has_self_ty() {
4850 self.flags.set(self.flags.get() | if result {
4851 TypeFlags::SIZEDNESS_CACHED | TypeFlags::IS_SIZED
4853 TypeFlags::SIZEDNESS_CACHED
4861 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
4862 pub enum LvaluePreference {
4867 impl LvaluePreference {
4868 pub fn from_mutbl(m: hir::Mutability) -> Self {
4870 hir::MutMutable => PreferMutLvalue,
4871 hir::MutImmutable => NoPreference,
4876 /// Describes whether a type is representable. For types that are not
4877 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
4878 /// distinguish between types that are recursive with themselves and types that
4879 /// contain a different recursive type. These cases can therefore be treated
4880 /// differently when reporting errors.
4882 /// The ordering of the cases is significant. They are sorted so that cmp::max
4883 /// will keep the "more erroneous" of two values.
4884 #[derive(Copy, Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
4885 pub enum Representability {
4891 impl<'tcx> TyS<'tcx> {
4892 /// Check whether a type is representable. This means it cannot contain unboxed
4893 /// structural recursion. This check is needed for structs and enums.
4894 pub fn is_representable(&'tcx self, cx: &ctxt<'tcx>, sp: Span) -> Representability {
4896 // Iterate until something non-representable is found
4897 fn find_nonrepresentable<'tcx, It: Iterator<Item=Ty<'tcx>>>(cx: &ctxt<'tcx>, sp: Span,
4898 seen: &mut Vec<Ty<'tcx>>,
4900 -> Representability {
4901 iter.fold(Representable,
4902 |r, ty| cmp::max(r, is_type_structurally_recursive(cx, sp, seen, ty)))
4905 fn are_inner_types_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
4906 seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
4907 -> Representability {
4909 TyTuple(ref ts) => {
4910 find_nonrepresentable(cx, sp, seen, ts.iter().cloned())
4912 // Fixed-length vectors.
4913 // FIXME(#11924) Behavior undecided for zero-length vectors.
4915 is_type_structurally_recursive(cx, sp, seen, ty)
4917 TyStruct(def, substs) | TyEnum(def, substs) => {
4918 find_nonrepresentable(cx,
4921 def.all_fields().map(|f| f.ty(cx, substs)))
4924 // this check is run on type definitions, so we don't expect
4925 // to see closure types
4926 cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
4932 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: AdtDef<'tcx>) -> bool {
4934 TyStruct(ty_def, _) | TyEnum(ty_def, _) => {
4941 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
4942 match (&a.sty, &b.sty) {
4943 (&TyStruct(did_a, ref substs_a), &TyStruct(did_b, ref substs_b)) |
4944 (&TyEnum(did_a, ref substs_a), &TyEnum(did_b, ref substs_b)) => {
4949 let types_a = substs_a.types.get_slice(subst::TypeSpace);
4950 let types_b = substs_b.types.get_slice(subst::TypeSpace);
4952 let mut pairs = types_a.iter().zip(types_b);
4954 pairs.all(|(&a, &b)| same_type(a, b))
4962 // Does the type `ty` directly (without indirection through a pointer)
4963 // contain any types on stack `seen`?
4964 fn is_type_structurally_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
4965 seen: &mut Vec<Ty<'tcx>>,
4966 ty: Ty<'tcx>) -> Representability {
4967 debug!("is_type_structurally_recursive: {:?}", ty);
4970 TyStruct(def, _) | TyEnum(def, _) => {
4972 // Iterate through stack of previously seen types.
4973 let mut iter = seen.iter();
4975 // The first item in `seen` is the type we are actually curious about.
4976 // We want to return SelfRecursive if this type contains itself.
4977 // It is important that we DON'T take generic parameters into account
4978 // for this check, so that Bar<T> in this example counts as SelfRecursive:
4981 // struct Bar<T> { x: Bar<Foo> }
4984 Some(&seen_type) => {
4985 if same_struct_or_enum(seen_type, def) {
4986 debug!("SelfRecursive: {:?} contains {:?}",
4989 return SelfRecursive;
4995 // We also need to know whether the first item contains other types
4996 // that are structurally recursive. If we don't catch this case, we
4997 // will recurse infinitely for some inputs.
4999 // It is important that we DO take generic parameters into account
5000 // here, so that code like this is considered SelfRecursive, not
5001 // ContainsRecursive:
5003 // struct Foo { Option<Option<Foo>> }
5005 for &seen_type in iter {
5006 if same_type(ty, seen_type) {
5007 debug!("ContainsRecursive: {:?} contains {:?}",
5010 return ContainsRecursive;
5015 // For structs and enums, track all previously seen types by pushing them
5016 // onto the 'seen' stack.
5018 let out = are_inner_types_recursive(cx, sp, seen, ty);
5023 // No need to push in other cases.
5024 are_inner_types_recursive(cx, sp, seen, ty)
5029 debug!("is_type_representable: {:?}", self);
5031 // To avoid a stack overflow when checking an enum variant or struct that
5032 // contains a different, structurally recursive type, maintain a stack
5033 // of seen types and check recursion for each of them (issues #3008, #3779).
5034 let mut seen: Vec<Ty> = Vec::new();
5035 let r = is_type_structurally_recursive(cx, sp, &mut seen, self);
5036 debug!("is_type_representable: {:?} is {:?}", self, r);
5040 pub fn is_trait(&self) -> bool {
5042 TyTrait(..) => true,
5047 pub fn is_integral(&self) -> bool {
5049 TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
5054 pub fn is_fresh(&self) -> bool {
5056 TyInfer(FreshTy(_)) => true,
5057 TyInfer(FreshIntTy(_)) => true,
5058 TyInfer(FreshFloatTy(_)) => true,
5063 pub fn is_uint(&self) -> bool {
5065 TyInfer(IntVar(_)) | TyUint(hir::TyUs) => true,
5070 pub fn is_char(&self) -> bool {
5077 pub fn is_bare_fn(&self) -> bool {
5079 TyBareFn(..) => true,
5084 pub fn is_bare_fn_item(&self) -> bool {
5086 TyBareFn(Some(_), _) => true,
5091 pub fn is_fp(&self) -> bool {
5093 TyInfer(FloatVar(_)) | TyFloat(_) => true,
5098 pub fn is_numeric(&self) -> bool {
5099 self.is_integral() || self.is_fp()
5102 pub fn is_signed(&self) -> bool {
5109 pub fn is_machine(&self) -> bool {
5111 TyInt(hir::TyIs) | TyUint(hir::TyUs) => false,
5112 TyInt(..) | TyUint(..) | TyFloat(..) => true,
5117 // Returns the type and mutability of *ty.
5119 // The parameter `explicit` indicates if this is an *explicit* dereference.
5120 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
5121 pub fn builtin_deref(&self, explicit: bool, pref: LvaluePreference)
5122 -> Option<TypeAndMut<'tcx>>
5129 if pref == PreferMutLvalue { hir::MutMutable } else { hir::MutImmutable },
5132 TyRef(_, mt) => Some(mt),
5133 TyRawPtr(mt) if explicit => Some(mt),
5138 // Returns the type of ty[i]
5139 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
5141 TyArray(ty, _) | TySlice(ty) => Some(ty),
5146 pub fn fn_sig(&self) -> &'tcx PolyFnSig<'tcx> {
5148 TyBareFn(_, ref f) => &f.sig,
5149 _ => panic!("Ty::fn_sig() called on non-fn type: {:?}", self)
5153 /// Returns the ABI of the given function.
5154 pub fn fn_abi(&self) -> abi::Abi {
5156 TyBareFn(_, ref f) => f.abi,
5157 _ => panic!("Ty::fn_abi() called on non-fn type"),
5161 // Type accessors for substructures of types
5162 pub fn fn_args(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
5163 self.fn_sig().inputs()
5166 pub fn fn_ret(&self) -> Binder<FnOutput<'tcx>> {
5167 self.fn_sig().output()
5170 pub fn is_fn(&self) -> bool {
5172 TyBareFn(..) => true,
5177 /// See `expr_ty_adjusted`
5178 pub fn adjust<F>(&'tcx self, cx: &ctxt<'tcx>,
5181 adjustment: Option<&AutoAdjustment<'tcx>>,
5184 F: FnMut(MethodCall) -> Option<Ty<'tcx>>,
5186 if let TyError = self.sty {
5190 return match adjustment {
5191 Some(adjustment) => {
5193 AdjustReifyFnPointer => {
5195 ty::TyBareFn(Some(_), b) => {
5200 &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
5206 AdjustUnsafeFnPointer => {
5208 ty::TyBareFn(None, b) => cx.safe_to_unsafe_fn_ty(b),
5211 &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
5218 AdjustDerefRef(ref adj) => {
5219 let mut adjusted_ty = self;
5221 if !adjusted_ty.references_error() {
5222 for i in 0..adj.autoderefs {
5224 adjusted_ty.adjust_for_autoderef(cx,
5232 if let Some(target) = adj.unsize {
5235 adjusted_ty.adjust_for_autoref(cx, adj.autoref)
5244 pub fn adjust_for_autoderef<F>(&'tcx self,
5246 expr_id: ast::NodeId,
5248 autoderef: u32, // how many autoderefs so far?
5251 F: FnMut(MethodCall) -> Option<Ty<'tcx>>,
5253 let method_call = MethodCall::autoderef(expr_id, autoderef);
5254 let mut adjusted_ty = self;
5255 if let Some(method_ty) = method_type(method_call) {
5256 // Method calls always have all late-bound regions
5257 // fully instantiated.
5258 let fn_ret = cx.no_late_bound_regions(&method_ty.fn_ret()).unwrap();
5259 adjusted_ty = fn_ret.unwrap();
5261 match adjusted_ty.builtin_deref(true, NoPreference) {
5266 &format!("the {}th autoderef failed: {}",
5274 pub fn adjust_for_autoref(&'tcx self, cx: &ctxt<'tcx>,
5275 autoref: Option<AutoRef<'tcx>>)
5279 Some(AutoPtr(r, m)) => {
5280 cx.mk_ref(r, TypeAndMut { ty: self, mutbl: m })
5282 Some(AutoUnsafe(m)) => {
5283 cx.mk_ptr(TypeAndMut { ty: self, mutbl: m })
5288 fn sort_string(&self, cx: &ctxt) -> String {
5291 TyBool | TyChar | TyInt(_) |
5292 TyUint(_) | TyFloat(_) | TyStr => self.to_string(),
5293 TyTuple(ref tys) if tys.is_empty() => self.to_string(),
5295 TyEnum(def, _) => format!("enum `{}`", cx.item_path_str(def.did)),
5296 TyBox(_) => "box".to_string(),
5297 TyArray(_, n) => format!("array of {} elements", n),
5298 TySlice(_) => "slice".to_string(),
5299 TyRawPtr(_) => "*-ptr".to_string(),
5300 TyRef(_, _) => "&-ptr".to_string(),
5301 TyBareFn(Some(_), _) => format!("fn item"),
5302 TyBareFn(None, _) => "fn pointer".to_string(),
5303 TyTrait(ref inner) => {
5304 format!("trait {}", cx.item_path_str(inner.principal_def_id()))
5306 TyStruct(def, _) => {
5307 format!("struct `{}`", cx.item_path_str(def.did))
5309 TyClosure(..) => "closure".to_string(),
5310 TyTuple(_) => "tuple".to_string(),
5311 TyInfer(TyVar(_)) => "inferred type".to_string(),
5312 TyInfer(IntVar(_)) => "integral variable".to_string(),
5313 TyInfer(FloatVar(_)) => "floating-point variable".to_string(),
5314 TyInfer(FreshTy(_)) => "skolemized type".to_string(),
5315 TyInfer(FreshIntTy(_)) => "skolemized integral type".to_string(),
5316 TyInfer(FreshFloatTy(_)) => "skolemized floating-point type".to_string(),
5317 TyProjection(_) => "associated type".to_string(),
5319 if p.space == subst::SelfSpace {
5322 "type parameter".to_string()
5325 TyError => "type error".to_string(),
5329 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
5330 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
5331 /// afterwards to present additional details, particularly when it comes to lifetime-related
5333 impl<'tcx> fmt::Display for TypeError<'tcx> {
5334 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5335 use self::TypeError::*;
5336 fn report_maybe_different(f: &mut fmt::Formatter,
5337 expected: String, found: String) -> fmt::Result {
5338 // A naive approach to making sure that we're not reporting silly errors such as:
5339 // (expected closure, found closure).
5340 if expected == found {
5341 write!(f, "expected {}, found a different {}", expected, found)
5343 write!(f, "expected {}, found {}", expected, found)
5348 CyclicTy => write!(f, "cyclic type of infinite size"),
5349 Mismatch => write!(f, "types differ"),
5350 UnsafetyMismatch(values) => {
5351 write!(f, "expected {} fn, found {} fn",
5355 AbiMismatch(values) => {
5356 write!(f, "expected {} fn, found {} fn",
5360 Mutability => write!(f, "values differ in mutability"),
5362 write!(f, "boxed values differ in mutability")
5364 VecMutability => write!(f, "vectors differ in mutability"),
5365 PtrMutability => write!(f, "pointers differ in mutability"),
5366 RefMutability => write!(f, "references differ in mutability"),
5367 TyParamSize(values) => {
5368 write!(f, "expected a type with {} type params, \
5369 found one with {} type params",
5373 FixedArraySize(values) => {
5374 write!(f, "expected an array with a fixed size of {} elements, \
5375 found one with {} elements",
5379 TupleSize(values) => {
5380 write!(f, "expected a tuple with {} elements, \
5381 found one with {} elements",
5386 write!(f, "incorrect number of function parameters")
5388 RegionsDoesNotOutlive(..) => {
5389 write!(f, "lifetime mismatch")
5391 RegionsNotSame(..) => {
5392 write!(f, "lifetimes are not the same")
5394 RegionsNoOverlap(..) => {
5395 write!(f, "lifetimes do not intersect")
5397 RegionsInsufficientlyPolymorphic(br, _) => {
5398 write!(f, "expected bound lifetime parameter {}, \
5399 found concrete lifetime", br)
5401 RegionsOverlyPolymorphic(br, _) => {
5402 write!(f, "expected concrete lifetime, \
5403 found bound lifetime parameter {}", br)
5405 Sorts(values) => tls::with(|tcx| {
5406 report_maybe_different(f, values.expected.sort_string(tcx),
5407 values.found.sort_string(tcx))
5409 Traits(values) => tls::with(|tcx| {
5410 report_maybe_different(f,
5411 format!("trait `{}`",
5412 tcx.item_path_str(values.expected)),
5413 format!("trait `{}`",
5414 tcx.item_path_str(values.found)))
5416 BuiltinBoundsMismatch(values) => {
5417 if values.expected.is_empty() {
5418 write!(f, "expected no bounds, found `{}`",
5420 } else if values.found.is_empty() {
5421 write!(f, "expected bounds `{}`, found no bounds",
5424 write!(f, "expected bounds `{}`, found bounds `{}`",
5430 write!(f, "expected an integral type, found `char`")
5432 IntMismatch(ref values) => {
5433 write!(f, "expected `{:?}`, found `{:?}`",
5437 FloatMismatch(ref values) => {
5438 write!(f, "expected `{:?}`, found `{:?}`",
5442 VariadicMismatch(ref values) => {
5443 write!(f, "expected {} fn, found {} function",
5444 if values.expected { "variadic" } else { "non-variadic" },
5445 if values.found { "variadic" } else { "non-variadic" })
5447 ConvergenceMismatch(ref values) => {
5448 write!(f, "expected {} fn, found {} function",
5449 if values.expected { "converging" } else { "diverging" },
5450 if values.found { "converging" } else { "diverging" })
5452 ProjectionNameMismatched(ref values) => {
5453 write!(f, "expected {}, found {}",
5457 ProjectionBoundsLength(ref values) => {
5458 write!(f, "expected {} associated type bindings, found {}",
5462 TyParamDefaultMismatch(ref values) => {
5463 write!(f, "conflicting type parameter defaults `{}` and `{}`",
5471 /// Helper for looking things up in the various maps that are populated during
5472 /// typeck::collect (e.g., `cx.impl_or_trait_items`, `cx.tcache`, etc). All of
5473 /// these share the pattern that if the id is local, it should have been loaded
5474 /// into the map by the `typeck::collect` phase. If the def-id is external,
5475 /// then we have to go consult the crate loading code (and cache the result for
5477 fn lookup_locally_or_in_crate_store<V, F>(descr: &str,
5479 map: &RefCell<DefIdMap<V>>,
5480 load_external: F) -> V where
5484 match map.borrow().get(&def_id).cloned() {
5485 Some(v) => { return v; }
5489 if def_id.is_local() {
5490 panic!("No def'n found for {:?} in tcx.{}", def_id, descr);
5492 let v = load_external();
5493 map.borrow_mut().insert(def_id, v.clone());
5498 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
5500 hir::MutMutable => MutBorrow,
5501 hir::MutImmutable => ImmBorrow,
5505 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
5506 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
5507 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
5509 pub fn to_mutbl_lossy(self) -> hir::Mutability {
5511 MutBorrow => hir::MutMutable,
5512 ImmBorrow => hir::MutImmutable,
5514 // We have no type corresponding to a unique imm borrow, so
5515 // use `&mut`. It gives all the capabilities of an `&uniq`
5516 // and hence is a safe "over approximation".
5517 UniqueImmBorrow => hir::MutMutable,
5521 pub fn to_user_str(&self) -> &'static str {
5523 MutBorrow => "mutable",
5524 ImmBorrow => "immutable",
5525 UniqueImmBorrow => "uniquely immutable",
5530 impl<'tcx> ctxt<'tcx> {
5531 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
5532 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
5533 pub fn positional_element_ty(&self,
5536 variant: Option<DefId>) -> Option<Ty<'tcx>> {
5537 match (&ty.sty, variant) {
5538 (&TyStruct(def, substs), None) => {
5539 def.struct_variant().fields.get(i).map(|f| f.ty(self, substs))
5541 (&TyEnum(def, substs), Some(vid)) => {
5542 def.variant_with_id(vid).fields.get(i).map(|f| f.ty(self, substs))
5544 (&TyEnum(def, substs), None) => {
5545 assert!(def.is_univariant());
5546 def.variants[0].fields.get(i).map(|f| f.ty(self, substs))
5548 (&TyTuple(ref v), None) => v.get(i).cloned(),
5553 /// Returns the type of element at field `n` in struct or struct-like type `t`.
5554 /// For an enum `t`, `variant` must be some def id.
5555 pub fn named_element_ty(&self,
5558 variant: Option<DefId>) -> Option<Ty<'tcx>> {
5559 match (&ty.sty, variant) {
5560 (&TyStruct(def, substs), None) => {
5561 def.struct_variant().find_field_named(n).map(|f| f.ty(self, substs))
5563 (&TyEnum(def, substs), Some(vid)) => {
5564 def.variant_with_id(vid).find_field_named(n).map(|f| f.ty(self, substs))
5570 pub fn node_id_to_type(&self, id: NodeId) -> Ty<'tcx> {
5571 match self.node_id_to_type_opt(id) {
5573 None => self.sess.bug(
5574 &format!("node_id_to_type: no type for node `{}`",
5575 self.map.node_to_string(id)))
5579 pub fn node_id_to_type_opt(&self, id: NodeId) -> Option<Ty<'tcx>> {
5580 self.tables.borrow().node_types.get(&id).cloned()
5583 pub fn node_id_item_substs(&self, id: NodeId) -> ItemSubsts<'tcx> {
5584 match self.tables.borrow().item_substs.get(&id) {
5585 None => ItemSubsts::empty(),
5586 Some(ts) => ts.clone(),
5590 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
5591 // doesn't provide type parameter substitutions.
5592 pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
5593 self.node_id_to_type(pat.id)
5595 pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
5596 self.node_id_to_type_opt(pat.id)
5599 // Returns the type of an expression as a monotype.
5601 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
5602 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
5603 // auto-ref. The type returned by this function does not consider such
5604 // adjustments. See `expr_ty_adjusted()` instead.
5606 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
5607 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
5608 // instead of "fn(ty) -> T with T = isize".
5609 pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
5610 self.node_id_to_type(expr.id)
5613 pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
5614 self.node_id_to_type_opt(expr.id)
5617 /// Returns the type of `expr`, considering any `AutoAdjustment`
5618 /// entry recorded for that expression.
5620 /// It would almost certainly be better to store the adjusted ty in with
5621 /// the `AutoAdjustment`, but I opted not to do this because it would
5622 /// require serializing and deserializing the type and, although that's not
5623 /// hard to do, I just hate that code so much I didn't want to touch it
5624 /// unless it was to fix it properly, which seemed a distraction from the
5625 /// thread at hand! -nmatsakis
5626 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
5628 .adjust(self, expr.span, expr.id,
5629 self.tables.borrow().adjustments.get(&expr.id),
5631 self.tables.borrow().method_map.get(&method_call).map(|method| method.ty)
5635 pub fn expr_span(&self, id: NodeId) -> Span {
5636 match self.map.find(id) {
5637 Some(ast_map::NodeExpr(e)) => {
5641 self.sess.bug(&format!("Node id {} is not an expr: {:?}",
5645 self.sess.bug(&format!("Node id {} is not present \
5646 in the node map", id));
5651 pub fn local_var_name_str(&self, id: NodeId) -> InternedString {
5652 match self.map.find(id) {
5653 Some(ast_map::NodeLocal(pat)) => {
5655 hir::PatIdent(_, ref path1, _) => path1.node.name.as_str(),
5657 self.sess.bug(&format!("Variable id {} maps to {:?}, not local", id, pat));
5661 r => self.sess.bug(&format!("Variable id {} maps to {:?}, not local", id, r)),
5665 pub fn resolve_expr(&self, expr: &hir::Expr) -> def::Def {
5666 match self.def_map.borrow().get(&expr.id) {
5667 Some(def) => def.full_def(),
5669 self.sess.span_bug(expr.span, &format!(
5670 "no def-map entry for expr {}", expr.id));
5675 pub fn expr_is_lval(&self, expr: &hir::Expr) -> bool {
5677 hir::ExprPath(..) => {
5678 // We can't use resolve_expr here, as this needs to run on broken
5679 // programs. We don't need to through - associated items are all
5681 match self.def_map.borrow().get(&expr.id) {
5682 Some(&def::PathResolution {
5683 base_def: def::DefStatic(..), ..
5684 }) | Some(&def::PathResolution {
5685 base_def: def::DefUpvar(..), ..
5686 }) | Some(&def::PathResolution {
5687 base_def: def::DefLocal(..), ..
5694 None => self.sess.span_bug(expr.span, &format!(
5695 "no def for path {}", expr.id))
5699 hir::ExprUnary(hir::UnDeref, _) |
5700 hir::ExprField(..) |
5701 hir::ExprTupField(..) |
5702 hir::ExprIndex(..) => {
5707 hir::ExprMethodCall(..) |
5708 hir::ExprStruct(..) |
5709 hir::ExprRange(..) |
5712 hir::ExprMatch(..) |
5713 hir::ExprClosure(..) |
5714 hir::ExprBlock(..) |
5715 hir::ExprRepeat(..) |
5717 hir::ExprBreak(..) |
5718 hir::ExprAgain(..) |
5720 hir::ExprWhile(..) |
5722 hir::ExprAssign(..) |
5723 hir::ExprInlineAsm(..) |
5724 hir::ExprAssignOp(..) |
5726 hir::ExprUnary(..) |
5728 hir::ExprAddrOf(..) |
5729 hir::ExprBinary(..) |
5730 hir::ExprCast(..) => {
5734 hir::ExprParen(ref e) => self.expr_is_lval(e),
5738 pub fn note_and_explain_type_err(&self, err: &TypeError<'tcx>, sp: Span) {
5739 use self::TypeError::*;
5742 RegionsDoesNotOutlive(subregion, superregion) => {
5743 self.note_and_explain_region("", subregion, "...");
5744 self.note_and_explain_region("...does not necessarily outlive ",
5747 RegionsNotSame(region1, region2) => {
5748 self.note_and_explain_region("", region1, "...");
5749 self.note_and_explain_region("...is not the same lifetime as ",
5752 RegionsNoOverlap(region1, region2) => {
5753 self.note_and_explain_region("", region1, "...");
5754 self.note_and_explain_region("...does not overlap ",
5757 RegionsInsufficientlyPolymorphic(_, conc_region) => {
5758 self.note_and_explain_region("concrete lifetime that was found is ",
5761 RegionsOverlyPolymorphic(_, ty::ReVar(_)) => {
5762 // don't bother to print out the message below for
5763 // inference variables, it's not very illuminating.
5765 RegionsOverlyPolymorphic(_, conc_region) => {
5766 self.note_and_explain_region("expected concrete lifetime is ",
5770 let expected_str = values.expected.sort_string(self);
5771 let found_str = values.found.sort_string(self);
5772 if expected_str == found_str && expected_str == "closure" {
5773 self.sess.span_note(sp,
5774 &format!("no two closures, even if identical, have the same type"));
5775 self.sess.span_help(sp,
5776 &format!("consider boxing your closure and/or \
5777 using it as a trait object"));
5780 TyParamDefaultMismatch(values) => {
5781 let expected = values.expected;
5782 let found = values.found;
5783 self.sess.span_note(sp,
5784 &format!("conflicting type parameter defaults `{}` and `{}`",
5788 match (expected.def_id.is_local(),
5789 self.map.opt_span(expected.def_id.node)) {
5790 (true, Some(span)) => {
5791 self.sess.span_note(span,
5792 &format!("a default was defined here..."));
5796 &format!("a default is defined on `{}`",
5797 self.item_path_str(expected.def_id)));
5801 self.sess.span_note(
5802 expected.origin_span,
5803 &format!("...that was applied to an unconstrained type variable here"));
5805 match (found.def_id.is_local(),
5806 self.map.opt_span(found.def_id.node)) {
5807 (true, Some(span)) => {
5808 self.sess.span_note(span,
5809 &format!("a second default was defined here..."));
5813 &format!("a second default is defined on `{}`",
5814 self.item_path_str(found.def_id)));
5818 self.sess.span_note(
5820 &format!("...that also applies to the same type variable here"));
5826 pub fn provided_source(&self, id: DefId) -> Option<DefId> {
5827 self.provided_method_sources.borrow().get(&id).cloned()
5830 pub fn provided_trait_methods(&self, id: DefId) -> Vec<Rc<Method<'tcx>>> {
5832 if let ItemTrait(_, _, _, ref ms) = self.map.expect_item(id.node).node {
5833 ms.iter().filter_map(|ti| {
5834 if let hir::MethodTraitItem(_, Some(_)) = ti.node {
5835 match self.impl_or_trait_item(DefId::local(ti.id)) {
5836 MethodTraitItem(m) => Some(m),
5838 self.sess.bug("provided_trait_methods(): \
5839 non-method item found from \
5840 looking up provided method?!")
5848 self.sess.bug(&format!("provided_trait_methods: `{:?}` is not a trait", id))
5851 csearch::get_provided_trait_methods(self, id)
5855 pub fn associated_consts(&self, id: DefId) -> Vec<Rc<AssociatedConst<'tcx>>> {
5857 match self.map.expect_item(id.node).node {
5858 ItemTrait(_, _, _, ref tis) => {
5859 tis.iter().filter_map(|ti| {
5860 if let hir::ConstTraitItem(_, _) = ti.node {
5861 match self.impl_or_trait_item(DefId::local(ti.id)) {
5862 ConstTraitItem(ac) => Some(ac),
5864 self.sess.bug("associated_consts(): \
5865 non-const item found from \
5866 looking up a constant?!")
5874 ItemImpl(_, _, _, _, _, ref iis) => {
5875 iis.iter().filter_map(|ii| {
5876 if let hir::ConstImplItem(_, _) = ii.node {
5877 match self.impl_or_trait_item(DefId::local(ii.id)) {
5878 ConstTraitItem(ac) => Some(ac),
5880 self.sess.bug("associated_consts(): \
5881 non-const item found from \
5882 looking up a constant?!")
5891 self.sess.bug(&format!("associated_consts: `{:?}` is not a trait \
5896 csearch::get_associated_consts(self, id)
5900 pub fn trait_items(&self, trait_did: DefId) -> Rc<Vec<ImplOrTraitItem<'tcx>>> {
5901 let mut trait_items = self.trait_items_cache.borrow_mut();
5902 match trait_items.get(&trait_did).cloned() {
5903 Some(trait_items) => trait_items,
5905 let def_ids = self.trait_item_def_ids(trait_did);
5906 let items: Rc<Vec<ImplOrTraitItem>> =
5907 Rc::new(def_ids.iter()
5908 .map(|d| self.impl_or_trait_item(d.def_id()))
5910 trait_items.insert(trait_did, items.clone());
5916 pub fn trait_impl_polarity(&self, id: DefId) -> Option<hir::ImplPolarity> {
5918 match self.map.find(id.node) {
5919 Some(ast_map::NodeItem(item)) => {
5921 hir::ItemImpl(_, polarity, _, _, _, _) => Some(polarity),
5928 csearch::get_impl_polarity(self, id)
5932 pub fn custom_coerce_unsized_kind(&self, did: DefId) -> CustomCoerceUnsized {
5933 memoized(&self.custom_coerce_unsized_kinds, did, |did: DefId| {
5934 let (kind, src) = if did.krate != LOCAL_CRATE {
5935 (csearch::get_custom_coerce_unsized_kind(self, did), "external")
5943 self.sess.bug(&format!("custom_coerce_unsized_kind: \
5944 {} impl `{}` is missing its kind",
5945 src, self.item_path_str(did)));
5951 pub fn impl_or_trait_item(&self, id: DefId) -> ImplOrTraitItem<'tcx> {
5952 lookup_locally_or_in_crate_store(
5953 "impl_or_trait_items", id, &self.impl_or_trait_items,
5954 || csearch::get_impl_or_trait_item(self, id))
5957 pub fn trait_item_def_ids(&self, id: DefId) -> Rc<Vec<ImplOrTraitItemId>> {
5958 lookup_locally_or_in_crate_store(
5959 "trait_item_def_ids", id, &self.trait_item_def_ids,
5960 || Rc::new(csearch::get_trait_item_def_ids(&self.sess.cstore, id)))
5963 /// Returns the trait-ref corresponding to a given impl, or None if it is
5964 /// an inherent impl.
5965 pub fn impl_trait_ref(&self, id: DefId) -> Option<TraitRef<'tcx>> {
5966 lookup_locally_or_in_crate_store(
5967 "impl_trait_refs", id, &self.impl_trait_refs,
5968 || csearch::get_impl_trait(self, id))
5971 /// Returns whether this DefId refers to an impl
5972 pub fn is_impl(&self, id: DefId) -> bool {
5974 if let Some(ast_map::NodeItem(
5975 &hir::Item { node: hir::ItemImpl(..), .. })) = self.map.find(id.node) {
5981 csearch::is_impl(&self.sess.cstore, id)
5985 pub fn trait_ref_to_def_id(&self, tr: &hir::TraitRef) -> DefId {
5986 self.def_map.borrow().get(&tr.ref_id).expect("no def-map entry for trait").def_id()
5989 pub fn try_add_builtin_trait(&self,
5990 trait_def_id: DefId,
5991 builtin_bounds: &mut EnumSet<BuiltinBound>)
5994 //! Checks whether `trait_ref` refers to one of the builtin
5995 //! traits, like `Send`, and adds the corresponding
5996 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
5997 //! is a builtin trait.
5999 match self.lang_items.to_builtin_kind(trait_def_id) {
6000 Some(bound) => { builtin_bounds.insert(bound); true }
6005 pub fn item_path_str(&self, id: DefId) -> String {
6006 self.with_path(id, |path| ast_map::path_to_string(path))
6009 pub fn with_path<T, F>(&self, id: DefId, f: F) -> T where
6010 F: FnOnce(ast_map::PathElems) -> T,
6013 self.map.with_path(id.node, f)
6015 f(csearch::get_item_path(self, id).iter().cloned().chain(LinkedPath::empty()))
6019 pub fn item_name(&self, id: DefId) -> ast::Name {
6021 self.map.get_path_elem(id.node).name()
6023 csearch::get_item_name(self, id)
6027 /// Returns `(normalized_type, ty)`, where `normalized_type` is the
6028 /// IntType representation of one of {i64,i32,i16,i8,u64,u32,u16,u8},
6029 /// and `ty` is the original type (i.e. may include `isize` or
6031 pub fn enum_repr_type(&self, opt_hint: Option<&attr::ReprAttr>)
6032 -> (attr::IntType, Ty<'tcx>) {
6033 let repr_type = match opt_hint {
6034 // Feed in the given type
6035 Some(&attr::ReprInt(_, int_t)) => int_t,
6036 // ... but provide sensible default if none provided
6038 // NB. Historically `fn enum_variants` generate i64 here, while
6039 // rustc_typeck::check would generate isize.
6040 _ => SignedInt(hir::TyIs),
6043 let repr_type_ty = repr_type.to_ty(self);
6044 let repr_type = match repr_type {
6045 SignedInt(hir::TyIs) =>
6046 SignedInt(self.sess.target.int_type),
6047 UnsignedInt(hir::TyUs) =>
6048 UnsignedInt(self.sess.target.uint_type),
6052 (repr_type, repr_type_ty)
6056 // Register a given item type
6057 pub fn register_item_type(&self, did: DefId, ty: TypeScheme<'tcx>) {
6058 self.tcache.borrow_mut().insert(did, ty);
6061 // If the given item is in an external crate, looks up its type and adds it to
6062 // the type cache. Returns the type parameters and type.
6063 pub fn lookup_item_type(&self, did: DefId) -> TypeScheme<'tcx> {
6064 lookup_locally_or_in_crate_store(
6065 "tcache", did, &self.tcache,
6066 || csearch::get_type(self, did))
6069 /// Given the did of a trait, returns its canonical trait ref.
6070 pub fn lookup_trait_def(&self, did: DefId) -> &'tcx TraitDef<'tcx> {
6071 lookup_locally_or_in_crate_store(
6072 "trait_defs", did, &self.trait_defs,
6073 || self.arenas.trait_defs.alloc(csearch::get_trait_def(self, did))
6077 /// Given the did of an ADT, return a master reference to its
6078 /// definition. Unless you are planning on fulfilling the ADT's fields,
6079 /// use lookup_adt_def instead.
6080 pub fn lookup_adt_def_master(&self, did: DefId) -> AdtDefMaster<'tcx> {
6081 lookup_locally_or_in_crate_store(
6082 "adt_defs", did, &self.adt_defs,
6083 || csearch::get_adt_def(self, did)
6087 /// Given the did of an ADT, return a reference to its definition.
6088 pub fn lookup_adt_def(&self, did: DefId) -> AdtDef<'tcx> {
6089 // when reverse-variance goes away, a transmute::<AdtDefMaster,AdtDef>
6090 // woud be needed here.
6091 self.lookup_adt_def_master(did)
6094 /// Return the list of all interned ADT definitions
6095 pub fn adt_defs(&self) -> Vec<AdtDef<'tcx>> {
6096 self.adt_defs.borrow().values().cloned().collect()
6099 /// Given the did of an item, returns its full set of predicates.
6100 pub fn lookup_predicates(&self, did: DefId) -> GenericPredicates<'tcx> {
6101 lookup_locally_or_in_crate_store(
6102 "predicates", did, &self.predicates,
6103 || csearch::get_predicates(self, did))
6106 /// Given the did of a trait, returns its superpredicates.
6107 pub fn lookup_super_predicates(&self, did: DefId) -> GenericPredicates<'tcx> {
6108 lookup_locally_or_in_crate_store(
6109 "super_predicates", did, &self.super_predicates,
6110 || csearch::get_super_predicates(self, did))
6113 /// Get the attributes of a definition.
6114 pub fn get_attrs(&self, did: DefId) -> Cow<'tcx, [hir::Attribute]> {
6116 Cow::Borrowed(self.map.attrs(did.node))
6118 Cow::Owned(csearch::get_item_attrs(&self.sess.cstore, did))
6122 /// Determine whether an item is annotated with an attribute
6123 pub fn has_attr(&self, did: DefId, attr: &str) -> bool {
6124 self.get_attrs(did).iter().any(|item| item.check_name(attr))
6127 /// Determine whether an item is annotated with `#[repr(packed)]`
6128 pub fn lookup_packed(&self, did: DefId) -> bool {
6129 self.lookup_repr_hints(did).contains(&attr::ReprPacked)
6132 /// Determine whether an item is annotated with `#[simd]`
6133 pub fn lookup_simd(&self, did: DefId) -> bool {
6134 self.has_attr(did, "simd")
6135 || self.lookup_repr_hints(did).contains(&attr::ReprSimd)
6138 /// Obtain the representation annotation for a struct definition.
6139 pub fn lookup_repr_hints(&self, did: DefId) -> Rc<Vec<attr::ReprAttr>> {
6140 memoized(&self.repr_hint_cache, did, |did: DefId| {
6141 Rc::new(if did.is_local() {
6142 self.get_attrs(did).iter().flat_map(|meta| {
6143 attr::find_repr_attrs(self.sess.diagnostic(), meta).into_iter()
6146 csearch::get_repr_attrs(&self.sess.cstore, did)
6152 /// Returns the deeply last field of nested structures, or the same type,
6153 /// if not a structure at all. Corresponds to the only possible unsized
6154 /// field, and its type can be used to determine unsizing strategy.
6155 pub fn struct_tail(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
6156 while let TyStruct(def, substs) = ty.sty {
6157 match def.struct_variant().fields.last() {
6158 Some(f) => ty = f.ty(self, substs),
6165 /// Same as applying struct_tail on `source` and `target`, but only
6166 /// keeps going as long as the two types are instances of the same
6167 /// structure definitions.
6168 /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
6169 /// whereas struct_tail produces `T`, and `Trait`, respectively.
6170 pub fn struct_lockstep_tails(&self,
6173 -> (Ty<'tcx>, Ty<'tcx>) {
6174 let (mut a, mut b) = (source, target);
6175 while let (&TyStruct(a_def, a_substs), &TyStruct(b_def, b_substs)) = (&a.sty, &b.sty) {
6179 if let Some(f) = a_def.struct_variant().fields.last() {
6180 a = f.ty(self, a_substs);
6181 b = f.ty(self, b_substs);
6189 // Returns the repeat count for a repeating vector expression.
6190 pub fn eval_repeat_count(&self, count_expr: &hir::Expr) -> usize {
6191 let hint = UncheckedExprHint(self.types.usize);
6192 match const_eval::eval_const_expr_partial(self, count_expr, hint) {
6194 let found = match val {
6195 ConstVal::Uint(count) => return count as usize,
6196 ConstVal::Int(count) if count >= 0 => return count as usize,
6197 const_val => const_val.description(),
6199 span_err!(self.sess, count_expr.span, E0306,
6200 "expected positive integer for repeat count, found {}",
6204 let err_msg = match count_expr.node {
6205 hir::ExprPath(None, hir::Path {
6209 }) if segments.len() == 1 =>
6210 format!("found variable"),
6211 _ => match err.kind {
6212 ErrKind::MiscCatchAll => format!("but found {}", err.description()),
6213 _ => format!("but {}", err.description())
6216 span_err!(self.sess, count_expr.span, E0307,
6217 "expected constant integer for repeat count, {}", err_msg);
6223 // Iterate over a type parameter's bounded traits and any supertraits
6224 // of those traits, ignoring kinds.
6225 // Here, the supertraits are the transitive closure of the supertrait
6226 // relation on the supertraits from each bounded trait's constraint
6228 pub fn each_bound_trait_and_supertraits<F>(&self,
6229 bounds: &[PolyTraitRef<'tcx>],
6232 F: FnMut(PolyTraitRef<'tcx>) -> bool,
6234 for bound_trait_ref in traits::transitive_bounds(self, bounds) {
6235 if !f(bound_trait_ref) {
6242 /// Given a set of predicates that apply to an object type, returns
6243 /// the region bounds that the (erased) `Self` type must
6244 /// outlive. Precisely *because* the `Self` type is erased, the
6245 /// parameter `erased_self_ty` must be supplied to indicate what type
6246 /// has been used to represent `Self` in the predicates
6247 /// themselves. This should really be a unique type; `FreshTy(0)` is a
6250 /// NB: in some cases, particularly around higher-ranked bounds,
6251 /// this function returns a kind of conservative approximation.
6252 /// That is, all regions returned by this function are definitely
6253 /// required, but there may be other region bounds that are not
6254 /// returned, as well as requirements like `for<'a> T: 'a`.
6256 /// Requires that trait definitions have been processed so that we can
6257 /// elaborate predicates and walk supertraits.
6258 pub fn required_region_bounds(&self,
6259 erased_self_ty: Ty<'tcx>,
6260 predicates: Vec<ty::Predicate<'tcx>>)
6261 -> Vec<ty::Region> {
6262 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
6266 assert!(!erased_self_ty.has_escaping_regions());
6268 traits::elaborate_predicates(self, predicates)
6269 .filter_map(|predicate| {
6271 ty::Predicate::Projection(..) |
6272 ty::Predicate::Trait(..) |
6273 ty::Predicate::Equate(..) |
6274 ty::Predicate::WellFormed(..) |
6275 ty::Predicate::ObjectSafe(..) |
6276 ty::Predicate::RegionOutlives(..) => {
6279 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
6280 // Search for a bound of the form `erased_self_ty
6281 // : 'a`, but be wary of something like `for<'a>
6282 // erased_self_ty : 'a` (we interpret a
6283 // higher-ranked bound like that as 'static,
6284 // though at present the code in `fulfill.rs`
6285 // considers such bounds to be unsatisfiable, so
6286 // it's kind of a moot point since you could never
6287 // construct such an object, but this seems
6288 // correct even if that code changes).
6289 if t == erased_self_ty && !r.has_escaping_regions() {
6300 pub fn item_variances(&self, item_id: DefId) -> Rc<ItemVariances> {
6301 lookup_locally_or_in_crate_store(
6302 "item_variance_map", item_id, &self.item_variance_map,
6303 || Rc::new(csearch::get_item_variances(&self.sess.cstore, item_id)))
6306 pub fn trait_has_default_impl(&self, trait_def_id: DefId) -> bool {
6307 self.populate_implementations_for_trait_if_necessary(trait_def_id);
6309 let def = self.lookup_trait_def(trait_def_id);
6310 def.flags.get().intersects(TraitFlags::HAS_DEFAULT_IMPL)
6313 /// Records a trait-to-implementation mapping.
6314 pub fn record_trait_has_default_impl(&self, trait_def_id: DefId) {
6315 let def = self.lookup_trait_def(trait_def_id);
6316 def.flags.set(def.flags.get() | TraitFlags::HAS_DEFAULT_IMPL)
6319 /// Load primitive inherent implementations if necessary
6320 pub fn populate_implementations_for_primitive_if_necessary(&self,
6321 primitive_def_id: DefId) {
6322 if primitive_def_id.is_local() {
6326 if self.populated_external_primitive_impls.borrow().contains(&primitive_def_id) {
6330 debug!("populate_implementations_for_primitive_if_necessary: searching for {:?}",
6333 let impl_items = csearch::get_impl_items(&self.sess.cstore, primitive_def_id);
6335 // Store the implementation info.
6336 self.impl_items.borrow_mut().insert(primitive_def_id, impl_items);
6337 self.populated_external_primitive_impls.borrow_mut().insert(primitive_def_id);
6340 /// Populates the type context with all the inherent implementations for
6341 /// the given type if necessary.
6342 pub fn populate_inherent_implementations_for_type_if_necessary(&self,
6344 if type_id.is_local() {
6348 if self.populated_external_types.borrow().contains(&type_id) {
6352 debug!("populate_inherent_implementations_for_type_if_necessary: searching for {:?}",
6355 let mut inherent_impls = Vec::new();
6356 csearch::each_inherent_implementation_for_type(&self.sess.cstore, type_id, |impl_def_id| {
6357 // Record the implementation.
6358 inherent_impls.push(impl_def_id);
6360 // Store the implementation info.
6361 let impl_items = csearch::get_impl_items(&self.sess.cstore, impl_def_id);
6362 self.impl_items.borrow_mut().insert(impl_def_id, impl_items);
6365 self.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
6366 self.populated_external_types.borrow_mut().insert(type_id);
6369 /// Populates the type context with all the implementations for the given
6370 /// trait if necessary.
6371 pub fn populate_implementations_for_trait_if_necessary(&self, trait_id: DefId) {
6372 if trait_id.is_local() {
6376 let def = self.lookup_trait_def(trait_id);
6377 if def.flags.get().intersects(TraitFlags::IMPLS_VALID) {
6381 debug!("populate_implementations_for_trait_if_necessary: searching for {:?}", def);
6383 if csearch::is_defaulted_trait(&self.sess.cstore, trait_id) {
6384 self.record_trait_has_default_impl(trait_id);
6387 csearch::each_implementation_for_trait(&self.sess.cstore, trait_id, |impl_def_id| {
6388 let impl_items = csearch::get_impl_items(&self.sess.cstore, impl_def_id);
6389 let trait_ref = self.impl_trait_ref(impl_def_id).unwrap();
6390 // Record the trait->implementation mapping.
6391 def.record_impl(self, impl_def_id, trait_ref);
6393 // For any methods that use a default implementation, add them to
6394 // the map. This is a bit unfortunate.
6395 for impl_item_def_id in &impl_items {
6396 let method_def_id = impl_item_def_id.def_id();
6397 match self.impl_or_trait_item(method_def_id) {
6398 MethodTraitItem(method) => {
6399 if let Some(source) = method.provided_source {
6400 self.provided_method_sources
6402 .insert(method_def_id, source);
6409 // Store the implementation info.
6410 self.impl_items.borrow_mut().insert(impl_def_id, impl_items);
6413 def.flags.set(def.flags.get() | TraitFlags::IMPLS_VALID);
6416 /// Given the def_id of an impl, return the def_id of the trait it implements.
6417 /// If it implements no trait, return `None`.
6418 pub fn trait_id_of_impl(&self, def_id: DefId) -> Option<DefId> {
6419 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
6422 /// If the given def ID describes a method belonging to an impl, return the
6423 /// ID of the impl that the method belongs to. Otherwise, return `None`.
6424 pub fn impl_of_method(&self, def_id: DefId) -> Option<DefId> {
6425 if def_id.krate != LOCAL_CRATE {
6426 return match csearch::get_impl_or_trait_item(self,
6427 def_id).container() {
6428 TraitContainer(_) => None,
6429 ImplContainer(def_id) => Some(def_id),
6432 match self.impl_or_trait_items.borrow().get(&def_id).cloned() {
6433 Some(trait_item) => {
6434 match trait_item.container() {
6435 TraitContainer(_) => None,
6436 ImplContainer(def_id) => Some(def_id),
6443 /// If the given def ID describes an item belonging to a trait (either a
6444 /// default method or an implementation of a trait method), return the ID of
6445 /// the trait that the method belongs to. Otherwise, return `None`.
6446 pub fn trait_of_item(&self, def_id: DefId) -> Option<DefId> {
6447 if def_id.krate != LOCAL_CRATE {
6448 return csearch::get_trait_of_item(&self.sess.cstore, def_id, self);
6450 match self.impl_or_trait_items.borrow().get(&def_id).cloned() {
6451 Some(impl_or_trait_item) => {
6452 match impl_or_trait_item.container() {
6453 TraitContainer(def_id) => Some(def_id),
6454 ImplContainer(def_id) => self.trait_id_of_impl(def_id),
6461 /// If the given def ID describes an item belonging to a trait, (either a
6462 /// default method or an implementation of a trait method), return the ID of
6463 /// the method inside trait definition (this means that if the given def ID
6464 /// is already that of the original trait method, then the return value is
6466 /// Otherwise, return `None`.
6467 pub fn trait_item_of_item(&self, def_id: DefId) -> Option<ImplOrTraitItemId> {
6468 let impl_item = match self.impl_or_trait_items.borrow().get(&def_id) {
6469 Some(m) => m.clone(),
6470 None => return None,
6472 let name = impl_item.name();
6473 match self.trait_of_item(def_id) {
6474 Some(trait_did) => {
6475 self.trait_items(trait_did).iter()
6476 .find(|item| item.name() == name)
6477 .map(|item| item.id())
6483 /// Creates a hash of the type `Ty` which will be the same no matter what crate
6484 /// context it's calculated within. This is used by the `type_id` intrinsic.
6485 pub fn hash_crate_independent(&self, ty: Ty<'tcx>, svh: &Svh) -> u64 {
6486 let mut state = SipHasher::new();
6487 helper(self, ty, svh, &mut state);
6488 return state.finish();
6490 fn helper<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh,
6491 state: &mut SipHasher) {
6492 macro_rules! byte { ($b:expr) => { ($b as u8).hash(state) } }
6493 macro_rules! hash { ($e:expr) => { $e.hash(state) } }
6495 let region = |state: &mut SipHasher, r: Region| {
6498 ReLateBound(db, BrAnon(i)) => {
6508 ReSkolemized(..) => {
6509 tcx.sess.bug("unexpected region found when hashing a type")
6513 let did = |state: &mut SipHasher, did: DefId| {
6514 let h = if did.is_local() {
6517 tcx.sess.cstore.get_crate_hash(did.krate)
6519 h.as_str().hash(state);
6520 did.node.hash(state);
6522 let mt = |state: &mut SipHasher, mt: TypeAndMut| {
6523 mt.mutbl.hash(state);
6525 let fn_sig = |state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| {
6526 let sig = tcx.anonymize_late_bound_regions(sig).0;
6527 for a in &sig.inputs { helper(tcx, *a, svh, state); }
6528 if let ty::FnConverging(output) = sig.output {
6529 helper(tcx, output, svh, state);
6532 ty.maybe_walk(|ty| {
6574 TyBareFn(opt_def_id, ref b) => {
6579 fn_sig(state, &b.sig);
6582 TyTrait(ref data) => {
6584 did(state, data.principal_def_id());
6587 let principal = tcx.anonymize_late_bound_regions(&data.principal).0;
6588 for subty in &principal.substs.types {
6589 helper(tcx, subty, svh, state);
6598 TyTuple(ref inner) => {
6606 hash!(p.name.as_str());
6608 TyInfer(_) => unreachable!(),
6609 TyError => byte!(21),
6610 TyClosure(d, _) => {
6614 TyProjection(ref data) => {
6616 did(state, data.trait_ref.def_id);
6617 hash!(data.item_name.as_str());
6625 /// Construct a parameter environment suitable for static contexts or other contexts where there
6626 /// are no free type/lifetime parameters in scope.
6627 pub fn empty_parameter_environment<'a>(&'a self)
6628 -> ParameterEnvironment<'a,'tcx> {
6629 ty::ParameterEnvironment { tcx: self,
6630 free_substs: Substs::empty(),
6631 caller_bounds: Vec::new(),
6632 implicit_region_bound: ty::ReEmpty,
6633 selection_cache: traits::SelectionCache::new(),
6635 // for an empty parameter
6636 // environment, there ARE no free
6637 // regions, so it shouldn't matter
6638 // what we use for the free id
6639 free_id: ast::DUMMY_NODE_ID }
6642 /// Constructs and returns a substitution that can be applied to move from
6643 /// the "outer" view of a type or method to the "inner" view.
6644 /// In general, this means converting from bound parameters to
6645 /// free parameters. Since we currently represent bound/free type
6646 /// parameters in the same way, this only has an effect on regions.
6647 pub fn construct_free_substs(&self, generics: &Generics<'tcx>,
6648 free_id: NodeId) -> Substs<'tcx> {
6650 let mut types = VecPerParamSpace::empty();
6651 for def in generics.types.as_slice() {
6652 debug!("construct_parameter_environment(): push_types_from_defs: def={:?}",
6654 types.push(def.space, self.mk_param_from_def(def));
6657 let free_id_outlive = self.region_maps.item_extent(free_id);
6659 // map bound 'a => free 'a
6660 let mut regions = VecPerParamSpace::empty();
6661 for def in generics.regions.as_slice() {
6663 ReFree(FreeRegion { scope: free_id_outlive,
6664 bound_region: BrNamed(def.def_id, def.name) });
6665 debug!("push_region_params {:?}", region);
6666 regions.push(def.space, region);
6671 regions: subst::NonerasedRegions(regions)
6675 /// See `ParameterEnvironment` struct def'n for details
6676 pub fn construct_parameter_environment<'a>(&'a self,
6678 generics: &ty::Generics<'tcx>,
6679 generic_predicates: &ty::GenericPredicates<'tcx>,
6681 -> ParameterEnvironment<'a, 'tcx>
6684 // Construct the free substs.
6687 let free_substs = self.construct_free_substs(generics, free_id);
6688 let free_id_outlive = self.region_maps.item_extent(free_id);
6691 // Compute the bounds on Self and the type parameters.
6694 let bounds = generic_predicates.instantiate(self, &free_substs);
6695 let bounds = self.liberate_late_bound_regions(free_id_outlive, &ty::Binder(bounds));
6696 let predicates = bounds.predicates.into_vec();
6698 debug!("construct_parameter_environment: free_id={:?} free_subst={:?} predicates={:?}",
6704 // Finally, we have to normalize the bounds in the environment, in
6705 // case they contain any associated type projections. This process
6706 // can yield errors if the put in illegal associated types, like
6707 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
6708 // report these errors right here; this doesn't actually feel
6709 // right to me, because constructing the environment feels like a
6710 // kind of a "idempotent" action, but I'm not sure where would be
6711 // a better place. In practice, we construct environments for
6712 // every fn once during type checking, and we'll abort if there
6713 // are any errors at that point, so after type checking you can be
6714 // sure that this will succeed without errors anyway.
6717 let unnormalized_env = ty::ParameterEnvironment {
6719 free_substs: free_substs,
6720 implicit_region_bound: ty::ReScope(free_id_outlive),
6721 caller_bounds: predicates,
6722 selection_cache: traits::SelectionCache::new(),
6726 let cause = traits::ObligationCause::misc(span, free_id);
6727 traits::normalize_param_env_or_error(unnormalized_env, cause)
6730 pub fn is_method_call(&self, expr_id: NodeId) -> bool {
6731 self.tables.borrow().method_map.contains_key(&MethodCall::expr(expr_id))
6734 pub fn is_overloaded_autoderef(&self, expr_id: NodeId, autoderefs: u32) -> bool {
6735 self.tables.borrow().method_map.contains_key(&MethodCall::autoderef(expr_id,
6739 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
6740 Some(self.tables.borrow().upvar_capture_map.get(&upvar_id).unwrap().clone())
6744 /// Returns true if this ADT is a dtorck type, i.e. whether it being
6745 /// safe for destruction requires it to be alive
6746 fn is_adt_dtorck(&self, adt: AdtDef<'tcx>) -> bool {
6747 let dtor_method = match adt.destructor() {
6749 None => return false
6751 let impl_did = self.impl_of_method(dtor_method).unwrap_or_else(|| {
6752 self.sess.bug(&format!("no Drop impl for the dtor of `{:?}`", adt))
6754 let generics = adt.type_scheme(self).generics;
6756 // In `impl<'a> Drop ...`, we automatically assume
6757 // `'a` is meaningful and thus represents a bound
6758 // through which we could reach borrowed data.
6760 // FIXME (pnkfelix): In the future it would be good to
6761 // extend the language to allow the user to express,
6762 // in the impl signature, that a lifetime is not
6763 // actually used (something like `where 'a: ?Live`).
6764 if generics.has_region_params(subst::TypeSpace) {
6765 debug!("typ: {:?} has interesting dtor due to region params",
6770 let mut seen_items = Vec::new();
6771 let mut items_to_inspect = vec![impl_did];
6772 while let Some(item_def_id) = items_to_inspect.pop() {
6773 if seen_items.contains(&item_def_id) {
6777 for pred in self.lookup_predicates(item_def_id).predicates {
6778 let result = match pred {
6779 ty::Predicate::Equate(..) |
6780 ty::Predicate::RegionOutlives(..) |
6781 ty::Predicate::TypeOutlives(..) |
6782 ty::Predicate::WellFormed(..) |
6783 ty::Predicate::ObjectSafe(..) |
6784 ty::Predicate::Projection(..) => {
6785 // For now, assume all these where-clauses
6786 // may give drop implementation capabilty
6787 // to access borrowed data.
6791 ty::Predicate::Trait(ty::Binder(ref t_pred)) => {
6792 let def_id = t_pred.trait_ref.def_id;
6793 if self.trait_items(def_id).len() != 0 {
6794 // If trait has items, assume it adds
6795 // capability to access borrowed data.
6798 // Trait without items is itself
6799 // uninteresting from POV of dropck.
6801 // However, may have parent w/ items;
6802 // so schedule checking of predicates,
6803 items_to_inspect.push(def_id);
6804 // and say "no capability found" for now.
6811 debug!("typ: {:?} has interesting dtor due to generic preds, e.g. {:?}",
6817 seen_items.push(item_def_id);
6820 debug!("typ: {:?} is dtorck-safe", adt);
6825 /// The category of explicit self.
6826 #[derive(Clone, Copy, Eq, PartialEq, Debug)]
6827 pub enum ExplicitSelfCategory {
6828 StaticExplicitSelfCategory,
6829 ByValueExplicitSelfCategory,
6830 ByReferenceExplicitSelfCategory(Region, hir::Mutability),
6831 ByBoxExplicitSelfCategory,
6834 /// A free variable referred to in a function.
6835 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
6836 pub struct Freevar {
6837 /// The variable being accessed free.
6840 // First span where it is accessed (there can be multiple).
6844 pub type FreevarMap = NodeMap<Vec<Freevar>>;
6846 pub type CaptureModeMap = NodeMap<hir::CaptureClause>;
6848 // Trait method resolution
6849 pub type TraitMap = NodeMap<Vec<DefId>>;
6851 // Map from the NodeId of a glob import to a list of items which are actually
6853 pub type GlobMap = HashMap<NodeId, HashSet<Name>>;
6855 impl<'tcx> AutoAdjustment<'tcx> {
6856 pub fn is_identity(&self) -> bool {
6858 AdjustReifyFnPointer |
6859 AdjustUnsafeFnPointer => false,
6860 AdjustDerefRef(ref r) => r.is_identity(),
6865 impl<'tcx> AutoDerefRef<'tcx> {
6866 pub fn is_identity(&self) -> bool {
6867 self.autoderefs == 0 && self.unsize.is_none() && self.autoref.is_none()
6871 impl<'tcx> ctxt<'tcx> {
6872 pub fn with_freevars<T, F>(&self, fid: NodeId, f: F) -> T where
6873 F: FnOnce(&[Freevar]) -> T,
6875 match self.freevars.borrow().get(&fid) {
6877 Some(d) => f(&d[..])
6881 /// Replace any late-bound regions bound in `value` with free variants attached to scope-id
6883 pub fn liberate_late_bound_regions<T>(&self,
6884 all_outlive_scope: region::CodeExtent,
6887 where T : TypeFoldable<'tcx>
6889 fold::replace_late_bound_regions(
6891 |br| ty::ReFree(ty::FreeRegion{scope: all_outlive_scope, bound_region: br})).0
6894 /// Flattens two binding levels into one. So `for<'a> for<'b> Foo`
6895 /// becomes `for<'a,'b> Foo`.
6896 pub fn flatten_late_bound_regions<T>(&self, bound2_value: &Binder<Binder<T>>)
6898 where T: TypeFoldable<'tcx>
6900 let bound0_value = bound2_value.skip_binder().skip_binder();
6901 let value = fold::fold_regions(self, bound0_value, &mut false,
6902 |region, current_depth| {
6904 ty::ReLateBound(debruijn, br) if debruijn.depth >= current_depth => {
6905 // should be true if no escaping regions from bound2_value
6906 assert!(debruijn.depth - current_depth <= 1);
6907 ty::ReLateBound(DebruijnIndex::new(current_depth), br)
6917 pub fn no_late_bound_regions<T>(&self, value: &Binder<T>) -> Option<T>
6918 where T : TypeFoldable<'tcx> + RegionEscape
6920 if value.0.has_escaping_regions() {
6923 Some(value.0.clone())
6927 /// Replace any late-bound regions bound in `value` with `'static`. Useful in trans but also
6928 /// method lookup and a few other places where precise region relationships are not required.
6929 pub fn erase_late_bound_regions<T>(&self, value: &Binder<T>) -> T
6930 where T : TypeFoldable<'tcx>
6932 fold::replace_late_bound_regions(self, value, |_| ty::ReStatic).0
6935 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
6936 /// assigned starting at 1 and increasing monotonically in the order traversed
6937 /// by the fold operation.
6939 /// The chief purpose of this function is to canonicalize regions so that two
6940 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
6941 /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
6942 /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
6943 pub fn anonymize_late_bound_regions<T>(&self, sig: &Binder<T>) -> Binder<T>
6944 where T : TypeFoldable<'tcx>,
6946 let mut counter = 0;
6947 ty::Binder(fold::replace_late_bound_regions(self, sig, |_| {
6949 ReLateBound(ty::DebruijnIndex::new(1), BrAnon(counter))
6953 pub fn make_substs_for_receiver_types(&self,
6954 trait_ref: &ty::TraitRef<'tcx>,
6955 method: &ty::Method<'tcx>)
6956 -> subst::Substs<'tcx>
6959 * Substitutes the values for the receiver's type parameters
6960 * that are found in method, leaving the method's type parameters
6964 let meth_tps: Vec<Ty> =
6965 method.generics.types.get_slice(subst::FnSpace)
6967 .map(|def| self.mk_param_from_def(def))
6969 let meth_regions: Vec<ty::Region> =
6970 method.generics.regions.get_slice(subst::FnSpace)
6972 .map(|def| def.to_early_bound_region())
6974 trait_ref.substs.clone().with_method(meth_tps, meth_regions)
6978 impl DebruijnIndex {
6979 pub fn new(depth: u32) -> DebruijnIndex {
6981 DebruijnIndex { depth: depth }
6984 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
6985 DebruijnIndex { depth: self.depth + amount }
6989 impl<'tcx> fmt::Debug for AutoAdjustment<'tcx> {
6990 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6992 AdjustReifyFnPointer => {
6993 write!(f, "AdjustReifyFnPointer")
6995 AdjustUnsafeFnPointer => {
6996 write!(f, "AdjustUnsafeFnPointer")
6998 AdjustDerefRef(ref data) => {
6999 write!(f, "{:?}", data)
7005 impl<'tcx> fmt::Debug for AutoDerefRef<'tcx> {
7006 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7007 write!(f, "AutoDerefRef({}, unsize={:?}, {:?})",
7008 self.autoderefs, self.unsize, self.autoref)
7012 impl<'tcx> fmt::Debug for TraitTy<'tcx> {
7013 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7014 write!(f, "TraitTy({:?},{:?})",
7020 impl<'tcx> fmt::Debug for ty::Predicate<'tcx> {
7021 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7023 Predicate::Trait(ref a) => write!(f, "{:?}", a),
7024 Predicate::Equate(ref pair) => write!(f, "{:?}", pair),
7025 Predicate::RegionOutlives(ref pair) => write!(f, "{:?}", pair),
7026 Predicate::TypeOutlives(ref pair) => write!(f, "{:?}", pair),
7027 Predicate::Projection(ref pair) => write!(f, "{:?}", pair),
7028 Predicate::WellFormed(ty) => write!(f, "WF({:?})", ty),
7029 Predicate::ObjectSafe(trait_def_id) => write!(f, "ObjectSafe({:?})", trait_def_id),
7034 // FIXME(#20298) -- all of these traits basically walk various
7035 // structures to test whether types/regions are reachable with various
7036 // properties. It should be possible to express them in terms of one
7037 // common "walker" trait or something.
7039 /// An "escaping region" is a bound region whose binder is not part of `t`.
7041 /// So, for example, consider a type like the following, which has two binders:
7043 /// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
7044 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
7045 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
7047 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
7048 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
7049 /// fn type*, that type has an escaping region: `'a`.
7051 /// Note that what I'm calling an "escaping region" is often just called a "free region". However,
7052 /// we already use the term "free region". It refers to the regions that we use to represent bound
7053 /// regions on a fn definition while we are typechecking its body.
7055 /// To clarify, conceptually there is no particular difference between an "escaping" region and a
7056 /// "free" region. However, there is a big difference in practice. Basically, when "entering" a
7057 /// binding level, one is generally required to do some sort of processing to a bound region, such
7058 /// as replacing it with a fresh/skolemized region, or making an entry in the environment to
7059 /// represent the scope to which it is attached, etc. An escaping region represents a bound region
7060 /// for which this processing has not yet been done.
7061 pub trait RegionEscape {
7062 fn has_escaping_regions(&self) -> bool {
7063 self.has_regions_escaping_depth(0)
7066 fn has_regions_escaping_depth(&self, depth: u32) -> bool;
7069 impl<'tcx> RegionEscape for Ty<'tcx> {
7070 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7071 self.region_depth > depth
7075 impl<'tcx> RegionEscape for TraitTy<'tcx> {
7076 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7077 self.principal.has_regions_escaping_depth(depth) ||
7078 self.bounds.has_regions_escaping_depth(depth)
7082 impl<'tcx> RegionEscape for ExistentialBounds<'tcx> {
7083 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7084 self.region_bound.has_regions_escaping_depth(depth) ||
7085 self.projection_bounds.has_regions_escaping_depth(depth)
7089 impl<'tcx> RegionEscape for Substs<'tcx> {
7090 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7091 self.types.has_regions_escaping_depth(depth) ||
7092 self.regions.has_regions_escaping_depth(depth)
7096 impl<'tcx> RegionEscape for ClosureSubsts<'tcx> {
7097 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7098 self.func_substs.has_regions_escaping_depth(depth) ||
7099 self.upvar_tys.iter().any(|t| t.has_regions_escaping_depth(depth))
7103 impl<T:RegionEscape> RegionEscape for Vec<T> {
7104 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7105 self.iter().any(|t| t.has_regions_escaping_depth(depth))
7109 impl<'tcx> RegionEscape for FnSig<'tcx> {
7110 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7111 self.inputs.has_regions_escaping_depth(depth) ||
7112 self.output.has_regions_escaping_depth(depth)
7116 impl<'tcx,T:RegionEscape> RegionEscape for VecPerParamSpace<T> {
7117 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7118 self.iter_enumerated().any(|(space, _, t)| {
7119 if space == subst::FnSpace {
7120 t.has_regions_escaping_depth(depth+1)
7122 t.has_regions_escaping_depth(depth)
7128 impl<'tcx> RegionEscape for TypeScheme<'tcx> {
7129 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7130 self.ty.has_regions_escaping_depth(depth)
7134 impl RegionEscape for Region {
7135 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7136 self.escapes_depth(depth)
7140 impl<'tcx> RegionEscape for GenericPredicates<'tcx> {
7141 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7142 self.predicates.has_regions_escaping_depth(depth)
7146 impl<'tcx> RegionEscape for Predicate<'tcx> {
7147 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7149 Predicate::Trait(ref data) => data.has_regions_escaping_depth(depth),
7150 Predicate::Equate(ref data) => data.has_regions_escaping_depth(depth),
7151 Predicate::RegionOutlives(ref data) => data.has_regions_escaping_depth(depth),
7152 Predicate::TypeOutlives(ref data) => data.has_regions_escaping_depth(depth),
7153 Predicate::Projection(ref data) => data.has_regions_escaping_depth(depth),
7154 Predicate::WellFormed(ty) => ty.has_regions_escaping_depth(depth),
7155 Predicate::ObjectSafe(_trait_def_id) => false,
7160 impl<'tcx,P:RegionEscape> RegionEscape for traits::Obligation<'tcx,P> {
7161 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7162 self.predicate.has_regions_escaping_depth(depth)
7166 impl<'tcx> RegionEscape for TraitRef<'tcx> {
7167 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7168 self.substs.types.iter().any(|t| t.has_regions_escaping_depth(depth)) ||
7169 self.substs.regions.has_regions_escaping_depth(depth)
7173 impl<'tcx> RegionEscape for subst::RegionSubsts {
7174 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7176 subst::ErasedRegions => false,
7177 subst::NonerasedRegions(ref r) => {
7178 r.iter().any(|t| t.has_regions_escaping_depth(depth))
7184 impl<'tcx,T:RegionEscape> RegionEscape for Binder<T> {
7185 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7186 self.0.has_regions_escaping_depth(depth + 1)
7190 impl<'tcx> RegionEscape for FnOutput<'tcx> {
7191 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7193 FnConverging(t) => t.has_regions_escaping_depth(depth),
7194 FnDiverging => false
7199 impl<'tcx> RegionEscape for EquatePredicate<'tcx> {
7200 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7201 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7205 impl<'tcx> RegionEscape for TraitPredicate<'tcx> {
7206 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7207 self.trait_ref.has_regions_escaping_depth(depth)
7211 impl<T:RegionEscape,U:RegionEscape> RegionEscape for OutlivesPredicate<T,U> {
7212 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7213 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7217 impl<'tcx> RegionEscape for ProjectionPredicate<'tcx> {
7218 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7219 self.projection_ty.has_regions_escaping_depth(depth) ||
7220 self.ty.has_regions_escaping_depth(depth)
7224 impl<'tcx> RegionEscape for ProjectionTy<'tcx> {
7225 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7226 self.trait_ref.has_regions_escaping_depth(depth)
7230 pub trait HasTypeFlags {
7231 fn has_type_flags(&self, flags: TypeFlags) -> bool;
7232 fn has_projection_types(&self) -> bool {
7233 self.has_type_flags(TypeFlags::HAS_PROJECTION)
7235 fn references_error(&self) -> bool {
7236 self.has_type_flags(TypeFlags::HAS_TY_ERR)
7238 fn has_param_types(&self) -> bool {
7239 self.has_type_flags(TypeFlags::HAS_PARAMS)
7241 fn has_self_ty(&self) -> bool {
7242 self.has_type_flags(TypeFlags::HAS_SELF)
7244 fn has_infer_types(&self) -> bool {
7245 self.has_type_flags(TypeFlags::HAS_TY_INFER)
7247 fn needs_infer(&self) -> bool {
7248 self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_RE_INFER)
7250 fn needs_subst(&self) -> bool {
7251 self.has_type_flags(TypeFlags::NEEDS_SUBST)
7253 fn has_closure_types(&self) -> bool {
7254 self.has_type_flags(TypeFlags::HAS_TY_CLOSURE)
7256 fn has_erasable_regions(&self) -> bool {
7257 self.has_type_flags(TypeFlags::HAS_RE_EARLY_BOUND |
7258 TypeFlags::HAS_RE_INFER |
7259 TypeFlags::HAS_FREE_REGIONS)
7261 /// Indicates whether this value references only 'global'
7262 /// types/lifetimes that are the same regardless of what fn we are
7263 /// in. This is used for caching. Errs on the side of returning
7265 fn is_global(&self) -> bool {
7266 !self.has_type_flags(TypeFlags::HAS_LOCAL_NAMES)
7270 impl<'tcx,T:HasTypeFlags> HasTypeFlags for Vec<T> {
7271 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7272 self[..].has_type_flags(flags)
7276 impl<'tcx,T:HasTypeFlags> HasTypeFlags for [T] {
7277 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7278 self.iter().any(|p| p.has_type_flags(flags))
7282 impl<'tcx,T:HasTypeFlags> HasTypeFlags for VecPerParamSpace<T> {
7283 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7284 self.iter().any(|p| p.has_type_flags(flags))
7288 impl HasTypeFlags for abi::Abi {
7289 fn has_type_flags(&self, _flags: TypeFlags) -> bool {
7294 impl HasTypeFlags for hir::Unsafety {
7295 fn has_type_flags(&self, _flags: TypeFlags) -> bool {
7300 impl HasTypeFlags for BuiltinBounds {
7301 fn has_type_flags(&self, _flags: TypeFlags) -> bool {
7306 impl<'tcx> HasTypeFlags for ClosureTy<'tcx> {
7307 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7308 self.sig.has_type_flags(flags)
7312 impl<'tcx> HasTypeFlags for ClosureUpvar<'tcx> {
7313 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7314 self.ty.has_type_flags(flags)
7318 impl<'tcx> HasTypeFlags for ExistentialBounds<'tcx> {
7319 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7320 self.projection_bounds.has_type_flags(flags)
7324 impl<'tcx> HasTypeFlags for ty::InstantiatedPredicates<'tcx> {
7325 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7326 self.predicates.has_type_flags(flags)
7330 impl<'tcx> HasTypeFlags for Predicate<'tcx> {
7331 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7333 Predicate::Trait(ref data) => data.has_type_flags(flags),
7334 Predicate::Equate(ref data) => data.has_type_flags(flags),
7335 Predicate::RegionOutlives(ref data) => data.has_type_flags(flags),
7336 Predicate::TypeOutlives(ref data) => data.has_type_flags(flags),
7337 Predicate::Projection(ref data) => data.has_type_flags(flags),
7338 Predicate::WellFormed(data) => data.has_type_flags(flags),
7339 Predicate::ObjectSafe(_trait_def_id) => false,
7344 impl<'tcx> HasTypeFlags for TraitPredicate<'tcx> {
7345 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7346 self.trait_ref.has_type_flags(flags)
7350 impl<'tcx> HasTypeFlags for EquatePredicate<'tcx> {
7351 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7352 self.0.has_type_flags(flags) || self.1.has_type_flags(flags)
7356 impl HasTypeFlags for Region {
7357 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7358 if flags.intersects(TypeFlags::HAS_LOCAL_NAMES) {
7359 // does this represent a region that cannot be named in a global
7360 // way? used in fulfillment caching.
7362 ty::ReStatic | ty::ReEmpty => {}
7366 if flags.intersects(TypeFlags::HAS_RE_INFER) {
7368 ty::ReVar(_) | ty::ReSkolemized(..) => { return true }
7376 impl<T:HasTypeFlags,U:HasTypeFlags> HasTypeFlags for OutlivesPredicate<T,U> {
7377 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7378 self.0.has_type_flags(flags) || self.1.has_type_flags(flags)
7382 impl<'tcx> HasTypeFlags for ProjectionPredicate<'tcx> {
7383 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7384 self.projection_ty.has_type_flags(flags) || self.ty.has_type_flags(flags)
7388 impl<'tcx> HasTypeFlags for ProjectionTy<'tcx> {
7389 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7390 self.trait_ref.has_type_flags(flags)
7394 impl<'tcx> HasTypeFlags for Ty<'tcx> {
7395 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7396 self.flags.get().intersects(flags)
7400 impl<'tcx> HasTypeFlags for TypeAndMut<'tcx> {
7401 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7402 self.ty.has_type_flags(flags)
7406 impl<'tcx> HasTypeFlags for TraitRef<'tcx> {
7407 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7408 self.substs.has_type_flags(flags)
7412 impl<'tcx> HasTypeFlags for subst::Substs<'tcx> {
7413 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7414 self.types.has_type_flags(flags) || match self.regions {
7415 subst::ErasedRegions => false,
7416 subst::NonerasedRegions(ref r) => r.has_type_flags(flags)
7421 impl<'tcx,T> HasTypeFlags for Option<T>
7422 where T : HasTypeFlags
7424 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7425 self.iter().any(|t| t.has_type_flags(flags))
7429 impl<'tcx,T> HasTypeFlags for Rc<T>
7430 where T : HasTypeFlags
7432 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7433 (**self).has_type_flags(flags)
7437 impl<'tcx,T> HasTypeFlags for Box<T>
7438 where T : HasTypeFlags
7440 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7441 (**self).has_type_flags(flags)
7445 impl<T> HasTypeFlags for Binder<T>
7446 where T : HasTypeFlags
7448 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7449 self.0.has_type_flags(flags)
7453 impl<'tcx> HasTypeFlags for FnOutput<'tcx> {
7454 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7456 FnConverging(t) => t.has_type_flags(flags),
7457 FnDiverging => false,
7462 impl<'tcx> HasTypeFlags for FnSig<'tcx> {
7463 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7464 self.inputs.iter().any(|t| t.has_type_flags(flags)) ||
7465 self.output.has_type_flags(flags)
7469 impl<'tcx> HasTypeFlags for BareFnTy<'tcx> {
7470 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7471 self.sig.has_type_flags(flags)
7475 impl<'tcx> HasTypeFlags for ClosureSubsts<'tcx> {
7476 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7477 self.func_substs.has_type_flags(flags) ||
7478 self.upvar_tys.iter().any(|t| t.has_type_flags(flags))
7482 impl<'tcx> fmt::Debug for ClosureTy<'tcx> {
7483 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7484 write!(f, "ClosureTy({},{:?},{})",
7491 impl<'tcx> fmt::Debug for ClosureUpvar<'tcx> {
7492 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7493 write!(f, "ClosureUpvar({:?},{:?})",
7499 impl<'a, 'tcx> fmt::Debug for ParameterEnvironment<'a, 'tcx> {
7500 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7501 write!(f, "ParameterEnvironment(\
7503 implicit_region_bound={:?}, \
7504 caller_bounds={:?})",
7506 self.implicit_region_bound,
7511 impl<'tcx> fmt::Debug for ObjectLifetimeDefault {
7512 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7514 ObjectLifetimeDefault::Ambiguous => write!(f, "Ambiguous"),
7515 ObjectLifetimeDefault::BaseDefault => write!(f, "BaseDefault"),
7516 ObjectLifetimeDefault::Specific(ref r) => write!(f, "{:?}", r),