]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/codec.rs
Auto merge of #102596 - scottmcm:option-bool-calloc, r=Mark-Simulacrum
[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::traits;
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};
21 use rustc_span::Span;
22 pub use rustc_type_ir::{TyDecoder, TyEncoder};
23 use std::hash::Hash;
24 use std::intrinsics;
25 use std::marker::DiscriminantKind;
26
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;
31
32 pub trait EncodableWithShorthand<E: TyEncoder>: Copy + Eq + Hash {
33     type Variant: Encodable<E>;
34     fn variant(&self) -> &Self::Variant;
35 }
36
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>;
40
41     #[inline]
42     fn variant(&self) -> &Self::Variant {
43         self.kind()
44     }
45 }
46
47 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> EncodableWithShorthand<E> for ty::PredicateKind<'tcx> {
48     type Variant = ty::PredicateKind<'tcx>;
49
50     #[inline]
51     fn variant(&self) -> &Self::Variant {
52         self
53     }
54 }
55
56 /// Trait for decoding to a reference.
57 ///
58 /// This is a separate trait from `Decodable` so that we can implement it for
59 /// upstream types, such as `FxHashSet`.
60 ///
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).
63 ///
64 /// `Decodable` can still be implemented in cases where `Decodable` is required
65 /// by a trait bound.
66 pub trait RefDecodable<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> {
67     fn decode(d: &mut D) -> &'tcx Self;
68 }
69
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)
72 where
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>,
78 {
79     let existing_shorthand = cache(encoder).get(value).copied();
80     if let Some(shorthand) = existing_shorthand {
81         encoder.emit_usize(shorthand);
82         return;
83     }
84
85     let variant = value.variant();
86
87     let start = encoder.position();
88     variant.encode(encoder);
89     let len = encoder.position() - start;
90
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);
95
96     let shorthand = start + SHORTHAND_OFFSET;
97
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;
101
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);
106     }
107 }
108
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);
112     }
113 }
114
115 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E>
116     for ty::Binder<'tcx, ty::PredicateKind<'tcx>>
117 {
118     fn encode(&self, e: &mut E) {
119         self.bound_vars().encode(e);
120         encode_with_shorthand(e, &self.skip_binder(), TyEncoder::predicate_shorthands);
121     }
122 }
123
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);
127     }
128 }
129
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);
133     }
134 }
135
136 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Const<'tcx> {
137     fn encode(&self, e: &mut E) {
138         self.0.0.encode(e);
139     }
140 }
141
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)
145     }
146 }
147
148 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for AdtDef<'tcx> {
149     fn encode(&self, e: &mut E) {
150         self.0.0.encode(e)
151     }
152 }
153
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)
157     }
158 }
159
160 #[inline]
161 fn decode_arena_allocable<
162     'tcx,
163     D: TyDecoder<I = TyCtxt<'tcx>>,
164     T: ArenaAllocatable<'tcx> + Decodable<D>,
165 >(
166     decoder: &mut D,
167 ) -> &'tcx T
168 where
169     D: TyDecoder,
170 {
171     decoder.interner().arena.alloc(Decodable::decode(decoder))
172 }
173
174 #[inline]
175 fn decode_arena_allocable_slice<
176     'tcx,
177     D: TyDecoder<I = TyCtxt<'tcx>>,
178     T: ArenaAllocatable<'tcx> + Decodable<D>,
179 >(
180     decoder: &mut D,
181 ) -> &'tcx [T]
182 where
183     D: TyDecoder,
184 {
185     decoder.interner().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder))
186 }
187
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;
196
197             decoder.cached_ty_for_shorthand(shorthand, |decoder| {
198                 decoder.with_position(shorthand, Ty::decode)
199             })
200         } else {
201             let tcx = decoder.interner();
202             tcx.mk_ty(rustc_type_ir::TyKind::decode(decoder))
203         }
204     }
205 }
206
207 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D>
208     for ty::Binder<'tcx, ty::PredicateKind<'tcx>>
209 {
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;
218
219                 decoder.with_position(shorthand, ty::PredicateKind::decode)
220             } else {
221                 ty::PredicateKind::decode(decoder)
222             },
223             bound_vars,
224         )
225     }
226 }
227
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)
232     }
233 }
234
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();
239         tcx.mk_substs(
240             (0..len).map::<ty::subst::GenericArg<'tcx>, _>(|_| Decodable::decode(decoder)),
241         )
242     }
243 }
244
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)),
251         );
252         mir::Place { local, projection }
253     }
254 }
255
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))
259     }
260 }
261
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())
268     }
269 }
270
271 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for AllocId {
272     fn decode(decoder: &mut D) -> Self {
273         decoder.decode_alloc_id()
274     }
275 }
276
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())
280     }
281 }
282
283 macro_rules! impl_decodable_via_ref {
284     ($($t:ty),+) => {
285         $(impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for $t {
286             fn decode(decoder: &mut D) -> Self {
287                 RefDecodable::decode(decoder)
288             }
289         })*
290     }
291 }
292
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)))
297     }
298 }
299
300 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D>
301     for ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>
302 {
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)),
307         )
308     }
309 }
310
311 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Const<'tcx> {
312     fn decode(decoder: &mut D) -> Self {
313         decoder.interner().mk_const(Decodable::decode(decoder))
314     }
315 }
316
317 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] {
318     fn decode(decoder: &mut D) -> &'tcx Self {
319         decoder.interner().arena.alloc_from_iter(
320             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
321         )
322     }
323 }
324
325 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ConstAllocation<'tcx> {
326     fn decode(decoder: &mut D) -> Self {
327         decoder.interner().intern_const_alloc(Decodable::decode(decoder))
328     }
329 }
330
331 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for AdtDef<'tcx> {
332     fn decode(decoder: &mut D) -> Self {
333         decoder.interner().intern_adt_def(Decodable::decode(decoder))
334     }
335 }
336
337 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D>
338     for [(ty::Predicate<'tcx>, Span)]
339 {
340     fn decode(decoder: &mut D) -> &'tcx Self {
341         decoder.interner().arena.alloc_from_iter(
342             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
343         )
344     }
345 }
346
347 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D>
348     for [ty::abstract_const::Node<'tcx>]
349 {
350     fn decode(decoder: &mut D) -> &'tcx Self {
351         decoder.interner().arena.alloc_from_iter(
352             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
353         )
354     }
355 }
356
357 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D>
358     for [ty::abstract_const::NodeId]
359 {
360     fn decode(decoder: &mut D) -> &'tcx Self {
361         decoder.interner().arena.alloc_from_iter(
362             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
363         )
364     }
365 }
366
367 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D>
368     for ty::List<ty::BoundVariableKind>
369 {
370     fn decode(decoder: &mut D) -> &'tcx Self {
371         let len = decoder.read_usize();
372         decoder.interner().mk_bound_variable_kinds(
373             (0..len).map::<ty::BoundVariableKind, _>(|_| Decodable::decode(decoder)),
374         )
375     }
376 }
377
378 impl_decodable_via_ref! {
379     &'tcx ty::TypeckResults<'tcx>,
380     &'tcx ty::List<Ty<'tcx>>,
381     &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
382     &'tcx traits::ImplSource<'tcx, ()>,
383     &'tcx mir::Body<'tcx>,
384     &'tcx mir::UnsafetyCheckResult,
385     &'tcx mir::BorrowCheckResult<'tcx>,
386     &'tcx mir::coverage::CodeRegion,
387     &'tcx ty::List<ty::BoundVariableKind>
388 }
389
390 #[macro_export]
391 macro_rules! __impl_decoder_methods {
392     ($($name:ident -> $ty:ty;)*) => {
393         $(
394             #[inline]
395             fn $name(&mut self) -> $ty {
396                 self.opaque.$name()
397             }
398         )*
399     }
400 }
401
402 macro_rules! impl_arena_allocatable_decoder {
403     ([]$args:tt) => {};
404     ([decode $(, $attrs:ident)*]
405      [$name:ident: $ty:ty]) => {
406         impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for $ty {
407             #[inline]
408             fn decode(decoder: &mut D) -> &'tcx Self {
409                 decode_arena_allocable(decoder)
410             }
411         }
412
413         impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [$ty] {
414             #[inline]
415             fn decode(decoder: &mut D) -> &'tcx Self {
416                 decode_arena_allocable_slice(decoder)
417             }
418         }
419     };
420 }
421
422 macro_rules! impl_arena_allocatable_decoders {
423     ([$($a:tt $name:ident: $ty:ty,)*]) => {
424         $(
425             impl_arena_allocatable_decoder!($a [$name: $ty]);
426         )*
427     }
428 }
429
430 rustc_hir::arena_types!(impl_arena_allocatable_decoders);
431 arena_types!(impl_arena_allocatable_decoders);
432
433 macro_rules! impl_arena_copy_decoder {
434     (<$tcx:tt> $($ty:ty,)*) => {
435         $(impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for $ty {
436             #[inline]
437             fn decode(decoder: &mut D) -> &'tcx Self {
438                 decoder.interner().arena.alloc(Decodable::decode(decoder))
439             }
440         }
441
442         impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [$ty] {
443             #[inline]
444             fn decode(decoder: &mut D) -> &'tcx Self {
445                 decoder.interner().arena.alloc_from_iter(<Vec<_> as Decodable<D>>::decode(decoder))
446             }
447         })*
448     };
449 }
450
451 impl_arena_copy_decoder! {<'tcx>
452     Span,
453     rustc_span::symbol::Ident,
454     ty::Variance,
455     rustc_span::def_id::DefId,
456     rustc_span::def_id::LocalDefId,
457     (rustc_middle::middle::exported_symbols::ExportedSymbol<'tcx>, rustc_middle::middle::exported_symbols::SymbolExportInfo),
458 }
459
460 #[macro_export]
461 macro_rules! implement_ty_decoder {
462     ($DecoderName:ident <$($typaram:tt),*>) => {
463         mod __ty_decoder_impl {
464             use std::borrow::Cow;
465             use rustc_serialize::Decoder;
466
467             use super::$DecoderName;
468
469             impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
470                 $crate::__impl_decoder_methods! {
471                     read_u128 -> u128;
472                     read_u64 -> u64;
473                     read_u32 -> u32;
474                     read_u16 -> u16;
475                     read_u8 -> u8;
476                     read_usize -> usize;
477
478                     read_i128 -> i128;
479                     read_i64 -> i64;
480                     read_i32 -> i32;
481                     read_i16 -> i16;
482                     read_i8 -> i8;
483                     read_isize -> isize;
484
485                     read_bool -> bool;
486                     read_f64 -> f64;
487                     read_f32 -> f32;
488                     read_char -> char;
489                     read_str -> &str;
490                 }
491
492                 #[inline]
493                 fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
494                     self.opaque.read_raw_bytes(len)
495                 }
496             }
497         }
498     }
499 }
500
501 macro_rules! impl_binder_encode_decode {
502     ($($t:ty),+ $(,)?) => {
503         $(
504             impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Binder<'tcx, $t> {
505                 fn encode(&self, e: &mut E) {
506                     self.bound_vars().encode(e);
507                     self.as_ref().skip_binder().encode(e);
508                 }
509             }
510             impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Binder<'tcx, $t> {
511                 fn decode(decoder: &mut D) -> Self {
512                     let bound_vars = Decodable::decode(decoder);
513                     ty::Binder::bind_with_vars(Decodable::decode(decoder), bound_vars)
514                 }
515             }
516         )*
517     }
518 }
519
520 impl_binder_encode_decode! {
521     &'tcx ty::List<Ty<'tcx>>,
522     ty::FnSig<'tcx>,
523     ty::ExistentialPredicate<'tcx>,
524     ty::TraitRef<'tcx>,
525     Vec<ty::GeneratorInteriorTypeCause<'tcx>>,
526     ty::ExistentialTraitRef<'tcx>,
527 }