]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/codec.rs
Merge remote-tracking branch 'origin/master' into frewsxcv-san
[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>
324     for ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>
325 {
326     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
327         let len = decoder.read_usize()?;
328         Ok(decoder
329             .tcx()
330             .mk_poly_existential_predicates((0..len).map(|_| Decodable::decode(decoder)))?)
331     }
332 }
333
334 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::Const<'tcx> {
335     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
336         Ok(decoder.tcx().mk_const(Decodable::decode(decoder)?))
337     }
338 }
339
340 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for Allocation {
341     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
342         Ok(decoder.tcx().intern_const_alloc(Decodable::decode(decoder)?))
343     }
344 }
345
346 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] {
347     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
348         Ok(decoder.tcx().arena.alloc_from_iter(
349             (0..decoder.read_usize()?)
350                 .map(|_| Decodable::decode(decoder))
351                 .collect::<Result<Vec<_>, _>>()?,
352         ))
353     }
354 }
355
356 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [mir::abstract_const::Node<'tcx>] {
357     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
358         Ok(decoder.tcx().arena.alloc_from_iter(
359             (0..decoder.read_usize()?)
360                 .map(|_| Decodable::decode(decoder))
361                 .collect::<Result<Vec<_>, _>>()?,
362         ))
363     }
364 }
365
366 impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [mir::abstract_const::NodeId] {
367     fn decode(decoder: &mut D) -> Result<&'tcx Self, D::Error> {
368         Ok(decoder.tcx().arena.alloc_from_iter(
369             (0..decoder.read_usize()?)
370                 .map(|_| Decodable::decode(decoder))
371                 .collect::<Result<Vec<_>, _>>()?,
372         ))
373     }
374 }
375
376 impl_decodable_via_ref! {
377     &'tcx ty::TypeckResults<'tcx>,
378     &'tcx ty::List<Ty<'tcx>>,
379     &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
380     &'tcx Allocation,
381     &'tcx mir::Body<'tcx>,
382     &'tcx mir::UnsafetyCheckResult,
383     &'tcx mir::BorrowCheckResult<'tcx>,
384     &'tcx mir::coverage::CodeRegion
385 }
386
387 #[macro_export]
388 macro_rules! __impl_decoder_methods {
389     ($($name:ident -> $ty:ty;)*) => {
390         $(
391             #[inline]
392             fn $name(&mut self) -> Result<$ty, Self::Error> {
393                 self.opaque.$name()
394             }
395         )*
396     }
397 }
398
399 macro_rules! impl_arena_allocatable_decoder {
400     ([]$args:tt) => {};
401     ([decode $(, $attrs:ident)*]
402      [[$name:ident: $ty:ty], $tcx:lifetime]) => {
403         impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for $ty {
404             #[inline]
405             fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
406                 decode_arena_allocable(decoder)
407             }
408         }
409
410         impl<$tcx, D: TyDecoder<$tcx>> RefDecodable<$tcx, D> for [$ty] {
411             #[inline]
412             fn decode(decoder: &mut D) -> Result<&$tcx Self, D::Error> {
413                 decode_arena_allocable_slice(decoder)
414             }
415         }
416     };
417     ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
418         impl_arena_allocatable_decoder!([$($attrs),*]$args);
419     };
420 }
421
422 macro_rules! impl_arena_allocatable_decoders {
423     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
424         $(
425             impl_arena_allocatable_decoder!($a [[$name: $ty], $tcx]);
426         )*
427     }
428 }
429
430 rustc_hir::arena_types!(impl_arena_allocatable_decoders, [], 'tcx);
431 arena_types!(impl_arena_allocatable_decoders, [], 'tcx);
432
433 #[macro_export]
434 macro_rules! implement_ty_decoder {
435     ($DecoderName:ident <$($typaram:tt),*>) => {
436         mod __ty_decoder_impl {
437             use std::borrow::Cow;
438             use rustc_serialize::Decoder;
439
440             use super::$DecoderName;
441
442             impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
443                 type Error = String;
444
445                 $crate::__impl_decoder_methods! {
446                     read_nil -> ();
447
448                     read_u128 -> u128;
449                     read_u64 -> u64;
450                     read_u32 -> u32;
451                     read_u16 -> u16;
452                     read_u8 -> u8;
453                     read_usize -> usize;
454
455                     read_i128 -> i128;
456                     read_i64 -> i64;
457                     read_i32 -> i32;
458                     read_i16 -> i16;
459                     read_i8 -> i8;
460                     read_isize -> isize;
461
462                     read_bool -> bool;
463                     read_f64 -> f64;
464                     read_f32 -> f32;
465                     read_char -> char;
466                     read_str -> Cow<'_, str>;
467                 }
468
469                 fn error(&mut self, err: &str) -> Self::Error {
470                     self.opaque.error(err)
471                 }
472             }
473         }
474     }
475 }