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;
47 use middle::check_const;
48 use middle::const_eval::{self, ConstVal, ErrKind};
49 use middle::const_eval::EvalHint::UncheckedExprHint;
50 use middle::def::{self, DefMap, ExportMap};
51 use middle::def_id::{DefId, LOCAL_CRATE};
52 use middle::fast_reject;
53 use middle::free_region::FreeRegionMap;
54 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
56 use middle::resolve_lifetime;
58 use middle::infer::type_variable;
60 use middle::region::RegionMaps;
61 use middle::stability;
62 use middle::subst::{self, ParamSpace, Subst, Substs, VecPerParamSpace};
65 use middle::ty_fold::{self, TypeFoldable, TypeFolder};
66 use middle::ty_walk::{self, TypeWalker};
67 use util::common::{memoized, ErrorReported};
68 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet};
69 use util::nodemap::FnvHashMap;
70 use util::num::ToPrimitive;
72 use arena::TypedArena;
73 use std::borrow::{Borrow, Cow};
74 use std::cell::{Cell, RefCell, Ref};
77 use std::hash::{Hash, SipHasher, Hasher};
79 use std::marker::PhantomData;
84 use std::vec::IntoIter;
85 use collections::enum_set::{self, EnumSet, CLike};
86 use core::nonzero::NonZero;
87 use std::collections::{HashMap, HashSet};
88 use rustc_data_structures::ivar;
90 use syntax::ast::{self, CrateNum, Name, NodeId};
91 use syntax::codemap::Span;
92 use syntax::parse::token::{InternedString, special_idents};
95 use rustc_front::hir::{ItemImpl, ItemTrait};
96 use rustc_front::hir::{MutImmutable, MutMutable, Visibility};
97 use rustc_front::attr::{self, AttrMetaMethods, SignedInt, UnsignedInt};
101 pub const INITIAL_DISCRIMINANT_VALUE: Disr = 0;
105 /// The complete set of all analyses described in this module. This is
106 /// produced by the driver and fed to trans and later passes.
107 pub struct CrateAnalysis {
108 pub export_map: ExportMap,
109 pub exported_items: middle::privacy::ExportedItems,
110 pub public_items: middle::privacy::PublicItems,
111 pub reachable: NodeSet,
113 pub glob_map: Option<GlobMap>,
117 #[derive(Copy, Clone)]
124 pub fn is_present(&self) -> bool {
126 TraitDtor(..) => true,
131 pub fn has_drop_flag(&self) -> bool {
134 &TraitDtor(flag) => flag
139 pub trait IntTypeExt {
140 fn to_ty<'tcx>(&self, cx: &ctxt<'tcx>) -> Ty<'tcx>;
141 fn i64_to_disr(&self, val: i64) -> Option<Disr>;
142 fn u64_to_disr(&self, val: u64) -> Option<Disr>;
143 fn disr_incr(&self, val: Disr) -> Option<Disr>;
144 fn disr_string(&self, val: Disr) -> String;
145 fn disr_wrap_incr(&self, val: Option<Disr>) -> Disr;
148 impl IntTypeExt for attr::IntType {
149 fn to_ty<'tcx>(&self, cx: &ctxt<'tcx>) -> Ty<'tcx> {
151 SignedInt(hir::TyI8) => cx.types.i8,
152 SignedInt(hir::TyI16) => cx.types.i16,
153 SignedInt(hir::TyI32) => cx.types.i32,
154 SignedInt(hir::TyI64) => cx.types.i64,
155 SignedInt(hir::TyIs) => cx.types.isize,
156 UnsignedInt(hir::TyU8) => cx.types.u8,
157 UnsignedInt(hir::TyU16) => cx.types.u16,
158 UnsignedInt(hir::TyU32) => cx.types.u32,
159 UnsignedInt(hir::TyU64) => cx.types.u64,
160 UnsignedInt(hir::TyUs) => cx.types.usize,
164 fn i64_to_disr(&self, val: i64) -> Option<Disr> {
166 SignedInt(hir::TyI8) => val.to_i8() .map(|v| v as Disr),
167 SignedInt(hir::TyI16) => val.to_i16() .map(|v| v as Disr),
168 SignedInt(hir::TyI32) => val.to_i32() .map(|v| v as Disr),
169 SignedInt(hir::TyI64) => val.to_i64() .map(|v| v as Disr),
170 UnsignedInt(hir::TyU8) => val.to_u8() .map(|v| v as Disr),
171 UnsignedInt(hir::TyU16) => val.to_u16() .map(|v| v as Disr),
172 UnsignedInt(hir::TyU32) => val.to_u32() .map(|v| v as Disr),
173 UnsignedInt(hir::TyU64) => val.to_u64() .map(|v| v as Disr),
175 UnsignedInt(hir::TyUs) |
176 SignedInt(hir::TyIs) => unreachable!(),
180 fn u64_to_disr(&self, val: u64) -> Option<Disr> {
182 SignedInt(hir::TyI8) => val.to_i8() .map(|v| v as Disr),
183 SignedInt(hir::TyI16) => val.to_i16() .map(|v| v as Disr),
184 SignedInt(hir::TyI32) => val.to_i32() .map(|v| v as Disr),
185 SignedInt(hir::TyI64) => val.to_i64() .map(|v| v as Disr),
186 UnsignedInt(hir::TyU8) => val.to_u8() .map(|v| v as Disr),
187 UnsignedInt(hir::TyU16) => val.to_u16() .map(|v| v as Disr),
188 UnsignedInt(hir::TyU32) => val.to_u32() .map(|v| v as Disr),
189 UnsignedInt(hir::TyU64) => val.to_u64() .map(|v| v as Disr),
191 UnsignedInt(hir::TyUs) |
192 SignedInt(hir::TyIs) => unreachable!(),
196 fn disr_incr(&self, val: Disr) -> Option<Disr> {
198 ($e:expr) => { $e.and_then(|v|v.checked_add(1)).map(|v| v as Disr) }
201 // SignedInt repr means we *want* to reinterpret the bits
202 // treating the highest bit of Disr as a sign-bit, so
203 // cast to i64 before range-checking.
204 SignedInt(hir::TyI8) => add1!((val as i64).to_i8()),
205 SignedInt(hir::TyI16) => add1!((val as i64).to_i16()),
206 SignedInt(hir::TyI32) => add1!((val as i64).to_i32()),
207 SignedInt(hir::TyI64) => add1!(Some(val as i64)),
209 UnsignedInt(hir::TyU8) => add1!(val.to_u8()),
210 UnsignedInt(hir::TyU16) => add1!(val.to_u16()),
211 UnsignedInt(hir::TyU32) => add1!(val.to_u32()),
212 UnsignedInt(hir::TyU64) => add1!(Some(val)),
214 UnsignedInt(hir::TyUs) |
215 SignedInt(hir::TyIs) => unreachable!(),
219 // This returns a String because (1.) it is only used for
220 // rendering an error message and (2.) a string can represent the
221 // full range from `i64::MIN` through `u64::MAX`.
222 fn disr_string(&self, val: Disr) -> String {
224 SignedInt(hir::TyI8) => format!("{}", val as i8 ),
225 SignedInt(hir::TyI16) => format!("{}", val as i16),
226 SignedInt(hir::TyI32) => format!("{}", val as i32),
227 SignedInt(hir::TyI64) => format!("{}", val as i64),
228 UnsignedInt(hir::TyU8) => format!("{}", val as u8 ),
229 UnsignedInt(hir::TyU16) => format!("{}", val as u16),
230 UnsignedInt(hir::TyU32) => format!("{}", val as u32),
231 UnsignedInt(hir::TyU64) => format!("{}", val as u64),
233 UnsignedInt(hir::TyUs) |
234 SignedInt(hir::TyIs) => unreachable!(),
238 fn disr_wrap_incr(&self, val: Option<Disr>) -> Disr {
240 ($e:expr) => { ($e).wrapping_add(1) as Disr }
242 let val = val.unwrap_or(ty::INITIAL_DISCRIMINANT_VALUE);
244 SignedInt(hir::TyI8) => add1!(val as i8 ),
245 SignedInt(hir::TyI16) => add1!(val as i16),
246 SignedInt(hir::TyI32) => add1!(val as i32),
247 SignedInt(hir::TyI64) => add1!(val as i64),
248 UnsignedInt(hir::TyU8) => add1!(val as u8 ),
249 UnsignedInt(hir::TyU16) => add1!(val as u16),
250 UnsignedInt(hir::TyU32) => add1!(val as u32),
251 UnsignedInt(hir::TyU64) => add1!(val as u64),
253 UnsignedInt(hir::TyUs) |
254 SignedInt(hir::TyIs) => unreachable!(),
259 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
260 pub enum ImplOrTraitItemContainer {
261 TraitContainer(DefId),
262 ImplContainer(DefId),
265 impl ImplOrTraitItemContainer {
266 pub fn id(&self) -> DefId {
268 TraitContainer(id) => id,
269 ImplContainer(id) => id,
275 pub enum ImplOrTraitItem<'tcx> {
276 ConstTraitItem(Rc<AssociatedConst<'tcx>>),
277 MethodTraitItem(Rc<Method<'tcx>>),
278 TypeTraitItem(Rc<AssociatedType<'tcx>>),
281 impl<'tcx> ImplOrTraitItem<'tcx> {
282 fn id(&self) -> ImplOrTraitItemId {
284 ConstTraitItem(ref associated_const) => {
285 ConstTraitItemId(associated_const.def_id)
287 MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
288 TypeTraitItem(ref associated_type) => {
289 TypeTraitItemId(associated_type.def_id)
294 pub fn def_id(&self) -> DefId {
296 ConstTraitItem(ref associated_const) => associated_const.def_id,
297 MethodTraitItem(ref method) => method.def_id,
298 TypeTraitItem(ref associated_type) => associated_type.def_id,
302 pub fn name(&self) -> Name {
304 ConstTraitItem(ref associated_const) => associated_const.name,
305 MethodTraitItem(ref method) => method.name,
306 TypeTraitItem(ref associated_type) => associated_type.name,
310 pub fn vis(&self) -> hir::Visibility {
312 ConstTraitItem(ref associated_const) => associated_const.vis,
313 MethodTraitItem(ref method) => method.vis,
314 TypeTraitItem(ref associated_type) => associated_type.vis,
318 pub fn container(&self) -> ImplOrTraitItemContainer {
320 ConstTraitItem(ref associated_const) => associated_const.container,
321 MethodTraitItem(ref method) => method.container,
322 TypeTraitItem(ref associated_type) => associated_type.container,
326 pub fn as_opt_method(&self) -> Option<Rc<Method<'tcx>>> {
328 MethodTraitItem(ref m) => Some((*m).clone()),
334 #[derive(Clone, Copy, Debug)]
335 pub enum ImplOrTraitItemId {
336 ConstTraitItemId(DefId),
337 MethodTraitItemId(DefId),
338 TypeTraitItemId(DefId),
341 impl ImplOrTraitItemId {
342 pub fn def_id(&self) -> DefId {
344 ConstTraitItemId(def_id) => def_id,
345 MethodTraitItemId(def_id) => def_id,
346 TypeTraitItemId(def_id) => def_id,
351 #[derive(Clone, Debug)]
352 pub struct Method<'tcx> {
354 pub generics: Generics<'tcx>,
355 pub predicates: GenericPredicates<'tcx>,
356 pub fty: BareFnTy<'tcx>,
357 pub explicit_self: ExplicitSelfCategory,
358 pub vis: hir::Visibility,
360 pub container: ImplOrTraitItemContainer,
362 // If this method is provided, we need to know where it came from
363 pub provided_source: Option<DefId>
366 impl<'tcx> Method<'tcx> {
367 pub fn new(name: Name,
368 generics: ty::Generics<'tcx>,
369 predicates: GenericPredicates<'tcx>,
371 explicit_self: ExplicitSelfCategory,
372 vis: hir::Visibility,
374 container: ImplOrTraitItemContainer,
375 provided_source: Option<DefId>)
380 predicates: predicates,
382 explicit_self: explicit_self,
385 container: container,
386 provided_source: provided_source
390 pub fn container_id(&self) -> DefId {
391 match self.container {
392 TraitContainer(id) => id,
393 ImplContainer(id) => id,
398 #[derive(Clone, Copy, Debug)]
399 pub struct AssociatedConst<'tcx> {
402 pub vis: hir::Visibility,
404 pub container: ImplOrTraitItemContainer,
405 pub default: Option<DefId>,
408 #[derive(Clone, Copy, Debug)]
409 pub struct AssociatedType<'tcx> {
411 pub ty: Option<Ty<'tcx>>,
412 pub vis: hir::Visibility,
414 pub container: ImplOrTraitItemContainer,
417 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
418 pub struct TypeAndMut<'tcx> {
420 pub mutbl: hir::Mutability,
424 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
425 pub struct ItemVariances {
426 pub types: VecPerParamSpace<Variance>,
427 pub regions: VecPerParamSpace<Variance>,
430 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
432 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
433 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
434 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
435 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
438 impl fmt::Debug for Variance {
439 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
440 f.write_str(match *self {
442 Contravariant => "-",
449 #[derive(Copy, Clone)]
450 pub enum AutoAdjustment<'tcx> {
451 AdjustReifyFnPointer, // go from a fn-item type to a fn-pointer type
452 AdjustUnsafeFnPointer, // go from a safe fn pointer to an unsafe fn pointer
453 AdjustDerefRef(AutoDerefRef<'tcx>),
456 /// Represents coercing a pointer to a different kind of pointer - where 'kind'
457 /// here means either or both of raw vs borrowed vs unique and fat vs thin.
459 /// We transform pointers by following the following steps in order:
460 /// 1. Deref the pointer `self.autoderefs` times (may be 0).
461 /// 2. If `autoref` is `Some(_)`, then take the address and produce either a
462 /// `&` or `*` pointer.
463 /// 3. If `unsize` is `Some(_)`, then apply the unsize transformation,
464 /// which will do things like convert thin pointers to fat
465 /// pointers, or convert structs containing thin pointers to
466 /// structs containing fat pointers, or convert between fat
467 /// pointers. We don't store the details of how the transform is
468 /// done (in fact, we don't know that, because it might depend on
469 /// the precise type parameters). We just store the target
470 /// type. Trans figures out what has to be done at monomorphization
471 /// time based on the precise source/target type at hand.
473 /// To make that more concrete, here are some common scenarios:
475 /// 1. The simplest cases are where the pointer is not adjusted fat vs thin.
476 /// Here the pointer will be dereferenced N times (where a dereference can
477 /// happen to to raw or borrowed pointers or any smart pointer which implements
478 /// Deref, including Box<_>). The number of dereferences is given by
479 /// `autoderefs`. It can then be auto-referenced zero or one times, indicated
480 /// by `autoref`, to either a raw or borrowed pointer. In these cases unsize is
483 /// 2. A thin-to-fat coercon involves unsizing the underlying data. We start
484 /// with a thin pointer, deref a number of times, unsize the underlying data,
485 /// then autoref. The 'unsize' phase may change a fixed length array to a
486 /// dynamically sized one, a concrete object to a trait object, or statically
487 /// sized struct to a dyncamically sized one. E.g., &[i32; 4] -> &[i32] is
492 /// autoderefs: 1, // &[i32; 4] -> [i32; 4]
493 /// autoref: Some(AutoPtr), // [i32] -> &[i32]
494 /// unsize: Some([i32]), // [i32; 4] -> [i32]
498 /// Note that for a struct, the 'deep' unsizing of the struct is not recorded.
499 /// E.g., `struct Foo<T> { x: T }` we can coerce &Foo<[i32; 4]> to &Foo<[i32]>
500 /// The autoderef and -ref are the same as in the above example, but the type
501 /// stored in `unsize` is `Foo<[i32]>`, we don't store any further detail about
502 /// the underlying conversions from `[i32; 4]` to `[i32]`.
504 /// 3. Coercing a `Box<T>` to `Box<Trait>` is an interesting special case. In
505 /// that case, we have the pointer we need coming in, so there are no
506 /// autoderefs, and no autoref. Instead we just do the `Unsize` transformation.
507 /// At some point, of course, `Box` should move out of the compiler, in which
508 /// case this is analogous to transformating a struct. E.g., Box<[i32; 4]> ->
509 /// Box<[i32]> is represented by:
515 /// unsize: Some(Box<[i32]>),
518 #[derive(Copy, Clone)]
519 pub struct AutoDerefRef<'tcx> {
520 /// Step 1. Apply a number of dereferences, producing an lvalue.
521 pub autoderefs: usize,
523 /// Step 2. Optionally produce a pointer/reference from the value.
524 pub autoref: Option<AutoRef<'tcx>>,
526 /// Step 3. Unsize a pointer/reference value, e.g. `&[T; n]` to
527 /// `&[T]`. The stored type is the target pointer type. Note that
528 /// the source could be a thin or fat pointer.
529 pub unsize: Option<Ty<'tcx>>,
532 #[derive(Copy, Clone, PartialEq, Debug)]
533 pub enum AutoRef<'tcx> {
534 /// Convert from T to &T.
535 AutoPtr(&'tcx Region, hir::Mutability),
537 /// Convert from T to *T.
538 /// Value to thin pointer.
539 AutoUnsafe(hir::Mutability),
542 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
543 pub enum CustomCoerceUnsized {
544 /// Records the index of the field being coerced.
548 #[derive(Clone, Copy, Debug)]
549 pub struct MethodCallee<'tcx> {
550 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
553 pub substs: &'tcx subst::Substs<'tcx>
556 /// With method calls, we store some extra information in
557 /// side tables (i.e method_map). We use
558 /// MethodCall as a key to index into these tables instead of
559 /// just directly using the expression's NodeId. The reason
560 /// for this being that we may apply adjustments (coercions)
561 /// with the resulting expression also needing to use the
562 /// side tables. The problem with this is that we don't
563 /// assign a separate NodeId to this new expression
564 /// and so it would clash with the base expression if both
565 /// needed to add to the side tables. Thus to disambiguate
566 /// we also keep track of whether there's an adjustment in
568 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
569 pub struct MethodCall {
575 pub fn expr(id: NodeId) -> MethodCall {
582 pub fn autoderef(expr_id: NodeId, autoderef: u32) -> MethodCall {
585 autoderef: 1 + autoderef
590 // maps from an expression id that corresponds to a method call to the details
591 // of the method to be invoked
592 pub type MethodMap<'tcx> = FnvHashMap<MethodCall, MethodCallee<'tcx>>;
594 // Contains information needed to resolve types and (in the future) look up
595 // the types of AST nodes.
596 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
597 pub struct CReaderCacheKey {
603 /// A restriction that certain types must be the same size. The use of
604 /// `transmute` gives rise to these restrictions. These generally
605 /// cannot be checked until trans; therefore, each call to `transmute`
606 /// will push one or more such restriction into the
607 /// `transmute_restrictions` vector during `intrinsicck`. They are
608 /// then checked during `trans` by the fn `check_intrinsics`.
609 #[derive(Copy, Clone)]
610 pub struct TransmuteRestriction<'tcx> {
611 /// The span whence the restriction comes.
614 /// The type being transmuted from.
615 pub original_from: Ty<'tcx>,
617 /// The type being transmuted to.
618 pub original_to: Ty<'tcx>,
620 /// The type being transmuted from, with all type parameters
621 /// substituted for an arbitrary representative. Not to be shown
623 pub substituted_from: Ty<'tcx>,
625 /// The type being transmuted to, with all type parameters
626 /// substituted for an arbitrary representative. Not to be shown
628 pub substituted_to: Ty<'tcx>,
630 /// NodeId of the transmute intrinsic.
635 pub struct CtxtArenas<'tcx> {
637 type_: TypedArena<TyS<'tcx>>,
638 substs: TypedArena<Substs<'tcx>>,
639 bare_fn: TypedArena<BareFnTy<'tcx>>,
640 region: TypedArena<Region>,
641 stability: TypedArena<attr::Stability>,
644 trait_defs: TypedArena<TraitDef<'tcx>>,
645 adt_defs: TypedArena<AdtDefData<'tcx, 'tcx>>,
648 impl<'tcx> CtxtArenas<'tcx> {
649 pub fn new() -> CtxtArenas<'tcx> {
651 type_: TypedArena::new(),
652 substs: TypedArena::new(),
653 bare_fn: TypedArena::new(),
654 region: TypedArena::new(),
655 stability: TypedArena::new(),
657 trait_defs: TypedArena::new(),
658 adt_defs: TypedArena::new()
663 pub struct CommonTypes<'tcx> {
681 pub struct Tables<'tcx> {
682 /// Stores the types for various nodes in the AST. Note that this table
683 /// is not guaranteed to be populated until after typeck. See
684 /// typeck::check::fn_ctxt for details.
685 pub node_types: NodeMap<Ty<'tcx>>,
687 /// Stores the type parameters which were substituted to obtain the type
688 /// of this node. This only applies to nodes that refer to entities
689 /// parameterized by type parameters, such as generic fns, types, or
691 pub item_substs: NodeMap<ItemSubsts<'tcx>>,
693 pub adjustments: NodeMap<ty::AutoAdjustment<'tcx>>,
695 pub method_map: MethodMap<'tcx>,
698 pub upvar_capture_map: UpvarCaptureMap,
700 /// Records the type of each closure. The def ID is the ID of the
701 /// expression defining the closure.
702 pub closure_tys: DefIdMap<ClosureTy<'tcx>>,
704 /// Records the type of each closure. The def ID is the ID of the
705 /// expression defining the closure.
706 pub closure_kinds: DefIdMap<ClosureKind>,
709 impl<'tcx> Tables<'tcx> {
710 pub fn empty() -> Tables<'tcx> {
712 node_types: FnvHashMap(),
713 item_substs: NodeMap(),
714 adjustments: NodeMap(),
715 method_map: FnvHashMap(),
716 upvar_capture_map: FnvHashMap(),
717 closure_tys: DefIdMap(),
718 closure_kinds: DefIdMap(),
723 /// The data structure to keep track of all the information that typechecker
724 /// generates so that so that it can be reused and doesn't have to be redone
726 pub struct ctxt<'tcx> {
727 /// The arenas that types etc are allocated from.
728 arenas: &'tcx CtxtArenas<'tcx>,
730 /// Specifically use a speedy hash algorithm for this hash map, it's used
732 // FIXME(eddyb) use a FnvHashSet<InternedTy<'tcx>> when equivalent keys can
733 // queried from a HashSet.
734 interner: RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>,
736 // FIXME as above, use a hashset if equivalent elements can be queried.
737 substs_interner: RefCell<FnvHashMap<&'tcx Substs<'tcx>, &'tcx Substs<'tcx>>>,
738 bare_fn_interner: RefCell<FnvHashMap<&'tcx BareFnTy<'tcx>, &'tcx BareFnTy<'tcx>>>,
739 region_interner: RefCell<FnvHashMap<&'tcx Region, &'tcx Region>>,
740 stability_interner: RefCell<FnvHashMap<&'tcx attr::Stability, &'tcx attr::Stability>>,
742 /// Common types, pre-interned for your convenience.
743 pub types: CommonTypes<'tcx>,
748 pub named_region_map: resolve_lifetime::NamedRegionMap,
750 pub region_maps: RegionMaps,
752 // For each fn declared in the local crate, type check stores the
753 // free-region relationships that were deduced from its where
754 // clauses and parameter types. These are then read-again by
755 // borrowck. (They are not used during trans, and hence are not
756 // serialized or needed for cross-crate fns.)
757 free_region_maps: RefCell<NodeMap<FreeRegionMap>>,
758 // FIXME: jroesch make this a refcell
760 pub tables: RefCell<Tables<'tcx>>,
762 /// Maps from a trait item to the trait item "descriptor"
763 pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem<'tcx>>>,
765 /// Maps from a trait def-id to a list of the def-ids of its trait items
766 pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
768 /// A cache for the trait_items() routine
769 pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem<'tcx>>>>>,
771 pub impl_trait_refs: RefCell<DefIdMap<Option<TraitRef<'tcx>>>>,
772 pub trait_defs: RefCell<DefIdMap<&'tcx TraitDef<'tcx>>>,
773 pub adt_defs: RefCell<DefIdMap<AdtDefMaster<'tcx>>>,
775 /// Maps from the def-id of an item (trait/struct/enum/fn) to its
776 /// associated predicates.
777 pub predicates: RefCell<DefIdMap<GenericPredicates<'tcx>>>,
779 /// Maps from the def-id of a trait to the list of
780 /// super-predicates. This is a subset of the full list of
781 /// predicates. We store these in a separate map because we must
782 /// evaluate them even during type conversion, often before the
783 /// full predicates are available (note that supertraits have
784 /// additional acyclicity requirements).
785 pub super_predicates: RefCell<DefIdMap<GenericPredicates<'tcx>>>,
787 pub map: ast_map::Map<'tcx>,
788 pub freevars: RefCell<FreevarMap>,
789 pub tcache: RefCell<DefIdMap<TypeScheme<'tcx>>>,
790 pub rcache: RefCell<FnvHashMap<CReaderCacheKey, Ty<'tcx>>>,
791 pub tc_cache: RefCell<FnvHashMap<Ty<'tcx>, TypeContents>>,
792 pub ast_ty_to_ty_cache: RefCell<NodeMap<Ty<'tcx>>>,
793 pub ty_param_defs: RefCell<NodeMap<TypeParameterDef<'tcx>>>,
794 pub normalized_cache: RefCell<FnvHashMap<Ty<'tcx>, Ty<'tcx>>>,
795 pub lang_items: middle::lang_items::LanguageItems,
796 /// A mapping of fake provided method def_ids to the default implementation
797 pub provided_method_sources: RefCell<DefIdMap<DefId>>,
799 /// Maps from def-id of a type or region parameter to its
800 /// (inferred) variance.
801 pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
803 /// True if the variance has been computed yet; false otherwise.
804 pub variance_computed: Cell<bool>,
806 /// A method will be in this list if and only if it is a destructor.
807 pub destructors: RefCell<DefIdSet>,
809 /// Maps a DefId of a type to a list of its inherent impls.
810 /// Contains implementations of methods that are inherent to a type.
811 /// Methods in these implementations don't need to be exported.
812 pub inherent_impls: RefCell<DefIdMap<Rc<Vec<DefId>>>>,
814 /// Maps a DefId of an impl to a list of its items.
815 /// Note that this contains all of the impls that we know about,
816 /// including ones in other crates. It's not clear that this is the best
818 pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
820 /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
821 /// present in this set can be warned about.
822 pub used_unsafe: RefCell<NodeSet>,
824 /// Set of nodes which mark locals as mutable which end up getting used at
825 /// some point. Local variable definitions not in this set can be warned
827 pub used_mut_nodes: RefCell<NodeSet>,
829 /// The set of external nominal types whose implementations have been read.
830 /// This is used for lazy resolution of methods.
831 pub populated_external_types: RefCell<DefIdSet>,
832 /// The set of external primitive types whose implementations have been read.
833 /// FIXME(arielb1): why is this separate from populated_external_types?
834 pub populated_external_primitive_impls: RefCell<DefIdSet>,
836 /// These caches are used by const_eval when decoding external constants.
837 pub extern_const_statics: RefCell<DefIdMap<NodeId>>,
838 pub extern_const_variants: RefCell<DefIdMap<NodeId>>,
839 pub extern_const_fns: RefCell<DefIdMap<NodeId>>,
841 pub node_lint_levels: RefCell<FnvHashMap<(NodeId, lint::LintId),
844 /// The types that must be asserted to be the same size for `transmute`
845 /// to be valid. We gather up these restrictions in the intrinsicck pass
846 /// and check them in trans.
847 pub transmute_restrictions: RefCell<Vec<TransmuteRestriction<'tcx>>>,
849 /// Maps any item's def-id to its stability index.
850 pub stability: RefCell<stability::Index<'tcx>>,
852 /// Caches the results of trait selection. This cache is used
853 /// for things that do not have to do with the parameters in scope.
854 pub selection_cache: traits::SelectionCache<'tcx>,
856 /// A set of predicates that have been fulfilled *somewhere*.
857 /// This is used to avoid duplicate work. Predicates are only
858 /// added to this set when they mention only "global" names
859 /// (i.e., no type or lifetime parameters).
860 pub fulfilled_predicates: RefCell<traits::FulfilledPredicates<'tcx>>,
862 /// Caches the representation hints for struct definitions.
863 pub repr_hint_cache: RefCell<DefIdMap<Rc<Vec<attr::ReprAttr>>>>,
865 /// Maps Expr NodeId's to their constant qualification.
866 pub const_qualif_map: RefCell<NodeMap<check_const::ConstQualif>>,
868 /// Caches CoerceUnsized kinds for impls on custom types.
869 pub custom_coerce_unsized_kinds: RefCell<DefIdMap<CustomCoerceUnsized>>,
871 /// Maps a cast expression to its kind. This is keyed on the
872 /// *from* expression of the cast, not the cast itself.
873 pub cast_kinds: RefCell<NodeMap<cast::CastKind>>,
875 /// Maps Fn items to a collection of fragment infos.
877 /// The main goal is to identify data (each of which may be moved
878 /// or assigned) whose subparts are not moved nor assigned
879 /// (i.e. their state is *unfragmented*) and corresponding ast
880 /// nodes where the path to that data is moved or assigned.
882 /// In the long term, unfragmented values will have their
883 /// destructor entirely driven by a single stack-local drop-flag,
884 /// and their parents, the collections of the unfragmented values
885 /// (or more simply, "fragmented values"), are mapped to the
886 /// corresponding collections of stack-local drop-flags.
888 /// (However, in the short term that is not the case; e.g. some
889 /// unfragmented paths still need to be zeroed, namely when they
890 /// reference parent data from an outer scope that was not
891 /// entirely moved, and therefore that needs to be zeroed so that
892 /// we do not get double-drop when we hit the end of the parent
895 /// Also: currently the table solely holds keys for node-ids of
896 /// unfragmented values (see `FragmentInfo` enum definition), but
897 /// longer-term we will need to also store mappings from
898 /// fragmented data to the set of unfragmented pieces that
900 pub fragment_infos: RefCell<DefIdMap<Vec<FragmentInfo>>>,
903 /// Describes the fragment-state associated with a NodeId.
905 /// Currently only unfragmented paths have entries in the table,
906 /// but longer-term this enum is expected to expand to also
907 /// include data for fragmented paths.
908 #[derive(Copy, Clone, Debug)]
909 pub enum FragmentInfo {
910 Moved { var: NodeId, move_expr: NodeId },
911 Assigned { var: NodeId, assign_expr: NodeId, assignee_id: NodeId },
914 impl<'tcx> ctxt<'tcx> {
915 pub fn node_types(&self) -> Ref<NodeMap<Ty<'tcx>>> {
916 fn projection<'a, 'tcx>(tables: &'a Tables<'tcx>) -> &'a NodeMap<Ty<'tcx>> {
920 Ref::map(self.tables.borrow(), projection)
923 pub fn node_type_insert(&self, id: NodeId, ty: Ty<'tcx>) {
924 self.tables.borrow_mut().node_types.insert(id, ty);
927 pub fn intern_trait_def(&self, def: TraitDef<'tcx>) -> &'tcx TraitDef<'tcx> {
928 let did = def.trait_ref.def_id;
929 let interned = self.arenas.trait_defs.alloc(def);
930 self.trait_defs.borrow_mut().insert(did, interned);
934 pub fn intern_adt_def(&self,
937 variants: Vec<VariantDefData<'tcx, 'tcx>>)
938 -> AdtDefMaster<'tcx> {
939 let def = AdtDefData::new(self, did, kind, variants);
940 let interned = self.arenas.adt_defs.alloc(def);
941 // this will need a transmute when reverse-variance is removed
942 self.adt_defs.borrow_mut().insert(did, interned);
946 pub fn intern_stability(&self, stab: attr::Stability) -> &'tcx attr::Stability {
947 if let Some(st) = self.stability_interner.borrow().get(&stab) {
951 let interned = self.arenas.stability.alloc(stab);
952 self.stability_interner.borrow_mut().insert(interned, interned);
956 pub fn store_free_region_map(&self, id: NodeId, map: FreeRegionMap) {
957 self.free_region_maps.borrow_mut()
961 pub fn free_region_map(&self, id: NodeId) -> FreeRegionMap {
962 self.free_region_maps.borrow()[&id].clone()
965 pub fn lift<T: ?Sized + Lift<'tcx>>(&self, value: &T) -> Option<T::Lifted> {
966 value.lift_to_tcx(self)
970 /// A trait implemented for all X<'a> types which can be safely and
971 /// efficiently converted to X<'tcx> as long as they are part of the
972 /// provided ty::ctxt<'tcx>.
973 /// This can be done, for example, for Ty<'tcx> or &'tcx Substs<'tcx>
974 /// by looking them up in their respective interners.
975 /// None is returned if the value or one of the components is not part
976 /// of the provided context.
977 /// For Ty, None can be returned if either the type interner doesn't
978 /// contain the TypeVariants key or if the address of the interned
979 /// pointer differs. The latter case is possible if a primitive type,
980 /// e.g. `()` or `u8`, was interned in a different context.
981 pub trait Lift<'tcx> {
983 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted>;
986 impl<'tcx, A: Lift<'tcx>, B: Lift<'tcx>> Lift<'tcx> for (A, B) {
987 type Lifted = (A::Lifted, B::Lifted);
988 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
989 tcx.lift(&self.0).and_then(|a| tcx.lift(&self.1).map(|b| (a, b)))
993 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for [T] {
994 type Lifted = Vec<T::Lifted>;
995 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
996 let mut result = Vec::with_capacity(self.len());
998 if let Some(value) = tcx.lift(x) {
1008 impl<'tcx> Lift<'tcx> for Region {
1010 fn lift_to_tcx(&self, _: &ctxt<'tcx>) -> Option<Region> {
1015 impl<'a, 'tcx> Lift<'tcx> for Ty<'a> {
1016 type Lifted = Ty<'tcx>;
1017 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Ty<'tcx>> {
1018 if let Some(&ty) = tcx.interner.borrow().get(&self.sty) {
1019 if *self as *const _ == ty as *const _ {
1027 impl<'a, 'tcx> Lift<'tcx> for &'a Substs<'a> {
1028 type Lifted = &'tcx Substs<'tcx>;
1029 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<&'tcx Substs<'tcx>> {
1030 if let Some(&substs) = tcx.substs_interner.borrow().get(*self) {
1031 if *self as *const _ == substs as *const _ {
1032 return Some(substs);
1039 impl<'a, 'tcx> Lift<'tcx> for TraitRef<'a> {
1040 type Lifted = TraitRef<'tcx>;
1041 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<TraitRef<'tcx>> {
1042 tcx.lift(&self.substs).map(|substs| TraitRef {
1043 def_id: self.def_id,
1049 impl<'a, 'tcx> Lift<'tcx> for TraitPredicate<'a> {
1050 type Lifted = TraitPredicate<'tcx>;
1051 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<TraitPredicate<'tcx>> {
1052 tcx.lift(&self.trait_ref).map(|trait_ref| TraitPredicate {
1053 trait_ref: trait_ref
1058 impl<'a, 'tcx> Lift<'tcx> for EquatePredicate<'a> {
1059 type Lifted = EquatePredicate<'tcx>;
1060 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<EquatePredicate<'tcx>> {
1061 tcx.lift(&(self.0, self.1)).map(|(a, b)| EquatePredicate(a, b))
1065 impl<'tcx, A: Copy+Lift<'tcx>, B: Copy+Lift<'tcx>> Lift<'tcx> for OutlivesPredicate<A, B> {
1066 type Lifted = OutlivesPredicate<A::Lifted, B::Lifted>;
1067 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
1068 tcx.lift(&(self.0, self.1)).map(|(a, b)| OutlivesPredicate(a, b))
1072 impl<'a, 'tcx> Lift<'tcx> for ProjectionPredicate<'a> {
1073 type Lifted = ProjectionPredicate<'tcx>;
1074 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<ProjectionPredicate<'tcx>> {
1075 tcx.lift(&(self.projection_ty.trait_ref, self.ty)).map(|(trait_ref, ty)| {
1076 ProjectionPredicate {
1077 projection_ty: ProjectionTy {
1078 trait_ref: trait_ref,
1079 item_name: self.projection_ty.item_name
1087 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Binder<T> {
1088 type Lifted = Binder<T::Lifted>;
1089 fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option<Self::Lifted> {
1090 tcx.lift(&self.0).map(|x| Binder(x))
1096 use session::Session;
1099 use syntax::codemap;
1101 /// Marker type used for the scoped TLS slot.
1102 /// The type context cannot be used directly because the scoped TLS
1103 /// in libstd doesn't allow types generic over lifetimes.
1104 struct ThreadLocalTyCx;
1106 scoped_thread_local!(static TLS_TCX: ThreadLocalTyCx);
1108 fn span_debug(span: codemap::Span, f: &mut fmt::Formatter) -> fmt::Result {
1110 write!(f, "{}", tcx.sess.codemap().span_to_string(span))
1114 pub fn enter<'tcx, F: FnOnce(&ty::ctxt<'tcx>) -> R, R>(tcx: ty::ctxt<'tcx>, f: F)
1116 let result = codemap::SPAN_DEBUG.with(|span_dbg| {
1117 let original_span_debug = span_dbg.get();
1118 span_dbg.set(span_debug);
1119 let tls_ptr = &tcx as *const _ as *const ThreadLocalTyCx;
1120 let result = TLS_TCX.set(unsafe { &*tls_ptr }, || f(&tcx));
1121 span_dbg.set(original_span_debug);
1127 pub fn with<F: FnOnce(&ty::ctxt) -> R, R>(f: F) -> R {
1128 TLS_TCX.with(|tcx| f(unsafe { &*(tcx as *const _ as *const ty::ctxt) }))
1131 pub fn with_opt<F: FnOnce(Option<&ty::ctxt>) -> R, R>(f: F) -> R {
1132 if TLS_TCX.is_set() {
1133 with(|v| f(Some(v)))
1140 // Flags that we track on types. These flags are propagated upwards
1141 // through the type during type construction, so that we can quickly
1142 // check whether the type has various kinds of types in it without
1143 // recursing over the type itself.
1145 flags TypeFlags: u32 {
1146 const HAS_PARAMS = 1 << 0,
1147 const HAS_SELF = 1 << 1,
1148 const HAS_TY_INFER = 1 << 2,
1149 const HAS_RE_INFER = 1 << 3,
1150 const HAS_RE_EARLY_BOUND = 1 << 4,
1151 const HAS_FREE_REGIONS = 1 << 5,
1152 const HAS_TY_ERR = 1 << 6,
1153 const HAS_PROJECTION = 1 << 7,
1154 const HAS_TY_CLOSURE = 1 << 8,
1156 // true if there are "names" of types and regions and so forth
1157 // that are local to a particular fn
1158 const HAS_LOCAL_NAMES = 1 << 9,
1160 const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
1161 TypeFlags::HAS_SELF.bits |
1162 TypeFlags::HAS_RE_EARLY_BOUND.bits,
1164 // Flags representing the nominal content of a type,
1165 // computed by FlagsComputation. If you add a new nominal
1166 // flag, it should be added here too.
1167 const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
1168 TypeFlags::HAS_SELF.bits |
1169 TypeFlags::HAS_TY_INFER.bits |
1170 TypeFlags::HAS_RE_INFER.bits |
1171 TypeFlags::HAS_RE_EARLY_BOUND.bits |
1172 TypeFlags::HAS_FREE_REGIONS.bits |
1173 TypeFlags::HAS_TY_ERR.bits |
1174 TypeFlags::HAS_PROJECTION.bits |
1175 TypeFlags::HAS_TY_CLOSURE.bits |
1176 TypeFlags::HAS_LOCAL_NAMES.bits,
1178 // Caches for type_is_sized, type_moves_by_default
1179 const SIZEDNESS_CACHED = 1 << 16,
1180 const IS_SIZED = 1 << 17,
1181 const MOVENESS_CACHED = 1 << 18,
1182 const MOVES_BY_DEFAULT = 1 << 19,
1186 macro_rules! sty_debug_print {
1187 ($ctxt: expr, $($variant: ident),*) => {{
1188 // curious inner module to allow variant names to be used as
1190 #[allow(non_snake_case)]
1193 #[derive(Copy, Clone)]
1196 region_infer: usize,
1201 pub fn go(tcx: &ty::ctxt) {
1202 let mut total = DebugStat {
1204 region_infer: 0, ty_infer: 0, both_infer: 0,
1206 $(let mut $variant = total;)*
1209 for (_, t) in tcx.interner.borrow().iter() {
1210 let variant = match t.sty {
1211 ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
1212 ty::TyFloat(..) | ty::TyStr => continue,
1213 ty::TyError => /* unimportant */ continue,
1214 $(ty::$variant(..) => &mut $variant,)*
1216 let region = t.flags.get().intersects(ty::TypeFlags::HAS_RE_INFER);
1217 let ty = t.flags.get().intersects(ty::TypeFlags::HAS_TY_INFER);
1221 if region { total.region_infer += 1; variant.region_infer += 1 }
1222 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
1223 if region && ty { total.both_infer += 1; variant.both_infer += 1 }
1225 println!("Ty interner total ty region both");
1226 $(println!(" {:18}: {uses:6} {usespc:4.1}%, \
1227 {ty:4.1}% {region:5.1}% {both:4.1}%",
1228 stringify!($variant),
1229 uses = $variant.total,
1230 usespc = $variant.total as f64 * 100.0 / total.total as f64,
1231 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
1232 region = $variant.region_infer as f64 * 100.0 / total.total as f64,
1233 both = $variant.both_infer as f64 * 100.0 / total.total as f64);
1235 println!(" total {uses:6} \
1236 {ty:4.1}% {region:5.1}% {both:4.1}%",
1238 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
1239 region = total.region_infer as f64 * 100.0 / total.total as f64,
1240 both = total.both_infer as f64 * 100.0 / total.total as f64)
1248 impl<'tcx> ctxt<'tcx> {
1249 pub fn print_debug_stats(&self) {
1252 TyEnum, TyBox, TyArray, TySlice, TyRawPtr, TyRef, TyBareFn, TyTrait,
1253 TyStruct, TyClosure, TyTuple, TyParam, TyInfer, TyProjection);
1255 println!("Substs interner: #{}", self.substs_interner.borrow().len());
1256 println!("BareFnTy interner: #{}", self.bare_fn_interner.borrow().len());
1257 println!("Region interner: #{}", self.region_interner.borrow().len());
1258 println!("Stability interner: #{}", self.stability_interner.borrow().len());
1262 pub struct TyS<'tcx> {
1263 pub sty: TypeVariants<'tcx>,
1264 pub flags: Cell<TypeFlags>,
1266 // the maximal depth of any bound regions appearing in this type.
1270 impl fmt::Debug for TypeFlags {
1271 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1272 write!(f, "{}", self.bits)
1276 impl<'tcx> PartialEq for TyS<'tcx> {
1278 fn eq(&self, other: &TyS<'tcx>) -> bool {
1279 // (self as *const _) == (other as *const _)
1280 (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
1283 impl<'tcx> Eq for TyS<'tcx> {}
1285 impl<'tcx> Hash for TyS<'tcx> {
1286 fn hash<H: Hasher>(&self, s: &mut H) {
1287 (self as *const TyS).hash(s)
1291 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
1293 /// An IVar that contains a Ty. 'lt is a (reverse-variant) upper bound
1294 /// on the lifetime of the IVar. This is required because of variance
1295 /// problems: the IVar needs to be variant with respect to 'tcx (so
1296 /// it can be referred to from Ty) but can only be modified if its
1297 /// lifetime is exactly 'tcx.
1299 /// Safety invariants:
1300 /// (A) self.0, if fulfilled, is a valid Ty<'tcx>
1301 /// (B) no aliases to this value with a 'tcx longer than this
1302 /// value's 'lt exist
1304 /// NonZero is used rather than Unique because Unique isn't Copy.
1305 pub struct TyIVar<'tcx, 'lt: 'tcx>(ivar::Ivar<NonZero<*const TyS<'static>>>,
1306 PhantomData<fn(TyS<'lt>)->TyS<'tcx>>);
1308 impl<'tcx, 'lt> TyIVar<'tcx, 'lt> {
1310 pub fn new() -> Self {
1311 // Invariant (A) satisfied because the IVar is unfulfilled
1312 // Invariant (B) because 'lt : 'tcx
1313 TyIVar(ivar::Ivar::new(), PhantomData)
1317 pub fn get(&self) -> Option<Ty<'tcx>> {
1318 match self.0.get() {
1320 // valid because of invariant (A)
1321 Some(v) => Some(unsafe { &*(*v as *const TyS<'tcx>) })
1325 pub fn unwrap(&self) -> Ty<'tcx> {
1329 pub fn fulfill(&self, value: Ty<'lt>) {
1330 // Invariant (A) is fulfilled, because by (B), every alias
1331 // of this has a 'tcx longer than 'lt.
1332 let value: *const TyS<'lt> = value;
1333 // FIXME(27214): unneeded [as *const ()]
1334 let value = value as *const () as *const TyS<'static>;
1335 self.0.fulfill(unsafe { NonZero::new(value) })
1339 impl<'tcx, 'lt> fmt::Debug for TyIVar<'tcx, 'lt> {
1340 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1342 Some(val) => write!(f, "TyIVar({:?})", val),
1343 None => f.write_str("TyIVar(<unfulfilled>)")
1348 /// An entry in the type interner.
1349 pub struct InternedTy<'tcx> {
1353 // NB: An InternedTy compares and hashes as a sty.
1354 impl<'tcx> PartialEq for InternedTy<'tcx> {
1355 fn eq(&self, other: &InternedTy<'tcx>) -> bool {
1356 self.ty.sty == other.ty.sty
1360 impl<'tcx> Eq for InternedTy<'tcx> {}
1362 impl<'tcx> Hash for InternedTy<'tcx> {
1363 fn hash<H: Hasher>(&self, s: &mut H) {
1368 impl<'tcx> Borrow<TypeVariants<'tcx>> for InternedTy<'tcx> {
1369 fn borrow<'a>(&'a self) -> &'a TypeVariants<'tcx> {
1374 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1375 pub struct BareFnTy<'tcx> {
1376 pub unsafety: hir::Unsafety,
1378 pub sig: PolyFnSig<'tcx>,
1381 #[derive(Clone, PartialEq, Eq, Hash)]
1382 pub struct ClosureTy<'tcx> {
1383 pub unsafety: hir::Unsafety,
1385 pub sig: PolyFnSig<'tcx>,
1388 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1389 pub enum FnOutput<'tcx> {
1390 FnConverging(Ty<'tcx>),
1394 impl<'tcx> FnOutput<'tcx> {
1395 pub fn diverges(&self) -> bool {
1396 *self == FnDiverging
1399 pub fn unwrap(self) -> Ty<'tcx> {
1401 ty::FnConverging(t) => t,
1402 ty::FnDiverging => unreachable!()
1406 pub fn unwrap_or(self, def: Ty<'tcx>) -> Ty<'tcx> {
1408 ty::FnConverging(t) => t,
1409 ty::FnDiverging => def
1414 pub type PolyFnOutput<'tcx> = Binder<FnOutput<'tcx>>;
1416 impl<'tcx> PolyFnOutput<'tcx> {
1417 pub fn diverges(&self) -> bool {
1422 /// Signature of a function type, which I have arbitrarily
1423 /// decided to use to refer to the input/output types.
1425 /// - `inputs` is the list of arguments and their modes.
1426 /// - `output` is the return type.
1427 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
1428 #[derive(Clone, PartialEq, Eq, Hash)]
1429 pub struct FnSig<'tcx> {
1430 pub inputs: Vec<Ty<'tcx>>,
1431 pub output: FnOutput<'tcx>,
1435 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1437 impl<'tcx> PolyFnSig<'tcx> {
1438 pub fn inputs(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
1439 self.map_bound_ref(|fn_sig| fn_sig.inputs.clone())
1441 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
1442 self.map_bound_ref(|fn_sig| fn_sig.inputs[index])
1444 pub fn output(&self) -> ty::Binder<FnOutput<'tcx>> {
1445 self.map_bound_ref(|fn_sig| fn_sig.output.clone())
1447 pub fn variadic(&self) -> bool {
1448 self.skip_binder().variadic
1452 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1453 pub struct ParamTy {
1454 pub space: subst::ParamSpace,
1459 /// A [De Bruijn index][dbi] is a standard means of representing
1460 /// regions (and perhaps later types) in a higher-ranked setting. In
1461 /// particular, imagine a type like this:
1463 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
1466 /// | +------------+ 1 | |
1468 /// +--------------------------------+ 2 |
1470 /// +------------------------------------------+ 1
1472 /// In this type, there are two binders (the outer fn and the inner
1473 /// fn). We need to be able to determine, for any given region, which
1474 /// fn type it is bound by, the inner or the outer one. There are
1475 /// various ways you can do this, but a De Bruijn index is one of the
1476 /// more convenient and has some nice properties. The basic idea is to
1477 /// count the number of binders, inside out. Some examples should help
1478 /// clarify what I mean.
1480 /// Let's start with the reference type `&'b isize` that is the first
1481 /// argument to the inner function. This region `'b` is assigned a De
1482 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
1483 /// fn). The region `'a` that appears in the second argument type (`&'a
1484 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
1485 /// second-innermost binder". (These indices are written on the arrays
1486 /// in the diagram).
1488 /// What is interesting is that De Bruijn index attached to a particular
1489 /// variable will vary depending on where it appears. For example,
1490 /// the final type `&'a char` also refers to the region `'a` declared on
1491 /// the outermost fn. But this time, this reference is not nested within
1492 /// any other binders (i.e., it is not an argument to the inner fn, but
1493 /// rather the outer one). Therefore, in this case, it is assigned a
1494 /// De Bruijn index of 1, because the innermost binder in that location
1495 /// is the outer fn.
1497 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1498 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
1499 pub struct DebruijnIndex {
1500 // We maintain the invariant that this is never 0. So 1 indicates
1501 // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
1505 /// Representation of regions.
1507 /// Unlike types, most region variants are "fictitious", not concrete,
1508 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1509 /// ones representing concrete regions.
1511 /// ## Bound Regions
1513 /// These are regions that are stored behind a binder and must be substituted
1514 /// with some concrete region before being used. There are 2 kind of
1515 /// bound regions: early-bound, which are bound in a TypeScheme/TraitDef,
1516 /// and are substituted by a Substs, and late-bound, which are part of
1517 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
1518 /// the likes of `liberate_late_bound_regions`. The distinction exists
1519 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1521 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
1522 /// outside their binder, e.g. in types passed to type inference, and
1523 /// should first be substituted (by skolemized regions, free regions,
1524 /// or region variables).
1526 /// ## Skolemized and Free Regions
1528 /// One often wants to work with bound regions without knowing their precise
1529 /// identity. For example, when checking a function, the lifetime of a borrow
1530 /// can end up being assigned to some region parameter. In these cases,
1531 /// it must be ensured that bounds on the region can't be accidentally
1532 /// assumed without being checked.
1534 /// The process of doing that is called "skolemization". The bound regions
1535 /// are replaced by skolemized markers, which don't satisfy any relation
1536 /// not explicity provided.
1538 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
1539 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
1540 /// to be used. These also support explicit bounds: both the internally-stored
1541 /// *scope*, which the region is assumed to outlive, as well as other
1542 /// relations stored in the `FreeRegionMap`. Note that these relations
1543 /// aren't checked when you `make_subregion` (or `mk_eqty`), only by
1544 /// `resolve_regions_and_report_errors`.
1546 /// When working with higher-ranked types, some region relations aren't
1547 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1548 /// `ReSkolemized` is designed for this purpose. In these contexts,
1549 /// there's also the risk that some inference variable laying around will
1550 /// get unified with your skolemized region: if you want to check whether
1551 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1552 /// with a skolemized region `'%a`, the variable `'_` would just be
1553 /// instantiated to the skolemized region `'%a`, which is wrong because
1554 /// the inference variable is supposed to satisfy the relation
1555 /// *for every value of the skolemized region*. To ensure that doesn't
1556 /// happen, you can use `leak_check`. This is more clearly explained
1557 /// by infer/higher_ranked/README.md.
1559 /// [1] http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1560 /// [2] http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1561 #[derive(Clone, PartialEq, Eq, Hash, Copy)]
1563 // Region bound in a type or fn declaration which will be
1564 // substituted 'early' -- that is, at the same time when type
1565 // parameters are substituted.
1566 ReEarlyBound(EarlyBoundRegion),
1568 // Region bound in a function scope, which will be substituted when the
1569 // function is called.
1570 ReLateBound(DebruijnIndex, BoundRegion),
1572 /// When checking a function body, the types of all arguments and so forth
1573 /// that refer to bound region parameters are modified to refer to free
1574 /// region parameters.
1577 /// A concrete region naming some statically determined extent
1578 /// (e.g. an expression or sequence of statements) within the
1579 /// current function.
1580 ReScope(region::CodeExtent),
1582 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1585 /// A region variable. Should not exist after typeck.
1588 /// A skolemized region - basically the higher-ranked version of ReFree.
1589 /// Should not exist after typeck.
1590 ReSkolemized(SkolemizedRegionVid, BoundRegion),
1592 /// Empty lifetime is for data that is never accessed.
1593 /// Bottom in the region lattice. We treat ReEmpty somewhat
1594 /// specially; at least right now, we do not generate instances of
1595 /// it during the GLB computations, but rather
1596 /// generate an error instead. This is to improve error messages.
1597 /// The only way to get an instance of ReEmpty is to have a region
1598 /// variable with no constraints.
1602 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
1603 pub struct EarlyBoundRegion {
1604 pub param_id: NodeId,
1605 pub space: subst::ParamSpace,
1610 /// Upvars do not get their own node-id. Instead, we use the pair of
1611 /// the original var id (that is, the root variable that is referenced
1612 /// by the upvar) and the id of the closure expression.
1613 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1614 pub struct UpvarId {
1616 pub closure_expr_id: NodeId,
1619 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
1620 pub enum BorrowKind {
1621 /// Data must be immutable and is aliasable.
1624 /// Data must be immutable but not aliasable. This kind of borrow
1625 /// cannot currently be expressed by the user and is used only in
1626 /// implicit closure bindings. It is needed when you the closure
1627 /// is borrowing or mutating a mutable referent, e.g.:
1629 /// let x: &mut isize = ...;
1630 /// let y = || *x += 5;
1632 /// If we were to try to translate this closure into a more explicit
1633 /// form, we'd encounter an error with the code as written:
1635 /// struct Env { x: & &mut isize }
1636 /// let x: &mut isize = ...;
1637 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
1638 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1640 /// This is then illegal because you cannot mutate a `&mut` found
1641 /// in an aliasable location. To solve, you'd have to translate with
1642 /// an `&mut` borrow:
1644 /// struct Env { x: & &mut isize }
1645 /// let x: &mut isize = ...;
1646 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
1647 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
1649 /// Now the assignment to `**env.x` is legal, but creating a
1650 /// mutable pointer to `x` is not because `x` is not mutable. We
1651 /// could fix this by declaring `x` as `let mut x`. This is ok in
1652 /// user code, if awkward, but extra weird for closures, since the
1653 /// borrow is hidden.
1655 /// So we introduce a "unique imm" borrow -- the referent is
1656 /// immutable, but not aliasable. This solves the problem. For
1657 /// simplicity, we don't give users the way to express this
1658 /// borrow, it's just used when translating closures.
1661 /// Data is mutable and not aliasable.
1665 /// Information describing the capture of an upvar. This is computed
1666 /// during `typeck`, specifically by `regionck`.
1667 #[derive(PartialEq, Clone, Debug, Copy)]
1668 pub enum UpvarCapture {
1669 /// Upvar is captured by value. This is always true when the
1670 /// closure is labeled `move`, but can also be true in other cases
1671 /// depending on inference.
1674 /// Upvar is captured by reference.
1678 #[derive(PartialEq, Clone, Copy)]
1679 pub struct UpvarBorrow {
1680 /// The kind of borrow: by-ref upvars have access to shared
1681 /// immutable borrows, which are not part of the normal language
1683 pub kind: BorrowKind,
1685 /// Region of the resulting reference.
1686 pub region: ty::Region,
1689 pub type UpvarCaptureMap = FnvHashMap<UpvarId, UpvarCapture>;
1691 #[derive(Copy, Clone)]
1692 pub struct ClosureUpvar<'tcx> {
1699 pub fn is_bound(&self) -> bool {
1701 ty::ReEarlyBound(..) => true,
1702 ty::ReLateBound(..) => true,
1707 pub fn needs_infer(&self) -> bool {
1709 ty::ReVar(..) | ty::ReSkolemized(..) => true,
1714 pub fn escapes_depth(&self, depth: u32) -> bool {
1716 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1721 /// Returns the depth of `self` from the (1-based) binding level `depth`
1722 pub fn from_depth(&self, depth: u32) -> Region {
1724 ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
1725 depth: debruijn.depth - (depth - 1)
1732 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1733 RustcEncodable, RustcDecodable, Copy)]
1734 /// A "free" region `fr` can be interpreted as "some region
1735 /// at least as big as the scope `fr.scope`".
1736 pub struct FreeRegion {
1737 pub scope: region::CodeExtent,
1738 pub bound_region: BoundRegion
1741 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1742 RustcEncodable, RustcDecodable, Copy)]
1743 pub enum BoundRegion {
1744 /// An anonymous region parameter for a given fn (&T)
1747 /// Named region parameters for functions (a in &'a T)
1749 /// The def-id is needed to distinguish free regions in
1750 /// the event of shadowing.
1751 BrNamed(DefId, Name),
1753 /// Fresh bound identifiers created during GLB computations.
1756 // Anonymous region for the implicit env pointer parameter
1761 // NB: If you change this, you'll probably want to change the corresponding
1762 // AST structure in libsyntax/ast.rs as well.
1763 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1764 pub enum TypeVariants<'tcx> {
1765 /// The primitive boolean type. Written as `bool`.
1768 /// The primitive character type; holds a Unicode scalar value
1769 /// (a non-surrogate code point). Written as `char`.
1772 /// A primitive signed integer type. For example, `i32`.
1775 /// A primitive unsigned integer type. For example, `u32`.
1776 TyUint(hir::UintTy),
1778 /// A primitive floating-point type. For example, `f64`.
1779 TyFloat(hir::FloatTy),
1781 /// An enumerated type, defined with `enum`.
1783 /// Substs here, possibly against intuition, *may* contain `TyParam`s.
1784 /// That is, even after substitution it is possible that there are type
1785 /// variables. This happens when the `TyEnum` corresponds to an enum
1786 /// definition and not a concrete use of it. To get the correct `TyEnum`
1787 /// from the tcx, use the `NodeId` from the `hir::Ty` and look it up in
1788 /// the `ast_ty_to_ty_cache`. This is probably true for `TyStruct` as
1790 TyEnum(AdtDef<'tcx>, &'tcx Substs<'tcx>),
1792 /// A structure type, defined with `struct`.
1794 /// See warning about substitutions for enumerated types.
1795 TyStruct(AdtDef<'tcx>, &'tcx Substs<'tcx>),
1797 /// `Box<T>`; this is nominally a struct in the documentation, but is
1798 /// special-cased internally. For example, it is possible to implicitly
1799 /// move the contents of a box out of that box, and methods of any type
1800 /// can have type `Box<Self>`.
1803 /// The pointee of a string slice. Written as `str`.
1806 /// An array with the given length. Written as `[T; n]`.
1807 TyArray(Ty<'tcx>, usize),
1809 /// The pointee of an array slice. Written as `[T]`.
1812 /// A raw pointer. Written as `*mut T` or `*const T`
1813 TyRawPtr(TypeAndMut<'tcx>),
1815 /// A reference; a pointer with an associated lifetime. Written as
1816 /// `&a mut T` or `&'a T`.
1817 TyRef(&'tcx Region, TypeAndMut<'tcx>),
1819 /// If the def-id is Some(_), then this is the type of a specific
1820 /// fn item. Otherwise, if None(_), it a fn pointer type.
1822 /// FIXME: Conflating function pointers and the type of a
1823 /// function is probably a terrible idea; a function pointer is a
1824 /// value with a specific type, but a function can be polymorphic
1825 /// or dynamically dispatched.
1826 TyBareFn(Option<DefId>, &'tcx BareFnTy<'tcx>),
1828 /// A trait, defined with `trait`.
1829 TyTrait(Box<TraitTy<'tcx>>),
1831 /// The anonymous type of a closure. Used to represent the type of
1833 TyClosure(DefId, Box<ClosureSubsts<'tcx>>),
1835 /// A tuple type. For example, `(i32, bool)`.
1836 TyTuple(Vec<Ty<'tcx>>),
1838 /// The projection of an associated type. For example,
1839 /// `<T as Trait<..>>::N`.
1840 TyProjection(ProjectionTy<'tcx>),
1842 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
1845 /// A type variable used during type-checking.
1848 /// A placeholder for a type which could not be computed; this is
1849 /// propagated to avoid useless error messages.
1853 /// A closure can be modeled as a struct that looks like:
1855 /// struct Closure<'l0...'li, T0...Tj, U0...Uk> {
1861 /// where 'l0...'li and T0...Tj are the lifetime and type parameters
1862 /// in scope on the function that defined the closure, and U0...Uk are
1863 /// type parameters representing the types of its upvars (borrowed, if
1866 /// So, for example, given this function:
1868 /// fn foo<'a, T>(data: &'a mut T) {
1869 /// do(|| data.count += 1)
1872 /// the type of the closure would be something like:
1874 /// struct Closure<'a, T, U0> {
1878 /// Note that the type of the upvar is not specified in the struct.
1879 /// You may wonder how the impl would then be able to use the upvar,
1880 /// if it doesn't know it's type? The answer is that the impl is
1881 /// (conceptually) not fully generic over Closure but rather tied to
1882 /// instances with the expected upvar types:
1884 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
1888 /// You can see that the *impl* fully specified the type of the upvar
1889 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
1890 /// (Here, I am assuming that `data` is mut-borrowed.)
1892 /// Now, the last question you may ask is: Why include the upvar types
1893 /// as extra type parameters? The reason for this design is that the
1894 /// upvar types can reference lifetimes that are internal to the
1895 /// creating function. In my example above, for example, the lifetime
1896 /// `'b` represents the extent of the closure itself; this is some
1897 /// subset of `foo`, probably just the extent of the call to the to
1898 /// `do()`. If we just had the lifetime/type parameters from the
1899 /// enclosing function, we couldn't name this lifetime `'b`. Note that
1900 /// there can also be lifetimes in the types of the upvars themselves,
1901 /// if one of them happens to be a reference to something that the
1902 /// creating fn owns.
1904 /// OK, you say, so why not create a more minimal set of parameters
1905 /// that just includes the extra lifetime parameters? The answer is
1906 /// primarily that it would be hard --- we don't know at the time when
1907 /// we create the closure type what the full types of the upvars are,
1908 /// nor do we know which are borrowed and which are not. In this
1909 /// design, we can just supply a fresh type parameter and figure that
1912 /// All right, you say, but why include the type parameters from the
1913 /// original function then? The answer is that trans may need them
1914 /// when monomorphizing, and they may not appear in the upvars. A
1915 /// closure could capture no variables but still make use of some
1916 /// in-scope type parameter with a bound (e.g., if our example above
1917 /// had an extra `U: Default`, and the closure called `U::default()`).
1919 /// There is another reason. This design (implicitly) prohibits
1920 /// closures from capturing themselves (except via a trait
1921 /// object). This simplifies closure inference considerably, since it
1922 /// means that when we infer the kind of a closure or its upvars, we
1923 /// don't have to handle cycles where the decisions we make for
1924 /// closure C wind up influencing the decisions we ought to make for
1925 /// closure C (which would then require fixed point iteration to
1926 /// handle). Plus it fixes an ICE. :P
1927 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
1928 pub struct ClosureSubsts<'tcx> {
1929 /// Lifetime and type parameters from the enclosing function.
1930 /// These are separated out because trans wants to pass them around
1931 /// when monomorphizing.
1932 pub func_substs: &'tcx Substs<'tcx>,
1934 /// The types of the upvars. The list parallels the freevars and
1935 /// `upvar_borrows` lists. These are kept distinct so that we can
1936 /// easily index into them.
1937 pub upvar_tys: Vec<Ty<'tcx>>
1940 #[derive(Clone, PartialEq, Eq, Hash)]
1941 pub struct TraitTy<'tcx> {
1942 pub principal: ty::PolyTraitRef<'tcx>,
1943 pub bounds: ExistentialBounds<'tcx>,
1946 impl<'tcx> TraitTy<'tcx> {
1947 pub fn principal_def_id(&self) -> DefId {
1948 self.principal.0.def_id
1951 /// Object types don't have a self-type specified. Therefore, when
1952 /// we convert the principal trait-ref into a normal trait-ref,
1953 /// you must give *some* self-type. A common choice is `mk_err()`
1954 /// or some skolemized type.
1955 pub fn principal_trait_ref_with_self_ty(&self,
1958 -> ty::PolyTraitRef<'tcx>
1960 // otherwise the escaping regions would be captured by the binder
1961 assert!(!self_ty.has_escaping_regions());
1963 ty::Binder(TraitRef {
1964 def_id: self.principal.0.def_id,
1965 substs: tcx.mk_substs(self.principal.0.substs.with_self_ty(self_ty)),
1969 pub fn projection_bounds_with_self_ty(&self,
1972 -> Vec<ty::PolyProjectionPredicate<'tcx>>
1974 // otherwise the escaping regions would be captured by the binders
1975 assert!(!self_ty.has_escaping_regions());
1977 self.bounds.projection_bounds.iter()
1978 .map(|in_poly_projection_predicate| {
1979 let in_projection_ty = &in_poly_projection_predicate.0.projection_ty;
1980 let substs = tcx.mk_substs(in_projection_ty.trait_ref.substs.with_self_ty(self_ty));
1981 let trait_ref = ty::TraitRef::new(in_projection_ty.trait_ref.def_id,
1983 let projection_ty = ty::ProjectionTy {
1984 trait_ref: trait_ref,
1985 item_name: in_projection_ty.item_name
1987 ty::Binder(ty::ProjectionPredicate {
1988 projection_ty: projection_ty,
1989 ty: in_poly_projection_predicate.0.ty
1996 /// A complete reference to a trait. These take numerous guises in syntax,
1997 /// but perhaps the most recognizable form is in a where clause:
2001 /// This would be represented by a trait-reference where the def-id is the
2002 /// def-id for the trait `Foo` and the substs defines `T` as parameter 0 in the
2003 /// `SelfSpace` and `U` as parameter 0 in the `TypeSpace`.
2005 /// Trait references also appear in object types like `Foo<U>`, but in
2006 /// that case the `Self` parameter is absent from the substitutions.
2008 /// Note that a `TraitRef` introduces a level of region binding, to
2009 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
2010 /// U>` or higher-ranked object types.
2011 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
2012 pub struct TraitRef<'tcx> {
2014 pub substs: &'tcx Substs<'tcx>,
2017 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
2019 impl<'tcx> PolyTraitRef<'tcx> {
2020 pub fn self_ty(&self) -> Ty<'tcx> {
2024 pub fn def_id(&self) -> DefId {
2028 pub fn substs(&self) -> &'tcx Substs<'tcx> {
2029 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
2033 pub fn input_types(&self) -> &[Ty<'tcx>] {
2034 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
2035 self.0.input_types()
2038 pub fn to_poly_trait_predicate(&self) -> PolyTraitPredicate<'tcx> {
2039 // Note that we preserve binding levels
2040 Binder(TraitPredicate { trait_ref: self.0.clone() })
2044 /// Binder is a binder for higher-ranked lifetimes. It is part of the
2045 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
2046 /// (which would be represented by the type `PolyTraitRef ==
2047 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
2048 /// erase, or otherwise "discharge" these bound regions, we change the
2049 /// type from `Binder<T>` to just `T` (see
2050 /// e.g. `liberate_late_bound_regions`).
2051 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
2052 pub struct Binder<T>(pub T);
2055 /// Skips the binder and returns the "bound" value. This is a
2056 /// risky thing to do because it's easy to get confused about
2057 /// debruijn indices and the like. It is usually better to
2058 /// discharge the binder using `no_late_bound_regions` or
2059 /// `replace_late_bound_regions` or something like
2060 /// that. `skip_binder` is only valid when you are either
2061 /// extracting data that has nothing to do with bound regions, you
2062 /// are doing some sort of test that does not involve bound
2063 /// regions, or you are being very careful about your depth
2066 /// Some examples where `skip_binder` is reasonable:
2067 /// - extracting the def-id from a PolyTraitRef;
2068 /// - comparing the self type of a PolyTraitRef to see if it is equal to
2069 /// a type parameter `X`, since the type `X` does not reference any regions
2070 pub fn skip_binder(&self) -> &T {
2074 pub fn as_ref(&self) -> Binder<&T> {
2078 pub fn map_bound_ref<F,U>(&self, f: F) -> Binder<U>
2079 where F: FnOnce(&T) -> U
2081 self.as_ref().map_bound(f)
2084 pub fn map_bound<F,U>(self, f: F) -> Binder<U>
2085 where F: FnOnce(T) -> U
2087 ty::Binder(f(self.0))
2091 #[derive(Clone, Copy, PartialEq)]
2092 pub enum IntVarValue {
2093 IntType(hir::IntTy),
2094 UintType(hir::UintTy),
2097 #[derive(Clone, Copy, Debug)]
2098 pub struct ExpectedFound<T> {
2103 // Data structures used in type unification
2104 #[derive(Clone, Debug)]
2105 pub enum TypeError<'tcx> {
2107 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
2108 AbiMismatch(ExpectedFound<abi::Abi>),
2114 TupleSize(ExpectedFound<usize>),
2115 FixedArraySize(ExpectedFound<usize>),
2116 TyParamSize(ExpectedFound<usize>),
2118 RegionsDoesNotOutlive(Region, Region),
2119 RegionsNotSame(Region, Region),
2120 RegionsNoOverlap(Region, Region),
2121 RegionsInsufficientlyPolymorphic(BoundRegion, Region),
2122 RegionsOverlyPolymorphic(BoundRegion, Region),
2123 Sorts(ExpectedFound<Ty<'tcx>>),
2125 IntMismatch(ExpectedFound<IntVarValue>),
2126 FloatMismatch(ExpectedFound<hir::FloatTy>),
2127 Traits(ExpectedFound<DefId>),
2128 BuiltinBoundsMismatch(ExpectedFound<BuiltinBounds>),
2129 VariadicMismatch(ExpectedFound<bool>),
2131 ConvergenceMismatch(ExpectedFound<bool>),
2132 ProjectionNameMismatched(ExpectedFound<Name>),
2133 ProjectionBoundsLength(ExpectedFound<usize>),
2134 TyParamDefaultMismatch(ExpectedFound<type_variable::Default<'tcx>>)
2137 /// Bounds suitable for an existentially quantified type parameter
2138 /// such as those that appear in object types or closure types.
2139 #[derive(PartialEq, Eq, Hash, Clone)]
2140 pub struct ExistentialBounds<'tcx> {
2141 pub region_bound: ty::Region,
2142 pub builtin_bounds: BuiltinBounds,
2143 pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
2146 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
2147 pub struct BuiltinBounds(EnumSet<BuiltinBound>);
2149 impl BuiltinBounds {
2150 pub fn empty() -> BuiltinBounds {
2151 BuiltinBounds(EnumSet::new())
2154 pub fn iter(&self) -> enum_set::Iter<BuiltinBound> {
2158 pub fn to_predicates<'tcx>(&self,
2159 tcx: &ty::ctxt<'tcx>,
2160 self_ty: Ty<'tcx>) -> Vec<Predicate<'tcx>> {
2161 self.iter().filter_map(|builtin_bound|
2162 match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, self_ty) {
2163 Ok(trait_ref) => Some(trait_ref.to_predicate()),
2164 Err(ErrorReported) => { None }
2170 impl ops::Deref for BuiltinBounds {
2171 type Target = EnumSet<BuiltinBound>;
2172 fn deref(&self) -> &Self::Target { &self.0 }
2175 impl ops::DerefMut for BuiltinBounds {
2176 fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
2179 impl<'a> IntoIterator for &'a BuiltinBounds {
2180 type Item = BuiltinBound;
2181 type IntoIter = enum_set::Iter<BuiltinBound>;
2182 fn into_iter(self) -> Self::IntoIter {
2183 (**self).into_iter()
2187 #[derive(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
2190 pub enum BuiltinBound {
2197 impl CLike for BuiltinBound {
2198 fn to_usize(&self) -> usize {
2201 fn from_usize(v: usize) -> BuiltinBound {
2202 unsafe { mem::transmute(v) }
2206 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2211 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2216 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2217 pub struct FloatVid {
2221 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
2222 pub struct RegionVid {
2226 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2227 pub struct SkolemizedRegionVid {
2231 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2237 /// A `FreshTy` is one that is generated as a replacement for an
2238 /// unbound type variable. This is convenient for caching etc. See
2239 /// `middle::infer::freshen` for more details.
2245 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
2246 pub enum UnconstrainedNumeric {
2253 impl fmt::Debug for TyVid {
2254 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2255 write!(f, "_#{}t", self.index)
2259 impl fmt::Debug for IntVid {
2260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2261 write!(f, "_#{}i", self.index)
2265 impl fmt::Debug for FloatVid {
2266 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2267 write!(f, "_#{}f", self.index)
2271 impl fmt::Debug for RegionVid {
2272 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2273 write!(f, "'_#{}r", self.index)
2277 impl<'tcx> fmt::Debug for FnSig<'tcx> {
2278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2279 write!(f, "({:?}; variadic: {})->{:?}", self.inputs, self.variadic, self.output)
2283 impl fmt::Debug for InferTy {
2284 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2286 TyVar(ref v) => v.fmt(f),
2287 IntVar(ref v) => v.fmt(f),
2288 FloatVar(ref v) => v.fmt(f),
2289 FreshTy(v) => write!(f, "FreshTy({:?})", v),
2290 FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
2291 FreshFloatTy(v) => write!(f, "FreshFloatTy({:?})", v)
2296 impl fmt::Debug for IntVarValue {
2297 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2299 IntType(ref v) => v.fmt(f),
2300 UintType(ref v) => v.fmt(f),
2305 /// Default region to use for the bound of objects that are
2306 /// supplied as the value for this type parameter. This is derived
2307 /// from `T:'a` annotations appearing in the type definition. If
2308 /// this is `None`, then the default is inherited from the
2309 /// surrounding context. See RFC #599 for details.
2310 #[derive(Copy, Clone)]
2311 pub enum ObjectLifetimeDefault {
2312 /// Require an explicit annotation. Occurs when multiple
2313 /// `T:'a` constraints are found.
2316 /// Use the base default, typically 'static, but in a fn body it is a fresh variable
2319 /// Use the given region as the default.
2324 pub struct TypeParameterDef<'tcx> {
2327 pub space: subst::ParamSpace,
2329 pub default_def_id: DefId, // for use in error reporing about defaults
2330 pub default: Option<Ty<'tcx>>,
2331 pub object_lifetime_default: ObjectLifetimeDefault,
2335 pub struct RegionParameterDef {
2338 pub space: subst::ParamSpace,
2340 pub bounds: Vec<ty::Region>,
2343 impl RegionParameterDef {
2344 pub fn to_early_bound_region(&self) -> ty::Region {
2345 ty::ReEarlyBound(ty::EarlyBoundRegion {
2346 param_id: self.def_id.node,
2352 pub fn to_bound_region(&self) -> ty::BoundRegion {
2353 ty::BoundRegion::BrNamed(self.def_id, self.name)
2357 /// Information about the formal type/lifetime parameters associated
2358 /// with an item or method. Analogous to hir::Generics.
2359 #[derive(Clone, Debug)]
2360 pub struct Generics<'tcx> {
2361 pub types: VecPerParamSpace<TypeParameterDef<'tcx>>,
2362 pub regions: VecPerParamSpace<RegionParameterDef>,
2365 impl<'tcx> Generics<'tcx> {
2366 pub fn empty() -> Generics<'tcx> {
2368 types: VecPerParamSpace::empty(),
2369 regions: VecPerParamSpace::empty(),
2373 pub fn is_empty(&self) -> bool {
2374 self.types.is_empty() && self.regions.is_empty()
2377 pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
2378 !self.types.is_empty_in(space)
2381 pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
2382 !self.regions.is_empty_in(space)
2386 /// Bounds on generics.
2388 pub struct GenericPredicates<'tcx> {
2389 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
2392 impl<'tcx> GenericPredicates<'tcx> {
2393 pub fn empty() -> GenericPredicates<'tcx> {
2395 predicates: VecPerParamSpace::empty(),
2399 pub fn instantiate(&self, tcx: &ctxt<'tcx>, substs: &Substs<'tcx>)
2400 -> InstantiatedPredicates<'tcx> {
2401 InstantiatedPredicates {
2402 predicates: self.predicates.subst(tcx, substs),
2406 pub fn instantiate_supertrait(&self,
2408 poly_trait_ref: &ty::PolyTraitRef<'tcx>)
2409 -> InstantiatedPredicates<'tcx>
2411 InstantiatedPredicates {
2412 predicates: self.predicates.map(|pred| pred.subst_supertrait(tcx, poly_trait_ref))
2417 #[derive(Clone, PartialEq, Eq, Hash)]
2418 pub enum Predicate<'tcx> {
2419 /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
2420 /// the `Self` type of the trait reference and `A`, `B`, and `C`
2421 /// would be the parameters in the `TypeSpace`.
2422 Trait(PolyTraitPredicate<'tcx>),
2424 /// where `T1 == T2`.
2425 Equate(PolyEquatePredicate<'tcx>),
2428 RegionOutlives(PolyRegionOutlivesPredicate),
2431 TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
2433 /// where <T as TraitRef>::Name == X, approximately.
2434 /// See `ProjectionPredicate` struct for details.
2435 Projection(PolyProjectionPredicate<'tcx>),
2438 WellFormed(Ty<'tcx>),
2440 /// trait must be object-safe
2444 impl<'tcx> Predicate<'tcx> {
2445 /// Performs a substitution suitable for going from a
2446 /// poly-trait-ref to supertraits that must hold if that
2447 /// poly-trait-ref holds. This is slightly different from a normal
2448 /// substitution in terms of what happens with bound regions. See
2449 /// lengthy comment below for details.
2450 pub fn subst_supertrait(&self,
2452 trait_ref: &ty::PolyTraitRef<'tcx>)
2453 -> ty::Predicate<'tcx>
2455 // The interaction between HRTB and supertraits is not entirely
2456 // obvious. Let me walk you (and myself) through an example.
2458 // Let's start with an easy case. Consider two traits:
2460 // trait Foo<'a> : Bar<'a,'a> { }
2461 // trait Bar<'b,'c> { }
2463 // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
2464 // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
2465 // knew that `Foo<'x>` (for any 'x) then we also know that
2466 // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
2467 // normal substitution.
2469 // In terms of why this is sound, the idea is that whenever there
2470 // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
2471 // holds. So if there is an impl of `T:Foo<'a>` that applies to
2472 // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
2475 // Another example to be careful of is this:
2477 // trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
2478 // trait Bar1<'b,'c> { }
2480 // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
2481 // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
2482 // reason is similar to the previous example: any impl of
2483 // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
2484 // basically we would want to collapse the bound lifetimes from
2485 // the input (`trait_ref`) and the supertraits.
2487 // To achieve this in practice is fairly straightforward. Let's
2488 // consider the more complicated scenario:
2490 // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
2491 // has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
2492 // where both `'x` and `'b` would have a DB index of 1.
2493 // The substitution from the input trait-ref is therefore going to be
2494 // `'a => 'x` (where `'x` has a DB index of 1).
2495 // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
2496 // early-bound parameter and `'b' is a late-bound parameter with a
2498 // - If we replace `'a` with `'x` from the input, it too will have
2499 // a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
2500 // just as we wanted.
2502 // There is only one catch. If we just apply the substitution `'a
2503 // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
2504 // adjust the DB index because we substituting into a binder (it
2505 // tries to be so smart...) resulting in `for<'x> for<'b>
2506 // Bar1<'x,'b>` (we have no syntax for this, so use your
2507 // imagination). Basically the 'x will have DB index of 2 and 'b
2508 // will have DB index of 1. Not quite what we want. So we apply
2509 // the substitution to the *contents* of the trait reference,
2510 // rather than the trait reference itself (put another way, the
2511 // substitution code expects equal binding levels in the values
2512 // from the substitution and the value being substituted into, and
2513 // this trick achieves that).
2515 let substs = &trait_ref.0.substs;
2517 Predicate::Trait(ty::Binder(ref data)) =>
2518 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
2519 Predicate::Equate(ty::Binder(ref data)) =>
2520 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
2521 Predicate::RegionOutlives(ty::Binder(ref data)) =>
2522 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
2523 Predicate::TypeOutlives(ty::Binder(ref data)) =>
2524 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
2525 Predicate::Projection(ty::Binder(ref data)) =>
2526 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
2527 Predicate::WellFormed(data) =>
2528 Predicate::WellFormed(data.subst(tcx, substs)),
2529 Predicate::ObjectSafe(trait_def_id) =>
2530 Predicate::ObjectSafe(trait_def_id),
2535 #[derive(Clone, PartialEq, Eq, Hash)]
2536 pub struct TraitPredicate<'tcx> {
2537 pub trait_ref: TraitRef<'tcx>
2539 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
2541 impl<'tcx> TraitPredicate<'tcx> {
2542 pub fn def_id(&self) -> DefId {
2543 self.trait_ref.def_id
2546 pub fn input_types(&self) -> &[Ty<'tcx>] {
2547 self.trait_ref.substs.types.as_slice()
2550 pub fn self_ty(&self) -> Ty<'tcx> {
2551 self.trait_ref.self_ty()
2555 impl<'tcx> PolyTraitPredicate<'tcx> {
2556 pub fn def_id(&self) -> DefId {
2561 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2562 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
2563 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
2565 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2566 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
2567 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
2568 pub type PolyRegionOutlivesPredicate = PolyOutlivesPredicate<ty::Region, ty::Region>;
2569 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region>;
2571 /// This kind of predicate has no *direct* correspondent in the
2572 /// syntax, but it roughly corresponds to the syntactic forms:
2574 /// 1. `T : TraitRef<..., Item=Type>`
2575 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
2577 /// In particular, form #1 is "desugared" to the combination of a
2578 /// normal trait predicate (`T : TraitRef<...>`) and one of these
2579 /// predicates. Form #2 is a broader form in that it also permits
2580 /// equality between arbitrary types. Processing an instance of Form
2581 /// #2 eventually yields one of these `ProjectionPredicate`
2582 /// instances to normalize the LHS.
2583 #[derive(Clone, PartialEq, Eq, Hash)]
2584 pub struct ProjectionPredicate<'tcx> {
2585 pub projection_ty: ProjectionTy<'tcx>,
2589 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
2591 impl<'tcx> PolyProjectionPredicate<'tcx> {
2592 pub fn item_name(&self) -> Name {
2593 self.0.projection_ty.item_name // safe to skip the binder to access a name
2596 pub fn sort_key(&self) -> (DefId, Name) {
2597 self.0.projection_ty.sort_key()
2601 /// Represents the projection of an associated type. In explicit UFCS
2602 /// form this would be written `<T as Trait<..>>::N`.
2603 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
2604 pub struct ProjectionTy<'tcx> {
2605 /// The trait reference `T as Trait<..>`.
2606 pub trait_ref: ty::TraitRef<'tcx>,
2608 /// The name `N` of the associated type.
2609 pub item_name: Name,
2612 impl<'tcx> ProjectionTy<'tcx> {
2613 pub fn sort_key(&self) -> (DefId, Name) {
2614 (self.trait_ref.def_id, self.item_name)
2618 pub trait ToPolyTraitRef<'tcx> {
2619 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
2622 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
2623 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2624 assert!(!self.has_escaping_regions());
2625 ty::Binder(self.clone())
2629 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
2630 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2631 self.map_bound_ref(|trait_pred| trait_pred.trait_ref.clone())
2635 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
2636 fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
2637 // Note: unlike with TraitRef::to_poly_trait_ref(),
2638 // self.0.trait_ref is permitted to have escaping regions.
2639 // This is because here `self` has a `Binder` and so does our
2640 // return value, so we are preserving the number of binding
2642 ty::Binder(self.0.projection_ty.trait_ref.clone())
2646 pub trait ToPredicate<'tcx> {
2647 fn to_predicate(&self) -> Predicate<'tcx>;
2650 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
2651 fn to_predicate(&self) -> Predicate<'tcx> {
2652 // we're about to add a binder, so let's check that we don't
2653 // accidentally capture anything, or else that might be some
2654 // weird debruijn accounting.
2655 assert!(!self.has_escaping_regions());
2657 ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
2658 trait_ref: self.clone()
2663 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
2664 fn to_predicate(&self) -> Predicate<'tcx> {
2665 ty::Predicate::Trait(self.to_poly_trait_predicate())
2669 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
2670 fn to_predicate(&self) -> Predicate<'tcx> {
2671 Predicate::Equate(self.clone())
2675 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate {
2676 fn to_predicate(&self) -> Predicate<'tcx> {
2677 Predicate::RegionOutlives(self.clone())
2681 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
2682 fn to_predicate(&self) -> Predicate<'tcx> {
2683 Predicate::TypeOutlives(self.clone())
2687 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
2688 fn to_predicate(&self) -> Predicate<'tcx> {
2689 Predicate::Projection(self.clone())
2693 impl<'tcx> Predicate<'tcx> {
2694 /// Iterates over the types in this predicate. Note that in all
2695 /// cases this is skipping over a binder, so late-bound regions
2696 /// with depth 0 are bound by the predicate.
2697 pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
2698 let vec: Vec<_> = match *self {
2699 ty::Predicate::Trait(ref data) => {
2700 data.0.trait_ref.substs.types.as_slice().to_vec()
2702 ty::Predicate::Equate(ty::Binder(ref data)) => {
2703 vec![data.0, data.1]
2705 ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
2708 ty::Predicate::RegionOutlives(..) => {
2711 ty::Predicate::Projection(ref data) => {
2712 let trait_inputs = data.0.projection_ty.trait_ref.substs.types.as_slice();
2715 .chain(Some(data.0.ty))
2718 ty::Predicate::WellFormed(data) => {
2721 ty::Predicate::ObjectSafe(_trait_def_id) => {
2726 // The only reason to collect into a vector here is that I was
2727 // too lazy to make the full (somewhat complicated) iterator
2728 // type that would be needed here. But I wanted this fn to
2729 // return an iterator conceptually, rather than a `Vec`, so as
2730 // to be closer to `Ty::walk`.
2734 pub fn has_escaping_regions(&self) -> bool {
2736 Predicate::Trait(ref trait_ref) => trait_ref.has_escaping_regions(),
2737 Predicate::Equate(ref p) => p.has_escaping_regions(),
2738 Predicate::RegionOutlives(ref p) => p.has_escaping_regions(),
2739 Predicate::TypeOutlives(ref p) => p.has_escaping_regions(),
2740 Predicate::Projection(ref p) => p.has_escaping_regions(),
2741 Predicate::WellFormed(p) => p.has_escaping_regions(),
2742 Predicate::ObjectSafe(_trait_def_id) => false,
2746 pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
2748 Predicate::Trait(ref t) => {
2749 Some(t.to_poly_trait_ref())
2751 Predicate::Projection(..) |
2752 Predicate::Equate(..) |
2753 Predicate::RegionOutlives(..) |
2754 Predicate::WellFormed(..) |
2755 Predicate::ObjectSafe(..) |
2756 Predicate::TypeOutlives(..) => {
2763 /// Represents the bounds declared on a particular set of type
2764 /// parameters. Should eventually be generalized into a flag list of
2765 /// where clauses. You can obtain a `InstantiatedPredicates` list from a
2766 /// `GenericPredicates` by using the `instantiate` method. Note that this method
2767 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
2768 /// the `GenericPredicates` are expressed in terms of the bound type
2769 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
2770 /// represented a set of bounds for some particular instantiation,
2771 /// meaning that the generic parameters have been substituted with
2776 /// struct Foo<T,U:Bar<T>> { ... }
2778 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
2779 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
2780 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
2781 /// [usize:Bar<isize>]]`.
2783 pub struct InstantiatedPredicates<'tcx> {
2784 pub predicates: VecPerParamSpace<Predicate<'tcx>>,
2787 impl<'tcx> InstantiatedPredicates<'tcx> {
2788 pub fn empty() -> InstantiatedPredicates<'tcx> {
2789 InstantiatedPredicates { predicates: VecPerParamSpace::empty() }
2792 pub fn has_escaping_regions(&self) -> bool {
2793 self.predicates.any(|p| p.has_escaping_regions())
2796 pub fn is_empty(&self) -> bool {
2797 self.predicates.is_empty()
2801 impl<'tcx> TraitRef<'tcx> {
2802 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
2803 TraitRef { def_id: def_id, substs: substs }
2806 pub fn self_ty(&self) -> Ty<'tcx> {
2807 self.substs.self_ty().unwrap()
2810 pub fn input_types(&self) -> &[Ty<'tcx>] {
2811 // Select only the "input types" from a trait-reference. For
2812 // now this is all the types that appear in the
2813 // trait-reference, but it should eventually exclude
2814 // associated types.
2815 self.substs.types.as_slice()
2819 /// When type checking, we use the `ParameterEnvironment` to track
2820 /// details about the type/lifetime parameters that are in scope.
2821 /// It primarily stores the bounds information.
2823 /// Note: This information might seem to be redundant with the data in
2824 /// `tcx.ty_param_defs`, but it is not. That table contains the
2825 /// parameter definitions from an "outside" perspective, but this
2826 /// struct will contain the bounds for a parameter as seen from inside
2827 /// the function body. Currently the only real distinction is that
2828 /// bound lifetime parameters are replaced with free ones, but in the
2829 /// future I hope to refine the representation of types so as to make
2830 /// more distinctions clearer.
2832 pub struct ParameterEnvironment<'a, 'tcx:'a> {
2833 pub tcx: &'a ctxt<'tcx>,
2835 /// See `construct_free_substs` for details.
2836 pub free_substs: Substs<'tcx>,
2838 /// Each type parameter has an implicit region bound that
2839 /// indicates it must outlive at least the function body (the user
2840 /// may specify stronger requirements). This field indicates the
2841 /// region of the callee.
2842 pub implicit_region_bound: ty::Region,
2844 /// Obligations that the caller must satisfy. This is basically
2845 /// the set of bounds on the in-scope type parameters, translated
2846 /// into Obligations, and elaborated and normalized.
2847 pub caller_bounds: Vec<ty::Predicate<'tcx>>,
2849 /// Caches the results of trait selection. This cache is used
2850 /// for things that have to do with the parameters in scope.
2851 pub selection_cache: traits::SelectionCache<'tcx>,
2853 /// Scope that is attached to free regions for this scope. This
2854 /// is usually the id of the fn body, but for more abstract scopes
2855 /// like structs we often use the node-id of the struct.
2857 /// FIXME(#3696). It would be nice to refactor so that free
2858 /// regions don't have this implicit scope and instead introduce
2859 /// relationships in the environment.
2860 pub free_id: ast::NodeId,
2863 impl<'a, 'tcx> ParameterEnvironment<'a, 'tcx> {
2864 pub fn with_caller_bounds(&self,
2865 caller_bounds: Vec<ty::Predicate<'tcx>>)
2866 -> ParameterEnvironment<'a,'tcx>
2868 ParameterEnvironment {
2870 free_substs: self.free_substs.clone(),
2871 implicit_region_bound: self.implicit_region_bound,
2872 caller_bounds: caller_bounds,
2873 selection_cache: traits::SelectionCache::new(),
2874 free_id: self.free_id,
2878 pub fn for_item(cx: &'a ctxt<'tcx>, id: NodeId) -> ParameterEnvironment<'a, 'tcx> {
2879 match cx.map.find(id) {
2880 Some(ast_map::NodeImplItem(ref impl_item)) => {
2881 match impl_item.node {
2882 hir::TypeImplItem(_) => {
2883 // associated types don't have their own entry (for some reason),
2884 // so for now just grab environment for the impl
2885 let impl_id = cx.map.get_parent(id);
2886 let impl_def_id = DefId::local(impl_id);
2887 let scheme = cx.lookup_item_type(impl_def_id);
2888 let predicates = cx.lookup_predicates(impl_def_id);
2889 cx.construct_parameter_environment(impl_item.span,
2894 hir::ConstImplItem(_, _) => {
2895 let def_id = DefId::local(id);
2896 let scheme = cx.lookup_item_type(def_id);
2897 let predicates = cx.lookup_predicates(def_id);
2898 cx.construct_parameter_environment(impl_item.span,
2903 hir::MethodImplItem(_, ref body) => {
2904 let method_def_id = DefId::local(id);
2905 match cx.impl_or_trait_item(method_def_id) {
2906 MethodTraitItem(ref method_ty) => {
2907 let method_generics = &method_ty.generics;
2908 let method_bounds = &method_ty.predicates;
2909 cx.construct_parameter_environment(
2917 .bug("ParameterEnvironment::for_item(): \
2918 got non-method item from impl method?!")
2924 Some(ast_map::NodeTraitItem(trait_item)) => {
2925 match trait_item.node {
2926 hir::TypeTraitItem(..) => {
2927 // associated types don't have their own entry (for some reason),
2928 // so for now just grab environment for the trait
2929 let trait_id = cx.map.get_parent(id);
2930 let trait_def_id = DefId::local(trait_id);
2931 let trait_def = cx.lookup_trait_def(trait_def_id);
2932 let predicates = cx.lookup_predicates(trait_def_id);
2933 cx.construct_parameter_environment(trait_item.span,
2934 &trait_def.generics,
2938 hir::ConstTraitItem(..) => {
2939 let def_id = DefId::local(id);
2940 let scheme = cx.lookup_item_type(def_id);
2941 let predicates = cx.lookup_predicates(def_id);
2942 cx.construct_parameter_environment(trait_item.span,
2947 hir::MethodTraitItem(_, ref body) => {
2948 // for the body-id, use the id of the body
2949 // block, unless this is a trait method with
2950 // no default, then fallback to the method id.
2951 let body_id = body.as_ref().map(|b| b.id).unwrap_or(id);
2952 let method_def_id = DefId::local(id);
2954 match cx.impl_or_trait_item(method_def_id) {
2955 MethodTraitItem(ref method_ty) => {
2956 let method_generics = &method_ty.generics;
2957 let method_bounds = &method_ty.predicates;
2958 cx.construct_parameter_environment(
2966 .bug("ParameterEnvironment::for_item(): \
2967 got non-method item from provided \
2974 Some(ast_map::NodeItem(item)) => {
2976 hir::ItemFn(_, _, _, _, _, ref body) => {
2977 // We assume this is a function.
2978 let fn_def_id = DefId::local(id);
2979 let fn_scheme = cx.lookup_item_type(fn_def_id);
2980 let fn_predicates = cx.lookup_predicates(fn_def_id);
2982 cx.construct_parameter_environment(item.span,
2983 &fn_scheme.generics,
2988 hir::ItemStruct(..) |
2990 hir::ItemConst(..) |
2991 hir::ItemStatic(..) => {
2992 let def_id = DefId::local(id);
2993 let scheme = cx.lookup_item_type(def_id);
2994 let predicates = cx.lookup_predicates(def_id);
2995 cx.construct_parameter_environment(item.span,
3000 hir::ItemTrait(..) => {
3001 let def_id = DefId::local(id);
3002 let trait_def = cx.lookup_trait_def(def_id);
3003 let predicates = cx.lookup_predicates(def_id);
3004 cx.construct_parameter_environment(item.span,
3005 &trait_def.generics,
3010 cx.sess.span_bug(item.span,
3011 "ParameterEnvironment::from_item():
3012 can't create a parameter \
3013 environment for this kind of item")
3017 Some(ast_map::NodeExpr(..)) => {
3018 // This is a convenience to allow closures to work.
3019 ParameterEnvironment::for_item(cx, cx.map.get_parent(id))
3022 cx.sess.bug(&format!("ParameterEnvironment::from_item(): \
3023 `{}` is not an item",
3024 cx.map.node_to_string(id)))
3029 pub fn can_type_implement_copy(&self, self_type: Ty<'tcx>, span: Span)
3030 -> Result<(),CopyImplementationError> {
3033 // FIXME: (@jroesch) float this code up
3034 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(self.clone()), false);
3036 let adt = match self_type.sty {
3037 ty::TyStruct(struct_def, substs) => {
3038 for field in struct_def.all_fields() {
3039 let field_ty = field.ty(tcx, substs);
3040 if infcx.type_moves_by_default(field_ty, span) {
3041 return Err(FieldDoesNotImplementCopy(field.name))
3046 ty::TyEnum(enum_def, substs) => {
3047 for variant in &enum_def.variants {
3048 for field in &variant.fields {
3049 let field_ty = field.ty(tcx, substs);
3050 if infcx.type_moves_by_default(field_ty, span) {
3051 return Err(VariantDoesNotImplementCopy(variant.name))
3057 _ => return Err(TypeIsStructural),
3061 return Err(TypeHasDestructor)
3068 #[derive(Copy, Clone)]
3069 pub enum CopyImplementationError {
3070 FieldDoesNotImplementCopy(Name),
3071 VariantDoesNotImplementCopy(Name),
3076 /// A "type scheme", in ML terminology, is a type combined with some
3077 /// set of generic types that the type is, well, generic over. In Rust
3078 /// terms, it is the "type" of a fn item or struct -- this type will
3079 /// include various generic parameters that must be substituted when
3080 /// the item/struct is referenced. That is called converting the type
3081 /// scheme to a monotype.
3083 /// - `generics`: the set of type parameters and their bounds
3084 /// - `ty`: the base types, which may reference the parameters defined
3087 /// Note that TypeSchemes are also sometimes called "polytypes" (and
3088 /// in fact this struct used to carry that name, so you may find some
3089 /// stray references in a comment or something). We try to reserve the
3090 /// "poly" prefix to refer to higher-ranked things, as in
3093 /// Note that each item also comes with predicates, see
3094 /// `lookup_predicates`.
3095 #[derive(Clone, Debug)]
3096 pub struct TypeScheme<'tcx> {
3097 pub generics: Generics<'tcx>,
3102 flags TraitFlags: u32 {
3103 const NO_TRAIT_FLAGS = 0,
3104 const HAS_DEFAULT_IMPL = 1 << 0,
3105 const IS_OBJECT_SAFE = 1 << 1,
3106 const OBJECT_SAFETY_VALID = 1 << 2,
3107 const IMPLS_VALID = 1 << 3,
3111 /// As `TypeScheme` but for a trait ref.
3112 pub struct TraitDef<'tcx> {
3113 pub unsafety: hir::Unsafety,
3115 /// If `true`, then this trait had the `#[rustc_paren_sugar]`
3116 /// attribute, indicating that it should be used with `Foo()`
3117 /// sugar. This is a temporary thing -- eventually any trait wil
3118 /// be usable with the sugar (or without it).
3119 pub paren_sugar: bool,
3121 /// Generic type definitions. Note that `Self` is listed in here
3122 /// as having a single bound, the trait itself (e.g., in the trait
3123 /// `Eq`, there is a single bound `Self : Eq`). This is so that
3124 /// default methods get to assume that the `Self` parameters
3125 /// implements the trait.
3126 pub generics: Generics<'tcx>,
3128 pub trait_ref: TraitRef<'tcx>,
3130 /// A list of the associated types defined in this trait. Useful
3131 /// for resolving `X::Foo` type markers.
3132 pub associated_type_names: Vec<Name>,
3134 // Impls of this trait. To allow for quicker lookup, the impls are indexed
3135 // by a simplified version of their Self type: impls with a simplifiable
3136 // Self are stored in nonblanket_impls keyed by it, while all other impls
3137 // are stored in blanket_impls.
3139 /// Impls of the trait.
3140 pub nonblanket_impls: RefCell<
3141 FnvHashMap<fast_reject::SimplifiedType, Vec<DefId>>
3144 /// Blanket impls associated with the trait.
3145 pub blanket_impls: RefCell<Vec<DefId>>,
3148 pub flags: Cell<TraitFlags>
3151 impl<'tcx> TraitDef<'tcx> {
3152 // returns None if not yet calculated
3153 pub fn object_safety(&self) -> Option<bool> {
3154 if self.flags.get().intersects(TraitFlags::OBJECT_SAFETY_VALID) {
3155 Some(self.flags.get().intersects(TraitFlags::IS_OBJECT_SAFE))
3161 pub fn set_object_safety(&self, is_safe: bool) {
3162 assert!(self.object_safety().map(|cs| cs == is_safe).unwrap_or(true));
3164 self.flags.get() | if is_safe {
3165 TraitFlags::OBJECT_SAFETY_VALID | TraitFlags::IS_OBJECT_SAFE
3167 TraitFlags::OBJECT_SAFETY_VALID
3172 /// Records a trait-to-implementation mapping.
3173 pub fn record_impl(&self,
3176 impl_trait_ref: TraitRef<'tcx>) {
3177 debug!("TraitDef::record_impl for {:?}, from {:?}",
3178 self, impl_trait_ref);
3180 // We don't want to borrow_mut after we already populated all impls,
3181 // so check if an impl is present with an immutable borrow first.
3182 if let Some(sty) = fast_reject::simplify_type(tcx,
3183 impl_trait_ref.self_ty(), false) {
3184 if let Some(is) = self.nonblanket_impls.borrow().get(&sty) {
3185 if is.contains(&impl_def_id) {
3186 return // duplicate - skip
3190 self.nonblanket_impls.borrow_mut().entry(sty).or_insert(vec![]).push(impl_def_id)
3192 if self.blanket_impls.borrow().contains(&impl_def_id) {
3193 return // duplicate - skip
3195 self.blanket_impls.borrow_mut().push(impl_def_id)
3200 pub fn for_each_impl<F: FnMut(DefId)>(&self, tcx: &ctxt<'tcx>, mut f: F) {
3201 tcx.populate_implementations_for_trait_if_necessary(self.trait_ref.def_id);
3203 for &impl_def_id in self.blanket_impls.borrow().iter() {
3207 for v in self.nonblanket_impls.borrow().values() {
3208 for &impl_def_id in v {
3214 /// Iterate over every impl that could possibly match the
3215 /// self-type `self_ty`.
3216 pub fn for_each_relevant_impl<F: FnMut(DefId)>(&self,
3221 tcx.populate_implementations_for_trait_if_necessary(self.trait_ref.def_id);
3223 for &impl_def_id in self.blanket_impls.borrow().iter() {
3227 // simplify_type(.., false) basically replaces type parameters and
3228 // projections with infer-variables. This is, of course, done on
3229 // the impl trait-ref when it is instantiated, but not on the
3230 // predicate trait-ref which is passed here.
3232 // for example, if we match `S: Copy` against an impl like
3233 // `impl<T:Copy> Copy for Option<T>`, we replace the type variable
3234 // in `Option<T>` with an infer variable, to `Option<_>` (this
3235 // doesn't actually change fast_reject output), but we don't
3236 // replace `S` with anything - this impl of course can't be
3237 // selected, and as there are hundreds of similar impls,
3238 // considering them would significantly harm performance.
3239 if let Some(simp) = fast_reject::simplify_type(tcx, self_ty, true) {
3240 if let Some(impls) = self.nonblanket_impls.borrow().get(&simp) {
3241 for &impl_def_id in impls {
3246 for v in self.nonblanket_impls.borrow().values() {
3247 for &impl_def_id in v {
3257 flags AdtFlags: u32 {
3258 const NO_ADT_FLAGS = 0,
3259 const IS_ENUM = 1 << 0,
3260 const IS_DTORCK = 1 << 1, // is this a dtorck type?
3261 const IS_DTORCK_VALID = 1 << 2,
3262 const IS_PHANTOM_DATA = 1 << 3,
3263 const IS_SIMD = 1 << 4,
3264 const IS_FUNDAMENTAL = 1 << 5,
3265 const IS_NO_DROP_FLAG = 1 << 6,
3269 pub type AdtDef<'tcx> = &'tcx AdtDefData<'tcx, 'static>;
3270 pub type VariantDef<'tcx> = &'tcx VariantDefData<'tcx, 'static>;
3271 pub type FieldDef<'tcx> = &'tcx FieldDefData<'tcx, 'static>;
3273 // See comment on AdtDefData for explanation
3274 pub type AdtDefMaster<'tcx> = &'tcx AdtDefData<'tcx, 'tcx>;
3275 pub type VariantDefMaster<'tcx> = &'tcx VariantDefData<'tcx, 'tcx>;
3276 pub type FieldDefMaster<'tcx> = &'tcx FieldDefData<'tcx, 'tcx>;
3278 pub struct VariantDefData<'tcx, 'container: 'tcx> {
3280 pub name: Name, // struct's name if this is a struct
3282 pub fields: Vec<FieldDefData<'tcx, 'container>>
3285 pub struct FieldDefData<'tcx, 'container: 'tcx> {
3286 /// The field's DefId. NOTE: the fields of tuple-like enum variants
3287 /// are not real items, and don't have entries in tcache etc.
3289 /// special_idents::unnamed_field.name
3290 /// if this is a tuple-like field
3292 pub vis: hir::Visibility,
3293 /// TyIVar is used here to allow for variance (see the doc at
3295 ty: TyIVar<'tcx, 'container>
3298 /// The definition of an abstract data type - a struct or enum.
3300 /// These are all interned (by intern_adt_def) into the adt_defs
3303 /// Because of the possibility of nested tcx-s, this type
3304 /// needs 2 lifetimes: the traditional variant lifetime ('tcx)
3305 /// bounding the lifetime of the inner types is of course necessary.
3306 /// However, it is not sufficient - types from a child tcx must
3307 /// not be leaked into the master tcx by being stored in an AdtDefData.
3309 /// The 'container lifetime ensures that by outliving the container
3310 /// tcx and preventing shorter-lived types from being inserted. When
3311 /// write access is not needed, the 'container lifetime can be
3312 /// erased to 'static, which can be done by the AdtDef wrapper.
3313 pub struct AdtDefData<'tcx, 'container: 'tcx> {
3315 pub variants: Vec<VariantDefData<'tcx, 'container>>,
3316 destructor: Cell<Option<DefId>>,
3317 flags: Cell<AdtFlags>,
3320 impl<'tcx, 'container> PartialEq for AdtDefData<'tcx, 'container> {
3321 // AdtDefData are always interned and this is part of TyS equality
3323 fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
3326 impl<'tcx, 'container> Eq for AdtDefData<'tcx, 'container> {}
3328 impl<'tcx, 'container> Hash for AdtDefData<'tcx, 'container> {
3330 fn hash<H: Hasher>(&self, s: &mut H) {
3331 (self as *const AdtDefData).hash(s)
3336 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3337 pub enum AdtKind { Struct, Enum }
3339 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3340 pub enum VariantKind { Dict, Tuple, Unit }
3342 impl<'tcx, 'container> AdtDefData<'tcx, 'container> {
3343 fn new(tcx: &ctxt<'tcx>,
3346 variants: Vec<VariantDefData<'tcx, 'container>>) -> Self {
3347 let mut flags = AdtFlags::NO_ADT_FLAGS;
3348 let attrs = tcx.get_attrs(did);
3349 if attr::contains_name(&attrs, "fundamental") {
3350 flags = flags | AdtFlags::IS_FUNDAMENTAL;
3352 if attr::contains_name(&attrs, "unsafe_no_drop_flag") {
3353 flags = flags | AdtFlags::IS_NO_DROP_FLAG;
3355 if tcx.lookup_simd(did) {
3356 flags = flags | AdtFlags::IS_SIMD;
3358 if Some(did) == tcx.lang_items.phantom_data() {
3359 flags = flags | AdtFlags::IS_PHANTOM_DATA;
3361 if let AdtKind::Enum = kind {
3362 flags = flags | AdtFlags::IS_ENUM;
3367 flags: Cell::new(flags),
3368 destructor: Cell::new(None)
3372 fn calculate_dtorck(&'tcx self, tcx: &ctxt<'tcx>) {
3373 if tcx.is_adt_dtorck(self) {
3374 self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK);
3376 self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK_VALID)
3379 /// Returns the kind of the ADT - Struct or Enum.
3381 pub fn adt_kind(&self) -> AdtKind {
3382 if self.flags.get().intersects(AdtFlags::IS_ENUM) {
3389 /// Returns whether this is a dtorck type. If this returns
3390 /// true, this type being safe for destruction requires it to be
3391 /// alive; Otherwise, only the contents are required to be.
3393 pub fn is_dtorck(&'tcx self, tcx: &ctxt<'tcx>) -> bool {
3394 if !self.flags.get().intersects(AdtFlags::IS_DTORCK_VALID) {
3395 self.calculate_dtorck(tcx)
3397 self.flags.get().intersects(AdtFlags::IS_DTORCK)
3400 /// Returns whether this type is #[fundamental] for the purposes
3401 /// of coherence checking.
3403 pub fn is_fundamental(&self) -> bool {
3404 self.flags.get().intersects(AdtFlags::IS_FUNDAMENTAL)
3408 pub fn is_simd(&self) -> bool {
3409 self.flags.get().intersects(AdtFlags::IS_SIMD)
3412 /// Returns true if this is PhantomData<T>.
3414 pub fn is_phantom_data(&self) -> bool {
3415 self.flags.get().intersects(AdtFlags::IS_PHANTOM_DATA)
3418 /// Returns whether this type has a destructor.
3419 pub fn has_dtor(&self) -> bool {
3420 match self.dtor_kind() {
3422 TraitDtor(..) => true
3426 /// Asserts this is a struct and returns the struct's unique
3428 pub fn struct_variant(&self) -> &VariantDefData<'tcx, 'container> {
3429 assert!(self.adt_kind() == AdtKind::Struct);
3434 pub fn type_scheme(&self, tcx: &ctxt<'tcx>) -> TypeScheme<'tcx> {
3435 tcx.lookup_item_type(self.did)
3439 pub fn predicates(&self, tcx: &ctxt<'tcx>) -> GenericPredicates<'tcx> {
3440 tcx.lookup_predicates(self.did)
3443 /// Returns an iterator over all fields contained
3446 pub fn all_fields(&self) ->
3448 slice::Iter<VariantDefData<'tcx, 'container>>,
3449 slice::Iter<FieldDefData<'tcx, 'container>>,
3450 for<'s> fn(&'s VariantDefData<'tcx, 'container>)
3451 -> slice::Iter<'s, FieldDefData<'tcx, 'container>>
3453 self.variants.iter().flat_map(VariantDefData::fields_iter)
3457 pub fn is_empty(&self) -> bool {
3458 self.variants.is_empty()
3462 pub fn is_univariant(&self) -> bool {
3463 self.variants.len() == 1
3466 pub fn is_payloadfree(&self) -> bool {
3467 !self.variants.is_empty() &&
3468 self.variants.iter().all(|v| v.fields.is_empty())
3471 pub fn variant_with_id(&self, vid: DefId) -> &VariantDefData<'tcx, 'container> {
3474 .find(|v| v.did == vid)
3475 .expect("variant_with_id: unknown variant")
3478 pub fn variant_index_with_id(&self, vid: DefId) -> usize {
3481 .position(|v| v.did == vid)
3482 .expect("variant_index_with_id: unknown variant")
3485 pub fn variant_of_def(&self, def: def::Def) -> &VariantDefData<'tcx, 'container> {
3487 def::DefVariant(_, vid, _) => self.variant_with_id(vid),
3488 def::DefStruct(..) | def::DefTy(..) => self.struct_variant(),
3489 _ => panic!("unexpected def {:?} in variant_of_def", def)
3493 pub fn destructor(&self) -> Option<DefId> {
3494 self.destructor.get()
3497 pub fn set_destructor(&self, dtor: DefId) {
3498 assert!(self.destructor.get().is_none());
3499 self.destructor.set(Some(dtor));
3502 pub fn dtor_kind(&self) -> DtorKind {
3503 match self.destructor.get() {
3505 TraitDtor(!self.flags.get().intersects(AdtFlags::IS_NO_DROP_FLAG))
3512 impl<'tcx, 'container> VariantDefData<'tcx, 'container> {
3514 fn fields_iter(&self) -> slice::Iter<FieldDefData<'tcx, 'container>> {
3518 pub fn kind(&self) -> VariantKind {
3519 match self.fields.get(0) {
3520 None => VariantKind::Unit,
3521 Some(&FieldDefData { name, .. }) if name == special_idents::unnamed_field.name => {
3524 Some(_) => VariantKind::Dict
3528 pub fn is_tuple_struct(&self) -> bool {
3529 self.kind() == VariantKind::Tuple
3533 pub fn find_field_named(&self,
3535 -> Option<&FieldDefData<'tcx, 'container>> {
3536 self.fields.iter().find(|f| f.name == name)
3540 pub fn field_named(&self, name: ast::Name) -> &FieldDefData<'tcx, 'container> {
3541 self.find_field_named(name).unwrap()
3545 impl<'tcx, 'container> FieldDefData<'tcx, 'container> {
3546 pub fn new(did: DefId,
3548 vis: hir::Visibility) -> Self {
3557 pub fn ty(&self, tcx: &ctxt<'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
3558 self.unsubst_ty().subst(tcx, subst)
3561 pub fn unsubst_ty(&self) -> Ty<'tcx> {
3565 pub fn fulfill_ty(&self, ty: Ty<'container>) {
3566 self.ty.fulfill(ty);
3570 /// Records the substitutions used to translate the polytype for an
3571 /// item into the monotype of an item reference.
3573 pub struct ItemSubsts<'tcx> {
3574 pub substs: Substs<'tcx>,
3577 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
3578 pub enum ClosureKind {
3579 // Warning: Ordering is significant here! The ordering is chosen
3580 // because the trait Fn is a subtrait of FnMut and so in turn, and
3581 // hence we order it so that Fn < FnMut < FnOnce.
3588 pub fn trait_did(&self, cx: &ctxt) -> DefId {
3589 let result = match *self {
3590 FnClosureKind => cx.lang_items.require(FnTraitLangItem),
3591 FnMutClosureKind => {
3592 cx.lang_items.require(FnMutTraitLangItem)
3594 FnOnceClosureKind => {
3595 cx.lang_items.require(FnOnceTraitLangItem)
3599 Ok(trait_did) => trait_did,
3600 Err(err) => cx.sess.fatal(&err[..]),
3604 /// True if this a type that impls this closure kind
3605 /// must also implement `other`.
3606 pub fn extends(self, other: ty::ClosureKind) -> bool {
3607 match (self, other) {
3608 (FnClosureKind, FnClosureKind) => true,
3609 (FnClosureKind, FnMutClosureKind) => true,
3610 (FnClosureKind, FnOnceClosureKind) => true,
3611 (FnMutClosureKind, FnMutClosureKind) => true,
3612 (FnMutClosureKind, FnOnceClosureKind) => true,
3613 (FnOnceClosureKind, FnOnceClosureKind) => true,
3619 impl<'tcx> CommonTypes<'tcx> {
3620 fn new(arena: &'tcx TypedArena<TyS<'tcx>>,
3621 interner: &RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>)
3622 -> CommonTypes<'tcx>
3624 let mk = |sty| ctxt::intern_ty(arena, interner, sty);
3629 isize: mk(TyInt(hir::TyIs)),
3630 i8: mk(TyInt(hir::TyI8)),
3631 i16: mk(TyInt(hir::TyI16)),
3632 i32: mk(TyInt(hir::TyI32)),
3633 i64: mk(TyInt(hir::TyI64)),
3634 usize: mk(TyUint(hir::TyUs)),
3635 u8: mk(TyUint(hir::TyU8)),
3636 u16: mk(TyUint(hir::TyU16)),
3637 u32: mk(TyUint(hir::TyU32)),
3638 u64: mk(TyUint(hir::TyU64)),
3639 f32: mk(TyFloat(hir::TyF32)),
3640 f64: mk(TyFloat(hir::TyF64)),
3645 struct FlagComputation {
3648 // maximum depth of any bound region that we have seen thus far
3652 impl FlagComputation {
3653 fn new() -> FlagComputation {
3654 FlagComputation { flags: TypeFlags::empty(), depth: 0 }
3657 fn for_sty(st: &TypeVariants) -> FlagComputation {
3658 let mut result = FlagComputation::new();
3663 fn add_flags(&mut self, flags: TypeFlags) {
3664 self.flags = self.flags | (flags & TypeFlags::NOMINAL_FLAGS);
3667 fn add_depth(&mut self, depth: u32) {
3668 if depth > self.depth {
3673 /// Adds the flags/depth from a set of types that appear within the current type, but within a
3675 fn add_bound_computation(&mut self, computation: &FlagComputation) {
3676 self.add_flags(computation.flags);
3678 // The types that contributed to `computation` occurred within
3679 // a region binder, so subtract one from the region depth
3680 // within when adding the depth to `self`.
3681 let depth = computation.depth;
3683 self.add_depth(depth - 1);
3687 fn add_sty(&mut self, st: &TypeVariants) {
3697 // You might think that we could just return TyError for
3698 // any type containing TyError as a component, and get
3699 // rid of the TypeFlags::HAS_TY_ERR flag -- likewise for ty_bot (with
3700 // the exception of function types that return bot).
3701 // But doing so caused sporadic memory corruption, and
3702 // neither I (tjc) nor nmatsakis could figure out why,
3703 // so we're doing it this way.
3705 self.add_flags(TypeFlags::HAS_TY_ERR)
3708 &TyParam(ref p) => {
3709 self.add_flags(TypeFlags::HAS_LOCAL_NAMES);
3710 if p.space == subst::SelfSpace {
3711 self.add_flags(TypeFlags::HAS_SELF);
3713 self.add_flags(TypeFlags::HAS_PARAMS);
3717 &TyClosure(_, ref substs) => {
3718 self.add_flags(TypeFlags::HAS_TY_CLOSURE);
3719 self.add_flags(TypeFlags::HAS_LOCAL_NAMES);
3720 self.add_substs(&substs.func_substs);
3721 self.add_tys(&substs.upvar_tys);
3725 self.add_flags(TypeFlags::HAS_LOCAL_NAMES); // it might, right?
3726 self.add_flags(TypeFlags::HAS_TY_INFER)
3729 &TyEnum(_, substs) | &TyStruct(_, substs) => {
3730 self.add_substs(substs);
3733 &TyProjection(ref data) => {
3734 self.add_flags(TypeFlags::HAS_PROJECTION);
3735 self.add_projection_ty(data);
3738 &TyTrait(box TraitTy { ref principal, ref bounds }) => {
3739 let mut computation = FlagComputation::new();
3740 computation.add_substs(principal.0.substs);
3741 for projection_bound in &bounds.projection_bounds {
3742 let mut proj_computation = FlagComputation::new();
3743 proj_computation.add_projection_predicate(&projection_bound.0);
3744 self.add_bound_computation(&proj_computation);
3746 self.add_bound_computation(&computation);
3748 self.add_bounds(bounds);
3751 &TyBox(tt) | &TyArray(tt, _) | &TySlice(tt) => {
3755 &TyRawPtr(ref m) => {
3759 &TyRef(r, ref m) => {
3760 self.add_region(*r);
3764 &TyTuple(ref ts) => {
3765 self.add_tys(&ts[..]);
3768 &TyBareFn(_, ref f) => {
3769 self.add_fn_sig(&f.sig);
3774 fn add_ty(&mut self, ty: Ty) {
3775 self.add_flags(ty.flags.get());
3776 self.add_depth(ty.region_depth);
3779 fn add_tys(&mut self, tys: &[Ty]) {
3785 fn add_fn_sig(&mut self, fn_sig: &PolyFnSig) {
3786 let mut computation = FlagComputation::new();
3788 computation.add_tys(&fn_sig.0.inputs);
3790 if let ty::FnConverging(output) = fn_sig.0.output {
3791 computation.add_ty(output);
3794 self.add_bound_computation(&computation);
3797 fn add_region(&mut self, r: Region) {
3800 ty::ReSkolemized(..) => { self.add_flags(TypeFlags::HAS_RE_INFER); }
3801 ty::ReLateBound(debruijn, _) => { self.add_depth(debruijn.depth); }
3802 ty::ReEarlyBound(..) => { self.add_flags(TypeFlags::HAS_RE_EARLY_BOUND); }
3804 _ => { self.add_flags(TypeFlags::HAS_FREE_REGIONS); }
3808 self.add_flags(TypeFlags::HAS_LOCAL_NAMES);
3812 fn add_projection_predicate(&mut self, projection_predicate: &ProjectionPredicate) {
3813 self.add_projection_ty(&projection_predicate.projection_ty);
3814 self.add_ty(projection_predicate.ty);
3817 fn add_projection_ty(&mut self, projection_ty: &ProjectionTy) {
3818 self.add_substs(projection_ty.trait_ref.substs);
3821 fn add_substs(&mut self, substs: &Substs) {
3822 self.add_tys(substs.types.as_slice());
3823 match substs.regions {
3824 subst::ErasedRegions => {}
3825 subst::NonerasedRegions(ref regions) => {
3833 fn add_bounds(&mut self, bounds: &ExistentialBounds) {
3834 self.add_region(bounds.region_bound);
3838 impl<'tcx> ctxt<'tcx> {
3839 /// Create a type context and call the closure with a `&ty::ctxt` reference
3840 /// to the context. The closure enforces that the type context and any interned
3841 /// value (types, substs, etc.) can only be used while `ty::tls` has a valid
3842 /// reference to the context, to allow formatting values that need it.
3843 pub fn create_and_enter<F, R>(s: Session,
3844 arenas: &'tcx CtxtArenas<'tcx>,
3846 named_region_map: resolve_lifetime::NamedRegionMap,
3847 map: ast_map::Map<'tcx>,
3848 freevars: RefCell<FreevarMap>,
3849 region_maps: RegionMaps,
3850 lang_items: middle::lang_items::LanguageItems,
3851 stability: stability::Index<'tcx>,
3852 f: F) -> (Session, R)
3853 where F: FnOnce(&ctxt<'tcx>) -> R
3855 let interner = RefCell::new(FnvHashMap());
3856 let common_types = CommonTypes::new(&arenas.type_, &interner);
3861 substs_interner: RefCell::new(FnvHashMap()),
3862 bare_fn_interner: RefCell::new(FnvHashMap()),
3863 region_interner: RefCell::new(FnvHashMap()),
3864 stability_interner: RefCell::new(FnvHashMap()),
3865 types: common_types,
3866 named_region_map: named_region_map,
3867 region_maps: region_maps,
3868 free_region_maps: RefCell::new(FnvHashMap()),
3869 item_variance_map: RefCell::new(DefIdMap()),
3870 variance_computed: Cell::new(false),
3873 tables: RefCell::new(Tables::empty()),
3874 impl_trait_refs: RefCell::new(DefIdMap()),
3875 trait_defs: RefCell::new(DefIdMap()),
3876 adt_defs: RefCell::new(DefIdMap()),
3877 predicates: RefCell::new(DefIdMap()),
3878 super_predicates: RefCell::new(DefIdMap()),
3879 fulfilled_predicates: RefCell::new(traits::FulfilledPredicates::new()),
3882 tcache: RefCell::new(DefIdMap()),
3883 rcache: RefCell::new(FnvHashMap()),
3884 tc_cache: RefCell::new(FnvHashMap()),
3885 ast_ty_to_ty_cache: RefCell::new(NodeMap()),
3886 impl_or_trait_items: RefCell::new(DefIdMap()),
3887 trait_item_def_ids: RefCell::new(DefIdMap()),
3888 trait_items_cache: RefCell::new(DefIdMap()),
3889 ty_param_defs: RefCell::new(NodeMap()),
3890 normalized_cache: RefCell::new(FnvHashMap()),
3891 lang_items: lang_items,
3892 provided_method_sources: RefCell::new(DefIdMap()),
3893 destructors: RefCell::new(DefIdSet()),
3894 inherent_impls: RefCell::new(DefIdMap()),
3895 impl_items: RefCell::new(DefIdMap()),
3896 used_unsafe: RefCell::new(NodeSet()),
3897 used_mut_nodes: RefCell::new(NodeSet()),
3898 populated_external_types: RefCell::new(DefIdSet()),
3899 populated_external_primitive_impls: RefCell::new(DefIdSet()),
3900 extern_const_statics: RefCell::new(DefIdMap()),
3901 extern_const_variants: RefCell::new(DefIdMap()),
3902 extern_const_fns: RefCell::new(DefIdMap()),
3903 node_lint_levels: RefCell::new(FnvHashMap()),
3904 transmute_restrictions: RefCell::new(Vec::new()),
3905 stability: RefCell::new(stability),
3906 selection_cache: traits::SelectionCache::new(),
3907 repr_hint_cache: RefCell::new(DefIdMap()),
3908 const_qualif_map: RefCell::new(NodeMap()),
3909 custom_coerce_unsized_kinds: RefCell::new(DefIdMap()),
3910 cast_kinds: RefCell::new(NodeMap()),
3911 fragment_infos: RefCell::new(DefIdMap()),
3915 // Type constructors
3917 pub fn mk_substs(&self, substs: Substs<'tcx>) -> &'tcx Substs<'tcx> {
3918 if let Some(substs) = self.substs_interner.borrow().get(&substs) {
3922 let substs = self.arenas.substs.alloc(substs);
3923 self.substs_interner.borrow_mut().insert(substs, substs);
3927 /// Create an unsafe fn ty based on a safe fn ty.
3928 pub fn safe_to_unsafe_fn_ty(&self, bare_fn: &BareFnTy<'tcx>) -> Ty<'tcx> {
3929 assert_eq!(bare_fn.unsafety, hir::Unsafety::Normal);
3930 let unsafe_fn_ty_a = self.mk_bare_fn(ty::BareFnTy {
3931 unsafety: hir::Unsafety::Unsafe,
3933 sig: bare_fn.sig.clone()
3935 self.mk_fn(None, unsafe_fn_ty_a)
3938 pub fn mk_bare_fn(&self, bare_fn: BareFnTy<'tcx>) -> &'tcx BareFnTy<'tcx> {
3939 if let Some(bare_fn) = self.bare_fn_interner.borrow().get(&bare_fn) {
3943 let bare_fn = self.arenas.bare_fn.alloc(bare_fn);
3944 self.bare_fn_interner.borrow_mut().insert(bare_fn, bare_fn);
3948 pub fn mk_region(&self, region: Region) -> &'tcx Region {
3949 if let Some(region) = self.region_interner.borrow().get(®ion) {
3953 let region = self.arenas.region.alloc(region);
3954 self.region_interner.borrow_mut().insert(region, region);
3958 pub fn closure_kind(&self, def_id: DefId) -> ty::ClosureKind {
3959 *self.tables.borrow().closure_kinds.get(&def_id).unwrap()
3962 pub fn closure_type(&self,
3964 substs: &ClosureSubsts<'tcx>)
3965 -> ty::ClosureTy<'tcx>
3967 self.tables.borrow().closure_tys.get(&def_id).unwrap().subst(self, &substs.func_substs)
3970 pub fn type_parameter_def(&self,
3972 -> TypeParameterDef<'tcx>
3974 self.ty_param_defs.borrow().get(&node_id).unwrap().clone()
3977 pub fn pat_contains_ref_binding(&self, pat: &hir::Pat) -> Option<hir::Mutability> {
3978 pat_util::pat_contains_ref_binding(&self.def_map, pat)
3981 pub fn arm_contains_ref_binding(&self, arm: &hir::Arm) -> Option<hir::Mutability> {
3982 pat_util::arm_contains_ref_binding(&self.def_map, arm)
3985 fn intern_ty(type_arena: &'tcx TypedArena<TyS<'tcx>>,
3986 interner: &RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>,
3987 st: TypeVariants<'tcx>)
3989 let ty: Ty /* don't be &mut TyS */ = {
3990 let mut interner = interner.borrow_mut();
3991 match interner.get(&st) {
3992 Some(ty) => return *ty,
3996 let flags = FlagComputation::for_sty(&st);
3999 () => type_arena.alloc(TyS { sty: st,
4000 flags: Cell::new(flags.flags),
4001 region_depth: flags.depth, }),
4004 interner.insert(InternedTy { ty: ty }, ty);
4008 debug!("Interned type: {:?} Pointer: {:?}",
4009 ty, ty as *const TyS);
4013 // Interns a type/name combination, stores the resulting box in cx.interner,
4014 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
4015 pub fn mk_ty(&self, st: TypeVariants<'tcx>) -> Ty<'tcx> {
4016 ctxt::intern_ty(&self.arenas.type_, &self.interner, st)
4019 pub fn mk_mach_int(&self, tm: hir::IntTy) -> Ty<'tcx> {
4021 hir::TyIs => self.types.isize,
4022 hir::TyI8 => self.types.i8,
4023 hir::TyI16 => self.types.i16,
4024 hir::TyI32 => self.types.i32,
4025 hir::TyI64 => self.types.i64,
4029 pub fn mk_mach_uint(&self, tm: hir::UintTy) -> Ty<'tcx> {
4031 hir::TyUs => self.types.usize,
4032 hir::TyU8 => self.types.u8,
4033 hir::TyU16 => self.types.u16,
4034 hir::TyU32 => self.types.u32,
4035 hir::TyU64 => self.types.u64,
4039 pub fn mk_mach_float(&self, tm: hir::FloatTy) -> Ty<'tcx> {
4041 hir::TyF32 => self.types.f32,
4042 hir::TyF64 => self.types.f64,
4046 pub fn mk_str(&self) -> Ty<'tcx> {
4050 pub fn mk_static_str(&self) -> Ty<'tcx> {
4051 self.mk_imm_ref(self.mk_region(ty::ReStatic), self.mk_str())
4054 pub fn mk_enum(&self, def: AdtDef<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
4055 // take a copy of substs so that we own the vectors inside
4056 self.mk_ty(TyEnum(def, substs))
4059 pub fn mk_box(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4060 self.mk_ty(TyBox(ty))
4063 pub fn mk_ptr(&self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
4064 self.mk_ty(TyRawPtr(tm))
4067 pub fn mk_ref(&self, r: &'tcx Region, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
4068 self.mk_ty(TyRef(r, tm))
4071 pub fn mk_mut_ref(&self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
4072 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutMutable})
4075 pub fn mk_imm_ref(&self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
4076 self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
4079 pub fn mk_mut_ptr(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4080 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutMutable})
4083 pub fn mk_imm_ptr(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4084 self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::MutImmutable})
4087 pub fn mk_nil_ptr(&self) -> Ty<'tcx> {
4088 self.mk_imm_ptr(self.mk_nil())
4091 pub fn mk_array(&self, ty: Ty<'tcx>, n: usize) -> Ty<'tcx> {
4092 self.mk_ty(TyArray(ty, n))
4095 pub fn mk_slice(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
4096 self.mk_ty(TySlice(ty))
4099 pub fn mk_tup(&self, ts: Vec<Ty<'tcx>>) -> Ty<'tcx> {
4100 self.mk_ty(TyTuple(ts))
4103 pub fn mk_nil(&self) -> Ty<'tcx> {
4104 self.mk_tup(Vec::new())
4107 pub fn mk_bool(&self) -> Ty<'tcx> {
4112 opt_def_id: Option<DefId>,
4113 fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
4114 self.mk_ty(TyBareFn(opt_def_id, fty))
4117 pub fn mk_ctor_fn(&self,
4119 input_tys: &[Ty<'tcx>],
4120 output: Ty<'tcx>) -> Ty<'tcx> {
4121 let input_args = input_tys.iter().cloned().collect();
4122 self.mk_fn(Some(def_id), self.mk_bare_fn(BareFnTy {
4123 unsafety: hir::Unsafety::Normal,
4125 sig: ty::Binder(FnSig {
4127 output: ty::FnConverging(output),
4133 pub fn mk_trait(&self,
4134 principal: ty::PolyTraitRef<'tcx>,
4135 bounds: ExistentialBounds<'tcx>)
4138 assert!(bound_list_is_sorted(&bounds.projection_bounds));
4140 let inner = box TraitTy {
4141 principal: principal,
4144 self.mk_ty(TyTrait(inner))
4147 pub fn mk_projection(&self,
4148 trait_ref: TraitRef<'tcx>,
4151 // take a copy of substs so that we own the vectors inside
4152 let inner = ProjectionTy { trait_ref: trait_ref, item_name: item_name };
4153 self.mk_ty(TyProjection(inner))
4156 pub fn mk_struct(&self, def: AdtDef<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
4157 // take a copy of substs so that we own the vectors inside
4158 self.mk_ty(TyStruct(def, substs))
4161 pub fn mk_closure(&self,
4163 substs: &'tcx Substs<'tcx>,
4166 self.mk_closure_from_closure_substs(closure_id, Box::new(ClosureSubsts {
4167 func_substs: substs,
4172 pub fn mk_closure_from_closure_substs(&self,
4174 closure_substs: Box<ClosureSubsts<'tcx>>)
4176 self.mk_ty(TyClosure(closure_id, closure_substs))
4179 pub fn mk_var(&self, v: TyVid) -> Ty<'tcx> {
4180 self.mk_infer(TyVar(v))
4183 pub fn mk_int_var(&self, v: IntVid) -> Ty<'tcx> {
4184 self.mk_infer(IntVar(v))
4187 pub fn mk_float_var(&self, v: FloatVid) -> Ty<'tcx> {
4188 self.mk_infer(FloatVar(v))
4191 pub fn mk_infer(&self, it: InferTy) -> Ty<'tcx> {
4192 self.mk_ty(TyInfer(it))
4195 pub fn mk_param(&self,
4196 space: subst::ParamSpace,
4198 name: Name) -> Ty<'tcx> {
4199 self.mk_ty(TyParam(ParamTy { space: space, idx: index, name: name }))
4202 pub fn mk_self_type(&self) -> Ty<'tcx> {
4203 self.mk_param(subst::SelfSpace, 0, special_idents::type_self.name)
4206 pub fn mk_param_from_def(&self, def: &TypeParameterDef) -> Ty<'tcx> {
4207 self.mk_param(def.space, def.index, def.name)
4211 fn bound_list_is_sorted(bounds: &[ty::PolyProjectionPredicate]) -> bool {
4212 bounds.is_empty() ||
4213 bounds[1..].iter().enumerate().all(
4214 |(index, bound)| bounds[index].sort_key() <= bound.sort_key())
4217 pub fn sort_bounds_list(bounds: &mut [ty::PolyProjectionPredicate]) {
4218 bounds.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()))
4221 impl<'tcx> TyS<'tcx> {
4222 /// Iterator that walks `self` and any types reachable from
4223 /// `self`, in depth-first order. Note that just walks the types
4224 /// that appear in `self`, it does not descend into the fields of
4225 /// structs or variants. For example:
4228 /// isize => { isize }
4229 /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
4230 /// [isize] => { [isize], isize }
4232 pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
4233 TypeWalker::new(self)
4236 /// Iterator that walks the immediate children of `self`. Hence
4237 /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
4238 /// (but not `i32`, like `walk`).
4239 pub fn walk_shallow(&'tcx self) -> IntoIter<Ty<'tcx>> {
4240 ty_walk::walk_shallow(self)
4243 pub fn as_opt_param_ty(&self) -> Option<ty::ParamTy> {
4245 ty::TyParam(ref d) => Some(d.clone()),
4250 pub fn is_param(&self, space: ParamSpace, index: u32) -> bool {
4252 ty::TyParam(ref data) => data.space == space && data.idx == index,
4257 /// Returns the regions directly referenced from this type (but
4258 /// not types reachable from this type via `walk_tys`). This
4259 /// ignores late-bound regions binders.
4260 pub fn regions(&self) -> Vec<ty::Region> {
4262 TyRef(region, _) => {
4265 TyTrait(ref obj) => {
4266 let mut v = vec![obj.bounds.region_bound];
4267 v.push_all(obj.principal.skip_binder().substs.regions().as_slice());
4271 TyStruct(_, substs) => {
4272 substs.regions().as_slice().to_vec()
4274 TyClosure(_, ref substs) => {
4275 substs.func_substs.regions().as_slice().to_vec()
4277 TyProjection(ref data) => {
4278 data.trait_ref.substs.regions().as_slice().to_vec()
4300 /// Walks `ty` and any types appearing within `ty`, invoking the
4301 /// callback `f` on each type. If the callback returns false, then the
4302 /// children of the current type are ignored.
4304 /// Note: prefer `ty.walk()` where possible.
4305 pub fn maybe_walk<F>(&'tcx self, mut f: F)
4306 where F : FnMut(Ty<'tcx>) -> bool
4308 let mut walker = self.walk();
4309 while let Some(ty) = walker.next() {
4311 walker.skip_current_subtree();
4318 pub fn new(space: subst::ParamSpace,
4322 ParamTy { space: space, idx: index, name: name }
4325 pub fn for_self() -> ParamTy {
4326 ParamTy::new(subst::SelfSpace, 0, special_idents::type_self.name)
4329 pub fn for_def(def: &TypeParameterDef) -> ParamTy {
4330 ParamTy::new(def.space, def.index, def.name)
4333 pub fn to_ty<'tcx>(self, tcx: &ctxt<'tcx>) -> Ty<'tcx> {
4334 tcx.mk_param(self.space, self.idx, self.name)
4337 pub fn is_self(&self) -> bool {
4338 self.space == subst::SelfSpace && self.idx == 0
4342 impl<'tcx> ItemSubsts<'tcx> {
4343 pub fn empty() -> ItemSubsts<'tcx> {
4344 ItemSubsts { substs: Substs::empty() }
4347 pub fn is_noop(&self) -> bool {
4348 self.substs.is_noop()
4353 impl<'tcx> TyS<'tcx> {
4354 pub fn is_nil(&self) -> bool {
4356 TyTuple(ref tys) => tys.is_empty(),
4361 pub fn is_empty(&self, _cx: &ctxt) -> bool {
4362 // FIXME(#24885): be smarter here
4364 TyEnum(def, _) | TyStruct(def, _) => def.is_empty(),
4369 pub fn is_ty_var(&self) -> bool {
4371 TyInfer(TyVar(_)) => true,
4376 pub fn is_bool(&self) -> bool { self.sty == TyBool }
4378 pub fn is_self(&self) -> bool {
4380 TyParam(ref p) => p.space == subst::SelfSpace,
4385 fn is_slice(&self) -> bool {
4387 TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
4388 TySlice(_) | TyStr => true,
4395 pub fn is_structural(&self) -> bool {
4397 TyStruct(..) | TyTuple(_) | TyEnum(..) |
4398 TyArray(..) | TyClosure(..) => true,
4399 _ => self.is_slice() | self.is_trait()
4404 pub fn is_simd(&self) -> bool {
4406 TyStruct(def, _) => def.is_simd(),
4411 pub fn sequence_element_type(&self, cx: &ctxt<'tcx>) -> Ty<'tcx> {
4413 TyArray(ty, _) | TySlice(ty) => ty,
4414 TyStr => cx.mk_mach_uint(hir::TyU8),
4415 _ => cx.sess.bug(&format!("sequence_element_type called on non-sequence value: {}",
4420 pub fn simd_type(&self, cx: &ctxt<'tcx>) -> Ty<'tcx> {
4422 TyStruct(def, substs) => {
4423 def.struct_variant().fields[0].ty(cx, substs)
4425 _ => panic!("simd_type called on invalid type")
4429 pub fn simd_size(&self, _cx: &ctxt) -> usize {
4431 TyStruct(def, _) => def.struct_variant().fields.len(),
4432 _ => panic!("simd_size called on invalid type")
4436 pub fn is_region_ptr(&self) -> bool {
4443 pub fn is_unsafe_ptr(&self) -> bool {
4445 TyRawPtr(_) => return true,
4450 pub fn is_unique(&self) -> bool {
4458 A scalar type is one that denotes an atomic datum, with no sub-components.
4459 (A TyRawPtr is scalar because it represents a non-managed pointer, so its
4460 contents are abstract to rustc.)
4462 pub fn is_scalar(&self) -> bool {
4464 TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
4465 TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
4466 TyBareFn(..) | TyRawPtr(_) => true,
4471 /// Returns true if this type is a floating point type and false otherwise.
4472 pub fn is_floating_point(&self) -> bool {
4475 TyInfer(FloatVar(_)) => true,
4480 pub fn ty_to_def_id(&self) -> Option<DefId> {
4482 TyTrait(ref tt) => Some(tt.principal_def_id()),
4484 TyEnum(def, _) => Some(def.did),
4485 TyClosure(id, _) => Some(id),
4490 pub fn ty_adt_def(&self) -> Option<AdtDef<'tcx>> {
4492 TyStruct(adt, _) | TyEnum(adt, _) => Some(adt),
4498 /// Type contents is how the type checker reasons about kinds.
4499 /// They track what kinds of things are found within a type. You can
4500 /// think of them as kind of an "anti-kind". They track the kinds of values
4501 /// and thinks that are contained in types. Having a larger contents for
4502 /// a type tends to rule that type *out* from various kinds. For example,
4503 /// a type that contains a reference is not sendable.
4505 /// The reason we compute type contents and not kinds is that it is
4506 /// easier for me (nmatsakis) to think about what is contained within
4507 /// a type than to think about what is *not* contained within a type.
4508 #[derive(Clone, Copy)]
4509 pub struct TypeContents {
4513 macro_rules! def_type_content_sets {
4514 (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
4515 #[allow(non_snake_case)]
4517 use middle::ty::TypeContents;
4519 #[allow(non_upper_case_globals)]
4520 pub const $name: TypeContents = TypeContents { bits: $bits };
4526 def_type_content_sets! {
4528 None = 0b0000_0000__0000_0000__0000,
4530 // Things that are interior to the value (first nibble):
4531 InteriorUnsafe = 0b0000_0000__0000_0000__0010,
4532 InteriorParam = 0b0000_0000__0000_0000__0100,
4533 // InteriorAll = 0b00000000__00000000__1111,
4535 // Things that are owned by the value (second and third nibbles):
4536 OwnsOwned = 0b0000_0000__0000_0001__0000,
4537 OwnsDtor = 0b0000_0000__0000_0010__0000,
4538 OwnsAll = 0b0000_0000__1111_1111__0000,
4540 // Things that mean drop glue is necessary
4541 NeedsDrop = 0b0000_0000__0000_0111__0000,
4544 All = 0b1111_1111__1111_1111__1111
4549 pub fn when(&self, cond: bool) -> TypeContents {
4550 if cond {*self} else {TC::None}
4553 pub fn intersects(&self, tc: TypeContents) -> bool {
4554 (self.bits & tc.bits) != 0
4557 pub fn owns_owned(&self) -> bool {
4558 self.intersects(TC::OwnsOwned)
4561 pub fn interior_param(&self) -> bool {
4562 self.intersects(TC::InteriorParam)
4565 pub fn interior_unsafe(&self) -> bool {
4566 self.intersects(TC::InteriorUnsafe)
4569 pub fn needs_drop(&self, _: &ctxt) -> bool {
4570 self.intersects(TC::NeedsDrop)
4573 /// Includes only those bits that still apply when indirected through a `Box` pointer
4574 pub fn owned_pointer(&self) -> TypeContents {
4575 TC::OwnsOwned | (*self & TC::OwnsAll)
4578 pub fn union<T, F>(v: &[T], mut f: F) -> TypeContents where
4579 F: FnMut(&T) -> TypeContents,
4581 v.iter().fold(TC::None, |tc, ty| tc | f(ty))
4584 pub fn has_dtor(&self) -> bool {
4585 self.intersects(TC::OwnsDtor)
4589 impl ops::BitOr for TypeContents {
4590 type Output = TypeContents;
4592 fn bitor(self, other: TypeContents) -> TypeContents {
4593 TypeContents {bits: self.bits | other.bits}
4597 impl ops::BitAnd for TypeContents {
4598 type Output = TypeContents;
4600 fn bitand(self, other: TypeContents) -> TypeContents {
4601 TypeContents {bits: self.bits & other.bits}
4605 impl ops::Sub for TypeContents {
4606 type Output = TypeContents;
4608 fn sub(self, other: TypeContents) -> TypeContents {
4609 TypeContents {bits: self.bits & !other.bits}
4613 impl fmt::Debug for TypeContents {
4614 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4615 write!(f, "TypeContents({:b})", self.bits)
4619 impl<'tcx> TyS<'tcx> {
4620 pub fn type_contents(&'tcx self, cx: &ctxt<'tcx>) -> TypeContents {
4621 return memoized(&cx.tc_cache, self, |ty| {
4622 tc_ty(cx, ty, &mut FnvHashMap())
4625 fn tc_ty<'tcx>(cx: &ctxt<'tcx>,
4627 cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
4629 // Subtle: Note that we are *not* using cx.tc_cache here but rather a
4630 // private cache for this walk. This is needed in the case of cyclic
4633 // struct List { next: Box<Option<List>>, ... }
4635 // When computing the type contents of such a type, we wind up deeply
4636 // recursing as we go. So when we encounter the recursive reference
4637 // to List, we temporarily use TC::None as its contents. Later we'll
4638 // patch up the cache with the correct value, once we've computed it
4639 // (this is basically a co-inductive process, if that helps). So in
4640 // the end we'll compute TC::OwnsOwned, in this case.
4642 // The problem is, as we are doing the computation, we will also
4643 // compute an *intermediate* contents for, e.g., Option<List> of
4644 // TC::None. This is ok during the computation of List itself, but if
4645 // we stored this intermediate value into cx.tc_cache, then later
4646 // requests for the contents of Option<List> would also yield TC::None
4647 // which is incorrect. This value was computed based on the crutch
4648 // value for the type contents of list. The correct value is
4649 // TC::OwnsOwned. This manifested as issue #4821.
4650 match cache.get(&ty) {
4651 Some(tc) => { return *tc; }
4654 match cx.tc_cache.borrow().get(&ty) { // Must check both caches!
4655 Some(tc) => { return *tc; }
4658 cache.insert(ty, TC::None);
4660 let result = match ty.sty {
4661 // usize and isize are ffi-unsafe
4662 TyUint(hir::TyUs) | TyInt(hir::TyIs) => {
4666 // Scalar and unique types are sendable, and durable
4667 TyInfer(ty::FreshIntTy(_)) | TyInfer(ty::FreshFloatTy(_)) |
4668 TyBool | TyInt(_) | TyUint(_) | TyFloat(_) |
4669 TyBareFn(..) | ty::TyChar => {
4674 tc_ty(cx, typ, cache).owned_pointer()
4678 TC::All - TC::InteriorParam
4690 tc_ty(cx, ty, cache)
4694 tc_ty(cx, ty, cache)
4698 TyClosure(_, ref substs) => {
4699 TypeContents::union(&substs.upvar_tys, |ty| tc_ty(cx, &ty, cache))
4702 TyTuple(ref tys) => {
4703 TypeContents::union(&tys[..],
4704 |ty| tc_ty(cx, *ty, cache))
4707 TyStruct(def, substs) | TyEnum(def, substs) => {
4709 TypeContents::union(&def.variants, |v| {
4710 TypeContents::union(&v.fields, |f| {
4711 tc_ty(cx, f.ty(cx, substs), cache)
4716 res = res | TC::OwnsDtor;
4719 apply_lang_items(cx, def.did, res)
4729 cx.sess.bug("asked to compute contents of error type");
4733 cache.insert(ty, result);
4737 fn apply_lang_items(cx: &ctxt, did: DefId, tc: TypeContents)
4739 if Some(did) == cx.lang_items.unsafe_cell_type() {
4740 tc | TC::InteriorUnsafe
4747 fn impls_bound<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4748 bound: ty::BuiltinBound,
4752 let tcx = param_env.tcx;
4753 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env.clone()), false);
4755 let is_impld = traits::type_known_to_meet_builtin_bound(&infcx,
4758 debug!("Ty::impls_bound({:?}, {:?}) = {:?}",
4759 self, bound, is_impld);
4764 // FIXME (@jroesch): I made this public to use it, not sure if should be private
4765 pub fn moves_by_default<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4766 span: Span) -> bool {
4767 if self.flags.get().intersects(TypeFlags::MOVENESS_CACHED) {
4768 return self.flags.get().intersects(TypeFlags::MOVES_BY_DEFAULT);
4771 assert!(!self.needs_infer());
4773 // Fast-path for primitive types
4774 let result = match self.sty {
4775 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
4776 TyRawPtr(..) | TyBareFn(..) | TyRef(_, TypeAndMut {
4777 mutbl: hir::MutImmutable, ..
4780 TyStr | TyBox(..) | TyRef(_, TypeAndMut {
4781 mutbl: hir::MutMutable, ..
4784 TyArray(..) | TySlice(_) | TyTrait(..) | TyTuple(..) |
4785 TyClosure(..) | TyEnum(..) | TyStruct(..) |
4786 TyProjection(..) | TyParam(..) | TyInfer(..) | TyError => None
4787 }.unwrap_or_else(|| !self.impls_bound(param_env, ty::BoundCopy, span));
4789 if !self.has_param_types() && !self.has_self_ty() {
4790 self.flags.set(self.flags.get() | if result {
4791 TypeFlags::MOVENESS_CACHED | TypeFlags::MOVES_BY_DEFAULT
4793 TypeFlags::MOVENESS_CACHED
4801 pub fn is_sized<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4804 if self.flags.get().intersects(TypeFlags::SIZEDNESS_CACHED) {
4805 return self.flags.get().intersects(TypeFlags::IS_SIZED);
4808 self.is_sized_uncached(param_env, span)
4811 fn is_sized_uncached<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx>,
4812 span: Span) -> bool {
4813 assert!(!self.needs_infer());
4815 // Fast-path for primitive types
4816 let result = match self.sty {
4817 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
4818 TyBox(..) | TyRawPtr(..) | TyRef(..) | TyBareFn(..) |
4819 TyArray(..) | TyTuple(..) | TyClosure(..) => Some(true),
4821 TyStr | TyTrait(..) | TySlice(_) => Some(false),
4823 TyEnum(..) | TyStruct(..) | TyProjection(..) | TyParam(..) |
4824 TyInfer(..) | TyError => None
4825 }.unwrap_or_else(|| self.impls_bound(param_env, ty::BoundSized, span));
4827 if !self.has_param_types() && !self.has_self_ty() {
4828 self.flags.set(self.flags.get() | if result {
4829 TypeFlags::SIZEDNESS_CACHED | TypeFlags::IS_SIZED
4831 TypeFlags::SIZEDNESS_CACHED
4839 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
4840 pub enum LvaluePreference {
4845 impl LvaluePreference {
4846 pub fn from_mutbl(m: hir::Mutability) -> Self {
4848 hir::MutMutable => PreferMutLvalue,
4849 hir::MutImmutable => NoPreference,
4854 /// Describes whether a type is representable. For types that are not
4855 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
4856 /// distinguish between types that are recursive with themselves and types that
4857 /// contain a different recursive type. These cases can therefore be treated
4858 /// differently when reporting errors.
4860 /// The ordering of the cases is significant. They are sorted so that cmp::max
4861 /// will keep the "more erroneous" of two values.
4862 #[derive(Copy, Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
4863 pub enum Representability {
4869 impl<'tcx> TyS<'tcx> {
4870 /// Check whether a type is representable. This means it cannot contain unboxed
4871 /// structural recursion. This check is needed for structs and enums.
4872 pub fn is_representable(&'tcx self, cx: &ctxt<'tcx>, sp: Span) -> Representability {
4874 // Iterate until something non-representable is found
4875 fn find_nonrepresentable<'tcx, It: Iterator<Item=Ty<'tcx>>>(cx: &ctxt<'tcx>, sp: Span,
4876 seen: &mut Vec<Ty<'tcx>>,
4878 -> Representability {
4879 iter.fold(Representable,
4880 |r, ty| cmp::max(r, is_type_structurally_recursive(cx, sp, seen, ty)))
4883 fn are_inner_types_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
4884 seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
4885 -> Representability {
4887 TyTuple(ref ts) => {
4888 find_nonrepresentable(cx, sp, seen, ts.iter().cloned())
4890 // Fixed-length vectors.
4891 // FIXME(#11924) Behavior undecided for zero-length vectors.
4893 is_type_structurally_recursive(cx, sp, seen, ty)
4895 TyStruct(def, substs) | TyEnum(def, substs) => {
4896 find_nonrepresentable(cx,
4899 def.all_fields().map(|f| f.ty(cx, substs)))
4902 // this check is run on type definitions, so we don't expect
4903 // to see closure types
4904 cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
4910 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: AdtDef<'tcx>) -> bool {
4912 TyStruct(ty_def, _) | TyEnum(ty_def, _) => {
4919 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
4920 match (&a.sty, &b.sty) {
4921 (&TyStruct(did_a, ref substs_a), &TyStruct(did_b, ref substs_b)) |
4922 (&TyEnum(did_a, ref substs_a), &TyEnum(did_b, ref substs_b)) => {
4927 let types_a = substs_a.types.get_slice(subst::TypeSpace);
4928 let types_b = substs_b.types.get_slice(subst::TypeSpace);
4930 let mut pairs = types_a.iter().zip(types_b);
4932 pairs.all(|(&a, &b)| same_type(a, b))
4940 // Does the type `ty` directly (without indirection through a pointer)
4941 // contain any types on stack `seen`?
4942 fn is_type_structurally_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
4943 seen: &mut Vec<Ty<'tcx>>,
4944 ty: Ty<'tcx>) -> Representability {
4945 debug!("is_type_structurally_recursive: {:?}", ty);
4948 TyStruct(def, _) | TyEnum(def, _) => {
4950 // Iterate through stack of previously seen types.
4951 let mut iter = seen.iter();
4953 // The first item in `seen` is the type we are actually curious about.
4954 // We want to return SelfRecursive if this type contains itself.
4955 // It is important that we DON'T take generic parameters into account
4956 // for this check, so that Bar<T> in this example counts as SelfRecursive:
4959 // struct Bar<T> { x: Bar<Foo> }
4962 Some(&seen_type) => {
4963 if same_struct_or_enum(seen_type, def) {
4964 debug!("SelfRecursive: {:?} contains {:?}",
4967 return SelfRecursive;
4973 // We also need to know whether the first item contains other types
4974 // that are structurally recursive. If we don't catch this case, we
4975 // will recurse infinitely for some inputs.
4977 // It is important that we DO take generic parameters into account
4978 // here, so that code like this is considered SelfRecursive, not
4979 // ContainsRecursive:
4981 // struct Foo { Option<Option<Foo>> }
4983 for &seen_type in iter {
4984 if same_type(ty, seen_type) {
4985 debug!("ContainsRecursive: {:?} contains {:?}",
4988 return ContainsRecursive;
4993 // For structs and enums, track all previously seen types by pushing them
4994 // onto the 'seen' stack.
4996 let out = are_inner_types_recursive(cx, sp, seen, ty);
5001 // No need to push in other cases.
5002 are_inner_types_recursive(cx, sp, seen, ty)
5007 debug!("is_type_representable: {:?}", self);
5009 // To avoid a stack overflow when checking an enum variant or struct that
5010 // contains a different, structurally recursive type, maintain a stack
5011 // of seen types and check recursion for each of them (issues #3008, #3779).
5012 let mut seen: Vec<Ty> = Vec::new();
5013 let r = is_type_structurally_recursive(cx, sp, &mut seen, self);
5014 debug!("is_type_representable: {:?} is {:?}", self, r);
5018 pub fn is_trait(&self) -> bool {
5020 TyTrait(..) => true,
5025 pub fn is_integral(&self) -> bool {
5027 TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
5032 pub fn is_fresh(&self) -> bool {
5034 TyInfer(FreshTy(_)) => true,
5035 TyInfer(FreshIntTy(_)) => true,
5036 TyInfer(FreshFloatTy(_)) => true,
5041 pub fn is_uint(&self) -> bool {
5043 TyInfer(IntVar(_)) | TyUint(hir::TyUs) => true,
5048 pub fn is_char(&self) -> bool {
5055 pub fn is_bare_fn(&self) -> bool {
5057 TyBareFn(..) => true,
5062 pub fn is_bare_fn_item(&self) -> bool {
5064 TyBareFn(Some(_), _) => true,
5069 pub fn is_fp(&self) -> bool {
5071 TyInfer(FloatVar(_)) | TyFloat(_) => true,
5076 pub fn is_numeric(&self) -> bool {
5077 self.is_integral() || self.is_fp()
5080 pub fn is_signed(&self) -> bool {
5087 pub fn is_machine(&self) -> bool {
5089 TyInt(hir::TyIs) | TyUint(hir::TyUs) => false,
5090 TyInt(..) | TyUint(..) | TyFloat(..) => true,
5095 // Returns the type and mutability of *ty.
5097 // The parameter `explicit` indicates if this is an *explicit* dereference.
5098 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
5099 pub fn builtin_deref(&self, explicit: bool, pref: LvaluePreference)
5100 -> Option<TypeAndMut<'tcx>>
5107 if pref == PreferMutLvalue { hir::MutMutable } else { hir::MutImmutable },
5110 TyRef(_, mt) => Some(mt),
5111 TyRawPtr(mt) if explicit => Some(mt),
5116 // Returns the type of ty[i]
5117 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
5119 TyArray(ty, _) | TySlice(ty) => Some(ty),
5124 pub fn fn_sig(&self) -> &'tcx PolyFnSig<'tcx> {
5126 TyBareFn(_, ref f) => &f.sig,
5127 _ => panic!("Ty::fn_sig() called on non-fn type: {:?}", self)
5131 /// Returns the ABI of the given function.
5132 pub fn fn_abi(&self) -> abi::Abi {
5134 TyBareFn(_, ref f) => f.abi,
5135 _ => panic!("Ty::fn_abi() called on non-fn type"),
5139 // Type accessors for substructures of types
5140 pub fn fn_args(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
5141 self.fn_sig().inputs()
5144 pub fn fn_ret(&self) -> Binder<FnOutput<'tcx>> {
5145 self.fn_sig().output()
5148 pub fn is_fn(&self) -> bool {
5150 TyBareFn(..) => true,
5155 /// See `expr_ty_adjusted`
5156 pub fn adjust<F>(&'tcx self, cx: &ctxt<'tcx>,
5159 adjustment: Option<&AutoAdjustment<'tcx>>,
5162 F: FnMut(MethodCall) -> Option<Ty<'tcx>>,
5164 if let TyError = self.sty {
5168 return match adjustment {
5169 Some(adjustment) => {
5171 AdjustReifyFnPointer => {
5173 ty::TyBareFn(Some(_), b) => {
5178 &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
5184 AdjustUnsafeFnPointer => {
5186 ty::TyBareFn(None, b) => cx.safe_to_unsafe_fn_ty(b),
5189 &format!("AdjustReifyFnPointer adjustment on non-fn-item: \
5196 AdjustDerefRef(ref adj) => {
5197 let mut adjusted_ty = self;
5199 if !adjusted_ty.references_error() {
5200 for i in 0..adj.autoderefs {
5202 adjusted_ty.adjust_for_autoderef(cx,
5210 if let Some(target) = adj.unsize {
5213 adjusted_ty.adjust_for_autoref(cx, adj.autoref)
5222 pub fn adjust_for_autoderef<F>(&'tcx self,
5224 expr_id: ast::NodeId,
5226 autoderef: u32, // how many autoderefs so far?
5229 F: FnMut(MethodCall) -> Option<Ty<'tcx>>,
5231 let method_call = MethodCall::autoderef(expr_id, autoderef);
5232 let mut adjusted_ty = self;
5233 if let Some(method_ty) = method_type(method_call) {
5234 // Method calls always have all late-bound regions
5235 // fully instantiated.
5236 let fn_ret = cx.no_late_bound_regions(&method_ty.fn_ret()).unwrap();
5237 adjusted_ty = fn_ret.unwrap();
5239 match adjusted_ty.builtin_deref(true, NoPreference) {
5244 &format!("the {}th autoderef failed: {}",
5252 pub fn adjust_for_autoref(&'tcx self, cx: &ctxt<'tcx>,
5253 autoref: Option<AutoRef<'tcx>>)
5257 Some(AutoPtr(r, m)) => {
5258 cx.mk_ref(r, TypeAndMut { ty: self, mutbl: m })
5260 Some(AutoUnsafe(m)) => {
5261 cx.mk_ptr(TypeAndMut { ty: self, mutbl: m })
5266 fn sort_string(&self, cx: &ctxt) -> String {
5269 TyBool | TyChar | TyInt(_) |
5270 TyUint(_) | TyFloat(_) | TyStr => self.to_string(),
5271 TyTuple(ref tys) if tys.is_empty() => self.to_string(),
5273 TyEnum(def, _) => format!("enum `{}`", cx.item_path_str(def.did)),
5274 TyBox(_) => "box".to_string(),
5275 TyArray(_, n) => format!("array of {} elements", n),
5276 TySlice(_) => "slice".to_string(),
5277 TyRawPtr(_) => "*-ptr".to_string(),
5278 TyRef(_, _) => "&-ptr".to_string(),
5279 TyBareFn(Some(_), _) => format!("fn item"),
5280 TyBareFn(None, _) => "fn pointer".to_string(),
5281 TyTrait(ref inner) => {
5282 format!("trait {}", cx.item_path_str(inner.principal_def_id()))
5284 TyStruct(def, _) => {
5285 format!("struct `{}`", cx.item_path_str(def.did))
5287 TyClosure(..) => "closure".to_string(),
5288 TyTuple(_) => "tuple".to_string(),
5289 TyInfer(TyVar(_)) => "inferred type".to_string(),
5290 TyInfer(IntVar(_)) => "integral variable".to_string(),
5291 TyInfer(FloatVar(_)) => "floating-point variable".to_string(),
5292 TyInfer(FreshTy(_)) => "skolemized type".to_string(),
5293 TyInfer(FreshIntTy(_)) => "skolemized integral type".to_string(),
5294 TyInfer(FreshFloatTy(_)) => "skolemized floating-point type".to_string(),
5295 TyProjection(_) => "associated type".to_string(),
5297 if p.space == subst::SelfSpace {
5300 "type parameter".to_string()
5303 TyError => "type error".to_string(),
5307 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
5308 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
5309 /// afterwards to present additional details, particularly when it comes to lifetime-related
5311 impl<'tcx> fmt::Display for TypeError<'tcx> {
5312 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5313 use self::TypeError::*;
5316 CyclicTy => write!(f, "cyclic type of infinite size"),
5317 Mismatch => write!(f, "types differ"),
5318 UnsafetyMismatch(values) => {
5319 write!(f, "expected {} fn, found {} fn",
5323 AbiMismatch(values) => {
5324 write!(f, "expected {} fn, found {} fn",
5328 Mutability => write!(f, "values differ in mutability"),
5330 write!(f, "boxed values differ in mutability")
5332 VecMutability => write!(f, "vectors differ in mutability"),
5333 PtrMutability => write!(f, "pointers differ in mutability"),
5334 RefMutability => write!(f, "references differ in mutability"),
5335 TyParamSize(values) => {
5336 write!(f, "expected a type with {} type params, \
5337 found one with {} type params",
5341 FixedArraySize(values) => {
5342 write!(f, "expected an array with a fixed size of {} elements, \
5343 found one with {} elements",
5347 TupleSize(values) => {
5348 write!(f, "expected a tuple with {} elements, \
5349 found one with {} elements",
5354 write!(f, "incorrect number of function parameters")
5356 RegionsDoesNotOutlive(..) => {
5357 write!(f, "lifetime mismatch")
5359 RegionsNotSame(..) => {
5360 write!(f, "lifetimes are not the same")
5362 RegionsNoOverlap(..) => {
5363 write!(f, "lifetimes do not intersect")
5365 RegionsInsufficientlyPolymorphic(br, _) => {
5366 write!(f, "expected bound lifetime parameter {}, \
5367 found concrete lifetime", br)
5369 RegionsOverlyPolymorphic(br, _) => {
5370 write!(f, "expected concrete lifetime, \
5371 found bound lifetime parameter {}", br)
5373 Sorts(values) => tls::with(|tcx| {
5374 // A naive approach to making sure that we're not reporting silly errors such as:
5375 // (expected closure, found closure).
5376 let expected_str = values.expected.sort_string(tcx);
5377 let found_str = values.found.sort_string(tcx);
5378 if expected_str == found_str {
5379 write!(f, "expected {}, found a different {}", expected_str, found_str)
5381 write!(f, "expected {}, found {}", expected_str, found_str)
5384 Traits(values) => tls::with(|tcx| {
5385 write!(f, "expected trait `{}`, found trait `{}`",
5386 tcx.item_path_str(values.expected),
5387 tcx.item_path_str(values.found))
5389 BuiltinBoundsMismatch(values) => {
5390 if values.expected.is_empty() {
5391 write!(f, "expected no bounds, found `{}`",
5393 } else if values.found.is_empty() {
5394 write!(f, "expected bounds `{}`, found no bounds",
5397 write!(f, "expected bounds `{}`, found bounds `{}`",
5403 write!(f, "expected an integral type, found `char`")
5405 IntMismatch(ref values) => {
5406 write!(f, "expected `{:?}`, found `{:?}`",
5410 FloatMismatch(ref values) => {
5411 write!(f, "expected `{:?}`, found `{:?}`",
5415 VariadicMismatch(ref values) => {
5416 write!(f, "expected {} fn, found {} function",
5417 if values.expected { "variadic" } else { "non-variadic" },
5418 if values.found { "variadic" } else { "non-variadic" })
5420 ConvergenceMismatch(ref values) => {
5421 write!(f, "expected {} fn, found {} function",
5422 if values.expected { "converging" } else { "diverging" },
5423 if values.found { "converging" } else { "diverging" })
5425 ProjectionNameMismatched(ref values) => {
5426 write!(f, "expected {}, found {}",
5430 ProjectionBoundsLength(ref values) => {
5431 write!(f, "expected {} associated type bindings, found {}",
5435 TyParamDefaultMismatch(ref values) => {
5436 write!(f, "conflicting type parameter defaults `{}` and `{}`",
5444 /// Helper for looking things up in the various maps that are populated during
5445 /// typeck::collect (e.g., `cx.impl_or_trait_items`, `cx.tcache`, etc). All of
5446 /// these share the pattern that if the id is local, it should have been loaded
5447 /// into the map by the `typeck::collect` phase. If the def-id is external,
5448 /// then we have to go consult the crate loading code (and cache the result for
5450 fn lookup_locally_or_in_crate_store<V, F>(descr: &str,
5452 map: &RefCell<DefIdMap<V>>,
5453 load_external: F) -> V where
5457 match map.borrow().get(&def_id).cloned() {
5458 Some(v) => { return v; }
5462 if def_id.is_local() {
5463 panic!("No def'n found for {:?} in tcx.{}", def_id, descr);
5465 let v = load_external();
5466 map.borrow_mut().insert(def_id, v.clone());
5471 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
5473 hir::MutMutable => MutBorrow,
5474 hir::MutImmutable => ImmBorrow,
5478 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
5479 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
5480 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
5482 pub fn to_mutbl_lossy(self) -> hir::Mutability {
5484 MutBorrow => hir::MutMutable,
5485 ImmBorrow => hir::MutImmutable,
5487 // We have no type corresponding to a unique imm borrow, so
5488 // use `&mut`. It gives all the capabilities of an `&uniq`
5489 // and hence is a safe "over approximation".
5490 UniqueImmBorrow => hir::MutMutable,
5494 pub fn to_user_str(&self) -> &'static str {
5496 MutBorrow => "mutable",
5497 ImmBorrow => "immutable",
5498 UniqueImmBorrow => "uniquely immutable",
5503 impl<'tcx> ctxt<'tcx> {
5504 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
5505 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
5506 pub fn positional_element_ty(&self,
5509 variant: Option<DefId>) -> Option<Ty<'tcx>> {
5510 match (&ty.sty, variant) {
5511 (&TyStruct(def, substs), None) => {
5512 def.struct_variant().fields.get(i).map(|f| f.ty(self, substs))
5514 (&TyEnum(def, substs), Some(vid)) => {
5515 def.variant_with_id(vid).fields.get(i).map(|f| f.ty(self, substs))
5517 (&TyEnum(def, substs), None) => {
5518 assert!(def.is_univariant());
5519 def.variants[0].fields.get(i).map(|f| f.ty(self, substs))
5521 (&TyTuple(ref v), None) => v.get(i).cloned(),
5526 /// Returns the type of element at field `n` in struct or struct-like type `t`.
5527 /// For an enum `t`, `variant` must be some def id.
5528 pub fn named_element_ty(&self,
5531 variant: Option<DefId>) -> Option<Ty<'tcx>> {
5532 match (&ty.sty, variant) {
5533 (&TyStruct(def, substs), None) => {
5534 def.struct_variant().find_field_named(n).map(|f| f.ty(self, substs))
5536 (&TyEnum(def, substs), Some(vid)) => {
5537 def.variant_with_id(vid).find_field_named(n).map(|f| f.ty(self, substs))
5543 pub fn node_id_to_type(&self, id: NodeId) -> Ty<'tcx> {
5544 match self.node_id_to_type_opt(id) {
5546 None => self.sess.bug(
5547 &format!("node_id_to_type: no type for node `{}`",
5548 self.map.node_to_string(id)))
5552 pub fn node_id_to_type_opt(&self, id: NodeId) -> Option<Ty<'tcx>> {
5553 self.tables.borrow().node_types.get(&id).cloned()
5556 pub fn node_id_item_substs(&self, id: NodeId) -> ItemSubsts<'tcx> {
5557 match self.tables.borrow().item_substs.get(&id) {
5558 None => ItemSubsts::empty(),
5559 Some(ts) => ts.clone(),
5563 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
5564 // doesn't provide type parameter substitutions.
5565 pub fn pat_ty(&self, pat: &hir::Pat) -> Ty<'tcx> {
5566 self.node_id_to_type(pat.id)
5568 pub fn pat_ty_opt(&self, pat: &hir::Pat) -> Option<Ty<'tcx>> {
5569 self.node_id_to_type_opt(pat.id)
5572 // Returns the type of an expression as a monotype.
5574 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in
5575 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
5576 // auto-ref. The type returned by this function does not consider such
5577 // adjustments. See `expr_ty_adjusted()` instead.
5579 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
5580 // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
5581 // instead of "fn(ty) -> T with T = isize".
5582 pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
5583 self.node_id_to_type(expr.id)
5586 pub fn expr_ty_opt(&self, expr: &hir::Expr) -> Option<Ty<'tcx>> {
5587 self.node_id_to_type_opt(expr.id)
5590 /// Returns the type of `expr`, considering any `AutoAdjustment`
5591 /// entry recorded for that expression.
5593 /// It would almost certainly be better to store the adjusted ty in with
5594 /// the `AutoAdjustment`, but I opted not to do this because it would
5595 /// require serializing and deserializing the type and, although that's not
5596 /// hard to do, I just hate that code so much I didn't want to touch it
5597 /// unless it was to fix it properly, which seemed a distraction from the
5598 /// thread at hand! -nmatsakis
5599 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> {
5601 .adjust(self, expr.span, expr.id,
5602 self.tables.borrow().adjustments.get(&expr.id),
5604 self.tables.borrow().method_map.get(&method_call).map(|method| method.ty)
5608 pub fn expr_span(&self, id: NodeId) -> Span {
5609 match self.map.find(id) {
5610 Some(ast_map::NodeExpr(e)) => {
5614 self.sess.bug(&format!("Node id {} is not an expr: {:?}",
5618 self.sess.bug(&format!("Node id {} is not present \
5619 in the node map", id));
5624 pub fn local_var_name_str(&self, id: NodeId) -> InternedString {
5625 match self.map.find(id) {
5626 Some(ast_map::NodeLocal(pat)) => {
5628 hir::PatIdent(_, ref path1, _) => path1.node.name.as_str(),
5630 self.sess.bug(&format!("Variable id {} maps to {:?}, not local", id, pat));
5634 r => self.sess.bug(&format!("Variable id {} maps to {:?}, not local", id, r)),
5638 pub fn resolve_expr(&self, expr: &hir::Expr) -> def::Def {
5639 match self.def_map.borrow().get(&expr.id) {
5640 Some(def) => def.full_def(),
5642 self.sess.span_bug(expr.span, &format!(
5643 "no def-map entry for expr {}", expr.id));
5648 pub fn expr_is_lval(&self, expr: &hir::Expr) -> bool {
5650 hir::ExprPath(..) => {
5651 // We can't use resolve_expr here, as this needs to run on broken
5652 // programs. We don't need to through - associated items are all
5654 match self.def_map.borrow().get(&expr.id) {
5655 Some(&def::PathResolution {
5656 base_def: def::DefStatic(..), ..
5657 }) | Some(&def::PathResolution {
5658 base_def: def::DefUpvar(..), ..
5659 }) | Some(&def::PathResolution {
5660 base_def: def::DefLocal(..), ..
5667 None => self.sess.span_bug(expr.span, &format!(
5668 "no def for path {}", expr.id))
5672 hir::ExprUnary(hir::UnDeref, _) |
5673 hir::ExprField(..) |
5674 hir::ExprTupField(..) |
5675 hir::ExprIndex(..) => {
5680 hir::ExprMethodCall(..) |
5681 hir::ExprStruct(..) |
5682 hir::ExprRange(..) |
5685 hir::ExprMatch(..) |
5686 hir::ExprClosure(..) |
5687 hir::ExprBlock(..) |
5688 hir::ExprRepeat(..) |
5690 hir::ExprBreak(..) |
5691 hir::ExprAgain(..) |
5693 hir::ExprWhile(..) |
5695 hir::ExprAssign(..) |
5696 hir::ExprInlineAsm(..) |
5697 hir::ExprAssignOp(..) |
5699 hir::ExprUnary(..) |
5701 hir::ExprAddrOf(..) |
5702 hir::ExprBinary(..) |
5703 hir::ExprCast(..) => {
5707 hir::ExprParen(ref e) => self.expr_is_lval(e),
5711 pub fn note_and_explain_type_err(&self, err: &TypeError<'tcx>, sp: Span) {
5712 use self::TypeError::*;
5715 RegionsDoesNotOutlive(subregion, superregion) => {
5716 self.note_and_explain_region("", subregion, "...");
5717 self.note_and_explain_region("...does not necessarily outlive ",
5720 RegionsNotSame(region1, region2) => {
5721 self.note_and_explain_region("", region1, "...");
5722 self.note_and_explain_region("...is not the same lifetime as ",
5725 RegionsNoOverlap(region1, region2) => {
5726 self.note_and_explain_region("", region1, "...");
5727 self.note_and_explain_region("...does not overlap ",
5730 RegionsInsufficientlyPolymorphic(_, conc_region) => {
5731 self.note_and_explain_region("concrete lifetime that was found is ",
5734 RegionsOverlyPolymorphic(_, ty::ReVar(_)) => {
5735 // don't bother to print out the message below for
5736 // inference variables, it's not very illuminating.
5738 RegionsOverlyPolymorphic(_, conc_region) => {
5739 self.note_and_explain_region("expected concrete lifetime is ",
5743 let expected_str = values.expected.sort_string(self);
5744 let found_str = values.found.sort_string(self);
5745 if expected_str == found_str && expected_str == "closure" {
5746 self.sess.span_note(sp,
5747 &format!("no two closures, even if identical, have the same type"));
5748 self.sess.span_help(sp,
5749 &format!("consider boxing your closure and/or \
5750 using it as a trait object"));
5753 TyParamDefaultMismatch(values) => {
5754 let expected = values.expected;
5755 let found = values.found;
5756 self.sess.span_note(sp,
5757 &format!("conflicting type parameter defaults `{}` and `{}`",
5761 match (expected.def_id.is_local(),
5762 self.map.opt_span(expected.def_id.node)) {
5763 (true, Some(span)) => {
5764 self.sess.span_note(span,
5765 &format!("a default was defined here..."));
5769 &format!("a default is defined on `{}`",
5770 self.item_path_str(expected.def_id)));
5774 self.sess.span_note(
5775 expected.origin_span,
5776 &format!("...that was applied to an unconstrained type variable here"));
5778 match (found.def_id.is_local(),
5779 self.map.opt_span(found.def_id.node)) {
5780 (true, Some(span)) => {
5781 self.sess.span_note(span,
5782 &format!("a second default was defined here..."));
5786 &format!("a second default is defined on `{}`",
5787 self.item_path_str(found.def_id)));
5791 self.sess.span_note(
5793 &format!("...that also applies to the same type variable here"));
5799 pub fn provided_source(&self, id: DefId) -> Option<DefId> {
5800 self.provided_method_sources.borrow().get(&id).cloned()
5803 pub fn provided_trait_methods(&self, id: DefId) -> Vec<Rc<Method<'tcx>>> {
5805 if let ItemTrait(_, _, _, ref ms) = self.map.expect_item(id.node).node {
5806 ms.iter().filter_map(|ti| {
5807 if let hir::MethodTraitItem(_, Some(_)) = ti.node {
5808 match self.impl_or_trait_item(DefId::local(ti.id)) {
5809 MethodTraitItem(m) => Some(m),
5811 self.sess.bug("provided_trait_methods(): \
5812 non-method item found from \
5813 looking up provided method?!")
5821 self.sess.bug(&format!("provided_trait_methods: `{:?}` is not a trait", id))
5824 csearch::get_provided_trait_methods(self, id)
5828 pub fn associated_consts(&self, id: DefId) -> Vec<Rc<AssociatedConst<'tcx>>> {
5830 match self.map.expect_item(id.node).node {
5831 ItemTrait(_, _, _, ref tis) => {
5832 tis.iter().filter_map(|ti| {
5833 if let hir::ConstTraitItem(_, _) = ti.node {
5834 match self.impl_or_trait_item(DefId::local(ti.id)) {
5835 ConstTraitItem(ac) => Some(ac),
5837 self.sess.bug("associated_consts(): \
5838 non-const item found from \
5839 looking up a constant?!")
5847 ItemImpl(_, _, _, _, _, ref iis) => {
5848 iis.iter().filter_map(|ii| {
5849 if let hir::ConstImplItem(_, _) = ii.node {
5850 match self.impl_or_trait_item(DefId::local(ii.id)) {
5851 ConstTraitItem(ac) => Some(ac),
5853 self.sess.bug("associated_consts(): \
5854 non-const item found from \
5855 looking up a constant?!")
5864 self.sess.bug(&format!("associated_consts: `{:?}` is not a trait \
5869 csearch::get_associated_consts(self, id)
5873 pub fn trait_items(&self, trait_did: DefId) -> Rc<Vec<ImplOrTraitItem<'tcx>>> {
5874 let mut trait_items = self.trait_items_cache.borrow_mut();
5875 match trait_items.get(&trait_did).cloned() {
5876 Some(trait_items) => trait_items,
5878 let def_ids = self.trait_item_def_ids(trait_did);
5879 let items: Rc<Vec<ImplOrTraitItem>> =
5880 Rc::new(def_ids.iter()
5881 .map(|d| self.impl_or_trait_item(d.def_id()))
5883 trait_items.insert(trait_did, items.clone());
5889 pub fn trait_impl_polarity(&self, id: DefId) -> Option<hir::ImplPolarity> {
5891 match self.map.find(id.node) {
5892 Some(ast_map::NodeItem(item)) => {
5894 hir::ItemImpl(_, polarity, _, _, _, _) => Some(polarity),
5901 csearch::get_impl_polarity(self, id)
5905 pub fn custom_coerce_unsized_kind(&self, did: DefId) -> CustomCoerceUnsized {
5906 memoized(&self.custom_coerce_unsized_kinds, did, |did: DefId| {
5907 let (kind, src) = if did.krate != LOCAL_CRATE {
5908 (csearch::get_custom_coerce_unsized_kind(self, did), "external")
5916 self.sess.bug(&format!("custom_coerce_unsized_kind: \
5917 {} impl `{}` is missing its kind",
5918 src, self.item_path_str(did)));
5924 pub fn impl_or_trait_item(&self, id: DefId) -> ImplOrTraitItem<'tcx> {
5925 lookup_locally_or_in_crate_store(
5926 "impl_or_trait_items", id, &self.impl_or_trait_items,
5927 || csearch::get_impl_or_trait_item(self, id))
5930 pub fn trait_item_def_ids(&self, id: DefId) -> Rc<Vec<ImplOrTraitItemId>> {
5931 lookup_locally_or_in_crate_store(
5932 "trait_item_def_ids", id, &self.trait_item_def_ids,
5933 || Rc::new(csearch::get_trait_item_def_ids(&self.sess.cstore, id)))
5936 /// Returns the trait-ref corresponding to a given impl, or None if it is
5937 /// an inherent impl.
5938 pub fn impl_trait_ref(&self, id: DefId) -> Option<TraitRef<'tcx>> {
5939 lookup_locally_or_in_crate_store(
5940 "impl_trait_refs", id, &self.impl_trait_refs,
5941 || csearch::get_impl_trait(self, id))
5944 /// Returns whether this DefId refers to an impl
5945 pub fn is_impl(&self, id: DefId) -> bool {
5947 if let Some(ast_map::NodeItem(
5948 &hir::Item { node: hir::ItemImpl(..), .. })) = self.map.find(id.node) {
5954 csearch::is_impl(&self.sess.cstore, id)
5958 pub fn trait_ref_to_def_id(&self, tr: &hir::TraitRef) -> DefId {
5959 self.def_map.borrow().get(&tr.ref_id).expect("no def-map entry for trait").def_id()
5962 pub fn try_add_builtin_trait(&self,
5963 trait_def_id: DefId,
5964 builtin_bounds: &mut EnumSet<BuiltinBound>)
5967 //! Checks whether `trait_ref` refers to one of the builtin
5968 //! traits, like `Send`, and adds the corresponding
5969 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
5970 //! is a builtin trait.
5972 match self.lang_items.to_builtin_kind(trait_def_id) {
5973 Some(bound) => { builtin_bounds.insert(bound); true }
5978 pub fn item_path_str(&self, id: DefId) -> String {
5979 self.with_path(id, |path| ast_map::path_to_string(path))
5982 pub fn with_path<T, F>(&self, id: DefId, f: F) -> T where
5983 F: FnOnce(ast_map::PathElems) -> T,
5986 self.map.with_path(id.node, f)
5988 f(csearch::get_item_path(self, id).iter().cloned().chain(LinkedPath::empty()))
5992 pub fn item_name(&self, id: DefId) -> ast::Name {
5994 self.map.get_path_elem(id.node).name()
5996 csearch::get_item_name(self, id)
6000 /// Returns `(normalized_type, ty)`, where `normalized_type` is the
6001 /// IntType representation of one of {i64,i32,i16,i8,u64,u32,u16,u8},
6002 /// and `ty` is the original type (i.e. may include `isize` or
6004 pub fn enum_repr_type(&self, opt_hint: Option<&attr::ReprAttr>)
6005 -> (attr::IntType, Ty<'tcx>) {
6006 let repr_type = match opt_hint {
6007 // Feed in the given type
6008 Some(&attr::ReprInt(_, int_t)) => int_t,
6009 // ... but provide sensible default if none provided
6011 // NB. Historically `fn enum_variants` generate i64 here, while
6012 // rustc_typeck::check would generate isize.
6013 _ => SignedInt(hir::TyIs),
6016 let repr_type_ty = repr_type.to_ty(self);
6017 let repr_type = match repr_type {
6018 SignedInt(hir::TyIs) =>
6019 SignedInt(self.sess.target.int_type),
6020 UnsignedInt(hir::TyUs) =>
6021 UnsignedInt(self.sess.target.uint_type),
6025 (repr_type, repr_type_ty)
6029 // Register a given item type
6030 pub fn register_item_type(&self, did: DefId, ty: TypeScheme<'tcx>) {
6031 self.tcache.borrow_mut().insert(did, ty);
6034 // If the given item is in an external crate, looks up its type and adds it to
6035 // the type cache. Returns the type parameters and type.
6036 pub fn lookup_item_type(&self, did: DefId) -> TypeScheme<'tcx> {
6037 lookup_locally_or_in_crate_store(
6038 "tcache", did, &self.tcache,
6039 || csearch::get_type(self, did))
6042 /// Given the did of a trait, returns its canonical trait ref.
6043 pub fn lookup_trait_def(&self, did: DefId) -> &'tcx TraitDef<'tcx> {
6044 lookup_locally_or_in_crate_store(
6045 "trait_defs", did, &self.trait_defs,
6046 || self.arenas.trait_defs.alloc(csearch::get_trait_def(self, did))
6050 /// Given the did of an ADT, return a master reference to its
6051 /// definition. Unless you are planning on fulfilling the ADT's fields,
6052 /// use lookup_adt_def instead.
6053 pub fn lookup_adt_def_master(&self, did: DefId) -> AdtDefMaster<'tcx> {
6054 lookup_locally_or_in_crate_store(
6055 "adt_defs", did, &self.adt_defs,
6056 || csearch::get_adt_def(self, did)
6060 /// Given the did of an ADT, return a reference to its definition.
6061 pub fn lookup_adt_def(&self, did: DefId) -> AdtDef<'tcx> {
6062 // when reverse-variance goes away, a transmute::<AdtDefMaster,AdtDef>
6063 // woud be needed here.
6064 self.lookup_adt_def_master(did)
6067 /// Return the list of all interned ADT definitions
6068 pub fn adt_defs(&self) -> Vec<AdtDef<'tcx>> {
6069 self.adt_defs.borrow().values().cloned().collect()
6072 /// Given the did of an item, returns its full set of predicates.
6073 pub fn lookup_predicates(&self, did: DefId) -> GenericPredicates<'tcx> {
6074 lookup_locally_or_in_crate_store(
6075 "predicates", did, &self.predicates,
6076 || csearch::get_predicates(self, did))
6079 /// Given the did of a trait, returns its superpredicates.
6080 pub fn lookup_super_predicates(&self, did: DefId) -> GenericPredicates<'tcx> {
6081 lookup_locally_or_in_crate_store(
6082 "super_predicates", did, &self.super_predicates,
6083 || csearch::get_super_predicates(self, did))
6086 /// Get the attributes of a definition.
6087 pub fn get_attrs(&self, did: DefId) -> Cow<'tcx, [hir::Attribute]> {
6089 Cow::Borrowed(self.map.attrs(did.node))
6091 Cow::Owned(csearch::get_item_attrs(&self.sess.cstore, did))
6095 /// Determine whether an item is annotated with an attribute
6096 pub fn has_attr(&self, did: DefId, attr: &str) -> bool {
6097 self.get_attrs(did).iter().any(|item| item.check_name(attr))
6100 /// Determine whether an item is annotated with `#[repr(packed)]`
6101 pub fn lookup_packed(&self, did: DefId) -> bool {
6102 self.lookup_repr_hints(did).contains(&attr::ReprPacked)
6105 /// Determine whether an item is annotated with `#[simd]`
6106 pub fn lookup_simd(&self, did: DefId) -> bool {
6107 self.has_attr(did, "simd")
6108 || self.lookup_repr_hints(did).contains(&attr::ReprSimd)
6111 /// Obtain the representation annotation for a struct definition.
6112 pub fn lookup_repr_hints(&self, did: DefId) -> Rc<Vec<attr::ReprAttr>> {
6113 memoized(&self.repr_hint_cache, did, |did: DefId| {
6114 Rc::new(if did.is_local() {
6115 self.get_attrs(did).iter().flat_map(|meta| {
6116 attr::find_repr_attrs(self.sess.diagnostic(), meta).into_iter()
6119 csearch::get_repr_attrs(&self.sess.cstore, did)
6125 /// Returns the deeply last field of nested structures, or the same type,
6126 /// if not a structure at all. Corresponds to the only possible unsized
6127 /// field, and its type can be used to determine unsizing strategy.
6128 pub fn struct_tail(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
6129 while let TyStruct(def, substs) = ty.sty {
6130 match def.struct_variant().fields.last() {
6131 Some(f) => ty = f.ty(self, substs),
6138 /// Same as applying struct_tail on `source` and `target`, but only
6139 /// keeps going as long as the two types are instances of the same
6140 /// structure definitions.
6141 /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
6142 /// whereas struct_tail produces `T`, and `Trait`, respectively.
6143 pub fn struct_lockstep_tails(&self,
6146 -> (Ty<'tcx>, Ty<'tcx>) {
6147 let (mut a, mut b) = (source, target);
6148 while let (&TyStruct(a_def, a_substs), &TyStruct(b_def, b_substs)) = (&a.sty, &b.sty) {
6152 if let Some(f) = a_def.struct_variant().fields.last() {
6153 a = f.ty(self, a_substs);
6154 b = f.ty(self, b_substs);
6162 // Returns the repeat count for a repeating vector expression.
6163 pub fn eval_repeat_count(&self, count_expr: &hir::Expr) -> usize {
6164 let hint = UncheckedExprHint(self.types.usize);
6165 match const_eval::eval_const_expr_partial(self, count_expr, hint) {
6167 let found = match val {
6168 ConstVal::Uint(count) => return count as usize,
6169 ConstVal::Int(count) if count >= 0 => return count as usize,
6170 const_val => const_val.description(),
6172 span_err!(self.sess, count_expr.span, E0306,
6173 "expected positive integer for repeat count, found {}",
6177 let err_msg = match count_expr.node {
6178 hir::ExprPath(None, hir::Path {
6182 }) if segments.len() == 1 =>
6183 format!("found variable"),
6184 _ => match err.kind {
6185 ErrKind::MiscCatchAll => format!("but found {}", err.description()),
6186 _ => format!("but {}", err.description())
6189 span_err!(self.sess, count_expr.span, E0307,
6190 "expected constant integer for repeat count, {}", err_msg);
6196 // Iterate over a type parameter's bounded traits and any supertraits
6197 // of those traits, ignoring kinds.
6198 // Here, the supertraits are the transitive closure of the supertrait
6199 // relation on the supertraits from each bounded trait's constraint
6201 pub fn each_bound_trait_and_supertraits<F>(&self,
6202 bounds: &[PolyTraitRef<'tcx>],
6205 F: FnMut(PolyTraitRef<'tcx>) -> bool,
6207 for bound_trait_ref in traits::transitive_bounds(self, bounds) {
6208 if !f(bound_trait_ref) {
6215 /// Given a set of predicates that apply to an object type, returns
6216 /// the region bounds that the (erased) `Self` type must
6217 /// outlive. Precisely *because* the `Self` type is erased, the
6218 /// parameter `erased_self_ty` must be supplied to indicate what type
6219 /// has been used to represent `Self` in the predicates
6220 /// themselves. This should really be a unique type; `FreshTy(0)` is a
6223 /// NB: in some cases, particularly around higher-ranked bounds,
6224 /// this function returns a kind of conservative approximation.
6225 /// That is, all regions returned by this function are definitely
6226 /// required, but there may be other region bounds that are not
6227 /// returned, as well as requirements like `for<'a> T: 'a`.
6229 /// Requires that trait definitions have been processed so that we can
6230 /// elaborate predicates and walk supertraits.
6231 pub fn required_region_bounds(&self,
6232 erased_self_ty: Ty<'tcx>,
6233 predicates: Vec<ty::Predicate<'tcx>>)
6234 -> Vec<ty::Region> {
6235 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
6239 assert!(!erased_self_ty.has_escaping_regions());
6241 traits::elaborate_predicates(self, predicates)
6242 .filter_map(|predicate| {
6244 ty::Predicate::Projection(..) |
6245 ty::Predicate::Trait(..) |
6246 ty::Predicate::Equate(..) |
6247 ty::Predicate::WellFormed(..) |
6248 ty::Predicate::ObjectSafe(..) |
6249 ty::Predicate::RegionOutlives(..) => {
6252 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
6253 // Search for a bound of the form `erased_self_ty
6254 // : 'a`, but be wary of something like `for<'a>
6255 // erased_self_ty : 'a` (we interpret a
6256 // higher-ranked bound like that as 'static,
6257 // though at present the code in `fulfill.rs`
6258 // considers such bounds to be unsatisfiable, so
6259 // it's kind of a moot point since you could never
6260 // construct such an object, but this seems
6261 // correct even if that code changes).
6262 if t == erased_self_ty && !r.has_escaping_regions() {
6273 pub fn item_variances(&self, item_id: DefId) -> Rc<ItemVariances> {
6274 lookup_locally_or_in_crate_store(
6275 "item_variance_map", item_id, &self.item_variance_map,
6276 || Rc::new(csearch::get_item_variances(&self.sess.cstore, item_id)))
6279 pub fn trait_has_default_impl(&self, trait_def_id: DefId) -> bool {
6280 self.populate_implementations_for_trait_if_necessary(trait_def_id);
6282 let def = self.lookup_trait_def(trait_def_id);
6283 def.flags.get().intersects(TraitFlags::HAS_DEFAULT_IMPL)
6286 /// Records a trait-to-implementation mapping.
6287 pub fn record_trait_has_default_impl(&self, trait_def_id: DefId) {
6288 let def = self.lookup_trait_def(trait_def_id);
6289 def.flags.set(def.flags.get() | TraitFlags::HAS_DEFAULT_IMPL)
6292 /// Load primitive inherent implementations if necessary
6293 pub fn populate_implementations_for_primitive_if_necessary(&self,
6294 primitive_def_id: DefId) {
6295 if primitive_def_id.is_local() {
6299 if self.populated_external_primitive_impls.borrow().contains(&primitive_def_id) {
6303 debug!("populate_implementations_for_primitive_if_necessary: searching for {:?}",
6306 let impl_items = csearch::get_impl_items(&self.sess.cstore, primitive_def_id);
6308 // Store the implementation info.
6309 self.impl_items.borrow_mut().insert(primitive_def_id, impl_items);
6310 self.populated_external_primitive_impls.borrow_mut().insert(primitive_def_id);
6313 /// Populates the type context with all the inherent implementations for
6314 /// the given type if necessary.
6315 pub fn populate_inherent_implementations_for_type_if_necessary(&self,
6317 if type_id.is_local() {
6321 if self.populated_external_types.borrow().contains(&type_id) {
6325 debug!("populate_inherent_implementations_for_type_if_necessary: searching for {:?}",
6328 let mut inherent_impls = Vec::new();
6329 csearch::each_inherent_implementation_for_type(&self.sess.cstore, type_id, |impl_def_id| {
6330 // Record the implementation.
6331 inherent_impls.push(impl_def_id);
6333 // Store the implementation info.
6334 let impl_items = csearch::get_impl_items(&self.sess.cstore, impl_def_id);
6335 self.impl_items.borrow_mut().insert(impl_def_id, impl_items);
6338 self.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
6339 self.populated_external_types.borrow_mut().insert(type_id);
6342 /// Populates the type context with all the implementations for the given
6343 /// trait if necessary.
6344 pub fn populate_implementations_for_trait_if_necessary(&self, trait_id: DefId) {
6345 if trait_id.is_local() {
6349 let def = self.lookup_trait_def(trait_id);
6350 if def.flags.get().intersects(TraitFlags::IMPLS_VALID) {
6354 debug!("populate_implementations_for_trait_if_necessary: searching for {:?}", def);
6356 if csearch::is_defaulted_trait(&self.sess.cstore, trait_id) {
6357 self.record_trait_has_default_impl(trait_id);
6360 csearch::each_implementation_for_trait(&self.sess.cstore, trait_id, |impl_def_id| {
6361 let impl_items = csearch::get_impl_items(&self.sess.cstore, impl_def_id);
6362 let trait_ref = self.impl_trait_ref(impl_def_id).unwrap();
6363 // Record the trait->implementation mapping.
6364 def.record_impl(self, impl_def_id, trait_ref);
6366 // For any methods that use a default implementation, add them to
6367 // the map. This is a bit unfortunate.
6368 for impl_item_def_id in &impl_items {
6369 let method_def_id = impl_item_def_id.def_id();
6370 match self.impl_or_trait_item(method_def_id) {
6371 MethodTraitItem(method) => {
6372 if let Some(source) = method.provided_source {
6373 self.provided_method_sources
6375 .insert(method_def_id, source);
6382 // Store the implementation info.
6383 self.impl_items.borrow_mut().insert(impl_def_id, impl_items);
6386 def.flags.set(def.flags.get() | TraitFlags::IMPLS_VALID);
6389 /// Given the def_id of an impl, return the def_id of the trait it implements.
6390 /// If it implements no trait, return `None`.
6391 pub fn trait_id_of_impl(&self, def_id: DefId) -> Option<DefId> {
6392 self.impl_trait_ref(def_id).map(|tr| tr.def_id)
6395 /// If the given def ID describes a method belonging to an impl, return the
6396 /// ID of the impl that the method belongs to. Otherwise, return `None`.
6397 pub fn impl_of_method(&self, def_id: DefId) -> Option<DefId> {
6398 if def_id.krate != LOCAL_CRATE {
6399 return match csearch::get_impl_or_trait_item(self,
6400 def_id).container() {
6401 TraitContainer(_) => None,
6402 ImplContainer(def_id) => Some(def_id),
6405 match self.impl_or_trait_items.borrow().get(&def_id).cloned() {
6406 Some(trait_item) => {
6407 match trait_item.container() {
6408 TraitContainer(_) => None,
6409 ImplContainer(def_id) => Some(def_id),
6416 /// If the given def ID describes an item belonging to a trait (either a
6417 /// default method or an implementation of a trait method), return the ID of
6418 /// the trait that the method belongs to. Otherwise, return `None`.
6419 pub fn trait_of_item(&self, def_id: DefId) -> Option<DefId> {
6420 if def_id.krate != LOCAL_CRATE {
6421 return csearch::get_trait_of_item(&self.sess.cstore, def_id, self);
6423 match self.impl_or_trait_items.borrow().get(&def_id).cloned() {
6424 Some(impl_or_trait_item) => {
6425 match impl_or_trait_item.container() {
6426 TraitContainer(def_id) => Some(def_id),
6427 ImplContainer(def_id) => self.trait_id_of_impl(def_id),
6434 /// If the given def ID describes an item belonging to a trait, (either a
6435 /// default method or an implementation of a trait method), return the ID of
6436 /// the method inside trait definition (this means that if the given def ID
6437 /// is already that of the original trait method, then the return value is
6439 /// Otherwise, return `None`.
6440 pub fn trait_item_of_item(&self, def_id: DefId) -> Option<ImplOrTraitItemId> {
6441 let impl_item = match self.impl_or_trait_items.borrow().get(&def_id) {
6442 Some(m) => m.clone(),
6443 None => return None,
6445 let name = impl_item.name();
6446 match self.trait_of_item(def_id) {
6447 Some(trait_did) => {
6448 self.trait_items(trait_did).iter()
6449 .find(|item| item.name() == name)
6450 .map(|item| item.id())
6456 /// Creates a hash of the type `Ty` which will be the same no matter what crate
6457 /// context it's calculated within. This is used by the `type_id` intrinsic.
6458 pub fn hash_crate_independent(&self, ty: Ty<'tcx>, svh: &Svh) -> u64 {
6459 let mut state = SipHasher::new();
6460 helper(self, ty, svh, &mut state);
6461 return state.finish();
6463 fn helper<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh,
6464 state: &mut SipHasher) {
6465 macro_rules! byte { ($b:expr) => { ($b as u8).hash(state) } }
6466 macro_rules! hash { ($e:expr) => { $e.hash(state) } }
6468 let region = |state: &mut SipHasher, r: Region| {
6471 ReLateBound(db, BrAnon(i)) => {
6481 ReSkolemized(..) => {
6482 tcx.sess.bug("unexpected region found when hashing a type")
6486 let did = |state: &mut SipHasher, did: DefId| {
6487 let h = if did.is_local() {
6490 tcx.sess.cstore.get_crate_hash(did.krate)
6492 h.as_str().hash(state);
6493 did.node.hash(state);
6495 let mt = |state: &mut SipHasher, mt: TypeAndMut| {
6496 mt.mutbl.hash(state);
6498 let fn_sig = |state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| {
6499 let sig = tcx.anonymize_late_bound_regions(sig).0;
6500 for a in &sig.inputs { helper(tcx, *a, svh, state); }
6501 if let ty::FnConverging(output) = sig.output {
6502 helper(tcx, output, svh, state);
6505 ty.maybe_walk(|ty| {
6547 TyBareFn(opt_def_id, ref b) => {
6552 fn_sig(state, &b.sig);
6555 TyTrait(ref data) => {
6557 did(state, data.principal_def_id());
6560 let principal = tcx.anonymize_late_bound_regions(&data.principal).0;
6561 for subty in &principal.substs.types {
6562 helper(tcx, subty, svh, state);
6571 TyTuple(ref inner) => {
6579 hash!(p.name.as_str());
6581 TyInfer(_) => unreachable!(),
6582 TyError => byte!(21),
6583 TyClosure(d, _) => {
6587 TyProjection(ref data) => {
6589 did(state, data.trait_ref.def_id);
6590 hash!(data.item_name.as_str());
6598 /// Construct a parameter environment suitable for static contexts or other contexts where there
6599 /// are no free type/lifetime parameters in scope.
6600 pub fn empty_parameter_environment<'a>(&'a self)
6601 -> ParameterEnvironment<'a,'tcx> {
6602 ty::ParameterEnvironment { tcx: self,
6603 free_substs: Substs::empty(),
6604 caller_bounds: Vec::new(),
6605 implicit_region_bound: ty::ReEmpty,
6606 selection_cache: traits::SelectionCache::new(),
6608 // for an empty parameter
6609 // environment, there ARE no free
6610 // regions, so it shouldn't matter
6611 // what we use for the free id
6612 free_id: ast::DUMMY_NODE_ID }
6615 /// Constructs and returns a substitution that can be applied to move from
6616 /// the "outer" view of a type or method to the "inner" view.
6617 /// In general, this means converting from bound parameters to
6618 /// free parameters. Since we currently represent bound/free type
6619 /// parameters in the same way, this only has an effect on regions.
6620 pub fn construct_free_substs(&self, generics: &Generics<'tcx>,
6621 free_id: NodeId) -> Substs<'tcx> {
6623 let mut types = VecPerParamSpace::empty();
6624 for def in generics.types.as_slice() {
6625 debug!("construct_parameter_environment(): push_types_from_defs: def={:?}",
6627 types.push(def.space, self.mk_param_from_def(def));
6630 let free_id_outlive = self.region_maps.item_extent(free_id);
6632 // map bound 'a => free 'a
6633 let mut regions = VecPerParamSpace::empty();
6634 for def in generics.regions.as_slice() {
6636 ReFree(FreeRegion { scope: free_id_outlive,
6637 bound_region: BrNamed(def.def_id, def.name) });
6638 debug!("push_region_params {:?}", region);
6639 regions.push(def.space, region);
6644 regions: subst::NonerasedRegions(regions)
6648 /// See `ParameterEnvironment` struct def'n for details
6649 pub fn construct_parameter_environment<'a>(&'a self,
6651 generics: &ty::Generics<'tcx>,
6652 generic_predicates: &ty::GenericPredicates<'tcx>,
6654 -> ParameterEnvironment<'a, 'tcx>
6657 // Construct the free substs.
6660 let free_substs = self.construct_free_substs(generics, free_id);
6661 let free_id_outlive = self.region_maps.item_extent(free_id);
6664 // Compute the bounds on Self and the type parameters.
6667 let bounds = generic_predicates.instantiate(self, &free_substs);
6668 let bounds = self.liberate_late_bound_regions(free_id_outlive, &ty::Binder(bounds));
6669 let predicates = bounds.predicates.into_vec();
6671 debug!("construct_parameter_environment: free_id={:?} free_subst={:?} predicates={:?}",
6677 // Finally, we have to normalize the bounds in the environment, in
6678 // case they contain any associated type projections. This process
6679 // can yield errors if the put in illegal associated types, like
6680 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
6681 // report these errors right here; this doesn't actually feel
6682 // right to me, because constructing the environment feels like a
6683 // kind of a "idempotent" action, but I'm not sure where would be
6684 // a better place. In practice, we construct environments for
6685 // every fn once during type checking, and we'll abort if there
6686 // are any errors at that point, so after type checking you can be
6687 // sure that this will succeed without errors anyway.
6690 let unnormalized_env = ty::ParameterEnvironment {
6692 free_substs: free_substs,
6693 implicit_region_bound: ty::ReScope(free_id_outlive),
6694 caller_bounds: predicates,
6695 selection_cache: traits::SelectionCache::new(),
6699 let cause = traits::ObligationCause::misc(span, free_id);
6700 traits::normalize_param_env_or_error(unnormalized_env, cause)
6703 pub fn is_method_call(&self, expr_id: NodeId) -> bool {
6704 self.tables.borrow().method_map.contains_key(&MethodCall::expr(expr_id))
6707 pub fn is_overloaded_autoderef(&self, expr_id: NodeId, autoderefs: u32) -> bool {
6708 self.tables.borrow().method_map.contains_key(&MethodCall::autoderef(expr_id,
6712 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
6713 Some(self.tables.borrow().upvar_capture_map.get(&upvar_id).unwrap().clone())
6717 /// Returns true if this ADT is a dtorck type, i.e. whether it being
6718 /// safe for destruction requires it to be alive
6719 fn is_adt_dtorck(&self, adt: AdtDef<'tcx>) -> bool {
6720 let dtor_method = match adt.destructor() {
6722 None => return false
6724 let impl_did = self.impl_of_method(dtor_method).unwrap_or_else(|| {
6725 self.sess.bug(&format!("no Drop impl for the dtor of `{:?}`", adt))
6727 let generics = adt.type_scheme(self).generics;
6729 // In `impl<'a> Drop ...`, we automatically assume
6730 // `'a` is meaningful and thus represents a bound
6731 // through which we could reach borrowed data.
6733 // FIXME (pnkfelix): In the future it would be good to
6734 // extend the language to allow the user to express,
6735 // in the impl signature, that a lifetime is not
6736 // actually used (something like `where 'a: ?Live`).
6737 if generics.has_region_params(subst::TypeSpace) {
6738 debug!("typ: {:?} has interesting dtor due to region params",
6743 let mut seen_items = Vec::new();
6744 let mut items_to_inspect = vec![impl_did];
6745 while let Some(item_def_id) = items_to_inspect.pop() {
6746 if seen_items.contains(&item_def_id) {
6750 for pred in self.lookup_predicates(item_def_id).predicates {
6751 let result = match pred {
6752 ty::Predicate::Equate(..) |
6753 ty::Predicate::RegionOutlives(..) |
6754 ty::Predicate::TypeOutlives(..) |
6755 ty::Predicate::WellFormed(..) |
6756 ty::Predicate::ObjectSafe(..) |
6757 ty::Predicate::Projection(..) => {
6758 // For now, assume all these where-clauses
6759 // may give drop implementation capabilty
6760 // to access borrowed data.
6764 ty::Predicate::Trait(ty::Binder(ref t_pred)) => {
6765 let def_id = t_pred.trait_ref.def_id;
6766 if self.trait_items(def_id).len() != 0 {
6767 // If trait has items, assume it adds
6768 // capability to access borrowed data.
6771 // Trait without items is itself
6772 // uninteresting from POV of dropck.
6774 // However, may have parent w/ items;
6775 // so schedule checking of predicates,
6776 items_to_inspect.push(def_id);
6777 // and say "no capability found" for now.
6784 debug!("typ: {:?} has interesting dtor due to generic preds, e.g. {:?}",
6790 seen_items.push(item_def_id);
6793 debug!("typ: {:?} is dtorck-safe", adt);
6798 /// The category of explicit self.
6799 #[derive(Clone, Copy, Eq, PartialEq, Debug)]
6800 pub enum ExplicitSelfCategory {
6801 StaticExplicitSelfCategory,
6802 ByValueExplicitSelfCategory,
6803 ByReferenceExplicitSelfCategory(Region, hir::Mutability),
6804 ByBoxExplicitSelfCategory,
6807 /// A free variable referred to in a function.
6808 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
6809 pub struct Freevar {
6810 /// The variable being accessed free.
6813 // First span where it is accessed (there can be multiple).
6817 pub type FreevarMap = NodeMap<Vec<Freevar>>;
6819 pub type CaptureModeMap = NodeMap<hir::CaptureClause>;
6821 // Trait method resolution
6822 pub type TraitMap = NodeMap<Vec<DefId>>;
6824 // Map from the NodeId of a glob import to a list of items which are actually
6826 pub type GlobMap = HashMap<NodeId, HashSet<Name>>;
6828 impl<'tcx> AutoAdjustment<'tcx> {
6829 pub fn is_identity(&self) -> bool {
6831 AdjustReifyFnPointer |
6832 AdjustUnsafeFnPointer => false,
6833 AdjustDerefRef(ref r) => r.is_identity(),
6838 impl<'tcx> AutoDerefRef<'tcx> {
6839 pub fn is_identity(&self) -> bool {
6840 self.autoderefs == 0 && self.unsize.is_none() && self.autoref.is_none()
6844 impl<'tcx> ctxt<'tcx> {
6845 pub fn with_freevars<T, F>(&self, fid: NodeId, f: F) -> T where
6846 F: FnOnce(&[Freevar]) -> T,
6848 match self.freevars.borrow().get(&fid) {
6850 Some(d) => f(&d[..])
6854 /// Replace any late-bound regions bound in `value` with free variants attached to scope-id
6856 pub fn liberate_late_bound_regions<T>(&self,
6857 all_outlive_scope: region::CodeExtent,
6860 where T : TypeFoldable<'tcx>
6862 ty_fold::replace_late_bound_regions(
6864 |br| ty::ReFree(ty::FreeRegion{scope: all_outlive_scope, bound_region: br})).0
6867 /// Flattens two binding levels into one. So `for<'a> for<'b> Foo`
6868 /// becomes `for<'a,'b> Foo`.
6869 pub fn flatten_late_bound_regions<T>(&self, bound2_value: &Binder<Binder<T>>)
6871 where T: TypeFoldable<'tcx>
6873 let bound0_value = bound2_value.skip_binder().skip_binder();
6874 let value = ty_fold::fold_regions(self, bound0_value, &mut false,
6875 |region, current_depth| {
6877 ty::ReLateBound(debruijn, br) if debruijn.depth >= current_depth => {
6878 // should be true if no escaping regions from bound2_value
6879 assert!(debruijn.depth - current_depth <= 1);
6880 ty::ReLateBound(DebruijnIndex::new(current_depth), br)
6890 pub fn no_late_bound_regions<T>(&self, value: &Binder<T>) -> Option<T>
6891 where T : TypeFoldable<'tcx> + RegionEscape
6893 if value.0.has_escaping_regions() {
6896 Some(value.0.clone())
6900 /// Replace any late-bound regions bound in `value` with `'static`. Useful in trans but also
6901 /// method lookup and a few other places where precise region relationships are not required.
6902 pub fn erase_late_bound_regions<T>(&self, value: &Binder<T>) -> T
6903 where T : TypeFoldable<'tcx>
6905 ty_fold::replace_late_bound_regions(self, value, |_| ty::ReStatic).0
6908 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
6909 /// assigned starting at 1 and increasing monotonically in the order traversed
6910 /// by the fold operation.
6912 /// The chief purpose of this function is to canonicalize regions so that two
6913 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
6914 /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
6915 /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
6916 pub fn anonymize_late_bound_regions<T>(&self, sig: &Binder<T>) -> Binder<T>
6917 where T : TypeFoldable<'tcx>,
6919 let mut counter = 0;
6920 ty::Binder(ty_fold::replace_late_bound_regions(self, sig, |_| {
6922 ReLateBound(ty::DebruijnIndex::new(1), BrAnon(counter))
6926 pub fn make_substs_for_receiver_types(&self,
6927 trait_ref: &ty::TraitRef<'tcx>,
6928 method: &ty::Method<'tcx>)
6929 -> subst::Substs<'tcx>
6932 * Substitutes the values for the receiver's type parameters
6933 * that are found in method, leaving the method's type parameters
6937 let meth_tps: Vec<Ty> =
6938 method.generics.types.get_slice(subst::FnSpace)
6940 .map(|def| self.mk_param_from_def(def))
6942 let meth_regions: Vec<ty::Region> =
6943 method.generics.regions.get_slice(subst::FnSpace)
6945 .map(|def| def.to_early_bound_region())
6947 trait_ref.substs.clone().with_method(meth_tps, meth_regions)
6951 impl DebruijnIndex {
6952 pub fn new(depth: u32) -> DebruijnIndex {
6954 DebruijnIndex { depth: depth }
6957 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
6958 DebruijnIndex { depth: self.depth + amount }
6962 impl<'tcx> fmt::Debug for AutoAdjustment<'tcx> {
6963 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6965 AdjustReifyFnPointer => {
6966 write!(f, "AdjustReifyFnPointer")
6968 AdjustUnsafeFnPointer => {
6969 write!(f, "AdjustUnsafeFnPointer")
6971 AdjustDerefRef(ref data) => {
6972 write!(f, "{:?}", data)
6978 impl<'tcx> fmt::Debug for AutoDerefRef<'tcx> {
6979 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6980 write!(f, "AutoDerefRef({}, unsize={:?}, {:?})",
6981 self.autoderefs, self.unsize, self.autoref)
6985 impl<'tcx> fmt::Debug for TraitTy<'tcx> {
6986 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6987 write!(f, "TraitTy({:?},{:?})",
6993 impl<'tcx> fmt::Debug for ty::Predicate<'tcx> {
6994 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6996 Predicate::Trait(ref a) => write!(f, "{:?}", a),
6997 Predicate::Equate(ref pair) => write!(f, "{:?}", pair),
6998 Predicate::RegionOutlives(ref pair) => write!(f, "{:?}", pair),
6999 Predicate::TypeOutlives(ref pair) => write!(f, "{:?}", pair),
7000 Predicate::Projection(ref pair) => write!(f, "{:?}", pair),
7001 Predicate::WellFormed(ty) => write!(f, "WF({:?})", ty),
7002 Predicate::ObjectSafe(trait_def_id) => write!(f, "ObjectSafe({:?})", trait_def_id),
7007 // FIXME(#20298) -- all of these traits basically walk various
7008 // structures to test whether types/regions are reachable with various
7009 // properties. It should be possible to express them in terms of one
7010 // common "walker" trait or something.
7012 /// An "escaping region" is a bound region whose binder is not part of `t`.
7014 /// So, for example, consider a type like the following, which has two binders:
7016 /// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
7017 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
7018 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
7020 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
7021 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
7022 /// fn type*, that type has an escaping region: `'a`.
7024 /// Note that what I'm calling an "escaping region" is often just called a "free region". However,
7025 /// we already use the term "free region". It refers to the regions that we use to represent bound
7026 /// regions on a fn definition while we are typechecking its body.
7028 /// To clarify, conceptually there is no particular difference between an "escaping" region and a
7029 /// "free" region. However, there is a big difference in practice. Basically, when "entering" a
7030 /// binding level, one is generally required to do some sort of processing to a bound region, such
7031 /// as replacing it with a fresh/skolemized region, or making an entry in the environment to
7032 /// represent the scope to which it is attached, etc. An escaping region represents a bound region
7033 /// for which this processing has not yet been done.
7034 pub trait RegionEscape {
7035 fn has_escaping_regions(&self) -> bool {
7036 self.has_regions_escaping_depth(0)
7039 fn has_regions_escaping_depth(&self, depth: u32) -> bool;
7042 impl<'tcx> RegionEscape for Ty<'tcx> {
7043 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7044 self.region_depth > depth
7048 impl<'tcx> RegionEscape for TraitTy<'tcx> {
7049 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7050 self.principal.has_regions_escaping_depth(depth) ||
7051 self.bounds.has_regions_escaping_depth(depth)
7055 impl<'tcx> RegionEscape for ExistentialBounds<'tcx> {
7056 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7057 self.region_bound.has_regions_escaping_depth(depth) ||
7058 self.projection_bounds.has_regions_escaping_depth(depth)
7062 impl<'tcx> RegionEscape for Substs<'tcx> {
7063 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7064 self.types.has_regions_escaping_depth(depth) ||
7065 self.regions.has_regions_escaping_depth(depth)
7069 impl<'tcx> RegionEscape for ClosureSubsts<'tcx> {
7070 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7071 self.func_substs.has_regions_escaping_depth(depth) ||
7072 self.upvar_tys.iter().any(|t| t.has_regions_escaping_depth(depth))
7076 impl<T:RegionEscape> RegionEscape for Vec<T> {
7077 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7078 self.iter().any(|t| t.has_regions_escaping_depth(depth))
7082 impl<'tcx> RegionEscape for FnSig<'tcx> {
7083 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7084 self.inputs.has_regions_escaping_depth(depth) ||
7085 self.output.has_regions_escaping_depth(depth)
7089 impl<'tcx,T:RegionEscape> RegionEscape for VecPerParamSpace<T> {
7090 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7091 self.iter_enumerated().any(|(space, _, t)| {
7092 if space == subst::FnSpace {
7093 t.has_regions_escaping_depth(depth+1)
7095 t.has_regions_escaping_depth(depth)
7101 impl<'tcx> RegionEscape for TypeScheme<'tcx> {
7102 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7103 self.ty.has_regions_escaping_depth(depth)
7107 impl RegionEscape for Region {
7108 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7109 self.escapes_depth(depth)
7113 impl<'tcx> RegionEscape for GenericPredicates<'tcx> {
7114 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7115 self.predicates.has_regions_escaping_depth(depth)
7119 impl<'tcx> RegionEscape for Predicate<'tcx> {
7120 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7122 Predicate::Trait(ref data) => data.has_regions_escaping_depth(depth),
7123 Predicate::Equate(ref data) => data.has_regions_escaping_depth(depth),
7124 Predicate::RegionOutlives(ref data) => data.has_regions_escaping_depth(depth),
7125 Predicate::TypeOutlives(ref data) => data.has_regions_escaping_depth(depth),
7126 Predicate::Projection(ref data) => data.has_regions_escaping_depth(depth),
7127 Predicate::WellFormed(ty) => ty.has_regions_escaping_depth(depth),
7128 Predicate::ObjectSafe(_trait_def_id) => false,
7133 impl<'tcx,P:RegionEscape> RegionEscape for traits::Obligation<'tcx,P> {
7134 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7135 self.predicate.has_regions_escaping_depth(depth)
7139 impl<'tcx> RegionEscape for TraitRef<'tcx> {
7140 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7141 self.substs.types.iter().any(|t| t.has_regions_escaping_depth(depth)) ||
7142 self.substs.regions.has_regions_escaping_depth(depth)
7146 impl<'tcx> RegionEscape for subst::RegionSubsts {
7147 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7149 subst::ErasedRegions => false,
7150 subst::NonerasedRegions(ref r) => {
7151 r.iter().any(|t| t.has_regions_escaping_depth(depth))
7157 impl<'tcx,T:RegionEscape> RegionEscape for Binder<T> {
7158 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7159 self.0.has_regions_escaping_depth(depth + 1)
7163 impl<'tcx> RegionEscape for FnOutput<'tcx> {
7164 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7166 FnConverging(t) => t.has_regions_escaping_depth(depth),
7167 FnDiverging => false
7172 impl<'tcx> RegionEscape for EquatePredicate<'tcx> {
7173 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7174 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7178 impl<'tcx> RegionEscape for TraitPredicate<'tcx> {
7179 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7180 self.trait_ref.has_regions_escaping_depth(depth)
7184 impl<T:RegionEscape,U:RegionEscape> RegionEscape for OutlivesPredicate<T,U> {
7185 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7186 self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7190 impl<'tcx> RegionEscape for ProjectionPredicate<'tcx> {
7191 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7192 self.projection_ty.has_regions_escaping_depth(depth) ||
7193 self.ty.has_regions_escaping_depth(depth)
7197 impl<'tcx> RegionEscape for ProjectionTy<'tcx> {
7198 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7199 self.trait_ref.has_regions_escaping_depth(depth)
7203 pub trait HasTypeFlags {
7204 fn has_type_flags(&self, flags: TypeFlags) -> bool;
7205 fn has_projection_types(&self) -> bool {
7206 self.has_type_flags(TypeFlags::HAS_PROJECTION)
7208 fn references_error(&self) -> bool {
7209 self.has_type_flags(TypeFlags::HAS_TY_ERR)
7211 fn has_param_types(&self) -> bool {
7212 self.has_type_flags(TypeFlags::HAS_PARAMS)
7214 fn has_self_ty(&self) -> bool {
7215 self.has_type_flags(TypeFlags::HAS_SELF)
7217 fn has_infer_types(&self) -> bool {
7218 self.has_type_flags(TypeFlags::HAS_TY_INFER)
7220 fn needs_infer(&self) -> bool {
7221 self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_RE_INFER)
7223 fn needs_subst(&self) -> bool {
7224 self.has_type_flags(TypeFlags::NEEDS_SUBST)
7226 fn has_closure_types(&self) -> bool {
7227 self.has_type_flags(TypeFlags::HAS_TY_CLOSURE)
7229 fn has_erasable_regions(&self) -> bool {
7230 self.has_type_flags(TypeFlags::HAS_RE_EARLY_BOUND |
7231 TypeFlags::HAS_RE_INFER |
7232 TypeFlags::HAS_FREE_REGIONS)
7234 /// Indicates whether this value references only 'global'
7235 /// types/lifetimes that are the same regardless of what fn we are
7236 /// in. This is used for caching. Errs on the side of returning
7238 fn is_global(&self) -> bool {
7239 !self.has_type_flags(TypeFlags::HAS_LOCAL_NAMES)
7243 impl<'tcx,T:HasTypeFlags> HasTypeFlags for Vec<T> {
7244 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7245 self[..].has_type_flags(flags)
7249 impl<'tcx,T:HasTypeFlags> HasTypeFlags for [T] {
7250 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7251 self.iter().any(|p| p.has_type_flags(flags))
7255 impl<'tcx,T:HasTypeFlags> HasTypeFlags for VecPerParamSpace<T> {
7256 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7257 self.iter().any(|p| p.has_type_flags(flags))
7261 impl HasTypeFlags for abi::Abi {
7262 fn has_type_flags(&self, _flags: TypeFlags) -> bool {
7267 impl HasTypeFlags for hir::Unsafety {
7268 fn has_type_flags(&self, _flags: TypeFlags) -> bool {
7273 impl HasTypeFlags for BuiltinBounds {
7274 fn has_type_flags(&self, _flags: TypeFlags) -> bool {
7279 impl<'tcx> HasTypeFlags for ClosureTy<'tcx> {
7280 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7281 self.sig.has_type_flags(flags)
7285 impl<'tcx> HasTypeFlags for ClosureUpvar<'tcx> {
7286 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7287 self.ty.has_type_flags(flags)
7291 impl<'tcx> HasTypeFlags for ExistentialBounds<'tcx> {
7292 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7293 self.projection_bounds.has_type_flags(flags)
7297 impl<'tcx> HasTypeFlags for ty::InstantiatedPredicates<'tcx> {
7298 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7299 self.predicates.has_type_flags(flags)
7303 impl<'tcx> HasTypeFlags for Predicate<'tcx> {
7304 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7306 Predicate::Trait(ref data) => data.has_type_flags(flags),
7307 Predicate::Equate(ref data) => data.has_type_flags(flags),
7308 Predicate::RegionOutlives(ref data) => data.has_type_flags(flags),
7309 Predicate::TypeOutlives(ref data) => data.has_type_flags(flags),
7310 Predicate::Projection(ref data) => data.has_type_flags(flags),
7311 Predicate::WellFormed(data) => data.has_type_flags(flags),
7312 Predicate::ObjectSafe(_trait_def_id) => false,
7317 impl<'tcx> HasTypeFlags for TraitPredicate<'tcx> {
7318 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7319 self.trait_ref.has_type_flags(flags)
7323 impl<'tcx> HasTypeFlags for EquatePredicate<'tcx> {
7324 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7325 self.0.has_type_flags(flags) || self.1.has_type_flags(flags)
7329 impl HasTypeFlags for Region {
7330 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7331 if flags.intersects(TypeFlags::HAS_LOCAL_NAMES) {
7332 // does this represent a region that cannot be named in a global
7333 // way? used in fulfillment caching.
7335 ty::ReStatic | ty::ReEmpty => {}
7339 if flags.intersects(TypeFlags::HAS_RE_INFER) {
7341 ty::ReVar(_) | ty::ReSkolemized(..) => { return true }
7349 impl<T:HasTypeFlags,U:HasTypeFlags> HasTypeFlags for OutlivesPredicate<T,U> {
7350 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7351 self.0.has_type_flags(flags) || self.1.has_type_flags(flags)
7355 impl<'tcx> HasTypeFlags for ProjectionPredicate<'tcx> {
7356 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7357 self.projection_ty.has_type_flags(flags) || self.ty.has_type_flags(flags)
7361 impl<'tcx> HasTypeFlags for ProjectionTy<'tcx> {
7362 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7363 self.trait_ref.has_type_flags(flags)
7367 impl<'tcx> HasTypeFlags for Ty<'tcx> {
7368 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7369 self.flags.get().intersects(flags)
7373 impl<'tcx> HasTypeFlags for TypeAndMut<'tcx> {
7374 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7375 self.ty.has_type_flags(flags)
7379 impl<'tcx> HasTypeFlags for TraitRef<'tcx> {
7380 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7381 self.substs.has_type_flags(flags)
7385 impl<'tcx> HasTypeFlags for subst::Substs<'tcx> {
7386 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7387 self.types.has_type_flags(flags) || match self.regions {
7388 subst::ErasedRegions => false,
7389 subst::NonerasedRegions(ref r) => r.has_type_flags(flags)
7394 impl<'tcx,T> HasTypeFlags for Option<T>
7395 where T : HasTypeFlags
7397 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7398 self.iter().any(|t| t.has_type_flags(flags))
7402 impl<'tcx,T> HasTypeFlags for Rc<T>
7403 where T : HasTypeFlags
7405 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7406 (**self).has_type_flags(flags)
7410 impl<'tcx,T> HasTypeFlags for Box<T>
7411 where T : HasTypeFlags
7413 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7414 (**self).has_type_flags(flags)
7418 impl<T> HasTypeFlags for Binder<T>
7419 where T : HasTypeFlags
7421 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7422 self.0.has_type_flags(flags)
7426 impl<'tcx> HasTypeFlags for FnOutput<'tcx> {
7427 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7429 FnConverging(t) => t.has_type_flags(flags),
7430 FnDiverging => false,
7435 impl<'tcx> HasTypeFlags for FnSig<'tcx> {
7436 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7437 self.inputs.iter().any(|t| t.has_type_flags(flags)) ||
7438 self.output.has_type_flags(flags)
7442 impl<'tcx> HasTypeFlags for BareFnTy<'tcx> {
7443 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7444 self.sig.has_type_flags(flags)
7448 impl<'tcx> HasTypeFlags for ClosureSubsts<'tcx> {
7449 fn has_type_flags(&self, flags: TypeFlags) -> bool {
7450 self.func_substs.has_type_flags(flags) ||
7451 self.upvar_tys.iter().any(|t| t.has_type_flags(flags))
7455 impl<'tcx> fmt::Debug for ClosureTy<'tcx> {
7456 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7457 write!(f, "ClosureTy({},{:?},{})",
7464 impl<'tcx> fmt::Debug for ClosureUpvar<'tcx> {
7465 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7466 write!(f, "ClosureUpvar({:?},{:?})",
7472 impl<'a, 'tcx> fmt::Debug for ParameterEnvironment<'a, 'tcx> {
7473 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7474 write!(f, "ParameterEnvironment(\
7476 implicit_region_bound={:?}, \
7477 caller_bounds={:?})",
7479 self.implicit_region_bound,
7484 impl<'tcx> fmt::Debug for ObjectLifetimeDefault {
7485 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7487 ObjectLifetimeDefault::Ambiguous => write!(f, "Ambiguous"),
7488 ObjectLifetimeDefault::BaseDefault => write!(f, "BaseDefault"),
7489 ObjectLifetimeDefault::Specific(ref r) => write!(f, "{:?}", r),