1 // Copyright 2012-2015 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 //! misc. type-system utilities too small to deserve their own file
14 use hir::def_id::DefId;
15 use hir::map::{DefPathData, Node};
17 use ich::NodeIdHashingMode;
18 use middle::const_val::ConstVal;
19 use traits::{self, Reveal};
20 use ty::{self, Ty, TyCtxt, TypeFoldable};
21 use ty::fold::TypeVisitor;
22 use ty::subst::{Subst, UnpackedKind};
23 use ty::maps::TyCtxtAt;
24 use ty::TypeVariants::*;
25 use ty::layout::Integer;
26 use util::common::ErrorReported;
27 use middle::lang_items;
28 use mir::interpret::{Value, PrimVal};
30 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
32 use rustc_data_structures::fx::FxHashMap;
36 use syntax::ast::{self, Name};
37 use syntax::attr::{self, SignedInt, UnsignedInt};
38 use syntax_pos::{Span, DUMMY_SP};
40 #[derive(Copy, Clone, Debug)]
41 pub struct Discr<'tcx> {
46 impl<'tcx> fmt::Display for Discr<'tcx> {
47 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
48 if self.ty.is_signed() {
49 write!(fmt, "{}", self.val as i128)
51 write!(fmt, "{}", self.val)
56 impl<'tcx> Discr<'tcx> {
57 /// Adds 1 to the value and wraps around if the maximum for the type is reached
58 pub fn wrap_incr<'a, 'gcx>(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
59 self.checked_add(tcx, 1).0
61 pub fn checked_add<'a, 'gcx>(self, tcx: TyCtxt<'a, 'gcx, 'tcx>, n: u128) -> (Self, bool) {
62 let (int, signed) = match self.ty.sty {
63 TyInt(ity) => (Integer::from_attr(tcx, SignedInt(ity)), true),
64 TyUint(uty) => (Integer::from_attr(tcx, UnsignedInt(uty)), false),
65 _ => bug!("non integer discriminant"),
68 let (min, max) = match int {
69 Integer::I8 => (i8::min_value() as i128, i8::max_value() as i128),
70 Integer::I16 => (i16::min_value() as i128, i16::max_value() as i128),
71 Integer::I32 => (i32::min_value() as i128, i32::max_value() as i128),
72 Integer::I64 => (i64::min_value() as i128, i64::max_value() as i128),
73 Integer::I128 => (i128::min_value(), i128::max_value()),
75 let val = self.val as i128;
77 let oflo = val > max - n;
79 min + (n - (max - val) - 1)
88 let (min, max) = match int {
89 Integer::I8 => (u8::min_value() as u128, u8::max_value() as u128),
90 Integer::I16 => (u16::min_value() as u128, u16::max_value() as u128),
91 Integer::I32 => (u32::min_value() as u128, u32::max_value() as u128),
92 Integer::I64 => (u64::min_value() as u128, u64::max_value() as u128),
93 Integer::I128 => (u128::min_value(), u128::max_value()),
96 let oflo = val > max - n;
98 min + (n - (max - val) - 1)
110 pub trait IntTypeExt {
111 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>;
112 fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Discr<'tcx>>)
113 -> Option<Discr<'tcx>>;
114 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Discr<'tcx>;
117 impl IntTypeExt for attr::IntType {
118 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
120 SignedInt(ast::IntTy::I8) => tcx.types.i8,
121 SignedInt(ast::IntTy::I16) => tcx.types.i16,
122 SignedInt(ast::IntTy::I32) => tcx.types.i32,
123 SignedInt(ast::IntTy::I64) => tcx.types.i64,
124 SignedInt(ast::IntTy::I128) => tcx.types.i128,
125 SignedInt(ast::IntTy::Isize) => tcx.types.isize,
126 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
127 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
128 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
129 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
130 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
131 UnsignedInt(ast::UintTy::Usize) => tcx.types.usize,
135 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Discr<'tcx> {
142 fn disr_incr<'a, 'tcx>(
144 tcx: TyCtxt<'a, 'tcx, 'tcx>,
145 val: Option<Discr<'tcx>>,
146 ) -> Option<Discr<'tcx>> {
147 if let Some(val) = val {
148 assert_eq!(self.to_ty(tcx), val.ty);
149 let (new, oflo) = val.checked_add(tcx, 1);
156 Some(self.initial_discriminant(tcx))
162 #[derive(Copy, Clone)]
163 pub enum CopyImplementationError<'tcx> {
164 InfrigingField(&'tcx ty::FieldDef),
169 /// Describes whether a type is representable. For types that are not
170 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
171 /// distinguish between types that are recursive with themselves and types that
172 /// contain a different recursive type. These cases can therefore be treated
173 /// differently when reporting errors.
175 /// The ordering of the cases is significant. They are sorted so that cmp::max
176 /// will keep the "more erroneous" of two values.
177 #[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
178 pub enum Representability {
181 SelfRecursive(Vec<Span>),
184 impl<'tcx> ty::ParamEnv<'tcx> {
185 /// Construct a trait environment suitable for contexts where
186 /// there are no where clauses in scope.
187 pub fn empty(reveal: Reveal) -> Self {
188 Self::new(ty::Slice::empty(), reveal, ty::UniverseIndex::ROOT)
191 /// Construct a trait environment with the given set of predicates.
192 pub fn new(caller_bounds: &'tcx ty::Slice<ty::Predicate<'tcx>>,
194 universe: ty::UniverseIndex)
196 ty::ParamEnv { caller_bounds, reveal, universe }
199 /// Returns a new parameter environment with the same clauses, but
200 /// which "reveals" the true results of projections in all cases
201 /// (even for associated types that are specializable). This is
202 /// the desired behavior during trans and certain other special
203 /// contexts; normally though we want to use `Reveal::UserFacing`,
204 /// which is the default.
205 pub fn reveal_all(self) -> Self {
206 ty::ParamEnv { reveal: Reveal::All, ..self }
209 pub fn can_type_implement_copy<'a>(self,
210 tcx: TyCtxt<'a, 'tcx, 'tcx>,
211 self_type: Ty<'tcx>, span: Span)
212 -> Result<(), CopyImplementationError<'tcx>> {
213 // FIXME: (@jroesch) float this code up
214 tcx.infer_ctxt().enter(|infcx| {
215 let (adt, substs) = match self_type.sty {
216 ty::TyAdt(adt, substs) => (adt, substs),
217 _ => return Err(CopyImplementationError::NotAnAdt),
220 let field_implements_copy = |field: &ty::FieldDef| {
221 let cause = traits::ObligationCause::dummy();
222 match traits::fully_normalize(&infcx, cause, self, &field.ty(tcx, substs)) {
223 Ok(ty) => !infcx.type_moves_by_default(self, ty, span),
228 for variant in &adt.variants {
229 for field in &variant.fields {
230 if !field_implements_copy(field) {
231 return Err(CopyImplementationError::InfrigingField(field));
236 if adt.has_dtor(tcx) {
237 return Err(CopyImplementationError::HasDestructor);
245 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
246 /// Creates a hash of the type `Ty` which will be the same no matter what crate
247 /// context it's calculated within. This is used by the `type_id` intrinsic.
248 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
249 let mut hasher = StableHasher::new();
250 let mut hcx = self.create_stable_hashing_context();
252 // We want the type_id be independent of the types free regions, so we
253 // erase them. The erase_regions() call will also anonymize bound
254 // regions, which is desirable too.
255 let ty = self.erase_regions(&ty);
257 hcx.while_hashing_spans(false, |hcx| {
258 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
259 ty.hash_stable(hcx, &mut hasher);
266 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
267 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
269 ty::TyAdt(def, substs) => {
270 for field in def.all_fields() {
271 let field_ty = field.ty(self, substs);
272 if let TyError = field_ty.sty {
282 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
283 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
284 pub fn positional_element_ty(self,
287 variant: Option<DefId>) -> Option<Ty<'tcx>> {
288 match (&ty.sty, variant) {
289 (&TyAdt(adt, substs), Some(vid)) => {
290 adt.variant_with_id(vid).fields.get(i).map(|f| f.ty(self, substs))
292 (&TyAdt(adt, substs), None) => {
293 // Don't use `non_enum_variant`, this may be a univariant enum.
294 adt.variants[0].fields.get(i).map(|f| f.ty(self, substs))
296 (&TyTuple(ref v, _), None) => v.get(i).cloned(),
301 /// Returns the type of element at field `n` in struct or struct-like type `t`.
302 /// For an enum `t`, `variant` must be some def id.
303 pub fn named_element_ty(self,
306 variant: Option<DefId>) -> Option<Ty<'tcx>> {
307 match (&ty.sty, variant) {
308 (&TyAdt(adt, substs), Some(vid)) => {
309 adt.variant_with_id(vid).find_field_named(n).map(|f| f.ty(self, substs))
311 (&TyAdt(adt, substs), None) => {
312 adt.non_enum_variant().find_field_named(n).map(|f| f.ty(self, substs))
318 /// Returns the deeply last field of nested structures, or the same type,
319 /// if not a structure at all. Corresponds to the only possible unsized
320 /// field, and its type can be used to determine unsizing strategy.
321 pub fn struct_tail(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
324 ty::TyAdt(def, substs) => {
325 if !def.is_struct() {
328 match def.non_enum_variant().fields.last() {
329 Some(f) => ty = f.ty(self, substs),
334 ty::TyTuple(tys, _) => {
335 if let Some((&last_ty, _)) = tys.split_last() {
350 /// Same as applying struct_tail on `source` and `target`, but only
351 /// keeps going as long as the two types are instances of the same
352 /// structure definitions.
353 /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
354 /// whereas struct_tail produces `T`, and `Trait`, respectively.
355 pub fn struct_lockstep_tails(self,
358 -> (Ty<'tcx>, Ty<'tcx>) {
359 let (mut a, mut b) = (source, target);
361 match (&a.sty, &b.sty) {
362 (&TyAdt(a_def, a_substs), &TyAdt(b_def, b_substs))
363 if a_def == b_def && a_def.is_struct() => {
364 if let Some(f) = a_def.non_enum_variant().fields.last() {
365 a = f.ty(self, a_substs);
366 b = f.ty(self, b_substs);
371 (&TyTuple(a_tys, _), &TyTuple(b_tys, _))
372 if a_tys.len() == b_tys.len() => {
373 if let Some(a_last) = a_tys.last() {
375 b = b_tys.last().unwrap();
386 /// Given a set of predicates that apply to an object type, returns
387 /// the region bounds that the (erased) `Self` type must
388 /// outlive. Precisely *because* the `Self` type is erased, the
389 /// parameter `erased_self_ty` must be supplied to indicate what type
390 /// has been used to represent `Self` in the predicates
391 /// themselves. This should really be a unique type; `FreshTy(0)` is a
394 /// NB: in some cases, particularly around higher-ranked bounds,
395 /// this function returns a kind of conservative approximation.
396 /// That is, all regions returned by this function are definitely
397 /// required, but there may be other region bounds that are not
398 /// returned, as well as requirements like `for<'a> T: 'a`.
400 /// Requires that trait definitions have been processed so that we can
401 /// elaborate predicates and walk supertraits.
403 /// FIXME callers may only have a &[Predicate], not a Vec, so that's
404 /// what this code should accept.
405 pub fn required_region_bounds(self,
406 erased_self_ty: Ty<'tcx>,
407 predicates: Vec<ty::Predicate<'tcx>>)
408 -> Vec<ty::Region<'tcx>> {
409 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
413 assert!(!erased_self_ty.has_escaping_regions());
415 traits::elaborate_predicates(self, predicates)
416 .filter_map(|predicate| {
418 ty::Predicate::Projection(..) |
419 ty::Predicate::Trait(..) |
420 ty::Predicate::Subtype(..) |
421 ty::Predicate::WellFormed(..) |
422 ty::Predicate::ObjectSafe(..) |
423 ty::Predicate::ClosureKind(..) |
424 ty::Predicate::RegionOutlives(..) |
425 ty::Predicate::ConstEvaluatable(..) => {
428 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
429 // Search for a bound of the form `erased_self_ty
430 // : 'a`, but be wary of something like `for<'a>
431 // erased_self_ty : 'a` (we interpret a
432 // higher-ranked bound like that as 'static,
433 // though at present the code in `fulfill.rs`
434 // considers such bounds to be unsatisfiable, so
435 // it's kind of a moot point since you could never
436 // construct such an object, but this seems
437 // correct even if that code changes).
438 if t == erased_self_ty && !r.has_escaping_regions() {
449 /// Calculate the destructor of a given type.
450 pub fn calculate_dtor(
453 validate: &mut dyn FnMut(Self, DefId) -> Result<(), ErrorReported>
454 ) -> Option<ty::Destructor> {
455 let drop_trait = if let Some(def_id) = self.lang_items().drop_trait() {
461 ty::maps::queries::coherent_trait::ensure(self, drop_trait);
463 let mut dtor_did = None;
464 let ty = self.type_of(adt_did);
465 self.for_each_relevant_impl(drop_trait, ty, |impl_did| {
466 if let Some(item) = self.associated_items(impl_did).next() {
467 if let Ok(()) = validate(self, impl_did) {
468 dtor_did = Some(item.def_id);
473 Some(ty::Destructor { did: dtor_did? })
476 /// Return the set of types that are required to be alive in
477 /// order to run the destructor of `def` (see RFCs 769 and
480 /// Note that this returns only the constraints for the
481 /// destructor of `def` itself. For the destructors of the
482 /// contents, you need `adt_dtorck_constraint`.
483 pub fn destructor_constraints(self, def: &'tcx ty::AdtDef)
484 -> Vec<ty::subst::Kind<'tcx>>
486 let dtor = match def.destructor(self) {
488 debug!("destructor_constraints({:?}) - no dtor", def.did);
491 Some(dtor) => dtor.did
494 // RFC 1238: if the destructor method is tagged with the
495 // attribute `unsafe_destructor_blind_to_params`, then the
496 // compiler is being instructed to *assume* that the
497 // destructor will not access borrowed data,
498 // even if such data is otherwise reachable.
500 // Such access can be in plain sight (e.g. dereferencing
501 // `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden
502 // (e.g. calling `foo.0.clone()` of `Foo<T:Clone>`).
503 if self.has_attr(dtor, "unsafe_destructor_blind_to_params") {
504 debug!("destructor_constraint({:?}) - blind", def.did);
508 let impl_def_id = self.associated_item(dtor).container.id();
509 let impl_generics = self.generics_of(impl_def_id);
511 // We have a destructor - all the parameters that are not
512 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
515 // We need to return the list of parameters from the ADTs
516 // generics/substs that correspond to impure parameters on the
517 // impl's generics. This is a bit ugly, but conceptually simple:
519 // Suppose our ADT looks like the following
521 // struct S<X, Y, Z>(X, Y, Z);
525 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
527 // We want to return the parameters (X, Y). For that, we match
528 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
529 // <P1, P2, P0>, and then look up which of the impl substs refer to
530 // parameters marked as pure.
532 let impl_substs = match self.type_of(impl_def_id).sty {
533 ty::TyAdt(def_, substs) if def_ == def => substs,
537 let item_substs = match self.type_of(def.did).sty {
538 ty::TyAdt(def_, substs) if def_ == def => substs,
542 let result = item_substs.iter().zip(impl_substs.iter())
545 UnpackedKind::Lifetime(&ty::RegionKind::ReEarlyBound(ref ebr)) => {
546 !impl_generics.region_param(ebr, self).pure_wrt_drop
548 UnpackedKind::Type(&ty::TyS {
549 sty: ty::TypeVariants::TyParam(ref pt), ..
551 !impl_generics.type_param(pt, self).pure_wrt_drop
553 UnpackedKind::Lifetime(_) | UnpackedKind::Type(_) => {
554 // not a type or region param - this should be reported
559 }).map(|(&item_param, _)| item_param).collect();
560 debug!("destructor_constraint({:?}) = {:?}", def.did, result);
564 /// Return a set of constraints that needs to be satisfied in
565 /// order for `ty` to be valid for destruction.
566 pub fn dtorck_constraint_for_ty(self,
571 -> Result<ty::DtorckConstraint<'tcx>, ErrorReported>
573 debug!("dtorck_constraint_for_ty({:?}, {:?}, {:?}, {:?})",
574 span, for_ty, depth, ty);
576 if depth >= self.sess.recursion_limit.get() {
577 let mut err = struct_span_err!(
578 self.sess, span, E0320,
579 "overflow while adding drop-check rules for {}", for_ty);
580 err.note(&format!("overflowed on {}", ty));
582 return Err(ErrorReported);
585 let result = match ty.sty {
586 ty::TyBool | ty::TyChar | ty::TyInt(_) | ty::TyUint(_) |
587 ty::TyFloat(_) | ty::TyStr | ty::TyNever | ty::TyForeign(..) |
588 ty::TyRawPtr(..) | ty::TyRef(..) | ty::TyFnDef(..) | ty::TyFnPtr(_) |
589 ty::TyGeneratorWitness(..) => {
590 // these types never have a destructor
591 Ok(ty::DtorckConstraint::empty())
594 ty::TyArray(ety, _) | ty::TySlice(ety) => {
595 // single-element containers, behave like their element
596 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ety)
599 ty::TyTuple(tys, _) => {
600 tys.iter().map(|ty| {
601 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
605 ty::TyClosure(def_id, substs) => {
606 substs.upvar_tys(def_id, self).map(|ty| {
607 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
611 ty::TyGenerator(def_id, substs, _) => {
612 // Note that the interior types are ignored here.
613 // Any type reachable inside the interior must also be reachable
614 // through the upvars.
615 substs.upvar_tys(def_id, self).map(|ty| {
616 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
620 ty::TyAdt(def, substs) => {
621 let ty::DtorckConstraint {
622 dtorck_types, outlives
623 } = self.at(span).adt_dtorck_constraint(def.did);
624 Ok(ty::DtorckConstraint {
625 // FIXME: we can try to recursively `dtorck_constraint_on_ty`
626 // there, but that needs some way to handle cycles.
627 dtorck_types: dtorck_types.subst(self, substs),
628 outlives: outlives.subst(self, substs)
632 // Objects must be alive in order for their destructor
634 ty::TyDynamic(..) => Ok(ty::DtorckConstraint {
635 outlives: vec![ty.into()],
636 dtorck_types: vec![],
639 // Types that can't be resolved. Pass them forward.
640 ty::TyProjection(..) | ty::TyAnon(..) | ty::TyParam(..) => {
641 Ok(ty::DtorckConstraint {
643 dtorck_types: vec![ty],
647 ty::TyInfer(..) | ty::TyError => {
648 self.sess.delay_span_bug(span, "unresolved type in dtorck");
653 debug!("dtorck_constraint_for_ty({:?}) = {:?}", ty, result);
657 pub fn is_closure(self, def_id: DefId) -> bool {
658 self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr
661 /// Given the `DefId` of a fn or closure, returns the `DefId` of
662 /// the innermost fn item that the closure is contained within.
663 /// This is a significant def-id because, when we do
664 /// type-checking, we type-check this fn item and all of its
665 /// (transitive) closures together. Therefore, when we fetch the
666 /// `typeck_tables_of` the closure, for example, we really wind up
667 /// fetching the `typeck_tables_of` the enclosing fn item.
668 pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
669 let mut def_id = def_id;
670 while self.is_closure(def_id) {
671 def_id = self.parent_def_id(def_id).unwrap_or_else(|| {
672 bug!("closure {:?} has no parent", def_id);
678 /// Given the def-id and substs a closure, creates the type of
679 /// `self` argument that the closure expects. For example, for a
680 /// `Fn` closure, this would return a reference type `&T` where
683 /// Returns `None` if this closure's kind has not yet been inferred.
684 /// This should only be possible during type checking.
686 /// Note that the return value is a late-bound region and hence
687 /// wrapped in a binder.
688 pub fn closure_env_ty(self,
689 closure_def_id: DefId,
690 closure_substs: ty::ClosureSubsts<'tcx>)
691 -> Option<ty::Binder<Ty<'tcx>>>
693 let closure_ty = self.mk_closure(closure_def_id, closure_substs);
694 let env_region = ty::ReLateBound(ty::DebruijnIndex::new(1), ty::BrEnv);
695 let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self);
696 let closure_kind = closure_kind_ty.to_opt_closure_kind()?;
697 let env_ty = match closure_kind {
698 ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty),
699 ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty),
700 ty::ClosureKind::FnOnce => closure_ty,
702 Some(ty::Binder(env_ty))
705 /// Given the def-id of some item that has no type parameters, make
706 /// a suitable "empty substs" for it.
707 pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> &'tcx ty::Substs<'tcx> {
708 ty::Substs::for_item(self, item_def_id,
709 |_, _| self.types.re_erased,
711 bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
715 /// Return whether the node pointed to by def_id is a static item, and its mutability
716 pub fn is_static(&self, def_id: DefId) -> Option<hir::Mutability> {
717 if let Some(node) = self.hir.get_if_local(def_id) {
719 Node::NodeItem(&hir::Item {
720 node: hir::ItemStatic(_, mutbl, _), ..
722 Node::NodeForeignItem(&hir::ForeignItem {
723 node: hir::ForeignItemStatic(_, is_mutbl), ..
726 hir::Mutability::MutMutable
728 hir::Mutability::MutImmutable
733 match self.describe_def(def_id) {
734 Some(Def::Static(_, is_mutbl)) =>
736 hir::Mutability::MutMutable
738 hir::Mutability::MutImmutable
746 pub struct TypeIdHasher<'a, 'gcx: 'a+'tcx, 'tcx: 'a, W> {
747 tcx: TyCtxt<'a, 'gcx, 'tcx>,
748 state: StableHasher<W>,
751 impl<'a, 'gcx, 'tcx, W> TypeIdHasher<'a, 'gcx, 'tcx, W>
752 where W: StableHasherResult
754 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
755 TypeIdHasher { tcx: tcx, state: StableHasher::new() }
758 pub fn finish(self) -> W {
762 pub fn hash<T: Hash>(&mut self, x: T) {
763 x.hash(&mut self.state);
766 fn hash_discriminant_u8<T>(&mut self, x: &T) {
768 intrinsics::discriminant_value(x)
771 assert_eq!(v, b as u64);
775 fn def_id(&mut self, did: DefId) {
776 // Hash the DefPath corresponding to the DefId, which is independent
777 // of compiler internal state. We already have a stable hash value of
778 // all DefPaths available via tcx.def_path_hash(), so we just feed that
780 let hash = self.tcx.def_path_hash(did);
785 impl<'a, 'gcx, 'tcx, W> TypeVisitor<'tcx> for TypeIdHasher<'a, 'gcx, 'tcx, W>
786 where W: StableHasherResult
788 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
789 // Distinguish between the Ty variants uniformly.
790 self.hash_discriminant_u8(&ty.sty);
793 TyInt(i) => self.hash(i),
794 TyUint(u) => self.hash(u),
795 TyFloat(f) => self.hash(f),
797 self.hash_discriminant_u8(&n.val);
799 ConstVal::Value(Value::ByVal(PrimVal::Bytes(b))) => self.hash(b),
800 ConstVal::Unevaluated(def_id, _) => self.def_id(def_id),
801 _ => bug!("arrays should not have {:?} as length", n)
805 TyRef(_, m) => self.hash(m.mutbl),
806 TyClosure(def_id, _) |
807 TyGenerator(def_id, _, _) |
809 TyFnDef(def_id, _) => self.def_id(def_id),
810 TyAdt(d, _) => self.def_id(d.did),
811 TyForeign(def_id) => self.def_id(def_id),
813 self.hash(f.unsafety());
815 self.hash(f.variadic());
816 self.hash(f.inputs().skip_binder().len());
818 TyDynamic(ref data, ..) => {
819 if let Some(p) = data.principal() {
820 self.def_id(p.def_id());
822 for d in data.auto_traits() {
826 TyGeneratorWitness(tys) => {
827 self.hash(tys.skip_binder().len());
829 TyTuple(tys, defaulted) => {
830 self.hash(tys.len());
831 self.hash(defaulted);
835 self.hash(p.name.as_str());
837 TyProjection(ref data) => {
838 self.def_id(data.item_def_id);
847 TyInfer(_) => bug!("TypeIdHasher: unexpected type {}", ty)
850 ty.super_visit_with(self)
853 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
854 self.hash_discriminant_u8(r);
859 // No variant fields to hash for these ...
861 ty::ReLateBound(db, ty::BrAnon(i)) => {
865 ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
869 ty::ReClosureBound(..) |
870 ty::ReLateBound(..) |
874 ty::ReSkolemized(..) => {
875 bug!("TypeIdHasher: unexpected region {:?}", r)
881 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, x: &ty::Binder<T>) -> bool {
882 // Anonymize late-bound regions so that, for example:
883 // `for<'a, b> fn(&'a &'b T)` and `for<'a, b> fn(&'b &'a T)`
884 // result in the same TypeId (the two types are equivalent).
885 self.tcx.anonymize_late_bound_regions(x).super_visit_with(self)
889 impl<'a, 'tcx> ty::TyS<'tcx> {
890 pub fn moves_by_default(&'tcx self,
891 tcx: TyCtxt<'a, 'tcx, 'tcx>,
892 param_env: ty::ParamEnv<'tcx>,
895 !tcx.at(span).is_copy_raw(param_env.and(self))
898 pub fn is_sized(&'tcx self,
899 tcx_at: TyCtxtAt<'a, 'tcx, 'tcx>,
900 param_env: ty::ParamEnv<'tcx>)-> bool
902 tcx_at.is_sized_raw(param_env.and(self))
905 pub fn is_freeze(&'tcx self,
906 tcx: TyCtxt<'a, 'tcx, 'tcx>,
907 param_env: ty::ParamEnv<'tcx>,
910 tcx.at(span).is_freeze_raw(param_env.and(self))
913 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
914 /// non-copy and *might* have a destructor attached; if it returns
915 /// `false`, then `ty` definitely has no destructor (i.e. no drop glue).
917 /// (Note that this implies that if `ty` has a destructor attached,
918 /// then `needs_drop` will definitely return `true` for `ty`.)
920 pub fn needs_drop(&'tcx self,
921 tcx: TyCtxt<'a, 'tcx, 'tcx>,
922 param_env: ty::ParamEnv<'tcx>)
924 tcx.needs_drop_raw(param_env.and(self))
927 /// Check whether a type is representable. This means it cannot contain unboxed
928 /// structural recursion. This check is needed for structs and enums.
929 pub fn is_representable(&'tcx self,
930 tcx: TyCtxt<'a, 'tcx, 'tcx>,
932 -> Representability {
934 // Iterate until something non-representable is found
935 fn fold_repr<It: Iterator<Item=Representability>>(iter: It) -> Representability {
936 iter.fold(Representability::Representable, |r1, r2| {
938 (Representability::SelfRecursive(v1),
939 Representability::SelfRecursive(v2)) => {
940 Representability::SelfRecursive(v1.iter().map(|s| *s).chain(v2).collect())
942 (r1, r2) => cmp::max(r1, r2)
947 fn are_inner_types_recursive<'a, 'tcx>(
948 tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span,
949 seen: &mut Vec<Ty<'tcx>>,
950 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
955 TyTuple(ref ts, _) => {
956 // Find non representable
957 fold_repr(ts.iter().map(|ty| {
958 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
961 // Fixed-length vectors.
962 // FIXME(#11924) Behavior undecided for zero-length vectors.
964 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
966 TyAdt(def, substs) => {
967 // Find non representable fields with their spans
968 fold_repr(def.all_fields().map(|field| {
969 let ty = field.ty(tcx, substs);
970 let span = tcx.hir.span_if_local(field.did).unwrap_or(sp);
971 match is_type_structurally_recursive(tcx, span, seen,
972 representable_cache, ty)
974 Representability::SelfRecursive(_) => {
975 Representability::SelfRecursive(vec![span])
982 // this check is run on type definitions, so we don't expect
983 // to see closure types
984 bug!("requires check invoked on inapplicable type: {:?}", ty)
986 _ => Representability::Representable,
990 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
992 TyAdt(ty_def, _) => {
999 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1000 match (&a.sty, &b.sty) {
1001 (&TyAdt(did_a, substs_a), &TyAdt(did_b, substs_b)) => {
1006 substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type(a, b))
1012 // Does the type `ty` directly (without indirection through a pointer)
1013 // contain any types on stack `seen`?
1014 fn is_type_structurally_recursive<'a, 'tcx>(
1015 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1017 seen: &mut Vec<Ty<'tcx>>,
1018 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
1019 ty: Ty<'tcx>) -> Representability
1021 debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
1022 if let Some(representability) = representable_cache.get(ty) {
1023 debug!("is_type_structurally_recursive: {:?} {:?} - (cached) {:?}",
1024 ty, sp, representability);
1025 return representability.clone();
1028 let representability = is_type_structurally_recursive_inner(
1029 tcx, sp, seen, representable_cache, ty);
1031 representable_cache.insert(ty, representability.clone());
1035 fn is_type_structurally_recursive_inner<'a, 'tcx>(
1036 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1038 seen: &mut Vec<Ty<'tcx>>,
1039 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
1040 ty: Ty<'tcx>) -> Representability
1045 // Iterate through stack of previously seen types.
1046 let mut iter = seen.iter();
1048 // The first item in `seen` is the type we are actually curious about.
1049 // We want to return SelfRecursive if this type contains itself.
1050 // It is important that we DON'T take generic parameters into account
1051 // for this check, so that Bar<T> in this example counts as SelfRecursive:
1054 // struct Bar<T> { x: Bar<Foo> }
1056 if let Some(&seen_type) = iter.next() {
1057 if same_struct_or_enum(seen_type, def) {
1058 debug!("SelfRecursive: {:?} contains {:?}",
1061 return Representability::SelfRecursive(vec![sp]);
1065 // We also need to know whether the first item contains other types
1066 // that are structurally recursive. If we don't catch this case, we
1067 // will recurse infinitely for some inputs.
1069 // It is important that we DO take generic parameters into account
1070 // here, so that code like this is considered SelfRecursive, not
1071 // ContainsRecursive:
1073 // struct Foo { Option<Option<Foo>> }
1075 for &seen_type in iter {
1076 if same_type(ty, seen_type) {
1077 debug!("ContainsRecursive: {:?} contains {:?}",
1080 return Representability::ContainsRecursive;
1085 // For structs and enums, track all previously seen types by pushing them
1086 // onto the 'seen' stack.
1088 let out = are_inner_types_recursive(tcx, sp, seen, representable_cache, ty);
1093 // No need to push in other cases.
1094 are_inner_types_recursive(tcx, sp, seen, representable_cache, ty)
1099 debug!("is_type_representable: {:?}", self);
1101 // To avoid a stack overflow when checking an enum variant or struct that
1102 // contains a different, structurally recursive type, maintain a stack
1103 // of seen types and check recursion for each of them (issues #3008, #3779).
1104 let mut seen: Vec<Ty> = Vec::new();
1105 let mut representable_cache = FxHashMap();
1106 let r = is_type_structurally_recursive(
1107 tcx, sp, &mut seen, &mut representable_cache, self);
1108 debug!("is_type_representable: {:?} is {:?}", self, r);
1113 fn is_copy_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1114 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1117 let (param_env, ty) = query.into_parts();
1118 let trait_def_id = tcx.require_lang_item(lang_items::CopyTraitLangItem);
1120 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
1127 fn is_sized_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1128 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1131 let (param_env, ty) = query.into_parts();
1132 let trait_def_id = tcx.require_lang_item(lang_items::SizedTraitLangItem);
1134 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
1141 fn is_freeze_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1142 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1145 let (param_env, ty) = query.into_parts();
1146 let trait_def_id = tcx.require_lang_item(lang_items::FreezeTraitLangItem);
1148 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
1155 fn needs_drop_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1156 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1159 let (param_env, ty) = query.into_parts();
1161 let needs_drop = |ty: Ty<'tcx>| -> bool {
1162 match ty::queries::needs_drop_raw::try_get(tcx, DUMMY_SP, param_env.and(ty)) {
1165 // Cycles should be reported as an error by `check_representable`.
1167 // Consider the type as not needing drop in the meanwhile to
1168 // avoid further errors.
1170 // In case we forgot to emit a bug elsewhere, delay our
1171 // diagnostic to get emitted as a compiler bug.
1178 assert!(!ty.needs_infer());
1181 // Fast-path for primitive types
1182 ty::TyInfer(ty::FreshIntTy(_)) | ty::TyInfer(ty::FreshFloatTy(_)) |
1183 ty::TyBool | ty::TyInt(_) | ty::TyUint(_) | ty::TyFloat(_) | ty::TyNever |
1184 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar | ty::TyGeneratorWitness(..) |
1185 ty::TyRawPtr(_) | ty::TyRef(..) | ty::TyStr => false,
1187 // Foreign types can never have destructors
1188 ty::TyForeign(..) => false,
1190 // Issue #22536: We first query type_moves_by_default. It sees a
1191 // normalized version of the type, and therefore will definitely
1192 // know whether the type implements Copy (and thus needs no
1193 // cleanup/drop/zeroing) ...
1194 _ if !ty.moves_by_default(tcx, param_env, DUMMY_SP) => false,
1196 // ... (issue #22536 continued) but as an optimization, still use
1197 // prior logic of asking for the structural "may drop".
1199 // FIXME(#22815): Note that this is a conservative heuristic;
1200 // it may report that the type "may drop" when actual type does
1201 // not actually have a destructor associated with it. But since
1202 // the type absolutely did not have the `Copy` bound attached
1203 // (see above), it is sound to treat it as having a destructor.
1205 // User destructors are the only way to have concrete drop types.
1206 ty::TyAdt(def, _) if def.has_dtor(tcx) => true,
1208 // Can refer to a type which may drop.
1209 // FIXME(eddyb) check this against a ParamEnv.
1210 ty::TyDynamic(..) | ty::TyProjection(..) | ty::TyParam(_) |
1211 ty::TyAnon(..) | ty::TyInfer(_) | ty::TyError => true,
1213 // Structural recursion.
1214 ty::TyArray(ty, _) | ty::TySlice(ty) => needs_drop(ty),
1216 ty::TyClosure(def_id, ref substs) => substs.upvar_tys(def_id, tcx).any(needs_drop),
1218 // Pessimistically assume that all generators will require destructors
1219 // as we don't know if a destructor is a noop or not until after the MIR
1220 // state transformation pass
1221 ty::TyGenerator(..) => true,
1223 ty::TyTuple(ref tys, _) => tys.iter().cloned().any(needs_drop),
1225 // unions don't have destructors regardless of the child types
1226 ty::TyAdt(def, _) if def.is_union() => false,
1228 ty::TyAdt(def, substs) =>
1229 def.variants.iter().any(
1230 |variant| variant.fields.iter().any(
1231 |field| needs_drop(field.ty(tcx, substs)))),
1235 pub enum ExplicitSelf<'tcx> {
1237 ByReference(ty::Region<'tcx>, hir::Mutability),
1238 ByRawPointer(hir::Mutability),
1243 impl<'tcx> ExplicitSelf<'tcx> {
1244 /// Categorizes an explicit self declaration like `self: SomeType`
1245 /// into either `self`, `&self`, `&mut self`, `Box<self>`, or
1247 /// This is mainly used to require the arbitrary_self_types feature
1248 /// in the case of `Other`, to improve error messages in the common cases,
1249 /// and to make `Other` non-object-safe.
1254 /// impl<'a> Foo for &'a T {
1255 /// // Legal declarations:
1256 /// fn method1(self: &&'a T); // ExplicitSelf::ByReference
1257 /// fn method2(self: &'a T); // ExplicitSelf::ByValue
1258 /// fn method3(self: Box<&'a T>); // ExplicitSelf::ByBox
1259 /// fn method4(self: Rc<&'a T>); // ExplicitSelf::Other
1261 /// // Invalid cases will be caught by `check_method_receiver`:
1262 /// fn method_err1(self: &'a mut T); // ExplicitSelf::Other
1263 /// fn method_err2(self: &'static T) // ExplicitSelf::ByValue
1264 /// fn method_err3(self: &&T) // ExplicitSelf::ByReference
1268 pub fn determine<P>(
1269 self_arg_ty: Ty<'tcx>,
1271 ) -> ExplicitSelf<'tcx>
1273 P: Fn(Ty<'tcx>) -> bool
1275 use self::ExplicitSelf::*;
1277 match self_arg_ty.sty {
1278 _ if is_self_ty(self_arg_ty) => ByValue,
1279 ty::TyRef(region, ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => {
1280 ByReference(region, mutbl)
1282 ty::TyRawPtr(ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => {
1285 ty::TyAdt(def, _) if def.is_box() && is_self_ty(self_arg_ty.boxed_ty()) => {
1293 pub fn provide(providers: &mut ty::maps::Providers) {
1294 *providers = ty::maps::Providers {