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