]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_serialize/src/serialize.rs
Auto merge of #92361 - vacuus:doctest-run-test-out-lines, r=CraftSpider
[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_unit(&mut self) -> Result<(), Self::Error>;
19     fn emit_usize(&mut self, v: usize) -> Result<(), Self::Error>;
20     fn emit_u128(&mut self, v: u128) -> Result<(), Self::Error>;
21     fn emit_u64(&mut self, v: u64) -> Result<(), Self::Error>;
22     fn emit_u32(&mut self, v: u32) -> Result<(), Self::Error>;
23     fn emit_u16(&mut self, v: u16) -> Result<(), Self::Error>;
24     fn emit_u8(&mut self, v: u8) -> Result<(), Self::Error>;
25     fn emit_isize(&mut self, v: isize) -> Result<(), Self::Error>;
26     fn emit_i128(&mut self, v: i128) -> Result<(), Self::Error>;
27     fn emit_i64(&mut self, v: i64) -> Result<(), Self::Error>;
28     fn emit_i32(&mut self, v: i32) -> Result<(), Self::Error>;
29     fn emit_i16(&mut self, v: i16) -> Result<(), Self::Error>;
30     fn emit_i8(&mut self, v: i8) -> Result<(), Self::Error>;
31     fn emit_bool(&mut self, v: bool) -> Result<(), Self::Error>;
32     fn emit_f64(&mut self, v: f64) -> Result<(), Self::Error>;
33     fn emit_f32(&mut self, v: f32) -> Result<(), Self::Error>;
34     fn emit_char(&mut self, v: char) -> Result<(), Self::Error>;
35     fn emit_str(&mut self, v: &str) -> Result<(), Self::Error>;
36     fn emit_raw_bytes(&mut self, s: &[u8]) -> Result<(), Self::Error>;
37
38     // Compound types:
39     #[inline]
40     fn emit_enum<F>(&mut self, f: F) -> Result<(), Self::Error>
41     where
42         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
43     {
44         f(self)
45     }
46
47     fn emit_enum_variant<F>(
48         &mut self,
49         _v_name: &str,
50         v_id: usize,
51         _len: usize,
52         f: F,
53     ) -> Result<(), Self::Error>
54     where
55         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
56     {
57         self.emit_usize(v_id)?;
58         f(self)
59     }
60
61     // We put the field index in a const generic to allow the emit_usize to be
62     // compiled into a more efficient form. In practice, the variant index is
63     // known at compile-time, and that knowledge allows much more efficient
64     // codegen than we'd otherwise get. LLVM isn't always able to make the
65     // optimization that would otherwise be necessary here, likely due to the
66     // multiple levels of inlining and const-prop that are needed.
67     #[inline]
68     fn emit_fieldless_enum_variant<const ID: usize>(
69         &mut self,
70         _v_name: &str,
71     ) -> Result<(), Self::Error> {
72         self.emit_usize(ID)
73     }
74
75     #[inline]
76     fn emit_enum_variant_arg<F>(&mut self, _first: bool, f: F) -> Result<(), Self::Error>
77     where
78         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
79     {
80         f(self)
81     }
82
83     #[inline]
84     fn emit_struct<F>(&mut self, _no_fields: bool, f: F) -> Result<(), Self::Error>
85     where
86         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
87     {
88         f(self)
89     }
90
91     #[inline]
92     fn emit_struct_field<F>(&mut self, _f_name: &str, _first: bool, f: F) -> Result<(), Self::Error>
93     where
94         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
95     {
96         f(self)
97     }
98
99     #[inline]
100     fn emit_tuple<F>(&mut self, _len: usize, f: F) -> Result<(), Self::Error>
101     where
102         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
103     {
104         f(self)
105     }
106
107     #[inline]
108     fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
109     where
110         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
111     {
112         f(self)
113     }
114
115     // Specialized types:
116     fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
117     where
118         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
119     {
120         self.emit_enum(f)
121     }
122
123     #[inline]
124     fn emit_option_none(&mut self) -> Result<(), Self::Error> {
125         self.emit_enum_variant("None", 0, 0, |_| Ok(()))
126     }
127
128     fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
129     where
130         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
131     {
132         self.emit_enum_variant("Some", 1, 1, f)
133     }
134
135     fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
136     where
137         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
138     {
139         self.emit_usize(len)?;
140         f(self)
141     }
142
143     #[inline]
144     fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
145     where
146         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
147     {
148         f(self)
149     }
150
151     fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
152     where
153         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
154     {
155         self.emit_usize(len)?;
156         f(self)
157     }
158
159     #[inline]
160     fn emit_map_elt_key<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
161     where
162         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
163     {
164         f(self)
165     }
166
167     #[inline]
168     fn emit_map_elt_val<F>(&mut self, f: F) -> Result<(), Self::Error>
169     where
170         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
171     {
172         f(self)
173     }
174 }
175
176 // Note: all the methods in this trait are infallible, which may be surprising.
177 // They used to be fallible (i.e. return a `Result`) but many of the impls just
178 // panicked when something went wrong, and for the cases that didn't the
179 // top-level invocation would also just panic on failure. Switching to
180 // infallibility made things faster and lots of code a little simpler and more
181 // concise.
182 pub trait Decoder {
183     // Primitive types:
184     fn read_usize(&mut self) -> usize;
185     fn read_u128(&mut self) -> u128;
186     fn read_u64(&mut self) -> u64;
187     fn read_u32(&mut self) -> u32;
188     fn read_u16(&mut self) -> u16;
189     fn read_u8(&mut self) -> u8;
190     fn read_isize(&mut self) -> isize;
191     fn read_i128(&mut self) -> i128;
192     fn read_i64(&mut self) -> i64;
193     fn read_i32(&mut self) -> i32;
194     fn read_i16(&mut self) -> i16;
195     fn read_i8(&mut self) -> i8;
196     fn read_bool(&mut self) -> bool;
197     fn read_f64(&mut self) -> f64;
198     fn read_f32(&mut self) -> f32;
199     fn read_char(&mut self) -> char;
200     fn read_str(&mut self) -> &str;
201     fn read_raw_bytes(&mut self, len: usize) -> &[u8];
202 }
203
204 /// Trait for types that can be serialized
205 ///
206 /// This can be implemented using the `Encodable`, `TyEncodable` and
207 /// `MetadataEncodable` macros.
208 ///
209 /// * `Encodable` should be used in crates that don't depend on
210 ///   `rustc_middle`.
211 /// * `MetadataEncodable` is used in `rustc_metadata` for types that contain
212 ///   `rustc_metadata::rmeta::Lazy`.
213 /// * `TyEncodable` should be used for types that are only serialized in crate
214 ///   metadata or the incremental cache. This is most types in `rustc_middle`.
215 pub trait Encodable<S: Encoder> {
216     fn encode(&self, s: &mut S) -> Result<(), S::Error>;
217 }
218
219 /// Trait for types that can be deserialized
220 ///
221 /// This can be implemented using the `Decodable`, `TyDecodable` and
222 /// `MetadataDecodable` macros.
223 ///
224 /// * `Decodable` should be used in crates that don't depend on
225 ///   `rustc_middle`.
226 /// * `MetadataDecodable` is used in `rustc_metadata` for types that contain
227 ///   `rustc_metadata::rmeta::Lazy`.
228 /// * `TyDecodable` should be used for types that are only serialized in crate
229 ///   metadata or the incremental cache. This is most types in `rustc_middle`.
230 pub trait Decodable<D: Decoder>: Sized {
231     fn decode(d: &mut D) -> Self;
232 }
233
234 macro_rules! direct_serialize_impls {
235     ($($ty:ident $emit_method:ident $read_method:ident),*) => {
236         $(
237             impl<S: Encoder> Encodable<S> for $ty {
238                 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
239                     s.$emit_method(*self)
240                 }
241             }
242
243             impl<D: Decoder> Decodable<D> for $ty {
244                 fn decode(d: &mut D) -> $ty {
245                     d.$read_method()
246                 }
247             }
248         )*
249     }
250 }
251
252 direct_serialize_impls! {
253     usize emit_usize read_usize,
254     u8 emit_u8 read_u8,
255     u16 emit_u16 read_u16,
256     u32 emit_u32 read_u32,
257     u64 emit_u64 read_u64,
258     u128 emit_u128 read_u128,
259     isize emit_isize read_isize,
260     i8 emit_i8 read_i8,
261     i16 emit_i16 read_i16,
262     i32 emit_i32 read_i32,
263     i64 emit_i64 read_i64,
264     i128 emit_i128 read_i128,
265     f32 emit_f32 read_f32,
266     f64 emit_f64 read_f64,
267     bool emit_bool read_bool,
268     char emit_char read_char
269 }
270
271 impl<S: Encoder> Encodable<S> for ! {
272     fn encode(&self, _s: &mut S) -> Result<(), S::Error> {
273         unreachable!()
274     }
275 }
276
277 impl<D: Decoder> Decodable<D> for ! {
278     fn decode(_d: &mut D) -> ! {
279         unreachable!()
280     }
281 }
282
283 impl<S: Encoder> Encodable<S> for ::std::num::NonZeroU32 {
284     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
285         s.emit_u32(self.get())
286     }
287 }
288
289 impl<D: Decoder> Decodable<D> for ::std::num::NonZeroU32 {
290     fn decode(d: &mut D) -> Self {
291         ::std::num::NonZeroU32::new(d.read_u32()).unwrap()
292     }
293 }
294
295 impl<S: Encoder> Encodable<S> for str {
296     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
297         s.emit_str(self)
298     }
299 }
300
301 impl<S: Encoder> Encodable<S> for &str {
302     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
303         s.emit_str(self)
304     }
305 }
306
307 impl<S: Encoder> Encodable<S> for String {
308     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
309         s.emit_str(&self[..])
310     }
311 }
312
313 impl<D: Decoder> Decodable<D> for String {
314     fn decode(d: &mut D) -> String {
315         d.read_str().to_owned()
316     }
317 }
318
319 impl<S: Encoder> Encodable<S> for () {
320     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
321         s.emit_unit()
322     }
323 }
324
325 impl<D: Decoder> Decodable<D> for () {
326     fn decode(_: &mut D) -> () {}
327 }
328
329 impl<S: Encoder, T> Encodable<S> for PhantomData<T> {
330     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
331         s.emit_unit()
332     }
333 }
334
335 impl<D: Decoder, T> Decodable<D> for PhantomData<T> {
336     fn decode(_: &mut D) -> PhantomData<T> {
337         PhantomData
338     }
339 }
340
341 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Box<[T]> {
342     fn decode(d: &mut D) -> Box<[T]> {
343         let v: Vec<T> = Decodable::decode(d);
344         v.into_boxed_slice()
345     }
346 }
347
348 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Rc<T> {
349     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
350         (**self).encode(s)
351     }
352 }
353
354 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Rc<T> {
355     fn decode(d: &mut D) -> Rc<T> {
356         Rc::new(Decodable::decode(d))
357     }
358 }
359
360 impl<S: Encoder, T: Encodable<S>> Encodable<S> for [T] {
361     default fn encode(&self, s: &mut S) -> Result<(), S::Error> {
362         s.emit_seq(self.len(), |s| {
363             for (i, e) in self.iter().enumerate() {
364                 s.emit_seq_elt(i, |s| e.encode(s))?
365             }
366             Ok(())
367         })
368     }
369 }
370
371 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Vec<T> {
372     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
373         let slice: &[T] = self;
374         slice.encode(s)
375     }
376 }
377
378 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Vec<T> {
379     default fn decode(d: &mut D) -> Vec<T> {
380         let len = d.read_usize();
381         // SAFETY: we set the capacity in advance, only write elements, and
382         // only set the length at the end once the writing has succeeded.
383         let mut vec = Vec::with_capacity(len);
384         unsafe {
385             let ptr: *mut T = vec.as_mut_ptr();
386             for i in 0..len {
387                 std::ptr::write(ptr.offset(i as isize), Decodable::decode(d));
388             }
389             vec.set_len(len);
390         }
391         vec
392     }
393 }
394
395 impl<S: Encoder, T: Encodable<S>, const N: usize> Encodable<S> for [T; N] {
396     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
397         let slice: &[T] = self;
398         slice.encode(s)
399     }
400 }
401
402 impl<D: Decoder, const N: usize> Decodable<D> for [u8; N] {
403     fn decode(d: &mut D) -> [u8; N] {
404         let len = d.read_usize();
405         assert!(len == N);
406         let mut v = [0u8; N];
407         for i in 0..len {
408             v[i] = Decodable::decode(d);
409         }
410         v
411     }
412 }
413
414 impl<'a, S: Encoder, T: Encodable<S>> Encodable<S> for Cow<'a, [T]>
415 where
416     [T]: ToOwned<Owned = Vec<T>>,
417 {
418     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
419         let slice: &[T] = self;
420         slice.encode(s)
421     }
422 }
423
424 impl<D: Decoder, T: Decodable<D> + ToOwned> Decodable<D> for Cow<'static, [T]>
425 where
426     [T]: ToOwned<Owned = Vec<T>>,
427 {
428     fn decode(d: &mut D) -> Cow<'static, [T]> {
429         let v: Vec<T> = Decodable::decode(d);
430         Cow::Owned(v)
431     }
432 }
433
434 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Option<T> {
435     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
436         s.emit_option(|s| match *self {
437             None => s.emit_option_none(),
438             Some(ref v) => s.emit_option_some(|s| v.encode(s)),
439         })
440     }
441 }
442
443 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Option<T> {
444     fn decode(d: &mut D) -> Option<T> {
445         match d.read_usize() {
446             0 => None,
447             1 => Some(Decodable::decode(d)),
448             _ => panic!("Encountered invalid discriminant while decoding `Option`."),
449         }
450     }
451 }
452
453 impl<S: Encoder, T1: Encodable<S>, T2: Encodable<S>> Encodable<S> for Result<T1, T2> {
454     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
455         s.emit_enum(|s| match *self {
456             Ok(ref v) => {
457                 s.emit_enum_variant("Ok", 0, 1, |s| s.emit_enum_variant_arg(true, |s| v.encode(s)))
458             }
459             Err(ref v) => {
460                 s.emit_enum_variant("Err", 1, 1, |s| s.emit_enum_variant_arg(true, |s| v.encode(s)))
461             }
462         })
463     }
464 }
465
466 impl<D: Decoder, T1: Decodable<D>, T2: Decodable<D>> Decodable<D> for Result<T1, T2> {
467     fn decode(d: &mut D) -> Result<T1, T2> {
468         match d.read_usize() {
469             0 => Ok(T1::decode(d)),
470             1 => Err(T2::decode(d)),
471             _ => panic!("Encountered invalid discriminant while decoding `Result`."),
472         }
473     }
474 }
475
476 macro_rules! peel {
477     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
478 }
479
480 /// Evaluates to the number of tokens passed to it.
481 ///
482 /// Logarithmic counting: every one or two recursive expansions, the number of
483 /// tokens to count is divided by two, instead of being reduced by one.
484 /// Therefore, the recursion depth is the binary logarithm of the number of
485 /// tokens to count, and the expanded tree is likewise very small.
486 macro_rules! count {
487     ()                     => (0usize);
488     ($one:tt)              => (1usize);
489     ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize);
490     ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize);
491 }
492
493 macro_rules! tuple {
494     () => ();
495     ( $($name:ident,)+ ) => (
496         impl<D: Decoder, $($name: Decodable<D>),+> Decodable<D> for ($($name,)+) {
497             fn decode(d: &mut D) -> ($($name,)+) {
498                 ($({ let element: $name = Decodable::decode(d); element },)+)
499             }
500         }
501         impl<S: Encoder, $($name: Encodable<S>),+> Encodable<S> for ($($name,)+) {
502             #[allow(non_snake_case)]
503             fn encode(&self, s: &mut S) -> Result<(), S::Error> {
504                 let ($(ref $name,)+) = *self;
505                 let len: usize = count!($($name)+);
506                 s.emit_tuple(len, |s| {
507                     let mut i = 0;
508                     $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)+
509                     Ok(())
510                 })
511             }
512         }
513         peel! { $($name,)+ }
514     )
515 }
516
517 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
518
519 impl<S: Encoder> Encodable<S> for path::Path {
520     fn encode(&self, e: &mut S) -> Result<(), S::Error> {
521         self.to_str().unwrap().encode(e)
522     }
523 }
524
525 impl<S: Encoder> Encodable<S> for path::PathBuf {
526     fn encode(&self, e: &mut S) -> Result<(), S::Error> {
527         path::Path::encode(self, e)
528     }
529 }
530
531 impl<D: Decoder> Decodable<D> for path::PathBuf {
532     fn decode(d: &mut D) -> path::PathBuf {
533         let bytes: String = Decodable::decode(d);
534         path::PathBuf::from(bytes)
535     }
536 }
537
538 impl<S: Encoder, T: Encodable<S> + Copy> Encodable<S> for Cell<T> {
539     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
540         self.get().encode(s)
541     }
542 }
543
544 impl<D: Decoder, T: Decodable<D> + Copy> Decodable<D> for Cell<T> {
545     fn decode(d: &mut D) -> Cell<T> {
546         Cell::new(Decodable::decode(d))
547     }
548 }
549
550 // FIXME: #15036
551 // Should use `try_borrow`, returning an
552 // `encoder.error("attempting to Encode borrowed RefCell")`
553 // from `encode` when `try_borrow` returns `None`.
554
555 impl<S: Encoder, T: Encodable<S>> Encodable<S> for RefCell<T> {
556     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
557         self.borrow().encode(s)
558     }
559 }
560
561 impl<D: Decoder, T: Decodable<D>> Decodable<D> for RefCell<T> {
562     fn decode(d: &mut D) -> RefCell<T> {
563         RefCell::new(Decodable::decode(d))
564     }
565 }
566
567 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Arc<T> {
568     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
569         (**self).encode(s)
570     }
571 }
572
573 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Arc<T> {
574     fn decode(d: &mut D) -> Arc<T> {
575         Arc::new(Decodable::decode(d))
576     }
577 }
578
579 impl<S: Encoder, T: ?Sized + Encodable<S>> Encodable<S> for Box<T> {
580     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
581         (**self).encode(s)
582     }
583 }
584 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Box<T> {
585     fn decode(d: &mut D) -> Box<T> {
586         Box::new(Decodable::decode(d))
587     }
588 }