]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/codec.rs
Rollup merge of #80022 - ssomers:btree_cleanup_8, 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, Allocation},
14 };
15 use crate::ty::subst::SubstsRef;
16 use crate::ty::{self, List, Ty, TyCtxt};
17 use rustc_data_structures::fx::FxHashMap;
18 use rustc_hir::def_id::{CrateNum, DefId};
19 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
20 use rustc_span::Span;
21 use std::convert::{TryFrom, TryInto};
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::Predicate<'tcx> {
47     type Variant = ty::PredicateKind<'tcx>;
48     fn variant(&self) -> &Self::Variant {
49         self.kind()
50     }
51 }
52
53 pub trait OpaqueEncoder: Encoder {
54     fn opaque(&mut self) -> &mut rustc_serialize::opaque::Encoder;
55     fn encoder_position(&self) -> usize;
56 }
57
58 impl OpaqueEncoder for rustc_serialize::opaque::Encoder {
59     #[inline]
60     fn opaque(&mut self) -> &mut rustc_serialize::opaque::Encoder {
61         self
62     }
63     #[inline]
64     fn encoder_position(&self) -> usize {
65         self.position()
66     }
67 }
68
69 pub trait TyEncoder<'tcx>: Encoder {
70     const CLEAR_CROSS_CRATE: bool;
71
72     fn position(&self) -> usize;
73     fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize>;
74     fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::Predicate<'tcx>, usize>;
75     fn encode_alloc_id(&mut self, alloc_id: &AllocId) -> Result<(), Self::Error>;
76 }
77
78 /// Trait for decoding to a reference.
79 ///
80 /// This is a separate trait from `Decodable` so that we can implement it for
81 /// upstream types, such as `FxHashSet`.
82 ///
83 /// The `TyDecodable` derive macro will use this trait for fields that are
84 /// references (and don't use a type alias to hide that).
85 ///
86 /// `Decodable` can still be implemented in cases where `Decodable` is required
87 /// by a trait bound.
88 pub trait RefDecodable<'tcx, D: TyDecoder<'tcx>> {
89     fn decode(d: &mut D) -> Result<&'tcx Self, D::Error>;
90 }
91
92 /// Encode the given value or a previously cached shorthand.
93 pub fn encode_with_shorthand<E, T, M>(encoder: &mut E, value: &T, cache: M) -> Result<(), E::Error>
94 where
95     E: TyEncoder<'tcx>,
96     M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap<T, usize>,
97     T: EncodableWithShorthand<'tcx, E>,
98     <T::Variant as DiscriminantKind>::Discriminant: Ord + TryFrom<usize>,
99 {
100     let existing_shorthand = cache(encoder).get(value).copied();
101     if let Some(shorthand) = existing_shorthand {
102         return encoder.emit_usize(shorthand);
103     }
104
105     let variant = value.variant();
106
107     let start = encoder.position();
108     variant.encode(encoder)?;
109     let len = encoder.position() - start;
110
111     // The shorthand encoding uses the same usize as the
112     // discriminant, with an offset so they can't conflict.
113     let discriminant = intrinsics::discriminant_value(variant);
114     assert!(discriminant < SHORTHAND_OFFSET.try_into().ok().unwrap());
115
116     let shorthand = start + SHORTHAND_OFFSET;
117
118     // Get the number of bits that leb128 could fit
119     // in the same space as the fully encoded type.
120     let leb128_bits = len * 7;
121
122     // Check that the shorthand is a not longer than the
123     // full encoding itself, i.e., it's an obvious win.
124     if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
125         cache(encoder).insert(*value, shorthand);
126     }
127
128     Ok(())
129 }
130
131 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Ty<'tcx> {
132     fn encode(&self, e: &mut E) -> Result<(), E::Error> {
133         encode_with_shorthand(e, self, TyEncoder::type_shorthands)
134     }
135 }
136
137 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Predicate<'tcx> {
138     fn encode(&self, e: &mut E) -> Result<(), E::Error> {
139         encode_with_shorthand(e, self, TyEncoder::predicate_shorthands)
140     }
141 }
142
143 impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for AllocId {
144     fn encode(&self, e: &mut E) -> Result<(), E::Error> {
145         e.encode_alloc_id(self)
146     }
147 }
148
149 macro_rules! encodable_via_deref {
150     ($($t:ty),+) => {
151         $(impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for $t {
152             fn encode(&self, e: &mut E) -> Result<(), E::Error> {
153                 (**self).encode(e)
154             }
155         })*
156     }
157 }
158
159 encodable_via_deref! {
160     &'tcx ty::TypeckResults<'tcx>,
161     ty::Region<'tcx>,
162     &'tcx mir::Body<'tcx>,
163     &'tcx mir::UnsafetyCheckResult,
164     &'tcx mir::BorrowCheckResult<'tcx>,
165     &'tcx mir::coverage::CodeRegion
166 }
167
168 pub trait TyDecoder<'tcx>: Decoder {
169     const CLEAR_CROSS_CRATE: bool;
170
171     fn tcx(&self) -> TyCtxt<'tcx>;
172
173     fn peek_byte(&self) -> u8;
174
175     fn position(&self) -> usize;
176
177     fn cached_ty_for_shorthand<F>(
178         &mut self,
179         shorthand: usize,
180         or_insert_with: F,
181     ) -> Result<Ty<'tcx>, Self::Error>
182     where
183         F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>;
184
185     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
186     where
187         F: FnOnce(&mut Self) -> R;
188
189     fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum;
190
191     fn positioned_at_shorthand(&self) -> bool {
192         (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0
193     }
194
195     fn decode_alloc_id(&mut self) -> Result<AllocId, Self::Error>;
196 }
197
198 #[inline]
199 pub fn decode_arena_allocable<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
200     decoder: &mut D,
201 ) -> Result<&'tcx T, D::Error>
202 where
203     D: TyDecoder<'tcx>,
204 {
205     Ok(decoder.tcx().arena.alloc(Decodable::decode(decoder)?))
206 }
207
208 #[inline]
209 pub fn decode_arena_allocable_slice<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>(
210     decoder: &mut D,
211 ) -> Result<&'tcx [T], D::Error>
212 where
213     D: TyDecoder<'tcx>,
214 {
215     Ok(decoder.tcx().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder)?))
216 }
217
218 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Ty<'tcx> {
219     #[allow(rustc::usage_of_ty_tykind)]
220     fn decode(decoder: &mut D) -> Result<Ty<'tcx>, D::Error> {
221         // Handle shorthands first, if we have an usize > 0x80.
222         if decoder.positioned_at_shorthand() {
223             let pos = decoder.read_usize()?;
224             assert!(pos >= SHORTHAND_OFFSET);
225             let shorthand = pos - SHORTHAND_OFFSET;
226
227             decoder.cached_ty_for_shorthand(shorthand, |decoder| {
228                 decoder.with_position(shorthand, Ty::decode)
229             })
230         } else {
231             let tcx = decoder.tcx();
232             Ok(tcx.mk_ty(ty::TyKind::decode(decoder)?))
233         }
234     }
235 }
236
237 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Predicate<'tcx> {
238     fn decode(decoder: &mut D) -> Result<ty::Predicate<'tcx>, D::Error> {
239         // Handle shorthands first, if we have an usize > 0x80.
240         let predicate_kind = if decoder.positioned_at_shorthand() {
241             let pos = decoder.read_usize()?;
242             assert!(pos >= SHORTHAND_OFFSET);
243             let shorthand = pos - SHORTHAND_OFFSET;
244
245             decoder.with_position(shorthand, ty::PredicateKind::decode)
246         } else {
247             ty::PredicateKind::decode(decoder)
248         }?;
249         let predicate = decoder.tcx().mk_predicate(predicate_kind);
250         Ok(predicate)
251     }
252 }
253
254 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for SubstsRef<'tcx> {
255     fn decode(decoder: &mut D) -> Result<Self, D::Error> {
256         let len = decoder.read_usize()?;
257         let tcx = decoder.tcx();
258         Ok(tcx.mk_substs((0..len).map(|_| Decodable::decode(decoder)))?)
259     }
260 }
261
262 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for mir::Place<'tcx> {
263     fn decode(decoder: &mut D) -> Result<Self, D::Error> {
264         let local: mir::Local = Decodable::decode(decoder)?;
265         let len = decoder.read_usize()?;
266         let projection: &'tcx List<mir::PlaceElem<'tcx>> =
267             decoder.tcx().mk_place_elems((0..len).map(|_| Decodable::decode(decoder)))?;
268         Ok(mir::Place { local, projection })
269     }
270 }
271
272 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Region<'tcx> {
273     fn decode(decoder: &mut D) -> Result<Self, D::Error> {
274         Ok(decoder.tcx().mk_region(Decodable::decode(decoder)?))
275     }
276 }
277
278 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for CanonicalVarInfos<'tcx> {
279     fn decode(decoder: &mut D) -> Result<Self, D::Error> {
280         let len = decoder.read_usize()?;
281         let interned: Result<Vec<CanonicalVarInfo<'tcx>>, _> =
282             (0..len).map(|_| Decodable::decode(decoder)).collect();
283         Ok(decoder.tcx().intern_canonical_var_infos(interned?.as_slice()))
284     }
285 }
286
287 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AllocId {
288     fn decode(decoder: &mut D) -> Result<Self, D::Error> {
289         decoder.decode_alloc_id()
290     }
291 }
292
293 impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::SymbolName<'tcx> {
294     fn decode(decoder: &mut D) -> Result<Self, D::Error> {
295         Ok(ty::SymbolName::new(decoder.tcx(), &decoder.read_str()?))
296     }
297 }
298
299 macro_rules! impl_decodable_via_ref {
300     ($($t:ty),+) => {
301         $(impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for $t {
302             fn decode(decoder: &mut D) -> Result<Self, D::Error> {
303                 RefDecodable::decode(decoder)
304             }
305         })*
306     }
307 }
308
309 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::AdtDef {
310     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
311         let def_id = <DefId as Decodable<D>>::decode(decoder)?;
312         Ok(decoder.tcx().adt_def(def_id))
313     }
314 }
315
316 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> {
317     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
318         let len = decoder.read_usize()?;
319         Ok(decoder.tcx().mk_type_list((0..len).map(|_| Decodable::decode(decoder)))?)
320     }
321 }
322
323 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<ty::ExistentialPredicate<'tcx>> {
324     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
325         let len = decoder.read_usize()?;
326         Ok(decoder.tcx().mk_existential_predicates((0..len).map(|_| Decodable::decode(decoder)))?)
327     }
328 }
329
330 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::Const<'tcx> {
331     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
332         Ok(decoder.tcx().mk_const(Decodable::decode(decoder)?))
333     }
334 }
335
336 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for Allocation {
337     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
338         Ok(decoder.tcx().intern_const_alloc(Decodable::decode(decoder)?))
339     }
340 }
341
342 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] {
343     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
344         Ok(decoder.tcx().arena.alloc_from_iter(
345             (0..decoder.read_usize()?)
346                 .map(|_| Decodable::decode(decoder))
347                 .collect::<Result<Vec<_>, _>>()?,
348         ))
349     }
350 }
351
352 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [mir::abstract_const::Node<'tcx>] {
353     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
354         Ok(decoder.tcx().arena.alloc_from_iter(
355             (0..decoder.read_usize()?)
356                 .map(|_| Decodable::decode(decoder))
357                 .collect::<Result<Vec<_>, _>>()?,
358         ))
359     }
360 }
361
362 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [mir::abstract_const::NodeId] {
363     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
364         Ok(decoder.tcx().arena.alloc_from_iter(
365             (0..decoder.read_usize()?)
366                 .map(|_| Decodable::decode(decoder))
367                 .collect::<Result<Vec<_>, _>>()?,
368         ))
369     }
370 }
371
372 impl_decodable_via_ref! {
373     &'tcx ty::TypeckResults<'tcx>,
374     &'tcx ty::List<Ty<'tcx>>,
375     &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
376     &'tcx Allocation,
377     &'tcx mir::Body<'tcx>,
378     &'tcx mir::UnsafetyCheckResult,
379     &'tcx mir::BorrowCheckResult<'tcx>,
380     &'tcx mir::coverage::CodeRegion
381 }
382
383 #[macro_export]
384 macro_rules! __impl_decoder_methods {
385     ($($name:ident -> $ty:ty;)*) => {
386         $(
387             #[inline]
388             fn $name(&mut self) -> Result<$ty, Self::Error> {
389                 self.opaque.$name()
390             }
391         )*
392     }
393 }
394
395 macro_rules! impl_arena_allocatable_decoder {
396     ([]$args:tt) => {};
397     ([decode $(, $attrs:ident)*]
398      [[$name:ident: $ty:ty], $tcx:lifetime]) => {
399         impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for $ty {
400             #[inline]
401             fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
402                 decode_arena_allocable(decoder)
403             }
404         }
405
406         impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for [$ty] {
407             #[inline]
408             fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
409                 decode_arena_allocable_slice(decoder)
410             }
411         }
412     };
413     ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
414         impl_arena_allocatable_decoder!([$($attrs),*]$args);
415     };
416 }
417
418 macro_rules! impl_arena_allocatable_decoders {
419     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
420         $(
421             impl_arena_allocatable_decoder!($a [[$name: $ty], $tcx]);
422         )*
423     }
424 }
425
426 rustc_hir::arena_types!(impl_arena_allocatable_decoders, [], 'tcx);
427 arena_types!(impl_arena_allocatable_decoders, [], 'tcx);
428
429 #[macro_export]
430 macro_rules! implement_ty_decoder {
431     ($DecoderName:ident <$($typaram:tt),*>) => {
432         mod __ty_decoder_impl {
433             use std::borrow::Cow;
434             use rustc_serialize::Decoder;
435
436             use super::$DecoderName;
437
438             impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
439                 type Error = String;
440
441                 $crate::__impl_decoder_methods! {
442                     read_nil -> ();
443
444                     read_u128 -> u128;
445                     read_u64 -> u64;
446                     read_u32 -> u32;
447                     read_u16 -> u16;
448                     read_u8 -> u8;
449                     read_usize -> usize;
450
451                     read_i128 -> i128;
452                     read_i64 -> i64;
453                     read_i32 -> i32;
454                     read_i16 -> i16;
455                     read_i8 -> i8;
456                     read_isize -> isize;
457
458                     read_bool -> bool;
459                     read_f64 -> f64;
460                     read_f32 -> f32;
461                     read_char -> char;
462                     read_str -> Cow<'_, str>;
463                 }
464
465                 fn error(&mut self, err: &str) -> Self::Error {
466                     self.opaque.error(err)
467                 }
468             }
469         }
470     }
471 }