]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/codec.rs
Rollup merge of #97232 - tshepang:typo, r=Dylan-DPC
[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, ConstAllocation},
14 };
15 use crate::thir;
16 use crate::traits;
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};
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 ConstAllocation<'tcx> {
154     fn encode(&self, e: &mut E) -> Result<(), E::Error> {
155         self.inner().encode(e)
156     }
157 }
158
159 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for AdtDef<'tcx> {
160     fn encode(&self, e: &mut E) -> Result<(), E::Error> {
161         self.0.0.encode(e)
162     }
163 }
164
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)
168     }
169 }
170
171 pub trait TyDecoder<'tcx>: Decoder {
172     const CLEAR_CROSS_CRATE: bool;
173
174     fn tcx(&self) -> TyCtxt<'tcx>;
175
176     fn peek_byte(&self) -> u8;
177
178     fn position(&self) -> usize;
179
180     fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx>
181     where
182         F: FnOnce(&mut Self) -> Ty<'tcx>;
183
184     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
185     where
186         F: FnOnce(&mut Self) -> R;
187
188     fn positioned_at_shorthand(&self) -> bool {
189         (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0
190     }
191
192     fn decode_alloc_id(&mut self) -> AllocId;
193 }
194
195 #[inline]
196 fn decode_arena_allocable<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
197     decoder: &mut D,
198 ) -> &'tcx T
199 where
200     D: TyDecoder<'tcx>,
201 {
202     decoder.tcx().arena.alloc(Decodable::decode(decoder))
203 }
204
205 #[inline]
206 fn decode_arena_allocable_slice<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
207     decoder: &mut D,
208 ) -> &'tcx [T]
209 where
210     D: TyDecoder<'tcx>,
211 {
212     decoder.tcx().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder))
213 }
214
215 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Ty<'tcx> {
216     #[allow(rustc::usage_of_ty_tykind)]
217     fn decode(decoder: &mut D) -> Ty<'tcx> {
218         // Handle shorthands first, if we have a usize > 0x80.
219         if decoder.positioned_at_shorthand() {
220             let pos = decoder.read_usize();
221             assert!(pos >= SHORTHAND_OFFSET);
222             let shorthand = pos - SHORTHAND_OFFSET;
223
224             decoder.cached_ty_for_shorthand(shorthand, |decoder| {
225                 decoder.with_position(shorthand, Ty::decode)
226             })
227         } else {
228             let tcx = decoder.tcx();
229             tcx.mk_ty(ty::TyKind::decode(decoder))
230         }
231     }
232 }
233
234 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
235     fn decode(decoder: &mut D) -> ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
236         let bound_vars = Decodable::decode(decoder);
237         // Handle shorthands first, if we have a usize > 0x80.
238         ty::Binder::bind_with_vars(
239             if decoder.positioned_at_shorthand() {
240                 let pos = decoder.read_usize();
241                 assert!(pos >= SHORTHAND_OFFSET);
242                 let shorthand = pos - SHORTHAND_OFFSET;
243
244                 decoder.with_position(shorthand, ty::PredicateKind::decode)
245             } else {
246                 ty::PredicateKind::decode(decoder)
247             },
248             bound_vars,
249         )
250     }
251 }
252
253 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Predicate<'tcx> {
254     fn decode(decoder: &mut D) -> ty::Predicate<'tcx> {
255         let predicate_kind = Decodable::decode(decoder);
256         decoder.tcx().mk_predicate(predicate_kind)
257     }
258 }
259
260 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for SubstsRef<'tcx> {
261     fn decode(decoder: &mut D) -> Self {
262         let len = decoder.read_usize();
263         let tcx = decoder.tcx();
264         tcx.mk_substs(
265             (0..len).map::<ty::subst::GenericArg<'tcx>, _>(|_| Decodable::decode(decoder)),
266         )
267     }
268 }
269
270 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for mir::Place<'tcx> {
271     fn decode(decoder: &mut D) -> Self {
272         let local: mir::Local = Decodable::decode(decoder);
273         let len = decoder.read_usize();
274         let projection = decoder.tcx().mk_place_elems(
275             (0..len).map::<mir::PlaceElem<'tcx>, _>(|_| Decodable::decode(decoder)),
276         );
277         mir::Place { local, projection }
278     }
279 }
280
281 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Region<'tcx> {
282     fn decode(decoder: &mut D) -> Self {
283         decoder.tcx().mk_region(Decodable::decode(decoder))
284     }
285 }
286
287 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for CanonicalVarInfos<'tcx> {
288     fn decode(decoder: &mut D) -> Self {
289         let len = decoder.read_usize();
290         let interned: Vec<CanonicalVarInfo<'tcx>> =
291             (0..len).map(|_| Decodable::decode(decoder)).collect();
292         decoder.tcx().intern_canonical_var_infos(interned.as_slice())
293     }
294 }
295
296 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AllocId {
297     fn decode(decoder: &mut D) -> Self {
298         decoder.decode_alloc_id()
299     }
300 }
301
302 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::SymbolName<'tcx> {
303     fn decode(decoder: &mut D) -> Self {
304         ty::SymbolName::new(decoder.tcx(), &decoder.read_str())
305     }
306 }
307
308 macro_rules! impl_decodable_via_ref {
309     ($($t:ty),+) => {
310         $(impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for $t {
311             fn decode(decoder: &mut D) -> Self {
312                 RefDecodable::decode(decoder)
313             }
314         })*
315     }
316 }
317
318 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> {
319     fn decode(decoder: &mut D) -> &'tcx Self {
320         let len = decoder.read_usize();
321         decoder.tcx().mk_type_list((0..len).map::<Ty<'tcx>, _>(|_| Decodable::decode(decoder)))
322     }
323 }
324
325 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D>
326     for ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>
327 {
328     fn decode(decoder: &mut D) -> &'tcx Self {
329         let len = decoder.read_usize();
330         decoder.tcx().mk_poly_existential_predicates(
331             (0..len).map::<ty::Binder<'tcx, _>, _>(|_| Decodable::decode(decoder)),
332         )
333     }
334 }
335
336 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Const<'tcx> {
337     fn decode(decoder: &mut D) -> Self {
338         decoder.tcx().mk_const(Decodable::decode(decoder))
339     }
340 }
341
342 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] {
343     fn decode(decoder: &mut D) -> &'tcx Self {
344         decoder.tcx().arena.alloc_from_iter(
345             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
346         )
347     }
348 }
349
350 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ConstAllocation<'tcx> {
351     fn decode(decoder: &mut D) -> Self {
352         decoder.tcx().intern_const_alloc(Decodable::decode(decoder))
353     }
354 }
355
356 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AdtDef<'tcx> {
357     fn decode(decoder: &mut D) -> Self {
358         decoder.tcx().intern_adt_def(Decodable::decode(decoder))
359     }
360 }
361
362 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] {
363     fn decode(decoder: &mut D) -> &'tcx Self {
364         decoder.tcx().arena.alloc_from_iter(
365             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
366         )
367     }
368 }
369
370 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [thir::abstract_const::Node<'tcx>] {
371     fn decode(decoder: &mut D) -> &'tcx Self {
372         decoder.tcx().arena.alloc_from_iter(
373             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
374         )
375     }
376 }
377
378 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [thir::abstract_const::NodeId] {
379     fn decode(decoder: &mut D) -> &'tcx Self {
380         decoder.tcx().arena.alloc_from_iter(
381             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
382         )
383     }
384 }
385
386 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<ty::BoundVariableKind> {
387     fn decode(decoder: &mut D) -> &'tcx Self {
388         let len = decoder.read_usize();
389         decoder.tcx().mk_bound_variable_kinds(
390             (0..len).map::<ty::BoundVariableKind, _>(|_| Decodable::decode(decoder)),
391         )
392     }
393 }
394
395 impl_decodable_via_ref! {
396     &'tcx ty::TypeckResults<'tcx>,
397     &'tcx ty::List<Ty<'tcx>>,
398     &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
399     &'tcx traits::ImplSource<'tcx, ()>,
400     &'tcx mir::Body<'tcx>,
401     &'tcx mir::UnsafetyCheckResult,
402     &'tcx mir::BorrowCheckResult<'tcx>,
403     &'tcx mir::coverage::CodeRegion,
404     &'tcx ty::List<ty::BoundVariableKind>
405 }
406
407 #[macro_export]
408 macro_rules! __impl_decoder_methods {
409     ($($name:ident -> $ty:ty;)*) => {
410         $(
411             #[inline]
412             fn $name(&mut self) -> $ty {
413                 self.opaque.$name()
414             }
415         )*
416     }
417 }
418
419 macro_rules! impl_arena_allocatable_decoder {
420     ([]$args:tt) => {};
421     ([decode $(, $attrs:ident)*]
422      [$name:ident: $ty:ty]) => {
423         impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for $ty {
424             #[inline]
425             fn decode(decoder: &mut D) -> &'tcx Self {
426                 decode_arena_allocable(decoder)
427             }
428         }
429
430         impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [$ty] {
431             #[inline]
432             fn decode(decoder: &mut D) -> &'tcx Self {
433                 decode_arena_allocable_slice(decoder)
434             }
435         }
436     };
437 }
438
439 macro_rules! impl_arena_allocatable_decoders {
440     ([$($a:tt $name:ident: $ty:ty,)*]) => {
441         $(
442             impl_arena_allocatable_decoder!($a [$name: $ty]);
443         )*
444     }
445 }
446
447 rustc_hir::arena_types!(impl_arena_allocatable_decoders);
448 arena_types!(impl_arena_allocatable_decoders);
449
450 macro_rules! impl_arena_copy_decoder {
451     (<$tcx:tt> $($ty:ty,)*) => {
452         $(impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for $ty {
453             #[inline]
454             fn decode(decoder: &mut D) -> &'tcx Self {
455                 decoder.tcx().arena.alloc(Decodable::decode(decoder))
456             }
457         }
458
459         impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [$ty] {
460             #[inline]
461             fn decode(decoder: &mut D) -> &'tcx Self {
462                 decoder.tcx().arena.alloc_from_iter(<Vec<_> as Decodable<D>>::decode(decoder))
463             }
464         })*
465     };
466 }
467
468 impl_arena_copy_decoder! {<'tcx>
469     Span,
470     rustc_span::symbol::Ident,
471     ty::Variance,
472     rustc_span::def_id::DefId,
473     rustc_span::def_id::LocalDefId,
474     (rustc_middle::middle::exported_symbols::ExportedSymbol<'tcx>, rustc_middle::middle::exported_symbols::SymbolExportInfo),
475 }
476
477 #[macro_export]
478 macro_rules! implement_ty_decoder {
479     ($DecoderName:ident <$($typaram:tt),*>) => {
480         mod __ty_decoder_impl {
481             use std::borrow::Cow;
482             use rustc_serialize::Decoder;
483
484             use super::$DecoderName;
485
486             impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
487                 $crate::__impl_decoder_methods! {
488                     read_u128 -> u128;
489                     read_u64 -> u64;
490                     read_u32 -> u32;
491                     read_u16 -> u16;
492                     read_u8 -> u8;
493                     read_usize -> usize;
494
495                     read_i128 -> i128;
496                     read_i64 -> i64;
497                     read_i32 -> i32;
498                     read_i16 -> i16;
499                     read_i8 -> i8;
500                     read_isize -> isize;
501
502                     read_bool -> bool;
503                     read_f64 -> f64;
504                     read_f32 -> f32;
505                     read_char -> char;
506                     read_str -> &str;
507                 }
508
509                 #[inline]
510                 fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
511                     self.opaque.read_raw_bytes(len)
512                 }
513             }
514         }
515     }
516 }
517
518 macro_rules! impl_binder_encode_decode {
519     ($($t:ty),+ $(,)?) => {
520         $(
521             impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Binder<'tcx, $t> {
522                 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
523                     self.bound_vars().encode(e)?;
524                     self.as_ref().skip_binder().encode(e)
525                 }
526             }
527             impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, $t> {
528                 fn decode(decoder: &mut D) -> Self {
529                     let bound_vars = Decodable::decode(decoder);
530                     ty::Binder::bind_with_vars(Decodable::decode(decoder), bound_vars)
531                 }
532             }
533         )*
534     }
535 }
536
537 impl_binder_encode_decode! {
538     &'tcx ty::List<Ty<'tcx>>,
539     ty::FnSig<'tcx>,
540     ty::ExistentialPredicate<'tcx>,
541     ty::TraitRef<'tcx>,
542     Vec<ty::GeneratorInteriorTypeCause<'tcx>>,
543 }