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