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