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