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