]> git.lizzy.rs Git - rust.git/blob - src/libdebug/repr.rs
librustc: Don't try to perform the magical
[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($suffix)
79         })
80     }
81 }))
82
83 num_repr!(f32, b"f32")
84 num_repr!(f64, b"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
262     fn visit_char(&mut self) -> bool {
263         self.get::<char>(|this, &ch| {
264             try!(this, this.writer.write(['\'' as u8]));
265             if !this.write_escaped_char(ch, false) { return false }
266             try!(this, this.writer.write(['\'' as u8]));
267             true
268         })
269     }
270
271     fn visit_estr_slice(&mut self) -> bool {
272         self.get::<&str>(|this, s| this.write_escaped_slice(*s))
273     }
274
275     // Type no longer exists, vestigial function.
276     fn visit_estr_fixed(&mut self, _n: uint, _sz: uint,
277                         _align: uint) -> bool { fail!(); }
278
279     fn visit_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
280         try!(self, self.writer.write("box(GC) ".as_bytes()));
281         self.write_mut_qualifier(mtbl);
282         self.get::<&raw::Box<()>>(|this, b| {
283             let p = &b.data as *() as *u8;
284             this.visit_ptr_inner(p, inner)
285         })
286     }
287
288     fn visit_uniq(&mut self, _mtbl: uint, inner: *TyDesc) -> bool {
289         try!(self, self.writer.write("box ".as_bytes()));
290         self.get::<*u8>(|this, b| {
291             this.visit_ptr_inner(*b, inner)
292         })
293     }
294
295     fn visit_ptr(&mut self, mtbl: uint, _inner: *TyDesc) -> bool {
296         self.get::<*u8>(|this, p| {
297             try!(this, write!(this.writer, "({} as *", *p));
298             this.write_mut_qualifier(mtbl);
299             try!(this, this.writer.write("())".as_bytes()));
300             true
301         })
302     }
303
304     fn visit_rptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
305         try!(self, self.writer.write(['&' as u8]));
306         self.write_mut_qualifier(mtbl);
307         self.get::<*u8>(|this, p| {
308             this.visit_ptr_inner(*p, inner)
309         })
310     }
311
312     fn visit_evec_slice(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
313         self.get::<raw::Slice<()>>(|this, s| {
314             try!(this, this.writer.write(['&' as u8]));
315             this.write_mut_qualifier(mtbl);
316             let size = unsafe {
317                 if (*inner).size == 0 { 1 } else { (*inner).size }
318             };
319             this.write_vec_range(s.data, s.len * size, inner)
320         })
321     }
322
323     fn visit_evec_fixed(&mut self, n: uint, sz: uint, _align: uint,
324                         _: uint, inner: *TyDesc) -> bool {
325         let assumed_size = if sz == 0 { n } else { sz };
326         self.get::<()>(|this, b| {
327             this.write_vec_range(b, assumed_size, inner)
328         })
329     }
330
331     fn visit_enter_rec(&mut self, _n_fields: uint,
332                        _sz: uint, _align: uint) -> bool {
333         try!(self, self.writer.write(['{' as u8]));
334         true
335     }
336
337     fn visit_rec_field(&mut self, i: uint, name: &str,
338                        mtbl: uint, inner: *TyDesc) -> bool {
339         if i != 0 {
340             try!(self, self.writer.write(", ".as_bytes()));
341         }
342         self.write_mut_qualifier(mtbl);
343         try!(self, self.writer.write(name.as_bytes()));
344         try!(self, self.writer.write(": ".as_bytes()));
345         self.visit_inner(inner);
346         true
347     }
348
349     fn visit_leave_rec(&mut self, _n_fields: uint,
350                        _sz: uint, _align: uint) -> bool {
351         try!(self, self.writer.write(['}' as u8]));
352         true
353     }
354
355     fn visit_enter_class(&mut self, name: &str, named_fields: bool, n_fields: uint,
356                          _sz: uint, _align: uint) -> bool {
357         try!(self, self.writer.write(name.as_bytes()));
358         if n_fields != 0 {
359             if named_fields {
360                 try!(self, self.writer.write(['{' as u8]));
361             } else {
362                 try!(self, self.writer.write(['(' as u8]));
363             }
364         }
365         true
366     }
367
368     fn visit_class_field(&mut self, i: uint, name: &str, named: bool,
369                          _mtbl: uint, inner: *TyDesc) -> bool {
370         if i != 0 {
371             try!(self, self.writer.write(", ".as_bytes()));
372         }
373         if named {
374             try!(self, self.writer.write(name.as_bytes()));
375             try!(self, self.writer.write(": ".as_bytes()));
376         }
377         self.visit_inner(inner);
378         true
379     }
380
381     fn visit_leave_class(&mut self, _name: &str, named_fields: bool, n_fields: uint,
382                          _sz: uint, _align: uint) -> bool {
383         if n_fields != 0 {
384             if named_fields {
385                 try!(self, self.writer.write(['}' as u8]));
386             } else {
387                 try!(self, self.writer.write([')' as u8]));
388             }
389         }
390         true
391     }
392
393     fn visit_enter_tup(&mut self, _n_fields: uint,
394                        _sz: uint, _align: uint) -> bool {
395         try!(self, self.writer.write(['(' as u8]));
396         true
397     }
398
399     fn visit_tup_field(&mut self, i: uint, inner: *TyDesc) -> bool {
400         if i != 0 {
401             try!(self, self.writer.write(", ".as_bytes()));
402         }
403         self.visit_inner(inner);
404         true
405     }
406
407     fn visit_leave_tup(&mut self, _n_fields: uint,
408                        _sz: uint, _align: uint) -> bool {
409         if _n_fields == 1 {
410             try!(self, self.writer.write([',' as u8]));
411         }
412         try!(self, self.writer.write([')' as u8]));
413         true
414     }
415
416     fn visit_enter_enum(&mut self,
417                         _n_variants: uint,
418                         get_disr: unsafe extern fn(ptr: *Opaque) -> Disr,
419                         _sz: uint,
420                         _align: uint) -> bool {
421         let disr = unsafe {
422             get_disr(mem::transmute(self.ptr))
423         };
424         self.var_stk.push(SearchingFor(disr));
425         true
426     }
427
428     fn visit_enter_enum_variant(&mut self, _variant: uint,
429                                 disr_val: Disr,
430                                 n_fields: uint,
431                                 name: &str) -> bool {
432         let mut write = false;
433         match self.var_stk.pop().unwrap() {
434             SearchingFor(sought) => {
435                 if disr_val == sought {
436                     self.var_stk.push(Matched);
437                     write = true;
438                 } else {
439                     self.var_stk.push(SearchingFor(sought));
440                 }
441             }
442             Matched | AlreadyFound => {
443                 self.var_stk.push(AlreadyFound);
444             }
445         }
446
447         if write {
448             try!(self, self.writer.write(name.as_bytes()));
449             if n_fields > 0 {
450                 try!(self, self.writer.write(['(' as u8]));
451             }
452         }
453         true
454     }
455
456     fn visit_enum_variant_field(&mut self,
457                                 i: uint,
458                                 _offset: uint,
459                                 inner: *TyDesc)
460                                 -> bool {
461         match *self.var_stk.get(self.var_stk.len() - 1) {
462             Matched => {
463                 if i != 0 {
464                     try!(self, self.writer.write(", ".as_bytes()));
465                 }
466                 if ! self.visit_inner(inner) {
467                     return false;
468                 }
469             }
470             _ => ()
471         }
472         true
473     }
474
475     fn visit_leave_enum_variant(&mut self, _variant: uint,
476                                 _disr_val: Disr,
477                                 n_fields: uint,
478                                 _name: &str) -> bool {
479         match *self.var_stk.get(self.var_stk.len() - 1) {
480             Matched => {
481                 if n_fields > 0 {
482                     try!(self, self.writer.write([')' as u8]));
483                 }
484             }
485             _ => ()
486         }
487         true
488     }
489
490     fn visit_leave_enum(&mut self,
491                         _n_variants: uint,
492                         _get_disr: unsafe extern fn(ptr: *Opaque) -> Disr,
493                         _sz: uint,
494                         _align: uint)
495                         -> bool {
496         match self.var_stk.pop().unwrap() {
497             SearchingFor(..) => fail!("enum value matched no variant"),
498             _ => true
499         }
500     }
501
502     fn visit_enter_fn(&mut self, _purity: uint, _proto: uint,
503                       _n_inputs: uint, _retstyle: uint) -> bool {
504         try!(self, self.writer.write("fn(".as_bytes()));
505         true
506     }
507
508     fn visit_fn_input(&mut self, i: uint, _mode: uint, inner: *TyDesc) -> bool {
509         if i != 0 {
510             try!(self, self.writer.write(", ".as_bytes()));
511         }
512         let name = unsafe { (*inner).name };
513         try!(self, self.writer.write(name.as_bytes()));
514         true
515     }
516
517     fn visit_fn_output(&mut self, _retstyle: uint, variadic: bool,
518                        inner: *TyDesc) -> bool {
519         if variadic {
520             try!(self, self.writer.write(", ...".as_bytes()));
521         }
522         try!(self, self.writer.write(")".as_bytes()));
523         let name = unsafe { (*inner).name };
524         if name != "()" {
525             try!(self, self.writer.write(" -> ".as_bytes()));
526             try!(self, self.writer.write(name.as_bytes()));
527         }
528         true
529     }
530
531     fn visit_leave_fn(&mut self, _purity: uint, _proto: uint,
532                       _n_inputs: uint, _retstyle: uint) -> bool { true }
533
534
535     fn visit_trait(&mut self, name: &str) -> bool {
536         try!(self, self.writer.write(name.as_bytes()));
537         true
538     }
539
540     fn visit_param(&mut self, _i: uint) -> bool { true }
541     fn visit_self(&mut self) -> bool { true }
542 }
543
544 pub fn write_repr<T>(writer: &mut io::Writer, object: &T) -> io::IoResult<()> {
545     unsafe {
546         let ptr = object as *T as *u8;
547         let tydesc = get_tydesc::<T>();
548         let u = ReprVisitor::new(ptr, writer);
549         let mut v = reflect::MovePtrAdaptor::new(u);
550         visit_tydesc(tydesc, &mut v as &mut TyVisitor);
551         match v.unwrap().last_err {
552             Some(e) => Err(e),
553             None => Ok(()),
554         }
555     }
556 }
557
558 pub fn repr_to_str<T>(t: &T) -> String {
559     let mut result = io::MemWriter::new();
560     write_repr(&mut result as &mut io::Writer, t).unwrap();
561     String::from_utf8(result.unwrap()).unwrap()
562 }
563
564 #[cfg(test)]
565 struct P {a: int, b: f64}
566
567 #[test]
568 fn test_repr() {
569     use std::str;
570     use std::io::stdio::println;
571     use std::char::is_alphabetic;
572     use std::mem::swap;
573     use std::gc::GC;
574
575     fn exact_test<T>(t: &T, e:&str) {
576         let mut m = io::MemWriter::new();
577         write_repr(&mut m as &mut io::Writer, t).unwrap();
578         let s = str::from_utf8(m.unwrap().as_slice()).unwrap().to_string();
579         assert_eq!(s.as_slice(), e);
580     }
581
582     exact_test(&10, "10");
583     exact_test(&true, "true");
584     exact_test(&false, "false");
585     exact_test(&1.234, "1.234f64");
586     exact_test(&("hello"), "\"hello\"");
587
588     exact_test(&(box(GC) 10), "box(GC) 10");
589     exact_test(&(box 10), "box 10");
590     exact_test(&(&10), "&10");
591     let mut x = 10;
592     exact_test(&(&mut x), "&mut 10");
593
594     exact_test(&(0 as *()), "(0x0 as *())");
595     exact_test(&(0 as *mut ()), "(0x0 as *mut ())");
596
597     exact_test(&(1,), "(1,)");
598     exact_test(&(&["hi", "there"]),
599                "&[\"hi\", \"there\"]");
600     exact_test(&(P{a:10, b:1.234}),
601                "repr::P{a: 10, b: 1.234f64}");
602     exact_test(&(box(GC) P{a:10, b:1.234}),
603                "box(GC) repr::P{a: 10, b: 1.234f64}");
604     exact_test(&(box P{a:10, b:1.234}),
605                "box repr::P{a: 10, b: 1.234f64}");
606
607     exact_test(&(&[1, 2]), "&[1, 2]");
608     exact_test(&(&mut [1, 2]), "&mut [1, 2]");
609
610     exact_test(&'\'', "'\\''");
611     exact_test(&'"', "'\"'");
612     exact_test(&("'"), "\"'\"");
613     exact_test(&("\""), "\"\\\"\"");
614
615     exact_test(&println, "fn(&str)");
616     exact_test(&swap::<int>, "fn(&mut int, &mut int)");
617     exact_test(&is_alphabetic, "fn(char) -> bool");
618
619     struct Bar(int, int);
620     exact_test(&(Bar(2, 2)), "repr::test_repr::Bar(2, 2)");
621 }