dellingr 0.2.0

An embeddable, pure-Rust Lua VM with precise instruction-cost accounting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Tests for GC handling of closed upvalues in closures.
//!
//! These tests verify that values captured in closures survive garbage collection
//! even after the original scope has ended and the upvalue has been "closed"
//! (moved from the stack to the upvalue pool).

use dellingr::{ArgCount, RetCount, State};

fn install_force_gc(state: &mut State) {
    state.push_rust_fn(|state| {
        state.gc_collect();
        Ok(0)
    });
    state.set_global("force_gc");
}

fn install_force_next_gc(state: &mut State) {
    state.push_rust_fn(|state| {
        state.gc_set_threshold(1);
        Ok(0)
    });
    state.set_global("force_next_gc");
}

#[test]
fn active_frame_string_literal_survives_explicit_gc() {
    let mut state = State::new();
    state.gc_disable_auto();
    install_force_gc(&mut state);

    state
        .load_string(
            r#"
        force_gc()
        return "literal after gc"
    "#,
        )
        .unwrap();
    state.call(ArgCount::Fixed(0), RetCount::Fixed(1)).unwrap();

    assert_eq!(state.to_string(-1).unwrap(), "literal after gc");
    state.pop(1);
}

#[test]
fn string_literals_are_unrooted_after_frame_exits() {
    let mut state = State::empty();
    state.gc_disable_auto();

    assert_eq!(state.string_count(), 0);
    state
        .load_string(
            r#"
        local temporary = "collect this literal after return"
    "#,
        )
        .unwrap();
    state.call(ArgCount::Fixed(0), RetCount::Fixed(0)).unwrap();

    assert!(state.string_count() > 0);
    state.gc_collect();
    assert_eq!(state.string_count(), 0);
}

#[test]
fn open_upvalue_survives_gc_while_defining_frame_is_active() {
    let mut state = State::new();
    state.gc_disable_auto();
    install_force_gc(&mut state);

    state
        .load_string(
            r#"
        local function outer()
            local captured = {value = 55}
            live = function()
                return captured.value
            end
            force_gc()
            return live()
        end

        return outer()
    "#,
        )
        .unwrap();
    state.call(ArgCount::Fixed(0), RetCount::Fixed(1)).unwrap();

    assert_eq!(state.to_number(-1).unwrap(), 55.0);
    state.pop(1);
}

#[test]
fn executing_returned_closure_roots_closed_upvalues_during_auto_gc() {
    let mut state = State::empty();

    state
        .load_string(
            r#"
        local function make_closure()
            local captured = {value = 42}
            return function()
                local trigger_gc = {}
                return captured.value
            end
        end

        return make_closure()()
    "#,
        )
        .unwrap();
    state.gc_set_threshold(1);
    state.call(ArgCount::Fixed(0), RetCount::Fixed(1)).unwrap();

    assert_eq!(state.to_number(-1).unwrap(), 42.0);
    state.pop(1);
}

#[test]
fn temporary_callable_table_survives_gc_during_call_metamethod_lookup() {
    let mut state = State::new();
    install_force_next_gc(&mut state);

    state
        .load_string(
            r#"
        local function make_callable()
            local callable = setmetatable({ value = 73 }, {
                __call = function(self)
                    return self.value
                end
            })
            force_next_gc()
            return callable
        end

        return make_callable()()
    "#,
        )
        .unwrap();
    state.call(ArgCount::Fixed(0), RetCount::Fixed(1)).unwrap();

    assert_eq!(state.to_number(-1).unwrap(), 73.0);
    state.pop(1);
}

/// Basic test: closure captures a table, table survives GC.
#[test]
fn closure_captured_table_survives_gc() {
    let mut state = State::new();
    state.gc_disable_auto(); // Manual GC control

    // Create a closure that captures a local table
    state
        .load_string(
            r#"
        local function make_closure()
            local captured = {value = 42}
            return function() return captured.value end
        end
        test_fn = make_closure()
    "#,
        )
        .unwrap();
    state.call(ArgCount::Fixed(0), RetCount::Fixed(0)).unwrap();

    // Force GC - the captured table should survive
    state.gc_collect();

    // Call the closure - should still work
    state.get_global("test_fn");
    state.call(ArgCount::Fixed(0), RetCount::Fixed(1)).unwrap();

    let result = state.to_number(-1).unwrap();
    assert_eq!(result, 42.0, "Captured table value should survive GC");
    state.pop(1);
}

/// Test multiple GC cycles with closure holding table.
#[test]
fn closure_survives_multiple_gc_cycles() {
    let mut state = State::new();
    state.gc_disable_auto();

    state
        .load_string(
            r#"
        local function make_closure()
            local data = {count = 0}
            return function()
                data.count = data.count + 1
                return data.count
            end
        end
        counter = make_closure()
    "#,
        )
        .unwrap();
    state.call(ArgCount::Fixed(0), RetCount::Fixed(0)).unwrap();

    // Call and GC multiple times
    for expected in 1..=5 {
        state.gc_collect();

        state.get_global("counter");
        state.call(ArgCount::Fixed(0), RetCount::Fixed(1)).unwrap();

        let result = state.to_number(-1).unwrap();
        assert_eq!(
            result, expected as f64,
            "Counter should be {expected} after GC cycle"
        );
        state.pop(1);
    }
}

/// Test closure capturing another closure (nested upvalues).
#[test]
fn nested_closures_survive_gc() {
    let mut state = State::new();
    state.gc_disable_auto();

    state
        .load_string(
            r#"
        local function outer()
            local x = 10
            local function middle()
                local y = 20
                return function()
                    return x + y
                end
            end
            return middle()
        end
        nested_fn = outer()
    "#,
        )
        .unwrap();
    state.call(ArgCount::Fixed(0), RetCount::Fixed(0)).unwrap();

    state.gc_collect();

    state.get_global("nested_fn");
    state.call(ArgCount::Fixed(0), RetCount::Fixed(1)).unwrap();

    let result = state.to_number(-1).unwrap();
    assert_eq!(result, 30.0, "Nested closure should access both upvalues");
    state.pop(1);
}

/// Test metatable stored as upvalue (the original bug case).
#[test]
fn metatable_as_upvalue_survives_gc() {
    let mut state = State::new();
    state.gc_disable_auto();

    // This pattern mirrors fleet:group() - metatable defined once, used by closure
    state
        .load_string(
            r#"
        local mt = {
            __index = {
                get_value = function(self) return self._value end
            }
        }

        function create_object(val)
            local obj = {_value = val}
            setmetatable(obj, mt)
            return obj
        end
    "#,
        )
        .unwrap();
    state.call(ArgCount::Fixed(0), RetCount::Fixed(0)).unwrap();

    // Force GC - mt should survive because create_object closure references it
    state.gc_collect();

    // Create an object using the closure
    state.get_global("create_object");
    state.push_number(99.0);
    state.call(ArgCount::Fixed(1), RetCount::Fixed(1)).unwrap();
    state.set_global("obj");

    // Access via metatable method
    state.load_string("return obj:get_value()").unwrap();
    state.call(ArgCount::Fixed(0), RetCount::Fixed(1)).unwrap();

    let result = state.to_number(-1).unwrap();
    assert_eq!(result, 99.0, "Metatable method should work after GC");
    state.pop(1);
}

/// Test that unreferenced closures ARE collected.
#[test]
fn unreferenced_closure_is_collected() {
    let mut state = State::new();
    state.gc_disable_auto();

    let size_before = state.heap_size();

    // Create and immediately discard a closure with captured table
    state
        .load_string(
            r#"
        local function make_and_discard()
            local big_table = {a=1, b=2, c=3, d=4}
            local fn = function() return big_table end
            -- fn goes out of scope here, not stored anywhere
        end
        make_and_discard()
    "#,
        )
        .unwrap();
    state.call(ArgCount::Fixed(0), RetCount::Fixed(0)).unwrap();

    let size_after_create = state.heap_size();
    assert!(
        size_after_create > size_before,
        "Heap should grow after creating objects"
    );

    state.gc_collect();

    let size_after_gc = state.heap_size();
    assert!(
        size_after_gc < size_after_create,
        "GC should collect unreferenced closure and table. Before GC: {size_after_create}, After: {size_after_gc}"
    );
}

/// Test closure with multiple upvalues of different types.
#[test]
fn closure_with_mixed_upvalues() {
    let mut state = State::new();
    state.gc_disable_auto();

    state
        .load_string(
            r#"
        local function make_closure()
            local num = 42
            local str = "hello"
            local tbl = {x = 1}
            local fn = function() return "inner" end

            return function()
                return num, str, tbl.x, fn()
            end
        end
        mixed_fn = make_closure()
    "#,
        )
        .unwrap();
    state.call(ArgCount::Fixed(0), RetCount::Fixed(0)).unwrap();

    state.gc_collect();

    state.get_global("mixed_fn");
    state.call(ArgCount::Fixed(0), RetCount::Fixed(4)).unwrap();

    assert_eq!(state.to_number(-4).unwrap(), 42.0);
    assert_eq!(state.to_string(-3).unwrap(), "hello");
    assert_eq!(state.to_number(-2).unwrap(), 1.0);
    assert_eq!(state.to_string(-1).unwrap(), "inner");
    state.pop(4);
}

/// Test closure stored in a table survives GC.
#[test]
fn closure_in_table_survives_gc() {
    let mut state = State::new();
    state.gc_disable_auto();

    state
        .load_string(
            r#"
        local registry = {}

        local function register(name, value)
            local captured = value
            registry[name] = function() return captured end
        end

        register("answer", 42)
        register("pi", 3.14159)

        function get(name)
            return registry[name]()
        end
    "#,
        )
        .unwrap();
    state.call(ArgCount::Fixed(0), RetCount::Fixed(0)).unwrap();

    state.gc_collect();

    // Check "answer"
    state.get_global("get");
    state.push_string("answer");
    state.call(ArgCount::Fixed(1), RetCount::Fixed(1)).unwrap();
    assert_eq!(state.to_number(-1).unwrap(), 42.0);
    state.pop(1);

    state.gc_collect();

    // Check "pi"
    state.get_global("get");
    state.push_string("pi");
    state.call(ArgCount::Fixed(1), RetCount::Fixed(1)).unwrap();
    let pi = state.to_number(-1).unwrap();
    assert!((pi - std::f64::consts::PI).abs() < 0.0001);
    state.pop(1);
}

/// Stress test: many closures with shared upvalue.
#[test]
fn many_closures_shared_upvalue() {
    let mut state = State::new();
    state.gc_disable_auto();

    state
        .load_string(
            r#"
        local shared = {value = 0}
        closures = {}

        for i = 1, 10 do
            closures[i] = function()
                shared.value = shared.value + 1
                return shared.value
            end
        end
    "#,
        )
        .unwrap();
    state.call(ArgCount::Fixed(0), RetCount::Fixed(0)).unwrap();

    state.gc_collect();

    // Call each closure, all should increment the same shared table
    for i in 1..=10 {
        state
            .load_string(format!("return closures[{i}]()"))
            .unwrap();
        state.call(ArgCount::Fixed(0), RetCount::Fixed(1)).unwrap();
        let result = state.to_number(-1).unwrap();
        assert_eq!(
            result, i as f64,
            "Shared upvalue should be incremented to {i}"
        );
        state.pop(1);

        // GC between calls
        state.gc_collect();
    }
}