luau-vm 0.732.0

Pure-Rust Luau virtual machine, garbage collector, and standard libraries
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
use core::ptr;

use luau_common::ByteSlice;

use crate::Table;
use crate::VmResult;
use crate::call::ThreadStack;
use crate::debug::DebugRuntime;
use crate::gc::GcBarrier;
use crate::gc::GcObject;
use crate::handle::RawHandle;
use crate::native::{NativeCallContext, NativeCallResult, NativeFunction};
use crate::state::ThreadState;
use crate::string::StringRuntime;
use crate::table::TableRuntime;
use crate::thread::stack::RawStackAccess;
use crate::thread::{LuaStringBuilder, LuaStringBuilderStorage, Thread};
use crate::types::{LUA_TFUNCTION, LUA_TNUMBER, LUA_TSTRING, LUA_TTABLE};
use crate::vm::VmOperations;

mod sort;

use sort::table_sort;

static TABLE_FUNCS: [NativeFunction; 17] = [
    NativeFunction {
        name: "concat",
        function: table_concat,
    },
    NativeFunction {
        name: "foreach",
        function: table_for_each,
    },
    NativeFunction {
        name: "foreachi",
        function: table_for_each_i,
    },
    NativeFunction {
        name: "getn",
        function: table_getn,
    },
    NativeFunction {
        name: "maxn",
        function: table_maxn,
    },
    NativeFunction {
        name: "insert",
        function: table_insert,
    },
    NativeFunction {
        name: "remove",
        function: table_remove,
    },
    NativeFunction {
        name: "sort",
        function: table_sort,
    },
    NativeFunction {
        name: "pack",
        function: table_pack,
    },
    NativeFunction {
        name: "unpack",
        function: table_unpack,
    },
    NativeFunction {
        name: "move",
        function: table_move,
    },
    NativeFunction {
        name: "create",
        function: table_create,
    },
    NativeFunction {
        name: "find",
        function: table_find,
    },
    NativeFunction {
        name: "clear",
        function: table_clear,
    },
    NativeFunction {
        name: "freeze",
        function: table_freeze,
    },
    NativeFunction {
        name: "isfrozen",
        function: table_is_frozen,
    },
    NativeFunction {
        name: "clone",
        function: table_clone,
    },
];

fn table_argument(thread: &Thread, argument: i32) -> VmResult<Table> {
    unsafe { thread.check_type(argument, LUA_TTABLE)? };
    Ok(unsafe { thread.to_object(argument).unwrap_unchecked().table_value() })
}

/// `moveelements`
unsafe fn move_elements(
    thread: &Thread,
    src_index: i32,
    dst_index: i32,
    first: i32,
    last: i32,
    target: i32,
) -> VmResult {
    let src = table_argument(thread, src_index)?;
    let dst = table_argument(thread, dst_index)?;

    unsafe {
        if dst.as_ptr().as_ref().unwrap_unchecked().readonly != 0 {
            return thread.readonly_error().map_err(Into::into);
        }

        let count = last - first + 1;
        let src_size = src.as_ptr().as_ref().unwrap_unchecked().size_array;
        let dst_size = dst.as_ptr().as_ref().unwrap_unchecked().size_array;

        if (first as u32).wrapping_sub(1) < src_size as u32
            && (target as u32).wrapping_sub(1) < dst_size as u32
            && (first as u32).wrapping_sub(1).wrapping_add(count as u32) <= src_size as u32
            && (target as u32).wrapping_sub(1).wrapping_add(count as u32) <= dst_size as u32
        {
            if count > 0 {
                let src_array = src.array_cursor().add((first - 1) as usize).as_ptr();
                let dst_array = dst.array_cursor().add((target - 1) as usize).as_ptr();
                ptr::copy(src_array, dst_array, count as usize);
            }

            let dst_object: GcObject = dst.into();
            if dst_object.is_black() {
                thread.barrier_back(
                    dst_object,
                    &raw mut dst.as_ptr().as_mut().unwrap_unchecked().gc_list,
                );
            }
        } else if target > last || target <= first || dst != src {
            for i in 0..count {
                thread.raw_geti(src_index, first + i)?;
                thread.raw_seti(dst_index, target + i)?;
            }
        } else {
            for i in (0..count).rev() {
                thread.raw_geti(src_index, first + i)?;
                thread.raw_seti(dst_index, target + i)?;
            }
        }
    }
    Ok(())
}

/// `addfield`
unsafe fn add_field(
    thread: &Thread,
    buffer: &mut LuaStringBuilder<'_, '_>,
    index: i32,
    table: Table,
) -> VmResult {
    unsafe {
        if (index as u32).wrapping_sub(1)
            < table.as_ptr().as_ref().unwrap_unchecked().size_array as u32
        {
            let entry = table.array_slot((index - 1) as usize);
            if entry.is_string() {
                buffer.push_bytes(entry.string_value().as_bytes())?;
                return Ok(());
            }
        }

        let value_type = thread.raw_geti(1, index)?;
        if value_type != LUA_TSTRING && value_type != LUA_TNUMBER {
            let type_name = thread.lua_type_name(-1);
            let message = luau_printf::sprintf!(
                "invalid value (%s) at index %d in table for 'concat'",
                type_name.as_bstr(),
                index
            );
            return crate::error!(thread, &message).map_err(Into::into);
        }

        buffer.push_stack_value()?;
    }
    Ok(())
}

/// `maxn`
fn table_maxn(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    let max = unsafe {
        thread.check_type(1, LUA_TTABLE)?;

        let table = thread.to_object(1).unwrap_unchecked().table_value();
        let mut max = 0.0f64;

        for i in 0..table.as_ptr().as_ref().unwrap_unchecked().size_array {
            if !table.array_slot(i as usize).is_nil() {
                max = (i + 1) as f64;
            }
        }

        for i in 0..table.node_count() {
            let node = table.node(i as i32);
            if !node.value_unchecked().is_nil() && node.key().tt() == LUA_TNUMBER {
                let value = node.key().number_value();
                if value > max {
                    max = value;
                }
            }
        }

        max
    };
    ctx.push_number(max)?;
    Ok(1)
}

/// `getn`
fn table_getn(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe { thread.check_type(1, LUA_TTABLE)? };
    ctx.push_integer(unsafe { thread.obj_len(1) })?;
    Ok(1)
}

/// `tinsert`
fn table_insert(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe {
        thread.check_type(1, LUA_TTABLE)?;
        let n = thread.obj_len(1);

        let pos = match thread.get_top() {
            2 => n + 1,
            3 => {
                let pos = thread.check_integer(2)?;
                if (1..=n).contains(&pos) {
                    move_elements(thread, 1, 1, pos, n, pos + 1)?;
                }
                pos
            }
            _ => {
                return crate::error!(thread, "wrong number of arguments to 'insert'")
                    .map_err(Into::into);
            }
        };

        thread.raw_seti(1, pos)?;
        Ok(0)
    }
}

/// `tremove`
fn table_remove(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe {
        thread.check_type(1, LUA_TTABLE)?;
        let n = thread.obj_len(1);
        let pos = thread.opt_integer(2, n)?;

        if !(1..=n).contains(&pos) {
            return Ok(0);
        }

        thread.raw_geti(1, pos)?;
        move_elements(thread, 1, 1, pos + 1, n, pos)?;
        thread.push_nil()?;
        thread.raw_seti(1, n)?;
        Ok(1)
    }
}

/// `tmove`
fn table_move(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    let dst_index = unsafe {
        thread.check_type(1, LUA_TTABLE)?;
        let first = thread.check_integer(2)?;
        let last = thread.check_integer(3)?;
        let target = thread.check_integer(4)?;
        let dst_index = if thread.is_none_or_nil(5) != 0 { 1 } else { 5 };
        thread.check_type(dst_index, LUA_TTABLE)?;

        if last >= first {
            if first <= 0 && last >= i32::MAX + first {
                return thread
                    .lua_arg_error(3, "too many elements to move")
                    .map_err(Into::into);
            }

            let count = last - first + 1;
            if target > i32::MAX - count + 1 {
                return thread
                    .lua_arg_error(4, "destination wrap around")
                    .map_err(Into::into);
            }

            let dst = thread.to_object(dst_index).unwrap_unchecked().table_value();
            if dst.as_ptr().as_ref().unwrap_unchecked().readonly != 0 {
                return thread.readonly_error().map_err(Into::into);
            }

            if target > 0
                && (target - 1) <= dst.as_ptr().as_ref().unwrap_unchecked().size_array
                && (target - 1 + count) > dst.as_ptr().as_ref().unwrap_unchecked().size_array
            {
                thread.resize_array(dst, target - 1 + count)?;
            }

            move_elements(thread, 1, dst_index, first, last, target)?;
        }

        dst_index
    };

    unsafe { thread.push_value(dst_index)? };
    Ok(1)
}

/// `tconcat`
fn table_concat(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe {
        let separator = thread.opt_string(2)?.unwrap_or(b"".as_bstr());
        thread.check_type(1, LUA_TTABLE)?;
        let mut index = thread.opt_integer(3, 1)?;
        let last = if thread.is_none_or_nil(4) != 0 {
            thread.obj_len(1)
        } else {
            thread.check_integer(4)?
        };
        let table = thread.to_object(1).unwrap_unchecked().table_value();
        let mut buffer_storage = LuaStringBuilderStorage::uninit();
        let mut buffer = LuaStringBuilder::new(thread, &mut buffer_storage);

        while index < last {
            add_field(thread, &mut buffer, index, table)?;
            if !separator.is_empty() {
                buffer.push_bytes(separator)?;
            }
            index += 1;
        }

        if index == last {
            add_field(thread, &mut buffer, index, table)?;
        }

        buffer.finish()?;
        Ok(1)
    }
}

/// `foreachi`
fn table_for_each_i(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe {
        thread.check_type(1, LUA_TTABLE)?;
        thread.check_type(2, LUA_TFUNCTION)?;
        let n = thread.obj_len(1);
        for index in 1..=n {
            thread.push_value(2)?;
            thread.push_integer(index)?;
            thread.raw_geti(1, index)?;
            thread.call(2, 1)?;

            if thread.is_nil(-1) == 0 {
                return Ok(1);
            }

            thread.pop(1);
        }

        Ok(0)
    }
}

/// `foreach`
fn table_for_each(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe {
        thread.check_type(1, LUA_TTABLE)?;
        thread.check_type(2, LUA_TFUNCTION)?;
        thread.push_nil()?;
        while thread.next(1)? != 0 {
            thread.push_value(2)?;
            thread.push_value(-3)?;
            thread.push_value(-3)?;
            thread.call(2, 1)?;

            if thread.is_nil(-1) == 0 {
                return Ok(1);
            }

            thread.pop(2);
        }

        Ok(0)
    }
}

/// `tpack`
fn table_pack(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe {
        let n = thread.get_top();
        thread.create_table(n as usize, 1)?;

        let table = thread.to_object(-1).unwrap_unchecked().table_value();
        let array = table.array_cursor();
        let base = thread.stack_base();
        for i in 0..n as usize {
            array
                .add(i)
                .value_unchecked()
                .set_obj(base.add(i).value_unchecked());
        }

        let key = thread.intern_string(b"n".as_bstr())?;
        let node_cursor = thread.set_str(table, key)?;
        node_cursor
            .node_unchecked()
            .value_unchecked()
            .set_number(n as f64);
        Ok(1)
    }
}

/// `tunpack`
fn table_unpack(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe {
        thread.check_type(1, LUA_TTABLE)?;
        let table = thread.to_object(1).unwrap_unchecked().table_value();
        let start = thread.opt_integer(2, 1)?;
        let end = if thread.is_none_or_nil(3) != 0 {
            thread.obj_len(1)
        } else {
            thread.check_integer(3)?
        };

        if start > end {
            return Ok(0);
        }

        let n = (end as u32).wrapping_sub(start as u32) as i32 + 1;
        if n <= 0 || thread.check_stack(n) == 0 {
            return crate::error!(thread, "too many results to unpack").map_err(Into::into);
        }

        if start == 1 && n <= table.as_ptr().as_ref().unwrap_unchecked().size_array {
            let top = thread.stack_top();
            for i in 0..n as usize {
                top.add(i).value_unchecked().set_obj(table.array_slot(i));
            }
            thread.expand_stack_limit(top.add(n as usize));
            thread.set_stack_top(top.add(n as usize));
        } else {
            for i in start..end {
                thread.raw_geti(1, i)?;
            }
            thread.raw_geti(1, end)?;
        }

        Ok(n as usize)
    }
}

/// `tcreate`
fn table_create(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe {
        let size = thread.check_integer(1)?;
        if size < 0 {
            return thread
                .lua_arg_error(1, "size out of range")
                .map_err(Into::into);
        }

        if thread.is_none_or_nil(2) == 0 {
            let value = thread.stack_base().add(1).value_unchecked();
            thread.create_table(size as usize, 0)?;
            let table = thread.to_object(-1).unwrap_unchecked().table_value();
            let array = table.array_cursor();
            for i in 0..size as usize {
                array.add(i).value_unchecked().set_obj(value);
            }
        } else {
            thread.create_table(size as usize, 0)?;
        }

        Ok(1)
    }
}

/// `tfind`
fn table_find(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe {
        thread.check_type(1, LUA_TTABLE)?;
        thread.check_any(2)?;

        let init = thread.opt_integer(3, 1)?;
        if init < 1 {
            return thread
                .lua_arg_error(3, "index out of range")
                .map_err(Into::into);
        }

        let table = thread.to_object(1).unwrap_unchecked().table_value();
        let needle = thread.stack_base().add(1).value_unchecked();

        for index in init.. {
            let entry = table.get_num(index);
            if entry.is_nil() {
                break;
            }

            let equal = if entry.tt() == needle.tt() {
                thread.equal_value(entry, needle)? != 0
            } else {
                false
            };

            if equal {
                thread.push_integer(index)?;
                return Ok(1);
            }
        }

        thread.push_nil()?;
    }
    Ok(1)
}

/// `tclear`
fn table_clear(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe { thread.check_type(1, LUA_TTABLE)? };
    unsafe { thread.clear_table(1)? };
    Ok(0)
}

/// `tfreeze`
fn table_freeze(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe {
        thread.check_type(1, LUA_TTABLE)?;
        if thread.get_readonly(1) != 0 {
            return thread
                .lua_arg_error(1, "table is already frozen")
                .map_err(Into::into);
        }
        if thread.get_metafield(1, "__metatable")? != 0 {
            return thread
                .lua_arg_error(1, "table has a protected metatable")
                .map_err(Into::into);
        }

        thread.set_readonly(1, 1);
        thread.push_value(1)?;
        Ok(1)
    }
}

/// `tisfrozen`
fn table_is_frozen(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe { thread.check_type(1, LUA_TTABLE)? };
    unsafe { thread.push_boolean(thread.get_readonly(1))? };
    Ok(1)
}

/// `tclone`
fn table_clone(ctx: NativeCallContext) -> NativeCallResult {
    let thread = ctx.raw_thread();
    unsafe {
        thread.check_type(1, LUA_TTABLE)?;
        if thread.get_metafield(1, "__metatable")? != 0 {
            return thread
                .lua_arg_error(1, "table has a protected metatable")
                .map_err(Into::into);
        }

        thread.clone_table(1)?;
        Ok(1)
    }
}

impl Thread {
    /// `luaopen_table`
    pub unsafe fn open_table(&self) -> NativeCallResult {
        unsafe { self.register(Some(super::LUA_TABLIB_NAME), &TABLE_FUNCS[..])? };

        // Lua 5.1 compatibility global.
        unsafe {
            self.push_native_function(table_unpack, Some("unpack"))?;
            self.set_global("unpack")?;
        }

        Ok(1)
    }
}