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::hir::def_id::{DefId, CrateNum};
11 use crate::infer::canonical::{CanonicalVarInfo, CanonicalVarInfos};
12 use rustc_data_structures::fx::FxHashMap;
13 use crate::rustc_serialize::{Decodable, Decoder, Encoder, Encodable, opaque};
16 use crate::ty::{self, Ty, TyCtxt};
17 use crate::ty::subst::SubstsRef;
18 use crate::mir::interpret::Allocation;
20 /// The shorthand encoding uses an enum's variant index `usize`
21 /// and is offset by this value so it never matches a real variant.
22 /// This offset is also chosen so that the first byte is never < 0x80.
23 pub const SHORTHAND_OFFSET: usize = 0x80;
25 pub trait EncodableWithShorthand: Clone + Eq + Hash {
26 type Variant: Encodable;
27 fn variant(&self) -> &Self::Variant;
30 #[cfg_attr(not(bootstrap), allow(rustc::usage_of_ty_tykind))]
31 impl<'tcx> EncodableWithShorthand for Ty<'tcx> {
32 type Variant = ty::TyKind<'tcx>;
33 fn variant(&self) -> &Self::Variant {
38 impl<'tcx> EncodableWithShorthand for ty::Predicate<'tcx> {
39 type Variant = ty::Predicate<'tcx>;
40 fn variant(&self) -> &Self::Variant {
45 pub trait TyEncoder: Encoder {
46 fn position(&self) -> usize;
49 impl TyEncoder for opaque::Encoder {
51 fn position(&self) -> usize {
56 /// Encode the given value or a previously cached shorthand.
57 pub fn encode_with_shorthand<E, T, M>(encoder: &mut E,
60 -> Result<(), E::Error>
62 M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap<T, usize>,
63 T: EncodableWithShorthand,
65 let existing_shorthand = cache(encoder).get(value).cloned();
66 if let Some(shorthand) = existing_shorthand {
67 return encoder.emit_usize(shorthand);
70 let variant = value.variant();
72 let start = encoder.position();
73 variant.encode(encoder)?;
74 let len = encoder.position() - start;
76 // The shorthand encoding uses the same usize as the
77 // discriminant, with an offset so they can't conflict.
78 let discriminant = unsafe { intrinsics::discriminant_value(variant) };
79 assert!(discriminant < SHORTHAND_OFFSET as u64);
80 let shorthand = start + SHORTHAND_OFFSET;
82 // Get the number of bits that leb128 could fit
83 // in the same space as the fully encoded type.
84 let leb128_bits = len * 7;
86 // Check that the shorthand is a not longer than the
87 // full encoding itself, i.e., it's an obvious win.
88 if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
89 cache(encoder).insert(value.clone(), shorthand);
95 pub fn encode_predicates<'tcx, E, C>(encoder: &mut E,
96 predicates: &ty::GenericPredicates<'tcx>,
98 -> Result<(), E::Error>
100 C: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap<ty::Predicate<'tcx>, usize>,
102 predicates.parent.encode(encoder)?;
103 predicates.predicates.len().encode(encoder)?;
104 for (predicate, span) in &predicates.predicates {
105 encode_with_shorthand(encoder, predicate, &cache)?;
106 span.encode(encoder)?;
111 pub trait TyDecoder<'tcx>: Decoder {
112 fn tcx(&self) -> TyCtxt<'tcx>;
114 fn peek_byte(&self) -> u8;
116 fn position(&self) -> usize;
118 fn cached_ty_for_shorthand<F>(&mut self,
121 -> Result<Ty<'tcx>, Self::Error>
122 where F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>;
124 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
125 where F: FnOnce(&mut Self) -> R;
127 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum;
129 fn positioned_at_shorthand(&self) -> bool {
130 (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0
135 pub fn decode_arena_allocable<D, T: ArenaAllocatable + Decodable>(
137 ) -> Result<&'tcx T, D::Error>
141 Ok(decoder.tcx().arena.alloc(Decodable::decode(decoder)?))
145 pub fn decode_arena_allocable_slice<D, T: ArenaAllocatable + Decodable>(
147 ) -> Result<&'tcx [T], D::Error>
151 Ok(decoder.tcx().arena.alloc_from_iter(<Vec<T> as Decodable>::decode(decoder)?))
155 pub fn decode_cnum<D>(decoder: &mut D) -> Result<CrateNum, D::Error>
159 let cnum = CrateNum::from_u32(u32::decode(decoder)?);
160 Ok(decoder.map_encoded_cnum_to_current(cnum))
163 #[cfg_attr(not(bootstrap), allow(rustc::usage_of_ty_tykind))]
165 pub fn decode_ty<D>(decoder: &mut D) -> Result<Ty<'tcx>, D::Error>
169 // Handle shorthands first, if we have an usize > 0x80.
170 if decoder.positioned_at_shorthand() {
171 let pos = decoder.read_usize()?;
172 assert!(pos >= SHORTHAND_OFFSET);
173 let shorthand = pos - SHORTHAND_OFFSET;
175 decoder.cached_ty_for_shorthand(shorthand, |decoder| {
176 decoder.with_position(shorthand, Ty::decode)
179 let tcx = decoder.tcx();
180 Ok(tcx.mk_ty(ty::TyKind::decode(decoder)?))
185 pub fn decode_predicates<D>(decoder: &mut D) -> Result<ty::GenericPredicates<'tcx>, D::Error>
189 Ok(ty::GenericPredicates {
190 parent: Decodable::decode(decoder)?,
191 predicates: (0..decoder.read_usize()?).map(|_| {
192 // Handle shorthands first, if we have an usize > 0x80.
193 let predicate = if decoder.positioned_at_shorthand() {
194 let pos = decoder.read_usize()?;
195 assert!(pos >= SHORTHAND_OFFSET);
196 let shorthand = pos - SHORTHAND_OFFSET;
198 decoder.with_position(shorthand, ty::Predicate::decode)
200 ty::Predicate::decode(decoder)
202 Ok((predicate, Decodable::decode(decoder)?))
204 .collect::<Result<Vec<_>, _>>()?,
209 pub fn decode_substs<D>(decoder: &mut D) -> Result<SubstsRef<'tcx>, D::Error>
213 let len = decoder.read_usize()?;
214 let tcx = decoder.tcx();
215 Ok(tcx.mk_substs((0..len).map(|_| Decodable::decode(decoder)))?)
219 pub fn decode_region<D>(decoder: &mut D) -> Result<ty::Region<'tcx>, D::Error>
223 Ok(decoder.tcx().mk_region(Decodable::decode(decoder)?))
227 pub fn decode_ty_slice<D>(decoder: &mut D) -> Result<&'tcx ty::List<Ty<'tcx>>, D::Error>
231 let len = decoder.read_usize()?;
232 Ok(decoder.tcx().mk_type_list((0..len).map(|_| Decodable::decode(decoder)))?)
236 pub fn decode_adt_def<D>(decoder: &mut D) -> Result<&'tcx ty::AdtDef, D::Error>
240 let def_id = DefId::decode(decoder)?;
241 Ok(decoder.tcx().adt_def(def_id))
245 pub fn decode_existential_predicate_slice<D>(
247 ) -> Result<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>, D::Error>
251 let len = decoder.read_usize()?;
253 .mk_existential_predicates((0..len).map(|_| Decodable::decode(decoder)))?)
257 pub fn decode_canonical_var_infos<D>(decoder: &mut D) -> Result<CanonicalVarInfos<'tcx>, D::Error>
261 let len = decoder.read_usize()?;
262 let interned: Result<Vec<CanonicalVarInfo>, _> = (0..len).map(|_| Decodable::decode(decoder))
265 .intern_canonical_var_infos(interned?.as_slice()))
269 pub fn decode_const<D>(decoder: &mut D) -> Result<&'tcx ty::Const<'tcx>, D::Error>
273 Ok(decoder.tcx().mk_const(Decodable::decode(decoder)?))
277 pub fn decode_allocation<D>(decoder: &mut D) -> Result<&'tcx Allocation, D::Error>
281 Ok(decoder.tcx().intern_const_alloc(Decodable::decode(decoder)?))
285 macro_rules! __impl_decoder_methods {
286 ($($name:ident -> $ty:ty;)*) => {
287 $(fn $name(&mut self) -> Result<$ty, Self::Error> {
294 macro_rules! impl_arena_allocatable_decoder {
296 ([decode $(, $attrs:ident)*]
297 [[$DecoderName:ident [$($typaram:tt),*]], [$name:ident: $ty:ty], $tcx:lifetime]) => {
298 impl<$($typaram),*> SpecializedDecoder<&$tcx $ty> for $DecoderName<$($typaram),*> {
300 fn specialized_decode(&mut self) -> Result<&$tcx $ty, Self::Error> {
301 decode_arena_allocable(self)
305 impl<$($typaram),*> SpecializedDecoder<&$tcx [$ty]> for $DecoderName<$($typaram),*> {
307 fn specialized_decode(&mut self) -> Result<&$tcx [$ty], Self::Error> {
308 decode_arena_allocable_slice(self)
312 ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
313 impl_arena_allocatable_decoder!([$($attrs),*]$args);
318 macro_rules! impl_arena_allocatable_decoders {
319 ($args:tt, [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
321 impl_arena_allocatable_decoder!($a [$args, [$name: $ty], $tcx]);
327 macro_rules! implement_ty_decoder {
328 ($DecoderName:ident <$($typaram:tt),*>) => {
329 mod __ty_decoder_impl {
330 use super::$DecoderName;
331 use $crate::infer::canonical::CanonicalVarInfos;
333 use $crate::ty::codec::*;
334 use $crate::ty::subst::SubstsRef;
335 use $crate::hir::def_id::{CrateNum};
336 use crate::rustc_serialize::{Decoder, SpecializedDecoder};
337 use std::borrow::Cow;
339 impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
342 __impl_decoder_methods! {
363 read_str -> Cow<'_, str>;
366 fn error(&mut self, err: &str) -> Self::Error {
367 self.opaque.error(err)
371 // FIXME(#36588) These impls are horribly unsound as they allow
372 // the caller to pick any lifetime for 'tcx, including 'static,
373 // by using the unspecialized proxies to them.
375 arena_types!(impl_arena_allocatable_decoders, [$DecoderName [$($typaram),*]], 'tcx);
377 impl<$($typaram),*> SpecializedDecoder<CrateNum>
378 for $DecoderName<$($typaram),*> {
379 fn specialized_decode(&mut self) -> Result<CrateNum, Self::Error> {
384 impl<$($typaram),*> SpecializedDecoder<ty::Ty<'tcx>>
385 for $DecoderName<$($typaram),*> {
386 fn specialized_decode(&mut self) -> Result<ty::Ty<'tcx>, Self::Error> {
391 impl<$($typaram),*> SpecializedDecoder<ty::GenericPredicates<'tcx>>
392 for $DecoderName<$($typaram),*> {
393 fn specialized_decode(&mut self)
394 -> Result<ty::GenericPredicates<'tcx>, Self::Error> {
395 decode_predicates(self)
399 impl<$($typaram),*> SpecializedDecoder<SubstsRef<'tcx>>
400 for $DecoderName<$($typaram),*> {
401 fn specialized_decode(&mut self) -> Result<SubstsRef<'tcx>, Self::Error> {
406 impl<$($typaram),*> SpecializedDecoder<ty::Region<'tcx>>
407 for $DecoderName<$($typaram),*> {
408 fn specialized_decode(&mut self) -> Result<ty::Region<'tcx>, Self::Error> {
413 impl<$($typaram),*> SpecializedDecoder<&'tcx ty::List<ty::Ty<'tcx>>>
414 for $DecoderName<$($typaram),*> {
415 fn specialized_decode(&mut self)
416 -> Result<&'tcx ty::List<ty::Ty<'tcx>>, Self::Error> {
417 decode_ty_slice(self)
421 impl<$($typaram),*> SpecializedDecoder<&'tcx ty::AdtDef>
422 for $DecoderName<$($typaram),*> {
423 fn specialized_decode(&mut self) -> Result<&'tcx ty::AdtDef, Self::Error> {
428 impl<$($typaram),*> SpecializedDecoder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>
429 for $DecoderName<$($typaram),*> {
430 fn specialized_decode(&mut self)
431 -> Result<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>, Self::Error> {
432 decode_existential_predicate_slice(self)
436 impl<$($typaram),*> SpecializedDecoder<CanonicalVarInfos<'tcx>>
437 for $DecoderName<$($typaram),*> {
438 fn specialized_decode(&mut self)
439 -> Result<CanonicalVarInfos<'tcx>, Self::Error> {
440 decode_canonical_var_infos(self)
444 impl<$($typaram),*> SpecializedDecoder<&'tcx $crate::ty::Const<'tcx>>
445 for $DecoderName<$($typaram),*> {
446 fn specialized_decode(&mut self) -> Result<&'tcx ty::Const<'tcx>, Self::Error> {
451 impl<$($typaram),*> SpecializedDecoder<&'tcx $crate::mir::interpret::Allocation>
452 for $DecoderName<$($typaram),*> {
453 fn specialized_decode(
455 ) -> Result<&'tcx $crate::mir::interpret::Allocation, Self::Error> {
456 decode_allocation(self)