1 // This module contains some shared code for encoding and decoding various
2 // things from the `ty` module, and in particular implements support for
3 // "shorthands" which allow to have pointers back into the already encoded
4 // stream instead of re-encoding the same thing twice.
6 // The functionality in here is shared between persisting to crate metadata and
7 // persisting to incr. comp. caches.
9 use crate::arena::ArenaAllocatable;
10 use crate::infer::canonical::{CanonicalVarInfo, CanonicalVarInfos};
13 interpret::{AllocId, Allocation},
15 use crate::ty::subst::SubstsRef;
16 use crate::ty::{self, List, Ty, TyCtxt};
17 use rustc_data_structures::fx::FxHashMap;
18 use rustc_hir::def_id::{CrateNum, DefId};
19 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
23 use std::marker::DiscriminantKind;
25 /// The shorthand encoding uses an enum's variant index `usize`
26 /// and is offset by this value so it never matches a real variant.
27 /// This offset is also chosen so that the first byte is never < 0x80.
28 pub const SHORTHAND_OFFSET: usize = 0x80;
30 pub trait EncodableWithShorthand<'tcx, E: TyEncoder<'tcx>>: Copy + Eq + Hash {
31 type Variant: Encodable<E>;
32 fn variant(&self) -> &Self::Variant;
35 #[allow(rustc::usage_of_ty_tykind)]
36 impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for Ty<'tcx> {
37 type Variant = ty::TyKind<'tcx>;
40 fn variant(&self) -> &Self::Variant {
45 impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for ty::PredicateKind<'tcx> {
46 type Variant = ty::PredicateKind<'tcx>;
49 fn variant(&self) -> &Self::Variant {
54 pub trait TyEncoder<'tcx>: Encoder {
55 const CLEAR_CROSS_CRATE: bool;
57 fn position(&self) -> usize;
58 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize>;
59 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize>;
60 fn encode_alloc_id(&mut self, alloc_id: &AllocId) -> Result<(), Self::Error>;
63 /// Trait for decoding to a reference.
65 /// This is a separate trait from `Decodable` so that we can implement it for
66 /// upstream types, such as `FxHashSet`.
68 /// The `TyDecodable` derive macro will use this trait for fields that are
69 /// references (and don't use a type alias to hide that).
71 /// `Decodable` can still be implemented in cases where `Decodable` is required
73 pub trait RefDecodable<'tcx, D: TyDecoder<'tcx>> {
74 fn decode(d: &mut D) -> Result<&'tcx Self, D::Error>;
77 /// Encode the given value or a previously cached shorthand.
78 pub fn encode_with_shorthand<E, T, M>(encoder: &mut E, value: &T, cache: M) -> Result<(), E::Error>
81 M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap<T, usize>,
82 T: EncodableWithShorthand<'tcx, E>,
83 // The discriminant and shorthand must have the same size.
84 T::Variant: DiscriminantKind<Discriminant = isize>,
86 let existing_shorthand = cache(encoder).get(value).copied();
87 if let Some(shorthand) = existing_shorthand {
88 return encoder.emit_usize(shorthand);
91 let variant = value.variant();
93 let start = encoder.position();
94 variant.encode(encoder)?;
95 let len = encoder.position() - start;
97 // The shorthand encoding uses the same usize as the
98 // discriminant, with an offset so they can't conflict.
99 let discriminant = intrinsics::discriminant_value(variant);
100 assert!(SHORTHAND_OFFSET > discriminant as usize);
102 let shorthand = start + SHORTHAND_OFFSET;
104 // Get the number of bits that leb128 could fit
105 // in the same space as the fully encoded type.
106 let leb128_bits = len * 7;
108 // Check that the shorthand is a not longer than the
109 // full encoding itself, i.e., it's an obvious win.
110 if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
111 cache(encoder).insert(*value, shorthand);
117 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Ty<'tcx> {
118 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
119 encode_with_shorthand(e, self, TyEncoder::type_shorthands)
123 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
124 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
125 self.bound_vars().encode(e)?;
126 encode_with_shorthand(e, &self.skip_binder(), TyEncoder::predicate_shorthands)
130 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Predicate<'tcx> {
131 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
132 self.kind().encode(e)
136 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for AllocId {
137 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
138 e.encode_alloc_id(self)
142 macro_rules! encodable_via_deref {
144 $(impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for $t {
145 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
152 encodable_via_deref! {
153 &'tcx ty::TypeckResults<'tcx>,
155 &'tcx mir::Body<'tcx>,
156 &'tcx mir::UnsafetyCheckResult,
157 &'tcx mir::BorrowCheckResult<'tcx>,
158 &'tcx mir::coverage::CodeRegion
161 pub trait TyDecoder<'tcx>: Decoder {
162 const CLEAR_CROSS_CRATE: bool;
164 fn tcx(&self) -> TyCtxt<'tcx>;
166 fn peek_byte(&self) -> u8;
168 fn position(&self) -> usize;
170 fn cached_ty_for_shorthand<F>(
174 ) -> Result<Ty<'tcx>, Self::Error>
176 F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>;
178 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
180 F: FnOnce(&mut Self) -> R;
182 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum;
184 fn positioned_at_shorthand(&self) -> bool {
185 (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0
188 fn decode_alloc_id(&mut self) -> Result<AllocId, Self::Error>;
192 fn decode_arena_allocable<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
194 ) -> Result<&'tcx T, D::Error>
198 Ok(decoder.tcx().arena.alloc(Decodable::decode(decoder)?))
202 fn decode_arena_allocable_slice<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
204 ) -> Result<&'tcx [T], D::Error>
208 Ok(decoder.tcx().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder)?))
211 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Ty<'tcx> {
212 #[allow(rustc::usage_of_ty_tykind)]
213 fn decode(decoder: &mut D) -> Result<Ty<'tcx>, D::Error> {
214 // Handle shorthands first, if we have an usize > 0x80.
215 if decoder.positioned_at_shorthand() {
216 let pos = decoder.read_usize()?;
217 assert!(pos >= SHORTHAND_OFFSET);
218 let shorthand = pos - SHORTHAND_OFFSET;
220 decoder.cached_ty_for_shorthand(shorthand, |decoder| {
221 decoder.with_position(shorthand, Ty::decode)
224 let tcx = decoder.tcx();
225 Ok(tcx.mk_ty(ty::TyKind::decode(decoder)?))
230 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
231 fn decode(decoder: &mut D) -> Result<ty::Binder<'tcx, ty::PredicateKind<'tcx>>, D::Error> {
232 let bound_vars = Decodable::decode(decoder)?;
233 // Handle shorthands first, if we have an usize > 0x80.
234 Ok(ty::Binder::bind_with_vars(
235 if decoder.positioned_at_shorthand() {
236 let pos = decoder.read_usize()?;
237 assert!(pos >= SHORTHAND_OFFSET);
238 let shorthand = pos - SHORTHAND_OFFSET;
240 decoder.with_position(shorthand, ty::PredicateKind::decode)?
242 ty::PredicateKind::decode(decoder)?
249 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Predicate<'tcx> {
250 fn decode(decoder: &mut D) -> Result<ty::Predicate<'tcx>, D::Error> {
251 let predicate_kind = Decodable::decode(decoder)?;
252 let predicate = decoder.tcx().mk_predicate(predicate_kind);
257 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for SubstsRef<'tcx> {
258 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
259 let len = decoder.read_usize()?;
260 let tcx = decoder.tcx();
261 tcx.mk_substs((0..len).map(|_| Decodable::decode(decoder)))
265 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for mir::Place<'tcx> {
266 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
267 let local: mir::Local = Decodable::decode(decoder)?;
268 let len = decoder.read_usize()?;
269 let projection: &'tcx List<mir::PlaceElem<'tcx>> =
270 decoder.tcx().mk_place_elems((0..len).map(|_| Decodable::decode(decoder)))?;
271 Ok(mir::Place { local, projection })
275 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Region<'tcx> {
276 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
277 Ok(decoder.tcx().mk_region(Decodable::decode(decoder)?))
281 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for CanonicalVarInfos<'tcx> {
282 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
283 let len = decoder.read_usize()?;
284 let interned: Result<Vec<CanonicalVarInfo<'tcx>>, _> =
285 (0..len).map(|_| Decodable::decode(decoder)).collect();
286 Ok(decoder.tcx().intern_canonical_var_infos(interned?.as_slice()))
290 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AllocId {
291 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
292 decoder.decode_alloc_id()
296 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::SymbolName<'tcx> {
297 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
298 Ok(ty::SymbolName::new(decoder.tcx(), &decoder.read_str()?))
302 macro_rules! impl_decodable_via_ref {
304 $(impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for $t {
305 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
306 RefDecodable::decode(decoder)
312 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::AdtDef {
313 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
314 let def_id = <DefId as Decodable<D>>::decode(decoder)?;
315 Ok(decoder.tcx().adt_def(def_id))
319 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> {
320 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
321 let len = decoder.read_usize()?;
322 decoder.tcx().mk_type_list((0..len).map(|_| Decodable::decode(decoder)))
326 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D>
327 for ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>
329 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
330 let len = decoder.read_usize()?;
331 decoder.tcx().mk_poly_existential_predicates((0..len).map(|_| Decodable::decode(decoder)))
335 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::Const<'tcx> {
336 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
337 Ok(decoder.tcx().mk_const(Decodable::decode(decoder)?))
341 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] {
342 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
343 Ok(decoder.tcx().arena.alloc_from_iter(
344 (0..decoder.read_usize()?)
345 .map(|_| Decodable::decode(decoder))
346 .collect::<Result<Vec<_>, _>>()?,
351 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for Allocation {
352 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
353 Ok(decoder.tcx().intern_const_alloc(Decodable::decode(decoder)?))
357 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] {
358 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
359 Ok(decoder.tcx().arena.alloc_from_iter(
360 (0..decoder.read_usize()?)
361 .map(|_| Decodable::decode(decoder))
362 .collect::<Result<Vec<_>, _>>()?,
367 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [mir::abstract_const::Node<'tcx>] {
368 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
369 Ok(decoder.tcx().arena.alloc_from_iter(
370 (0..decoder.read_usize()?)
371 .map(|_| Decodable::decode(decoder))
372 .collect::<Result<Vec<_>, _>>()?,
377 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [mir::abstract_const::NodeId] {
378 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
379 Ok(decoder.tcx().arena.alloc_from_iter(
380 (0..decoder.read_usize()?)
381 .map(|_| Decodable::decode(decoder))
382 .collect::<Result<Vec<_>, _>>()?,
387 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<ty::BoundVariableKind> {
388 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
389 let len = decoder.read_usize()?;
390 Ok(decoder.tcx().mk_bound_variable_kinds((0..len).map(|_| Decodable::decode(decoder)))?)
394 impl_decodable_via_ref! {
395 &'tcx ty::TypeckResults<'tcx>,
396 &'tcx ty::List<Ty<'tcx>>,
397 &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
399 &'tcx mir::Body<'tcx>,
400 &'tcx mir::UnsafetyCheckResult,
401 &'tcx mir::BorrowCheckResult<'tcx>,
402 &'tcx mir::coverage::CodeRegion,
403 &'tcx ty::List<ty::BoundVariableKind>
407 macro_rules! __impl_decoder_methods {
408 ($($name:ident -> $ty:ty;)*) => {
411 fn $name(&mut self) -> Result<$ty, Self::Error> {
418 macro_rules! impl_arena_allocatable_decoder {
420 ([decode $(, $attrs:ident)*]
421 [[$name:ident: $ty:ty], $tcx:lifetime]) => {
422 impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for $ty {
424 fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
425 decode_arena_allocable(decoder)
429 impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for [$ty] {
431 fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
432 decode_arena_allocable_slice(decoder)
436 ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
437 impl_arena_allocatable_decoder!([$($attrs),*]$args);
441 macro_rules! impl_arena_allocatable_decoders {
442 ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
444 impl_arena_allocatable_decoder!($a [[$name: $ty], $tcx]);
449 rustc_hir::arena_types!(impl_arena_allocatable_decoders, [], 'tcx);
450 arena_types!(impl_arena_allocatable_decoders, [], 'tcx);
453 macro_rules! implement_ty_decoder {
454 ($DecoderName:ident <$($typaram:tt),*>) => {
455 mod __ty_decoder_impl {
456 use std::borrow::Cow;
457 use rustc_serialize::Decoder;
459 use super::$DecoderName;
461 impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
464 $crate::__impl_decoder_methods! {
485 read_str -> Cow<'_, str>;
489 fn read_raw_bytes_into(&mut self, bytes: &mut [u8]) -> Result<(), Self::Error> {
490 self.opaque.read_raw_bytes_into(bytes)
493 fn error(&mut self, err: &str) -> Self::Error {
494 self.opaque.error(err)
501 macro_rules! impl_binder_encode_decode {
502 ($($t:ty),+ $(,)?) => {
504 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Binder<'tcx, $t> {
505 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
506 self.bound_vars().encode(e)?;
507 self.as_ref().skip_binder().encode(e)
510 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, $t> {
511 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
512 let bound_vars = Decodable::decode(decoder)?;
513 Ok(ty::Binder::bind_with_vars(Decodable::decode(decoder)?, bound_vars))
520 impl_binder_encode_decode! {
521 &'tcx ty::List<Ty<'tcx>>,
523 ty::ExistentialPredicate<'tcx>,
525 Vec<ty::GeneratorInteriorTypeCause<'tcx>>,