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 = align_of(self.bcx.ccx(), t);
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_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));
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).
158 fail!("Can't reflect unsized type")
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")
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())
171 // Should remove mt from box and uniq.
173 let extra = self.c_mt(&ty::mt {
175 mutbl: ast::MutImmutable,
177 self.visit("box", extra.as_slice())
179 ty::ty_ptr(ref mt) => {
180 let extra = self.c_mt(mt);
181 self.visit("ptr", extra.as_slice())
183 ty::ty_uniq(typ) => {
184 match ty::get(typ).sty {
185 ty::ty_trait(..) => {
187 self.c_slice(token::intern_and_get_ident(
188 ty_to_string(tcx, t).as_slice()))
190 self.visit("trait", extra);
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")
197 ty::ty_str => fail!("Can't reflect Box<str> which shouldn't be used anyway"),
199 let extra = self.c_mt(&ty::mt {
201 mutbl: ast::MutImmutable,
203 self.visit("uniq", extra.as_slice())
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())
213 ty::ty_str => self.visit("estr_slice", &[]),
214 ty::ty_trait(..) => {
216 self.c_slice(token::intern_and_get_ident(
217 ty_to_string(tcx, t).as_slice()))
219 self.visit("trait", extra);
222 let extra = self.c_mt(mt);
223 self.visit("rptr", extra.as_slice())
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());
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,
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());
257 // FIXME (#2594): fetch constants out of intrinsic:: for the
259 ty::ty_bare_fn(ref fty) => {
260 let pureval = ast_fn_style_constant(fty.fn_style);
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());
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;
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();
288 token::intern_and_get_ident(ty_to_string(tcx,
290 self.c_bool(named_fields),
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() {
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());
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
309 ty::ty_enum(did, ref substs) => {
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 });
318 let make_get_disr = || {
319 let sym = mangle_internal_name_by_path_and_seq(
320 ast_map::Values([].iter()).chain(None), "get_disr");
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,
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,
332 let bcx = init_function(&fcx, false, ty::mk_u64());
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
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),
347 finish_fn(&fcx, bcx, ty::mk_u64());
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()),
360 this.bracketed("enum_variant",
363 for (j, a) in v.args.iter().enumerate() {
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),
371 this.visit("enum_variant_field",
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())
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());
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());
405 // Emit a sequence of calls to visit_ty::visit_foo
406 pub fn emit_calls_to_trait_visit_ty<'a>(
409 visitor_val: ValueRef,
410 visitor_trait_id: DefId)
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(),
421 tydesc_ty: tydesc_ty,
425 Br(r.bcx, final.llbb);
429 pub fn ast_fn_style_constant(fn_style: ast::FnStyle) -> uint {