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.
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
18 use std::intrinsics::{Disr, Opaque, TyDesc, TyVisitor, get_tydesc, visit_tydesc};
24 use reflect::{MovePtr, align};
26 macro_rules! try( ($me:expr, $e:expr) => (
29 Err(e) => { $me.last_err = Some(e); return false; }
36 fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()>;
40 fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
41 writer.write("()".as_bytes())
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())
53 fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
54 write!(writer, "{}", *self)
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)
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(|()| {
83 num_repr!(f32, b"f32")
84 num_repr!(f64, b"f64")
86 // New implementation using reflect::MovePtr
94 pub struct ReprVisitor<'a> {
96 ptr_stk: Vec<*const u8>,
97 var_stk: Vec<VariantState>,
98 writer: &'a mut io::Writer,
99 last_err: Option<io::IoError>,
102 impl<'a> MovePtr for ReprVisitor<'a> {
104 fn move_ptr(&mut self, adjustment: |*const u8| -> *const u8) {
105 self.ptr = adjustment(self.ptr);
107 fn push_ptr(&mut self) {
108 self.ptr_stk.push(self.ptr);
110 fn pop_ptr(&mut self) {
111 self.ptr = self.ptr_stk.pop().unwrap();
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> {
128 pub fn get<T>(&mut self, f: |&mut ReprVisitor, &T| -> bool) -> bool {
131 f(self, mem::transmute::<*const u8,&T>(ptr))
136 pub fn visit_inner(&mut self, inner: *const TyDesc) -> bool {
138 self.visit_ptr_inner(ptr, inner)
142 pub fn visit_ptr_inner(&mut self, ptr: *const u8,
143 inner: *const TyDesc) -> bool {
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 {
151 self.last_err = Some(e);
160 pub fn write<T:Repr>(&mut self) -> bool {
161 self.get(|this, v:&T| {
162 try!(this, v.write_repr(this.writer));
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 }
172 try!(self, self.writer.write(['"' as u8]));
176 pub fn write_mut_qualifier(&mut self, mtbl: uint) -> bool {
178 try!(self, self.writer.write("mut ".as_bytes()));
179 } else if mtbl == 1 {
180 // skip, this is ast::m_imm
182 fail!("invalid mutability value");
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;
194 // unit structs have 0 size, and don't loop forever.
195 let dec = if sz == 0 {1} else {sz};
200 try!(self, self.writer.write(", ".as_bytes()));
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;
206 try!(self, self.writer.write([']' as u8]));
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()),
218 self.writer.write("'".as_bytes())
220 self.writer.write("\\'".as_bytes())
225 self.writer.write("\\\"".as_bytes())
227 self.writer.write("\"".as_bytes())
230 '\x20'..'\x7e' => self.writer.write([ch as u8]),
232 char::escape_unicode(ch, |c| {
233 let _ = self.writer.write([c as u8]);
242 impl<'a> TyVisitor for ReprVisitor<'a> {
243 fn visit_bot(&mut self) -> bool {
244 try!(self, self.writer.write("!".as_bytes()));
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>() }
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>() }
261 fn visit_f32(&mut self) -> bool { self.write::<f32>() }
262 fn visit_f64(&mut self) -> bool { self.write::<f64>() }
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]));
273 fn visit_estr_slice(&mut self) -> bool {
274 self.get::<&str>(|this, s| this.write_escaped_slice(*s))
277 // Type no longer exists, vestigial function.
278 fn visit_estr_fixed(&mut self, _n: uint, _sz: uint,
279 _align: uint) -> bool { fail!(); }
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)
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)
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));
301 try!(this, this.writer.write("mut ".as_bytes()));
302 } else if mtbl == 1 {
303 try!(this, this.writer.write("const ".as_bytes()));
305 fail!("invalid mutability value");
307 try!(this, this.writer.write("())".as_bytes()));
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)
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);
325 if (*inner).size == 0 { 1 } else { (*inner).size }
327 this.write_vec_range(s.data, s.len * size, inner)
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)
339 fn visit_enter_rec(&mut self, _n_fields: uint,
340 _sz: uint, _align: uint) -> bool {
341 try!(self, self.writer.write(['{' as u8]));
345 fn visit_rec_field(&mut self, i: uint, name: &str,
346 mtbl: uint, inner: *const TyDesc) -> bool {
348 try!(self, self.writer.write(", ".as_bytes()));
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);
357 fn visit_leave_rec(&mut self, _n_fields: uint,
358 _sz: uint, _align: uint) -> bool {
359 try!(self, self.writer.write(['}' as u8]));
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()));
368 try!(self, self.writer.write(['{' as u8]));
370 try!(self, self.writer.write(['(' as u8]));
376 fn visit_class_field(&mut self, i: uint, name: &str, named: bool,
377 _mtbl: uint, inner: *const TyDesc) -> bool {
379 try!(self, self.writer.write(", ".as_bytes()));
382 try!(self, self.writer.write(name.as_bytes()));
383 try!(self, self.writer.write(": ".as_bytes()));
385 self.visit_inner(inner);
389 fn visit_leave_class(&mut self, _name: &str, named_fields: bool, n_fields: uint,
390 _sz: uint, _align: uint) -> bool {
393 try!(self, self.writer.write(['}' as u8]));
395 try!(self, self.writer.write([')' as u8]));
401 fn visit_enter_tup(&mut self, _n_fields: uint,
402 _sz: uint, _align: uint) -> bool {
403 try!(self, self.writer.write(['(' as u8]));
407 fn visit_tup_field(&mut self, i: uint, inner: *const TyDesc) -> bool {
409 try!(self, self.writer.write(", ".as_bytes()));
411 self.visit_inner(inner);
415 fn visit_leave_tup(&mut self, _n_fields: uint,
416 _sz: uint, _align: uint) -> bool {
418 try!(self, self.writer.write([',' as u8]));
420 try!(self, self.writer.write([')' as u8]));
424 fn visit_enter_enum(&mut self,
426 get_disr: unsafe extern fn(ptr: *const Opaque) -> Disr,
428 _align: uint) -> bool {
430 get_disr(mem::transmute(self.ptr))
432 self.var_stk.push(SearchingFor(disr));
436 fn visit_enter_enum_variant(&mut self, _variant: 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);
447 self.var_stk.push(SearchingFor(sought));
450 Matched | AlreadyFound => {
451 self.var_stk.push(AlreadyFound);
456 try!(self, self.writer.write(name.as_bytes()));
458 try!(self, self.writer.write(['(' as u8]));
464 fn visit_enum_variant_field(&mut self,
467 inner: *const TyDesc)
469 match *self.var_stk.get(self.var_stk.len() - 1) {
472 try!(self, self.writer.write(", ".as_bytes()));
474 if ! self.visit_inner(inner) {
483 fn visit_leave_enum_variant(&mut self, _variant: uint,
486 _name: &str) -> bool {
487 match *self.var_stk.get(self.var_stk.len() - 1) {
490 try!(self, self.writer.write([')' as u8]));
498 fn visit_leave_enum(&mut self,
500 _get_disr: unsafe extern fn(ptr: *const Opaque) -> Disr,
504 match self.var_stk.pop().unwrap() {
505 SearchingFor(..) => fail!("enum value matched no variant"),
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()));
516 fn visit_fn_input(&mut self, i: uint, _mode: uint,
517 inner: *const TyDesc) -> bool {
519 try!(self, self.writer.write(", ".as_bytes()));
521 let name = unsafe { (*inner).name };
522 try!(self, self.writer.write(name.as_bytes()));
526 fn visit_fn_output(&mut self, _retstyle: uint, variadic: bool,
527 inner: *const TyDesc) -> bool {
529 try!(self, self.writer.write(", ...".as_bytes()));
531 try!(self, self.writer.write(")".as_bytes()));
532 let name = unsafe { (*inner).name };
534 try!(self, self.writer.write(" -> ".as_bytes()));
535 try!(self, self.writer.write(name.as_bytes()));
540 fn visit_leave_fn(&mut self, _purity: uint, _proto: uint,
541 _n_inputs: uint, _retstyle: uint) -> bool { true }
544 fn visit_trait(&mut self, name: &str) -> bool {
545 try!(self, self.writer.write(name.as_bytes()));
549 fn visit_param(&mut self, _i: uint) -> bool { true }
550 fn visit_self(&mut self) -> bool { true }
553 pub fn write_repr<T>(writer: &mut io::Writer, object: &T) -> io::IoResult<()> {
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 {
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()
574 struct P {a: int, b: f64}
579 use std::io::stdio::println;
580 use std::char::is_alphabetic;
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);
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\"");
597 exact_test(&(box(GC) 10), "box(GC) 10");
598 exact_test(&(box 10), "box 10");
599 exact_test(&(&10), "&10");
601 exact_test(&(&mut x), "&mut 10");
603 exact_test(&(0 as *const ()), "(0x0 as *const ())");
604 exact_test(&(0 as *mut ()), "(0x0 as *mut ())");
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}");
616 exact_test(&(&[1, 2]), "&[1, 2]");
617 exact_test(&(&mut [1, 2]), "&mut [1, 2]");
619 exact_test(&'\'', "'\\''");
620 exact_test(&'"', "'\"'");
621 exact_test(&("'"), "\"'\"");
622 exact_test(&("\""), "\"\\\"\"");
624 exact_test(&println, "fn(&str)");
625 exact_test(&swap::<int>, "fn(&mut int, &mut int)");
626 exact_test(&is_alphabetic, "fn(char) -> bool");
628 struct Bar(int, int);
629 exact_test(&(Bar(2, 2)), "repr::test_repr::Bar(2, 2)");