]> git.lizzy.rs Git - rust.git/blob - src/comp/middle/trans_closure.rs
Make binding of fns with bounded type parameters work
[rust.git] / src / comp / middle / trans_closure.rs
1 import syntax::ast;
2 import syntax::ast_util;
3 import lib::llvm::llvm;
4 import llvm::{ValueRef, TypeRef};
5 import trans_common::*;
6 import trans_build::*;
7 import trans::*;
8 import middle::freevars::{get_freevars, freevar_info};
9 import option::{some, none};
10 import back::abi;
11 import syntax::codemap::span;
12 import back::link::{
13     mangle_internal_name_by_path,
14     mangle_internal_name_by_path_and_seq};
15 import trans::{
16     trans_shared_malloc,
17     type_of_inner,
18     size_of,
19     node_id_type,
20     INIT,
21     trans_shared_free,
22     drop_ty,
23     new_sub_block_ctxt,
24     load_if_immediate,
25     dest
26 };
27
28 // ___Good to know (tm)__________________________________________________
29 //
30 // The layout of a closure environment in memory is
31 // roughly as follows:
32 //
33 // struct closure_box {
34 //    unsigned ref_count; // only used for sharid environments
35 //    struct closure {
36 //      type_desc *tydesc;         // descriptor for the env type
37 //      type_desc *bound_tdescs[]; // bound descriptors
38 //      struct {
39 //          upvar1_t upvar1;
40 //          ...
41 //          upvarN_t upvarN;
42 //      } bound_data;
43 //   };
44 // };
45 //
46 // NB: this struct is defined in the code in trans_common::T_closure()
47 // and mk_closure_ty() below.  The former defines the LLVM version and
48 // the latter the Rust equivalent.  It occurs to me that these could
49 // perhaps be unified, but currently they are not.
50 //
51 // Note that the closure carries a type descriptor that describes
52 // itself.  Trippy.  This is needed because the precise types of the
53 // closed over data are lost in the closure type (`fn(T)->U`), so if
54 // we need to take/drop, we must know what data is in the upvars and
55 // so forth.
56 //
57 // The allocation strategy for this closure depends on the closure
58 // type.  For a sendfn, the closure (and the referenced type
59 // descriptors) will be allocated in the exchange heap.  For a fn, the
60 // closure is allocated in the task heap and is reference counted.
61 // For a block, the closure is allocated on the stack.  Note that in
62 // all cases we allocate space for a ref count just to make our lives
63 // easier when upcasting to block(T)->U, in the shape code, and so
64 // forth.
65 //
66 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
67
68 tag environment_value {
69     // Evaluate expr and store result in env (used for bind).
70     env_expr(@ast::expr);
71
72     // Copy the value from this llvm ValueRef into the environment.
73     env_copy(ValueRef, ty::t, lval_kind);
74
75     // Move the value from this llvm ValueRef into the environment.
76     env_move(ValueRef, ty::t, lval_kind);
77
78     // Access by reference (used for blocks).
79     env_ref(ValueRef, ty::t, lval_kind);
80 }
81
82 // Given a closure ty, emits a corresponding tuple ty
83 fn mk_closure_ty(tcx: ty::ctxt,
84                  ck: ty::closure_kind,
85                  ty_params: [fn_ty_param],
86                  bound_data_ty: ty::t)
87     -> ty::t {
88     let tydesc_ty = alt ck {
89       ty::closure_block. | ty::closure_shared. { ty::mk_type(tcx) }
90       ty::closure_send. { ty::mk_send_type(tcx) }
91     };
92     let param_ptrs = [];
93     for tp in ty_params {
94         param_ptrs += [tydesc_ty];
95         option::may(tp.dicts) {|dicts|
96             for dict in dicts { param_ptrs += [tydesc_ty]; }
97         }
98     }
99     ty::mk_tup(tcx, [tydesc_ty, ty::mk_tup(tcx, param_ptrs), bound_data_ty])
100 }
101
102 fn shared_opaque_closure_box_ty(tcx: ty::ctxt) -> ty::t {
103     let opaque_closure_ty = ty::mk_opaque_closure(tcx);
104     ret ty::mk_imm_box(tcx, opaque_closure_ty);
105 }
106
107 fn send_opaque_closure_box_ty(tcx: ty::ctxt) -> ty::t {
108     let opaque_closure_ty = ty::mk_opaque_closure(tcx);
109     let tup_ty = ty::mk_tup(tcx, [ty::mk_int(tcx), opaque_closure_ty]);
110     ret ty::mk_uniq(tcx, {ty: tup_ty, mut: ast::imm});
111 }
112
113 type closure_result = {
114     llbox: ValueRef,  // llvalue of boxed environment
115     box_ty: ty::t,    // type of boxed environment
116     bcx: @block_ctxt  // final bcx
117 };
118
119 // Given a block context and a list of tydescs and values to bind
120 // construct a closure out of them. If copying is true, it is a
121 // heap allocated closure that copies the upvars into environment.
122 // Otherwise, it is stack allocated and copies pointers to the upvars.
123 fn store_environment(
124     bcx: @block_ctxt, lltyparams: [fn_ty_param],
125     bound_values: [environment_value],
126     ck: ty::closure_kind)
127     -> closure_result {
128
129     fn dummy_environment_box(bcx: @block_ctxt, r: result)
130         -> (@block_ctxt, ValueRef, ValueRef) {
131         // Prevent glue from trying to free this.
132         let ccx = bcx_ccx(bcx);
133         let ref_cnt = GEPi(bcx, r.val, [0, abi::box_rc_field_refcnt]);
134         Store(r.bcx, C_int(ccx, 2), ref_cnt);
135         let closure = GEPi(r.bcx, r.val, [0, abi::box_rc_field_body]);
136         (r.bcx, closure, r.val)
137     }
138
139     fn maybe_clone_tydesc(bcx: @block_ctxt,
140                           ck: ty::closure_kind,
141                           td: ValueRef) -> ValueRef {
142         ret alt ck {
143           ty::closure_block. | ty::closure_shared. {
144             td
145           }
146           ty::closure_send. {
147             Call(bcx, bcx_ccx(bcx).upcalls.create_shared_type_desc, [td])
148           }
149         };
150     }
151
152     //let ccx = bcx_ccx(bcx);
153     let tcx = bcx_tcx(bcx);
154
155     // First, synthesize a tuple type containing the types of all the
156     // bound expressions.
157     // bindings_ty = [bound_ty1, bound_ty2, ...]
158     let bound_tys = [];
159     for bv in bound_values {
160         bound_tys += [alt bv {
161             env_copy(_, t, _) { t }
162             env_move(_, t, _) { t }
163             env_ref(_, t, _) { t }
164             env_expr(e) { ty::expr_ty(tcx, e) }
165         }];
166     }
167     let bound_data_ty = ty::mk_tup(tcx, bound_tys);
168     let closure_ty =
169         mk_closure_ty(tcx, ck, lltyparams, bound_data_ty);
170
171     let temp_cleanups = [];
172
173     // Allocate a box that can hold something closure-sized.
174     //
175     // For now, no matter what kind of closure we have, we always allocate
176     // space for a ref cnt in the closure.  If the closure is a block or
177     // unique closure, this ref count isn't really used: we initialize it to 2
178     // so that it will never drop to zero.  This is a hack and could go away
179     // but then we'd have to modify the code to do the right thing when
180     // casting from a shared closure to a block.
181     let (bcx, closure, box) = alt ck {
182       ty::closure_shared. {
183         let r = trans::trans_malloc_boxed(bcx, closure_ty);
184         add_clean_free(bcx, r.box, false);
185         temp_cleanups += [r.box];
186         (r.bcx, r.body, r.box)
187       }
188       ty::closure_send. {
189         // Dummy up a box in the exchange heap.
190         let tup_ty = ty::mk_tup(tcx, [ty::mk_int(tcx), closure_ty]);
191         let box_ty = ty::mk_uniq(tcx, {ty: tup_ty, mut: ast::imm});
192         check trans_uniq::type_is_unique_box(bcx, box_ty);
193         let r = trans_uniq::alloc_uniq(bcx, box_ty);
194         add_clean_free(bcx, r.val, true);
195         temp_cleanups += [r.val];
196         dummy_environment_box(bcx, r)
197       }
198       ty::closure_block. {
199         // Dummy up a box on the stack,
200         let ty = ty::mk_tup(tcx, [ty::mk_int(tcx), closure_ty]);
201         let r = trans::alloc_ty(bcx, ty);
202         dummy_environment_box(bcx, r)
203       }
204     };
205
206     // Store bindings tydesc.
207     alt ck {
208       ty::closure_shared. | ty::closure_send. {
209         let bound_tydesc = GEPi(bcx, closure, [0, abi::closure_elt_tydesc]);
210         let ti = none;
211
212         // NDM I believe this is the correct value,
213         // but using it exposes bugs and limitations
214         // in the shape code.  Therefore, I am using
215         // tps_normal, which is what we used before.
216         //
217         // let tps = tps_fn(vec::len(lltyparams));
218
219         let tps = tps_normal;
220         let {result:closure_td, _} =
221             trans::get_tydesc(bcx, closure_ty, true, tps, ti);
222         trans::lazily_emit_tydesc_glue(bcx, abi::tydesc_field_drop_glue, ti);
223         trans::lazily_emit_tydesc_glue(bcx, abi::tydesc_field_free_glue, ti);
224         bcx = closure_td.bcx;
225         let td = maybe_clone_tydesc(bcx, ck, closure_td.val);
226         Store(bcx, td, bound_tydesc);
227       }
228       ty::closure_block. { /* skip this for blocks, not really relevant */ }
229     }
230
231     check type_is_tup_like(bcx, closure_ty);
232     let box_ty = ty::mk_imm_box(bcx_tcx(bcx), closure_ty);
233
234     // If necessary, copy tydescs describing type parameters into the
235     // appropriate slot in the closure.
236     let {bcx:bcx, val:ty_params_slot} =
237         GEP_tup_like_1(bcx, closure_ty, closure,
238                        [0, abi::closure_elt_ty_params]);
239     let off = 0;
240
241     for tp in lltyparams {
242         let cloned_td = maybe_clone_tydesc(bcx, ck, tp.desc);
243         Store(bcx, cloned_td, GEPi(bcx, ty_params_slot, [0, off]));
244         off += 1;
245         option::may(tp.dicts, {|dicts|
246             for dict in dicts {
247                 let cast = PointerCast(bcx, dict, val_ty(cloned_td));
248                 Store(bcx, cast, GEPi(bcx, ty_params_slot, [0, off]));
249                 off += 1;
250             }
251         });
252     }
253
254     // Copy expr values into boxed bindings.
255     // Silly check
256     vec::iteri(bound_values) { |i, bv|
257         let bound = trans::GEP_tup_like_1(bcx, box_ty, box,
258                                           [0, abi::box_rc_field_body,
259                                            abi::closure_elt_bindings,
260                                            i as int]);
261         bcx = bound.bcx;
262         alt bv {
263           env_expr(e) {
264             bcx = trans::trans_expr_save_in(bcx, e, bound.val);
265             add_clean_temp_mem(bcx, bound.val, bound_tys[i]);
266             temp_cleanups += [bound.val];
267           }
268           env_copy(val, ty, owned.) {
269             let val1 = load_if_immediate(bcx, val, ty);
270             bcx = trans::copy_val(bcx, INIT, bound.val, val1, ty);
271           }
272           env_copy(val, ty, owned_imm.) {
273             bcx = trans::copy_val(bcx, INIT, bound.val, val, ty);
274           }
275           env_copy(_, _, temporary.) {
276             fail "Cannot capture temporary upvar";
277           }
278           env_move(val, ty, kind) {
279             let src = {bcx:bcx, val:val, kind:kind};
280             bcx = move_val(bcx, INIT, bound.val, src, ty);
281           }
282           env_ref(val, ty, owned.) {
283             Store(bcx, val, bound.val);
284           }
285           env_ref(val, ty, owned_imm.) {
286             let addr = do_spill_noroot(bcx, val);
287             Store(bcx, addr, bound.val);
288           }
289           env_ref(_, _, temporary.) {
290             fail "Cannot capture temporary upvar";
291           }
292         }
293     }
294     for cleanup in temp_cleanups { revoke_clean(bcx, cleanup); }
295
296     ret {llbox: box, box_ty: box_ty, bcx: bcx};
297 }
298
299 // Given a context and a list of upvars, build a closure. This just
300 // collects the upvars and packages them up for store_environment.
301 fn build_closure(bcx0: @block_ctxt,
302                  cap_vars: [capture::capture_var],
303                  ck: ty::closure_kind)
304     -> closure_result {
305     // If we need to, package up the iterator body to call
306     let env_vals = [];
307     let bcx = bcx0;
308     let tcx = bcx_tcx(bcx);
309
310     // Package up the captured upvars
311     vec::iter(cap_vars) { |cap_var|
312         let lv = trans_local_var(bcx, cap_var.def);
313         let nid = ast_util::def_id_of_def(cap_var.def).node;
314         let ty = ty::node_id_to_monotype(tcx, nid);
315         alt cap_var.mode {
316           capture::cap_ref. {
317             assert ck == ty::closure_block;
318             ty = ty::mk_mut_ptr(tcx, ty);
319             env_vals += [env_ref(lv.val, ty, lv.kind)];
320           }
321           capture::cap_copy. {
322             env_vals += [env_copy(lv.val, ty, lv.kind)];
323           }
324           capture::cap_move. {
325             env_vals += [env_move(lv.val, ty, lv.kind)];
326           }
327           capture::cap_drop. {
328             bcx = drop_ty(bcx, lv.val, ty);
329           }
330         }
331     }
332     ret store_environment(bcx, copy bcx.fcx.lltyparams, env_vals, ck);
333 }
334
335 // Given an enclosing block context, a new function context, a closure type,
336 // and a list of upvars, generate code to load and populate the environment
337 // with the upvars and type descriptors.
338 fn load_environment(enclosing_cx: @block_ctxt,
339                     fcx: @fn_ctxt,
340                     boxed_closure_ty: ty::t,
341                     cap_vars: [capture::capture_var],
342                     ck: ty::closure_kind) {
343     let bcx = new_raw_block_ctxt(fcx, fcx.llloadenv);
344
345     let ccx = bcx_ccx(bcx);
346     let sp = bcx.sp;
347     check (type_has_static_size(ccx, boxed_closure_ty));
348     let llty = type_of(ccx, sp, boxed_closure_ty);
349     let llclosure = PointerCast(bcx, fcx.llenv, llty);
350
351     // Populate the type parameters from the environment. We need to
352     // do this first because the tydescs are needed to index into
353     // the bindings if they are dynamically sized.
354     let lltydescs = GEPi(bcx, llclosure,
355                          [0, abi::box_rc_field_body,
356                           abi::closure_elt_ty_params]);
357     let off = 0;
358     for tp in copy enclosing_cx.fcx.lltyparams {
359         let tydesc = Load(bcx, GEPi(bcx, lltydescs, [0, off]));
360         off += 1;
361         let dicts = option::map(tp.dicts, {|dicts|
362             let rslt = [];
363             for dict in dicts {
364                 let dict = Load(bcx, GEPi(bcx, lltydescs, [0, off]));
365                 rslt += [PointerCast(bcx, dict, T_ptr(T_dict()))];
366                 off += 1;
367             }
368             rslt
369         });
370         fcx.lltyparams += [{desc: tydesc, dicts: dicts}];
371     }
372
373     // Populate the upvars from the environment.
374     let path = [0, abi::box_rc_field_body, abi::closure_elt_bindings];
375     let i = 0u;
376     vec::iter(cap_vars) { |cap_var|
377         alt cap_var.mode {
378           capture::cap_drop. { /* ignore */ }
379           _ {
380             check type_is_tup_like(bcx, boxed_closure_ty);
381             let upvarptr = GEP_tup_like(
382                 bcx, boxed_closure_ty, llclosure, path + [i as int]);
383             bcx = upvarptr.bcx;
384             let llupvarptr = upvarptr.val;
385             alt ck {
386               ty::closure_block. { llupvarptr = Load(bcx, llupvarptr); }
387               ty::closure_send. | ty::closure_shared. { }
388             }
389             let def_id = ast_util::def_id_of_def(cap_var.def);
390             fcx.llupvars.insert(def_id.node, llupvarptr);
391             i += 1u;
392           }
393         }
394     }
395 }
396
397 fn trans_expr_fn(bcx: @block_ctxt,
398                  proto: ast::proto,
399                  decl: ast::fn_decl,
400                  body: ast::blk,
401                  sp: span,
402                  id: ast::node_id,
403                  cap_clause: ast::capture_clause,
404                  dest: dest) -> @block_ctxt {
405     if dest == ignore { ret bcx; }
406     let ccx = bcx_ccx(bcx), bcx = bcx;
407     let fty = node_id_type(ccx, id);
408     let llfnty = type_of_fn_from_ty(ccx, sp, fty, []);
409     let sub_cx = extend_path(bcx.fcx.lcx, ccx.names.next("anon"));
410     let s = mangle_internal_name_by_path(ccx, sub_cx.path);
411     let llfn = decl_internal_cdecl_fn(ccx.llmod, s, llfnty);
412     register_fn(ccx, sp, sub_cx.path, "anon fn", [], id);
413
414     let trans_closure_env = lambda(ck: ty::closure_kind) -> ValueRef {
415         let cap_vars = capture::compute_capture_vars(
416             ccx.tcx, id, proto, cap_clause);
417         let {llbox, box_ty, bcx} = build_closure(bcx, cap_vars, ck);
418         trans_closure(sub_cx, sp, decl, body, llfn, no_self, [], id, {|fcx|
419             load_environment(bcx, fcx, box_ty, cap_vars, ck);
420         });
421         llbox
422     };
423
424     let closure = alt proto {
425       ast::proto_block. { trans_closure_env(ty::closure_block) }
426       ast::proto_shared(_) { trans_closure_env(ty::closure_shared) }
427       ast::proto_send. { trans_closure_env(ty::closure_send) }
428       ast::proto_bare. {
429         let closure = C_null(T_opaque_boxed_closure_ptr(ccx));
430         trans_closure(sub_cx, sp, decl, body, llfn, no_self, [],
431                       id, {|_fcx|});
432         closure
433       }
434     };
435     fill_fn_pair(bcx, get_dest_addr(dest), llfn, closure);
436     ret bcx;
437 }
438
439 fn trans_bind(cx: @block_ctxt, f: @ast::expr, args: [option::t<@ast::expr>],
440               id: ast::node_id, dest: dest) -> @block_ctxt {
441     let f_res = trans_callee(cx, f);
442     ret trans_bind_1(cx, ty::expr_ty(bcx_tcx(cx), f), f_res, args,
443                      ty::node_id_to_type(bcx_tcx(cx), id), dest);
444 }
445
446 fn trans_bind_1(cx: @block_ctxt, outgoing_fty: ty::t,
447                 f_res: lval_maybe_callee,
448                 args: [option::t<@ast::expr>], pair_ty: ty::t,
449                 dest: dest) -> @block_ctxt {
450     let bound: [@ast::expr] = [];
451     for argopt: option::t<@ast::expr> in args {
452         alt argopt { none. { } some(e) { bound += [e]; } }
453     }
454     let bcx = f_res.bcx;
455     if dest == ignore {
456         for ex in bound { bcx = trans_expr(bcx, ex, ignore); }
457         ret bcx;
458     }
459
460     // Figure out which tydescs we need to pass, if any.
461     let (outgoing_fty_real, lltydescs, param_bounds) = alt f_res.generic {
462       none. { (outgoing_fty, [], @[]) }
463       some(ginfo) {
464         let tds = [], orig = 0u;
465         vec::iter2(ginfo.tydescs, *ginfo.param_bounds) {|td, bounds|
466             tds += [td];
467             for bound in *bounds {
468                 alt bound {
469                   ty::bound_iface(_) {
470                     let dict = trans_impl::get_dict(
471                         bcx, option::get(ginfo.origins)[orig]);
472                     tds += [PointerCast(bcx, dict.val, val_ty(td))];
473                     orig += 1u;
474                     bcx = dict.bcx;
475                   }
476                   _ {}
477                 }
478             }
479         }
480         lazily_emit_all_generic_info_tydesc_glues(cx, ginfo);
481         (ginfo.item_type, tds, ginfo.param_bounds)
482       }
483     };
484
485     if vec::len(bound) == 0u && vec::len(lltydescs) == 0u {
486         // Trivial 'binding': just return the closure
487         let lv = lval_maybe_callee_to_lval(f_res, pair_ty);
488         bcx = lv.bcx;
489         ret memmove_ty(bcx, get_dest_addr(dest), lv.val, pair_ty);
490     }
491     let closure = alt f_res.env {
492       null_env. { none }
493       _ { let (_, cl) = maybe_add_env(cx, f_res); some(cl) }
494     };
495
496     // FIXME: should follow from a precondition on trans_bind_1
497     let ccx = bcx_ccx(cx);
498     check (type_has_static_size(ccx, outgoing_fty));
499
500     // Arrange for the bound function to live in the first binding spot
501     // if the function is not statically known.
502     let (env_vals, target_res) = alt closure {
503       some(cl) {
504         // Cast the function we are binding to be the type that the
505         // closure will expect it to have. The type the closure knows
506         // about has the type parameters substituted with the real types.
507         let sp = cx.sp;
508         let llclosurety = T_ptr(type_of(ccx, sp, outgoing_fty));
509         let src_loc = PointerCast(bcx, cl, llclosurety);
510         ([env_copy(src_loc, pair_ty, owned)], none)
511       }
512       none. { ([], some(f_res.val)) }
513     };
514
515     // Actually construct the closure
516     let {llbox, box_ty, bcx} = store_environment(
517         bcx, vec::map(lltydescs, {|d| {desc: d, dicts: none}}),
518         env_vals + vec::map(bound, {|x| env_expr(x)}),
519         ty::closure_shared);
520
521     // Make thunk
522     let llthunk =
523         trans_bind_thunk(cx.fcx.lcx, cx.sp, pair_ty, outgoing_fty_real, args,
524                          box_ty, *param_bounds, target_res);
525
526     // Fill the function pair
527     fill_fn_pair(bcx, get_dest_addr(dest), llthunk.val, llbox);
528     ret bcx;
529 }
530
531 fn make_fn_glue(
532     cx: @block_ctxt,
533     v: ValueRef,
534     t: ty::t,
535     glue_fn: fn(@block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt)
536     -> @block_ctxt {
537     let bcx = cx;
538     let tcx = bcx_tcx(cx);
539
540     let fn_env = lambda(blk: block(@block_ctxt, ValueRef) -> @block_ctxt)
541         -> @block_ctxt {
542         let box_cell_v = GEPi(cx, v, [0, abi::fn_field_box]);
543         let box_ptr_v = Load(cx, box_cell_v);
544         let inner_cx = new_sub_block_ctxt(cx, "iter box");
545         let next_cx = new_sub_block_ctxt(cx, "next");
546         let null_test = IsNull(cx, box_ptr_v);
547         CondBr(cx, null_test, next_cx.llbb, inner_cx.llbb);
548         inner_cx = blk(inner_cx, box_cell_v);
549         Br(inner_cx, next_cx.llbb);
550         ret next_cx;
551     };
552
553     ret alt ty::struct(tcx, t) {
554       ty::ty_native_fn(_, _) | ty::ty_fn({proto: ast::proto_bare., _}) {
555         bcx
556       }
557       ty::ty_fn({proto: ast::proto_block., _}) {
558         bcx
559       }
560       ty::ty_fn({proto: ast::proto_send., _}) {
561         fn_env({ |bcx, box_cell_v|
562             let box_ty = trans_closure::send_opaque_closure_box_ty(tcx);
563             glue_fn(bcx, box_cell_v, box_ty)
564         })
565       }
566       ty::ty_fn({proto: ast::proto_shared(_), _}) {
567         fn_env({ |bcx, box_cell_v|
568             let box_ty = trans_closure::shared_opaque_closure_box_ty(tcx);
569             glue_fn(bcx, box_cell_v, box_ty)
570         })
571       }
572       _ { fail "make_fn_glue invoked on non-function type" }
573     };
574 }
575
576 fn call_opaque_closure_glue(bcx: @block_ctxt,
577                             v: ValueRef,     // ptr to an opaque closure
578                             field: int) -> @block_ctxt {
579     let ccx = bcx_ccx(bcx);
580     let v = PointerCast(bcx, v, T_ptr(T_opaque_closure(ccx)));
581     let tydescptr = GEPi(bcx, v, [0, abi::closure_elt_tydesc]);
582     let tydesc = Load(bcx, tydescptr);
583     let ti = none;
584     call_tydesc_glue_full(bcx, v, tydesc, field, ti);
585     ret bcx;
586 }
587
588 // pth is cx.path
589 fn trans_bind_thunk(cx: @local_ctxt,
590                     sp: span,
591                     incoming_fty: ty::t,
592                     outgoing_fty: ty::t,
593                     args: [option::t<@ast::expr>],
594                     boxed_closure_ty: ty::t,
595                     param_bounds: [ty::param_bounds],
596                     target_fn: option::t<ValueRef>)
597     -> {val: ValueRef, ty: TypeRef} {
598     // If we supported constraints on record fields, we could make the
599     // constraints for this function:
600     /*
601     : returns_non_ty_var(ccx, outgoing_fty),
602       type_has_static_size(ccx, incoming_fty) ->
603     */
604     // but since we don't, we have to do the checks at the beginning.
605     let ccx = cx.ccx;
606     check type_has_static_size(ccx, incoming_fty);
607
608     // Here we're not necessarily constructing a thunk in the sense of
609     // "function with no arguments".  The result of compiling 'bind f(foo,
610     // bar, baz)' would be a thunk that, when called, applies f to those
611     // arguments and returns the result.  But we're stretching the meaning of
612     // the word "thunk" here to also mean the result of compiling, say, 'bind
613     // f(foo, _, baz)', or any other bind expression that binds f and leaves
614     // some (or all) of the arguments unbound.
615
616     // Here, 'incoming_fty' is the type of the entire bind expression, while
617     // 'outgoing_fty' is the type of the function that is having some of its
618     // arguments bound.  If f is a function that takes three arguments of type
619     // int and returns int, and we're translating, say, 'bind f(3, _, 5)',
620     // then outgoing_fty is the type of f, which is (int, int, int) -> int,
621     // and incoming_fty is the type of 'bind f(3, _, 5)', which is int -> int.
622
623     // Once translated, the entire bind expression will be the call f(foo,
624     // bar, baz) wrapped in a (so-called) thunk that takes 'bar' as its
625     // argument and that has bindings of 'foo' to 3 and 'baz' to 5 and a
626     // pointer to 'f' all saved in its environment.  So, our job is to
627     // construct and return that thunk.
628
629     // Give the thunk a name, type, and value.
630     let s: str = mangle_internal_name_by_path_and_seq(ccx, cx.path, "thunk");
631     let llthunk_ty: TypeRef = get_pair_fn_ty(type_of(ccx, sp, incoming_fty));
632     let llthunk: ValueRef = decl_internal_cdecl_fn(ccx.llmod, s, llthunk_ty);
633
634     // Create a new function context and block context for the thunk, and hold
635     // onto a pointer to the first block in the function for later use.
636     let fcx = new_fn_ctxt(cx, sp, llthunk);
637     let bcx = new_top_block_ctxt(fcx);
638     let lltop = bcx.llbb;
639     // Since we might need to construct derived tydescs that depend on
640     // our bound tydescs, we need to load tydescs out of the environment
641     // before derived tydescs are constructed. To do this, we load them
642     // in the load_env block.
643     let l_bcx = new_raw_block_ctxt(fcx, fcx.llloadenv);
644
645     // The 'llenv' that will arrive in the thunk we're creating is an
646     // environment that will contain the values of its arguments and a pointer
647     // to the original function.  So, let's create one of those:
648
649     // The llenv pointer needs to be the correct size.  That size is
650     // 'boxed_closure_ty', which was determined by trans_bind.
651     check (type_has_static_size(ccx, boxed_closure_ty));
652     let llclosure_ptr_ty = type_of(ccx, sp, boxed_closure_ty);
653     let llclosure = PointerCast(l_bcx, fcx.llenv, llclosure_ptr_ty);
654
655     // "target", in this context, means the function that's having some of its
656     // arguments bound and that will be called inside the thunk we're
657     // creating.  (In our running example, target is the function f.)  Pick
658     // out the pointer to the target function from the environment. The
659     // target function lives in the first binding spot.
660     let (lltargetfn, lltargetenv, starting_idx) = alt target_fn {
661       some(fptr) {
662         (fptr, llvm::LLVMGetUndef(T_opaque_boxed_closure_ptr(ccx)), 0)
663       }
664       none. {
665         // Silly check
666         check type_is_tup_like(bcx, boxed_closure_ty);
667         let {bcx: cx, val: pair} =
668             GEP_tup_like(bcx, boxed_closure_ty, llclosure,
669                          [0, abi::box_rc_field_body,
670                           abi::closure_elt_bindings, 0]);
671         let lltargetenv =
672             Load(cx, GEPi(cx, pair, [0, abi::fn_field_box]));
673         let lltargetfn = Load
674             (cx, GEPi(cx, pair, [0, abi::fn_field_code]));
675         bcx = cx;
676         (lltargetfn, lltargetenv, 1)
677       }
678     };
679
680     // And then, pick out the target function's own environment.  That's what
681     // we'll use as the environment the thunk gets.
682
683     // Get f's return type, which will also be the return type of the entire
684     // bind expression.
685     let outgoing_ret_ty = ty::ty_fn_ret(cx.ccx.tcx, outgoing_fty);
686
687     // Get the types of the arguments to f.
688     let outgoing_args = ty::ty_fn_args(cx.ccx.tcx, outgoing_fty);
689
690     // The 'llretptr' that will arrive in the thunk we're creating also needs
691     // to be the correct type.  Cast it to f's return type, if necessary.
692     let llretptr = fcx.llretptr;
693     let ccx = cx.ccx;
694     if ty::type_contains_params(ccx.tcx, outgoing_ret_ty) {
695         check non_ty_var(ccx, outgoing_ret_ty);
696         let llretty = type_of_inner(ccx, sp, outgoing_ret_ty);
697         llretptr = PointerCast(bcx, llretptr, T_ptr(llretty));
698     }
699
700     // Set up the three implicit arguments to the thunk.
701     let llargs: [ValueRef] = [llretptr, lltargetenv];
702
703     // Copy in the type parameters.
704     check type_is_tup_like(l_bcx, boxed_closure_ty);
705     let {bcx: l_bcx, val: param_record} =
706         GEP_tup_like(l_bcx, boxed_closure_ty, llclosure,
707                      [0, abi::box_rc_field_body, abi::closure_elt_ty_params]);
708     let off = 0;
709     for param in param_bounds {
710         let dsc = Load(l_bcx, GEPi(l_bcx, param_record, [0, off])),
711             dicts = none;
712         llargs += [dsc];
713         off += 1;
714         for bound in *param {
715             alt bound {
716               ty::bound_iface(_) {
717                 let dict = Load(l_bcx, GEPi(l_bcx, param_record, [0, off]));
718                 dict = PointerCast(l_bcx, dict, T_ptr(T_dict()));
719                 llargs += [dict];
720                 off += 1;
721                 dicts = some(alt dicts {
722                   none. { [dict] }
723                   some(ds) { ds + [dict] }
724                 });
725               }
726               _ {}
727             }
728         }
729         fcx.lltyparams += [{desc: dsc, dicts: dicts}];
730     }
731
732     let a: uint = 2u; // retptr, env come first
733     let b: int = starting_idx;
734     let outgoing_arg_index: uint = 0u;
735     let llout_arg_tys: [TypeRef] =
736         type_of_explicit_args(cx.ccx, sp, outgoing_args);
737     for arg: option::t<@ast::expr> in args {
738         let out_arg = outgoing_args[outgoing_arg_index];
739         let llout_arg_ty = llout_arg_tys[outgoing_arg_index];
740         alt arg {
741           // Arg provided at binding time; thunk copies it from
742           // closure.
743           some(e) {
744             // Silly check
745             check type_is_tup_like(bcx, boxed_closure_ty);
746             let bound_arg =
747                 GEP_tup_like(bcx, boxed_closure_ty, llclosure,
748                              [0, abi::box_rc_field_body,
749                               abi::closure_elt_bindings, b]);
750             bcx = bound_arg.bcx;
751             let val = bound_arg.val;
752             if out_arg.mode == ast::by_val { val = Load(bcx, val); }
753             if out_arg.mode == ast::by_copy {
754                 let {bcx: cx, val: alloc} = alloc_ty(bcx, out_arg.ty);
755                 bcx = memmove_ty(cx, alloc, val, out_arg.ty);
756                 bcx = take_ty(bcx, alloc, out_arg.ty);
757                 val = alloc;
758             }
759             // If the type is parameterized, then we need to cast the
760             // type we actually have to the parameterized out type.
761             if ty::type_contains_params(cx.ccx.tcx, out_arg.ty) {
762                 val = PointerCast(bcx, val, llout_arg_ty);
763             }
764             llargs += [val];
765             b += 1;
766           }
767
768           // Arg will be provided when the thunk is invoked.
769           none. {
770             let arg: ValueRef = llvm::LLVMGetParam(llthunk, a);
771             if ty::type_contains_params(cx.ccx.tcx, out_arg.ty) {
772                 arg = PointerCast(bcx, arg, llout_arg_ty);
773             }
774             llargs += [arg];
775             a += 1u;
776           }
777         }
778         outgoing_arg_index += 1u;
779     }
780
781     // Cast the outgoing function to the appropriate type.
782     // This is necessary because the type of the function that we have
783     // in the closure does not know how many type descriptors the function
784     // needs to take.
785     let ccx = bcx_ccx(bcx);
786
787     let lltargetty =
788         type_of_fn_from_ty(ccx, sp, outgoing_fty, param_bounds);
789     lltargetfn = PointerCast(bcx, lltargetfn, T_ptr(lltargetty));
790     Call(bcx, lltargetfn, llargs);
791     build_return(bcx);
792     finish_fn(fcx, lltop);
793     ret {val: llthunk, ty: llthunk_ty};
794 }