]> git.lizzy.rs Git - rust.git/blob - src/libstd/repr.rs
auto merge of #13600 : brandonw/rust/master, r=brson
[rust.git] / src / libstd / repr.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 /*!
12
13 More runtime type reflection
14
15 */
16
17 #![allow(missing_doc)]
18
19 use cast::transmute;
20 use char;
21 use container::Container;
22 use io;
23 use iter::Iterator;
24 use option::{Some, None, Option};
25 use ptr::RawPtr;
26 use reflect;
27 use reflect::{MovePtr, align};
28 use result::{Ok, Err};
29 use str::StrSlice;
30 use to_str::ToStr;
31 use slice::Vector;
32 use intrinsics::{Disr, Opaque, TyDesc, TyVisitor, get_tydesc, visit_tydesc};
33 use raw;
34 use vec::Vec;
35
36 macro_rules! try( ($me:expr, $e:expr) => (
37     match $e {
38         Ok(()) => {},
39         Err(e) => { $me.last_err = Some(e); return false; }
40     }
41 ) )
42
43 /// Representations
44
45 trait Repr {
46     fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()>;
47 }
48
49 impl Repr for () {
50     fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
51         writer.write("()".as_bytes())
52     }
53 }
54
55 impl Repr for bool {
56     fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
57         let s = if *self { "true" } else { "false" };
58         writer.write(s.as_bytes())
59     }
60 }
61
62 impl Repr for int {
63     fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
64         write!(writer, "{}", *self)
65     }
66 }
67
68 macro_rules! int_repr(($ty:ident, $suffix:expr) => (impl Repr for $ty {
69     fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
70         write!(writer, "{}{}", *self, $suffix)
71     }
72 }))
73
74 int_repr!(i8, "i8")
75 int_repr!(i16, "i16")
76 int_repr!(i32, "i32")
77 int_repr!(i64, "i64")
78 int_repr!(uint, "u")
79 int_repr!(u8, "u8")
80 int_repr!(u16, "u16")
81 int_repr!(u32, "u32")
82 int_repr!(u64, "u64")
83
84 macro_rules! num_repr(($ty:ident, $suffix:expr) => (impl Repr for $ty {
85     fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
86         let s = self.to_str();
87         writer.write(s.as_bytes()).and_then(|()| {
88             writer.write(bytes!($suffix))
89         })
90     }
91 }))
92
93 num_repr!(f32, "f32")
94 num_repr!(f64, "f64")
95
96 // New implementation using reflect::MovePtr
97
98 enum VariantState {
99     SearchingFor(Disr),
100     Matched,
101     AlreadyFound
102 }
103
104 pub struct ReprVisitor<'a> {
105     ptr: *u8,
106     ptr_stk: Vec<*u8>,
107     var_stk: Vec<VariantState>,
108     writer: &'a mut io::Writer,
109     last_err: Option<io::IoError>,
110 }
111
112 pub fn ReprVisitor<'a>(ptr: *u8,
113                        writer: &'a mut io::Writer) -> ReprVisitor<'a> {
114     ReprVisitor {
115         ptr: ptr,
116         ptr_stk: vec!(),
117         var_stk: vec!(),
118         writer: writer,
119         last_err: None,
120     }
121 }
122
123 impl<'a> MovePtr for ReprVisitor<'a> {
124     #[inline]
125     fn move_ptr(&mut self, adjustment: |*u8| -> *u8) {
126         self.ptr = adjustment(self.ptr);
127     }
128     fn push_ptr(&mut self) {
129         self.ptr_stk.push(self.ptr);
130     }
131     fn pop_ptr(&mut self) {
132         self.ptr = self.ptr_stk.pop().unwrap();
133     }
134 }
135
136 impl<'a> ReprVisitor<'a> {
137     // Various helpers for the TyVisitor impl
138
139     #[inline]
140     pub fn get<T>(&mut self, f: |&mut ReprVisitor, &T| -> bool) -> bool {
141         unsafe {
142             f(self, transmute::<*u8,&T>(self.ptr))
143         }
144     }
145
146     #[inline]
147     pub fn visit_inner(&mut self, inner: *TyDesc) -> bool {
148         self.visit_ptr_inner(self.ptr, inner)
149     }
150
151     #[inline]
152     pub fn visit_ptr_inner(&mut self, ptr: *u8, inner: *TyDesc) -> bool {
153         unsafe {
154             // This should call the constructor up above, but due to limiting
155             // issues we have to recreate it here.
156             let u = ReprVisitor {
157                 ptr: ptr,
158                 ptr_stk: vec!(),
159                 var_stk: vec!(),
160                 writer: ::cast::transmute_copy(&self.writer),
161                 last_err: None,
162             };
163             let mut v = reflect::MovePtrAdaptor(u);
164             // Obviously this should not be a thing, but blame #8401 for now
165             visit_tydesc(inner, &mut v as &mut TyVisitor);
166             match v.unwrap().last_err {
167                 Some(e) => {
168                     self.last_err = Some(e);
169                     false
170                 }
171                 None => true,
172             }
173         }
174     }
175
176     #[inline]
177     pub fn write<T:Repr>(&mut self) -> bool {
178         self.get(|this, v:&T| {
179             try!(this, v.write_repr(this.writer));
180             true
181         })
182     }
183
184     pub fn write_escaped_slice(&mut self, slice: &str) -> bool {
185         try!(self, self.writer.write(['"' as u8]));
186         for ch in slice.chars() {
187             if !self.write_escaped_char(ch, true) { return false }
188         }
189         try!(self, self.writer.write(['"' as u8]));
190         true
191     }
192
193     pub fn write_mut_qualifier(&mut self, mtbl: uint) -> bool {
194         if mtbl == 0 {
195             try!(self, self.writer.write("mut ".as_bytes()));
196         } else if mtbl == 1 {
197             // skip, this is ast::m_imm
198         } else {
199             fail!("invalid mutability value");
200         }
201         true
202     }
203
204     pub fn write_vec_range(&mut self, ptr: *(), len: uint, inner: *TyDesc) -> bool {
205         let mut p = ptr as *u8;
206         let (sz, al) = unsafe { ((*inner).size, (*inner).align) };
207         try!(self, self.writer.write(['[' as u8]));
208         let mut first = true;
209         let mut left = len;
210         // unit structs have 0 size, and don't loop forever.
211         let dec = if sz == 0 {1} else {sz};
212         while left > 0 {
213             if first {
214                 first = false;
215             } else {
216                 try!(self, self.writer.write(", ".as_bytes()));
217             }
218             self.visit_ptr_inner(p as *u8, inner);
219             p = align(unsafe { p.offset(sz as int) as uint }, al) as *u8;
220             left -= dec;
221         }
222         try!(self, self.writer.write([']' as u8]));
223         true
224     }
225
226     pub fn write_unboxed_vec_repr(&mut self, _: uint, v: &raw::Vec<()>, inner: *TyDesc) -> bool {
227         self.write_vec_range(&v.data, v.fill, inner)
228     }
229
230     fn write_escaped_char(&mut self, ch: char, is_str: bool) -> bool {
231         try!(self, match ch {
232             '\t' => self.writer.write("\\t".as_bytes()),
233             '\r' => self.writer.write("\\r".as_bytes()),
234             '\n' => self.writer.write("\\n".as_bytes()),
235             '\\' => self.writer.write("\\\\".as_bytes()),
236             '\'' => {
237                 if is_str {
238                     self.writer.write("'".as_bytes())
239                 } else {
240                     self.writer.write("\\'".as_bytes())
241                 }
242             }
243             '"' => {
244                 if is_str {
245                     self.writer.write("\\\"".as_bytes())
246                 } else {
247                     self.writer.write("\"".as_bytes())
248                 }
249             }
250             '\x20'..'\x7e' => self.writer.write([ch as u8]),
251             _ => {
252                 char::escape_unicode(ch, |c| {
253                     let _ = self.writer.write([c as u8]);
254                 });
255                 Ok(())
256             }
257         });
258         return true;
259     }
260 }
261
262 impl<'a> TyVisitor for ReprVisitor<'a> {
263     fn visit_bot(&mut self) -> bool {
264         try!(self, self.writer.write("!".as_bytes()));
265         true
266     }
267     fn visit_nil(&mut self) -> bool { self.write::<()>() }
268     fn visit_bool(&mut self) -> bool { self.write::<bool>() }
269     fn visit_int(&mut self) -> bool { self.write::<int>() }
270     fn visit_i8(&mut self) -> bool { self.write::<i8>() }
271     fn visit_i16(&mut self) -> bool { self.write::<i16>() }
272     fn visit_i32(&mut self) -> bool { self.write::<i32>()  }
273     fn visit_i64(&mut self) -> bool { self.write::<i64>() }
274
275     fn visit_uint(&mut self) -> bool { self.write::<uint>() }
276     fn visit_u8(&mut self) -> bool { self.write::<u8>() }
277     fn visit_u16(&mut self) -> bool { self.write::<u16>() }
278     fn visit_u32(&mut self) -> bool { self.write::<u32>() }
279     fn visit_u64(&mut self) -> bool { self.write::<u64>() }
280
281     fn visit_f32(&mut self) -> bool { self.write::<f32>() }
282     fn visit_f64(&mut self) -> bool { self.write::<f64>() }
283
284     fn visit_char(&mut self) -> bool {
285         self.get::<char>(|this, &ch| {
286             try!(this, this.writer.write(['\'' as u8]));
287             if !this.write_escaped_char(ch, false) { return false }
288             try!(this, this.writer.write(['\'' as u8]));
289             true
290         })
291     }
292
293     fn visit_estr_box(&mut self) -> bool {
294         true
295     }
296
297     fn visit_estr_uniq(&mut self) -> bool {
298         self.get::<~str>(|this, s| {
299             try!(this, this.writer.write(['~' as u8]));
300             this.write_escaped_slice(*s)
301         })
302     }
303
304     fn visit_estr_slice(&mut self) -> bool {
305         self.get::<&str>(|this, s| this.write_escaped_slice(*s))
306     }
307
308     // Type no longer exists, vestigial function.
309     fn visit_estr_fixed(&mut self, _n: uint, _sz: uint,
310                         _align: uint) -> bool { fail!(); }
311
312     fn visit_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
313         try!(self, self.writer.write(['@' as u8]));
314         self.write_mut_qualifier(mtbl);
315         self.get::<&raw::Box<()>>(|this, b| {
316             let p = &b.data as *() as *u8;
317             this.visit_ptr_inner(p, inner)
318         })
319     }
320
321     fn visit_uniq(&mut self, _mtbl: uint, inner: *TyDesc) -> bool {
322         try!(self, self.writer.write(['~' as u8]));
323         self.get::<*u8>(|this, b| {
324             this.visit_ptr_inner(*b, inner)
325         })
326     }
327
328     fn visit_ptr(&mut self, mtbl: uint, _inner: *TyDesc) -> bool {
329         self.get::<*u8>(|this, p| {
330             try!(this, write!(this.writer, "({} as *", *p));
331             this.write_mut_qualifier(mtbl);
332             try!(this, this.writer.write("())".as_bytes()));
333             true
334         })
335     }
336
337     fn visit_rptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
338         try!(self, self.writer.write(['&' as u8]));
339         self.write_mut_qualifier(mtbl);
340         self.get::<*u8>(|this, p| {
341             this.visit_ptr_inner(*p, inner)
342         })
343     }
344
345     fn visit_evec_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
346         self.get::<&raw::Box<raw::Vec<()>>>(|this, b| {
347             try!(this, this.writer.write(['@' as u8]));
348             this.write_mut_qualifier(mtbl);
349             this.write_unboxed_vec_repr(mtbl, &b.data, inner)
350         })
351     }
352
353     fn visit_evec_uniq(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
354         self.get::<&raw::Vec<()>>(|this, b| {
355             try!(this, this.writer.write(['~' as u8]));
356             this.write_unboxed_vec_repr(mtbl, *b, inner)
357         })
358     }
359
360     fn visit_evec_slice(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
361         self.get::<raw::Slice<()>>(|this, s| {
362             try!(this, this.writer.write(['&' as u8]));
363             this.write_mut_qualifier(mtbl);
364             let size = unsafe {
365                 if (*inner).size == 0 { 1 } else { (*inner).size }
366             };
367             this.write_vec_range(s.data, s.len * size, inner)
368         })
369     }
370
371     fn visit_evec_fixed(&mut self, n: uint, sz: uint, _align: uint,
372                         _: uint, inner: *TyDesc) -> bool {
373         let assumed_size = if sz == 0 { n } else { sz };
374         self.get::<()>(|this, b| {
375             this.write_vec_range(b, assumed_size, inner)
376         })
377     }
378
379     fn visit_enter_rec(&mut self, _n_fields: uint,
380                        _sz: uint, _align: uint) -> bool {
381         try!(self, self.writer.write(['{' as u8]));
382         true
383     }
384
385     fn visit_rec_field(&mut self, i: uint, name: &str,
386                        mtbl: uint, inner: *TyDesc) -> bool {
387         if i != 0 {
388             try!(self, self.writer.write(", ".as_bytes()));
389         }
390         self.write_mut_qualifier(mtbl);
391         try!(self, self.writer.write(name.as_bytes()));
392         try!(self, self.writer.write(": ".as_bytes()));
393         self.visit_inner(inner);
394         true
395     }
396
397     fn visit_leave_rec(&mut self, _n_fields: uint,
398                        _sz: uint, _align: uint) -> bool {
399         try!(self, self.writer.write(['}' as u8]));
400         true
401     }
402
403     fn visit_enter_class(&mut self, name: &str, named_fields: bool, n_fields: uint,
404                          _sz: uint, _align: uint) -> bool {
405         try!(self, self.writer.write(name.as_bytes()));
406         if n_fields != 0 {
407             if named_fields {
408                 try!(self, self.writer.write(['{' as u8]));
409             } else {
410                 try!(self, self.writer.write(['(' as u8]));
411             }
412         }
413         true
414     }
415
416     fn visit_class_field(&mut self, i: uint, name: &str, named: bool,
417                          _mtbl: uint, inner: *TyDesc) -> bool {
418         if i != 0 {
419             try!(self, self.writer.write(", ".as_bytes()));
420         }
421         if named {
422             try!(self, self.writer.write(name.as_bytes()));
423             try!(self, self.writer.write(": ".as_bytes()));
424         }
425         self.visit_inner(inner);
426         true
427     }
428
429     fn visit_leave_class(&mut self, _name: &str, named_fields: bool, n_fields: uint,
430                          _sz: uint, _align: uint) -> bool {
431         if n_fields != 0 {
432             if named_fields {
433                 try!(self, self.writer.write(['}' as u8]));
434             } else {
435                 try!(self, self.writer.write([')' as u8]));
436             }
437         }
438         true
439     }
440
441     fn visit_enter_tup(&mut self, _n_fields: uint,
442                        _sz: uint, _align: uint) -> bool {
443         try!(self, self.writer.write(['(' as u8]));
444         true
445     }
446
447     fn visit_tup_field(&mut self, i: uint, inner: *TyDesc) -> bool {
448         if i != 0 {
449             try!(self, self.writer.write(", ".as_bytes()));
450         }
451         self.visit_inner(inner);
452         true
453     }
454
455     fn visit_leave_tup(&mut self, _n_fields: uint,
456                        _sz: uint, _align: uint) -> bool {
457         if _n_fields == 1 {
458             try!(self, self.writer.write([',' as u8]));
459         }
460         try!(self, self.writer.write([')' as u8]));
461         true
462     }
463
464     fn visit_enter_enum(&mut self,
465                         _n_variants: uint,
466                         get_disr: extern unsafe fn(ptr: *Opaque) -> Disr,
467                         _sz: uint,
468                         _align: uint) -> bool {
469         let disr = unsafe {
470             get_disr(transmute(self.ptr))
471         };
472         self.var_stk.push(SearchingFor(disr));
473         true
474     }
475
476     fn visit_enter_enum_variant(&mut self, _variant: uint,
477                                 disr_val: Disr,
478                                 n_fields: uint,
479                                 name: &str) -> bool {
480         let mut write = false;
481         match self.var_stk.pop().unwrap() {
482             SearchingFor(sought) => {
483                 if disr_val == sought {
484                     self.var_stk.push(Matched);
485                     write = true;
486                 } else {
487                     self.var_stk.push(SearchingFor(sought));
488                 }
489             }
490             Matched | AlreadyFound => {
491                 self.var_stk.push(AlreadyFound);
492             }
493         }
494
495         if write {
496             try!(self, self.writer.write(name.as_bytes()));
497             if n_fields > 0 {
498                 try!(self, self.writer.write(['(' as u8]));
499             }
500         }
501         true
502     }
503
504     fn visit_enum_variant_field(&mut self,
505                                 i: uint,
506                                 _offset: uint,
507                                 inner: *TyDesc)
508                                 -> bool {
509         match *self.var_stk.get(self.var_stk.len() - 1) {
510             Matched => {
511                 if i != 0 {
512                     try!(self, self.writer.write(", ".as_bytes()));
513                 }
514                 if ! self.visit_inner(inner) {
515                     return false;
516                 }
517             }
518             _ => ()
519         }
520         true
521     }
522
523     fn visit_leave_enum_variant(&mut self, _variant: uint,
524                                 _disr_val: Disr,
525                                 n_fields: uint,
526                                 _name: &str) -> bool {
527         match *self.var_stk.get(self.var_stk.len() - 1) {
528             Matched => {
529                 if n_fields > 0 {
530                     try!(self, self.writer.write([')' as u8]));
531                 }
532             }
533             _ => ()
534         }
535         true
536     }
537
538     fn visit_leave_enum(&mut self,
539                         _n_variants: uint,
540                         _get_disr: extern unsafe fn(ptr: *Opaque) -> Disr,
541                         _sz: uint,
542                         _align: uint)
543                         -> bool {
544         match self.var_stk.pop().unwrap() {
545             SearchingFor(..) => fail!("enum value matched no variant"),
546             _ => true
547         }
548     }
549
550     fn visit_enter_fn(&mut self, _purity: uint, _proto: uint,
551                       _n_inputs: uint, _retstyle: uint) -> bool {
552         try!(self, self.writer.write("fn(".as_bytes()));
553         true
554     }
555
556     fn visit_fn_input(&mut self, i: uint, _mode: uint, inner: *TyDesc) -> bool {
557         if i != 0 {
558             try!(self, self.writer.write(", ".as_bytes()));
559         }
560         let name = unsafe { (*inner).name };
561         try!(self, self.writer.write(name.as_bytes()));
562         true
563     }
564
565     fn visit_fn_output(&mut self, _retstyle: uint, variadic: bool,
566                        inner: *TyDesc) -> bool {
567         if variadic {
568             try!(self, self.writer.write(", ...".as_bytes()));
569         }
570         try!(self, self.writer.write(")".as_bytes()));
571         let name = unsafe { (*inner).name };
572         if name != "()" {
573             try!(self, self.writer.write(" -> ".as_bytes()));
574             try!(self, self.writer.write(name.as_bytes()));
575         }
576         true
577     }
578
579     fn visit_leave_fn(&mut self, _purity: uint, _proto: uint,
580                       _n_inputs: uint, _retstyle: uint) -> bool { true }
581
582
583     fn visit_trait(&mut self, name: &str) -> bool {
584         try!(self, self.writer.write(name.as_bytes()));
585         true
586     }
587
588     fn visit_param(&mut self, _i: uint) -> bool { true }
589     fn visit_self(&mut self) -> bool { true }
590 }
591
592 pub fn write_repr<T>(writer: &mut io::Writer, object: &T) -> io::IoResult<()> {
593     unsafe {
594         let ptr = object as *T as *u8;
595         let tydesc = get_tydesc::<T>();
596         let u = ReprVisitor(ptr, writer);
597         let mut v = reflect::MovePtrAdaptor(u);
598         visit_tydesc(tydesc, &mut v as &mut TyVisitor);
599         match v.unwrap().last_err {
600             Some(e) => Err(e),
601             None => Ok(()),
602         }
603     }
604 }
605
606 pub fn repr_to_str<T>(t: &T) -> ~str {
607     use str;
608     use io;
609
610     let mut result = io::MemWriter::new();
611     write_repr(&mut result as &mut io::Writer, t).unwrap();
612     str::from_utf8(result.unwrap().as_slice()).unwrap().to_owned()
613 }
614
615 #[cfg(test)]
616 struct P {a: int, b: f64}
617
618 #[test]
619 fn test_repr() {
620     use prelude::*;
621     use str;
622     use str::Str;
623     use io::stdio::println;
624     use char::is_alphabetic;
625     use mem::swap;
626
627     fn exact_test<T>(t: &T, e:&str) {
628         let mut m = io::MemWriter::new();
629         write_repr(&mut m as &mut io::Writer, t).unwrap();
630         let s = str::from_utf8(m.unwrap().as_slice()).unwrap().to_owned();
631         assert_eq!(s.as_slice(), e);
632     }
633
634     exact_test(&10, "10");
635     exact_test(&true, "true");
636     exact_test(&false, "false");
637     exact_test(&1.234, "1.234f64");
638     exact_test(&(&"hello"), "\"hello\"");
639     exact_test(&(~"he\u10f3llo"), "~\"he\\u10f3llo\"");
640
641     exact_test(&(@10), "@10");
642     exact_test(&(~10), "~10");
643     exact_test(&(&10), "&10");
644     let mut x = 10;
645     exact_test(&(&mut x), "&mut 10");
646
647     exact_test(&(0 as *()), "(0x0 as *())");
648     exact_test(&(0 as *mut ()), "(0x0 as *mut ())");
649
650     exact_test(&(1,), "(1,)");
651     exact_test(&(~["hi", "there"]),
652                "~[\"hi\", \"there\"]");
653     exact_test(&(&["hi", "there"]),
654                "&[\"hi\", \"there\"]");
655     exact_test(&(P{a:10, b:1.234}),
656                "repr::P{a: 10, b: 1.234f64}");
657     exact_test(&(@P{a:10, b:1.234}),
658                "@repr::P{a: 10, b: 1.234f64}");
659     exact_test(&(~P{a:10, b:1.234}),
660                "~repr::P{a: 10, b: 1.234f64}");
661     exact_test(&(10u8, ~"hello"),
662                "(10u8, ~\"hello\")");
663     exact_test(&(10u16, ~"hello"),
664                "(10u16, ~\"hello\")");
665     exact_test(&(10u32, ~"hello"),
666                "(10u32, ~\"hello\")");
667     exact_test(&(10u64, ~"hello"),
668                "(10u64, ~\"hello\")");
669
670     exact_test(&(&[1, 2]), "&[1, 2]");
671     exact_test(&(&mut [1, 2]), "&mut [1, 2]");
672
673     exact_test(&'\'', "'\\''");
674     exact_test(&'"', "'\"'");
675     exact_test(&("'"), "\"'\"");
676     exact_test(&("\""), "\"\\\"\"");
677
678     exact_test(&println, "fn(&str)");
679     exact_test(&swap::<int>, "fn(&mut int, &mut int)");
680     exact_test(&is_alphabetic, "fn(char) -> bool");
681     exact_test(&(~5 as ~ToStr), "~to_str::ToStr<no-bounds>");
682
683     struct Foo;
684     exact_test(&(~[Foo, Foo]), "~[repr::test_repr::Foo, repr::test_repr::Foo]");
685
686     struct Bar(int, int);
687     exact_test(&(Bar(2, 2)), "repr::test_repr::Bar(2, 2)");
688 }