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