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.
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::*;
26 use util::ppaux::ty_to_string;
28 use arena::TypedArena;
30 use syntax::ast::DefId;
33 use syntax::parse::token::{InternedString, special_idents};
34 use syntax::parse::token;
36 pub struct Reflector<'a, 'b> {
37 visitor_val: ValueRef,
38 visitor_items: &'a [ty::ImplOrTraitItem],
39 final_bcx: &'b Block<'b>,
44 impl<'a, 'b> Reflector<'a, 'b> {
45 pub fn c_uint(&mut self, u: uint) -> ValueRef {
46 C_uint(self.bcx.ccx(), u)
49 pub fn c_bool(&mut self, b: bool) -> ValueRef {
50 C_bool(self.bcx.ccx(), b)
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.)
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 ]));
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 = machine::llalign_of_min(self.bcx.ccx(), tr);
70 return vec!(self.c_uint(s as uint),
71 self.c_uint(a as uint));
74 pub fn c_tydesc(&mut self, t: ty::t) -> ValueRef {
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())
81 pub fn c_mt(&mut self, mt: &ty::mt) -> Vec<ValueRef> {
82 vec!(self.c_uint(mt.mutbl as uint),
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(),
96 let mth_ty = ty::mk_bare_fn(tcx, method.fty.clone());
97 debug!("Emit call visit method: visit_{}: {}", ty_name, ty_to_str(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));
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,
110 ArgVals(args), None));
111 let next_bcx = fcx.new_temp_block("next");
112 CondBr(bcx, result, next_bcx.llbb, self.final_bcx.llbb);
116 pub fn bracketed(&mut self,
119 inner: |&mut Reflector|) {
120 self.visit(format!("enter_{}", bracket_name).as_slice(), extra);
122 self.visit(format!("leave_{}", bracket_name).as_slice(), extra);
125 pub fn leaf(&mut self, name: &str) {
126 self.visit(name, []);
130 pub fn visit_ty(&mut self, t: ty::t) {
133 debug!("reflect::visit_ty {}", ty_to_string(bcx.tcx(), t));
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"),
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). See
158 // ty_struct for where this causes issues.
159 fail!("Can't reflect unsized type")
162 // Should rename to vec_*.
163 ty::ty_vec(ty, Some(sz)) => {
164 let mut extra = (vec!(self.c_uint(sz))).append(self.c_size_and_align(t).as_slice());
165 extra.push(self.c_tydesc(ty));
166 self.visit("evec_fixed", extra.as_slice())
168 // Should remove mt from box and uniq.
170 let extra = self.c_mt(&ty::mt {
172 mutbl: ast::MutImmutable,
174 self.visit("box", extra.as_slice())
176 ty::ty_ptr(ref mt) => {
177 let extra = self.c_mt(mt);
178 self.visit("ptr", extra.as_slice())
180 ty::ty_uniq(typ) => {
181 match ty::get(typ).sty {
182 ty::ty_trait(..) => {
184 self.c_slice(token::intern_and_get_ident(
185 ty_to_string(tcx, t).as_slice()))
187 self.visit("trait", extra);
189 // FIXME(15049) allow reflection of Box<[T]>. You'll need to
190 // restore visit_evec_uniq.
191 ty::ty_vec(_, None) => {
192 fail!("Box<[T]> theoretically doesn't exist, so don't try to reflect it")
194 ty::ty_str => fail!("Can't reflect Box<str> which shouldn't be used anyway"),
196 let extra = self.c_mt(&ty::mt {
198 mutbl: ast::MutImmutable,
200 self.visit("uniq", extra.as_slice())
204 ty::ty_rptr(_, ref mt) => {
205 match ty::get(mt.ty).sty {
206 ty::ty_vec(ty, None) => {
207 let extra = self.c_mt(&ty::mt{ty: ty, mutbl: mt.mutbl});
208 self.visit("evec_slice", extra.as_slice())
210 ty::ty_str => self.visit("estr_slice", &[]),
211 ty::ty_trait(..) => {
213 self.c_slice(token::intern_and_get_ident(
214 ty_to_string(tcx, t).as_slice()))
216 self.visit("trait", extra);
219 let extra = self.c_mt(mt);
220 self.visit("rptr", extra.as_slice())
225 ty::ty_tup(ref tys) => {
226 let extra = (vec!(self.c_uint(tys.len())))
227 .append(self.c_size_and_align(t).as_slice());
228 self.bracketed("tup", extra.as_slice(), |this| {
229 for (i, t) in tys.iter().enumerate() {
230 let extra = vec!(this.c_uint(i), this.c_tydesc(*t));
231 this.visit("tup_field", extra.as_slice());
236 // FIXME (#2594): fetch constants out of intrinsic
237 // FIXME (#4809): visitor should break out bare fns from other fns
238 ty::ty_closure(ref fty) => {
239 let pureval = ast_fn_style_constant(fty.fn_style);
240 let sigilval = match fty.store {
241 ty::UniqTraitStore => 2u,
242 ty::RegionTraitStore(..) => 4u,
244 let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
245 let extra = vec!(self.c_uint(pureval),
246 self.c_uint(sigilval),
247 self.c_uint(fty.sig.inputs.len()),
248 self.c_uint(retval));
249 self.visit("enter_fn", extra.as_slice());
250 self.visit_sig(retval, &fty.sig);
251 self.visit("leave_fn", extra.as_slice());
254 // FIXME (#2594): fetch constants out of intrinsic:: for the
256 ty::ty_bare_fn(ref fty) => {
257 let pureval = ast_fn_style_constant(fty.fn_style);
259 let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
260 let extra = vec!(self.c_uint(pureval),
261 self.c_uint(sigilval),
262 self.c_uint(fty.sig.inputs.len()),
263 self.c_uint(retval));
264 self.visit("enter_fn", extra.as_slice());
265 self.visit_sig(retval, &fty.sig);
266 self.visit("leave_fn", extra.as_slice());
269 ty::ty_struct(did, ref substs) => {
270 let fields = ty::struct_fields(tcx, did, substs);
271 let mut named_fields = false;
272 if !fields.is_empty() {
273 named_fields = fields.get(0).ident.name !=
274 special_idents::unnamed_field.name;
277 // This and the type_is_sized check on individual field types are
278 // because we cannot reflect unsized types (see note above). We
279 // just pretend the unsized field does not exist and print nothing.
280 // This is sub-optimal.
281 let len = if ty::type_is_sized(tcx, t) {
284 assert!(fields.len() > 0);
290 token::intern_and_get_ident(ty_to_string(tcx,
292 self.c_bool(named_fields),
294 )).append(self.c_size_and_align(t).as_slice());
295 self.bracketed("class", extra.as_slice(), |this| {
296 for (i, field) in fields.iter().enumerate() {
297 if ty::type_is_sized(tcx, field.mt.ty) {
300 this.c_slice(token::get_ident(field.ident)),
301 this.c_bool(named_fields)
302 )).append(this.c_mt(&field.mt).as_slice());
303 this.visit("class_field", extra.as_slice());
309 // FIXME (#2595): visiting all the variants in turn is probably
310 // not ideal. It'll work but will get costly on big enums. Maybe
311 // let the visitor tell us if it wants to visit only a particular
313 ty::ty_enum(did, ref substs) => {
315 let repr = adt::represent_type(bcx.ccx(), t);
316 let variants = ty::substd_enum_variants(ccx.tcx(), did, substs);
317 let llptrty = type_of(ccx, t).ptr_to();
318 let opaquety = ty::get_opaque_ty(ccx.tcx()).unwrap();
319 let opaqueptrty = ty::mk_ptr(ccx.tcx(), ty::mt { ty: opaquety,
320 mutbl: ast::MutImmutable });
322 let make_get_disr = || {
323 let sym = mangle_internal_name_by_path_and_seq(
324 ast_map::Values([].iter()).chain(None), "get_disr");
326 let fn_ty = ty::mk_ctor_fn(&ccx.tcx, ast::DUMMY_NODE_ID,
327 [opaqueptrty], ty::mk_u64());
328 let llfdecl = decl_internal_rust_fn(ccx,
331 let arena = TypedArena::new();
332 let empty_param_substs = param_substs::empty();
333 let fcx = new_fn_ctxt(ccx, llfdecl, ast::DUMMY_NODE_ID, false,
334 ty::mk_u64(), &empty_param_substs,
336 let bcx = init_function(&fcx, false, ty::mk_u64());
338 // we know the return type of llfdecl is an int here, so
339 // no need for a special check to see if the return type
341 let arg = get_param(llfdecl, fcx.arg_pos(0u) as c_uint);
342 let arg = BitCast(bcx, arg, llptrty);
343 let ret = adt::trans_get_discr(bcx, &*repr, arg, Some(Type::i64(ccx)));
344 assert!(!fcx.needs_ret_allocas);
345 let ret_slot = fcx.get_ret_slot(bcx, ty::mk_u64(), "ret_slot");
346 Store(bcx, ret, ret_slot);
347 match fcx.llreturn.get() {
348 Some(llreturn) => Br(bcx, llreturn),
351 finish_fn(&fcx, bcx, ty::mk_u64());
355 let enum_args = (vec!(self.c_uint(variants.len()), make_get_disr()))
356 .append(self.c_size_and_align(t).as_slice());
357 self.bracketed("enum", enum_args.as_slice(), |this| {
358 for (i, v) in variants.iter().enumerate() {
359 let name = token::get_ident(v.name);
360 let variant_args = [this.c_uint(i),
361 C_u64(ccx, v.disr_val),
362 this.c_uint(v.args.len()),
364 this.bracketed("enum_variant",
367 for (j, a) in v.args.iter().enumerate() {
369 let null = C_null(llptrty);
370 let ptr = adt::trans_field_ptr(bcx, &*repr, null, v.disr_val, j);
371 let offset = p2i(ccx, ptr);
372 let field_args = [this.c_uint(j),
375 this.visit("enum_variant_field",
383 // Miscellaneous extra types
384 ty::ty_infer(_) => self.leaf("infer"),
385 ty::ty_err => self.leaf("err"),
386 ty::ty_unboxed_closure(..) => self.leaf("err"),
387 ty::ty_param(ref p) => {
388 let extra = vec!(self.c_uint(p.idx));
389 self.visit("param", extra.as_slice())
394 pub fn visit_sig(&mut self, retval: uint, sig: &ty::FnSig) {
395 for (i, arg) in sig.inputs.iter().enumerate() {
396 let modeval = 5u; // "by copy"
397 let extra = vec!(self.c_uint(i),
398 self.c_uint(modeval),
399 self.c_tydesc(*arg));
400 self.visit("fn_input", extra.as_slice());
402 let extra = vec!(self.c_uint(retval),
403 self.c_bool(sig.variadic),
404 self.c_tydesc(sig.output));
405 self.visit("fn_output", extra.as_slice());
409 // Emit a sequence of calls to visit_ty::visit_foo
410 pub fn emit_calls_to_trait_visit_ty<'a>(
413 visitor_val: ValueRef,
414 visitor_trait_id: DefId)
417 let final = fcx.new_temp_block("final");
418 let tydesc_ty = ty::get_tydesc_ty(bcx.tcx()).unwrap();
419 let tydesc_ty = type_of(bcx.ccx(), tydesc_ty);
420 let visitor_items = ty::trait_items(bcx.tcx(), visitor_trait_id);
421 let mut r = Reflector {
422 visitor_val: visitor_val,
423 visitor_items: visitor_items.as_slice(),
425 tydesc_ty: tydesc_ty,
429 Br(r.bcx, final.llbb);
433 pub fn ast_fn_style_constant(fn_style: ast::FnStyle) -> uint {