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};
21 use std::convert::{TryFrom, TryInto};
24 use std::marker::DiscriminantKind;
26 /// The shorthand encoding uses an enum's variant index `usize`
27 /// and is offset by this value so it never matches a real variant.
28 /// This offset is also chosen so that the first byte is never < 0x80.
29 pub const SHORTHAND_OFFSET: usize = 0x80;
31 pub trait EncodableWithShorthand<'tcx, E: TyEncoder<'tcx>>: Copy + Eq + Hash {
32 type Variant: Encodable<E>;
33 fn variant(&self) -> &Self::Variant;
36 #[allow(rustc::usage_of_ty_tykind)]
37 impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for Ty<'tcx> {
38 type Variant = ty::TyKind<'tcx>;
41 fn variant(&self) -> &Self::Variant {
46 impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for ty::Predicate<'tcx> {
47 type Variant = ty::PredicateKind<'tcx>;
48 fn variant(&self) -> &Self::Variant {
53 pub trait OpaqueEncoder: Encoder {
54 fn opaque(&mut self) -> &mut rustc_serialize::opaque::Encoder;
55 fn encoder_position(&self) -> usize;
58 impl OpaqueEncoder for rustc_serialize::opaque::Encoder {
60 fn opaque(&mut self) -> &mut rustc_serialize::opaque::Encoder {
64 fn encoder_position(&self) -> usize {
69 pub trait TyEncoder<'tcx>: Encoder {
70 const CLEAR_CROSS_CRATE: bool;
72 fn position(&self) -> usize;
73 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize>;
74 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::Predicate<'tcx>, usize>;
75 fn encode_alloc_id(&mut self, alloc_id: &AllocId) -> Result<(), Self::Error>;
78 /// Trait for decoding to a reference.
80 /// This is a separate trait from `Decodable` so that we can implement it for
81 /// upstream types, such as `FxHashSet`.
83 /// The `TyDecodable` derive macro will use this trait for fields that are
84 /// references (and don't use a type alias to hide that).
86 /// `Decodable` can still be implemented in cases where `Decodable` is required
88 pub trait RefDecodable<'tcx, D: TyDecoder<'tcx>> {
89 fn decode(d: &mut D) -> Result<&'tcx Self, D::Error>;
92 /// Encode the given value or a previously cached shorthand.
93 pub fn encode_with_shorthand<E, T, M>(encoder: &mut E, value: &T, cache: M) -> Result<(), E::Error>
96 M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap<T, usize>,
97 T: EncodableWithShorthand<'tcx, E>,
98 <T::Variant as DiscriminantKind>::Discriminant: Ord + TryFrom<usize>,
100 let existing_shorthand = cache(encoder).get(value).copied();
101 if let Some(shorthand) = existing_shorthand {
102 return encoder.emit_usize(shorthand);
105 let variant = value.variant();
107 let start = encoder.position();
108 variant.encode(encoder)?;
109 let len = encoder.position() - start;
111 // The shorthand encoding uses the same usize as the
112 // discriminant, with an offset so they can't conflict.
113 let discriminant = intrinsics::discriminant_value(variant);
114 assert!(discriminant < SHORTHAND_OFFSET.try_into().ok().unwrap());
116 let shorthand = start + SHORTHAND_OFFSET;
118 // Get the number of bits that leb128 could fit
119 // in the same space as the fully encoded type.
120 let leb128_bits = len * 7;
122 // Check that the shorthand is a not longer than the
123 // full encoding itself, i.e., it's an obvious win.
124 if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
125 cache(encoder).insert(*value, shorthand);
131 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Ty<'tcx> {
132 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
133 encode_with_shorthand(e, self, TyEncoder::type_shorthands)
137 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Predicate<'tcx> {
138 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
139 encode_with_shorthand(e, self, TyEncoder::predicate_shorthands)
143 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for AllocId {
144 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
145 e.encode_alloc_id(self)
149 macro_rules! encodable_via_deref {
151 $(impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for $t {
152 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
159 encodable_via_deref! {
160 &'tcx ty::TypeckResults<'tcx>,
162 &'tcx mir::Body<'tcx>,
163 &'tcx mir::UnsafetyCheckResult,
164 &'tcx mir::BorrowCheckResult<'tcx>,
165 &'tcx mir::coverage::CodeRegion
168 pub trait TyDecoder<'tcx>: Decoder {
169 const CLEAR_CROSS_CRATE: bool;
171 fn tcx(&self) -> TyCtxt<'tcx>;
173 fn peek_byte(&self) -> u8;
175 fn position(&self) -> usize;
177 fn cached_ty_for_shorthand<F>(
181 ) -> Result<Ty<'tcx>, Self::Error>
183 F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>;
185 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
187 F: FnOnce(&mut Self) -> R;
189 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum;
191 fn positioned_at_shorthand(&self) -> bool {
192 (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0
195 fn decode_alloc_id(&mut self) -> Result<AllocId, Self::Error>;
199 pub fn decode_arena_allocable<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
201 ) -> Result<&'tcx T, D::Error>
205 Ok(decoder.tcx().arena.alloc(Decodable::decode(decoder)?))
209 pub fn decode_arena_allocable_slice<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
211 ) -> Result<&'tcx [T], D::Error>
215 Ok(decoder.tcx().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder)?))
218 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Ty<'tcx> {
219 #[allow(rustc::usage_of_ty_tykind)]
220 fn decode(decoder: &mut D) -> Result<Ty<'tcx>, D::Error> {
221 // Handle shorthands first, if we have an usize > 0x80.
222 if decoder.positioned_at_shorthand() {
223 let pos = decoder.read_usize()?;
224 assert!(pos >= SHORTHAND_OFFSET);
225 let shorthand = pos - SHORTHAND_OFFSET;
227 decoder.cached_ty_for_shorthand(shorthand, |decoder| {
228 decoder.with_position(shorthand, Ty::decode)
231 let tcx = decoder.tcx();
232 Ok(tcx.mk_ty(ty::TyKind::decode(decoder)?))
237 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Predicate<'tcx> {
238 fn decode(decoder: &mut D) -> Result<ty::Predicate<'tcx>, D::Error> {
239 // Handle shorthands first, if we have an usize > 0x80.
240 let predicate_kind = if decoder.positioned_at_shorthand() {
241 let pos = decoder.read_usize()?;
242 assert!(pos >= SHORTHAND_OFFSET);
243 let shorthand = pos - SHORTHAND_OFFSET;
245 decoder.with_position(shorthand, ty::PredicateKind::decode)
247 ty::PredicateKind::decode(decoder)
249 let predicate = decoder.tcx().mk_predicate(predicate_kind);
254 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for SubstsRef<'tcx> {
255 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
256 let len = decoder.read_usize()?;
257 let tcx = decoder.tcx();
258 Ok(tcx.mk_substs((0..len).map(|_| Decodable::decode(decoder)))?)
262 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for mir::Place<'tcx> {
263 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
264 let local: mir::Local = Decodable::decode(decoder)?;
265 let len = decoder.read_usize()?;
266 let projection: &'tcx List<mir::PlaceElem<'tcx>> =
267 decoder.tcx().mk_place_elems((0..len).map(|_| Decodable::decode(decoder)))?;
268 Ok(mir::Place { local, projection })
272 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Region<'tcx> {
273 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
274 Ok(decoder.tcx().mk_region(Decodable::decode(decoder)?))
278 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for CanonicalVarInfos<'tcx> {
279 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
280 let len = decoder.read_usize()?;
281 let interned: Result<Vec<CanonicalVarInfo<'tcx>>, _> =
282 (0..len).map(|_| Decodable::decode(decoder)).collect();
283 Ok(decoder.tcx().intern_canonical_var_infos(interned?.as_slice()))
287 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AllocId {
288 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
289 decoder.decode_alloc_id()
293 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::SymbolName<'tcx> {
294 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
295 Ok(ty::SymbolName::new(decoder.tcx(), &decoder.read_str()?))
299 macro_rules! impl_decodable_via_ref {
301 $(impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for $t {
302 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
303 RefDecodable::decode(decoder)
309 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::AdtDef {
310 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
311 let def_id = <DefId as Decodable<D>>::decode(decoder)?;
312 Ok(decoder.tcx().adt_def(def_id))
316 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> {
317 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
318 let len = decoder.read_usize()?;
319 Ok(decoder.tcx().mk_type_list((0..len).map(|_| Decodable::decode(decoder)))?)
323 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D>
324 for ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>
326 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
327 let len = decoder.read_usize()?;
330 .mk_poly_existential_predicates((0..len).map(|_| Decodable::decode(decoder)))?)
334 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::Const<'tcx> {
335 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
336 Ok(decoder.tcx().mk_const(Decodable::decode(decoder)?))
340 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for Allocation {
341 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
342 Ok(decoder.tcx().intern_const_alloc(Decodable::decode(decoder)?))
346 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] {
347 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
348 Ok(decoder.tcx().arena.alloc_from_iter(
349 (0..decoder.read_usize()?)
350 .map(|_| Decodable::decode(decoder))
351 .collect::<Result<Vec<_>, _>>()?,
356 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [mir::abstract_const::Node<'tcx>] {
357 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
358 Ok(decoder.tcx().arena.alloc_from_iter(
359 (0..decoder.read_usize()?)
360 .map(|_| Decodable::decode(decoder))
361 .collect::<Result<Vec<_>, _>>()?,
366 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [mir::abstract_const::NodeId] {
367 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
368 Ok(decoder.tcx().arena.alloc_from_iter(
369 (0..decoder.read_usize()?)
370 .map(|_| Decodable::decode(decoder))
371 .collect::<Result<Vec<_>, _>>()?,
376 impl_decodable_via_ref! {
377 &'tcx ty::TypeckResults<'tcx>,
378 &'tcx ty::List<Ty<'tcx>>,
379 &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
381 &'tcx mir::Body<'tcx>,
382 &'tcx mir::UnsafetyCheckResult,
383 &'tcx mir::BorrowCheckResult<'tcx>,
384 &'tcx mir::coverage::CodeRegion
388 macro_rules! __impl_decoder_methods {
389 ($($name:ident -> $ty:ty;)*) => {
392 fn $name(&mut self) -> Result<$ty, Self::Error> {
399 macro_rules! impl_arena_allocatable_decoder {
401 ([decode $(, $attrs:ident)*]
402 [[$name:ident: $ty:ty], $tcx:lifetime]) => {
403 impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for $ty {
405 fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
406 decode_arena_allocable(decoder)
410 impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for [$ty] {
412 fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
413 decode_arena_allocable_slice(decoder)
417 ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
418 impl_arena_allocatable_decoder!([$($attrs),*]$args);
422 macro_rules! impl_arena_allocatable_decoders {
423 ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
425 impl_arena_allocatable_decoder!($a [[$name: $ty], $tcx]);
430 rustc_hir::arena_types!(impl_arena_allocatable_decoders, [], 'tcx);
431 arena_types!(impl_arena_allocatable_decoders, [], 'tcx);
434 macro_rules! implement_ty_decoder {
435 ($DecoderName:ident <$($typaram:tt),*>) => {
436 mod __ty_decoder_impl {
437 use std::borrow::Cow;
438 use rustc_serialize::Decoder;
440 use super::$DecoderName;
442 impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
445 $crate::__impl_decoder_methods! {
466 read_str -> Cow<'_, str>;
469 fn error(&mut self, err: &str) -> Self::Error {
470 self.opaque.error(err)