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::Binder<ty::PredicateAtom<'tcx>>;
48 fn variant(&self) -> &Self::Variant {
53 pub trait TyEncoder<'tcx>: Encoder {
54 const CLEAR_CROSS_CRATE: bool;
56 fn position(&self) -> usize;
57 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize>;
58 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::Predicate<'tcx>, usize>;
59 fn encode_alloc_id(&mut self, alloc_id: &AllocId) -> Result<(), Self::Error>;
62 /// Trait for decoding to a reference.
64 /// This is a separate trait from `Decodable` so that we can implement it for
65 /// upstream types, such as `FxHashSet`.
67 /// The `TyDecodable` derive macro will use this trait for fields that are
68 /// references (and don't use a type alias to hide that).
70 /// `Decodable` can still be implemented in cases where `Decodable` is required
72 pub trait RefDecodable<'tcx, D: TyDecoder<'tcx>> {
73 fn decode(d: &mut D) -> Result<&'tcx Self, D::Error>;
76 /// Encode the given value or a previously cached shorthand.
77 pub fn encode_with_shorthand<E, T, M>(encoder: &mut E, value: &T, cache: M) -> Result<(), E::Error>
80 M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap<T, usize>,
81 T: EncodableWithShorthand<'tcx, E>,
82 <T::Variant as DiscriminantKind>::Discriminant: Ord + TryFrom<usize>,
84 let existing_shorthand = cache(encoder).get(value).copied();
85 if let Some(shorthand) = existing_shorthand {
86 return encoder.emit_usize(shorthand);
89 let variant = value.variant();
91 let start = encoder.position();
92 variant.encode(encoder)?;
93 let len = encoder.position() - start;
95 // The shorthand encoding uses the same usize as the
96 // discriminant, with an offset so they can't conflict.
97 let discriminant = intrinsics::discriminant_value(variant);
98 assert!(discriminant < SHORTHAND_OFFSET.try_into().ok().unwrap());
100 let shorthand = start + SHORTHAND_OFFSET;
102 // Get the number of bits that leb128 could fit
103 // in the same space as the fully encoded type.
104 let leb128_bits = len * 7;
106 // Check that the shorthand is a not longer than the
107 // full encoding itself, i.e., it's an obvious win.
108 if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
109 cache(encoder).insert(*value, shorthand);
115 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Ty<'tcx> {
116 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
117 encode_with_shorthand(e, self, TyEncoder::type_shorthands)
121 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Predicate<'tcx> {
122 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
123 encode_with_shorthand(e, self, TyEncoder::predicate_shorthands)
127 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for AllocId {
128 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
129 e.encode_alloc_id(self)
133 macro_rules! encodable_via_deref {
135 $(impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for $t {
136 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
143 encodable_via_deref! {
144 &'tcx ty::TypeckResults<'tcx>,
146 &'tcx mir::Body<'tcx>,
147 &'tcx mir::UnsafetyCheckResult,
148 &'tcx mir::BorrowCheckResult<'tcx>,
149 &'tcx mir::coverage::CodeRegion
152 pub trait TyDecoder<'tcx>: Decoder {
153 const CLEAR_CROSS_CRATE: bool;
155 fn tcx(&self) -> TyCtxt<'tcx>;
157 fn peek_byte(&self) -> u8;
159 fn position(&self) -> usize;
161 fn cached_ty_for_shorthand<F>(
165 ) -> Result<Ty<'tcx>, Self::Error>
167 F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>;
169 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
171 F: FnOnce(&mut Self) -> R;
173 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum;
175 fn positioned_at_shorthand(&self) -> bool {
176 (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0
179 fn decode_alloc_id(&mut self) -> Result<AllocId, Self::Error>;
183 pub fn decode_arena_allocable<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
185 ) -> Result<&'tcx T, D::Error>
189 Ok(decoder.tcx().arena.alloc(Decodable::decode(decoder)?))
193 pub fn decode_arena_allocable_slice<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
195 ) -> Result<&'tcx [T], D::Error>
199 Ok(decoder.tcx().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder)?))
202 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Ty<'tcx> {
203 #[allow(rustc::usage_of_ty_tykind)]
204 fn decode(decoder: &mut D) -> Result<Ty<'tcx>, D::Error> {
205 // Handle shorthands first, if we have an usize > 0x80.
206 if decoder.positioned_at_shorthand() {
207 let pos = decoder.read_usize()?;
208 assert!(pos >= SHORTHAND_OFFSET);
209 let shorthand = pos - SHORTHAND_OFFSET;
211 decoder.cached_ty_for_shorthand(shorthand, |decoder| {
212 decoder.with_position(shorthand, Ty::decode)
215 let tcx = decoder.tcx();
216 Ok(tcx.mk_ty(ty::TyKind::decode(decoder)?))
221 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Predicate<'tcx> {
222 fn decode(decoder: &mut D) -> Result<ty::Predicate<'tcx>, D::Error> {
223 // Handle shorthands first, if we have an usize > 0x80.
224 let predicate_kind = if decoder.positioned_at_shorthand() {
225 let pos = decoder.read_usize()?;
226 assert!(pos >= SHORTHAND_OFFSET);
227 let shorthand = pos - SHORTHAND_OFFSET;
229 decoder.with_position(shorthand, ty::Binder::<ty::PredicateAtom<'tcx>>::decode)
231 ty::Binder::<ty::PredicateAtom<'tcx>>::decode(decoder)
233 let predicate = decoder.tcx().mk_predicate(predicate_kind);
238 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for SubstsRef<'tcx> {
239 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
240 let len = decoder.read_usize()?;
241 let tcx = decoder.tcx();
242 Ok(tcx.mk_substs((0..len).map(|_| Decodable::decode(decoder)))?)
246 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for mir::Place<'tcx> {
247 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
248 let local: mir::Local = Decodable::decode(decoder)?;
249 let len = decoder.read_usize()?;
250 let projection: &'tcx List<mir::PlaceElem<'tcx>> =
251 decoder.tcx().mk_place_elems((0..len).map(|_| Decodable::decode(decoder)))?;
252 Ok(mir::Place { local, projection })
256 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Region<'tcx> {
257 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
258 Ok(decoder.tcx().mk_region(Decodable::decode(decoder)?))
262 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for CanonicalVarInfos<'tcx> {
263 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
264 let len = decoder.read_usize()?;
265 let interned: Result<Vec<CanonicalVarInfo<'tcx>>, _> =
266 (0..len).map(|_| Decodable::decode(decoder)).collect();
267 Ok(decoder.tcx().intern_canonical_var_infos(interned?.as_slice()))
271 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AllocId {
272 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
273 decoder.decode_alloc_id()
277 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::SymbolName<'tcx> {
278 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
279 Ok(ty::SymbolName::new(decoder.tcx(), &decoder.read_str()?))
283 macro_rules! impl_decodable_via_ref {
285 $(impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for $t {
286 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
287 RefDecodable::decode(decoder)
293 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::AdtDef {
294 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
295 let def_id = <DefId as Decodable<D>>::decode(decoder)?;
296 Ok(decoder.tcx().adt_def(def_id))
300 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> {
301 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
302 let len = decoder.read_usize()?;
303 Ok(decoder.tcx().mk_type_list((0..len).map(|_| Decodable::decode(decoder)))?)
307 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D>
308 for ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>
310 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
311 let len = decoder.read_usize()?;
314 .mk_poly_existential_predicates((0..len).map(|_| Decodable::decode(decoder)))?)
318 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::Const<'tcx> {
319 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
320 Ok(decoder.tcx().mk_const(Decodable::decode(decoder)?))
324 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for Allocation {
325 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
326 Ok(decoder.tcx().intern_const_alloc(Decodable::decode(decoder)?))
330 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] {
331 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
332 Ok(decoder.tcx().arena.alloc_from_iter(
333 (0..decoder.read_usize()?)
334 .map(|_| Decodable::decode(decoder))
335 .collect::<Result<Vec<_>, _>>()?,
340 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [mir::abstract_const::Node<'tcx>] {
341 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
342 Ok(decoder.tcx().arena.alloc_from_iter(
343 (0..decoder.read_usize()?)
344 .map(|_| Decodable::decode(decoder))
345 .collect::<Result<Vec<_>, _>>()?,
350 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [mir::abstract_const::NodeId] {
351 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
352 Ok(decoder.tcx().arena.alloc_from_iter(
353 (0..decoder.read_usize()?)
354 .map(|_| Decodable::decode(decoder))
355 .collect::<Result<Vec<_>, _>>()?,
360 impl_decodable_via_ref! {
361 &'tcx ty::TypeckResults<'tcx>,
362 &'tcx ty::List<Ty<'tcx>>,
363 &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
365 &'tcx mir::Body<'tcx>,
366 &'tcx mir::UnsafetyCheckResult,
367 &'tcx mir::BorrowCheckResult<'tcx>,
368 &'tcx mir::coverage::CodeRegion
372 macro_rules! __impl_decoder_methods {
373 ($($name:ident -> $ty:ty;)*) => {
376 fn $name(&mut self) -> Result<$ty, Self::Error> {
383 macro_rules! impl_arena_allocatable_decoder {
385 ([decode $(, $attrs:ident)*]
386 [[$name:ident: $ty:ty], $tcx:lifetime]) => {
387 impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for $ty {
389 fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
390 decode_arena_allocable(decoder)
394 impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for [$ty] {
396 fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
397 decode_arena_allocable_slice(decoder)
401 ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
402 impl_arena_allocatable_decoder!([$($attrs),*]$args);
406 macro_rules! impl_arena_allocatable_decoders {
407 ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
409 impl_arena_allocatable_decoder!($a [[$name: $ty], $tcx]);
414 rustc_hir::arena_types!(impl_arena_allocatable_decoders, [], 'tcx);
415 arena_types!(impl_arena_allocatable_decoders, [], 'tcx);
418 macro_rules! implement_ty_decoder {
419 ($DecoderName:ident <$($typaram:tt),*>) => {
420 mod __ty_decoder_impl {
421 use std::borrow::Cow;
422 use rustc_serialize::Decoder;
424 use super::$DecoderName;
426 impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
429 $crate::__impl_decoder_methods! {
450 read_str -> Cow<'_, str>;
453 fn error(&mut self, err: &str) -> Self::Error {
454 self.opaque.error(err)