]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_serialize/src/serialize.rs
Replace try_upvars_resolved with try_to_place
[rust.git] / compiler / rustc_serialize / src / serialize.rs
1 //! Support code for encoding and decoding types.
2
3 /*
4 Core encoding and decoding interfaces.
5 */
6
7 use std::alloc::Allocator;
8 use std::borrow::Cow;
9 use std::cell::{Cell, RefCell};
10 use std::marker::PhantomData;
11 use std::path;
12 use std::rc::Rc;
13 use std::sync::Arc;
14
15 /// A note about error handling.
16 ///
17 /// Encoders may be fallible, but in practice failure is rare and there are so
18 /// many nested calls that typical Rust error handling (via `Result` and `?`)
19 /// is pervasive and has non-trivial cost. Instead, impls of this trait must
20 /// implement a delayed error handling strategy. If a failure occurs, they
21 /// should record this internally, and all subsequent encoding operations can
22 /// be processed or ignored, whichever is appropriate. Then they should provide
23 /// a `finish` method that finishes up encoding. If the encoder is fallible,
24 /// `finish` should return a `Result` that indicates success or failure.
25 pub trait Encoder {
26     // Primitive types:
27     fn emit_usize(&mut self, v: usize);
28     fn emit_u128(&mut self, v: u128);
29     fn emit_u64(&mut self, v: u64);
30     fn emit_u32(&mut self, v: u32);
31     fn emit_u16(&mut self, v: u16);
32     fn emit_u8(&mut self, v: u8);
33     fn emit_isize(&mut self, v: isize);
34     fn emit_i128(&mut self, v: i128);
35     fn emit_i64(&mut self, v: i64);
36     fn emit_i32(&mut self, v: i32);
37     fn emit_i16(&mut self, v: i16);
38     fn emit_i8(&mut self, v: i8);
39     fn emit_bool(&mut self, v: bool);
40     fn emit_f64(&mut self, v: f64);
41     fn emit_f32(&mut self, v: f32);
42     fn emit_char(&mut self, v: char);
43     fn emit_str(&mut self, v: &str);
44     fn emit_raw_bytes(&mut self, s: &[u8]);
45
46     // Convenience for the derive macro:
47     fn emit_enum_variant<F>(&mut self, v_id: usize, f: F)
48     where
49         F: FnOnce(&mut Self),
50     {
51         self.emit_usize(v_id);
52         f(self);
53     }
54
55     // We put the field index in a const generic to allow the emit_usize to be
56     // compiled into a more efficient form. In practice, the variant index is
57     // known at compile-time, and that knowledge allows much more efficient
58     // codegen than we'd otherwise get. LLVM isn't always able to make the
59     // optimization that would otherwise be necessary here, likely due to the
60     // multiple levels of inlining and const-prop that are needed.
61     #[inline]
62     fn emit_fieldless_enum_variant<const ID: usize>(&mut self) {
63         self.emit_usize(ID)
64     }
65 }
66
67 // Note: all the methods in this trait are infallible, which may be surprising.
68 // They used to be fallible (i.e. return a `Result`) but many of the impls just
69 // panicked when something went wrong, and for the cases that didn't the
70 // top-level invocation would also just panic on failure. Switching to
71 // infallibility made things faster and lots of code a little simpler and more
72 // concise.
73 pub trait Decoder {
74     // Primitive types:
75     fn read_usize(&mut self) -> usize;
76     fn read_u128(&mut self) -> u128;
77     fn read_u64(&mut self) -> u64;
78     fn read_u32(&mut self) -> u32;
79     fn read_u16(&mut self) -> u16;
80     fn read_u8(&mut self) -> u8;
81     fn read_isize(&mut self) -> isize;
82     fn read_i128(&mut self) -> i128;
83     fn read_i64(&mut self) -> i64;
84     fn read_i32(&mut self) -> i32;
85     fn read_i16(&mut self) -> i16;
86     fn read_i8(&mut self) -> i8;
87     fn read_bool(&mut self) -> bool;
88     fn read_f64(&mut self) -> f64;
89     fn read_f32(&mut self) -> f32;
90     fn read_char(&mut self) -> char;
91     fn read_str(&mut self) -> &str;
92     fn read_raw_bytes(&mut self, len: usize) -> &[u8];
93 }
94
95 /// Trait for types that can be serialized
96 ///
97 /// This can be implemented using the `Encodable`, `TyEncodable` and
98 /// `MetadataEncodable` macros.
99 ///
100 /// * `Encodable` should be used in crates that don't depend on
101 ///   `rustc_middle`.
102 /// * `MetadataEncodable` is used in `rustc_metadata` for types that contain
103 ///   `rustc_metadata::rmeta::Lazy`.
104 /// * `TyEncodable` should be used for types that are only serialized in crate
105 ///   metadata or the incremental cache. This is most types in `rustc_middle`.
106 pub trait Encodable<S: Encoder> {
107     fn encode(&self, s: &mut S);
108 }
109
110 /// Trait for types that can be deserialized
111 ///
112 /// This can be implemented using the `Decodable`, `TyDecodable` and
113 /// `MetadataDecodable` macros.
114 ///
115 /// * `Decodable` should be used in crates that don't depend on
116 ///   `rustc_middle`.
117 /// * `MetadataDecodable` is used in `rustc_metadata` for types that contain
118 ///   `rustc_metadata::rmeta::Lazy`.
119 /// * `TyDecodable` should be used for types that are only serialized in crate
120 ///   metadata or the incremental cache. This is most types in `rustc_middle`.
121 pub trait Decodable<D: Decoder>: Sized {
122     fn decode(d: &mut D) -> Self;
123 }
124
125 macro_rules! direct_serialize_impls {
126     ($($ty:ident $emit_method:ident $read_method:ident),*) => {
127         $(
128             impl<S: Encoder> Encodable<S> for $ty {
129                 fn encode(&self, s: &mut S) {
130                     s.$emit_method(*self);
131                 }
132             }
133
134             impl<D: Decoder> Decodable<D> for $ty {
135                 fn decode(d: &mut D) -> $ty {
136                     d.$read_method()
137                 }
138             }
139         )*
140     }
141 }
142
143 direct_serialize_impls! {
144     usize emit_usize read_usize,
145     u8 emit_u8 read_u8,
146     u16 emit_u16 read_u16,
147     u32 emit_u32 read_u32,
148     u64 emit_u64 read_u64,
149     u128 emit_u128 read_u128,
150
151     isize emit_isize read_isize,
152     i8 emit_i8 read_i8,
153     i16 emit_i16 read_i16,
154     i32 emit_i32 read_i32,
155     i64 emit_i64 read_i64,
156     i128 emit_i128 read_i128,
157
158     f32 emit_f32 read_f32,
159     f64 emit_f64 read_f64,
160     bool emit_bool read_bool,
161     char emit_char read_char
162 }
163
164 impl<S: Encoder, T: ?Sized> Encodable<S> for &T
165 where
166     T: Encodable<S>,
167 {
168     fn encode(&self, s: &mut S) {
169         (**self).encode(s)
170     }
171 }
172
173 impl<S: Encoder> Encodable<S> for ! {
174     fn encode(&self, _s: &mut S) {
175         unreachable!();
176     }
177 }
178
179 impl<D: Decoder> Decodable<D> for ! {
180     fn decode(_d: &mut D) -> ! {
181         unreachable!()
182     }
183 }
184
185 impl<S: Encoder> Encodable<S> for ::std::num::NonZeroU32 {
186     fn encode(&self, s: &mut S) {
187         s.emit_u32(self.get());
188     }
189 }
190
191 impl<D: Decoder> Decodable<D> for ::std::num::NonZeroU32 {
192     fn decode(d: &mut D) -> Self {
193         ::std::num::NonZeroU32::new(d.read_u32()).unwrap()
194     }
195 }
196
197 impl<S: Encoder> Encodable<S> for str {
198     fn encode(&self, s: &mut S) {
199         s.emit_str(self);
200     }
201 }
202
203 impl<S: Encoder> Encodable<S> for String {
204     fn encode(&self, s: &mut S) {
205         s.emit_str(&self[..]);
206     }
207 }
208
209 impl<D: Decoder> Decodable<D> for String {
210     fn decode(d: &mut D) -> String {
211         d.read_str().to_owned()
212     }
213 }
214
215 impl<S: Encoder> Encodable<S> for () {
216     fn encode(&self, _s: &mut S) {}
217 }
218
219 impl<D: Decoder> Decodable<D> for () {
220     fn decode(_: &mut D) -> () {}
221 }
222
223 impl<S: Encoder, T> Encodable<S> for PhantomData<T> {
224     fn encode(&self, _s: &mut S) {}
225 }
226
227 impl<D: Decoder, T> Decodable<D> for PhantomData<T> {
228     fn decode(_: &mut D) -> PhantomData<T> {
229         PhantomData
230     }
231 }
232
233 impl<D: Decoder, A: Allocator + Default, T: Decodable<D>> Decodable<D> for Box<[T], A> {
234     fn decode(d: &mut D) -> Box<[T], A> {
235         let v: Vec<T, A> = Decodable::decode(d);
236         v.into_boxed_slice()
237     }
238 }
239
240 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Rc<T> {
241     fn encode(&self, s: &mut S) {
242         (**self).encode(s);
243     }
244 }
245
246 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Rc<T> {
247     fn decode(d: &mut D) -> Rc<T> {
248         Rc::new(Decodable::decode(d))
249     }
250 }
251
252 impl<S: Encoder, T: Encodable<S>> Encodable<S> for [T] {
253     default fn encode(&self, s: &mut S) {
254         s.emit_usize(self.len());
255         for e in self.iter() {
256             e.encode(s);
257         }
258     }
259 }
260
261 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Vec<T> {
262     fn encode(&self, s: &mut S) {
263         let slice: &[T] = self;
264         slice.encode(s);
265     }
266 }
267
268 impl<D: Decoder, T: Decodable<D>, A: Allocator + Default> Decodable<D> for Vec<T, A> {
269     default fn decode(d: &mut D) -> Vec<T, A> {
270         let len = d.read_usize();
271         let allocator = A::default();
272         // SAFETY: we set the capacity in advance, only write elements, and
273         // only set the length at the end once the writing has succeeded.
274         let mut vec = Vec::with_capacity_in(len, allocator);
275         unsafe {
276             let ptr: *mut T = vec.as_mut_ptr();
277             for i in 0..len {
278                 std::ptr::write(ptr.add(i), Decodable::decode(d));
279             }
280             vec.set_len(len);
281         }
282         vec
283     }
284 }
285
286 impl<S: Encoder, T: Encodable<S>, const N: usize> Encodable<S> for [T; N] {
287     fn encode(&self, s: &mut S) {
288         let slice: &[T] = self;
289         slice.encode(s);
290     }
291 }
292
293 impl<D: Decoder, const N: usize> Decodable<D> for [u8; N] {
294     fn decode(d: &mut D) -> [u8; N] {
295         let len = d.read_usize();
296         assert!(len == N);
297         let mut v = [0u8; N];
298         for i in 0..len {
299             v[i] = Decodable::decode(d);
300         }
301         v
302     }
303 }
304
305 impl<'a, S: Encoder, T: Encodable<S>> Encodable<S> for Cow<'a, [T]>
306 where
307     [T]: ToOwned<Owned = Vec<T>>,
308 {
309     fn encode(&self, s: &mut S) {
310         let slice: &[T] = self;
311         slice.encode(s);
312     }
313 }
314
315 impl<D: Decoder, T: Decodable<D> + ToOwned> Decodable<D> for Cow<'static, [T]>
316 where
317     [T]: ToOwned<Owned = Vec<T>>,
318 {
319     fn decode(d: &mut D) -> Cow<'static, [T]> {
320         let v: Vec<T> = Decodable::decode(d);
321         Cow::Owned(v)
322     }
323 }
324
325 impl<'a, S: Encoder> Encodable<S> for Cow<'a, str> {
326     fn encode(&self, s: &mut S) {
327         let val: &str = self;
328         val.encode(s)
329     }
330 }
331
332 impl<'a, D: Decoder> Decodable<D> for Cow<'a, str> {
333     fn decode(d: &mut D) -> Cow<'static, str> {
334         let v: String = Decodable::decode(d);
335         Cow::Owned(v)
336     }
337 }
338
339 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Option<T> {
340     fn encode(&self, s: &mut S) {
341         match *self {
342             None => s.emit_enum_variant(0, |_| {}),
343             Some(ref v) => s.emit_enum_variant(1, |s| v.encode(s)),
344         }
345     }
346 }
347
348 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Option<T> {
349     fn decode(d: &mut D) -> Option<T> {
350         match d.read_usize() {
351             0 => None,
352             1 => Some(Decodable::decode(d)),
353             _ => panic!("Encountered invalid discriminant while decoding `Option`."),
354         }
355     }
356 }
357
358 impl<S: Encoder, T1: Encodable<S>, T2: Encodable<S>> Encodable<S> for Result<T1, T2> {
359     fn encode(&self, s: &mut S) {
360         match *self {
361             Ok(ref v) => s.emit_enum_variant(0, |s| v.encode(s)),
362             Err(ref v) => s.emit_enum_variant(1, |s| v.encode(s)),
363         }
364     }
365 }
366
367 impl<D: Decoder, T1: Decodable<D>, T2: Decodable<D>> Decodable<D> for Result<T1, T2> {
368     fn decode(d: &mut D) -> Result<T1, T2> {
369         match d.read_usize() {
370             0 => Ok(T1::decode(d)),
371             1 => Err(T2::decode(d)),
372             _ => panic!("Encountered invalid discriminant while decoding `Result`."),
373         }
374     }
375 }
376
377 macro_rules! peel {
378     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
379 }
380
381 macro_rules! tuple {
382     () => ();
383     ( $($name:ident,)+ ) => (
384         impl<D: Decoder, $($name: Decodable<D>),+> Decodable<D> for ($($name,)+) {
385             fn decode(d: &mut D) -> ($($name,)+) {
386                 ($({ let element: $name = Decodable::decode(d); element },)+)
387             }
388         }
389         impl<S: Encoder, $($name: Encodable<S>),+> Encodable<S> for ($($name,)+) {
390             #[allow(non_snake_case)]
391             fn encode(&self, s: &mut S) {
392                 let ($(ref $name,)+) = *self;
393                 $($name.encode(s);)+
394             }
395         }
396         peel! { $($name,)+ }
397     )
398 }
399
400 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
401
402 impl<S: Encoder> Encodable<S> for path::Path {
403     fn encode(&self, e: &mut S) {
404         self.to_str().unwrap().encode(e);
405     }
406 }
407
408 impl<S: Encoder> Encodable<S> for path::PathBuf {
409     fn encode(&self, e: &mut S) {
410         path::Path::encode(self, e);
411     }
412 }
413
414 impl<D: Decoder> Decodable<D> for path::PathBuf {
415     fn decode(d: &mut D) -> path::PathBuf {
416         let bytes: String = Decodable::decode(d);
417         path::PathBuf::from(bytes)
418     }
419 }
420
421 impl<S: Encoder, T: Encodable<S> + Copy> Encodable<S> for Cell<T> {
422     fn encode(&self, s: &mut S) {
423         self.get().encode(s);
424     }
425 }
426
427 impl<D: Decoder, T: Decodable<D> + Copy> Decodable<D> for Cell<T> {
428     fn decode(d: &mut D) -> Cell<T> {
429         Cell::new(Decodable::decode(d))
430     }
431 }
432
433 // FIXME: #15036
434 // Should use `try_borrow`, returning an
435 // `encoder.error("attempting to Encode borrowed RefCell")`
436 // from `encode` when `try_borrow` returns `None`.
437
438 impl<S: Encoder, T: Encodable<S>> Encodable<S> for RefCell<T> {
439     fn encode(&self, s: &mut S) {
440         self.borrow().encode(s);
441     }
442 }
443
444 impl<D: Decoder, T: Decodable<D>> Decodable<D> for RefCell<T> {
445     fn decode(d: &mut D) -> RefCell<T> {
446         RefCell::new(Decodable::decode(d))
447     }
448 }
449
450 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Arc<T> {
451     fn encode(&self, s: &mut S) {
452         (**self).encode(s);
453     }
454 }
455
456 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Arc<T> {
457     fn decode(d: &mut D) -> Arc<T> {
458         Arc::new(Decodable::decode(d))
459     }
460 }
461
462 impl<S: Encoder, T: ?Sized + Encodable<S>, A: Allocator + Default> Encodable<S> for Box<T, A> {
463     fn encode(&self, s: &mut S) {
464         (**self).encode(s)
465     }
466 }
467
468 impl<D: Decoder, A: Allocator + Default, T: Decodable<D>> Decodable<D> for Box<T, A> {
469     fn decode(d: &mut D) -> Box<T, A> {
470         let allocator = A::default();
471         Box::new_in(Decodable::decode(d), allocator)
472     }
473 }