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},
16 use crate::ty::subst::SubstsRef;
17 use crate::ty::{self, List, Ty, TyCtxt};
18 use rustc_data_structures::fx::FxHashMap;
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<'tcx, E, T, M>(
82 ) -> Result<(), E::Error>
85 M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap<T, usize>,
86 T: EncodableWithShorthand<'tcx, E>,
87 // The discriminant and shorthand must have the same size.
88 T::Variant: DiscriminantKind<Discriminant = isize>,
90 let existing_shorthand = cache(encoder).get(value).copied();
91 if let Some(shorthand) = existing_shorthand {
92 return encoder.emit_usize(shorthand);
95 let variant = value.variant();
97 let start = encoder.position();
98 variant.encode(encoder)?;
99 let len = encoder.position() - start;
101 // The shorthand encoding uses the same usize as the
102 // discriminant, with an offset so they can't conflict.
103 let discriminant = intrinsics::discriminant_value(variant);
104 assert!(SHORTHAND_OFFSET > discriminant as usize);
106 let shorthand = start + SHORTHAND_OFFSET;
108 // Get the number of bits that leb128 could fit
109 // in the same space as the fully encoded type.
110 let leb128_bits = len * 7;
112 // Check that the shorthand is a not longer than the
113 // full encoding itself, i.e., it's an obvious win.
114 if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
115 cache(encoder).insert(*value, shorthand);
121 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Ty<'tcx> {
122 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
123 encode_with_shorthand(e, self, TyEncoder::type_shorthands)
127 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
128 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
129 self.bound_vars().encode(e)?;
130 encode_with_shorthand(e, &self.skip_binder(), TyEncoder::predicate_shorthands)
134 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Predicate<'tcx> {
135 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
136 self.kind().encode(e)
140 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for AllocId {
141 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
142 e.encode_alloc_id(self)
146 macro_rules! encodable_via_deref {
148 $(impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for $t {
149 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
156 encodable_via_deref! {
157 &'tcx ty::TypeckResults<'tcx>,
159 &'tcx mir::Body<'tcx>,
160 &'tcx mir::UnsafetyCheckResult,
161 &'tcx mir::BorrowCheckResult<'tcx>,
162 &'tcx mir::coverage::CodeRegion,
166 pub trait TyDecoder<'tcx>: Decoder {
167 const CLEAR_CROSS_CRATE: bool;
169 fn tcx(&self) -> TyCtxt<'tcx>;
171 fn peek_byte(&self) -> u8;
173 fn position(&self) -> usize;
175 fn cached_ty_for_shorthand<F>(
179 ) -> Result<Ty<'tcx>, Self::Error>
181 F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>;
183 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
185 F: FnOnce(&mut Self) -> R;
187 fn positioned_at_shorthand(&self) -> bool {
188 (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0
191 fn decode_alloc_id(&mut self) -> Result<AllocId, Self::Error>;
195 fn decode_arena_allocable<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
197 ) -> Result<&'tcx T, D::Error>
201 Ok(decoder.tcx().arena.alloc(Decodable::decode(decoder)?))
205 fn decode_arena_allocable_slice<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
207 ) -> Result<&'tcx [T], D::Error>
211 Ok(decoder.tcx().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder)?))
214 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Ty<'tcx> {
215 #[allow(rustc::usage_of_ty_tykind)]
216 fn decode(decoder: &mut D) -> Result<Ty<'tcx>, D::Error> {
217 // Handle shorthands first, if we have a usize > 0x80.
218 if decoder.positioned_at_shorthand() {
219 let pos = decoder.read_usize()?;
220 assert!(pos >= SHORTHAND_OFFSET);
221 let shorthand = pos - SHORTHAND_OFFSET;
223 decoder.cached_ty_for_shorthand(shorthand, |decoder| {
224 decoder.with_position(shorthand, Ty::decode)
227 let tcx = decoder.tcx();
228 Ok(tcx.mk_ty(ty::TyKind::decode(decoder)?))
233 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
234 fn decode(decoder: &mut D) -> Result<ty::Binder<'tcx, ty::PredicateKind<'tcx>>, D::Error> {
235 let bound_vars = Decodable::decode(decoder)?;
236 // Handle shorthands first, if we have a usize > 0x80.
237 Ok(ty::Binder::bind_with_vars(
238 if decoder.positioned_at_shorthand() {
239 let pos = decoder.read_usize()?;
240 assert!(pos >= SHORTHAND_OFFSET);
241 let shorthand = pos - SHORTHAND_OFFSET;
243 decoder.with_position(shorthand, ty::PredicateKind::decode)?
245 ty::PredicateKind::decode(decoder)?
252 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Predicate<'tcx> {
253 fn decode(decoder: &mut D) -> Result<ty::Predicate<'tcx>, D::Error> {
254 let predicate_kind = Decodable::decode(decoder)?;
255 let predicate = decoder.tcx().mk_predicate(predicate_kind);
260 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for SubstsRef<'tcx> {
261 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
262 let len = decoder.read_usize()?;
263 let tcx = decoder.tcx();
264 tcx.mk_substs((0..len).map(|_| Decodable::decode(decoder)))
268 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for mir::Place<'tcx> {
269 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
270 let local: mir::Local = Decodable::decode(decoder)?;
271 let len = decoder.read_usize()?;
272 let projection: &'tcx List<mir::PlaceElem<'tcx>> =
273 decoder.tcx().mk_place_elems((0..len).map(|_| Decodable::decode(decoder)))?;
274 Ok(mir::Place { local, projection })
278 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Region<'tcx> {
279 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
280 Ok(decoder.tcx().mk_region(Decodable::decode(decoder)?))
284 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for CanonicalVarInfos<'tcx> {
285 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
286 let len = decoder.read_usize()?;
287 let interned: Result<Vec<CanonicalVarInfo<'tcx>>, _> =
288 (0..len).map(|_| Decodable::decode(decoder)).collect();
289 Ok(decoder.tcx().intern_canonical_var_infos(interned?.as_slice()))
293 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AllocId {
294 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
295 decoder.decode_alloc_id()
299 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::SymbolName<'tcx> {
300 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
301 Ok(ty::SymbolName::new(decoder.tcx(), &decoder.read_str()?))
305 macro_rules! impl_decodable_via_ref {
307 $(impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for $t {
308 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
309 RefDecodable::decode(decoder)
315 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> {
316 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
317 let len = decoder.read_usize()?;
318 decoder.tcx().mk_type_list((0..len).map(|_| Decodable::decode(decoder)))
322 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D>
323 for ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>
325 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
326 let len = decoder.read_usize()?;
327 decoder.tcx().mk_poly_existential_predicates((0..len).map(|_| Decodable::decode(decoder)))
331 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::Const<'tcx> {
332 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
333 Ok(decoder.tcx().mk_const(Decodable::decode(decoder)?))
337 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] {
338 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
339 Ok(decoder.tcx().arena.alloc_from_iter(
340 (0..decoder.read_usize()?)
341 .map(|_| Decodable::decode(decoder))
342 .collect::<Result<Vec<_>, _>>()?,
347 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for Allocation {
348 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
349 Ok(decoder.tcx().intern_const_alloc(Decodable::decode(decoder)?))
353 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] {
354 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
355 Ok(decoder.tcx().arena.alloc_from_iter(
356 (0..decoder.read_usize()?)
357 .map(|_| Decodable::decode(decoder))
358 .collect::<Result<Vec<_>, _>>()?,
363 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [thir::abstract_const::Node<'tcx>] {
364 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
365 Ok(decoder.tcx().arena.alloc_from_iter(
366 (0..decoder.read_usize()?)
367 .map(|_| Decodable::decode(decoder))
368 .collect::<Result<Vec<_>, _>>()?,
373 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [thir::abstract_const::NodeId] {
374 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
375 Ok(decoder.tcx().arena.alloc_from_iter(
376 (0..decoder.read_usize()?)
377 .map(|_| Decodable::decode(decoder))
378 .collect::<Result<Vec<_>, _>>()?,
383 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<ty::BoundVariableKind> {
384 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
385 let len = decoder.read_usize()?;
386 decoder.tcx().mk_bound_variable_kinds((0..len).map(|_| Decodable::decode(decoder)))
390 impl_decodable_via_ref! {
391 &'tcx ty::TypeckResults<'tcx>,
392 &'tcx ty::List<Ty<'tcx>>,
393 &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
395 &'tcx mir::Body<'tcx>,
396 &'tcx mir::UnsafetyCheckResult,
397 &'tcx mir::BorrowCheckResult<'tcx>,
398 &'tcx mir::coverage::CodeRegion,
399 &'tcx ty::List<ty::BoundVariableKind>,
404 macro_rules! __impl_decoder_methods {
405 ($($name:ident -> $ty:ty;)*) => {
408 fn $name(&mut self) -> Result<$ty, Self::Error> {
415 macro_rules! impl_arena_allocatable_decoder {
417 ([decode $(, $attrs:ident)*]
418 [$name:ident: $ty:ty]) => {
419 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for $ty {
421 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
422 decode_arena_allocable(decoder)
426 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [$ty] {
428 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
429 decode_arena_allocable_slice(decoder)
433 ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
434 impl_arena_allocatable_decoder!([$($attrs),*]$args);
438 macro_rules! impl_arena_allocatable_decoders {
439 ([$($a:tt $name:ident: $ty:ty,)*]) => {
441 impl_arena_allocatable_decoder!($a [$name: $ty]);
446 rustc_hir::arena_types!(impl_arena_allocatable_decoders);
447 arena_types!(impl_arena_allocatable_decoders);
450 macro_rules! implement_ty_decoder {
451 ($DecoderName:ident <$($typaram:tt),*>) => {
452 mod __ty_decoder_impl {
453 use std::borrow::Cow;
454 use rustc_serialize::Decoder;
456 use super::$DecoderName;
458 impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
461 $crate::__impl_decoder_methods! {
482 read_str -> Cow<'_, str>;
486 fn read_raw_bytes_into(&mut self, bytes: &mut [u8]) -> Result<(), Self::Error> {
487 self.opaque.read_raw_bytes_into(bytes)
490 fn error(&mut self, err: &str) -> Self::Error {
491 self.opaque.error(err)
498 macro_rules! impl_binder_encode_decode {
499 ($($t:ty),+ $(,)?) => {
501 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Binder<'tcx, $t> {
502 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
503 self.bound_vars().encode(e)?;
504 self.as_ref().skip_binder().encode(e)
507 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, $t> {
508 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
509 let bound_vars = Decodable::decode(decoder)?;
510 Ok(ty::Binder::bind_with_vars(Decodable::decode(decoder)?, bound_vars))
517 impl_binder_encode_decode! {
518 &'tcx ty::List<Ty<'tcx>>,
520 ty::ExistentialPredicate<'tcx>,
522 Vec<ty::GeneratorInteriorTypeCause<'tcx>>,