]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/reflect.rs
auto merge of #16827 : steveklabnik/rust/fix_doc_index, r=brson
[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, 'blk, 'tcx: 'blk> {
37     visitor_val: ValueRef,
38     visitor_items: &'a [ty::ImplOrTraitItem],
39     final_bcx: Block<'blk, 'tcx>,
40     tydesc_ty: Type,
41     bcx: Block<'blk, 'tcx>
42 }
43
44 impl<'a, 'blk, 'tcx> Reflector<'a, 'blk, 'tcx> {
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_ptr/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               match ty::get(mt.ty).sty {
181                   ty::ty_vec(ty, None) => {
182                       let extra = self.c_mt(&ty::mt{ty: ty, mutbl: mt.mutbl});
183                       self.visit("evec_slice", extra.as_slice())
184                   }
185                   ty::ty_str => self.visit("estr_slice", &[]),
186                   ty::ty_trait(..) => {
187                       let extra = [
188                           self.c_slice(token::intern_and_get_ident(
189                                   ty_to_string(tcx, t).as_slice()))
190                       ];
191                       self.visit("trait", extra);
192                   }
193                   _ => {
194                       let extra = self.c_mt(mt);
195                       self.visit("ptr", extra.as_slice())
196                   }
197               }
198           }
199           ty::ty_uniq(typ) => {
200               match ty::get(typ).sty {
201                   ty::ty_trait(..) => {
202                       let extra = [
203                           self.c_slice(token::intern_and_get_ident(
204                                   ty_to_string(tcx, t).as_slice()))
205                       ];
206                       self.visit("trait", extra);
207                   }
208                   // FIXME(15049) allow reflection of Box<[T]>. You'll need to
209                   // restore visit_evec_uniq.
210                   ty::ty_vec(_, None) => {
211                       fail!("Box<[T]> theoretically doesn't exist, so don't try to reflect it")
212                   }
213                   ty::ty_str => fail!("Can't reflect Box<str> which shouldn't be used anyway"),
214                   _ => {
215                       let extra = self.c_mt(&ty::mt {
216                           ty: typ,
217                           mutbl: ast::MutImmutable,
218                       });
219                       self.visit("uniq", extra.as_slice())
220                   }
221               }
222           }
223           ty::ty_rptr(_, ref mt) => {
224               match ty::get(mt.ty).sty {
225                   ty::ty_vec(ty, None) => {
226                       let extra = self.c_mt(&ty::mt{ty: ty, mutbl: mt.mutbl});
227                       self.visit("evec_slice", extra.as_slice())
228                   }
229                   ty::ty_str => self.visit("estr_slice", &[]),
230                   ty::ty_trait(..) => {
231                       let extra = [
232                           self.c_slice(token::intern_and_get_ident(
233                                   ty_to_string(tcx, t).as_slice()))
234                       ];
235                       self.visit("trait", extra);
236                   }
237                   _ => {
238                       let extra = self.c_mt(mt);
239                       self.visit("rptr", extra.as_slice())
240                   }
241               }
242           }
243
244           ty::ty_tup(ref tys) => {
245               let extra = (vec!(self.c_uint(tys.len())))
246                           .append(self.c_size_and_align(t).as_slice());
247               self.bracketed("tup", extra.as_slice(), |this| {
248                   for (i, t) in tys.iter().enumerate() {
249                       let extra = vec!(this.c_uint(i), this.c_tydesc(*t));
250                       this.visit("tup_field", extra.as_slice());
251                   }
252               })
253           }
254
255           // FIXME (#2594): fetch constants out of intrinsic
256           // FIXME (#4809): visitor should break out bare fns from other fns
257           ty::ty_closure(ref fty) => {
258             let pureval = ast_fn_style_constant(fty.fn_style);
259             let sigilval = match fty.store {
260                 ty::UniqTraitStore => 2u,
261                 ty::RegionTraitStore(..) => 4u,
262             };
263             let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
264             let extra = vec!(self.c_uint(pureval),
265                           self.c_uint(sigilval),
266                           self.c_uint(fty.sig.inputs.len()),
267                           self.c_uint(retval));
268             self.visit("enter_fn", extra.as_slice());
269             self.visit_sig(retval, &fty.sig);
270             self.visit("leave_fn", extra.as_slice());
271           }
272
273           // FIXME (#2594): fetch constants out of intrinsic:: for the
274           // numbers.
275           ty::ty_bare_fn(ref fty) => {
276             let pureval = ast_fn_style_constant(fty.fn_style);
277             let sigilval = 0u;
278             let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
279             let extra = vec!(self.c_uint(pureval),
280                           self.c_uint(sigilval),
281                           self.c_uint(fty.sig.inputs.len()),
282                           self.c_uint(retval));
283             self.visit("enter_fn", extra.as_slice());
284             self.visit_sig(retval, &fty.sig);
285             self.visit("leave_fn", extra.as_slice());
286           }
287
288           ty::ty_struct(did, ref substs) => {
289               let fields = ty::struct_fields(tcx, did, substs);
290               let mut named_fields = false;
291               if !fields.is_empty() {
292                   named_fields = fields.get(0).ident.name !=
293                       special_idents::unnamed_field.name;
294               }
295
296               // This and the type_is_sized check on individual field types are
297               // because we cannot reflect unsized types (see note above). We
298               // just pretend the unsized field does not exist and print nothing.
299               // This is sub-optimal.
300               let len = fields.len();
301
302               let extra = (vec!(
303                   self.c_slice(
304                       token::intern_and_get_ident(ty_to_string(tcx,
305                                                             t).as_slice())),
306                   self.c_bool(named_fields),
307                   self.c_uint(len)
308               )).append(self.c_size_and_align(t).as_slice());
309               self.bracketed("class", extra.as_slice(), |this| {
310                   for (i, field) in fields.iter().enumerate() {
311                       let extra = (vec!(
312                         this.c_uint(i),
313                         this.c_slice(token::get_ident(field.ident)),
314                         this.c_bool(named_fields)
315                       )).append(this.c_mt(&field.mt).as_slice());
316                       this.visit("class_field", extra.as_slice());
317                   }
318               })
319           }
320
321           // FIXME (#2595): visiting all the variants in turn is probably
322           // not ideal. It'll work but will get costly on big enums. Maybe
323           // let the visitor tell us if it wants to visit only a particular
324           // variant?
325           ty::ty_enum(did, ref substs) => {
326             let ccx = bcx.ccx();
327             let repr = adt::represent_type(bcx.ccx(), t);
328             let variants = ty::substd_enum_variants(ccx.tcx(), did, substs);
329             let llptrty = type_of(ccx, t).ptr_to();
330             let opaquety = ty::get_opaque_ty(ccx.tcx()).unwrap();
331             let opaqueptrty = ty::mk_ptr(ccx.tcx(), ty::mt { ty: opaquety,
332                                                            mutbl: ast::MutImmutable });
333
334             let make_get_disr = || {
335                 let sym = mangle_internal_name_by_path_and_seq(
336                     ast_map::Values([].iter()).chain(None), "get_disr");
337
338                 let fn_ty = ty::mk_ctor_fn(ccx.tcx(), ast::DUMMY_NODE_ID,
339                                            [opaqueptrty], ty::mk_u64());
340                 let llfdecl = decl_internal_rust_fn(ccx,
341                                                     fn_ty,
342                                                     sym.as_slice());
343                 let arena = TypedArena::new();
344                 let empty_param_substs = param_substs::empty();
345                 let fcx = new_fn_ctxt(ccx, llfdecl, ast::DUMMY_NODE_ID, false,
346                                       ty::mk_u64(), &empty_param_substs,
347                                       None, &arena);
348                 let bcx = init_function(&fcx, false, ty::mk_u64());
349
350                 // we know the return type of llfdecl is an int here, so
351                 // no need for a special check to see if the return type
352                 // is immediate.
353                 let arg = get_param(llfdecl, fcx.arg_pos(0u) as c_uint);
354                 let arg = BitCast(bcx, arg, llptrty);
355                 let ret = adt::trans_get_discr(bcx, &*repr, arg, Some(Type::i64(ccx)));
356                 assert!(!fcx.needs_ret_allocas);
357                 let ret_slot = fcx.get_ret_slot(bcx, ty::mk_u64(), "ret_slot");
358                 Store(bcx, ret, ret_slot);
359                 match fcx.llreturn.get() {
360                     Some(llreturn) => Br(bcx, llreturn),
361                     None => {}
362                 };
363                 finish_fn(&fcx, bcx, ty::mk_u64());
364                 llfdecl
365             };
366
367             let enum_args = (vec!(self.c_uint(variants.len()), make_get_disr()))
368                             .append(self.c_size_and_align(t).as_slice());
369             self.bracketed("enum", enum_args.as_slice(), |this| {
370                 for (i, v) in variants.iter().enumerate() {
371                     let name = token::get_ident(v.name);
372                     let variant_args = [this.c_uint(i),
373                                          C_u64(ccx, v.disr_val),
374                                          this.c_uint(v.args.len()),
375                                          this.c_slice(name)];
376                     this.bracketed("enum_variant",
377                                    variant_args,
378                                    |this| {
379                         for (j, a) in v.args.iter().enumerate() {
380                             let bcx = this.bcx;
381                             let null = C_null(llptrty);
382                             let ptr = adt::trans_field_ptr(bcx, &*repr, null, v.disr_val, j);
383                             let offset = p2i(ccx, ptr);
384                             let field_args = [this.c_uint(j),
385                                                offset,
386                                                this.c_tydesc(*a)];
387                             this.visit("enum_variant_field",
388                                        field_args);
389                         }
390                     })
391                 }
392             })
393           }
394
395           // Miscellaneous extra types
396           ty::ty_infer(_) => self.leaf("infer"),
397           ty::ty_err => self.leaf("err"),
398           ty::ty_unboxed_closure(..) => self.leaf("err"),
399           ty::ty_param(ref p) => {
400               let extra = vec!(self.c_uint(p.idx));
401               self.visit("param", extra.as_slice())
402           }
403         }
404     }
405
406     pub fn visit_sig(&mut self, retval: uint, sig: &ty::FnSig) {
407         for (i, arg) in sig.inputs.iter().enumerate() {
408             let modeval = 5u;   // "by copy"
409             let extra = vec!(self.c_uint(i),
410                          self.c_uint(modeval),
411                          self.c_tydesc(*arg));
412             self.visit("fn_input", extra.as_slice());
413         }
414         let extra = vec!(self.c_uint(retval),
415                       self.c_bool(sig.variadic),
416                       self.c_tydesc(sig.output));
417         self.visit("fn_output", extra.as_slice());
418     }
419 }
420
421 // Emit a sequence of calls to visit_ty::visit_foo
422 pub fn emit_calls_to_trait_visit_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
423                                                 t: ty::t,
424                                                 visitor_val: ValueRef,
425                                                 visitor_trait_id: DefId)
426                                                 -> Block<'blk, 'tcx> {
427     let fcx = bcx.fcx;
428     let final = fcx.new_temp_block("final");
429     let tydesc_ty = ty::get_tydesc_ty(bcx.tcx()).unwrap();
430     let tydesc_ty = type_of(bcx.ccx(), tydesc_ty);
431     let visitor_items = ty::trait_items(bcx.tcx(), visitor_trait_id);
432     let mut r = Reflector {
433         visitor_val: visitor_val,
434         visitor_items: visitor_items.as_slice(),
435         final_bcx: final,
436         tydesc_ty: tydesc_ty,
437         bcx: bcx
438     };
439     r.visit_ty(t);
440     Br(r.bcx, final.llbb);
441     return final;
442 }
443
444 pub fn ast_fn_style_constant(fn_style: ast::FnStyle) -> uint {
445     match fn_style {
446         ast::UnsafeFn => 1u,
447         ast::NormalFn => 2u,
448     }
449 }