]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/codec.rs
Delete Decoder::read_unit
[rust.git] / compiler / rustc_middle / src / ty / codec.rs
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.
5 //!
6 //! The functionality in here is shared between persisting to crate metadata and
7 //! persisting to incr. comp. caches.
8
9 use crate::arena::ArenaAllocatable;
10 use crate::infer::canonical::{CanonicalVarInfo, CanonicalVarInfos};
11 use crate::mir::{
12     self,
13     interpret::{AllocId, Allocation},
14 };
15 use crate::thir;
16 use crate::traits;
17 use crate::ty::subst::SubstsRef;
18 use crate::ty::{self, Ty, TyCtxt};
19 use rustc_data_structures::fx::FxHashMap;
20 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
21 use rustc_span::Span;
22 use std::hash::Hash;
23 use std::intrinsics;
24 use std::marker::DiscriminantKind;
25
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;
30
31 pub trait EncodableWithShorthand<'tcx, E: TyEncoder<'tcx>>: Copy + Eq + Hash {
32     type Variant: Encodable<E>;
33     fn variant(&self) -> &Self::Variant;
34 }
35
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>;
39
40     #[inline]
41     fn variant(&self) -> &Self::Variant {
42         self.kind()
43     }
44 }
45
46 impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for ty::PredicateKind<'tcx> {
47     type Variant = ty::PredicateKind<'tcx>;
48
49     #[inline]
50     fn variant(&self) -> &Self::Variant {
51         self
52     }
53 }
54
55 pub trait TyEncoder<'tcx>: Encoder {
56     const CLEAR_CROSS_CRATE: bool;
57
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>;
62 }
63
64 /// Trait for decoding to a reference.
65 ///
66 /// This is a separate trait from `Decodable` so that we can implement it for
67 /// upstream types, such as `FxHashSet`.
68 ///
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).
71 ///
72 /// `Decodable` can still be implemented in cases where `Decodable` is required
73 /// by a trait bound.
74 pub trait RefDecodable<'tcx, D: TyDecoder<'tcx>> {
75     fn decode(d: &mut D) -> &'tcx Self;
76 }
77
78 /// Encode the given value or a previously cached shorthand.
79 pub fn encode_with_shorthand<'tcx, E, T, M>(
80     encoder: &mut E,
81     value: &T,
82     cache: M,
83 ) -> Result<(), E::Error>
84 where
85     E: TyEncoder<'tcx>,
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>,
90 {
91     let existing_shorthand = cache(encoder).get(value).copied();
92     if let Some(shorthand) = existing_shorthand {
93         return encoder.emit_usize(shorthand);
94     }
95
96     let variant = value.variant();
97
98     let start = encoder.position();
99     variant.encode(encoder)?;
100     let len = encoder.position() - start;
101
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);
106
107     let shorthand = start + SHORTHAND_OFFSET;
108
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;
112
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);
117     }
118
119     Ok(())
120 }
121
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)
125     }
126 }
127
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)
132     }
133 }
134
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)
138     }
139 }
140
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)
144     }
145 }
146
147 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Const<'tcx> {
148     fn encode(&self, e: &mut E) -> Result<(), E::Error> {
149         self.0.0.encode(e)
150     }
151 }
152
153 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for AllocId {
154     fn encode(&self, e: &mut E) -> Result<(), E::Error> {
155         e.encode_alloc_id(self)
156     }
157 }
158
159 macro_rules! encodable_via_deref {
160     ($($t:ty),+) => {
161         $(impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for $t {
162             fn encode(&self, e: &mut E) -> Result<(), E::Error> {
163                 (**self).encode(e)
164             }
165         })*
166     }
167 }
168
169 encodable_via_deref! {
170     &'tcx ty::TypeckResults<'tcx>,
171     &'tcx traits::ImplSource<'tcx, ()>,
172     &'tcx mir::Body<'tcx>,
173     &'tcx mir::UnsafetyCheckResult,
174     &'tcx mir::BorrowCheckResult<'tcx>,
175     &'tcx mir::coverage::CodeRegion,
176     &'tcx ty::AdtDef
177 }
178
179 pub trait TyDecoder<'tcx>: Decoder {
180     const CLEAR_CROSS_CRATE: bool;
181
182     fn tcx(&self) -> TyCtxt<'tcx>;
183
184     fn peek_byte(&self) -> u8;
185
186     fn position(&self) -> usize;
187
188     fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx>
189     where
190         F: FnOnce(&mut Self) -> Ty<'tcx>;
191
192     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
193     where
194         F: FnOnce(&mut Self) -> R;
195
196     fn positioned_at_shorthand(&self) -> bool {
197         (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0
198     }
199
200     fn decode_alloc_id(&mut self) -> AllocId;
201 }
202
203 #[inline]
204 fn decode_arena_allocable<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
205     decoder: &mut D,
206 ) -> &'tcx T
207 where
208     D: TyDecoder<'tcx>,
209 {
210     decoder.tcx().arena.alloc(Decodable::decode(decoder))
211 }
212
213 #[inline]
214 fn decode_arena_allocable_slice<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
215     decoder: &mut D,
216 ) -> &'tcx [T]
217 where
218     D: TyDecoder<'tcx>,
219 {
220     decoder.tcx().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder))
221 }
222
223 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Ty<'tcx> {
224     #[allow(rustc::usage_of_ty_tykind)]
225     fn decode(decoder: &mut D) -> Ty<'tcx> {
226         // Handle shorthands first, if we have a usize > 0x80.
227         if decoder.positioned_at_shorthand() {
228             let pos = decoder.read_usize();
229             assert!(pos >= SHORTHAND_OFFSET);
230             let shorthand = pos - SHORTHAND_OFFSET;
231
232             decoder.cached_ty_for_shorthand(shorthand, |decoder| {
233                 decoder.with_position(shorthand, Ty::decode)
234             })
235         } else {
236             let tcx = decoder.tcx();
237             tcx.mk_ty(ty::TyKind::decode(decoder))
238         }
239     }
240 }
241
242 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
243     fn decode(decoder: &mut D) -> ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
244         let bound_vars = Decodable::decode(decoder);
245         // Handle shorthands first, if we have a usize > 0x80.
246         ty::Binder::bind_with_vars(
247             if decoder.positioned_at_shorthand() {
248                 let pos = decoder.read_usize();
249                 assert!(pos >= SHORTHAND_OFFSET);
250                 let shorthand = pos - SHORTHAND_OFFSET;
251
252                 decoder.with_position(shorthand, ty::PredicateKind::decode)
253             } else {
254                 ty::PredicateKind::decode(decoder)
255             },
256             bound_vars,
257         )
258     }
259 }
260
261 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Predicate<'tcx> {
262     fn decode(decoder: &mut D) -> ty::Predicate<'tcx> {
263         let predicate_kind = Decodable::decode(decoder);
264         decoder.tcx().mk_predicate(predicate_kind)
265     }
266 }
267
268 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for SubstsRef<'tcx> {
269     fn decode(decoder: &mut D) -> Self {
270         let len = decoder.read_usize();
271         let tcx = decoder.tcx();
272         tcx.mk_substs(
273             (0..len).map::<ty::subst::GenericArg<'tcx>, _>(|_| Decodable::decode(decoder)),
274         )
275     }
276 }
277
278 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for mir::Place<'tcx> {
279     fn decode(decoder: &mut D) -> Self {
280         let local: mir::Local = Decodable::decode(decoder);
281         let len = decoder.read_usize();
282         let projection = decoder.tcx().mk_place_elems(
283             (0..len).map::<mir::PlaceElem<'tcx>, _>(|_| Decodable::decode(decoder)),
284         );
285         mir::Place { local, projection }
286     }
287 }
288
289 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Region<'tcx> {
290     fn decode(decoder: &mut D) -> Self {
291         decoder.tcx().mk_region(Decodable::decode(decoder))
292     }
293 }
294
295 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for CanonicalVarInfos<'tcx> {
296     fn decode(decoder: &mut D) -> Self {
297         let len = decoder.read_usize();
298         let interned: Vec<CanonicalVarInfo<'tcx>> =
299             (0..len).map(|_| Decodable::decode(decoder)).collect();
300         decoder.tcx().intern_canonical_var_infos(interned.as_slice())
301     }
302 }
303
304 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AllocId {
305     fn decode(decoder: &mut D) -> Self {
306         decoder.decode_alloc_id()
307     }
308 }
309
310 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::SymbolName<'tcx> {
311     fn decode(decoder: &mut D) -> Self {
312         ty::SymbolName::new(decoder.tcx(), &decoder.read_str())
313     }
314 }
315
316 macro_rules! impl_decodable_via_ref {
317     ($($t:ty),+) => {
318         $(impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for $t {
319             fn decode(decoder: &mut D) -> Self {
320                 RefDecodable::decode(decoder)
321             }
322         })*
323     }
324 }
325
326 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> {
327     fn decode(decoder: &mut D) -> &'tcx Self {
328         let len = decoder.read_usize();
329         decoder.tcx().mk_type_list((0..len).map::<Ty<'tcx>, _>(|_| Decodable::decode(decoder)))
330     }
331 }
332
333 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D>
334     for ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>
335 {
336     fn decode(decoder: &mut D) -> &'tcx Self {
337         let len = decoder.read_usize();
338         decoder.tcx().mk_poly_existential_predicates(
339             (0..len).map::<ty::Binder<'tcx, _>, _>(|_| Decodable::decode(decoder)),
340         )
341     }
342 }
343
344 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Const<'tcx> {
345     fn decode(decoder: &mut D) -> Self {
346         decoder.tcx().mk_const(Decodable::decode(decoder))
347     }
348 }
349
350 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] {
351     fn decode(decoder: &mut D) -> &'tcx Self {
352         decoder.tcx().arena.alloc_from_iter(
353             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
354         )
355     }
356 }
357
358 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for Allocation {
359     fn decode(decoder: &mut D) -> &'tcx Self {
360         decoder.tcx().intern_const_alloc(Decodable::decode(decoder))
361     }
362 }
363
364 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] {
365     fn decode(decoder: &mut D) -> &'tcx Self {
366         decoder.tcx().arena.alloc_from_iter(
367             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
368         )
369     }
370 }
371
372 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [thir::abstract_const::Node<'tcx>] {
373     fn decode(decoder: &mut D) -> &'tcx Self {
374         decoder.tcx().arena.alloc_from_iter(
375             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
376         )
377     }
378 }
379
380 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [thir::abstract_const::NodeId] {
381     fn decode(decoder: &mut D) -> &'tcx Self {
382         decoder.tcx().arena.alloc_from_iter(
383             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
384         )
385     }
386 }
387
388 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<ty::BoundVariableKind> {
389     fn decode(decoder: &mut D) -> &'tcx Self {
390         let len = decoder.read_usize();
391         decoder.tcx().mk_bound_variable_kinds(
392             (0..len).map::<ty::BoundVariableKind, _>(|_| Decodable::decode(decoder)),
393         )
394     }
395 }
396
397 impl_decodable_via_ref! {
398     &'tcx ty::TypeckResults<'tcx>,
399     &'tcx ty::List<Ty<'tcx>>,
400     &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
401     &'tcx traits::ImplSource<'tcx, ()>,
402     &'tcx Allocation,
403     &'tcx mir::Body<'tcx>,
404     &'tcx mir::UnsafetyCheckResult,
405     &'tcx mir::BorrowCheckResult<'tcx>,
406     &'tcx mir::coverage::CodeRegion,
407     &'tcx ty::List<ty::BoundVariableKind>,
408     &'tcx ty::AdtDef
409 }
410
411 #[macro_export]
412 macro_rules! __impl_decoder_methods {
413     ($($name:ident -> $ty:ty;)*) => {
414         $(
415             #[inline]
416             fn $name(&mut self) -> $ty {
417                 self.opaque.$name()
418             }
419         )*
420     }
421 }
422
423 macro_rules! impl_arena_allocatable_decoder {
424     ([]$args:tt) => {};
425     ([decode $(, $attrs:ident)*]
426      [$name:ident: $ty:ty]) => {
427         impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for $ty {
428             #[inline]
429             fn decode(decoder: &mut D) -> &'tcx Self {
430                 decode_arena_allocable(decoder)
431             }
432         }
433
434         impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [$ty] {
435             #[inline]
436             fn decode(decoder: &mut D) -> &'tcx Self {
437                 decode_arena_allocable_slice(decoder)
438             }
439         }
440     };
441     ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
442         impl_arena_allocatable_decoder!([$($attrs),*]$args);
443     };
444 }
445
446 macro_rules! impl_arena_allocatable_decoders {
447     ([$($a:tt $name:ident: $ty:ty,)*]) => {
448         $(
449             impl_arena_allocatable_decoder!($a [$name: $ty]);
450         )*
451     }
452 }
453
454 rustc_hir::arena_types!(impl_arena_allocatable_decoders);
455 arena_types!(impl_arena_allocatable_decoders);
456
457 #[macro_export]
458 macro_rules! implement_ty_decoder {
459     ($DecoderName:ident <$($typaram:tt),*>) => {
460         mod __ty_decoder_impl {
461             use std::borrow::Cow;
462             use rustc_serialize::Decoder;
463
464             use super::$DecoderName;
465
466             impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
467                 $crate::__impl_decoder_methods! {
468                     read_u128 -> u128;
469                     read_u64 -> u64;
470                     read_u32 -> u32;
471                     read_u16 -> u16;
472                     read_u8 -> u8;
473                     read_usize -> usize;
474
475                     read_i128 -> i128;
476                     read_i64 -> i64;
477                     read_i32 -> i32;
478                     read_i16 -> i16;
479                     read_i8 -> i8;
480                     read_isize -> isize;
481
482                     read_bool -> bool;
483                     read_f64 -> f64;
484                     read_f32 -> f32;
485                     read_char -> char;
486                     read_str -> &str;
487                 }
488
489                 #[inline]
490                 fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
491                     self.opaque.read_raw_bytes(len)
492                 }
493             }
494         }
495     }
496 }
497
498 macro_rules! impl_binder_encode_decode {
499     ($($t:ty),+ $(,)?) => {
500         $(
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)
505                 }
506             }
507             impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, $t> {
508                 fn decode(decoder: &mut D) -> Self {
509                     let bound_vars = Decodable::decode(decoder);
510                     ty::Binder::bind_with_vars(Decodable::decode(decoder), bound_vars)
511                 }
512             }
513         )*
514     }
515 }
516
517 impl_binder_encode_decode! {
518     &'tcx ty::List<Ty<'tcx>>,
519     ty::FnSig<'tcx>,
520     ty::ExistentialPredicate<'tcx>,
521     ty::TraitRef<'tcx>,
522     Vec<ty::GeneratorInteriorTypeCause<'tcx>>,
523 }