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},
16 use crate::ty::subst::SubstsRef;
17 use crate::ty::{self, AdtDef, Ty};
18 use rustc_data_structures::fx::FxHashMap;
19 use rustc_middle::ty::TyCtxt;
20 use rustc_serialize::{Decodable, Encodable};
22 pub use rustc_type_ir::{TyDecoder, TyEncoder};
25 use std::marker::DiscriminantKind;
27 /// The shorthand encoding uses an enum's variant index `usize`
28 /// and is offset by this value so it never matches a real variant.
29 /// This offset is also chosen so that the first byte is never < 0x80.
30 pub const SHORTHAND_OFFSET: usize = 0x80;
32 pub trait EncodableWithShorthand<E: TyEncoder>: Copy + Eq + Hash {
33 type Variant: Encodable<E>;
34 fn variant(&self) -> &Self::Variant;
37 #[allow(rustc::usage_of_ty_tykind)]
38 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> EncodableWithShorthand<E> for Ty<'tcx> {
39 type Variant = ty::TyKind<'tcx>;
42 fn variant(&self) -> &Self::Variant {
47 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> EncodableWithShorthand<E> for ty::PredicateKind<'tcx> {
48 type Variant = ty::PredicateKind<'tcx>;
51 fn variant(&self) -> &Self::Variant {
56 /// Trait for decoding to a reference.
58 /// This is a separate trait from `Decodable` so that we can implement it for
59 /// upstream types, such as `FxHashSet`.
61 /// The `TyDecodable` derive macro will use this trait for fields that are
62 /// references (and don't use a type alias to hide that).
64 /// `Decodable` can still be implemented in cases where `Decodable` is required
66 pub trait RefDecodable<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> {
67 fn decode(d: &mut D) -> &'tcx Self;
70 /// Encode the given value or a previously cached shorthand.
71 pub fn encode_with_shorthand<'tcx, E, T, M>(encoder: &mut E, value: &T, cache: M)
73 E: TyEncoder<I = TyCtxt<'tcx>>,
74 M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap<T, usize>,
75 T: EncodableWithShorthand<E>,
76 // The discriminant and shorthand must have the same size.
77 T::Variant: DiscriminantKind<Discriminant = isize>,
79 let existing_shorthand = cache(encoder).get(value).copied();
80 if let Some(shorthand) = existing_shorthand {
81 encoder.emit_usize(shorthand);
85 let variant = value.variant();
87 let start = encoder.position();
88 variant.encode(encoder);
89 let len = encoder.position() - start;
91 // The shorthand encoding uses the same usize as the
92 // discriminant, with an offset so they can't conflict.
93 let discriminant = intrinsics::discriminant_value(variant);
94 assert!(SHORTHAND_OFFSET > discriminant as usize);
96 let shorthand = start + SHORTHAND_OFFSET;
98 // Get the number of bits that leb128 could fit
99 // in the same space as the fully encoded type.
100 let leb128_bits = len * 7;
102 // Check that the shorthand is a not longer than the
103 // full encoding itself, i.e., it's an obvious win.
104 if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
105 cache(encoder).insert(*value, shorthand);
109 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for Ty<'tcx> {
110 fn encode(&self, e: &mut E) {
111 encode_with_shorthand(e, self, TyEncoder::type_shorthands);
115 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E>
116 for ty::Binder<'tcx, ty::PredicateKind<'tcx>>
118 fn encode(&self, e: &mut E) {
119 self.bound_vars().encode(e);
120 encode_with_shorthand(e, &self.skip_binder(), TyEncoder::predicate_shorthands);
124 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Predicate<'tcx> {
125 fn encode(&self, e: &mut E) {
126 self.kind().encode(e);
130 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Region<'tcx> {
131 fn encode(&self, e: &mut E) {
132 self.kind().encode(e);
136 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Const<'tcx> {
137 fn encode(&self, e: &mut E) {
142 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ConstAllocation<'tcx> {
143 fn encode(&self, e: &mut E) {
144 self.inner().encode(e)
148 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for AdtDef<'tcx> {
149 fn encode(&self, e: &mut E) {
154 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for AllocId {
155 fn encode(&self, e: &mut E) {
156 e.encode_alloc_id(self)
161 fn decode_arena_allocable<
163 D: TyDecoder<I = TyCtxt<'tcx>>,
164 T: ArenaAllocatable<'tcx> + Decodable<D>,
171 decoder.interner().arena.alloc(Decodable::decode(decoder))
175 fn decode_arena_allocable_slice<
177 D: TyDecoder<I = TyCtxt<'tcx>>,
178 T: ArenaAllocatable<'tcx> + Decodable<D>,
185 decoder.interner().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder))
188 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for Ty<'tcx> {
189 #[allow(rustc::usage_of_ty_tykind)]
190 fn decode(decoder: &mut D) -> Ty<'tcx> {
191 // Handle shorthands first, if we have a usize > 0x80.
192 if decoder.positioned_at_shorthand() {
193 let pos = decoder.read_usize();
194 assert!(pos >= SHORTHAND_OFFSET);
195 let shorthand = pos - SHORTHAND_OFFSET;
197 decoder.cached_ty_for_shorthand(shorthand, |decoder| {
198 decoder.with_position(shorthand, Ty::decode)
201 let tcx = decoder.interner();
202 tcx.mk_ty(rustc_type_ir::TyKind::decode(decoder))
207 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D>
208 for ty::Binder<'tcx, ty::PredicateKind<'tcx>>
210 fn decode(decoder: &mut D) -> ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
211 let bound_vars = Decodable::decode(decoder);
212 // Handle shorthands first, if we have a usize > 0x80.
213 ty::Binder::bind_with_vars(
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.with_position(shorthand, ty::PredicateKind::decode)
221 ty::PredicateKind::decode(decoder)
228 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Predicate<'tcx> {
229 fn decode(decoder: &mut D) -> ty::Predicate<'tcx> {
230 let predicate_kind = Decodable::decode(decoder);
231 decoder.interner().mk_predicate(predicate_kind)
235 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for SubstsRef<'tcx> {
236 fn decode(decoder: &mut D) -> Self {
237 let len = decoder.read_usize();
238 let tcx = decoder.interner();
240 (0..len).map::<ty::subst::GenericArg<'tcx>, _>(|_| Decodable::decode(decoder)),
245 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for mir::Place<'tcx> {
246 fn decode(decoder: &mut D) -> Self {
247 let local: mir::Local = Decodable::decode(decoder);
248 let len = decoder.read_usize();
249 let projection = decoder.interner().mk_place_elems(
250 (0..len).map::<mir::PlaceElem<'tcx>, _>(|_| Decodable::decode(decoder)),
252 mir::Place { local, projection }
256 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Region<'tcx> {
257 fn decode(decoder: &mut D) -> Self {
258 decoder.interner().mk_region(Decodable::decode(decoder))
262 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for CanonicalVarInfos<'tcx> {
263 fn decode(decoder: &mut D) -> Self {
264 let len = decoder.read_usize();
265 let interned: Vec<CanonicalVarInfo<'tcx>> =
266 (0..len).map(|_| Decodable::decode(decoder)).collect();
267 decoder.interner().intern_canonical_var_infos(interned.as_slice())
271 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for AllocId {
272 fn decode(decoder: &mut D) -> Self {
273 decoder.decode_alloc_id()
277 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::SymbolName<'tcx> {
278 fn decode(decoder: &mut D) -> Self {
279 ty::SymbolName::new(decoder.interner(), &decoder.read_str())
283 macro_rules! impl_decodable_via_ref {
285 $(impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for $t {
286 fn decode(decoder: &mut D) -> Self {
287 RefDecodable::decode(decoder)
293 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> {
294 fn decode(decoder: &mut D) -> &'tcx Self {
295 let len = decoder.read_usize();
296 decoder.interner().mk_type_list((0..len).map::<Ty<'tcx>, _>(|_| Decodable::decode(decoder)))
300 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D>
301 for ty::List<ty::PolyExistentialPredicate<'tcx>>
303 fn decode(decoder: &mut D) -> &'tcx Self {
304 let len = decoder.read_usize();
305 decoder.interner().mk_poly_existential_predicates(
306 (0..len).map::<ty::Binder<'tcx, _>, _>(|_| Decodable::decode(decoder)),
311 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Const<'tcx> {
312 fn decode(decoder: &mut D) -> Self {
313 let consts: ty::ConstS<'tcx> = Decodable::decode(decoder);
314 decoder.interner().mk_const(consts.kind, consts.ty)
318 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] {
319 fn decode(decoder: &mut D) -> &'tcx Self {
320 decoder.interner().arena.alloc_from_iter(
321 (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
326 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ConstAllocation<'tcx> {
327 fn decode(decoder: &mut D) -> Self {
328 decoder.interner().intern_const_alloc(Decodable::decode(decoder))
332 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for AdtDef<'tcx> {
333 fn decode(decoder: &mut D) -> Self {
334 decoder.interner().intern_adt_def(Decodable::decode(decoder))
338 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D>
339 for [(ty::Predicate<'tcx>, Span)]
341 fn decode(decoder: &mut D) -> &'tcx Self {
342 decoder.interner().arena.alloc_from_iter(
343 (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
348 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D>
349 for [ty::abstract_const::Node<'tcx>]
351 fn decode(decoder: &mut D) -> &'tcx Self {
352 decoder.interner().arena.alloc_from_iter(
353 (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
358 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D>
359 for [ty::abstract_const::NodeId]
361 fn decode(decoder: &mut D) -> &'tcx Self {
362 decoder.interner().arena.alloc_from_iter(
363 (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
368 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D>
369 for ty::List<ty::BoundVariableKind>
371 fn decode(decoder: &mut D) -> &'tcx Self {
372 let len = decoder.read_usize();
373 decoder.interner().mk_bound_variable_kinds(
374 (0..len).map::<ty::BoundVariableKind, _>(|_| Decodable::decode(decoder)),
379 impl_decodable_via_ref! {
380 &'tcx ty::TypeckResults<'tcx>,
381 &'tcx ty::List<Ty<'tcx>>,
382 &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
383 &'tcx traits::ImplSource<'tcx, ()>,
384 &'tcx mir::Body<'tcx>,
385 &'tcx mir::UnsafetyCheckResult,
386 &'tcx mir::BorrowCheckResult<'tcx>,
387 &'tcx mir::coverage::CodeRegion,
388 &'tcx ty::List<ty::BoundVariableKind>
392 macro_rules! __impl_decoder_methods {
393 ($($name:ident -> $ty:ty;)*) => {
396 fn $name(&mut self) -> $ty {
403 macro_rules! impl_arena_allocatable_decoder {
405 ([decode $(, $attrs:ident)*]
406 [$name:ident: $ty:ty]) => {
407 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for $ty {
409 fn decode(decoder: &mut D) -> &'tcx Self {
410 decode_arena_allocable(decoder)
414 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [$ty] {
416 fn decode(decoder: &mut D) -> &'tcx Self {
417 decode_arena_allocable_slice(decoder)
423 macro_rules! impl_arena_allocatable_decoders {
424 ([$($a:tt $name:ident: $ty:ty,)*]) => {
426 impl_arena_allocatable_decoder!($a [$name: $ty]);
431 rustc_hir::arena_types!(impl_arena_allocatable_decoders);
432 arena_types!(impl_arena_allocatable_decoders);
434 macro_rules! impl_arena_copy_decoder {
435 (<$tcx:tt> $($ty:ty,)*) => {
436 $(impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for $ty {
438 fn decode(decoder: &mut D) -> &'tcx Self {
439 decoder.interner().arena.alloc(Decodable::decode(decoder))
443 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [$ty] {
445 fn decode(decoder: &mut D) -> &'tcx Self {
446 decoder.interner().arena.alloc_from_iter(<Vec<_> as Decodable<D>>::decode(decoder))
452 impl_arena_copy_decoder! {<'tcx>
454 rustc_span::symbol::Ident,
456 rustc_span::def_id::DefId,
457 rustc_span::def_id::LocalDefId,
458 (rustc_middle::middle::exported_symbols::ExportedSymbol<'tcx>, rustc_middle::middle::exported_symbols::SymbolExportInfo),
459 ty::DeducedParamAttrs,
463 macro_rules! implement_ty_decoder {
464 ($DecoderName:ident <$($typaram:tt),*>) => {
465 mod __ty_decoder_impl {
466 use std::borrow::Cow;
467 use rustc_serialize::Decoder;
469 use super::$DecoderName;
471 impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
472 $crate::__impl_decoder_methods! {
495 fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
496 self.opaque.read_raw_bytes(len)
503 macro_rules! impl_binder_encode_decode {
504 ($($t:ty),+ $(,)?) => {
506 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Binder<'tcx, $t> {
507 fn encode(&self, e: &mut E) {
508 self.bound_vars().encode(e);
509 self.as_ref().skip_binder().encode(e);
512 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Binder<'tcx, $t> {
513 fn decode(decoder: &mut D) -> Self {
514 let bound_vars = Decodable::decode(decoder);
515 ty::Binder::bind_with_vars(Decodable::decode(decoder), bound_vars)
522 impl_binder_encode_decode! {
523 &'tcx ty::List<Ty<'tcx>>,
525 ty::ExistentialPredicate<'tcx>,
527 Vec<ty::GeneratorInteriorTypeCause<'tcx>>,
528 ty::ExistentialTraitRef<'tcx>,