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, ConstAllocation},
17 use crate::ty::subst::SubstsRef;
18 use crate::ty::{self, AdtDef, Ty, TyCtxt};
19 use rustc_data_structures::fx::FxHashMap;
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) -> &'tcx Self;
78 /// Encode the given value or a previously cached shorthand.
79 pub fn encode_with_shorthand<'tcx, E, T, M>(
83 ) -> Result<(), E::Error>
86 M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap<T, usize>,
87 T: EncodableWithShorthand<'tcx, E>,
88 // The discriminant and shorthand must have the same size.
89 T::Variant: DiscriminantKind<Discriminant = isize>,
91 let existing_shorthand = cache(encoder).get(value).copied();
92 if let Some(shorthand) = existing_shorthand {
93 return encoder.emit_usize(shorthand);
96 let variant = value.variant();
98 let start = encoder.position();
99 variant.encode(encoder)?;
100 let len = encoder.position() - start;
102 // The shorthand encoding uses the same usize as the
103 // discriminant, with an offset so they can't conflict.
104 let discriminant = intrinsics::discriminant_value(variant);
105 assert!(SHORTHAND_OFFSET > discriminant as usize);
107 let shorthand = start + SHORTHAND_OFFSET;
109 // Get the number of bits that leb128 could fit
110 // in the same space as the fully encoded type.
111 let leb128_bits = len * 7;
113 // Check that the shorthand is a not longer than the
114 // full encoding itself, i.e., it's an obvious win.
115 if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
116 cache(encoder).insert(*value, shorthand);
122 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Ty<'tcx> {
123 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
124 encode_with_shorthand(e, self, TyEncoder::type_shorthands)
128 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
129 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
130 self.bound_vars().encode(e)?;
131 encode_with_shorthand(e, &self.skip_binder(), TyEncoder::predicate_shorthands)
135 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Predicate<'tcx> {
136 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
137 self.kind().encode(e)
141 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Region<'tcx> {
142 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
143 self.kind().encode(e)
147 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Const<'tcx> {
148 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
153 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ConstAllocation<'tcx> {
154 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
155 self.inner().encode(e)
159 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for AdtDef<'tcx> {
160 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
165 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for AllocId {
166 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
167 e.encode_alloc_id(self)
171 macro_rules! encodable_via_deref {
173 $(impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for $t {
174 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
181 encodable_via_deref! {
182 &'tcx ty::TypeckResults<'tcx>,
183 &'tcx traits::ImplSource<'tcx, ()>,
184 &'tcx mir::Body<'tcx>,
185 &'tcx mir::UnsafetyCheckResult,
186 &'tcx mir::BorrowCheckResult<'tcx>,
187 &'tcx mir::coverage::CodeRegion
190 pub trait TyDecoder<'tcx>: Decoder {
191 const CLEAR_CROSS_CRATE: bool;
193 fn tcx(&self) -> TyCtxt<'tcx>;
195 fn peek_byte(&self) -> u8;
197 fn position(&self) -> usize;
199 fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx>
201 F: FnOnce(&mut Self) -> Ty<'tcx>;
203 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
205 F: FnOnce(&mut Self) -> R;
207 fn positioned_at_shorthand(&self) -> bool {
208 (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0
211 fn decode_alloc_id(&mut self) -> AllocId;
215 fn decode_arena_allocable<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
221 decoder.tcx().arena.alloc(Decodable::decode(decoder))
225 fn decode_arena_allocable_slice<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
231 decoder.tcx().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder))
234 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Ty<'tcx> {
235 #[allow(rustc::usage_of_ty_tykind)]
236 fn decode(decoder: &mut D) -> Ty<'tcx> {
237 // Handle shorthands first, if we have a usize > 0x80.
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.cached_ty_for_shorthand(shorthand, |decoder| {
244 decoder.with_position(shorthand, Ty::decode)
247 let tcx = decoder.tcx();
248 tcx.mk_ty(ty::TyKind::decode(decoder))
253 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
254 fn decode(decoder: &mut D) -> ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
255 let bound_vars = Decodable::decode(decoder);
256 // Handle shorthands first, if we have a usize > 0x80.
257 ty::Binder::bind_with_vars(
258 if decoder.positioned_at_shorthand() {
259 let pos = decoder.read_usize();
260 assert!(pos >= SHORTHAND_OFFSET);
261 let shorthand = pos - SHORTHAND_OFFSET;
263 decoder.with_position(shorthand, ty::PredicateKind::decode)
265 ty::PredicateKind::decode(decoder)
272 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Predicate<'tcx> {
273 fn decode(decoder: &mut D) -> ty::Predicate<'tcx> {
274 let predicate_kind = Decodable::decode(decoder);
275 decoder.tcx().mk_predicate(predicate_kind)
279 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for SubstsRef<'tcx> {
280 fn decode(decoder: &mut D) -> Self {
281 let len = decoder.read_usize();
282 let tcx = decoder.tcx();
284 (0..len).map::<ty::subst::GenericArg<'tcx>, _>(|_| Decodable::decode(decoder)),
289 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for mir::Place<'tcx> {
290 fn decode(decoder: &mut D) -> Self {
291 let local: mir::Local = Decodable::decode(decoder);
292 let len = decoder.read_usize();
293 let projection = decoder.tcx().mk_place_elems(
294 (0..len).map::<mir::PlaceElem<'tcx>, _>(|_| Decodable::decode(decoder)),
296 mir::Place { local, projection }
300 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Region<'tcx> {
301 fn decode(decoder: &mut D) -> Self {
302 decoder.tcx().mk_region(Decodable::decode(decoder))
306 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for CanonicalVarInfos<'tcx> {
307 fn decode(decoder: &mut D) -> Self {
308 let len = decoder.read_usize();
309 let interned: Vec<CanonicalVarInfo<'tcx>> =
310 (0..len).map(|_| Decodable::decode(decoder)).collect();
311 decoder.tcx().intern_canonical_var_infos(interned.as_slice())
315 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AllocId {
316 fn decode(decoder: &mut D) -> Self {
317 decoder.decode_alloc_id()
321 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::SymbolName<'tcx> {
322 fn decode(decoder: &mut D) -> Self {
323 ty::SymbolName::new(decoder.tcx(), &decoder.read_str())
327 macro_rules! impl_decodable_via_ref {
329 $(impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for $t {
330 fn decode(decoder: &mut D) -> Self {
331 RefDecodable::decode(decoder)
337 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> {
338 fn decode(decoder: &mut D) -> &'tcx Self {
339 let len = decoder.read_usize();
340 decoder.tcx().mk_type_list((0..len).map::<Ty<'tcx>, _>(|_| Decodable::decode(decoder)))
344 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D>
345 for ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>
347 fn decode(decoder: &mut D) -> &'tcx Self {
348 let len = decoder.read_usize();
349 decoder.tcx().mk_poly_existential_predicates(
350 (0..len).map::<ty::Binder<'tcx, _>, _>(|_| Decodable::decode(decoder)),
355 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Const<'tcx> {
356 fn decode(decoder: &mut D) -> Self {
357 decoder.tcx().mk_const(Decodable::decode(decoder))
361 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] {
362 fn decode(decoder: &mut D) -> &'tcx Self {
363 decoder.tcx().arena.alloc_from_iter(
364 (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
369 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ConstAllocation<'tcx> {
370 fn decode(decoder: &mut D) -> Self {
371 decoder.tcx().intern_const_alloc(Decodable::decode(decoder))
375 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AdtDef<'tcx> {
376 fn decode(decoder: &mut D) -> Self {
377 decoder.tcx().intern_adt_def(Decodable::decode(decoder))
381 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] {
382 fn decode(decoder: &mut D) -> &'tcx Self {
383 decoder.tcx().arena.alloc_from_iter(
384 (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
389 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [thir::abstract_const::Node<'tcx>] {
390 fn decode(decoder: &mut D) -> &'tcx Self {
391 decoder.tcx().arena.alloc_from_iter(
392 (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
397 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [thir::abstract_const::NodeId] {
398 fn decode(decoder: &mut D) -> &'tcx Self {
399 decoder.tcx().arena.alloc_from_iter(
400 (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
405 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<ty::BoundVariableKind> {
406 fn decode(decoder: &mut D) -> &'tcx Self {
407 let len = decoder.read_usize();
408 decoder.tcx().mk_bound_variable_kinds(
409 (0..len).map::<ty::BoundVariableKind, _>(|_| Decodable::decode(decoder)),
414 impl_decodable_via_ref! {
415 &'tcx ty::TypeckResults<'tcx>,
416 &'tcx ty::List<Ty<'tcx>>,
417 &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
418 &'tcx traits::ImplSource<'tcx, ()>,
419 &'tcx mir::Body<'tcx>,
420 &'tcx mir::UnsafetyCheckResult,
421 &'tcx mir::BorrowCheckResult<'tcx>,
422 &'tcx mir::coverage::CodeRegion,
423 &'tcx ty::List<ty::BoundVariableKind>
427 macro_rules! __impl_decoder_methods {
428 ($($name:ident -> $ty:ty;)*) => {
431 fn $name(&mut self) -> $ty {
438 macro_rules! impl_arena_allocatable_decoder {
440 ([decode $(, $attrs:ident)*]
441 [$name:ident: $ty:ty]) => {
442 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for $ty {
444 fn decode(decoder: &mut D) -> &'tcx Self {
445 decode_arena_allocable(decoder)
449 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [$ty] {
451 fn decode(decoder: &mut D) -> &'tcx Self {
452 decode_arena_allocable_slice(decoder)
456 ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
457 impl_arena_allocatable_decoder!([$($attrs),*]$args);
461 macro_rules! impl_arena_allocatable_decoders {
462 ([$($a:tt $name:ident: $ty:ty,)*]) => {
464 impl_arena_allocatable_decoder!($a [$name: $ty]);
469 rustc_hir::arena_types!(impl_arena_allocatable_decoders);
470 arena_types!(impl_arena_allocatable_decoders);
473 macro_rules! implement_ty_decoder {
474 ($DecoderName:ident <$($typaram:tt),*>) => {
475 mod __ty_decoder_impl {
476 use std::borrow::Cow;
477 use rustc_serialize::Decoder;
479 use super::$DecoderName;
481 impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
482 $crate::__impl_decoder_methods! {
505 fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
506 self.opaque.read_raw_bytes(len)
513 macro_rules! impl_binder_encode_decode {
514 ($($t:ty),+ $(,)?) => {
516 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Binder<'tcx, $t> {
517 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
518 self.bound_vars().encode(e)?;
519 self.as_ref().skip_binder().encode(e)
522 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, $t> {
523 fn decode(decoder: &mut D) -> Self {
524 let bound_vars = Decodable::decode(decoder);
525 ty::Binder::bind_with_vars(Decodable::decode(decoder), bound_vars)
532 impl_binder_encode_decode! {
533 &'tcx ty::List<Ty<'tcx>>,
535 ty::ExistentialPredicate<'tcx>,
537 Vec<ty::GeneratorInteriorTypeCause<'tcx>>,