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