]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_serialize/src/serialize.rs
Use count! macro in tuple length computation
[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_unit(&mut self) -> ();
185     fn read_usize(&mut self) -> usize;
186     fn read_u128(&mut self) -> u128;
187     fn read_u64(&mut self) -> u64;
188     fn read_u32(&mut self) -> u32;
189     fn read_u16(&mut self) -> u16;
190     fn read_u8(&mut self) -> u8;
191     fn read_isize(&mut self) -> isize;
192     fn read_i128(&mut self) -> i128;
193     fn read_i64(&mut self) -> i64;
194     fn read_i32(&mut self) -> i32;
195     fn read_i16(&mut self) -> i16;
196     fn read_i8(&mut self) -> i8;
197     fn read_bool(&mut self) -> bool;
198     fn read_f64(&mut self) -> f64;
199     fn read_f32(&mut self) -> f32;
200     fn read_char(&mut self) -> char;
201     fn read_str(&mut self) -> Cow<'_, str>;
202     fn read_raw_bytes_into(&mut self, s: &mut [u8]);
203
204     #[inline]
205     fn read_enum_variant<T, F>(&mut self, mut f: F) -> T
206     where
207         F: FnMut(&mut Self, usize) -> T,
208     {
209         let disr = self.read_usize();
210         f(self, disr)
211     }
212
213     #[inline]
214     fn read_tuple<T, F>(&mut self, _len: usize, f: F) -> T
215     where
216         F: FnOnce(&mut Self) -> T,
217     {
218         f(self)
219     }
220
221     #[inline]
222     fn read_tuple_arg<T, F>(&mut self, f: F) -> T
223     where
224         F: FnOnce(&mut Self) -> T,
225     {
226         f(self)
227     }
228
229     // Specialized types:
230     fn read_option<T, F>(&mut self, mut f: F) -> T
231     where
232         F: FnMut(&mut Self, bool) -> T,
233     {
234         self.read_enum_variant(move |this, idx| match idx {
235             0 => f(this, false),
236             1 => f(this, true),
237             _ => panic!("read_option: expected 0 for None or 1 for Some"),
238         })
239     }
240
241     fn read_seq<T, F>(&mut self, f: F) -> T
242     where
243         F: FnOnce(&mut Self, usize) -> T,
244     {
245         let len = self.read_usize();
246         f(self, len)
247     }
248
249     #[inline]
250     fn read_seq_elt<T, F>(&mut self, f: F) -> T
251     where
252         F: FnOnce(&mut Self) -> T,
253     {
254         f(self)
255     }
256
257     fn read_map<T, F>(&mut self, f: F) -> T
258     where
259         F: FnOnce(&mut Self, usize) -> T,
260     {
261         let len = self.read_usize();
262         f(self, len)
263     }
264
265     #[inline]
266     fn read_map_elt_key<T, F>(&mut self, f: F) -> T
267     where
268         F: FnOnce(&mut Self) -> T,
269     {
270         f(self)
271     }
272
273     #[inline]
274     fn read_map_elt_val<T, F>(&mut self, f: F) -> T
275     where
276         F: FnOnce(&mut Self) -> T,
277     {
278         f(self)
279     }
280 }
281
282 /// Trait for types that can be serialized
283 ///
284 /// This can be implemented using the `Encodable`, `TyEncodable` and
285 /// `MetadataEncodable` macros.
286 ///
287 /// * `Encodable` should be used in crates that don't depend on
288 ///   `rustc_middle`.
289 /// * `MetadataEncodable` is used in `rustc_metadata` for types that contain
290 ///   `rustc_metadata::rmeta::Lazy`.
291 /// * `TyEncodable` should be used for types that are only serialized in crate
292 ///   metadata or the incremental cache. This is most types in `rustc_middle`.
293 pub trait Encodable<S: Encoder> {
294     fn encode(&self, s: &mut S) -> Result<(), S::Error>;
295 }
296
297 /// Trait for types that can be deserialized
298 ///
299 /// This can be implemented using the `Decodable`, `TyDecodable` and
300 /// `MetadataDecodable` macros.
301 ///
302 /// * `Decodable` should be used in crates that don't depend on
303 ///   `rustc_middle`.
304 /// * `MetadataDecodable` is used in `rustc_metadata` for types that contain
305 ///   `rustc_metadata::rmeta::Lazy`.
306 /// * `TyDecodable` should be used for types that are only serialized in crate
307 ///   metadata or the incremental cache. This is most types in `rustc_middle`.
308 pub trait Decodable<D: Decoder>: Sized {
309     fn decode(d: &mut D) -> Self;
310 }
311
312 macro_rules! direct_serialize_impls {
313     ($($ty:ident $emit_method:ident $read_method:ident),*) => {
314         $(
315             impl<S: Encoder> Encodable<S> for $ty {
316                 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
317                     s.$emit_method(*self)
318                 }
319             }
320
321             impl<D: Decoder> Decodable<D> for $ty {
322                 fn decode(d: &mut D) -> $ty {
323                     d.$read_method()
324                 }
325             }
326         )*
327     }
328 }
329
330 direct_serialize_impls! {
331     usize emit_usize read_usize,
332     u8 emit_u8 read_u8,
333     u16 emit_u16 read_u16,
334     u32 emit_u32 read_u32,
335     u64 emit_u64 read_u64,
336     u128 emit_u128 read_u128,
337     isize emit_isize read_isize,
338     i8 emit_i8 read_i8,
339     i16 emit_i16 read_i16,
340     i32 emit_i32 read_i32,
341     i64 emit_i64 read_i64,
342     i128 emit_i128 read_i128,
343     f32 emit_f32 read_f32,
344     f64 emit_f64 read_f64,
345     bool emit_bool read_bool,
346     char emit_char read_char
347 }
348
349 impl<S: Encoder> Encodable<S> for ! {
350     fn encode(&self, _s: &mut S) -> Result<(), S::Error> {
351         unreachable!()
352     }
353 }
354
355 impl<D: Decoder> Decodable<D> for ! {
356     fn decode(_d: &mut D) -> ! {
357         unreachable!()
358     }
359 }
360
361 impl<S: Encoder> Encodable<S> for ::std::num::NonZeroU32 {
362     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
363         s.emit_u32(self.get())
364     }
365 }
366
367 impl<D: Decoder> Decodable<D> for ::std::num::NonZeroU32 {
368     fn decode(d: &mut D) -> Self {
369         ::std::num::NonZeroU32::new(d.read_u32()).unwrap()
370     }
371 }
372
373 impl<S: Encoder> Encodable<S> for str {
374     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
375         s.emit_str(self)
376     }
377 }
378
379 impl<S: Encoder> Encodable<S> for &str {
380     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
381         s.emit_str(self)
382     }
383 }
384
385 impl<S: Encoder> Encodable<S> for String {
386     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
387         s.emit_str(&self[..])
388     }
389 }
390
391 impl<D: Decoder> Decodable<D> for String {
392     fn decode(d: &mut D) -> String {
393         d.read_str().into_owned()
394     }
395 }
396
397 impl<S: Encoder> Encodable<S> for () {
398     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
399         s.emit_unit()
400     }
401 }
402
403 impl<D: Decoder> Decodable<D> for () {
404     fn decode(d: &mut D) -> () {
405         d.read_unit()
406     }
407 }
408
409 impl<S: Encoder, T> Encodable<S> for PhantomData<T> {
410     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
411         s.emit_unit()
412     }
413 }
414
415 impl<D: Decoder, T> Decodable<D> for PhantomData<T> {
416     fn decode(d: &mut D) -> PhantomData<T> {
417         d.read_unit();
418         PhantomData
419     }
420 }
421
422 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Box<[T]> {
423     fn decode(d: &mut D) -> Box<[T]> {
424         let v: Vec<T> = Decodable::decode(d);
425         v.into_boxed_slice()
426     }
427 }
428
429 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Rc<T> {
430     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
431         (**self).encode(s)
432     }
433 }
434
435 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Rc<T> {
436     fn decode(d: &mut D) -> Rc<T> {
437         Rc::new(Decodable::decode(d))
438     }
439 }
440
441 impl<S: Encoder, T: Encodable<S>> Encodable<S> for [T] {
442     default fn encode(&self, s: &mut S) -> Result<(), S::Error> {
443         s.emit_seq(self.len(), |s| {
444             for (i, e) in self.iter().enumerate() {
445                 s.emit_seq_elt(i, |s| e.encode(s))?
446             }
447             Ok(())
448         })
449     }
450 }
451
452 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Vec<T> {
453     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
454         let slice: &[T] = self;
455         slice.encode(s)
456     }
457 }
458
459 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Vec<T> {
460     default fn decode(d: &mut D) -> Vec<T> {
461         d.read_seq(|d, len| {
462             // SAFETY: we set the capacity in advance, only write elements, and
463             // only set the length at the end once the writing has succeeded.
464             let mut vec = Vec::with_capacity(len);
465             unsafe {
466                 let ptr: *mut T = vec.as_mut_ptr();
467                 for i in 0..len {
468                     std::ptr::write(
469                         ptr.offset(i as isize),
470                         d.read_seq_elt(|d| Decodable::decode(d)),
471                     );
472                 }
473                 vec.set_len(len);
474             }
475             vec
476         })
477     }
478 }
479
480 impl<S: Encoder, T: Encodable<S>, const N: usize> Encodable<S> for [T; N] {
481     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
482         let slice: &[T] = self;
483         slice.encode(s)
484     }
485 }
486
487 impl<D: Decoder, const N: usize> Decodable<D> for [u8; N] {
488     fn decode(d: &mut D) -> [u8; N] {
489         d.read_seq(|d, len| {
490             assert!(len == N);
491             let mut v = [0u8; N];
492             for i in 0..len {
493                 v[i] = d.read_seq_elt(|d| Decodable::decode(d));
494             }
495             v
496         })
497     }
498 }
499
500 impl<'a, S: Encoder, T: Encodable<S>> Encodable<S> for Cow<'a, [T]>
501 where
502     [T]: ToOwned<Owned = Vec<T>>,
503 {
504     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
505         let slice: &[T] = self;
506         slice.encode(s)
507     }
508 }
509
510 impl<D: Decoder, T: Decodable<D> + ToOwned> Decodable<D> for Cow<'static, [T]>
511 where
512     [T]: ToOwned<Owned = Vec<T>>,
513 {
514     fn decode(d: &mut D) -> Cow<'static, [T]> {
515         let v: Vec<T> = Decodable::decode(d);
516         Cow::Owned(v)
517     }
518 }
519
520 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Option<T> {
521     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
522         s.emit_option(|s| match *self {
523             None => s.emit_option_none(),
524             Some(ref v) => s.emit_option_some(|s| v.encode(s)),
525         })
526     }
527 }
528
529 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Option<T> {
530     fn decode(d: &mut D) -> Option<T> {
531         d.read_option(|d, b| if b { Some(Decodable::decode(d)) } else { None })
532     }
533 }
534
535 impl<S: Encoder, T1: Encodable<S>, T2: Encodable<S>> Encodable<S> for Result<T1, T2> {
536     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
537         s.emit_enum(|s| match *self {
538             Ok(ref v) => {
539                 s.emit_enum_variant("Ok", 0, 1, |s| s.emit_enum_variant_arg(true, |s| v.encode(s)))
540             }
541             Err(ref v) => {
542                 s.emit_enum_variant("Err", 1, 1, |s| s.emit_enum_variant_arg(true, |s| v.encode(s)))
543             }
544         })
545     }
546 }
547
548 impl<D: Decoder, T1: Decodable<D>, T2: Decodable<D>> Decodable<D> for Result<T1, T2> {
549     fn decode(d: &mut D) -> Result<T1, T2> {
550         d.read_enum_variant(|d, disr| match disr {
551             0 => Ok(T1::decode(d)),
552             1 => Err(T2::decode(d)),
553             _ => panic!("Encountered invalid discriminant while decoding `Result`."),
554         })
555     }
556 }
557
558 macro_rules! peel {
559     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
560 }
561
562 /// Evaluates to the number of tokens passed to it.
563 ///
564 /// Logarithmic counting: every one or two recursive expansions, the number of
565 /// tokens to count is divided by two, instead of being reduced by one.
566 /// Therefore, the recursion depth is the binary logarithm of the number of
567 /// tokens to count, and the expanded tree is likewise very small.
568 macro_rules! count {
569     ()                     => (0usize);
570     ($one:tt)              => (1usize);
571     ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize);
572     ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize);
573 }
574
575 macro_rules! tuple {
576     () => ();
577     ( $($name:ident,)+ ) => (
578         impl<D: Decoder, $($name: Decodable<D>),+> Decodable<D> for ($($name,)+) {
579             #[allow(non_snake_case)]
580             fn decode(d: &mut D) -> ($($name,)+) {
581                 let len: usize = count!($($name)+);
582                 d.read_tuple(len, |d| {
583                     let ret = ($(d.read_tuple_arg(|d| -> $name {
584                         Decodable::decode(d)
585                     }),)+);
586                     ret
587                 })
588             }
589         }
590         impl<S: Encoder, $($name: Encodable<S>),+> Encodable<S> for ($($name,)+) {
591             #[allow(non_snake_case)]
592             fn encode(&self, s: &mut S) -> Result<(), S::Error> {
593                 let ($(ref $name,)+) = *self;
594                 let len: usize = count!($($name)+);
595                 s.emit_tuple(len, |s| {
596                     let mut i = 0;
597                     $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)+
598                     Ok(())
599                 })
600             }
601         }
602         peel! { $($name,)+ }
603     )
604 }
605
606 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
607
608 impl<S: Encoder> Encodable<S> for path::Path {
609     fn encode(&self, e: &mut S) -> Result<(), S::Error> {
610         self.to_str().unwrap().encode(e)
611     }
612 }
613
614 impl<S: Encoder> Encodable<S> for path::PathBuf {
615     fn encode(&self, e: &mut S) -> Result<(), S::Error> {
616         path::Path::encode(self, e)
617     }
618 }
619
620 impl<D: Decoder> Decodable<D> for path::PathBuf {
621     fn decode(d: &mut D) -> path::PathBuf {
622         let bytes: String = Decodable::decode(d);
623         path::PathBuf::from(bytes)
624     }
625 }
626
627 impl<S: Encoder, T: Encodable<S> + Copy> Encodable<S> for Cell<T> {
628     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
629         self.get().encode(s)
630     }
631 }
632
633 impl<D: Decoder, T: Decodable<D> + Copy> Decodable<D> for Cell<T> {
634     fn decode(d: &mut D) -> Cell<T> {
635         Cell::new(Decodable::decode(d))
636     }
637 }
638
639 // FIXME: #15036
640 // Should use `try_borrow`, returning an
641 // `encoder.error("attempting to Encode borrowed RefCell")`
642 // from `encode` when `try_borrow` returns `None`.
643
644 impl<S: Encoder, T: Encodable<S>> Encodable<S> for RefCell<T> {
645     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
646         self.borrow().encode(s)
647     }
648 }
649
650 impl<D: Decoder, T: Decodable<D>> Decodable<D> for RefCell<T> {
651     fn decode(d: &mut D) -> RefCell<T> {
652         RefCell::new(Decodable::decode(d))
653     }
654 }
655
656 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Arc<T> {
657     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
658         (**self).encode(s)
659     }
660 }
661
662 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Arc<T> {
663     fn decode(d: &mut D) -> Arc<T> {
664         Arc::new(Decodable::decode(d))
665     }
666 }
667
668 impl<S: Encoder, T: ?Sized + Encodable<S>> Encodable<S> for Box<T> {
669     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
670         (**self).encode(s)
671     }
672 }
673 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Box<T> {
674     fn decode(d: &mut D) -> Box<T> {
675         Box::new(Decodable::decode(d))
676     }
677 }