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::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 positioned_at_shorthand(&self) -> bool {
183 (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0
186 fn decode_alloc_id(&mut self) -> Result<AllocId, Self::Error>;
190 fn decode_arena_allocable<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
192 ) -> Result<&'tcx T, D::Error>
196 Ok(decoder.tcx().arena.alloc(Decodable::decode(decoder)?))
200 fn decode_arena_allocable_slice<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
202 ) -> Result<&'tcx [T], D::Error>
206 Ok(decoder.tcx().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder)?))
209 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Ty<'tcx> {
210 #[allow(rustc::usage_of_ty_tykind)]
211 fn decode(decoder: &mut D) -> Result<Ty<'tcx>, D::Error> {
212 // Handle shorthands first, if we have an usize > 0x80.
213 if decoder.positioned_at_shorthand() {
214 let pos = decoder.read_usize()?;
215 assert!(pos >= SHORTHAND_OFFSET);
216 let shorthand = pos - SHORTHAND_OFFSET;
218 decoder.cached_ty_for_shorthand(shorthand, |decoder| {
219 decoder.with_position(shorthand, Ty::decode)
222 let tcx = decoder.tcx();
223 Ok(tcx.mk_ty(ty::TyKind::decode(decoder)?))
228 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
229 fn decode(decoder: &mut D) -> Result<ty::Binder<'tcx, ty::PredicateKind<'tcx>>, D::Error> {
230 let bound_vars = Decodable::decode(decoder)?;
231 // Handle shorthands first, if we have an usize > 0x80.
232 Ok(ty::Binder::bind_with_vars(
233 if decoder.positioned_at_shorthand() {
234 let pos = decoder.read_usize()?;
235 assert!(pos >= SHORTHAND_OFFSET);
236 let shorthand = pos - SHORTHAND_OFFSET;
238 decoder.with_position(shorthand, ty::PredicateKind::decode)?
240 ty::PredicateKind::decode(decoder)?
247 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Predicate<'tcx> {
248 fn decode(decoder: &mut D) -> Result<ty::Predicate<'tcx>, D::Error> {
249 let predicate_kind = Decodable::decode(decoder)?;
250 let predicate = decoder.tcx().mk_predicate(predicate_kind);
255 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for SubstsRef<'tcx> {
256 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
257 let len = decoder.read_usize()?;
258 let tcx = decoder.tcx();
259 tcx.mk_substs((0..len).map(|_| Decodable::decode(decoder)))
263 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for mir::Place<'tcx> {
264 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
265 let local: mir::Local = Decodable::decode(decoder)?;
266 let len = decoder.read_usize()?;
267 let projection: &'tcx List<mir::PlaceElem<'tcx>> =
268 decoder.tcx().mk_place_elems((0..len).map(|_| Decodable::decode(decoder)))?;
269 Ok(mir::Place { local, projection })
273 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Region<'tcx> {
274 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
275 Ok(decoder.tcx().mk_region(Decodable::decode(decoder)?))
279 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for CanonicalVarInfos<'tcx> {
280 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
281 let len = decoder.read_usize()?;
282 let interned: Result<Vec<CanonicalVarInfo<'tcx>>, _> =
283 (0..len).map(|_| Decodable::decode(decoder)).collect();
284 Ok(decoder.tcx().intern_canonical_var_infos(interned?.as_slice()))
288 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AllocId {
289 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
290 decoder.decode_alloc_id()
294 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::SymbolName<'tcx> {
295 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
296 Ok(ty::SymbolName::new(decoder.tcx(), &decoder.read_str()?))
300 macro_rules! impl_decodable_via_ref {
302 $(impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for $t {
303 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
304 RefDecodable::decode(decoder)
310 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::AdtDef {
311 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
312 let def_id = <DefId as Decodable<D>>::decode(decoder)?;
313 Ok(decoder.tcx().adt_def(def_id))
317 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> {
318 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
319 let len = decoder.read_usize()?;
320 decoder.tcx().mk_type_list((0..len).map(|_| Decodable::decode(decoder)))
324 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D>
325 for ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>
327 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
328 let len = decoder.read_usize()?;
329 decoder.tcx().mk_poly_existential_predicates((0..len).map(|_| Decodable::decode(decoder)))
333 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::Const<'tcx> {
334 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
335 Ok(decoder.tcx().mk_const(Decodable::decode(decoder)?))
339 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] {
340 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
341 Ok(decoder.tcx().arena.alloc_from_iter(
342 (0..decoder.read_usize()?)
343 .map(|_| Decodable::decode(decoder))
344 .collect::<Result<Vec<_>, _>>()?,
349 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for Allocation {
350 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
351 Ok(decoder.tcx().intern_const_alloc(Decodable::decode(decoder)?))
355 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] {
356 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
357 Ok(decoder.tcx().arena.alloc_from_iter(
358 (0..decoder.read_usize()?)
359 .map(|_| Decodable::decode(decoder))
360 .collect::<Result<Vec<_>, _>>()?,
365 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [mir::abstract_const::Node<'tcx>] {
366 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
367 Ok(decoder.tcx().arena.alloc_from_iter(
368 (0..decoder.read_usize()?)
369 .map(|_| Decodable::decode(decoder))
370 .collect::<Result<Vec<_>, _>>()?,
375 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [mir::abstract_const::NodeId] {
376 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
377 Ok(decoder.tcx().arena.alloc_from_iter(
378 (0..decoder.read_usize()?)
379 .map(|_| Decodable::decode(decoder))
380 .collect::<Result<Vec<_>, _>>()?,
385 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<ty::BoundVariableKind> {
386 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
387 let len = decoder.read_usize()?;
388 Ok(decoder.tcx().mk_bound_variable_kinds((0..len).map(|_| Decodable::decode(decoder)))?)
392 impl_decodable_via_ref! {
393 &'tcx ty::TypeckResults<'tcx>,
394 &'tcx ty::List<Ty<'tcx>>,
395 &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
397 &'tcx mir::Body<'tcx>,
398 &'tcx mir::UnsafetyCheckResult,
399 &'tcx mir::BorrowCheckResult<'tcx>,
400 &'tcx mir::coverage::CodeRegion,
401 &'tcx ty::List<ty::BoundVariableKind>
405 macro_rules! __impl_decoder_methods {
406 ($($name:ident -> $ty:ty;)*) => {
409 fn $name(&mut self) -> Result<$ty, Self::Error> {
416 macro_rules! impl_arena_allocatable_decoder {
418 ([decode $(, $attrs:ident)*]
419 [[$name:ident: $ty:ty], $tcx:lifetime]) => {
420 impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for $ty {
422 fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
423 decode_arena_allocable(decoder)
427 impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for [$ty] {
429 fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
430 decode_arena_allocable_slice(decoder)
434 ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
435 impl_arena_allocatable_decoder!([$($attrs),*]$args);
439 macro_rules! impl_arena_allocatable_decoders {
440 ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
442 impl_arena_allocatable_decoder!($a [[$name: $ty], $tcx]);
447 rustc_hir::arena_types!(impl_arena_allocatable_decoders, [], 'tcx);
448 arena_types!(impl_arena_allocatable_decoders, [], 'tcx);
451 macro_rules! implement_ty_decoder {
452 ($DecoderName:ident <$($typaram:tt),*>) => {
453 mod __ty_decoder_impl {
454 use std::borrow::Cow;
455 use rustc_serialize::Decoder;
457 use super::$DecoderName;
459 impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
462 $crate::__impl_decoder_methods! {
483 read_str -> Cow<'_, str>;
487 fn read_raw_bytes_into(&mut self, bytes: &mut [u8]) -> Result<(), Self::Error> {
488 self.opaque.read_raw_bytes_into(bytes)
491 fn error(&mut self, err: &str) -> Self::Error {
492 self.opaque.error(err)
499 macro_rules! impl_binder_encode_decode {
500 ($($t:ty),+ $(,)?) => {
502 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Binder<'tcx, $t> {
503 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
504 self.bound_vars().encode(e)?;
505 self.as_ref().skip_binder().encode(e)
508 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, $t> {
509 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
510 let bound_vars = Decodable::decode(decoder)?;
511 Ok(ty::Binder::bind_with_vars(Decodable::decode(decoder)?, bound_vars))
518 impl_binder_encode_decode! {
519 &'tcx ty::List<Ty<'tcx>>,
521 ty::ExistentialPredicate<'tcx>,
523 Vec<ty::GeneratorInteriorTypeCause<'tcx>>,