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