dellingr 0.4.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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
use std::str;

use super::super::compiler::{
    FieldLookupCacheEntry, FieldLookupCacheSlot, GlobalLookupCacheEntry, GlobalLookupCacheSlot,
    MethodLookupCacheEntry, StringMethodCacheEntry,
};
use super::super::error::{ErrorKind, TypeError};
use super::Result;
use super::State;
use super::Val;
use super::frame::Frame;
use super::object::{ObjectPtr, Upvalue};

impl State {
    #[hotpath::measure]
    pub(super) fn instr_get_field(
        &mut self,
        frame: &mut Frame,
        field_id: u16,
        cache_idx: u8,
        local_cost: &mut u64,
    ) -> Result<()> {
        // Pop value, handle both tables and strings
        let val = self.pop_val();
        let key = self.get_string_constant(frame, field_id);

        let cache = frame.runtime.caches.field_lookup.get(cache_idx as usize);

        // Every push below is balanced against the receiver popped above, so
        // this path never exceeds the height it was entered at and needs no
        // preflight.
        if let Some(ptr) = val.as_object_ptr()
            && let Some((direct, has_metatable)) = self.get_table_field_direct(ptr, key, cache)
        {
            if let Some(result) = direct {
                self.push_unchecked(result);
                return Ok(());
            }

            if !has_metatable {
                return self.push_table_library_field(key, local_cost);
            }

            if let Some(result) = self.get_index_table_field_direct(val, ptr, key, cache) {
                self.push_unchecked(result);
                return Ok(());
            }

            self.push_unchecked(val);
            let table_idx = self.stack.len() - 1;
            self.get_table_with_key(table_idx, key, local_cost)?;
            let result = self.pop_val();
            self.pop_val();

            if matches!(result, Val::Nil) {
                self.push_table_library_field(key, local_cost)
            } else {
                self.push_unchecked(result);
                Ok(())
            }
        } else if val.as_string_ptr().is_some() {
            self.get_string_table_field(key, cache, local_cost)
        } else {
            Err(self.type_error(TypeError::TableIndex(val.typ(&self.heap))))
        }
    }

    /// Resolves a string index through the current global `string` table.
    pub(super) fn get_string_table_field(
        &mut self,
        key: Val,
        cache: Option<&FieldLookupCacheSlot>,
        local_cost: &mut u64,
    ) -> Result<()> {
        // Net-positive by one slot: callers in `metamethod.rs` reach this
        // without having popped a receiver first, so the check belongs here
        // rather than at the call sites.
        if let Some(cache) = cache
            && let Some(method) = self.get_cached_string_method(key, cache)
        {
            self.check_stack_space(1)?;
            self.push_unchecked(method);
            return Ok(());
        }

        self.get_global("string")?;
        let string_lib_idx = self.stack.len() - 1;
        self.get_table_with_key(string_lib_idx, key, local_cost)?;
        let result = self.pop_val();
        let string_lib = self.pop_val();

        if let Some(cache) = cache
            && let Some(lib_ptr) = string_lib.as_object_ptr()
            && let Some(tbl) = self.heap.as_table_ref(lib_ptr)
            && let Some((index, _)) = tbl.get_with_index(&key)
        {
            cache.set_string_method(StringMethodCacheEntry {
                string_lib: lib_ptr,
                version: tbl.version(),
                index,
                globals_version: self.globals_version,
            });
        }

        self.check_stack_space(1)?;
        self.push_unchecked(result);
        Ok(())
    }

    #[inline(always)]
    pub(super) fn get_table_field_direct(
        &self,
        ptr: ObjectPtr,
        key: Val,
        cache: Option<&FieldLookupCacheSlot>,
    ) -> Option<(Option<Val>, bool)> {
        if let Some(val) = cache.and_then(|cache| self.get_cached_field(ptr, key, cache)) {
            return Some((Some(val), false));
        }

        let tbl = self.heap.as_table_ref(ptr)?;
        if let Some((index, val)) = tbl.get_with_index(&key) {
            if let Some(cache) = cache {
                cache.set_field(FieldLookupCacheEntry {
                    table: ptr,
                    table_version: tbl.version(),
                    index,
                });
            }
            return Some((Some(val), tbl.get_metatable().is_some()));
        }

        Some((None, tbl.get_metatable().is_some()))
    }

    #[inline(always)]
    pub(super) fn get_cached_string_method(
        &self,
        key: Val,
        cache: &FieldLookupCacheSlot,
    ) -> Option<Val> {
        let entry = cache.get_string_method()?;
        // Reject the cache when the global `string` binding has been
        // rebound or swapped via with_restricted_env. Otherwise the
        // cached `string_lib` ObjectPtr (which may stay alive in
        // `saved_builtins`) silently bypasses the new binding.
        if entry.globals_version != self.globals_version {
            return None;
        }
        let tbl = self.heap.as_table_ref(entry.string_lib)?;
        let version = tbl.version();
        if entry.version == version {
            return tbl.get_index(entry.index).map(|(_, val)| val);
        }
        // Slow validation: re-read the key at the cached index. If still
        // the same method name, refresh the entry's version and use it.
        let (cached_key, cached_val) = tbl.get_index(entry.index)?;
        if cached_key == key {
            cache.set_string_method(StringMethodCacheEntry {
                string_lib: entry.string_lib,
                version,
                index: entry.index,
                globals_version: self.globals_version,
            });
            Some(cached_val)
        } else {
            None
        }
    }

    #[inline(always)]
    pub(super) fn get_cached_field(
        &self,
        ptr: ObjectPtr,
        key: Val,
        cache: &FieldLookupCacheSlot,
    ) -> Option<Val> {
        let entry = cache.get_field()?;
        if entry.table != ptr {
            return None;
        }
        let tbl = self.heap.as_table_ref(ptr)?;
        let table_version = tbl.version();
        if entry.table_version == table_version {
            return tbl.get_index(entry.index).map(|(_, val)| val);
        }
        let (cached_key, cached_val) = tbl.get_index(entry.index)?;
        if cached_key == key {
            cache.set_field(FieldLookupCacheEntry {
                table: ptr,
                table_version,
                index: entry.index,
            });
            Some(cached_val)
        } else {
            None
        }
    }

    #[inline(always)]
    pub(super) fn get_index_table_field_direct(
        &mut self,
        receiver: Val,
        ptr: ObjectPtr,
        key: Val,
        cache: Option<&FieldLookupCacheSlot>,
    ) -> Option<Val> {
        if cache
            .and_then(FieldLookupCacheSlot::get_method)
            .is_some_and(|entry| entry.method_index.is_none())
        {
            return None;
        }

        if let Some(cached) =
            cache.and_then(|cache| self.get_cached_index_table_field(ptr, key, cache))
        {
            return cached;
        }

        let index_key = self.protected_index_key(receiver, key)?;
        let receiver_table = self.heap.as_table_ref(ptr)?;
        let receiver_metatable = receiver_table.get_metatable()?;
        let metatable = self.heap.as_table_ref(receiver_metatable)?;
        let (index_field_index, index_handler) = metatable.get_with_index(&index_key)?;
        let Some(index_table) = index_handler.as_object_ptr() else {
            if let Some(cache) = cache {
                cache.set_method(MethodLookupCacheEntry {
                    receiver_metatable,
                    index_key,
                    index_field_index,
                    index_handler,
                    method_table_version: 0,
                    method_index: None,
                    globals_version: self.globals_version,
                });
            }
            return None;
        };
        let Some(method_table) = self.heap.as_table_ref(index_table) else {
            if let Some(cache) = cache {
                cache.set_method(MethodLookupCacheEntry {
                    receiver_metatable,
                    index_key,
                    index_field_index,
                    index_handler,
                    method_table_version: 0,
                    method_index: None,
                    globals_version: self.globals_version,
                });
            }
            return None;
        };
        let method_table_version = method_table.version();
        let Some((method_index, method)) = method_table.get_with_index(&key) else {
            if let Some(cache) = cache {
                cache.set_method(MethodLookupCacheEntry {
                    receiver_metatable,
                    index_key,
                    index_field_index,
                    index_handler,
                    method_table_version,
                    method_index: None,
                    globals_version: self.globals_version,
                });
            }
            return None;
        };

        if let Some(cache) = cache {
            cache.set_method(MethodLookupCacheEntry {
                receiver_metatable,
                index_key,
                index_field_index,
                index_handler,
                method_table_version,
                method_index: Some(method_index),
                globals_version: self.globals_version,
            });
        }

        Some(method)
    }

    #[inline(always)]
    pub(super) fn get_cached_index_table_field(
        &self,
        ptr: ObjectPtr,
        key: Val,
        cache: &FieldLookupCacheSlot,
    ) -> Option<Option<Val>> {
        let entry = cache.get_method()?;

        // Reject the cache when a builtin global has been rebound or
        // sandboxed via with_restricted_env. The cached `index_handler`
        // can point at a global library table that was reachable via
        // `mt.__index = string` (or similar) and stays alive across the
        // swap, so without this check a pre-warmed callsite resurrects
        // the pre-swap binding inside the sandbox.
        if entry.globals_version != self.globals_version {
            return None;
        }

        let receiver_table = self.heap.as_table_ref(ptr)?;
        if receiver_table.get_metatable() != Some(entry.receiver_metatable) {
            return None;
        }

        let metatable = self.heap.as_table_ref(entry.receiver_metatable)?;
        let (index_key, index_handler) = metatable.get_index(entry.index_field_index)?;
        if index_key != entry.index_key || index_handler != entry.index_handler {
            return None;
        }

        let Some(index_table) = entry.index_handler.as_object_ptr() else {
            return Some(None);
        };
        let Some(method_table) = self.heap.as_table_ref(index_table) else {
            return Some(None);
        };
        let method_table_version = method_table.version();
        let Some(method_index) = entry.method_index else {
            return if entry.method_table_version == method_table_version {
                Some(None)
            } else {
                None
            };
        };

        if entry.method_table_version == method_table_version {
            return method_table
                .get_index(method_index)
                .map(|(_, val)| Some(val));
        }

        let (cached_key, method) = method_table.get_index(method_index)?;
        if cached_key == key {
            cache.set_method(MethodLookupCacheEntry {
                receiver_metatable: entry.receiver_metatable,
                index_key: entry.index_key,
                index_field_index: entry.index_field_index,
                index_handler: entry.index_handler,
                method_table_version,
                method_index: Some(method_index),
                globals_version: self.globals_version,
            });
            Some(Some(method))
        } else {
            None
        }
    }

    #[inline(always)]
    /// Interns `"__index"` while keeping `receiver` and `key` reachable for the
    /// GC across the allocation.
    ///
    /// This pushes its two protection values *before* popping anything, so it
    /// is net-positive while it runs and must respect the cap like any other
    /// growth path. It sits on an `Option`-returning inline-cache fast path, so
    /// exhaustion is reported as `None`: the caller then falls through to the
    /// slow lookup, which performs the same work through checked pushes and
    /// surfaces a proper `StackOverflow`.
    pub(super) fn protected_index_key(&mut self, receiver: Val, key: Val) -> Option<Val> {
        if self.check_stack_space(2).is_err() {
            return None;
        }
        self.push_unchecked(receiver);
        self.push_unchecked(key);
        let index_key = self
            .alloc_string("__index")
            .expect("fixed metamethod key is below the string size limit");
        // Internal invariant, not host input: exactly the two values pushed
        // above are removed, so this uses the panicking form rather than the
        // now-fallible public `pop`.
        self.pop_val();
        self.pop_val();
        Some(index_key)
    }

    #[inline(always)]
    #[hotpath::measure]
    pub(super) fn push_table_library_field(
        &mut self,
        key: Val,
        local_cost: &mut u64,
    ) -> Result<()> {
        if let Some(cache) = &self.table_library_fallback {
            if key.as_string_ptr().is_some_and(|key_ptr| {
                cache
                    .names
                    .iter()
                    .any(|name| name.as_string_ptr() == Some(key_ptr))
            }) {
                return self.push_table_library_field_slow(key, local_cost);
            }

            if self.builtins[crate::instr::Builtin::Table as usize].as_object_ptr()
                == Some(cache.table)
                && self
                    .heap
                    .as_table_ref(cache.table)
                    .is_some_and(|table| table.fallback_shape() == cache.shape)
            {
                // The normal fallback temporarily pushes the library and its
                // result, so preflight its two-slot high-water mark even though
                // this proven-nil path only pushes the final replacement value.
                self.check_stack_space(2)?;
                self.push_unchecked(Val::Nil);
                return Ok(());
            }
        }
        self.push_table_library_field_slow(key, local_cost)
    }

    fn push_table_library_field_slow(&mut self, key: Val, local_cost: &mut u64) -> Result<()> {
        self.get_global("table")?;
        let table_lib_idx = self.stack.len() - 1;
        self.get_table_with_key(table_lib_idx, key, local_cost)?;
        let result = self.pop_val();
        self.pop_val();
        // Net-negative from here: two values popped, one pushed back.
        self.push_unchecked(result);
        Ok(())
    }

    pub(super) fn instr_get_global(
        &mut self,
        frame: &Frame,
        string_num: u16,
        cache_idx: u8,
    ) -> Result<()> {
        let s = &frame.bytecode().string_literals[string_num as usize];
        let cache = frame.runtime.caches.global_lookup.get(cache_idx as usize);
        // Net-positive by one slot, matching the uncached `get_global` path.
        if let Some(val) = cache.and_then(|cache| self.get_cached_global(cache)) {
            self.check_stack_space(1)?;
            self.push_unchecked(val);
            return Ok(());
        }

        let name = str::from_utf8(s).map_err(|_| {
            self.error(ErrorKind::InternalError(
                "compiler emitted non-UTF-8 global name".to_string(),
            ))
        })?;
        let val = if let Some(slot) = crate::instr::Builtin::from_name(name) {
            self.builtins[slot as usize]
        } else if let Some(index) = self.globals.get_index_of(name) {
            if let Some(cache) = cache {
                cache.set(GlobalLookupCacheEntry {
                    globals_version: self.globals_version,
                    index,
                });
            }
            self.globals
                .get_index(index)
                .map(|(_, val)| *val)
                .unwrap_or_default()
        } else {
            Val::Nil
        };
        self.check_stack_space(1)?;
        self.push_unchecked(val);
        Ok(())
    }

    #[inline(always)]
    pub(super) fn get_cached_global(&self, cache: &GlobalLookupCacheSlot) -> Option<Val> {
        let entry = cache.get()?;
        if entry.globals_version != self.globals_version {
            return None;
        }
        self.globals.get_index(entry.index).map(|(_, val)| *val)
    }

    /// Fast path for getting well-known builtin globals.
    #[inline(always)]
    pub(super) fn instr_get_builtin(&mut self, slot: u8) -> Result<()> {
        let val = self.builtins[slot as usize];
        self.check_stack_space(1)?;
        self.push_unchecked(val);
        Ok(())
    }

    /// Fast path for setting well-known builtin globals.
    #[inline(always)]
    pub(super) fn instr_set_builtin(&mut self, slot: u8) {
        let val = self.pop_val();
        self.builtins[slot as usize] = val;
        // Bump globals_version so ICs holding a direct ObjectPtr into a
        // builtin library table (string-method IC, method-lookup IC
        // reaching the lib via __index) re-resolve through the new
        // binding instead of resurrecting the old one.
        self.globals_version = self.globals_version.wrapping_add(1);
        if crate::instr::Builtin::from_u8(slot) == Some(crate::instr::Builtin::Table) {
            self.invalidate_table_library_fallback_rebind(val);
        }
        // Also update globals for _G compatibility
        if let Some(builtin) = crate::instr::Builtin::from_u8(slot) {
            self.globals.insert(builtin.name().to_string(), val);
        }
    }

    #[inline(always)]
    pub(super) fn instr_get_local(&mut self, local_num: u8) -> Result<()> {
        let i = local_num as usize + self.stack_bottom;
        let val = self.stack[i];
        self.check_stack_space(1)?;
        self.push_unchecked(val);
        Ok(())
    }

    pub(super) fn instr_get_upvalue(&mut self, frame: &Frame, upvalue_num: u8) -> Result<()> {
        let uv_ref = frame.upvalues[upvalue_num as usize];
        let val = match self.upvalue_pool.get(uv_ref) {
            Upvalue::Open(stack_idx) => self.stack[*stack_idx],
            Upvalue::Closed(v) => *v,
        };
        self.check_stack_space(1)?;
        self.push_unchecked(val);
        Ok(())
    }

    pub(super) fn instr_set_upvalue(&mut self, frame: &Frame, upvalue_num: u8) {
        let val = self.pop_val();
        let uv_ref = frame.upvalues[upvalue_num as usize];
        match self.upvalue_pool.get(uv_ref).clone() {
            Upvalue::Open(stack_idx) => {
                self.stack[stack_idx] = val;
            }
            Upvalue::Closed(_) => {
                *self.upvalue_pool.get_mut(uv_ref) = Upvalue::Closed(val);
            }
        }
    }

    #[hotpath::measure]
    pub(super) fn instr_get_table(&mut self, local_cost: &mut u64) -> Result<()> {
        let key = self.pop_val();
        // Table is now on top of the stack
        let table_idx = self.stack.len() - 1;
        let tbl_val = self.stack[table_idx];
        if tbl_val.as_string_ptr().is_some() {
            self.get_string_table_field(key, None, local_cost)?;
            let result = self.pop_val();
            self.stack[table_idx] = result;
            return Ok(());
        }
        let obj_ptr = tbl_val.as_object_ptr();
        let (val, has_metatable) = match obj_ptr.and_then(|ptr| self.heap.as_table_ref(ptr)) {
            Some(tbl) => {
                let val = tbl.get(&key);
                (val, tbl.get_metatable().is_some())
            }
            None => {
                let typ = tbl_val.typ(&self.heap);
                self.pop_val();
                return Err(self.type_error(TypeError::TableIndex(typ)));
            }
        };

        if !has_metatable || !matches!(val, Val::Nil) {
            self.stack[table_idx] = val;
            return Ok(());
        }

        self.get_table_with_key(table_idx, key, local_cost)?;
        // Stack now: [... table, result]
        let result = self.pop_val();
        self.stack[table_idx] = result;
        Ok(())
    }
}