]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/reflect.rs
auto merge of #16766 : kevinmehall/rust/issue-15976, r=alexcrichton
[rust.git] / src / librustc / middle / trans / reflect.rs
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.
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 use back::link::mangle_internal_name_by_path_and_seq;
12 use llvm::{ValueRef, get_param};
13 use middle::trans::adt;
14 use middle::trans::base::*;
15 use middle::trans::build::*;
16 use middle::trans::callee::ArgVals;
17 use middle::trans::callee;
18 use middle::trans::common::*;
19 use middle::trans::datum::*;
20 use middle::trans::glue;
21 use middle::trans::machine;
22 use middle::trans::meth;
23 use middle::trans::type_::Type;
24 use middle::trans::type_of::*;
25 use middle::ty;
26 use util::ppaux::ty_to_string;
27
28 use arena::TypedArena;
29 use libc::c_uint;
30 use syntax::ast::DefId;
31 use syntax::ast;
32 use syntax::ast_map;
33 use syntax::parse::token::{InternedString, special_idents};
34 use syntax::parse::token;
35
36 pub struct Reflector<'a, 'b> {
37     visitor_val: ValueRef,
38     visitor_items: &'a [ty::ImplOrTraitItem],
39     final_bcx: &'b Block<'b>,
40     tydesc_ty: Type,
41     bcx: &'b Block<'b>
42 }
43
44 impl<'a, 'b> Reflector<'a, 'b> {
45     pub fn c_uint(&mut self, u: uint) -> ValueRef {
46         C_uint(self.bcx.ccx(), u)
47     }
48
49     pub fn c_bool(&mut self, b: bool) -> ValueRef {
50         C_bool(self.bcx.ccx(), b)
51     }
52
53     pub fn c_slice(&mut self, s: InternedString) -> ValueRef {
54         // We're careful to not use first class aggregates here because that
55         // will kick us off fast isel. (Issue #4352.)
56         let bcx = self.bcx;
57         let str_ty = ty::mk_str_slice(bcx.tcx(), ty::ReStatic, ast::MutImmutable);
58         let scratch = rvalue_scratch_datum(bcx, str_ty, "");
59         let len = C_uint(bcx.ccx(), s.get().len());
60         let c_str = PointerCast(bcx, C_cstr(bcx.ccx(), s, false), Type::i8p(bcx.ccx()));
61         Store(bcx, c_str, GEPi(bcx, scratch.val, [ 0, 0 ]));
62         Store(bcx, len, GEPi(bcx, scratch.val, [ 0, 1 ]));
63         scratch.val
64     }
65
66     pub fn c_size_and_align(&mut self, t: ty::t) -> Vec<ValueRef> {
67         let tr = type_of(self.bcx.ccx(), t);
68         let s = machine::llsize_of_real(self.bcx.ccx(), tr);
69         let a = align_of(self.bcx.ccx(), t);
70         return vec!(self.c_uint(s as uint),
71              self.c_uint(a as uint));
72     }
73
74     pub fn c_tydesc(&mut self, t: ty::t) -> ValueRef {
75         let bcx = self.bcx;
76         let static_ti = get_tydesc(bcx.ccx(), t);
77         glue::lazily_emit_visit_glue(bcx.ccx(), &*static_ti);
78         PointerCast(bcx, static_ti.tydesc, self.tydesc_ty.ptr_to())
79     }
80
81     pub fn c_mt(&mut self, mt: &ty::mt) -> Vec<ValueRef> {
82         vec!(self.c_uint(mt.mutbl as uint),
83           self.c_tydesc(mt.ty))
84     }
85
86     pub fn visit(&mut self, ty_name: &str, args: &[ValueRef]) {
87         let fcx = self.bcx.fcx;
88         let tcx = self.bcx.tcx();
89         let mth_idx = ty::impl_or_trait_item_idx(token::str_to_ident(format!(
90                         "visit_{}", ty_name).as_slice()),
91                                      self.visitor_items.as_slice()).expect(
92                 format!("couldn't find visit method for {}", ty_name).as_slice());
93         let method = match self.visitor_items[mth_idx] {
94             ty::MethodTraitItem(ref method) => (*method).clone(),
95         };
96         let mth_ty = ty::mk_bare_fn(tcx, method.fty.clone());
97         debug!("Emit call visit method: visit_{}: {}", ty_name, ty_to_string(tcx, mth_ty));
98         let v = self.visitor_val;
99         debug!("passing {} args:", args.len());
100         let mut bcx = self.bcx;
101         for (i, a) in args.iter().enumerate() {
102             debug!("arg {}: {}", i, bcx.val_to_string(*a));
103         }
104         let result = unpack_result!(bcx, callee::trans_call_inner(
105             self.bcx, None, mth_ty,
106             |bcx, _| meth::trans_trait_callee_from_llval(bcx,
107                                                          mth_ty,
108                                                          mth_idx,
109                                                          v),
110             ArgVals(args), None));
111         let next_bcx = fcx.new_temp_block("next");
112         CondBr(bcx, result, next_bcx.llbb, self.final_bcx.llbb);
113         self.bcx = next_bcx
114     }
115
116     pub fn bracketed(&mut self,
117                      bracket_name: &str,
118                      extra: &[ValueRef],
119                      inner: |&mut Reflector|) {
120         self.visit(format!("enter_{}", bracket_name).as_slice(), extra);
121         inner(self);
122         self.visit(format!("leave_{}", bracket_name).as_slice(), extra);
123     }
124
125     pub fn leaf(&mut self, name: &str) {
126         self.visit(name, []);
127     }
128
129     // Entrypoint
130     pub fn visit_ty(&mut self, t: ty::t) {
131         let bcx = self.bcx;
132         let tcx = bcx.tcx();
133         debug!("reflect::visit_ty {}", ty_to_string(bcx.tcx(), t));
134
135         match ty::get(t).sty {
136           ty::ty_bot => self.leaf("bot"),
137           ty::ty_nil => self.leaf("nil"),
138           ty::ty_bool => self.leaf("bool"),
139           ty::ty_char => self.leaf("char"),
140           ty::ty_int(ast::TyI) => self.leaf("int"),
141           ty::ty_int(ast::TyI8) => self.leaf("i8"),
142           ty::ty_int(ast::TyI16) => self.leaf("i16"),
143           ty::ty_int(ast::TyI32) => self.leaf("i32"),
144           ty::ty_int(ast::TyI64) => self.leaf("i64"),
145           ty::ty_uint(ast::TyU) => self.leaf("uint"),
146           ty::ty_uint(ast::TyU8) => self.leaf("u8"),
147           ty::ty_uint(ast::TyU16) => self.leaf("u16"),
148           ty::ty_uint(ast::TyU32) => self.leaf("u32"),
149           ty::ty_uint(ast::TyU64) => self.leaf("u64"),
150           ty::ty_float(ast::TyF32) => self.leaf("f32"),
151           ty::ty_float(ast::TyF64) => self.leaf("f64"),
152
153           ty::ty_open(_) | ty::ty_str | ty::ty_vec(_, None) | ty::ty_trait(..) => {
154               // Unfortunately we can't do anything here because at runtime we
155               // pass around the value by pointer (*u8). But unsized pointers are
156               // fat and so we can't just cast them to *u8 and back. So we have
157               // to work with the pointer directly (see ty_rptr/ty_uniq).
158               fail!("Can't reflect unsized type")
159           }
160           // FIXME(15049) Reflection for unsized structs.
161           ty::ty_struct(..) if !ty::type_is_sized(bcx.tcx(), t) => {
162               fail!("Can't reflect unsized type")
163           }
164
165           // Should rename to vec_*.
166           ty::ty_vec(ty, Some(sz)) => {
167               let mut extra = (vec!(self.c_uint(sz))).append(self.c_size_and_align(t).as_slice());
168               extra.push(self.c_tydesc(ty));
169               self.visit("evec_fixed", extra.as_slice())
170           }
171           // Should remove mt from box and uniq.
172           ty::ty_box(typ) => {
173               let extra = self.c_mt(&ty::mt {
174                   ty: typ,
175                   mutbl: ast::MutImmutable,
176               });
177               self.visit("box", extra.as_slice())
178           }
179           ty::ty_ptr(ref mt) => {
180               let extra = self.c_mt(mt);
181               self.visit("ptr", extra.as_slice())
182           }
183           ty::ty_uniq(typ) => {
184               match ty::get(typ).sty {
185                   ty::ty_trait(..) => {
186                       let extra = [
187                           self.c_slice(token::intern_and_get_ident(
188                                   ty_to_string(tcx, t).as_slice()))
189                       ];
190                       self.visit("trait", extra);
191                   }
192                   // FIXME(15049) allow reflection of Box<[T]>. You'll need to
193                   // restore visit_evec_uniq.
194                   ty::ty_vec(_, None) => {
195                       fail!("Box<[T]> theoretically doesn't exist, so don't try to reflect it")
196                   }
197                   ty::ty_str => fail!("Can't reflect Box<str> which shouldn't be used anyway"),
198                   _ => {
199                       let extra = self.c_mt(&ty::mt {
200                           ty: typ,
201                           mutbl: ast::MutImmutable,
202                       });
203                       self.visit("uniq", extra.as_slice())
204                   }
205               }
206           }
207           ty::ty_rptr(_, ref mt) => {
208               match ty::get(mt.ty).sty {
209                   ty::ty_vec(ty, None) => {
210                       let extra = self.c_mt(&ty::mt{ty: ty, mutbl: mt.mutbl});
211                       self.visit("evec_slice", extra.as_slice())
212                   }
213                   ty::ty_str => self.visit("estr_slice", &[]),
214                   ty::ty_trait(..) => {
215                       let extra = [
216                           self.c_slice(token::intern_and_get_ident(
217                                   ty_to_string(tcx, t).as_slice()))
218                       ];
219                       self.visit("trait", extra);
220                   }
221                   _ => {
222                       let extra = self.c_mt(mt);
223                       self.visit("rptr", extra.as_slice())
224                   }
225               }
226           }
227
228           ty::ty_tup(ref tys) => {
229               let extra = (vec!(self.c_uint(tys.len())))
230                           .append(self.c_size_and_align(t).as_slice());
231               self.bracketed("tup", extra.as_slice(), |this| {
232                   for (i, t) in tys.iter().enumerate() {
233                       let extra = vec!(this.c_uint(i), this.c_tydesc(*t));
234                       this.visit("tup_field", extra.as_slice());
235                   }
236               })
237           }
238
239           // FIXME (#2594): fetch constants out of intrinsic
240           // FIXME (#4809): visitor should break out bare fns from other fns
241           ty::ty_closure(ref fty) => {
242             let pureval = ast_fn_style_constant(fty.fn_style);
243             let sigilval = match fty.store {
244                 ty::UniqTraitStore => 2u,
245                 ty::RegionTraitStore(..) => 4u,
246             };
247             let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
248             let extra = vec!(self.c_uint(pureval),
249                           self.c_uint(sigilval),
250                           self.c_uint(fty.sig.inputs.len()),
251                           self.c_uint(retval));
252             self.visit("enter_fn", extra.as_slice());
253             self.visit_sig(retval, &fty.sig);
254             self.visit("leave_fn", extra.as_slice());
255           }
256
257           // FIXME (#2594): fetch constants out of intrinsic:: for the
258           // numbers.
259           ty::ty_bare_fn(ref fty) => {
260             let pureval = ast_fn_style_constant(fty.fn_style);
261             let sigilval = 0u;
262             let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
263             let extra = vec!(self.c_uint(pureval),
264                           self.c_uint(sigilval),
265                           self.c_uint(fty.sig.inputs.len()),
266                           self.c_uint(retval));
267             self.visit("enter_fn", extra.as_slice());
268             self.visit_sig(retval, &fty.sig);
269             self.visit("leave_fn", extra.as_slice());
270           }
271
272           ty::ty_struct(did, ref substs) => {
273               let fields = ty::struct_fields(tcx, did, substs);
274               let mut named_fields = false;
275               if !fields.is_empty() {
276                   named_fields = fields.get(0).ident.name !=
277                       special_idents::unnamed_field.name;
278               }
279
280               // This and the type_is_sized check on individual field types are
281               // because we cannot reflect unsized types (see note above). We
282               // just pretend the unsized field does not exist and print nothing.
283               // This is sub-optimal.
284               let len = fields.len();
285
286               let extra = (vec!(
287                   self.c_slice(
288                       token::intern_and_get_ident(ty_to_string(tcx,
289                                                             t).as_slice())),
290                   self.c_bool(named_fields),
291                   self.c_uint(len)
292               )).append(self.c_size_and_align(t).as_slice());
293               self.bracketed("class", extra.as_slice(), |this| {
294                   for (i, field) in fields.iter().enumerate() {
295                       let extra = (vec!(
296                         this.c_uint(i),
297                         this.c_slice(token::get_ident(field.ident)),
298                         this.c_bool(named_fields)
299                       )).append(this.c_mt(&field.mt).as_slice());
300                       this.visit("class_field", extra.as_slice());
301                   }
302               })
303           }
304
305           // FIXME (#2595): visiting all the variants in turn is probably
306           // not ideal. It'll work but will get costly on big enums. Maybe
307           // let the visitor tell us if it wants to visit only a particular
308           // variant?
309           ty::ty_enum(did, ref substs) => {
310             let ccx = bcx.ccx();
311             let repr = adt::represent_type(bcx.ccx(), t);
312             let variants = ty::substd_enum_variants(ccx.tcx(), did, substs);
313             let llptrty = type_of(ccx, t).ptr_to();
314             let opaquety = ty::get_opaque_ty(ccx.tcx()).unwrap();
315             let opaqueptrty = ty::mk_ptr(ccx.tcx(), ty::mt { ty: opaquety,
316                                                            mutbl: ast::MutImmutable });
317
318             let make_get_disr = || {
319                 let sym = mangle_internal_name_by_path_and_seq(
320                     ast_map::Values([].iter()).chain(None), "get_disr");
321
322                 let fn_ty = ty::mk_ctor_fn(&ccx.tcx, ast::DUMMY_NODE_ID,
323                                            [opaqueptrty], ty::mk_u64());
324                 let llfdecl = decl_internal_rust_fn(ccx,
325                                                     fn_ty,
326                                                     sym.as_slice());
327                 let arena = TypedArena::new();
328                 let empty_param_substs = param_substs::empty();
329                 let fcx = new_fn_ctxt(ccx, llfdecl, ast::DUMMY_NODE_ID, false,
330                                       ty::mk_u64(), &empty_param_substs,
331                                       None, &arena);
332                 let bcx = init_function(&fcx, false, ty::mk_u64());
333
334                 // we know the return type of llfdecl is an int here, so
335                 // no need for a special check to see if the return type
336                 // is immediate.
337                 let arg = get_param(llfdecl, fcx.arg_pos(0u) as c_uint);
338                 let arg = BitCast(bcx, arg, llptrty);
339                 let ret = adt::trans_get_discr(bcx, &*repr, arg, Some(Type::i64(ccx)));
340                 assert!(!fcx.needs_ret_allocas);
341                 let ret_slot = fcx.get_ret_slot(bcx, ty::mk_u64(), "ret_slot");
342                 Store(bcx, ret, ret_slot);
343                 match fcx.llreturn.get() {
344                     Some(llreturn) => Br(bcx, llreturn),
345                     None => {}
346                 };
347                 finish_fn(&fcx, bcx, ty::mk_u64());
348                 llfdecl
349             };
350
351             let enum_args = (vec!(self.c_uint(variants.len()), make_get_disr()))
352                             .append(self.c_size_and_align(t).as_slice());
353             self.bracketed("enum", enum_args.as_slice(), |this| {
354                 for (i, v) in variants.iter().enumerate() {
355                     let name = token::get_ident(v.name);
356                     let variant_args = [this.c_uint(i),
357                                          C_u64(ccx, v.disr_val),
358                                          this.c_uint(v.args.len()),
359                                          this.c_slice(name)];
360                     this.bracketed("enum_variant",
361                                    variant_args,
362                                    |this| {
363                         for (j, a) in v.args.iter().enumerate() {
364                             let bcx = this.bcx;
365                             let null = C_null(llptrty);
366                             let ptr = adt::trans_field_ptr(bcx, &*repr, null, v.disr_val, j);
367                             let offset = p2i(ccx, ptr);
368                             let field_args = [this.c_uint(j),
369                                                offset,
370                                                this.c_tydesc(*a)];
371                             this.visit("enum_variant_field",
372                                        field_args);
373                         }
374                     })
375                 }
376             })
377           }
378
379           // Miscellaneous extra types
380           ty::ty_infer(_) => self.leaf("infer"),
381           ty::ty_err => self.leaf("err"),
382           ty::ty_unboxed_closure(..) => self.leaf("err"),
383           ty::ty_param(ref p) => {
384               let extra = vec!(self.c_uint(p.idx));
385               self.visit("param", extra.as_slice())
386           }
387         }
388     }
389
390     pub fn visit_sig(&mut self, retval: uint, sig: &ty::FnSig) {
391         for (i, arg) in sig.inputs.iter().enumerate() {
392             let modeval = 5u;   // "by copy"
393             let extra = vec!(self.c_uint(i),
394                          self.c_uint(modeval),
395                          self.c_tydesc(*arg));
396             self.visit("fn_input", extra.as_slice());
397         }
398         let extra = vec!(self.c_uint(retval),
399                       self.c_bool(sig.variadic),
400                       self.c_tydesc(sig.output));
401         self.visit("fn_output", extra.as_slice());
402     }
403 }
404
405 // Emit a sequence of calls to visit_ty::visit_foo
406 pub fn emit_calls_to_trait_visit_ty<'a>(
407                                     bcx: &'a Block<'a>,
408                                     t: ty::t,
409                                     visitor_val: ValueRef,
410                                     visitor_trait_id: DefId)
411                                     -> &'a Block<'a> {
412     let fcx = bcx.fcx;
413     let final = fcx.new_temp_block("final");
414     let tydesc_ty = ty::get_tydesc_ty(bcx.tcx()).unwrap();
415     let tydesc_ty = type_of(bcx.ccx(), tydesc_ty);
416     let visitor_items = ty::trait_items(bcx.tcx(), visitor_trait_id);
417     let mut r = Reflector {
418         visitor_val: visitor_val,
419         visitor_items: visitor_items.as_slice(),
420         final_bcx: final,
421         tydesc_ty: tydesc_ty,
422         bcx: bcx
423     };
424     r.visit_ty(t);
425     Br(r.bcx, final.llbb);
426     return final;
427 }
428
429 pub fn ast_fn_style_constant(fn_style: ast::FnStyle) -> uint {
430     match fn_style {
431         ast::UnsafeFn => 1u,
432         ast::NormalFn => 2u,
433     }
434 }