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.
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.
13 More runtime type reflection
17 #![allow(missing_doc)]
21 use container::Container;
24 use option::{Some, None, Option};
27 use reflect::{MovePtr, align};
28 use result::{Ok, Err};
32 use intrinsics::{Disr, Opaque, TyDesc, TyVisitor, get_tydesc, visit_tydesc};
36 macro_rules! try( ($me:expr, $e:expr) => (
39 Err(e) => { $me.last_err = Some(e); return false; }
46 fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()>;
50 fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
51 writer.write("()".as_bytes())
56 fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
57 let s = if *self { "true" } else { "false" };
58 writer.write(s.as_bytes())
63 fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
64 write!(writer, "{}", *self)
68 macro_rules! int_repr(($ty:ident, $suffix:expr) => (impl Repr for $ty {
69 fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
70 write!(writer, "{}{}", *self, $suffix)
84 macro_rules! num_repr(($ty:ident, $suffix:expr) => (impl Repr for $ty {
85 fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
86 let s = self.to_str();
87 writer.write(s.as_bytes()).and_then(|()| {
88 writer.write(bytes!($suffix))
96 // New implementation using reflect::MovePtr
104 pub struct ReprVisitor<'a> {
107 var_stk: Vec<VariantState>,
108 writer: &'a mut io::Writer,
109 last_err: Option<io::IoError>,
112 pub fn ReprVisitor<'a>(ptr: *u8,
113 writer: &'a mut io::Writer) -> ReprVisitor<'a> {
123 impl<'a> MovePtr for ReprVisitor<'a> {
125 fn move_ptr(&mut self, adjustment: |*u8| -> *u8) {
126 self.ptr = adjustment(self.ptr);
128 fn push_ptr(&mut self) {
129 self.ptr_stk.push(self.ptr);
131 fn pop_ptr(&mut self) {
132 self.ptr = self.ptr_stk.pop().unwrap();
136 impl<'a> ReprVisitor<'a> {
137 // Various helpers for the TyVisitor impl
140 pub fn get<T>(&mut self, f: |&mut ReprVisitor, &T| -> bool) -> bool {
142 f(self, transmute::<*u8,&T>(self.ptr))
147 pub fn visit_inner(&mut self, inner: *TyDesc) -> bool {
148 self.visit_ptr_inner(self.ptr, inner)
152 pub fn visit_ptr_inner(&mut self, ptr: *u8, inner: *TyDesc) -> bool {
154 // This should call the constructor up above, but due to limiting
155 // issues we have to recreate it here.
156 let u = ReprVisitor {
160 writer: ::cast::transmute_copy(&self.writer),
163 let mut v = reflect::MovePtrAdaptor(u);
164 // Obviously this should not be a thing, but blame #8401 for now
165 visit_tydesc(inner, &mut v as &mut TyVisitor);
166 match v.unwrap().last_err {
168 self.last_err = Some(e);
177 pub fn write<T:Repr>(&mut self) -> bool {
178 self.get(|this, v:&T| {
179 try!(this, v.write_repr(this.writer));
184 pub fn write_escaped_slice(&mut self, slice: &str) -> bool {
185 try!(self, self.writer.write(['"' as u8]));
186 for ch in slice.chars() {
187 if !self.write_escaped_char(ch, true) { return false }
189 try!(self, self.writer.write(['"' as u8]));
193 pub fn write_mut_qualifier(&mut self, mtbl: uint) -> bool {
195 try!(self, self.writer.write("mut ".as_bytes()));
196 } else if mtbl == 1 {
197 // skip, this is ast::m_imm
199 fail!("invalid mutability value");
204 pub fn write_vec_range(&mut self, ptr: *(), len: uint, inner: *TyDesc) -> bool {
205 let mut p = ptr as *u8;
206 let (sz, al) = unsafe { ((*inner).size, (*inner).align) };
207 try!(self, self.writer.write(['[' as u8]));
208 let mut first = true;
210 // unit structs have 0 size, and don't loop forever.
211 let dec = if sz == 0 {1} else {sz};
216 try!(self, self.writer.write(", ".as_bytes()));
218 self.visit_ptr_inner(p as *u8, inner);
219 p = align(unsafe { p.offset(sz as int) as uint }, al) as *u8;
222 try!(self, self.writer.write([']' as u8]));
226 pub fn write_unboxed_vec_repr(&mut self, _: uint, v: &raw::Vec<()>, inner: *TyDesc) -> bool {
227 self.write_vec_range(&v.data, v.fill, inner)
230 fn write_escaped_char(&mut self, ch: char, is_str: bool) -> bool {
231 try!(self, match ch {
232 '\t' => self.writer.write("\\t".as_bytes()),
233 '\r' => self.writer.write("\\r".as_bytes()),
234 '\n' => self.writer.write("\\n".as_bytes()),
235 '\\' => self.writer.write("\\\\".as_bytes()),
238 self.writer.write("'".as_bytes())
240 self.writer.write("\\'".as_bytes())
245 self.writer.write("\\\"".as_bytes())
247 self.writer.write("\"".as_bytes())
250 '\x20'..'\x7e' => self.writer.write([ch as u8]),
252 char::escape_unicode(ch, |c| {
253 let _ = self.writer.write([c as u8]);
262 impl<'a> TyVisitor for ReprVisitor<'a> {
263 fn visit_bot(&mut self) -> bool {
264 try!(self, self.writer.write("!".as_bytes()));
267 fn visit_nil(&mut self) -> bool { self.write::<()>() }
268 fn visit_bool(&mut self) -> bool { self.write::<bool>() }
269 fn visit_int(&mut self) -> bool { self.write::<int>() }
270 fn visit_i8(&mut self) -> bool { self.write::<i8>() }
271 fn visit_i16(&mut self) -> bool { self.write::<i16>() }
272 fn visit_i32(&mut self) -> bool { self.write::<i32>() }
273 fn visit_i64(&mut self) -> bool { self.write::<i64>() }
275 fn visit_uint(&mut self) -> bool { self.write::<uint>() }
276 fn visit_u8(&mut self) -> bool { self.write::<u8>() }
277 fn visit_u16(&mut self) -> bool { self.write::<u16>() }
278 fn visit_u32(&mut self) -> bool { self.write::<u32>() }
279 fn visit_u64(&mut self) -> bool { self.write::<u64>() }
281 fn visit_f32(&mut self) -> bool { self.write::<f32>() }
282 fn visit_f64(&mut self) -> bool { self.write::<f64>() }
284 fn visit_char(&mut self) -> bool {
285 self.get::<char>(|this, &ch| {
286 try!(this, this.writer.write(['\'' as u8]));
287 if !this.write_escaped_char(ch, false) { return false }
288 try!(this, this.writer.write(['\'' as u8]));
293 fn visit_estr_box(&mut self) -> bool {
297 fn visit_estr_uniq(&mut self) -> bool {
298 self.get::<~str>(|this, s| {
299 try!(this, this.writer.write(['~' as u8]));
300 this.write_escaped_slice(*s)
304 fn visit_estr_slice(&mut self) -> bool {
305 self.get::<&str>(|this, s| this.write_escaped_slice(*s))
308 // Type no longer exists, vestigial function.
309 fn visit_estr_fixed(&mut self, _n: uint, _sz: uint,
310 _align: uint) -> bool { fail!(); }
312 fn visit_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
313 try!(self, self.writer.write(['@' as u8]));
314 self.write_mut_qualifier(mtbl);
315 self.get::<&raw::Box<()>>(|this, b| {
316 let p = &b.data as *() as *u8;
317 this.visit_ptr_inner(p, inner)
321 fn visit_uniq(&mut self, _mtbl: uint, inner: *TyDesc) -> bool {
322 try!(self, self.writer.write(['~' as u8]));
323 self.get::<*u8>(|this, b| {
324 this.visit_ptr_inner(*b, inner)
328 fn visit_ptr(&mut self, mtbl: uint, _inner: *TyDesc) -> bool {
329 self.get::<*u8>(|this, p| {
330 try!(this, write!(this.writer, "({} as *", *p));
331 this.write_mut_qualifier(mtbl);
332 try!(this, this.writer.write("())".as_bytes()));
337 fn visit_rptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
338 try!(self, self.writer.write(['&' as u8]));
339 self.write_mut_qualifier(mtbl);
340 self.get::<*u8>(|this, p| {
341 this.visit_ptr_inner(*p, inner)
345 fn visit_evec_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
346 self.get::<&raw::Box<raw::Vec<()>>>(|this, b| {
347 try!(this, this.writer.write(['@' as u8]));
348 this.write_mut_qualifier(mtbl);
349 this.write_unboxed_vec_repr(mtbl, &b.data, inner)
353 fn visit_evec_uniq(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
354 self.get::<&raw::Vec<()>>(|this, b| {
355 try!(this, this.writer.write(['~' as u8]));
356 this.write_unboxed_vec_repr(mtbl, *b, inner)
360 fn visit_evec_slice(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
361 self.get::<raw::Slice<()>>(|this, s| {
362 try!(this, this.writer.write(['&' as u8]));
363 this.write_mut_qualifier(mtbl);
365 if (*inner).size == 0 { 1 } else { (*inner).size }
367 this.write_vec_range(s.data, s.len * size, inner)
371 fn visit_evec_fixed(&mut self, n: uint, sz: uint, _align: uint,
372 _: uint, inner: *TyDesc) -> bool {
373 let assumed_size = if sz == 0 { n } else { sz };
374 self.get::<()>(|this, b| {
375 this.write_vec_range(b, assumed_size, inner)
379 fn visit_enter_rec(&mut self, _n_fields: uint,
380 _sz: uint, _align: uint) -> bool {
381 try!(self, self.writer.write(['{' as u8]));
385 fn visit_rec_field(&mut self, i: uint, name: &str,
386 mtbl: uint, inner: *TyDesc) -> bool {
388 try!(self, self.writer.write(", ".as_bytes()));
390 self.write_mut_qualifier(mtbl);
391 try!(self, self.writer.write(name.as_bytes()));
392 try!(self, self.writer.write(": ".as_bytes()));
393 self.visit_inner(inner);
397 fn visit_leave_rec(&mut self, _n_fields: uint,
398 _sz: uint, _align: uint) -> bool {
399 try!(self, self.writer.write(['}' as u8]));
403 fn visit_enter_class(&mut self, name: &str, named_fields: bool, n_fields: uint,
404 _sz: uint, _align: uint) -> bool {
405 try!(self, self.writer.write(name.as_bytes()));
408 try!(self, self.writer.write(['{' as u8]));
410 try!(self, self.writer.write(['(' as u8]));
416 fn visit_class_field(&mut self, i: uint, name: &str, named: bool,
417 _mtbl: uint, inner: *TyDesc) -> bool {
419 try!(self, self.writer.write(", ".as_bytes()));
422 try!(self, self.writer.write(name.as_bytes()));
423 try!(self, self.writer.write(": ".as_bytes()));
425 self.visit_inner(inner);
429 fn visit_leave_class(&mut self, _name: &str, named_fields: bool, n_fields: uint,
430 _sz: uint, _align: uint) -> bool {
433 try!(self, self.writer.write(['}' as u8]));
435 try!(self, self.writer.write([')' as u8]));
441 fn visit_enter_tup(&mut self, _n_fields: uint,
442 _sz: uint, _align: uint) -> bool {
443 try!(self, self.writer.write(['(' as u8]));
447 fn visit_tup_field(&mut self, i: uint, inner: *TyDesc) -> bool {
449 try!(self, self.writer.write(", ".as_bytes()));
451 self.visit_inner(inner);
455 fn visit_leave_tup(&mut self, _n_fields: uint,
456 _sz: uint, _align: uint) -> bool {
458 try!(self, self.writer.write([',' as u8]));
460 try!(self, self.writer.write([')' as u8]));
464 fn visit_enter_enum(&mut self,
466 get_disr: extern unsafe fn(ptr: *Opaque) -> Disr,
468 _align: uint) -> bool {
470 get_disr(transmute(self.ptr))
472 self.var_stk.push(SearchingFor(disr));
476 fn visit_enter_enum_variant(&mut self, _variant: uint,
479 name: &str) -> bool {
480 let mut write = false;
481 match self.var_stk.pop().unwrap() {
482 SearchingFor(sought) => {
483 if disr_val == sought {
484 self.var_stk.push(Matched);
487 self.var_stk.push(SearchingFor(sought));
490 Matched | AlreadyFound => {
491 self.var_stk.push(AlreadyFound);
496 try!(self, self.writer.write(name.as_bytes()));
498 try!(self, self.writer.write(['(' as u8]));
504 fn visit_enum_variant_field(&mut self,
509 match *self.var_stk.get(self.var_stk.len() - 1) {
512 try!(self, self.writer.write(", ".as_bytes()));
514 if ! self.visit_inner(inner) {
523 fn visit_leave_enum_variant(&mut self, _variant: uint,
526 _name: &str) -> bool {
527 match *self.var_stk.get(self.var_stk.len() - 1) {
530 try!(self, self.writer.write([')' as u8]));
538 fn visit_leave_enum(&mut self,
540 _get_disr: extern unsafe fn(ptr: *Opaque) -> Disr,
544 match self.var_stk.pop().unwrap() {
545 SearchingFor(..) => fail!("enum value matched no variant"),
550 fn visit_enter_fn(&mut self, _purity: uint, _proto: uint,
551 _n_inputs: uint, _retstyle: uint) -> bool {
552 try!(self, self.writer.write("fn(".as_bytes()));
556 fn visit_fn_input(&mut self, i: uint, _mode: uint, inner: *TyDesc) -> bool {
558 try!(self, self.writer.write(", ".as_bytes()));
560 let name = unsafe { (*inner).name };
561 try!(self, self.writer.write(name.as_bytes()));
565 fn visit_fn_output(&mut self, _retstyle: uint, variadic: bool,
566 inner: *TyDesc) -> bool {
568 try!(self, self.writer.write(", ...".as_bytes()));
570 try!(self, self.writer.write(")".as_bytes()));
571 let name = unsafe { (*inner).name };
573 try!(self, self.writer.write(" -> ".as_bytes()));
574 try!(self, self.writer.write(name.as_bytes()));
579 fn visit_leave_fn(&mut self, _purity: uint, _proto: uint,
580 _n_inputs: uint, _retstyle: uint) -> bool { true }
583 fn visit_trait(&mut self, name: &str) -> bool {
584 try!(self, self.writer.write(name.as_bytes()));
588 fn visit_param(&mut self, _i: uint) -> bool { true }
589 fn visit_self(&mut self) -> bool { true }
592 pub fn write_repr<T>(writer: &mut io::Writer, object: &T) -> io::IoResult<()> {
594 let ptr = object as *T as *u8;
595 let tydesc = get_tydesc::<T>();
596 let u = ReprVisitor(ptr, writer);
597 let mut v = reflect::MovePtrAdaptor(u);
598 visit_tydesc(tydesc, &mut v as &mut TyVisitor);
599 match v.unwrap().last_err {
606 pub fn repr_to_str<T>(t: &T) -> ~str {
610 let mut result = io::MemWriter::new();
611 write_repr(&mut result as &mut io::Writer, t).unwrap();
612 str::from_utf8(result.unwrap().as_slice()).unwrap().to_owned()
616 struct P {a: int, b: f64}
623 use io::stdio::println;
624 use char::is_alphabetic;
627 fn exact_test<T>(t: &T, e:&str) {
628 let mut m = io::MemWriter::new();
629 write_repr(&mut m as &mut io::Writer, t).unwrap();
630 let s = str::from_utf8(m.unwrap().as_slice()).unwrap().to_owned();
631 assert_eq!(s.as_slice(), e);
634 exact_test(&10, "10");
635 exact_test(&true, "true");
636 exact_test(&false, "false");
637 exact_test(&1.234, "1.234f64");
638 exact_test(&(&"hello"), "\"hello\"");
639 exact_test(&(~"he\u10f3llo"), "~\"he\\u10f3llo\"");
641 exact_test(&(@10), "@10");
642 exact_test(&(~10), "~10");
643 exact_test(&(&10), "&10");
645 exact_test(&(&mut x), "&mut 10");
647 exact_test(&(0 as *()), "(0x0 as *())");
648 exact_test(&(0 as *mut ()), "(0x0 as *mut ())");
650 exact_test(&(1,), "(1,)");
651 exact_test(&(~["hi", "there"]),
652 "~[\"hi\", \"there\"]");
653 exact_test(&(&["hi", "there"]),
654 "&[\"hi\", \"there\"]");
655 exact_test(&(P{a:10, b:1.234}),
656 "repr::P{a: 10, b: 1.234f64}");
657 exact_test(&(@P{a:10, b:1.234}),
658 "@repr::P{a: 10, b: 1.234f64}");
659 exact_test(&(~P{a:10, b:1.234}),
660 "~repr::P{a: 10, b: 1.234f64}");
661 exact_test(&(10u8, ~"hello"),
662 "(10u8, ~\"hello\")");
663 exact_test(&(10u16, ~"hello"),
664 "(10u16, ~\"hello\")");
665 exact_test(&(10u32, ~"hello"),
666 "(10u32, ~\"hello\")");
667 exact_test(&(10u64, ~"hello"),
668 "(10u64, ~\"hello\")");
670 exact_test(&(&[1, 2]), "&[1, 2]");
671 exact_test(&(&mut [1, 2]), "&mut [1, 2]");
673 exact_test(&'\'', "'\\''");
674 exact_test(&'"', "'\"'");
675 exact_test(&("'"), "\"'\"");
676 exact_test(&("\""), "\"\\\"\"");
678 exact_test(&println, "fn(&str)");
679 exact_test(&swap::<int>, "fn(&mut int, &mut int)");
680 exact_test(&is_alphabetic, "fn(char) -> bool");
681 exact_test(&(~5 as ~ToStr), "~to_str::ToStr<no-bounds>");
684 exact_test(&(~[Foo, Foo]), "~[repr::test_repr::Foo, repr::test_repr::Foo]");
686 struct Bar(int, int);
687 exact_test(&(Bar(2, 2)), "repr::test_repr::Bar(2, 2)");