Commit 5b1035c8

5b1035c879cdMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 6 files · +2 added · ~4 modified

Description

codegen: let an escaping closure capture pointer-typed locals

A captured local lives in a pointer-sized mrb_int *_cell_<name> cell, so only int/bool (and a laundered proc) could be captured -- a string, array, hash, or heap object raised "closure capturing a non-integer variable".

Extend the cell to any pointer slot (proc_slot_is_ptr, minus by-value objects): launder the value through the cell as (mrb_int)(uintptr_t)<ptr> the way the proc capture already does, cast it back on read, and -- the part that makes it GC-safe -- give the cell a scan function that marks the laundered referent (sp_cell_scan_str for strings, sp_cell_scan_ptr for heap objects/arrays/hashes). The cell is reachable from the proc's cap struct, so the referent now survives after the defining method returns and across a collection. Float / poly / by-value-struct captures don't fit a single int cell and stay deferred.

Two inline markers added to sp_gc.h (additive). Verified with a heap-churn test that the captured string/array/object survive a GC triggered after the capturing method returned.

Details

Commit
5b1035c879cd
Parent
8f300c2c0491

lib/sp_gc.hmodifiedView file

@@ -70,6 +70,11 @@
7070 if (v.tag == SP_TAG_STR) sp_mark_string(v.v.s);
7171 else if (v.tag == SP_TAG_OBJ) sp_gc_mark(v.v.p);
7272 }
73+/* Closure-cell content markers. A captured non-int local is laundered into the
74+ pointer-sized mrb_int cell as (uintptr_t)<ptr>; the cell's GC scan marks the
75+ referent so it survives as long as the capturing proc does. */
76+static inline void sp_cell_scan_str(void *p) { sp_mark_string(*(const char **)p); }
77+static inline void sp_cell_scan_ptr(void *p) { sp_gc_mark(*(void **)p); }
7378 /* A low-bit-tagged root entry is an sp_RbVal* (see SP_GC_ROOT_RBVAL);
7479 an untagged entry is a plain void** to a direct GC pointer. */
7580 static inline void sp_gc_mark_root_entry(void **e) {