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_hir::def_id::DefId;
20 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
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::PredicateKind<'tcx> {
47 type Variant = ty::PredicateKind<'tcx>;
50 fn variant(&self) -> &Self::Variant {
55 pub trait TyEncoder<'tcx>: Encoder {
56 const CLEAR_CROSS_CRATE: bool;
58 fn position(&self) -> usize;
59 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize>;
60 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize>;
61 fn encode_alloc_id(&mut self, alloc_id: &AllocId) -> Result<(), Self::Error>;
64 /// Trait for decoding to a reference.
66 /// This is a separate trait from `Decodable` so that we can implement it for
67 /// upstream types, such as `FxHashSet`.
69 /// The `TyDecodable` derive macro will use this trait for fields that are
70 /// references (and don't use a type alias to hide that).
72 /// `Decodable` can still be implemented in cases where `Decodable` is required
74 pub trait RefDecodable<'tcx, D: TyDecoder<'tcx>> {
75 fn decode(d: &mut D) -> Result<&'tcx Self, D::Error>;
78 /// Encode the given value or a previously cached shorthand.
79 pub fn encode_with_shorthand<E, T, M>(encoder: &mut E, value: &T, cache: M) -> Result<(), E::Error>
82 M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap<T, usize>,
83 T: EncodableWithShorthand<'tcx, E>,
84 // The discriminant and shorthand must have the same size.
85 T::Variant: DiscriminantKind<Discriminant = isize>,
87 let existing_shorthand = cache(encoder).get(value).copied();
88 if let Some(shorthand) = existing_shorthand {
89 return encoder.emit_usize(shorthand);
92 let variant = value.variant();
94 let start = encoder.position();
95 variant.encode(encoder)?;
96 let len = encoder.position() - start;
98 // The shorthand encoding uses the same usize as the
99 // discriminant, with an offset so they can't conflict.
100 let discriminant = intrinsics::discriminant_value(variant);
101 assert!(SHORTHAND_OFFSET > discriminant as usize);
103 let shorthand = start + SHORTHAND_OFFSET;
105 // Get the number of bits that leb128 could fit
106 // in the same space as the fully encoded type.
107 let leb128_bits = len * 7;
109 // Check that the shorthand is a not longer than the
110 // full encoding itself, i.e., it's an obvious win.
111 if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
112 cache(encoder).insert(*value, shorthand);
118 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Ty<'tcx> {
119 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
120 encode_with_shorthand(e, self, TyEncoder::type_shorthands)
124 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
125 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
126 self.bound_vars().encode(e)?;
127 encode_with_shorthand(e, &self.skip_binder(), TyEncoder::predicate_shorthands)
131 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Predicate<'tcx> {
132 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
133 self.kind().encode(e)
137 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for AllocId {
138 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
139 e.encode_alloc_id(self)
143 macro_rules! encodable_via_deref {
145 $(impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for $t {
146 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
153 encodable_via_deref! {
154 &'tcx ty::TypeckResults<'tcx>,
156 &'tcx mir::Body<'tcx>,
157 &'tcx mir::UnsafetyCheckResult,
158 &'tcx mir::BorrowCheckResult<'tcx>,
159 &'tcx mir::coverage::CodeRegion
162 pub trait TyDecoder<'tcx>: Decoder {
163 const CLEAR_CROSS_CRATE: bool;
165 fn tcx(&self) -> TyCtxt<'tcx>;
167 fn peek_byte(&self) -> u8;
169 fn position(&self) -> usize;
171 fn cached_ty_for_shorthand<F>(
175 ) -> Result<Ty<'tcx>, Self::Error>
177 F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>;
179 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
181 F: FnOnce(&mut Self) -> R;
183 fn positioned_at_shorthand(&self) -> bool {
184 (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0
187 fn decode_alloc_id(&mut self) -> Result<AllocId, Self::Error>;
191 fn decode_arena_allocable<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
193 ) -> Result<&'tcx T, D::Error>
197 Ok(decoder.tcx().arena.alloc(Decodable::decode(decoder)?))
201 fn decode_arena_allocable_slice<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
203 ) -> Result<&'tcx [T], D::Error>
207 Ok(decoder.tcx().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder)?))
210 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Ty<'tcx> {
211 #[allow(rustc::usage_of_ty_tykind)]
212 fn decode(decoder: &mut D) -> Result<Ty<'tcx>, D::Error> {
213 // Handle shorthands first, if we have a usize > 0x80.
214 if decoder.positioned_at_shorthand() {
215 let pos = decoder.read_usize()?;
216 assert!(pos >= SHORTHAND_OFFSET);
217 let shorthand = pos - SHORTHAND_OFFSET;
219 decoder.cached_ty_for_shorthand(shorthand, |decoder| {
220 decoder.with_position(shorthand, Ty::decode)
223 let tcx = decoder.tcx();
224 Ok(tcx.mk_ty(ty::TyKind::decode(decoder)?))
229 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
230 fn decode(decoder: &mut D) -> Result<ty::Binder<'tcx, ty::PredicateKind<'tcx>>, D::Error> {
231 let bound_vars = Decodable::decode(decoder)?;
232 // Handle shorthands first, if we have a usize > 0x80.
233 Ok(ty::Binder::bind_with_vars(
234 if decoder.positioned_at_shorthand() {
235 let pos = decoder.read_usize()?;
236 assert!(pos >= SHORTHAND_OFFSET);
237 let shorthand = pos - SHORTHAND_OFFSET;
239 decoder.with_position(shorthand, ty::PredicateKind::decode)?
241 ty::PredicateKind::decode(decoder)?
248 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Predicate<'tcx> {
249 fn decode(decoder: &mut D) -> Result<ty::Predicate<'tcx>, D::Error> {
250 let predicate_kind = Decodable::decode(decoder)?;
251 let predicate = decoder.tcx().mk_predicate(predicate_kind);
256 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for SubstsRef<'tcx> {
257 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
258 let len = decoder.read_usize()?;
259 let tcx = decoder.tcx();
260 tcx.mk_substs((0..len).map(|_| Decodable::decode(decoder)))
264 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for mir::Place<'tcx> {
265 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
266 let local: mir::Local = Decodable::decode(decoder)?;
267 let len = decoder.read_usize()?;
268 let projection: &'tcx List<mir::PlaceElem<'tcx>> =
269 decoder.tcx().mk_place_elems((0..len).map(|_| Decodable::decode(decoder)))?;
270 Ok(mir::Place { local, projection })
274 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Region<'tcx> {
275 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
276 Ok(decoder.tcx().mk_region(Decodable::decode(decoder)?))
280 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for CanonicalVarInfos<'tcx> {
281 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
282 let len = decoder.read_usize()?;
283 let interned: Result<Vec<CanonicalVarInfo<'tcx>>, _> =
284 (0..len).map(|_| Decodable::decode(decoder)).collect();
285 Ok(decoder.tcx().intern_canonical_var_infos(interned?.as_slice()))
289 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AllocId {
290 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
291 decoder.decode_alloc_id()
295 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::SymbolName<'tcx> {
296 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
297 Ok(ty::SymbolName::new(decoder.tcx(), &decoder.read_str()?))
301 macro_rules! impl_decodable_via_ref {
303 $(impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for $t {
304 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
305 RefDecodable::decode(decoder)
311 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::AdtDef {
312 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
313 let def_id = <DefId as Decodable<D>>::decode(decoder)?;
314 Ok(decoder.tcx().adt_def(def_id))
318 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> {
319 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
320 let len = decoder.read_usize()?;
321 decoder.tcx().mk_type_list((0..len).map(|_| Decodable::decode(decoder)))
325 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D>
326 for ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>
328 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
329 let len = decoder.read_usize()?;
330 decoder.tcx().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 [ty::ValTree<'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 Allocation {
351 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
352 Ok(decoder.tcx().intern_const_alloc(Decodable::decode(decoder)?))
356 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] {
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 [thir::abstract_const::Node<'tcx>] {
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<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [thir::abstract_const::NodeId] {
377 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
378 Ok(decoder.tcx().arena.alloc_from_iter(
379 (0..decoder.read_usize()?)
380 .map(|_| Decodable::decode(decoder))
381 .collect::<Result<Vec<_>, _>>()?,
386 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<ty::BoundVariableKind> {
387 fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
388 let len = decoder.read_usize()?;
389 decoder.tcx().mk_bound_variable_kinds((0..len).map(|_| Decodable::decode(decoder)))
393 impl_decodable_via_ref! {
394 &'tcx ty::TypeckResults<'tcx>,
395 &'tcx ty::List<Ty<'tcx>>,
396 &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
398 &'tcx mir::Body<'tcx>,
399 &'tcx mir::UnsafetyCheckResult,
400 &'tcx mir::BorrowCheckResult<'tcx>,
401 &'tcx mir::coverage::CodeRegion,
402 &'tcx ty::List<ty::BoundVariableKind>
406 macro_rules! __impl_decoder_methods {
407 ($($name:ident -> $ty:ty;)*) => {
410 fn $name(&mut self) -> Result<$ty, Self::Error> {
417 macro_rules! impl_arena_allocatable_decoder {
419 ([decode $(, $attrs:ident)*]
420 [[$name:ident: $ty:ty], $tcx:lifetime]) => {
421 impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for $ty {
423 fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
424 decode_arena_allocable(decoder)
428 impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for [$ty] {
430 fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
431 decode_arena_allocable_slice(decoder)
435 ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
436 impl_arena_allocatable_decoder!([$($attrs),*]$args);
440 macro_rules! impl_arena_allocatable_decoders {
441 ([$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
443 impl_arena_allocatable_decoder!($a [[$name: $ty], $tcx]);
448 rustc_hir::arena_types!(impl_arena_allocatable_decoders, 'tcx);
449 arena_types!(impl_arena_allocatable_decoders, 'tcx);
452 macro_rules! implement_ty_decoder {
453 ($DecoderName:ident <$($typaram:tt),*>) => {
454 mod __ty_decoder_impl {
455 use std::borrow::Cow;
456 use rustc_serialize::Decoder;
458 use super::$DecoderName;
460 impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
463 $crate::__impl_decoder_methods! {
484 read_str -> Cow<'_, str>;
488 fn read_raw_bytes_into(&mut self, bytes: &mut [u8]) -> Result<(), Self::Error> {
489 self.opaque.read_raw_bytes_into(bytes)
492 fn error(&mut self, err: &str) -> Self::Error {
493 self.opaque.error(err)
500 macro_rules! impl_binder_encode_decode {
501 ($($t:ty),+ $(,)?) => {
503 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Binder<'tcx, $t> {
504 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
505 self.bound_vars().encode(e)?;
506 self.as_ref().skip_binder().encode(e)
509 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, $t> {
510 fn decode(decoder: &mut D) -> Result<Self, D::Error> {
511 let bound_vars = Decodable::decode(decoder)?;
512 Ok(ty::Binder::bind_with_vars(Decodable::decode(decoder)?, bound_vars))
519 impl_binder_encode_decode! {
520 &'tcx ty::List<Ty<'tcx>>,
522 ty::ExistentialPredicate<'tcx>,
524 Vec<ty::GeneratorInteriorTypeCause<'tcx>>,